dolibarr 25.0.0-alpha
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-2026 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-2026 Nick Fragoulis
19 * Copyright (C) 2026 Pierre Ardoin <developpeur@lesmetiersdubatiment.fr>
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 3 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <https://www.gnu.org/licenses/>.
33 */
34
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42require_once DOL_DOCUMENT_ROOT."/expedition/class/expeditionligne.class.php";
43require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
44if (isModEnabled("propal")) {
45 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
46}
47if (isModEnabled('order')) {
48 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
49}
50require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionlinebatch.class.php';
51require_once DOL_DOCUMENT_ROOT.'/core/class/commonsignedobject.class.php';
52require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
53
60{
61 use CommonIncoterm;
62 use CommonSignedObject;
63 use CommonSubtotal;
64
68 public $element = "shipping";
69
73 public $fk_element = "fk_expedition";
74
78 public $table_element = "expedition";
79
83 public $table_element_line = "expeditiondet";
84
88 public $class_element_line = 'ExpeditionLigne';
89
93 public $picto = 'dolly';
94
95
99 public $fields = array();
100
105 public $user_author_id;
106
111 public $fk_user_author;
112
117 public $fk_user_valid;
118
122 public $socid;
123
129 public $ref_client;
130
134 public $ref_customer;
135
139 public $entrepot_id;
140
144 public $tracking_number;
145
149 public $tracking_url;
153 public $billed = 0;
154
158 public $trueWeight;
162 public $weight_units;
166 public $trueWidth;
170 public $width_units;
174 public $trueHeight;
178 public $height_units;
182 public $trueDepth;
186 public $depth_units;
190 public $trueSize;
191
195 public $livraison_id;
196
200 public $multicurrency_subprice;
201
205 public $size_units;
206
210 public $sizeH;
211
215 public $sizeS;
216
220 public $sizeW;
221
225 public $weight;
226
230 public $date_delivery;
231
237 public $date;
238
244 public $date_expedition;
245
250 public $date_shipping;
251
255 public $date_valid;
256
260 public $meths;
264 public $listmeths; // List of carriers
265
269 public $commande_id;
270
274 public $commande;
275
279 public $lines = array();
280
281 // Multicurrency
285 public $fk_multicurrency;
286
290 public $multicurrency_code;
294 public $multicurrency_tx;
298 public $multicurrency_total_ht;
302 public $multicurrency_total_tva;
306 public $multicurrency_total_ttc;
307
311 const STATUS_DRAFT = 0;
312
320
329
335 const STATUS_CLOSED = 2;
336
340 const STATUS_CANCELED = -1;
341
347 public function __construct($db)
348 {
349 $this->db = $db;
350
351 $this->ismultientitymanaged = 1;
352 $this->isextrafieldmanaged = 1;
353
354 // List of long language codes for status
355 $this->labelStatus = array();
356 $this->labelStatus[-1] = 'StatusSendingCanceled';
357 $this->labelStatus[0] = 'StatusSendingDraft';
358 $this->labelStatus[1] = 'StatusSendingValidated';
359 $this->labelStatus[2] = 'StatusSendingProcessed';
360
361 // List of short language codes for status
362 $this->labelStatusShort = array();
363 $this->labelStatusShort[-1] = 'StatusSendingCanceledShort';
364 $this->labelStatusShort[0] = 'StatusSendingDraftShort';
365 $this->labelStatusShort[1] = 'StatusSendingValidatedShort';
366 $this->labelStatusShort[2] = 'StatusSendingProcessedShort';
367 }
368
375 public function getNextNumRef($soc)
376 {
377 global $langs, $conf;
378 $langs->load("sendings");
379
380 if (getDolGlobalString('EXPEDITION_ADDON_NUMBER')) {
381 $mybool = false;
382
383 $file = getDolGlobalString('EXPEDITION_ADDON_NUMBER') . ".php";
384 $classname = getDolGlobalString('EXPEDITION_ADDON_NUMBER');
385
386 // Include file with class
387 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
388
389 foreach ($dirmodels as $reldir) {
390 $dir = dol_buildpath($reldir."core/modules/expedition/");
391
392 // Load file with numbering class (if found)
393 $mybool = ((bool) @include_once $dir.$file) || $mybool;
394 }
395
396 if (!$mybool) {
397 dol_print_error(null, "Failed to include file ".$file);
398 return '';
399 }
400
401 $obj = new $classname();
402 '@phan-var-force ModelNumRefExpedition $obj';
404 $numref = $obj->getNextValue($soc, $this);
405
406 if ($numref != "") {
407 return $numref;
408 } else {
409 dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error);
410 return "";
411 }
412 } else {
413 print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined");
414 return "";
415 }
416 }
417
425 public function create($user, $notrigger = 0)
426 {
427 $now = dol_now();
428
429 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
430 $error = 0;
431
432 // Clean parameters
433 $this->tracking_number = dol_sanitizeFileName((string) $this->tracking_number);
434 $this->tracking_number = preg_replace('/\s+/', '', $this->tracking_number);
435
436 if (empty($this->fk_project)) {
437 $this->fk_project = 0;
438 }
439 if (empty($this->date_creation)) {
440 $this->date_creation = $now;
441 }
442 if (empty($this->date_shipping) && !empty($this->date_expedition)) {
443 $this->date_shipping = $this->date_expedition;
444 }
445 $this->entity = setEntity($this);
446
447 $this->user = $user;
448
449 $this->db->begin();
450
451 $sql = "INSERT INTO ".MAIN_DB_PREFIX."expedition (";
452 $sql .= "ref";
453 $sql .= ", entity";
454 $sql .= ", ref_customer";
455 $sql .= ", ref_ext";
456 $sql .= ", date_creation";
457 $sql .= ", fk_user_author";
458 $sql .= ", date_expedition";
459 $sql .= ", date_delivery";
460 $sql .= ", fk_soc";
461 $sql .= ", fk_projet";
462 $sql .= ", fk_address";
463 $sql .= ", fk_shipping_method";
464 $sql .= ", tracking_number";
465 $sql .= ", weight";
466 $sql .= ", size";
467 $sql .= ", width";
468 $sql .= ", height";
469 $sql .= ", weight_units";
470 $sql .= ", size_units";
471 $sql .= ", note_private";
472 $sql .= ", note_public";
473 $sql .= ", model_pdf";
474 $sql .= ", fk_incoterms, location_incoterms";
475 $sql .= ", signed_status";
476 $sql .= ", billed";
477 $sql .= ") VALUES (";
478 $sql .= "'(PROV)'";
479 $sql .= ", ".((int) $this->entity);
480 $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : "null");
481 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
482 $sql .= ", '".$this->db->idate($this->date_creation)."'";
483 $sql .= ", ".((int) $user->id);
484 $sql .= ", ".($this->date_shipping > 0 ? "'".$this->db->idate($this->date_shipping)."'" : "null");
485 $sql .= ", ".($this->date_delivery > 0 ? "'".$this->db->idate($this->date_delivery)."'" : "null");
486 $sql .= ", ".($this->socid > 0 ? ((int) $this->socid) : "null");
487 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
488 $sql .= ", ".($this->fk_delivery_address > 0 ? ((int) $this->fk_delivery_address) : "null");
489 $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : "null");
490 $sql .= ", '".$this->db->escape($this->tracking_number)."'";
491 $sql .= ", ".(is_numeric($this->weight) ? (float) $this->weight : 'NULL');
492 $sql .= ", ".(is_numeric($this->sizeS) ? (float) $this->sizeS : 'NULL'); // TODO Should use this->trueDepth
493 $sql .= ", ".(is_numeric($this->sizeW) ? (float) $this->sizeW : 'NULL'); // TODO Should use this->trueWidth
494 $sql .= ", ".(is_numeric($this->sizeH) ? (float) $this->sizeH : 'NULL'); // TODO Should use this->trueHeight
495 $sql .= ", ".($this->weight_units != '' ? (int) $this->weight_units : 'NULL');
496 $sql .= ", ".($this->size_units != '' ? (int) $this->size_units : 'NULL');
497 $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
498 $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
499 $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
500 $sql .= ", ".((int) $this->fk_incoterms);
501 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
502 $sql .= ", ".((int) $this->signed_status);
503 $sql .= ", ".((int) $this->billed);
504 $sql .= ")";
505
506 dol_syslog(get_class($this)."::create", LOG_DEBUG);
507 $resql = $this->db->query($sql);
508 if ($resql) {
509 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expedition");
510
511 // update ref
512 $initialref = '(PROV'.$this->id.')';
513 if (!empty($this->ref)) {
514 $initialref = $this->ref;
515 }
516
517 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
518 $sql .= " SET ref = '".$this->db->escape($initialref)."'";
519 $sql .= " WHERE rowid = ".((int) $this->id);
520
521 dol_syslog(get_class($this)."::create", LOG_DEBUG);
522 if ($this->db->query($sql)) {
523 $this->ref = $initialref;
524 // Insert of lines
525 $num = count($this->lines);
526 $kits_list = array();
527 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
528 for ($i = 0; $i < $num; $i++) {
529 $objectsrc = new OrderLine($this->db);
530 $objectsrc->fetch($this->lines[$i]->origin_line_id);
531 if ($this->lines[$i]->product_type == "9" && $objectsrc->special_code == SUBTOTALS_SPECIAL_CODE) {
532 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) {
533 $error++;
534 }
535 continue;
536 }
537 if (empty($this->lines[$i]->product_type) || getDolGlobalString('STOCK_SUPPORTS_SERVICES') || getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES')) {
538 // virtual products
539 $line = $this->lines[$i];
540 if ($line->fk_product > 0) {
541 // We group kit lines by the fulfilled order line (fk_elementdet) and not by product id: when a same kit product
542 // is present on several distinct order lines, each order line must keep its own shipment line so the ordered
543 // qty stays consistent with the shipped qty (grouping by product would sum the shipped qty of all lines while
544 // keeping the ordered qty of a single line, resulting in a wrong/negative remaining qty to ship). Several
545 // warehouse pickings of the same order line still share the same fk_elementdet and are grouped together.
546 if (!isset($kits_list[$line->fk_elementdet])) {
547 if (!is_object($line->product)) {
548 $line_product = new Product($this->db);
549 $result = $line_product->fetch($line->fk_product, '', '', '', 1, 1, 1);
550 if ($result <= 0) {
551 $error++;
552 }
553 } else {
554 $line_product = $line->product;
555 }
556
557 // get all children of virtual product
558 $line_product->get_sousproduits_arbo();
559 $prods_arbo = $line_product->get_arbo_each_prod($line->qty);
560 if (count($prods_arbo) > 0) {
561 $kits_list[$line->fk_elementdet] = array(
562 'arbo' => $prods_arbo,
563 'total_qty' => $line->qty,
564 );
565 }
566 } else {
567 $kits_list[$line->fk_elementdet]['total_qty'] += $line->qty;
568 }
569 }
570 }
571 }
572 }
573 $kits_id_cached = array();
574 $sub_kits_id_cached = array();
575 $sub_parents_cached = array();
576 for ($i = 0; $i < $num; $i++) {
577 $line = $this->lines[$i];
578 if (empty($line->product_type) || getDolGlobalString('STOCK_SUPPORTS_SERVICES') || getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES')) {
579 $line_id = 0;
580 if (!isset($kits_id_cached[$line->fk_elementdet])) {
581 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
582 $qty = isset($kits_list[$line->fk_elementdet]) ? $kits_list[$line->fk_elementdet]['total_qty'] : $line->qty;
583 $warehouse_id = (isset($kits_list[$line->fk_elementdet]) && !getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) ? 0 : $line->entrepot_id;
584 $line_id = $this->create_line($warehouse_id, $line->origin_line_id, $qty, $line->rang, $line->array_options, 0, $line->fk_product);
585 if ($line_id <= 0) {
586 $error++;
587 }
588 if (isset($kits_list[$line->fk_elementdet])) {
589 $kits_id_cached[$line->fk_elementdet] = $line_id;
590 }
591 } else { // with batch management
592 if ($this->create_line_batch($line, $line->array_options) <= 0) {
593 $error++;
594 }
595 }
596 } else {
597 $line_id = $kits_id_cached[$line->fk_elementdet];
598 }
599
600 // virtual products
601 if (isset($kits_list[$line->fk_elementdet]) && !getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) {
602 $prods_arbo = $kits_list[$line->fk_elementdet]['arbo'];
603
604 // get all children of virtual product
605 $parent_line_id = $line_id; // parent line created
606 $level_last = 1;
607 $product_child_id = 0;
608 foreach ($prods_arbo as $index => $product_child_arr) {
609 // 'id' => Id product
610 // 'id_parent' => Id parent product
611 // 'ref' => Ref product
612 // 'nb' => Nb of units that compose parent product
613 // 'nb_total' => // Nb of units for all nb of product
614 // 'stock' => Stock
615 // 'stock_alert' => Stock alert
616 // 'label' => Label
617 // 'fullpath' => // Full path label
618 // 'type' =>
619 // 'desiredstock' => Desired stock
620 // 'level' => Level
621 // 'incdec' => Need to be incremented or decremented
622 // 'entity' => Entity
623 $product_child_level = (int) $product_child_arr['level'];
624 $product_child_incdec = !empty($product_child_arr['incdec']);
625
626 // detect new level
627 if ($product_child_level != $level_last) {
628 $parent_line_id = $line_id; // last line id
629 $parent_product_id = $product_child_id; // last line id
630 if (isset($sub_parents_cached[$line->fk_elementdet][$parent_product_id])) {
631 $parent_line_id = $sub_parents_cached[$line->fk_elementdet][$parent_product_id];
632 } else {
633 $sub_parents_cached[$line->fk_elementdet][$parent_product_id] = $parent_line_id;
634 }
635 }
636
637 // determine if it's a kit : check next level
638 $is_kit = false;
639 $next_level = $product_child_level;
640 $next_index = $index + 1;
641 if (isset($prods_arbo[$next_index])) {
642 $next_level = (int) $prods_arbo[$next_index]['level'];
643 }
644 if ($next_level > $product_child_level) {
645 $is_kit = true;
646 }
647
648 // determine quantity of sub-product
649 $product_child_id = (int) $product_child_arr['id'];
650 $product_child_qty = (float) $product_child_arr['nb_total']; // by default
651 $warehouse_id = $line->entrepot_id; // by default
652 if ($is_kit || !$product_child_incdec) {
653 if (!$product_child_incdec) {
654 $product_child_qty = 0;
655 }
656 $warehouse_id = 0; // no warehouse used for a kit or if stock is not managed (empty incdec)
657 }
658
659 // create line for a child of virtual product
660 if (!isset($sub_kits_id_cached[$line->fk_elementdet][$product_child_id]) || $warehouse_id > 0) {
661 $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);
662 if ($line_id <= 0) {
663 $error++;
664 dol_syslog(__METHOD__ . ' : ' . $this->errorsToString(), LOG_ERR);
665 break;
666 }
667
668 // if kit or not manage stock (empty incdec)
669 if (empty($warehouse_id)) {
670 $sub_kits_id_cached[$line->fk_elementdet][$product_child_id] = $line_id;
671 }
672 }
673
674 $level_last = $product_child_level;
675 }
676 }
677 }
678 }
679
680 if (!$error && $this->id && $this->origin_id) {
681 $ret = $this->add_object_linked();
682 if (!$ret) {
683 $error++;
684 }
685 }
686
687 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
688 $originforcontact = $this->origin_type;
689 $originidforcontact = $this->origin_id;
690
691 $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";
692 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
693
694 $resqlcontact = $this->db->query($sqlcontact);
695 if ($resqlcontact) {
696 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
697 $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
698 }
699 } else {
700 dol_print_error($this->db);
701 }
702 }
703
704 // Actions on extra fields
705 if (!$error) {
706 $result = $this->insertExtraFields();
707 if ($result < 0) {
708 $error++;
709 }
710 }
711
712 if (!$error && !$notrigger) {
713 // Call trigger
714 $result = $this->call_trigger('SHIPPING_CREATE', $user);
715 if ($result < 0) {
716 $error++;
717 }
718 // End call triggers
719
720 if (!$error) {
721 $this->db->commit();
722 return $this->id;
723 } else {
724 foreach ($this->errors as $errmsg) {
725 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
726 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
727 }
728 $this->db->rollback();
729 return -1 * $error;
730 }
731 } else {
732 $error++;
733 $this->db->rollback();
734 return -3;
735 }
736 } else {
737 $error++;
738 $this->error = $this->db->lasterror()." - sql=$sql";
739 $this->db->rollback();
740 return -2;
741 }
742 } else {
743 $error++;
744 $this->error = $this->db->error()." - sql=$sql";
745 $this->db->rollback();
746 return -1;
747 }
748 }
749
750 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
763 public function create_line($entrepot_id, $origin_line_id, $qty, $rang = 0, $array_options = [], $parent_line_id = 0, $product_id = 0)
764 {
765 //phpcs:enable
766 global $user;
767
768 $expeditionline = new ExpeditionLigne($this->db);
769 $expeditionline->fk_expedition = $this->id;
770 $expeditionline->entrepot_id = $entrepot_id;
771 $expeditionline->fk_elementdet = $origin_line_id;
772 $expeditionline->element_type = $this->origin;
773 $expeditionline->fk_parent = $parent_line_id;
774 $expeditionline->fk_product = $product_id;
775 $expeditionline->qty = $qty;
776 $expeditionline->rang = $rang;
777 $expeditionline->array_options = $array_options;
778
779 if (!($expeditionline->fk_product > 0)) {
780 $order_line = new OrderLine($this->db);
781 $order_line->fetch($expeditionline->fk_elementdet);
782 $expeditionline->fk_product = $order_line->fk_product;
783 }
784
785 if (($lineId = $expeditionline->insert($user)) < 0) {
786 // insert() reports through errors[], so copying the singular error only lost the message
787 $this->setErrorsFromObject($expeditionline);
788 }
789 return $lineId;
790 }
791
792
793 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
801 public function create_line_batch($line_ext, $array_options = [])
802 {
803 // phpcs:enable
804 $error = 0;
805 $stockLocationQty = array(); // associated array with batch qty in stock location
806
807 $tab = $line_ext->detail_batch;
808 // create stockLocation Qty array
809 foreach ($tab as $detbatch) {
810 if (!empty($detbatch->fk_warehouse)) {
811 if (empty($stockLocationQty[$detbatch->fk_warehouse])) {
812 $stockLocationQty[$detbatch->fk_warehouse] = 0;
813 }
814 $stockLocationQty[$detbatch->fk_warehouse] += $detbatch->qty;
815 }
816 }
817 // create shipment lines
818 foreach ($stockLocationQty as $stockLocation => $qty) {
819 $line_id = $this->create_line($stockLocation, $line_ext->origin_line_id, $qty, $line_ext->rang, $array_options);
820 if ($line_id < 0) {
821 $error++;
822 } else {
823 // create shipment batch lines for stockLocation
824 foreach ($tab as $detbatch) {
825 if ($detbatch->fk_warehouse == $stockLocation) {
826 if (!($detbatch->create($line_id) > 0)) { // Create an ExpeditionLineBatch
827 $this->errors = $detbatch->errors;
828 $error++;
829 }
830 }
831 }
832 }
833 }
834
835 if (!$error) {
836 return 1;
837 } else {
838 return -1;
839 }
840 }
841
851 public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
852 {
853 global $conf;
854
855 // Check parameters
856 if (empty($id) && empty($ref) && empty($ref_ext)) {
857 return -1;
858 }
859
860 $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";
861 $sql .= ", e.date_valid, e.fk_user_valid";
862 $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
863 $sql .= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery";
864 $sql .= ", e.fk_shipping_method, e.tracking_number";
865 $sql .= ", e.note_private, e.note_public";
866 $sql .= ', e.fk_incoterms, e.location_incoterms';
867 $sql .= ', e.signed_status';
868 $sql .= ', i.libelle as label_incoterms';
869 $sql .= ', s.libelle as shipping_method';
870 $sql .= ", el.fk_source as origin_id, el.sourcetype as origin_type";
871 $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e";
872 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
873 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
874 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_shipment_mode as s ON e.fk_shipping_method = s.rowid';
875 $sql .= " WHERE e.entity IN (".getEntity('expedition').")";
876 if ($id) {
877 $sql .= " AND e.rowid = ".((int) $id);
878 }
879 if ($ref) {
880 $sql .= " AND e.ref='".$this->db->escape($ref)."'";
881 }
882 if ($ref_ext) {
883 $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'";
884 }
885
886 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
887 $result = $this->db->query($sql);
888 if ($result) {
889 if ($this->db->num_rows($result)) {
890 $obj = $this->db->fetch_object($result);
891
892 $this->id = (int) $obj->rowid;
893 $this->entity = $obj->entity;
894 $this->ref = $obj->ref;
895 $this->socid = $obj->socid;
896 $this->ref_customer = $obj->ref_customer;
897 $this->ref_ext = $obj->ref_ext;
898 $this->status = $obj->fk_statut;
899 $this->statut = $this->status; // Deprecated
900 $this->signed_status = $obj->signed_status;
901 $this->user_author_id = $obj->fk_user_author;
902 $this->fk_user_author = $obj->fk_user_author;
903 $this->user_creation_id = $obj->fk_user_author;
904 $this->fk_user_valid = $obj->fk_user_valid;
905 $this->date_creation = $this->db->jdate($obj->date_creation);
906 $this->date_valid = $this->db->jdate($obj->date_valid);
907 $this->date = $this->db->jdate($obj->date_expedition); // TODO deprecated
908 $this->date_expedition = $this->db->jdate($obj->date_expedition); // TODO deprecated
909 $this->date_shipping = $this->db->jdate($obj->date_expedition); // Date real
910 $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planned
911 $this->fk_delivery_address = $obj->fk_address;
912 $this->model_pdf = $obj->model_pdf;
913 $this->shipping_method_id = $obj->fk_shipping_method;
914 $this->shipping_method = $obj->shipping_method;
915 $this->tracking_number = $obj->tracking_number;
916 $this->origin = ($obj->origin_type ? $obj->origin_type : 'commande'); // For compatibility
917 $this->origin_type = ($obj->origin_type ? $obj->origin_type : 'commande');
918 $this->origin_id = $obj->origin_id;
919 $this->billed = $obj->billed;
920 $this->fk_project = $obj->fk_project;
921 $this->signed_status = $obj->signed_status;
922 $this->trueWeight = $obj->weight;
923 $this->weight_units = $obj->weight_units;
924
925 $this->trueWidth = $obj->width;
926 $this->width_units = $obj->size_units;
927 $this->trueHeight = $obj->height;
928 $this->height_units = $obj->size_units;
929 $this->trueDepth = $obj->size;
930 $this->depth_units = $obj->size_units;
931
932 $this->note_public = $obj->note_public;
933 $this->note_private = $obj->note_private;
934
935 // A denormalized value
936 $this->trueSize = $obj->size."x".$obj->width."x".$obj->height;
937 $this->size_units = $obj->size_units;
938
939 //Incoterms
940 $this->fk_incoterms = $obj->fk_incoterms;
941 $this->location_incoterms = $obj->location_incoterms;
942 $this->label_incoterms = $obj->label_incoterms;
943
944 $this->db->free($result);
945
946 // Tracking url
947 $this->getUrlTrackingStatus($obj->tracking_number);
948
949 // Thirdparty
950 $result = $this->fetch_thirdparty(); // TODO Remove this
951
952 // Retrieve extrafields
953 $this->fetch_optionals();
954
955 // Fix Get multicurrency param for transmitted
956 if (isModEnabled('multicurrency')) {
957 if (!empty($this->multicurrency_code)) {
958 $this->multicurrency_code = $this->thirdparty->multicurrency_code;
959 }
960 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($this->thirdparty->multicurrency_tx)) {
961 $this->multicurrency_tx = $this->thirdparty->multicurrency_tx;
962 }
963 }
964
965 /*
966 * Lines
967 */
968 if (empty($obj->origin_id)) {
969 $result = $this->fetch_lines_free();
970 } else {
971 $result = $this->fetch_lines();
972 }
973 if ($result < 0) {
974 return -3;
975 }
976
977 return 1;
978 } else {
979 dol_syslog(get_class($this).'::Fetch no expedition found', LOG_ERR);
980 $this->error = 'Shipment with id '.$id.' not found';
981 return 0;
982 }
983 } else {
984 $this->error = $this->db->error();
985 return -1;
986 }
987 }
988
996 public function valid($user, $notrigger = 0)
997 {
998 global $conf;
999
1000 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1001
1002 dol_syslog(get_class($this)."::valid");
1003
1004 // Protection
1005 if ($this->status) {
1006 dol_syslog(get_class($this)."::valid not in draft status", LOG_WARNING);
1007 return 0;
1008 }
1009
1010 if (!isset($this->socid)) {
1011 dol_syslog(get_class($this)."::can't valid socid not set", LOG_WARNING);
1012 return 0;
1013 }
1014
1015 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'creer'))
1016 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'shipping_advance', 'validate')))) {
1017 $this->error = 'Permission denied';
1018 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1019 return -1;
1020 }
1021
1022 $this->db->begin();
1023
1024 $error = 0;
1025
1026 // Define new ref
1027 $soc = new Societe($this->db);
1028 $soc->fetch($this->socid);
1029
1030 // Class of company linked to order
1031 $result = $soc->setAsCustomer();
1032
1033 // Define new ref
1034 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1035 $numref = $this->getNextNumRef($soc);
1036 } elseif (!empty($this->ref)) {
1037 $numref = (string) $this->ref;
1038 } else {
1039 $numref = "EXP".$this->id;
1040 }
1041 $this->newref = dol_sanitizeFileName($numref);
1042
1043 $now = dol_now();
1044
1045 // Validate
1046 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
1047 $sql .= " ref = '".$this->db->escape($numref)."'";
1048 $sql .= ", fk_statut = 1";
1049 $sql .= ", date_valid = '".$this->db->idate($now)."'";
1050 $sql .= ", fk_user_valid = ".((int) $user->id);
1051 $sql .= " WHERE rowid = ".((int) $this->id);
1052
1053 dol_syslog(get_class($this)."::valid update expedition", LOG_DEBUG);
1054 $resql = $this->db->query($sql);
1055 if (!$resql) {
1056 $this->error = $this->db->lasterror();
1057 $error++;
1058 }
1059
1060 // If stock increment is done on sending (recommended choice)
1061 if (!$error && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT')) {
1062 $result = $this->manageStockMvtOnEvt($user, "ShipmentValidatedInDolibarr");
1063 if ($result < 0) {
1064 $error++;
1065 }
1066 }
1067
1068 // Change status of order to "shipment in process"
1069 if (!$error && $this->origin_id > 0) {
1070 $origintype = ($this->origin_type ? $this->origin_type : $this->origin);
1071 if ($origintype == 'order') {
1072 $origintype = 'commande'; // Like into add_object_linked()
1073 }
1074 if ($origintype == 'commande') {
1075 // Because when the trigger is fired the object is a shipping and not the real target object, so we add a prefix like SHIPPING_ to avoid confusion
1076 $triggerKey = 'SHIPPING_ORDER_SHIPMENTONPROCESS';
1077
1078 // TODO : load the origin object to trigger the right setStatus according to origin object
1079 $ret = $this->setStatut(Commande::STATUS_SHIPMENTONPROCESS, $this->origin_id, $origintype, $triggerKey);
1080 if (!$ret) {
1081 $error++;
1082 }
1083 }
1084 }
1085
1086 if (!$error && !$notrigger) {
1087 // Call trigger
1088 $result = $this->call_trigger('SHIPPING_VALIDATE', $user);
1089 if ($result < 0) {
1090 $error++;
1091 }
1092 // End call triggers
1093 }
1094
1095 if (!$error) {
1096 $this->oldref = $this->ref;
1097
1098 // Rename directory if dir was a temporary ref
1099 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1100 // Now we rename also files into index
1101 $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)."'";
1102 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/sending/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1103 $resql = $this->db->query($sql);
1104 if (!$resql) {
1105 $error++;
1106 $this->error = $this->db->lasterror();
1107 }
1108 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'expedition/sending/".$this->db->escape($this->newref)."'";
1109 $sql .= " WHERE filepath = 'expedition/sending/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1110 $resql = $this->db->query($sql);
1111 if (!$resql) {
1112 $error++;
1113 $this->error = $this->db->lasterror();
1114 }
1115
1116 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1117 $oldref = dol_sanitizeFileName($this->ref);
1118 $newref = dol_sanitizeFileName($numref);
1119 $dirsource = $conf->expedition->dir_output.'/sending/'.$oldref;
1120 $dirdest = $conf->expedition->dir_output.'/sending/'.$newref;
1121 if (!$error && file_exists($dirsource)) {
1122 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
1123
1124 if (@rename($dirsource, $dirdest)) {
1125 dol_syslog("Rename ok");
1126 // Rename docs starting with $oldref with $newref
1127 $listoffiles = dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1128 foreach ($listoffiles as $fileentry) {
1129 $dirsource = $fileentry['name'];
1130 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1131 $dirsource = $fileentry['path'].'/'.$dirsource;
1132 $dirdest = $fileentry['path'].'/'.$dirdest;
1133 @rename($dirsource, $dirdest);
1134 }
1135 }
1136 }
1137 }
1138 }
1139
1140 // Set new ref and current status
1141 if (!$error) {
1142 $this->ref = $numref;
1143 $this->statut = self::STATUS_VALIDATED;
1145 }
1146
1147 if (!$error) {
1148 $this->db->commit();
1149 return 1;
1150 } else {
1151 $this->db->rollback();
1152 return -1 * $error;
1153 }
1154 }
1155
1156 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1163 public function line_ajaxorder($rows)
1164 {
1165 if (empty($rows) || !is_array($rows)) {
1166 return;
1167 }
1168
1169 $rowToOrigin = array();
1170 $originToRows = array();
1171
1172 $sql = "SELECT rowid, fk_elementdet";
1173 $sql .= " FROM ".$this->db->prefix()."expeditiondet";
1174 $sql .= " WHERE fk_expedition = ".((int) $this->id);
1175 $sql .= " ORDER BY rang ASC, rowid ASC";
1176
1177 $resql = $this->db->query($sql);
1178 if ($resql) {
1179 while ($obj = $this->db->fetch_object($resql)) {
1180 $rowid = (int) $obj->rowid;
1181 $originLine = (int) $obj->fk_elementdet;
1182 $rowToOrigin[$rowid] = $originLine;
1183
1184 if (!isset($originToRows[$originLine])) {
1185 $originToRows[$originLine] = array();
1186 }
1187 $originToRows[$originLine][] = $rowid;
1188 }
1189 $this->db->free($resql);
1190 } else {
1191 parent::line_ajaxorder($rows);
1192 return;
1193 }
1194
1195 $processedOrigins = array();
1196 $position = 1;
1197
1198 foreach ($rows as $rowid) {
1199 $rowid = (int) $rowid;
1200 if (empty($rowid)) {
1201 continue;
1202 }
1203
1204 $originLine = isset($rowToOrigin[$rowid]) ? $rowToOrigin[$rowid] : 0;
1205 if ($originLine > 0 && !empty($processedOrigins[$originLine])) {
1206 continue;
1207 }
1208
1209 $rowidsToUpdate = array($rowid);
1210 if ($originLine > 0 && !empty($originToRows[$originLine])) {
1211 $rowidsToUpdate = $originToRows[$originLine];
1212 $processedOrigins[$originLine] = 1;
1213 }
1214
1215 foreach ($rowidsToUpdate as $childRowId) {
1216 $this->updateRangOfLine($childRowId, $position);
1217 $position++;
1218 }
1219 }
1220 }
1221 // phpcs:enable
1222
1223 // phpcs:disable
1230 public function create_delivery($user)
1231 {
1232 // phpcs:enable
1233 if (getDolGlobalInt('MAIN_SUBMODULE_DELIVERY')) {
1234 if ($this->status == self::STATUS_VALIDATED || $this->status == self::STATUS_CLOSED) {
1235 // Expedition validated
1236 include_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php';
1237 $delivery = new Delivery($this->db);
1238 $result = $delivery->create_from_sending($user, $this->id);
1239 if ($result <= 0) {
1240 $this->setErrorsFromObject($delivery);
1241 }
1242 return $result;
1243 }
1244 }
1245
1246 return 0;
1247 }
1248
1260 private function checkLineStockRequirements($fk_product, $fk_entrepot, $qty, $product_type = null, $forbid_batch_product = false, $allowEmptyWarehouse = false)
1261 {
1262 global $langs;
1263
1264 if (!($fk_product > 0)) {
1265 return 1;
1266 }
1267
1268 $warehouseId = (int) $fk_entrepot;
1269
1270 if (!isModEnabled('stock') && !($forbid_batch_product && isModEnabled('productbatch'))) {
1271 return 1;
1272 }
1273
1274 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1275
1276 $product = new Product($this->db);
1277 $result = $product->fetch($fk_product);
1278 if ($result <= 0) {
1279 $this->setErrorsFromObject($product);
1280 return -1;
1281 }
1282
1283 if ($product_type === null) {
1284 $product_type = $product->type;
1285 }
1286
1287 if ($forbid_batch_product && isModEnabled('productbatch') && $product->hasbatch()) {
1288 $langs->load('errors');
1289 $this->error = $langs->trans('ErrorTryToMakeMoveOnProductRequiringBatchData', $product->ref);
1290 $this->errorhidden = 'ErrorTryToMakeMoveOnProductRequiringBatchData';
1291 return -4;
1292 }
1293
1294 if (!isModEnabled('stock')) {
1295 return 1;
1296 }
1297
1298 // An order-independent line may deliberately carry NO warehouse: a sample,
1299 // goods sent out for servicing, or a delivery note issued for e-reporting
1300 // with no stock effect. Empty warehouse = no stock movement, as merged for
1301 // receptions in #39293. Order-based lines keep the requirement.
1302 if (!$allowEmptyWarehouse && !empty($qty) && !($warehouseId > 0) && !getDolGlobalString('STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS') && !(getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES') && $product_type == Product::TYPE_SERVICE) && $product->stockable_product == Product::ENABLED_STOCK) {
1303 $langs->load("errors");
1304 $this->error = $langs->trans("ErrorWarehouseRequiredIntoShipmentLine");
1305 return -1;
1306 }
1307
1308 // No warehouse, by intent: there is nothing to check stock against.
1309 if ($allowEmptyWarehouse && !($warehouseId > 0)) {
1310 return 1;
1311 }
1312
1313 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT') && ($qty > 0 || !getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1314 $productChildrenNb = 0;
1315 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
1316 $productChildrenNb = $product->hasFatherOrChild(1);
1317 }
1318 if ($productChildrenNb > 0) {
1319 $product_stock = null;
1320 $product->loadStockForVirtualProduct('warehouseopen', $qty);
1321 if ($warehouseId > 0) {
1322 if (isset($product->stock_warehouse[$warehouseId])) {
1323 $product_stock = $product->stock_warehouse[$warehouseId]->real;
1324 }
1325 } else {
1326 foreach ($product->stock_warehouse as $componentStockWarehouse) {
1327 if ($product_stock === null) {
1328 $product_stock = $componentStockWarehouse->real;
1329 } else {
1330 $product_stock = min($product_stock, $componentStockWarehouse->real);
1331 }
1332 }
1333 }
1334 if ($product_stock === null) {
1335 $product_stock = 0;
1336 }
1337 } else {
1338 // Check must be done for stock of product into warehouse if $fk_entrepot defined
1339 if ($warehouseId > 0) {
1340 $result = $product->load_stock('warehouseopen');
1341 if ($result < 0) {
1342 $this->setErrorsFromObject($product);
1343 return -1;
1344 }
1345 $product_stock = empty($product->stock_warehouse[$warehouseId]) ? 0 : $product->stock_warehouse[$warehouseId]->real;
1346 } else {
1347 $product_stock = $product->stock_reel;
1348 }
1349 }
1350
1351 if ($product->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1352 $isavirtualproduct = ($productChildrenNb > 0);
1353 // The product is qualified for a check of quantity (must be enough in stock to be added into shipment).
1354 if (
1355 !$isavirtualproduct
1356 || !getDolGlobalInt('PRODUIT_SOUSPRODUITS')
1357 || ($isavirtualproduct && !getDolGlobalInt('STOCK_EXCLUDE_VIRTUAL_PRODUCTS'))
1358 ) {
1359 // If STOCK_EXCLUDE_VIRTUAL_PRODUCTS is set, we do not manage stock for kits/virtual products.
1360 if ($product->stockable_product == Product::ENABLED_STOCK && $product_stock < $qty) {
1361 $langs->load("errors");
1362 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $product->ref);
1363 $this->errorhidden = 'ErrorStockIsNotEnoughToAddProductOnShipment';
1364
1365 return -3;
1366 }
1367 }
1368 }
1369 }
1370
1371 return 1;
1372 }
1373
1388 public function addline($entrepot_id, $id, $qty, $array_options = [], $fk_product = 0, $fk_parent = 0)
1389 {
1390 global $langs;
1391
1392 $num = count($this->lines);
1393 $line = new ExpeditionLigne($this->db);
1394
1395 $line->entrepot_id = $entrepot_id;
1396 $line->origin_line_id = $id;
1397 $line->fk_elementdet = $id;
1398 $line->element_type = 'order';
1399 $line->fk_parent = $fk_parent;
1400 $line->fk_product = $fk_product;
1401 $line->qty = $qty;
1402
1403 $orderline = new OrderLine($this->db);
1404 $orderline->fetch($id);
1405
1406 // Copy the rang of the order line to the expedition line
1407 $line->rang = $orderline->rang;
1408 $line->product_type = $orderline->product_type;
1409 if (!($line->fk_product > 0)) {
1410 $line->fk_product = $orderline->fk_product;
1411 }
1412
1413 if (!empty($orderline->fk_product)) {
1414 $result = $this->checkLineStockRequirements((int) $orderline->fk_product, $entrepot_id, (float) $line->qty, (int) $line->product_type);
1415 if ($result < 0) {
1416 return $result;
1417 }
1418 }
1419
1420 // If product need a batch number, we should not have called this function but addline_batch instead.
1421 // If this happen, we may have a bug in card.php page
1422 if (isModEnabled('productbatch') && !empty($line->fk_product) && !empty($orderline->product_tobatch)) {
1423 $this->error = 'ADDLINE_WAS_CALLED_INSTEAD_OF_ADDLINEBATCH '.$orderline->id.' '.$line->fk_product; //
1424 return -4;
1425 }
1426
1427 // extrafields
1428 if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1429 $line->array_options = $array_options;
1430 }
1431
1432 $this->lines[$num] = $line;
1433
1434 return 1;
1435 }
1436
1451 public function addlinefree($qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $array_options = [], $fk_entrepot = 0)
1452 {
1453 global $mysoc, $langs, $user;
1454
1455 if ($this->status == self::STATUS_DRAFT) {
1456 if (empty($rang)) {
1457 $rang = 0;
1458 }
1459
1460 $qty = (float) price2num($qty);
1461
1462 $result = $this->checkLineStockRequirements((int) $fk_product, $fk_entrepot, (float) $qty, null, true, true);
1463 if ($result < 0) {
1464 return $result;
1465 }
1466
1467 $this->db->begin();
1468
1469 // Rang to use
1470 $ranktouse = $rang;
1471 if ($ranktouse == -1) {
1472 $rangmax = $this->line_max($fk_parent);
1473 $ranktouse = $rangmax + 1;
1474 }
1475
1476 // Insert line
1477 $this->line = new ExpeditionLigne($this->db);
1478 $this->line->fk_expedition = $this->id;
1479 $this->line->element_type = $element_type;
1480 $this->line->fk_product = $fk_product;
1481 $this->line->entrepot_id = (int) $fk_entrepot;
1482 $this->line->fk_entrepot = (int) $fk_entrepot;
1483 $this->line->description = $description;
1484 $this->line->desc = $description;
1485 $this->line->fk_parent = $fk_parent;
1486 $this->line->qty = (float) $qty;
1487 $this->line->fk_unit = $fk_unit;
1488 $this->line->rang = $ranktouse;
1489
1490 if (is_array($array_options) && count($array_options) > 0) {
1491 $this->line->array_options = $array_options;
1492 }
1493
1494 $result = $this->line->insert($user);
1495 if ($result > 0) {
1496 if (!isset($this->context['createfromclone'])) {
1497 if (!empty($fk_parent)) {
1498 $this->line_order(true, 'DESC');
1499 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
1500 $linecount = count($this->lines);
1501 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
1502 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
1503 }
1504 }
1505 $this->lines[] = $this->line;
1506 }
1507
1508 $this->db->commit();
1509 return $this->line->id;
1510 } else {
1511 $this->error = $this->line->error;
1512 dol_syslog(get_class($this)."::addlinefree error=".$this->error, LOG_ERR);
1513 $this->db->rollback();
1514 return -2;
1515 }
1516 } else {
1517 dol_syslog(get_class($this)."::addlinefree status of shipment must be Draft to allow use of ->addlinefree()", LOG_ERR);
1518 return -3;
1519 }
1520 }
1521
1538 public function updatelinefree($rowid, $qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $notrigger, $array_options = array(), $fk_entrepot = -1)
1539 {
1540 global $mysoc, $langs, $user;
1541
1542 if ($this->status == self::STATUS_DRAFT) {
1543 $this->db->begin();
1544
1545 if (empty($qty)) {
1546 $qty = 0;
1547 }
1548 if (empty($rang)) {
1549 $rang = 0;
1550 }
1551
1552 $qty = (float) $qty;
1553 $description = trim($description);
1554
1555 // Fetch current line from the database and then clone the object and set it in $oldline property
1556 $line = new ExpeditionLigne($this->db);
1557
1558 $result = $line->fetch($rowid);
1559 if ($result < 0) {
1560 $this->setErrorsFromObject($line);
1561 $this->db->rollback();
1562 return -1;
1563 }
1564 $result = $line->fetch_optionals();
1565 if ($result < 0) {
1566 $this->setErrorsFromObject($line);
1567 $this->db->rollback();
1568 return -1;
1569 }
1570
1571 // Updating a shipment line does not change its stored product.
1572 $fk_product = (int) $line->fk_product;
1573 if ($fk_entrepot < 0) {
1574 $fk_entrepot = (int) $line->entrepot_id;
1575 }
1576
1577 $result = $this->checkLineStockRequirements((int) $fk_product, $fk_entrepot, (float) $qty, null, true, true);
1578 if ($result < 0) {
1579 $this->db->rollback();
1580 return $result;
1581 }
1582
1583 $staticline = clone $line;
1584
1585 $line->oldline = $staticline;
1586 $this->line = $line;
1587 $this->line->context = $this->context;
1588 $this->line->rang = $rang;
1589 $this->line->fk_expedition = $this->id;
1590 $this->line->element_type = $element_type;
1591 $this->line->fk_product = $fk_product;
1592 $this->line->entrepot_id = (int) $fk_entrepot;
1593 $this->line->fk_entrepot = (int) $fk_entrepot;
1594 $this->line->qty = $qty;
1595 $this->line->fk_unit = $fk_unit;
1596 $this->line->fk_parent = $fk_parent;
1597 $this->line->description = $description;
1598
1599 if (is_array($array_options) && count($array_options) > 0) {
1600 // We replace values in this->line->array_options only for entries defined into $array_options
1601 foreach ($array_options as $key => $value) {
1602 $this->line->array_options[$key] = $array_options[$key];
1603 }
1604 }
1605
1606 $result = $this->line->update($user, $notrigger);
1607 if ($result > 0) {
1608 // Reorder if child line
1609 if (!empty($fk_parent)) {
1610 $this->line_order(true, 'DESC');
1611 }
1612
1613 $this->db->commit();
1614 return $result;
1615 } else {
1616 $this->error = $this->line->error;
1617
1618 $this->db->rollback();
1619 return -1;
1620 }
1621 } else {
1622 $this->error = get_class($this)."::updatelinefree Shipment status makes operation forbidden";
1623 $this->errors = array('ShipmentStatusMakeOperationForbidden');
1624 return -2;
1625 }
1626 }
1627
1628 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1637 public function addline_batch($dbatch, $array_options = [], $origin_line = null)
1638 {
1639 // phpcs:enable
1640 global $langs;
1641
1642 $num = count($this->lines);
1643 $linebatch = null;
1644 if ($dbatch['qty'] > 0 || ($dbatch['qty'] == 0 && getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1645 $line = new ExpeditionLigne($this->db);
1646 $tab = array();
1647 foreach ($dbatch['detail'] as $key => $value) {
1648 if ($value['q'] > 0 || ($value['q'] == 0 && getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1649 // $value['q']=qty to move
1650 // $value['id_batch']=id into llx_product_batch of record to move
1651 //var_dump($value);
1652
1653 $linebatch = new ExpeditionLineBatch($this->db);
1654 $ret = $linebatch->fetchFromStock($value['id_batch']); // load serial, sellby, eatby
1655 if ($ret < 0) {
1656 $this->setErrorsFromObject($linebatch);
1657 return -1;
1658 }
1659 $linebatch->qty = $value['q'];
1660 if ($linebatch->qty == 0 && getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS')) {
1661 $linebatch->batch = null;
1662 }
1663 $tab[] = $linebatch;
1664
1665 if (getDolGlobalString("STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT", '0') && ($linebatch->qty > 0 || !getDolGlobalString('SHIPMENT_GETS_ALL_ORDER_PRODUCTS'))) {
1666 require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
1667 $prod_batch = new Productbatch($this->db);
1668 $prod_batch->fetch($value['id_batch']);
1669
1670 if ($prod_batch->qty < $linebatch->qty) {
1671 $langs->load("errors");
1672 $this->errors[] = $langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product);
1673 dol_syslog(get_class($this)."::addline_batch error=Product ".$prod_batch->batch.": ".$this->errorsToString(), LOG_ERR);
1674 return -1;
1675 }
1676 }
1677 }
1678 }
1679 if (is_object($linebatch)) {
1680 $line->entrepot_id = $linebatch->fk_warehouse;
1681 }
1682 $line->origin_line_id = $dbatch['ix_l']; // deprecated
1683 $line->fk_elementdet = $dbatch['ix_l'];
1684 $line->qty = $dbatch['qty'];
1685 $line->detail_batch = $tab;
1686 if (!($line->rang > 0)) {
1687 $line->rang = $origin_line->rang;
1688 }
1689 if (!($line->fk_product > 0)) {
1690 $line->fk_product = $origin_line->fk_product;
1691 }
1692
1693 // extrafields
1694 if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
1695 $line->array_options = $array_options;
1696 }
1697
1698 //var_dump($line);
1699 $this->lines[$num] = $line;
1700 return 1;
1701 }
1702 return 0;
1703 }
1704
1712 public function update($user = null, $notrigger = 0)
1713 {
1714 global $conf;
1715 $error = 0;
1716
1717 // Clean parameters
1718
1719 if (isset($this->ref)) {
1720 $this->ref = trim($this->ref);
1721 }
1722 if (isset($this->entity)) {
1723 $this->entity = (int) $this->entity;
1724 }
1725 if (isset($this->ref_customer)) {
1726 $this->ref_customer = trim($this->ref_customer);
1727 }
1728 if (isset($this->socid)) {
1729 $this->socid = (int) $this->socid;
1730 }
1731 if (isset($this->fk_user_author)) {
1732 $this->fk_user_author = (int) $this->fk_user_author;
1733 }
1734 if (isset($this->fk_user_valid)) {
1735 $this->fk_user_valid = (int) $this->fk_user_valid;
1736 }
1737 if (isset($this->fk_delivery_address)) {
1738 $this->fk_delivery_address = (int) $this->fk_delivery_address;
1739 }
1740 if (isset($this->shipping_method_id)) {
1741 $this->shipping_method_id = (int) $this->shipping_method_id;
1742 }
1743 if (isset($this->tracking_number)) {
1744 $this->tracking_number = trim($this->tracking_number);
1745 }
1746 if (isset($this->statut)) {
1747 $this->statut = (int) $this->statut;
1748 }
1749 if (isset($this->status)) {
1750 $this->status = (int) $this->status;
1751 }
1752 if (isset($this->trueDepth)) {
1753 $this->trueDepth = trim($this->trueDepth);
1754 }
1755 if (isset($this->trueWidth)) {
1756 $this->trueWidth = trim($this->trueWidth);
1757 }
1758 if (isset($this->trueHeight)) {
1759 $this->trueHeight = trim($this->trueHeight);
1760 }
1761 if (isset($this->size_units)) {
1762 $this->size_units = trim($this->size_units);
1763 }
1764 if (isset($this->weight_units)) {
1765 $this->weight_units = (int) $this->weight_units;
1766 }
1767 if (isset($this->trueWeight)) {
1768 $this->weight = trim((string) $this->trueWeight);
1769 }
1770 if (isset($this->note_private)) {
1771 $this->note_private = trim($this->note_private);
1772 }
1773 if (isset($this->note_public)) {
1774 $this->note_public = trim($this->note_public);
1775 }
1776 if (isset($this->model_pdf)) {
1777 $this->model_pdf = trim($this->model_pdf);
1778 }
1779 if (!empty($this->date_expedition)) {
1780 $this->date_shipping = $this->date_expedition;
1781 }
1782
1783 // Check parameters
1784 // Put here code to add control on parameters values
1785
1786 // Update request
1787 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
1788 $sql .= " ref = ".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1789 $sql .= " ref_ext = ".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1790 $sql .= " ref_customer = ".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1791 $sql .= " fk_soc = ".(isset($this->socid) ? ((int) $this->socid) : "null").",";
1792 $sql .= " date_creation = ".(dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
1793 $sql .= " fk_user_author = ".(isset($this->fk_user_author) ? ((int) $this->fk_user_author) : "null").",";
1794 $sql .= " date_valid = ".(dol_strlen($this->date_valid) != 0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
1795 $sql .= " fk_user_valid = ".(isset($this->fk_user_valid) ? ((int) $this->fk_user_valid) : "null").",";
1796 $sql .= " date_expedition = ".(dol_strlen($this->date_shipping) != 0 ? "'".$this->db->idate($this->date_shipping)."'" : 'null').",";
1797 $sql .= " date_delivery = ".(dol_strlen($this->date_delivery) != 0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
1798 $sql .= " fk_address = ".(isset($this->fk_delivery_address) ? ((int) $this->fk_delivery_address) : "null").",";
1799 $sql .= " fk_shipping_method = ".((isset($this->shipping_method_id) && $this->shipping_method_id > 0) ? ((int) $this->shipping_method_id) : "null").",";
1800 $sql .= " tracking_number = ".(isset($this->tracking_number) ? "'".$this->db->escape($this->tracking_number)."'" : "null").",";
1801 $sql .= " fk_statut = ".(isset($this->status) ? ((int) $this->status) : "null").",";
1802 $sql .= " fk_projet = ".(isset($this->fk_project) ? ((int) $this->fk_project) : "null").",";
1803 $sql .= " height = ".(($this->trueHeight != '') ? ((float) $this->trueHeight) : "null").",";
1804 $sql .= " width = ".(($this->trueWidth != '') ? ((float) $this->trueWidth) : "null").",";
1805 $sql .= " size_units = ".(isset($this->size_units) ? ((int) $this->size_units) : "null").",";
1806 $sql .= " size = ".(($this->trueDepth != '') ? ((float) $this->trueDepth) : "null").",";
1807 $sql .= " weight_units = ".(isset($this->weight_units) ? ((int) $this->weight_units) : "null").",";
1808 $sql .= " weight = ".(($this->trueWeight != '') ? ((float) $this->trueWeight) : "null").",";
1809 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1810 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1811 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1812 $sql .= " entity = ".((int) $conf->entity);
1813 $sql .= " WHERE rowid = ".((int) $this->id);
1814
1815 $this->db->begin();
1816
1817 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1818 $resql = $this->db->query($sql);
1819 if (!$resql) {
1820 $error++;
1821 $this->errors[] = "Error ".$this->db->lasterror();
1822 }
1823
1824 // Actions on extra fields
1825 if (!$error) {
1826 $result = $this->insertExtraFields();
1827 if ($result < 0) {
1828 $error++;
1829 }
1830 }
1831
1832 if (!$error && !$notrigger) {
1833 // Call trigger
1834 $result = $this->call_trigger('SHIPPING_MODIFY', $user);
1835 if ($result < 0) {
1836 $error++;
1837 }
1838 // End call triggers
1839 }
1840
1841 // Commit or rollback
1842 if ($error) {
1843 foreach ($this->errors as $errmsg) {
1844 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1845 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1846 }
1847 $this->db->rollback();
1848 return -1 * $error;
1849 } else {
1850 $this->db->commit();
1851 return 1;
1852 }
1853 }
1854
1855
1864 public function cancel($user, $notrigger = 0, $also_update_stock = false)
1865 {
1866 global $conf, $langs, $user;
1867
1868 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1869
1870 $error = 0;
1871 $this->error = '';
1872
1873 $this->db->begin();
1874
1875 // Add a protection to refuse deleting if shipment has at least one delivery
1876 $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment
1877 if (isset($this->linkedObjectsIds['delivery']) && count($this->linkedObjectsIds['delivery']) > 0) {
1878 $this->error = 'ErrorThereIsSomeDeliveries';
1879 $error++;
1880 }
1881
1882 if (!$error && !$notrigger) {
1883 // Call trigger
1884 $result = $this->call_trigger('SHIPPING_CANCEL', $user);
1885 if ($result < 0) {
1886 $error++;
1887 }
1888 // End call triggers
1889 }
1890
1891 // Stock control
1892 $can_update_stock = isModEnabled('stock') && $also_update_stock &&
1893 ((getDolGlobalInt('STOCK_CALCULATE_ON_SHIPMENT') && $this->status == self::STATUS_VALIDATED) ||
1894 ((getDolGlobalInt('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalInt('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) && $this->status == self::STATUS_CLOSED));
1895 if (!$error) {
1896 require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
1897
1898 $langs->load("agenda");
1899
1900 // Loop on each product line to add a stock movement (contain sub-products)
1901 $sql = "SELECT ";
1902 $sql .= " ed.fk_product";
1903 $sql .= ", ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
1904 $sql .= ", SUM(".$this->db->ifsql("pa.rowid IS NOT NULL", "1", "0").") as iskit";
1905 $sql .= ", ".$this->db->ifsql("pai.incdec IS NULL", "1", "pai.incdec")." as incdec";
1906 $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
1907 $sql .= " LEFT JOIN ".$this->db->prefix()."product_association as pa ON pa.fk_product_pere = ed.fk_product";
1908 $sql .= " LEFT JOIN ".$this->db->prefix()."expeditiondet as edp ON edp.rowid = ed.fk_parent";
1909 $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";
1910 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
1911 $sql .= " GROUP BY ed.fk_product, ed.qty, ed.fk_entrepot, ed.rowid, pai.incdec";
1912 $sql .= $this->db->order("ed.rowid", "DESC");
1913
1914 dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
1915 $resql = $this->db->query($sql);
1916 if ($resql) {
1917 $cpt = $this->db->num_rows($resql);
1918
1919 $shipmentlinebatch = new ExpeditionLineBatch($this->db);
1920
1921 for ($i = 0; $i < $cpt; $i++) {
1922 dol_syslog(get_class($this)."::delete movement index ".$i);
1923 $obj = $this->db->fetch_object($resql);
1924 $line_id = (int) $obj->expeditiondet_id;
1925
1926 if ($can_update_stock && (empty($obj->iskit) || getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) && !empty($obj->incdec)) {
1927 $mouvS = new MouvementStock($this->db);
1928 // we do not log origin because it will be deleted
1929 $mouvS->origin = '';
1930 // get lot/serial
1931 $lotArray = null;
1932 if (isModEnabled('productbatch')) {
1933 $lotArray = $shipmentlinebatch->fetchAll($obj->expeditiondet_id);
1934 if (!is_array($lotArray)) {
1935 $error++;
1936 $this->errors[] = "Error ".$this->db->lasterror();
1937 }
1938 }
1939
1940 if (empty($lotArray)) {
1941 // no lot/serial
1942 // We increment stock of product (and sub-products)
1943 // We use warehouse selected for each line
1944 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->transnoentitiesnoconv("ShipmentCanceledInDolibarr", $this->ref), '', '', '', '', 0, '', 0, (empty($obj->iskit) ? 1 : 0)); // Price is set to 0, because we don't want to see WAP changed
1945 if ($result < 0) {
1946 $error++;
1947 $this->errors = array_merge($this->errors, $mouvS->errors);
1948 break;
1949 }
1950 } else {
1951 // We increment stock of batches
1952 // We use warehouse selected for each line
1953 foreach ($lotArray as $lot) {
1954 if (empty($lot->qty)) {
1955 continue;
1956 }
1957 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->transnoentitiesnoconv("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)
1958 if ($result < 0) {
1959 $error++;
1960 $this->errors = array_merge($this->errors, $mouvS->errors);
1961 break;
1962 }
1963 }
1964 if ($error) {
1965 break; // break for loop in case of error
1966 }
1967 }
1968 }
1969
1970 if (!$error) {
1971 // delete all children and batches of this shipment line
1972 $shipment_line = new ExpeditionLigne($this->db);
1973 $res = $shipment_line->fetch($line_id);
1974 if ($res > 0) {
1975 $result = $shipment_line->delete($user);
1976 if ($result < 0) {
1977 $error++;
1978 $this->errors[] = "Error ".$shipment_line->errorsToString();
1979 }
1980 } else {
1981 $error++;
1982 $this->errors[] = "Error ".$shipment_line->errorsToString();
1983 }
1984 }
1985
1986 if ($error) {
1987 break;
1988 }
1989 }
1990 } else {
1991 $error++;
1992 $this->errors[] = "Error ".$this->db->lasterror();
1993 }
1994 }
1995
1996 // No delete expedition
1997 if (!$error) {
1998 $sql = "SELECT rowid FROM ".$this->db->prefix()."expedition";
1999 $sql .= " WHERE rowid = ".((int) $this->id);
2000
2001 if ($this->db->query($sql)) {
2002 if (!empty($this->origin) && $this->origin_id > 0) {
2003 $this->fetch_origin();
2005 '@phan-var-force Facture|Commande $origin_object';
2007 if ($origin_object->status == Commande::STATUS_SHIPMENTONPROCESS) { // If order source of shipment is "shipment in progress"
2008 // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
2009 $origin_object->loadExpeditions();
2010 if (count($origin_object->expeditions) <= 0) {
2012 }
2013 }
2014 }
2015
2016 $this->db->commit();
2017
2018 // We delete PDFs
2019 $ref = dol_sanitizeFileName($this->ref);
2020 if (!empty($conf->expedition->dir_output)) {
2021 $dir = $conf->expedition->dir_output.'/sending/'.$ref;
2022 $file = $dir.'/'.$ref.'.pdf';
2023 if (file_exists($file)) {
2024 if (!dol_delete_file($file)) {
2025 return 0;
2026 }
2027 }
2028 if (file_exists($dir)) {
2029 if (!dol_delete_dir_recursive($dir)) {
2030 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
2031 return 0;
2032 }
2033 }
2034 }
2035
2036 return 1;
2037 } else {
2038 $this->error = $this->db->lasterror()." - sql=$sql";
2039 $this->db->rollback();
2040 return -3;
2041 }
2042 } else {
2043 $this->db->rollback();
2044 return -2;
2045 }
2046 }
2047
2057 public function delete($user = null, $notrigger = 0, $also_update_stock = false)
2058 {
2059 global $conf, $langs;
2060
2061 if (empty($user)) {
2062 global $user;
2063 }
2064
2065 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2066
2067 $error = 0;
2068 $this->error = '';
2069
2070 $this->db->begin();
2071
2072 // Add a protection to refuse deleting if shipment has at least one delivery
2073 $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment
2074 if (isset($this->linkedObjectsIds['delivery']) && count($this->linkedObjectsIds['delivery']) > 0) {
2075 $this->error = 'ErrorThereIsSomeDeliveries';
2076 $error++;
2077 }
2078
2079 if (!$error && !$notrigger) {
2080 // Call trigger
2081 $result = $this->call_trigger('SHIPPING_DELETE', $user);
2082 if ($result < 0) {
2083 $error++;
2084 }
2085 // End call triggers
2086 }
2087
2088 // Stock control
2089 $can_update_stock = isModEnabled('stock') && $also_update_stock &&
2090 ((getDolGlobalInt('STOCK_CALCULATE_ON_SHIPMENT') && $this->status == self::STATUS_VALIDATED) ||
2091 ((getDolGlobalInt('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalInt('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) && $this->status == self::STATUS_CLOSED));
2092 if (!$error) {
2093 require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
2094
2095 $langs->load("agenda");
2096
2097 // we try deletion of batch line even if module batch not enabled in case of the module were enabled and disabled previously
2098 $shipmentlinebatch = new ExpeditionLineBatch($this->db);
2099
2100 // Loop on each product line to add a stock movement (contain sub-products)
2101 $sql = "SELECT ";
2102 $sql .= " ed.fk_product";
2103 $sql .= ", ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
2104 $sql .= ", SUM(".$this->db->ifsql("pa.rowid IS NOT NULL", "1", "0").") as iskit";
2105 $sql .= ", ".$this->db->ifsql("pai.incdec IS NULL", "1", "pai.incdec")." as incdec";
2106 $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
2107 $sql .= " LEFT JOIN ".$this->db->prefix()."product_association as pa ON pa.fk_product_pere = ed.fk_product";
2108 $sql .= " LEFT JOIN ".$this->db->prefix()."expeditiondet as edp ON edp.rowid = ed.fk_parent";
2109 $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";
2110 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
2111 $sql .= " GROUP BY ed.fk_product, ed.qty, ed.fk_entrepot, ed.rowid, pai.incdec";
2112 $sql .= $this->db->order("ed.rowid", "DESC");
2113
2114 dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
2115 $resql = $this->db->query($sql);
2116 if ($resql) {
2117 $cpt = $this->db->num_rows($resql);
2118 for ($i = 0; $i < $cpt; $i++) {
2119 dol_syslog(get_class($this)."::delete movement index ".$i);
2120 $obj = $this->db->fetch_object($resql);
2121 $line_id = (int) $obj->expeditiondet_id;
2122
2123 if ($can_update_stock && (empty($obj->iskit) || getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE')) && !empty($obj->incdec)) {
2124 $mouvS = new MouvementStock($this->db);
2125 // we do not log origin because it will be deleted
2126 $mouvS->origin = '';
2127 // get lot/serial
2128 $lotArray = $shipmentlinebatch->fetchAll($line_id);
2129 if (!is_array($lotArray)) {
2130 $error++;
2131 $this->errors[] = "Error ".$this->db->lasterror();
2132 }
2133 if (empty($lotArray)) {
2134 // no lot/serial
2135 // We increment stock of product (disable for sub-products : already in shipment lines)
2136 // We use warehouse selected for each line
2137 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->transnoentitiesnoconv("ShipmentDeletedInDolibarr", $this->ref), '', '', '', '', 0, '', 0, (empty($obj->iskit) ? 1 : 0)); // Price is set to 0, because we don't want to see WAP changed
2138 if ($result < 0) {
2139 $error++;
2140 $this->errors = array_merge($this->errors, $mouvS->errors);
2141 break;
2142 }
2143 } else {
2144 // We increment stock of batches
2145 // We use warehouse selected for each line
2146 foreach ($lotArray as $lot) {
2147 if (empty($lot->qty)) {
2148 continue;
2149 }
2150 $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->transnoentitiesnoconv("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)
2151 if ($result < 0) {
2152 $error++;
2153 $this->errors = array_merge($this->errors, $mouvS->errors);
2154 break;
2155 }
2156 }
2157 if ($error) {
2158 break; // break for loop in case of error
2159 }
2160 }
2161 }
2162
2163 if (!$error) {
2164 // delete all children and batches of this shipment line
2165 $shipment_line = new ExpeditionLigne($this->db);
2166 $res = $shipment_line->fetch($line_id);
2167 if ($res > 0) {
2168 $result = $shipment_line->delete($user);
2169 if ($result < 0) {
2170 $error++;
2171 $this->errors[] = "Error ".$shipment_line->errorsToString();
2172 }
2173 } else {
2174 $error++;
2175 $this->errors[] = "Error ".$shipment_line->errorsToString();
2176 }
2177 }
2178
2179 if ($error) {
2180 break;
2181 }
2182 }
2183 } else {
2184 $error++;
2185 $this->errors[] = "Error ".$this->db->lasterror();
2186 }
2187 }
2188
2189 if (!$error) {
2190 // Delete linked object
2191 $res = $this->deleteObjectLinked();
2192 if ($res < 0) {
2193 $error++;
2194 }
2195
2196 // delete extrafields
2197 $res = $this->deleteExtraFields();
2198 if ($res < 0) {
2199 $error++;
2200 }
2201
2202 if (!$error) {
2203 // Delete linked contacts
2204 $res = $this->delete_linked_contact();
2205 if ($res < 0) {
2206 $error++;
2207 }
2208 }
2209 if (!$error) {
2210 $sql = "DELETE FROM ".$this->db->prefix()."expedition";
2211 $sql .= " WHERE rowid = ".((int) $this->id);
2212
2213 if ($this->db->query($sql)) {
2214 if (!empty($this->origin) && $this->origin_id > 0) {
2215 $this->fetch_origin();
2217 '@phan-var-force Facture|Commande $origin_object';
2218 if ($origin_object->status == Commande::STATUS_SHIPMENTONPROCESS) { // If order source of shipment is "shipment in progress"
2219 // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
2220 $origin_object->loadExpeditions();
2221 if (count($origin_object->expeditions) <= 0) {
2223 }
2224 }
2225 }
2226
2227 $this->db->commit();
2228
2229 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2230 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2231 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2232
2233 // We delete PDFs
2234 $ref = dol_sanitizeFileName($this->ref);
2235 if (!empty($conf->expedition->dir_output) && !empty($ref)) {
2236 $dir = $conf->expedition->dir_output . '/sending/' . $ref;
2237 $file = $dir . '/' . $ref . '.pdf';
2238 if (file_exists($file)) {
2239 if (!dol_delete_file($file)) {
2240 return 0;
2241 }
2242 }
2243 if (file_exists($dir)) {
2244 if (!dol_delete_dir_recursive($dir)) {
2245 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
2246 return 0;
2247 }
2248 }
2249 }
2250
2251 return 1;
2252 } else {
2253 $this->error = $this->db->lasterror()." - sql=$sql";
2254 $this->db->rollback();
2255 return -3;
2256 }
2257 } else {
2258 $this->db->rollback();
2259 return -2;
2260 }
2261 } else {
2262 $this->db->rollback();
2263 return -1;
2264 }
2265 }
2266
2267 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2273 public function fetch_lines()
2274 {
2275 // phpcs:enable
2276 global $mysoc;
2277
2278 $this->lines = array();
2279
2280 // NOTE: This fetch_lines is special because it groups all lines with the same origin_line_id into one line.
2281 // TODO: See if we can restore a common fetch_lines (one line = one record)
2282
2283 $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";
2284 $sql .= ", cd.total_ht, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.total_tva";
2285 $sql .= ", cd.fk_remise_except, cd.fk_product_fournisseur_price as fk_fournprice";
2286 $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";
2287 $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";
2288 $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";
2289 $sql .= ", p.ref as product_ref, p.label as product_label, p.fk_product_type, p.barcode as product_barcode";
2290 $sql .= ", p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units";
2291 $sql .= ", p.surface, p.surface_units, p.volume, p.volume_units, p.tosell as product_tosell, p.tobuy as product_tobuy";
2292 $sql .= ", p.tobatch as product_tobatch, p.stockable_product";
2293 $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed, ".MAIN_DB_PREFIX."commandedet as cd";
2294 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = cd.fk_product";
2295 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
2296 $sql .= " AND ed.fk_elementdet = cd.rowid";
2297 $sql .= " ORDER BY CASE WHEN ed.rang IS NULL OR ed.rang = 0 THEN cd.rang ELSE ed.rang END, ed.rowid";
2298
2299 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
2300 $resql = $this->db->query($sql);
2301 if ($resql) {
2302 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2303
2304 $num = $this->db->num_rows($resql);
2305 $i = 0;
2306 $line = new ExpeditionLigne($this->db);
2307 $lineindex = 0;
2308 $originline = 0;
2309
2310 $this->total_ht = 0;
2311 $this->total_tva = 0;
2312 $this->total_ttc = 0;
2313 $this->total_localtax1 = 0;
2314 $this->total_localtax2 = 0;
2315
2316 $this->multicurrency_total_ht = 0;
2317 $this->multicurrency_total_tva = 0;
2318 $this->multicurrency_total_ttc = 0;
2319
2320 $shipmentlinebatch = new ExpeditionLineBatch($this->db);
2321
2322 $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.
2323 while ($i < $num) {
2324 $obj = $this->db->fetch_object($resql);
2325
2326 if ($originline > 0 && $originline == $obj->fk_elementdet) {
2327 // '@phan-var-force ExpeditionLigne $line'; // $line from previous loop
2328 $line->entrepot_id = 0; // entrepod_id in details_entrepot
2329 $line->qty_shipped += $obj->qty_shipped;
2330 } else {
2331 $line = new ExpeditionLigne($this->db); // new group to start
2332 $line->entrepot_id = $obj->fk_entrepot; // this is a property of a shipment line
2333 $line->qty_shipped = $obj->qty_shipped; // this is a property of a shipment line
2334 }
2335
2336 $detail_entrepot = new stdClass();
2337 $detail_entrepot->entrepot_id = $obj->fk_entrepot;
2338 $detail_entrepot->qty_shipped = $obj->qty_shipped;
2339 $detail_entrepot->line_id = $obj->line_id;
2340 $line->details_entrepot[] = $detail_entrepot;
2341
2342 $line->line_id = $obj->line_id; // TODO deprecated
2343 $line->rowid = $obj->line_id; // TODO deprecated
2344 $line->id = $obj->line_id;
2345
2346 $line->fk_origin = 'orderline'; // TODO deprecated, we already have element_type that can be use to guess type of line
2347
2348 $line->fk_element = $obj->fk_element;
2349 $line->origin_id = $obj->fk_element;
2350 $line->fk_elementdet = $obj->fk_elementdet;
2351 $line->origin_line_id = $obj->fk_elementdet;
2352 $line->element_type = $obj->element_type;
2353
2354 $line->fk_expedition = $this->id; // id of parent
2355
2356 $line->stockable_product = $obj->stockable_product;
2357 $line->product_type = $obj->product_type;
2358 $line->fk_product = $obj->fk_product;
2359 $line->fk_product_type = $obj->fk_product_type;
2360 $line->ref = $obj->product_ref; // TODO deprecated
2361 $line->product_ref = $obj->product_ref;
2362 $line->product_label = $obj->product_label;
2363 $line->product_barcode = $obj->product_barcode; // Barcode number product
2364 $line->product_tosell = $obj->product_tosell;
2365 $line->product_tobuy = $obj->product_tobuy;
2366 $line->product_tobatch = $obj->product_tobatch;
2367 $line->fk_fournprice = $obj->fk_fournprice;
2368 $line->label = $obj->custom_label;
2369
2370 $line->description = $obj->description;
2371 $line->desc = $obj->description;
2372
2373 $line->qty_asked = $obj->qty_asked;
2374 $line->rang = $obj->rang;
2375 $line->weight = $obj->weight;
2376 $line->weight_units = $obj->weight_units;
2377 $line->length = $obj->length;
2378 $line->length_units = $obj->length_units;
2379 $line->width = $obj->width;
2380 $line->width_units = $obj->width_units;
2381 $line->height = $obj->height;
2382 $line->height_units = $obj->height_units;
2383 $line->surface = $obj->surface;
2384 $line->surface_units = $obj->surface_units;
2385 $line->volume = $obj->volume;
2386 $line->volume_units = $obj->volume_units;
2387 $line->stockable_product = $obj->stockable_product;
2388 $line->fk_unit = $obj->fk_unit;
2389
2390 $line->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2391
2392 $line->pa_ht = $obj->pa_ht;
2393
2394 // Local taxes
2395 $localtax_array = array(0 => $obj->localtax1_type, 1 => $obj->localtax1_tx, 2 => $obj->localtax2_type, 3 => $obj->localtax2_tx);
2396 $localtax1_tx = get_localtax($obj->tva_tx, 1, $this->thirdparty);
2397 $localtax2_tx = get_localtax($obj->tva_tx, 2, $this->thirdparty);
2398
2399 // For invoicing
2400 $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
2401 $line->desc = $obj->description; // We need ->desc because some code into CommonObject use desc (property defined for other elements)
2402 $line->qty = $line->qty_shipped;
2403 $line->total_ht = (float) $tabprice[0];
2404 $line->total_localtax1 = (float) $tabprice[9];
2405 $line->total_localtax2 = (float) $tabprice[10];
2406 $line->total_ttc = (float) $tabprice[2];
2407 $line->total_tva = (float) $tabprice[1];
2408 $line->vat_src_code = $obj->vat_src_code;
2409 $line->tva_tx = $obj->tva_tx;
2410 $line->localtax1_tx = $obj->localtax1_tx;
2411 $line->localtax2_tx = $obj->localtax2_tx;
2412 $line->info_bits = $obj->info_bits;
2413 $line->price = $obj->price;
2414 $line->subprice = $obj->subprice;
2415 $line->fk_remise_except = $obj->fk_remise_except;
2416 $line->remise_percent = $obj->remise_percent;
2417
2418 $this->total_ht += $tabprice[0];
2419 $this->total_tva += $tabprice[1];
2420 $this->total_ttc += $tabprice[2];
2421 $this->total_localtax1 += $tabprice[9];
2422 $this->total_localtax2 += $tabprice[10];
2423
2424 $line->date_start = $this->db->jdate($obj->date_start);
2425 $line->date_end = $this->db->jdate($obj->date_end);
2426
2427 $line->special_code = $obj->special_code;
2428
2429 // Multicurrency
2430 $this->fk_multicurrency = $obj->fk_multicurrency;
2431 $this->multicurrency_code = $obj->multicurrency_code;
2432 $line->multicurrency_subprice = $obj->multicurrency_subprice;
2433 $line->multicurrency_total_ht = $obj->multicurrency_total_ht;
2434 $line->multicurrency_total_tva = $obj->multicurrency_total_tva;
2435 $line->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2436
2437 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
2438 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
2439 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
2440
2441 // Detail of batch
2442 if (isModEnabled('productbatch') && $obj->line_id > 0 && $obj->product_tobatch > 0) {
2443 if ($originline != $obj->fk_elementdet) {
2444 $line->detail_batch = array();
2445 }
2446 $newdetailbatch = $shipmentlinebatch->fetchAll($obj->line_id, $obj->fk_product);
2447
2448 if (is_array($newdetailbatch)) {
2449 if ($originline != $obj->fk_elementdet) {
2450 $line->detail_batch = $newdetailbatch;
2451 } else {
2452 $line->detail_batch = array_merge($line->detail_batch, $newdetailbatch);
2453 }
2454 }
2455 }
2456
2457 // virtual product : find all children stock (group by product id and warehouse id)
2458 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
2459 $detail_children = array(); // detail by product : array of [warehouse_id => total_qty]
2460 $line_child_list = array();
2461 $res = $line->findAllChild($line->id, $line_child_list, 1);
2462 if ($res > 0) {
2463 foreach ($line_child_list as $child_line) {
2464 foreach ($child_line as $child_obj) {
2465 $child_product_id = (int) $child_obj->fk_product;
2466 $child_warehouse_id = (int) $child_obj->fk_warehouse;
2467
2468 if ($child_warehouse_id > 0) {
2469 // child quantities group by warehouses
2470 if (!isset($detail_children[$child_product_id])) {
2471 $detail_children[$child_product_id] = array();
2472 }
2473 if (!isset($detail_children[$child_product_id][$child_warehouse_id])) {
2474 $detail_children[$child_product_id][$child_warehouse_id] = 0;
2475 }
2476 $detail_children[$child_product_id][$child_warehouse_id] += $child_obj->qty;
2477 }
2478 }
2479 }
2480 }
2481 $line->detail_children = $detail_children;
2482 }
2483
2484 $line->fetch_optionals();
2485
2486 if ($originline != $obj->fk_elementdet) {
2487 $this->lines[$lineindex] = $line;
2488 $lineindex++;
2489 } else {
2490 $line->total_ht += $tabprice[0];
2491 $line->total_localtax1 += $tabprice[9];
2492 $line->total_localtax2 += $tabprice[10];
2493 $line->total_ttc += $tabprice[2];
2494 $line->total_tva += $tabprice[1];
2495 }
2496
2497 $i++;
2498 $originline = $obj->fk_elementdet;
2499 }
2500 $this->db->free($resql);
2501 return 1;
2502 } else {
2503 $this->error = $this->db->error();
2504 return -3;
2505 }
2506 }
2507
2514 public function countStandalone()
2515 {
2516 global $conf;
2517
2518 $sql = "SELECT COUNT(e.rowid) as nb";
2519 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as e";
2520 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
2521 $sql .= " WHERE e.entity = ".((int) $conf->entity);
2522 $sql .= " AND el.rowid IS NULL";
2523
2524 $resql = $this->db->query($sql);
2525 if (!$resql) {
2526 $this->error = $this->db->lasterror();
2527 return -1;
2528 }
2529 $obj = $this->db->fetch_object($resql);
2530 $this->db->free($resql);
2531
2532 return (int) $obj->nb;
2533 }
2534
2535
2536 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2542 public function fetch_lines_free()
2543 {
2544 // phpcs:enable
2545 global $mysoc;
2546
2547 $this->lines = array();
2548
2549 $sql = 'SELECT ed.rowid, ed.fk_expedition, ed.fk_entrepot, ed.fk_product, ed.fk_parent, ed.fk_unit, ed.description, ed.fk_elementdet, ed.fk_element, ed.element_type, ed.qty, ed.rang';
2550 $sql .= ', p.ref as product_ref, p.label as product_label, p.fk_product_type, p.barcode as product_barcode';
2551 $sql .= ', p.weight, p.weight_units, p.volume, p.volume_units';
2552 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as ed';
2553 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = ed.fk_product)';
2554 $sql .= ' WHERE ed.fk_expedition = '.((int) $this->id);
2555 $sql .= ' ORDER BY ed.rang, ed.rowid';
2556
2557 dol_syslog(get_class($this)."::fetch_lines_free", LOG_DEBUG);
2558 $result = $this->db->query($sql);
2559 if ($result) {
2560 $num = $this->db->num_rows($result);
2561
2562 $i = 0;
2563 while ($i < $num) {
2564 $objp = $this->db->fetch_object($result);
2565
2566 $line = new ExpeditionLigne($this->db);
2567
2568 $line->rowid = $objp->rowid;
2569 $line->id = $objp->rowid;
2570 $line->fk_expedition = $this->id;
2571 $line->description = $objp->description;
2572 $line->desc = $objp->description;
2573 $line->qty = $objp->qty;
2574 $line->qty_shipped = $objp->qty; // Same properties as fetch_lines(): read by the PDF models and getTotalWeightVolume()
2575 $line->fk_entrepot = $objp->fk_entrepot;
2576 $line->entrepot_id = $objp->fk_entrepot;
2577 $line->fk_product = $objp->fk_product;
2578 $line->product_type = (int) $objp->fk_product_type;
2579 $line->fk_product_type = $objp->fk_product_type;
2580 $line->product_ref = $objp->product_ref;
2581 $line->product_label = $objp->product_label;
2582 $line->product_barcode = $objp->product_barcode;
2583 $line->weight = $objp->weight;
2584 $line->weight_units = $objp->weight_units;
2585 $line->volume = $objp->volume;
2586 $line->volume_units = $objp->volume_units;
2587 $line->fk_parent = $objp->fk_parent;
2588 $line->rang = $objp->rang;
2589 $line->fk_element = $objp->fk_element;
2590 $line->fk_unit = $objp->fk_unit;
2591 $line->fk_elementdet = $objp->fk_elementdet;
2592 $line->element_type = $objp->element_type;
2593 $line->fetch_optionals();
2594
2595 $this->lines[$i] = $line;
2596
2597 $i++;
2598 }
2599
2600 $this->db->free($result);
2601
2602 return 1;
2603 } else {
2604 $this->error = $this->db->error();
2605 return -3;
2606 }
2607 }
2608
2614 public function getLinesArray()
2615 {
2616 return $this->fetch_lines_free();
2617 }
2618
2626 public function deleteLine($user, $lineid)
2627 {
2628 global $user;
2629
2630 if ($this->status == self::STATUS_DRAFT) {
2631 $this->db->begin();
2632
2633 $line = new ExpeditionLigne($this->db);
2634
2635 // For triggers
2636 $line->fetch($lineid);
2637
2638 if ($this->id > 0 && (int) $line->fk_expedition !== (int) $this->id) {
2639 $this->db->rollback();
2640 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2641 return -1;
2642 }
2643
2644 if ($line->delete($user) > 0) {
2645 //$this->update_price(1);
2646
2647 $this->db->commit();
2648 return 1;
2649 } else {
2650 $this->db->rollback();
2651 return -1;
2652 }
2653 } else {
2654 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
2655 return -2;
2656 }
2657 }
2658
2659
2666 public function getTooltipContentArray($params)
2667 {
2668 global $conf, $langs;
2669
2670 $langs->load('sendings');
2671
2672 $nofetch = !empty($params['nofetch']);
2673
2674 $datas = array();
2675 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Shipment").'</u>';
2676 if (isset($this->status)) {
2677 $datas['picto'] .= ' '.$this->getLibStatut(5);
2678 }
2679 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2680 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.($this->ref_customer ? $this->ref_customer : $this->ref_client);
2681 if (!$nofetch) {
2682 $langs->load('companies');
2683 if (empty($this->thirdparty)) {
2684 $this->fetch_thirdparty();
2685 }
2686 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
2687 }
2688
2689 return $datas;
2690 }
2691
2704 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
2705 {
2706 global $langs, $hookmanager, $user;
2707
2708 $result = '';
2709 $params = [
2710 'id' => $this->id,
2711 'objecttype' => $this->element,
2712 'option' => $option,
2713 'nofetch' => 1,
2714 ];
2715 $classfortooltip = 'classfortooltip';
2716 $dataparams = '';
2717 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2718 $classfortooltip = 'classforajaxtooltip';
2719 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2720 $label = '';
2721 } else {
2722 $label = implode($this->getTooltipContentArray($params));
2723 }
2724
2725 $url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id;
2726
2727 if ($short) {
2728 return $url;
2729 }
2730
2731 if ($option !== 'nolink') {
2732 // Add param to save lastsearch_values or not
2733 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2734 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2735 $add_save_lastsearch_values = 1;
2736 }
2737 if ($add_save_lastsearch_values) {
2738 $url .= '&save_lastsearch_values=1';
2739 }
2740 }
2741
2742 $linkclose = '';
2743 if (empty($notooltip)) {
2744 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2745 $label = $langs->trans("Shipment");
2746 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2747 }
2748 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2749 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2750 }
2751
2752 $linkstart = '<a href="'.$url.'"';
2753 $linkstart .= $linkclose.'>';
2754 $linkend = '</a>';
2755
2756 $result .= $linkstart;
2757 if ($withpicto) {
2758 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
2759 }
2760 if ($withpicto != 2) {
2761 $result .= $this->ref;
2762 }
2763 $result .= $linkend;
2764
2765 if ($addlinktonotes) {
2766 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2767 if ($txttoshow) {
2768 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
2769 $result .= ' <span class="note inline-block">';
2770 $result .= '<a href="'.DOL_URL_ROOT.'/expedition/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
2771 $result .= img_picto('', 'note');
2772 $result .= '</a>';
2773 $result .= '</span>';
2774 }
2775 }
2776
2777 global $action;
2778 $hookmanager->initHooks(array($this->element . 'dao'));
2779 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2780 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2781 if ($reshook > 0) {
2782 $result = $hookmanager->resPrint;
2783 } else {
2784 $result .= $hookmanager->resPrint;
2785 }
2786 return $result;
2787 }
2788
2795 public function getLibStatut($mode = 0)
2796 {
2797 return $this->LibStatut($this->status, $mode);
2798 }
2799
2800 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2808 public function LibStatut($status, $mode)
2809 {
2810 // phpcs:enable
2811 global $langs;
2812
2813 $labelStatus = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
2814 $labelStatusShort = $langs->transnoentitiesnoconv($this->labelStatusShort[$status]);
2815
2816 $statusType = 'status'.$status;
2817 if ($status == self::STATUS_VALIDATED) {
2818 $statusType = 'status4';
2819 }
2820 if ($status == self::STATUS_CLOSED) {
2821 $statusType = 'status6';
2822 }
2823 if ($status == self::STATUS_CANCELED) {
2824 $statusType = 'status9';
2825 }
2826
2827 $signed_label = ' (' . $this->getLibSignedStatus() . ')';
2828 $status_label = $this->signed_status ? $labelStatus . $signed_label : $labelStatus;
2829 $status_label_short = $this->signed_status ? $labelStatusShort . $signed_label : $labelStatusShort;
2830
2831 return dolGetStatus($status_label, $status_label_short, '', $statusType, $mode);
2832 }
2833
2841 public function getKanbanView($option = '', $arraydata = null)
2842 {
2843 global $langs, $conf;
2844
2845 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2846
2847 $return = '<div class="box-flex-item box-flex-grow-zero">';
2848 $return .= '<div class="info-box info-box-sm">';
2849 $return .= '<div class="info-box-icon bg-infobox-action">';
2850 $return .= img_picto('', 'order');
2851 $return .= '</div>';
2852 $return .= '<div class="info-box-content">';
2853 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
2854 if ($selected >= 0) {
2855 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2856 }
2857 $return .= '<br><div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
2858 $return .= '<div class="info-box-ref amount">'.price($this->total_ht, 0, $langs, 0, -1, -1, getDolCurrency()).' '.$langs->trans('HT').'</div>';
2859 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2860 $return .= '</div>';
2861 $return .= '</div>';
2862 $return .= '</div>';
2863
2864 return $return;
2865 }
2866
2874 public function initAsSpecimen()
2875 {
2876 global $langs;
2877
2878 $now = dol_now();
2879
2880 dol_syslog(get_class($this)."::initAsSpecimen");
2881
2882 $order = new Commande($this->db);
2883 $order->initAsSpecimen();
2884
2885 // Initialise parameters
2886 $this->id = 0;
2887 $this->ref = 'SPECIMEN';
2888 $this->specimen = 1;
2889 $this->status = self::STATUS_VALIDATED;
2890 $this->livraison_id = 0;
2891 $this->date = $now;
2892 $this->date_creation = $now;
2893 $this->date_valid = $now;
2894 $this->date_delivery = $now + 24 * 3600;
2895 $this->date_expedition = $now + 24 * 3600;
2896
2897 $this->entrepot_id = 0;
2898 $this->fk_delivery_address = 0;
2899 $this->socid = 1;
2900
2901 $this->commande_id = 0;
2902 $this->commande = $order;
2903
2904 $this->origin_id = 1;
2905 $this->origin_type = 'commande';
2906
2907 $this->note_private = 'Private note';
2908 $this->note_public = 'Public note';
2909
2910 $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)
2911 $xnbp = 0;
2912 while ($xnbp < $nbp) {
2913 $line = new ExpeditionLigne($this->db);
2914 $line->product_desc = $langs->trans("Description")." ".$xnbp;
2915 $line->product_label = $langs->trans("Description")." ".$xnbp;
2916 $line->qty = 10;
2917 $line->qty_asked = 5;
2918 $line->qty_shipped = 4;
2919 $line->fk_product = $this->commande->lines[$xnbp]->fk_product;
2920
2921 $line->weight = 1.123456;
2922 $line->weight_units = 0; // kg
2923
2924 $line->volume = 2.34567;
2925 $line->volume_unit = 0;
2926
2927 $this->lines[] = $line;
2928 $xnbp++;
2929 }
2930
2931 return 1;
2932 }
2933
2934 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2943 public function set_date_livraison($user, $delivery_date)
2944 {
2945 // phpcs:enable
2946 return $this->setDeliveryDate($user, $delivery_date);
2947 }
2948
2957 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2958 {
2959 if ($user->hasRight('expedition', 'creer')) {
2960 $this->db->begin();
2961
2962 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
2963 $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2964 $sql .= " WHERE rowid = ".((int) $this->id);
2965
2966 dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
2967 $resql = $this->db->query($sql);
2968 if ($resql) {
2969 $this->date_delivery = $delivery_date;
2970
2971 if (!$notrigger) {
2972 // Call trigger
2973 $result = $this->call_trigger('SHIPPING_MODIFY', $user);
2974 if ($result < 0) {
2975 $this->db->rollback();
2976 return -1;
2977 }
2978 // End call triggers
2979 }
2980
2981 $this->db->commit();
2982 return 1;
2983 } else {
2984 $this->error = $this->db->error();
2985 $this->db->rollback();
2986 return -1;
2987 }
2988 } else {
2989 return -2;
2990 }
2991 }
2992
3001 public function setShippingDate($user, $shipping_date, $notrigger = 0)
3002 {
3003 if ($user->hasRight('expedition', 'creer')) {
3004 $this->db->begin();
3005
3006 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
3007 $sql .= " SET date_expedition = ".($shipping_date ? "'".$this->db->idate($shipping_date)."'" : 'null');
3008 $sql .= " WHERE rowid = ".((int) $this->id);
3009
3010 dol_syslog(get_class($this)."::setShippingDate", LOG_DEBUG);
3011 $resql = $this->db->query($sql);
3012 if ($resql) {
3013 $this->date_shipping = $shipping_date;
3014
3015 if (!$notrigger) {
3016 // Call trigger
3017 $result = $this->call_trigger('SHIPPING_MODIFY', $user);
3018 if ($result < 0) {
3019 $this->db->rollback();
3020 return -1;
3021 }
3022 // End call triggers
3023 }
3024
3025 $this->db->commit();
3026 return 1;
3027 } else {
3028 $this->error = $this->db->error();
3029 $this->db->rollback();
3030 return -1;
3031 }
3032 } else {
3033 return -2;
3034 }
3035 }
3036
3037 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3043 public function fetch_delivery_methods()
3044 {
3045 // phpcs:enable
3046 global $langs;
3047 $this->meths = [];
3048
3049 $sql = "SELECT em.rowid, em.code, em.libelle as label";
3050 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
3051 $sql .= " WHERE em.active = 1";
3052 $sql .= " ORDER BY em.libelle ASC";
3053
3054 $resql = $this->db->query($sql);
3055 if ($resql) {
3056 while ($obj = $this->db->fetch_object($resql)) {
3057 $label = $langs->trans('SendingMethod'.$obj->code);
3058 $this->meths[(int) $obj->rowid] = ($label != 'SendingMethod'.$obj->code ? $label : $obj->label);
3059 }
3060 }
3061 }
3062
3063 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3070 public function list_delivery_methods($id = 0)
3071 {
3072 // phpcs:enable
3073 global $langs;
3074
3075 $this->listmeths = [];
3076 $i = 0;
3077
3078 $sql = "SELECT em.rowid, em.code, em.libelle as label, em.description, em.tracking, em.active";
3079 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
3080 if (!empty($id)) {
3081 $sql .= " WHERE em.rowid=".((int) $id);
3082 }
3083
3084 $resql = $this->db->query($sql);
3085 if ($resql) {
3086 while ($obj = $this->db->fetch_object($resql)) {
3087 $label = $langs->trans('SendingMethod'.$obj->code);
3088 $this->listmeths[$i] = [
3089 'rowid' => (int) $obj->rowid,
3090 'code' => $obj->code,
3091 'libelle' => ($label != 'SendingMethod'.$obj->code ? $label : $obj->label),
3092 'description' => $obj->description,
3093 'tracking' => $obj->tracking,
3094 'active' => (int) $obj->active,
3095 ];
3096 $i++;
3097 }
3098 }
3099 }
3100
3107 public function getUrlTrackingStatus($value = '')
3108 {
3109 $tracking = '';
3110 if (!empty($this->shipping_method_id)) {
3111 $sql = "SELECT em.code, em.tracking";
3112 $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
3113 $sql .= " WHERE em.rowid = ".((int) $this->shipping_method_id);
3114
3115 $resql = $this->db->query($sql);
3116 if ($resql) {
3117 if ($obj = $this->db->fetch_object($resql)) {
3118 $tracking = (string) $obj->tracking;
3119 }
3120 }
3121 }
3122
3123 if (!empty($tracking) && !empty($value)) {
3124 $url = str_replace('{TRACKID}', $value, $tracking);
3125 $this->tracking_url = sprintf('<a target="_blank" rel="noopener noreferrer" href="%s">%s</a>', $url, $value);
3126 } else {
3127 $this->tracking_url = $value;
3128 }
3129 }
3130
3136 public function setClosed()
3137 {
3138 global $langs, $user;
3139
3140 $error = 0;
3141
3142 // Protection. This avoid to move stock later when we should not
3143 if ($this->status == self::STATUS_CLOSED) {
3144 return 0;
3145 }
3146
3147 // We need to validate shipping before closing it
3148 if ($this->status == self::STATUS_DRAFT) {
3149 $this->valid($user);
3150 }
3151
3152 $this->db->begin();
3153
3154 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET fk_statut = ".self::STATUS_CLOSED;
3155 if (empty($this->date_shipping)) { // Date of real shipment was not yet set, we force it on closing
3156 $sql .= ", date_expedition = '".$this->db->escape($this->db->idate(dol_now()))."'";
3157 }
3158 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut > 0";
3159 $sql .= " AND fk_statut <> ".self::STATUS_CLOSED;
3160
3161 $resql = $this->db->query($sql);
3162 if ($resql && $this->db->affected_rows($resql) <= 0) {
3163 // The shipment is not validated (draft, canceled or already closed): nothing to close and no stock must be moved.
3164 // 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.
3165 $this->db->rollback();
3166 dol_syslog(get_class($this)."::setClosed shipment ".$this->id." is not validated, nothing done", LOG_WARNING);
3167 return 0;
3168 }
3169 if ($resql) {
3170 // Set order billed if 100% of order is shipped (qty in shipment lines match qty in order lines)
3171 if ($this->origin_type == 'commande' && $this->origin_id > 0) {
3172 $order = new Commande($this->db);
3173 $order->fetch($this->origin_id);
3174
3175 $order->loadExpeditions(self::STATUS_CLOSED); // Fill $order->expeditions = array(orderlineid => qty)
3176
3177 $shipments_match_order = 1;
3178 foreach ($order->lines as $line) {
3179 $lineid = $line->id;
3180 $qty = $line->qty;
3181 if (($line->product_type == 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) && $order->expeditions[$lineid] != $qty) {
3182 $shipments_match_order = 0;
3183 $text = 'Qty for order line id '.$lineid.' is '.$qty.'. However in the shipments with status Expedition::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$order->expeditions[$lineid].', so we can t close order';
3184 dol_syslog($text);
3185 break;
3186 }
3187 }
3188 if ($shipments_match_order) {
3189 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');
3190 // We close the order
3191 $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
3192 }
3193 }
3194
3195 $this->statut = self::STATUS_CLOSED; // Will be revert to STATUS_VALIDATED at end if there is a rollback
3196 $this->status = self::STATUS_CLOSED; // Will be revert to STATUS_VALIDATED at end if there is a rollback
3197
3198 // If stock increment is done on closing
3199 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
3200 $result = $this->manageStockMvtOnEvt($user);
3201
3202 if ($result < 0) {
3203 $error++;
3204 }
3205 }
3206
3207 // Call trigger
3208 if (!$error) {
3209 $result = $this->call_trigger('SHIPPING_CLOSED', $user);
3210 if ($result < 0) {
3211 $error++;
3212 }
3213 }
3214 } else {
3215 dol_print_error($this->db);
3216 $error++;
3217 }
3218
3219 if (!$error) {
3220 $this->db->commit();
3221 return 1;
3222 } else {
3223 $this->statut = self::STATUS_VALIDATED;
3224 $this->status = self::STATUS_VALIDATED;
3225
3226 $this->db->rollback();
3227 return -1;
3228 }
3229 }
3230
3240 private function manageStockMvtOnEvt($user, $labelmovement = 'ShipmentClassifyClosedInDolibarr', $reverse = false)
3241 {
3242 global $langs;
3243
3244 $error = 0;
3245
3246 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php';
3247
3248 $langs->load("agenda");
3249
3250 // Label is stored into llx_stock_mouvement.label, so it must not be HTML encoded
3251 $labelmvt = $langs->transnoentitiesnoconv($labelmovement, $this->ref);
3252
3253 // Loop on each product line to add a stock movement
3254 $sql = "SELECT";
3255 $sql .= " ed.rowid as edid, ed.fk_product, ed.qty, ed.fk_entrepot";
3256 $sql .= ", cd.rowid as cdid";
3257 $sql .= ", cd.subprice";
3258 $sql .= ", edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
3259 $sql .= ", e.ref";
3260 $sql .= " FROM " . $this->db->prefix() . "expeditiondet as ed";
3261 $sql .= " LEFT JOIN " . $this->db->prefix() . "commandedet as cd ON cd.rowid = ed.fk_elementdet";
3262 $sql .= " LEFT JOIN " . $this->db->prefix() . "expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
3263 $sql .= " INNER JOIN " . $this->db->prefix() . "expedition as e ON ed.fk_expedition = e.rowid";
3264 $sql .= " WHERE ed.fk_expedition = " . ((int) $this->id);
3265 //$sql .= " AND cd.rowid = ed.fk_elementdet";
3266
3267 dol_syslog(get_class($this) . "::valid select details", LOG_DEBUG);
3268 $resql = $this->db->query($sql);
3269 if ($resql) {
3270 $cpt = $this->db->num_rows($resql);
3271 for ($i = 0; $i < $cpt; $i++) {
3272 $obj = $this->db->fetch_object($resql);
3273 if (empty($obj->edbrowid)) {
3274 $qty = $obj->qty;
3275 } else {
3276 $qty = $obj->edbqty;
3277 }
3278 if ($qty <= 0 || ($qty < 0 && !getDolGlobalInt('SHIPMENT_ALLOW_NEGATIVE_QTY'))) {
3279 continue;
3280 }
3281 dol_syslog(get_class($this) . "::valid movement index " . $i . " ed.rowid=" . $obj->edid . " edb.rowid=" . $obj->edbrowid);
3282
3283 // livraison() decrements stock by the quantity it is given, so a negated quantity re-increments
3284 // stock instead. Used to reverse the movement created at validation, e.g. when a shipment is
3285 // set back to draft, so a later re-validation does not create a duplicate stock movement.
3286 $qtytouse = $reverse ? -$qty : $qty;
3287
3288 $mouvS = new MouvementStock($this->db);
3289 $mouvS->origin = &$this;
3290 $mouvS->setOrigin($this->element, $this->id, $obj->cdid, $obj->edid);
3291
3292 if (empty($obj->edbrowid)) {
3293 // line without batch detail
3294
3295 // 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
3296 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qtytouse, $obj->subprice, $labelmvt);
3297 if ($result < 0) {
3298 $this->setErrorsFromObject($mouvS);
3299 $error++;
3300 break;
3301 }
3302 } else {
3303 // line with batch detail
3304
3305 // 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
3306 // When reversing, the stock is added back: the dates are not given so those of the lot are used (the copy on the line may be outdated)
3307 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qtytouse, $obj->subprice, $labelmvt, '', $reverse ? '' : $this->db->jdate($obj->eatby), $reverse ? '' : $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
3308 if ($result < 0) {
3309 $this->setErrorsFromObject($mouvS);
3310 $error++;
3311 break;
3312 }
3313 }
3314
3315 // 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
3316 // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
3317 $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)";
3318 $resqldelete = $this->db->query($sqldelete);
3319 // The NOT IN clause already excludes the rows still referenced by product_batch (the only child FK on
3320 // product_stock), so this DELETE can not fail on a child constraint. Any failure is a real error, in
3321 // particular a deadlock (1213) that rolls back the whole transaction including the stock movements just
3322 // recorded; if we swallowed it, the caller would commit an empty transaction and report a success while
3323 // the movements were lost.
3324 if (!$resqldelete) {
3325 $this->error = $this->db->lasterror();
3326 $this->errors[] = $this->db->lasterror();
3327 $error++;
3328 break;
3329 }
3330 }
3331 } else {
3332 $this->error = $this->db->lasterror();
3333 $this->errors[] = $this->db->lasterror();
3334 $error++;
3335 }
3336
3337 if (!$error) {
3338 return 1;
3339 } else {
3340 return -1;
3341 }
3342 }
3343
3349 public function setBilled()
3350 {
3351 global $user;
3352 $error = 0;
3353
3354 $this->db->begin();
3355
3356 $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET billed = 1';
3357 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
3358
3359 $resql = $this->db->query($sql);
3360 if ($resql) {
3361 $this->billed = 1;
3362
3363 // Call trigger
3364 $result = $this->call_trigger('SHIPPING_BILLED', $user);
3365 if ($result < 0) {
3366 $this->billed = 0;
3367 $error++;
3368 }
3369 } else {
3370 $error++;
3371 $this->errors[] = $this->db->lasterror;
3372 }
3373
3374 if (empty($error)) {
3375 $this->db->commit();
3376 return 1;
3377 } else {
3378 $this->db->rollback();
3379 return -1;
3380 }
3381 }
3382
3390 public function setDraft($user, $notrigger = 0)
3391 {
3392 global $langs;
3393
3394 // Protection
3395 if ($this->status <= self::STATUS_DRAFT) {
3396 return 0;
3397 }
3398 // Only a validated shipment can go back to draft. A closed one must be reopened first, so that the stock
3399 // decreased on closing (STOCK_CALCULATE_ON_SHIPMENT_CLOSE) is restored.
3400 if ($this->status != self::STATUS_VALIDATED) {
3401 $langs->load("sendings");
3402 $this->error = $langs->trans("StatusOfRefMustBe", $this->ref, $langs->transnoentitiesnoconv("StatusSendingValidatedShort"));
3403 $this->errors[] = $this->error;
3404 return -1;
3405 }
3406
3407 $this->db->begin();
3408
3409 $error = 0;
3410
3411 // If stock was decremented on shipment validation, reverse it now, before going back to draft, so that
3412 // a later re-validation does not create a duplicate stock movement (see setStatusCommon() below, which
3413 // does not know about this class' stock logic and only updates the status).
3414 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT')) {
3415 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3416
3417 $langs->load("agenda");
3418
3419 $result = $this->manageStockMvtOnEvt($user, "ShipmentBackToDraftInDolibarr", true);
3420 if ($result < 0) {
3421 $error++;
3422 }
3423 }
3424
3425 if (!$error) {
3426 $result = $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'SHIPMENT_UNVALIDATE');
3427 if ($result < 0) {
3428 $error++;
3429 }
3430 }
3431
3432 if (!$error) {
3433 $this->db->commit();
3434 return 1;
3435 } else {
3436 $this->db->rollback();
3437 return -1;
3438 }
3439 }
3440
3446 public function reOpen()
3447 {
3448 global $langs, $user;
3449
3450 $error = 0;
3451
3452 // Protection. This avoid to move stock later when we should not
3453 if ($this->status == self::STATUS_VALIDATED) {
3454 return 0;
3455 }
3456
3457 $this->db->begin();
3458
3459 $oldbilled = $this->billed;
3460
3461 $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut = 1';
3462 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut = '.self::STATUS_CLOSED;
3463
3464 $resql = $this->db->query($sql);
3465 if ($resql && $this->db->affected_rows($resql) <= 0) {
3466 // The shipment is not closed (draft or canceled), so no stock must be moved
3467 $this->db->rollback();
3468 $langs->load("sendings");
3469 $this->error = $langs->trans("StatusOfRefMustBe", $this->ref, $langs->transnoentitiesnoconv("StatusSendingProcessedShort"));
3470 $this->errors[] = $this->error;
3471 return -1;
3472 }
3473 if ($resql) {
3474 $this->statut = self::STATUS_VALIDATED;
3475 $this->status = self::STATUS_VALIDATED;
3476 $this->billed = 0;
3477
3478 // If stock increment is done on closing
3479 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
3480 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3481
3482 $langs->load("agenda");
3483
3484 // Loop on each product line to add a stock movement
3485 // Lines are selected like in manageStockMvtOnEvt(), so reopening restores exactly what closing removed,
3486 // including lines with no source order line (standalone shipment, SHIPMENT_STANDALONE)
3487 $sql = "SELECT ed.fk_product, cd.subprice,";
3488 $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
3489 $sql .= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
3490 $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed";
3491 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commandedet as cd ON cd.rowid = ed.fk_elementdet";
3492 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
3493 $sql .= " WHERE ed.fk_expedition = ".((int) $this->id);
3494
3495 dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
3496 $resql = $this->db->query($sql);
3497 if ($resql) {
3498 $cpt = $this->db->num_rows($resql);
3499 for ($i = 0; $i < $cpt; $i++) {
3500 $obj = $this->db->fetch_object($resql);
3501 if (empty($obj->edbrowid)) {
3502 $qty = $obj->qty;
3503 } else {
3504 $qty = $obj->edbqty;
3505 }
3506 if ($qty <= 0) {
3507 continue;
3508 }
3509 dol_syslog(get_class($this)."::reopen expedition movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
3510
3511 //var_dump($this->lines[$i]);
3512 $mouvS = new MouvementStock($this->db);
3513 $mouvS->origin = &$this;
3514 $mouvS->setOrigin($this->element, $this->id);
3515
3516 if (empty($obj->edbrowid)) {
3517 // line without batch detail
3518
3519 // 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
3520 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->transnoentitiesnoconv("ShipmentUnClassifyCloseddInDolibarr", $this->ref));
3521 if ($result < 0) {
3522 $this->setErrorsFromObject($mouvS);
3523 $error++;
3524 break;
3525 }
3526 } else {
3527 // line with batch detail
3528
3529 // 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
3530 $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->transnoentitiesnoconv("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)
3531 if ($result < 0) {
3532 $this->setErrorsFromObject($mouvS);
3533 $error++;
3534 break;
3535 }
3536 }
3537 }
3538 } else {
3539 $this->error = $this->db->lasterror();
3540 $error++;
3541 }
3542 }
3543
3544 if (!$error) {
3545 // Call trigger
3546 $result = $this->call_trigger('SHIPPING_REOPEN', $user);
3547 if ($result < 0) {
3548 $error++;
3549 }
3550 }
3551 } else {
3552 $error++;
3553 $this->errors[] = $this->db->lasterror();
3554 }
3555
3556 if (!$error) {
3557 $this->db->commit();
3558 return 1;
3559 } else {
3560 $this->statut = self::STATUS_CLOSED;
3561 $this->status = self::STATUS_CLOSED;
3562 $this->billed = $oldbilled;
3563 $this->db->rollback();
3564 return -1;
3565 }
3566 }
3567
3579 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3580 {
3581 $outputlangs->load("products");
3582
3583 if (!dol_strlen($modele)) {
3584 $modele = 'espadon';
3585
3586 if (!empty($this->model_pdf)) {
3587 $modele = $this->model_pdf;
3588 } elseif (getDolGlobalString('EXPEDITION_ADDON_PDF')) {
3589 $modele = getDolGlobalString('EXPEDITION_ADDON_PDF');
3590 }
3591 }
3592
3593 $modelpath = "core/modules/expedition/doc/";
3594
3595 $this->fetch_origin();
3596
3597 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3598 }
3599
3608 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3609 {
3610 $tables = array(
3611 'expedition'
3612 );
3613
3614 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3615 }
3616
3625 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
3626 {
3627 $tables = array(
3628 'expeditiondet'
3629 );
3630
3631 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
3632 }
3633}
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage customers orders.
const STATUS_SHIPMENTONPROCESS
Shipment on process.
const STATUS_VALIDATED
Validated status.
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.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
fetch_origin()
Read linked origin object.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
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.
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.
manageStockMvtOnEvt($user, $labelmovement='ShipmentClassifyClosedInDolibarr', $reverse=false)
Manage Stock MVt onb Close or valid Shipment.
setShippingDate($user, $shipping_date, $notrigger=0)
Set the shipping date.
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.
checkLineStockRequirements($fk_product, $fk_entrepot, $qty, $product_type=null, $forbid_batch_product=false, $allowEmptyWarehouse=false)
Check stock constraints for a shipment line.
setBilled()
Classify the shipping as invoiced (used for example by trigger when WORKFLOW_SHIPPING_CLASSIFY_BILLED...
updatelinefree($rowid, $qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $notrigger, $array_options=array(), $fk_entrepot=-1)
Update a simple expedition line.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
getTooltipContentArray($params)
getTooltipContentArray
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
const STATUS_DRAFT
Draft status.
setDeliveryDate($user, $delivery_date, $notrigger=0)
Set the planned delivery date.
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.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=0)
Return clickable link of object (with eventually picto)
getLibStatut($mode=0)
Return status label.
set_date_livraison($user, $delivery_date)
Set delivery date.
initAsSpecimen()
Initialise an instance with random values.
static replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a product id with another one.
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.
addlinefree($qty, $element_type, $fk_product, $fk_unit, $rang, $description, $fk_parent, $array_options=[], $fk_entrepot=0)
Add a simple expedition line.
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.
countStandalone()
Count the standalone shipments (shipments without source object, like a sales order) of the current e...
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_PRODUCT
Regular product.
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
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
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:166