dolibarr  13.0.2
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-2018 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  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see <https://www.gnu.org/licenses/>.
22  */
23 
30 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
32 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
33 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
34 if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
35 if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
36 
37 
41 class Delivery extends CommonObject
42 {
43  use CommonIncoterm;
44 
48  public $element = "delivery";
49 
53  public $fk_element = "fk_delivery";
54 
58  public $table_element = "delivery";
59 
63  public $table_element_line = "deliverydet";
64 
68  public $picto = 'sending';
69 
73  public $draft;
74 
78  public $socid;
79 
83  public $ref_customer;
84 
88  public $date_delivery;
89 
93  public $date_creation;
94 
98  public $date_valid;
99 
103  public $model_pdf;
104 
105  public $lines = array();
106 
107 
113  public function __construct($db)
114  {
115  $this->db = $db;
116 
117  // List of short language codes for status
118  $this->statuts[-1] = 'StatusDeliveryCanceled';
119  $this->statuts[0] = 'StatusDeliveryDraft';
120  $this->statuts[1] = 'StatusDeliveryValidated';
121  }
122 
129  public function create($user)
130  {
131  global $conf;
132 
133  dol_syslog("Delivery::create");
134 
135  if (empty($this->model_pdf)) $this->model_pdf = $conf->global->DELIVERY_ADDON_PDF;
136 
137  $error = 0;
138 
139  $now = dol_now();
140 
141  /* Delivery note as draft On positionne en mode draft le bon de livraison */
142  $this->draft = 1;
143 
144  $this->user = $user;
145 
146  $this->db->begin();
147 
148  $sql = "INSERT INTO ".MAIN_DB_PREFIX."delivery (";
149  $sql .= "ref";
150  $sql .= ", entity";
151  $sql .= ", fk_soc";
152  $sql .= ", ref_customer";
153  $sql .= ", date_creation";
154  $sql .= ", fk_user_author";
155  $sql .= ", date_delivery";
156  $sql .= ", fk_address";
157  $sql .= ", note_private";
158  $sql .= ", note_public";
159  $sql .= ", model_pdf";
160  $sql .= ", fk_incoterms, location_incoterms";
161  $sql .= ") VALUES (";
162  $sql .= "'(PROV)'";
163  $sql .= ", ".$conf->entity;
164  $sql .= ", ".$this->socid;
165  $sql .= ", '".$this->db->escape($this->ref_customer)."'";
166  $sql .= ", '".$this->db->idate($now)."'";
167  $sql .= ", ".$user->id;
168  $sql .= ", ".($this->date_delivery ? "'".$this->db->idate($this->date_delivery)."'" : "null");
169  $sql .= ", ".($this->fk_delivery_address > 0 ? $this->fk_delivery_address : "null");
170  $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
171  $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
172  $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
173  $sql .= ", ".(int) $this->fk_incoterms;
174  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
175  $sql .= ")";
176 
177  dol_syslog("Delivery::create", LOG_DEBUG);
178  $resql = $this->db->query($sql);
179  if ($resql)
180  {
181  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."delivery");
182 
183  $numref = "(PROV".$this->id.")";
184 
185  $sql = "UPDATE ".MAIN_DB_PREFIX."delivery ";
186  $sql .= "SET ref = '".$this->db->escape($numref)."'";
187  $sql .= " WHERE rowid = ".$this->id;
188 
189  dol_syslog("Delivery::create", LOG_DEBUG);
190  $resql = $this->db->query($sql);
191  if ($resql)
192  {
193  if (!$conf->expedition_bon->enabled)
194  {
195  $commande = new Commande($this->db);
196  $commande->id = $this->commande_id;
197  $commande->fetch_lines();
198  }
199 
200 
201  /*
202  * Inserting products into the database
203  */
204  $num = count($this->lines);
205  for ($i = 0; $i < $num; $i++)
206  {
207  $origin_id = $this->lines[$i]->origin_line_id;
208  if (!$origin_id) $origin_id = $this->lines[$i]->commande_ligne_id; // For backward compatibility
209 
210  if (!$this->create_line($origin_id, $this->lines[$i]->qty, $this->lines[$i]->fk_product, $this->lines[$i]->description))
211  {
212  $error++;
213  }
214  }
215 
216  if (!$error && $this->id && $this->origin_id)
217  {
218  $ret = $this->add_object_linked();
219  if (!$ret)
220  {
221  $error++;
222  }
223 
224  if (!$conf->expedition_bon->enabled)
225  {
226  // TODO standardize status uniformiser les statuts
227  $ret = $this->setStatut(2, $this->origin_id, $this->origin);
228  if (!$ret)
229  {
230  $error++;
231  }
232  }
233  }
234 
235  if (!$error)
236  {
237  $this->db->commit();
238  return $this->id;
239  } else {
240  $error++;
241  $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
242  $this->db->rollback();
243  return -3;
244  }
245  } else {
246  $error++;
247  $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
248  $this->db->rollback();
249  return -2;
250  }
251  } else {
252  $error++;
253  $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
254  $this->db->rollback();
255  return -1;
256  }
257  }
258 
259  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
269  public function create_line($origin_id, $qty, $fk_product, $description)
270  {
271  // phpcs:enable
272  $error = 0;
273  $idprod = $fk_product;
274  $j = 0;
275 
276  $sql = "INSERT INTO ".MAIN_DB_PREFIX."deliverydet (fk_delivery, fk_origin_line,";
277  $sql .= " fk_product, description, qty)";
278  $sql .= " VALUES (".$this->id.",".$origin_id.",";
279  $sql .= " ".($idprod > 0 ? $idprod : "null").",";
280  $sql .= " ".($description ? "'".$this->db->escape($description)."'" : "null").",";
281  $sql .= $qty.")";
282 
283  dol_syslog(get_class($this)."::create_line", LOG_DEBUG);
284  if (!$this->db->query($sql))
285  {
286  $error++;
287  }
288 
289  if ($error == 0)
290  {
291  return 1;
292  }
293  }
294 
301  public function fetch($id)
302  {
303  global $conf;
304 
305  $sql = "SELECT l.rowid, l.fk_soc, l.date_creation, l.date_valid, l.ref, l.ref_customer, l.fk_user_author,";
306  $sql .= " l.total_ht, l.fk_statut, l.fk_user_valid, l.note_private, l.note_public";
307  $sql .= ", l.date_delivery, l.fk_address, l.model_pdf";
308  $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
309  $sql .= ', l.fk_incoterms, l.location_incoterms';
310  $sql .= ", i.libelle as label_incoterms";
311  $sql .= " FROM ".MAIN_DB_PREFIX."delivery as l";
312  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = l.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
313  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON l.fk_incoterms = i.rowid';
314  $sql .= " WHERE l.rowid = ".$id;
315 
316  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
317  $result = $this->db->query($sql);
318  if ($result)
319  {
320  if ($this->db->num_rows($result))
321  {
322  $obj = $this->db->fetch_object($result);
323 
324  $this->id = $obj->rowid;
325  $this->date_delivery = $this->db->jdate($obj->date_delivery);
326  $this->date_creation = $this->db->jdate($obj->date_creation);
327  $this->date_valid = $this->db->jdate($obj->date_valid);
328  $this->ref = $obj->ref;
329  $this->ref_customer = $obj->ref_customer;
330  $this->socid = $obj->fk_soc;
331  $this->statut = $obj->fk_statut;
332  $this->user_author_id = $obj->fk_user_author;
333  $this->user_valid_id = $obj->fk_user_valid;
334  $this->fk_delivery_address = $obj->fk_address;
335  $this->note = $obj->note_private; //TODO deprecated
336  $this->note_private = $obj->note_private;
337  $this->note_public = $obj->note_public;
338  $this->model_pdf = $obj->model_pdf;
339  $this->modelpdf = $obj->model_pdf; // deprecated
340  $this->origin = $obj->origin; // May be 'shipping'
341  $this->origin_id = $obj->origin_id; // May be id of shipping
342 
343  //Incoterms
344  $this->fk_incoterms = $obj->fk_incoterms;
345  $this->location_incoterms = $obj->location_incoterms;
346  $this->label_incoterms = $obj->label_incoterms;
347  $this->db->free($result);
348 
349  if ($this->statut == 0) $this->draft = 1;
350 
351  // Retrieve all extrafields
352  // fetch optionals attributes and labels
353  $this->fetch_optionals();
354 
355  // Load lines
356  $result = $this->fetch_lines();
357  if ($result < 0)
358  {
359  return -3;
360  }
361 
362  return 1;
363  } else {
364  $this->error = 'Delivery with id '.$id.' not found sql='.$sql;
365  dol_syslog(get_class($this).'::fetch Error '.$this->error, LOG_ERR);
366  return -2;
367  }
368  } else {
369  $this->error = $this->db->error();
370  return -1;
371  }
372  }
373 
381  public function valid($user, $notrigger = 0)
382  {
383  global $conf, $langs;
384  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
385 
386  dol_syslog(get_class($this)."::valid begin");
387 
388  $this->db->begin();
389 
390  $error = 0;
391 
392  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery->creer))
393  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate)))
394  {
395  if (!empty($conf->global->DELIVERY_ADDON_NUMBER))
396  {
397  // Setting the command numbering module name
398  $modName = $conf->global->DELIVERY_ADDON_NUMBER;
399 
400  if (is_readable(DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php'))
401  {
402  require_once DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php';
403 
404  $now = dol_now();
405 
406  // Retrieving the new reference
407  $objMod = new $modName($this->db);
408  $soc = new Societe($this->db);
409  $soc->fetch($this->socid);
410 
411  if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
412  {
413  $numref = $objMod->delivery_get_num($soc, $this);
414  } else {
415  $numref = $this->ref;
416  }
417  $this->newref = dol_sanitizeFileName($numref);
418 
419  // Test if is not already in valid status. If so, we stop to avoid decrementing the stock twice.
420  $sql = "SELECT ref";
421  $sql .= " FROM ".MAIN_DB_PREFIX."delivery";
422  $sql .= " WHERE ref = '".$this->db->escape($numref)."'";
423  $sql .= " AND fk_statut <> 0";
424  $sql .= " AND entity = ".$conf->entity;
425 
426  $resql = $this->db->query($sql);
427  if ($resql)
428  {
429  $num = $this->db->num_rows($resql);
430  if ($num > 0)
431  {
432  return 0;
433  }
434  }
435 
436  $sql = "UPDATE ".MAIN_DB_PREFIX."delivery SET";
437  $sql .= " ref='".$this->db->escape($numref)."'";
438  $sql .= ", fk_statut = 1";
439  $sql .= ", date_valid = '".$this->db->idate($now)."'";
440  $sql .= ", fk_user_valid = ".$user->id;
441  $sql .= " WHERE rowid = ".$this->id;
442  $sql .= " AND fk_statut = 0";
443 
444  $resql = $this->db->query($sql);
445  if (!$resql)
446  {
447  dol_print_error($this->db);
448  $this->error = $this->db->lasterror();
449  $error++;
450  }
451 
452  if (!$error && !$notrigger)
453  {
454  // Call trigger
455  $result = $this->call_trigger('DELIVERY_VALIDATE', $user);
456  if ($result < 0) $error++;
457  // End call triggers
458  }
459 
460  if (!$error)
461  {
462  $this->oldref = $this->ref;
463 
464  // Rename directory if dir was a temporary ref
465  if (preg_match('/^[\(]?PROV/i', $this->ref))
466  {
467  // Now we rename also files into index
468  $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)."'";
469  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/receipt/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
470  $resql = $this->db->query($sql);
471  if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
472 
473  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
474  $oldref = dol_sanitizeFileName($this->ref);
475  $newref = dol_sanitizeFileName($numref);
476  $dirsource = $conf->expedition->dir_output.'/receipt/'.$oldref;
477  $dirdest = $conf->expedition->dir_output.'/receipt/'.$newref;
478  if (!$error && file_exists($dirsource))
479  {
480  dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
481 
482  if (@rename($dirsource, $dirdest))
483  {
484  dol_syslog("Rename ok");
485  // Rename docs starting with $oldref with $newref
486  $listoffiles = dol_dir_list($conf->expedition->dir_output.'/receipt/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
487  foreach ($listoffiles as $fileentry)
488  {
489  $dirsource = $fileentry['name'];
490  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
491  $dirsource = $fileentry['path'].'/'.$dirsource;
492  $dirdest = $fileentry['path'].'/'.$dirdest;
493  @rename($dirsource, $dirdest);
494  }
495  }
496  }
497  }
498 
499  // Set new ref and current status
500  if (!$error)
501  {
502  $this->ref = $numref;
503  $this->statut = 1;
504  }
505 
506  dol_syslog(get_class($this)."::valid ok");
507  }
508 
509  if (!$error)
510  {
511  $this->db->commit();
512  return 1;
513  } else {
514  $this->db->rollback();
515  return -1;
516  }
517  }
518  }
519  } else {
520  $this->error = "Non autorise";
521  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
522  return -1;
523  }
524  }
525 
526  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
534  public function create_from_sending($user, $sending_id)
535  {
536  // phpcs:enable
537  $expedition = new Expedition($this->db);
538  $result = $expedition->fetch($sending_id);
539 
540  $this->lines = array();
541 
542  $num = count($expedition->lines);
543  for ($i = 0; $i < $num; $i++)
544  {
545  $line = new DeliveryLine($this->db);
546  $line->origin_line_id = $expedition->lines[$i]->origin_line_id;
547  $line->label = $expedition->lines[$i]->label;
548  $line->description = $expedition->lines[$i]->description;
549  $line->qty = $expedition->lines[$i]->qty_shipped;
550  $line->fk_product = $expedition->lines[$i]->fk_product;
551 
552  $this->lines[$i] = $line;
553  }
554 
555  $this->origin = $expedition->element;
556  $this->origin_id = $expedition->id;
557  $this->note_private = $expedition->note_private;
558  $this->note_public = $expedition->note_public;
559  $this->fk_project = $expedition->fk_project;
560  $this->date_delivery = $expedition->date_delivery;
561  $this->fk_delivery_address = $expedition->fk_delivery_address;
562  $this->socid = $expedition->socid;
563  $this->ref_customer = $expedition->ref_customer;
564 
565  //Incoterms
566  $this->fk_incoterms = $expedition->fk_incoterms;
567  $this->location_incoterms = $expedition->location_incoterms;
568 
569  return $this->create($user);
570  }
571 
572  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
580  public function update_line($id, $array_options = 0)
581  {
582  // phpcs:enable
583  global $conf;
584  $error = 0;
585 
586  if ($id > 0 && !$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used
587  {
588  $line = new DeliveryLine($this->db);
589  $line->array_options = $array_options;
590  $line->id = $id;
591  $result = $line->insertExtraFields();
592 
593  if ($result < 0)
594  {
595  $this->error[] = $line->error;
596  $error++;
597  }
598  }
599 
600  if (!$error) return 1;
601  else return -1;
602  }
603 
604 
612  public function addline($origin_id, $qty)
613  {
614  $num = count($this->lines);
615  $line = new DeliveryLine($this->db);
616 
617  $line->origin_id = $origin_id;
618  $line->qty = $qty;
619 
620  $this->lines[$num] = $line;
621  }
622 
629  public function deleteline($lineid)
630  {
631  if ($this->statut == 0)
632  {
633  $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
634  $sql .= " WHERE rowid = ".$lineid;
635 
636  if ($this->db->query($sql))
637  {
638  $this->update_price();
639 
640  return 1;
641  } else {
642  return 0;
643  }
644  }
645  }
646 
652  public function delete()
653  {
654  global $conf, $langs, $user;
655 
656  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
657  $this->db->begin();
658 
659  $error = 0;
660 
661  $sql = "DELETE FROM ".MAIN_DB_PREFIX."deliverydet";
662  $sql .= " WHERE fk_delivery = ".$this->id;
663  if ($this->db->query($sql))
664  {
665  // Delete linked object
666  $res = $this->deleteObjectLinked();
667  if ($res < 0) $error++;
668 
669  if (!$error)
670  {
671  $sql = "DELETE FROM ".MAIN_DB_PREFIX."delivery";
672  $sql .= " WHERE rowid = ".$this->id;
673  if ($this->db->query($sql))
674  {
675  $this->db->commit();
676 
677  // Deleting pdf folder's draft On efface le repertoire de pdf provisoire
678  $ref = dol_sanitizeFileName($this->ref);
679  if (!empty($conf->expedition->dir_output))
680  {
681  $dir = $conf->expedition->dir_output.'/receipt/'.$ref;
682  $file = $dir.'/'.$ref.'.pdf';
683  if (file_exists($file))
684  {
685  if (!dol_delete_file($file))
686  {
687  return 0;
688  }
689  }
690  if (file_exists($dir))
691  {
692  if (!dol_delete_dir($dir))
693  {
694  $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
695  return 0;
696  }
697  }
698  }
699 
700  // Call trigger
701  $result = $this->call_trigger('DELIVERY_DELETE', $user);
702  if ($result < 0)
703  {
704  $this->db->rollback();
705  return -4;
706  }
707  // End call triggers
708 
709  return 1;
710  } else {
711  $this->error = $this->db->lasterror()." - sql=$sql";
712  $this->db->rollback();
713  return -3;
714  }
715  } else {
716  $this->error = $this->db->lasterror()." - sql=$sql";
717  $this->db->rollback();
718  return -2;
719  }
720  } else {
721  $this->error = $this->db->lasterror()." - sql=$sql";
722  $this->db->rollback();
723  return -1;
724  }
725  }
726 
734  public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1)
735  {
736  global $langs;
737 
738  $result = '';
739 
740  $label = img_picto('', $this->picto).' <u>'.$langs->trans("ShowReceiving").'</u>:<br>';
741  $label .= '<b>'.$langs->trans("Status").'</b>: '.$this->ref;
742 
743  $url = DOL_URL_ROOT.'/delivery/card.php?id='.$this->id;
744 
745  //if ($option !== 'nolink')
746  //{
747  // Add param to save lastsearch_values or not
748  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
749  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
750  if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
751  //}
752 
753 
754  $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
755  $linkend = '</a>';
756 
757  if ($withpicto) $result .= ($linkstart.img_object($label, $this->picto, 'class="classfortooltip"').$linkend);
758  if ($withpicto && $withpicto != 2) $result .= ' ';
759  $result .= $linkstart.$this->ref.$linkend;
760  return $result;
761  }
762 
763  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
769  public function fetch_lines()
770  {
771  // phpcs:enable
772  $this->lines = array();
773 
774  $sql = "SELECT ld.rowid, ld.fk_product, ld.description, ld.subprice, ld.total_ht, ld.qty as qty_shipped, ld.fk_origin_line, ";
775  $sql .= " cd.qty as qty_asked, cd.label as custom_label, cd.fk_unit,";
776  $sql .= " p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc,";
777  $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";
778  $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."deliverydet as ld";
779  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on p.rowid = ld.fk_product";
780  $sql .= " WHERE ld.fk_origin_line = cd.rowid";
781  $sql .= " AND ld.fk_delivery = ".$this->id;
782 
783  dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
784  $resql = $this->db->query($sql);
785  if ($resql)
786  {
787  $num = $this->db->num_rows($resql);
788  $i = 0;
789  while ($i < $num)
790  {
791  $line = new DeliveryLine($this->db);
792 
793  $obj = $this->db->fetch_object($resql);
794 
795  $line->id = $obj->rowid;
796  $line->label = $obj->custom_label;
797  $line->description = $obj->description;
798  $line->fk_product = $obj->fk_product;
799  $line->qty_asked = $obj->qty_asked;
800  $line->qty_shipped = $obj->qty_shipped;
801 
802  $line->ref = $obj->product_ref; // deprecated
803  $line->libelle = $obj->product_label; // deprecated
804  $line->product_label = $obj->product_label; // Product label
805  $line->product_ref = $obj->product_ref; // Product ref
806  $line->product_desc = $obj->product_desc; // Product description
807  $line->product_type = $obj->fk_product_type;
808  $line->fk_origin_line = $obj->fk_origin_line;
809 
810  $line->price = $obj->price;
811  $line->total_ht = $obj->total_ht;
812 
813  // units
814  $line->weight = $obj->weight;
815  $line->weight_units = $obj->weight_units;
816  $line->width = $obj->width;
817  $line->width_units = $obj->width_units;
818  $line->height = $obj->height;
819  $line->height_units = $obj->height_units;
820  $line->length = $obj->length;
821  $line->length_units = $obj->length_units;
822  $line->surface = $obj->surface;
823  $line->surface_units = $obj->surface_units;
824  $line->volume = $obj->volume;
825  $line->volume_units = $obj->volume_units;
826 
827  $line->fk_unit = $obj->fk_unit;
828  $line->fetch_optionals();
829 
830  $this->lines[$i] = $line;
831 
832  $i++;
833  }
834  $this->db->free($resql);
835  }
836 
837  return $this->lines;
838  }
839 
840 
847  public function getLibStatut($mode = 0)
848  {
849  return $this->LibStatut($this->statut, $mode);
850  }
851 
852  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
860  public function LibStatut($status, $mode)
861  {
862  // phpcs:enable
863  global $langs;
864 
865  if (empty($this->labelStatus) || empty($this->labelStatusShort))
866  {
867  global $langs;
868  //$langs->load("mymodule");
869  $this->labelStatus[-1] = $langs->trans('StatusDeliveryCanceled');
870  $this->labelStatus[0] = $langs->trans('StatusDeliveryDraft');
871  $this->labelStatus[1] = $langs->trans('StatusDeliveryValidated');
872  $this->labelStatusShort[-1] = $langs->trans('StatusDeliveryCanceled');
873  $this->labelStatusShort[0] = $langs->trans('StatusDeliveryDraft');
874  $this->labelStatusShort[1] = $langs->trans('StatusDeliveryValidated');
875  }
876 
877  $statusType = 'status0';
878  if ($status == -1) $statusType = 'status5';
879  if ($status == 1) $statusType = 'status4';
880 
881  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
882  }
883 
884 
892  public function initAsSpecimen()
893  {
894  global $user, $langs, $conf;
895 
896  $now = dol_now();
897 
898  // Load array of products prodids
899  $num_prods = 0;
900  $prodids = array();
901  $sql = "SELECT rowid";
902  $sql .= " FROM ".MAIN_DB_PREFIX."product";
903  $sql .= " WHERE entity IN (".getEntity('product').")";
904  $sql .= " AND tosell = 1";
905  $sql .= $this->db->plimit(100);
906 
907  $resql = $this->db->query($sql);
908  if ($resql)
909  {
910  $num_prods = $this->db->num_rows($resql);
911  $i = 0;
912  while ($i < $num_prods)
913  {
914  $i++;
915  $row = $this->db->fetch_row($resql);
916  $prodids[$i] = $row[0];
917  }
918  }
919 
920  // Initialise parametres
921  $this->id = 0;
922  $this->ref = 'SPECIMEN';
923  $this->specimen = 1;
924  $this->socid = 1;
925  $this->date_delivery = $now;
926  $this->note_public = 'Public note';
927  $this->note_private = 'Private note';
928 
929  $i = 0;
930  $line = new DeliveryLine($this->db);
931  $line->fk_product = $prodids[0];
932  $line->qty_asked = 10;
933  $line->qty_shipped = 9;
934  $line->ref = 'REFPROD';
935  $line->label = 'Specimen';
936  $line->description = 'Description';
937  $line->price = 100;
938  $line->total_ht = 100;
939 
940  $this->lines[$i] = $line;
941  }
942 
949  public function getRemainingDelivered()
950  {
951  global $langs;
952 
953  // Get the linked object
954  $this->fetchObjectLinked('', '', $this->id, $this->element);
955  //var_dump($this->linkedObjectsIds);
956  // Get the product ref and qty in source
957  $sqlSourceLine = "SELECT st.rowid, st.description, st.qty";
958  $sqlSourceLine .= ", p.ref, p.label";
959  $sqlSourceLine .= " FROM ".MAIN_DB_PREFIX.$this->linkedObjectsIds[0]['type']."det as st";
960  $sqlSourceLine .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON st.fk_product = p.rowid";
961  $sqlSourceLine .= " WHERE fk_".$this->linked_object[0]['type']." = ".$this->linked_object[0]['linkid'];
962 
963  $resultSourceLine = $this->db->query($sqlSourceLine);
964  if ($resultSourceLine)
965  {
966  $num_lines = $this->db->num_rows($resultSourceLine);
967  $i = 0;
968  $resultArray = array();
969  while ($i < $num_lines)
970  {
971  $objSourceLine = $this->db->fetch_object($resultSourceLine);
972 
973  // Get lines of sources alread delivered
974  $sql = "SELECT ld.fk_origin_line, sum(ld.qty) as qty";
975  $sql .= " FROM ".MAIN_DB_PREFIX."deliverydet as ld, ".MAIN_DB_PREFIX."delivery as l,";
976  $sql .= " ".MAIN_DB_PREFIX.$this->linked_object[0]['type']." as c";
977  $sql .= ", ".MAIN_DB_PREFIX.$this->linked_object[0]['type']."det as cd";
978  $sql .= " WHERE ld.fk_delivery = l.rowid";
979  $sql .= " AND ld.fk_origin_line = cd.rowid";
980  $sql .= " AND cd.fk_".$this->linked_object[0]['type']." = c.rowid";
981  $sql .= " AND cd.fk_".$this->linked_object[0]['type']." = ".$this->linked_object[0]['linkid'];
982  $sql .= " AND ld.fk_origin_line = ".$objSourceLine->rowid;
983  $sql .= " GROUP BY ld.fk_origin_line";
984 
985  $result = $this->db->query($sql);
986  $row = $this->db->fetch_row($result);
987 
988  if ($objSourceLine->qty - $row[1] > 0)
989  {
990  if ($row[0] == $objSourceLine->rowid)
991  {
992  $array[$i]['qty'] = $objSourceLine->qty - $row[1];
993  } else {
994  $array[$i]['qty'] = $objSourceLine->qty;
995  }
996 
997  $array[$i]['ref'] = $objSourceLine->ref;
998  $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
999  } elseif ($objSourceLine->qty - $row[1] < 0)
1000  {
1001  $array[$i]['qty'] = $objSourceLine->qty - $row[1]." Erreur livraison !";
1002  $array[$i]['ref'] = $objSourceLine->ref;
1003  $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
1004  }
1005 
1006  $i++;
1007  }
1008  return $array;
1009  } else {
1010  $this->error = $this->db->error()." - sql=$sqlSourceLine";
1011  return -1;
1012  }
1013  }
1014 
1022  public function setDeliveryDate($user, $delivery_date)
1023  {
1024  if ($user->rights->expedition->creer)
1025  {
1026  $sql = "UPDATE ".MAIN_DB_PREFIX."delivery";
1027  $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
1028  $sql .= " WHERE rowid = ".$this->id;
1029 
1030  dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
1031  $resql = $this->db->query($sql);
1032  if ($resql)
1033  {
1034  $this->date_delivery = $delivery_date;
1035  return 1;
1036  } else {
1037  $this->error = $this->db->error();
1038  return -1;
1039  }
1040  } else {
1041  return -2;
1042  }
1043  }
1044 
1055  public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1056  {
1057  global $conf, $user, $langs;
1058 
1059  $langs->load("deliveries");
1060  $outputlangs->load("products");
1061 
1062  if (!dol_strlen($modele)) {
1063  $modele = 'typhon';
1064 
1065  if ($this->model_pdf) {
1066  $modele = $this->model_pdf;
1067  } elseif (!empty($conf->global->DELIVERY_ADDON_PDF)) {
1068  $modele = $conf->global->DELIVERY_ADDON_PDF;
1069  }
1070  }
1071 
1072  $modelpath = "core/modules/delivery/doc/";
1073 
1074  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1075  }
1076 
1085  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
1086  {
1087  $tables = array(
1088  'delivery'
1089  );
1090 
1091  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1092  }
1093 }
1094 
1095 
1096 
1101 {
1105  public $db;
1106 
1110  public $element = 'deliverydet';
1111 
1115  public $table_element = 'deliverydet';
1116 
1117  // From llx_expeditiondet
1118  public $qty;
1119  public $qty_asked;
1120  public $qty_shipped;
1121  public $price;
1122  public $fk_product;
1123  public $origin_id;
1124 
1128  public $label;
1129 
1133  public $description;
1134 
1139  public $ref;
1144  public $libelle;
1145 
1146  public $origin_line_id;
1147 
1148  public $product_ref;
1149  public $product_label;
1150 
1156  public function __construct($db)
1157  {
1158  $this->db = $db;
1159  }
1160 }
__construct($db)
Constructor.
Class to manage receptions.
__construct($db)
Constructor.
valid($user, $notrigger=0)
Validate object and update stock if option enabled.
if(!empty($arrayfields['u.datec']['checked'])) print_liste_field_titre("DateCreationShort"u if(!empty($arrayfields['u.tms']['checked'])) print_liste_field_titre("DateModificationShort"u if(!empty($arrayfields['u.statut']['checked'])) print_liste_field_titre("Status"u statut
Definition: list.php:632
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getNomUrl($withpicto=0, $save_lastsearch_value=-1)
Return clicable name (with picto eventually)
</td > param sortfield sortorder printFieldListOption< tdclass="liste_titremaxwidthsearchright"></td ></tr >< trclass="liste_titre">< inputtype="checkbox"onClick="toggle(this)"/> Ref p ref Label p label Duration p duration center DesiredStock p desiredstock right StockLimitShort p seuil_stock_alerte right stock_physique right stock_real_warehouse right Ordered right StockToBuy right SupplierRef right param sortfield sortorder printFieldListTitle warehouseinternal SELECT description FROM product_lang WHERE qty< br > qty qty qty StockTooLow StockTooLow help help help< trclass="oddeven">< td >< inputtype="checkbox"class="check"name="choose'.$i.'"></td >< tdclass="nowrap"> stock</td >< td >< inputtype="hidden"name="desc'.$i.'"value="'.dol_escape_htmltag($objp-> description
Only used if Module[ID]Desc translation string is not found.
Definition: replenish.php:750
create($user)
Create delivery receipt in database.
dol_now($mode= 'auto')
Return date for now.
getLibStatut($mode=0)
Retourne le libelle du statut d&#39;une expedition.
Management class of delivery note lines.
Class to manage Dolibarr database access.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
generateDocument($modele, $outputlangs= '', $hidedetails=0, $hidedesc=0, $hideref=0)
Create object on disk.
LibStatut($status, $mode)
Renvoi le libelle d&#39;un statut donne.
initAsSpecimen()
Initialise an instance with random values.
$conf db
API class for accounts.
Definition: inc.php:54
setDeliveryDate($user, $delivery_date)
Set the planned delivery date.
fetch_lines()
Load lines.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
update_line($id, $array_options=0)
Update a livraison line (only extrafields)
Class to manage third parties objects (customers, suppliers, prospects...)
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
$conf db user
Definition: repair.php:109
getRemainingDelivered()
Renvoie la quantite de produit restante a livrer pour une commande.
addline($origin_id, $qty)
Add line.
Class to manage shipments.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
Class to manage customers orders.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
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). ...
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
Definition: files.lib.php:1144
deleteline($lineid)
Delete line.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
deleteObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $rowid= '')
Delete all links between an object $this.
print $_SERVER["PHP_SELF"]
Edit parameters.
trait CommonIncoterm
Superclass for incoterm classes.
call_trigger($triggerName, $user)
Call trigger based on this instance.
create_line($origin_id, $qty, $fk_product, $description)
Create a line.
fetch($id)
Load a delivery receipt.
setStatut($status, $elementId=null, $elementType= '', $trigkey= '')
Set status of an object.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
create_from_sending($user, $sending_id)
Creating the delivery slip from an existing shipment.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
add_object_linked($origin=null, $origin_id=null)
Add objects linked in llx_element_element.
dol_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
Definition: files.lib.php:1262
update_price($exclspec=0, $roundingadjust= 'none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines)...
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
if(!empty($search_group)) natural_search(array("g.nom"g note
Definition: list.php:122
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...