dolibarr 22.0.5
delivery.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2006-2007 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
6 * Copyright (C) 2011-2023 Philippe Grand <philippe.grand@atoo-net.com>
7 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
8 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
9 * Copyright (C) 2023-2024 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 */
25
32require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
33require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
34require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
35require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
36if (isModEnabled("propal")) {
37 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
38}
39if (isModEnabled('order')) {
40 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
41}
42
43
48{
49 use CommonIncoterm;
50
54 public $element = "delivery";
55
59 public $fk_element = "fk_delivery";
60
64 public $table_element = "delivery";
65
69 public $table_element_line = "deliverydet";
70
74 public $picto = 'sending';
75
79 public $draft;
80
84 public $socid;
85
89 public $ref_customer;
90
94 public $date_delivery;
95
99 public $date_valid;
100
104 public $model_pdf;
105
109 public $commande_id;
110
114 public $lines = array();
115
119 public $user_author_id;
120
121
122 const STATUS_DRAFT = 0;
123 const STATUS_VALIDATED = 1;
124 const STATUS_CANCELED = -1;
125
126
132 public function __construct($db)
133 {
134 $this->db = $db;
135
136 // List of short language codes for status
137 $this->labelStatus[-1] = 'StatusDeliveryCanceled';
138 $this->labelStatus[0] = 'StatusDeliveryDraft';
139 $this->labelStatus[1] = 'StatusDeliveryValidated';
140 }
141
148 public function create($user)
149 {
150 global $conf;
151
152 dol_syslog("Delivery::create");
153
154 if (empty($this->model_pdf)) {
155 $this->model_pdf = getDolGlobalString('DELIVERY_ADDON_PDF');
156 }
157
158 $error = 0;
159
160 $now = dol_now();
161
162 /* Delivery note as draft On positionne en mode draft le bon de livraison */
163 $this->draft = 1;
164
165 $this->user = $user;
166
167 $this->db->begin();
168
169 $sql = "INSERT INTO ".MAIN_DB_PREFIX."delivery (";
170 $sql .= "ref";
171 $sql .= ", entity";
172 $sql .= ", fk_soc";
173 $sql .= ", ref_customer";
174 $sql .= ", date_creation";
175 $sql .= ", fk_user_author";
176 $sql .= ", date_delivery";
177 $sql .= ", fk_address";
178 $sql .= ", note_private";
179 $sql .= ", note_public";
180 $sql .= ", model_pdf";
181 $sql .= ", fk_incoterms, location_incoterms";
182 $sql .= ") VALUES (";
183 $sql .= "'(PROV)'";
184 $sql .= ", ".((int) $conf->entity);
185 $sql .= ", ".((int) $this->socid);
186 $sql .= ", '".$this->db->escape($this->ref_customer)."'";
187 $sql .= ", '".$this->db->idate($now)."'";
188 $sql .= ", ".((int) $user->id);
189 $sql .= ", ".($this->date_delivery ? "'".$this->db->idate($this->date_delivery)."'" : "null");
190 $sql .= ", ".($this->fk_delivery_address > 0 ? $this->fk_delivery_address : "null");
191 $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
192 $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
193 $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
194 $sql .= ", ".(int) $this->fk_incoterms;
195 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
196 $sql .= ")";
197
198 dol_syslog("Delivery::create", LOG_DEBUG);
199
200 $resql = $this->db->query($sql);
201 if ($resql) {
202 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."delivery");
203
204 $numref = "(PROV".$this->id.")";
205
206 $sql = "UPDATE ".MAIN_DB_PREFIX."delivery ";
207 $sql .= "SET ref = '".$this->db->escape($numref)."'";
208 $sql .= " WHERE rowid = ".((int) $this->id);
209
210 dol_syslog("Delivery::create", LOG_DEBUG);
211 $resql = $this->db->query($sql);
212 if ($resql) {
213 if (!getDolGlobalInt('MAIN_SUBMODULE_EXPEDITION')) {
214 $commande = new Commande($this->db);
215 $commande->id = $this->commande_id;
216 $commande->fetch_lines();
217 }
218
219
220 /*
221 * Inserting products into the database
222 */
223 $num = count($this->lines);
224 for ($i = 0; $i < $num; $i++) {
225 $origin_id = $this->lines[$i]->origin_line_id;
226 if (!$origin_id) {
227 $origin_id = $this->lines[$i]->commande_ligne_id; // For backward compatibility
228 }
229
230 if (!$this->create_line($origin_id, $this->lines[$i]->qty, $this->lines[$i]->fk_product, $this->lines[$i]->description, $this->lines[$i]->array_options)) {
231 $error++;
232 }
233 }
234
235 if (!$error && $this->id && $this->origin_id) {
236 $ret = $this->add_object_linked();
237 if (!$ret) {
238 $error++;
239 }
240
241 if (!getDolGlobalInt('MAIN_SUBMODULE_EXPEDITION')) {
242 $ret = $this->setStatut(2, $this->origin_id, $this->origin);
243 if (!$ret) {
244 $error++;
245 }
246 }
247 }
248
249 if (!$error) {
250 $this->db->commit();
251 return $this->id;
252 } else {
253 $error++;
254 $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
255 $this->db->rollback();
256 return -3;
257 }
258 } else {
259 $error++;
260 $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
261 $this->db->rollback();
262 return -2;
263 }
264 } else {
265 $error++;
266 $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
267 $this->db->rollback();
268 return -1;
269 }
270 }
271
272 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
283 public function create_line($origin_id, $qty, $fk_product, $description, $array_options = [])
284 {
285 // phpcs:enable
286 $error = 0;
287
288 $sql = "INSERT INTO ".MAIN_DB_PREFIX."deliverydet (fk_delivery, fk_origin_line,";
289 $sql .= " fk_product, description, qty)";
290 $sql .= " VALUES (".$this->id.",".((int) $origin_id).",";
291 $sql .= " ".($fk_product > 0 ? ((int) $fk_product) : "null").",";
292 $sql .= " ".($description ? "'".$this->db->escape($description)."'" : "null").",";
293 $sql .= (price2num($qty, 'MS')).")";
294
295 dol_syslog(get_class($this)."::create_line", LOG_DEBUG);
296 if (!$this->db->query($sql)) {
297 $error++;
298 }
299
300 $id = $this->db->last_insert_id(MAIN_DB_PREFIX."deliverydet");
301
302 if (is_array($array_options) && count($array_options) > 0) {
303 $line = new DeliveryLine($this->db);
304 $line->id = $id;
305 $line->array_options = $array_options;
306 $result = $line->insertExtraFields();
307 }
308
309 if (!$error) {
310 return 1;
311 }
312
313 return -1;
314 }
315
322 public function fetch($id)
323 {
324 $sql = "SELECT l.rowid, l.fk_soc, l.date_creation, l.date_valid, l.ref, l.ref_customer, l.fk_user_author,";
325 $sql .= " l.total_ht, l.fk_statut, l.fk_user_valid, l.note_private, l.note_public";
326 $sql .= ", l.date_delivery, l.fk_address, l.model_pdf";
327 $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
328 $sql .= ', l.fk_incoterms, l.location_incoterms';
329 $sql .= ", i.libelle as label_incoterms";
330 $sql .= " FROM ".MAIN_DB_PREFIX."delivery as l";
331 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = l.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
332 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON l.fk_incoterms = i.rowid';
333 $sql .= " WHERE l.rowid = ".((int) $id);
334
335 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
336 $result = $this->db->query($sql);
337 if ($result) {
338 if ($this->db->num_rows($result)) {
339 $obj = $this->db->fetch_object($result);
340
341 $this->id = $obj->rowid;
342 $this->date_delivery = $this->db->jdate($obj->date_delivery);
343 $this->date_creation = $this->db->jdate($obj->date_creation);
344 $this->date_valid = $this->db->jdate($obj->date_valid);
345 $this->ref = $obj->ref;
346 $this->ref_customer = $obj->ref_customer;
347 $this->socid = $obj->fk_soc;
348 $this->statut = $obj->fk_statut;
349 $this->status = $obj->fk_statut;
350 $this->user_author_id = $obj->fk_user_author;
351 $this->user_validation_id = $obj->fk_user_valid;
352 $this->fk_delivery_address = $obj->fk_address;
353 $this->note = $obj->note_private; //TODO deprecated
354 $this->note_private = $obj->note_private;
355 $this->note_public = $obj->note_public;
356 $this->model_pdf = $obj->model_pdf;
357 $this->origin = $obj->origin; // May be 'shipping'
358 $this->origin_type = $obj->origin; // May be 'shipping'
359 $this->origin_id = $obj->origin_id; // May be id of shipping
360
361 //Incoterms
362 $this->fk_incoterms = $obj->fk_incoterms;
363 $this->location_incoterms = $obj->location_incoterms;
364 $this->label_incoterms = $obj->label_incoterms;
365 $this->db->free($result);
366
367 if ($this->status == 0) {
368 $this->draft = 1;
369 }
370
371 // Retrieve all extrafields
372 // fetch optionals attributes and labels
373 $this->fetch_optionals();
374
375 // Load lines
376 $result = $this->fetch_lines();
377 if ($result < 0) {
378 return -3;
379 }
380
381 return 1;
382 } else {
383 $this->error = 'Delivery with id '.$id.' not found sql='.$sql;
384 dol_syslog(get_class($this).'::fetch Error '.$this->error, LOG_ERR);
385 return -2;
386 }
387 } else {
388 $this->error = $this->db->error();
389 return -1;
390 }
391 }
392
400 public function valid($user, $notrigger = 0)
401 {
402 global $conf;
403
404 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
405
406 dol_syslog(get_class($this)."::valid begin");
407
408 $this->db->begin();
409
410 $error = 0;
411
412 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'delivery', 'creer'))
413 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'delivery_advance', 'validate'))) {
414 if (getDolGlobalString('DELIVERY_ADDON_NUMBER')) {
415 // Setting the command numbering module name
416 $modName = getDolGlobalString('DELIVERY_ADDON_NUMBER');
417
418 if (is_readable(DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php')) {
419 require_once DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php';
420
421 $now = dol_now();
422
423 // Retrieving the new reference
424 $objMod = new $modName($this->db);
425 '@phan-var-force ModeleNumRefDeliveryOrder $objMod';
426 $soc = new Societe($this->db);
427 $soc->fetch($this->socid);
428
429 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
430 $numref = $objMod->getNextValue($soc, $this);
431 } else {
432 $numref = $this->ref;
433 }
434 $this->newref = dol_sanitizeFileName($numref);
435
436 // Test if is not already in valid status. If so, we stop to avoid decrementing the stock twice.
437 $sql = "SELECT ref";
438 $sql .= " FROM ".MAIN_DB_PREFIX."delivery";
439 $sql .= " WHERE ref = '".$this->db->escape($numref)."'";
440 $sql .= " AND fk_statut <> 0";
441 $sql .= " AND entity = ".((int) $conf->entity);
442
443 $resql = $this->db->query($sql);
444 if ($resql) {
445 $num = $this->db->num_rows($resql);
446 if ($num > 0) {
447 return 0;
448 }
449 }
450
451 $sql = "UPDATE ".MAIN_DB_PREFIX."delivery SET";
452 $sql .= " ref = '".$this->db->escape($numref)."'";
453 $sql .= ", fk_statut = 1";
454 $sql .= ", date_valid = '".$this->db->idate($now)."'";
455 if (!empty($this->date_delivery)) {
456 $sql .= ", date_delivery = '".$this->db->idate($this->date_delivery)."'";
457 }
458 $sql .= ", fk_user_valid = ".((int) $user->id);
459 $sql .= " WHERE rowid = ".((int) $this->id);
460 $sql .= " AND fk_statut = 0";
461
462 $resql = $this->db->query($sql);
463 if (!$resql) {
464 dol_print_error($this->db);
465 $this->error = $this->db->lasterror();
466 $error++;
467 }
468
469 if (!$error && !$notrigger) {
470 // Call trigger
471 $result = $this->call_trigger('DELIVERY_VALIDATE', $user);
472 if ($result < 0) {
473 $error++;
474 }
475 // End call triggers
476 }
477
478 if (!$error) {
479 $this->oldref = $this->ref;
480
481 // Rename directory if dir was a temporary ref
482 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
483 // Now we rename also files into index
484 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expedition/receipt/".$this->db->escape($this->newref)."'";
485 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/receipt/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
486 $resql = $this->db->query($sql);
487 if (!$resql) {
488 $error++;
489 $this->error = $this->db->lasterror();
490 }
491 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'expedition/receipt/".$this->db->escape($this->newref)."'";
492 $sql .= " WHERE filepath = 'expedition/receipt/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
493 $resql = $this->db->query($sql);
494 if (!$resql) {
495 $error++;
496 $this->error = $this->db->lasterror();
497 }
498
499 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
500 $oldref = dol_sanitizeFileName($this->ref);
501 $newref = dol_sanitizeFileName($numref);
502 $dirsource = $conf->expedition->dir_output.'/receipt/'.$oldref;
503 $dirdest = $conf->expedition->dir_output.'/receipt/'.$newref;
504 if (!$error && file_exists($dirsource)) {
505 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
506
507 if (@rename($dirsource, $dirdest)) {
508 dol_syslog("Rename ok");
509 // Rename docs starting with $oldref with $newref
510 $listoffiles = dol_dir_list($conf->expedition->dir_output.'/receipt/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
511 foreach ($listoffiles as $fileentry) {
512 $dirsource = $fileentry['name'];
513 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
514 $dirsource = $fileentry['path'].'/'.$dirsource;
515 $dirdest = $fileentry['path'].'/'.$dirdest;
516 @rename($dirsource, $dirdest);
517 }
518 }
519 }
520 }
521
522 // Set new ref and current status
523 if (!$error) {
524 $this->ref = $numref;
525 $this->status = 1;
526 }
527
528 dol_syslog(get_class($this)."::valid ok");
529 }
530
531 if (!$error) {
532 $this->db->commit();
533 return 1;
534 } else {
535 $this->db->rollback();
536 return -1;
537 }
538 }
539 }
540
541 return -1;
542 } else {
543 $this->error = "NotAllowed";
544 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
545 return -1;
546 }
547 }
548
549 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
557 public function create_from_sending($user, $sending_id)
558 {
559 // phpcs:enable
560 global $conf;
561
562 $expedition = new Expedition($this->db);
563 $result = $expedition->fetch($sending_id);
564 if ($result <= 0) {
565 return $result;
566 }
567
568 $this->lines = array();
569
570 $num = count($expedition->lines);
571 for ($i = 0; $i < $num; $i++) {
572 $line = new DeliveryLine($this->db);
573 $line->origin_line_id = $expedition->lines[$i]->origin_line_id;
574 $line->label = $expedition->lines[$i]->label;
575 $line->description = $expedition->lines[$i]->description;
576 $line->qty = $expedition->lines[$i]->qty_shipped;
577 $line->fk_product = $expedition->lines[$i]->fk_product;
578 if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($expedition->lines[$i]->array_options) && count($expedition->lines[$i]->array_options) > 0) { // For avoid conflicts if trigger used
579 $line->array_options = $expedition->lines[$i]->array_options;
580 }
581 $this->lines[$i] = $line;
582 }
583
584 $this->origin = $expedition->element;
585 $this->origin_id = $expedition->id;
586 $this->note_private = $expedition->note_private;
587 $this->note_public = $expedition->note_public;
588 $this->fk_project = $expedition->fk_project;
589 $this->date_delivery = ''; // Date of real reception. The Expedition->date_delivery is the planned one.
590 $this->fk_delivery_address = $expedition->fk_delivery_address;
591 $this->socid = $expedition->socid;
592 $this->ref_customer = $expedition->ref_customer;
593
594 //Incoterms
595 $this->fk_incoterms = $expedition->fk_incoterms;
596 $this->location_incoterms = $expedition->location_incoterms;
597
598 return $this->create($user);
599 }
600
601 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
609 public function update_line($id, $array_options = [])
610 {
611 // phpcs:enable
612 global $conf;
613 $error = 0;
614
615 if ($id > 0 && !$error && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
616 $line = new DeliveryLine($this->db);
617 $line->array_options = $array_options;
618 $line->id = $id;
619 $result = $line->insertExtraFields();
620
621 if ($result < 0) {
622 $this->errors[] = $line->error;
623 $error++;
624 }
625 }
626
627 if (!$error) {
628 return 1;
629 } else {
630 return -1;
631 }
632 }
633
634
643 public function addline($origin_id, $qty, $array_options = [])
644 {
645 $num = count($this->lines);
646 $line = new DeliveryLine($this->db);
647
648 $line->origin_id = $origin_id;
649 $line->qty = $qty;
650 if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
651 $line->array_options = $array_options;
652 }
653 $this->lines[$num] = $line;
654 }
655
662 public function deleteLine($lineid)
663 {
664 if ($this->status == 0) {
665 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
666 $sql .= " WHERE rowid = ".((int) $lineid);
667
668 if ($this->db->query($sql)) {
669 $this->update_price(1);
670
671 return 1;
672 } else {
673 return -1;
674 }
675 }
676
677 return 0;
678 }
679
686 public function delete($user = null)
687 {
688 global $conf, $langs;
689
690 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
691
692 $this->db->begin();
693
694 $error = 0;
695
696 $sql = "DELETE FROM ".MAIN_DB_PREFIX."deliverydet";
697 $sql .= " WHERE fk_delivery = ".((int) $this->id);
698 if ($this->db->query($sql)) {
699 // Delete linked object
700 $res = $this->deleteObjectLinked();
701 if ($res < 0) {
702 $error++;
703 }
704
705 if (!$error) {
706 $sql = "DELETE FROM ".MAIN_DB_PREFIX."delivery";
707 $sql .= " WHERE rowid = ".((int) $this->id);
708 if ($this->db->query($sql)) {
709 $this->db->commit();
710
711 // Deleting pdf folder's draft On efface le repertoire de pdf provisoire
712 $ref = dol_sanitizeFileName($this->ref);
713 if (!empty($conf->expedition->dir_output)) {
714 $dir = $conf->expedition->dir_output.'/receipt/'.$ref;
715 $file = $dir.'/'.$ref.'.pdf';
716 if (file_exists($file)) {
717 if (!dol_delete_file($file)) {
718 return 0;
719 }
720 }
721 if (file_exists($dir)) {
722 if (!dol_delete_dir($dir)) {
723 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
724 return 0;
725 }
726 }
727 }
728
729 // Call trigger
730 $result = $this->call_trigger('DELIVERY_DELETE', $user);
731 if ($result < 0) {
732 $this->db->rollback();
733 return -4;
734 }
735 // End call triggers
736
737 return 1;
738 } else {
739 $this->error = $this->db->lasterror()." - sql=$sql";
740 $this->db->rollback();
741 return -3;
742 }
743 } else {
744 $this->error = $this->db->lasterror()." - sql=$sql";
745 $this->db->rollback();
746 return -2;
747 }
748 } else {
749 $this->error = $this->db->lasterror()." - sql=$sql";
750 $this->db->rollback();
751 return -1;
752 }
753 }
754
761 public function getTooltipContentArray($params)
762 {
763 global $langs;
764
765 $langs->load('deliveries');
766
767 $datas = [];
768
769 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').' <u>'.$langs->trans("ShowReceiving").'</u>:<br>';
770 $datas['ref'] = '<b>'.$langs->trans("Ref").'</b>: '.$this->ref;
771
772 return $datas;
773 }
774
782 public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1)
783 {
784 global $langs, $hookmanager;
785
786 $result = '';
787
788 $params = [
789 'id' => $this->id,
790 'objecttype' => $this->element,
791 ];
792 $classfortooltip = 'classfortooltip';
793 $dataparams = '';
794 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
795 $classfortooltip = 'classforajaxtooltip';
796 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
797 $label = '';
798 } else {
799 $label = implode($this->getTooltipContentArray($params));
800 }
801
802 $url = DOL_URL_ROOT.'/delivery/card.php?id='.$this->id;
803
804 //if ($option !== 'nolink')
805 //{
806 // Add param to save lastsearch_values or not
807 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
808 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
809 $add_save_lastsearch_values = 1;
810 }
811 if ($add_save_lastsearch_values) {
812 $url .= '&save_lastsearch_values=1';
813 }
814 //}
815
816 $linkstart = '<a href="'.$url.'"';
817 $linkstart .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
818 $linkstart .= $dataparams.' class="'.$classfortooltip.'">';
819 $linkend = '</a>';
820
821 if ($withpicto) {
822 $result .= ($linkstart.img_object($label, $this->picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
823 }
824 if ($withpicto && $withpicto != 2) {
825 $result .= ' ';
826 }
827 $result .= $linkstart.$this->ref.$linkend;
828
829 global $action;
830 $hookmanager->initHooks(array($this->element . 'dao'));
831 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
832 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
833 if ($reshook > 0) {
834 $result = $hookmanager->resPrint;
835 } else {
836 $result .= $hookmanager->resPrint;
837 }
838 return $result;
839 }
840
841 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
847 public function fetch_lines()
848 {
849 // phpcs:enable
850 $this->lines = array();
851
852 $sql = "SELECT ld.rowid, ld.fk_product, ld.description, ld.subprice, ld.total_ht, ld.qty as qty_shipped, ld.fk_origin_line, ld.extraparams,";
853 $sql .= " cd.qty as qty_asked, cd.label as custom_label, cd.fk_unit,";
854 $sql .= " p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc,";
855 $sql .= " p.weight, p.weight_units, p.width, p.width_units, p.length, p.length_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units, p.tobatch as product_tobatch";
856 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."deliverydet as ld";
857 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on p.rowid = ld.fk_product";
858 $sql .= " WHERE ld.fk_origin_line = cd.rowid";
859 $sql .= " AND ld.fk_delivery = ".((int) $this->id);
860
861 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
862 $resql = $this->db->query($sql);
863 if ($resql) {
864 $num = $this->db->num_rows($resql);
865 $i = 0;
866 while ($i < $num) {
867 $obj = $this->db->fetch_object($resql);
868
869 $line = new DeliveryLine($this->db);
870
871 $line->id = $obj->rowid;
872 $line->label = $obj->custom_label;
873 $line->description = $obj->description;
874 $line->fk_product = $obj->fk_product;
875 $line->qty_asked = $obj->qty_asked;
876 $line->qty_shipped = $obj->qty_shipped;
877
878 $line->product_label = $obj->product_label; // Product label
879 $line->product_ref = $obj->product_ref; // Product ref
880 $line->product_desc = $obj->product_desc; // Product description
881 $line->product_type = $obj->fk_product_type;
882
883 $line->fk_origin_line = $obj->fk_origin_line;
884
885 $line->price = $obj->subprice;
886 $line->total_ht = $obj->total_ht;
887
888 // units
889 $line->weight = $obj->weight;
890 $line->weight_units = $obj->weight_units;
891 $line->width = $obj->width;
892 $line->width_units = $obj->width_units;
893 $line->height = $obj->height;
894 $line->height_units = $obj->height_units;
895 $line->length = $obj->length;
896 $line->length_units = $obj->length_units;
897 $line->surface = $obj->surface;
898 $line->surface_units = $obj->surface_units;
899 $line->volume = $obj->volume;
900 $line->volume_units = $obj->volume_units;
901
902 $line->fk_unit = $obj->fk_unit;
903 $line->fetch_optionals();
904
905 $line->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
906
907 $this->lines[$i] = $line;
908
909 $i++;
910 }
911 $this->db->free($resql);
912
913 return 1;
914 } else {
915 return -1;
916 }
917 }
918
919
926 public function getLibStatut($mode = 0)
927 {
928 return $this->LibStatut($this->status, $mode);
929 }
930
931 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
939 public function LibStatut($status, $mode)
940 {
941 // phpcs:enable
942 global $langs;
943
944 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
945 global $langs;
946 //$langs->load("mymodule");
947 $this->labelStatus[-1] = $langs->transnoentitiesnoconv('StatusDeliveryCanceled');
948 $this->labelStatus[0] = $langs->transnoentitiesnoconv('StatusDeliveryDraft');
949 $this->labelStatus[1] = $langs->transnoentitiesnoconv('StatusDeliveryValidated');
950 $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv('StatusDeliveryCanceled');
951 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv('StatusDeliveryDraft');
952 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv('StatusDeliveryValidated');
953 }
954
955 $statusType = 'status0';
956 if ($status == -1) {
957 $statusType = 'status5';
958 }
959 if ($status == 1) {
960 $statusType = 'status4';
961 }
962
963 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
964 }
965
966
974 public function initAsSpecimen()
975 {
976 $now = dol_now();
977
978 // Load array of products prodids
979 $num_prods = 0;
980 $prodids = array();
981 $sql = "SELECT rowid";
982 $sql .= " FROM ".MAIN_DB_PREFIX."product";
983 $sql .= " WHERE entity IN (".getEntity('product').")";
984 $sql .= " AND tosell = 1";
985 $sql .= $this->db->plimit(100);
986
987 $resql = $this->db->query($sql);
988 if ($resql) {
989 $num_prods = $this->db->num_rows($resql);
990 $i = 0;
991 while ($i < $num_prods) {
992 $i++;
993 $row = $this->db->fetch_row($resql);
994 $prodids[$i] = $row[0];
995 }
996 }
997
998 // Initialise parameters
999 $this->id = 0;
1000 $this->ref = 'SPECIMEN';
1001 $this->specimen = 1;
1002 $this->socid = 1;
1003 $this->date_delivery = $now;
1004 $this->note_public = 'Public note';
1005 $this->note_private = 'Private note';
1006
1007 $i = 0;
1008 $line = new DeliveryLine($this->db);
1009 $line->fk_product = reset($prodids);
1010 $line->qty_asked = 10;
1011 $line->qty_shipped = 9;
1012 $line->product_ref = 'REFPROD';
1013 $line->label = 'Specimen';
1014 $line->description = 'Description';
1015 $line->price = 100;
1016 $line->total_ht = 100;
1017
1018 $this->lines[$i] = $line;
1019
1020 return 1;
1021 }
1022
1029 public function getRemainingDelivered()
1030 {
1031 // Get the linked object
1032 $this->fetchObjectLinked(null, '', $this->id, $this->element);
1033 //var_dump($this->linkedObjectsIds);
1034 // Get the product ref and qty in source
1035 $sqlSourceLine = "SELECT st.rowid, st.description, st.qty";
1036 $sqlSourceLine .= ", p.ref, p.label";
1037 $sqlSourceLine .= " FROM ".MAIN_DB_PREFIX.$this->linkedObjectsIds[0]['type']."det as st";
1038 $sqlSourceLine .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON st.fk_product = p.rowid";
1039 $sqlSourceLine .= " WHERE fk_".$this->linked_objects[0]['type']." = ".((int) $this->linked_objects[0]['linkid']);
1040
1041 $resultSourceLine = $this->db->query($sqlSourceLine);
1042 if ($resultSourceLine) {
1043 $num_lines = $this->db->num_rows($resultSourceLine);
1044 $i = 0;
1045 $array = array();
1046 while ($i < $num_lines) {
1047 $objSourceLine = $this->db->fetch_object($resultSourceLine);
1048
1049 // Get lines of sources already delivered
1050 $sql = "SELECT ld.fk_origin_line, sum(ld.qty) as qty";
1051 $sql .= " FROM ".MAIN_DB_PREFIX."deliverydet as ld, ".MAIN_DB_PREFIX."delivery as l,";
1052 $sql .= " ".MAIN_DB_PREFIX.$this->linked_objects[0]['type']." as c";
1053 $sql .= ", ".MAIN_DB_PREFIX.$this->linked_objects[0]['type']."det as cd";
1054 $sql .= " WHERE ld.fk_delivery = l.rowid";
1055 $sql .= " AND ld.fk_origin_line = cd.rowid";
1056 $sql .= " AND cd.fk_".$this->linked_objects[0]['type']." = c.rowid";
1057 $sql .= " AND cd.fk_".$this->linked_objects[0]['type']." = ".((int) $this->linked_objects[0]['linkid']);
1058 $sql .= " AND ld.fk_origin_line = ".((int) $objSourceLine->rowid);
1059 $sql .= " GROUP BY ld.fk_origin_line";
1060
1061 $result = $this->db->query($sql);
1062 $row = $this->db->fetch_row($result);
1063
1064 if ($objSourceLine->qty - $row[1] > 0) {
1065 if ($row[0] == $objSourceLine->rowid) {
1066 $array[$i]['qty'] = $objSourceLine->qty - $row[1];
1067 } else {
1068 $array[$i]['qty'] = $objSourceLine->qty;
1069 }
1070
1071 $array[$i]['ref'] = $objSourceLine->ref;
1072 $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
1073 } elseif ($objSourceLine->qty - $row[1] < 0) {
1074 $array[$i]['qty'] = $objSourceLine->qty - $row[1]." Erreur livraison !";
1075 $array[$i]['ref'] = $objSourceLine->ref;
1076 $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
1077 }
1078
1079 $i++;
1080 }
1081 return $array;
1082 } else {
1083 $this->error = $this->db->error()." - sql=$sqlSourceLine";
1084 return -1;
1085 }
1086 }
1087
1095 public function setDeliveryDate($user, $delivery_date)
1096 {
1097 if ($user->hasRight('expedition', 'creer')) {
1098 $sql = "UPDATE ".MAIN_DB_PREFIX."delivery";
1099 $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
1100 $sql .= " WHERE rowid = ".((int) $this->id);
1101
1102 dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
1103 $resql = $this->db->query($sql);
1104 if ($resql) {
1105 $this->date_delivery = $delivery_date;
1106 return 1;
1107 } else {
1108 $this->error = $this->db->error();
1109 return -1;
1110 }
1111 } else {
1112 return -2;
1113 }
1114 }
1115
1126 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1127 {
1128 global $conf, $langs;
1129
1130 $langs->load("deliveries");
1131 $outputlangs->load("products");
1132
1133 if (!dol_strlen($modele)) {
1134 $modele = 'typhon';
1135
1136 if ($this->model_pdf) {
1137 $modele = $this->model_pdf;
1138 } elseif (getDolGlobalString('DELIVERY_ADDON_PDF')) {
1139 $modele = getDolGlobalString('DELIVERY_ADDON_PDF');
1140 }
1141 }
1142
1143 $modelpath = "core/modules/delivery/doc/";
1144
1145 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1146 }
1147
1156 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
1157 {
1158 $tables = array(
1159 'delivery'
1160 );
1161
1162 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
1163 }
1164
1173 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
1174 {
1175 $tables = array(
1176 'deliverydet'
1177 );
1178
1179 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
1180 }
1181}
1182
1183
1188{
1192 public $db;
1193
1197 public $element = 'deliverydet';
1198
1202 public $table_element = 'deliverydet';
1203
1207 public $label;
1208
1212 public $description;
1213
1219 public $ref;
1225 public $libelle;
1226
1227 // From llx_expeditiondet
1231 public $qty;
1232
1236 public $qty_asked;
1237
1241 public $qty_shipped;
1242
1246 public $fk_product;
1250 public $product_desc;
1254 public $product_type;
1258 public $product_ref;
1262 public $product_label;
1263
1267 public $price;
1268
1272 public $fk_origin_line;
1276 public $origin_id;
1277
1281 public $origin_line_id;
1282
1288 public $commande_ligne_id;
1289
1290
1296 public function __construct($db)
1297 {
1298 $this->db = $db;
1299 }
1300}
$object ref
Definition info.php:90
Class to manage customers orders.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
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.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
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).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Class to manage receptions.
create_line($origin_id, $qty, $fk_product, $description, $array_options=[])
Create a line.
valid($user, $notrigger=0)
Validate object and update stock if option enabled.
__construct($db)
Constructor.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
deleteLine($lineid)
Delete line.
setDeliveryDate($user, $delivery_date)
Set the planned delivery date.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create object on disk.
update_line($id, $array_options=[])
Update a livraison line (only extrafields)
addline($origin_id, $qty, $array_options=[])
Add line.
fetch($id)
Load a delivery receipt.
create($user)
Create delivery receipt in database.
initAsSpecimen()
Initialise an instance with random values.
create_from_sending($user, $sending_id)
Creating the delivery slip from an existing shipment.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getTooltipContentArray($params)
getTooltipContentArray
getLibStatut($mode=0)
Return the label of the status.
LibStatut($status, $mode)
Return the label of a given status.
fetch_lines()
Load lines insto $this->lines.
getRemainingDelivered()
Get data list of Products remaining to be delivered for an order (with qty)
getNomUrl($withpicto=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
Management class of delivery note lines.
__construct($db)
Constructor.
Class to manage Dolibarr database access.
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
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
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($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:162