dolibarr 24.0.3
expedition.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@inodbox.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-2020 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-2017 Francis Appels <francis.appels@yahoo.com>
11 * Copyright (C) 2015 Claudio Aschieri <c.aschieri@19.coop>
12 * Copyright (C) 2016-2024 Ferran Marcet <fmarcet@2byte.es>
13 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
14 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
15 * Copyright (C) 2020 Lenin Rivas <lenin@leninrivas.com>
16 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
17 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
18 * Copyright (C) 2025 Nick Fragoulis
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."/expedition/class/expeditionligne.class.php";
42require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
43if (isModEnabled("propal")) {
44 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
45}
46if (isModEnabled('order')) {
47 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
48}
49require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionlinebatch.class.php';
50require_once DOL_DOCUMENT_ROOT.'/core/class/commonsignedobject.class.php';
51require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
52
59{
60 use CommonIncoterm;
61 use CommonSignedObject;
62 use CommonSubtotal;
63
67 public $element = "shipping";
68
72 public $fk_element = "fk_expedition";
73
77 public $table_element = "expedition";
78
82 public $table_element_line = "expeditiondet";
83
87 public $class_element_line = 'ExpeditionLigne';
88
92 public $picto = 'dolly';
93
94
98 public $fields = array();
99
104 public $user_author_id;
105
110 public $fk_user_author;
111
116 public $fk_user_valid;
117
121 public $socid;
122
128 public $ref_client;
129
133 public $ref_customer;
134
138 public $entrepot_id;
139
143 public $tracking_number;
144
148 public $tracking_url;
152 public $billed = 0;
153
157 public $trueWeight;
161 public $weight_units;
165 public $trueWidth;
169 public $width_units;
173 public $trueHeight;
177 public $height_units;
181 public $trueDepth;
185 public $depth_units;
189 public $trueSize;
190
194 public $livraison_id;
195
199 public $multicurrency_subprice;
200
204 public $size_units;
205
209 public $sizeH;
210
214 public $sizeS;
215
219 public $sizeW;
220
224 public $weight;
225
229 public $date_delivery;
230
236 public $date;
237
243 public $date_expedition;
244
249 public $date_shipping;
250
254 public $date_valid;
255
259 public $meths;
263 public $listmeths; // List of carriers
264
268 public $commande_id;
269
273 public $commande;
274
278 public $lines = array();
279
280 // Multicurrency
284 public $fk_multicurrency;
285
289 public $multicurrency_code;
293 public $multicurrency_tx;
297 public $multicurrency_total_ht;
301 public $multicurrency_total_tva;
305 public $multicurrency_total_ttc;
306
310 const STATUS_DRAFT = 0;
311
319
325 const STATUS_CLOSED = 2;
326
330 const STATUS_CANCELED = -1;
331
340
346 public function __construct($db)
347 {
348 $this->db = $db;
349
350 $this->ismultientitymanaged = 1;
351 $this->isextrafieldmanaged = 1;
352
353 // List of long language codes for status
354 $this->labelStatus = array();
355 $this->labelStatus[-1] = 'StatusSendingCanceled';
356 $this->labelStatus[0] = 'StatusSendingDraft';
357 $this->labelStatus[1] = 'StatusSendingValidated';
358 $this->labelStatus[2] = 'StatusSendingProcessed';
359
360 // List of short language codes for status
361 $this->labelStatusShort = array();
362 $this->labelStatusShort[-1] = 'StatusSendingCanceledShort';
363 $this->labelStatusShort[0] = 'StatusSendingDraftShort';
364 $this->labelStatusShort[1] = 'StatusSendingValidatedShort';
365 $this->labelStatusShort[2] = 'StatusSendingProcessedShort';
366 }
367
374 public function getNextNumRef($soc)
375 {
376 global $langs, $conf;
377 $langs->load("sendings");
378
379 if (getDolGlobalString('EXPEDITION_ADDON_NUMBER')) {
380 $mybool = false;
381
382 $file = getDolGlobalString('EXPEDITION_ADDON_NUMBER') . ".php";
383 $classname = getDolGlobalString('EXPEDITION_ADDON_NUMBER');
384
385 // Include file with class
386 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
387
388 foreach ($dirmodels as $reldir) {
389 $dir = dol_buildpath($reldir."core/modules/expedition/");
390
391 // Load file with numbering class (if found)
392 $mybool = ((bool) @include_once $dir.$file) || $mybool;
393 }
394
395 if (!$mybool) {
396 dol_print_error(null, "Failed to include file ".$file);
397 return '';
398 }
399
400 $obj = new $classname();
401 '@phan-var-force ModelNumRefExpedition $obj';
403 $numref = $obj->getNextValue($soc, $this);
404
405 if ($numref != "") {
406 return $numref;
407 } else {
408 dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error);
409 return "";
410 }
411 } else {
412 print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined");
413 return "";
414 }
415 }
416
424 public function create($user, $notrigger = 0)
425 {
426 $now = dol_now();
427
428 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
429 $error = 0;
430
431 // Clean parameters
432 $this->tracking_number = dol_sanitizeFileName((string) $this->tracking_number);
433 $this->tracking_number = preg_replace('/\s+/', '', $this->tracking_number);
434
435 if (empty($this->fk_project)) {
436 $this->fk_project = 0;
437 }
438 if (empty($this->date_creation)) {
439 $this->date_creation = $now;
440 }
441 if (empty($this->date_shipping) && !empty($this->date_expedition)) {
442 $this->date_shipping = $this->date_expedition;
443 }
444 $this->entity = setEntity($this);
445
446 $this->user = $user;
447
448 $this->db->begin();
449
450 $sql = "INSERT INTO ".MAIN_DB_PREFIX."expedition (";
451 $sql .= "ref";
452 $sql .= ", entity";
453 $sql .= ", ref_customer";
454 $sql .= ", ref_ext";
455 $sql .= ", date_creation";
456 $sql .= ", fk_user_author";
457 $sql .= ", date_expedition";
458 $sql .= ", date_delivery";
459 $sql .= ", fk_soc";
460 $sql .= ", fk_projet";
461 $sql .= ", fk_address";
462 $sql .= ", fk_shipping_method";
463 $sql .= ", tracking_number";
464 $sql .= ", weight";
465 $sql .= ", size";
466 $sql .= ", width";
467 $sql .= ", height";
468 $sql .= ", weight_units";
469 $sql .= ", size_units";
470 $sql .= ", note_private";
471 $sql .= ", note_public";
472 $sql .= ", model_pdf";
473 $sql .= ", fk_incoterms, location_incoterms";
474 $sql .= ", signed_status";
475 $sql .= ", billed";
476 $sql .= ") VALUES (";
477 $sql .= "'(PROV)'";
478 $sql .= ", ".((int) $this->entity);
479 $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : "null");
480 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
481 $sql .= ", '".$this->db->idate($this->date_creation)."'";
482 $sql .= ", ".((int) $user->id);
483 $sql .= ", ".($this->date_shipping > 0 ? "'".$this->db->idate($this->date_shipping)."'" : "null");
484 $sql .= ", ".($this->date_delivery > 0 ? "'".$this->db->idate($this->date_delivery)."'" : "null");
485 $sql .= ", ".($this->socid > 0 ? ((int) $this->socid) : "null");
486 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
487 $sql .= ", ".($this->fk_delivery_address > 0 ? ((int) $this->fk_delivery_address) : "null");
488 $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : "null");
489 $sql .= ", '".$this->db->escape($this->tracking_number)."'";
490 $sql .= ", ".(is_numeric($this->weight) ? (float) $this->weight : 'NULL');
491 $sql .= ", ".(is_numeric($this->sizeS) ? (float) $this->sizeS : 'NULL'); // TODO Should use this->trueDepth
492 $sql .= ", ".(is_numeric($this->sizeW) ? (float) $this->sizeW : 'NULL'); // TODO Should use this->trueWidth
493 $sql .= ", ".(is_numeric($this->sizeH) ? (float) $this->sizeH : 'NULL'); // TODO Should use this->trueHeight
494 $sql .= ", ".($this->weight_units != '' ? (int) $this->weight_units : 'NULL');
495 $sql .= ", ".($this->size_units != '' ? (int) $this->size_units : 'NULL');
496 $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
497 $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
498 $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
499 $sql .= ", ".((int) $this->fk_incoterms);
500 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
501 $sql .= ", ".((int) $this->signed_status);
502 $sql .= ", ".((int) $this->billed);
503 $sql .= ")";
504
505 dol_syslog(get_class($this)."::create", LOG_DEBUG);
506 $resql = $this->db->query($sql);
507 if ($resql) {
508 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expedition");
509
510 // update ref
511 $initialref = '(PROV'.$this->id.')';
512 if (!empty($this->ref)) {
513 $initialref = $this->ref;
514 }
515
516 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
517 $sql .= " SET ref = '".$this->db->escape($initialref)."'";
518 $sql .= " WHERE rowid = ".((int) $this->id);
519
520 dol_syslog(get_class($this)."::create", LOG_DEBUG);
521 if ($this->db->query($sql)) {
522 $this->ref = $initialref;
523 // Insert of lines
524 $num = count($this->lines);
525 $kits_list = array();
526 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
527 for ($i = 0; $i < $num; $i++) {
528 $objectsrc = new OrderLine($this->db);
529 $objectsrc->fetch($this->lines[$i]->origin_line_id);
530 if ($this->lines[$i]->product_type == "9" && $objectsrc->special_code == SUBTOTALS_SPECIAL_CODE) {
531 if ($this->create_line($this->lines[$i]->entrepot_id, $this->lines[$i]->origin_line_id, $this->lines[$i]->qty, $this->lines[$i]->rang, $this->lines[$i]->array_options) <= 0) {
532 $error++;
533 }
534 continue;
535 }
536 if (empty($this->lines[$i]->product_type) || getDolGlobalString('STOCK_SUPPORTS_SERVICES') || getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES')) {
537 // virtual products
538 $line = $this->lines[$i];
539 if ($line->fk_product > 0) {
540 // We group kit lines by the fulfilled order line (fk_elementdet) and not by product id: when a same kit product
541 // is present on several distinct order lines, each order line must keep its own shipment line so the ordered
542 // qty stays consistent with the shipped qty (grouping by product would sum the shipped qty of all lines while
543 // keeping the ordered qty of a single line, resulting in a wrong/negative remaining qty to ship). Several
544 // warehouse pickings of the same order line still share the same fk_elementdet and are grouped together.
545 if (!isset($kits_list[$line->fk_elementdet])) {
546 if (!is_object($line->product)) {
547 $line_product = new Product($this->db);
548 $result = $line_product->fetch($line->fk_product, '', '', '', 1, 1, 1);
549 if ($result <= 0) {
550 $error++;
551 }
552 } else {
553 $line_product = $line->product;
554 }
555
556 // get all children of virtual product
557 $line_product->get_sousproduits_arbo();
558 $prods_arbo = $line_product->get_arbo_each_prod($line->qty);
559 if (count($prods_arbo) > 0) {
560 $kits_list[$line->fk_elementdet] = array(
561 'arbo' => $prods_arbo,
562 'total_qty' => $line->qty,
563 );
564 }
565 } else {
566 $kits_list[$line->fk_elementdet]['total_qty'] += $line->qty;
567 }
568 }
569 }
570 }
571 }
572 $kits_id_cached = array();
573 $sub_kits_id_cached = array();
574 $sub_parents_cached = array();
575 for ($i = 0; $i < $num; $i++) {
576 $line = $this->lines[$i];
577 if (empty($line->product_type) || getDolGlobalString('STOCK_SUPPORTS_SERVICES') || getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES')) {
578 $line_id = 0;
579 if (!isset($kits_id_cached[$line->fk_elementdet])) {
580 if (!isset($line->detail_batch) || (isset($kits_list[$line->fk_elementdet]) && !getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE'))) { // no batch management or is kit
581 $qty = isset($kits_list[$line->fk_elementdet]) ? $kits_list[$line->fk_elementdet]['total_qty'] : $line->qty;
582 $warehouse_id = (isset($kits_list[$line->fk_elementdet]) && !getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) ? 0 : $line->entrepot_id;
583 $line_id = $this->create_line($warehouse_id, $line->origin_line_id, $qty, $line->rang, $line->array_options, 0, $line->fk_product);
584 if ($line_id <= 0) {
585 $error++;
586 }
587 if (isset($kits_list[$line->fk_elementdet])) {
588 $kits_id_cached[$line->fk_elementdet] = $line_id;
589 }
590 } else { // with batch management
591 if ($this->create_line_batch($line, $line->array_options) <= 0) {
592 $error++;
593 }
594 }
595 } else {
596 $line_id = $kits_id_cached[$line->fk_elementdet];
597 }
598
599 // virtual products
600 if (isset($kits_list[$line->fk_elementdet]) && !getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) {
601 $prods_arbo = $kits_list[$line->fk_elementdet]['arbo'];
602
603 // get all children of virtual product
604 $parent_line_id = $line_id; // parent line created
605 $level_last = 1;
606 $product_child_id = 0;
607 foreach ($prods_arbo as $index => $product_child_arr) {
608 // 'id' => Id product
609 // 'id_parent' => Id parent product
610 // 'ref' => Ref product
611 // 'nb' => Nb of units that compose parent product
612 // 'nb_total' => // Nb of units for all nb of product
613 // 'stock' => Stock
614 // 'stock_alert' => Stock alert
615 // 'label' => Label
616 // 'fullpath' => // Full path label
617 // 'type' =>
618 // 'desiredstock' => Desired stock
619 // 'level' => Level
620 // 'incdec' => Need to be incremented or decremented
621 // 'entity' => Entity
622 $product_child_level = (int) $product_child_arr['level'];
623 $product_child_incdec = !empty($product_child_arr['incdec']);
624
625 // detect new level
626 if ($product_child_level != $level_last) {
627 $parent_line_id = $line_id; // last line id
628 $parent_product_id = $product_child_id; // last line id
629 if (isset($sub_parents_cached[$line->fk_elementdet][$parent_product_id])) {
630 $parent_line_id = $sub_parents_cached[$line->fk_elementdet][$parent_product_id];
631 } else {
632 $sub_parents_cached[$line->fk_elementdet][$parent_product_id] = $parent_line_id;
633 }
634 }
635
636 // determine if it's a kit : check next level
637 $is_kit = false;
638 $next_level = $product_child_level;
639 $next_index = $index + 1;
640 if (isset($prods_arbo[$next_index])) {
641 $next_level = (int) $prods_arbo[$next_index]['level'];
642 }
643 if ($next_level > $product_child_level) {
644 $is_kit = true;
645 }
646
647 // determine quantity of sub-product
648 $product_child_id = (int) $product_child_arr['id'];
649 $product_child_qty = (float) $product_child_arr['nb_total']; // by default
650 $warehouse_id = $line->entrepot_id; // by default
651 if ($is_kit || !$product_child_incdec) {
652 if (!$product_child_incdec) {
653 $product_child_qty = 0;
654 }
655 $warehouse_id = 0; // no warehouse used for a kit or if stock is not managed (empty incdec)
656 }
657
658 // create line for a child of virtual product
659 if (!isset($sub_kits_id_cached[$line->fk_elementdet][$product_child_id]) || $warehouse_id > 0) {
660 $line_id = $this->create_line($warehouse_id, ($parent_line_id ? 0 : $line->origin_line_id), $product_child_qty, $line->rang, $line->array_options, $parent_line_id, $product_child_id);
661 if ($line_id <= 0) {
662 $error++;
663 dol_syslog(__METHOD__ . ' : ' . $this->errorsToString(), LOG_ERR);
664 break;
665 }
666
667 // if kit or not manage stock (empty incdec)
668 if (empty($warehouse_id)) {
669 $sub_kits_id_cached[$line->fk_elementdet][$product_child_id] = $line_id;
670 }
671 }
672
673 $level_last = $product_child_level;
674 }
675 }
676 }
677 }
678
679 if (!$error && $this->id && $this->origin_id) {
680 $ret = $this->add_object_linked();
681 if (!$ret) {
682 $error++;
683 }
684 }
685
686 if (!$error && $this->id && getDolGlobalInt('SHIPPING_USE_ITS_OWN_CONTACTS') && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin_type) && !empty($this->origin_id)) { // Get contact from origin object
687 $originforcontact = $this->origin_type;
688 $originidforcontact = $this->origin_id;
689
690 $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
691 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
692
693 $resqlcontact = $this->db->query($sqlcontact);
694 if ($resqlcontact) {
695 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
696 $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
697 }
698 } else {
699 dol_print_error($this->db);
700 }
701 }
702
703 // Actions on extra fields
704 if (!$error) {
705 $result = $this->insertExtraFields();
706 if ($result < 0) {
707 $error++;
708 }
709 }
710
711 if (!$error && !$notrigger) {
712 // Call trigger
713 $result = $this->call_trigger('SHIPPING_CREATE', $user);
714 if ($result < 0) {
715 $error++;
716 }
717 // End call triggers
718
719 if (!$error) {
720 $this->db->commit();
721 return $this->id;
722 } else {
723 foreach ($this->errors as $errmsg) {
724 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
725 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
726 }
727 $this->db->rollback();
728 return -1 * $error;
729 }
730 } else {
731 $error++;
732 $this->db->rollback();
733 return -3;
734 }
735 } else {
736 $error++;
737 $this->error = $this->db->lasterror()." - sql=$sql";
738 $this->db->rollback();
739 return -2;
740 }
741 } else {
742 $error++;
743 $this->error = $this->db->error()." - sql=$sql";
744 $this->db->rollback();
745 return -1;
746 }
747 }
748
749 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
762 public function create_line($entrepot_id, $origin_line_id, $qty, $rang = 0, $array_options = [], $parent_line_id = 0, $product_id = 0)
763 {
764 //phpcs:enable
765 global $user;
766
767 $expeditionline = new ExpeditionLigne($this->db);
768 $expeditionline->fk_expedition = $this->id;
769 $expeditionline->entrepot_id = $entrepot_id;
770 $expeditionline->fk_elementdet = $origin_line_id;
771 $expeditionline->element_type = $this->origin;
772 $expeditionline->fk_parent = $parent_line_id;
773 $expeditionline->fk_product = $product_id;
774 $expeditionline->qty = $qty;
775 $expeditionline->rang = $rang;
776 $expeditionline->array_options = $array_options;
777
778 if (!($expeditionline->fk_product > 0)) {
779 $order_line = new OrderLine($this->db);
780 $order_line->fetch($expeditionline->fk_elementdet);
781 $expeditionline->fk_product = $order_line->fk_product;
782 }
783
784 if (($lineId = $expeditionline->insert($user)) < 0) {
785 // insert() reports through errors[], so copying the singular error only lost the message
786 $this->setErrorsFromObject($expeditionline);
787 }
788 return $lineId;
789 }
790
791
792 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
800 public function create_line_batch($line_ext, $array_options = [])
801 {
802 // phpcs:enable
803 $error = 0;
804 $stockLocationQty = array(); // associated array with batch qty in stock location
805
806 $tab = $line_ext->detail_batch;
807 // create stockLocation Qty array
808 foreach ($tab as $detbatch) {
809 if (!empty($detbatch->fk_warehouse)) {
810 if (empty($stockLocationQty[$detbatch->fk_warehouse])) {
811 $stockLocationQty[$detbatch->fk_warehouse] = 0;
812 }
813 $stockLocationQty[$detbatch->fk_warehouse] += $detbatch->qty;
814 }
815 }
816 // create shipment lines
817 foreach ($stockLocationQty as $stockLocation => $qty) {
818 $line_id = $this->create_line($stockLocation, $line_ext->origin_line_id, $qty, $line_ext->rang, $array_options);
819 if ($line_id < 0) {
820 $error++;
821 } else {
822 // create shipment batch lines for stockLocation
823 foreach ($tab as $detbatch) {
824 if ($detbatch->fk_warehouse == $stockLocation) {
825 if (!($detbatch->create($line_id) > 0)) { // Create an ExpeditionLineBatch
826 $this->errors = $detbatch->errors;
827 $error++;
828 }
829 }
830 }
831 }
832 }
833
834 if (!$error) {
835 return 1;
836 } else {
837 return -1;
838 }
839 }
840
850 public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
851 {
852 global $conf;
853
854 // Check parameters
855 if (empty($id) && empty($ref) && empty($ref_ext)) {
856 return -1;
857 }
858
859 $sql = "SELECT e.rowid, e.entity, e.ref, e.fk_soc as socid, e.date_creation, e.ref_customer, e.ref_ext, e.fk_user_author, e.fk_statut, e.signed_status, e.fk_projet as fk_project, e.billed";
860 $sql .= ", e.date_valid, e.fk_user_valid";
861 $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
862 $sql .= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery";
863 $sql .= ", e.fk_shipping_method, e.tracking_number";
864 $sql .= ", e.note_private, e.note_public";
865 $sql .= ', e.fk_incoterms, e.location_incoterms';
866 $sql .= ', e.signed_status';
867 $sql .= ', i.libelle as label_incoterms';
868 $sql .= ', s.libelle as shipping_method';
869 $sql .= ", el.fk_source as origin_id, el.sourcetype as origin_type";
870 $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e";
871 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
872 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
873 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_shipment_mode as s ON e.fk_shipping_method = s.rowid';
874 $sql .= " WHERE e.entity IN (".getEntity('expedition').")";
875 if ($id) {
876 $sql .= " AND e.rowid = ".((int) $id);
877 }
878 if ($ref) {
879 $sql .= " AND e.ref='".$this->db->escape($ref)."'";
880 }
881 if ($ref_ext) {
882 $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'";
883 }
884
885 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
886 $result = $this->db->query($sql);
887 if ($result) {
888 if ($this->db->num_rows($result)) {
889 $obj = $this->db->fetch_object($result);
890
891 $this->id = (int) $obj->rowid;
892 $this->entity = $obj->entity;
893 $this->ref = $obj->ref;
894 $this->socid = $obj->socid;
895 $this->ref_customer = $obj->ref_customer;
896 $this->ref_ext = $obj->ref_ext;
897 $this->status = $obj->fk_statut;
898 $this->statut = $this->status; // Deprecated
899 $this->signed_status = $obj->signed_status;
900 $this->user_author_id = $obj->fk_user_author;
901 $this->fk_user_author = $obj->fk_user_author;
902 $this->user_creation_id = $obj->fk_user_author;
903 $this->fk_user_valid = $obj->fk_user_valid;
904 $this->date_creation = $this->db->jdate($obj->date_creation);
905 $this->date_valid = $this->db->jdate($obj->date_valid);
906 $this->date = $this->db->jdate($obj->date_expedition); // TODO deprecated
907 $this->date_expedition = $this->db->jdate($obj->date_expedition); // TODO deprecated
908 $this->date_shipping = $this->db->jdate($obj->date_expedition); // Date real
909 $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planned
910 $this->fk_delivery_address = $obj->fk_address;
911 $this->model_pdf = $obj->model_pdf;
912 $this->shipping_method_id = $obj->fk_shipping_method;
913 $this->shipping_method = $obj->shipping_method;
914 $this->tracking_number = $obj->tracking_number;
915 $this->origin = ($obj->origin_type ? $obj->origin_type : 'commande'); // For compatibility
916 $this->origin_type = ($obj->origin_type ? $obj->origin_type : 'commande');
917 $this->origin_id = $obj->origin_id;
918 $this->billed = $obj->billed;
919 $this->fk_project = $obj->fk_project;
920 $this->signed_status = $obj->signed_status;
921 $this->trueWeight = $obj->weight;
922 $this->weight_units = $obj->weight_units;
923
924 $this->trueWidth = $obj->width;
925 $this->width_units = $obj->size_units;
926 $this->trueHeight = $obj->height;
927 $this->height_units = $obj->size_units;
928 $this->trueDepth = $obj->size;
929 $this->depth_units = $obj->size_units;
930
931 $this->note_public = $obj->note_public;
932 $this->note_private = $obj->note_private;
933
934 // A denormalized value
935 $this->trueSize = $obj->size."x".$obj->width."x".$obj->height;
936 $this->size_units = $obj->size_units;
937
938 //Incoterms
939 $this->fk_incoterms = $obj->fk_incoterms;
940 $this->location_incoterms = $obj->location_incoterms;
941 $this->label_incoterms = $obj->label_incoterms;
942
943 $this->db->free($result);
944
945 // Tracking url
946 $this->getUrlTrackingStatus($obj->tracking_number);
947
948 // Thirdparty
949 $result = $this->fetch_thirdparty(); // TODO Remove this
950
951 // Retrieve extrafields
952 $this->fetch_optionals();
953
954 // Fix Get multicurrency param for transmitted
955 if (isModEnabled('multicurrency')) {
956 if (!empty($this->multicurrency_code)) {
957 $this->multicurrency_code = $this->thirdparty->multicurrency_code;
958 }
959 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($this->thirdparty->multicurrency_tx)) {
960 $this->multicurrency_tx = $this->thirdparty->multicurrency_tx;
961 }
962 }
963
964 /*
965 * Lines
966 */
967 if (empty($obj->origin_id)) {
968 $result = $this->fetch_lines_free();
969 } else {
970 $result = $this->fetch_lines();
971 }
972 if ($result < 0) {
973 return -3;
974 }
975
976 return 1;
977 } else {
978 dol_syslog(get_class($this).'::Fetch no expedition found', LOG_ERR);
979 $this->error = 'Shipment with id '.$id.' not found';
980 return 0;
981 }
982 } else {
983 $this->error = $this->db->error();
984 return -1;
985 }
986 }
987
995 public function valid($user, $notrigger = 0)
996 {
997 global $conf;
998
999 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1000
1001 dol_syslog(get_class($this)."::valid");
1002
1003 // Protection
1004 if ($this->status) {
1005 dol_syslog(get_class($this)."::valid not in draft status", LOG_WARNING);
1006 return 0;
1007 }
1008
1009 if (!isset($this->socid)) {
1010 dol_syslog(get_class($this)."::can't valid socid not set", LOG_WARNING);
1011 return 0;
1012 }
1013
1014 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'creer'))
1015 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'shipping_advance', 'validate')))) {
1016 $this->error = 'Permission denied';
1017 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1018 return -1;
1019 }
1020
1021 $this->db->begin();
1022
1023 $error = 0;
1024
1025 // Define new ref
1026 $soc = new Societe($this->db);
1027 $soc->fetch($this->socid);
1028
1029 // Class of company linked to order
1030 $result = $soc->setAsCustomer();
1031
1032 // Define new ref
1033 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1034 $numref = $this->getNextNumRef($soc);
1035 } elseif (!empty($this->ref)) {
1036 $numref = (string) $this->ref;
1037 } else {
1038 $numref = "EXP".$this->id;
1039 }
1040 $this->newref = dol_sanitizeFileName($numref);
1041
1042 $now = dol_now();
1043
1044 // Validate
1045 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
1046 $sql .= " ref = '".$this->db->escape($numref)."'";
1047 $sql .= ", fk_statut = 1";
1048 $sql .= ", date_valid = '".$this->db->idate($now)."'";
1049 $sql .= ", fk_user_valid = ".((int) $user->id);
1050 $sql .= " WHERE rowid = ".((int) $this->id);
1051
1052 dol_syslog(get_class($this)."::valid update expedition", LOG_DEBUG);
1053 $resql = $this->db->query($sql);
1054 if (!$resql) {
1055 $this->error = $this->db->lasterror();
1056 $error++;
1057 }
1058
1059 // If stock increment is done on sending (recommended choice)
1060 if (!$error && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT')) {
1061 $result = $this->manageStockMvtOnEvt($user, "ShipmentValidatedInDolibarr");
1062 if ($result < 0) {
1063 $error++;
1064 }
1065 }
1066
1067 // Change status of order to "shipment in process"
1068 if (!$error) {
1069 $triggerKey = 'SHIPPING_'; // Because when the trigger is fired the object is a shipping and not the real target object, so I add a prefix like SHIPPING_ to avoid confusion
1070 if ($this->origin == 'commande') {
1071 $triggerKey.= 'ORDER_SHIPMENTONPROCESS';
1072 } else {
1073 $triggerKey.= strtoupper($this->origin).'_SHIPMENTONPROCESS';
1074 }
1075
1076 // TODO : load the origin object to trigger the right setStatus according to origin object
1077 $ret = $this->setStatut(Commande::STATUS_SHIPMENTONPROCESS, $this->origin_id, $this->origin, $triggerKey);
1078 if (!$ret) {
1079 $error++;
1080 }
1081 }
1082
1083 if (!$error && !$notrigger) {
1084 // Call trigger
1085 $result = $this->call_trigger('SHIPPING_VALIDATE', $user);
1086 if ($result < 0) {
1087 $error++;
1088 }
1089 // End call triggers
1090 }
1091
1092 if (!$error) {
1093 $this->oldref = $this->ref;
1094
1095 // Rename directory if dir was a temporary ref
1096 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1097 // Now we rename also files into index
1098 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expedition/sending/".$this->db->escape($this->newref)."'";
1099 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/sending/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1100 $resql = $this->db->query($sql);
1101 if (!$resql) {
1102 $error++;
1103 $this->error = $this->db->lasterror();
1104 }
1105 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'expedition/sending/".$this->db->escape($this->newref)."'";
1106 $sql .= " WHERE filepath = 'expedition/sending/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1107 $resql = $this->db->query($sql);
1108 if (!$resql) {
1109 $error++;
1110 $this->error = $this->db->lasterror();
1111 }
1112
1113 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1114 $oldref = dol_sanitizeFileName($this->ref);
1115 $newref = dol_sanitizeFileName($numref);
1116 $dirsource = $conf->expedition->dir_output.'/sending/'.$oldref;
1117 $dirdest = $conf->expedition->dir_output.'/sending/'.$newref;
1118 if (!$error && file_exists($dirsource)) {
1119 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
1120
1121 if (@rename($dirsource, $dirdest)) {
1122 dol_syslog("Rename ok");
1123 // Rename docs starting with $oldref with $newref
1124 $listoffiles = dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1125 foreach ($listoffiles as $fileentry) {
1126 $dirsource = $fileentry['name'];
1127 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1128 $dirsource = $fileentry['path'].'/'.$dirsource;
1129 $dirdest = $fileentry['path'].'/'.$dirdest;
1130 @rename($dirsource, $dirdest);
1131 }
1132 }
1133 }
1134 }
1135 }
1136
1137 // Set new ref and current status
1138 if (!$error) {
1139 $this->ref = $numref;
1140 $this->statut = self::STATUS_VALIDATED;
1142 }
1143
1144 if (!$error) {
1145 $this->db->commit();
1146 return 1;
1147 } else {
1148 $this->db->rollback();
1149 return -1 * $error;
1150 }
1151 }
1152
1153 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1160 public function line_ajaxorder($rows)
1161 {
1162 if (empty($rows) || !is_array($rows)) {
1163 return;
1164 }
1165
1166 $rowToOrigin = array();
1167 $originToRows = array();
1168
1169 $sql = "SELECT rowid, fk_elementdet";
1170 $sql .= " FROM ".$this->db->prefix()."expeditiondet";
1171 $sql .= " WHERE fk_expedition = ".((int) $this->id);
1172 $sql .= " ORDER BY rang ASC, rowid ASC";
1173
1174 $resql = $this->db->query($sql);
1175 if ($resql) {
1176 while ($obj = $this->db->fetch_object($resql)) {
1177 $rowid = (int) $obj->rowid;
1178 $originLine = (int) $obj->fk_elementdet;
1179 $rowToOrigin[$rowid] = $originLine;
1180
1181 if (!isset($originToRows[$originLine])) {
1182 $originToRows[$originLine] = array();
1183 }
1184 $originToRows[$originLine][] = $rowid;
1185 }
1186 $this->db->free($resql);
1187 } else {
1188 parent::line_ajaxorder($rows);
1189 return;
1190 }
1191
1192 $processedOrigins = array();
1193 $position = 1;
1194
1195 foreach ($rows as $rowid) {
1196 $rowid = (int) $rowid;
1197 if (empty($rowid)) {
1198 continue;
1199 }
1200
1201 $originLine = isset($rowToOrigin[$rowid]) ? $rowToOrigin[$rowid] : 0;
1202 if ($originLine > 0 && !empty($processedOrigins[$originLine])) {
1203 continue;
1204 }
1205
1206 $rowidsToUpdate = array($rowid);
1207 if ($originLine > 0 && !empty($originToRows[$originLine])) {
1208 $rowidsToUpdate = $originToRows[$originLine];
1209 $processedOrigins[$originLine] = 1;
1210 }
1211
1212 foreach ($rowidsToUpdate as $childRowId) {
1213 $this->updateRangOfLine($childRowId, $position);
1214 $position++;
1215 }
1216 }
1217 }
1218 // phpcs:enable
1219
1220 // phpcs:disable
1227 public function create_delivery($user)
1228 {
1229 // phpcs:enable
1230 if (getDolGlobalInt('MAIN_SUBMODULE_DELIVERY')) {
1231 if ($this->status == self::STATUS_VALIDATED || $this->status == self::STATUS_CLOSED) {
1232 // Expedition validated
1233 include_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php';
1234 $delivery = new Delivery($this->db);
1235 $result = $delivery->create_from_sending($user, $this->id);
1236 if ($result <= 0) {
1237 $this->setErrorsFromObject($delivery);
1238 }
1239 return $result;
1240 }
1241 }
1242
1243 return 0;
1244 }
1245
1260 public function addline($entrepot_id, $id, $qty, $array_options = [], $fk_product = 0, $fk_parent = 0)
1261 {
1262 global $langs;
1263
1264 $num = count($this->lines);
1265 $line = new ExpeditionLigne($this->db);
1266
1267 $line->entrepot_id = $entrepot_id;
1268 $line->origin_line_id = $id;
1269 $line->fk_elementdet = $id;
1270 $line->element_type = 'order';
1271 $line->fk_parent = $fk_parent;
1272 $line->fk_product = $fk_product;
1273 $line->qty = $qty;
1274
1275 $orderline = new OrderLine($this->db);
1276 $orderline->fetch($id);
1277
1278 // Copy the rang of the order line to the expedition line
1279 $line->rang = $orderline->rang;
1280 $line->product_type = $orderline->product_type;
1281 if (!($line->fk_product > 0)) {
1282 $line->fk_product = $orderline->fk_product;
1283 }
1284
1285 if (isModEnabled('stock') && !empty($orderline->fk_product)) {
1286 $product = new Product($this->db);
1287 $product->fetch($orderline->fk_product);
1288
1289 if (!($entrepot_id > 0) && !getDolGlobalString('STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS') && !(getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES') && $line->product_type == Product::TYPE_SERVICE) && $product->stockable_product == Product::ENABLED_STOCK && !empty($line->qty)) {
1290 $langs->load("errors");
1291 $this->error = $langs->trans("ErrorWarehouseRequiredIntoShipmentLine");
1292 return -1;
1293 }
1294
1295 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT') && ($qty > 0 || !getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1296 $productChildrenNb = 0;
1297 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
1298 $productChildrenNb = $product->hasFatherOrChild(1);
1299 }
1300 if ($productChildrenNb > 0) {
1301 $product_stock = null;
1302 $product->loadStockForVirtualProduct('warehouseopen', $line->qty);
1303 if ($entrepot_id > 0) {
1304 if (isset($product->stock_warehouse[$entrepot_id])) {
1305 $product_stock = $product->stock_warehouse[$entrepot_id]->real;
1306 }
1307 } else {
1308 foreach ($product->stock_warehouse as $componentStockWarehouse) {
1309 if ($product_stock === null) {
1310 $product_stock = $componentStockWarehouse->real;
1311 } else {
1312 $product_stock = min($product_stock, $componentStockWarehouse->real);
1313 }
1314 }
1315 }
1316 if ($product_stock === null) {
1317 $product_stock = 0;
1318 }
1319 } else {
1320 // Check must be done for stock of product into warehouse if $entrepot_id defined
1321 if ($entrepot_id > 0) {
1322 $product->load_stock('warehouseopen');
1323 $product_stock = $product->stock_warehouse[$entrepot_id]->real;
1324 } else {
1325 $product_stock = $product->stock_reel;
1326 }
1327 }
1328
1329 $product_type = $product->type;
1330 if ($product_type == 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1331 $isavirtualproduct = ($productChildrenNb > 0);
1332 // The product is qualified for a check of quantity (must be enough in stock to be added into shipment).
1333 if (
1334 !$isavirtualproduct
1335 || !getDolGlobalInt('PRODUIT_SOUSPRODUITS')
1336 || ($isavirtualproduct && !getDolGlobalInt('STOCK_EXCLUDE_VIRTUAL_PRODUCTS'))
1337 ) {
1338 // If STOCK_EXCLUDE_VIRTUAL_PRODUCTS is set, we do not manage stock for kits/virtual products.
1339 if ($product->stockable_product == Product::ENABLED_STOCK && $product_stock < $qty) {
1340 $langs->load("errors");
1341 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $product->ref);
1342 $this->errorhidden = 'ErrorStockIsNotEnoughToAddProductOnShipment';
1343
1344 return -3;
1345 }
1346 }
1347 }
1348 }
1349 }
1350
1351 // If product need a batch number, we should not have called this function but addline_batch instead.
1352 // If this happen, we may have a bug in card.php page
1353 if (isModEnabled('productbatch') && !empty($line->fk_product) && !empty($orderline->product_tobatch)) {
1354 $this->error = 'ADDLINE_WAS_CALLED_INSTEAD_OF_ADDLINEBATCH '.$orderline->id.' '.$line->fk_product; //
1355 return -4;
1356 }
1357
1358 // extrafields
1359 if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1360 $line->array_options = $array_options;
1361 }
1362
1363 $this->lines[$num] = $line;
1364
1365 return 1;
1366 }
1367
1381 public function addlinefree($qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $array_options = [])
1382 {
1383 global $mysoc, $langs, $user;
1384
1385 if ($this->status == self::STATUS_DRAFT) {
1386 if (empty($rang)) {
1387 $rang = 0;
1388 }
1389
1390 $qty = (float) price2num($qty);
1391
1392 $this->db->begin();
1393
1394 // Rang to use
1395 $ranktouse = $rang;
1396 if ($ranktouse == -1) {
1397 $rangmax = $this->line_max($fk_parent);
1398 $ranktouse = $rangmax + 1;
1399 }
1400
1401 // Insert line
1402 $this->line = new ExpeditionLigne($this->db);
1403 $this->line->fk_expedition = $this->id;
1404 $this->line->element_type = $element_type;
1405 $this->line->fk_product = $fk_product;
1406 $this->line->description = $description;
1407 $this->line->desc = $description;
1408 $this->line->fk_parent = $fk_parent;
1409 $this->line->qty = (float) $qty;
1410 $this->line->fk_unit = $fk_unit;
1411 $this->line->rang = $ranktouse;
1412
1413 if (is_array($array_options) && count($array_options) > 0) {
1414 $this->line->array_options = $array_options;
1415 }
1416
1417 $result = $this->line->insert($user);
1418 if ($result > 0) {
1419 if (!isset($this->context['createfromclone'])) {
1420 if (!empty($fk_parent)) {
1421 $this->line_order(true, 'DESC');
1422 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
1423 $linecount = count($this->lines);
1424 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
1425 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
1426 }
1427 }
1428 $this->lines[] = $this->line;
1429 }
1430
1431 $this->db->commit();
1432 return $this->line->id;
1433 } else {
1434 $this->error = $this->line->error;
1435 dol_syslog(get_class($this)."::addlinefree error=".$this->error, LOG_ERR);
1436 $this->db->rollback();
1437 return -2;
1438 }
1439 } else {
1440 dol_syslog(get_class($this)."::addlinefree status of shipment must be Draft to allow use of ->addlinefree()", LOG_ERR);
1441 return -3;
1442 }
1443 }
1444
1460 public function updatelinefree($rowid, $qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $notrigger, $array_options = array())
1461 {
1462 global $mysoc, $langs, $user;
1463
1464 if ($this->status == self::STATUS_DRAFT) {
1465 $this->db->begin();
1466
1467 if (empty($qty)) {
1468 $qty = 0;
1469 }
1470 if (empty($rang)) {
1471 $rang = 0;
1472 }
1473
1474 $qty = (float) $qty;
1475 $description = trim($description);
1476
1477 // Fetch current line from the database and then clone the object and set it in $oldline property
1478 $line = new ExpeditionLigne($this->db);
1479
1480 $line->fetch($rowid);
1481 $line->fetch_optionals();
1482
1483 if (!empty($line->fk_product)) {
1484 $product = new Product($this->db);
1485 $result = $product->fetch($line->fk_product);
1486 $product_type = $product->type;
1487 }
1488
1489 $staticline = clone $line;
1490
1491 $line->oldline = $staticline;
1492 $this->line = $line;
1493 $this->line->context = $this->context;
1494 $this->line->rang = $rang;
1495 $this->line->fk_expedition = $this->id;
1496 $this->line->element_type = $element_type;
1497 $this->line->fk_product = $fk_product;
1498 $this->line->qty = $qty;
1499 $this->line->fk_unit = $fk_unit;
1500 $this->line->fk_parent = $fk_parent;
1501 $this->line->description = $description;
1502
1503 if (is_array($array_options) && count($array_options) > 0) {
1504 // We replace values in this->line->array_options only for entries defined into $array_options
1505 foreach ($array_options as $key => $value) {
1506 $this->line->array_options[$key] = $array_options[$key];
1507 }
1508 }
1509
1510 $result = $this->line->update($user, $notrigger);
1511 if ($result > 0) {
1512 // Reorder if child line
1513 if (!empty($fk_parent)) {
1514 $this->line_order(true, 'DESC');
1515 }
1516
1517 $this->db->commit();
1518 return $result;
1519 } else {
1520 $this->error = $this->line->error;
1521
1522 $this->db->rollback();
1523 return -1;
1524 }
1525 } else {
1526 $this->error = get_class($this)."::updatelinefree Shipment status makes operation forbidden";
1527 $this->errors = array('ShipmentStatusMakeOperationForbidden');
1528 return -2;
1529 }
1530 }
1531
1532 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1541 public function addline_batch($dbatch, $array_options = [], $origin_line = null)
1542 {
1543 // phpcs:enable
1544 global $langs;
1545
1546 $num = count($this->lines);
1547 $linebatch = null;
1548 if ($dbatch['qty'] > 0 || ($dbatch['qty'] == 0 && getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1549 $line = new ExpeditionLigne($this->db);
1550 $tab = array();
1551 foreach ($dbatch['detail'] as $key => $value) {
1552 if ($value['q'] > 0 || ($value['q'] == 0 && getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1553 // $value['q']=qty to move
1554 // $value['id_batch']=id into llx_product_batch of record to move
1555 //var_dump($value);
1556
1557 $linebatch = new ExpeditionLineBatch($this->db);
1558 $ret = $linebatch->fetchFromStock($value['id_batch']); // load serial, sellby, eatby
1559 if ($ret < 0) {
1560 $this->setErrorsFromObject($linebatch);
1561 return -1;
1562 }
1563 $linebatch->qty = $value['q'];
1564 if ($linebatch->qty == 0 && getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS')) {
1565 $linebatch->batch = null;
1566 }
1567 $tab[] = $linebatch;
1568
1569 if (getDolGlobalString("STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT", '0') && ($linebatch->qty > 0 || !getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1570 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
1571 $prod_batch = new Productbatch($this->db);
1572 $prod_batch->fetch($value['id_batch']);
1573
1574 if ($prod_batch->qty < $linebatch->qty) {
1575 $langs->load("errors");
1576 $this->errors[] = $langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product);
1577 dol_syslog(get_class($this)."::addline_batch error=Product ".$prod_batch->batch.": ".$this->errorsToString(), LOG_ERR);
1578 return -1;
1579 }
1580 }
1581 }
1582 }
1583 if (is_object($linebatch)) {
1584 $line->entrepot_id = $linebatch->fk_warehouse;
1585 }
1586 $line->origin_line_id = $dbatch['ix_l']; // deprecated
1587 $line->fk_elementdet = $dbatch['ix_l'];
1588 $line->qty = $dbatch['qty'];
1589 $line->detail_batch = $tab;
1590 if (!($line->rang > 0)) {
1591 $line->rang = $origin_line->rang;
1592 }
1593 if (!($line->fk_product > 0)) {
1594 $line->fk_product = $origin_line->fk_product;
1595 }
1596
1597 // extrafields
1598 if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1599 $line->array_options = $array_options;
1600 }
1601
1602 //var_dump($line);
1603 $this->lines[$num] = $line;
1604 return 1;
1605 }
1606 return 0;
1607 }
1608
1616 public function update($user = null, $notrigger = 0)
1617 {
1618 global $conf;
1619 $error = 0;
1620
1621 // Clean parameters
1622
1623 if (isset($this->ref)) {
1624 $this->ref = trim($this->ref);
1625 }
1626 if (isset($this->entity)) {
1627 $this->entity = (int) $this->entity;
1628 }
1629 if (isset($this->ref_customer)) {
1630 $this->ref_customer = trim($this->ref_customer);
1631 }
1632 if (isset($this->socid)) {
1633 $this->socid = (int) $this->socid;
1634 }
1635 if (isset($this->fk_user_author)) {
1636 $this->fk_user_author = (int) $this->fk_user_author;
1637 }
1638 if (isset($this->fk_user_valid)) {
1639 $this->fk_user_valid = (int) $this->fk_user_valid;
1640 }
1641 if (isset($this->fk_delivery_address)) {
1642 $this->fk_delivery_address = (int) $this->fk_delivery_address;
1643 }
1644 if (isset($this->shipping_method_id)) {
1645 $this->shipping_method_id = (int) $this->shipping_method_id;
1646 }
1647 if (isset($this->tracking_number)) {
1648 $this->tracking_number = trim($this->tracking_number);
1649 }
1650 if (isset($this->statut)) {
1651 $this->statut = (int) $this->statut;
1652 }
1653 if (isset($this->status)) {
1654 $this->status = (int) $this->status;
1655 }
1656 if (isset($this->trueDepth)) {
1657 $this->trueDepth = trim($this->trueDepth);
1658 }
1659 if (isset($this->trueWidth)) {
1660 $this->trueWidth = trim($this->trueWidth);
1661 }
1662 if (isset($this->trueHeight)) {
1663 $this->trueHeight = trim($this->trueHeight);
1664 }
1665 if (isset($this->size_units)) {
1666 $this->size_units = trim($this->size_units);
1667 }
1668 if (isset($this->weight_units)) {
1669 $this->weight_units = (int) $this->weight_units;
1670 }
1671 if (isset($this->trueWeight)) {
1672 $this->weight = trim((string) $this->trueWeight);
1673 }
1674 if (isset($this->note_private)) {
1675 $this->note_private = trim($this->note_private);
1676 }
1677 if (isset($this->note_public)) {
1678 $this->note_public = trim($this->note_public);
1679 }
1680 if (isset($this->model_pdf)) {
1681 $this->model_pdf = trim($this->model_pdf);
1682 }
1683 if (!empty($this->date_expedition)) {
1684 $this->date_shipping = $this->date_expedition;
1685 }
1686
1687 // Check parameters
1688 // Put here code to add control on parameters values
1689
1690 // Update request
1691 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
1692 $sql .= " ref = ".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1693 $sql .= " ref_ext = ".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1694 $sql .= " ref_customer = ".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1695 $sql .= " fk_soc = ".(isset($this->socid) ? ((int) $this->socid) : "null").",";
1696 $sql .= " date_creation = ".(dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1697 $sql .= " fk_user_author = ".(isset($this->fk_user_author) ? ((int) $this->fk_user_author) : "null").",";
1698 $sql .= " date_valid = ".(dol_strlen($this->date_valid) != 0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
1699 $sql .= " fk_user_valid = ".(isset($this->fk_user_valid) ? ((int) $this->fk_user_valid) : "null").",";
1700 $sql .= " date_expedition = ".(dol_strlen($this->date_shipping) != 0 ? "'".$this->db->idate($this->date_shipping)."'" : 'null').",";
1701 $sql .= " date_delivery = ".(dol_strlen($this->date_delivery) != 0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
1702 $sql .= " fk_address = ".(isset($this->fk_delivery_address) ? ((int) $this->fk_delivery_address) : "null").",";
1703 $sql .= " fk_shipping_method = ".((isset($this->shipping_method_id) && $this->shipping_method_id > 0) ? ((int) $this->shipping_method_id) : "null").",";
1704 $sql .= " tracking_number = ".(isset($this->tracking_number) ? "'".$this->db->escape($this->tracking_number)."'" : "null").",";
1705 $sql .= " fk_statut = ".(isset($this->status) ? ((int) $this->status) : "null").",";
1706 $sql .= " fk_projet = ".(isset($this->fk_project) ? ((int) $this->fk_project) : "null").",";
1707 $sql .= " height = ".(($this->trueHeight != '') ? ((float) $this->trueHeight) : "null").",";
1708 $sql .= " width = ".(($this->trueWidth != '') ? ((float) $this->trueWidth) : "null").",";
1709 $sql .= " size_units = ".(isset($this->size_units) ? ((int) $this->size_units) : "null").",";
1710 $sql .= " size = ".(($this->trueDepth != '') ? ((float) $this->trueDepth) : "null").",";
1711 $sql .= " weight_units = ".(isset($this->weight_units) ? ((int) $this->weight_units) : "null").",";
1712 $sql .= " weight = ".(($this->trueWeight != '') ? ((float) $this->trueWeight) : "null").",";
1713 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1714 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1715 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1716 $sql .= " entity = ".((int) $conf->entity);
1717 $sql .= " WHERE rowid = ".((int) $this->id);
1718
1719 $this->db->begin();
1720
1721 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1722 $resql = $this->db->query($sql);
1723 if (!$resql) {
1724 $error++;
1725 $this->errors[] = "Error ".$this->db->lasterror();
1726 }
1727
1728 // Actions on extra fields
1729 if (!$error) {
1730 $result = $this->insertExtraFields();
1731 if ($result < 0) {
1732 $error++;
1733 }
1734 }
1735
1736 if (!$error && !$notrigger) {
1737 // Call trigger
1738 $result = $this->call_trigger('SHIPPING_MODIFY', $user);
1739 if ($result < 0) {
1740 $error++;
1741 }
1742 // End call triggers
1743 }
1744
1745 // Commit or rollback
1746 if ($error) {
1747 foreach ($this->errors as $errmsg) {
1748 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1749 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1750 }
1751 $this->db->rollback();
1752 return -1 * $error;
1753 } else {
1754 $this->db->commit();
1755 return 1;
1756 }
1757 }
1758
1759
1768 public function cancel($user, $notrigger = 0, $also_update_stock = false)
1769 {
1770 global $conf, $langs, $user;
1771
1772 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1773
1774 $error = 0;
1775 $this->error = '';
1776
1777 $this->db->begin();
1778
1779 // Add a protection to refuse deleting if shipment has at least one delivery
1780 $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment
1781 if (isset($this->linkedObjectsIds['delivery']) && count($this->linkedObjectsIds['delivery']) > 0) {
1782 $this->error = 'ErrorThereIsSomeDeliveries';
1783 $error++;
1784 }
1785
1786 if (!$error && !$notrigger) {
1787 // Call trigger
1788 $result = $this->call_trigger('SHIPPING_CANCEL', $user);
1789 if ($result < 0) {
1790 $error++;
1791 }
1792 // End call triggers
1793 }
1794
1795 // Stock control
1796 $can_update_stock = isModEnabled('stock') &&
1797 ((getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') && $this->status > self::STATUS_DRAFT) ||
1798 (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE') && $this->status == self::STATUS_CLOSED && $also_update_stock));
1799 if (!$error) {
1800 require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
1801
1802 $langs->load("agenda");
1803
1804 // Loop on each product line to add a stock movement (contain sub-products)
1805 $sql = "SELECT ";
1806 $sql .= " ed.fk_product";
1807 $sql .= ", ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
1808 $sql .= ", SUM(".$this->db->ifsql("pa.rowid IS NOT NULL", "1", "0").") as iskit";
1809 $sql .= ", ".$this->db->ifsql("pai.incdec IS NULL", "1", "pai.incdec")." as incdec";
1810 $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
1811 $sql .= " LEFT JOIN ".$this->db->prefix()."product_association as pa ON pa.fk_product_pere = ed.fk_product";
1812 $sql .= " LEFT JOIN ".$this->db->prefix()."expeditiondet as edp ON edp.rowid = ed.fk_parent";
1813 $sql .= " LEFT JOIN ".$this->db->prefix()."product_association as pai ON pai.fk_product_pere = edp.fk_product AND pai.fk_product_fils = ed.fk_product";
1814 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
1815 $sql .= " GROUP BY ed.fk_product, ed.qty, ed.fk_entrepot, ed.rowid, pai.incdec";
1816 $sql .= $this->db->order("ed.rowid", "DESC");
1817
1818 dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
1819 $resql = $this->db->query($sql);
1820 if ($resql) {
1821 $cpt = $this->db->num_rows($resql);
1822
1823 $shipmentlinebatch = new ExpeditionLineBatch($this->db);
1824
1825 for ($i = 0; $i < $cpt; $i++) {
1826 dol_syslog(get_class($this)."::delete movement index ".$i);
1827 $obj = $this->db->fetch_object($resql);
1828 $line_id = (int) $obj->expeditiondet_id;
1829
1830 if ($can_update_stock && (empty($obj->iskit) || getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) && !empty($obj->incdec)) {
1831 $mouvS = new MouvementStock($this->db);
1832 // we do not log origin because it will be deleted
1833 $mouvS->origin = '';
1834 // get lot/serial
1835 $lotArray = null;
1836 if (isModEnabled('productbatch')) {
1837 $lotArray = $shipmentlinebatch->fetchAll($obj->expeditiondet_id);
1838 if (!is_array($lotArray)) {
1839 $error++;
1840 $this->errors[] = "Error ".$this->db->lasterror();
1841 }
1842 }
1843
1844 if (empty($lotArray)) {
1845 // no lot/serial
1846 // We increment stock of product (and sub-products)
1847 // We use warehouse selected for each line
1848 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ShipmentCanceledInDolibarr", $this->ref), '', '', '', '', 0, '', 0, (empty($obj->iskit) ? 1 : 0)); // Price is set to 0, because we don't want to see WAP changed
1849 if ($result < 0) {
1850 $error++;
1851 $this->errors = array_merge($this->errors, $mouvS->errors);
1852 break;
1853 }
1854 } else {
1855 // We increment stock of batches
1856 // We use warehouse selected for each line
1857 foreach ($lotArray as $lot) {
1858 if (empty($lot->qty)) {
1859 continue;
1860 }
1861 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->trans("ShipmentCanceledInDolibarr", $this->ref), '', '', (string) $lot->batch, '', 0, '', 0, (empty($obj->iskit) ? 1 : 0)); // Price is set to 0, because we don't want to see WAP changed. Dates are not given: those of the lot are used (the copy on the line may be outdated)
1862 if ($result < 0) {
1863 $error++;
1864 $this->errors = array_merge($this->errors, $mouvS->errors);
1865 break;
1866 }
1867 }
1868 if ($error) {
1869 break; // break for loop in case of error
1870 }
1871 }
1872 }
1873
1874 if (!$error) {
1875 // delete all children and batches of this shipment line
1876 $shipment_line = new ExpeditionLigne($this->db);
1877 $res = $shipment_line->fetch($line_id);
1878 if ($res > 0) {
1879 $result = $shipment_line->delete($user);
1880 if ($result < 0) {
1881 $error++;
1882 $this->errors[] = "Error ".$shipment_line->errorsToString();
1883 }
1884 } else {
1885 $error++;
1886 $this->errors[] = "Error ".$shipment_line->errorsToString();
1887 }
1888 }
1889
1890 if ($error) {
1891 break;
1892 }
1893 }
1894 } else {
1895 $error++;
1896 $this->errors[] = "Error ".$this->db->lasterror();
1897 }
1898 }
1899
1900 // No delete expedition
1901 if (!$error) {
1902 $sql = "SELECT rowid FROM ".$this->db->prefix()."expedition";
1903 $sql .= " WHERE rowid = ".((int) $this->id);
1904
1905 if ($this->db->query($sql)) {
1906 if (!empty($this->origin) && $this->origin_id > 0) {
1907 $this->fetch_origin();
1909 '@phan-var-force Facture|Commande $origin_object';
1911 if ($origin_object->status == Commande::STATUS_SHIPMENTONPROCESS) { // If order source of shipment is "shipment in progress"
1912 // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
1913 $origin_object->loadExpeditions();
1914 if (count($origin_object->expeditions) <= 0) {
1916 }
1917 }
1918 }
1919
1920 $this->db->commit();
1921
1922 // We delete PDFs
1923 $ref = dol_sanitizeFileName($this->ref);
1924 if (!empty($conf->expedition->dir_output)) {
1925 $dir = $conf->expedition->dir_output.'/sending/'.$ref;
1926 $file = $dir.'/'.$ref.'.pdf';
1927 if (file_exists($file)) {
1928 if (!dol_delete_file($file)) {
1929 return 0;
1930 }
1931 }
1932 if (file_exists($dir)) {
1933 if (!dol_delete_dir_recursive($dir)) {
1934 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
1935 return 0;
1936 }
1937 }
1938 }
1939
1940 return 1;
1941 } else {
1942 $this->error = $this->db->lasterror()." - sql=$sql";
1943 $this->db->rollback();
1944 return -3;
1945 }
1946 } else {
1947 $this->db->rollback();
1948 return -2;
1949 }
1950 }
1951
1961 public function delete($user = null, $notrigger = 0, $also_update_stock = false)
1962 {
1963 global $conf, $langs;
1964
1965 if (empty($user)) {
1966 global $user;
1967 }
1968
1969 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1970
1971 $error = 0;
1972 $this->error = '';
1973
1974 $this->db->begin();
1975
1976 // Add a protection to refuse deleting if shipment has at least one delivery
1977 $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment
1978 if (isset($this->linkedObjectsIds['delivery']) && count($this->linkedObjectsIds['delivery']) > 0) {
1979 $this->error = 'ErrorThereIsSomeDeliveries';
1980 $error++;
1981 }
1982
1983 if (!$error && !$notrigger) {
1984 // Call trigger
1985 $result = $this->call_trigger('SHIPPING_DELETE', $user);
1986 if ($result < 0) {
1987 $error++;
1988 }
1989 // End call triggers
1990 }
1991
1992 // Stock control
1993 $can_update_stock = isModEnabled('stock') &&
1994 ((getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') && $this->status > self::STATUS_DRAFT) ||
1995 (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE') && $this->status == self::STATUS_CLOSED && $also_update_stock));
1996 if (!$error) {
1997 require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
1998
1999 $langs->load("agenda");
2000
2001 // we try deletion of batch line even if module batch not enabled in case of the module were enabled and disabled previously
2002 $shipmentlinebatch = new ExpeditionLineBatch($this->db);
2003
2004 // Loop on each product line to add a stock movement (contain sub-products)
2005 $sql = "SELECT ";
2006 $sql .= " ed.fk_product";
2007 $sql .= ", ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
2008 $sql .= ", SUM(".$this->db->ifsql("pa.rowid IS NOT NULL", "1", "0").") as iskit";
2009 $sql .= ", ".$this->db->ifsql("pai.incdec IS NULL", "1", "pai.incdec")." as incdec";
2010 $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
2011 $sql .= " LEFT JOIN ".$this->db->prefix()."product_association as pa ON pa.fk_product_pere = ed.fk_product";
2012 $sql .= " LEFT JOIN ".$this->db->prefix()."expeditiondet as edp ON edp.rowid = ed.fk_parent";
2013 $sql .= " LEFT JOIN ".$this->db->prefix()."product_association as pai ON pai.fk_product_pere = edp.fk_product AND pai.fk_product_fils = ed.fk_product";
2014 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
2015 $sql .= " GROUP BY ed.fk_product, ed.qty, ed.fk_entrepot, ed.rowid, pai.incdec";
2016 $sql .= $this->db->order("ed.rowid", "DESC");
2017
2018 dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
2019 $resql = $this->db->query($sql);
2020 if ($resql) {
2021 $cpt = $this->db->num_rows($resql);
2022 for ($i = 0; $i < $cpt; $i++) {
2023 dol_syslog(get_class($this)."::delete movement index ".$i);
2024 $obj = $this->db->fetch_object($resql);
2025 $line_id = (int) $obj->expeditiondet_id;
2026
2027 if ($can_update_stock && (empty($obj->iskit) || getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) && !empty($obj->incdec)) {
2028 $mouvS = new MouvementStock($this->db);
2029 // we do not log origin because it will be deleted
2030 $mouvS->origin = '';
2031 // get lot/serial
2032 $lotArray = $shipmentlinebatch->fetchAll($line_id);
2033 if (!is_array($lotArray)) {
2034 $error++;
2035 $this->errors[] = "Error ".$this->db->lasterror();
2036 }
2037 if (empty($lotArray)) {
2038 // no lot/serial
2039 // We increment stock of product (disable for sub-products : already in shipment lines)
2040 // We use warehouse selected for each line
2041 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref), '', '', '', '', 0, '', 0, (empty($obj->iskit) ? 1 : 0)); // Price is set to 0, because we don't want to see WAP changed
2042 if ($result < 0) {
2043 $error++;
2044 $this->errors = array_merge($this->errors, $mouvS->errors);
2045 break;
2046 }
2047 } else {
2048 // We increment stock of batches
2049 // We use warehouse selected for each line
2050 foreach ($lotArray as $lot) {
2051 if (empty($lot->qty)) {
2052 continue;
2053 }
2054 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref), '', '', (string) $lot->batch, '', 0, '', 0, (empty($obj->iskit) ? 1 : 0)); // Price is set to 0, because we don't want to see WAP changed. Dates are not given: those of the lot are used (the copy on the line may be outdated)
2055 if ($result < 0) {
2056 $error++;
2057 $this->errors = array_merge($this->errors, $mouvS->errors);
2058 break;
2059 }
2060 }
2061 if ($error) {
2062 break; // break for loop in case of error
2063 }
2064 }
2065 }
2066
2067 if (!$error) {
2068 // delete all children and batches of this shipment line
2069 $shipment_line = new ExpeditionLigne($this->db);
2070 $res = $shipment_line->fetch($line_id);
2071 if ($res > 0) {
2072 $result = $shipment_line->delete($user);
2073 if ($result < 0) {
2074 $error++;
2075 $this->errors[] = "Error ".$shipment_line->errorsToString();
2076 }
2077 } else {
2078 $error++;
2079 $this->errors[] = "Error ".$shipment_line->errorsToString();
2080 }
2081 }
2082
2083 if ($error) {
2084 break;
2085 }
2086 }
2087 } else {
2088 $error++;
2089 $this->errors[] = "Error ".$this->db->lasterror();
2090 }
2091 }
2092
2093 if (!$error) {
2094 // Delete linked object
2095 $res = $this->deleteObjectLinked();
2096 if ($res < 0) {
2097 $error++;
2098 }
2099
2100 // delete extrafields
2101 $res = $this->deleteExtraFields();
2102 if ($res < 0) {
2103 $error++;
2104 }
2105
2106 if (!$error) {
2107 // Delete linked contacts
2108 $res = $this->delete_linked_contact();
2109 if ($res < 0) {
2110 $error++;
2111 }
2112 }
2113 if (!$error) {
2114 $sql = "DELETE FROM ".$this->db->prefix()."expedition";
2115 $sql .= " WHERE rowid = ".((int) $this->id);
2116
2117 if ($this->db->query($sql)) {
2118 if (!empty($this->origin) && $this->origin_id > 0) {
2119 $this->fetch_origin();
2121 '@phan-var-force Facture|Commande $origin_object';
2122 if ($origin_object->status == Commande::STATUS_SHIPMENTONPROCESS) { // If order source of shipment is "shipment in progress"
2123 // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
2124 $origin_object->loadExpeditions();
2125 if (count($origin_object->expeditions) <= 0) {
2127 }
2128 }
2129 }
2130
2131 $this->db->commit();
2132
2133 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2134 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2135 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2136
2137 // We delete PDFs
2138 $ref = dol_sanitizeFileName($this->ref);
2139 if (!empty($conf->expedition->dir_output) && !empty($ref)) {
2140 $dir = $conf->expedition->dir_output . '/sending/' . $ref;
2141 $file = $dir . '/' . $ref . '.pdf';
2142 if (file_exists($file)) {
2143 if (!dol_delete_file($file)) {
2144 return 0;
2145 }
2146 }
2147 if (file_exists($dir)) {
2148 if (!dol_delete_dir_recursive($dir)) {
2149 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
2150 return 0;
2151 }
2152 }
2153 }
2154
2155 return 1;
2156 } else {
2157 $this->error = $this->db->lasterror()." - sql=$sql";
2158 $this->db->rollback();
2159 return -3;
2160 }
2161 } else {
2162 $this->db->rollback();
2163 return -2;
2164 }
2165 } else {
2166 $this->db->rollback();
2167 return -1;
2168 }
2169 }
2170
2171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2177 public function fetch_lines()
2178 {
2179 // phpcs:enable
2180 global $mysoc;
2181
2182 $this->lines = array();
2183
2184 // NOTE: This fetch_lines is special because it groups all lines with the same origin_line_id into one line.
2185 // TODO: See if we can restore a common fetch_lines (one line = one record)
2186
2187 $sql = "SELECT cd.rowid, cd.fk_product, cd.label as custom_label, cd.description, cd.qty as qty_asked, cd.product_type, cd.fk_unit";
2188 $sql .= ", cd.total_ht, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.total_tva";
2189 $sql .= ", cd.fk_remise_except, cd.fk_product_fournisseur_price as fk_fournprice";
2190 $sql .= ", cd.vat_src_code, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.info_bits, cd.price, cd.subprice, cd.remise_percent,cd.buy_price_ht as pa_ht";
2191 $sql .= ", cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc, cd.rang, cd.date_start, cd.date_end, cd.special_code";
2192 $sql .= ", ed.rowid as line_id, ed.qty as qty_shipped, ed.fk_element, ed.fk_elementdet, ed.element_type, ed.fk_entrepot, ed.extraparams";
2193 $sql .= ", p.ref as product_ref, p.label as product_label, p.fk_product_type, p.barcode as product_barcode";
2194 $sql .= ", p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units";
2195 $sql .= ", p.surface, p.surface_units, p.volume, p.volume_units, p.tosell as product_tosell, p.tobuy as product_tobuy";
2196 $sql .= ", p.tobatch as product_tobatch, p.stockable_product";
2197 $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed, ".MAIN_DB_PREFIX."commandedet as cd";
2198 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = cd.fk_product";
2199 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
2200 $sql .= " AND ed.fk_elementdet = cd.rowid";
2201 $sql .= " ORDER BY CASE WHEN ed.rang IS NULL OR ed.rang = 0 THEN cd.rang ELSE ed.rang END, ed.rowid";
2202
2203 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
2204 $resql = $this->db->query($sql);
2205 if ($resql) {
2206 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2207
2208 $num = $this->db->num_rows($resql);
2209 $i = 0;
2210 $line = new ExpeditionLigne($this->db);
2211 $lineindex = 0;
2212 $originline = 0;
2213
2214 $this->total_ht = 0;
2215 $this->total_tva = 0;
2216 $this->total_ttc = 0;
2217 $this->total_localtax1 = 0;
2218 $this->total_localtax2 = 0;
2219
2220 $this->multicurrency_total_ht = 0;
2221 $this->multicurrency_total_tva = 0;
2222 $this->multicurrency_total_ttc = 0;
2223
2224 $shipmentlinebatch = new ExpeditionLineBatch($this->db);
2225
2226 $line = new ExpeditionLigne($this->db); // always set $line for PHAN analyser. @phan-var-force muse be used after an assignation, and there is no assignation for $line.
2227 while ($i < $num) {
2228 $obj = $this->db->fetch_object($resql);
2229
2230 if ($originline > 0 && $originline == $obj->fk_elementdet) {
2231 // '@phan-var-force ExpeditionLigne $line'; // $line from previous loop
2232 $line->entrepot_id = 0; // entrepod_id in details_entrepot
2233 $line->qty_shipped += $obj->qty_shipped;
2234 } else {
2235 $line = new ExpeditionLigne($this->db); // new group to start
2236 $line->entrepot_id = $obj->fk_entrepot; // this is a property of a shipment line
2237 $line->qty_shipped = $obj->qty_shipped; // this is a property of a shipment line
2238 }
2239
2240 $detail_entrepot = new stdClass();
2241 $detail_entrepot->entrepot_id = $obj->fk_entrepot;
2242 $detail_entrepot->qty_shipped = $obj->qty_shipped;
2243 $detail_entrepot->line_id = $obj->line_id;
2244 $line->details_entrepot[] = $detail_entrepot;
2245
2246 $line->line_id = $obj->line_id; // TODO deprecated
2247 $line->rowid = $obj->line_id; // TODO deprecated
2248 $line->id = $obj->line_id;
2249
2250 $line->fk_origin = 'orderline'; // TODO deprecated, we already have element_type that can be use to guess type of line
2251
2252 $line->fk_element = $obj->fk_element;
2253 $line->origin_id = $obj->fk_element;
2254 $line->fk_elementdet = $obj->fk_elementdet;
2255 $line->origin_line_id = $obj->fk_elementdet;
2256 $line->element_type = $obj->element_type;
2257
2258 $line->fk_expedition = $this->id; // id of parent
2259
2260 $line->stockable_product = $obj->stockable_product;
2261 $line->product_type = $obj->product_type;
2262 $line->fk_product = $obj->fk_product;
2263 $line->fk_product_type = $obj->fk_product_type;
2264 $line->ref = $obj->product_ref; // TODO deprecated
2265 $line->product_ref = $obj->product_ref;
2266 $line->product_label = $obj->product_label;
2267 $line->libelle = $obj->product_label; // TODO deprecated
2268 $line->product_barcode = $obj->product_barcode; // Barcode number product
2269 $line->product_tosell = $obj->product_tosell;
2270 $line->product_tobuy = $obj->product_tobuy;
2271 $line->product_tobatch = $obj->product_tobatch;
2272 $line->fk_fournprice = $obj->fk_fournprice;
2273 $line->label = $obj->custom_label;
2274 $line->description = $obj->description;
2275 $line->qty_asked = $obj->qty_asked;
2276 $line->rang = $obj->rang;
2277 $line->weight = $obj->weight;
2278 $line->weight_units = $obj->weight_units;
2279 $line->length = $obj->length;
2280 $line->length_units = $obj->length_units;
2281 $line->width = $obj->width;
2282 $line->width_units = $obj->width_units;
2283 $line->height = $obj->height;
2284 $line->height_units = $obj->height_units;
2285 $line->surface = $obj->surface;
2286 $line->surface_units = $obj->surface_units;
2287 $line->volume = $obj->volume;
2288 $line->volume_units = $obj->volume_units;
2289 $line->stockable_product = $obj->stockable_product;
2290 $line->fk_unit = $obj->fk_unit;
2291
2292 $line->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2293
2294 $line->pa_ht = $obj->pa_ht;
2295
2296 // Local taxes
2297 $localtax_array = array(0 => $obj->localtax1_type, 1 => $obj->localtax1_tx, 2 => $obj->localtax2_type, 3 => $obj->localtax2_tx);
2298 $localtax1_tx = get_localtax($obj->tva_tx, 1, $this->thirdparty);
2299 $localtax2_tx = get_localtax($obj->tva_tx, 2, $this->thirdparty);
2300
2301 // For invoicing
2302 $tabprice = calcul_price_total($obj->qty_shipped, $obj->subprice, $obj->remise_percent, $obj->tva_tx, $localtax1_tx, $localtax2_tx, 0, 'HT', $obj->info_bits, $obj->fk_product_type, $mysoc, $localtax_array); // We force type to 0
2303 $line->desc = $obj->description; // We need ->desc because some code into CommonObject use desc (property defined for other elements)
2304 $line->qty = $line->qty_shipped;
2305 $line->total_ht = (float) $tabprice[0];
2306 $line->total_localtax1 = (float) $tabprice[9];
2307 $line->total_localtax2 = (float) $tabprice[10];
2308 $line->total_ttc = (float) $tabprice[2];
2309 $line->total_tva = (float) $tabprice[1];
2310 $line->vat_src_code = $obj->vat_src_code;
2311 $line->tva_tx = $obj->tva_tx;
2312 $line->localtax1_tx = $obj->localtax1_tx;
2313 $line->localtax2_tx = $obj->localtax2_tx;
2314 $line->info_bits = $obj->info_bits;
2315 $line->price = $obj->price;
2316 $line->subprice = $obj->subprice;
2317 $line->fk_remise_except = $obj->fk_remise_except;
2318 $line->remise_percent = $obj->remise_percent;
2319
2320 $this->total_ht += $tabprice[0];
2321 $this->total_tva += $tabprice[1];
2322 $this->total_ttc += $tabprice[2];
2323 $this->total_localtax1 += $tabprice[9];
2324 $this->total_localtax2 += $tabprice[10];
2325
2326 $line->date_start = $this->db->jdate($obj->date_start);
2327 $line->date_end = $this->db->jdate($obj->date_end);
2328
2329 $line->special_code = $obj->special_code;
2330
2331 // Multicurrency
2332 $this->fk_multicurrency = $obj->fk_multicurrency;
2333 $this->multicurrency_code = $obj->multicurrency_code;
2334 $line->multicurrency_subprice = $obj->multicurrency_subprice;
2335 $line->multicurrency_total_ht = $obj->multicurrency_total_ht;
2336 $line->multicurrency_total_tva = $obj->multicurrency_total_tva;
2337 $line->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2338
2339 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
2340 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
2341 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
2342
2343 // Detail of batch
2344 if (isModEnabled('productbatch') && $obj->line_id > 0 && $obj->product_tobatch > 0) {
2345 if ($originline != $obj->fk_elementdet) {
2346 $line->detail_batch = array();
2347 }
2348 $newdetailbatch = $shipmentlinebatch->fetchAll($obj->line_id, $obj->fk_product);
2349
2350 if (is_array($newdetailbatch)) {
2351 if ($originline != $obj->fk_elementdet) {
2352 $line->detail_batch = $newdetailbatch;
2353 } else {
2354 $line->detail_batch = array_merge($line->detail_batch, $newdetailbatch);
2355 }
2356 }
2357 }
2358
2359 // virtual product : find all children stock (group by product id and warehouse id)
2360 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
2361 $detail_children = array(); // detail by product : array of [warehouse_id => total_qty]
2362 $line_child_list = array();
2363 $res = $line->findAllChild($line->id, $line_child_list, 1);
2364 if ($res > 0) {
2365 foreach ($line_child_list as $child_line) {
2366 foreach ($child_line as $child_obj) {
2367 $child_product_id = (int) $child_obj->fk_product;
2368 $child_warehouse_id = (int) $child_obj->fk_warehouse;
2369
2370 if ($child_warehouse_id > 0) {
2371 // child quantities group by warehouses
2372 if (!isset($detail_children[$child_product_id])) {
2373 $detail_children[$child_product_id] = array();
2374 }
2375 if (!isset($detail_children[$child_product_id][$child_warehouse_id])) {
2376 $detail_children[$child_product_id][$child_warehouse_id] = 0;
2377 }
2378 $detail_children[$child_product_id][$child_warehouse_id] += $child_obj->qty;
2379 }
2380 }
2381 }
2382 }
2383 $line->detail_children = $detail_children;
2384 }
2385
2386 $line->fetch_optionals();
2387
2388 if ($originline != $obj->fk_elementdet) {
2389 $this->lines[$lineindex] = $line;
2390 $lineindex++;
2391 } else {
2392 $line->total_ht += $tabprice[0];
2393 $line->total_localtax1 += $tabprice[9];
2394 $line->total_localtax2 += $tabprice[10];
2395 $line->total_ttc += $tabprice[2];
2396 $line->total_tva += $tabprice[1];
2397 }
2398
2399 $i++;
2400 $originline = $obj->fk_elementdet;
2401 }
2402 $this->db->free($resql);
2403 return 1;
2404 } else {
2405 $this->error = $this->db->error();
2406 return -3;
2407 }
2408 }
2409
2410
2411 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2417 public function fetch_lines_free()
2418 {
2419 // phpcs:enable
2420 global $mysoc;
2421
2422 $this->lines = array();
2423
2424 $sql = 'SELECT ed.rowid, ed.fk_expedition, ed.fk_entrepot, ed.fk_product, ed.fk_unit, ed.description, ed.fk_elementdet, ed.fk_element, ed.element_type, ed.qty, ed.rang';
2425 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as ed';
2426 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = ed.fk_product)';
2427 $sql .= ' WHERE ed.fk_expedition = '.((int) $this->id);
2428 $sql .= ' ORDER BY ed.rang, ed.rowid';
2429
2430 dol_syslog(get_class($this)."::fetch_lines_free", LOG_DEBUG);
2431 $result = $this->db->query($sql);
2432 if ($result) {
2433 $num = $this->db->num_rows($result);
2434
2435 $i = 0;
2436 while ($i < $num) {
2437 $objp = $this->db->fetch_object($result);
2438
2439 $line = new ExpeditionLigne($this->db);
2440
2441 $line->rowid = $objp->rowid;
2442 $line->id = $objp->rowid;
2443 $line->fk_expedition = $this->id;
2444 $line->description = $objp->description;
2445 $line->qty = $objp->qty;
2446 $line->fk_entrepot = $objp->fk_entrepot;
2447 $line->fk_product = $objp->fk_product;
2448 $line->rang = $objp->rang;
2449 $line->fk_element = $objp->fk_element;
2450 $line->fk_unit = $objp->fk_unit;
2451 $line->fk_elementdet = $objp->fk_elementdet;
2452 $line->fk_element_type = $objp->element_type;
2453 $line->fetch_optionals();
2454
2455 $this->lines[$i] = $line;
2456
2457 $i++;
2458 }
2459
2460 $this->db->free($result);
2461
2462 return 1;
2463 } else {
2464 $this->error = $this->db->error();
2465 return -3;
2466 }
2467 }
2468
2474 public function getLinesArray()
2475 {
2476 return $this->fetch_lines_free();
2477 }
2478
2486 public function deleteLine($user, $lineid)
2487 {
2488 global $user;
2489
2490 if ($this->status == self::STATUS_DRAFT) {
2491 $this->db->begin();
2492
2493 $line = new ExpeditionLigne($this->db);
2494
2495 // For triggers
2496 $line->fetch($lineid);
2497
2498 if ($this->id > 0 && (int) $line->fk_expedition !== (int) $this->id) {
2499 $this->db->rollback();
2500 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2501 return -1;
2502 }
2503
2504 if ($line->delete($user) > 0) {
2505 //$this->update_price(1);
2506
2507 $this->db->commit();
2508 return 1;
2509 } else {
2510 $this->db->rollback();
2511 return -1;
2512 }
2513 } else {
2514 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
2515 return -2;
2516 }
2517 }
2518
2519
2526 public function getTooltipContentArray($params)
2527 {
2528 global $conf, $langs;
2529
2530 $langs->load('sendings');
2531
2532 $nofetch = !empty($params['nofetch']);
2533
2534 $datas = array();
2535 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Shipment").'</u>';
2536 if (isset($this->status)) {
2537 $datas['picto'] .= ' '.$this->getLibStatut(5);
2538 }
2539 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2540 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.($this->ref_customer ? $this->ref_customer : $this->ref_client);
2541 if (!$nofetch) {
2542 $langs->load('companies');
2543 if (empty($this->thirdparty)) {
2544 $this->fetch_thirdparty();
2545 }
2546 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2547 }
2548
2549 return $datas;
2550 }
2551
2563 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1)
2564 {
2565 global $langs, $hookmanager;
2566
2567 $result = '';
2568 $params = [
2569 'id' => $this->id,
2570 'objecttype' => $this->element,
2571 'option' => $option,
2572 'nofetch' => 1,
2573 ];
2574 $classfortooltip = 'classfortooltip';
2575 $dataparams = '';
2576 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2577 $classfortooltip = 'classforajaxtooltip';
2578 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2579 $label = '';
2580 } else {
2581 $label = implode($this->getTooltipContentArray($params));
2582 }
2583
2584 $url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id;
2585
2586 if ($short) {
2587 return $url;
2588 }
2589
2590 if ($option !== 'nolink') {
2591 // Add param to save lastsearch_values or not
2592 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2593 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2594 $add_save_lastsearch_values = 1;
2595 }
2596 if ($add_save_lastsearch_values) {
2597 $url .= '&save_lastsearch_values=1';
2598 }
2599 }
2600
2601 $linkclose = '';
2602 if (empty($notooltip)) {
2603 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2604 $label = $langs->trans("Shipment");
2605 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2606 }
2607 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2608 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2609 }
2610
2611 $linkstart = '<a href="'.$url.'"';
2612 $linkstart .= $linkclose.'>';
2613 $linkend = '</a>';
2614
2615 $result .= $linkstart;
2616 if ($withpicto) {
2617 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2618 }
2619 if ($withpicto != 2) {
2620 $result .= $this->ref;
2621 }
2622 $result .= $linkend;
2623 global $action;
2624 $hookmanager->initHooks(array($this->element . 'dao'));
2625 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2626 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2627 if ($reshook > 0) {
2628 $result = $hookmanager->resPrint;
2629 } else {
2630 $result .= $hookmanager->resPrint;
2631 }
2632 return $result;
2633 }
2634
2641 public function getLibStatut($mode = 0)
2642 {
2643 return $this->LibStatut($this->status, $mode);
2644 }
2645
2646 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2654 public function LibStatut($status, $mode)
2655 {
2656 // phpcs:enable
2657 global $langs;
2658
2659 $labelStatus = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
2660 $labelStatusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
2661
2662 $statusType = 'status'.$status;
2663 if ($status == self::STATUS_VALIDATED) {
2664 $statusType = 'status4';
2665 }
2666 if ($status == self::STATUS_CLOSED) {
2667 $statusType = 'status6';
2668 }
2669 if ($status == self::STATUS_CANCELED) {
2670 $statusType = 'status9';
2671 }
2672
2673 $signed_label = ' (' . $this->getLibSignedStatus() . ')';
2674 $status_label = $this->signed_status ? $labelStatus . $signed_label : $labelStatus;
2675 $status_label_short = $this->signed_status ? $labelStatusShort . $signed_label : $labelStatusShort;
2676
2677 return dolGetStatus($status_label, $status_label_short, '', $statusType, $mode);
2678 }
2679
2687 public function getKanbanView($option = '', $arraydata = null)
2688 {
2689 global $langs, $conf;
2690
2691 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2692
2693 $return = '<div class="box-flex-item box-flex-grow-zero">';
2694 $return .= '<div class="info-box info-box-sm">';
2695 $return .= '<div class="info-box-icon bg-infobox-action">';
2696 $return .= img_picto('', 'order');
2697 $return .= '</div>';
2698 $return .= '<div class="info-box-content">';
2699 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
2700 if ($selected >= 0) {
2701 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2702 }
2703 $return .= '<br><div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
2704 $return .= '<div class="info-box-ref amount">'.price($this->total_ht, 0, $langs, 0, -1, -1, getDolCurrency()).' '.$langs->trans('HT').'</div>';
2705 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2706 $return .= '</div>';
2707 $return .= '</div>';
2708 $return .= '</div>';
2709
2710 return $return;
2711 }
2712
2720 public function initAsSpecimen()
2721 {
2722 global $langs;
2723
2724 $now = dol_now();
2725
2726 dol_syslog(get_class($this)."::initAsSpecimen");
2727
2728 $order = new Commande($this->db);
2729 $order->initAsSpecimen();
2730
2731 // Initialise parameters
2732 $this->id = 0;
2733 $this->ref = 'SPECIMEN';
2734 $this->specimen = 1;
2736 $this->livraison_id = 0;
2737 $this->date = $now;
2738 $this->date_creation = $now;
2739 $this->date_valid = $now;
2740 $this->date_delivery = $now + 24 * 3600;
2741 $this->date_expedition = $now + 24 * 3600;
2742
2743 $this->entrepot_id = 0;
2744 $this->fk_delivery_address = 0;
2745 $this->socid = 1;
2746
2747 $this->commande_id = 0;
2748 $this->commande = $order;
2749
2750 $this->origin_id = 1;
2751 $this->origin_type = 'commande';
2752
2753 $this->note_private = 'Private note';
2754 $this->note_public = 'Public note';
2755
2756 $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)
2757 $xnbp = 0;
2758 while ($xnbp < $nbp) {
2759 $line = new ExpeditionLigne($this->db);
2760 $line->product_desc = $langs->trans("Description")." ".$xnbp;
2761 $line->product_label = $langs->trans("Description")." ".$xnbp;
2762 $line->qty = 10;
2763 $line->qty_asked = 5;
2764 $line->qty_shipped = 4;
2765 $line->fk_product = $this->commande->lines[$xnbp]->fk_product;
2766
2767 $line->weight = 1.123456;
2768 $line->weight_units = 0; // kg
2769
2770 $line->volume = 2.34567;
2771 $line->volume_unit = 0;
2772
2773 $this->lines[] = $line;
2774 $xnbp++;
2775 }
2776
2777 return 1;
2778 }
2779
2780 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2789 public function set_date_livraison($user, $delivery_date)
2790 {
2791 // phpcs:enable
2792 return $this->setDeliveryDate($user, $delivery_date);
2793 }
2794
2802 public function setDeliveryDate($user, $delivery_date)
2803 {
2804 if ($user->hasRight('expedition', 'creer')) {
2805 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
2806 $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2807 $sql .= " WHERE rowid = ".((int) $this->id);
2808
2809 dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
2810 $resql = $this->db->query($sql);
2811 if ($resql) {
2812 $this->date_delivery = $delivery_date;
2813 return 1;
2814 } else {
2815 $this->error = $this->db->error();
2816 return -1;
2817 }
2818 } else {
2819 return -2;
2820 }
2821 }
2822
2830 public function setShippingDate($user, $shipping_date)
2831 {
2832 if ($user->hasRight('expedition', 'creer')) {
2833 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
2834 $sql .= " SET date_expedition = ".($shipping_date ? "'".$this->db->idate($shipping_date)."'" : 'null');
2835 $sql .= " WHERE rowid = ".((int) $this->id);
2836
2837 dol_syslog(get_class($this)."::setShippingDate", LOG_DEBUG);
2838 $resql = $this->db->query($sql);
2839 if ($resql) {
2840 $this->date_shipping = $shipping_date;
2841 return 1;
2842 } else {
2843 $this->error = $this->db->error();
2844 return -1;
2845 }
2846 } else {
2847 return -2;
2848 }
2849 }
2850
2851 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2857 public function fetch_delivery_methods()
2858 {
2859 // phpcs:enable
2860 global $langs;
2861 $this->meths = [];
2862
2863 $sql = "SELECT em.rowid, em.code, em.libelle as label";
2864 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
2865 $sql .= " WHERE em.active = 1";
2866 $sql .= " ORDER BY em.libelle ASC";
2867
2868 $resql = $this->db->query($sql);
2869 if ($resql) {
2870 while ($obj = $this->db->fetch_object($resql)) {
2871 $label = $langs->trans('SendingMethod'.$obj->code);
2872 $this->meths[(int) $obj->rowid] = ($label != 'SendingMethod'.$obj->code ? $label : $obj->label);
2873 }
2874 }
2875 }
2876
2877 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2884 public function list_delivery_methods($id = 0)
2885 {
2886 // phpcs:enable
2887 global $langs;
2888
2889 $this->listmeths = [];
2890 $i = 0;
2891
2892 $sql = "SELECT em.rowid, em.code, em.libelle as label, em.description, em.tracking, em.active";
2893 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
2894 if (!empty($id)) {
2895 $sql .= " WHERE em.rowid=".((int) $id);
2896 }
2897
2898 $resql = $this->db->query($sql);
2899 if ($resql) {
2900 while ($obj = $this->db->fetch_object($resql)) {
2901 $label = $langs->trans('SendingMethod'.$obj->code);
2902 $this->listmeths[$i] = [
2903 'rowid' => (int) $obj->rowid,
2904 'code' => $obj->code,
2905 'libelle' => ($label != 'SendingMethod'.$obj->code ? $label : $obj->label),
2906 'description' => $obj->description,
2907 'tracking' => $obj->tracking,
2908 'active' => (int) $obj->active,
2909 ];
2910 $i++;
2911 }
2912 }
2913 }
2914
2921 public function getUrlTrackingStatus($value = '')
2922 {
2923 $tracking = '';
2924 if (!empty($this->shipping_method_id)) {
2925 $sql = "SELECT em.code, em.tracking";
2926 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
2927 $sql .= " WHERE em.rowid = ".((int) $this->shipping_method_id);
2928
2929 $resql = $this->db->query($sql);
2930 if ($resql) {
2931 if ($obj = $this->db->fetch_object($resql)) {
2932 $tracking = (string) $obj->tracking;
2933 }
2934 }
2935 }
2936
2937 if (!empty($tracking) && !empty($value)) {
2938 $url = str_replace('{TRACKID}', $value, $tracking);
2939 $this->tracking_url = sprintf('<a target="_blank" rel="noopener noreferrer" href="%s">%s</a>', $url, $value);
2940 } else {
2941 $this->tracking_url = $value;
2942 }
2943 }
2944
2950 public function setClosed()
2951 {
2952 global $langs, $user;
2953
2954 $error = 0;
2955
2956 // Protection. This avoid to move stock later when we should not
2957 if ($this->status == self::STATUS_CLOSED) {
2958 return 0;
2959 }
2960
2961 // We need to validate shipping before closing it
2962 if ($this->status == self::STATUS_DRAFT) {
2963 $this->valid($user);
2964 }
2965
2966 $this->db->begin();
2967
2968 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET fk_statut = ".self::STATUS_CLOSED;
2969 if (empty($this->date_shipping)) { // Date of real shipment was not yet set, we force it on closing
2970 $sql .= ", date_expedition = '".$this->db->escape($this->db->idate(dol_now()))."'";
2971 }
2972 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut > 0";
2973 $sql .= " AND fk_statut <> ".self::STATUS_CLOSED;
2974
2975 $resql = $this->db->query($sql);
2976 if ($resql && $this->db->affected_rows($resql) <= 0) {
2977 // The shipment is not validated (draft, canceled or already closed): nothing to close and no stock must be moved.
2978 // Return 0 (nothing done) as when it is already closed, so the workflow closing the shipments of an invoice is not stopped by a draft one.
2979 $this->db->rollback();
2980 dol_syslog(get_class($this)."::setClosed shipment ".$this->id." is not validated, nothing done", LOG_WARNING);
2981 return 0;
2982 }
2983 if ($resql) {
2984 // Set order billed if 100% of order is shipped (qty in shipment lines match qty in order lines)
2985 if ($this->origin_type == 'commande' && $this->origin_id > 0) {
2986 $order = new Commande($this->db);
2987 $order->fetch($this->origin_id);
2988
2989 $order->loadExpeditions(self::STATUS_CLOSED); // Fill $order->expeditions = array(orderlineid => qty)
2990
2991 $shipments_match_order = 1;
2992 foreach ($order->lines as $line) {
2993 $lineid = $line->id;
2994 $qty = $line->qty;
2995 $expQty = isset($order->expeditions[$lineid]) ? $order->expeditions[$lineid] : 0;
2996 if (($line->product_type == 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) && $expQty != $qty) {
2997 $shipments_match_order = 0;
2998 $text = 'Qty for order line id '.$lineid.' is '.$qty.'. However in the shipments with status Expedition::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$expQty.', so we can t close order';
2999 dol_syslog($text);
3000 break;
3001 }
3002 }
3003 if ($shipments_match_order) {
3004 dol_syslog("Qty for the ".count($order->lines)." lines of the origin order is same than qty for lines in the shipment we close (shipments_match_order is true), with new status Expedition::STATUS_CLOSED=".self::STATUS_CLOSED.', so we close order');
3005 // We close the order
3006 $order->cloture($user, 0, 0); // 0 = do not check the close permission: this is an automatic action of the shipment closing. Note this may also create an invoice if module workflow ask it
3007 }
3008 }
3009
3010 $this->statut = self::STATUS_CLOSED; // Will be revert to STATUS_VALIDATED at end if there is a rollback
3011 $this->status = self::STATUS_CLOSED; // Will be revert to STATUS_VALIDATED at end if there is a rollback
3012
3013 // If stock increment is done on closing
3014 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
3015 $result = $this->manageStockMvtOnEvt($user);
3016
3017 if ($result < 0) {
3018 $error++;
3019 }
3020 }
3021
3022 // Call trigger
3023 if (!$error) {
3024 $result = $this->call_trigger('SHIPPING_CLOSED', $user);
3025 if ($result < 0) {
3026 $error++;
3027 }
3028 }
3029 } else {
3030 dol_print_error($this->db);
3031 $error++;
3032 }
3033
3034 if (!$error) {
3035 $this->db->commit();
3036 return 1;
3037 } else {
3038 $this->statut = self::STATUS_VALIDATED;
3040
3041 $this->db->rollback();
3042 return -1;
3043 }
3044 }
3045
3054 private function manageStockMvtOnEvt($user, $labelmovement = 'ShipmentClassifyClosedInDolibarr')
3055 {
3056 global $langs;
3057
3058 $error = 0;
3059
3060 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php';
3061
3062 $langs->load("agenda");
3063
3064 // Loop on each product line to add a stock movement
3065 $sql = "SELECT";
3066 $sql .= " ed.rowid as edid, ed.fk_product, ed.qty, ed.fk_entrepot";
3067 $sql .= ", cd.rowid as cdid";
3068 $sql .= ", cd.subprice";
3069 $sql .= ", edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
3070 $sql .= ", e.ref";
3071 $sql .= " FROM " . $this->db->prefix() . "expeditiondet as ed";
3072 $sql .= " LEFT JOIN " . $this->db->prefix() . "commandedet as cd ON cd.rowid = ed.fk_elementdet";
3073 $sql .= " LEFT JOIN " . $this->db->prefix() . "expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
3074 $sql .= " INNER JOIN " . $this->db->prefix() . "expedition as e ON ed.fk_expedition = e.rowid";
3075 $sql .= " WHERE ed.fk_expedition = " . ((int) $this->id);
3076 //$sql .= " AND cd.rowid = ed.fk_elementdet";
3077
3078 dol_syslog(get_class($this) . "::valid select details", LOG_DEBUG);
3079 $resql = $this->db->query($sql);
3080 if ($resql) {
3081 $cpt = $this->db->num_rows($resql);
3082 for ($i = 0; $i < $cpt; $i++) {
3083 $obj = $this->db->fetch_object($resql);
3084 if (empty($obj->edbrowid)) {
3085 $qty = $obj->qty;
3086 } else {
3087 $qty = $obj->edbqty;
3088 }
3089 if ($qty <= 0 || ($qty < 0 && !getDolGlobalInt('SHIPMENT_ALLOW_NEGATIVE_QTY'))) {
3090 continue;
3091 }
3092 dol_syslog(get_class($this) . "::valid movement index " . $i . " ed.rowid=" . $obj->edid . " edb.rowid=" . $obj->edbrowid);
3093
3094 $mouvS = new MouvementStock($this->db);
3095 $mouvS->origin = &$this;
3096 $mouvS->setOrigin($this->element, $this->id, $obj->cdid, $obj->edid);
3097
3098 if (empty($obj->edbrowid)) {
3099 // line without batch detail
3100
3101 // 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
3102 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans($labelmovement, $obj->ref));
3103 if ($result < 0) {
3104 $this->setErrorsFromObject($mouvS);
3105 $error++;
3106 break;
3107 }
3108 } else {
3109 // line with batch detail
3110
3111 // 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
3112 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans($labelmovement, $obj->ref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
3113 if ($result < 0) {
3114 $this->setErrorsFromObject($mouvS);
3115 $error++;
3116 break;
3117 }
3118 }
3119
3120 // If some stock lines are now 0, we can remove entry into llx_product_stock, but only if there is no child lines into llx_product_batch (detail of batch, because we can imagine
3121 // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
3122 $sqldelete = "DELETE FROM ".$this->db->prefix()."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".$this->db->prefix()."product_batch as pb)";
3123 $resqldelete = $this->db->query($sqldelete);
3124 // We do not test error, it can fails if there is child in batch details
3125 }
3126 } else {
3127 $this->error = $this->db->lasterror();
3128 $this->errors[] = $this->db->lasterror();
3129 $error++;
3130 }
3131
3132 if (!$error) {
3133 return 1;
3134 } else {
3135 return -1;
3136 }
3137 }
3138
3144 public function setBilled()
3145 {
3146 global $user;
3147 $error = 0;
3148
3149 $this->db->begin();
3150
3151 $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET billed = 1';
3152 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
3153
3154 $resql = $this->db->query($sql);
3155 if ($resql) {
3156 $this->billed = 1;
3157
3158 // Call trigger
3159 $result = $this->call_trigger('SHIPPING_BILLED', $user);
3160 if ($result < 0) {
3161 $this->billed = 0;
3162 $error++;
3163 }
3164 } else {
3165 $error++;
3166 $this->errors[] = $this->db->lasterror;
3167 }
3168
3169 if (empty($error)) {
3170 $this->db->commit();
3171 return 1;
3172 } else {
3173 $this->db->rollback();
3174 return -1;
3175 }
3176 }
3177
3185 public function setDraft($user, $notrigger = 0)
3186 {
3187 // Protection
3188 if ($this->status <= self::STATUS_DRAFT) {
3189 return 0;
3190 }
3191
3192 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'SHIPMENT_UNVALIDATE');
3193 }
3194
3200 public function reOpen()
3201 {
3202 global $langs, $user;
3203
3204 $error = 0;
3205
3206 // Protection. This avoid to move stock later when we should not
3207 if ($this->status == self::STATUS_VALIDATED) {
3208 return 0;
3209 }
3210
3211 $this->db->begin();
3212
3213 $oldbilled = $this->billed;
3214
3215 $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut = 1';
3216 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut = '.self::STATUS_CLOSED;
3217
3218 $resql = $this->db->query($sql);
3219 if ($resql && $this->db->affected_rows($resql) <= 0) {
3220 // The shipment is not closed (draft or canceled), so no stock must be moved
3221 $this->db->rollback();
3222 $langs->load("sendings");
3223 $this->error = $langs->trans("StatusOfRefMustBe", $this->ref, $langs->transnoentitiesnoconv("StatusSendingProcessedShort"));
3224 $this->errors[] = $this->error;
3225 return -1;
3226 }
3227 if ($resql) {
3228 $this->statut = self::STATUS_VALIDATED;
3230 $this->billed = 0;
3231
3232 // If stock increment is done on closing
3233 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
3234 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3235
3236 $langs->load("agenda");
3237
3238 // Loop on each product line to add a stock movement
3239 // Lines are selected like in manageStockMvtOnEvt(), so reopening restores exactly what closing removed,
3240 // including lines with no source order line (standalone shipment, SHIPMENT_STANDALONE)
3241 $sql = "SELECT ed.fk_product, cd.subprice,";
3242 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
3243 $sql .= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
3244 $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed";
3245 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commandedet as cd ON cd.rowid = ed.fk_elementdet";
3246 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
3247 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
3248
3249 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
3250 $resql = $this->db->query($sql);
3251 if ($resql) {
3252 $cpt = $this->db->num_rows($resql);
3253 for ($i = 0; $i < $cpt; $i++) {
3254 $obj = $this->db->fetch_object($resql);
3255 if (empty($obj->edbrowid)) {
3256 $qty = $obj->qty;
3257 } else {
3258 $qty = $obj->edbqty;
3259 }
3260 if ($qty <= 0) {
3261 continue;
3262 }
3263 dol_syslog(get_class($this)."::reopen expedition movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
3264
3265 //var_dump($this->lines[$i]);
3266 $mouvS = new MouvementStock($this->db);
3267 $mouvS->origin = &$this;
3268 $mouvS->setOrigin($this->element, $this->id);
3269
3270 if (empty($obj->edbrowid)) {
3271 // line without batch detail
3272
3273 // 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
3274 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr", $this->ref));
3275 if ($result < 0) {
3276 $this->setErrorsFromObject($mouvS);
3277 $error++;
3278 break;
3279 }
3280 } else {
3281 // line with batch detail
3282
3283 // 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
3284 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr", $this->ref), '', '', '', $obj->batch, $obj->fk_origin_stock); // Dates are not given: those of the lot are used (the copy on the line may be outdated)
3285 if ($result < 0) {
3286 $this->setErrorsFromObject($mouvS);
3287 $error++;
3288 break;
3289 }
3290 }
3291 }
3292 } else {
3293 $this->error = $this->db->lasterror();
3294 $error++;
3295 }
3296 }
3297
3298 if (!$error) {
3299 // Call trigger
3300 $result = $this->call_trigger('SHIPPING_REOPEN', $user);
3301 if ($result < 0) {
3302 $error++;
3303 }
3304 }
3305 } else {
3306 $error++;
3307 $this->errors[] = $this->db->lasterror();
3308 }
3309
3310 if (!$error) {
3311 $this->db->commit();
3312 return 1;
3313 } else {
3314 $this->statut = self::STATUS_CLOSED;
3315 $this->status = self::STATUS_CLOSED;
3316 $this->billed = $oldbilled;
3317 $this->db->rollback();
3318 return -1;
3319 }
3320 }
3321
3333 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3334 {
3335 $outputlangs->load("products");
3336
3337 if (!dol_strlen($modele)) {
3338 $modele = 'rouget';
3339
3340 if (!empty($this->model_pdf)) {
3341 $modele = $this->model_pdf;
3342 } elseif (getDolGlobalString('EXPEDITION_ADDON_PDF')) {
3343 $modele = getDolGlobalString('EXPEDITION_ADDON_PDF');
3344 }
3345 }
3346
3347 $modelpath = "core/modules/expedition/doc/";
3348
3349 $this->fetch_origin();
3350
3351 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3352 }
3353
3362 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3363 {
3364 $tables = array(
3365 'expedition'
3366 );
3367
3368 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3369 }
3370}
$object ref
Definition info.php:90
Class to manage customers orders.
const STATUS_SHIPMENTONPROCESS
Shipment on process.
const STATUS_VALIDATED
Validated status.
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...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
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)
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
errorsToString()
Method to output saved errors.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty 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.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage receptions.
Class to manage Dolibarr database access.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1)
Return clickable link of object (with eventually picto)
addline_batch($dbatch, $array_options=[], $origin_line=null)
Add a shipment line with batch record.
create_delivery($user)
Create a delivery receipt from a shipment.
setDraft($user, $notrigger=0)
Set draft status.
const STATUS_SHIPMENT_IN_PROGRESS
Expedition in progress -> package exit the warehouse and is now in the truck or into the hand of the ...
getUrlTrackingStatus($value='')
Forge an set tracking url.
setClosed()
Classify the shipping as closed (this records also the stock movement)
__construct($db)
Constructor.
create_line($entrepot_id, $origin_line_id, $qty, $rang=0, $array_options=[], $parent_line_id=0, $product_id=0)
Create a expedition line.
fetch_lines()
Load lines.
addline($entrepot_id, $id, $qty, $array_options=[], $fk_product=0, $fk_parent=0)
Add an expedition line.
create($user, $notrigger=0)
Create expedition en base.
LibStatut($status, $mode)
Return label of a status.
setBilled()
Classify the shipping as invoiced (used for example by trigger when WORKFLOW_SHIPPING_CLASSIFY_BILLED...
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
getTooltipContentArray($params)
getTooltipContentArray
addlinefree($qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $array_options=[])
Add a simple expedition line.
setDeliveryDate($user, $delivery_date)
Set the planned delivery date.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
setShippingDate($user, $shipping_date)
Set the shipping date.
const STATUS_DRAFT
Draft status.
line_ajaxorder($rows)
Override to keep every expeditiondet row that belongs to the displayed line in sync when drag & drop ...
const STATUS_CANCELED
Canceled status.
getLibStatut($mode=0)
Return status label.
set_date_livraison($user, $delivery_date)
Set delivery date.
initAsSpecimen()
Initialise an instance with random values.
updatelinefree($rowid, $qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $notrigger, $array_options=array())
Update a simple expedition line.
const STATUS_CLOSED
Closed status -> parcel was received by customer / end of process prev status : validated or shipment...
const STATUS_VALIDATED
Validated status -> parcel is ready to be sent prev status : draft next status : closed or shipment_i...
create_line_batch($line_ext, $array_options=[])
Create the detail of the expedition line.
manageStockMvtOnEvt($user, $labelmovement='ShipmentClassifyClosedInDolibarr')
Manage Stock MVt onb Close or valid Shipment.
valid($user, $notrigger=0)
Validate object and update stock if option enabled.
update($user=null, $notrigger=0)
Update database.
fetch_lines_free()
Load lines of simple shipment.
fetch_delivery_methods()
Fetch deliveries method and return an array.
fetch($id, $ref='', $ref_ext='', $notused='')
Get object and lines from database.
reOpen()
Classify the shipping as validated/opened.
deleteLine($user, $lineid)
Delete detail line.
getLinesArray()
Create an array of shipment lines.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
list_delivery_methods($id=0)
Fetch all deliveries method and return an array.
Class to manage lines of shipment.
CRUD class for batch number management within shipment.
Class to manage stock movements.
Class to manage order lines.
Class to manage products or services.
const TYPE_SERVICE
Service.
Manage record for batch number management.
Class to manage third parties objects (customers, suppliers, prospects...)
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
getLibSignedStatus(int $mode=0)
Returns the label for signed status.
global $mysoc
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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:64
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
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)
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_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
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.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
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:141