dolibarr 21.0.0-alpha
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 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 $resql = $this->db->query($sql);
200 if ($resql) {
201 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."delivery");
202
203 $numref = "(PROV".$this->id.")";
204
205 $sql = "UPDATE ".MAIN_DB_PREFIX."delivery ";
206 $sql .= "SET ref = '".$this->db->escape($numref)."'";
207 $sql .= " WHERE rowid = ".((int) $this->id);
208
209 dol_syslog("Delivery::create", LOG_DEBUG);
210 $resql = $this->db->query($sql);
211 if ($resql) {
212 if (!getDolGlobalInt('MAIN_SUBMODULE_EXPEDITION')) {
213 $commande = new Commande($this->db);
214 $commande->id = $this->commande_id;
215 $commande->fetch_lines();
216 }
217
218
219 /*
220 * Inserting products into the database
221 */
222 $num = count($this->lines);
223 for ($i = 0; $i < $num; $i++) {
224 $origin_id = $this->lines[$i]->origin_line_id;
225 if (!$origin_id) {
226 $origin_id = $this->lines[$i]->commande_ligne_id; // For backward compatibility
227 }
228
229 if (!$this->create_line($origin_id, $this->lines[$i]->qty, $this->lines[$i]->fk_product, $this->lines[$i]->description, $this->lines[$i]->array_options)) {
230 $error++;
231 }
232 }
233
234 if (!$error && $this->id && $this->origin_id) {
235 $ret = $this->add_object_linked();
236 if (!$ret) {
237 $error++;
238 }
239
240 if (!getDolGlobalInt('MAIN_SUBMODULE_EXPEDITION')) {
241 $ret = $this->setStatut(2, $this->origin_id, $this->origin);
242 if (!$ret) {
243 $error++;
244 }
245 }
246 }
247
248 if (!$error) {
249 $this->db->commit();
250 return $this->id;
251 } else {
252 $error++;
253 $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
254 $this->db->rollback();
255 return -3;
256 }
257 } else {
258 $error++;
259 $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
260 $this->db->rollback();
261 return -2;
262 }
263 } else {
264 $error++;
265 $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
266 $this->db->rollback();
267 return -1;
268 }
269 }
270
271 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
282 public function create_line($origin_id, $qty, $fk_product, $description, $array_options = [])
283 {
284 // phpcs:enable
285 $error = 0;
286
287 $sql = "INSERT INTO ".MAIN_DB_PREFIX."deliverydet (fk_delivery, fk_origin_line,";
288 $sql .= " fk_product, description, qty)";
289 $sql .= " VALUES (".$this->id.",".((int) $origin_id).",";
290 $sql .= " ".($fk_product > 0 ? ((int) $fk_product) : "null").",";
291 $sql .= " ".($description ? "'".$this->db->escape($description)."'" : "null").",";
292 $sql .= (price2num($qty, 'MS')).")";
293
294 dol_syslog(get_class($this)."::create_line", LOG_DEBUG);
295 if (!$this->db->query($sql)) {
296 $error++;
297 }
298
299 $id = $this->db->last_insert_id(MAIN_DB_PREFIX."deliverydet");
300
301 if (is_array($array_options) && count($array_options) > 0) {
302 $line = new DeliveryLine($this->db);
303 $line->id = $id;
304 $line->array_options = $array_options;
305 $result = $line->insertExtraFields();
306 }
307
308 if (!$error) {
309 return 1;
310 }
311
312 return -1;
313 }
314
321 public function fetch($id)
322 {
323 $sql = "SELECT l.rowid, l.fk_soc, l.date_creation, l.date_valid, l.ref, l.ref_customer, l.fk_user_author,";
324 $sql .= " l.total_ht, l.fk_statut, l.fk_user_valid, l.note_private, l.note_public";
325 $sql .= ", l.date_delivery, l.fk_address, l.model_pdf";
326 $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
327 $sql .= ', l.fk_incoterms, l.location_incoterms';
328 $sql .= ", i.libelle as label_incoterms";
329 $sql .= " FROM ".MAIN_DB_PREFIX."delivery as l";
330 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = l.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
331 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON l.fk_incoterms = i.rowid';
332 $sql .= " WHERE l.rowid = ".((int) $id);
333
334 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
335 $result = $this->db->query($sql);
336 if ($result) {
337 if ($this->db->num_rows($result)) {
338 $obj = $this->db->fetch_object($result);
339
340 $this->id = $obj->rowid;
341 $this->date_delivery = $this->db->jdate($obj->date_delivery);
342 $this->date_creation = $this->db->jdate($obj->date_creation);
343 $this->date_valid = $this->db->jdate($obj->date_valid);
344 $this->ref = $obj->ref;
345 $this->ref_customer = $obj->ref_customer;
346 $this->socid = $obj->fk_soc;
347 $this->statut = $obj->fk_statut;
348 $this->status = $obj->fk_statut;
349 $this->user_author_id = $obj->fk_user_author;
350 $this->user_validation_id = $obj->fk_user_valid;
351 $this->fk_delivery_address = $obj->fk_address;
352 $this->note = $obj->note_private; //TODO deprecated
353 $this->note_private = $obj->note_private;
354 $this->note_public = $obj->note_public;
355 $this->model_pdf = $obj->model_pdf;
356 $this->origin = $obj->origin; // May be 'shipping'
357 $this->origin_id = $obj->origin_id; // May be id of shipping
358
359 //Incoterms
360 $this->fk_incoterms = $obj->fk_incoterms;
361 $this->location_incoterms = $obj->location_incoterms;
362 $this->label_incoterms = $obj->label_incoterms;
363 $this->db->free($result);
364
365 if ($this->status == 0) {
366 $this->draft = 1;
367 }
368
369 // Retrieve all extrafields
370 // fetch optionals attributes and labels
371 $this->fetch_optionals();
372
373 // Load lines
374 $result = $this->fetch_lines();
375 if ($result < 0) {
376 return -3;
377 }
378
379 return 1;
380 } else {
381 $this->error = 'Delivery with id '.$id.' not found sql='.$sql;
382 dol_syslog(get_class($this).'::fetch Error '.$this->error, LOG_ERR);
383 return -2;
384 }
385 } else {
386 $this->error = $this->db->error();
387 return -1;
388 }
389 }
390
398 public function valid($user, $notrigger = 0)
399 {
400 global $conf;
401
402 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
403
404 dol_syslog(get_class($this)."::valid begin");
405
406 $this->db->begin();
407
408 $error = 0;
409
410 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'delivery', 'creer'))
411 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('expedition', 'delivery_advance', 'validate'))) {
412 if (getDolGlobalString('DELIVERY_ADDON_NUMBER')) {
413 // Setting the command numbering module name
414 $modName = getDolGlobalString('DELIVERY_ADDON_NUMBER');
415
416 if (is_readable(DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php')) {
417 require_once DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php';
418
419 $now = dol_now();
420
421 // Retrieving the new reference
422 $objMod = new $modName($this->db);
423 '@phan-var-force ModeleNumRefDeliveryOrder $objMod';
424 $soc = new Societe($this->db);
425 $soc->fetch($this->socid);
426
427 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
428 $numref = $objMod->getNextValue($soc, $this);
429 } else {
430 $numref = $this->ref;
431 }
432 $this->newref = dol_sanitizeFileName($numref);
433
434 // Test if is not already in valid status. If so, we stop to avoid decrementing the stock twice.
435 $sql = "SELECT ref";
436 $sql .= " FROM ".MAIN_DB_PREFIX."delivery";
437 $sql .= " WHERE ref = '".$this->db->escape($numref)."'";
438 $sql .= " AND fk_statut <> 0";
439 $sql .= " AND entity = ".((int) $conf->entity);
440
441 $resql = $this->db->query($sql);
442 if ($resql) {
443 $num = $this->db->num_rows($resql);
444 if ($num > 0) {
445 return 0;
446 }
447 }
448
449 $sql = "UPDATE ".MAIN_DB_PREFIX."delivery SET";
450 $sql .= " ref='".$this->db->escape($numref)."'";
451 $sql .= ", fk_statut = 1";
452 $sql .= ", date_valid = '".$this->db->idate($now)."'";
453 $sql .= ", fk_user_valid = ".((int) $user->id);
454 $sql .= " WHERE rowid = ".((int) $this->id);
455 $sql .= " AND fk_statut = 0";
456
457 $resql = $this->db->query($sql);
458 if (!$resql) {
459 dol_print_error($this->db);
460 $this->error = $this->db->lasterror();
461 $error++;
462 }
463
464 if (!$error && !$notrigger) {
465 // Call trigger
466 $result = $this->call_trigger('DELIVERY_VALIDATE', $user);
467 if ($result < 0) {
468 $error++;
469 }
470 // End call triggers
471 }
472
473 if (!$error) {
474 $this->oldref = $this->ref;
475
476 // Rename directory if dir was a temporary ref
477 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
478 // Now we rename also files into index
479 $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)."'";
480 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/receipt/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
481 $resql = $this->db->query($sql);
482 if (!$resql) {
483 $error++;
484 $this->error = $this->db->lasterror();
485 }
486 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'expedition/receipt/".$this->db->escape($this->newref)."'";
487 $sql .= " WHERE filepath = 'expedition/receipt/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
488 $resql = $this->db->query($sql);
489 if (!$resql) {
490 $error++;
491 $this->error = $this->db->lasterror();
492 }
493
494 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
495 $oldref = dol_sanitizeFileName($this->ref);
496 $newref = dol_sanitizeFileName($numref);
497 $dirsource = $conf->expedition->dir_output.'/receipt/'.$oldref;
498 $dirdest = $conf->expedition->dir_output.'/receipt/'.$newref;
499 if (!$error && file_exists($dirsource)) {
500 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
501
502 if (@rename($dirsource, $dirdest)) {
503 dol_syslog("Rename ok");
504 // Rename docs starting with $oldref with $newref
505 $listoffiles = dol_dir_list($conf->expedition->dir_output.'/receipt/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
506 foreach ($listoffiles as $fileentry) {
507 $dirsource = $fileentry['name'];
508 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
509 $dirsource = $fileentry['path'].'/'.$dirsource;
510 $dirdest = $fileentry['path'].'/'.$dirdest;
511 @rename($dirsource, $dirdest);
512 }
513 }
514 }
515 }
516
517 // Set new ref and current status
518 if (!$error) {
519 $this->ref = $numref;
520 $this->status = 1;
521 }
522
523 dol_syslog(get_class($this)."::valid ok");
524 }
525
526 if (!$error) {
527 $this->db->commit();
528 return 1;
529 } else {
530 $this->db->rollback();
531 return -1;
532 }
533 }
534 }
535
536 return -1;
537 } else {
538 $this->error = "NotAllowed";
539 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
540 return -1;
541 }
542 }
543
544 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
552 public function create_from_sending($user, $sending_id)
553 {
554 // phpcs:enable
555 global $conf;
556
557 $expedition = new Expedition($this->db);
558 $result = $expedition->fetch($sending_id);
559 if ($result <= 0) {
560 return $result;
561 }
562
563 $this->lines = array();
564
565 $num = count($expedition->lines);
566 for ($i = 0; $i < $num; $i++) {
567 $line = new DeliveryLine($this->db);
568 $line->origin_line_id = $expedition->lines[$i]->origin_line_id;
569 $line->label = $expedition->lines[$i]->label;
570 $line->description = $expedition->lines[$i]->description;
571 $line->qty = $expedition->lines[$i]->qty_shipped;
572 $line->fk_product = $expedition->lines[$i]->fk_product;
573 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
574 $line->array_options = $expedition->lines[$i]->array_options;
575 }
576 $this->lines[$i] = $line;
577 }
578
579 $this->origin = $expedition->element;
580 $this->origin_id = $expedition->id;
581 $this->note_private = $expedition->note_private;
582 $this->note_public = $expedition->note_public;
583 $this->fk_project = $expedition->fk_project;
584 $this->date_delivery = $expedition->date_delivery;
585 $this->fk_delivery_address = $expedition->fk_delivery_address;
586 $this->socid = $expedition->socid;
587 $this->ref_customer = $expedition->ref_customer;
588
589 //Incoterms
590 $this->fk_incoterms = $expedition->fk_incoterms;
591 $this->location_incoterms = $expedition->location_incoterms;
592
593 return $this->create($user);
594 }
595
596 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
604 public function update_line($id, $array_options = [])
605 {
606 // phpcs:enable
607 global $conf;
608 $error = 0;
609
610 if ($id > 0 && !$error && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
611 $line = new DeliveryLine($this->db);
612 $line->array_options = $array_options;
613 $line->id = $id;
614 $result = $line->insertExtraFields();
615
616 if ($result < 0) {
617 $this->errors[] = $line->error;
618 $error++;
619 }
620 }
621
622 if (!$error) {
623 return 1;
624 } else {
625 return -1;
626 }
627 }
628
629
638 public function addline($origin_id, $qty, $array_options = [])
639 {
640 $num = count($this->lines);
641 $line = new DeliveryLine($this->db);
642
643 $line->origin_id = $origin_id;
644 $line->qty = $qty;
645 if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
646 $line->array_options = $array_options;
647 }
648 $this->lines[$num] = $line;
649 }
650
657 public function deleteLine($lineid)
658 {
659 if ($this->status == 0) {
660 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
661 $sql .= " WHERE rowid = ".((int) $lineid);
662
663 if ($this->db->query($sql)) {
664 $this->update_price(1);
665
666 return 1;
667 } else {
668 return -1;
669 }
670 }
671
672 return 0;
673 }
674
681 public function delete($user = null)
682 {
683 global $conf, $langs;
684
685 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
686
687 $this->db->begin();
688
689 $error = 0;
690
691 $sql = "DELETE FROM ".MAIN_DB_PREFIX."deliverydet";
692 $sql .= " WHERE fk_delivery = ".((int) $this->id);
693 if ($this->db->query($sql)) {
694 // Delete linked object
695 $res = $this->deleteObjectLinked();
696 if ($res < 0) {
697 $error++;
698 }
699
700 if (!$error) {
701 $sql = "DELETE FROM ".MAIN_DB_PREFIX."delivery";
702 $sql .= " WHERE rowid = ".((int) $this->id);
703 if ($this->db->query($sql)) {
704 $this->db->commit();
705
706 // Deleting pdf folder's draft On efface le repertoire de pdf provisoire
707 $ref = dol_sanitizeFileName($this->ref);
708 if (!empty($conf->expedition->dir_output)) {
709 $dir = $conf->expedition->dir_output.'/receipt/'.$ref;
710 $file = $dir.'/'.$ref.'.pdf';
711 if (file_exists($file)) {
712 if (!dol_delete_file($file)) {
713 return 0;
714 }
715 }
716 if (file_exists($dir)) {
717 if (!dol_delete_dir($dir)) {
718 $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
719 return 0;
720 }
721 }
722 }
723
724 // Call trigger
725 $result = $this->call_trigger('DELIVERY_DELETE', $user);
726 if ($result < 0) {
727 $this->db->rollback();
728 return -4;
729 }
730 // End call triggers
731
732 return 1;
733 } else {
734 $this->error = $this->db->lasterror()." - sql=$sql";
735 $this->db->rollback();
736 return -3;
737 }
738 } else {
739 $this->error = $this->db->lasterror()." - sql=$sql";
740 $this->db->rollback();
741 return -2;
742 }
743 } else {
744 $this->error = $this->db->lasterror()." - sql=$sql";
745 $this->db->rollback();
746 return -1;
747 }
748 }
749
756 public function getTooltipContentArray($params)
757 {
758 global $langs;
759
760 $langs->load('deliveries');
761
762 $datas = [];
763
764 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').' <u>'.$langs->trans("ShowReceiving").'</u>:<br>';
765 $datas['ref'] = '<b>'.$langs->trans("Ref").'</b>: '.$this->ref;
766
767 return $datas;
768 }
769
777 public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1)
778 {
779 global $langs, $hookmanager;
780
781 $result = '';
782
783 $params = [
784 'id' => $this->id,
785 'objecttype' => $this->element,
786 ];
787 $classfortooltip = 'classfortooltip';
788 $dataparams = '';
789 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
790 $classfortooltip = 'classforajaxtooltip';
791 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
792 $label = '';
793 } else {
794 $label = implode($this->getTooltipContentArray($params));
795 }
796
797 $url = DOL_URL_ROOT.'/delivery/card.php?id='.$this->id;
798
799 //if ($option !== 'nolink')
800 //{
801 // Add param to save lastsearch_values or not
802 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
803 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
804 $add_save_lastsearch_values = 1;
805 }
806 if ($add_save_lastsearch_values) {
807 $url .= '&save_lastsearch_values=1';
808 }
809 //}
810
811 $linkstart = '<a href="'.$url.'"';
812 $linkstart .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
813 $linkstart .= $dataparams.' class="'.$classfortooltip.'">';
814 $linkend = '</a>';
815
816 if ($withpicto) {
817 $result .= ($linkstart.img_object($label, $this->picto, $dataparams.' class="'.$classfortooltip.'"').$linkend);
818 }
819 if ($withpicto && $withpicto != 2) {
820 $result .= ' ';
821 }
822 $result .= $linkstart.$this->ref.$linkend;
823
824 global $action;
825 $hookmanager->initHooks(array($this->element . 'dao'));
826 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
827 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
828 if ($reshook > 0) {
829 $result = $hookmanager->resPrint;
830 } else {
831 $result .= $hookmanager->resPrint;
832 }
833 return $result;
834 }
835
836 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
842 public function fetch_lines()
843 {
844 // phpcs:enable
845 $this->lines = array();
846
847 $sql = "SELECT ld.rowid, ld.fk_product, ld.description, ld.subprice, ld.total_ht, ld.qty as qty_shipped, ld.fk_origin_line, ";
848 $sql .= " cd.qty as qty_asked, cd.label as custom_label, cd.fk_unit,";
849 $sql .= " p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc,";
850 $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";
851 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."deliverydet as ld";
852 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on p.rowid = ld.fk_product";
853 $sql .= " WHERE ld.fk_origin_line = cd.rowid";
854 $sql .= " AND ld.fk_delivery = ".((int) $this->id);
855
856 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
857 $resql = $this->db->query($sql);
858 if ($resql) {
859 $num = $this->db->num_rows($resql);
860 $i = 0;
861 while ($i < $num) {
862 $obj = $this->db->fetch_object($resql);
863
864 $line = new DeliveryLine($this->db);
865
866 $line->id = $obj->rowid;
867 $line->label = $obj->custom_label;
868 $line->description = $obj->description;
869 $line->fk_product = $obj->fk_product;
870 $line->qty_asked = $obj->qty_asked;
871 $line->qty_shipped = $obj->qty_shipped;
872
873 $line->product_label = $obj->product_label; // Product label
874 $line->product_ref = $obj->product_ref; // Product ref
875 $line->product_desc = $obj->product_desc; // Product description
876 $line->product_type = $obj->fk_product_type;
877
878 $line->fk_origin_line = $obj->fk_origin_line;
879
880 $line->price = $obj->subprice;
881 $line->total_ht = $obj->total_ht;
882
883 // units
884 $line->weight = $obj->weight;
885 $line->weight_units = $obj->weight_units;
886 $line->width = $obj->width;
887 $line->width_units = $obj->width_units;
888 $line->height = $obj->height;
889 $line->height_units = $obj->height_units;
890 $line->length = $obj->length;
891 $line->length_units = $obj->length_units;
892 $line->surface = $obj->surface;
893 $line->surface_units = $obj->surface_units;
894 $line->volume = $obj->volume;
895 $line->volume_units = $obj->volume_units;
896
897 $line->fk_unit = $obj->fk_unit;
898 $line->fetch_optionals();
899
900 $this->lines[$i] = $line;
901
902 $i++;
903 }
904 $this->db->free($resql);
905
906 return 1;
907 } else {
908 return -1;
909 }
910 }
911
912
919 public function getLibStatut($mode = 0)
920 {
921 return $this->LibStatut($this->status, $mode);
922 }
923
924 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
932 public function LibStatut($status, $mode)
933 {
934 // phpcs:enable
935 global $langs;
936
937 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
938 global $langs;
939 //$langs->load("mymodule");
940 $this->labelStatus[-1] = $langs->transnoentitiesnoconv('StatusDeliveryCanceled');
941 $this->labelStatus[0] = $langs->transnoentitiesnoconv('StatusDeliveryDraft');
942 $this->labelStatus[1] = $langs->transnoentitiesnoconv('StatusDeliveryValidated');
943 $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv('StatusDeliveryCanceled');
944 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv('StatusDeliveryDraft');
945 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv('StatusDeliveryValidated');
946 }
947
948 $statusType = 'status0';
949 if ($status == -1) {
950 $statusType = 'status5';
951 }
952 if ($status == 1) {
953 $statusType = 'status4';
954 }
955
956 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
957 }
958
959
967 public function initAsSpecimen()
968 {
969 $now = dol_now();
970
971 // Load array of products prodids
972 $num_prods = 0;
973 $prodids = array();
974 $sql = "SELECT rowid";
975 $sql .= " FROM ".MAIN_DB_PREFIX."product";
976 $sql .= " WHERE entity IN (".getEntity('product').")";
977 $sql .= " AND tosell = 1";
978 $sql .= $this->db->plimit(100);
979
980 $resql = $this->db->query($sql);
981 if ($resql) {
982 $num_prods = $this->db->num_rows($resql);
983 $i = 0;
984 while ($i < $num_prods) {
985 $i++;
986 $row = $this->db->fetch_row($resql);
987 $prodids[$i] = $row[0];
988 }
989 }
990
991 // Initialise parameters
992 $this->id = 0;
993 $this->ref = 'SPECIMEN';
994 $this->specimen = 1;
995 $this->socid = 1;
996 $this->date_delivery = $now;
997 $this->note_public = 'Public note';
998 $this->note_private = 'Private note';
999
1000 $i = 0;
1001 $line = new DeliveryLine($this->db);
1002 $line->fk_product = reset($prodids);
1003 $line->qty_asked = 10;
1004 $line->qty_shipped = 9;
1005 $line->product_ref = 'REFPROD';
1006 $line->label = 'Specimen';
1007 $line->description = 'Description';
1008 $line->price = 100;
1009 $line->total_ht = 100;
1010
1011 $this->lines[$i] = $line;
1012
1013 return 1;
1014 }
1015
1022 public function getRemainingDelivered()
1023 {
1024 // Get the linked object
1025 $this->fetchObjectLinked(null, '', $this->id, $this->element);
1026 //var_dump($this->linkedObjectsIds);
1027 // Get the product ref and qty in source
1028 $sqlSourceLine = "SELECT st.rowid, st.description, st.qty";
1029 $sqlSourceLine .= ", p.ref, p.label";
1030 $sqlSourceLine .= " FROM ".MAIN_DB_PREFIX.$this->linkedObjectsIds[0]['type']."det as st";
1031 $sqlSourceLine .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON st.fk_product = p.rowid";
1032 $sqlSourceLine .= " WHERE fk_".$this->linked_objects[0]['type']." = ".((int) $this->linked_objects[0]['linkid']);
1033
1034 $resultSourceLine = $this->db->query($sqlSourceLine);
1035 if ($resultSourceLine) {
1036 $num_lines = $this->db->num_rows($resultSourceLine);
1037 $i = 0;
1038 $array = array();
1039 while ($i < $num_lines) {
1040 $objSourceLine = $this->db->fetch_object($resultSourceLine);
1041
1042 // Get lines of sources already delivered
1043 $sql = "SELECT ld.fk_origin_line, sum(ld.qty) as qty";
1044 $sql .= " FROM ".MAIN_DB_PREFIX."deliverydet as ld, ".MAIN_DB_PREFIX."delivery as l,";
1045 $sql .= " ".MAIN_DB_PREFIX.$this->linked_objects[0]['type']." as c";
1046 $sql .= ", ".MAIN_DB_PREFIX.$this->linked_objects[0]['type']."det as cd";
1047 $sql .= " WHERE ld.fk_delivery = l.rowid";
1048 $sql .= " AND ld.fk_origin_line = cd.rowid";
1049 $sql .= " AND cd.fk_".$this->linked_objects[0]['type']." = c.rowid";
1050 $sql .= " AND cd.fk_".$this->linked_objects[0]['type']." = ".((int) $this->linked_objects[0]['linkid']);
1051 $sql .= " AND ld.fk_origin_line = ".((int) $objSourceLine->rowid);
1052 $sql .= " GROUP BY ld.fk_origin_line";
1053
1054 $result = $this->db->query($sql);
1055 $row = $this->db->fetch_row($result);
1056
1057 if ($objSourceLine->qty - $row[1] > 0) {
1058 if ($row[0] == $objSourceLine->rowid) {
1059 $array[$i]['qty'] = $objSourceLine->qty - $row[1];
1060 } else {
1061 $array[$i]['qty'] = $objSourceLine->qty;
1062 }
1063
1064 $array[$i]['ref'] = $objSourceLine->ref;
1065 $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
1066 } elseif ($objSourceLine->qty - $row[1] < 0) {
1067 $array[$i]['qty'] = $objSourceLine->qty - $row[1]." Erreur livraison !";
1068 $array[$i]['ref'] = $objSourceLine->ref;
1069 $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
1070 }
1071
1072 $i++;
1073 }
1074 return $array;
1075 } else {
1076 $this->error = $this->db->error()." - sql=$sqlSourceLine";
1077 return -1;
1078 }
1079 }
1080
1088 public function setDeliveryDate($user, $delivery_date)
1089 {
1090 if ($user->hasRight('expedition', 'creer')) {
1091 $sql = "UPDATE ".MAIN_DB_PREFIX."delivery";
1092 $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
1093 $sql .= " WHERE rowid = ".((int) $this->id);
1094
1095 dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
1096 $resql = $this->db->query($sql);
1097 if ($resql) {
1098 $this->date_delivery = $delivery_date;
1099 return 1;
1100 } else {
1101 $this->error = $this->db->error();
1102 return -1;
1103 }
1104 } else {
1105 return -2;
1106 }
1107 }
1108
1119 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1120 {
1121 global $conf, $langs;
1122
1123 $langs->load("deliveries");
1124 $outputlangs->load("products");
1125
1126 if (!dol_strlen($modele)) {
1127 $modele = 'typhon';
1128
1129 if ($this->model_pdf) {
1130 $modele = $this->model_pdf;
1131 } elseif (getDolGlobalString('DELIVERY_ADDON_PDF')) {
1132 $modele = getDolGlobalString('DELIVERY_ADDON_PDF');
1133 }
1134 }
1135
1136 $modelpath = "core/modules/delivery/doc/";
1137
1138 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1139 }
1140
1149 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
1150 {
1151 $tables = array(
1152 'delivery'
1153 );
1154
1155 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
1156 }
1157
1166 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
1167 {
1168 $tables = array(
1169 'deliverydet'
1170 );
1171
1172 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
1173 }
1174}
1175
1176
1181{
1185 public $db;
1186
1190 public $element = 'deliverydet';
1191
1195 public $table_element = 'deliverydet';
1196
1200 public $label;
1201
1205 public $description;
1206
1212 public $ref;
1218 public $libelle;
1219
1220 // From llx_expeditiondet
1224 public $qty;
1225
1229 public $qty_asked;
1230
1234 public $qty_shipped;
1235
1239 public $fk_product;
1243 public $product_desc;
1247 public $product_type;
1251 public $product_ref;
1255 public $product_label;
1256
1260 public $price;
1261
1265 public $fk_origin_line;
1269 public $origin_id;
1270
1274 public $origin_line_id;
1275
1281 public $commande_ligne_id;
1282
1283
1289 public function __construct($db)
1290 {
1291 $this->db = $db;
1292 }
1293}
$object ref
Definition info.php:79
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:162
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)
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.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:141