dolibarr  9.0.0
commande.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
6  * Copyright (C) 2010-2016 Juanjo Menent <jmenent@2byte.es>
7  * Copyright (C) 2011 Jean Heimburger <jean@tiaris.info>
8  * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
9  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11  * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
12  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
13  * Copyright (C) 2016-2018 Ferran Marcet <fmarcet@2byte.es>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 3 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program. If not, see <http://www.gnu.org/licenses/>.
27  */
28 
34 include_once DOL_DOCUMENT_ROOT .'/core/class/commonorder.class.php';
35 require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php';
36 require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php';
37 require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php';
38 require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php';
39 
43 class Commande extends CommonOrder
44 {
48  public $element='commande';
49 
53  public $table_element='commande';
54 
58  public $table_element_line = 'commandedet';
59 
60  public $class_element_line = 'OrderLine';
61 
65  public $fk_element = 'fk_commande';
66 
70  public $picto = 'order';
71 
76  public $ismultientitymanaged = 1;
77 
82  public $restrictiononfksoc = 1;
83 
87  protected $table_ref_field = 'ref';
88 
93  public $socid;
94 
95  public $ref_client;
96  public $ref_int;
97  public $contactid;
98 
103  public $statut;
104 
109  public $billed; // billed or not
110 
114  public $brouillon;
115  public $cond_reglement_code;
116 
120  public $fk_account;
121 
126  public $mode_reglement;
127 
132  public $mode_reglement_id;
133 
138  public $mode_reglement_code;
139 
144  public $availability_id;
145 
150  public $availability_code;
151 
156  public $availability;
157 
158  public $demand_reason_id; // Source reason. Why we receive order (after a phone campaign, ...)
159  public $demand_reason_code;
160  public $date; // Date commande
161 
167 
168  public $date_livraison; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
169 
173  public $fk_remise_except;
174 
175  public $remise_percent;
176  public $remise_absolue;
177  public $info_bits;
178  public $rang;
179  public $special_code;
180  public $source; // Order mode. How we received order (by phone, by email, ...)
181  public $extraparams=array();
182 
183  public $linked_objects=array();
184 
185  public $user_author_id;
186  public $user_valid;
187 
191  public $lines = array();
192 
193  // Multicurrency
197  public $fk_multicurrency;
198 
199  public $multicurrency_code;
200  public $multicurrency_tx;
201  public $multicurrency_total_ht;
202  public $multicurrency_total_tva;
203  public $multicurrency_total_ttc;
204 
205  public $oldcopy;
206 
211 
215  const STATUS_CANCELED = -1;
219  const STATUS_DRAFT = 0;
223  const STATUS_VALIDATED = 1;
228  const STATUS_ACCEPTED = 2; // For backward compatibility. Use key STATUS_SHIPMENTONPROCESS instead.
229 
233  const STATUS_CLOSED = 3;
234 
235 
241  function __construct($db)
242  {
243  $this->db = $db;
244 
245  $this->remise = 0;
246  $this->remise_percent = 0;
247 
248  $this->products = array();
249  }
250 
258  function getNextNumRef($soc)
259  {
260  global $langs, $conf;
261  $langs->load("order");
262 
263  if (! empty($conf->global->COMMANDE_ADDON))
264  {
265  $mybool=false;
266 
267  $file = $conf->global->COMMANDE_ADDON.".php";
268  $classname = $conf->global->COMMANDE_ADDON;
269 
270  // Include file with class
271  $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
272  foreach ($dirmodels as $reldir)
273  {
274  $dir = dol_buildpath($reldir."core/modules/commande/");
275 
276  // Load file with numbering class (if found)
277  $mybool|=@include_once $dir.$file;
278  }
279 
280  if ($mybool === false)
281  {
282  dol_print_error('',"Failed to include file ".$file);
283  return '';
284  }
285 
286  $obj = new $classname();
287  $numref = $obj->getNextValue($soc,$this);
288 
289  if ($numref != "")
290  {
291  return $numref;
292  }
293  else
294  {
295  $this->error=$obj->error;
296  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
297  return "";
298  }
299  }
300  else
301  {
302  print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
303  return "";
304  }
305  }
306 
307 
316  function valid($user, $idwarehouse=0, $notrigger=0)
317  {
318  global $conf,$langs;
319  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
320 
321  $error=0;
322 
323  // Protection
324  if ($this->statut == self::STATUS_VALIDATED)
325  {
326  dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
327  return 0;
328  }
329 
330  if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
331  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
332  {
333  $this->error='NotEnoughPermissions';
334  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
335  return -1;
336  }
337 
338  $now=dol_now();
339 
340  $this->db->begin();
341 
342  // Definition du nom de module de numerotation de commande
343  $soc = new Societe($this->db);
344  $soc->fetch($this->socid);
345 
346  // Class of company linked to order
347  $result=$soc->set_as_client();
348 
349  // Define new ref
350  if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
351  {
352  $num = $this->getNextNumRef($soc);
353  }
354  else
355  {
356  $num = $this->ref;
357  }
358  $this->newref = $num;
359 
360  // Validate
361  $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
362  $sql.= " SET ref = '".$num."',";
363  $sql.= " fk_statut = ".self::STATUS_VALIDATED.",";
364  $sql.= " date_valid='".$this->db->idate($now)."',";
365  $sql.= " fk_user_valid = ".$user->id;
366  $sql.= " WHERE rowid = ".$this->id;
367 
368  dol_syslog(get_class($this)."::valid()", LOG_DEBUG);
369  $resql=$this->db->query($sql);
370  if (! $resql)
371  {
372  dol_print_error($this->db);
373  $this->error=$this->db->lasterror();
374  $error++;
375  }
376 
377  if (! $error)
378  {
379  // If stock is incremented on validate order, we must increment it
380  if ($result >= 0 && ! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
381  {
382  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
383  $langs->load("agenda");
384 
385  // Loop on each line
386  $cpt=count($this->lines);
387  for ($i = 0; $i < $cpt; $i++)
388  {
389  if ($this->lines[$i]->fk_product > 0)
390  {
391  $mouvP = new MouvementStock($this->db);
392  $mouvP->origin = &$this;
393  // We decrement stock of product (and sub-products)
394  $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr",$num));
395  if ($result < 0)
396  {
397  $error++;
398  $this->error=$mouvP->error;
399  }
400  }
401  if ($error) break;
402  }
403  }
404  }
405 
406  if (! $error && ! $notrigger)
407  {
408  // Call trigger
409  $result=$this->call_trigger('ORDER_VALIDATE',$user);
410  if ($result < 0) $error++;
411  // End call triggers
412  }
413 
414  if (! $error)
415  {
416  $this->oldref = $this->ref;
417 
418  // Rename directory if dir was a temporary ref
419  if (preg_match('/^[\(]?PROV/i', $this->ref))
420  {
421  // On renomme repertoire ($this->ref = ancienne ref, $num = nouvelle ref)
422  // in order not to lose the attachments
423  $oldref = dol_sanitizeFileName($this->ref);
424  $newref = dol_sanitizeFileName($num);
425  $dirsource = $conf->commande->dir_output.'/'.$oldref;
426  $dirdest = $conf->commande->dir_output.'/'.$newref;
427  if (file_exists($dirsource))
428  {
429  dol_syslog(get_class($this)."::valid() rename dir ".$dirsource." into ".$dirdest);
430 
431  if (@rename($dirsource, $dirdest))
432  {
433  dol_syslog("Rename ok");
434  // Rename docs starting with $oldref with $newref
435  $listoffiles=dol_dir_list($conf->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
436  foreach($listoffiles as $fileentry)
437  {
438  $dirsource=$fileentry['name'];
439  $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
440  $dirsource=$fileentry['path'].'/'.$dirsource;
441  $dirdest=$fileentry['path'].'/'.$dirdest;
442  @rename($dirsource, $dirdest);
443  }
444  }
445  }
446  }
447  }
448 
449  // Set new ref and current status
450  if (! $error)
451  {
452  $this->ref = $num;
453  $this->statut = self::STATUS_VALIDATED;
454  $this->brouillon = 0;
455  }
456 
457  if (! $error)
458  {
459  $this->db->commit();
460  return 1;
461  }
462  else
463  {
464  $this->db->rollback();
465  return -1;
466  }
467  }
468 
469  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
477  function set_draft($user, $idwarehouse=-1)
478  {
479  //phpcs:enable
480  global $conf,$langs;
481 
482  $error=0;
483 
484  // Protection
485  if ($this->statut <= self::STATUS_DRAFT)
486  {
487  return 0;
488  }
489 
490  if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
491  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))))
492  {
493  $this->error='Permission denied';
494  return -1;
495  }
496 
497  $this->db->begin();
498 
499  $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
500  $sql.= " SET fk_statut = ".self::STATUS_DRAFT;
501  $sql.= " WHERE rowid = ".$this->id;
502 
503  dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
504  if ($this->db->query($sql))
505  {
506  // If stock is decremented on validate order, we must reincrement it
507  if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
508  {
509  $result = 0;
510 
511  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
512  $langs->load("agenda");
513 
514  $num=count($this->lines);
515  for ($i = 0; $i < $num; $i++)
516  {
517  if ($this->lines[$i]->fk_product > 0)
518  {
519  $mouvP = new MouvementStock($this->db);
520  $mouvP->origin = &$this;
521  // We increment stock of product (and sub-products)
522  $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr",$this->ref));
523  if ($result < 0) { $error++; $this->error=$mouvP->error; break; }
524  }
525  }
526  }
527 
528  if (!$error) {
529  // Call trigger
530  $result=$this->call_trigger('ORDER_UNVALIDATE',$user);
531  if ($result < 0) $error++;
532  }
533 
534  if (!$error) {
535  $this->statut=self::STATUS_DRAFT;
536  $this->db->commit();
537  return 1;
538  }else {
539  $this->db->rollback();
540  return -1;
541  }
542  }
543  else
544  {
545  $this->error=$this->db->error();
546  $this->db->rollback();
547  return -1;
548  }
549  }
550 
551 
552  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
560  function set_reopen($user)
561  {
562  // phpcs:enable
563  $error=0;
564 
565  if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED)
566  {
567  dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING);
568  return 0;
569  }
570 
571  $this->db->begin();
572 
573  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
574  $sql.= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0';
575  $sql.= ' WHERE rowid = '.$this->id;
576 
577  dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
578  $resql = $this->db->query($sql);
579  if ($resql)
580  {
581  // Call trigger
582  $result=$this->call_trigger('ORDER_REOPEN',$user);
583  if ($result < 0) $error++;
584  // End call triggers
585  }
586  else
587  {
588  $error++;
589  $this->error=$this->db->lasterror();
590  dol_print_error($this->db);
591  }
592 
593  if (! $error)
594  {
595  $this->statut = self::STATUS_VALIDATED;
596  $this->billed = 0;
597 
598  $this->db->commit();
599  return 1;
600  }
601  else
602  {
603  foreach($this->errors as $errmsg)
604  {
605  dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
606  $this->error.=($this->error?', '.$errmsg:$errmsg);
607  }
608  $this->db->rollback();
609  return -1*$error;
610  }
611  }
612 
620  function cloture($user, $notrigger=0)
621  {
622  global $conf;
623 
624  $error=0;
625 
626  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
627  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate)))
628  {
629  $this->db->begin();
630 
631  $now=dol_now();
632 
633  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
634  $sql.= ' SET fk_statut = '.self::STATUS_CLOSED.',';
635  $sql.= ' fk_user_cloture = '.$user->id.',';
636  $sql.= " date_cloture = '".$this->db->idate($now)."'";
637  $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
638 
639  if ($this->db->query($sql))
640  {
641  if (! $notrigger)
642  {
643  // Call trigger
644  $result=$this->call_trigger('ORDER_CLOSE',$user);
645  if ($result < 0) $error++;
646  // End call triggers
647  }
648 
649  if (! $error)
650  {
651  $this->statut=self::STATUS_CLOSED;
652 
653  $this->db->commit();
654  return 1;
655  }
656  else
657  {
658  $this->db->rollback();
659  return -1;
660  }
661  }
662  else
663  {
664  $this->error=$this->db->lasterror();
665 
666  $this->db->rollback();
667  return -1;
668  }
669  }
670  return 0;
671  }
672 
680  function cancel($idwarehouse=-1)
681  {
682  global $conf,$user,$langs;
683 
684  $error=0;
685 
686  $this->db->begin();
687 
688  $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
689  $sql.= " SET fk_statut = ".self::STATUS_CANCELED;
690  $sql.= " WHERE rowid = ".$this->id;
691  $sql.= " AND fk_statut = ".self::STATUS_VALIDATED;
692 
693  dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
694  if ($this->db->query($sql))
695  {
696  // If stock is decremented on validate order, we must reincrement it
697  if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
698  {
699  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
700  $langs->load("agenda");
701 
702  $num=count($this->lines);
703  for ($i = 0; $i < $num; $i++)
704  {
705  if ($this->lines[$i]->fk_product > 0)
706  {
707  $mouvP = new MouvementStock($this->db);
708  // We increment stock of product (and sub-products)
709  $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr",$this->ref)); // price is 0, we don't want WAP to be changed
710  if ($result < 0)
711  {
712  $error++;
713  $this->error=$mouvP->error;
714  break;
715  }
716  }
717  }
718  }
719 
720  if (! $error)
721  {
722  // Call trigger
723  $result=$this->call_trigger('ORDER_CANCEL',$user);
724  if ($result < 0) $error++;
725  // End call triggers
726  }
727 
728  if (! $error)
729  {
730  $this->statut=self::STATUS_CANCELED;
731  $this->db->commit();
732  return 1;
733  }
734  else
735  {
736  foreach($this->errors as $errmsg)
737  {
738  dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
739  $this->error.=($this->error?', '.$errmsg:$errmsg);
740  }
741  $this->db->rollback();
742  return -1*$error;
743  }
744  }
745  else
746  {
747  $this->error=$this->db->error();
748  $this->db->rollback();
749  return -1;
750  }
751  }
752 
761  function create($user, $notrigger=0)
762  {
763  global $conf,$langs;
764  $error=0;
765 
766  // Clean parameters
767  $this->brouillon = 1; // set command as draft
768 
769  // $date_commande is deprecated
770  $date = ($this->date_commande ? $this->date_commande : $this->date);
771 
772  // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
773  if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
774  else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
775  if (empty($this->fk_multicurrency))
776  {
777  $this->multicurrency_code = $conf->currency;
778  $this->fk_multicurrency = 0;
779  $this->multicurrency_tx = 1;
780  }
781 
782  dol_syslog(get_class($this)."::create user=".$user->id);
783 
784  // Check parameters
785  if (! empty($this->ref)) // We check that ref is not already used
786  {
787  $result=self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
788  if ($result > 0)
789  {
790  $this->error='ErrorRefAlreadyExists';
791  dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING);
792  $this->db->rollback();
793  return -1;
794  }
795  }
796 
797  $soc = new Societe($this->db);
798  $result=$soc->fetch($this->socid);
799  if ($result < 0)
800  {
801  $this->error="Failed to fetch company";
802  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
803  return -2;
804  }
805  if (! empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0)
806  {
807  $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Source"));
808  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
809  return -1;
810  }
811 
812  $now=dol_now();
813 
814  $this->db->begin();
815 
816  $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande (";
817  $sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
818  $sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
819  $sql.= ", fk_shipping_method";
820  $sql.= ", fk_warehouse";
821  $sql.= ", remise_absolue, remise_percent";
822  $sql.= ", fk_incoterms, location_incoterms";
823  $sql.= ", entity";
824  $sql.= ", fk_multicurrency";
825  $sql.= ", multicurrency_code";
826  $sql.= ", multicurrency_tx";
827  $sql.= ")";
828  $sql.= " VALUES ('(PROV)', ".$this->socid.", '".$this->db->idate($now)."', ".$user->id;
829  $sql.= ", ".($this->fk_project>0?$this->fk_project:"null");
830  $sql.= ", '".$this->db->idate($date)."'";
831  $sql.= ", ".($this->source>=0 && $this->source != '' ?$this->db->escape($this->source):'null');
832  $sql.= ", '".$this->db->escape($this->note_private)."'";
833  $sql.= ", '".$this->db->escape($this->note_public)."'";
834  $sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null");
835  $sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
836  $sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
837  $sql.= ", '".$this->db->escape($this->modelpdf)."'";
838  $sql.= ", ".($this->cond_reglement_id>0?$this->cond_reglement_id:"null");
839  $sql.= ", ".($this->mode_reglement_id>0?$this->mode_reglement_id:"null");
840  $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
841  $sql.= ", ".($this->availability_id>0?$this->availability_id:"null");
842  $sql.= ", ".($this->demand_reason_id>0?$this->demand_reason_id:"null");
843  $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
844  $sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:'NULL');
845  $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
846  $sql.= ", ".($this->warehouse_id>0?$this->warehouse_id:'NULL');
847  $sql.= ", ".($this->remise_absolue>0?$this->db->escape($this->remise_absolue):'NULL');
848  $sql.= ", ".($this->remise_percent>0?$this->db->escape($this->remise_percent):0);
849  $sql.= ", ".(int) $this->fk_incoterms;
850  $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
851  $sql.= ", ".$conf->entity;
852  $sql.= ", ".(int) $this->fk_multicurrency;
853  $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
854  $sql.= ", ".(double) $this->multicurrency_tx;
855  $sql.= ")";
856 
857  dol_syslog(get_class($this)."::create", LOG_DEBUG);
858  $resql=$this->db->query($sql);
859  if ($resql)
860  {
861  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
862 
863  if ($this->id)
864  {
865  $fk_parent_line=0;
866  $num=count($this->lines);
867 
868  /*
869  * Insert products details into db
870  */
871  for ($i=0;$i<$num;$i++)
872  {
873  $line = $this->lines[$i];
874 
875  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
876  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
877  if (! is_object($line)) $line = (object) $line;
878 
879  // Reset fk_parent_line for no child products and special product
880  if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
881  $fk_parent_line = 0;
882  }
883 
884  // Complete vat rate with code
885  $vatrate = $line->tva_tx;
886  if ($line->vat_src_code && ! preg_match('/\(.*\)/', $vatrate)) $vatrate.=' ('.$line->vat_src_code.')';
887 
888  $result = $this->addline(
889  $line->desc,
890  $line->subprice,
891  $line->qty,
892  $vatrate,
893  $line->localtax1_tx,
894  $line->localtax2_tx,
895  $line->fk_product,
896  $line->remise_percent,
897  $line->info_bits,
898  $line->fk_remise_except,
899  'HT',
900  0,
901  $line->date_start,
902  $line->date_end,
903  $line->product_type,
904  $line->rang,
905  $line->special_code,
906  $fk_parent_line,
907  $line->fk_fournprice,
908  $line->pa_ht,
909  $line->label,
910  $line->array_options,
911  $line->fk_unit,
912  $this->element,
913  $line->id
914  );
915  if ($result < 0)
916  {
917  if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER)
918  {
919  $this->error=$this->db->lasterror();
920  dol_print_error($this->db);
921  }
922  $this->db->rollback();
923  return -1;
924  }
925  // Defined the new fk_parent_line
926  if ($result > 0 && $line->product_type == 9) {
927  $fk_parent_line = $result;
928  }
929  }
930 
931  // update ref
932  $initialref='(PROV'.$this->id.')';
933  if (! empty($this->ref)) $initialref=$this->ref;
934 
935  $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id;
936  if ($this->db->query($sql))
937  {
938  if ($this->id)
939  {
940  $this->ref = $initialref;
941 
942  if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
943  {
944  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
945  }
946 
947  // Add object linked
948  if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
949  {
950  foreach($this->linked_objects as $origin => $tmp_origin_id)
951  {
952  if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
953  {
954  foreach($tmp_origin_id as $origin_id)
955  {
956  $ret = $this->add_object_linked($origin, $origin_id);
957  if (! $ret)
958  {
959  $this->error=$this->db->lasterror();
960  $error++;
961  }
962  }
963  }
964  else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
965  {
966  $origin_id = $tmp_origin_id;
967  $ret = $this->add_object_linked($origin, $origin_id);
968  if (! $ret)
969  {
970  $this->error=$this->db->lasterror();
971  $error++;
972  }
973  }
974  }
975  }
976 
977  if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id)) // Get contact from origin object
978  {
979  $originforcontact = $this->origin;
980  $originidforcontact = $this->origin_id;
981  if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
982  {
983  require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
984  $exp = new Expedition($this->db);
985  $exp->fetch($this->origin_id);
986  $exp->fetchObjectLinked();
987  if (count($exp->linkedObjectsIds['commande']) > 0)
988  {
989  foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
990  {
991  $originforcontact = 'commande';
992  if (is_object($value)) $originidforcontact = $value->id;
993  else $originidforcontact = $value;
994  break; // We take first one
995  }
996  }
997  }
998 
999  $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
1000  $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
1001 
1002  $resqlcontact = $this->db->query($sqlcontact);
1003  if ($resqlcontact)
1004  {
1005  while($objcontact = $this->db->fetch_object($resqlcontact))
1006  {
1007  //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1008  $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
1009  }
1010  }
1011  else dol_print_error($resqlcontact);
1012  }
1013  }
1014 
1015  if (! $error)
1016  {
1017  $result=$this->insertExtraFields();
1018  if ($result < 0) $error++;
1019  }
1020 
1021  if (! $error && ! $notrigger)
1022  {
1023  // Call trigger
1024  $result=$this->call_trigger('ORDER_CREATE',$user);
1025  if ($result < 0) $error++;
1026  // End call triggers
1027  }
1028 
1029  if (! $error)
1030  {
1031  $this->db->commit();
1032  return $this->id;
1033  }
1034  else
1035  {
1036  $this->db->rollback();
1037  return -1*$error;
1038  }
1039  }
1040  else
1041  {
1042  $this->error=$this->db->lasterror();
1043  $this->db->rollback();
1044  return -1;
1045  }
1046  }
1047  }
1048  else
1049  {
1050  dol_print_error($this->db);
1051  $this->db->rollback();
1052  return -1;
1053  }
1054  }
1055 
1056 
1063  function createFromClone($socid=0)
1064  {
1065  global $user,$hookmanager;
1066 
1067  $error=0;
1068 
1069  $this->db->begin();
1070 
1071  // get lines so they will be clone
1072  foreach($this->lines as $line)
1073  $line->fetch_optionals();
1074 
1075  // Load source object
1076  $objFrom = clone $this;
1077 
1078  // Change socid if needed
1079  if (! empty($socid) && $socid != $this->socid)
1080  {
1081  $objsoc = new Societe($this->db);
1082 
1083  if ($objsoc->fetch($socid)>0)
1084  {
1085  $this->socid = $objsoc->id;
1086  $this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1087  $this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1088  $this->fk_project = 0;
1089  $this->fk_delivery_address = 0;
1090  }
1091 
1092  // TODO Change product price if multi-prices
1093  }
1094 
1095  $this->id=0;
1096  $this->ref = '';
1097  $this->statut=self::STATUS_DRAFT;
1098 
1099  // Clear fields
1100  $this->user_author_id = $user->id;
1101  $this->user_valid = '';
1102  $this->date = dol_now();
1103  $this->date_commande = dol_now();
1104  $this->date_creation = '';
1105  $this->date_validation = '';
1106  $this->ref_client = '';
1107 
1108  // Create clone
1109  $this->context['createfromclone'] = 'createfromclone';
1110  $result=$this->create($user);
1111  if ($result < 0) $error++;
1112 
1113  if (! $error)
1114  {
1115  // Hook of thirdparty module
1116  if (is_object($hookmanager))
1117  {
1118  $parameters=array('objFrom'=>$objFrom);
1119  $action='';
1120  $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
1121  if ($reshook < 0) $error++;
1122  }
1123  }
1124 
1125  unset($this->context['createfromclone']);
1126 
1127  // End
1128  if (! $error)
1129  {
1130  $this->db->commit();
1131  return $this->id;
1132  }
1133  else
1134  {
1135  $this->db->rollback();
1136  return -1;
1137  }
1138  }
1139 
1140 
1148  function createFromProposal($object, User $user)
1149  {
1150  global $conf, $hookmanager;
1151 
1152  dol_include_once('/core/class/extrafields.class.php');
1153 
1154  $error=0;
1155 
1156 
1157  $this->date_commande = dol_now();
1158  $this->source = 0;
1159 
1160  $num=count($object->lines);
1161  for ($i = 0; $i < $num; $i++)
1162  {
1163  $line = new OrderLine($this->db);
1164 
1165  $line->libelle = $object->lines[$i]->libelle;
1166  $line->label = $object->lines[$i]->label;
1167  $line->desc = $object->lines[$i]->desc;
1168  $line->price = $object->lines[$i]->price;
1169  $line->subprice = $object->lines[$i]->subprice;
1170  $line->vat_src_code = $object->lines[$i]->vat_src_code;
1171  $line->tva_tx = $object->lines[$i]->tva_tx;
1172  $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1173  $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1174  $line->qty = $object->lines[$i]->qty;
1175  $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1176  $line->remise_percent = $object->lines[$i]->remise_percent;
1177  $line->fk_product = $object->lines[$i]->fk_product;
1178  $line->info_bits = $object->lines[$i]->info_bits;
1179  $line->product_type = $object->lines[$i]->product_type;
1180  $line->rang = $object->lines[$i]->rang;
1181  $line->special_code = $object->lines[$i]->special_code;
1182  $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1183  $line->fk_unit = $object->lines[$i]->fk_unit;
1184 
1185  $line->date_start = $object->lines[$i]->date_start;
1186  $line->date_end = $object->lines[$i]->date_end;
1187 
1188  $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1189  $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
1190  $line->pa_ht = $marginInfos[0];
1191  $line->marge_tx = $marginInfos[1];
1192  $line->marque_tx = $marginInfos[2];
1193 
1194  // get extrafields from original line
1195  $object->lines[$i]->fetch_optionals();
1196  foreach($object->lines[$i]->array_options as $options_key => $value)
1197  $line->array_options[$options_key] = $value;
1198 
1199  $this->lines[$i] = $line;
1200  }
1201 
1202  $this->socid = $object->socid;
1203  $this->fk_project = $object->fk_project;
1204  $this->cond_reglement_id = $object->cond_reglement_id;
1205  $this->mode_reglement_id = $object->mode_reglement_id;
1206  $this->fk_account = $object->fk_account;
1207  $this->availability_id = $object->availability_id;
1208  $this->demand_reason_id = $object->demand_reason_id;
1209  $this->date_livraison = $object->date_livraison;
1210  $this->shipping_method_id = $object->shipping_method_id;
1211  $this->warehouse_id = $object->warehouse_id;
1212  $this->fk_delivery_address = $object->fk_delivery_address;
1213  $this->contact_id = $object->contactid;
1214  $this->ref_client = $object->ref_client;
1215  $this->note_private = $object->note_private;
1216  $this->note_public = $object->note_public;
1217 
1218  $this->origin = $object->element;
1219  $this->origin_id = $object->id;
1220 
1221  // get extrafields from original line
1222  $object->fetch_optionals($object->id);
1223 
1224  $e = new ExtraFields($this->db);
1225  $element_extrafields = $e->fetch_name_optionals_label($this->element);
1226 
1227  foreach($object->array_options as $options_key => $value) {
1228  if(array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)){
1229  $this->array_options[$options_key] = $value;
1230  }
1231  }
1232  // Possibility to add external linked objects with hooks
1233  $this->linked_objects[$this->origin] = $this->origin_id;
1234  if (is_array($object->other_linked_objects) && ! empty($object->other_linked_objects))
1235  {
1236  $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1237  }
1238 
1239  $ret = $this->create($user);
1240 
1241  if ($ret > 0)
1242  {
1243  // Actions hooked (by external module)
1244  $hookmanager->initHooks(array('orderdao'));
1245 
1246  $parameters=array('objFrom'=>$object);
1247  $action='';
1248  $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
1249  if ($reshook < 0) $error++;
1250 
1251  if (! $error)
1252  {
1253  // Ne pas passer par la commande provisoire
1254  if ($conf->global->COMMANDE_VALID_AFTER_CLOSE_PROPAL == 1)
1255  {
1256  $this->fetch($ret);
1257  $this->valid($user);
1258  }
1259  return $ret;
1260  }
1261  else return -1;
1262  }
1263  else return -1;
1264  }
1265 
1266 
1305  function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise = 0)
1306  {
1307  global $mysoc, $conf, $langs, $user;
1308 
1309  $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent";
1310  $logtext.= ", info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start";
1311  $logtext.= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise";
1312  dol_syslog(get_class($this).$logtext, LOG_DEBUG);
1313 
1314  if ($this->statut == self::STATUS_DRAFT)
1315  {
1316  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1317 
1318  // Clean parameters
1319  if (empty($remise_percent)) $remise_percent=0;
1320  if (empty($qty)) $qty=0;
1321  if (empty($info_bits)) $info_bits=0;
1322  if (empty($rang)) $rang=0;
1323  if (empty($txtva)) $txtva=0;
1324  if (empty($txlocaltax1)) $txlocaltax1=0;
1325  if (empty($txlocaltax2)) $txlocaltax2=0;
1326  if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
1327  if (empty($this->fk_multicurrency)) $this->fk_multicurrency=0;
1328 
1329  $remise_percent=price2num($remise_percent);
1330  $qty=price2num($qty);
1331  $pu_ht=price2num($pu_ht);
1332  $pu_ht_devise=price2num($pu_ht_devise);
1333  $pu_ttc=price2num($pu_ttc);
1334  $pa_ht=price2num($pa_ht);
1335  if (!preg_match('/\((.*)\)/', $txtva)) {
1336  $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
1337  }
1338  $txlocaltax1 = price2num($txlocaltax1);
1339  $txlocaltax2 = price2num($txlocaltax2);
1340  if ($price_base_type=='HT')
1341  {
1342  $pu=$pu_ht;
1343  }
1344  else
1345  {
1346  $pu=$pu_ttc;
1347  }
1348  $label=trim($label);
1349  $desc=trim($desc);
1350 
1351  // Check parameters
1352  if ($type < 0) return -1;
1353 
1354  $this->db->begin();
1355 
1356  $product_type=$type;
1357  if (!empty($fk_product))
1358  {
1359  $product=new Product($this->db);
1360  $result=$product->fetch($fk_product);
1361  $product_type=$product->type;
1362 
1363  if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
1364  {
1365  $langs->load("errors");
1366  $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1367  dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
1368  $this->db->rollback();
1369  return self::STOCK_NOT_ENOUGH_FOR_ORDER;
1370  }
1371  }
1372  // Calcul du total TTC et de la TVA pour la ligne a partir de
1373  // qty, pu, remise_percent et txtva
1374  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1375  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1376 
1377  $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc);
1378 
1379  // Clean vat code
1380  $vat_src_code='';
1381  if (preg_match('/\((.*)\)/', $txtva, $reg))
1382  {
1383  $vat_src_code = $reg[1];
1384  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
1385  }
1386 
1387  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1388 
1389  /*var_dump($txlocaltax1);
1390  var_dump($txlocaltax2);
1391  var_dump($localtaxes_type);
1392  var_dump($tabprice);
1393  var_dump($tabprice[9]);
1394  var_dump($tabprice[10]);
1395  exit;*/
1396 
1397  $total_ht = $tabprice[0];
1398  $total_tva = $tabprice[1];
1399  $total_ttc = $tabprice[2];
1400  $total_localtax1 = $tabprice[9];
1401  $total_localtax2 = $tabprice[10];
1402  $pu_ht = $tabprice[3];
1403 
1404  // MultiCurrency
1405  $multicurrency_total_ht = $tabprice[16];
1406  $multicurrency_total_tva = $tabprice[17];
1407  $multicurrency_total_ttc = $tabprice[18];
1408  $pu_ht_devise = $tabprice[19];
1409 
1410  // Rang to use
1411  $rangtouse = $rang;
1412  if ($rangtouse == -1)
1413  {
1414  $rangmax = $this->line_max($fk_parent_line);
1415  $rangtouse = $rangmax + 1;
1416  }
1417 
1418  // TODO A virer
1419  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1420  $price = $pu;
1421  $remise = 0;
1422  if ($remise_percent > 0)
1423  {
1424  $remise = round(($pu * $remise_percent / 100), 2);
1425  $price = $pu - $remise;
1426  }
1427 
1428  // Insert line
1429  $this->line=new OrderLine($this->db);
1430 
1431  $this->line->context = $this->context;
1432 
1433  $this->line->fk_commande=$this->id;
1434  $this->line->label=$label;
1435  $this->line->desc=$desc;
1436  $this->line->qty=$qty;
1437 
1438  $this->line->vat_src_code=$vat_src_code;
1439  $this->line->tva_tx=$txtva;
1440  $this->line->localtax1_tx=($total_localtax1?$localtaxes_type[1]:0);
1441  $this->line->localtax2_tx=($total_localtax2?$localtaxes_type[3]:0);
1442  $this->line->localtax1_type=$localtaxes_type[0];
1443  $this->line->localtax2_type=$localtaxes_type[2];
1444  $this->line->fk_product=$fk_product;
1445  $this->line->product_type=$product_type;
1446  $this->line->fk_remise_except=$fk_remise_except;
1447  $this->line->remise_percent=$remise_percent;
1448  $this->line->subprice=$pu_ht;
1449  $this->line->rang=$rangtouse;
1450  $this->line->info_bits=$info_bits;
1451  $this->line->total_ht=$total_ht;
1452  $this->line->total_tva=$total_tva;
1453  $this->line->total_localtax1=$total_localtax1;
1454  $this->line->total_localtax2=$total_localtax2;
1455  $this->line->total_ttc=$total_ttc;
1456  $this->line->special_code=$special_code;
1457  $this->line->origin=$origin;
1458  $this->line->origin_id=$origin_id;
1459  $this->line->fk_parent_line=$fk_parent_line;
1460  $this->line->fk_unit=$fk_unit;
1461 
1462  $this->line->date_start=$date_start;
1463  $this->line->date_end=$date_end;
1464 
1465  $this->line->fk_fournprice = $fk_fournprice;
1466  $this->line->pa_ht = $pa_ht;
1467 
1468  // Multicurrency
1469  $this->line->fk_multicurrency = $this->fk_multicurrency;
1470  $this->line->multicurrency_code = $this->multicurrency_code;
1471  $this->line->multicurrency_subprice = $pu_ht_devise;
1472  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
1473  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
1474  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
1475 
1476  // TODO Ne plus utiliser
1477  $this->line->price=$price;
1478  $this->line->remise=$remise;
1479 
1480  if (is_array($array_options) && count($array_options)>0) {
1481  $this->line->array_options=$array_options;
1482  }
1483 
1484  $result=$this->line->insert($user);
1485  if ($result > 0)
1486  {
1487  // Reorder if child line
1488  if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1489 
1490  // Mise a jour informations denormalisees au niveau de la commande meme
1491  $result=$this->update_price(1,'auto',0,$mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1492  if ($result > 0)
1493  {
1494  $this->db->commit();
1495  return $this->line->rowid;
1496  }
1497  else
1498  {
1499  $this->db->rollback();
1500  return -1;
1501  }
1502  }
1503  else
1504  {
1505  $this->error=$this->line->error;
1506  dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1507  $this->db->rollback();
1508  return -2;
1509  }
1510  }
1511  else
1512  {
1513  dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
1514  return -3;
1515  }
1516  }
1517 
1518 
1519  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1534  function add_product($idproduct, $qty, $remise_percent=0.0, $date_start='', $date_end='')
1535  {
1536  // phpcs:enable
1537  global $conf, $mysoc;
1538 
1539  if (! $qty) $qty = 1;
1540 
1541  if ($idproduct > 0)
1542  {
1543  $prod=new Product($this->db);
1544  $prod->fetch($idproduct);
1545 
1546  $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id);
1547  $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id);
1548  if (empty($tva_tx)) $tva_npr=0;
1549  $vat_src_code = ''; // May be defined into tva_tx
1550 
1551  $localtax1_tx=get_localtax($tva_tx,1,$this->thirdparty,$mysoc,$tva_npr);
1552  $localtax2_tx=get_localtax($tva_tx,2,$this->thirdparty,$mysoc,$tva_npr);
1553 
1554  // multiprix
1555  if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) {
1556  $price = $prod->multiprices[$this->thirdparty->price_level];
1557  } else {
1558  $price = $prod->price;
1559  }
1560 
1561  $line=new OrderLine($this->db);
1562 
1563  $line->context = $this->context;
1564 
1565  $line->fk_product=$idproduct;
1566  $line->desc=$prod->description;
1567  $line->qty=$qty;
1568  $line->subprice=$price;
1569  $line->remise_percent=$remise_percent;
1570  $line->vat_src_code=$vat_src_code;
1571  $line->tva_tx=$tva_tx;
1572  $line->localtax1_tx=$localtax1_tx;
1573  $line->localtax2_tx=$localtax2_tx;
1574  $line->ref=$prod->ref;
1575  $line->libelle=$prod->label;
1576  $line->product_desc=$prod->description;
1577  $line->fk_unit=$prod->fk_unit;
1578 
1579  // Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
1580  // Save the start and end date of the line in the object
1581  if ($date_start) { $line->date_start = $date_start; }
1582  if ($date_end) { $line->date_end = $date_end; }
1583 
1584  $this->lines[] = $line;
1585 
1606  }
1607  }
1608 
1609 
1619  function fetch($id, $ref='', $ref_ext='', $ref_int='')
1620  {
1621 
1622  // Check parameters
1623  if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
1624 
1625  $sql = 'SELECT c.rowid, c.entity, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut';
1626  $sql.= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
1627  $sql.= ', c.fk_account';
1628  $sql.= ', c.date_commande, c.date_valid, c.tms';
1629  $sql.= ', c.date_livraison';
1630  $sql.= ', c.fk_shipping_method';
1631  $sql.= ', c.fk_warehouse';
1632  $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
1633  $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams';
1634  $sql.= ', c.fk_incoterms, c.location_incoterms';
1635  $sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
1636  $sql.= ", i.libelle as libelle_incoterms";
1637  $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1638  $sql.= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
1639  $sql.= ', ca.code as availability_code, ca.label as availability_label';
1640  $sql.= ', dr.code as demand_reason_code';
1641  $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
1642  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
1643  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
1644  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
1645  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid';
1646  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
1647 
1648  if ($id) $sql.= " WHERE c.rowid=".$id;
1649  else $sql.= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid
1650 
1651  if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'";
1652  if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
1653  if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
1654 
1655  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1656  $result = $this->db->query($sql);
1657  if ($result)
1658  {
1659  $obj = $this->db->fetch_object($result);
1660  if ($obj)
1661  {
1662  $this->id = $obj->rowid;
1663  $this->entity = $obj->entity;
1664 
1665  $this->ref = $obj->ref;
1666  $this->ref_client = $obj->ref_client;
1667  $this->ref_customer = $obj->ref_client;
1668  $this->ref_ext = $obj->ref_ext;
1669  $this->ref_int = $obj->ref_int;
1670  $this->socid = $obj->fk_soc;
1671  $this->statut = $obj->fk_statut;
1672  $this->user_author_id = $obj->fk_user_author;
1673  $this->user_valid = $obj->fk_user_valid;
1674  $this->total_ht = $obj->total_ht;
1675  $this->total_tva = $obj->total_tva;
1676  $this->total_localtax1 = $obj->total_localtax1;
1677  $this->total_localtax2 = $obj->total_localtax2;
1678  $this->total_ttc = $obj->total_ttc;
1679  $this->date = $this->db->jdate($obj->date_commande);
1680  $this->date_commande = $this->db->jdate($obj->date_commande);
1681  $this->date_creation = $this->db->jdate($obj->date_creation);
1682  $this->date_validation = $this->db->jdate($obj->date_valid);
1683  $this->date_modification = $this->db->jdate($obj->tms);
1684  $this->remise = $obj->remise;
1685  $this->remise_percent = $obj->remise_percent;
1686  $this->remise_absolue = $obj->remise_absolue;
1687  $this->source = $obj->source;
1688  $this->billed = $obj->billed;
1689  $this->note = $obj->note_private; // deprecated
1690  $this->note_private = $obj->note_private;
1691  $this->note_public = $obj->note_public;
1692  $this->fk_project = $obj->fk_projet;
1693  $this->modelpdf = $obj->model_pdf;
1694  $this->last_main_doc = $obj->last_main_doc;
1695  $this->mode_reglement_id = $obj->fk_mode_reglement;
1696  $this->mode_reglement_code = $obj->mode_reglement_code;
1697  $this->mode_reglement = $obj->mode_reglement_libelle;
1698  $this->cond_reglement_id = $obj->fk_cond_reglement;
1699  $this->cond_reglement_code = $obj->cond_reglement_code;
1700  $this->cond_reglement = $obj->cond_reglement_libelle;
1701  $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1702  $this->fk_account = $obj->fk_account;
1703  $this->availability_id = $obj->fk_availability;
1704  $this->availability_code = $obj->availability_code;
1705  $this->availability = $obj->availability_label;
1706  $this->demand_reason_id = $obj->fk_input_reason;
1707  $this->demand_reason_code = $obj->demand_reason_code;
1708  $this->date_livraison = $this->db->jdate($obj->date_livraison);
1709  $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1710  $this->warehouse_id = ($obj->fk_warehouse>0)?$obj->fk_warehouse:null;
1711  $this->fk_delivery_address = $obj->fk_delivery_address;
1712 
1713  //Incoterms
1714  $this->fk_incoterms = $obj->fk_incoterms;
1715  $this->location_incoterms = $obj->location_incoterms;
1716  $this->libelle_incoterms = $obj->libelle_incoterms;
1717 
1718  // Multicurrency
1719  $this->fk_multicurrency = $obj->fk_multicurrency;
1720  $this->multicurrency_code = $obj->multicurrency_code;
1721  $this->multicurrency_tx = $obj->multicurrency_tx;
1722  $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1723  $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1724  $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1725 
1726  $this->extraparams = (array) json_decode($obj->extraparams, true);
1727 
1728  $this->lines = array();
1729 
1730  if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
1731 
1732  // Retreive all extrafield
1733  // fetch optionals attributes and labels
1734  $this->fetch_optionals();
1735 
1736  $this->db->free($result);
1737 
1738  /*
1739  * Lines
1740  */
1741  $result=$this->fetch_lines();
1742  if ($result < 0)
1743  {
1744  return -3;
1745  }
1746  return 1;
1747  }
1748  else
1749  {
1750  $this->error='Order with id '.$id.' not found sql='.$sql;
1751  return 0;
1752  }
1753  }
1754  else
1755  {
1756  $this->error=$this->db->error();
1757  return -1;
1758  }
1759  }
1760 
1761 
1762  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1769  function insert_discount($idremise)
1770  {
1771  // phpcs:enable
1772  global $langs;
1773 
1774  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1775  include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1776 
1777  $this->db->begin();
1778 
1779  $remise=new DiscountAbsolute($this->db);
1780  $result=$remise->fetch($idremise);
1781 
1782  if ($result > 0)
1783  {
1784  if ($remise->fk_facture) // Protection against multiple submission
1785  {
1786  $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
1787  $this->db->rollback();
1788  return -5;
1789  }
1790 
1791  $line = new OrderLine($this->db);
1792 
1793  $line->fk_commande=$this->id;
1794  $line->fk_remise_except=$remise->id;
1795  $line->desc=$remise->description; // Description ligne
1796  $line->vat_src_code=$remise->vat_src_code;
1797  $line->tva_tx=$remise->tva_tx;
1798  $line->subprice=-$remise->amount_ht;
1799  $line->price=-$remise->amount_ht;
1800  $line->fk_product=0; // Id produit predefini
1801  $line->qty=1;
1802  $line->remise=0;
1803  $line->remise_percent=0;
1804  $line->rang=-1;
1805  $line->info_bits=2;
1806 
1807  $line->total_ht = -$remise->amount_ht;
1808  $line->total_tva = -$remise->amount_tva;
1809  $line->total_ttc = -$remise->amount_ttc;
1810 
1811  $result=$line->insert();
1812  if ($result > 0)
1813  {
1814  $result=$this->update_price(1);
1815  if ($result > 0)
1816  {
1817  $this->db->commit();
1818  return 1;
1819  }
1820  else
1821  {
1822  $this->db->rollback();
1823  return -1;
1824  }
1825  }
1826  else
1827  {
1828  $this->error=$line->error;
1829  $this->db->rollback();
1830  return -2;
1831  }
1832  }
1833  else
1834  {
1835  $this->db->rollback();
1836  return -2;
1837  }
1838  }
1839 
1840 
1841  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1848  function fetch_lines($only_product=0)
1849  {
1850  // phpcs:enable
1851  $this->lines=array();
1852 
1853  $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx,';
1854  $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
1855  $sql.= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
1856  $sql.= ' l.fk_unit,';
1857  $sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
1858  $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch,';
1859  $sql.= ' p.weight, p.weight_units, p.volume, p.volume_units';
1860  $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as l';
1861  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
1862  $sql.= ' WHERE l.fk_commande = '.$this->id;
1863  if ($only_product) $sql .= ' AND p.fk_product_type = 0';
1864  $sql .= ' ORDER BY l.rang, l.rowid';
1865 
1866  dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1867  $result = $this->db->query($sql);
1868  if ($result)
1869  {
1870  $num = $this->db->num_rows($result);
1871 
1872  $i = 0;
1873  while ($i < $num)
1874  {
1875  $objp = $this->db->fetch_object($result);
1876 
1877  $line = new OrderLine($this->db);
1878 
1879  $line->rowid = $objp->rowid;
1880  $line->id = $objp->rowid;
1881  $line->fk_commande = $objp->fk_commande;
1882  $line->commande_id = $objp->fk_commande;
1883  $line->label = $objp->custom_label;
1884  $line->desc = $objp->description;
1885  $line->description = $objp->description; // Description line
1886  $line->product_type = $objp->product_type;
1887  $line->qty = $objp->qty;
1888 
1889  $line->vat_src_code = $objp->vat_src_code;
1890  $line->tva_tx = $objp->tva_tx;
1891  $line->localtax1_tx = $objp->localtax1_tx;
1892  $line->localtax2_tx = $objp->localtax2_tx;
1893  $line->localtax1_type = $objp->localtax1_type;
1894  $line->localtax2_type = $objp->localtax2_type;
1895  $line->total_ht = $objp->total_ht;
1896  $line->total_ttc = $objp->total_ttc;
1897  $line->total_tva = $objp->total_tva;
1898  $line->total_localtax1 = $objp->total_localtax1;
1899  $line->total_localtax2 = $objp->total_localtax2;
1900  $line->subprice = $objp->subprice;
1901  $line->fk_remise_except = $objp->fk_remise_except;
1902  $line->remise_percent = $objp->remise_percent;
1903  $line->price = $objp->price;
1904  $line->fk_product = $objp->fk_product;
1905  $line->fk_fournprice = $objp->fk_fournprice;
1906  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1907  $line->pa_ht = $marginInfos[0];
1908  $line->marge_tx = $marginInfos[1];
1909  $line->marque_tx = $marginInfos[2];
1910  $line->rang = $objp->rang;
1911  $line->info_bits = $objp->info_bits;
1912  $line->special_code = $objp->special_code;
1913  $line->fk_parent_line = $objp->fk_parent_line;
1914 
1915  $line->ref = $objp->product_ref;
1916  $line->product_ref = $objp->product_ref;
1917  $line->libelle = $objp->product_label;
1918  $line->product_label = $objp->product_label;
1919  $line->product_desc = $objp->product_desc;
1920  $line->product_tobatch = $objp->product_tobatch;
1921  $line->fk_product_type = $objp->fk_product_type; // Produit ou service
1922  $line->fk_unit = $objp->fk_unit;
1923 
1924  $line->weight = $objp->weight;
1925  $line->weight_units = $objp->weight_units;
1926  $line->volume = $objp->volume;
1927  $line->volume_units = $objp->volume_units;
1928 
1929  $line->date_start = $this->db->jdate($objp->date_start);
1930  $line->date_end = $this->db->jdate($objp->date_end);
1931 
1932  // Multicurrency
1933  $line->fk_multicurrency = $objp->fk_multicurrency;
1934  $line->multicurrency_code = $objp->multicurrency_code;
1935  $line->multicurrency_subprice = $objp->multicurrency_subprice;
1936  $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
1937  $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
1938  $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
1939 
1940  $line->fetch_optionals();
1941 
1942  $this->lines[$i] = $line;
1943 
1944  $i++;
1945  }
1946 
1947  $this->db->free($result);
1948 
1949  return 1;
1950  }
1951  else
1952  {
1953  $this->error=$this->db->error();
1954  return -3;
1955  }
1956  }
1957 
1958 
1965  {
1966  $nb=0;
1967  foreach($this->lines as $line)
1968  {
1969  if ($line->product_type == 0) $nb++;
1970  }
1971  return $nb;
1972  }
1973 
1980  {
1981  $nb=0;
1982  foreach($this->lines as $line)
1983  {
1984  if ($line->product_type == 1) $nb++;
1985  }
1986  return $nb;
1987  }
1988 
1994  function getNbOfShipments()
1995  {
1996  $nb = 0;
1997 
1998  $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb';
1999  $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2000  $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd';
2001  $sql.= ' WHERE';
2002  $sql.= ' ed.fk_origin_line = cd.rowid';
2003  $sql.= ' AND cd.fk_commande =' .$this->id;
2004  //print $sql;
2005 
2006  dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG);
2007  $resql = $this->db->query($sql);
2008  if ($resql)
2009  {
2010  $obj = $this->db->fetch_object($resql);
2011  if ($obj) $nb = $obj->nb;
2012 
2013  $this->db->free($resql);
2014  return $nb;
2015  }
2016  else
2017  {
2018  $this->error=$this->db->lasterror();
2019  return -1;
2020  }
2021  }
2022 
2030  function loadExpeditions($filtre_statut=-1)
2031  {
2032  $this->expeditions = array();
2033 
2034  $sql = 'SELECT cd.rowid, cd.fk_product,';
2035  $sql.= ' sum(ed.qty) as qty';
2036  $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2037  if ($filtre_statut >= 0) $sql.= ' '.MAIN_DB_PREFIX.'expedition as e,';
2038  $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd';
2039  $sql.= ' WHERE';
2040  if ($filtre_statut >= 0) $sql.= ' ed.fk_expedition = e.rowid AND';
2041  $sql.= ' ed.fk_origin_line = cd.rowid';
2042  $sql.= ' AND cd.fk_commande =' .$this->id;
2043  if ($this->fk_product > 0) $sql.= ' AND cd.fk_product = '.$this->fk_product;
2044  if ($filtre_statut >= 0) $sql.=' AND e.fk_statut >= '.$filtre_statut;
2045  $sql.= ' GROUP BY cd.rowid, cd.fk_product';
2046  //print $sql;
2047 
2048  dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
2049  $resql = $this->db->query($sql);
2050  if ($resql)
2051  {
2052  $num = $this->db->num_rows($resql);
2053  $i = 0;
2054  while ($i < $num)
2055  {
2056  $obj = $this->db->fetch_object($resql);
2057  $this->expeditions[$obj->rowid] = $obj->qty;
2058  $i++;
2059  }
2060  $this->db->free($resql);
2061  return $num;
2062  }
2063  else
2064  {
2065  $this->error=$this->db->lasterror();
2066  return -1;
2067  }
2068  }
2069 
2070  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2078  function nb_expedition()
2079  {
2080  // phpcs:enable
2081  $sql = 'SELECT count(*)';
2082  $sql.= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
2083  $sql.= ', '.MAIN_DB_PREFIX.'element_element as el';
2084  $sql.= ' WHERE el.fk_source = '.$this->id;
2085  $sql.= " AND el.fk_target = e.rowid";
2086  $sql.= " AND el.targettype = 'shipping'";
2087 
2088  $resql = $this->db->query($sql);
2089  if ($resql)
2090  {
2091  $row = $this->db->fetch_row($resql);
2092  return $row[0];
2093  }
2094  else dol_print_error($this->db);
2095  }
2096 
2097  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2106  function stock_array($filtre_statut=self::STATUS_CANCELED)
2107  {
2108  // phpcs:enable
2109  $this->stocks = array();
2110 
2111  // Tableau des id de produit de la commande
2112  $array_of_product=array();
2113 
2114  // Recherche total en stock pour chaque produit
2115  // TODO $array_of_product est défini vide juste au dessus !!
2116  if (count($array_of_product))
2117  {
2118  $sql = "SELECT fk_product, sum(ps.reel) as total";
2119  $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
2120  $sql.= " WHERE ps.fk_product IN (".join(',',$array_of_product).")";
2121  $sql.= ' GROUP BY fk_product ';
2122  $resql = $this->db->query($sql);
2123  if ($resql)
2124  {
2125  $num = $this->db->num_rows($resql);
2126  $i = 0;
2127  while ($i < $num)
2128  {
2129  $obj = $this->db->fetch_object($resql);
2130  $this->stocks[$obj->fk_product] = $obj->total;
2131  $i++;
2132  }
2133  $this->db->free($resql);
2134  }
2135  }
2136  return 0;
2137  }
2138 
2146  function deleteline($user=null, $lineid=0)
2147  {
2148  if ($this->statut == self::STATUS_DRAFT)
2149  {
2150  $this->db->begin();
2151 
2152  $sql = "SELECT fk_product, qty";
2153  $sql.= " FROM ".MAIN_DB_PREFIX."commandedet";
2154  $sql.= " WHERE rowid = ".$lineid;
2155 
2156  $result = $this->db->query($sql);
2157  if ($result)
2158  {
2159  $obj = $this->db->fetch_object($result);
2160 
2161  if ($obj)
2162  {
2163  $product = new Product($this->db);
2164  $product->id = $obj->fk_product;
2165 
2166  // Delete line
2167  $line = new OrderLine($this->db);
2168 
2169  // For triggers
2170  $line->fetch($lineid);
2171 
2172  if ($line->delete($user) > 0)
2173  {
2174  $result=$this->update_price(1);
2175 
2176  if ($result > 0)
2177  {
2178  $this->db->commit();
2179  return 1;
2180  }
2181  else
2182  {
2183  $this->db->rollback();
2184  $this->error=$this->db->lasterror();
2185  return -1;
2186  }
2187  }
2188  else
2189  {
2190  $this->db->rollback();
2191  $this->error=$line->error;
2192  return -1;
2193  }
2194  }
2195  else
2196  {
2197  $this->db->rollback();
2198  return 0;
2199  }
2200  }
2201  else
2202  {
2203  $this->db->rollback();
2204  $this->error=$this->db->lasterror();
2205  return -1;
2206  }
2207  }
2208  else
2209  {
2210  $this->error='ErrorDeleteLineNotAllowedByObjectStatus';
2211  return -1;
2212  }
2213  }
2214 
2215  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2224  function set_remise($user, $remise, $notrigger=0)
2225  {
2226  // phpcs:enable
2227  $remise=trim($remise)?trim($remise):0;
2228 
2229  if ($user->rights->commande->creer)
2230  {
2231  $error=0;
2232 
2233  $this->db->begin();
2234 
2235  $remise=price2num($remise);
2236 
2237  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2238  $sql.= ' SET remise_percent = '.$remise;
2239  $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2240 
2241  dol_syslog(__METHOD__, LOG_DEBUG);
2242  $resql=$this->db->query($sql);
2243  if (!$resql)
2244  {
2245  $this->errors[]=$this->db->error();
2246  $error++;
2247  }
2248 
2249  if (! $error)
2250  {
2251  $this->oldcopy= clone $this;
2252  $this->remise_percent = $remise;
2253  $this->update_price(1);
2254  }
2255 
2256  if (! $notrigger && empty($error))
2257  {
2258  // Call trigger
2259  $result=$this->call_trigger('ORDER_MODIFY',$user);
2260  if ($result < 0) $error++;
2261  // End call triggers
2262  }
2263 
2264  if (! $error)
2265  {
2266  $this->db->commit();
2267  return 1;
2268  }
2269  else
2270  {
2271  foreach($this->errors as $errmsg)
2272  {
2273  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2274  $this->error.=($this->error?', '.$errmsg:$errmsg);
2275  }
2276  $this->db->rollback();
2277  return -1*$error;
2278  }
2279  }
2280  }
2281 
2282 
2283  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2292  function set_remise_absolue($user, $remise, $notrigger=0)
2293  {
2294  // phpcs:enable
2295  $remise=trim($remise)?trim($remise):0;
2296 
2297  if ($user->rights->commande->creer)
2298  {
2299  $error=0;
2300 
2301  $this->db->begin();
2302 
2303  $remise=price2num($remise);
2304 
2305  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2306  $sql.= ' SET remise_absolue = '.$remise;
2307  $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;';
2308 
2309  dol_syslog(__METHOD__, LOG_DEBUG);
2310  $resql=$this->db->query($sql);
2311  if (!$resql)
2312  {
2313  $this->errors[]=$this->db->error();
2314  $error++;
2315  }
2316 
2317  if (! $error)
2318  {
2319  $this->oldcopy= clone $this;
2320  $this->remise_absolue = $remise;
2321  $this->update_price(1);
2322  }
2323 
2324  if (! $notrigger && empty($error))
2325  {
2326  // Call trigger
2327  $result=$this->call_trigger('ORDER_MODIFY',$user);
2328  if ($result < 0) $error++;
2329  // End call triggers
2330  }
2331 
2332  if (! $error)
2333  {
2334  $this->db->commit();
2335  return 1;
2336  }
2337  else
2338  {
2339  foreach($this->errors as $errmsg)
2340  {
2341  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2342  $this->error.=($this->error?', '.$errmsg:$errmsg);
2343  }
2344  $this->db->rollback();
2345  return -1*$error;
2346  }
2347  }
2348  }
2349 
2350 
2351  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2360  function set_date($user, $date, $notrigger=0)
2361  {
2362  // phpcs:enable
2363  if ($user->rights->commande->creer)
2364  {
2365  $error=0;
2366 
2367  $this->db->begin();
2368 
2369  $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2370  $sql.= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2371  $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT;
2372 
2373  dol_syslog(__METHOD__, LOG_DEBUG);
2374  $resql=$this->db->query($sql);
2375  if (!$resql)
2376  {
2377  $this->errors[]=$this->db->error();
2378  $error++;
2379  }
2380 
2381  if (! $error)
2382  {
2383  $this->oldcopy= clone $this;
2384  $this->date = $date;
2385  }
2386 
2387  if (! $notrigger && empty($error))
2388  {
2389  // Call trigger
2390  $result=$this->call_trigger('ORDER_MODIFY',$user);
2391  if ($result < 0) $error++;
2392  // End call triggers
2393  }
2394 
2395  if (! $error)
2396  {
2397  $this->db->commit();
2398  return 1;
2399  }
2400  else
2401  {
2402  foreach($this->errors as $errmsg)
2403  {
2404  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2405  $this->error.=($this->error?', '.$errmsg:$errmsg);
2406  }
2407  $this->db->rollback();
2408  return -1*$error;
2409  }
2410  }
2411  else
2412  {
2413  return -2;
2414  }
2415  }
2416 
2417  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2426  function set_date_livraison($user, $date_livraison, $notrigger=0)
2427  {
2428  // phpcs:enable
2429  if ($user->rights->commande->creer)
2430  {
2431  $error=0;
2432 
2433  $this->db->begin();
2434 
2435  $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
2436  $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2437  $sql.= " WHERE rowid = ".$this->id;
2438 
2439  dol_syslog(__METHOD__, LOG_DEBUG);
2440  $resql=$this->db->query($sql);
2441  if (!$resql)
2442  {
2443  $this->errors[]=$this->db->error();
2444  $error++;
2445  }
2446 
2447  if (! $error)
2448  {
2449  $this->oldcopy= clone $this;
2450  $this->date_livraison = $date_livraison;
2451  }
2452 
2453  if (! $notrigger && empty($error))
2454  {
2455  // Call trigger
2456  $result=$this->call_trigger('ORDER_MODIFY',$user);
2457  if ($result < 0) $error++;
2458  // End call triggers
2459  }
2460 
2461  if (! $error)
2462  {
2463  $this->db->commit();
2464  return 1;
2465  }
2466  else
2467  {
2468  foreach($this->errors as $errmsg)
2469  {
2470  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2471  $this->error.=($this->error?', '.$errmsg:$errmsg);
2472  }
2473  $this->db->rollback();
2474  return -1*$error;
2475  }
2476  }
2477  else
2478  {
2479  return -2;
2480  }
2481  }
2482 
2483  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2497  function liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='c.date_commande', $sortorder='DESC')
2498  {
2499  // phpcs:enable
2500  global $user;
2501 
2502  $ga = array();
2503 
2504  $sql = "SELECT s.rowid, s.nom as name, s.client,";
2505  $sql.= " c.rowid as cid, c.ref";
2506  if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user";
2507  $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
2508  if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2509  $sql.= " WHERE c.entity IN (".getEntity('commande').")";
2510  $sql.= " AND c.fk_soc = s.rowid";
2511  if (! $user->rights->societe->client->voir && ! $socid) //restriction
2512  {
2513  $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
2514  }
2515  if ($socid) $sql.= " AND s.rowid = ".$socid;
2516  if ($draft) $sql.= " AND c.fk_statut = ".self::STATUS_DRAFT;
2517  if (is_object($excluser)) $sql.= " AND c.fk_user_author <> ".$excluser->id;
2518  $sql.= $this->db->order($sortfield,$sortorder);
2519  $sql.= $this->db->plimit($limit,$offset);
2520 
2521  $result=$this->db->query($sql);
2522  if ($result)
2523  {
2524  $numc = $this->db->num_rows($result);
2525  if ($numc)
2526  {
2527  $i = 0;
2528  while ($i < $numc)
2529  {
2530  $obj = $this->db->fetch_object($result);
2531 
2532  if ($shortlist == 1)
2533  {
2534  $ga[$obj->cid] = $obj->ref;
2535  }
2536  else if ($shortlist == 2)
2537  {
2538  $ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
2539  }
2540  else
2541  {
2542  $ga[$i]['id'] = $obj->cid;
2543  $ga[$i]['ref'] = $obj->ref;
2544  $ga[$i]['name'] = $obj->name;
2545  }
2546  $i++;
2547  }
2548  }
2549  return $ga;
2550  }
2551  else
2552  {
2553  dol_print_error($this->db);
2554  return -1;
2555  }
2556  }
2557 
2565  function availability($availability_id, $notrigger=0)
2566  {
2567  global $user;
2568 
2569  dol_syslog('Commande::availability('.$availability_id.')');
2570  if ($this->statut >= self::STATUS_DRAFT)
2571  {
2572  $error=0;
2573 
2574  $this->db->begin();
2575 
2576  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2577  $sql .= ' SET fk_availability = '.$availability_id;
2578  $sql .= ' WHERE rowid='.$this->id;
2579 
2580  dol_syslog(__METHOD__, LOG_DEBUG);
2581  $resql=$this->db->query($sql);
2582  if (!$resql)
2583  {
2584  $this->errors[]=$this->db->error();
2585  $error++;
2586  }
2587 
2588  if (! $error)
2589  {
2590  $this->oldcopy= clone $this;
2591  $this->availability_id = $availability_id;
2592  }
2593 
2594  if (! $notrigger && empty($error))
2595  {
2596  // Call trigger
2597  $result=$this->call_trigger('ORDER_MODIFY',$user);
2598  if ($result < 0) $error++;
2599  // End call triggers
2600  }
2601 
2602  if (! $error)
2603  {
2604  $this->db->commit();
2605  return 1;
2606  }
2607  else
2608  {
2609  foreach($this->errors as $errmsg)
2610  {
2611  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2612  $this->error.=($this->error?', '.$errmsg:$errmsg);
2613  }
2614  $this->db->rollback();
2615  return -1*$error;
2616  }
2617  }
2618  else
2619  {
2620  $error_str='Command status do not meet requirement '.$this->statut;
2621  dol_syslog(__METHOD__.$error_str, LOG_ERR);
2622  $this->error=$error_str;
2623  $this->errors[]= $this->error;
2624  return -2;
2625  }
2626  }
2627 
2628  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2636  function demand_reason($demand_reason_id, $notrigger=0)
2637  {
2638  // phpcs:enable
2639  global $user;
2640 
2641  dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
2642  if ($this->statut >= self::STATUS_DRAFT)
2643  {
2644  $error=0;
2645 
2646  $this->db->begin();
2647 
2648  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
2649  $sql .= ' SET fk_input_reason = '.$demand_reason_id;
2650  $sql .= ' WHERE rowid='.$this->id;
2651 
2652  dol_syslog(__METHOD__, LOG_DEBUG);
2653  $resql=$this->db->query($sql);
2654  if (!$resql)
2655  {
2656  $this->errors[]=$this->db->error();
2657  $error++;
2658  }
2659 
2660  if (! $error)
2661  {
2662  $this->oldcopy= clone $this;
2663  $this->demand_reason_id = $demand_reason_id;
2664  }
2665 
2666  if (! $notrigger && empty($error))
2667  {
2668  // Call trigger
2669  $result=$this->call_trigger('ORDER_MODIFY',$user);
2670  if ($result < 0) $error++;
2671  // End call triggers
2672  }
2673 
2674  if (! $error)
2675  {
2676  $this->db->commit();
2677  return 1;
2678  }
2679  else
2680  {
2681  foreach($this->errors as $errmsg)
2682  {
2683  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2684  $this->error.=($this->error?', '.$errmsg:$errmsg);
2685  }
2686  $this->db->rollback();
2687  return -1*$error;
2688  }
2689  }
2690  else
2691  {
2692  $error_str='order status do not meet requirement '.$this->statut;
2693  dol_syslog(__METHOD__.$error_str, LOG_ERR);
2694  $this->error=$error_str;
2695  $this->errors[]= $this->error;
2696  return -2;
2697  }
2698  }
2699 
2700  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2709  function set_ref_client($user, $ref_client, $notrigger=0)
2710  {
2711  // phpcs:enable
2712  if ($user->rights->commande->creer)
2713  {
2714  $error=0;
2715 
2716  $this->db->begin();
2717 
2718  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET';
2719  $sql.= ' ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\'');
2720  $sql.= ' WHERE rowid = '.$this->id;
2721 
2722  dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2723  $resql=$this->db->query($sql);
2724  if (!$resql)
2725  {
2726  $this->errors[]=$this->db->error();
2727  $error++;
2728  }
2729 
2730  if (! $error)
2731  {
2732  $this->oldcopy= clone $this;
2733  $this->ref_client = $ref_client;
2734  }
2735 
2736  if (! $notrigger && empty($error))
2737  {
2738  // Call trigger
2739  $result=$this->call_trigger('ORDER_MODIFY',$user);
2740  if ($result < 0) $error++;
2741  // End call triggers
2742  }
2743  if (! $error)
2744  {
2745  $this->db->commit();
2746  return 1;
2747  }
2748  else
2749  {
2750  foreach($this->errors as $errmsg)
2751  {
2752  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2753  $this->error.=($this->error?', '.$errmsg:$errmsg);
2754  }
2755  $this->db->rollback();
2756  return -1*$error;
2757  }
2758  }
2759  else
2760  {
2761  return -1;
2762  }
2763  }
2764 
2772  function classifyBilled(User $user, $notrigger=0)
2773  {
2774  $error = 0;
2775 
2776  $this->db->begin();
2777 
2778  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 1';
2779  $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2780 
2781  dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
2782  if ($this->db->query($sql))
2783  {
2784 
2785  if (! $error)
2786  {
2787  $this->oldcopy= clone $this;
2788  $this->billed=1;
2789  }
2790 
2791  if (! $notrigger && empty($error))
2792  {
2793  // Call trigger
2794  $result=$this->call_trigger('ORDER_CLASSIFY_BILLED',$user);
2795  if ($result < 0) $error++;
2796  // End call triggers
2797  }
2798 
2799  if (! $error)
2800  {
2801  $this->db->commit();
2802  return 1;
2803  }
2804  else
2805  {
2806  foreach($this->errors as $errmsg)
2807  {
2808  dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
2809  $this->error.=($this->error?', '.$errmsg:$errmsg);
2810  }
2811  $this->db->rollback();
2812  return -1*$error;
2813  }
2814  }
2815  else
2816  {
2817  $this->error=$this->db->error();
2818  $this->db->rollback();
2819  return -1;
2820  }
2821  }
2822 
2828  function classifyUnBilled()
2829  {
2830  global $conf, $user, $langs;
2831  $error = 0;
2832 
2833  $this->db->begin();
2834 
2835  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 0';
2836  $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
2837 
2838  dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
2839  if ($this->db->query($sql))
2840  {
2841  if (! $error)
2842  {
2843  $this->oldcopy= clone $this;
2844  $this->billed=1;
2845  }
2846 
2847  // Call trigger
2848  $result=$this->call_trigger('ORDER_CLASSIFY_UNBILLED',$user);
2849  if ($result < 0) $error++;
2850  // End call triggers
2851 
2852  if (! $error)
2853  {
2854  $this->billed=0;
2855 
2856  $this->db->commit();
2857  return 1;
2858  }
2859  else
2860  {
2861  foreach($this->errors as $errmsg)
2862  {
2863  dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
2864  $this->error.=($this->error?', '.$errmsg:$errmsg);
2865  }
2866  $this->db->rollback();
2867  return -1*$error;
2868  }
2869  }
2870  else
2871  {
2872  $this->error=$this->db->error();
2873  $this->db->rollback();
2874  return -1;
2875  }
2876  }
2877 
2878 
2907  function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0,$txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0)
2908  {
2909  global $conf, $mysoc, $langs, $user;
2910 
2911  dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code");
2912  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2913 
2914  if (! empty($this->brouillon))
2915  {
2916  $this->db->begin();
2917 
2918  // Clean parameters
2919  if (empty($qty)) $qty=0;
2920  if (empty($info_bits)) $info_bits=0;
2921  if (empty($txtva)) $txtva=0;
2922  if (empty($txlocaltax1)) $txlocaltax1=0;
2923  if (empty($txlocaltax2)) $txlocaltax2=0;
2924  if (empty($remise_percent)) $remise_percent=0;
2925  if (empty($special_code) || $special_code == 3) $special_code=0;
2926 
2927  $remise_percent=price2num($remise_percent);
2928  $qty=price2num($qty);
2929  $pu = price2num($pu);
2930  $pa_ht=price2num($pa_ht);
2931  $pu_ht_devise=price2num($pu_ht_devise);
2932  $txtva=price2num($txtva);
2933  $txlocaltax1=price2num($txlocaltax1);
2934  $txlocaltax2=price2num($txlocaltax2);
2935 
2936  // Calcul du total TTC et de la TVA pour la ligne a partir de
2937  // qty, pu, remise_percent et txtva
2938  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2939  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2940 
2941  $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
2942 
2943  // Clean vat code
2944  $vat_src_code='';
2945  if (preg_match('/\((.*)\)/', $txtva, $reg))
2946  {
2947  $vat_src_code = $reg[1];
2948  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
2949  }
2950 
2951  $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2952 
2953  $total_ht = $tabprice[0];
2954  $total_tva = $tabprice[1];
2955  $total_ttc = $tabprice[2];
2956  $total_localtax1 = $tabprice[9];
2957  $total_localtax2 = $tabprice[10];
2958  $pu_ht = $tabprice[3];
2959  $pu_tva = $tabprice[4];
2960  $pu_ttc = $tabprice[5];
2961 
2962  // MultiCurrency
2963  $multicurrency_total_ht = $tabprice[16];
2964  $multicurrency_total_tva = $tabprice[17];
2965  $multicurrency_total_ttc = $tabprice[18];
2966  $pu_ht_devise = $tabprice[19];
2967 
2968  // Anciens indicateurs: $price, $subprice (a ne plus utiliser)
2969  $price = $pu_ht;
2970  if ($price_base_type == 'TTC')
2971  {
2972  $subprice = $pu_ttc;
2973  }
2974  else
2975  {
2976  $subprice = $pu_ht;
2977  }
2978  $remise = 0;
2979  if ($remise_percent > 0)
2980  {
2981  $remise = round(($pu * $remise_percent / 100),2);
2982  $price = ($pu - $remise);
2983  }
2984 
2985  //Fetch current line from the database and then clone the object and set it in $oldline property
2986  $line = new OrderLine($this->db);
2987  $line->fetch($rowid);
2988 
2989  if (!empty($line->fk_product))
2990  {
2991  $product=new Product($this->db);
2992  $result=$product->fetch($line->fk_product);
2993  $product_type=$product->type;
2994 
2995  if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty)
2996  {
2997  $langs->load("errors");
2998  $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
2999  dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
3000  $this->db->rollback();
3001  return self::STOCK_NOT_ENOUGH_FOR_ORDER;
3002  }
3003  }
3004 
3005  $staticline = clone $line;
3006 
3007  $line->oldline = $staticline;
3008  $this->line = $line;
3009  $this->line->context = $this->context;
3010 
3011  // Reorder if fk_parent_line change
3012  if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
3013  {
3014  $rangmax = $this->line_max($fk_parent_line);
3015  $this->line->rang = $rangmax + 1;
3016  }
3017 
3018  $this->line->rowid=$rowid;
3019  $this->line->label=$label;
3020  $this->line->desc=$desc;
3021  $this->line->qty=$qty;
3022 
3023  $this->line->vat_src_code = $vat_src_code;
3024  $this->line->tva_tx = $txtva;
3025  $this->line->localtax1_tx = $txlocaltax1;
3026  $this->line->localtax2_tx = $txlocaltax2;
3027  $this->line->localtax1_type = $localtaxes_type[0];
3028  $this->line->localtax2_type = $localtaxes_type[2];
3029  $this->line->remise_percent = $remise_percent;
3030  $this->line->subprice = $subprice;
3031  $this->line->info_bits = $info_bits;
3032  $this->line->special_code = $special_code;
3033  $this->line->total_ht = $total_ht;
3034  $this->line->total_tva = $total_tva;
3035  $this->line->total_localtax1= $total_localtax1;
3036  $this->line->total_localtax2= $total_localtax2;
3037  $this->line->total_ttc = $total_ttc;
3038  $this->line->date_start = $date_start;
3039  $this->line->date_end = $date_end;
3040  $this->line->product_type = $type;
3041  $this->line->fk_parent_line = $fk_parent_line;
3042  $this->line->skip_update_total=$skip_update_total;
3043  $this->line->fk_unit = $fk_unit;
3044 
3045  $this->line->fk_fournprice = $fk_fournprice;
3046  $this->line->pa_ht = $pa_ht;
3047 
3048  // Multicurrency
3049  $this->line->multicurrency_subprice = $pu_ht_devise;
3050  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
3051  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
3052  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
3053 
3054  // TODO deprecated
3055  $this->line->price=$price;
3056  $this->line->remise=$remise;
3057 
3058  if (is_array($array_options) && count($array_options)>0) {
3059  $this->line->array_options=$array_options;
3060  }
3061 
3062  $result=$this->line->update($user, $notrigger);
3063  if ($result > 0)
3064  {
3065  // Reorder if child line
3066  if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
3067 
3068  // Mise a jour info denormalisees
3069  $this->update_price(1);
3070 
3071  $this->db->commit();
3072  return $result;
3073  }
3074  else
3075  {
3076  $this->error=$this->line->error;
3077 
3078  $this->db->rollback();
3079  return -1;
3080  }
3081  }
3082  else
3083  {
3084  $this->error=get_class($this)."::updateline Order status makes operation forbidden";
3085  $this->errors=array('OrderStatusMakeOperationForbidden');
3086  return -2;
3087  }
3088  }
3089 
3097  function update(User $user, $notrigger=0)
3098  {
3099  global $conf;
3100 
3101  $error=0;
3102 
3103  // Clean parameters
3104  if (isset($this->ref)) $this->ref=trim($this->ref);
3105  if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client);
3106  if (isset($this->note) || isset($this->note_private)) $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
3107  if (isset($this->note_public)) $this->note_public=trim($this->note_public);
3108  if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
3109  if (isset($this->import_key)) $this->import_key=trim($this->import_key);
3110 
3111  // Check parameters
3112  // Put here code to add control on parameters values
3113 
3114  // Update request
3115  $sql = "UPDATE ".MAIN_DB_PREFIX."commande SET";
3116 
3117  $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
3118  $sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").",";
3119  $sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").",";
3120  $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
3121  $sql.= " date_commande=".(strval($this->date_commande)!='' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
3122  $sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
3123  $sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
3124  $sql.= " localtax1=".(isset($this->total_localtax1)?$this->total_localtax1:"null").",";
3125  $sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").",";
3126  $sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").",";
3127  $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
3128  $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
3129  $sql.= " fk_user_author=".(isset($this->user_author_id)?$this->user_author_id:"null").",";
3130  $sql.= " fk_user_valid=".(isset($this->user_valid)?$this->user_valid:"null").",";
3131  $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
3132  $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
3133  $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").",";
3134  $sql.= " fk_account=".($this->fk_account>0?$this->fk_account:"null").",";
3135  $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
3136  $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
3137  $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
3138  $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
3139 
3140  $sql.= " WHERE rowid=".$this->id;
3141 
3142  $this->db->begin();
3143 
3144  dol_syslog(get_class($this)."::update", LOG_DEBUG);
3145  $resql = $this->db->query($sql);
3146  if (! $resql) {
3147  $error++; $this->errors[]="Error ".$this->db->lasterror();
3148  }
3149 
3150  if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
3151  {
3152  $result=$this->insertExtraFields();
3153  if ($result < 0)
3154  {
3155  $error++;
3156  }
3157  }
3158 
3159  if (! $error && ! $notrigger)
3160  {
3161  // Call trigger
3162  $result=$this->call_trigger('ORDER_MODIFY', $user);
3163  if ($result < 0) $error++;
3164  // End call triggers
3165  }
3166 
3167  // Commit or rollback
3168  if ($error)
3169  {
3170  foreach($this->errors as $errmsg)
3171  {
3172  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
3173  $this->error.=($this->error?', '.$errmsg:$errmsg);
3174  }
3175  $this->db->rollback();
3176  return -1*$error;
3177  }
3178  else
3179  {
3180  $this->db->commit();
3181  return 1;
3182  }
3183  }
3184 
3192  function delete($user, $notrigger=0)
3193  {
3194  global $conf, $langs;
3195  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3196 
3197  $error = 0;
3198 
3199  dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG);
3200 
3201  $this->db->begin();
3202 
3203  if (! $error && ! $notrigger)
3204  {
3205  // Call trigger
3206  $result=$this->call_trigger('ORDER_DELETE',$user);
3207  if ($result < 0) $error++;
3208  // End call triggers
3209  }
3210 
3211  if ($this->nb_expedition() != 0)
3212  {
3213  $this->errors[] = $langs->trans('SomeShipmentExists');
3214  $error++;
3215  }
3216 
3217  if (! $error)
3218  {
3219  // Delete order details
3220  $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE fk_commande = ".$this->id;
3221  if (! $this->db->query($sql) )
3222  {
3223  $error++;
3224  $this->errors[]=$this->db->lasterror();
3225  }
3226  }
3227 
3228  if (! $error)
3229  {
3230  // Delete linked object
3231  $res = $this->deleteObjectLinked();
3232  if ($res < 0) $error++;
3233  }
3234 
3235  if (! $error)
3236  {
3237  // Delete linked contacts
3238  $res = $this->delete_linked_contact();
3239  if ($res < 0) $error++;
3240  }
3241 
3242  if (! $error)
3243  {
3244  // Remove extrafields
3245  if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
3246  {
3247  $result=$this->deleteExtraFields();
3248  if ($result < 0)
3249  {
3250  $error++;
3251  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
3252  }
3253  }
3254  }
3255 
3256  if (! $error)
3257  {
3258  // Delete object
3259  $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande WHERE rowid = ".$this->id;
3260  if (! $this->db->query($sql) )
3261  {
3262  $error++;
3263  $this->errors[]=$this->db->lasterror();
3264  }
3265  }
3266 
3267  if (! $error)
3268  {
3269  // Remove directory with files
3270  $comref = dol_sanitizeFileName($this->ref);
3271  if ($conf->commande->dir_output && !empty($this->ref))
3272  {
3273  $dir = $conf->commande->dir_output . "/" . $comref ;
3274  $file = $conf->commande->dir_output . "/" . $comref . "/" . $comref . ".pdf";
3275  if (file_exists($file)) // We must delete all files before deleting directory
3276  {
3277  dol_delete_preview($this);
3278 
3279  if (! dol_delete_file($file,0,0,0,$this)) // For triggers
3280  {
3281  $this->db->rollback();
3282  return 0;
3283  }
3284  }
3285  if (file_exists($dir))
3286  {
3287  if (! dol_delete_dir_recursive($dir))
3288  {
3289  $this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
3290  $this->db->rollback();
3291  return 0;
3292  }
3293  }
3294  }
3295  }
3296 
3297  if (! $error)
3298  {
3299  $this->db->commit();
3300  return 1;
3301  }
3302  else
3303  {
3304  foreach($this->errors as $errmsg)
3305  {
3306  $this->error.=($this->error?', '.$errmsg:$errmsg);
3307  }
3308  $this->db->rollback();
3309  return -1*$error;
3310  }
3311  }
3312 
3313 
3314  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3321  function load_board($user)
3322  {
3323  // phpcs:enable
3324  global $conf, $langs;
3325 
3326  $clause = " WHERE";
3327 
3328  $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut, c.total_ht";
3329  $sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
3330  if (!$user->rights->societe->client->voir && !$user->societe_id)
3331  {
3332  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3333  $sql.= " WHERE sc.fk_user = " .$user->id;
3334  $clause = " AND";
3335  }
3336  $sql.= $clause." c.entity IN (".getEntity('commande').")";
3337  //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3338  $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_SHIPMENTONPROCESS.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected
3339  if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
3340 
3341  $resql=$this->db->query($sql);
3342  if ($resql)
3343  {
3344  $response = new WorkboardResponse();
3345  $response->warning_delay=$conf->commande->client->warning_delay/60/60/24;
3346  $response->label=$langs->trans("OrdersToProcess");
3347  $response->url=DOL_URL_ROOT.'/commande/list.php?viewstatut=-3&mainmenu=commercial&leftmenu=orders';
3348  $response->img=img_object('',"order");
3349 
3350  $generic_commande = new Commande($this->db);
3351 
3352  while ($obj=$this->db->fetch_object($resql))
3353  {
3354  $response->nbtodo++;
3355  $response->total+= $obj->total_ht;
3356 
3357  $generic_commande->statut = $obj->fk_statut;
3358  $generic_commande->date_commande = $this->db->jdate($obj->date_commande);
3359  $generic_commande->date_livraison = $this->db->jdate($obj->delivery_date);
3360 
3361  if ($generic_commande->hasDelay()) {
3362  $response->nbtodolate++;
3363  }
3364  }
3365 
3366  return $response;
3367  }
3368  else
3369  {
3370  $this->error=$this->db->error();
3371  return -1;
3372  }
3373  }
3374 
3380  function getLabelSource()
3381  {
3382  global $langs;
3383 
3384  $label=$langs->trans('OrderSource'.$this->source);
3385 
3386  if ($label == 'OrderSource') return '';
3387  return $label;
3388  }
3389 
3396  function getLibStatut($mode)
3397  {
3398  return $this->LibStatut($this->statut, $this->billed, $mode);
3399  }
3400 
3401  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3411  function LibStatut($statut,$billed,$mode,$donotshowbilled=0)
3412  {
3413  // phpcs:enable
3414  global $langs, $conf;
3415 
3416  $billedtext = '';
3417  if (empty($donotshowbilled)) $billedtext .= ($billed?' - '.$langs->trans("Billed"):'');
3418 
3419  //print 'x'.$statut.'-'.$billed;
3420  if ($mode == 0)
3421  {
3422  if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled');
3423  if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft');
3424  if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext;
3425  if ($statut==self::STATUS_SHIPMENTONPROCESS) return $langs->trans('StatusOrderSentShort').$billedtext;
3426  if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill');
3427  if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3428  if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3429  }
3430  elseif ($mode == 1)
3431  {
3432  if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort');
3433  if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort');
3434  if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext;
3435  if ($statut==self::STATUS_SHIPMENTONPROCESS) return $langs->trans('StatusOrderSentShort').$billedtext;
3436  if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort');
3437  if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext;
3438  if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered');
3439  }
3440  elseif ($mode == 2)
3441  {
3442  if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort');
3443  if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort');
3444  if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext;
3445  if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext;
3446  if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort');
3447  if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3448  if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort');
3449  }
3450  elseif ($mode == 3)
3451  {
3452  if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3453  if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
3454  if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3455  if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3');
3456  if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
3457  if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3458  if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3459  }
3460  elseif ($mode == 4)
3461  {
3462  if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled');
3463  if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft');
3464  if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext;
3465  if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext;
3466  if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill');
3467  if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext;
3468  if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered');
3469  }
3470  elseif ($mode == 5)
3471  {
3472  if ($statut==self::STATUS_CANCELED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceledShort').' </span>'.img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3473  if ($statut==self::STATUS_DRAFT) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraftShort').' </span>'.img_picto($langs->trans('StatusOrderDraft'),'statut0');
3474  if ($statut==self::STATUS_VALIDATED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidatedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3475  if ($statut==self::STATUS_SHIPMENTONPROCESS) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSentShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3');
3476  if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBillShort').' </span>'.img_picto($langs->trans('StatusOrderToBill'),'statut4');
3477  if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessedShort').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3478  if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDeliveredShort').' </span>'.img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3479  }
3480  elseif ($mode == 6)
3481  {
3482  if ($statut==self::STATUS_CANCELED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderCanceled').' </span>'.img_picto($langs->trans('StatusOrderCanceled'),'statut5');
3483  if ($statut==self::STATUS_DRAFT) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDraft').' </span>'.img_picto($langs->trans('StatusOrderDraft'),'statut0');
3484  if ($statut==self::STATUS_VALIDATED) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderValidated').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1');
3485  if ($statut==self::STATUS_SHIPMENTONPROCESS) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderSent').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3');
3486  if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderToBill').' </span>'.img_picto($langs->trans('StatusOrderToBill'),'statut4');
3487  if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderProcessed').$billedtext.' </span>'.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6');
3488  if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return '<span class="hideonsmartphone">'.$langs->trans('StatusOrderDelivered').' </span>'.img_picto($langs->trans('StatusOrderDelivered'),'statut6');
3489  }
3490  }
3491 
3492 
3504  function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1)
3505  {
3506  global $conf, $langs, $user;
3507 
3508  if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
3509 
3510  $result='';
3511 
3512  if (! empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
3513  else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id;
3514 
3515  if (!$user->rights->commande->lire)
3516  $option = 'nolink';
3517 
3518  if ($option !== 'nolink')
3519  {
3520  // Add param to save lastsearch_values or not
3521  $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
3522  if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
3523  if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
3524  }
3525 
3526  if ($short) return $url;
3527 
3528  $label = '';
3529 
3530  if ($user->rights->commande->lire) {
3531  $label = '<u>'.$langs->trans("ShowOrder").'</u>';
3532  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3533  $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.($this->ref_customer ? $this->ref_customer : $this->ref_client);
3534  if (!empty($this->total_ht)) {
3535  $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3536  }
3537  if (!empty($this->total_tva)) {
3538  $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3539  }
3540  if (!empty($this->total_ttc)) {
3541  $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3542  }
3543  }
3544 
3545  $linkclose='';
3546  if (empty($notooltip) && $user->rights->commande->lire)
3547  {
3548  if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
3549  {
3550  $label=$langs->trans("ShowOrder");
3551  $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
3552  }
3553  $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
3554  $linkclose.=' class="classfortooltip"';
3555  }
3556 
3557  $linkstart = '<a href="'.$url.'"';
3558  $linkstart.=$linkclose.'>';
3559  $linkend='</a>';
3560 
3561  if ($option === 'nolink') {
3562  $linkstart = '';
3563  $linkend = '';
3564  }
3565 
3566  $result .= $linkstart;
3567  if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
3568  if ($withpicto != 2) $result.= $this->ref;
3569  $result .= $linkend;
3570 
3571  return $result;
3572  }
3573 
3574 
3581  function info($id)
3582  {
3583  $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
3584  $sql.= ' date_valid as datev,';
3585  $sql.= ' date_cloture as datecloture,';
3586  $sql.= ' fk_user_author, fk_user_valid, fk_user_cloture';
3587  $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
3588  $sql.= ' WHERE c.rowid = '.$id;
3589  $result=$this->db->query($sql);
3590  if ($result)
3591  {
3592  if ($this->db->num_rows($result))
3593  {
3594  $obj = $this->db->fetch_object($result);
3595  $this->id = $obj->rowid;
3596  if ($obj->fk_user_author)
3597  {
3598  $cuser = new User($this->db);
3599  $cuser->fetch($obj->fk_user_author);
3600  $this->user_creation = $cuser;
3601  }
3602 
3603  if ($obj->fk_user_valid)
3604  {
3605  $vuser = new User($this->db);
3606  $vuser->fetch($obj->fk_user_valid);
3607  $this->user_validation = $vuser;
3608  }
3609 
3610  if ($obj->fk_user_cloture)
3611  {
3612  $cluser = new User($this->db);
3613  $cluser->fetch($obj->fk_user_cloture);
3614  $this->user_cloture = $cluser;
3615  }
3616 
3617  $this->date_creation = $this->db->jdate($obj->datec);
3618  $this->date_modification = $this->db->jdate($obj->datem);
3619  $this->date_validation = $this->db->jdate($obj->datev);
3620  $this->date_cloture = $this->db->jdate($obj->datecloture);
3621  }
3622 
3623  $this->db->free($result);
3624  }
3625  else
3626  {
3627  dol_print_error($this->db);
3628  }
3629  }
3630 
3631 
3639  function initAsSpecimen()
3640  {
3641  global $langs;
3642 
3643  dol_syslog(get_class($this)."::initAsSpecimen");
3644 
3645  // Load array of products prodids
3646  $num_prods = 0;
3647  $prodids = array();
3648  $sql = "SELECT rowid";
3649  $sql.= " FROM ".MAIN_DB_PREFIX."product";
3650  $sql.= " WHERE entity IN (".getEntity('product').")";
3651  $resql = $this->db->query($sql);
3652  if ($resql)
3653  {
3654  $num_prods = $this->db->num_rows($resql);
3655  $i = 0;
3656  while ($i < $num_prods)
3657  {
3658  $i++;
3659  $row = $this->db->fetch_row($resql);
3660  $prodids[$i] = $row[0];
3661  }
3662  }
3663 
3664  // Initialise parametres
3665  $this->id=0;
3666  $this->ref = 'SPECIMEN';
3667  $this->specimen=1;
3668  $this->socid = 1;
3669  $this->date = time();
3670  $this->date_lim_reglement=$this->date+3600*24*30;
3671  $this->cond_reglement_code = 'RECEP';
3672  $this->mode_reglement_code = 'CHQ';
3673  $this->availability_code = 'DSP';
3674  $this->demand_reason_code = 'SRC_00';
3675  $this->note_public='This is a comment (public)';
3676  $this->note_private='This is a comment (private)';
3677  // Lines
3678  $nbp = 5;
3679  $xnbp = 0;
3680  while ($xnbp < $nbp)
3681  {
3682  $line=new OrderLine($this->db);
3683 
3684  $line->desc=$langs->trans("Description")." ".$xnbp;
3685  $line->qty=1;
3686  $line->subprice=100;
3687  $line->price=100;
3688  $line->tva_tx=20;
3689  if ($xnbp == 2)
3690  {
3691  $line->total_ht=50;
3692  $line->total_ttc=60;
3693  $line->total_tva=10;
3694  $line->remise_percent=50;
3695  }
3696  else
3697  {
3698  $line->total_ht=100;
3699  $line->total_ttc=120;
3700  $line->total_tva=20;
3701  $line->remise_percent=0;
3702  }
3703  if ($num_prods > 0)
3704  {
3705  $prodid = mt_rand(1, $num_prods);
3706  $line->fk_product=$prodids[$prodid];
3707  $line->product_ref='SPECIMEN';
3708  }
3709 
3710  $this->lines[$xnbp]=$line;
3711 
3712  $this->total_ht += $line->total_ht;
3713  $this->total_tva += $line->total_tva;
3714  $this->total_ttc += $line->total_ttc;
3715 
3716  $xnbp++;
3717  }
3718  }
3719 
3720 
3721  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3727  function load_state_board()
3728  {
3729  // phpcs:enable
3730  global $user;
3731 
3732  $this->nb=array();
3733  $clause = "WHERE";
3734 
3735  $sql = "SELECT count(co.rowid) as nb";
3736  $sql.= " FROM ".MAIN_DB_PREFIX."commande as co";
3737  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
3738  if (!$user->rights->societe->client->voir && !$user->societe_id)
3739  {
3740  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3741  $sql.= " WHERE sc.fk_user = " .$user->id;
3742  $clause = "AND";
3743  }
3744  $sql.= " ".$clause." co.entity IN (".getEntity('commande').")";
3745 
3746  $resql=$this->db->query($sql);
3747  if ($resql)
3748  {
3749  while ($obj=$this->db->fetch_object($resql))
3750  {
3751  $this->nb["orders"]=$obj->nb;
3752  }
3753  $this->db->free($resql);
3754  return 1;
3755  }
3756  else
3757  {
3758  dol_print_error($this->db);
3759  $this->error=$this->db->error();
3760  return -1;
3761  }
3762  }
3763 
3769  function getLinesArray()
3770  {
3771  return $this->fetch_lines();
3772  }
3773 
3785  public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
3786  {
3787  global $conf,$langs;
3788 
3789  $langs->load("orders");
3790 
3791  if (! dol_strlen($modele)) {
3792 
3793  $modele = 'einstein';
3794 
3795  if ($this->modelpdf) {
3796  $modele = $this->modelpdf;
3797  } elseif (! empty($conf->global->COMMANDE_ADDON_PDF)) {
3798  $modele = $conf->global->COMMANDE_ADDON_PDF;
3799  }
3800  }
3801 
3802  $modelpath = "core/modules/commande/doc/";
3803 
3804  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3805  }
3806 
3807 
3816  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
3817  {
3818  $tables = array(
3819  'commande'
3820  );
3821 
3822  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3823  }
3824 
3830  public function hasDelay()
3831  {
3832  global $conf;
3833 
3834  if (! ($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) {
3835  return false; // Never late if not inside this status range
3836  }
3837 
3838  $now = dol_now();
3839 
3840  return max($this->date_commande, $this->date_livraison) < ($now - $conf->commande->client->warning_delay);
3841  }
3842 
3848  public function showDelay()
3849  {
3850  global $conf, $langs;
3851 
3852  if (empty($this->date_livraison)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3853  else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day');
3854  $text.=' '.($conf->commande->client->warning_delay>0?'+':'-').' '.round(abs($conf->commande->client->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3855 
3856  return $text;
3857  }
3858 }
3859 
3860 
3865 {
3869  public $element='commandedet';
3870 
3871  public $table_element='commandedet';
3872 
3873  var $oldline;
3874 
3879  public $fk_commande;
3880 
3887  public $commande_id;
3888 
3889  // From llx_commandedet
3890  var $fk_parent_line;
3891  var $fk_facture;
3892 
3896  public $label;
3897 
3898  var $fk_remise_except;
3899  var $rang = 0;
3900  var $fk_fournprice;
3901 
3906  var $pa_ht;
3907  var $marge_tx;
3908  var $marque_tx;
3909 
3914  var $remise;
3915 
3916  // Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
3917  // Start and end date of the line
3918  var $date_start;
3919  var $date_end;
3920 
3921  var $skip_update_total; // Skip update price total for special lines
3922 
3923 
3929  function __construct($db)
3930  {
3931  $this->db= $db;
3932  }
3933 
3940  function fetch($rowid)
3941  {
3942  $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_parent_line, cd.fk_product, cd.product_type, cd.label as custom_label, cd.description, cd.price, cd.qty, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx,';
3943  $sql.= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice,';
3944  $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,';
3945  $sql.= ' cd.fk_unit,';
3946  $sql.= ' cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,';
3947  $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc, p.tobatch as product_tobatch,';
3948  $sql.= ' cd.date_start, cd.date_end';
3949  $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd';
3950  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3951  $sql.= ' WHERE cd.rowid = '.$rowid;
3952  $result = $this->db->query($sql);
3953  if ($result)
3954  {
3955  $objp = $this->db->fetch_object($result);
3956  $this->rowid = $objp->rowid;
3957  $this->id = $objp->rowid;
3958  $this->fk_commande = $objp->fk_commande;
3959  $this->fk_parent_line = $objp->fk_parent_line;
3960  $this->label = $objp->custom_label;
3961  $this->desc = $objp->description;
3962  $this->qty = $objp->qty;
3963  $this->price = $objp->price;
3964  $this->subprice = $objp->subprice;
3965  $this->vat_src_code = $objp->vat_src_code;
3966  $this->tva_tx = $objp->tva_tx;
3967  $this->localtax1_tx = $objp->localtax1_tx;
3968  $this->localtax2_tx = $objp->localtax2_tx;
3969  $this->remise = $objp->remise;
3970  $this->remise_percent = $objp->remise_percent;
3971  $this->fk_remise_except = $objp->fk_remise_except;
3972  $this->fk_product = $objp->fk_product;
3973  $this->product_type = $objp->product_type;
3974  $this->info_bits = $objp->info_bits;
3975  $this->special_code = $objp->special_code;
3976  $this->total_ht = $objp->total_ht;
3977  $this->total_tva = $objp->total_tva;
3978  $this->total_localtax1 = $objp->total_localtax1;
3979  $this->total_localtax2 = $objp->total_localtax2;
3980  $this->total_ttc = $objp->total_ttc;
3981  $this->fk_fournprice = $objp->fk_fournprice;
3982  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
3983  $this->pa_ht = $marginInfos[0];
3984  $this->marge_tx = $marginInfos[1];
3985  $this->marque_tx = $marginInfos[2];
3986  $this->special_code = $objp->special_code;
3987  $this->rang = $objp->rang;
3988 
3989  $this->ref = $objp->product_ref; // deprecated
3990  $this->product_ref = $objp->product_ref;
3991  $this->libelle = $objp->product_libelle; // deprecated
3992  $this->product_label = $objp->product_libelle;
3993  $this->product_desc = $objp->product_desc;
3994  $this->product_tobatch = $objp->product_tobatch;
3995  $this->fk_unit = $objp->fk_unit;
3996 
3997  $this->date_start = $this->db->jdate($objp->date_start);
3998  $this->date_end = $this->db->jdate($objp->date_end);
3999 
4000  $this->fk_multicurrency = $objp->fk_multicurrency;
4001  $this->multicurrency_code = $objp->multicurrency_code;
4002  $this->multicurrency_subprice = $objp->multicurrency_subprice;
4003  $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
4004  $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
4005  $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
4006 
4007  $this->db->free($result);
4008 
4009  return 1;
4010  }
4011  else
4012  {
4013  $this->error = $this->db->lasterror();
4014  return -1;
4015  }
4016  }
4017 
4025  function delete($user=null, $notrigger=0)
4026  {
4027  global $conf, $user, $langs;
4028 
4029  $error=0;
4030 
4031  $this->db->begin();
4032 
4033  $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE rowid=".$this->rowid;
4034 
4035  dol_syslog("OrderLine::delete", LOG_DEBUG);
4036  $resql=$this->db->query($sql);
4037  if ($resql)
4038  {
4039  // Remove extrafields
4040  if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
4041  {
4042  $this->id=$this->rowid;
4043  $result=$this->deleteExtraFields();
4044  if ($result < 0)
4045  {
4046  $error++;
4047  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
4048  }
4049  }
4050 
4051  if (! $error && ! $notrigger)
4052  {
4053  // Call trigger
4054  $result=$this->call_trigger('LINEORDER_DELETE',$user);
4055  if ($result < 0) $error++;
4056  // End call triggers
4057  }
4058 
4059  if (!$error) {
4060  $this->db->commit();
4061  return 1;
4062  }
4063 
4064  foreach($this->errors as $errmsg)
4065  {
4066  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
4067  $this->error.=($this->error?', '.$errmsg:$errmsg);
4068  }
4069  $this->db->rollback();
4070  return -1*$error;
4071  }
4072  else
4073  {
4074  $this->error=$this->db->lasterror();
4075  return -1;
4076  }
4077  }
4078 
4086  function insert($user=null, $notrigger=0)
4087  {
4088  global $langs, $conf;
4089 
4090  $error=0;
4091 
4092  $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4093 
4094  dol_syslog(get_class($this)."::insert rang=".$this->rang);
4095 
4096  // Clean parameters
4097  if (empty($this->tva_tx)) $this->tva_tx=0;
4098  if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4099  if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4100  if (empty($this->localtax1_type)) $this->localtax1_type=0;
4101  if (empty($this->localtax2_type)) $this->localtax2_type=0;
4102  if (empty($this->total_localtax1)) $this->total_localtax1=0;
4103  if (empty($this->total_localtax2)) $this->total_localtax2=0;
4104  if (empty($this->rang)) $this->rang=0;
4105  if (empty($this->remise)) $this->remise=0;
4106  if (empty($this->remise_percent)) $this->remise_percent=0;
4107  if (empty($this->info_bits)) $this->info_bits=0;
4108  if (empty($this->special_code)) $this->special_code=0;
4109  if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4110  if (empty($this->pa_ht)) $this->pa_ht=0;
4111 
4112  // if buy price not defined, define buyprice as configured in margin admin
4113  if ($this->pa_ht == 0 && $pa_ht_isemptystring)
4114  {
4115  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
4116  {
4117  return $result;
4118  }
4119  else
4120  {
4121  $this->pa_ht = $result;
4122  }
4123  }
4124 
4125  // Check parameters
4126  if ($this->product_type < 0) return -1;
4127 
4128  $this->db->begin();
4129 
4130  // Insertion dans base de la ligne
4131  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'commandedet';
4132  $sql.= ' (fk_commande, fk_parent_line, label, description, qty, ';
4133  $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4134  $sql.= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
4135  $sql.= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
4136  $sql.= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
4137  $sql.= ' fk_unit';
4138  $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4139  $sql.= ')';
4140  $sql.= " VALUES (".$this->fk_commande.",";
4141  $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
4142  $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
4143  $sql.= " '".$this->db->escape($this->desc)."',";
4144  $sql.= " '".price2num($this->qty)."',";
4145  $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
4146  $sql.= " '".price2num($this->tva_tx)."',";
4147  $sql.= " '".price2num($this->localtax1_tx)."',";
4148  $sql.= " '".price2num($this->localtax2_tx)."',";
4149  $sql.= " '".$this->db->escape($this->localtax1_type)."',";
4150  $sql.= " '".$this->db->escape($this->localtax2_type)."',";
4151  $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
4152  $sql.= " '".$this->db->escape($this->product_type)."',";
4153  $sql.= " '".price2num($this->remise_percent)."',";
4154  $sql.= " ".(price2num($this->subprice)!==''?price2num($this->subprice):"null").",";
4155  $sql.= " ".($this->price!=''?"'".price2num($this->price)."'":"null").",";
4156  $sql.= " '".price2num($this->remise)."',";
4157  $sql.= ' '.(! empty($this->fk_remise_except)?$this->fk_remise_except:"null").',';
4158  $sql.= ' '.$this->special_code.',';
4159  $sql.= ' '.$this->rang.',';
4160  $sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").',';
4161  $sql.= ' '.price2num($this->pa_ht).',';
4162  $sql.= " '".$this->db->escape($this->info_bits)."',";
4163  $sql.= " ".price2num($this->total_ht).",";
4164  $sql.= " ".price2num($this->total_tva).",";
4165  $sql.= " ".price2num($this->total_localtax1).",";
4166  $sql.= " ".price2num($this->total_localtax2).",";
4167  $sql.= " ".price2num($this->total_ttc).",";
4168  $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
4169  $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").',';
4170  $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4171  $sql.= ", ".(! empty($this->fk_multicurrency) ? $this->fk_multicurrency : 'NULL');
4172  $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
4173  $sql.= ", ".$this->multicurrency_subprice;
4174  $sql.= ", ".$this->multicurrency_total_ht;
4175  $sql.= ", ".$this->multicurrency_total_tva;
4176  $sql.= ", ".$this->multicurrency_total_ttc;
4177  $sql.= ')';
4178 
4179  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
4180  $resql=$this->db->query($sql);
4181  if ($resql)
4182  {
4183  $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
4184 
4185  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4186  {
4187  $this->id=$this->rowid;
4188  $result=$this->insertExtraFields();
4189  if ($result < 0)
4190  {
4191  $error++;
4192  }
4193  }
4194 
4195  if (! $error && ! $notrigger)
4196  {
4197  // Call trigger
4198  $result=$this->call_trigger('LINEORDER_INSERT',$user);
4199  if ($result < 0) $error++;
4200  // End call triggers
4201  }
4202 
4203  if (!$error) {
4204  $this->db->commit();
4205  return 1;
4206  }
4207 
4208  foreach($this->errors as $errmsg)
4209  {
4210  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
4211  $this->error.=($this->error?', '.$errmsg:$errmsg);
4212  }
4213  $this->db->rollback();
4214  return -1*$error;
4215  }
4216  else
4217  {
4218  $this->error=$this->db->error();
4219  $this->db->rollback();
4220  return -2;
4221  }
4222  }
4223 
4231  function update(User $user, $notrigger=0)
4232  {
4233  global $conf,$langs;
4234 
4235  $error=0;
4236 
4237  $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4238 
4239  // Clean parameters
4240  if (empty($this->tva_tx)) $this->tva_tx=0;
4241  if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
4242  if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
4243  if (empty($this->localtax1_type)) $this->localtax1_type=0;
4244  if (empty($this->localtax2_type)) $this->localtax2_type=0;
4245  if (empty($this->qty)) $this->qty=0;
4246  if (empty($this->total_localtax1)) $this->total_localtax1=0;
4247  if (empty($this->total_localtax2)) $this->total_localtax2=0;
4248  if (empty($this->marque_tx)) $this->marque_tx=0;
4249  if (empty($this->marge_tx)) $this->marge_tx=0;
4250  if (empty($this->remise)) $this->remise=0;
4251  if (empty($this->remise_percent)) $this->remise_percent=0;
4252  if (empty($this->info_bits)) $this->info_bits=0;
4253  if (empty($this->special_code)) $this->special_code=0;
4254  if (empty($this->product_type)) $this->product_type=0;
4255  if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
4256  if (empty($this->pa_ht)) $this->pa_ht=0;
4257 
4258  // if buy price not defined, define buyprice as configured in margin admin
4259  if ($this->pa_ht == 0 && $pa_ht_isemptystring)
4260  {
4261  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
4262  {
4263  return $result;
4264  }
4265  else
4266  {
4267  $this->pa_ht = $result;
4268  }
4269  }
4270 
4271  $this->db->begin();
4272 
4273  // Mise a jour ligne en base
4274  $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
4275  $sql.= " description='".$this->db->escape($this->desc)."'";
4276  $sql.= " , label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
4277  $sql.= " , vat_src_code=".(! empty($this->vat_src_code)?"'".$this->db->escape($this->vat_src_code)."'":"''");
4278  $sql.= " , tva_tx=".price2num($this->tva_tx);
4279  $sql.= " , localtax1_tx=".price2num($this->localtax1_tx);
4280  $sql.= " , localtax2_tx=".price2num($this->localtax2_tx);
4281  $sql.= " , localtax1_type='".$this->db->escape($this->localtax1_type)."'";
4282  $sql.= " , localtax2_type='".$this->db->escape($this->localtax2_type)."'";
4283  $sql.= " , qty=".price2num($this->qty);
4284  $sql.= " , subprice=".price2num($this->subprice)."";
4285  $sql.= " , remise_percent=".price2num($this->remise_percent)."";
4286  $sql.= " , price=".price2num($this->price).""; // TODO A virer
4287  $sql.= " , remise=".price2num($this->remise).""; // TODO A virer
4288  if (empty($this->skip_update_total))
4289  {
4290  $sql.= " , total_ht=".price2num($this->total_ht)."";
4291  $sql.= " , total_tva=".price2num($this->total_tva)."";
4292  $sql.= " , total_ttc=".price2num($this->total_ttc)."";
4293  $sql.= " , total_localtax1=".price2num($this->total_localtax1);
4294  $sql.= " , total_localtax2=".price2num($this->total_localtax2);
4295  }
4296  $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?$this->fk_fournprice:"null");
4297  $sql.= " , buy_price_ht='".price2num($this->pa_ht)."'";
4298  $sql.= " , info_bits=".$this->info_bits;
4299  $sql.= " , special_code=".$this->special_code;
4300  $sql.= " , date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
4301  $sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
4302  $sql.= " , product_type=".$this->product_type;
4303  $sql.= " , fk_parent_line=".(! empty($this->fk_parent_line)?$this->fk_parent_line:"null");
4304  if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
4305  $sql.= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4306 
4307  // Multicurrency
4308  $sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
4309  $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
4310  $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
4311  $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
4312 
4313  $sql.= " WHERE rowid = ".$this->rowid;
4314 
4315  dol_syslog(get_class($this)."::update", LOG_DEBUG);
4316  $resql=$this->db->query($sql);
4317  if ($resql)
4318  {
4319  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
4320  {
4321  $this->id=$this->rowid;
4322  $result=$this->insertExtraFields();
4323  if ($result < 0)
4324  {
4325  $error++;
4326  }
4327  }
4328 
4329  if (! $error && ! $notrigger)
4330  {
4331  // Call trigger
4332  $result=$this->call_trigger('LINEORDER_UPDATE',$user);
4333  if ($result < 0) $error++;
4334  // End call triggers
4335  }
4336 
4337  if (!$error) {
4338  $this->db->commit();
4339  return 1;
4340  }
4341 
4342  foreach($this->errors as $errmsg)
4343  {
4344  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
4345  $this->error.=($this->error?', '.$errmsg:$errmsg);
4346  }
4347  $this->db->rollback();
4348  return -1*$error;
4349  }
4350  else
4351  {
4352  $this->error=$this->db->error();
4353  $this->db->rollback();
4354  return -2;
4355  }
4356  }
4357 
4358  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4365  function update_total()
4366  {
4367  // phpcs:enable
4368  $this->db->begin();
4369 
4370  // Clean parameters
4371  if (empty($this->total_localtax1)) $this->total_localtax1=0;
4372  if (empty($this->total_localtax2)) $this->total_localtax2=0;
4373 
4374  // Mise a jour ligne en base
4375  $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
4376  $sql.= " total_ht='".price2num($this->total_ht)."'";
4377  $sql.= ",total_tva='".price2num($this->total_tva)."'";
4378  $sql.= ",total_localtax1='".price2num($this->total_localtax1)."'";
4379  $sql.= ",total_localtax2='".price2num($this->total_localtax2)."'";
4380  $sql.= ",total_ttc='".price2num($this->total_ttc)."'";
4381  $sql.= " WHERE rowid = ".$this->rowid;
4382 
4383  dol_syslog("OrderLine::update_total", LOG_DEBUG);
4384 
4385  $resql=$this->db->query($sql);
4386  if ($resql)
4387  {
4388  $this->db->commit();
4389  return 1;
4390  }
4391  else
4392  {
4393  $this->error=$this->db->error();
4394  $this->db->rollback();
4395  return -2;
4396  }
4397  }
4398 }
print $object label
hash of file content (md5_file(dol_osencode($destfull))
Definition: edit.php:153
getNbOfProductsLines()
Return number of line with type product.
Class to manage stock movements.
const STATUS_CLOSED
Closed (Sent, billed or not)
getLinesArray()
Create an array of order lines.
print
Draft customers invoices.
Definition: index.php:91
if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) if(! empty($conf->don->enabled) && $user->rights->societe->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) && $user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1053
static getIdFromCode(&$db, $code)
Get id of currency from code.
set_date($user, $date, $notrigger=0)
Set the order date.
cancel($idwarehouse=-1)
Cancel an order If stock is decremented on order validation, we must reincrement it.
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
set_draft($user, $idwarehouse=-1)
Set draft status.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
Delete all links between an object $this.
LibStatut($statut, $billed, $mode, $donotshowbilled=0)
Return label of status.
getNextNumRef($soc)
Returns the reference to the following non used Order depending on the active numbering module define...
update(User $user, $notrigger=0)
Update the line object into db.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0)
Add an order line into database (linked to product/service or not)
getNbOfServicesLines()
Return number of line with type service.
hasDelay()
Is the customer order delayed?
demand_reason($demand_reason_id, $notrigger=0)
Update order demand_reason.
createFromClone($socid=0)
Load an object from its id and create a new one in database.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
__construct($db)
Constructor.
if(! empty($search_group)) natural_search(array("g.nom" g note
Definition: list.php:123
Class to manage products or services.
set_remise($user, $remise, $notrigger=0)
Applique une remise relative.
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1324
loadExpeditions($filtre_statut=-1)
Load array this->expeditions of lines of shipments with nb of products sent for each order line Note:...
Class to manage Dolibarr users.
Definition: user.class.php:41
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Class to manage Dolibarr database access.
initAsSpecimen()
Initialise an instance with random values.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
classifyBilled(User $user, $notrigger=0)
Classify the order as invoiced.
valid($user, $idwarehouse=0, $notrigger=0)
Validate order.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
const STATUS_SHIPMENTONPROCESS
Shipment on process.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
availability($availability_id, $notrigger=0)
Update delivery delay.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
set_date_livraison($user, $date_livraison, $notrigger=0)
Set the planned delivery date.
get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller Note: This function applies same rules than get_default_tva.
nb_expedition()
Returns a array with expeditions lines number.
info($id)
Charge les informations d&#39;ordre info dans l&#39;objet commande.
set_remise_absolue($user, $remise, $notrigger=0)
Applique une remise absolue.
Class to manage order lines.
$table_ref_field
{}
stock_array($filtre_statut=self::STATUS_CANCELED)
Return a array with the pending stock by product.
const STOCK_NOT_ENOUGH_FOR_ORDER
ERR Not enough stock.
Class to manage standard extra fields.
create($user, $notrigger=0)
Create order Note that this->ref can be set or empty.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
insert_discount($idremise)
Adding line of fixed discount in the order in DB.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
Class to manage third parties objects (customers, suppliers, prospects...)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
if(! function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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)...
insert($user=null, $notrigger=0)
Insert line into database.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
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.
Class to manage customers orders.
const STATUS_DRAFT
Draft status.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
Definition: files.lib.php:1273
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:1139
deleteExtraFields()
Delete all extra fields values for the current object.
set_reopen($user)
Tag the order as validated (opened) Function used when order is reopend after being closed...
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:59
deleteline($user=null, $lineid=0)
Delete an order line.
getLibStatut($mode)
Return status label of Order.
dol_now($mode='gmt')
Return date for now.
fetch($id, $ref='', $ref_ext='', $ref_int='')
Get object and lines from database.
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...
Superclass for orders classes.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0)
Calculate totals (net, vat, ...) of a line.
Definition: price.lib.php:85
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages...
dol_print_date($time, $format='', $tzoutput='tzserver', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
const STATUS_VALIDATED
Validated status.
Superclass for orders classes.
cloture($user, $notrigger=0)
Close order.
fetch_lines($only_product=0)
Load array lines.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) Si ...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
getLabelSource()
Return source label of order.
classifyUnBilled()
Classify the order as not invoiced.
Class to manage absolute discounts.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=0, $fk_unit=null, $pu_ht_devise=0, $notrigger=0)
Update a line in database.
add_product($idproduct, $qty, $remise_percent=0.0, $date_start='', $date_end='')
Add line into array $this->client must be loaded.
call_trigger($trigger_name, $user)
Call trigger based on this instance.
load_state_board()
Charge indicateurs this->nb de tableau de bord.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
update(User $user, $notrigger=0)
Update database.
add_object_linked($origin=null, $origin_id=null)
Add objects linked in llx_element_element.
createFromProposal($object, User $user)
Load an object from a proposal and create a new order into database.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='')
Show picto whatever it&#39;s its name (generic function)
update_total()
Update DB line fields total_xxx Used by migration.
price2num($amount, $rounding='', $alreadysqlnb=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1)
Return clicable link of object (with eventually picto)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
liste_array($shortlist=0, $draft=0, $excluser='', $socid=0, $limit=0, $offset=0, $sortfield='c.date_commande', $sortorder='DESC')
Return list of orders (eventuelly filtered on a user) into an array.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
fetch($rowid)
Load line order.
showDelay()
Show the customer delayed info.
getNbOfShipments()
Count numbe rof shipments for this order.
__construct($db)
Constructor.
static getIdAndTxFromCode(&$db, $code, $date_document='')
Get id and rate of currency from code.
set_ref_client($user, $ref_client, $notrigger=0)
Set customer ref.
const STATUS_CANCELED
Canceled status.