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