dolibarr  16.0.5
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-2020 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-2022 Frédéric France <frederic.france@netlogic.fr>
13  * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
14  * Copyright (C) 2021 Josep Lluís Amador <joseplluis@lliuretic.cat>
15  * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program. If not, see <https://www.gnu.org/licenses/>.
29  */
30 
37 require_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
39 if (!empty($conf->productbatch->enabled)) {
40  require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
41 }
42 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
43 
48 {
52  public $element = 'order_supplier';
53 
57  public $table_element = 'commande_fournisseur';
58 
62  public $table_element_line = 'commande_fournisseurdet';
63 
67  public $fk_element = 'fk_commande';
68 
72  public $picto = 'supplier_order';
73 
78  public $ismultientitymanaged = 1;
79 
84  public $restrictiononfksoc = 1;
85 
89  protected $table_ref_field = 'ref';
90 
94  public $id;
95 
100  public $ref;
101 
102  public $ref_supplier;
103  public $brouillon;
104  public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially
105  // -> 7=Canceled/Never received -> (reopen) 3=Process runing
106  // -> 6=Canceled -> (reopen) 2=Approved
107  // -> 9=Refused -> (reopen) 1=Validated
108  // Note: billed or not is on another field "billed"
109  public $statuts; // List of status
110 
111  public $billed;
112 
113  public $socid;
114  public $fourn_id;
115  public $date;
116  public $date_creation;
117  public $date_valid;
118  public $date_approve;
119  public $date_approve2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
120  public $date_commande;
121 
126  public $date_livraison;
127 
131  public $delivery_date;
132 
133  public $total_ht;
134  public $total_tva;
135  public $total_localtax1; // Total Local tax 1
136  public $total_localtax2; // Total Local tax 2
137  public $total_ttc;
138  public $source;
139 
143  public $fk_project;
144 
145  public $cond_reglement_id;
146  public $cond_reglement_code;
147  public $cond_reglement_label; // Label
148  public $cond_reglement_doc; // Label on documents
149 
153  public $fk_account;
154 
155  public $mode_reglement_id;
156  public $mode_reglement_code;
157  public $user_author_id;
158  public $user_valid_id;
159  public $user_approve_id;
160  public $user_approve_id2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set
161 
162  public $refuse_note;
163 
164  public $extraparams = array();
165 
169  public $lines = array();
170 
171  //Add for supplier_proposal
172  public $origin;
173  public $origin_id;
174  public $linked_objects = array();
175 
176  // Multicurrency
180  public $fk_multicurrency;
181 
182  public $multicurrency_code;
183  public $multicurrency_tx;
184  public $multicurrency_total_ht;
185  public $multicurrency_total_tva;
186  public $multicurrency_total_ttc;
187 
188 
216  public $fields = array(
217  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>10),
218  'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'showoncombobox'=>1, 'position'=>25, 'searchall'=>1),
219  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>35),
220  'ref_supplier' =>array('type'=>'varchar(255)', 'label'=>'RefOrderSupplierShort', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'searchall'=>1),
221  'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>'$conf->project->enabled', 'visible'=>-1, 'position'=>45),
222  'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
223  'date_approve' =>array('type'=>'datetime', 'label'=>'DateApprove', 'enabled'=>1, 'visible'=>-1, 'position'=>62),
224  'date_approve2' =>array('type'=>'datetime', 'label'=>'DateApprove2', 'enabled'=>1, 'visible'=>3, 'position'=>64),
225  'date_commande' =>array('type'=>'date', 'label'=>'OrderDateShort', 'enabled'=>1, 'visible'=>1, 'position'=>70),
226  'date_livraison' =>array('type'=>'datetime', 'label'=>'DeliveryDate', 'enabled'=>'empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)', 'visible'=>1, 'position'=>74),
227  'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>3, 'position'=>75),
228  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>3, 'notnull'=>-1, 'position'=>80),
229  'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>3, 'position'=>85),
230  'fk_user_approve' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserApproval', 'enabled'=>1, 'visible'=>3, 'position'=>90),
231  'fk_user_approve2' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserApproval2', 'enabled'=>1, 'visible'=>3, 'position'=>95),
232  'source' =>array('type'=>'smallint(6)', 'label'=>'Source', 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>100),
233  'billed' =>array('type'=>'smallint(6)', 'label'=>'Billed', 'enabled'=>1, 'visible'=>1, 'position'=>110),
234  'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>1, 'position'=>130, 'isameasure'=>1),
235  'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>3, 'position'=>135, 'isameasure'=>1),
236  'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>3, 'position'=>140, 'isameasure'=>1),
237  'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>1, 'position'=>145, 'isameasure'=>1),
238  'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>150, 'isameasure'=>1),
239  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>155, 'searchall'=>1),
240  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>160, 'searchall'=>1),
241  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPDF', 'enabled'=>1, 'visible'=>0, 'position'=>165),
242  'fk_input_method' =>array('type'=>'integer', 'label'=>'OrderMode', 'enabled'=>1, 'visible'=>3, 'position'=>170),
243  'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>3, 'position'=>175),
244  'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>3, 'position'=>180),
245  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>0, 'position'=>190),
246  'fk_account' =>array('type'=>'integer', 'label'=>'BankAccount', 'enabled'=>'$conf->banque->enabled', 'visible'=>3, 'position'=>200),
247  'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>1, 'visible'=>3, 'position'=>205),
248  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLocation', 'enabled'=>1, 'visible'=>3, 'position'=>210),
249  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>0, 'position'=>215),
250  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Currency', 'enabled'=>'!empty($conf->multicurrency->enabled)', 'visible'=>-1, 'position'=>220),
251  'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'CurrencyRate', 'enabled'=>'!empty($conf->multicurrency->enabled)', 'visible'=>-1, 'position'=>225),
252  'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'!empty($conf->multicurrency->enabled)', 'visible'=>-1, 'position'=>230),
253  'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'!empty($conf->multicurrency->enabled)', 'visible'=>-1, 'position'=>235),
254  'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'!empty($conf->multicurrency->enabled)', 'visible'=>-1, 'position'=>240),
255  'date_creation' =>array('type'=>'datetime', 'label'=>'Date creation', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
256  'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'$conf->societe->enabled', 'visible'=>1, 'notnull'=>1, 'position'=>46),
257  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>1000, 'index'=>1),
258  'tms'=>array('type'=>'datetime', 'label'=>"DateModificationShort", 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>501),
259  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>0, 'position'=>700),
260  'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'position'=>701),
261  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>0, 'position'=>900),
262  );
263 
264 
268  const STATUS_DRAFT = 0;
269 
273  const STATUS_VALIDATED = 1;
274 
278  const STATUS_ACCEPTED = 2;
279 
283  const STATUS_ORDERSENT = 3;
284 
289 
294 
298  const STATUS_CANCELED = 6;
299 
304 
308  const STATUS_REFUSED = 9;
309 
310 
315 
316 
317 
323  public function __construct($db)
324  {
325  $this->db = $db;
326  }
327 
328 
336  public function fetch($id, $ref = '')
337  {
338  global $conf;
339 
340  // Check parameters
341  if (empty($id) && empty($ref)) {
342  return -1;
343  }
344 
345  $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.total_tva,";
346  $sql .= " c.localtax1, c.localtax2, ";
347  $sql .= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,";
348  $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,";
349  $sql .= " c.date_commande as date_commande, c.date_livraison as delivery_date, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
350  $sql .= " c.fk_account,";
351  $sql .= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,";
352  $sql .= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,";
353  $sql .= " cm.libelle as methode_commande,";
354  $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_label, cr.libelle_facture as cond_reglement_doc,";
355  $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
356  $sql .= ', c.fk_incoterms, c.location_incoterms';
357  $sql .= ', i.libelle as label_incoterms';
358  $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
359  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid";
360  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id";
361  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method";
362  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
363 
364  if (empty($id)) {
365  $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")";
366  } else {
367  $sql .= " WHERE c.rowid=".((int) $id);
368  }
369 
370  if ($ref) {
371  $sql .= " AND c.ref='".$this->db->escape($ref)."'";
372  }
373 
374  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
375  $resql = $this->db->query($sql);
376  if ($resql) {
377  $obj = $this->db->fetch_object($resql);
378  if (!$obj) {
379  $this->error = 'Bill with id '.$id.' not found';
380  dol_syslog(get_class($this).'::fetch '.$this->error);
381  return 0;
382  }
383 
384  $this->id = $obj->rowid;
385  $this->entity = $obj->entity;
386 
387  $this->ref = $obj->ref;
388  $this->ref_supplier = $obj->ref_supplier;
389  $this->socid = $obj->fk_soc;
390  $this->fourn_id = $obj->fk_soc;
391  $this->statut = $obj->fk_statut;
392  $this->status = $obj->fk_statut;
393  $this->billed = $obj->billed;
394  $this->user_author_id = $obj->fk_user_author;
395  $this->user_valid_id = $obj->fk_user_valid;
396  $this->user_approve_id = $obj->fk_user_approve;
397  $this->user_approve_id2 = $obj->fk_user_approve2;
398  $this->total_ht = $obj->total_ht;
399  $this->total_tva = $obj->total_tva;
400  $this->total_localtax1 = $obj->localtax1;
401  $this->total_localtax2 = $obj->localtax2;
402  $this->total_ttc = $obj->total_ttc;
403  $this->date_creation = $this->db->jdate($obj->date_creation);
404  $this->date_valid = $this->db->jdate($obj->date_valid);
405  $this->date_approve = $this->db->jdate($obj->date_approve);
406  $this->date_approve2 = $this->db->jdate($obj->date_approve2);
407  $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier
408  if (isset($obj->date_commande)) {
409  $this->date = $this->date_commande;
410  } else {
411  $this->date = $this->date_creation;
412  }
413  $this->date_livraison = $this->db->jdate($obj->delivery_date); // deprecated
414  $this->delivery_date = $this->db->jdate($obj->delivery_date);
415  $this->remise_percent = $obj->remise_percent;
416  $this->methode_commande_id = $obj->fk_input_method;
417  $this->methode_commande = $obj->methode_commande;
418 
419  $this->source = $obj->source;
420  $this->fk_project = $obj->fk_project;
421  $this->cond_reglement_id = $obj->fk_cond_reglement;
422  $this->cond_reglement_code = $obj->cond_reglement_code;
423  $this->cond_reglement = $obj->cond_reglement_label; // deprecated
424  $this->cond_reglement_label = $obj->cond_reglement_label;
425  $this->cond_reglement_doc = $obj->cond_reglement_doc;
426  $this->fk_account = $obj->fk_account;
427  $this->mode_reglement_id = $obj->fk_mode_reglement;
428  $this->mode_reglement_code = $obj->mode_reglement_code;
429  $this->mode_reglement = $obj->mode_reglement_libelle;
430  $this->note = $obj->note_private; // deprecated
431  $this->note_private = $obj->note_private;
432  $this->note_public = $obj->note_public;
433  $this->model_pdf = $obj->model_pdf;
434  $this->modelpdf = $obj->model_pdf; // deprecated
435 
436  //Incoterms
437  $this->fk_incoterms = $obj->fk_incoterms;
438  $this->location_incoterms = $obj->location_incoterms;
439  $this->label_incoterms = $obj->label_incoterms;
440 
441  // Multicurrency
442  $this->fk_multicurrency = $obj->fk_multicurrency;
443  $this->multicurrency_code = $obj->multicurrency_code;
444  $this->multicurrency_tx = $obj->multicurrency_tx;
445  $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
446  $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
447  $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
448 
449  $this->extraparams = (array) json_decode($obj->extraparams, true);
450 
451  $this->db->free($resql);
452 
453  // Retrieve all extrafield
454  // fetch optionals attributes and labels
455  $this->fetch_optionals();
456 
457  if ($this->statut == 0) {
458  $this->brouillon = 1;
459  }
460 
461  /*
462  * Lines
463  */
464  $result = $this->fetch_lines();
465 
466  if ($result < 0) {
467  return -1;
468  } else {
469  return 1;
470  }
471  } else {
472  $this->error = $this->db->error()." sql=".$sql;
473  return -1;
474  }
475  }
476 
477  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
484  public function fetch_lines($only_product = 0)
485  {
486  global $conf;
487  // phpcs:enable
488 
489  $this->lines = array();
490 
491  $sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,";
492  $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,";
493  $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,";
494  $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,";
495  $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc, p.tobatch as product_tobatch, p.barcode as product_barcode,";
496  $sql .= " l.fk_unit,";
497  $sql .= " l.date_start, l.date_end,";
498  $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc';
499  $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l";
500  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
501  $sql .= " WHERE l.fk_commande = ".((int) $this->id);
502  if ($only_product) {
503  $sql .= ' AND p.fk_product_type = 0';
504  }
505  $sql .= " ORDER BY l.rang, l.rowid";
506  //print $sql;
507 
508  dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
509 
510  $result = $this->db->query($sql);
511  if ($result) {
512  $num = $this->db->num_rows($result);
513  $i = 0;
514 
515  while ($i < $num) {
516  $objp = $this->db->fetch_object($result);
517 
518  $line = new CommandeFournisseurLigne($this->db);
519 
520  $line->id = $objp->rowid;
521  $line->desc = $objp->description;
522  $line->description = $objp->description;
523  $line->qty = $objp->qty;
524  $line->tva_tx = $objp->tva_tx;
525  $line->localtax1_tx = $objp->localtax1_tx;
526  $line->localtax2_tx = $objp->localtax2_tx;
527  $line->localtax1_type = $objp->localtax1_type;
528  $line->localtax2_type = $objp->localtax2_type;
529  $line->subprice = $objp->subprice;
530  $line->pu_ht = $objp->subprice;
531  $line->remise_percent = $objp->remise_percent;
532 
533  $line->vat_src_code = $objp->vat_src_code;
534  $line->total_ht = $objp->total_ht;
535  $line->total_tva = $objp->total_tva;
536  $line->total_localtax1 = $objp->total_localtax1;
537  $line->total_localtax2 = $objp->total_localtax2;
538  $line->total_ttc = $objp->total_ttc;
539  $line->product_type = $objp->product_type;
540 
541  $line->fk_product = $objp->fk_product;
542 
543  $line->libelle = $objp->product_label; // deprecated
544  $line->product_label = $objp->product_label;
545  $line->product_desc = $objp->product_desc;
546  $line->product_tobatch = $objp->product_tobatch;
547  $line->product_barcode = $objp->product_barcode;
548 
549  $line->ref = $objp->product_ref; // Ref of product
550  $line->product_ref = $objp->product_ref; // Ref of product
551  $line->ref_fourn = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
552  $line->ref_supplier = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since
553 
554  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
555  // TODO We should not fetch this properties into the fetch_lines. This is NOT properties of a line.
556  // Move this into another method and call it when required.
557 
558  // Take better packaging for $objp->qty (first supplier ref quantity <= $objp->qty)
559  $sqlsearchpackage = 'SELECT rowid, packaging FROM '.MAIN_DB_PREFIX."product_fournisseur_price";
560  $sqlsearchpackage .= ' WHERE entity IN ('.getEntity('product_fournisseur_price').")";
561  $sqlsearchpackage .= " AND fk_product = ".((int) $objp->fk_product);
562  $sqlsearchpackage .= " AND ref_fourn = '".$this->db->escape($objp->ref_supplier)."'";
563  $sqlsearchpackage .= " AND quantity <= ".((float) $objp->qty); // required to be qualified
564  $sqlsearchpackage .= " AND (packaging IS NULL OR packaging = 0 OR packaging <= ".((float) $objp->qty).")"; // required to be qualified
565  $sqlsearchpackage .= " AND fk_soc = ".((int) $this->socid);
566  $sqlsearchpackage .= " ORDER BY packaging ASC"; // Take the smaller package first
567  $sqlsearchpackage .= " LIMIT 1";
568 
569  $resqlsearchpackage = $this->db->query($sqlsearchpackage);
570  if ($resqlsearchpackage) {
571  $objsearchpackage = $this->db->fetch_object($resqlsearchpackage);
572  if ($objsearchpackage) {
573  $line->fk_fournprice = $objsearchpackage->rowid;
574  $line->packaging = $objsearchpackage->packaging;
575  }
576  } else {
577  $this->error = $this->db->lasterror();
578  return -1;
579  }
580  }
581 
582  $line->date_start = $this->db->jdate($objp->date_start);
583  $line->date_end = $this->db->jdate($objp->date_end);
584  $line->fk_unit = $objp->fk_unit;
585 
586  // Multicurrency
587  $line->fk_multicurrency = $objp->fk_multicurrency;
588  $line->multicurrency_code = $objp->multicurrency_code;
589  $line->multicurrency_subprice = $objp->multicurrency_subprice;
590  $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
591  $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
592  $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
593 
594  $line->special_code = $objp->special_code;
595  $line->fk_parent_line = $objp->fk_parent_line;
596 
597  $line->rang = $objp->rang;
598 
599  // Retrieve all extrafield
600  // fetch optionals attributes and labels
601  $line->fetch_optionals();
602 
603  $this->lines[$i] = $line;
604 
605  $i++;
606  }
607  $this->db->free($result);
608 
609  return $num;
610  } else {
611  $this->error = $this->db->error()." sql=".$sql;
612  return -1;
613  }
614  }
615 
624  public function valid($user, $idwarehouse = 0, $notrigger = 0)
625  {
626  global $langs, $conf;
627  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
628 
629  $error = 0;
630 
631  dol_syslog(get_class($this)."::valid");
632  $result = 0;
633  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && (!empty($user->rights->fournisseur->commande->creer) || !empty($user->rights->supplier_order->creer)))
634  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate))) {
635  $this->db->begin();
636 
637  // Definition of supplier order numbering model name
638  $soc = new Societe($this->db);
639  $soc->fetch($this->fourn_id);
640 
641  // Check if object has a temporary ref
642  if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
643  $num = $this->getNextNumRef($soc);
644  } else {
645  $num = $this->ref;
646  }
647  $this->newref = dol_sanitizeFileName($num);
648 
649  $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur";
650  $sql .= " SET ref='".$this->db->escape($num)."',";
651  $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
652  $sql .= " date_valid='".$this->db->idate(dol_now())."',";
653  $sql .= " fk_user_valid = ".((int) $user->id);
654  $sql .= " WHERE rowid = ".((int) $this->id);
655  $sql .= " AND fk_statut = ".self::STATUS_DRAFT;
656 
657  $resql = $this->db->query($sql);
658  if (!$resql) {
659  dol_print_error($this->db);
660  $error++;
661  }
662 
663  if (!$error && !$notrigger) {
664  // Call trigger
665  $result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user);
666  if ($result < 0) {
667  $error++;
668  }
669  // End call triggers
670  }
671 
672  if (!$error) {
673  $this->oldref = $this->ref;
674 
675  // Rename directory if dir was a temporary ref
676  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
677  // Now we rename also files into index
678  $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/commande/".$this->db->escape($this->newref)."'";
679  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
680  $resql = $this->db->query($sql);
681  if (!$resql) {
682  $error++; $this->error = $this->db->lasterror();
683  }
684 
685  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
686  $oldref = dol_sanitizeFileName($this->ref);
687  $newref = dol_sanitizeFileName($num);
688  $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref;
689  $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref;
690  if (!$error && file_exists($dirsource)) {
691  dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
692 
693  if (@rename($dirsource, $dirdest)) {
694  dol_syslog("Rename ok");
695  // Rename docs starting with $oldref with $newref
696  $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
697  foreach ($listoffiles as $fileentry) {
698  $dirsource = $fileentry['name'];
699  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
700  $dirsource = $fileentry['path'].'/'.$dirsource;
701  $dirdest = $fileentry['path'].'/'.$dirdest;
702  @rename($dirsource, $dirdest);
703  }
704  }
705  }
706  }
707  }
708 
709  if (!$error) {
710  $result = 1;
711  $this->statut = self::STATUS_VALIDATED;
712  $this->ref = $num;
713  }
714 
715  if (!$error) {
716  $this->db->commit();
717  return 1;
718  } else {
719  $this->db->rollback();
720  return -1;
721  }
722  } else {
723  $this->error = 'NotAuthorized';
724  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
725  return -1;
726  }
727  }
728 
735  public function getLibStatut($mode = 0)
736  {
737  return $this->LibStatut($this->statut, $mode, $this->billed);
738  }
739 
740  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
749  public function LibStatut($status, $mode = 0, $billed = 0)
750  {
751  // phpcs:enable
752  global $conf, $langs, $hookmanager;
753 
754  if (empty($this->statuts) || empty($this->statutshort)) {
755  $langs->load('orders');
756 
757  $this->statuts[0] = 'StatusSupplierOrderDraft';
758  $this->statuts[1] = 'StatusSupplierOrderValidated';
759  $this->statuts[2] = 'StatusSupplierOrderApproved';
760  if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
761  $this->statuts[3] = 'StatusSupplierOrderOnProcess';
762  } else {
763  $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation';
764  }
765  $this->statuts[4] = 'StatusSupplierOrderReceivedPartially';
766  $this->statuts[5] = 'StatusSupplierOrderReceivedAll';
767  $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled
768  $this->statuts[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled
769  $this->statuts[9] = 'StatusSupplierOrderRefused';
770 
771  // List of language codes for status
772  $this->statutshort[0] = 'StatusSupplierOrderDraftShort';
773  $this->statutshort[1] = 'StatusSupplierOrderValidatedShort';
774  $this->statutshort[2] = 'StatusSupplierOrderApprovedShort';
775  $this->statutshort[3] = 'StatusSupplierOrderOnProcessShort';
776  $this->statutshort[4] = 'StatusSupplierOrderReceivedPartiallyShort';
777  $this->statutshort[5] = 'StatusSupplierOrderReceivedAllShort';
778  $this->statutshort[6] = 'StatusSupplierOrderCanceledShort';
779  $this->statutshort[7] = 'StatusSupplierOrderCanceledShort';
780  $this->statutshort[9] = 'StatusSupplierOrderRefusedShort';
781  }
782 
783  $statustrans = array(
784  0 => 'status0',
785  1 => 'status1b',
786  2 => 'status1',
787  3 => 'status4',
788  4 => 'status4b',
789  5 => 'status6',
790  6 => 'status9',
791  7 => 'status9',
792  9 => 'status9',
793  );
794 
795  $statusClass = 'status0';
796  if (!empty($statustrans[$status])) {
797  $statusClass = $statustrans[$status];
798  }
799 
800  $billedtext = '';
801  if ($billed) {
802  $billedtext = ' - '.$langs->trans("Billed");
803  }
804  if ($status == 5 && $billed) {
805  $statusClass = 'status6';
806  }
807 
808  $statusLong = $langs->transnoentitiesnoconv($this->statuts[$status]).$billedtext;
809  $statusShort = $langs->transnoentitiesnoconv($this->statutshort[$status]);
810 
811  $parameters = array('status' => $status, 'mode' => $mode, 'billed' => $billed);
812  $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
813  if ($reshook > 0) {
814  return $hookmanager->resPrint;
815  }
816 
817  return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode);
818  }
819 
820 
831  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
832  {
833  global $langs, $conf, $user, $hookmanager;
834 
835  $result = '';
836 
837  $label = '';
838 
839  if ($user->rights->fournisseur->commande->lire) {
840  $label = '<u class="paddingrightonly">'.$langs->trans("SupplierOrder").'</u>';
841  if (isset($this->statut)) {
842  $label .= ' '.$this->getLibStatut(5);
843  }
844  if (!empty($this->ref)) {
845  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
846  }
847  if (!empty($this->ref_supplier)) {
848  $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
849  }
850  if (!empty($this->total_ht)) {
851  $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
852  }
853  if (!empty($this->total_tva)) {
854  $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
855  }
856  if (!empty($this->total_ttc)) {
857  $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
858  }
859  if (!empty($this->date)) {
860  $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
861  }
862  if (!empty($this->delivery_date)) {
863  $label .= '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
864  }
865  }
866 
867  $picto = 'order';
868  $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
869 
870  if ($option !== 'nolink') {
871  // Add param to save lastsearch_values or not
872  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
873  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
874  $add_save_lastsearch_values = 1;
875  }
876  if ($add_save_lastsearch_values) {
877  $url .= '&save_lastsearch_values=1';
878  }
879  }
880 
881  $linkclose = '';
882  if (empty($notooltip)) {
883  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
884  $label = $langs->trans("ShowOrder");
885  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
886  }
887  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
888  $linkclose .= ' class="classfortooltip"';
889  }
890 
891  $linkstart = '<a href="'.$url.'"';
892  $linkstart .= $linkclose.'>';
893  $linkend = '</a>';
894 
895  $result .= $linkstart;
896  if ($withpicto) {
897  $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
898  }
899  if ($withpicto != 2) {
900  $result .= $this->ref;
901  }
902  $result .= $linkend;
903 
904  if ($addlinktonotes) {
905  $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
906  if ($txttoshow) {
907  $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
908  $result .= ' <span class="note inline-block">';
909  $result .= '<a href="'.DOL_URL_ROOT.'/fourn/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
910  $result .= img_picto('', 'note');
911  $result .= '</a>';
912  //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
913  //$result.='</a>';
914  $result .= '</span>';
915  }
916  }
917 
918  global $action;
919  $hookmanager->initHooks(array($this->element . 'dao'));
920  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
921  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
922  if ($reshook > 0) {
923  $result = $hookmanager->resPrint;
924  } else {
925  $result .= $hookmanager->resPrint;
926  }
927  return $result;
928  }
929 
930 
938  public function getNextNumRef($soc)
939  {
940  global $db, $langs, $conf;
941  $langs->load("orders");
942 
943  if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER)) {
944  $mybool = false;
945 
946  $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
947  $classname = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
948 
949  // Include file with class
950  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
951 
952  foreach ($dirmodels as $reldir) {
953  $dir = dol_buildpath($reldir."core/modules/supplier_order/");
954 
955  // Load file with numbering class (if found)
956  $mybool |= @include_once $dir.$file;
957  }
958 
959  if ($mybool === false) {
960  dol_print_error('', "Failed to include file ".$file);
961  return '';
962  }
963 
964  $obj = new $classname();
965  $numref = $obj->getNextValue($soc, $this);
966 
967  if ($numref != "") {
968  return $numref;
969  } else {
970  $this->error = $obj->error;
971  return -1;
972  }
973  } else {
974  $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
975  return -2;
976  }
977  }
984  public function classifyBilled(User $user)
985  {
986  $error = 0;
987 
988  if ($this->billed) {
989  return 0;
990  }
991 
992  $this->db->begin();
993 
994  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1';
995  $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
996 
997  if ($this->db->query($sql)) {
998  if (!$error) {
999  // Call trigger
1000  $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user);
1001  if ($result < 0) {
1002  $error++;
1003  }
1004  // End call triggers
1005  }
1006 
1007  if (!$error) {
1008  $this->billed = 1;
1009 
1010  $this->db->commit();
1011  return 1;
1012  } else {
1013  $this->db->rollback();
1014  return -1;
1015  }
1016  } else {
1017  dol_print_error($this->db);
1018 
1019  $this->db->rollback();
1020  return -1;
1021  }
1022  }
1023 
1032  public function approve($user, $idwarehouse = 0, $secondlevel = 0)
1033  {
1034  global $langs, $conf;
1035  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1036 
1037  $error = 0;
1038 
1039  dol_syslog(get_class($this)."::approve");
1040 
1041  if ($user->rights->fournisseur->commande->approuver) {
1042  $now = dol_now();
1043 
1044  $this->db->begin();
1045 
1046  // Definition of order numbering model name
1047  $soc = new Societe($this->db);
1048  $soc->fetch($this->fourn_id);
1049 
1050  // Check if object has a temporary ref
1051  if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1052  $num = $this->getNextNumRef($soc);
1053  } else {
1054  $num = $this->ref;
1055  }
1056  $this->newref = dol_sanitizeFileName($num);
1057 
1058  // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
1059  $movetoapprovestatus = true;
1060  $comment = '';
1061 
1062  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
1063  $sql .= " SET ref='".$this->db->escape($num)."',";
1064  if (empty($secondlevel)) { // standard or first level approval
1065  $sql .= " date_approve='".$this->db->idate($now)."',";
1066  $sql .= " fk_user_approve = ".$user->id;
1067  if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) {
1068  if (empty($this->user_approve_id2)) {
1069  $movetoapprovestatus = false; // second level approval not done
1070  $comment = ' (first level)';
1071  }
1072  }
1073  } else // request a second level approval
1074  {
1075  $sql .= " date_approve2='".$this->db->idate($now)."',";
1076  $sql .= " fk_user_approve2 = ".((int) $user->id);
1077  if (empty($this->user_approve_id)) {
1078  $movetoapprovestatus = false; // first level approval not done
1079  }
1080  $comment = ' (second level)';
1081  }
1082  // If double approval is required and first approval, we keep status to 1 = validated
1083  if ($movetoapprovestatus) {
1084  $sql .= ", fk_statut = ".self::STATUS_ACCEPTED;
1085  } else {
1086  $sql .= ", fk_statut = ".self::STATUS_VALIDATED;
1087  }
1088  $sql .= " WHERE rowid = ".((int) $this->id);
1089  $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
1090 
1091  if ($this->db->query($sql)) {
1092  if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT)) {
1093  $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
1094  if ($result < 0 && $result != -2) { // -2 means already exists
1095  $error++;
1096  }
1097  }
1098 
1099  // If stock is incremented on validate order, we must increment it
1100  if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) {
1101  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
1102  $langs->load("agenda");
1103 
1104  $cpt = count($this->lines);
1105  for ($i = 0; $i < $cpt; $i++) {
1106  // Product with reference
1107  if ($this->lines[$i]->fk_product > 0) {
1108  $this->line = $this->lines[$i];
1109  $mouvP = new MouvementStock($this->db);
1110  $mouvP->origin = &$this;
1111  $mouvP->setOrigin($this->element, $this->id);
1112  // We decrement stock of product (and sub-products)
1113  $up_ht_disc = $this->lines[$i]->subprice;
1114  if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) {
1115  $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
1116  }
1117  $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref));
1118  if ($result < 0) {
1119  $error++;
1120  }
1121  unset($this->line);
1122  }
1123  }
1124  }
1125 
1126  if (!$error) {
1127  // Call trigger
1128  $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user);
1129  if ($result < 0) {
1130  $error++;
1131  }
1132  // End call triggers
1133  }
1134 
1135  if (!$error) {
1136  $this->ref = $this->newref;
1137 
1138  if ($movetoapprovestatus) {
1139  $this->statut = self::STATUS_ACCEPTED;
1140  } else {
1141  $this->statut = self::STATUS_VALIDATED;
1142  }
1143  if (empty($secondlevel)) { // standard or first level approval
1144  $this->date_approve = $now;
1145  $this->user_approve_id = $user->id;
1146  } else // request a second level approval
1147  {
1148  $this->date_approve2 = $now;
1149  $this->user_approve_id2 = $user->id;
1150  }
1151 
1152  $this->db->commit();
1153  return 1;
1154  } else {
1155  $this->db->rollback();
1156  return -1;
1157  }
1158  } else {
1159  $this->db->rollback();
1160  $this->error = $this->db->lasterror();
1161  return -1;
1162  }
1163  } else {
1164  dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
1165  }
1166  return -1;
1167  }
1168 
1175  public function refuse($user)
1176  {
1177  global $conf, $langs;
1178 
1179  $error = 0;
1180 
1181  dol_syslog(get_class($this)."::refuse");
1182  $result = 0;
1183  if ($user->rights->fournisseur->commande->approuver) {
1184  $this->db->begin();
1185 
1186  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED;
1187  $sql .= " WHERE rowid = ".((int) $this->id);
1188 
1189  if ($this->db->query($sql)) {
1190  $result = 0;
1191 
1192  if ($error == 0) {
1193  // Call trigger
1194  $result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user);
1195  if ($result < 0) {
1196  $error++;
1197  $this->db->rollback();
1198  } else {
1199  $this->db->commit();
1200  }
1201  // End call triggers
1202  }
1203  } else {
1204  $this->db->rollback();
1205  $this->error = $this->db->lasterror();
1206  dol_syslog(get_class($this)."::refuse Error -1");
1207  $result = -1;
1208  }
1209  } else {
1210  dol_syslog(get_class($this)."::refuse Not Authorized");
1211  }
1212  return $result;
1213  }
1214 
1215  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1224  public function Cancel($user, $idwarehouse = -1)
1225  {
1226  // phpcs:enable
1227  global $langs, $conf;
1228 
1229  $error = 0;
1230 
1231  //dol_syslog("CommandeFournisseur::Cancel");
1232  $result = 0;
1233  if ($user->rights->fournisseur->commande->commander) {
1234  $statut = self::STATUS_CANCELED;
1235 
1236  $this->db->begin();
1237 
1238  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".((int) $statut);
1239  $sql .= " WHERE rowid = ".((int) $this->id);
1240  dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
1241  if ($this->db->query($sql)) {
1242  $result = 0;
1243 
1244  // Call trigger
1245  $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user);
1246  if ($result < 0) {
1247  $error++;
1248  }
1249  // End call triggers
1250 
1251  if ($error == 0) {
1252  $this->db->commit();
1253  return 1;
1254  } else {
1255  $this->db->rollback();
1256  return -1;
1257  }
1258  } else {
1259  $this->db->rollback();
1260  $this->error = $this->db->lasterror();
1261  dol_syslog(get_class($this)."::cancel ".$this->error);
1262  return -1;
1263  }
1264  } else {
1265  dol_syslog(get_class($this)."::cancel Not Authorized");
1266  return -1;
1267  }
1268  }
1269 
1279  public function commande($user, $date, $methode, $comment = '')
1280  {
1281  global $langs;
1282  dol_syslog(get_class($this)."::commande");
1283  $error = 0;
1284  if ($user->rights->fournisseur->commande->commander) {
1285  $this->db->begin();
1286 
1287  $newnoteprivate = $this->note_private;
1288  if ($comment) {
1289  $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment);
1290  }
1291 
1292  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
1293  $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."', ";
1294  $sql .= " note_private='".$this->db->escape($newnoteprivate)."'";
1295  $sql .= " WHERE rowid=".((int) $this->id);
1296 
1297  dol_syslog(get_class($this)."::commande", LOG_DEBUG);
1298  if ($this->db->query($sql)) {
1299  $this->statut = self::STATUS_ORDERSENT;
1300  $this->methode_commande_id = $methode;
1301  $this->date_commande = $date;
1302  $this->context = array('comments' => $comment);
1303 
1304  // Call trigger
1305  $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user);
1306  if ($result < 0) {
1307  $error++;
1308  }
1309  // End call triggers
1310  } else {
1311  $error++;
1312  $this->error = $this->db->lasterror();
1313  $this->errors[] = $this->db->lasterror();
1314  }
1315 
1316  if (!$error) {
1317  $this->db->commit();
1318  } else {
1319  $this->db->rollback();
1320  }
1321  } else {
1322  $error++;
1323  $this->error = $langs->trans('NotAuthorized');
1324  $this->errors[] = $langs->trans('NotAuthorized');
1325  dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
1326  }
1327 
1328  return ($error ? -1 : 1);
1329  }
1330 
1338  public function create($user, $notrigger = 0)
1339  {
1340  global $langs, $conf, $hookmanager;
1341 
1342  $this->db->begin();
1343 
1344  $error = 0;
1345  $now = dol_now();
1346 
1347  // set tmp vars
1348  $date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set
1349  if (empty($date)) {
1350  $date = $now;
1351  }
1352  $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date;
1353 
1354  // Clean parameters
1355  if (empty($this->source)) {
1356  $this->source = 0;
1357  }
1358 
1359  // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1360  if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1361  list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
1362  } else {
1363  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1364  }
1365  if (empty($this->fk_multicurrency)) {
1366  $this->multicurrency_code = $conf->currency;
1367  $this->fk_multicurrency = 0;
1368  $this->multicurrency_tx = 1;
1369  }
1370 
1371  // We set order into draft status
1372  $this->brouillon = 1;
1373 
1374  $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
1375  $sql .= "ref";
1376  $sql .= ", ref_supplier";
1377  $sql .= ", note_private";
1378  $sql .= ", note_public";
1379  $sql .= ", entity";
1380  $sql .= ", fk_soc";
1381  $sql .= ", fk_projet";
1382  $sql .= ", date_creation";
1383  $sql .= ", date_livraison";
1384  $sql .= ", fk_user_author";
1385  $sql .= ", fk_statut";
1386  $sql .= ", source";
1387  $sql .= ", model_pdf";
1388  $sql .= ", fk_mode_reglement";
1389  $sql .= ", fk_cond_reglement";
1390  $sql .= ", fk_account";
1391  $sql .= ", fk_incoterms, location_incoterms";
1392  $sql .= ", fk_multicurrency";
1393  $sql .= ", multicurrency_code";
1394  $sql .= ", multicurrency_tx";
1395  $sql .= ") ";
1396  $sql .= " VALUES (";
1397  $sql .= "'(PROV)'";
1398  $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
1399  $sql .= ", '".$this->db->escape($this->note_private)."'";
1400  $sql .= ", '".$this->db->escape($this->note_public)."'";
1401  $sql .= ", ".((int) $conf->entity);
1402  $sql .= ", ".((int) $this->socid);
1403  $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1404  $sql .= ", '".$this->db->idate($date)."'";
1405  $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
1406  $sql .= ", ".((int) $user->id);
1407  $sql .= ", ".self::STATUS_DRAFT;
1408  $sql .= ", ".((int) $this->source);
1409  $sql .= ", '".$this->db->escape($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)."'";
1410  $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
1411  $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
1412  $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
1413  $sql .= ", ".(int) $this->fk_incoterms;
1414  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1415  $sql .= ", ".(int) $this->fk_multicurrency;
1416  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1417  $sql .= ", ".(double) $this->multicurrency_tx;
1418  $sql .= ")";
1419 
1420  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1421  if ($this->db->query($sql)) {
1422  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur");
1423 
1424  if ($this->id) {
1425  $num = count($this->lines);
1426 
1427  // insert products details into database
1428  for ($i = 0; $i < $num; $i++) {
1429  $line = $this->lines[$i];
1430  if (!is_object($line)) {
1431  $line = (object) $line;
1432  }
1433 
1434 
1435  $this->special_code = $line->special_code; // TODO : remove this in 9.0 and add special_code param to addline()
1436 
1437  // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
1438  $result = $this->addline(
1439  $line->desc,
1440  $line->subprice,
1441  $line->qty,
1442  $line->tva_tx,
1443  $line->localtax1_tx,
1444  $line->localtax2_tx,
1445  $line->fk_product,
1446  0,
1447  $line->ref_fourn, // $line->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
1448  $line->remise_percent,
1449  'HT',
1450  0,
1451  $line->product_type,
1452  $line->info_bits,
1453  false,
1454  $line->date_start,
1455  $line->date_end,
1456  $line->array_options,
1457  $line->fk_unit
1458  );
1459  if ($result < 0) {
1460  dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functionnal error
1461  $this->db->rollback();
1462  return -1;
1463  }
1464  }
1465 
1466  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
1467  $sql .= " SET ref='(PROV".$this->id.")'";
1468  $sql .= " WHERE rowid=".((int) $this->id);
1469  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1470  if ($this->db->query($sql)) {
1471  // Add link with price request and supplier order
1472  if ($this->id) {
1473  $this->ref = "(PROV".$this->id.")";
1474 
1475  if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1476  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1477  }
1478 
1479  // Add object linked
1480  if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1481  foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1482  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, ...))
1483  foreach ($tmp_origin_id as $origin_id) {
1484  $ret = $this->add_object_linked($origin, $origin_id);
1485  if (!$ret) {
1486  dol_print_error($this->db);
1487  $error++;
1488  }
1489  }
1490  } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1491  {
1492  $origin_id = $tmp_origin_id;
1493  $ret = $this->add_object_linked($origin, $origin_id);
1494  if (!$ret) {
1495  dol_print_error($this->db);
1496  $error++;
1497  }
1498  }
1499  }
1500  }
1501  }
1502 
1503  if (!$error) {
1504  $result = $this->insertExtraFields();
1505  if ($result < 0) {
1506  $error++;
1507  }
1508  }
1509 
1510  if (!$error && !$notrigger) {
1511  // Call trigger
1512  $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user);
1513  if ($result < 0) {
1514  $this->db->rollback();
1515  return -1;
1516  }
1517  // End call triggers
1518  }
1519 
1520  $this->db->commit();
1521  return $this->id;
1522  } else {
1523  $this->error = $this->db->lasterror();
1524  $this->db->rollback();
1525  return -2;
1526  }
1527  }
1528  } else {
1529  $this->error = $this->db->lasterror();
1530  $this->db->rollback();
1531  return -1;
1532  }
1533  }
1534 
1542  public function update(User $user, $notrigger = 0)
1543  {
1544  global $conf;
1545 
1546  $error = 0;
1547 
1548  // Clean parameters
1549  if (isset($this->ref)) {
1550  $this->ref = trim($this->ref);
1551  }
1552  if (isset($this->ref_supplier)) {
1553  $this->ref_supplier = trim($this->ref_supplier);
1554  }
1555  if (isset($this->note_private)) {
1556  $this->note_private = trim($this->note_private);
1557  }
1558  if (isset($this->note_public)) {
1559  $this->note_public = trim($this->note_public);
1560  }
1561  if (isset($this->model_pdf)) {
1562  $this->model_pdf = trim($this->model_pdf);
1563  }
1564  if (isset($this->import_key)) {
1565  $this->import_key = trim($this->import_key);
1566  }
1567 
1568  // Update request
1569  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1570 
1571  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1572  $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1573  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1574  $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
1575  $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
1576  $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1577  $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
1578  $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
1579  $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
1580  $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
1581  $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
1582  $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
1583  $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").",";
1584  $sql .= " fk_user_valid=".(isset($this->user_valid) && $this->user_valid > 0 ? $this->user_valid : "null").",";
1585  $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
1586  $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
1587  $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
1588  $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
1589  //$sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? $this->shipping_method_id : "null").",";
1590  $sql .= " fk_account=".($this->fk_account > 0 ? $this->fk_account : "null").",";
1591  //$sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null").",";
1592  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1593  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1594  $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1595  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
1596 
1597  $sql .= " WHERE rowid=".((int) $this->id);
1598 
1599  $this->db->begin();
1600 
1601  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1602  $resql = $this->db->query($sql);
1603  if (!$resql) {
1604  $error++;
1605  $this->errors[] = "Error ".$this->db->lasterror();
1606  }
1607 
1608  if (!$error) {
1609  $result = $this->insertExtraFields();
1610  if ($result < 0) {
1611  $error++;
1612  }
1613  }
1614 
1615  if (!$error && !$notrigger) {
1616  // Call trigger
1617  $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
1618  if ($result < 0) {
1619  $error++;
1620  }
1621  // End call triggers
1622  }
1623 
1624  // Commit or rollback
1625  if ($error) {
1626  foreach ($this->errors as $errmsg) {
1627  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1628  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1629  }
1630  $this->db->rollback();
1631  return -1 * $error;
1632  } else {
1633  $this->db->commit();
1634  return 1;
1635  }
1636  }
1637 
1646  public function createFromClone(User $user, $socid = 0, $notrigger = 0)
1647  {
1648  global $conf, $user, $hookmanager;
1649 
1650  $error = 0;
1651 
1652  $this->db->begin();
1653 
1654  // get extrafields so they will be clone
1655  foreach ($this->lines as $line) {
1656  $line->fetch_optionals();
1657  }
1658 
1659  // Load source object
1660  $objFrom = clone $this;
1661 
1662  // Change socid if needed
1663  if (!empty($socid) && $socid != $this->socid) {
1664  $objsoc = new Societe($this->db);
1665 
1666  if ($objsoc->fetch($socid) > 0) {
1667  $this->socid = $objsoc->id;
1668  $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1669  $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1670  $this->fk_project = 0;
1671  $this->fk_delivery_address = 0;
1672  }
1673 
1674  // TODO Change product price if multi-prices
1675  }
1676 
1677  $this->id = 0;
1678  $this->statut = self::STATUS_DRAFT;
1679 
1680  // Clear fields
1681  $this->user_author_id = $user->id;
1682  $this->user_valid = 0;
1683  $this->date_creation = '';
1684  $this->date_validation = '';
1685  $this->ref_supplier = '';
1686  $this->user_approve_id = '';
1687  $this->user_approve_id2 = '';
1688  $this->date_approve = '';
1689  $this->date_approve2 = '';
1690 
1691  // Create clone
1692  $this->context['createfromclone'] = 'createfromclone';
1693  $result = $this->create($user, $notrigger);
1694  if ($result < 0) {
1695  $error++;
1696  }
1697 
1698  if (!$error) {
1699  // Hook of thirdparty module
1700  if (is_object($hookmanager)) {
1701  $parameters = array('objFrom'=>$objFrom);
1702  $action = '';
1703  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1704  if ($reshook < 0) {
1705  $this->errors += $hookmanager->errors;
1706  $this->error = $hookmanager->error;
1707  $error++;
1708  }
1709  }
1710  }
1711 
1712  unset($this->context['createfromclone']);
1713 
1714  // End
1715  if (!$error) {
1716  $this->db->commit();
1717  return $this->id;
1718  } else {
1719  $this->db->rollback();
1720  return -1;
1721  }
1722  }
1723 
1752  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, $rang = -1)
1753  {
1754  global $langs, $mysoc, $conf;
1755 
1756  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");
1757  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1758 
1759  if ($this->statut == self::STATUS_DRAFT) {
1760  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1761 
1762  // Clean parameters
1763  if (empty($qty)) {
1764  $qty = 0;
1765  }
1766  if (!$info_bits) {
1767  $info_bits = 0;
1768  }
1769  if (empty($txtva)) {
1770  $txtva = 0;
1771  }
1772  if (empty($rang)) {
1773  $rang = 0;
1774  }
1775  if (empty($txlocaltax1)) {
1776  $txlocaltax1 = 0;
1777  }
1778  if (empty($txlocaltax2)) {
1779  $txlocaltax2 = 0;
1780  }
1781  if (empty($remise_percent)) {
1782  $remise_percent = 0;
1783  }
1784 
1785  $remise_percent = price2num($remise_percent);
1786  $qty = price2num($qty);
1787  $pu_ht = price2num($pu_ht);
1788  $pu_ht_devise = price2num($pu_ht_devise);
1789  $pu_ttc = price2num($pu_ttc);
1790  if (!preg_match('/\((.*)\)/', $txtva)) {
1791  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1792  }
1793  $txlocaltax1 = price2num($txlocaltax1);
1794  $txlocaltax2 = price2num($txlocaltax2);
1795  if ($price_base_type == 'HT') {
1796  $pu = $pu_ht;
1797  } else {
1798  $pu = $pu_ttc;
1799  }
1800  $desc = trim($desc);
1801 
1802  // Check parameters
1803  if ($qty < 0 && !$fk_product) {
1804  $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product"));
1805  return -1;
1806  }
1807  if ($type < 0) {
1808  return -1;
1809  }
1810  if ($date_start && $date_end && $date_start > $date_end) {
1811  $langs->load("errors");
1812  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1813  return -1;
1814  }
1815 
1816 
1817  $this->db->begin();
1818 
1819  $product_type = $type;
1820  $label = ''; // deprecated
1821 
1822  if ($fk_product > 0) {
1823  if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) {
1824  // Check quantity is enough
1825  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);
1826  $prod = new Product($this->db);
1827  if ($prod->fetch($fk_product) > 0) {
1828  $product_type = $prod->type;
1829  $label = $prod->label;
1830 
1831  // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
1832  // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
1833  $result = $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', (isset($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
1834 
1835  // If supplier order created from customer order, we take best supplier price
1836  // If $pu (defined previously from pu_ht or pu_ttc) is not defined at all, we also take the best supplier price
1837  if ($result > 0 && ($origin == 'commande' || $pu === '')) {
1838  $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice
1839  $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice
1840  // is remise percent not keyed but present for the product we add it
1841  if ($remise_percent == 0 && $prod->remise_percent != 0) {
1842  $remise_percent = $prod->remise_percent;
1843  }
1844  }
1845  if ($result == 0) { // If result == 0, we failed to found the supplier reference price
1846  $langs->load("errors");
1847  $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
1848  $this->db->rollback();
1849  dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
1850  //$pu = $prod->fourn_pu; // We do not overwrite unit price
1851  //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price
1852  return -1;
1853  }
1854  if ($result == -1) {
1855  $langs->load("errors");
1856  $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
1857  $this->db->rollback();
1858  dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
1859  return -1;
1860  }
1861  if ($result < -1) {
1862  $this->error = $prod->error;
1863  $this->db->rollback();
1864  dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
1865  return -1;
1866  }
1867  } else {
1868  $this->error = $prod->error;
1869  $this->db->rollback();
1870  return -1;
1871  }
1872  }
1873 
1874  // Predefine quantity according to packaging
1875  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
1876  $prod = new Product($this->db);
1877  $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', (empty($this->fk_soc) ? $this->socid : $this->fk_soc));
1878 
1879  if ($qty < $prod->packaging) {
1880  $qty = $prod->packaging;
1881  } else {
1882  if (!empty($prod->packaging) && ($qty % $prod->packaging) > 0) {
1883  $coeff = intval($qty / $prod->packaging) + 1;
1884  $qty = $prod->packaging * $coeff;
1885  setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs');
1886  }
1887  }
1888  }
1889  }
1890 
1891  if (!empty($conf->multicurrency->enabled) && $pu_ht_devise > 0) {
1892  $pu = 0;
1893  }
1894 
1895  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
1896 
1897  // Clean vat code
1898  $vat_src_code = '';
1899  if (preg_match('/\((.*)\)/', $txtva, $reg)) {
1900  $vat_src_code = $reg[1];
1901  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
1902  }
1903 
1904  // Calcul du total TTC et de la TVA pour la ligne a partir de
1905  // qty, pu, remise_percent et txtva
1906  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1907  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1908 
1909  $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);
1910 
1911  $total_ht = $tabprice[0];
1912  $total_tva = $tabprice[1];
1913  $total_ttc = $tabprice[2];
1914  $total_localtax1 = $tabprice[9];
1915  $total_localtax2 = $tabprice[10];
1916  $pu = $pu_ht = $tabprice[3];
1917 
1918  // MultiCurrency
1919  $multicurrency_total_ht = $tabprice[16];
1920  $multicurrency_total_tva = $tabprice[17];
1921  $multicurrency_total_ttc = $tabprice[18];
1922  $pu_ht_devise = $tabprice[19];
1923 
1924  $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
1925  $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
1926 
1927  if ($rang < 0) {
1928  $rangmax = $this->line_max();
1929  $rang = $rangmax + 1;
1930  }
1931 
1932  // Insert line
1933  $this->line = new CommandeFournisseurLigne($this->db);
1934 
1935  $this->line->context = $this->context;
1936 
1937  $this->line->fk_commande = $this->id;
1938  $this->line->label = $label;
1939  $this->line->ref_fourn = $ref_supplier;
1940  $this->line->ref_supplier = $ref_supplier;
1941  $this->line->desc = $desc;
1942  $this->line->qty = $qty;
1943  $this->line->tva_tx = $txtva;
1944  $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
1945  $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
1946  $this->line->localtax1_type = $localtax1_type;
1947  $this->line->localtax2_type = $localtax2_type;
1948  $this->line->fk_product = $fk_product;
1949  $this->line->product_type = $product_type;
1950  $this->line->remise_percent = $remise_percent;
1951  $this->line->subprice = $pu_ht;
1952  $this->line->rang = $rang;
1953  $this->line->info_bits = $info_bits;
1954 
1955  $this->line->vat_src_code = $vat_src_code;
1956  $this->line->total_ht = $total_ht;
1957  $this->line->total_tva = $total_tva;
1958  $this->line->total_localtax1 = $total_localtax1;
1959  $this->line->total_localtax2 = $total_localtax2;
1960  $this->line->total_ttc = $total_ttc;
1961  $this->line->product_type = $type;
1962  $this->line->special_code = $this->special_code;
1963  $this->line->origin = $origin;
1964  $this->line->origin_id = $origin_id;
1965  $this->line->fk_unit = $fk_unit;
1966 
1967  $this->line->date_start = $date_start;
1968  $this->line->date_end = $date_end;
1969 
1970  // Multicurrency
1971  $this->line->fk_multicurrency = $this->fk_multicurrency;
1972  $this->line->multicurrency_code = $this->multicurrency_code;
1973  $this->line->multicurrency_subprice = $pu_ht_devise;
1974  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
1975  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
1976  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
1977 
1978  $this->line->subprice = $pu_ht;
1979  $this->line->price = $this->line->subprice;
1980 
1981  $this->line->remise_percent = $remise_percent;
1982 
1983  if (is_array($array_options) && count($array_options) > 0) {
1984  $this->line->array_options = $array_options;
1985  }
1986 
1987  $result = $this->line->insert($notrigger);
1988  if ($result > 0) {
1989  // Reorder if child line
1990  if (!empty($fk_parent_line)) {
1991  $this->line_order(true, 'DESC');
1992  } elseif ($rang > 0 && $rang <= count($this->lines)) { // Update all rank of all other lines
1993  $linecount = count($this->lines);
1994  for ($ii = $rang; $ii <= $linecount; $ii++) {
1995  $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
1996  }
1997  }
1998 
1999  // Mise a jour informations denormalisees au niveau de la commande meme
2000  $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.
2001  if ($result > 0) {
2002  $this->db->commit();
2003  return $this->line->id;
2004  } else {
2005  $this->db->rollback();
2006  return -1;
2007  }
2008  } else {
2009  $this->error = $this->line->error;
2010  $this->errors = $this->line->errors;
2011  dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
2012  $this->db->rollback();
2013  return -1;
2014  }
2015  }
2016  }
2017 
2018 
2035  public function dispatchProduct($user, $product, $qty, $entrepot, $price = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $fk_commandefourndet = 0, $notrigger = 0)
2036  {
2037  global $conf, $langs;
2038 
2039  $error = 0;
2040  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
2041 
2042  // Check parameters (if test are wrong here, there is bug into caller)
2043  if ($entrepot <= 0) {
2044  $this->error = 'ErrorBadValueForParameterWarehouse';
2045  return -1;
2046  }
2047  if ($qty == 0) {
2048  $this->error = 'ErrorBadValueForParameterQty';
2049  return -1;
2050  }
2051 
2052  $dispatchstatus = 1;
2053  if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
2054  $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on
2055  }
2056 
2057  $now = dol_now();
2058 
2059  $inventorycode = dol_print_date(dol_now(), 'dayhourlog');
2060 
2061  if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) {
2062  $this->db->begin();
2063 
2064  $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch";
2065  $sql .= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES";
2066  $sql .= " ('".$this->id."','".$product."','".$qty."',".($entrepot > 0 ? "'".$entrepot."'" : "null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', ";
2067  $sql .= ($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ".($batch ? "'".$this->db->escape($batch)."'" : "null");
2068  $sql .= ")";
2069 
2070  dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG);
2071  $resql = $this->db->query($sql);
2072  if ($resql) {
2073  if (!$notrigger) {
2074  global $conf, $langs, $user;
2075  // Call trigger
2076  $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user);
2077  if ($result < 0) {
2078  $error++;
2079  }
2080  // End call triggers
2081  }
2082  } else {
2083  $this->error = $this->db->lasterror();
2084  $error++;
2085  }
2086 
2087  // If module stock is enabled and the stock increase is done on purchase order dispatching
2088  if (!$error && $entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) {
2089  $mouv = new MouvementStock($this->db);
2090  if ($product > 0) {
2091  // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on)
2092  $mouv->origin = &$this;
2093  $mouv->setOrigin($this->element, $this->id);
2094 
2095  // Method change if qty < 0
2096  if (!empty($conf->global->SUPPLIER_ORDER_ALLOW_NEGATIVE_QTY_FOR_SUPPLIER_ORDER_RETURN) && $qty < 0) {
2097  $result = $mouv->livraison($user, $product, $entrepot, $qty*(-1), $price, $comment, $now, $eatby, $sellby, $batch, 0, $inventorycode);
2098  } else {
2099  $result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch, '', 0, $inventorycode);
2100  }
2101 
2102  if ($result < 0) {
2103  $this->error = $mouv->error;
2104  $this->errors = $mouv->errors;
2105  dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',', $this->errors), LOG_ERR);
2106  $error++;
2107  }
2108  }
2109  }
2110 
2111  if ($error == 0) {
2112  $this->db->commit();
2113  return 1;
2114  } else {
2115  $this->db->rollback();
2116  return -1;
2117  }
2118  } else {
2119  $this->error = 'BadStatusForObject';
2120  return -2;
2121  }
2122  }
2123 
2131  public function deleteline($idline, $notrigger = 0)
2132  {
2133  if ($this->statut == 0) {
2134  $line = new CommandeFournisseurLigne($this->db);
2135 
2136  if ($line->fetch($idline) <= 0) {
2137  return 0;
2138  }
2139 
2140  if ($line->delete($notrigger) > 0) {
2141  $this->update_price();
2142  return 1;
2143  } else {
2144  $this->error = $line->error;
2145  $this->errors = $line->errors;
2146  return -1;
2147  }
2148  } else {
2149  return -2;
2150  }
2151  }
2152 
2160  public function delete(User $user, $notrigger = 0)
2161  {
2162  global $langs, $conf;
2163  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2164 
2165  $error = 0;
2166 
2167  $this->db->begin();
2168 
2169  if (empty($notrigger)) {
2170  // Call trigger
2171  $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user);
2172  if ($result < 0) {
2173  $this->errors[] = 'ErrorWhenRunningTrigger';
2174  dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2175  $this->db->rollback();
2176  return -1;
2177  }
2178  // End call triggers
2179  }
2180 
2181  // Test we can delete
2182  $this->fetchObjectLinked(null, 'order_supplier');
2183  if (!empty($this->linkedObjects) && array_key_exists('reception', $this->linkedObjects)) {
2184  foreach ($this->linkedObjects['reception'] as $element) {
2185  if ($element->statut >= 0) {
2186  $this->errors[] = $langs->trans('ReceptionExist');
2187  $error++;
2188  break;
2189  }
2190  }
2191  }
2192 
2193  $main = MAIN_DB_PREFIX.'commande_fournisseurdet';
2194  $ef = $main."_extrafields";
2195  $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_commande = ".((int) $this->id).")";
2196  dol_syslog(get_class($this)."::delete extrafields lines", LOG_DEBUG);
2197  if (!$this->db->query($sql)) {
2198  $this->error = $this->db->lasterror();
2199  $this->errors[] = $this->db->lasterror();
2200  $error++;
2201  }
2202 
2203  $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =".((int) $this->id);
2204  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2205  if (!$this->db->query($sql)) {
2206  $this->error = $this->db->lasterror();
2207  $this->errors[] = $this->db->lasterror();
2208  $error++;
2209  }
2210 
2211  $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".((int) $this->id);
2212  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
2213  if ($resql = $this->db->query($sql)) {
2214  if ($this->db->affected_rows($resql) < 1) {
2215  $this->error = $this->db->lasterror();
2216  $this->errors[] = $this->db->lasterror();
2217  $error++;
2218  }
2219  } else {
2220  $this->error = $this->db->lasterror();
2221  $this->errors[] = $this->db->lasterror();
2222  $error++;
2223  }
2224 
2225  // Remove extrafields
2226  if (!$error) {
2227  $result = $this->deleteExtraFields();
2228  if ($result < 0) {
2229  $this->error = 'FailToDeleteExtraFields';
2230  $this->errors[] = 'FailToDeleteExtraFields';
2231  $error++;
2232  dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
2233  }
2234  }
2235 
2236  // Delete linked object
2237  $res = $this->deleteObjectLinked();
2238  if ($res < 0) {
2239  $this->error = 'FailToDeleteObjectLinked';
2240  $this->errors[] = 'FailToDeleteObjectLinked';
2241  $error++;
2242  }
2243 
2244  if (!$error) {
2245  // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2246  $this->deleteEcmFiles();
2247 
2248  // We remove directory
2249  $ref = dol_sanitizeFileName($this->ref);
2250  if ($conf->fournisseur->commande->dir_output) {
2251  $dir = $conf->fournisseur->commande->dir_output."/".$ref;
2252  $file = $dir."/".$ref.".pdf";
2253  if (file_exists($file)) {
2254  if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2255  $this->error = 'ErrorFailToDeleteFile';
2256  $this->errors[] = 'ErrorFailToDeleteFile';
2257  $error++;
2258  }
2259  }
2260  if (file_exists($dir)) {
2261  $res = @dol_delete_dir_recursive($dir);
2262  if (!$res) {
2263  $this->error = 'ErrorFailToDeleteDir';
2264  $this->errors[] = 'ErrorFailToDeleteDir';
2265  $error++;
2266  }
2267  }
2268  }
2269  }
2270 
2271  if (!$error) {
2272  dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
2273  $this->db->commit();
2274  return 1;
2275  } else {
2276  dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
2277  $this->db->rollback();
2278  return -$error;
2279  }
2280  }
2281 
2282  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2288  public function get_methodes_commande()
2289  {
2290  // phpcs:enable
2291  $sql = "SELECT rowid, libelle";
2292  $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method";
2293  $sql .= " WHERE active = 1";
2294 
2295  $resql = $this->db->query($sql);
2296  if ($resql) {
2297  $i = 0;
2298  $num = $this->db->num_rows($resql);
2299  $this->methodes_commande = array();
2300  while ($i < $num) {
2301  $row = $this->db->fetch_row($resql);
2302 
2303  $this->methodes_commande[$row[0]] = $row[1];
2304 
2305  $i++;
2306  }
2307  return 0;
2308  } else {
2309  return -1;
2310  }
2311  }
2312 
2321  public function getDispachedLines($status = -1)
2322  {
2323  $ret = array();
2324 
2325  // List of already dispatched lines
2326  $sql = "SELECT p.ref, p.label,";
2327  $sql .= " e.rowid as warehouse_id, e.ref as entrepot,";
2328  $sql .= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status";
2329  $sql .= " FROM ".MAIN_DB_PREFIX."product as p,";
2330  $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd";
2331  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid";
2332  $sql .= " WHERE cfd.fk_commande = ".((int) $this->id);
2333  $sql .= " AND cfd.fk_product = p.rowid";
2334  if ($status >= 0) {
2335  $sql .= " AND cfd.status = ".((int) $status);
2336  }
2337  $sql .= " ORDER BY cfd.rowid ASC";
2338 
2339  $resql = $this->db->query($sql);
2340  if ($resql) {
2341  $num = $this->db->num_rows($resql);
2342  $i = 0;
2343 
2344  while ($i < $num) {
2345  $objp = $this->db->fetch_object($resql);
2346  if ($objp) {
2347  $ret[] = array(
2348  'id' => $objp->dispatchedlineid,
2349  'productid' => $objp->fk_product,
2350  'warehouseid' => $objp->warehouse_id,
2351  'qty' => $objp->qty,
2352  );
2353  }
2354 
2355  $i++;
2356  }
2357  } else {
2358  dol_print_error($this->db, 'Failed to execute request to get dispatched lines');
2359  }
2360 
2361  return $ret;
2362  }
2363 
2364  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2374  public function Livraison($user, $date, $type, $comment)
2375  {
2376  // phpcs:enable
2377  global $conf, $langs;
2378 
2379  $result = 0;
2380  $error = 0;
2381 
2382  dol_syslog(get_class($this)."::Livraison");
2383 
2384  $usercanreceive = 0;
2385  if (empty($conf->reception->enabled)) {
2386  $usercanreceive = $user->rights->fournisseur->commande->receptionner;
2387  } else {
2388  $usercanreceive = $user->rights->reception->creer;
2389  }
2390 
2391  if ($usercanreceive) {
2392  // Define the new status
2393  if ($type == 'par') {
2395  } elseif ($type == 'tot') {
2397  } elseif ($type == 'nev') {
2399  } elseif ($type == 'can') {
2401  } else {
2402  $error++;
2403  dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR);
2404  return -2;
2405  }
2406 
2407  // Some checks to accept the record
2408  if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
2409  // If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done"
2410  if (!$error && ($type == 'tot')) {
2411  $dispatchedlinearray = $this->getDispachedLines(0);
2412  if (count($dispatchedlinearray) > 0) {
2413  $result = -1;
2414  $error++;
2415  $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionToApprove';
2416  dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG);
2417  }
2418  }
2419  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)
2420  $dispatcheddenied = $this->getDispachedLines(2);
2421  if (count($dispatchedlinearray) > 0) {
2422  $result = -1;
2423  $error++;
2424  $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied';
2425  dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG);
2426  }
2427  }
2428  }
2429 
2430  // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
2431 
2432  if (empty($error)) {
2433  $this->db->begin();
2434 
2435  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2436  $sql .= " SET fk_statut = ".((int) $statut);
2437  $sql .= " WHERE rowid = ".((int) $this->id);
2438  $sql .= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received
2439 
2440  dol_syslog(get_class($this)."::Livraison", LOG_DEBUG);
2441  $resql = $this->db->query($sql);
2442  if ($resql) {
2443  $result = 1;
2444  $old_statut = $this->statut;
2445  $this->statut = $statut;
2446  $this->actionmsg2 = $comment;
2447 
2448  // Call trigger
2449  $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user);
2450  if ($result_trigger < 0) {
2451  $error++;
2452  }
2453  // End call triggers
2454 
2455  if (empty($error)) {
2456  $this->db->commit();
2457  } else {
2458  $this->statut = $old_statut;
2459  $this->db->rollback();
2460  $this->error = $this->db->lasterror();
2461  $result = -1;
2462  }
2463  } else {
2464  $this->db->rollback();
2465  $this->error = $this->db->lasterror();
2466  $result = -1;
2467  }
2468  }
2469  } else {
2470  $this->error = $langs->trans('NotAuthorized');
2471  $this->errors[] = $langs->trans('NotAuthorized');
2472  dol_syslog(get_class($this)."::Livraison Not Authorized");
2473  $result = -3;
2474  }
2475  return $result;
2476  }
2477 
2478  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2488  public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2489  {
2490  // phpcs:enable
2491  return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2492  }
2493 
2502  public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2503  {
2504  if ($user->rights->fournisseur->commande->creer || $user->rights->supplier_order->creer) {
2505  $error = 0;
2506 
2507  $this->db->begin();
2508 
2509  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2510  $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2511  $sql .= " WHERE rowid = ".((int) $this->id);
2512 
2513  dol_syslog(__METHOD__, LOG_DEBUG);
2514  $resql = $this->db->query($sql);
2515  if (!$resql) {
2516  $this->errors[] = $this->db->error();
2517  $error++;
2518  }
2519 
2520  if (!$error) {
2521  $this->oldcopy = clone $this;
2522  $this->date_livraison = $delivery_date;
2523  $this->delivery_date = $delivery_date;
2524  }
2525 
2526  if (!$notrigger && empty($error)) {
2527  // Call trigger
2528  $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2529  if ($result < 0) {
2530  $error++;
2531  }
2532  // End call triggers
2533  }
2534 
2535  if (!$error) {
2536  $this->db->commit();
2537  return 1;
2538  } else {
2539  foreach ($this->errors as $errmsg) {
2540  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2541  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2542  }
2543  $this->db->rollback();
2544  return -1 * $error;
2545  }
2546  } else {
2547  return -2;
2548  }
2549  }
2550 
2551  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2560  public function set_id_projet($user, $id_projet, $notrigger = 0)
2561  {
2562  // phpcs:enable
2563  if ($user->rights->fournisseur->commande->creer || $user->rights->supplier_order->creer) {
2564  $error = 0;
2565 
2566  $this->db->begin();
2567 
2568  $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
2569  $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null');
2570  $sql .= " WHERE rowid = ".((int) $this->id);
2571 
2572  dol_syslog(__METHOD__, LOG_DEBUG);
2573  $resql = $this->db->query($sql);
2574  if (!$resql) {
2575  $this->errors[] = $this->db->error();
2576  $error++;
2577  }
2578 
2579  if (!$error) {
2580  $this->oldcopy = clone $this;
2581  $this->fk_projet = $id_projet;
2582  $this->fk_project = $id_projet;
2583  }
2584 
2585  if (!$notrigger && empty($error)) {
2586  // Call trigger
2587  $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user);
2588  if ($result < 0) {
2589  $error++;
2590  }
2591  // End call triggers
2592  }
2593 
2594  if (!$error) {
2595  $this->db->commit();
2596  return 1;
2597  } else {
2598  foreach ($this->errors as $errmsg) {
2599  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2600  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2601  }
2602  $this->db->rollback();
2603  return -1 * $error;
2604  }
2605  } else {
2606  return -2;
2607  }
2608  }
2609 
2618  public function updateFromCommandeClient($user, $idc, $comclientid)
2619  {
2620  $comclient = new Commande($this->db);
2621  $comclient->fetch($comclientid);
2622 
2623  $this->id = $idc;
2624 
2625  $this->lines = array();
2626 
2627  $num = count($comclient->lines);
2628  for ($i = 0; $i < $num; $i++) {
2629  $prod = new Product($this->db);
2630  $label = '';
2631  $ref = '';
2632  if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) {
2633  $label = $prod->label;
2634  $ref = $prod->ref;
2635  }
2636 
2637  $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet";
2638  $sql .= " (fk_commande, label, description, fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
2639  $sql .= " VALUES (".((int) $idc).", '".$this->db->escape($label)."', '".$this->db->escape($comclient->lines[$i]->desc)."'";
2640  $sql .= ",".$comclient->lines[$i]->fk_product.", ".price2num($comclient->lines[$i]->price, 'MU');
2641  $sql .= ", ".price2num($comclient->lines[$i]->qty, 'MS').", ".price2num($comclient->lines[$i]->tva_tx, 5).", ".price2num($comclient->lines[$i]->localtax1_tx, 5).", ".price2num($comclient->lines[$i]->localtax2_tx, 5).", ".price2num($comclient->lines[$i]->remise_percent, 3);
2642  $sql .= ", '".price2num($comclient->lines[$i]->subprice, 'MT')."','0', '".$this->db->escape($ref)."');";
2643  if ($this->db->query($sql)) {
2644  $this->update_price();
2645  }
2646  }
2647 
2648  return 1;
2649  }
2650 
2658  public function setStatus($user, $status)
2659  {
2660  global $conf, $langs;
2661  $error = 0;
2662 
2663  $this->db->begin();
2664 
2665  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
2666  $sql .= " SET fk_statut = ".$status;
2667  $sql .= " WHERE rowid = ".((int) $this->id);
2668 
2669  dol_syslog(get_class($this)."::setStatus", LOG_DEBUG);
2670  $resql = $this->db->query($sql);
2671  if ($resql) {
2672  // Trigger names for each status
2673  $triggerName = array();
2674  $triggerName[0] = 'DRAFT';
2675  $triggerName[1] = 'VALIDATED';
2676  $triggerName[2] = 'APPROVED';
2677  $triggerName[3] = 'ORDERED'; // Ordered
2678  $triggerName[4] = 'RECEIVED_PARTIALLY';
2679  $triggerName[5] = 'RECEIVED_COMPLETELY';
2680  $triggerName[6] = 'CANCELED';
2681  $triggerName[7] = 'CANCELED';
2682  $triggerName[9] = 'REFUSED';
2683 
2684  // Call trigger
2685  $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user);
2686  if ($result < 0) {
2687  $error++;
2688  }
2689  // End call triggers
2690  } else {
2691  $error++;
2692  $this->error = $this->db->lasterror();
2693  dol_syslog(get_class($this)."::setStatus ".$this->error);
2694  }
2695 
2696  if (!$error) {
2697  $this->statut = $status;
2698  $this->db->commit();
2699  return 1;
2700  } else {
2701  $this->db->rollback();
2702  return -1;
2703  }
2704  }
2705 
2729  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 = '')
2730  {
2731  global $mysoc, $conf, $langs;
2732  dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit");
2733  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2734 
2735  $error = 0;
2736 
2737  if ($this->brouillon) {
2738  // Clean parameters
2739  if (empty($qty)) {
2740  $qty = 0;
2741  }
2742  if (empty($info_bits)) {
2743  $info_bits = 0;
2744  }
2745  if (empty($txtva)) {
2746  $txtva = 0;
2747  }
2748  if (empty($txlocaltax1)) {
2749  $txlocaltax1 = 0;
2750  }
2751  if (empty($txlocaltax2)) {
2752  $txlocaltax2 = 0;
2753  }
2754  if (empty($remise)) {
2755  $remise = 0;
2756  }
2757  if (empty($remise_percent)) {
2758  $remise_percent = 0;
2759  }
2760 
2761  $remise_percent = price2num($remise_percent);
2762  $qty = price2num($qty);
2763  if (!$qty) {
2764  $qty = 1;
2765  }
2766  $pu = price2num($pu);
2767  $pu_ht_devise = price2num($pu_ht_devise);
2768  if (!preg_match('/\((.*)\)/', $txtva)) {
2769  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
2770  }
2771  $txlocaltax1 = price2num($txlocaltax1);
2772  $txlocaltax2 = price2num($txlocaltax2);
2773 
2774  // Check parameters
2775  if ($type < 0) {
2776  return -1;
2777  }
2778  if ($date_start && $date_end && $date_start > $date_end) {
2779  $langs->load("errors");
2780  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
2781  return -1;
2782  }
2783 
2784  $this->db->begin();
2785 
2786  // Calcul du total TTC et de la TVA pour la ligne a partir de
2787  // qty, pu, remise_percent et txtva
2788  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2789  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2790 
2791  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
2792 
2793  // Clean vat code
2794  $reg = array();
2795  $vat_src_code = '';
2796  if (preg_match('/\((.*)\)/', $txtva, $reg)) {
2797  $vat_src_code = $reg[1];
2798  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
2799  }
2800 
2801  $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);
2802  $total_ht = $tabprice[0];
2803  $total_tva = $tabprice[1];
2804  $total_ttc = $tabprice[2];
2805  $total_localtax1 = $tabprice[9];
2806  $total_localtax2 = $tabprice[10];
2807  $pu_ht = $tabprice[3];
2808  $pu_tva = $tabprice[4];
2809  $pu_ttc = $tabprice[5];
2810 
2811  // MultiCurrency
2812  $multicurrency_total_ht = $tabprice[16];
2813  $multicurrency_total_tva = $tabprice[17];
2814  $multicurrency_total_ttc = $tabprice[18];
2815  $pu_ht_devise = $tabprice[19];
2816 
2817  $localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
2818  $localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
2819 
2820  //Fetch current line from the database and then clone the object and set it in $oldline property
2821  $this->line = new CommandeFournisseurLigne($this->db);
2822  $this->line->fetch($rowid);
2823 
2824  $oldline = clone $this->line;
2825  $this->line->oldline = $oldline;
2826 
2827  $this->line->context = $this->context;
2828 
2829  $this->line->fk_commande = $this->id;
2830  //$this->line->label=$label;
2831  $this->line->desc = $desc;
2832 
2833  // redefine quantity according to packaging
2834  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
2835  if ($qty < $this->line->packaging) {
2836  $qty = $this->line->packaging;
2837  } else {
2838  if (! empty($this->line->packaging) && ($qty % $this->line->packaging) > 0) {
2839  $coeff = intval($qty / $this->line->packaging) + 1;
2840  $qty = $this->line->packaging * $coeff;
2841  setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs');
2842  }
2843  }
2844  }
2845 
2846  $this->line->qty = $qty;
2847  $this->line->ref_supplier = $ref_supplier;
2848 
2849  $this->line->vat_src_code = $vat_src_code;
2850  $this->line->tva_tx = $txtva;
2851  $this->line->localtax1_tx = $txlocaltax1;
2852  $this->line->localtax2_tx = $txlocaltax2;
2853  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
2854  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
2855  $this->line->remise_percent = $remise_percent;
2856  $this->line->subprice = $pu_ht;
2857  $this->line->rang = $oldline->rang;
2858  $this->line->info_bits = $info_bits;
2859  $this->line->total_ht = $total_ht;
2860  $this->line->total_tva = $total_tva;
2861  $this->line->total_localtax1 = $total_localtax1;
2862  $this->line->total_localtax2 = $total_localtax2;
2863  $this->line->total_ttc = $total_ttc;
2864  $this->line->product_type = $type;
2865  $this->line->special_code = $oldline->special_code;
2866  $this->line->origin = $this->origin;
2867  $this->line->fk_unit = $fk_unit;
2868 
2869  $this->line->date_start = $date_start;
2870  $this->line->date_end = $date_end;
2871 
2872  // Multicurrency
2873  $this->line->fk_multicurrency = $this->fk_multicurrency;
2874  $this->line->multicurrency_code = $this->multicurrency_code;
2875  $this->line->multicurrency_subprice = $pu_ht_devise;
2876  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
2877  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
2878  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
2879 
2880  $this->line->subprice = $pu_ht;
2881  $this->line->price = $this->line->subprice;
2882 
2883  $this->line->remise_percent = $remise_percent;
2884 
2885  if (is_array($array_options) && count($array_options) > 0) {
2886  // We replace values in this->line->array_options only for entries defined into $array_options
2887  foreach ($array_options as $key => $value) {
2888  $this->line->array_options[$key] = $array_options[$key];
2889  }
2890  }
2891 
2892  $result = $this->line->update($notrigger);
2893 
2894 
2895  // Mise a jour info denormalisees au niveau facture
2896  if ($result >= 0) {
2897  $this->update_price('', 'auto');
2898  $this->db->commit();
2899  return $result;
2900  } else {
2901  $this->error = $this->db->lasterror();
2902  $this->db->rollback();
2903  return -1;
2904  }
2905  } else {
2906  $this->error = "Order status makes operation forbidden";
2907  dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR);
2908  return -2;
2909  }
2910  }
2911 
2912 
2920  public function initAsSpecimen()
2921  {
2922  global $user, $langs, $conf;
2923 
2924  include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
2925 
2926  dol_syslog(get_class($this)."::initAsSpecimen");
2927 
2928  $now = dol_now();
2929 
2930  // Find first product
2931  $prodid = 0;
2932  $product = new ProductFournisseur($this->db);
2933  $sql = "SELECT rowid";
2934  $sql .= " FROM ".MAIN_DB_PREFIX."product";
2935  $sql .= " WHERE entity IN (".getEntity('product').")";
2936  $sql .= $this->db->order("rowid", "ASC");
2937  $sql .= $this->db->plimit(1);
2938  $resql = $this->db->query($sql);
2939  if ($resql) {
2940  $obj = $this->db->fetch_object($resql);
2941  $prodid = $obj->rowid;
2942  }
2943 
2944  // Initialise parametres
2945  $this->id = 0;
2946  $this->ref = 'SPECIMEN';
2947  $this->specimen = 1;
2948  $this->socid = 1;
2949  $this->date = $now;
2950  $this->date_commande = $now;
2951  $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
2952  $this->cond_reglement_code = 'RECEP';
2953  $this->mode_reglement_code = 'CHQ';
2954 
2955  $this->note_public = 'This is a comment (public)';
2956  $this->note_private = 'This is a comment (private)';
2957 
2958  $this->multicurrency_tx = 1;
2959  $this->multicurrency_code = $conf->currency;
2960 
2961  $this->statut = 0;
2962 
2963  // Lines
2964  $nbp = 5;
2965  $xnbp = 0;
2966  while ($xnbp < $nbp) {
2967  $line = new CommandeFournisseurLigne($this->db);
2968  $line->desc = $langs->trans("Description")." ".$xnbp;
2969  $line->qty = 1;
2970  $line->subprice = 100;
2971  $line->price = 100;
2972  $line->tva_tx = 19.6;
2973  $line->localtax1_tx = 0;
2974  $line->localtax2_tx = 0;
2975  if ($xnbp == 2) {
2976  $line->total_ht = 50;
2977  $line->total_ttc = 59.8;
2978  $line->total_tva = 9.8;
2979  $line->remise_percent = 50;
2980  } else {
2981  $line->total_ht = 100;
2982  $line->total_ttc = 119.6;
2983  $line->total_tva = 19.6;
2984  $line->remise_percent = 00;
2985  }
2986  $line->fk_product = $prodid;
2987 
2988  $this->lines[$xnbp] = $line;
2989 
2990  $this->total_ht += $line->total_ht;
2991  $this->total_tva += $line->total_tva;
2992  $this->total_ttc += $line->total_ttc;
2993 
2994  $xnbp++;
2995  }
2996  }
2997 
3004  public function info($id)
3005  {
3006  $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,';
3007  $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2';
3008  $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c';
3009  $sql .= ' WHERE c.rowid = '.((int) $id);
3010 
3011  $result = $this->db->query($sql);
3012  if ($result) {
3013  if ($this->db->num_rows($result)) {
3014  $obj = $this->db->fetch_object($result);
3015  $this->id = $obj->rowid;
3016  if ($obj->fk_user_author) {
3017  $this->user_creation_id = $obj->fk_user_author;
3018  }
3019  if ($obj->fk_user_valid) {
3020  $this->user_validation_id = $obj->fk_user_valid;
3021  }
3022  if ($obj->fk_user_modif) {
3023  $this->user_modification_id = $obj->fk_user_modif;
3024  }
3025  if ($obj->fk_user_approve) {
3026  $this->user_approve_id = $obj->fk_user_approve;
3027  }
3028  if ($obj->fk_user_approve2) {
3029  $this->user_approve_id2 = $obj->fk_user_approve2;
3030  }
3031 
3032  $this->date_creation = $this->db->jdate($obj->datec);
3033  $this->date_modification = $this->db->jdate($obj->datem);
3034  $this->date_approve = $this->db->jdate($obj->datea);
3035  $this->date_approve2 = $this->db->jdate($obj->datea2);
3036  $this->date_validation = $this->db->jdate($obj->date_validation);
3037  }
3038  $this->db->free($result);
3039  } else {
3040  dol_print_error($this->db);
3041  }
3042  }
3043 
3044  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3050  public function load_state_board()
3051  {
3052  // phpcs:enable
3053  global $conf, $user;
3054 
3055  $this->nb = array();
3056  $clause = "WHERE";
3057 
3058  $sql = "SELECT count(co.rowid) as nb";
3059  $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
3060  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
3061  if (empty($user->rights->societe->client->voir) && !$user->socid) {
3062  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3063  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3064  $clause = "AND";
3065  }
3066  $sql .= " ".$clause." co.entity IN (".getEntity('supplier_order').")";
3067 
3068  $resql = $this->db->query($sql);
3069  if ($resql) {
3070  while ($obj = $this->db->fetch_object($resql)) {
3071  $this->nb["supplier_orders"] = $obj->nb;
3072  }
3073  $this->db->free($resql);
3074  return 1;
3075  } else {
3076  dol_print_error($this->db);
3077  $this->error = $this->db->error();
3078  return -1;
3079  }
3080  }
3081 
3082  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3090  public function load_board($user, $mode = 'opened')
3091  {
3092  // phpcs:enable
3093  global $conf, $langs;
3094 
3095  $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date, c.total_ht";
3096  $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
3097  if (empty($user->rights->societe->client->voir) && !$user->socid) {
3098  $sql .= " JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
3099  }
3100  $sql .= " WHERE c.entity = ".$conf->entity;
3101  if ($mode === 'awaiting') {
3102  $sql .= " AND c.fk_statut IN (".self::STATUS_ORDERSENT.", ".self::STATUS_RECEIVED_PARTIALLY.")";
3103  } else {
3104  $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")";
3105  }
3106  if ($user->socid) {
3107  $sql .= " AND c.fk_soc = ".((int) $user->socid);
3108  }
3109 
3110  $resql = $this->db->query($sql);
3111  if ($resql) {
3112  $commandestatic = new CommandeFournisseur($this->db);
3113 
3114  $response = new WorkboardResponse();
3115  $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24;
3116  $response->label = $langs->trans("SuppliersOrdersToProcess");
3117  $response->labelShort = $langs->trans("Opened");
3118  $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=1,2&mainmenu=commercial&leftmenu=orders_suppliers';
3119  $response->img = img_object('', "order");
3120 
3121  if ($mode === 'awaiting') {
3122  $response->label = $langs->trans("SuppliersOrdersAwaitingReception");
3123  $response->labelShort = $langs->trans("AwaitingReception");
3124  $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?search_status=3,4&mainmenu=commercial&leftmenu=orders_suppliers';
3125  }
3126 
3127  while ($obj = $this->db->fetch_object($resql)) {
3128  $commandestatic->delivery_date = $this->db->jdate($obj->delivery_date);
3129  $commandestatic->date_commande = $this->db->jdate($obj->date_commande);
3130  $commandestatic->statut = $obj->fk_statut;
3131 
3132  $response->nbtodo++;
3133  $response->total += $obj->total_ht;
3134 
3135  if ($commandestatic->hasDelay()) {
3136  $response->nbtodolate++;
3137  }
3138  }
3139 
3140  return $response;
3141  } else {
3142  $this->error = $this->db->error();
3143  return -1;
3144  }
3145  }
3146 
3153  public function getInputMethod()
3154  {
3155  global $db, $langs;
3156 
3157  if ($this->methode_commande_id > 0) {
3158  $sql = "SELECT rowid, code, libelle as label";
3159  $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_method';
3160  $sql .= " WHERE active=1 AND rowid = ".((int) $this->methode_commande_id);
3161 
3162  $resql = $this->db->query($sql);
3163  if ($resql) {
3164  if ($this->db->num_rows($resql)) {
3165  $obj = $this->db->fetch_object($resql);
3166 
3167  $string = $langs->trans($obj->code);
3168  if ($string == $obj->code) {
3169  $string = $obj->label != '-' ? $obj->label : '';
3170  }
3171  return $string;
3172  }
3173  } else {
3174  dol_print_error($this->db);
3175  }
3176  }
3177 
3178  return '';
3179  }
3180 
3192  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3193  {
3194  global $conf, $langs;
3195 
3196  $langs->load("suppliers");
3197  $outputlangs->load("products");
3198 
3199  if (!dol_strlen($modele)) {
3200  $modele = '';
3201  if ($this->model_pdf) {
3202  $modele = $this->model_pdf;
3203  } elseif (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) {
3204  $modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF;
3205  }
3206  }
3207  if (empty($modele)) {
3208  return 0;
3209  } else {
3210  $modelpath = "core/modules/supplier_order/doc/";
3211  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3212  }
3213  }
3214 
3221  public function getMaxDeliveryTimeDay($langs)
3222  {
3223  if (empty($this->lines)) {
3224  return '';
3225  }
3226 
3227  $obj = new ProductFournisseur($this->db);
3228 
3229  $nb = 0;
3230  foreach ($this->lines as $line) {
3231  if ($line->fk_product > 0) {
3232  $idp = $obj->find_min_price_product_fournisseur($line->fk_product, $line->qty);
3233  if ($idp) {
3234  $obj->fetch($idp);
3235  if ($obj->delivery_time_days > $nb) {
3236  $nb = $obj->delivery_time_days;
3237  }
3238  }
3239  }
3240  }
3241 
3242  if ($nb === 0) {
3243  return '';
3244  } else {
3245  return $nb.' '.$langs->trans('Days');
3246  }
3247  }
3248 
3253  public function getRights()
3254  {
3255  global $user;
3256 
3257  return $user->rights->fournisseur->commande;
3258  }
3259 
3260 
3269  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
3270  {
3271  $tables = array(
3272  'commande_fournisseur'
3273  );
3274 
3275  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3276  }
3277 
3286  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
3287  {
3288  $tables = array(
3289  'commande_fournisseurdet'
3290  );
3291 
3292  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
3293  }
3294 
3302  public function hasDelay()
3303  {
3304  global $conf;
3305 
3306  if (empty($this->delivery_date) && !empty($this->date_livraison)) {
3307  $this->delivery_date = $this->date_livraison; // For backward compatibility
3308  }
3309 
3310  if ($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY) {
3311  $now = dol_now();
3312  if (!empty($this->delivery_date)) {
3313  $date_to_test = $this->delivery_date;
3314  return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3315  } else {
3316  //$date_to_test = $this->date_commande;
3317  //return $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3318  return false;
3319  }
3320  } else {
3321  $now = dol_now();
3322  $date_to_test = $this->date_commande;
3323 
3324  return ($this->statut > 0 && $this->statut < 5) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay);
3325  }
3326  }
3327 
3335  public function showDelay()
3336  {
3337  global $conf, $langs;
3338 
3339  if (empty($this->delivery_date) && !empty($this->date_livraison)) {
3340  $this->delivery_date = $this->date_livraison; // For backward compatibility
3341  }
3342 
3343  $text = '';
3344 
3345  if ($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY) {
3346  if (!empty($this->delivery_date)) {
3347  $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
3348  } else {
3349  $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3350  }
3351  } else {
3352  $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day');
3353  }
3354  if ($text) {
3355  $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
3356  }
3357 
3358  return $text;
3359  }
3360 
3361 
3370  public function calcAndSetStatusDispatch(User $user, $closeopenorder = 1, $comment = '')
3371  {
3372  global $conf, $langs;
3373 
3374  if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled)) {
3375  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
3376 
3377  $qtydelivered = array();
3378  $qtywished = array();
3379 
3380  $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
3381  $filter = array('t.fk_commande'=>$this->id);
3382  if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
3383  $filter['t.status'] = 1; // Restrict to lines with status validated
3384  }
3385 
3386  $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
3387  if ($ret < 0) {
3388  $this->error = $supplierorderdispatch->error; $this->errors = $supplierorderdispatch->errors;
3389  return $ret;
3390  } else {
3391  if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0) {
3392  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3393  $date_liv = dol_now();
3394 
3395  // Build array with quantity deliverd by product
3396  foreach ($supplierorderdispatch->lines as $line) {
3397  $qtydelivered[$line->fk_product] += $line->qty;
3398  }
3399  foreach ($this->lines as $line) {
3400  // Exclude lines not qualified for shipment, similar code is found into interface_20_modWrokflow for customers
3401  if (empty($conf->global->STOCK_SUPPORTS_SERVICES) && $line->product_type > 0) {
3402  continue;
3403  }
3404  $qtywished[$line->fk_product] += $line->qty;
3405  }
3406 
3407  //Compare array
3408  $diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys.
3409  $keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys
3410  $keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys
3411  //var_dump(array_keys($qtydelivered));
3412  //var_dump(array_keys($qtywished));
3413  //var_dump($diff_array);
3414  //var_dump($keysinwishednotindelivered);
3415  //var_dump($keysindeliverednotinwished);
3416  //exit;
3417 
3418  if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) { //No diff => mean everythings is received
3419  if ($closeopenorder) {
3420  //$ret=$this->setStatus($user,5);
3421  $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3422  if ($ret < 0) {
3423  return -1;
3424  }
3425  return 5;
3426  } else {
3427  //Diff => received partially
3428  //$ret=$this->setStatus($user,4);
3429  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3430  if ($ret < 0) {
3431  return -1;
3432  }
3433  return 4;
3434  }
3435  } elseif (!empty($conf->global->SUPPLIER_ORDER_MORE_THAN_WISHED)) {
3436  //set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...)
3437 
3438  $close = 0;
3439 
3440  if (count($diff_array) > 0) {
3441  //there are some difference between the two arrays
3442 
3443  //scan the array of results
3444  foreach ($diff_array as $key => $value) {
3445  //if the quantity delivered is greater or equal to wish quantity
3446  if ($qtydelivered[$key] >= $qtywished[$key]) {
3447  $close++;
3448  }
3449  }
3450  }
3451 
3452 
3453  if ($close == count($diff_array)) {
3454  //all the products are received equal or more than the wished quantity
3455  if ($closeopenorder) {
3456  $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3457  if ($ret < 0) {
3458  return -1;
3459  }
3460  return 5;
3461  } else {
3462  //Diff => received partially
3463  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3464  if ($ret < 0) {
3465  return -1;
3466  }
3467  return 4;
3468  }
3469  } else {
3470  //all the products are not received
3471  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3472  if ($ret < 0) {
3473  return -1;
3474  }
3475  return 4;
3476  }
3477  } else {
3478  //Diff => received partially
3479  $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
3480  if ($ret < 0) {
3481  return -1;
3482  }
3483  return 4;
3484  }
3485  }
3486  return 1;
3487  }
3488  }
3489  return 0;
3490  }
3491 
3499  public function loadReceptions($filtre_statut = -1)
3500  {
3501  $this->receptions = array();
3502 
3503  dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG);
3504 
3505  $sql = 'SELECT cd.rowid, cd.fk_product,';
3506  $sql .= ' sum(cfd.qty) as qty';
3507  $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur_dispatch as cfd,';
3508  if ($filtre_statut >= 0) {
3509  $sql .= ' '.MAIN_DB_PREFIX.'reception as e,';
3510  }
3511  $sql .= ' '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd';
3512  $sql .= ' WHERE';
3513  if ($filtre_statut >= 0) {
3514  $sql .= ' cfd.fk_reception = e.rowid AND';
3515  }
3516  $sql .= ' cfd.fk_commandefourndet = cd.rowid';
3517  $sql .= ' AND cd.fk_commande ='.((int) $this->id);
3518  if ($this->fk_product > 0) {
3519  $sql .= ' AND cd.fk_product = '.((int) $this->fk_product);
3520  }
3521  if ($filtre_statut >= 0) {
3522  $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
3523  }
3524  $sql .= ' GROUP BY cd.rowid, cd.fk_product';
3525 
3526  $resql = $this->db->query($sql);
3527  if ($resql) {
3528  $num = $this->db->num_rows($resql);
3529  $i = 0;
3530  while ($i < $num) {
3531  $obj = $this->db->fetch_object($resql);
3532  empty($this->receptions[$obj->rowid]) ? $this->receptions[$obj->rowid] = $obj->qty : $this->receptions[$obj->rowid] += $obj->qty;
3533  $i++;
3534  }
3535  $this->db->free($resql);
3536 
3537  return $num;
3538  } else {
3539  $this->error = $this->db->lasterror();
3540  return -1;
3541  }
3542  }
3543 }
3544 
3545 
3546 
3551 {
3555  public $element = 'commande_fournisseurdet';
3556 
3560  public $table_element = 'commande_fournisseurdet';
3561 
3562  public $oldline;
3563 
3568  public $fk_commande;
3569 
3570  // From llx_commande_fournisseurdet
3574  public $fk_parent_line;
3575 
3579  public $fk_facture;
3580 
3581  public $rang = 0;
3582  public $special_code = 0;
3583 
3588  public $pu_ht;
3589 
3590  public $date_start;
3591  public $date_end;
3592 
3593  // From llx_product_fournisseur_price
3594 
3599  public $ref_supplier;
3600  public $remise;
3601 
3602 
3608  public function __construct($db)
3609  {
3610  $this->db = $db;
3611  }
3612 
3619  public function fetch($rowid)
3620  {
3621  global $conf;
3622 
3623  $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx, cd.special_code,';
3624  $sql .= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref as ref_supplier,';
3625  $sql .= ' cd.remise, cd.remise_percent, cd.subprice,';
3626  $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,';
3627  $sql .= ' cd.total_localtax1, cd.total_localtax2,';
3628  $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,';
3629  $sql .= ' cd.date_start, cd.date_end, cd.fk_unit,';
3630  $sql .= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,';
3631  $sql .= ' c.fk_soc as socid';
3632  $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c, '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd';
3633  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
3634  $sql .= ' WHERE cd.fk_commande = c.rowid AND cd.rowid = '.((int) $rowid);
3635 
3636  $result = $this->db->query($sql);
3637  if ($result) {
3638  $objp = $this->db->fetch_object($result);
3639 
3640  if (!empty($objp)) {
3641  $this->rowid = $objp->rowid;
3642  $this->id = $objp->rowid;
3643  $this->fk_commande = $objp->fk_commande;
3644  $this->desc = $objp->description;
3645  $this->qty = $objp->qty;
3646  $this->ref_fourn = $objp->ref_supplier;
3647  $this->ref_supplier = $objp->ref_supplier;
3648  $this->subprice = $objp->subprice;
3649  $this->tva_tx = $objp->tva_tx;
3650  $this->localtax1_tx = $objp->localtax1_tx;
3651  $this->localtax2_tx = $objp->localtax2_tx;
3652  $this->localtax1_type = $objp->localtax1_type;
3653  $this->localtax2_type = $objp->localtax2_type;
3654  $this->remise = $objp->remise;
3655  $this->remise_percent = $objp->remise_percent;
3656  $this->fk_product = $objp->fk_product;
3657  $this->info_bits = $objp->info_bits;
3658  $this->total_ht = $objp->total_ht;
3659  $this->total_tva = $objp->total_tva;
3660  $this->total_localtax1 = $objp->total_localtax1;
3661  $this->total_localtax2 = $objp->total_localtax2;
3662  $this->total_ttc = $objp->total_ttc;
3663  $this->product_type = $objp->product_type;
3664  $this->special_code = $objp->special_code;
3665 
3666  $this->ref = $objp->product_ref;
3667 
3668  $this->product_ref = $objp->product_ref;
3669  $this->product_label = $objp->product_label;
3670  $this->product_desc = $objp->product_desc;
3671 
3672  if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
3673  // TODO We should not fetch this properties into the fetch_lines. This is NOT properties of a line.
3674  // Move this into another method and call it when required.
3675 
3676  // Take better packaging for $objp->qty (first supplier ref quantity <= $objp->qty)
3677  $sqlsearchpackage = 'SELECT rowid, packaging FROM '.MAIN_DB_PREFIX."product_fournisseur_price";
3678  $sqlsearchpackage .= ' WHERE entity IN ('.getEntity('product_fournisseur_price').")";
3679  $sqlsearchpackage .= " AND fk_product = ".((int) $objp->fk_product);
3680  $sqlsearchpackage .= " AND ref_fourn = '".$this->db->escape($objp->ref_supplier)."'";
3681  $sqlsearchpackage .= " AND quantity <= ".((float) $objp->qty); // required to be qualified
3682  $sqlsearchpackage .= " AND (packaging IS NULL OR packaging = 0 OR packaging <= ".((float) $objp->qty).")"; // required to be qualified
3683  $sqlsearchpackage .= " AND fk_soc = ".((int) $objp->socid);
3684  $sqlsearchpackage .= " ORDER BY packaging ASC"; // Take the smaller package first
3685  $sqlsearchpackage .= " LIMIT 1";
3686 
3687  $resqlsearchpackage = $this->db->query($sqlsearchpackage);
3688  if ($resqlsearchpackage) {
3689  $objsearchpackage = $this->db->fetch_object($resqlsearchpackage);
3690  if ($objsearchpackage) {
3691  $this->fk_fournprice = $objsearchpackage->rowid;
3692  $this->packaging = $objsearchpackage->packaging;
3693  }
3694  } else {
3695  $this->error = $this->db->lasterror();
3696  return -1;
3697  }
3698  }
3699 
3700  $this->date_start = $this->db->jdate($objp->date_start);
3701  $this->date_end = $this->db->jdate($objp->date_end);
3702  $this->fk_unit = $objp->fk_unit;
3703 
3704  $this->multicurrency_subprice = $objp->multicurrency_subprice;
3705  $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
3706  $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
3707  $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
3708 
3709  $this->fetch_optionals();
3710 
3711  $this->db->free($result);
3712  return 1;
3713  } else {
3714  $this->error = 'Supplier order line with id='.$rowid.' not found';
3715  dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR);
3716  return 0;
3717  }
3718  } else {
3719  dol_print_error($this->db);
3720  return -1;
3721  }
3722  }
3723 
3730  public function insert($notrigger = 0)
3731  {
3732  global $conf, $user;
3733 
3734  $error = 0;
3735 
3736  dol_syslog(get_class($this)."::insert rang=".$this->rang);
3737 
3738  // Clean parameters
3739  if (empty($this->tva_tx)) {
3740  $this->tva_tx = 0;
3741  }
3742  if (empty($this->localtax1_tx)) {
3743  $this->localtax1_tx = 0;
3744  }
3745  if (empty($this->localtax2_tx)) {
3746  $this->localtax2_tx = 0;
3747  }
3748  if (empty($this->localtax1_type)) {
3749  $this->localtax1_type = '0';
3750  }
3751  if (empty($this->localtax2_type)) {
3752  $this->localtax2_type = '0';
3753  }
3754  if (empty($this->total_localtax1)) {
3755  $this->total_localtax1 = 0;
3756  }
3757  if (empty($this->total_localtax2)) {
3758  $this->total_localtax2 = 0;
3759  }
3760  if (empty($this->rang)) {
3761  $this->rang = 0;
3762  }
3763  if (empty($this->remise_percent)) {
3764  $this->remise_percent = 0;
3765  }
3766  if (empty($this->info_bits)) {
3767  $this->info_bits = 0;
3768  }
3769  if (empty($this->special_code)) {
3770  $this->special_code = 0;
3771  }
3772  if (empty($this->fk_parent_line)) {
3773  $this->fk_parent_line = 0;
3774  }
3775  if (empty($this->pa_ht)) {
3776  $this->pa_ht = 0;
3777  }
3778 
3779  // Multicurrency
3780  if (!empty($this->multicurrency_code)) {
3781  list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
3782  }
3783  if (empty($this->fk_multicurrency)) {
3784  $this->multicurrency_code = $conf->currency;
3785  $this->fk_multicurrency = 0;
3786  $this->multicurrency_tx = 1;
3787  }
3788 
3789  // Check parameters
3790  if ($this->product_type < 0) {
3791  return -1;
3792  }
3793 
3794  $this->db->begin();
3795 
3796  // Insertion dans base de la ligne
3797  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
3798  $sql .= " (fk_commande, label, description, date_start, date_end,";
3799  $sql .= " fk_product, product_type, special_code, rang,";
3800  $sql .= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,";
3801  $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,";
3802  $sql .= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc";
3803  $sql .= ")";
3804  $sql .= " VALUES (".$this->fk_commande.", '".$this->db->escape($this->label)."','".$this->db->escape($this->desc)."',";
3805  $sql .= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3806  $sql .= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3807  if ($this->fk_product) {
3808  $sql .= $this->fk_product.",";
3809  } else {
3810  $sql .= "null,";
3811  }
3812  $sql .= "'".$this->db->escape($this->product_type)."',";
3813  $sql .= "'".$this->db->escape($this->special_code)."',";
3814  $sql .= "'".$this->db->escape($this->rang)."',";
3815  $sql .= "'".$this->db->escape($this->qty)."', ";
3816  $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
3817  $sql .= " ".price2num($this->tva_tx).", ";
3818  $sql .= " ".price2num($this->localtax1_tx).",";
3819  $sql .= " ".price2num($this->localtax2_tx).",";
3820  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3821  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3822  $sql .= " ".((float) $this->remise_percent).", ".price2num($this->subprice, 'MU').", '".$this->db->escape($this->ref_supplier)."',";
3823  $sql .= " ".price2num($this->total_ht).",";
3824  $sql .= " ".price2num($this->total_tva).",";
3825  $sql .= " ".price2num($this->total_localtax1).",";
3826  $sql .= " ".price2num($this->total_localtax2).",";
3827  $sql .= " ".price2num($this->total_ttc).",";
3828  $sql .= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null");
3829  $sql .= ", ".($this->fk_multicurrency ? ((int) $this->fk_multicurrency) : "null");
3830  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
3831  $sql .= ", ".($this->multicurrency_subprice ? price2num($this->multicurrency_subprice) : '0');
3832  $sql .= ", ".($this->multicurrency_total_ht ? price2num($this->multicurrency_total_ht) : '0');
3833  $sql .= ", ".($this->multicurrency_total_tva ? price2num($this->multicurrency_total_tva) : '0');
3834  $sql .= ", ".($this->multicurrency_total_ttc ? price2num($this->multicurrency_total_ttc) : '0');
3835  $sql .= ")";
3836 
3837  dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3838  $resql = $this->db->query($sql);
3839  if ($resql) {
3840  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
3841  $this->rowid = $this->id;
3842 
3843  if (!$error) {
3844  $result = $this->insertExtraFields();
3845  if ($result < 0) {
3846  $error++;
3847  }
3848  }
3849 
3850  if (!$error && !$notrigger) {
3851  // Call trigger
3852  $result = $this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user);
3853  if ($result < 0) {
3854  $error++;
3855  }
3856  // End call triggers
3857  }
3858 
3859  if (!$error) {
3860  $this->db->commit();
3861  return 1;
3862  }
3863 
3864  foreach ($this->errors as $errmsg) {
3865  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
3866  $this->errors[] = ($this->errors ? ', '.$errmsg : $errmsg);
3867  }
3868  $this->db->rollback();
3869  return -1 * $error;
3870  } else {
3871  $this->errors[] = $this->db->error();
3872  $this->db->rollback();
3873  return -2;
3874  }
3875  }
3882  public function update($notrigger = 0)
3883  {
3884  global $conf, $user;
3885 
3886  $error = 0;
3887 
3888  $this->db->begin();
3889 
3890  // Mise a jour ligne en base
3891  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3892  $sql .= " description='".$this->db->escape($this->desc)."'";
3893  $sql .= ", ref='".$this->db->escape($this->ref_supplier)."'";
3894  $sql .= ", subprice='".price2num($this->subprice)."'";
3895  //$sql.= ",remise='".price2num($remise)."'";
3896  $sql .= ", remise_percent='".price2num($this->remise_percent)."'";
3897 
3898  $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'";
3899  $sql .= ", tva_tx='".price2num($this->tva_tx)."'";
3900  $sql .= ", localtax1_tx='".price2num($this->localtax1_tx)."'";
3901  $sql .= ", localtax2_tx='".price2num($this->localtax2_tx)."'";
3902  $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
3903  $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
3904  $sql .= ", qty='".price2num($this->qty)."'";
3905  $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
3906  $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
3907  $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
3908  $sql .= ", total_ht='".price2num($this->total_ht)."'";
3909  $sql .= ", total_tva='".price2num($this->total_tva)."'";
3910  $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'";
3911  $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'";
3912  $sql .= ", total_ttc='".price2num($this->total_ttc)."'";
3913  $sql .= ", product_type=".$this->product_type;
3914  $sql .= ", special_code=".(!empty($this->special_code) ? $this->special_code : 0);
3915  $sql .= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'" : ", fk_unit=null");
3916 
3917  // Multicurrency
3918  $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
3919  $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
3920  $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
3921  $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
3922 
3923  $sql .= " WHERE rowid = ".((int) $this->id);
3924 
3925  dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
3926  $result = $this->db->query($sql);
3927  if ($result > 0) {
3928  if (!$error) {
3929  $result = $this->insertExtraFields();
3930  if ($result < 0) {
3931  $error++;
3932  }
3933  }
3934 
3935  if (!$error && !$notrigger) {
3936  global $user;
3937  // Call trigger
3938  $result = $this->call_trigger('LINEORDER_SUPPLIER_MODIFY', $user);
3939  if ($result < 0) {
3940  $this->db->rollback();
3941  return -1;
3942  }
3943  // End call triggers
3944  }
3945 
3946  if (!$error) {
3947  $this->db->commit();
3948  return 1;
3949  } else {
3950  $this->db->rollback();
3951  return -1;
3952  }
3953  } else {
3954  $this->error = $this->db->lasterror();
3955  $this->db->rollback();
3956  return -1;
3957  }
3958  }
3959 
3966  public function delete($notrigger = 0)
3967  {
3968  global $user;
3969 
3970  $error = 0;
3971 
3972  $this->db->begin();
3973 
3974  // extrafields
3975  $result = $this->deleteExtraFields();
3976  if ($result < 0) {
3977  $this->db->rollback();
3978  return -1;
3979  }
3980 
3981  $sql1 = 'UPDATE '.MAIN_DB_PREFIX."commandedet SET fk_commandefourndet = NULL WHERE rowid=".((int) $this->id);
3982  $resql = $this->db->query($sql1);
3983  if (!$resql) {
3984  $this->db->rollback();
3985  return -1;
3986  }
3987 
3988  $sql2 = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".((int) $this->id);
3989 
3990  dol_syslog(__METHOD__, LOG_DEBUG);
3991  $resql = $this->db->query($sql2);
3992  if ($resql) {
3993  if (!$notrigger) {
3994  // Call trigger
3995  $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user);
3996  if ($result < 0) {
3997  $error++;
3998  }
3999  // End call triggers
4000  }
4001 
4002  if (!$error) {
4003  $this->db->commit();
4004  return 1;
4005  }
4006 
4007  foreach ($this->errors as $errmsg) {
4008  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
4009  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
4010  }
4011  $this->db->rollback();
4012  return -1 * $error;
4013  } else {
4014  $this->error = $this->db->lasterror();
4015  return -1;
4016  }
4017  }
4018 }
CommandeFournisseur\fetch_lines
fetch_lines($only_product=0)
Load array lines.
Definition: fournisseur.commande.class.php:484
CommandeFournisseur\STATUS_ACCEPTED
const STATUS_ACCEPTED
Accepted.
Definition: fournisseur.commande.class.php:278
CommandeFournisseur\STATUS_CANCELED
const STATUS_CANCELED
Order canceled.
Definition: fournisseur.commande.class.php:298
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
getLocalTaxesFromRate
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
Definition: functions.lib.php:6097
db
$conf db
API class for accounts.
Definition: inc.php:41
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1468
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
CommandeFournisseur\deleteline
deleteline($idline, $notrigger=0)
Delete line.
Definition: fournisseur.commande.class.php:2131
CommandeFournisseur\updateFromCommandeClient
updateFromCommandeClient($user, $idc, $comclientid)
Update a supplier order from a customer order.
Definition: fournisseur.commande.class.php:2618
CommandeFournisseur\create
create($user, $notrigger=0)
Create order with draft status.
Definition: fournisseur.commande.class.php:1338
CommandeFournisseurLigne\__construct
__construct($db)
Constructor.
Definition: fournisseur.commande.class.php:3608
dol_delete_dir_recursive
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
Definition: files.lib.php:1383
CommandeFournisseur\setDeliveryDate
setDeliveryDate($user, $delivery_date, $notrigger=0)
Set the planned delivery date.
Definition: fournisseur.commande.class.php:2502
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
ProductFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.product.class.php:41
CommandeFournisseur\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template model.
Definition: fournisseur.commande.class.php:3192
CommandeFournisseurDispatch
Class to manage table commandefournisseurdispatch.
Definition: fournisseur.commande.dispatch.class.php:34
CommonObject\updateRangOfLine
updateRangOfLine($rowid, $rang)
Update position of line (rang)
Definition: commonobject.class.php:3219
CommonObject\fetchObjectLinked
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
Definition: commonobject.class.php:3916
CommandeFournisseur\$table_ref_field
$table_ref_field
{}
Definition: fournisseur.commande.class.php:89
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
CommonOrder
Superclass for orders classes.
Definition: commonorder.class.php:31
CommandeFournisseur\getRights
getRights()
Returns the rights used for this class.
Definition: fournisseur.commande.class.php:3253
CommandeFournisseur\hasDelay
hasDelay()
Is the supplier order delayed? We suppose a purchase ordered as late if a the purchase order has been...
Definition: fournisseur.commande.class.php:3302
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1062
CommandeFournisseurLigne\fetch
fetch($rowid)
Load line order.
Definition: fournisseur.commande.class.php:3619
MultiCurrency\getIdFromCode
static getIdFromCode($dbs, $code)
Get id of currency from code.
Definition: multicurrency.class.php:501
CommandeFournisseur\fetch
fetch($id, $ref='')
Get object and lines from database.
Definition: fournisseur.commande.class.php:336
CommandeFournisseur\getLibStatut
getLibStatut($mode=0)
Return label of the status of object.
Definition: fournisseur.commande.class.php:735
CommonObject\deleteObjectLinked
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
Definition: commonobject.class.php:4228
ref
$object ref
Definition: info.php:77
CommonObject\commonReplaceProduct
static commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
Definition: commonobject.class.php:8376
rowid
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
Definition: email_expire_services_to_representatives.php:79
dol_dir_list
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
CommandeFournisseur\get_methodes_commande
get_methodes_commande()
Get list of order methods.
Definition: fournisseur.commande.class.php:2288
CommandeFournisseur\dispatchProduct
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...
Definition: fournisseur.commande.class.php:2035
CommandeFournisseur\valid
valid($user, $idwarehouse=0, $notrigger=0)
Validate an order.
Definition: fournisseur.commande.class.php:624
CommandeFournisseur\getDispachedLines
getDispachedLines($status=-1)
Return array of dispatched lines waiting to be approved for this order.
Definition: fournisseur.commande.class.php:2321
CommandeFournisseur\getNomUrl
getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=0)
Return clicable name (with picto eventually)
Definition: fournisseur.commande.class.php:831
CommandeFournisseur\load_state_board
load_state_board()
Charge indicateurs this->nb de tableau de bord.
Definition: fournisseur.commande.class.php:3050
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
CommandeFournisseur\replaceProduct
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
Definition: fournisseur.commande.class.php:3286
CommandeFournisseurLigne\insert
insert($notrigger=0)
Insert line into database.
Definition: fournisseur.commande.class.php:3730
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
CommandeFournisseur\showDelay
showDelay()
Show the customer delayed info.
Definition: fournisseur.commande.class.php:3335
WorkboardResponse
Definition: workboardresponse.class.php:25
dol_concatdesc
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
Definition: functions.lib.php:7248
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5406
calcul_price_total
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, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition: price.lib.php:86
dol_delete_file
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
Definition: files.lib.php:1231
CommandeFournisseur\Livraison
Livraison($user, $date, $type, $comment)
Set a delivery in database for this supplier order.
Definition: fournisseur.commande.class.php:2374
CommonObject\update_price
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).
Definition: commonobject.class.php:3525
CommandeFournisseur\STATUS_ORDERSENT
const STATUS_ORDERSENT
Order sent, shipment on process.
Definition: fournisseur.commande.class.php:283
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:148
CommandeFournisseur\STATUS_VALIDATED
const STATUS_VALIDATED
Validated status.
Definition: fournisseur.commande.class.php:273
CommandeFournisseur\LibStatut
LibStatut($status, $mode=0, $billed=0)
Return label of a status.
Definition: fournisseur.commande.class.php:749
CommandeFournisseur\STATUS_REFUSED
const STATUS_REFUSED
Refused.
Definition: fournisseur.commande.class.php:308
MouvementStock
Class to manage stock movements.
Definition: mouvementstock.class.php:31
CommandeFournisseur\Cancel
Cancel($user, $idwarehouse=-1)
Cancel an approved order.
Definition: fournisseur.commande.class.php:1224
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6156
Commande
Class to manage customers orders.
Definition: commande.class.php:46
CommandeFournisseurLigne\update
update($notrigger=0)
Update the line object into db.
Definition: fournisseur.commande.class.php:3882
CommandeFournisseur\replaceThirdparty
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: fournisseur.commande.class.php:3269
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6694
CommonObject\deleteEcmFiles
deleteEcmFiles($mode=0)
Delete related files of object in database.
Definition: commonobject.class.php:9966
CommonObject\add_contact
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Definition: commonobject.class.php:1108
CommandeFournisseur\classifyBilled
classifyBilled(User $user)
Class invoiced the supplier order.
Definition: fournisseur.commande.class.php:984
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8347
CommandeFournisseur\commande
commande($user, $date, $methode, $comment='')
Submit a supplier order to supplier.
Definition: fournisseur.commande.class.php:1279
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
setEventMessage
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
Definition: functions.lib.php:8108
MultiCurrency\getIdAndTxFromCode
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Definition: multicurrency.class.php:526
CommonObject\line_max
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
Definition: commonobject.class.php:3373
CommandeFournisseur\refuse
refuse($user)
Refuse an order.
Definition: fournisseur.commande.class.php:1175
CommandeFournisseur\set_id_projet
set_id_projet($user, $id_projet, $notrigger=0)
Set the id projet.
Definition: fournisseur.commande.class.php:2560
CommandeFournisseur\getMaxDeliveryTimeDay
getMaxDeliveryTimeDay($langs)
Return the max number delivery delay in day.
Definition: fournisseur.commande.class.php:3221
CommandeFournisseur\STATUS_RECEIVED_COMPLETELY
const STATUS_RECEIVED_COMPLETELY
Received completely.
Definition: fournisseur.commande.class.php:293
CommandeFournisseur\createFromClone
createFromClone(User $user, $socid=0, $notrigger=0)
Load an object from its id and create a new one in database.
Definition: fournisseur.commande.class.php:1646
CommonObject\fetch_optionals
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...
Definition: commonobject.class.php:6007
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
CommandeFournisseur\SOURCE_ID_REPLENISHMENT
const SOURCE_ID_REPLENISHMENT
The constant used into source field to track the order was generated by the replenishement feature.
Definition: fournisseur.commande.class.php:314
CommandeFournisseur\getNextNumRef
getNextNumRef($soc)
Returns the following order reference not used depending on the numbering model activated defined wit...
Definition: fournisseur.commande.class.php:938
CommandeFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.commande.class.php:47
User
Class to manage Dolibarr users.
Definition: user.class.php:44
CommandeFournisseur\update
update(User $user, $notrigger=0)
Update Supplier Order.
Definition: fournisseur.commande.class.php:1542
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6116
CommandeFournisseur\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: fournisseur.commande.class.php:268
Product
Class to manage products or services.
Definition: product.class.php:46
CommandeFournisseur\setStatus
setStatus($user, $status)
Tag order with a particular status.
Definition: fournisseur.commande.class.php:2658
CommonObject\add_object_linked
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
Definition: commonobject.class.php:3818
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
CommandeFournisseur\approve
approve($user, $idwarehouse=0, $secondlevel=0)
Approve a supplier order.
Definition: fournisseur.commande.class.php:1032
CommandeFournisseur\set_date_livraison
set_date_livraison($user, $delivery_date, $notrigger=0)
Set delivery date.
Definition: fournisseur.commande.class.php:2488
CommandeFournisseur\loadReceptions
loadReceptions($filtre_statut=-1)
Load array this->receptions of lines of shipments with nb of products sent for each order line Note: ...
Definition: fournisseur.commande.class.php:3499
CommandeFournisseur\addline
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, $rang=-1)
Add order line.
Definition: fournisseur.commande.class.php:1752
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
CommandeFournisseur\$fields
$fields
'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortf...
Definition: fournisseur.commande.class.php:216
CommandeFournisseur\updateline
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.
Definition: fournisseur.commande.class.php:2729
price
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.
Definition: functions.lib.php:5541
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
CommandeFournisseur\info
info($id)
Charge les informations d'ordre info dans l'objet facture.
Definition: fournisseur.commande.class.php:3004
CommandeFournisseur\__construct
__construct($db)
Constructor.
Definition: fournisseur.commande.class.php:323
CommandeFournisseur\load_board
load_board($user, $mode='opened')
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: fournisseur.commande.class.php:3090
CommandeFournisseur\STATUS_RECEIVED_PARTIALLY
const STATUS_RECEIVED_PARTIALLY
Received partially.
Definition: fournisseur.commande.class.php:288
CommonOrderLine
Superclass for orders classes.
Definition: commonorder.class.php:39
CommonObject\line_order
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
Definition: commonobject.class.php:3055
CommandeFournisseur\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: fournisseur.commande.class.php:2920
CommandeFournisseurLigne
Class to manage line orders.
Definition: fournisseur.commande.class.php:3550
CommandeFournisseur\getInputMethod
getInputMethod()
Returns the translated input method of object (defined if $this->methode_commande_id > 0).
Definition: fournisseur.commande.class.php:3153
CommandeFournisseur\STATUS_CANCELED_AFTER_ORDER
const STATUS_CANCELED_AFTER_ORDER
Order canceled/never received.
Definition: fournisseur.commande.class.php:303
CommandeFournisseur\calcAndSetStatusDispatch
calcAndSetStatusDispatch(User $user, $closeopenorder=1, $comment='')
Calc status regarding to dispatched stock.
Definition: fournisseur.commande.class.php:3370