dolibarr 22.0.5
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-2024 Frédéric France <frederic.france@free.fr>
15 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
16 * Copyright (C) 2026 Mathieu Moulin <mathieu@iprospective.fr>
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 3 of the License, or
21 * (at your option) any later version.
22 *
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <https://www.gnu.org/licenses/>.
30 */
31
38require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
39require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
40require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
41if (isModEnabled("propal")) {
42 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
43}
44if (isModEnabled('order')) {
45 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
46}
47
48
53{
54 use CommonIncoterm;
55
59 public $code = "";
60
64 public $element = "reception";
65
69 public $fk_element = "fk_reception";
70 public $table_element = "reception";
71 public $table_element_line = "receptiondet_batch";
72
76 public $picto = 'dollyrevert';
77
81 public $socid;
85 public $ref_supplier;
86
90 public $entrepot_id;
94 public $tracking_number;
98 public $tracking_url;
102 public $billed;
103
107 public $weight;
111 public $trueWeight;
115 public $weight_units;
119 public $trueWidth;
123 public $width_units;
127 public $trueHeight;
131 public $height_units;
135 public $trueDepth;
139 public $depth_units;
143 public $trueSize;
147 public $size_units;
151 public $user_author_id;
152
156 public $date_delivery;
157
163 public $date;
164
168 public $date_reception;
169
173 public $date_valid;
174
178 public $fk_user_author;
179
183 public $fk_user_valid;
184
188 public $meths;
192 public $listmeths; // List of carriers
193
197 public $lines = array();
198
199
204 public $detail_batch;
205
206 const STATUS_DRAFT = 0;
207 const STATUS_VALIDATED = 1;
208 const STATUS_CLOSED = 2;
209
210
216 public function __construct($db)
217 {
218 $this->db = $db;
219
220 $this->ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
221 }
222
229 public function getNextNumRef($soc)
230 {
231 global $langs, $conf;
232 $langs->load("receptions");
233
234 if (getDolGlobalString('RECEPTION_ADDON_NUMBER')) {
235 $mybool = false;
236
237 $file = getDolGlobalString('RECEPTION_ADDON_NUMBER') . ".php";
238 $classname = getDolGlobalString('RECEPTION_ADDON_NUMBER');
239
240 // Include file with class
241 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
242
243 foreach ($dirmodels as $reldir) {
244 $dir = dol_buildpath($reldir."core/modules/reception/");
245
246 // Load file with numbering class (if found)
247 $mybool = ((bool) @include_once $dir.$file) || $mybool;
248 }
249
250 if (!$mybool) {
251 dol_print_error(null, "Failed to include file ".$file);
252 return '';
253 }
254
255 $obj = new $classname();
256 '@phan-var-force ModelNumRefReception $obj';
257
258 $numref = $obj->getNextValue($soc, $this);
259
260 if ($numref != "") {
261 return $numref;
262 } else {
263 dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error);
264 return "";
265 }
266 } else {
267 print $langs->trans("Error")." ".$langs->trans("Error_RECEPTION_ADDON_NUMBER_NotDefined");
268 return "";
269 }
270 }
271
279 public function create($user, $notrigger = 0)
280 {
281 global $conf;
282
283 $now = dol_now();
284
285 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
286 $error = 0;
287
288 // Clean parameters
289 $this->tracking_number = dol_sanitizeFileName($this->tracking_number);
290 if (empty($this->fk_project)) {
291 $this->fk_project = 0;
292 }
293 if (empty($this->weight_units)) {
294 $this->weight_units = 0;
295 }
296 if (empty($this->size_units)) {
297 $this->size_units = 0;
298 }
299
300 $this->user = $user;
301
302 $this->db->begin();
303
304 $sql = "INSERT INTO ".MAIN_DB_PREFIX."reception (";
305 $sql .= "ref";
306 $sql .= ", entity";
307 $sql .= ", ref_supplier";
308 $sql .= ", date_creation";
309 $sql .= ", fk_user_author";
310 $sql .= ", date_reception";
311 $sql .= ", date_delivery";
312 $sql .= ", fk_soc";
313 $sql .= ", fk_projet";
314 $sql .= ", fk_shipping_method";
315 $sql .= ", tracking_number";
316 $sql .= ", weight";
317 $sql .= ", size";
318 $sql .= ", width";
319 $sql .= ", height";
320 $sql .= ", weight_units";
321 $sql .= ", size_units";
322 $sql .= ", note_private";
323 $sql .= ", note_public";
324 $sql .= ", model_pdf";
325 $sql .= ", fk_incoterms, location_incoterms";
326 $sql .= ") VALUES (";
327 $sql .= "'(PROV)'";
328 $sql .= ", ".((int) $conf->entity);
329 $sql .= ", ".($this->ref_supplier ? "'".$this->db->escape($this->ref_supplier)."'" : "null");
330 $sql .= ", '".$this->db->idate($now)."'";
331 $sql .= ", ".((int) $user->id);
332 $sql .= ", ".($this->date_reception > 0 ? "'".$this->db->idate($this->date_reception)."'" : "null");
333 $sql .= ", ".($this->date_delivery > 0 ? "'".$this->db->idate($this->date_delivery)."'" : "null");
334 $sql .= ", ".((int) $this->socid);
335 $sql .= ", ".((int) $this->fk_project);
336 $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : "null");
337 $sql .= ", '".$this->db->escape($this->tracking_number)."'";
338 $sql .= ", ".(is_null($this->weight) ? "NULL" : ((float) $this->weight));
339 $sql .= ", ".(is_null($this->trueDepth) ? "NULL" : ((float) $this->trueDepth));
340 $sql .= ", ".(is_null($this->trueWidth) ? "NULL" : ((float) $this->trueWidth));
341 $sql .= ", ".(is_null($this->trueHeight) ? "NULL" : ((float) $this->trueHeight));
342 $sql .= ", ".((int) $this->weight_units);
343 $sql .= ", ".((int) $this->size_units);
344 $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
345 $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
346 $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
347 $sql .= ", ".(int) $this->fk_incoterms;
348 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
349 $sql .= ")";
350
351 dol_syslog(get_class($this)."::create", LOG_DEBUG);
352
353 $resql = $this->db->query($sql);
354
355 if ($resql) {
356 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."reception");
357
358 $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
359 $sql .= " SET ref = '(PROV".((int) $this->id).")'";
360 $sql .= " WHERE rowid = ".((int) $this->id);
361
362 dol_syslog(get_class($this)."::create", LOG_DEBUG);
363 if ($this->db->query($sql)) {
364 // Insert of lines
365 $num = count($this->lines);
366 for ($i = 0; $i < $num; $i++) {
367 $this->lines[$i]->fk_reception = $this->id;
368
369 if (!$this->lines[$i]->create($user) > 0) {
370 $error++;
371 }
372 }
373
374 if (!$error && $this->id && $this->origin_id) {
375 $ret = $this->add_object_linked();
376 if (!$ret) {
377 $error++;
378 }
379 }
380
381 // Create extrafields
382 if (!$error) {
383 $result = $this->insertExtraFields();
384 if ($result < 0) {
385 $error++;
386 }
387 }
388
389 if (!$error && !$notrigger) {
390 // Call trigger
391 $result = $this->call_trigger('RECEPTION_CREATE', $user);
392 if ($result < 0) {
393 $error++;
394 }
395 // End call triggers
396 }
397
398 if (!$error) {
399 $this->db->commit();
400 return $this->id;
401 } else {
402 foreach ($this->errors as $errmsg) {
403 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
404 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
405 }
406 $this->db->rollback();
407 return -1 * $error;
408 }
409 } else {
410 $error++;
411 $this->error = $this->db->lasterror()." - sql=$sql";
412 $this->db->rollback();
413 return -2;
414 }
415 } else {
416 $error++;
417 $this->error = $this->db->error()." - sql=$sql";
418 $this->db->rollback();
419 return -1;
420 }
421 }
422
423
424
433 public function fetch($id, $ref = '', $ref_ext = '')
434 {
435 // Check parameters
436 if (empty($id) && empty($ref) && empty($ref_ext)) {
437 return -1;
438 }
439
440 $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.billed";
441 $sql .= ", e.fk_user_valid";
442 $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
443 $sql .= ", e.date_reception as date_reception, e.model_pdf, e.date_delivery, e.date_valid";
444 $sql .= ", e.fk_shipping_method, e.tracking_number";
445 $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
446 $sql .= ", e.note_private, e.note_public";
447 $sql .= ', e.fk_incoterms, e.location_incoterms';
448 $sql .= ', i.libelle as label_incoterms';
449 $sql .= " FROM ".MAIN_DB_PREFIX."reception as e";
450 $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'";
451 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
452
453 if ($id) {
454 $sql .= " WHERE e.rowid = ".((int) $id);
455 } else {
456 $sql .= " WHERE e.entity IN (".getEntity('reception').")";
457 if ($ref) {
458 $sql .= " AND e.ref = '".$this->db->escape($ref)."'";
459 } elseif ($ref_ext) {
460 $sql .= " AND e.ref_ext = '".$this->db->escape($ref_ext)."'";
461 }
462 }
463
464 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
465 $result = $this->db->query($sql);
466 if ($result) {
467 if ($this->db->num_rows($result)) {
468 $obj = $this->db->fetch_object($result);
469
470 $this->id = $obj->rowid;
471 $this->entity = $obj->entity;
472 $this->ref = $obj->ref;
473 $this->socid = $obj->socid;
474 $this->ref_supplier = $obj->ref_supplier;
475 $this->ref_ext = $obj->ref_ext;
476 $this->statut = $obj->status;
477 $this->status = $obj->status;
478 $this->billed = $obj->billed;
479
480 $this->user_author_id = $obj->fk_user_author;
481 $this->fk_user_author = $obj->fk_user_author;
482 $this->fk_user_valid = $obj->fk_user_valid;
483 $this->date_valid = $this->db->jdate($obj->date_valid);
484 $this->date_creation = $this->db->jdate($obj->date_creation);
485 $this->date = $this->db->jdate($obj->date_reception); // TODO deprecated
486 $this->date_reception = $this->db->jdate($obj->date_reception); // Date real
487 $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planned
488 $this->date_valid = $this->db->jdate($obj->date_valid); // Date validation
489 $this->model_pdf = $obj->model_pdf;
490 $this->shipping_method_id = $obj->fk_shipping_method;
491 $this->tracking_number = $obj->tracking_number;
492 $this->origin = ($obj->origin ? $obj->origin : 'commande'); // For compatibility
493 $this->origin_type = ($obj->origin ? $obj->origin : 'commande'); // For compatibility
494 $this->origin_id = $obj->origin_id;
495
496 $this->trueWeight = $obj->weight;
497 $this->weight_units = $obj->weight_units;
498
499 $this->trueWidth = $obj->width;
500 $this->width_units = $obj->size_units;
501 $this->trueHeight = $obj->height;
502 $this->height_units = $obj->size_units;
503 $this->trueDepth = $obj->size;
504 $this->depth_units = $obj->size_units;
505
506 $this->note_public = $obj->note_public;
507 $this->note_private = $obj->note_private;
508
509 // A denormalized value
510 $this->trueSize = $obj->size."x".$obj->width."x".$obj->height;
511 $this->size_units = $obj->size_units;
512
513 //Incoterms
514 $this->fk_incoterms = $obj->fk_incoterms;
515 $this->location_incoterms = $obj->location_incoterms;
516 $this->label_incoterms = $obj->label_incoterms;
517
518 $this->db->free($result);
519
520 //$file = $conf->reception->dir_output."/".get_exdir(0, 0, 0, 1, $this, 'reception')."/".$this->id.".pdf";
521 //$this->pdf_filename = $file;
522
523 // Tracking url
524 $this->getUrlTrackingStatus($obj->tracking_number);
525
526 /*
527 * Thirdparty
528 */
529 $result = $this->fetch_thirdparty();
530
531
532 // Retrieve all extrafields for reception
533 // fetch optionals attributes and labels
534 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
535 $extrafields = new ExtraFields($this->db);
536 $extrafields->fetch_name_optionals_label($this->table_element, true);
537 $this->fetch_optionals();
538
539 /*
540 * Lines
541 */
542 $result = $this->fetch_lines();
543 if ($result < 0) {
544 return -3;
545 }
546
547 return 1;
548 } else {
549 dol_syslog(get_class($this).'::Fetch no reception found', LOG_ERR);
550 $this->error = 'Reception with id '.$id.' not found';
551 return 0;
552 }
553 } else {
554 $this->error = $this->db->error();
555 return -1;
556 }
557 }
558
566 public function valid($user, $notrigger = 0)
567 {
568 global $conf, $langs;
569
570 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
571
572 dol_syslog(get_class($this)."::valid");
573
574 // Protection
575 if ($this->statut) {
576 dol_syslog(get_class($this)."::valid no draft status", LOG_WARNING);
577 return 0;
578 }
579
580 if (!((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'creer'))
581 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'reception_advance', 'validate')))) {
582 $this->error = 'Permission denied';
583 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
584 return -1;
585 }
586
587 $this->db->begin();
588
589 $error = 0;
590
591 // Define new ref
592 $soc = new Societe($this->db);
593 $soc->fetch($this->socid);
594
595
596 // Define new ref
597 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
598 $numref = $this->getNextNumRef($soc);
599 } else {
600 $numref = $this->ref;
601 }
602
603 $this->newref = dol_sanitizeFileName($numref);
604
605 $now = dol_now();
606
607 // Validate
608 $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET";
609 $sql .= " ref='".$this->db->escape($numref)."'";
610 $sql .= ", fk_statut = 1";
611 $sql .= ", date_valid = '".$this->db->idate($now)."'";
612 $sql .= ", fk_user_valid = ".((int) $user->id);
613 $sql .= " WHERE rowid = ".((int) $this->id);
614 dol_syslog(get_class($this)."::valid update reception", LOG_DEBUG);
615 $resql = $this->db->query($sql);
616 if (!$resql) {
617 $this->error = $this->db->lasterror();
618 $error++;
619 }
620
621 // If stock increment is done on reception (recommended choice)
622 if (!$error && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION')) {
623 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
624
625 $langs->load("agenda");
626
627 // Loop on each product line to add a stock movement
628 // TODO in future, reception lines may not be linked to order line
629 $sql = "SELECT cd.fk_product, cd.subprice, cd.remise_percent,";
630 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
631 $sql .= " ed.eatby, ed.sellby, ed.batch,";
632 $sql .= " ed.cost_price";
633 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
634 $sql .= " ".MAIN_DB_PREFIX."receptiondet_batch as ed";
635 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
636 $sql .= " AND cd.rowid = ed.fk_elementdet";
637
638 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
639 $resql = $this->db->query($sql);
640 if ($resql) {
641 $cpt = $this->db->num_rows($resql);
642 for ($i = 0; $i < $cpt; $i++) {
643 $obj = $this->db->fetch_object($resql);
644
645 $qty = $obj->qty;
646
647 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
648 continue;
649 }
650
651 dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid);
652
653 //var_dump($this->lines[$i]);
654 $mouvS = new MouvementStock($this->db);
655 $mouvS->origin = &$this;
656 $mouvS->setOrigin($this->element, $this->id);
657
658 if (empty($obj->batch)) {
659 // line without batch detail
660
661 // 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.
662 $inventorycode = '';
663 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionValidatedInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
664
665 if (intval($result) < 0) {
666 $error++;
667 $this->setErrorsFromObject($mouvS);
668 break;
669 }
670 } else {
671 // line with batch detail
672
673 // 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.
674 // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version)
675 $inventorycode = '';
676 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionValidatedInDolibarr", $numref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
677
678 if (intval($result) < 0) {
679 $error++;
680 $this->setErrorsFromObject($mouvS);
681 break;
682 }
683 }
684 }
685 } else {
686 $this->db->rollback();
687 $this->error = $this->db->error();
688 return -2;
689 }
690 }
691
692 if (!$error) {
693 // Change status of purchase order to "reception in process" or "totally received"
694 $status = $this->getStatusDispatch();
695 if ($status < 0) {
696 $error++;
697 } else {
698 $trigger_key = '';
699 if ($this->origin_object instanceof CommandeFournisseur && $status == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) {
700 $ret = $this->origin_object->Livraison($user, dol_now(), 'tot', '');
701 if ($ret < 0) {
702 $error++;
703 $this->errors = array_merge($this->errors, $this->origin_object->errors);
704 }
705 } else {
706 $ret = $this->setStatut($status, $this->origin_id, 'commande_fournisseur', $trigger_key);
707 if ($ret < 0) {
708 $error++;
709 }
710 }
711 }
712 }
713
714 if (!$error && !$notrigger) {
715 // Call trigger
716 $result = $this->call_trigger('RECEPTION_VALIDATE', $user);
717 if ($result < 0) {
718 $error++;
719 }
720 // End call triggers
721 }
722
723 if (!$error) {
724 $this->oldref = $this->ref;
725
726 // Rename directory if dir was a temporary ref
727 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
728 // Now we rename also files into index
729 $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)."'";
730 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'reception/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity);
731 $resql = $this->db->query($sql);
732 if (!$resql) {
733 $error++;
734 $this->error = $this->db->lasterror();
735 }
736 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'reception/".$this->db->escape($this->newref)."'";
737 $sql .= " WHERE filepath = 'reception/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
738 $resql = $this->db->query($sql);
739 if (!$resql) {
740 $error++;
741 $this->error = $this->db->lasterror();
742 }
743
744 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
745 $oldref = dol_sanitizeFileName($this->ref);
746 $newref = dol_sanitizeFileName($numref);
747 $dirsource = $conf->reception->dir_output.'/'.$oldref;
748 $dirdest = $conf->reception->dir_output.'/'.$newref;
749 if (!$error && file_exists($dirsource)) {
750 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
751
752 if (@rename($dirsource, $dirdest)) {
753 dol_syslog("Rename ok");
754 // Rename docs starting with $oldref with $newref
755 $listoffiles = dol_dir_list($conf->reception->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
756 foreach ($listoffiles as $fileentry) {
757 $dirsource = $fileentry['name'];
758 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
759 $dirsource = $fileentry['path'].'/'.$dirsource;
760 $dirdest = $fileentry['path'].'/'.$dirdest;
761 @rename($dirsource, $dirdest);
762 }
763 }
764 }
765 }
766 }
767
768 // Set new ref and current status
769 if (!$error) {
770 $this->ref = $numref;
771 $this->statut = self::STATUS_VALIDATED;
772 $this->status = self::STATUS_VALIDATED;
773 }
774
775 if (!$error) {
776 $this->db->commit();
777 return 1;
778 } else {
779 foreach ($this->errors as $errmsg) {
780 dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR);
781 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
782 }
783 $this->db->rollback();
784 return -1 * $error;
785 }
786 }
787
793 public function getStatusDispatch()
794 {
795 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
796 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
797
799
800 if (!empty($this->origin) && $this->origin_id > 0 && ($this->origin == 'order_supplier' || $this->origin == 'commandeFournisseur')) {
801 if (empty($this->origin_object)) {
802 $this->fetch_origin();
803 if ($this->origin_object instanceof CommonObject && empty($this->origin_object->lines)) {
804 $res = $this->origin_object->fetch_lines();
805 $this->commandeFournisseur = null; // deprecated
806 if ($res < 0) {
807 return $res;
808 }
809 } elseif ($this->origin_object instanceof CommandeFournisseur && empty($this->origin_object->lines)) {
810 $res = $this->origin_object->fetch_lines();
811 $this->commandeFournisseur = $this->origin_object; // deprecated
812 if ($res < 0) {
813 return $res;
814 }
815 }
816 }
817
818 $qty_received = array();
819 $qty_wished = array();
820
821 $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
822 $filter = array('t.fk_element' => $this->origin_id);
823 if (getDolGlobalInt('SUPPLIER_ORDER_USE_DISPATCH_STATUS')) {
824 $filter['t.status'] = 1; // Restrict to lines with status validated
825 }
826
827 $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
828 if ($ret < 0) {
829 $this->setErrorsFromObject($supplierorderdispatch);
830 return $ret;
831 } else {
832 // Lines of draft receptions are not received yet
833 $draft_lines = array();
834 $sql = "SELECT rb.rowid FROM ".MAIN_DB_PREFIX."receptiondet_batch as rb";
835 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."reception as r ON r.rowid = rb.fk_reception";
836 $sql .= " WHERE rb.fk_element = ".((int) $this->origin_id);
837 $sql .= " AND r.fk_statut = ".self::STATUS_DRAFT;
838 $resql = $this->db->query($sql);
839 if (!$resql) {
840 $this->error = $this->db->lasterror();
841 return -1;
842 }
843 while ($obj = $this->db->fetch_object($resql)) {
844 $draft_lines[(int) $obj->rowid] = (int) $obj->rowid;
845 }
846 $this->db->free($resql);
847
848 // build array with quantity received by product in all supplier orders (origin)
849 foreach ($supplierorderdispatch->lines as $dispatch_line) {
850 if (isset($draft_lines[(int) $dispatch_line->id])) {
851 continue;
852 }
853 if (array_key_exists($dispatch_line->fk_product, $qty_received)) {
854 $qty_received[$dispatch_line->fk_product] += $dispatch_line->qty;
855 } else {
856 $qty_received[$dispatch_line->fk_product] = $dispatch_line->qty;
857 }
858 }
859
860 // qty wished in origin (purchase order, ...)
861 foreach ($this->origin_object->lines as $origin_line) {
862 // exclude lines not qualified for reception
863 if ((!getDolGlobalInt('STOCK_SUPPORTS_SERVICES') && $origin_line->product_type > 0) || $origin_line->product_type > 1) {
864 continue;
865 }
866 if (array_key_exists($origin_line->fk_product, $qty_wished)) {
867 $qty_wished[$origin_line->fk_product] += $origin_line->qty;
868 } else {
869 $qty_wished[$origin_line->fk_product] = $origin_line->qty;
870 }
871 }
872
873 // compare array
874 $diff_array = array_diff_assoc($qty_received, $qty_wished); // Warning: $diff_array is done only on common keys.
875 $keys_in_wished_not_in_received = array_diff(array_keys($qty_wished), array_keys($qty_received));
876 $keys_in_received_not_in_wished = array_diff(array_keys($qty_received), array_keys($qty_wished));
877
878 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
880 } elseif (getDolGlobalInt('SUPPLIER_ORDER_MORE_THAN_WISHED')) {
881 // set totally received if more products received than ordered
882 $close = 0;
883
884 if (count($diff_array) > 0) {
885 // there are some difference between the two arrays
886 // scan the array of results
887 foreach ($diff_array as $key => $value) {
888 // if the quantity delivered is greater or equal to ordered quantity @phan-suppress-next-line PhanTypeInvalidDimOffset
889 if ($qty_received[$key] >= $qty_wished[$key]) {
890 $close++;
891 }
892 }
893 }
894
895 if ($close == count($diff_array)) {
896 // all the products are received equal or more than the ordered quantity
898 }
899 }
900 }
901 }
902
903 return $status;
904 }
905
922 public function addline($entrepot_id, $id, $qty, $array_options = [], $comment = '', $eatby = null, $sellby = null, $batch = '', $cost_price = 0)
923 {
924 global $conf, $langs, $user;
925
926 $num = count($this->lines);
927 $line = new CommandeFournisseurDispatch($this->db);
928
929 $line->fk_entrepot = $entrepot_id;
930 $line->fk_commandefourndet = $id;
931 $line->qty = $qty;
932
933 $supplierorderline = new CommandeFournisseurLigne($this->db);
934 $result = $supplierorderline->fetch($id);
935 if ($result <= 0) {
936 $this->setErrorsFromObject($supplierorderline);
937 return -1;
938 }
939
940 $fk_product = 0;
941 if (isModEnabled('stock') && !empty($supplierorderline->fk_product)) {
942 $fk_product = $supplierorderline->fk_product;
943
944 if (!($entrepot_id > 0) && !getDolGlobalInt('STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS')) {
945 $langs->load("errors");
946 $this->error = $langs->trans("ErrorWarehouseRequiredIntoReceptionLine");
947 return -1;
948 }
949 }
950
951 // Check batch is set
952 $product = new Product($this->db);
953 $product->fetch($fk_product);
954 if (isModEnabled('productbatch')) {
955 $langs->load("errors");
956 if (!empty($product->status_batch) && empty($batch)) {
957 $this->error = $langs->trans('ErrorProductNeedBatchNumber', $product->ref);
958 return -1;
959 } elseif (empty($product->status_batch) && !empty($batch)) {
960 $this->error = $langs->trans('ErrorProductDoesNotNeedBatchNumber', $product->ref);
961 return -1;
962 }
963
964 // check sell-by / eat-by date is mandatory
965 $errorMsgArr = Productlot::checkSellOrEatByMandatoryFromProductAndDates($product, $sellby, $eatby);
966 if (!empty($errorMsgArr)) {
967 $errorMessage = '<b>' . $product->ref . '</b> : ';
968 $errorMessage .= '<ul>';
969 foreach ($errorMsgArr as $errorMsg) {
970 $errorMessage .= '<li>' . $errorMsg . '</li>';
971 }
972 $errorMessage .= '</ul>';
973 $this->error = $errorMessage;
974 return -1;
975 }
976 }
977 unset($product);
978
979 // extrafields
980 $line->array_options = $supplierorderline->array_options;
981 if (!getDolGlobalInt('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) {
982 foreach ($array_options as $key => $value) {
983 $line->array_options[$key] = $value;
984 }
985 }
986
987 $line->fk_product = $fk_product;
988 $line->fk_commande = $supplierorderline->fk_commande;
989 $line->fk_user = $user->id;
990 $line->comment = $comment;
991 $line->batch = $batch;
992 $line->eatby = $eatby;
993 $line->sellby = $sellby;
994 $line->status = 1;
995 $line->cost_price = $cost_price;
996 $line->fk_reception = $this->id;
997
998 $this->lines[$num] = $line;
999
1000 return $num;
1001 }
1002
1003
1011 public function update($user = null, $notrigger = 0)
1012 {
1013 global $conf;
1014 $error = 0;
1015
1016 // Clean parameters
1017
1018 if (isset($this->ref)) {
1019 $this->ref = trim($this->ref);
1020 }
1021 if (isset($this->entity)) {
1022 $this->entity = (int) $this->entity;
1023 }
1024 if (isset($this->ref_supplier)) {
1025 $this->ref_supplier = trim($this->ref_supplier);
1026 }
1027 if (isset($this->socid)) {
1028 $this->socid = (int) trim((string) $this->socid);
1029 }
1030 if (isset($this->fk_user_author)) {
1031 $this->fk_user_author = (int) $this->fk_user_author;
1032 }
1033 if (isset($this->fk_user_valid)) {
1034 $this->fk_user_valid = (int) $this->fk_user_valid;
1035 }
1036 if (isset($this->shipping_method_id)) {
1037 $this->shipping_method_id = (int) $this->shipping_method_id;
1038 }
1039 if (isset($this->tracking_number)) {
1040 $this->tracking_number = trim($this->tracking_number);
1041 }
1042 if (isset($this->statut)) {
1043 $this->statut = (int) $this->statut;
1044 }
1045 if (isset($this->trueDepth)) {
1046 $this->trueDepth = price2num($this->trueDepth);
1047 }
1048 if (isset($this->trueWidth)) {
1049 $this->trueWidth = price2num($this->trueWidth);
1050 }
1051 if (isset($this->trueHeight)) {
1052 $this->trueHeight = price2num($this->trueHeight);
1053 }
1054 $this->size_units = (int) $this->size_units;
1055
1056 if (isset($this->trueWeight)) {
1057 $this->weight = price2num($this->trueWeight);
1058 }
1059 $this->weight_units = (int) $this->weight_units;
1060
1061 if (isset($this->note_private)) {
1062 $this->note_private = trim($this->note_private);
1063 }
1064 if (isset($this->note_public)) {
1065 $this->note_public = trim($this->note_public);
1066 }
1067 if (isset($this->model_pdf)) {
1068 $this->model_pdf = trim($this->model_pdf);
1069 }
1070
1071
1072 // Check parameters
1073 // Put here code to add control on parameters values
1074
1075 // Update request
1076 $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET";
1077
1078 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1079 $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1080 $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
1081 $sql .= " date_creation=".(dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1082 $sql .= " fk_user_author=".(isset($this->fk_user_author) ? $this->fk_user_author : "null").",";
1083 $sql .= " date_valid=".(dol_strlen($this->date_valid) != 0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
1084 $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
1085 $sql .= " date_reception=".(dol_strlen($this->date_reception) != 0 ? "'".$this->db->idate($this->date_reception)."'" : 'null').",";
1086 $sql .= " date_delivery=".(dol_strlen($this->date_delivery) != 0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
1087 $sql .= " fk_shipping_method=".((isset($this->shipping_method_id) && $this->shipping_method_id > 0) ? $this->shipping_method_id : "null").",";
1088 $sql .= " tracking_number=".(isset($this->tracking_number) ? "'".$this->db->escape($this->tracking_number)."'" : "null").",";
1089 $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
1090 $sql .= " height=".(($this->trueHeight != '') ? (float) $this->trueHeight : "null").",";
1091 $sql .= " width=".(($this->trueWidth != '') ? (float) $this->trueWidth : "null").",";
1092 $sql .= " size_units=".((int) $this->size_units).",";
1093 $sql .= " size=".(($this->trueDepth != '') ? (float) $this->trueDepth : "null").",";
1094 $sql .= " weight_units=".((int) $this->weight_units).",";
1095 $sql .= " weight=".(($this->trueWeight != '') ? (float) $this->trueWeight : "null").",";
1096 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1097 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1098 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1099 $sql .= " entity = ".((int) $conf->entity);
1100 $sql .= " WHERE rowid=".((int) $this->id);
1101
1102 $this->db->begin();
1103
1104 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1105 $resql = $this->db->query($sql);
1106 if (!$resql) {
1107 $error++;
1108 $this->errors[] = "Error ".$this->db->lasterror();
1109 }
1110
1111 if (!$error) {
1112 if (!$notrigger) {
1113 // Call trigger
1114 $result = $this->call_trigger('RECEPTION_MODIFY', $user);
1115 if ($result < 0) {
1116 $error++;
1117 }
1118 // End call triggers
1119 }
1120 }
1121
1122 // Commit or rollback
1123 if ($error) {
1124 foreach ($this->errors as $errmsg) {
1125 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1126 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1127 }
1128 $this->db->rollback();
1129 return -1 * $error;
1130 } else {
1131 $this->db->commit();
1132 return 1;
1133 }
1134 }
1135
1142 public function delete(User $user)
1143 {
1144 global $conf, $langs, $user;
1145 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1146
1147 $error = 0;
1148 $this->error = '';
1149
1150
1151 $this->db->begin();
1152
1153 // Stock control
1154 if (isModEnabled('stock') && ((getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION') && $this->status > Reception::STATUS_DRAFT)
1155 || (getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE') && $this->status == Reception::STATUS_CLOSED))
1156 ) {
1157 require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
1158
1159 $langs->load("agenda");
1160
1161 // Loop on each product line to add a stock movement
1162 $sql = "SELECT cd.fk_product, cd.subprice, ed.qty, ed.fk_entrepot, ed.eatby, ed.sellby, ed.batch, ed.rowid as receptiondet_batch_id";
1163 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
1164 $sql .= " ".MAIN_DB_PREFIX."receptiondet_batch as ed";
1165 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
1166 $sql .= " AND cd.rowid = ed.fk_elementdet";
1167
1168 dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
1169 $resql = $this->db->query($sql);
1170 if ($resql) {
1171 $cpt = $this->db->num_rows($resql);
1172 for ($i = 0; $i < $cpt; $i++) {
1173 dol_syslog(get_class($this)."::delete movement index ".$i);
1174 $obj = $this->db->fetch_object($resql);
1175
1176 // Same lines as the ones that moved the stock in valid() and setClosed()
1177 if ($obj->qty == 0 || ($obj->qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
1178 continue;
1179 }
1180
1181 $mouvS = new MouvementStock($this->db);
1182 // we do not log origin because it will be deleted
1183 $mouvS->origin = null;
1184
1185 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("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
1186 if ($result < 0) {
1187 $error++;
1188 $this->error = $mouvS->error;
1189 $this->errors = $mouvS->errors;
1190 }
1191 }
1192 } else {
1193 $error++;
1194 $this->errors[] = "Error ".$this->db->lasterror();
1195 }
1196 }
1197
1198 if (!$error) {
1199 $main = MAIN_DB_PREFIX.'receptiondet_batch';
1200 $ef = $main."_extrafields";
1201
1202 $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_reception = ".((int) $this->id).")";
1203
1204 $sql = "DELETE FROM ".MAIN_DB_PREFIX."receptiondet_batch";
1205 $sql .= " WHERE fk_reception = ".((int) $this->id);
1206
1207 if ($this->db->query($sqlef) && $this->db->query($sql)) {
1208 // Delete linked object
1209 $res = $this->deleteObjectLinked();
1210 if ($res < 0) {
1211 $error++;
1212 }
1213
1214 if (!$error) {
1215 $sql = "DELETE FROM ".MAIN_DB_PREFIX."reception";
1216 $sql .= " WHERE rowid = ".((int) $this->id);
1217
1218 if ($this->db->query($sql)) {
1219 // Call trigger
1220 $result = $this->call_trigger('RECEPTION_DELETE', $user);
1221 if ($result < 0) {
1222 $error++;
1223 }
1224 // End call triggers
1225
1226 if (!empty($this->origin) && $this->origin_id > 0) {
1227 $this->fetch_origin();
1229 '@phan-var-force CommandeFournisseur $origin_object';
1230 if ($origin_object->statut == 4) { // If order source of reception is "partially received"
1231 // Check if there is no more reception. If not, we can move back status of order to "validated" instead of "reception in progress"
1232 $origin_object->loadReceptions();
1233 //var_dump($this->$origin->receptions);exit;
1234 if (count($origin_object->receptions) <= 0) {
1235 $origin_object->setStatut(3); // ordered
1236 }
1237 }
1238 }
1239
1240 if (!$error) {
1241 $this->db->commit();
1242
1243 // We delete PDFs
1244 $ref = dol_sanitizeFileName($this->ref);
1245 if (!empty($conf->reception->dir_output)) {
1246 $dir = $conf->reception->dir_output.'/'.$ref;
1247 $file = $dir.'/'.$ref.'.pdf';
1248 if (file_exists($file)) {
1249 if (!dol_delete_file($file)) {
1250 return 0;
1251 }
1252 }
1253 if (file_exists($dir)) {
1254 if (!dol_delete_dir_recursive($dir)) {
1255 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
1256 return 0;
1257 }
1258 }
1259 }
1260
1261 return 1;
1262 } else {
1263 $this->db->rollback();
1264 return -1;
1265 }
1266 } else {
1267 $this->error = $this->db->lasterror()." - sql=$sql";
1268 $this->db->rollback();
1269 return -3;
1270 }
1271 } else {
1272 $this->error = $this->db->lasterror()." - sql=$sql";
1273 $this->db->rollback();
1274 return -2;
1275 }
1276 } else {
1277 $this->error = $this->db->lasterror()." - sql=$sql";
1278 $this->db->rollback();
1279 return -1;
1280 }
1281 } else {
1282 $this->db->rollback();
1283 return -1;
1284 }
1285 }
1286
1287 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1293 public function fetch_lines()
1294 {
1295 // phpcs:enable
1296 $this->lines = array();
1297
1298 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
1299
1300 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."receptiondet_batch";
1301 $sql .= " WHERE fk_reception = ".((int) $this->id);
1302
1303 $resql = $this->db->query($sql);
1304
1305 if (!empty($resql)) {
1306 while ($obj = $this->db->fetch_object($resql)) {
1307 $line = new CommandeFournisseurDispatch($this->db);
1308
1309 $line->fetch($obj->rowid);
1310
1311 // TODO Remove or keep this ?
1312 $line->fetch_product();
1313
1314 $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';
1315 $sql_commfourndet .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet';
1316 $sql_commfourndet .= ' WHERE rowid = '.((int) $line->fk_commandefourndet);
1317 $sql_commfourndet .= ' ORDER BY rang';
1318
1319 $resql_commfourndet = $this->db->query($sql_commfourndet);
1320 if (!empty($resql_commfourndet)) {
1321 $obj = $this->db->fetch_object($resql_commfourndet);
1322 $line->qty_asked = $obj->qty;
1323 $line->description = $obj->description;
1324 $line->desc = $obj->description;
1325 $line->tva_tx = $obj->tva_tx;
1326 $line->vat_src_code = $obj->vat_src_code;
1327 $line->localtax1_tx = $obj->localtax1_tx;
1328 $line->localtax2_tx = $obj->localtax2_tx;
1329 $line->subprice = $obj->subprice;
1330 $line->multicurrency_subprice = $obj->multicurrency_subprice;
1331 $line->remise_percent = $obj->remise_percent;
1332 $line->label = !empty($obj->label) ? $obj->label : (is_object($line->product) ? $line->product->label : '');
1333 $line->ref_supplier = $obj->ref;
1334 $line->total_ht = $obj->total_ht;
1335 $line->total_ttc = $obj->total_ttc;
1336 $line->total_tva = $obj->total_tva;
1337 $line->date_start = $this->db->jdate($obj->date_start);
1338 $line->date_end = $this->db->jdate($obj->date_end);
1339 $line->product_type = $obj->product_type;
1340 } else {
1341 $line->qty_asked = 0;
1342 $line->description = '';
1343 $line->desc = '';
1344 $line->label = $obj->label;
1345 }
1346
1347 $pu_ht = ($line->subprice * $line->qty) * (100 - $line->remise_percent) / 100;
1348 $tva = $pu_ht * $line->tva_tx / 100;
1349 $this->total_ht += $pu_ht;
1350 $this->total_tva += $pu_ht * $line->tva_tx / 100;
1351
1352 $this->total_ttc += $pu_ht + $tva;
1353
1354 if (isModEnabled('productbatch') && !empty($line->batch)) {
1355 $detail_batch = new stdClass();
1356 $detail_batch->eatby = $line->eatby;
1357 $detail_batch->sellby = $line->sellby;
1358 $detail_batch->batch = $line->batch;
1359 $detail_batch->qty = $line->qty;
1360
1361 $line->detail_batch[] = $detail_batch;
1362 }
1363
1364 $this->lines[] = $line;
1365 }
1366
1367 return 1;
1368 } else {
1369 return -1;
1370 }
1371 }
1372
1383 public function getNomUrl($withpicto = 0, $option = 0, $max = 0, $short = 0, $notooltip = 0)
1384 {
1385 global $langs, $hookmanager;
1386
1387 $result = '';
1388 $label = img_picto('', $this->picto).' <u>'.$langs->trans("Reception").'</u>';
1389 $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1390 $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.($this->ref_supplier ? $this->ref_supplier : '');
1391
1392 $url = DOL_URL_ROOT.'/reception/card.php?id='.$this->id;
1393
1394 if ($short) {
1395 return $url;
1396 }
1397
1398 $linkclose = '';
1399 if (empty($notooltip)) {
1400 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1401 $label = $langs->trans("Reception");
1402 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1403 }
1404 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
1405 $linkclose .= ' class="classfortooltip"';
1406 }
1407
1408 $linkstart = '<a href="'.$url.'"';
1409 $linkstart .= $linkclose.'>';
1410 $linkend = '</a>';
1411
1412 $result .= $linkstart;
1413 if ($withpicto) {
1414 $result .= img_object(($notooltip ? '' : $label), $this->picto, '', 0, 0, $notooltip ? 0 : 1);
1415 }
1416 if ($withpicto != 2) {
1417 $result .= $this->ref;
1418 }
1419
1420 $result .= $linkend;
1421
1422 global $action;
1423 $hookmanager->initHooks(array($this->element . 'dao'));
1424 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1425 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1426 if ($reshook > 0) {
1427 $result = $hookmanager->resPrint;
1428 } else {
1429 $result .= $hookmanager->resPrint;
1430 }
1431 return $result;
1432 }
1433
1440 public function getLibStatut($mode = 0)
1441 {
1442 return $this->LibStatut($this->statut, $mode);
1443 }
1444
1445 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1453 public function LibStatut($status, $mode)
1454 {
1455 // phpcs:enable
1456 global $langs;
1457
1458 // List of long language codes for status
1459 $this->labelStatus[-1] = 'StatusReceptionCanceled';
1460 $this->labelStatus[0] = 'StatusReceptionDraft';
1461 // product to receive if stock increase is on close or already received if stock increase is on validation
1462 $this->labelStatus[1] = 'StatusReceptionValidated';
1463 if (getDolGlobalInt("STOCK_CALCULATE_ON_RECEPTION")) {
1464 $this->labelStatus[1] = 'StatusReceptionValidatedReceived';
1465 }
1466 if (getDolGlobalInt("STOCK_CALCULATE_ON_RECEPTION_CLOSE")) {
1467 $this->labelStatus[1] = 'StatusReceptionValidatedToReceive';
1468 }
1469 $this->labelStatus[2] = 'StatusReceptionProcessed';
1470
1471 // List of short language codes for status
1472 $this->labelStatusShort[-1] = 'StatusReceptionCanceledShort';
1473 $this->labelStatusShort[0] = 'StatusReceptionDraftShort';
1474 $this->labelStatusShort[1] = 'StatusReceptionValidatedShort';
1475 $this->labelStatusShort[2] = 'StatusReceptionProcessedShort';
1476
1477 $labelStatus = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
1478 $labelStatusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
1479
1480 $statusType = 'status'.$status;
1481 if ($status == self::STATUS_VALIDATED) {
1482 $statusType = 'status4';
1483 }
1484 if ($status == self::STATUS_CLOSED) {
1485 $statusType = 'status6';
1486 }
1487
1488 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
1489 }
1490
1498 public function getKanbanView($option = '', $arraydata = null)
1499 {
1500 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1501
1502 $return = '<div class="box-flex-item box-flex-grow-zero">';
1503 $return .= '<div class="info-box info-box-sm">';
1504 $return .= '<div class="info-box-icon bg-infobox-action">';
1505 $return .= img_picto('', 'order');
1506 $return .= '</div>';
1507 $return .= '<div class="info-box-content">';
1508 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
1509 if ($selected >= 0) {
1510 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
1511 }
1512 if (property_exists($this, 'thirdparty') && is_object($this->thirdparty)) {
1513 $return .= '<br><div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
1514 }
1515 /*if (property_exists($this, 'total_ht')) {
1516 $return .= '<div class="info-box-ref amount">'.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency).' '.$langs->trans('HT').'</div>';
1517 }*/
1518 if (method_exists($this, 'getLibStatut')) {
1519 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
1520 }
1521 $return .= '</div>';
1522 $return .= '</div>';
1523 $return .= '</div>';
1524
1525 return $return;
1526 }
1527
1535 public function initAsSpecimen()
1536 {
1537 global $langs;
1538
1539 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1540 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
1541 $now = dol_now();
1542
1543 dol_syslog(get_class($this)."::initAsSpecimen");
1544
1545 $order = new CommandeFournisseur($this->db);
1546 $order->initAsSpecimen();
1547
1548 // Initialise parameters
1549 $this->id = 0;
1550 $this->ref = 'SPECIMEN';
1551 $this->specimen = 1;
1552 $this->statut = 1;
1553 $this->status = 1;
1554 $this->date = $now;
1555 $this->date_creation = $now;
1556 $this->date_valid = $now;
1557 $this->date_delivery = $now;
1558 $this->date_reception = $now + 24 * 3600;
1559
1560 $this->entrepot_id = 0;
1561 $this->socid = 1;
1562
1563 $this->origin_id = 1;
1564 $this->origin_type = 'supplier_order';
1565 $this->origin_object = $order;
1566
1567 $this->note_private = 'Private note';
1568 $this->note_public = 'Public note';
1569
1570 $this->tracking_number = 'TRACKID-ABC123';
1571
1572 $this->fk_incoterms = 1;
1573
1574 $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)
1575 $xnbp = 0;
1576 while ($xnbp < $nbp) {
1577 $line = new CommandeFournisseurDispatch($this->db);
1578 $line->desc = $langs->trans("Description")." ".$xnbp;
1579 $line->libelle = $langs->trans("Description")." ".$xnbp; // deprecated
1580 $line->label = $langs->trans("Description")." ".$xnbp;
1581 $line->qty = 10;
1582
1583 $line->fk_product = $this->origin_object->lines[$xnbp]->fk_product;
1584
1585 $this->lines[] = $line;
1586 $xnbp++;
1587 }
1588
1589 return 1;
1590 }
1591
1599 public function setDeliveryDate($user, $delivery_date)
1600 {
1601 // phpcs:enable
1602 if ($user->hasRight('reception', 'creer')) {
1603 $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
1604 $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
1605 $sql .= " WHERE rowid = ".((int) $this->id);
1606
1607 dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
1608 $resql = $this->db->query($sql);
1609 if ($resql) {
1610 $this->date_delivery = $delivery_date;
1611 return 1;
1612 } else {
1613 $this->error = $this->db->error();
1614 return -1;
1615 }
1616 } else {
1617 return -2;
1618 }
1619 }
1620
1621 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1627 public function fetch_delivery_methods()
1628 {
1629 // phpcs:enable
1630 global $langs;
1631 $this->meths = array();
1632
1633 $sql = "SELECT em.rowid, em.code, em.libelle";
1634 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1635 $sql .= " WHERE em.active = 1";
1636 $sql .= " ORDER BY em.libelle ASC";
1637
1638 $resql = $this->db->query($sql);
1639 if ($resql) {
1640 while ($obj = $this->db->fetch_object($resql)) {
1641 $label = $langs->trans('ReceptionMethod'.$obj->code);
1642 $this->meths[$obj->rowid] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
1643 }
1644 }
1645 }
1646
1647 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1654 public function list_delivery_methods($id = 0)
1655 {
1656 // phpcs:enable
1657 global $langs;
1658
1659 $this->listmeths = array();
1660 $i = 0;
1661
1662 $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active";
1663 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1664 if (!empty($id)) {
1665 $sql .= " WHERE em.rowid = ".((int) $id);
1666 }
1667
1668 $resql = $this->db->query($sql);
1669 if ($resql) {
1670 while ($obj = $this->db->fetch_object($resql)) {
1671 $this->listmeths[$i]['rowid'] = $obj->rowid;
1672 $this->listmeths[$i]['code'] = $obj->code;
1673 $label = $langs->trans('ReceptionMethod'.$obj->code);
1674 $this->listmeths[$i]['libelle'] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
1675 $this->listmeths[$i]['description'] = $obj->description;
1676 $this->listmeths[$i]['tracking'] = $obj->tracking;
1677 $this->listmeths[$i]['active'] = $obj->active;
1678 $i++;
1679 }
1680 }
1681 }
1682
1689 public function getUrlTrackingStatus($value = '')
1690 {
1691 if (!empty($this->shipping_method_id)) {
1692 $sql = "SELECT em.code, em.tracking";
1693 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1694 $sql .= " WHERE em.rowid = ".((int) $this->shipping_method_id);
1695
1696 $resql = $this->db->query($sql);
1697 if ($resql) {
1698 if ($obj = $this->db->fetch_object($resql)) {
1699 $tracking = $obj->tracking;
1700 }
1701 }
1702 }
1703
1704 if (!empty($tracking) && !empty($value)) {
1705 $url = str_replace('{TRACKID}', $value, $tracking);
1706 $this->tracking_url = sprintf('<a target="_blank" rel="noopener noreferrer" href="%s">%s</a>', $url, ($value ? $value : 'url'));
1707 } else {
1708 $this->tracking_url = $value;
1709 }
1710 }
1711
1717 public function setClosed()
1718 {
1719 global $conf, $langs, $user;
1720
1721 $error = 0;
1722
1723 // Protection. This avoid to move stock later when we should not
1724 if ($this->statut == Reception::STATUS_CLOSED) {
1725 dol_syslog(get_class($this)."::setClosed already in closed status", LOG_WARNING);
1726 return 0;
1727 }
1728 // Only a validated reception can be closed (a draft reception must not move stock)
1729 if ($this->statut != Reception::STATUS_VALIDATED) {
1730 $langs->load("receptions");
1731 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionValidatedShort'));
1732 dol_syslog(get_class($this)."::setClosed reception is not validated", LOG_WARNING);
1733 return -1;
1734 }
1735
1736 $this->db->begin();
1737
1738 $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut = '.self::STATUS_CLOSED;
1739 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut = '.self::STATUS_VALIDATED;
1740
1741 $resql = $this->db->query($sql);
1742 if ($resql && $this->db->affected_rows($resql) <= 0) {
1743 // Status in database is not validated (already closed or back to draft): no stock movement
1744 $this->db->rollback();
1745 $langs->load("receptions");
1746 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionValidatedShort'));
1747 dol_syslog(get_class($this)."::setClosed reception is not validated in database", LOG_WARNING);
1748 return -1;
1749 }
1750 if ($resql) {
1751 // Set order billed if 100% of order is received (qty in reception lines match qty in order lines)
1752 if ($this->origin == 'order_supplier' && $this->origin_id > 0) {
1753 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1754
1755 $order = new CommandeFournisseur($this->db);
1756 $order->fetch($this->origin_id);
1757
1758 $order->loadReceptions(self::STATUS_CLOSED); // Fill $order->receptions = array(orderlineid => qty)
1759
1760 $receptions_match_order = 1;
1761 foreach ($order->lines as $line) {
1762 $lineid = $line->id;
1763 $qty = $line->qty;
1764 if (($line->product_type == 0 || getDolGlobalInt('STOCK_SUPPORTS_SERVICES')) && $order->receptions[$lineid] < $qty) {
1765 $receptions_match_order = 0;
1766 $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';
1767 dol_syslog($text);
1768 break;
1769 }
1770 }
1771 if ($receptions_match_order) {
1772 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');
1773 $order->Livraison($user, dol_now(), 'tot', 'Reception '.$this->ref);
1774 }
1775 }
1776
1777 $this->statut = self::STATUS_CLOSED;
1778 $this->status = self::STATUS_CLOSED;
1779
1780 // If stock increment is done on closing
1781 if (!$error && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE')) {
1782 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1783
1784 $langs->load("agenda");
1785
1786 // Loop on each product line to add a stock movement
1787 // TODO possibilite de receptionner a partir d'une propale ou autre origine ?
1788 $sql = "SELECT cd.fk_product, cd.subprice,";
1789 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
1790 $sql .= " ed.eatby, ed.sellby, ed.batch,";
1791 $sql .= " ed.cost_price";
1792 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
1793 $sql .= " ".MAIN_DB_PREFIX."receptiondet_batch as ed";
1794 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
1795 $sql .= " AND cd.rowid = ed.fk_elementdet";
1796
1797 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
1798 $resql = $this->db->query($sql);
1799
1800 if ($resql) {
1801 $cpt = $this->db->num_rows($resql);
1802 for ($i = 0; $i < $cpt; $i++) {
1803 $obj = $this->db->fetch_object($resql);
1804
1805 $qty = $obj->qty;
1806
1807 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
1808 continue;
1809 }
1810
1811 dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid);
1812
1813 $mouvS = new MouvementStock($this->db);
1814 $mouvS->origin = &$this;
1815 $mouvS->setOrigin($this->element, $this->id);
1816
1817 if (empty($obj->batch)) {
1818 // line without batch detail
1819
1820 // 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
1821 $inventorycode = '';
1822 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionClassifyClosedInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
1823 if ($result < 0) {
1824 $this->error = $mouvS->error;
1825 $this->errors = $mouvS->errors;
1826 $error++;
1827 break;
1828 }
1829 } else {
1830 // line with batch detail
1831
1832 // 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
1833 $inventorycode = '';
1834 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionClassifyClosedInDolibarr", $this->ref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
1835
1836 if ($result < 0) {
1837 $this->error = $mouvS->error;
1838 $this->errors = $mouvS->errors;
1839 $error++;
1840 break;
1841 }
1842 }
1843 }
1844 } else {
1845 $this->error = $this->db->lasterror();
1846 $error++;
1847 }
1848 }
1849
1850 // Call trigger
1851 if (!$error) {
1852 $result = $this->call_trigger('RECEPTION_CLOSED', $user);
1853 if ($result < 0) {
1854 $error++;
1855 }
1856 }
1857 } else {
1858 dol_print_error($this->db);
1859 $error++;
1860 }
1861
1862 if (!$error) {
1863 $this->db->commit();
1864 return 1;
1865 } else {
1866 $this->statut = self::STATUS_VALIDATED;
1867 $this->status = self::STATUS_VALIDATED;
1868 $this->db->rollback();
1869 return -1;
1870 }
1871 }
1872
1878 public function setBilled()
1879 {
1880 global $user;
1881 $error = 0;
1882
1883 $this->db->begin();
1884
1885 if ($this->statut == Reception::STATUS_VALIDATED) {
1886 // do not close if already closed
1887 $this->setClosed();
1888 }
1889
1890 $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET billed=1';
1891 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
1892
1893 $resql = $this->db->query($sql);
1894 if ($resql) {
1895 $this->billed = 1;
1896
1897 // Call trigger
1898 $result = $this->call_trigger('RECEPTION_BILLED', $user);
1899 if ($result < 0) {
1900 $this->billed = 0;
1901 $error++;
1902 }
1903 } else {
1904 $error++;
1905 $this->errors[] = $this->db->lasterror;
1906 }
1907
1908 if (empty($error)) {
1909 $this->db->commit();
1910 return 1;
1911 } else {
1912 $this->db->rollback();
1913 return -1;
1914 }
1915 }
1916
1922 public function reOpen()
1923 {
1924 global $conf, $langs, $user;
1925
1926 $error = 0;
1927
1928 // Protection: only a closed reception can be reopened (with stock on closing, it removes the stock added by the closing)
1929 if ($this->statut != self::STATUS_CLOSED) {
1930 $langs->load("receptions");
1931 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionProcessedShort'));
1932 return -1;
1933 }
1934
1935 $this->db->begin();
1936
1937 $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut=1, billed=0';
1938 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut = '.self::STATUS_CLOSED;
1939
1940 $resql = $this->db->query($sql);
1941 if ($resql) {
1942 if ($this->db->affected_rows($resql) <= 0) {
1943 // Status in database is not closed (reopened meanwhile): no stock movement
1944 $this->db->rollback();
1945 $langs->load("receptions");
1946 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv('StatusReceptionProcessedShort'));
1947 return -1;
1948 }
1949 $this->statut = self::STATUS_VALIDATED;
1950 $this->status = self::STATUS_VALIDATED;
1951 $this->billed = 0;
1952
1953 // If stock increment is done on closing
1954 if (!$error && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE')) {
1955 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1956 $numref = $this->ref;
1957 $langs->load("agenda");
1958
1959 // Loop on each product line to add a stock movement
1960 // TODO possibilite de receptionner a partir d'une propale ou autre origine
1961 $sql = "SELECT ed.fk_product, cd.subprice,";
1962 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
1963 $sql .= " ed.eatby, ed.sellby, ed.batch,";
1964 $sql .= " ed.cost_price";
1965 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
1966 $sql .= " ".MAIN_DB_PREFIX."receptiondet_batch as ed";
1967 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
1968 $sql .= " AND cd.rowid = ed.fk_elementdet";
1969
1970 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
1971 $resql = $this->db->query($sql);
1972 if ($resql) {
1973 $cpt = $this->db->num_rows($resql);
1974 for ($i = 0; $i < $cpt; $i++) {
1975 $obj = $this->db->fetch_object($resql);
1976
1977 $qty = $obj->qty;
1978
1979 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
1980 continue;
1981 }
1982 dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid);
1983
1984 //var_dump($this->lines[$i]);
1985 $mouvS = new MouvementStock($this->db);
1986 $mouvS->origin = &$this;
1987 $mouvS->setOrigin($this->element, $this->id);
1988
1989 if (empty($obj->batch)) {
1990 // line without batch detail
1991
1992 // 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
1993 $inventorycode = '';
1994 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionUnClassifyCloseddInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
1995
1996 if ($result < 0) {
1997 $this->error = $mouvS->error;
1998 $this->errors = $mouvS->errors;
1999 $error++;
2000 break;
2001 }
2002 } else {
2003 // line with batch detail
2004
2005 // 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
2006 $inventorycode = '';
2007 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionUnClassifyCloseddInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, 0, $inventorycode);
2008 if ($result < 0) {
2009 $this->error = $mouvS->error;
2010 $this->errors = $mouvS->errors;
2011 $error++;
2012 break;
2013 }
2014 }
2015 }
2016 } else {
2017 $this->error = $this->db->lasterror();
2018 $error++;
2019 }
2020 }
2021
2022 if (!$error) {
2023 // Call trigger
2024 $result = $this->call_trigger('RECEPTION_REOPEN', $user);
2025 if ($result < 0) {
2026 $error++;
2027 }
2028 }
2029
2030 if (!$error && $this->origin == 'order_supplier') {
2031 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
2032
2033 $commande = new CommandeFournisseur($this->db);
2034 $commande->fetch($this->origin_id);
2035 $result = $commande->setStatus($user, 4);
2036 if ($result < 0) {
2037 $error++;
2038 $this->error = $commande->error;
2039 $this->errors = $commande->errors;
2040 }
2041 }
2042 } else {
2043 $error++;
2044 $this->errors[] = $this->db->lasterror();
2045 }
2046
2047 if (!$error) {
2048 $this->db->commit();
2049 return 1;
2050 } else {
2051 $this->db->rollback();
2052 return -1;
2053 }
2054 }
2055
2062 public function setDraft($user)
2063 {
2064 // phpcs:enable
2065 global $conf, $langs;
2066
2067 $error = 0;
2068
2069 // Protection
2070 if ($this->statut <= self::STATUS_DRAFT) {
2071 return 0;
2072 }
2073
2074 if (!((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'creer'))
2075 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('reception', 'reception_advance', 'validate')))) {
2076 $this->error = 'Permission denied';
2077 return -1;
2078 }
2079
2080 $this->db->begin();
2081
2082 $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
2083 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2084 $sql .= " WHERE rowid = ".((int) $this->id);
2085 $sql .= " AND fk_statut = ".((int) $this->statut); // Status may have changed since the object was loaded
2086
2087 dol_syslog(__METHOD__, LOG_DEBUG);
2088 $resql = $this->db->query($sql);
2089 if ($resql && $this->db->affected_rows($resql) <= 0) {
2090 // Status in database is not the one of the object (changed meanwhile): no stock movement
2091 $this->db->rollback();
2092 $langs->load("receptions");
2093 $this->error = $langs->trans('StatusOfRefMustBe', $this->ref, $langs->transnoentitiesnoconv($this->statut == self::STATUS_CLOSED ? 'StatusReceptionProcessedShort' : 'StatusReceptionValidatedShort'));
2094 return -1;
2095 }
2096 if ($resql) {
2097 // If stock increment is done on validation, or on closing and the reception was closed, we revert it
2098 if (!$error && isModEnabled('stock') && (getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION') || (getDolGlobalInt('STOCK_CALCULATE_ON_RECEPTION_CLOSE') && $this->statut == self::STATUS_CLOSED))) {
2099 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2100
2101 $langs->load("agenda");
2102
2103 // Loop on each product line to add a stock movement
2104 // TODO possibilite de receptionner a partir d'une propale ou autre origine
2105 $sql = "SELECT cd.fk_product, cd.subprice,";
2106 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
2107 $sql .= " ed.eatby, ed.sellby, ed.batch,";
2108 $sql .= " ed.cost_price";
2109 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
2110 $sql .= " ".MAIN_DB_PREFIX."receptiondet_batch as ed";
2111 $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
2112 $sql .= " AND cd.rowid = ed.fk_elementdet";
2113
2114 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
2115 $resql = $this->db->query($sql);
2116 if ($resql) {
2117 $cpt = $this->db->num_rows($resql);
2118 for ($i = 0; $i < $cpt; $i++) {
2119 $obj = $this->db->fetch_object($resql);
2120
2121 $qty = $obj->qty;
2122
2123 if ($qty == 0 || ($qty < 0 && !getDolGlobalInt('RECEPTION_ALLOW_NEGATIVE_QTY'))) {
2124 continue;
2125 }
2126
2127 dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid);
2128
2129 //var_dump($this->lines[$i]);
2130 $mouvS = new MouvementStock($this->db);
2131 $mouvS->origin = &$this;
2132 $mouvS->setOrigin($this->element, $this->id);
2133
2134 if (empty($obj->batch)) {
2135 // line without batch detail
2136
2137 // 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
2138 $inventorycode = '';
2139 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionBackToDraftInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
2140 if ($result < 0) {
2141 $this->error = $mouvS->error;
2142 $this->errors = $mouvS->errors;
2143 $error++;
2144 break;
2145 }
2146 } else {
2147 // line with batch detail
2148
2149 // 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
2150 $inventorycode = '';
2151 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionBackToDraftInDolibarr", $this->ref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, 0, $inventorycode);
2152 if ($result < 0) {
2153 $this->error = $mouvS->error;
2154 $this->errors = $mouvS->errors;
2155 $error++;
2156 break;
2157 }
2158 }
2159 }
2160 } else {
2161 $this->error = $this->db->lasterror();
2162 $error++;
2163 }
2164 }
2165
2166 if (!$error) {
2167 // Call trigger
2168 $result = $this->call_trigger('RECEPTION_UNVALIDATE', $user);
2169 if ($result < 0) {
2170 $error++;
2171 }
2172 }
2173 if ($this->origin == 'order_supplier') {
2174 if (!empty($this->origin) && $this->origin_id > 0) {
2175 $this->fetch_origin();
2176 if ($this->origin_object->statut == 4) { // If order source of reception is "partially received"
2177 // Check if there is no more reception validated.
2178 $this->origin_object->fetchObjectLinked();
2179 $setStatut = 1;
2180 if (!empty($this->origin_object->linkedObjects['reception'])) {
2181 foreach ($this->origin_object->linkedObjects['reception'] as $rcption) {
2182 if ($rcption->statut > 0) {
2183 $setStatut = 0;
2184 break;
2185 }
2186 }
2187 //var_dump($this->$origin->receptions);exit;
2188 if ($setStatut) {
2189 $this->origin_object->setStatut(3); // ordered
2190 }
2191 }
2192 }
2193 }
2194 }
2195
2196 if (!$error) {
2197 $this->statut = self::STATUS_DRAFT;
2198 $this->status = self::STATUS_DRAFT;
2199 $this->db->commit();
2200 return 1;
2201 } else {
2202 $this->db->rollback();
2203 return -1;
2204 }
2205 } else {
2206 $this->error = $this->db->error();
2207 $this->db->rollback();
2208 return -1;
2209 }
2210 }
2211
2222 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2223 {
2224 global $conf, $langs;
2225
2226 $langs->load("receptions");
2227
2228 if (!dol_strlen($modele)) {
2229 $modele = 'squille';
2230
2231 if ($this->model_pdf) {
2232 $modele = $this->model_pdf;
2233 } elseif (getDolGlobalString('RECEPTION_ADDON_PDF')) {
2234 $modele = getDolGlobalString('RECEPTION_ADDON_PDF');
2235 }
2236 }
2237
2238 $modelpath = "core/modules/reception/doc/";
2239
2240 $this->fetch_origin();
2241
2242 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2243 }
2244
2253 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2254 {
2255 $tables = array('reception');
2256
2257 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2258 }
2259
2268 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
2269 {
2270 $tables = array(
2271 'receptiondet_batch'
2272 );
2273
2274 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
2275 }
2276}
$object ref
Definition info.php:90
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.
Parent class of all other business classes (invoices, contracts, proposals, 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...
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
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
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.
fetch_origin()
Read linked origin object.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
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.
getNomUrl($withpicto=0, $option=0, $max=0, $short=0, $notooltip=0)
Return clickable link of object (with eventually picto)
update($user=null, $notrigger=0)
Update database.
setClosed()
Classify the reception as closed (this records also the stock movement)
getNextNumRef($soc)
Return next contract ref.
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.
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)
__construct($db)
Constructor.
initAsSpecimen()
Initialise an instance with random values.
fetch_lines()
Load lines.
create($user, $notrigger=0)
Create reception en base.
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 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:171
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:63
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:162