dolibarr  9.0.0
fournisseur.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-2017 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
6  * Copyright (C) 2010-2014 Juanjo Menent <jmenent@2byte.es>
7  * Copyright (C) 2010-2018 Philippe Grand <philippe.grand@atoo-net.com>
8  * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
9  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10  * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
11  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
12  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
13  * Copyright (C) 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 
35 include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
37 if (! empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
39 
44 {
48  public $element='order_supplier';
49 
53  public $table_element='commande_fournisseur';
54 
58  public $table_element_line = 'commande_fournisseurdet';
59 
63  public $fk_element = 'fk_commande';
64 
65  public $picto='order';
66 
71  public $ismultientitymanaged = 1;
72 
77  public $restrictiononfksoc = 1;
78 
82  protected $table_ref_field = 'ref';
83 
87  public $id;
88 
93  public $ref;
94 
95  public $ref_supplier;
96  public $brouillon;
97  public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
98  // -> 7=Canceled/Never received -> (reopen) 3=Process runing
99  // -> 6=Canceled -> (reopen) 2=Approved
100  // -> 9=Refused -> (reopen) 1=Validated
101  // Note: billed or not is on another field "billed"
102  public $statuts; // List of status
103 
104  public $socid;
105  public $fourn_id;
106  public $date;
107  public $date_valid;
108  public $date_approve;
109  public $date_approve2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
110  public $date_commande;
111 
116 
117  public $total_ht;
118  public $total_tva;
119  public $total_localtax1; // Total Local tax 1
120  public $total_localtax2; // Total Local tax 2
121  public $total_ttc;
122  public $source;
123 
128  public $note;
129 
130  public $note_private;
131  public $note_public;
132  public $model_pdf;
133 
137  public $fk_project;
138 
139  public $cond_reglement_id;
140  public $cond_reglement_code;
141 
145  public $fk_account;
146 
147  public $mode_reglement_id;
148  public $mode_reglement_code;
149  public $user_author_id;
150  public $user_valid_id;
151  public $user_approve_id;
152  public $user_approve_id2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
153 
154  //Incoterms
155  public $fk_incoterms;
156  public $location_incoterms;
157  public $libelle_incoterms; //Used into tooltip
158 
159  public $extraparams=array();
160 
164  public $lines = array();
165 
166  //Add for supplier_proposal
167  public $origin;
168  public $origin_id;
169  public $linked_objects=array();
170 
171  // Multicurrency
175  public $fk_multicurrency;
176 
177  public $multicurrency_code;
178  public $multicurrency_tx;
179  public $multicurrency_total_ht;
180  public $multicurrency_total_tva;
181  public $multicurrency_total_ttc;
182 
186  const STATUS_DRAFT = 0;
187 
191  const STATUS_VALIDATED = 1;
192 
196  const STATUS_ACCEPTED = 2;
197 
201  const STATUS_ORDERSENT = 3;
202 
207 
212 
216  const STATUS_CANCELED = 6;
217 
222 
226  const STATUS_REFUSED = 9;
227 
228 
229 
230 
236  public function __construct($db)
237  {
238  $this->db = $db;
239 
240  $this->products = array();
241  }
242 
243 
251  public function fetch($id, $ref='')
252  {
253  global $conf;
254 
255  // Check parameters
256  if (empty($id) && empty($ref)) return -1;
257 
258  $sql = "SELECT c.rowid, c.entity, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_vat,";
259  $sql.= " c.localtax1, c.localtax2, ";
260  $sql.= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
261  $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,";
262  $sql.= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
263  $sql.= " c.fk_account,";
264  $sql.= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,";
265  $sql.= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
266  $sql.= " cm.libelle as methode_commande,";
267  $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
268  $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
269  $sql.= ', c.fk_incoterms, c.location_incoterms';
270  $sql.= ', i.libelle as libelle_incoterms';
271  $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
272  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid";
273  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id";
274  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method";
275  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
276  $sql.= " WHERE c.entity = ".$conf->entity;
277  if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'";
278  else $sql.= " AND c.rowid=".$id;
279 
280  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
281  $resql = $this->db->query($sql);
282  if ($resql)
283  {
284  $obj = $this->db->fetch_object($resql);
285  if (! $obj)
286  {
287  $this->error='Bill with id '.$id.' not found';
288  dol_syslog(get_class($this).'::fetch '.$this->error);
289  return 0;
290  }
291 
292  $this->id = $obj->rowid;
293  $this->entity = $obj->entity;
294 
295  $this->ref = $obj->ref;
296  $this->ref_supplier = $obj->ref_supplier;
297  $this->socid = $obj->fk_soc;
298  $this->fourn_id = $obj->fk_soc;
299  $this->statut = $obj->fk_statut;
300  $this->billed = $obj->billed;
301  $this->user_author_id = $obj->fk_user_author;
302  $this->user_valid_id = $obj->fk_user_valid;
303  $this->user_approve_id = $obj->fk_user_approve;
304  $this->user_approve_id2 = $obj->fk_user_approve2;
305  $this->total_ht = $obj->total_ht;
306  $this->total_tva = $obj->total_vat;
307  $this->total_localtax1 = $obj->localtax1;
308  $this->total_localtax2 = $obj->localtax2;
309  $this->total_ttc = $obj->total_ttc;
310  $this->date = $this->db->jdate($obj->date_creation);
311  $this->date_valid = $this->db->jdate($obj->date_valid);
312  $this->date_approve = $this->db->jdate($obj->date_approve);
313  $this->date_approve2 = $this->db->jdate($obj->date_approve2);
314  $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier
315  $this->date_livraison = $this->db->jdate($obj->date_livraison);
316  $this->remise_percent = $obj->remise_percent;
317  $this->methode_commande_id = $obj->fk_input_method;
318  $this->methode_commande = $obj->methode_commande;
319 
320  $this->source = $obj->source;
321  $this->fk_project = $obj->fk_project;
322  $this->cond_reglement_id = $obj->fk_cond_reglement;
323  $this->cond_reglement_code = $obj->cond_reglement_code;
324  $this->cond_reglement = $obj->cond_reglement_libelle;
325  $this->cond_reglement_doc = $obj->cond_reglement_libelle;
326  $this->fk_account = $obj->fk_account;
327  $this->mode_reglement_id = $obj->fk_mode_reglement;
328  $this->mode_reglement_code = $obj->mode_reglement_code;
329  $this->mode_reglement = $obj->mode_reglement_libelle;
330  $this->note = $obj->note_private; // deprecated
331  $this->note_private = $obj->note_private;
332  $this->note_public = $obj->note_public;
333  $this->modelpdf = $obj->model_pdf;
334 
335  //Incoterms
336  $this->fk_incoterms = $obj->fk_incoterms;
337  $this->location_incoterms = $obj->location_incoterms;
338  $this->libelle_incoterms = $obj->libelle_incoterms;
339 
340  // Multicurrency
341  $this->fk_multicurrency = $obj->fk_multicurrency;
342  $this->multicurrency_code = $obj->multicurrency_code;
343  $this->multicurrency_tx = $obj->multicurrency_tx;
344  $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
345  $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
346  $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
347 
348  $this->extraparams = (array) json_decode($obj->extraparams, true);
349 
350  $this->db->free($resql);
351 
352  // Retreive all extrafield
353  // fetch optionals attributes and labels
354  $this->fetch_optionals();
355 
356  if ($this->statut == 0) $this->brouillon = 1;
357 
358  /*
359  * Lines
360  */
361  $result=$this->fetch_lines();
362  if ($result < 0)
363  {
364  return -1;
365  }
366  else
367  {
368  return 1;
369  }
370  }
371  else
372  {
373  $this->error=$this->db->error()." sql=".$sql;
374  return -1;
375  }
376  }
377 
378  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
385  function fetch_lines($only_product=0)
386  {
387  // phpcs:enable
388  //$result=$this->fetch_lines();
389  $this->lines=array();
390 
391  $sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
392  $sql.= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
393  $sql.= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
394  $sql.= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,";
395  $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,";
396  $sql.= " l.fk_unit,";
397  $sql.= " l.date_start, l.date_end,";
398  $sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
399  $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l";
400  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
401  $sql.= " WHERE l.fk_commande = ".$this->id;
402  if ($only_product) $sql .= ' AND p.fk_product_type = 0';
403  $sql.= " ORDER BY l.rang, l.rowid";
404  //print $sql;
405 
406  dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG);
407  $result = $this->db->query($sql);
408  if ($result)
409  {
410  $num = $this->db->num_rows($result);
411  $i = 0;
412 
413  while ($i < $num)
414  {
415  $objp = $this->db->fetch_object($result);
416 
417  $line = new CommandeFournisseurLigne($this->db);
418 
419  $line->id = $objp->rowid;
420  $line->desc = $objp->description;
421  $line->description = $objp->description;
422  $line->qty = $objp->qty;
423  $line->tva_tx = $objp->tva_tx;
424  $line->localtax1_tx = $objp->localtax1_tx;
425  $line->localtax2_tx = $objp->localtax2_tx;
426  $line->localtax1_type = $objp->localtax1_type;
427  $line->localtax2_type = $objp->localtax2_type;
428  $line->subprice = $objp->subprice;
429  $line->pu_ht = $objp->subprice;
430  $line->remise_percent = $objp->remise_percent;
431 
432  $line->vat_src_code = $objp->vat_src_code;
433  $line->total_ht = $objp->total_ht;
434  $line->total_tva = $objp->total_tva;
435  $line->total_localtax1 = $objp->total_localtax1;
436  $line->total_localtax2 = $objp->total_localtax2;
437  $line->total_ttc = $objp->total_ttc;
438  $line->product_type = $objp->product_type;
439 
440  $line->fk_product = $objp->fk_product;
441 
442  $line->libelle = $objp->product_label;
443  $line->product_label = $objp->product_label;
444  $line->product_desc = $objp->product_desc;
445 
446  $line->ref = $objp->product_ref; // Ref of product
447  $line->product_ref = $objp->product_ref; // Ref of product
448  $line->ref_fourn = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
449  $line->ref_supplier = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
450 
451  $line->date_start = $this->db->jdate($objp->date_start);
452  $line->date_end = $this->db->jdate($objp->date_end);
453  $line->fk_unit = $objp->fk_unit;
454 
455  // Multicurrency
456  $line->fk_multicurrency = $objp->fk_multicurrency;
457  $line->multicurrency_code = $objp->multicurrency_code;
458  $line->multicurrency_subprice = $objp->multicurrency_subprice;
459  $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
460  $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
461  $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
462 
463  $line->special_code = $objp->special_code;
464  $line->fk_parent_line = $objp->fk_parent_line;
465 
466  $line->rang = $objp->rang;
467 
468  // Retreive all extrafield
469  // fetch optionals attributes and labels
470  $line->fetch_optionals();
471 
472  $this->lines[$i] = $line;
473 
474  $i++;
475  }
476  $this->db->free($result);
477 
478  return $num;
479  }
480  else
481  {
482  $this->error=$this->db->error()." sql=".$sql;
483  return -1;
484  }
485  }
486 
495  public function valid($user,$idwarehouse=0,$notrigger=0)
496  {
497  global $langs,$conf;
498  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
499 
500  $error=0;
501 
502  dol_syslog(get_class($this)."::valid");
503  $result = 0;
504  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer))
505  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate)))
506  {
507  $this->db->begin();
508 
509  // Definition of supplier order numbering model name
510  $soc = new Societe($this->db);
511  $soc->fetch($this->fourn_id);
512 
513  // Check if object has a temporary ref
514  if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
515  {
516  $num = $this->getNextNumRef($soc);
517  }
518  else
519  {
520  $num = $this->ref;
521  }
522  $this->newref = $num;
523 
524  $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur";
525  $sql.= " SET ref='".$this->db->escape($num)."',";
526  $sql.= " fk_statut = ".self::STATUS_VALIDATED.",";
527  $sql.= " date_valid='".$this->db->idate(dol_now())."',";
528  $sql.= " fk_user_valid = ".$user->id;
529  $sql.= " WHERE rowid = ".$this->id;
530  $sql.= " AND fk_statut = ".self::STATUS_DRAFT;
531 
532  $resql=$this->db->query($sql);
533  if (! $resql)
534  {
535  dol_print_error($this->db);
536  $error++;
537  }
538 
539  if (! $error && ! $notrigger)
540  {
541  // Call trigger
542  $result=$this->call_trigger('ORDER_SUPPLIER_VALIDATE',$user);
543  if ($result < 0) $error++;
544  // End call triggers
545  }
546 
547  if (! $error)
548  {
549  $this->oldref = $this->ref;
550 
551  // Rename directory if dir was a temporary ref
552  if (preg_match('/^[\(]?PROV/i', $this->ref))
553  {
554  // We rename directory ($this->ref = ancienne ref, $num = nouvelle ref)
555  // in order not to lose the attached files
556  $oldref = dol_sanitizeFileName($this->ref);
557  $newref = dol_sanitizeFileName($num);
558  $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref;
559  $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref;
560  if (file_exists($dirsource))
561  {
562  dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
563 
564  if (@rename($dirsource, $dirdest))
565  {
566  dol_syslog("Rename ok");
567  // Rename docs starting with $oldref with $newref
568  $listoffiles=dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
569  foreach($listoffiles as $fileentry)
570  {
571  $dirsource=$fileentry['name'];
572  $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
573  $dirsource=$fileentry['path'].'/'.$dirsource;
574  $dirdest=$fileentry['path'].'/'.$dirdest;
575  @rename($dirsource, $dirdest);
576  }
577  }
578  }
579  }
580  }
581 
582  if (! $error)
583  {
584  $result = 1;
585  $this->statut = self::STATUS_VALIDATED;
586  $this->ref = $num;
587  }
588 
589  if (! $error)
590  {
591  $this->db->commit();
592  return 1;
593  }
594  else
595  {
596  $this->db->rollback();
597  return -1;
598  }
599  }
600  else
601  {
602  $this->error='NotAuthorized';
603  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
604  return -1;
605  }
606  }
607 
614  public function getLibStatut($mode=0)
615  {
616  return $this->LibStatut($this->statut,$mode,$this->billed);
617  }
618 
619  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
628  function LibStatut($statut,$mode=0,$billed=0)
629  {
630  // phpcs:enable
631  global $conf, $langs;
632 
633  if (empty($this->statuts) || empty($this->statutshort))
634  {
635  $langs->load('orders');
636 
637  $this->statuts[0] = 'StatusOrderDraft';
638  $this->statuts[1] = 'StatusOrderValidated';
639  $this->statuts[2] = 'StatusOrderApproved';
640  if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusOrderOnProcess';
641  else $this->statuts[3] = 'StatusOrderOnProcessWithValidation';
642  $this->statuts[4] = 'StatusOrderReceivedPartially';
643  $this->statuts[5] = 'StatusOrderReceivedAll';
644  $this->statuts[6] = 'StatusOrderCanceled'; // Approved->Canceled
645  $this->statuts[7] = 'StatusOrderCanceled'; // Process running->canceled
646  //$this->statuts[8] = 'StatusOrderBilled'; // Everything is finished, order received totally and bill received
647  $this->statuts[9] = 'StatusOrderRefused';
648 
649  // List of language codes for status
650  $this->statutshort[0] = 'StatusOrderDraftShort';
651  $this->statutshort[1] = 'StatusOrderValidatedShort';
652  $this->statutshort[2] = 'StatusOrderApprovedShort';
653  $this->statutshort[3] = 'StatusOrderOnProcessShort';
654  $this->statutshort[4] = 'StatusOrderReceivedPartiallyShort';
655  $this->statutshort[5] = 'StatusOrderReceivedAllShort';
656  $this->statutshort[6] = 'StatusOrderCanceledShort';
657  $this->statutshort[7] = 'StatusOrderCanceledShort';
658  $this->statutshort[9] = 'StatusOrderRefusedShort';
659  }
660 
661  $billedtext='';
662  //if ($statut==5 && $this->billed == 1) $statut = 8;
663  if ($billed == 1) $billedtext=$langs->trans("Billed");
664 
665  if ($mode == 0)
666  {
667  return $langs->trans($this->statuts[$statut]);
668  }
669  elseif ($mode == 1)
670  {
671  return $langs->trans($this->statutshort[$statut]);
672  }
673  elseif ($mode == 2)
674  {
675  return $langs->trans($this->statuts[$statut]);
676  }
677  elseif ($mode == 3)
678  {
679  if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0');
680  elseif ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1');
681  elseif ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
682  elseif ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
683  elseif ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3');
684  elseif ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6');
685  elseif ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
686  elseif ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5');
687  }
688  elseif ($mode == 4)
689  {
690  if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
691  elseif ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
692  elseif ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
693  elseif ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
694  elseif ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
695  elseif ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
696  elseif ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
697  elseif ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:'');
698  }
699  elseif ($mode == 5)
700  {
701  if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut0');
702  elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut1');
703  elseif ($statut==2) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
704  elseif ($statut==3) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
705  elseif ($statut==4) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut3');
706  elseif ($statut==5) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut6');
707  elseif ($statut==6 || $statut==7) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
708  elseif ($statut==9) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),'statut5');
709  }
710  }
711 
712 
722  public function getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1)
723  {
724  global $langs, $conf;
725 
726  $result='';
727  $label = '<u>' . $langs->trans("ShowOrder") . '</u>';
728  if (! empty($this->ref))
729  $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
730  if (! empty($this->ref_supplier))
731  $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
732  if (! empty($this->total_ht))
733  $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
734  if (! empty($this->total_tva))
735  $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
736  if (! empty($this->total_ttc))
737  $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
738 
739  $picto='order';
740  $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
741 
742  if ($option !== 'nolink')
743  {
744  // Add param to save lastsearch_values or not
745  $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
746  if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
747  if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
748  }
749 
750  $linkclose='';
751  if (empty($notooltip))
752  {
753  if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
754  {
755  $label=$langs->trans("ShowOrder");
756  $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
757  }
758  $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
759  $linkclose.=' class="classfortooltip"';
760  }
761 
762  $linkstart = '<a href="'.$url.'"';
763  $linkstart.=$linkclose.'>';
764  $linkend='</a>';
765 
766  $result .= $linkstart;
767  if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
768  if ($withpicto != 2) $result.= $this->ref;
769  $result .= $linkend;
770 
771  return $result;
772  }
773 
774 
782  public function getNextNumRef($soc)
783  {
784  global $db, $langs, $conf;
785  $langs->load("orders");
786 
787  if (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
788  {
789  $mybool = false;
790 
791  $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
792  $classname=$conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
793 
794  // Include file with class
795  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
796 
797  foreach ($dirmodels as $reldir) {
798 
799  $dir = dol_buildpath($reldir."core/modules/supplier_order/");
800 
801  // Load file with numbering class (if found)
802  $mybool|=@include_once $dir.$file;
803  }
804 
805  if ($mybool === false) {
806  dol_print_error('',"Failed to include file ".$file);
807  return '';
808  }
809 
810  $obj = new $classname();
811  $numref = $obj->getNextValue($soc,$this);
812 
813  if ( $numref != "")
814  {
815  return $numref;
816  }
817  else
818  {
819  $this->error = $obj->error;
820  return -1;
821  }
822  }
823  else
824  {
825  $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
826  return -2;
827  }
828  }
835  public function classifyBilled(User $user)
836  {
837  $error=0;
838  $this->db->begin();
839 
840  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1';
841  $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
842  if ($this->db->query($sql))
843  {
844  if (! $error)
845  {
846  // Call trigger
847  $result=$this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED',$user);
848  if ($result < 0) $error++;
849  // End call triggers
850  }
851 
852  if (! $error)
853  {
854  $this->billed=1;
855 
856  $this->db->commit();
857  return 1;
858  }
859  else
860  {
861  $this->db->rollback();
862  return -1;
863  }
864  }
865  else
866  {
867  dol_print_error($this->db);
868 
869  $this->db->rollback();
870  return -1;
871  }
872  }
873 
882  public function approve($user, $idwarehouse=0, $secondlevel=0)
883  {
884  global $langs,$conf;
885  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
886 
887  $error=0;
888 
889  dol_syslog(get_class($this)."::approve");
890 
891  if ($user->rights->fournisseur->commande->approuver)
892  {
893  $now = dol_now();
894 
895  $this->db->begin();
896 
897  // Definition of order numbering model name
898  $soc = new Societe($this->db);
899  $soc->fetch($this->fourn_id);
900 
901  // Check if object has a temporary ref
902  if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
903  {
904  $num = $this->getNextNumRef($soc);
905  }
906  else
907  {
908  $num = $this->ref;
909  }
910  $this->newref = $num;
911 
912  // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
913  $movetoapprovestatus=true;
914  $comment='';
915 
916  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
917  $sql.= " SET ref='".$this->db->escape($num)."',";
918  if (empty($secondlevel)) // standard or first level approval
919  {
920  $sql.= " date_approve='".$this->db->idate($now)."',";
921  $sql.= " fk_user_approve = ".$user->id;
922  if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
923  {
924  if (empty($this->user_approve_id2))
925  {
926  $movetoapprovestatus=false; // second level approval not done
927  $comment=' (first level)';
928  }
929  }
930  }
931  else // request a second level approval
932  {
933  $sql.= " date_approve2='".$this->db->idate($now)."',";
934  $sql.= " fk_user_approve2 = ".$user->id;
935  if (empty($this->user_approve_id)) $movetoapprovestatus=false; // first level approval not done
936  $comment=' (second level)';
937  }
938  // If double approval is required and first approval, we keep status to 1 = validated
939  if ($movetoapprovestatus) $sql.= ", fk_statut = ".self::STATUS_ACCEPTED;
940  else $sql.= ", fk_statut = ".self::STATUS_VALIDATED;
941  $sql.= " WHERE rowid = ".$this->id;
942  $sql.= " AND fk_statut = ".self::STATUS_VALIDATED;
943 
944  if ($this->db->query($sql))
945  {
946  if (! empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
947  {
948  $result=$this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
949  if ($result < 0 && $result != -2) // -2 means already exists
950  {
951  $error++;
952  }
953  }
954 
955  // If stock is incremented on validate order, we must increment it
956  if (! $error && $movetoapprovestatus && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER))
957  {
958  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
959  $langs->load("agenda");
960 
961  $cpt=count($this->lines);
962  for ($i = 0; $i < $cpt; $i++)
963  {
964  // Product with reference
965  if ($this->lines[$i]->fk_product > 0)
966  {
967  $this->line = $this->lines[$i];
968  $mouvP = new MouvementStock($this->db);
969  $mouvP->origin = &$this;
970  // We decrement stock of product (and sub-products)
971  $up_ht_disc=$this->lines[$i]->subprice;
972  if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
973  $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr",$this->ref));
974  if ($result < 0) { $error++; }
975  unset($this->line);
976  }
977  }
978  }
979 
980  if (! $error)
981  {
982  // Call trigger
983  $result=$this->call_trigger('ORDER_SUPPLIER_APPROVE',$user);
984  if ($result < 0) $error++;
985  // End call triggers
986  }
987 
988  if (! $error)
989  {
990  $this->ref = $this->newref;
991 
992  if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED;
993  else $this->statut = self::STATUS_VALIDATED;
994  if (empty($secondlevel)) // standard or first level approval
995  {
996  $this->date_approve = $now;
997  $this->user_approve_id = $user->id;
998  }
999  else // request a second level approval
1000  {
1001  $this->date_approve2 = $now;
1002  $this->user_approve_id2 = $user->id;
1003  }
1004 
1005  $this->db->commit();
1006  return 1;
1007  }
1008  else
1009  {
1010  $this->db->rollback();
1011  return -1;
1012  }
1013  }
1014  else
1015  {
1016  $this->db->rollback();
1017  $this->error=$this->db->lasterror();
1018  return -1;
1019  }
1020  }
1021  else
1022  {
1023  dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
1024  }
1025  return -1;
1026  }
1027 
1034  public function refuse($user)
1035  {
1036  global $conf, $langs;
1037 
1038  $error=0;
1039 
1040  dol_syslog(get_class($this)."::refuse");
1041  $result = 0;
1042  if ($user->rights->fournisseur->commande->approuver)
1043  {
1044  $this->db->begin();
1045 
1046  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED;
1047  $sql .= " WHERE rowid = ".$this->id;
1048 
1049  if ($this->db->query($sql))
1050  {
1051  $result = 0;
1052 
1053  if ($error == 0)
1054  {
1055  // Call trigger
1056  $result=$this->call_trigger('ORDER_SUPPLIER_REFUSE',$user);
1057  if ($result < 0)
1058  {
1059  $error++;
1060  $this->db->rollback();
1061  }
1062  else
1063  $this->db->commit();
1064  // End call triggers
1065  }
1066  }
1067  else
1068  {
1069  $this->db->rollback();
1070  $this->error=$this->db->lasterror();
1071  dol_syslog(get_class($this)."::refuse Error -1");
1072  $result = -1;
1073  }
1074  }
1075  else
1076  {
1077  dol_syslog(get_class($this)."::refuse Not Authorized");
1078  }
1079  return $result ;
1080  }
1081 
1082  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1091  function Cancel($user, $idwarehouse=-1)
1092  {
1093  // phpcs:enable
1094  global $langs,$conf;
1095 
1096  $error=0;
1097 
1098  //dol_syslog("CommandeFournisseur::Cancel");
1099  $result = 0;
1100  if ($user->rights->fournisseur->commande->commander)
1101  {
1102  $statut = self::STATUS_CANCELED;
1103 
1104  $this->db->begin();
1105 
1106  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut;
1107  $sql .= " WHERE rowid = ".$this->id;
1108  dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
1109  if ($this->db->query($sql))
1110  {
1111  $result = 0;
1112 
1113  // Call trigger
1114  $result=$this->call_trigger('ORDER_SUPPLIER_CANCEL',$user);
1115  if ($result < 0) $error++;
1116  // End call triggers
1117 
1118  if ($error == 0)
1119  {
1120  $this->db->commit();
1121  return 1;
1122  }
1123  else
1124  {
1125  $this->db->rollback();
1126  return -1;
1127  }
1128  }
1129  else
1130  {
1131  $this->db->rollback();
1132  $this->error=$this->db->lasterror();
1133  dol_syslog(get_class($this)."::cancel ".$this->error);
1134  return -1;
1135  }
1136  }
1137  else
1138  {
1139  dol_syslog(get_class($this)."::cancel Not Authorized");
1140  return -1;
1141  }
1142  }
1143 
1153  public function commande($user, $date, $methode, $comment='')
1154  {
1155  global $langs;
1156  dol_syslog(get_class($this)."::commande");
1157  $error = 0;
1158  if ($user->rights->fournisseur->commande->commander)
1159  {
1160  $this->db->begin();
1161 
1162  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."'";
1163  $sql .= " WHERE rowid = ".$this->id;
1164 
1165  dol_syslog(get_class($this)."::commande", LOG_DEBUG);
1166  if ($this->db->query($sql))
1167  {
1168  $this->statut = self::STATUS_ORDERSENT;
1169  $this->methode_commande_id = $methode;
1170  $this->date_commande = $date;
1171 
1172  // Call trigger
1173  $result=$this->call_trigger('ORDER_SUPPLIER_SUBMIT',$user);
1174  if ($result < 0) $error++;
1175  // End call triggers
1176  }
1177  else
1178  {
1179  $error++;
1180  $this->error = $this->db->lasterror();
1181  $this->errors[] = $this->db->lasterror();
1182  }
1183 
1184  if (! $error)
1185  {
1186  $this->db->commit();
1187  }
1188  else
1189  {
1190  $this->db->rollback();
1191  }
1192  }
1193  else
1194  {
1195  $error++;
1196  $this->error = $langs->trans('NotAuthorized');
1197  $this->errors[] = $langs->trans('NotAuthorized');
1198  dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
1199  }
1200 
1201  return ($error ? -1 : 1);
1202  }
1203 
1211  public function create($user, $notrigger=0)
1212  {
1213  global $langs,$conf,$hookmanager;
1214 
1215  $this->db->begin();
1216 
1217  $error=0;
1218  $now=dol_now();
1219 
1220  // Clean parameters
1221  if (empty($this->source)) $this->source = 0;
1222 
1223  // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1224  if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
1225  else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1226  if (empty($this->fk_multicurrency))
1227  {
1228  $this->multicurrency_code = $conf->currency;
1229  $this->fk_multicurrency = 0;
1230  $this->multicurrency_tx = 1;
1231  }
1232 
1233  // We set order into draft status
1234  $this->brouillon = 1;
1235 
1236  $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
1237  $sql.= "ref";
1238  $sql.= ", ref_supplier";
1239  $sql.= ", note_private";
1240  $sql.= ", note_public";
1241  $sql.= ", entity";
1242  $sql.= ", fk_soc";
1243  $sql.= ", fk_projet";
1244  $sql.= ", date_creation";
1245  $sql.= ", date_livraison";
1246  $sql.= ", fk_user_author";
1247  $sql.= ", fk_statut";
1248  $sql.= ", source";
1249  $sql.= ", model_pdf";
1250  $sql.= ", fk_mode_reglement";
1251  $sql.= ", fk_cond_reglement";
1252  $sql.= ", fk_account";
1253  $sql.= ", fk_incoterms, location_incoterms";
1254  $sql.= ", fk_multicurrency";
1255  $sql.= ", multicurrency_code";
1256  $sql.= ", multicurrency_tx";
1257  $sql.= ") ";
1258  $sql.= " VALUES (";
1259  $sql.= "''";
1260  $sql.= ", '".$this->db->escape($this->ref_supplier)."'";
1261  $sql.= ", '".$this->db->escape($this->note_private)."'";
1262  $sql.= ", '".$this->db->escape($this->note_public)."'";
1263  $sql.= ", ".$conf->entity;
1264  $sql.= ", ".$this->socid;
1265  $sql.= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
1266  $sql.= ", '".$this->db->idate($now)."'";
1267  $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
1268  $sql.= ", ".$user->id;
1269  $sql.= ", ".self::STATUS_DRAFT;
1270  $sql.= ", ".$this->db->escape($this->source);
1271  $sql.= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'";
1272  $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1273  $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1274  $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
1275  $sql.= ", ".(int) $this->fk_incoterms;
1276  $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
1277  $sql.= ", ".(int) $this->fk_multicurrency;
1278  $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
1279  $sql.= ", ".(double) $this->multicurrency_tx;
1280  $sql.= ")";
1281 
1282  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1283  if ($this->db->query($sql))
1284  {
1285  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur");
1286 
1287  if ($this->id) {
1288  $num=count($this->lines);
1289 
1290  // insert products details into database
1291  for ($i=0;$i<$num;$i++)
1292  {
1293 
1294  $this->special_code = $this->lines[$i]->special_code; // TODO : remove this in 9.0 and add special_code param to addline()
1295 
1296  $result = $this->addline( // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1297  $this->lines[$i]->desc,
1298  $this->lines[$i]->subprice,
1299  $this->lines[$i]->qty,
1300  $this->lines[$i]->tva_tx,
1301  $this->lines[$i]->localtax1_tx,
1302  $this->lines[$i]->localtax2_tx,
1303  $this->lines[$i]->fk_product,
1304  0,
1305  $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
1306  $this->lines[$i]->remise_percent,
1307  'HT',
1308  0,
1309  $this->lines[$i]->product_type,
1310  $this->lines[$i]->info_bits,
1311  false,
1312  $this->lines[$i]->date_start,
1313  $this->lines[$i]->date_end,
1314  0,
1315  $this->lines[$i]->fk_unit
1316  );
1317  if ($result < 0)
1318  {
1319  dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functionnal error
1320  $this->db->rollback();
1321  return -1;
1322  }
1323  }
1324 
1325  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
1326  $sql.= " SET ref='(PROV".$this->id.")'";
1327  $sql.= " WHERE rowid=".$this->id;
1328  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1329  if ($this->db->query($sql))
1330  {
1331  // Add link with price request and supplier order
1332  if ($this->id)
1333  {
1334  $this->ref="(PROV".$this->id.")";
1335 
1336  if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
1337  {
1338  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1339  }
1340 
1341  // Add object linked
1342  if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
1343  {
1344  foreach($this->linked_objects as $origin => $tmp_origin_id)
1345  {
1346  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, ...))
1347  {
1348  foreach($tmp_origin_id as $origin_id)
1349  {
1350  $ret = $this->add_object_linked($origin, $origin_id);
1351  if (! $ret)
1352  {
1353  dol_print_error($this->db);
1354  $error++;
1355  }
1356  }
1357  }
1358  else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1359  {
1360  $origin_id = $tmp_origin_id;
1361  $ret = $this->add_object_linked($origin, $origin_id);
1362  if (! $ret)
1363  {
1364  dol_print_error($this->db);
1365  $error++;
1366  }
1367  }
1368  }
1369  }
1370  }
1371 
1372  if (! $error)
1373  {
1374  $result=$this->insertExtraFields();
1375  if ($result < 0) $error++;
1376  }
1377 
1378  if (! $error && ! $notrigger)
1379  {
1380  // Call trigger
1381  $result=$this->call_trigger('ORDER_SUPPLIER_CREATE',$user);
1382  if ($result < 0)
1383  {
1384  $this->db->rollback();
1385  return -1;
1386  }
1387  // End call triggers
1388  }
1389 
1390  $this->db->commit();
1391  return $this->id;
1392  }
1393  else
1394  {
1395  $this->error=$this->db->lasterror();
1396  $this->db->rollback();
1397  return -2;
1398  }
1399  }
1400  }
1401  else
1402  {
1403  $this->error=$this->db->lasterror();
1404  $this->db->rollback();
1405  return -1;
1406  }
1407  }
1408 
1414  public function createFromClone()
1415  {
1416  global $conf,$user,$langs,$hookmanager;
1417 
1418  $error=0;
1419 
1420  $this->db->begin();
1421 
1422  // Load source object
1423  $objFrom = clone $this;
1424 
1425  $this->id=0;
1426  $this->statut=self::STATUS_DRAFT;
1427 
1428  // Clear fields
1429  $this->user_author_id = $user->id;
1430  $this->user_valid = '';
1431  $this->date_creation = '';
1432  $this->date_validation = '';
1433  $this->ref_supplier = '';
1434  $this->user_approve_id = '';
1435  $this->user_approve_id2 = '';
1436  $this->date_approve = '';
1437  $this->date_approve2 = '';
1438 
1439  // Create clone
1440  $this->context['createfromclone'] = 'createfromclone';
1441  $result=$this->create($user);
1442  if ($result < 0) $error++;
1443 
1444  if (! $error)
1445  {
1446  // Hook of thirdparty module
1447  if (is_object($hookmanager))
1448  {
1449  $parameters=array('objFrom'=>$objFrom);
1450  $action='';
1451  $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
1452  if ($reshook < 0) $error++;
1453  }
1454  }
1455 
1456  unset($this->context['createfromclone']);
1457 
1458  // End
1459  if (! $error)
1460  {
1461  $this->db->commit();
1462  return $this->id;
1463  }
1464  else
1465  {
1466  $this->db->rollback();
1467  return -1;
1468  }
1469  }
1470 
1498  public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $ref_supplier='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=false, $date_start=null, $date_end=null, $array_options=0, $fk_unit=null, $pu_ht_devise=0, $origin='', $origin_id=0)
1499  {
1500  global $langs,$mysoc,$conf;
1501 
1502  $error = 0;
1503 
1504  dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type, $info_bits, $notrigger, $date_start, $date_end, $fk_unit, $pu_ht_devise, $origin, $origin_id");
1505  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1506 
1507  if ($this->statut == self::STATUS_DRAFT)
1508  {
1509  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1510 
1511  // Clean parameters
1512  if (! $qty) $qty=1;
1513  if (! $info_bits) $info_bits=0;
1514  if (empty($txtva)) $txtva=0;
1515  if (empty($txlocaltax1)) $txlocaltax1=0;
1516  if (empty($txlocaltax2)) $txlocaltax2=0;
1517  if (empty($remise_percent)) $remise_percent=0;
1518 
1519  $remise_percent=price2num($remise_percent);
1520  $qty=price2num($qty);
1521  $pu_ht=price2num($pu_ht);
1522  $pu_ht_devise=price2num($pu_ht_devise);
1523  $pu_ttc=price2num($pu_ttc);
1524  if (!preg_match('/\((.*)\)/', $txtva)) {
1525  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1526  }
1527  $txlocaltax1 = price2num($txlocaltax1);
1528  $txlocaltax2 = price2num($txlocaltax2);
1529  if ($price_base_type=='HT')
1530  {
1531  $pu=$pu_ht;
1532  }
1533  else
1534  {
1535  $pu=$pu_ttc;
1536  }
1537  $desc=trim($desc);
1538 
1539  // Check parameters
1540  if ($qty < 1 && ! $fk_product)
1541  {
1542  $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Product"));
1543  return -1;
1544  }
1545  if ($type < 0) return -1;
1546 
1547 
1548  $this->db->begin();
1549 
1550  if ($fk_product > 0)
1551  {
1552  if (! empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY))
1553  {
1554  // Check quantity is enough
1555  dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_prod_fourn_price=".$fk_prod_fourn_price." qty=".$qty." ref_supplier=".$ref_supplier);
1556  $prod = new Product($this->db, $fk_product);
1557  if ($prod->fetch($fk_product) > 0)
1558  {
1559  $product_type = $prod->type;
1560  $label = $prod->label;
1561 
1562  // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
1563  // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
1564  $result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', ($this->fk_soc?$this->fk_soc:$this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->fk_soc
1565  // If supplier order created from customer order, we take best supplier price
1566  // If $pu (defined previously from pu_ht or pu_ttc) is not defined at all, we also take the best supplier price
1567  if ($result > 0 && ($origin == 'commande' || $pu === ''))
1568  {
1569  $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
1570  $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
1571  // is remise percent not keyed but present for the product we add it
1572  if ($remise_percent == 0 && $prod->remise_percent !=0) $remise_percent =$prod->remise_percent;
1573  }
1574  if ($result == 0) // If result == 0, we failed to found the supplier reference price
1575  {
1576  $langs->load("errors");
1577  $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1578  $this->db->rollback();
1579  dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
1580  //$pu = $prod->fourn_pu; // We do not overwrite unit price
1581  //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
1582  return -1;
1583  }
1584  if ($result == -1)
1585  {
1586  $langs->load("errors");
1587  $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier");
1588  $this->db->rollback();
1589  dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
1590  return -1;
1591  }
1592  if ($result < -1)
1593  {
1594  $this->error=$prod->error;
1595  $this->db->rollback();
1596  dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
1597  return -1;
1598  }
1599  }
1600  else
1601  {
1602  $this->error=$prod->error;
1603  $this->db->rollback();
1604  return -1;
1605  }
1606  }
1607  }
1608  else
1609  {
1610  $product_type = $type;
1611  }
1612 
1613  if ($conf->multicurrency->enabled && $pu_ht_devise > 0) {
1614  $pu = 0;
1615  }
1616 
1617  $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc,$this->thirdparty);
1618 
1619  // Clean vat code
1620  $vat_src_code='';
1621  if (preg_match('/\((.*)\)/', $txtva, $reg))
1622  {
1623  $vat_src_code = $reg[1];
1624  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
1625  }
1626 
1627  // Calcul du total TTC et de la TVA pour la ligne a partir de
1628  // qty, pu, remise_percent et txtva
1629  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1630  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1631 
1632  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx,$pu_ht_devise);
1633 
1634  $total_ht = $tabprice[0];
1635  $total_tva = $tabprice[1];
1636  $total_ttc = $tabprice[2];
1637  $total_localtax1 = $tabprice[9];
1638  $total_localtax2 = $tabprice[10];
1639  $pu = $pu_ht = $tabprice[3];
1640 
1641  // MultiCurrency
1642  $multicurrency_total_ht = $tabprice[16];
1643  $multicurrency_total_tva = $tabprice[17];
1644  $multicurrency_total_ttc = $tabprice[18];
1645  $pu_ht_devise = $tabprice[19];
1646 
1647  $localtax1_type=$localtaxes_type[0];
1648  $localtax2_type=$localtaxes_type[2];
1649 
1650  $subprice = price2num($pu,'MU');
1651 
1652  $rangmax = $this->line_max();
1653  $rang = $rangmax + 1;
1654 
1655  // Insert line
1656  $this->line=new CommandeFournisseurLigne($this->db);
1657 
1658  $this->line->context = $this->context;
1659 
1660  $this->line->fk_commande=$this->id;
1661  $this->line->label=$label;
1662  $this->line->ref_fourn = $ref_supplier;
1663  $this->line->ref_supplier = $ref_supplier;
1664  $this->line->desc=$desc;
1665  $this->line->qty=$qty;
1666  $this->line->tva_tx=$txtva;
1667  $this->line->localtax1_tx=($total_localtax1?$localtaxes_type[1]:0);
1668  $this->line->localtax2_tx=($total_localtax2?$localtaxes_type[3]:0);
1669  $this->line->localtax1_type = $localtaxes_type[0];
1670  $this->line->localtax2_type = $localtaxes_type[2];
1671  $this->line->fk_product=$fk_product;
1672  $this->line->product_type=$product_type;
1673  $this->line->remise_percent=$remise_percent;
1674  $this->line->subprice=$pu_ht;
1675  $this->line->rang=$rang;
1676  $this->line->info_bits=$info_bits;
1677 
1678  $this->line->vat_src_code=$vat_src_code;
1679  $this->line->total_ht=$total_ht;
1680  $this->line->total_tva=$total_tva;
1681  $this->line->total_localtax1=$total_localtax1;
1682  $this->line->total_localtax2=$total_localtax2;
1683  $this->line->total_ttc=$total_ttc;
1684  $this->line->product_type=$type;
1685  $this->line->special_code=$this->special_code;
1686  $this->line->origin=$origin;
1687  $this->line->origin_id=$origin_id;
1688  $this->line->fk_unit=$fk_unit;
1689 
1690  $this->line->date_start=$date_start;
1691  $this->line->date_end=$date_end;
1692 
1693  // Multicurrency
1694  $this->line->fk_multicurrency = $this->fk_multicurrency;
1695  $this->line->multicurrency_code = $this->multicurrency_code;
1696  $this->line->multicurrency_subprice = $pu_ht_devise;
1697  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
1698  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
1699  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
1700 
1701  $this->line->subprice=$pu_ht;
1702  $this->line->price=$this->line->subprice;
1703 
1704  $this->line->remise_percent=$remise_percent;
1705 
1706  if (is_array($array_options) && count($array_options)>0) {
1707  $this->line->array_options=$array_options;
1708  }
1709 
1710  $result=$this->line->insert($notrigger);
1711  if ($result > 0)
1712  {
1713  // Reorder if child line
1714  if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
1715 
1716  // Mise a jour informations denormalisees au niveau de la commande meme
1717  $result=$this->update_price(1,'auto',0,$this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1718  if ($result > 0)
1719  {
1720  $this->db->commit();
1721  return $this->line->id;
1722  }
1723  else
1724  {
1725  $this->db->rollback();
1726  return -1;
1727  }
1728  }
1729  else
1730  {
1731  $this->error=$this->line->error;
1732  $this->errors=$this->line->errors;
1733  dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1734  $this->db->rollback();
1735  return -1;
1736  }
1737  }
1738  }
1739 
1740 
1757  public function dispatchProduct($user, $product, $qty, $entrepot, $price=0, $comment='', $eatby='', $sellby='', $batch='', $fk_commandefourndet=0, $notrigger=0)
1758  {
1759  global $conf, $langs;
1760 
1761  $error = 0;
1762  require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php';
1763 
1764  // Check parameters (if test are wrong here, there is bug into caller)
1765  if ($entrepot <= 0)
1766  {
1767  $this->error='ErrorBadValueForParameterWarehouse';
1768  return -1;
1769  }
1770  if ($qty == 0)
1771  {
1772  $this->error='ErrorBadValueForParameterQty';
1773  return -1;
1774  }
1775 
1776  $dispatchstatus = 1;
1777  if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
1778 
1779  $now=dol_now();
1780 
1781  if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY))
1782  {
1783  $this->db->begin();
1784 
1785  $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch";
1786  $sql.= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES";
1787  $sql.= " ('".$this->id."','".$product."','".$qty."',".($entrepot>0?"'".$entrepot."'":"null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
1788  $sql.= ($eatby?"'".$this->db->idate($eatby)."'":"null").", ".($sellby?"'".$this->db->idate($sellby)."'":"null").", ".($batch?"'".$batch."'":"null");
1789  $sql.= ")";
1790 
1791  dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
1792  $resql = $this->db->query($sql);
1793  if ($resql)
1794  {
1795  if (! $notrigger)
1796  {
1797  global $conf, $langs, $user;
1798  // Call trigger
1799  $result=$this->call_trigger('LINEORDER_SUPPLIER_DISPATCH',$user);
1800  if ($result < 0)
1801  {
1802  $error++;
1803  return -1;
1804  }
1805  // End call triggers
1806  }
1807  }
1808  else
1809  {
1810  $this->error=$this->db->lasterror();
1811  $error++;
1812  }
1813 
1814  // Si module stock gere et que incrementation faite depuis un dispatching en stock
1815  if (! $error && $entrepot > 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
1816  {
1817 
1818  $mouv = new MouvementStock($this->db);
1819  if ($product > 0)
1820  {
1821  // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
1822  $mouv->origin = &$this;
1823  $result=$mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch);
1824  if ($result < 0)
1825  {
1826  $this->error=$mouv->error;
1827  $this->errors=$mouv->errors;
1828  dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',',$this->errors), LOG_ERR);
1829  $error++;
1830  }
1831  }
1832  }
1833 
1834  if ($error == 0)
1835  {
1836  $this->db->commit();
1837  return 1;
1838  }
1839  else
1840  {
1841  $this->db->rollback();
1842  return -1;
1843  }
1844  }
1845  else
1846  {
1847  $this->error='BadStatusForObject';
1848  return -2;
1849  }
1850  }
1851 
1859  public function deleteline($idline, $notrigger=0)
1860  {
1861  if ($this->statut == 0)
1862  {
1863  $line = new CommandeFournisseurLigne($this->db);
1864 
1865  if ($line->fetch($idline) <= 0)
1866  {
1867  return 0;
1868  }
1869 
1870  if ($line->delete($notrigger) > 0)
1871  {
1872  $this->update_price();
1873  return 1;
1874  }
1875  else
1876  {
1877  $this->error = $line->error;
1878  $this->errors = $line->errors;
1879  return -1;
1880  }
1881  }
1882  else
1883  {
1884  return -2;
1885  }
1886  }
1887 
1895  public function delete(User $user, $notrigger=0)
1896  {
1897  global $langs,$conf;
1898  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1899 
1900  $error = 0;
1901 
1902  $this->db->begin();
1903 
1904  if (empty($notrigger))
1905  {
1906  // Call trigger
1907  $result=$this->call_trigger('ORDER_SUPPLIER_DELETE',$user);
1908  if ($result < 0)
1909  {
1910  $this->errors[]='ErrorWhenRunningTrigger';
1911  dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1912  return -1;
1913  }
1914  // End call triggers
1915  }
1916 
1917  $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =". $this->id ;
1918  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1919  if (! $this->db->query($sql) )
1920  {
1921  $this->error=$this->db->lasterror();
1922  $this->errors[]=$this->db->lasterror();
1923  $error++;
1924  }
1925 
1926  $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".$this->id;
1927  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1928  if ($resql = $this->db->query($sql) )
1929  {
1930  if ($this->db->affected_rows($resql) < 1)
1931  {
1932  $this->error=$this->db->lasterror();
1933  $this->errors[]=$this->db->lasterror();
1934  $error++;
1935  }
1936  }
1937  else
1938  {
1939  $this->error=$this->db->lasterror();
1940  $this->errors[]=$this->db->lasterror();
1941  $error++;
1942  }
1943 
1944  // Remove extrafields
1945  if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1946  {
1947  $result=$this->deleteExtraFields();
1948  if ($result < 0)
1949  {
1950  $this->error='FailToDeleteExtraFields';
1951  $this->errors[]='FailToDeleteExtraFields';
1952  $error++;
1953  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1954  }
1955  }
1956 
1957  // Delete linked object
1958  $res = $this->deleteObjectLinked();
1959  if ($res < 0) {
1960  $this->error='FailToDeleteObjectLinked';
1961  $this->errors[]='FailToDeleteObjectLinked';
1962  $error++;
1963  }
1964 
1965  if (! $error)
1966  {
1967  // We remove directory
1968  $ref = dol_sanitizeFileName($this->ref);
1969  if ($conf->fournisseur->commande->dir_output)
1970  {
1971  $dir = $conf->fournisseur->commande->dir_output . "/" . $ref ;
1972  $file = $dir . "/" . $ref . ".pdf";
1973  if (file_exists($file))
1974  {
1975  if (! dol_delete_file($file,0,0,0,$this)) // For triggers
1976  {
1977  $this->error='ErrorFailToDeleteFile';
1978  $this->errors[]='ErrorFailToDeleteFile';
1979  $error++;
1980  }
1981  }
1982  if (file_exists($dir))
1983  {
1984  $res=@dol_delete_dir_recursive($dir);
1985  if (! $res)
1986  {
1987  $this->error='ErrorFailToDeleteDir';
1988  $this->errors[]='ErrorFailToDeleteDir';
1989  $error++;
1990  }
1991  }
1992  }
1993  }
1994 
1995  if (! $error)
1996  {
1997  dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
1998  $this->db->commit();
1999  return 1;
2000  }
2001  else
2002  {
2003  dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2004  $this->db->rollback();
2005  return -$error;
2006  }
2007  }
2008 
2009  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2016  {
2017  // phpcs:enable
2018  $sql = "SELECT rowid, libelle";
2019  $sql.= " FROM ".MAIN_DB_PREFIX."c_input_method";
2020  $sql.= " WHERE active = 1";
2021 
2022  $resql=$this->db->query($sql);
2023  if ($resql)
2024  {
2025  $i = 0;
2026  $num = $this->db->num_rows($resql);
2027  $this->methodes_commande = array();
2028  while ($i < $num)
2029  {
2030  $row = $this->db->fetch_row($resql);
2031 
2032  $this->methodes_commande[$row[0]] = $row[1];
2033 
2034  $i++;
2035  }
2036  return 0;
2037  }
2038  else
2039  {
2040  return -1;
2041  }
2042  }
2043 
2052  public function getDispachedLines($status=-1)
2053  {
2054  $ret = array();
2055 
2056  // List of already dispatched lines
2057  $sql = "SELECT p.ref, p.label,";
2058  $sql.= " e.rowid as warehouse_id, e.ref as entrepot,";
2059  $sql.= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status";
2060  $sql.= " FROM ".MAIN_DB_PREFIX."product as p,";
2061  $sql.= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd";
2062  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid";
2063  $sql.= " WHERE cfd.fk_commande = ".$this->id;
2064  $sql.= " AND cfd.fk_product = p.rowid";
2065  if ($status >= 0) $sql.=" AND cfd.status = ".$status;
2066  $sql.= " ORDER BY cfd.rowid ASC";
2067 
2068  $resql = $this->db->query($sql);
2069  if ($resql)
2070  {
2071  $num = $this->db->num_rows($resql);
2072  $i = 0;
2073 
2074  while ($i < $num)
2075  {
2076  $objp = $this->db->fetch_object($resql);
2077  if ($objp)
2078  {
2079  $ret[] = array(
2080  'id' => $objp->dispatchedlineid,
2081  'productid' => $objp->fk_product,
2082  'warehouseid' => $objp->warehouse_id,
2083  'qty' => $objp->qty,
2084  );
2085  }
2086 
2087  $i++;
2088  }
2089  }
2090  else dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
2091 
2092  return $ret;
2093  }
2094 
2095 
2096  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2106  function Livraison($user, $date, $type, $comment)
2107  {
2108  // phpcs:enable
2109  global $conf, $langs;
2110 
2111  $result = 0;
2112  $error = 0;
2113 
2114  dol_syslog(get_class($this)."::Livraison");
2115 
2116  if ($user->rights->fournisseur->commande->receptionner)
2117  {
2118  // Define the new status
2119  if ($type == 'par') $statut = self::STATUS_RECEIVED_PARTIALLY;
2120  elseif ($type == 'tot') $statut = self::STATUS_RECEIVED_COMPLETELY;
2121  elseif ($type == 'nev') $statut = self::STATUS_CANCELED_AFTER_ORDER;
2122  elseif ($type == 'can') $statut = self::STATUS_CANCELED_AFTER_ORDER;
2123  else {
2124  $error++;
2125  dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
2126  return -2;
2127  }
2128 
2129  // Some checks to accept the record
2130  if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS))
2131  {
2132  // If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
2133  if (! $error && ($type == 'tot'))
2134  {
2135  $dispatchedlinearray=$this->getDispachedLines(0);
2136  if (count($dispatchedlinearray) > 0)
2137  {
2138  $result=-1;
2139  $error++;
2140  $this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
2141  dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
2142  }
2143  }
2144  if (! $error && ! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot')) // Accept to move to reception done, only if status of all line are ok (refuse denied)
2145  {
2146  $dispatcheddenied=$this->getDispachedLines(2);
2147  if (count($dispatchedlinearray) > 0)
2148  {
2149  $result=-1;
2150  $error++;
2151  $this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
2152  dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
2153  }
2154  }
2155  }
2156 
2157  // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
2158 
2159 
2160  if (! $error)
2161  {
2162  $this->db->begin();
2163 
2164  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2165  $sql.= " SET fk_statut = ".$statut;
2166  $sql.= " WHERE rowid = ".$this->id;
2167  $sql.= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received
2168 
2169  dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2170  $resql=$this->db->query($sql);
2171  if ($resql)
2172  {
2173  $result = 0;
2174  $old_statut = $this->statut;
2175  $this->statut = $statut;
2176  $this->actionmsg2 = $comment;
2177 
2178  // Call trigger
2179  $result=$this->call_trigger('ORDER_SUPPLIER_RECEIVE',$user);
2180  if ($result < 0) $error++;
2181  // End call triggers
2182 
2183  if (! $error)
2184  {
2185  $this->db->commit();
2186  }
2187  else
2188  {
2189  $this->statut = $old_statut;
2190  $this->db->rollback();
2191  $this->error=$this->db->lasterror();
2192  $result = -1;
2193  }
2194  }
2195  else
2196  {
2197  $this->db->rollback();
2198  $this->error=$this->db->lasterror();
2199  $result = -1;
2200  }
2201  }
2202  }
2203  else
2204  {
2205  $this->error = $langs->trans('NotAuthorized');
2206  $this->errors[] = $langs->trans('NotAuthorized');
2207  dol_syslog(get_class($this)."::Livraison Not Authorized");
2208  $result = -3;
2209  }
2210  return $result ;
2211  }
2212 
2213  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2222  function set_date_livraison($user, $date_livraison, $notrigger=0)
2223  {
2224  // phpcs:enable
2225  if ($user->rights->fournisseur->commande->creer)
2226  {
2227  $error=0;
2228 
2229  $this->db->begin();
2230 
2231  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2232  $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
2233  $sql.= " WHERE rowid = ".$this->id;
2234 
2235  dol_syslog(__METHOD__, LOG_DEBUG);
2236  $resql=$this->db->query($sql);
2237  if (!$resql)
2238  {
2239  $this->errors[]=$this->db->error();
2240  $error++;
2241  }
2242 
2243  if (! $error)
2244  {
2245  $this->oldcopy= clone $this;
2246  $this->date_livraison = $date_livraison;
2247  }
2248 
2249  if (! $notrigger && empty($error))
2250  {
2251  // Call trigger
2252  $result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2253  if ($result < 0) $error++;
2254  // End call triggers
2255  }
2256 
2257  if (! $error)
2258  {
2259  $this->db->commit();
2260  return 1;
2261  }
2262  else
2263  {
2264  foreach($this->errors as $errmsg)
2265  {
2266  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2267  $this->error.=($this->error?', '.$errmsg:$errmsg);
2268  }
2269  $this->db->rollback();
2270  return -1*$error;
2271  }
2272  }
2273  else
2274  {
2275  return -2;
2276  }
2277  }
2278 
2279  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2288  function set_id_projet($user, $id_projet, $notrigger=0)
2289  {
2290  // phpcs:enable
2291  if ($user->rights->fournisseur->commande->creer)
2292  {
2293  $error=0;
2294 
2295  $this->db->begin();
2296 
2297  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2298  $sql.= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2299  $sql.= " WHERE rowid = ".$this->id;
2300 
2301  dol_syslog(__METHOD__, LOG_DEBUG);
2302  $resql=$this->db->query($sql);
2303  if (!$resql)
2304  {
2305  $this->errors[]=$this->db->error();
2306  $error++;
2307  }
2308 
2309  if (! $error)
2310  {
2311  $this->oldcopy= clone $this;
2312  $this->fk_projet = $id_projet;
2313  }
2314 
2315  if (! $notrigger && empty($error))
2316  {
2317  // Call trigger
2318  $result=$this->call_trigger('ORDER_SUPPLIER_MODIFY',$user);
2319  if ($result < 0) $error++;
2320  // End call triggers
2321  }
2322 
2323  if (! $error)
2324  {
2325  $this->db->commit();
2326  return 1;
2327  }
2328  else
2329  {
2330  foreach($this->errors as $errmsg)
2331  {
2332  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2333  $this->error.=($this->error?', '.$errmsg:$errmsg);
2334  }
2335  $this->db->rollback();
2336  return -1*$error;
2337  }
2338  }
2339  else
2340  {
2341  return -2;
2342  }
2343  }
2344 
2353  public function updateFromCommandeClient($user, $idc, $comclientid)
2354  {
2355  $comclient = new Commande($this->db);
2356  $comclient->fetch($comclientid);
2357 
2358  $this->id = $idc;
2359 
2360  $this->lines = array();
2361 
2362  $num=count($comclient->lines);
2363  for ($i = 0; $i < $num; $i++)
2364  {
2365  $prod = new Product($this->db);
2366  $libelle = '';
2367  $ref = '';
2368  if ($prod->fetch($comclient->lines[$i]->fk_product) > 0)
2369  {
2370  $libelle = $prod->libelle;
2371  $ref = $prod->ref;
2372  }
2373 
2374  $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet";
2375  $sql .= " (fk_commande,label,description,fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
2376  $sql .= " VALUES (".$idc.", '" . $this->db->escape($libelle) . "','" . $this->db->escape($comclient->lines[$i]->desc) . "'";
2377  $sql .= ",".$comclient->lines[$i]->fk_product.",'".price2num($comclient->lines[$i]->price)."'";
2378  $sql .= ", '".$comclient->lines[$i]->qty."', ".$comclient->lines[$i]->tva_tx.", ".$comclient->lines[$i]->localtax1_tx.", ".$comclient->lines[$i]->localtax2_tx.", ".$comclient->lines[$i]->remise_percent;
2379  $sql .= ", '".price2num($comclient->lines[$i]->subprice)."','0','".$ref."');";
2380  if ($this->db->query($sql))
2381  {
2382  $this->update_price();
2383  }
2384  }
2385 
2386  return 1;
2387  }
2388 
2396  public function setStatus($user, $status)
2397  {
2398  global $conf,$langs;
2399  $error=0;
2400 
2401  $this->db->begin();
2402 
2403  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
2404  $sql.= ' SET fk_statut='.$status;
2405  $sql.= ' WHERE rowid = '.$this->id;
2406 
2407  dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
2408  $resql = $this->db->query($sql);
2409  if ($resql)
2410  {
2411  // Trigger names for each status
2412  $trigger_name[0] = 'DRAFT';
2413  $trigger_name[1] = 'VALIDATED';
2414  $trigger_name[2] = 'APPROVED';
2415  $trigger_name[3] = 'ORDERED'; // Ordered
2416  $trigger_name[4] = 'RECEIVED_PARTIALLY';
2417  $trigger_name[5] = 'RECEIVED_COMPLETELY';
2418  $trigger_name[6] = 'CANCELED';
2419  $trigger_name[7] = 'CANCELED';
2420  $trigger_name[9] = 'REFUSED';
2421 
2422  // Call trigger
2423  $result=$this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status],$user);
2424  if ($result < 0) { $error++; }
2425  // End call triggers
2426  }
2427  else
2428  {
2429  $error++;
2430  $this->error=$this->db->lasterror();
2431  dol_syslog(get_class($this)."::setStatus ".$this->error);
2432  }
2433 
2434  if (! $error)
2435  {
2436  $this->statut = $status;
2437  $this->db->commit();
2438  return 1;
2439  }
2440  else
2441  {
2442  $this->db->rollback();
2443  return -1;
2444  }
2445  }
2446 
2470  public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise=0, $ref_supplier='')
2471  {
2472  global $mysoc, $conf;
2473  dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
2474  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2475 
2476  $error = 0;
2477 
2478  if ($this->brouillon)
2479  {
2480  $this->db->begin();
2481 
2482  // Clean parameters
2483  if (empty($qty)) $qty=0;
2484  if (empty($info_bits)) $info_bits=0;
2485  if (empty($txtva)) $txtva=0;
2486  if (empty($txlocaltax1)) $txlocaltax1=0;
2487  if (empty($txlocaltax2)) $txlocaltax2=0;
2488  if (empty($remise)) $remise=0;
2489  if (empty($remise_percent)) $remise_percent=0;
2490 
2491  $remise_percent=price2num($remise_percent);
2492  $qty=price2num($qty);
2493  if (! $qty) $qty=1;
2494  $pu = price2num($pu);
2495  $pu_ht_devise=price2num($pu_ht_devise);
2496  $txtva=price2num($txtva);
2497  $txlocaltax1=price2num($txlocaltax1);
2498  $txlocaltax2=price2num($txlocaltax2);
2499 
2500  // Check parameters
2501  if ($type < 0) return -1;
2502 
2503  // Calcul du total TTC et de la TVA pour la ligne a partir de
2504  // qty, pu, remise_percent et txtva
2505  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2506  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2507 
2508  $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc, $this->thirdparty);
2509 
2510  // Clean vat code
2511  $vat_src_code='';
2512  if (preg_match('/\((.*)\)/', $txtva, $reg))
2513  {
2514  $vat_src_code = $reg[1];
2515  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
2516  }
2517 
2518  $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
2519  $total_ht = $tabprice[0];
2520  $total_tva = $tabprice[1];
2521  $total_ttc = $tabprice[2];
2522  $total_localtax1 = $tabprice[9];
2523  $total_localtax2 = $tabprice[10];
2524  $pu_ht = $tabprice[3];
2525  $pu_tva = $tabprice[4];
2526  $pu_ttc = $tabprice[5];
2527 
2528  // MultiCurrency
2529  $multicurrency_total_ht = $tabprice[16];
2530  $multicurrency_total_tva = $tabprice[17];
2531  $multicurrency_total_ttc = $tabprice[18];
2532  $pu_ht_devise = $tabprice[19];
2533 
2534  $localtax1_type=$localtaxes_type[0];
2535  $localtax2_type=$localtaxes_type[2];
2536 
2537  $subprice = price2num($pu_ht,'MU');
2538 
2539  //Fetch current line from the database and then clone the object and set it in $oldline property
2540  $this->line=new CommandeFournisseurLigne($this->db);
2541  $this->line->fetch($rowid);
2542  $oldline = clone $this->line;
2543  $this->line->oldline = $oldline;
2544 
2545  $this->line->context = $this->context;
2546 
2547  $this->line->fk_commande=$this->id;
2548  //$this->line->label=$label;
2549  $this->line->desc=$desc;
2550  $this->line->qty=$qty;
2551  $this->line->ref_supplier=$ref_supplier;
2552 
2553  $this->line->vat_src_code = $vat_src_code;
2554  $this->line->tva_tx = $txtva;
2555  $this->line->localtax1_tx = $txlocaltax1;
2556  $this->line->localtax2_tx = $txlocaltax2;
2557  $this->line->localtax1_type = $localtaxes_type[0];
2558  $this->line->localtax2_type = $localtaxes_type[2];
2559  $this->line->remise_percent = $remise_percent;
2560  $this->line->subprice = $pu_ht;
2561  $this->line->rang = $this->rang;
2562  $this->line->info_bits = $info_bits;
2563  $this->line->total_ht = $total_ht;
2564  $this->line->total_tva = $total_tva;
2565  $this->line->total_localtax1= $total_localtax1;
2566  $this->line->total_localtax2= $total_localtax2;
2567  $this->line->total_ttc = $total_ttc;
2568  $this->line->product_type = $type;
2569  $this->line->special_code = $this->special_code;
2570  $this->line->origin = $this->origin;
2571  $this->line->fk_unit = $fk_unit;
2572 
2573  $this->line->date_start = $date_start;
2574  $this->line->date_end = $date_end;
2575 
2576  // Multicurrency
2577  $this->line->fk_multicurrency = $this->fk_multicurrency;
2578  $this->line->multicurrency_code = $this->multicurrency_code;
2579  $this->line->multicurrency_subprice = $pu_ht_devise;
2580  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
2581  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
2582  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
2583 
2584  $this->line->subprice=$pu_ht;
2585  $this->line->price=$this->line->subprice;
2586 
2587  $this->line->remise_percent=$remise_percent;
2588 
2589  if (is_array($array_options) && count($array_options)>0) {
2590  $this->line->array_options=$array_options;
2591  }
2592 
2593  $result=$this->line->update($notrigger);
2594 
2595 
2596  // Mise a jour info denormalisees au niveau facture
2597  if ($result >= 0)
2598  {
2599  $this->update_price('','auto');
2600  $this->db->commit();
2601  return $result;
2602  }
2603  else
2604  {
2605  $this->error=$this->db->lasterror();
2606  $this->db->rollback();
2607  return -1;
2608  }
2609  }
2610  else
2611  {
2612  $this->error="Order status makes operation forbidden";
2613  dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
2614  return -2;
2615  }
2616  }
2617 
2618 
2626  public function initAsSpecimen()
2627  {
2628  global $user,$langs,$conf;
2629 
2630  dol_syslog(get_class($this)."::initAsSpecimen");
2631 
2632  $now=dol_now();
2633 
2634  // Find first product
2635  $prodid=0;
2636  $product=new ProductFournisseur($this->db);
2637  $sql = "SELECT rowid";
2638  $sql.= " FROM ".MAIN_DB_PREFIX."product";
2639  $sql.= " WHERE entity IN (".getEntity('product').")";
2640  $sql.=$this->db->order("rowid","ASC");
2641  $sql.=$this->db->plimit(1);
2642  $resql = $this->db->query($sql);
2643  if ($resql)
2644  {
2645  $obj = $this->db->fetch_object($resql);
2646  $prodid = $obj->rowid;
2647  }
2648 
2649  // Initialise parametres
2650  $this->id=0;
2651  $this->ref = 'SPECIMEN';
2652  $this->specimen=1;
2653  $this->socid = 1;
2654  $this->date = $now;
2655  $this->date_commande = $now;
2656  $this->date_lim_reglement=$this->date+3600*24*30;
2657  $this->cond_reglement_code = 'RECEP';
2658  $this->mode_reglement_code = 'CHQ';
2659  $this->note_public='This is a comment (public)';
2660  $this->note_private='This is a comment (private)';
2661  $this->statut=0;
2662 
2663  // Lines
2664  $nbp = 5;
2665  $xnbp = 0;
2666  while ($xnbp < $nbp)
2667  {
2668  $line=new CommandeFournisseurLigne($this->db);
2669  $line->desc=$langs->trans("Description")." ".$xnbp;
2670  $line->qty=1;
2671  $line->subprice=100;
2672  $line->price=100;
2673  $line->tva_tx=19.6;
2674  $line->localtax1_tx=0;
2675  $line->localtax2_tx=0;
2676  if ($xnbp == 2)
2677  {
2678  $line->total_ht=50;
2679  $line->total_ttc=59.8;
2680  $line->total_tva=9.8;
2681  $line->remise_percent=50;
2682  }
2683  else
2684  {
2685  $line->total_ht=100;
2686  $line->total_ttc=119.6;
2687  $line->total_tva=19.6;
2688  $line->remise_percent=00;
2689  }
2690  $line->fk_product=$prodid;
2691 
2692  $this->lines[$xnbp]=$line;
2693 
2694  $this->total_ht += $line->total_ht;
2695  $this->total_tva += $line->total_tva;
2696  $this->total_ttc += $line->total_ttc;
2697 
2698  $xnbp++;
2699  }
2700  }
2701 
2708  public function info($id)
2709  {
2710  $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
2711  $sql.= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
2712  $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c';
2713  $sql.= ' WHERE c.rowid = '.$id;
2714 
2715  $result=$this->db->query($sql);
2716  if ($result)
2717  {
2718  if ($this->db->num_rows($result))
2719  {
2720  $obj = $this->db->fetch_object($result);
2721  $this->id = $obj->rowid;
2722  if ($obj->fk_user_author) $this->user_creation_id = $obj->fk_user_author;
2723  if ($obj->fk_user_valid) $this->user_validation_id = $obj->fk_user_valid;
2724  if ($obj->fk_user_modif) $this->user_modification_id =$obj->fk_user_modif;
2725  if ($obj->fk_user_approve) $this->user_approve_id = $obj->fk_user_approve;
2726  if ($obj->fk_user_approve2) $this->user_approve_id2 = $obj->fk_user_approve2;
2727 
2728  $this->date_creation = $this->db->idate($obj->datec);
2729  $this->date_modification = $this->db->idate($obj->datem);
2730  $this->date_approve = $this->db->idate($obj->datea);
2731  $this->date_approve2 = $this->db->idate($obj->datea2);
2732  $this->date_validation = $this->db->idate($obj->date_validation);
2733  }
2734  $this->db->free($result);
2735  }
2736  else
2737  {
2738  dol_print_error($this->db);
2739  }
2740  }
2741 
2742  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2748  function load_state_board()
2749  {
2750  // phpcs:enable
2751  global $conf, $user;
2752 
2753  $this->nb=array();
2754  $clause = "WHERE";
2755 
2756  $sql = "SELECT count(co.rowid) as nb";
2757  $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
2758  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
2759  if (!$user->rights->societe->client->voir && !$user->societe_id)
2760  {
2761  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2762  $sql.= " WHERE sc.fk_user = " .$user->id;
2763  $clause = "AND";
2764  }
2765  $sql.= " ".$clause." co.entity = ".$conf->entity;
2766 
2767  $resql=$this->db->query($sql);
2768  if ($resql)
2769  {
2770  while ($obj=$this->db->fetch_object($resql))
2771  {
2772  $this->nb["supplier_orders"]=$obj->nb;
2773  }
2774  $this->db->free($resql);
2775  return 1;
2776  }
2777  else
2778  {
2779  dol_print_error($this->db);
2780  $this->error=$this->db->error();
2781  return -1;
2782  }
2783  }
2784 
2785  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2792  function load_board($user)
2793  {
2794  // phpcs:enable
2795  global $conf, $langs;
2796 
2797  $clause = " WHERE";
2798 
2799  $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date";
2800  $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
2801  if (!$user->rights->societe->client->voir && !$user->societe_id)
2802  {
2803  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
2804  $sql.= " WHERE sc.fk_user = " .$user->id;
2805  $clause = " AND";
2806  }
2807  $sql.= $clause." c.entity = ".$conf->entity;
2808  $sql.= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")";
2809  if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2810 
2811  $resql=$this->db->query($sql);
2812  if ($resql)
2813  {
2814  $commandestatic = new CommandeFournisseur($this->db);
2815 
2816  $response = new WorkboardResponse();
2817  $response->warning_delay=$conf->commande->fournisseur->warning_delay/60/60/24;
2818  $response->label=$langs->trans("SuppliersOrdersToProcess");
2819  $response->url=DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2,3&mainmenu=commercial&leftmenu=orders_suppliers';
2820  $response->img=img_object('',"order");
2821 
2822  while ($obj=$this->db->fetch_object($resql))
2823  {
2824  $response->nbtodo++;
2825 
2826  $commandestatic->date_livraison = $this->db->jdate($obj->delivery_date);
2827  $commandestatic->date_commande = $this->db->jdate($obj->date_commande);
2828  $commandestatic->statut = $obj->fk_statut;
2829 
2830  if ($commandestatic->hasDelay()) {
2831  $response->nbtodolate++;
2832  }
2833  }
2834 
2835  return $response;
2836  }
2837  else
2838  {
2839  $this->error=$this->db->error();
2840  return -1;
2841  }
2842  }
2843 
2850  public function getInputMethod()
2851  {
2852  global $db, $langs;
2853 
2854  if ($this->methode_commande_id > 0)
2855  {
2856  $sql = "SELECT rowid, code, libelle as label";
2857  $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_method';
2858  $sql.= " WHERE active=1 AND rowid = ".$db->escape($this->methode_commande_id);
2859 
2860  $resql = $db->query($sql);
2861  if ($resql)
2862  {
2863  if ($db->num_rows($query))
2864  {
2865  $obj = $db->fetch_object($query);
2866 
2867  $string = $langs->trans($obj->code);
2868  if ($string == $obj->code)
2869  {
2870  $string = $obj->label != '-' ? $obj->label : '';
2871  }
2872  return $string;
2873  }
2874  }
2875  else dol_print_error($db);
2876  }
2877 
2878  return '';
2879  }
2880 
2892  public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
2893  {
2894  global $conf, $langs;
2895 
2896  $langs->load("suppliers");
2897 
2898  if (! dol_strlen($modele)) {
2899 
2900  $modele = 'muscadet';
2901 
2902  if ($this->modelpdf) {
2903  $modele = $this->modelpdf;
2904  } elseif (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) {
2905  $modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF;
2906  }
2907  }
2908 
2909  $modelpath = "core/modules/supplier_order/pdf/";
2910 
2911  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2912  }
2913 
2920  public function getMaxDeliveryTimeDay($langs)
2921  {
2922  if (empty($this->lines)) return '';
2923 
2924  $obj = new ProductFournisseur($this->db);
2925 
2926  $nb = 0;
2927  foreach ($this->lines as $line)
2928  {
2929  if ($line->fk_product > 0)
2930  {
2931  $idp = $obj->find_min_price_product_fournisseur($line->fk_product, $line->qty);
2932  if ($idp)
2933  {
2934  $obj->fetch($idp);
2935  if ($obj->delivery_time_days > $nb) $nb = $obj->delivery_time_days;
2936  }
2937  }
2938  }
2939 
2940  if ($nb === 0) return '';
2941  else return $nb.' '.$langs->trans('Days');
2942  }
2943 
2948  public function getRights()
2949  {
2950  global $user;
2951 
2952  return $user->rights->fournisseur->commande;
2953  }
2954 
2955 
2964  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
2965  {
2966  $tables = array(
2967  'commande_fournisseur'
2968  );
2969 
2970  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2971  }
2972 
2978  public function hasDelay()
2979  {
2980  global $conf;
2981 
2982  if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility
2983 
2984  $now = dol_now();
2985  $date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery;
2986 
2987  return ($this->statut > 0 && $this->statut < 4) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
2988  }
2989 
2995  public function showDelay()
2996  {
2997  global $conf, $langs;
2998 
2999  if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility
3000 
3001  if (empty($this->date_delivery)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3002  else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day');
3003  $text.=' '.($conf->commande->fournisseur->warning_delay>0?'+':'-').' '.round(abs($conf->commande->fournisseur->warning_delay)/3600/24,1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3004 
3005  return $text;
3006  }
3007 
3008 
3017  public function calcAndSetStatusDispatch(User $user, $closeopenorder=1, $comment='')
3018  {
3019  global $conf, $langs;
3020 
3021  if (! empty($conf->fournisseur->enabled))
3022  {
3023  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
3024 
3025  $qtydelivered=array();
3026  $qtywished=array();
3027 
3028  $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
3029  $filter=array('t.fk_commande'=>$this->id);
3030  if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
3031  $filter['t.status']=1; // Restrict to lines with status validated
3032  }
3033 
3034  $ret=$supplierorderdispatch->fetchAll('','',0,0,$filter);
3035  if ($ret<0)
3036  {
3037  $this->error=$supplierorderdispatch->error; $this->errors=$supplierorderdispatch->errors;
3038  return $ret;
3039  }
3040  else
3041  {
3042  if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines)>0)
3043  {
3044  $date_liv = dol_now();
3045 
3046  // Build array with quantity deliverd by product
3047  foreach($supplierorderdispatch->lines as $line) {
3048  $qtydelivered[$line->fk_product]+=$line->qty;
3049  }
3050  foreach($this->lines as $line) {
3051  $qtywished[$line->fk_product]+=$line->qty;
3052  }
3053  //Compare array
3054  $diff_array=array_diff_assoc($qtydelivered,$qtywished); // Warning: $diff_array is done only on common keys.
3055  $keysinwishednotindelivered=array_diff(array_keys($qtywished),array_keys($qtydelivered)); // To check we also have same number of keys
3056  $keysindeliverednotinwished=array_diff(array_keys($qtydelivered),array_keys($qtywished)); // To check we also have same number of keys
3057  /*var_dump(array_keys($qtydelivered));
3058  var_dump(array_keys($qtywished));
3059  var_dump($diff_array);
3060  var_dump($keysinwishednotindelivered);
3061  var_dump($keysindeliverednotinwished);
3062  exit;*/
3063 
3064  if (count($diff_array)==0 && count($keysinwishednotindelivered)==0 && count($keysindeliverednotinwished)==0) //No diff => mean everythings is received
3065  {
3066  if ($closeopenorder)
3067  {
3068  //$ret=$this->setStatus($user,5);
3069  $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3070  if ($ret<0) {
3071  return -1;
3072  }
3073  return 5;
3074  }
3075  else
3076  {
3077  //Diff => received partially
3078  //$ret=$this->setStatus($user,4);
3079  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3080  if ($ret<0) {
3081  return -1;
3082  }
3083  return 4;
3084  }
3085  }elseif(! empty($conf->global->SUPPLIER_ORDER_MORE_THAN_WISHED) )
3086  {//set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...)
3087 
3088  $close=0;
3089 
3090  if( count($diff_array) > 0 )
3091  {//there are some difference between the two arrays
3092 
3093  //scan the array of results
3094  foreach($diff_array as $key => $value)
3095  {//if the quantity delivered is greater or equal to wish quantity
3096  if($qtydelivered[$key] >= $qtywished[$key] )
3097  {
3098  $close++;
3099  }
3100  }
3101  }
3102 
3103 
3104  if($close == count($diff_array))
3105  {//all the products are received equal or more than the wished quantity
3106  if ($closeopenorder)
3107  {
3108  $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3109  if ($ret<0) {
3110  return -1;
3111  }
3112  return 5;
3113  }
3114  else
3115  {
3116  //Diff => received partially
3117  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3118  if ($ret<0) {
3119  return -1;
3120  }
3121  return 4;
3122  }
3123  }
3124  else
3125  {//all the products are not received
3126  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3127  if ($ret<0) {
3128  return -1;
3129  }
3130  return 4;
3131  }
3132  }
3133  else
3134  {
3135  //Diff => received partially
3136  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3137  if ($ret<0) {
3138  return -1;
3139  }
3140  return 4;
3141  }
3142  }
3143  return 1;
3144  }
3145  }
3146  return 0;
3147  }
3148 }
3149 
3150 
3151 
3156 {
3160  public $element='commande_fournisseurdet';
3161 
3165  public $table_element='commande_fournisseurdet';
3166 
3167  public $oldline;
3168 
3173  public $fk_commande;
3174 
3175  // From llx_commande_fournisseurdet
3179  public $fk_parent_line;
3180 
3184  public $fk_facture;
3185 
3189  public $label;
3190 
3191  public $rang = 0;
3192  public $special_code = 0;
3193 
3198  public $pu_ht;
3199 
3200  public $date_start;
3201  public $date_end;
3202 
3203  // From llx_product_fournisseur_price
3204 
3209  public $ref_supplier;
3210  public $remise;
3211  public $product_libelle;
3212 
3213 
3219  public function __construct($db)
3220  {
3221  $this->db= $db;
3222  }
3223 
3230  public function fetch($rowid)
3231  {
3232  $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx, cd.special_code,';
3233  $sql.= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,';
3234  $sql.= ' cd.remise, cd.remise_percent, cd.subprice,';
3235  $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,';
3236  $sql.= ' cd.total_localtax1, cd.total_localtax2,';
3237  $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,';
3238  $sql.= ' cd.date_start, cd.date_end, cd.fk_unit,';
3239  $sql.= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc';
3240  $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd';
3241  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3242  $sql.= ' WHERE cd.rowid = '.$rowid;
3243  $result = $this->db->query($sql);
3244  if ($result)
3245  {
3246  $objp = $this->db->fetch_object($result);
3247 
3248  if (!empty($objp))
3249  {
3250  $this->rowid = $objp->rowid;
3251  $this->id = $objp->rowid;
3252  $this->fk_commande = $objp->fk_commande;
3253  $this->desc = $objp->description;
3254  $this->qty = $objp->qty;
3255  $this->ref_fourn = $objp->ref;
3256  $this->ref_supplier = $objp->ref;
3257  $this->subprice = $objp->subprice;
3258  $this->tva_tx = $objp->tva_tx;
3259  $this->localtax1_tx = $objp->localtax1_tx;
3260  $this->localtax2_tx = $objp->localtax2_tx;
3261  $this->localtax1_type = $objp->localtax1_type;
3262  $this->localtax2_type = $objp->localtax2_type;
3263  $this->remise = $objp->remise;
3264  $this->remise_percent = $objp->remise_percent;
3265  $this->fk_product = $objp->fk_product;
3266  $this->info_bits = $objp->info_bits;
3267  $this->total_ht = $objp->total_ht;
3268  $this->total_tva = $objp->total_tva;
3269  $this->total_localtax1 = $objp->total_localtax1;
3270  $this->total_localtax2 = $objp->total_localtax2;
3271  $this->total_ttc = $objp->total_ttc;
3272  $this->product_type = $objp->product_type;
3273  $this->special_code = $objp->special_code;
3274 
3275  $this->ref = $objp->product_ref;
3276  $this->product_ref = $objp->product_ref;
3277  $this->product_libelle = $objp->product_libelle;
3278  $this->product_desc = $objp->product_desc;
3279 
3280  $this->date_start = $this->db->jdate($objp->date_start);
3281  $this->date_end = $this->db->jdate($objp->date_end);
3282  $this->fk_unit = $objp->fk_unit;
3283 
3284  $this->multicurrency_subprice = $objp->multicurrency_subprice;
3285  $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
3286  $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
3287  $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
3288 
3289  $this->fetch_optionals();
3290 
3291  $this->db->free($result);
3292  return 1;
3293  }
3294  else
3295  {
3296  $this->error='Supplier order line with id='.$rowid.' not found';
3297  dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR);
3298  return 0;
3299  }
3300  }
3301  else
3302  {
3303  dol_print_error($this->db);
3304  return -1;
3305  }
3306  }
3307 
3314  public function insert($notrigger=0)
3315  {
3316  global $conf, $user;
3317 
3318  $error=0;
3319 
3320  dol_syslog(get_class($this)."::insert rang=".$this->rang);
3321 
3322  // Clean parameters
3323  if (empty($this->tva_tx)) $this->tva_tx=0;
3324  if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
3325  if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
3326  if (empty($this->localtax1_type)) $this->localtax1_type='0';
3327  if (empty($this->localtax2_type)) $this->localtax2_type='0';
3328  if (empty($this->total_localtax1)) $this->total_localtax1=0;
3329  if (empty($this->total_localtax2)) $this->total_localtax2=0;
3330  if (empty($this->rang)) $this->rang=0;
3331  if (empty($this->remise)) $this->remise=0;
3332  if (empty($this->remise_percent)) $this->remise_percent=0;
3333  if (empty($this->info_bits)) $this->info_bits=0;
3334  if (empty($this->special_code)) $this->special_code=0;
3335  if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
3336  if (empty($this->pa_ht)) $this->pa_ht=0;
3337 
3338  // Multicurrency
3339  if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3340  if (empty($this->fk_multicurrency))
3341  {
3342  $this->multicurrency_code = $conf->currency;
3343  $this->fk_multicurrency = 0;
3344  $this->multicurrency_tx = 1;
3345  }
3346 
3347  // Check parameters
3348  if ($this->product_type < 0) return -1;
3349 
3350  $this->db->begin();
3351 
3352  // Insertion dans base de la ligne
3353  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
3354  $sql.= " (fk_commande, label, description, date_start, date_end,";
3355  $sql.= " fk_product, product_type, special_code, rang,";
3356  $sql.= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,";
3357  $sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,";
3358  $sql.= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
3359  $sql.= ")";
3360  $sql.= " VALUES (".$this->fk_commande.", '" . $this->db->escape($this->label) . "','" . $this->db->escape($this->desc) . "',";
3361  $sql.= " ".($this->date_start?"'".$this->db->idate($this->date_start)."'":"null").",";
3362  $sql.= " ".($this->date_end?"'".$this->db->idate($this->date_end)."'":"null").",";
3363  if ($this->fk_product) { $sql.= $this->fk_product.","; }
3364  else { $sql.= "null,"; }
3365  $sql.= "'".$this->db->escape($this->product_type)."',";
3366  $sql.= "'".$this->db->escape($this->special_code)."',";
3367  $sql.= "'".$this->db->escape($this->rang)."',";
3368  $sql.= "'".$this->db->escape($this->qty)."', ";
3369  $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
3370  $sql.= " ".$this->tva_tx.", ";
3371  $sql.= " ".$this->localtax1_tx.",";
3372  $sql.= " ".$this->localtax2_tx.",";
3373  $sql.= " '".$this->db->escape($this->localtax1_type)."',";
3374  $sql.= " '".$this->db->escape($this->localtax2_type)."',";
3375  $sql.= " ".$this->remise_percent.", ".price2num($this->subprice,'MU').", '".$this->db->escape($this->ref_supplier)."',";
3376  $sql.= " ".price2num($this->total_ht).",";
3377  $sql.= " ".price2num($this->total_tva).",";
3378  $sql.= " ".price2num($this->total_localtax1).",";
3379  $sql.= " ".price2num($this->total_localtax2).",";
3380  $sql.= " ".price2num($this->total_ttc).",";
3381  $sql.= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'":"null");
3382  $sql.= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null");
3383  $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
3384  $sql.= ", ".($this->multicurrency_subprice ? price2num($this->multicurrency_subprice) : '0');
3385  $sql.= ", ".($this->multicurrency_total_ht ? price2num($this->multicurrency_total_ht) : '0');
3386  $sql.= ", ".($this->multicurrency_total_tva ? price2num($this->multicurrency_total_tva) : '0');
3387  $sql.= ", ".($this->multicurrency_total_ttc ? price2num($this->multicurrency_total_ttc) : '0');
3388  $sql.= ")";
3389 
3390  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3391  $resql=$this->db->query($sql);
3392  if ($resql)
3393  {
3394  $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
3395  $this->rowid =$this->id;
3396 
3397  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3398  {
3399  $result=$this->insertExtraFields();
3400  if ($result < 0)
3401  {
3402  $error++;
3403  }
3404  }
3405 
3406  if (! $error && ! $notrigger)
3407  {
3408  // Call trigger
3409  $result=$this->call_trigger('LINEORDER_SUPPLIER_CREATE',$user);
3410  if ($result < 0) $error++;
3411  // End call triggers
3412  }
3413 
3414  if (!$error) {
3415  $this->db->commit();
3416  return 1;
3417  }
3418 
3419  foreach($this->errors as $errmsg)
3420  {
3421  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3422  $this->errors[]=($this->errors?', '.$errmsg:$errmsg);
3423  }
3424  $this->db->rollback();
3425  return -1*$error;
3426  }
3427  else
3428  {
3429  $this->errors[]=$this->db->error();
3430  $this->db->rollback();
3431  return -2;
3432  }
3433  }
3440  public function update($notrigger=0)
3441  {
3442  global $conf,$user;
3443 
3444  $error=0;
3445 
3446  // Mise a jour ligne en base
3447  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3448  $sql.= " description='".$this->db->escape($this->desc)."'";
3449  $sql.= ", ref='".$this->db->escape($this->ref_supplier)."'";
3450  $sql.= ", subprice='".price2num($this->subprice)."'";
3451  //$sql.= ",remise='".price2num($remise)."'";
3452  $sql.= ", remise_percent='".price2num($this->remise_percent)."'";
3453 
3454  $sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'";
3455  $sql.= ", tva_tx='".price2num($this->tva_tx)."'";
3456  $sql.= ", localtax1_tx='".price2num($this->total_localtax1)."'";
3457  $sql.= ", localtax2_tx='".price2num($this->total_localtax2)."'";
3458  $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3459  $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3460  $sql.= ", qty='".price2num($this->qty)."'";
3461  $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null");
3462  $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null");
3463  $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'";
3464  $sql.= ", total_ht='".price2num($this->total_ht)."'";
3465  $sql.= ", total_tva='".price2num($this->total_tva)."'";
3466  $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'";
3467  $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'";
3468  $sql.= ", total_ttc='".price2num($this->total_ttc)."'";
3469  $sql.= ", product_type=".$this->product_type;
3470  $sql.= ", special_code=".(!empty($this->special_code) ? $this->special_code : 0);
3471  $sql.= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'":", fk_unit=null");
3472 
3473  // Multicurrency
3474  $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3475  $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3476  $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
3477  $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
3478 
3479  $sql.= " WHERE rowid = ".$this->id;
3480 
3481  dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
3482  $result = $this->db->query($sql);
3483  if ($result > 0)
3484  {
3485  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
3486  {
3487  $result=$this->insertExtraFields();
3488  if ($result < 0)
3489  {
3490  $error++;
3491  }
3492  }
3493 
3494  if (! $error && ! $notrigger)
3495  {
3496  global $user;
3497  // Call trigger
3498  $result=$this->call_trigger('LINEORDER_SUPPLIER_UPDATE',$user);
3499  if ($result < 0)
3500  {
3501  $this->db->rollback();
3502  return -1;
3503  }
3504  // End call triggers
3505  }
3506 
3507  if (! $error)
3508  {
3509  $this->db->commit();
3510  return $result;
3511  }
3512  else
3513  {
3514  $this->db->rollback();
3515  return -1;
3516  }
3517  }
3518  else
3519  {
3520  $this->error=$this->db->lasterror();
3521  $this->db->rollback();
3522  return -1;
3523  }
3524  }
3525 
3532  function delete($notrigger)
3533  {
3534  global $user;
3535 
3536  $error=0;
3537 
3538  $this->db->begin();
3539 
3540  $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".$this->rowid;
3541 
3542  dol_syslog(__METHOD__, LOG_DEBUG);
3543  $resql=$this->db->query($sql);
3544  if ($resql)
3545  {
3546 
3547  if (!$notrigger)
3548  {
3549  // Call trigger
3550  $result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE',$user);
3551  if ($result < 0) $error++;
3552  // End call triggers
3553  }
3554 
3555  if (!$error)
3556  {
3557  $this->db->commit();
3558  return 1;
3559  }
3560 
3561  foreach($this->errors as $errmsg)
3562  {
3563  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3564  $this->error.=($this->error?', '.$errmsg:$errmsg);
3565  }
3566  $this->db->rollback();
3567  return -1*$error;
3568  }
3569  else
3570  {
3571  $this->error=$this->db->lasterror();
3572  return -1;
3573  }
3574  }
3575 }
print $object label
hash of file content (md5_file(dol_osencode($destfull))
Definition: edit.php:153
createFromClone()
Load an object from its id and create a new one in database.
Class to manage stock movements.
Cancel($user, $idwarehouse=-1)
Cancel an approved order.
const STATUS_DRAFT
Draft status.
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.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
Delete all links between an object $this.
deleteline($idline, $notrigger=0)
Delete line.
const STATUS_RECEIVED_COMPLETELY
Received completely.
Class to manage table commandefournisseurdispatch.
dispatchProduct($user, $product, $qty, $entrepot, $price=0, $comment='', $eatby='', $sellby='', $batch='', $fk_commandefourndet=0, $notrigger=0)
Save a receiving into the tracking table of receiving (commande_fournisseur_dispatch) and add product...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
if(! empty($search_group)) natural_search(array("g.nom" g note
Definition: list.php:123
set_date_livraison($user, $date_livraison, $notrigger=0)
Set the planned delivery date.
Class to manage products or services.
const STATUS_CANCELED_AFTER_ORDER
Order canceled/never received.
getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1)
Return clicable name (with picto eventually)
Class to manage Dolibarr users.
Definition: user.class.php:41
showDelay()
Show the customer delayed info.
Class to manage Dolibarr database access.
getMaxDeliveryTimeDay($langs)
Return the max number delivery delay in day.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise=0, $ref_supplier='')
Update line.
hasDelay()
Is the supplier order delayed?
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
getNextNumRef($soc)
Returns the following order reference not used depending on the numbering model activated defined wit...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
refuse($user)
Refuse an order.
updateFromCommandeClient($user, $idc, $comclientid)
Update a supplier order from a customer order.
create($user, $notrigger=0)
Create order with draft status.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $fk_prod_fourn_price=0, $ref_supplier='', $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $type=0, $info_bits=0, $notrigger=false, $date_start=null, $date_end=null, $array_options=0, $fk_unit=null, $pu_ht_devise=0, $origin='', $origin_id=0)
Add order line.
getInputMethod()
Returns the translated input method of object (defined if $this->methode_commande_id > 0)...
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
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.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
calcAndSetStatusDispatch(User $user, $closeopenorder=1, $comment='')
Calc status regarding to dispatched stock.
fetch($id, $ref='')
Get object and lines from database.
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)...
info($id)
Charge les informations d&#39;ordre info dans l&#39;objet facture.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
const STATUS_RECEIVED_PARTIALLY
Received partially.
Class to manage customers orders.
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
const STATUS_VALIDATED
Validated status.
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.
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
classifyBilled(User $user)
Class invoiced the supplier order.
setStatus($user, $status)
Tag order with a particular status.
commande($user, $date, $methode, $comment='')
Submit a supplier order to supplier.
dol_now($mode='gmt')
Return date for now.
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.
Class to manage predefined suppliers products.
Livraison($user, $date, $type, $comment)
Set a delivery in database for this supplier order.
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).
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getDispachedLines($status=-1)
Return array of dispatched lines waiting to be approved for this order.
const STATUS_ORDERSENT
Order sent, shipment on process.
Superclass for orders classes.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template model.
valid($user, $idwarehouse=0, $notrigger=0)
Validate an order.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
update($notrigger=0)
Update the line object into db.
initAsSpecimen()
Initialise an instance with random values.
load_state_board()
Charge indicateurs this->nb de tableau de bord.
getLibStatut($mode=0)
Return label of the status of object.
call_trigger($trigger_name, $user)
Call trigger based on this instance.
getRights()
Returns the rights used for this class.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
approve($user, $idwarehouse=0, $secondlevel=0)
Approve a supplier order.
add_object_linked($origin=null, $origin_id=null)
Add objects linked in llx_element_element.
const STATUS_CANCELED
Order canceled.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='')
Show picto whatever it&#39;s its name (generic function)
fetch_lines($only_product=0)
Load array lines.
get_methodes_commande()
Get list of order methods.
price2num($amount, $rounding='', $alreadysqlnb=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
insert($notrigger=0)
Insert line into database.
set_id_projet($user, $id_projet, $notrigger=0)
Set the id projet.
Class to manage predefined suppliers products.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Class to manage line orders.
LibStatut($statut, $mode=0, $billed=0)
Return label of a status.
static getIdAndTxFromCode(&$db, $code, $date_document='')
Get id and rate of currency from code.