dolibarr  18.0.0-alpha
propal.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
4  * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
5  * Copyright (C) 2005 Marc Barilley <marc@ocebo.com>
6  * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
7  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
8  * Copyright (C) 2008 Raphael Bertrand <raphael.bertrand@resultic.fr>
9  * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
10  * Copyright (C) 2010-2022 Philippe Grand <philippe.grand@atoo-net.com>
11  * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
12  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
13  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
14  * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
15  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
16  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
17  * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
18  * Copyright (C) 2022 ATM Consulting <contact@atm-consulting.fr>
19  * Copyright (C) 2022 OpenDSI <support@open-dsi.fr>
20  * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
21  *
22  * This program is free software; you can redistribute it and/or modify
23  * it under the terms of the GNU General Public License as published by
24  * the Free Software Foundation; either version 3 of the License, or
25  * (at your option) any later version.
26  *
27  * This program is distributed in the hope that it will be useful,
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30  * GNU General Public License for more details.
31  *
32  * You should have received a copy of the GNU General Public License
33  * along with this program. If not, see <https://www.gnu.org/licenses/>.
34  */
35 
41 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
42 require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
43 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
45 require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
46 require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
47 require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
48 
52 class Propal extends CommonObject
53 {
54  use CommonIncoterm;
55 
59  public $code = "";
60 
64  public $element = 'propal';
65 
69  public $table_element = 'propal';
70 
74  public $table_element_line = 'propaldet';
75 
79  public $fk_element = 'fk_propal';
80 
84  public $picto = 'propal';
85 
90  public $ismultientitymanaged = 1;
91 
96  public $restrictiononfksoc = 1;
97 
101  protected $table_ref_field = 'ref';
102 
107  public $socid;
108 
113  public $contactid;
114  public $author;
115 
120  public $ref_client;
121 
127  public $statut;
128 
134  public $status;
135 
140  public $datec;
141 
145  public $date_creation;
146 
151  public $datev;
152 
156  public $date_validation;
157 
161  public $date_signature;
162 
166  public $user_signature;
167 
171  public $date;
172 
177  public $datep;
178 
183  public $date_livraison; // deprecated; Use delivery_date instead.
184 
188  public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
189 
190 
191  public $fin_validite;
192 
193  public $user_author_id;
194  public $user_valid_id;
195  public $user_close_id;
196 
201  public $price;
206  public $tva;
211  public $total;
212 
213  public $cond_reglement_code;
214  public $deposit_percent;
215  public $mode_reglement_code;
216  public $remise_percent;
217 
221  public $remise;
226 
231  public $fk_address;
232 
233  public $address_type;
234  public $address;
235 
236  public $availability_id;
237  public $availability_code;
238 
239  public $duree_validite;
240 
241  public $demand_reason_id;
242  public $demand_reason_code;
243 
244  public $warehouse_id;
245 
246  public $extraparams = array();
247 
251  public $lines = array();
252  public $line;
253 
254  public $labelStatus = array();
255  public $labelStatusShort = array();
256 
257  // Multicurrency
261  public $fk_multicurrency;
262 
263  public $multicurrency_code;
264  public $multicurrency_tx;
265  public $multicurrency_total_ht;
266  public $multicurrency_total_tva;
267  public $multicurrency_total_ttc;
268 
269 
294  // BEGIN MODULEBUILDER PROPERTIES
298  public $fields = array(
299  'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
300  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>15, 'index'=>1),
301  'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>20),
302  'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>22),
303  'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>40),
304  'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'isModEnabled("societe")', 'visible'=>-1, 'position'=>23),
305  'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Fk projet', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>24),
306  'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
307  'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
308  'datep' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
309  'fin_validite' =>array('type'=>'datetime', 'label'=>'DateEnd', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
310  'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
311  'date_cloture' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
312  'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
313  'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>85),
314  'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
315  'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user cloture', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
316  'price' =>array('type'=>'double', 'label'=>'Price', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
317  'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
318  //'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
319  //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
320  'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1),
321  'total_tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1),
322  'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LocalTax1', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1),
323  'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LocalTax2', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1),
324  'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1),
325  'fk_account' =>array('type'=>'integer', 'label'=>'BankAccount', 'enabled'=>'$conf->banque->enabled', 'visible'=>-1, 'position'=>150),
326  'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
327  'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
328  'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>161),
329  'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
330  'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>170),
331  'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>175),
332  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'PDFTemplate', 'enabled'=>1, 'visible'=>0, 'position'=>180),
333  'date_livraison' =>array('type'=>'date', 'label'=>'DateDeliveryPlanned', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
334  'fk_shipping_method' =>array('type'=>'integer', 'label'=>'ShippingMethod', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
335  'fk_warehouse' =>array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Fk warehouse', 'enabled'=>'$conf->stock->enabled', 'visible'=>-1, 'position'=>191),
336  'fk_availability' =>array('type'=>'integer', 'label'=>'Availability', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
337  'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>0, 'position'=>200), // deprecated
338  'fk_input_reason' =>array('type'=>'integer', 'label'=>'InputReason', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
339  'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
340  'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>220),
341  'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>225),
342  'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>1, 'visible'=>-1, 'position'=>230),
343  'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCurrency', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>235),
344  'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>240, 'isameasure'=>1),
345  'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>245, 'isameasure'=>1),
346  'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>250, 'isameasure'=>1),
347  'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>255, 'isameasure'=>1),
348  'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
349  'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
350  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
351  );
352  // END MODULEBUILDER PROPERTIES
353 
357  const STATUS_DRAFT = 0;
361  const STATUS_VALIDATED = 1;
365  const STATUS_SIGNED = 2;
369  const STATUS_NOTSIGNED = 3;
373  const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ?
374 
375 
383  public function __construct($db, $socid = 0, $propalid = 0)
384  {
385  global $conf, $langs;
386 
387  $this->db = $db;
388 
389  $this->socid = $socid;
390  $this->id = $propalid;
391 
392  $this->duree_validite = getDolGlobalInt('PROPALE_VALIDITY_DURATION', 0);
393  }
394 
395 
396  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
408  public function add_product($idproduct, $qty, $remise_percent = 0)
409  {
410  // phpcs:enable
411  global $conf, $mysoc;
412 
413  if (!$qty) {
414  $qty = 1;
415  }
416 
417  dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
418  if ($idproduct > 0) {
419  $prod = new Product($this->db);
420  $prod->fetch($idproduct);
421 
422  $productdesc = $prod->description;
423 
424  $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
425  $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
426  if (empty($tva_tx)) {
427  $tva_npr = 0;
428  }
429  $vat_src_code = ''; // May be defined into tva_tx
430 
431  $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr);
432  $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr);
433 
434  // multiprices
435  if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) {
436  $price = $prod->multiprices[$this->thirdparty->price_level];
437  } else {
438  $price = $prod->price;
439  }
440 
441  $line = new PropaleLigne($this->db);
442 
443  $line->fk_product = $idproduct;
444  $line->desc = $productdesc;
445  $line->qty = $qty;
446  $line->subprice = $price;
447  $line->remise_percent = $remise_percent;
448  $line->vat_src_code = $vat_src_code;
449  $line->tva_tx = $tva_tx;
450  $line->fk_unit = $prod->fk_unit;
451  if ($tva_npr) {
452  $line->info_bits = 1;
453  }
454 
455  $this->lines[] = $line;
456  }
457 
458  return 1;
459  }
460 
461  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
468  public function insert_discount($idremise)
469  {
470  // phpcs:enable
471  global $langs;
472 
473  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
474  include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
475 
476  $this->db->begin();
477 
478  $remise = new DiscountAbsolute($this->db);
479  $result = $remise->fetch($idremise);
480 
481  if ($result > 0) {
482  if ($remise->fk_facture) { // Protection against multiple submission
483  $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
484  $this->db->rollback();
485  return -5;
486  }
487 
488  $line = new PropaleLigne($this->db);
489 
490  $this->line->context = $this->context;
491 
492  $line->fk_propal = $this->id;
493  $line->fk_remise_except = $remise->id;
494  $line->desc = $remise->description; // Description ligne
495  $line->vat_src_code = $remise->vat_src_code;
496  $line->tva_tx = $remise->tva_tx;
497  $line->subprice = -$remise->amount_ht;
498  $line->fk_product = 0; // Id produit predefined
499  $line->qty = 1;
500  $line->remise_percent = 0;
501  $line->rang = -1;
502  $line->info_bits = 2;
503 
504  // TODO deprecated
505  $line->price = -$remise->amount_ht;
506 
507  $line->total_ht = -$remise->amount_ht;
508  $line->total_tva = -$remise->amount_tva;
509  $line->total_ttc = -$remise->amount_ttc;
510 
511  $result = $line->insert();
512  if ($result > 0) {
513  $result = $this->update_price(1);
514  if ($result > 0) {
515  $this->db->commit();
516  return 1;
517  } else {
518  $this->db->rollback();
519  return -1;
520  }
521  } else {
522  $this->error = $line->error;
523  $this->errors = $line->errors;
524  $this->db->rollback();
525  return -2;
526  }
527  } else {
528  $this->db->rollback();
529  return -2;
530  }
531  }
532 
570  public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $fk_remise_except = 0, $noupdateafterinsertline = 0)
571  {
572  global $mysoc, $conf, $langs;
573 
574  dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except);
575 
576  if ($this->statut == self::STATUS_DRAFT) {
577  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
578 
579  // Clean parameters
580  if (empty($remise_percent)) {
581  $remise_percent = 0;
582  }
583  if (empty($qty)) {
584  $qty = 0;
585  }
586  if (empty($info_bits)) {
587  $info_bits = 0;
588  }
589  if (empty($rang)) {
590  $rang = 0;
591  }
592  if (empty($fk_parent_line) || $fk_parent_line < 0) {
593  $fk_parent_line = 0;
594  }
595 
596  $remise_percent = price2num($remise_percent);
597  $qty = price2num($qty);
598  $pu_ht = price2num($pu_ht);
599  $pu_ht_devise = price2num($pu_ht_devise);
600  $pu_ttc = price2num($pu_ttc);
601  if (!preg_match('/\((.*)\)/', $txtva)) {
602  $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
603  }
604  $txlocaltax1 = price2num($txlocaltax1);
605  $txlocaltax2 = price2num($txlocaltax2);
606  $pa_ht = price2num($pa_ht);
607  if ($price_base_type == 'HT') {
608  $pu = $pu_ht;
609  } else {
610  $pu = $pu_ttc;
611  }
612 
613  // Check parameters
614  if ($type < 0) {
615  return -1;
616  }
617 
618  if ($date_start && $date_end && $date_start > $date_end) {
619  $langs->load("errors");
620  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
621  return -1;
622  }
623 
624  $this->db->begin();
625 
626  $product_type = $type;
627  if (!empty($fk_product) && $fk_product > 0) {
628  $product = new Product($this->db);
629  $result = $product->fetch($fk_product);
630  $product_type = $product->type;
631 
632  if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) {
633  $langs->load("errors");
634  $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
635  $this->db->rollback();
636  return -3;
637  }
638  }
639 
640  // Calcul du total TTC et de la TVA pour la ligne a partir de
641  // qty, pu, remise_percent et txtva
642  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
643  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
644 
645  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
646 
647  // Clean vat code
648  $reg = array();
649  $vat_src_code = '';
650  $reg = array();
651  if (preg_match('/\((.*)\)/', $txtva, $reg)) {
652  $vat_src_code = $reg[1];
653  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
654  }
655 
656  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
657 
658  $total_ht = $tabprice[0];
659  $total_tva = $tabprice[1];
660  $total_ttc = $tabprice[2];
661  $total_localtax1 = $tabprice[9];
662  $total_localtax2 = $tabprice[10];
663  $pu_ht = $tabprice[3];
664  $pu_tva = $tabprice[4];
665  $pu_ttc = $tabprice[5];
666 
667  // MultiCurrency
668  $multicurrency_total_ht = $tabprice[16];
669  $multicurrency_total_tva = $tabprice[17];
670  $multicurrency_total_ttc = $tabprice[18];
671  $pu_ht_devise = $tabprice[19];
672 
673  // Rang to use
674  $ranktouse = $rang;
675  if ($ranktouse == -1) {
676  $rangmax = $this->line_max($fk_parent_line);
677  $ranktouse = $rangmax + 1;
678  }
679 
680  // TODO A virer
681  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
682  $price = $pu;
683  $remise = 0;
684  if ($remise_percent > 0) {
685  $remise = round(($pu * $remise_percent / 100), 2);
686  $price = $pu - $remise;
687  }
688 
689  // Insert line
690  $this->line = new PropaleLigne($this->db);
691 
692  $this->line->context = $this->context;
693 
694  $this->line->fk_propal = $this->id;
695  $this->line->label = $label;
696  $this->line->desc = $desc;
697  $this->line->qty = $qty;
698 
699  $this->line->vat_src_code = $vat_src_code;
700  $this->line->tva_tx = $txtva;
701  $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
702  $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
703  $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
704  $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
705  $this->line->fk_product = $fk_product;
706  $this->line->product_type = $type;
707  $this->line->fk_remise_except = $fk_remise_except;
708  $this->line->remise_percent = $remise_percent;
709  $this->line->subprice = $pu_ht;
710  $this->line->rang = $ranktouse;
711  $this->line->info_bits = $info_bits;
712  $this->line->total_ht = $total_ht;
713  $this->line->total_tva = $total_tva;
714  $this->line->total_localtax1 = $total_localtax1;
715  $this->line->total_localtax2 = $total_localtax2;
716  $this->line->total_ttc = $total_ttc;
717  $this->line->special_code = $special_code;
718  $this->line->fk_parent_line = $fk_parent_line;
719  $this->line->fk_unit = $fk_unit;
720 
721  $this->line->date_start = $date_start;
722  $this->line->date_end = $date_end;
723 
724  $this->line->fk_fournprice = $fk_fournprice;
725  $this->line->pa_ht = $pa_ht;
726 
727  $this->line->origin_id = $origin_id;
728  $this->line->origin = $origin;
729 
730  // Multicurrency
731  $this->line->fk_multicurrency = $this->fk_multicurrency;
732  $this->line->multicurrency_code = $this->multicurrency_code;
733  $this->line->multicurrency_subprice = $pu_ht_devise;
734  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
735  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
736  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
737 
738  // Mise en option de la ligne
739  if (empty($qty) && empty($special_code)) {
740  $this->line->special_code = 3;
741  }
742 
743  // TODO deprecated
744  $this->line->price = $price;
745 
746  if (is_array($array_options) && count($array_options) > 0) {
747  $this->line->array_options = $array_options;
748  }
749 
750  $result = $this->line->insert();
751  if ($result > 0) {
752  // Reorder if child line
753  if (!empty($fk_parent_line)) {
754  $this->line_order(true, 'DESC');
755  } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
756  $linecount = count($this->lines);
757  for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
758  $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
759  }
760  }
761 
762  // Mise a jour informations denormalisees au niveau de la propale meme
763  if (empty($noupdateafterinsertline)) {
764  $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
765  }
766 
767  if ($result > 0) {
768  $this->db->commit();
769  return $this->line->id;
770  } else {
771  $this->error = $this->db->error();
772  $this->db->rollback();
773  return -1;
774  }
775  } else {
776  $this->error = $this->line->error;
777  $this->errors = $this->line->errors;
778  $this->db->rollback();
779  return -2;
780  }
781  } else {
782  dol_syslog(get_class($this)."::addline status of proposal must be Draft to allow use of ->addline()", LOG_ERR);
783  return -3;
784  }
785  }
786 
787 
817  public function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $desc = '', $price_base_type = 'HT', $info_bits = 0, $special_code = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $type = 0, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $rang = 0)
818  {
819  global $mysoc, $langs;
820 
821  dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent,
822  txtva=$txtva, desc=$desc, price_base_type=$price_base_type, info_bits=$info_bits, special_code=$special_code, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, type=$type, date_start=$date_start, date_end=$date_end");
823  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
824 
825  // Clean parameters
826  $remise_percent = price2num($remise_percent);
827  $qty = price2num($qty);
828  $pu = price2num($pu);
829  $pu_ht_devise = price2num($pu_ht_devise);
830  if (!preg_match('/\((.*)\)/', $txtva)) {
831  $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
832  }
833  $txlocaltax1 = price2num($txlocaltax1);
834  $txlocaltax2 = price2num($txlocaltax2);
835  $pa_ht = price2num($pa_ht);
836  if (empty($qty) && empty($special_code)) {
837  $special_code = 3; // Set option tag
838  }
839  if (!empty($qty) && $special_code == 3) {
840  $special_code = 0; // Remove option tag
841  }
842  if (empty($type)) {
843  $type = 0;
844  }
845 
846  if ($date_start && $date_end && $date_start > $date_end) {
847  $langs->load("errors");
848  $this->error = $langs->trans('ErrorStartDateGreaterEnd');
849  return -1;
850  }
851 
852  if ($this->statut == self::STATUS_DRAFT) {
853  $this->db->begin();
854 
855  // Calcul du total TTC et de la TVA pour la ligne a partir de
856  // qty, pu, remise_percent et txtva
857  // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
858  // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
859 
860  $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
861 
862  // Clean vat code
863  $reg = array();
864  $vat_src_code = '';
865  if (preg_match('/\((.*)\)/', $txtva, $reg)) {
866  $vat_src_code = $reg[1];
867  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
868  }
869 
870  $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
871  $total_ht = $tabprice[0];
872  $total_tva = $tabprice[1];
873  $total_ttc = $tabprice[2];
874  $total_localtax1 = $tabprice[9];
875  $total_localtax2 = $tabprice[10];
876  $pu_ht = $tabprice[3];
877  $pu_tva = $tabprice[4];
878  $pu_ttc = $tabprice[5];
879 
880  // MultiCurrency
881  $multicurrency_total_ht = $tabprice[16];
882  $multicurrency_total_tva = $tabprice[17];
883  $multicurrency_total_ttc = $tabprice[18];
884  $pu_ht_devise = $tabprice[19];
885 
886  // Anciens indicateurs: $price, $remise (a ne plus utiliser)
887  $price = $pu;
888  $remise = 0;
889  if ($remise_percent > 0) {
890  $remise = round(($pu * $remise_percent / 100), 2);
891  $price = $pu - $remise;
892  }
893 
894  //Fetch current line from the database and then clone the object and set it in $oldline property
895  $line = new PropaleLigne($this->db);
896  $line->fetch($rowid);
897 
898  $staticline = clone $line;
899 
900  $line->oldline = $staticline;
901  $this->line = $line;
902  $this->line->context = $this->context;
903  $this->line->rang = $rang;
904 
905  // Reorder if fk_parent_line change
906  if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
907  $rangmax = $this->line_max($fk_parent_line);
908  $this->line->rang = $rangmax + 1;
909  }
910 
911  $this->line->id = $rowid;
912  $this->line->label = $label;
913  $this->line->desc = $desc;
914  $this->line->qty = $qty;
915  $this->line->product_type = $type;
916  $this->line->vat_src_code = $vat_src_code;
917  $this->line->tva_tx = $txtva;
918  $this->line->localtax1_tx = $txlocaltax1;
919  $this->line->localtax2_tx = $txlocaltax2;
920  $this->line->localtax1_type = $localtaxes_type[0];
921  $this->line->localtax2_type = $localtaxes_type[2];
922  $this->line->remise_percent = $remise_percent;
923  $this->line->subprice = $pu_ht;
924  $this->line->info_bits = $info_bits;
925 
926  $this->line->total_ht = $total_ht;
927  $this->line->total_tva = $total_tva;
928  $this->line->total_localtax1 = $total_localtax1;
929  $this->line->total_localtax2 = $total_localtax2;
930  $this->line->total_ttc = $total_ttc;
931  $this->line->special_code = $special_code;
932  $this->line->fk_parent_line = $fk_parent_line;
933  $this->line->skip_update_total = $skip_update_total;
934  $this->line->fk_unit = $fk_unit;
935 
936  $this->line->fk_fournprice = $fk_fournprice;
937  $this->line->pa_ht = $pa_ht;
938 
939  $this->line->date_start = $date_start;
940  $this->line->date_end = $date_end;
941 
942  if (is_array($array_options) && count($array_options) > 0) {
943  // We replace values in this->line->array_options only for entries defined into $array_options
944  foreach ($array_options as $key => $value) {
945  $this->line->array_options[$key] = $array_options[$key];
946  }
947  }
948 
949  // Multicurrency
950  $this->line->multicurrency_subprice = $pu_ht_devise;
951  $this->line->multicurrency_total_ht = $multicurrency_total_ht;
952  $this->line->multicurrency_total_tva = $multicurrency_total_tva;
953  $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
954 
955  $result = $this->line->update($notrigger);
956  if ($result > 0) {
957  // Reorder if child line
958  if (!empty($fk_parent_line)) {
959  $this->line_order(true, 'DESC');
960  }
961 
962  $this->update_price(1);
963 
964  $this->fk_propal = $this->id;
965  $this->rowid = $rowid;
966 
967  $this->db->commit();
968  return $result;
969  } else {
970  $this->error = $this->line->error;
971  $this->errors = $this->line->errors;
972  $this->db->rollback();
973  return -1;
974  }
975  } else {
976  dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
977  return -2;
978  }
979  }
980 
981 
989  public function deleteline($lineid, $id = 0)
990  {
991  global $user;
992 
993  if ($this->statut == self::STATUS_DRAFT) {
994  $this->db->begin();
995 
996  $line = new PropaleLigne($this->db);
997 
998  $line->context = $this->context;
999 
1000  // Load data
1001  $line->fetch($lineid);
1002 
1003  if ($id > 0 && $line->fk_propal != $id) {
1004  $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1005  return -1;
1006  }
1007 
1008  // Memorize previous line for triggers
1009  $staticline = clone $line;
1010  $line->oldline = $staticline;
1011 
1012  if ($line->delete($user) > 0) {
1013  $this->update_price(1);
1014 
1015  $this->db->commit();
1016  return 1;
1017  } else {
1018  $this->error = $line->error;
1019  $this->errors = $line->errors;
1020  $this->db->rollback();
1021  return -1;
1022  }
1023  } else {
1024  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1025  return -2;
1026  }
1027  }
1028 
1029 
1038  public function create($user, $notrigger = 0)
1039  {
1040  global $conf, $hookmanager, $mysoc;
1041  $error = 0;
1042 
1043  $now = dol_now();
1044 
1045  // Clean parameters
1046  if (empty($this->date)) {
1047  $this->date = $this->datep;
1048  }
1049  $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1050  if (empty($this->availability_id)) {
1051  $this->availability_id = 0;
1052  }
1053  if (empty($this->demand_reason_id)) {
1054  $this->demand_reason_id = 0;
1055  }
1056 
1057  // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1058  if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1059  list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
1060  } else {
1061  $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1062  }
1063  if (empty($this->fk_multicurrency)) {
1064  $this->multicurrency_code = $conf->currency;
1065  $this->fk_multicurrency = 0;
1066  $this->multicurrency_tx = 1;
1067  }
1068 
1069  // Set tmp vars
1070  $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date;
1071 
1072  dol_syslog(get_class($this)."::create");
1073 
1074  // Check parameters
1075  $result = $this->fetch_thirdparty();
1076  if ($result < 0) {
1077  $this->error = "Failed to fetch company";
1078  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1079  return -3;
1080  }
1081 
1082  // Check parameters
1083  if (!empty($this->ref)) { // We check that ref is not already used
1084  $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
1085  if ($result > 0) {
1086  $this->error = 'ErrorRefAlreadyExists';
1087  dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1088  $this->db->rollback();
1089  return -1;
1090  }
1091  }
1092 
1093  if (empty($this->date)) {
1094  $this->error = "Date of proposal is required";
1095  dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1096  return -4;
1097  }
1098 
1099 
1100  $this->db->begin();
1101 
1102  // Insert into database
1103  $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal (";
1104  $sql .= "fk_soc";
1105  $sql .= ", price";
1106  $sql .= ", remise";
1107  $sql .= ", remise_percent";
1108  $sql .= ", remise_absolue";
1109  $sql .= ", total_tva";
1110  $sql .= ", total_ttc";
1111  $sql .= ", datep";
1112  $sql .= ", datec";
1113  $sql .= ", ref";
1114  $sql .= ", fk_user_author";
1115  $sql .= ", note_private";
1116  $sql .= ", note_public";
1117  $sql .= ", model_pdf";
1118  $sql .= ", fin_validite";
1119  $sql .= ", fk_cond_reglement";
1120  $sql .= ", deposit_percent";
1121  $sql .= ", fk_mode_reglement";
1122  $sql .= ", fk_account";
1123  $sql .= ", ref_client";
1124  $sql .= ", ref_ext";
1125  $sql .= ", date_livraison";
1126  $sql .= ", fk_shipping_method";
1127  $sql .= ", fk_warehouse";
1128  $sql .= ", fk_availability";
1129  $sql .= ", fk_input_reason";
1130  $sql .= ", fk_projet";
1131  $sql .= ", fk_incoterms";
1132  $sql .= ", location_incoterms";
1133  $sql .= ", entity";
1134  $sql .= ", fk_multicurrency";
1135  $sql .= ", multicurrency_code";
1136  $sql .= ", multicurrency_tx";
1137  $sql .= ") ";
1138  $sql .= " VALUES (";
1139  $sql .= $this->socid;
1140  $sql .= ", 0";
1141  $sql .= ", ".((float) $this->remise); // deprecated
1142  $sql .= ", ".($this->remise_percent ? ((float) $this->remise_percent) : 'NULL');
1143  $sql .= ", ".($this->remise_absolue ? ((float) $this->remise_absolue) : 'NULL'); // deprecated
1144  $sql .= ", 0";
1145  $sql .= ", 0";
1146  $sql .= ", '".$this->db->idate($this->date)."'";
1147  $sql .= ", '".$this->db->idate($now)."'";
1148  $sql .= ", '(PROV)'";
1149  $sql .= ", ".($user->id > 0 ? ((int) $user->id) : "NULL");
1150  $sql .= ", '".$this->db->escape($this->note_private)."'";
1151  $sql .= ", '".$this->db->escape($this->note_public)."'";
1152  $sql .= ", '".$this->db->escape($this->model_pdf)."'";
1153  $sql .= ", ".($this->fin_validite != '' ? "'".$this->db->idate($this->fin_validite)."'" : "NULL");
1154  $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'NULL');
1155  $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : 'NULL');
1156  $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'NULL');
1157  $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1158  $sql .= ", '".$this->db->escape($this->ref_client)."'";
1159  $sql .= ", '".$this->db->escape($this->ref_ext)."'";
1160  $sql .= ", ".(empty($delivery_date) ? "NULL" : "'".$this->db->idate($delivery_date)."'");
1161  $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
1162  $sql .= ", ".($this->warehouse_id > 0 ? $this->warehouse_id : 'NULL');
1163  $sql .= ", ".$this->availability_id;
1164  $sql .= ", ".$this->demand_reason_id;
1165  $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
1166  $sql .= ", ".(int) $this->fk_incoterms;
1167  $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1168  $sql .= ", ".setEntity($this);
1169  $sql .= ", ".(int) $this->fk_multicurrency;
1170  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1171  $sql .= ", ".(double) $this->multicurrency_tx;
1172  $sql .= ")";
1173 
1174  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1175  $resql = $this->db->query($sql);
1176  if ($resql) {
1177  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal");
1178 
1179  if ($this->id) {
1180  $this->ref = '(PROV'.$this->id.')';
1181  $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
1182 
1183  dol_syslog(get_class($this)."::create", LOG_DEBUG);
1184  $resql = $this->db->query($sql);
1185  if (!$resql) {
1186  $error++;
1187  }
1188 
1189  if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1190  $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1191  }
1192 
1193  // Add object linked
1194  if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1195  foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1196  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, ...))
1197  foreach ($tmp_origin_id as $origin_id) {
1198  $ret = $this->add_object_linked($origin, $origin_id);
1199  if (!$ret) {
1200  $this->error = $this->db->lasterror();
1201  $error++;
1202  }
1203  }
1204  } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1205  {
1206  $origin_id = $tmp_origin_id;
1207  $ret = $this->add_object_linked($origin, $origin_id);
1208  if (!$ret) {
1209  $this->error = $this->db->lasterror();
1210  $error++;
1211  }
1212  }
1213  }
1214  }
1215 
1216  /*
1217  * Insertion du detail des produits dans la base
1218  * Insert products detail in database
1219  */
1220  if (!$error) {
1221  $fk_parent_line = 0;
1222  $num = count($this->lines);
1223 
1224  for ($i = 0; $i < $num; $i++) {
1225  if (!is_object($this->lines[$i])) { // If this->lines is not array of objects, coming from REST API
1226  // Convert into object this->lines[$i].
1227  $line = (object) $this->lines[$i];
1228  } else {
1229  $line = $this->lines[$i];
1230  }
1231  // Reset fk_parent_line for line that are not child lines or special product
1232  if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1233  $fk_parent_line = 0;
1234  }
1235  // Complete vat rate with code
1236  $vatrate = $line->tva_tx;
1237  if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) {
1238  $vatrate .= ' ('.$line->vat_src_code.')';
1239  }
1240 
1241  if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
1242  $originid = $line->origin_id;
1243  $origintype = $line->origin;
1244  } else {
1245  $originid = $line->id;
1246  $origintype = $this->element;
1247  }
1248 
1249  $result = $this->addline(
1250  $line->desc,
1251  $line->subprice,
1252  $line->qty,
1253  $vatrate,
1254  $line->localtax1_tx,
1255  $line->localtax2_tx,
1256  $line->fk_product,
1257  $line->remise_percent,
1258  'HT',
1259  0,
1260  $line->info_bits,
1261  $line->product_type,
1262  $line->rang,
1263  $line->special_code,
1264  $fk_parent_line,
1265  $line->fk_fournprice,
1266  $line->pa_ht,
1267  $line->label,
1268  $line->date_start,
1269  $line->date_end,
1270  $line->array_options,
1271  $line->fk_unit,
1272  $origintype,
1273  $originid,
1274  0,
1275  0,
1276  1
1277  );
1278 
1279  if ($result < 0) {
1280  $error++;
1281  $this->error = $this->db->error;
1282  dol_print_error($this->db);
1283  break;
1284  }
1285  // Defined the new fk_parent_line
1286  if ($result > 0 && $line->product_type == 9) {
1287  $fk_parent_line = $result;
1288  }
1289  }
1290  }
1291 
1292  // Set delivery address
1293  /*if (! $error && $this->fk_delivery_address)
1294  {
1295  $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1296  $sql.= " SET fk_delivery_address = ".((int) $this->fk_delivery_address);
1297  $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'";
1298  $sql.= " AND entity = ".setEntity($this);
1299 
1300  $result=$this->db->query($sql);
1301  }*/
1302 
1303  if (!$error) {
1304  // Mise a jour infos denormalisees
1305  $resql = $this->update_price(1, 'auto', 0, $mysoc);
1306  if ($resql) {
1307  $action = 'update';
1308 
1309  // Actions on extra fields
1310  if (!$error) {
1311  $result = $this->insertExtraFields();
1312  if ($result < 0) {
1313  $error++;
1314  }
1315  }
1316 
1317  if (!$error && !$notrigger) {
1318  // Call trigger
1319  $result = $this->call_trigger('PROPAL_CREATE', $user);
1320  if ($result < 0) {
1321  $error++;
1322  }
1323  // End call triggers
1324  }
1325  } else {
1326  $this->error = $this->db->lasterror();
1327  $error++;
1328  }
1329  }
1330  } else {
1331  $this->error = $this->db->lasterror();
1332  $error++;
1333  }
1334 
1335  if (!$error) {
1336  $this->db->commit();
1337  dol_syslog(get_class($this)."::create done id=".$this->id);
1338  return $this->id;
1339  } else {
1340  $this->db->rollback();
1341  return -2;
1342  }
1343  } else {
1344  $this->error = $this->db->lasterror();
1345  $this->db->rollback();
1346  return -1;
1347  }
1348  }
1349 
1359  public function createFromClone(User $user, $socid = 0, $forceentity = null, $update_prices = false)
1360  {
1361  global $conf, $hookmanager, $mysoc;
1362 
1363  dol_include_once('/projet/class/project.class.php');
1364 
1365  $error = 0;
1366  $now = dol_now();
1367 
1368  dol_syslog(__METHOD__, LOG_DEBUG);
1369 
1370  $object = new self($this->db);
1371 
1372  $this->db->begin();
1373 
1374  // Load source object
1375  $object->fetch($this->id);
1376 
1377  $objsoc = new Societe($this->db);
1378 
1379  // Change socid if needed
1380  if (!empty($socid) && $socid != $object->socid) {
1381  if ($objsoc->fetch($socid) > 0) {
1382  $object->socid = $objsoc->id;
1383  $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1384  $object->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : null);
1385  $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1386  $object->fk_delivery_address = '';
1387 
1388  /*if (isModEnabled('project'))
1389  {
1390  $project = new Project($db);
1391  if ($this->fk_project > 0 && $project->fetch($this->fk_project)) {
1392  if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project;
1393  else $clonedObj->fk_project = '';
1394  } else {
1395  $clonedObj->fk_project = '';
1396  }
1397  }*/
1398  $object->fk_project = ''; // A cloned proposal is set by default to no project.
1399  }
1400 
1401  // reset ref_client
1402  $object->ref_client = '';
1403 
1404  // TODO Change product price if multi-prices
1405  } else {
1406  $objsoc->fetch($object->socid);
1407  }
1408 
1409  // update prices
1410  if ($update_prices === true) {
1411  if ($objsoc->id > 0 && !empty($object->lines)) {
1412  if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
1413  // If price per customer
1414  require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
1415  }
1416 
1417  foreach ($object->lines as $line) {
1418  if ($line->fk_product > 0) {
1419  $prod = new Product($this->db);
1420  $res = $prod->fetch($line->fk_product);
1421  if ($res > 0) {
1422  $pu_ht = $prod->price;
1423  $tva_tx = get_default_tva($mysoc, $objsoc, $prod->id);
1424  $remise_percent = $objsoc->remise_percent;
1425 
1426  if (!empty($conf->global->PRODUIT_MULTIPRICES) && $objsoc->price_level > 0) {
1427  $pu_ht = $prod->multiprices[$objsoc->price_level];
1428  if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
1429  if (isset($prod->multiprices_tva_tx[$objsoc->price_level])) {
1430  $tva_tx = $prod->multiprices_tva_tx[$objsoc->price_level];
1431  }
1432  }
1433  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
1434  $prodcustprice = new Productcustomerprice($this->db);
1435  $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $objsoc->id);
1436  $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
1437  if ($result) {
1438  // If there is some prices specific to the customer
1439  if (count($prodcustprice->lines) > 0) {
1440  $pu_ht = price($prodcustprice->lines[0]->price);
1441  $tva_tx = ($prodcustprice->lines[0]->default_vat_code ? $prodcustprice->lines[0]->tva_tx.' ('.$prodcustprice->lines[0]->default_vat_code.' )' : $prodcustprice->lines[0]->tva_tx);
1442  if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
1443  $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
1444  }
1445  }
1446  }
1447  }
1448 
1449  $line->subprice = $pu_ht;
1450  $line->tva_tx = $tva_tx;
1451  $line->remise_percent = $remise_percent;
1452  }
1453  }
1454  }
1455  }
1456  }
1457 
1458  $object->id = 0;
1459  $object->ref = '';
1460  $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1461  $object->statut = self::STATUS_DRAFT;
1462 
1463  // Clear fields
1464  $object->user_author = $user->id;
1465  $object->user_valid = 0;
1466  $object->date = $now;
1467  $object->datep = $now; // deprecated
1468  $object->fin_validite = $object->date + ($object->duree_validite * 24 * 3600);
1469  if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) {
1470  $object->ref_client = '';
1471  }
1472  if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1473  $object->note_private = '';
1474  $object->note_public = '';
1475  }
1476  // Create clone
1477  $object->context['createfromclone'] = 'createfromclone';
1478  $result = $object->create($user);
1479  if ($result < 0) {
1480  $this->error = $object->error;
1481  $this->errors = array_merge($this->errors, $object->errors);
1482  $error++;
1483  }
1484 
1485  if (!$error) {
1486  // copy internal contacts
1487  if ($object->copy_linked_contact($this, 'internal') < 0) {
1488  $error++;
1489  }
1490  }
1491 
1492  if (!$error) {
1493  // copy external contacts if same company
1494  if ($this->socid == $object->socid) {
1495  if ($object->copy_linked_contact($this, 'external') < 0) {
1496  $error++;
1497  }
1498  }
1499  }
1500 
1501  if (!$error) {
1502  // Hook of thirdparty module
1503  if (is_object($hookmanager)) {
1504  $parameters = array('objFrom'=>$this, 'clonedObj'=>$object);
1505  $action = '';
1506  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1507  if ($reshook < 0) {
1508  $this->setErrorsFromObject($hookmanager);
1509  $error++;
1510  }
1511  }
1512  }
1513 
1514  unset($object->context['createfromclone']);
1515 
1516  // End
1517  if (!$error) {
1518  $this->db->commit();
1519  return $object->id;
1520  } else {
1521  $this->db->rollback();
1522  return -1;
1523  }
1524  }
1525 
1535  public function fetch($rowid, $ref = '', $ref_ext = '', $forceentity = 0)
1536  {
1537  $sql = "SELECT p.rowid, p.ref, p.entity, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc";
1538  $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht";
1539  $sql .= ", p.datec";
1540  $sql .= ", p.date_signature as dates";
1541  $sql .= ", p.date_valid as datev";
1542  $sql .= ", p.datep as dp";
1543  $sql .= ", p.fin_validite as dfv";
1544  $sql .= ", p.date_livraison as delivery_date";
1545  $sql .= ", p.model_pdf, p.last_main_doc, p.ref_client, ref_ext, p.extraparams";
1546  $sql .= ", p.note_private, p.note_public";
1547  $sql .= ", p.fk_projet as fk_project, p.fk_statut";
1548  $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1549  $sql .= ", p.fk_delivery_address";
1550  $sql .= ", p.fk_availability";
1551  $sql .= ", p.fk_input_reason";
1552  $sql .= ", p.fk_cond_reglement";
1553  $sql .= ", p.fk_mode_reglement";
1554  $sql .= ', p.fk_account';
1555  $sql .= ", p.fk_shipping_method";
1556  $sql .= ", p.fk_warehouse";
1557  $sql .= ", p.fk_incoterms, p.location_incoterms";
1558  $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1559  $sql .= ", p.tms as date_modification";
1560  $sql .= ", i.libelle as label_incoterms";
1561  $sql .= ", c.label as statut_label";
1562  $sql .= ", ca.code as availability_code, ca.label as availability";
1563  $sql .= ", dr.code as demand_reason_code, dr.label as demand_reason";
1564  $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc, p.deposit_percent";
1565  $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1566  $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
1567  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id';
1568  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')';
1569  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')';
1570  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1571  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1572  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1573 
1574  if (!empty($ref)) {
1575  if (!empty($forceentity)) {
1576  $sql .= " WHERE p.entity = ".(int) $forceentity; // Check only the current entity because we may have the same reference in several entities
1577  } else {
1578  $sql .= " WHERE p.entity IN (".getEntity('propal').")";
1579  }
1580  $sql .= " AND p.ref='".$this->db->escape($ref)."'";
1581  } else {
1582  // Dont't use entity if you use rowid
1583  $sql .= " WHERE p.rowid = ".((int) $rowid);
1584  }
1585 
1586  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1587  $resql = $this->db->query($sql);
1588  if ($resql) {
1589  if ($this->db->num_rows($resql)) {
1590  $obj = $this->db->fetch_object($resql);
1591 
1592  $this->id = $obj->rowid;
1593  $this->entity = $obj->entity;
1594 
1595  $this->ref = $obj->ref;
1596  $this->ref_client = $obj->ref_client;
1597  $this->ref_ext = $obj->ref_ext;
1598  $this->remise = $obj->remise;
1599  $this->remise_percent = $obj->remise_percent;
1600  $this->remise_absolue = $obj->remise_absolue;
1601  $this->total = $obj->total_ttc; // TODO deprecated
1602  $this->total_ttc = $obj->total_ttc;
1603  $this->total_ht = $obj->total_ht;
1604  $this->total_tva = $obj->total_tva;
1605  $this->total_localtax1 = $obj->localtax1;
1606  $this->total_localtax2 = $obj->localtax2;
1607 
1608  $this->socid = $obj->fk_soc;
1609  $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
1610 
1611  $this->fk_project = $obj->fk_project;
1612  $this->project = null; // Clear if another value was already set by fetch_projet
1613 
1614  $this->model_pdf = $obj->model_pdf;
1615  $this->modelpdf = $obj->model_pdf; // deprecated
1616  $this->last_main_doc = $obj->last_main_doc;
1617  $this->note = $obj->note_private; // TODO deprecated
1618  $this->note_private = $obj->note_private;
1619  $this->note_public = $obj->note_public;
1620 
1621  $this->status = (int) $obj->fk_statut;
1622  $this->statut = $this->status; // deprecated
1623  $this->statut_libelle = $obj->statut_label;
1624 
1625  $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
1626  $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
1627  $this->date_creation = $this->db->jdate($obj->datec); //Creation date
1628  $this->date_validation = $this->db->jdate($obj->datev); //Validation date
1629  $this->date_modification = $this->db->jdate($obj->date_modification); // tms
1630  $this->date_signature = $this->db->jdate($obj->dates); // Signature date
1631  $this->date = $this->db->jdate($obj->dp); // Proposal date
1632  $this->datep = $this->db->jdate($obj->dp); // deprecated
1633  $this->fin_validite = $this->db->jdate($obj->dfv);
1634  $this->date_livraison = $this->db->jdate($obj->delivery_date); // deprecated
1635  $this->delivery_date = $this->db->jdate($obj->delivery_date);
1636  $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1637  $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
1638  $this->availability_id = $obj->fk_availability;
1639  $this->availability_code = $obj->availability_code;
1640  $this->availability = $obj->availability;
1641  $this->demand_reason_id = $obj->fk_input_reason;
1642  $this->demand_reason_code = $obj->demand_reason_code;
1643  $this->demand_reason = $obj->demand_reason;
1644  $this->fk_address = $obj->fk_delivery_address;
1645 
1646  $this->mode_reglement_id = $obj->fk_mode_reglement;
1647  $this->mode_reglement_code = $obj->mode_reglement_code;
1648  $this->mode_reglement = $obj->mode_reglement;
1649  $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
1650  $this->cond_reglement_id = $obj->fk_cond_reglement;
1651  $this->cond_reglement_code = $obj->cond_reglement_code;
1652  $this->cond_reglement = $obj->cond_reglement;
1653  $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1654  $this->deposit_percent = $obj->deposit_percent;
1655 
1656  $this->extraparams = (array) json_decode($obj->extraparams, true);
1657 
1658  $this->user_author_id = $obj->fk_user_author;
1659  $this->user_valid_id = $obj->fk_user_valid;
1660  $this->user_close_id = $obj->fk_user_cloture;
1661 
1662  //Incoterms
1663  $this->fk_incoterms = $obj->fk_incoterms;
1664  $this->location_incoterms = $obj->location_incoterms;
1665  $this->label_incoterms = $obj->label_incoterms;
1666 
1667  // Multicurrency
1668  $this->fk_multicurrency = $obj->fk_multicurrency;
1669  $this->multicurrency_code = $obj->multicurrency_code;
1670  $this->multicurrency_tx = $obj->multicurrency_tx;
1671  $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1672  $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1673  $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1674 
1675  if ($obj->fk_statut == self::STATUS_DRAFT) {
1676  $this->brouillon = 1;
1677  }
1678 
1679  // Retrieve all extrafield
1680  // fetch optionals attributes and labels
1681  $this->fetch_optionals();
1682 
1683  $this->db->free($resql);
1684 
1685  $this->lines = array();
1686 
1687  // Lines
1688  $result = $this->fetch_lines();
1689  if ($result < 0) {
1690  return -3;
1691  }
1692 
1693  return 1;
1694  }
1695 
1696  $this->error = "Record Not Found";
1697  return 0;
1698  } else {
1699  $this->error = $this->db->lasterror();
1700  return -1;
1701  }
1702  }
1703 
1711  public function update(User $user, $notrigger = 0)
1712  {
1713  global $conf;
1714 
1715  $error = 0;
1716 
1717  // Clean parameters
1718  if (isset($this->ref)) {
1719  $this->ref = trim($this->ref);
1720  }
1721  if (isset($this->ref_client)) {
1722  $this->ref_client = trim($this->ref_client);
1723  }
1724  if (isset($this->note) || isset($this->note_private)) {
1725  $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1726  }
1727  if (isset($this->note_public)) {
1728  $this->note_public = trim($this->note_public);
1729  }
1730  if (isset($this->model_pdf)) {
1731  $this->model_pdf = trim($this->model_pdf);
1732  }
1733  if (isset($this->import_key)) {
1734  $this->import_key = trim($this->import_key);
1735  }
1736  if (!empty($this->duree_validite) && is_numeric($this->duree_validite)) {
1737  $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1738  }
1739 
1740  // Check parameters
1741  // Put here code to add control on parameters values
1742 
1743  // Update request
1744  $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET";
1745  $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1746  $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
1747  $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1748  $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
1749  $sql .= " datep=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
1750  if (!empty($this->fin_validite)) {
1751  $sql .= " fin_validite=".(strval($this->fin_validite) != '' ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1752  }
1753  $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1754  $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
1755  $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
1756  $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
1757  $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
1758  $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
1759  $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
1760  $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").",";
1761  $sql .= " fk_user_valid=".(isset($this->user_valid) ? $this->user_valid : "null").",";
1762  $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
1763  $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
1764  $sql .= " deposit_percent=".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
1765  $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
1766  $sql .= " fk_input_reason=".(isset($this->demand_reason_id) ? $this->demand_reason_id : "null").",";
1767  $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1768  $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1769  $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1770  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1771  $sql .= " WHERE rowid=".((int) $this->id);
1772 
1773  $this->db->begin();
1774 
1775  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1776  $resql = $this->db->query($sql);
1777  if (!$resql) {
1778  $error++;
1779  $this->errors[] = "Error ".$this->db->lasterror();
1780  }
1781 
1782  if (!$error) {
1783  $result = $this->insertExtraFields();
1784  if ($result < 0) {
1785  $error++;
1786  }
1787  }
1788 
1789  if (!$error && !$notrigger) {
1790  // Call trigger
1791  $result = $this->call_trigger('PROPAL_MODIFY', $user);
1792  if ($result < 0) {
1793  $error++;
1794  }
1795  // End call triggers
1796  }
1797 
1798  // Commit or rollback
1799  if ($error) {
1800  foreach ($this->errors as $errmsg) {
1801  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1802  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1803  }
1804  $this->db->rollback();
1805  return -1 * $error;
1806  } else {
1807  $this->db->commit();
1808  return 1;
1809  }
1810  }
1811 
1812 
1813  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1823  public function fetch_lines($only_product = 0, $loadalsotranslation = 0, $filters = '')
1824  {
1825  // phpcs:enable
1826  global $langs, $conf;
1827 
1828  $this->lines = array();
1829 
1830  $sql = 'SELECT d.rowid, d.fk_propal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,';
1831  $sql .= ' d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,';
1832  $sql .= ' d.fk_unit,';
1833  $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch, p.barcode as product_barcode,';
1834  $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units,';
1835  $sql .= ' d.date_start, d.date_end,';
1836  $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
1837  $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as d';
1838  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
1839  $sql .= ' WHERE d.fk_propal = '.((int) $this->id);
1840  if ($only_product) {
1841  $sql .= ' AND p.fk_product_type = 0';
1842  }
1843  if ($filters) {
1844  $sql .= $filters;
1845  }
1846  $sql .= ' ORDER by d.rang';
1847 
1848  dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1849  $result = $this->db->query($sql);
1850  if ($result) {
1851  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1852 
1853  $num = $this->db->num_rows($result);
1854 
1855  $i = 0;
1856  while ($i < $num) {
1857  $objp = $this->db->fetch_object($result);
1858 
1859  $line = new PropaleLigne($this->db);
1860 
1861  $line->rowid = $objp->rowid; //Deprecated
1862  $line->id = $objp->rowid;
1863  $line->fk_propal = $objp->fk_propal;
1864  $line->fk_parent_line = $objp->fk_parent_line;
1865  $line->product_type = $objp->product_type;
1866  $line->label = $objp->custom_label;
1867  $line->desc = $objp->description; // Description ligne
1868  $line->description = $objp->description; // Description ligne
1869  $line->qty = $objp->qty;
1870  $line->vat_src_code = $objp->vat_src_code;
1871  $line->tva_tx = $objp->tva_tx;
1872  $line->localtax1_tx = $objp->localtax1_tx;
1873  $line->localtax2_tx = $objp->localtax2_tx;
1874  $line->localtax1_type = $objp->localtax1_type;
1875  $line->localtax2_type = $objp->localtax2_type;
1876  $line->subprice = $objp->subprice;
1877  $line->fk_remise_except = $objp->fk_remise_except;
1878  $line->remise_percent = $objp->remise_percent;
1879  $line->price = $objp->price; // TODO deprecated
1880 
1881  $line->info_bits = $objp->info_bits;
1882  $line->total_ht = $objp->total_ht;
1883  $line->total_tva = $objp->total_tva;
1884  $line->total_localtax1 = $objp->total_localtax1;
1885  $line->total_localtax2 = $objp->total_localtax2;
1886  $line->total_ttc = $objp->total_ttc;
1887  $line->fk_fournprice = $objp->fk_fournprice;
1888  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1889  $line->pa_ht = $marginInfos[0];
1890  $line->marge_tx = $marginInfos[1];
1891  $line->marque_tx = $marginInfos[2];
1892  $line->special_code = $objp->special_code;
1893  $line->rang = $objp->rang;
1894 
1895  $line->fk_product = $objp->fk_product;
1896 
1897  $line->ref = $objp->product_ref; // deprecated
1898  $line->libelle = $objp->product_label; // deprecated
1899 
1900  $line->product_ref = $objp->product_ref;
1901  $line->product_label = $objp->product_label;
1902  $line->product_desc = $objp->product_desc; // Description produit
1903  $line->product_tobatch = $objp->product_tobatch;
1904  $line->product_barcode = $objp->product_barcode;
1905 
1906  $line->fk_product_type = $objp->fk_product_type; // deprecated
1907  $line->fk_unit = $objp->fk_unit;
1908  $line->weight = $objp->weight;
1909  $line->weight_units = $objp->weight_units;
1910  $line->volume = $objp->volume;
1911  $line->volume_units = $objp->volume_units;
1912 
1913  $line->date_start = $this->db->jdate($objp->date_start);
1914  $line->date_end = $this->db->jdate($objp->date_end);
1915 
1916  // Multicurrency
1917  $line->fk_multicurrency = $objp->fk_multicurrency;
1918  $line->multicurrency_code = $objp->multicurrency_code;
1919  $line->multicurrency_subprice = $objp->multicurrency_subprice;
1920  $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
1921  $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
1922  $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
1923 
1924  $line->fetch_optionals();
1925 
1926  // multilangs
1927  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
1928  $tmpproduct = new Product($this->db);
1929  $tmpproduct->fetch($objp->fk_product);
1930  $tmpproduct->getMultiLangs();
1931 
1932  $line->multilangs = $tmpproduct->multilangs;
1933  }
1934 
1935  $this->lines[$i] = $line;
1936 
1937  $i++;
1938  }
1939 
1940  $this->db->free($result);
1941 
1942  return $num;
1943  } else {
1944  $this->error = $this->db->lasterror();
1945  return -3;
1946  }
1947  }
1948 
1956  public function valid($user, $notrigger = 0)
1957  {
1958  global $conf;
1959 
1960  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1961 
1962  $error = 0;
1963 
1964  // Protection
1965  if ($this->statut == self::STATUS_VALIDATED) {
1966  dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
1967  return 0;
1968  }
1969 
1970  if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->creer))
1971  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate)))) {
1972  $this->error = 'ErrorPermissionDenied';
1973  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1974  return -1;
1975  }
1976 
1977  $now = dol_now();
1978 
1979  $this->db->begin();
1980 
1981  // Numbering module definition
1982  $soc = new Societe($this->db);
1983  $soc->fetch($this->socid);
1984 
1985  // Define new ref
1986  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
1987  $num = $this->getNextNumRef($soc);
1988  } else {
1989  $num = $this->ref;
1990  }
1991  $this->newref = dol_sanitizeFileName($num);
1992 
1993  $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
1994  $sql .= " SET ref = '".$this->db->escape($num)."',";
1995  $sql .= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".((int) $user->id);
1996  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
1997 
1998  dol_syslog(get_class($this)."::valid", LOG_DEBUG);
1999  $resql = $this->db->query($sql);
2000  if (!$resql) {
2001  dol_print_error($this->db);
2002  $error++;
2003  }
2004 
2005  // Trigger calls
2006  if (!$error && !$notrigger) {
2007  // Call trigger
2008  $result = $this->call_trigger('PROPAL_VALIDATE', $user);
2009  if ($result < 0) {
2010  $error++;
2011  }
2012  // End call triggers
2013  }
2014 
2015  if (!$error) {
2016  $this->oldref = $this->ref;
2017 
2018  // Rename directory if dir was a temporary ref
2019  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
2020  // Now we rename also files into index
2021  $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'propale/".$this->db->escape($this->newref)."'";
2022  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
2023  $resql = $this->db->query($sql);
2024  if (!$resql) {
2025  $error++;
2026  $this->error = $this->db->lasterror();
2027  }
2028 
2029  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
2030  $oldref = dol_sanitizeFileName($this->ref);
2031  $newref = dol_sanitizeFileName($num);
2032  $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref;
2033  $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref;
2034  if (!$error && file_exists($dirsource)) {
2035  dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
2036  if (@rename($dirsource, $dirdest)) {
2037  dol_syslog("Rename ok");
2038  // Rename docs starting with $oldref with $newref
2039  $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
2040  foreach ($listoffiles as $fileentry) {
2041  $dirsource = $fileentry['name'];
2042  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
2043  $dirsource = $fileentry['path'].'/'.$dirsource;
2044  $dirdest = $fileentry['path'].'/'.$dirdest;
2045  @rename($dirsource, $dirdest);
2046  }
2047  }
2048  }
2049  }
2050 
2051  $this->ref = $num;
2052  $this->brouillon = 0;
2053  $this->statut = self::STATUS_VALIDATED;
2054  $this->user_valid_id = $user->id;
2055  $this->datev = $now;
2056 
2057  $this->db->commit();
2058  return 1;
2059  } else {
2060  $this->db->rollback();
2061  return -1;
2062  }
2063  }
2064 
2065 
2066  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2075  public function set_date($user, $date, $notrigger = 0)
2076  {
2077  // phpcs:enable
2078  if (empty($date)) {
2079  $this->error = 'ErrorBadParameter';
2080  dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
2081  return -1;
2082  }
2083 
2084  if (!empty($user->rights->propal->creer)) {
2085  $error = 0;
2086 
2087  $this->db->begin();
2088 
2089  $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'";
2090  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
2091 
2092  dol_syslog(__METHOD__, LOG_DEBUG);
2093  $resql = $this->db->query($sql);
2094  if (!$resql) {
2095  $this->errors[] = $this->db->error();
2096  $error++;
2097  }
2098 
2099  if (!$error) {
2100  $this->oldcopy = clone $this;
2101  $this->date = $date;
2102  $this->datep = $date; // deprecated
2103  }
2104 
2105  if (!$notrigger && empty($error)) {
2106  // Call trigger
2107  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2108  if ($result < 0) {
2109  $error++;
2110  }
2111  // End call triggers
2112  }
2113 
2114  if (!$error) {
2115  $this->db->commit();
2116  return 1;
2117  } else {
2118  foreach ($this->errors as $errmsg) {
2119  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2120  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2121  }
2122  $this->db->rollback();
2123  return -1 * $error;
2124  }
2125  }
2126 
2127  return -1;
2128  }
2129 
2130  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2139  public function set_echeance($user, $date_end_validity, $notrigger = 0)
2140  {
2141  // phpcs:enable
2142  if (!empty($user->rights->propal->creer)) {
2143  $error = 0;
2144 
2145  $this->db->begin();
2146 
2147  $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_end_validity != '' ? "'".$this->db->idate($date_end_validity)."'" : 'null');
2148  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".((int) self::STATUS_DRAFT);
2149 
2150  dol_syslog(__METHOD__, LOG_DEBUG);
2151  $resql = $this->db->query($sql);
2152  if (!$resql) {
2153  $this->errors[] = $this->db->error();
2154  $error++;
2155  }
2156 
2157 
2158  if (!$error) {
2159  $this->oldcopy = clone $this;
2160  $this->fin_validite = $date_end_validity;
2161  }
2162 
2163  if (!$notrigger && empty($error)) {
2164  // Call trigger
2165  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2166  if ($result < 0) {
2167  $error++;
2168  }
2169  // End call triggers
2170  }
2171 
2172  if (!$error) {
2173  $this->db->commit();
2174  return 1;
2175  } else {
2176  foreach ($this->errors as $errmsg) {
2177  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2178  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2179  }
2180  $this->db->rollback();
2181  return -1 * $error;
2182  }
2183  }
2184 
2185  return -1;
2186  }
2187 
2188  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2198  public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2199  {
2200  // phpcs:enable
2201  return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2202  }
2203 
2212  public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2213  {
2214  if (!empty($user->rights->propal->creer)) {
2215  $error = 0;
2216 
2217  $this->db->begin();
2218 
2219  $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
2220  $sql .= " SET date_livraison = ".($delivery_date != '' ? "'".$this->db->idate($delivery_date)."'" : 'null');
2221  $sql .= " WHERE rowid = ".((int) $this->id);
2222 
2223  dol_syslog(__METHOD__, LOG_DEBUG);
2224  $resql = $this->db->query($sql);
2225  if (!$resql) {
2226  $this->errors[] = $this->db->error();
2227  $error++;
2228  }
2229 
2230  if (!$error) {
2231  $this->oldcopy = clone $this;
2232  $this->date_livraison = $delivery_date;
2233  $this->delivery_date = $delivery_date;
2234  }
2235 
2236  if (!$notrigger && empty($error)) {
2237  // Call trigger
2238  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2239  if ($result < 0) {
2240  $error++;
2241  }
2242  // End call triggers
2243  }
2244 
2245  if (!$error) {
2246  $this->db->commit();
2247  return 1;
2248  } else {
2249  foreach ($this->errors as $errmsg) {
2250  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2251  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2252  }
2253  $this->db->rollback();
2254  return -1 * $error;
2255  }
2256  }
2257 
2258  return -1;
2259  }
2260 
2261  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2270  public function set_availability($user, $id, $notrigger = 0)
2271  {
2272  // phpcs:enable
2273  if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) {
2274  $error = 0;
2275 
2276  $this->db->begin();
2277 
2278  $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2279  $sql .= " SET fk_availability = ".((int) $id);
2280  $sql .= " WHERE rowid = ".((int) $this->id);
2281 
2282  dol_syslog(__METHOD__.' availability('.$id.')', LOG_DEBUG);
2283  $resql = $this->db->query($sql);
2284  if (!$resql) {
2285  $this->errors[] = $this->db->error();
2286  $error++;
2287  }
2288 
2289  if (!$error) {
2290  $this->oldcopy = clone $this;
2291  $this->fk_availability = $id;
2292  $this->availability_id = $id;
2293  }
2294 
2295  if (!$notrigger && empty($error)) {
2296  // Call trigger
2297  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2298  if ($result < 0) {
2299  $error++;
2300  }
2301  // End call triggers
2302  }
2303 
2304  if (!$error) {
2305  $this->db->commit();
2306  return 1;
2307  } else {
2308  foreach ($this->errors as $errmsg) {
2309  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2310  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2311  }
2312  $this->db->rollback();
2313  return -1 * $error;
2314  }
2315  } else {
2316  $error_str = 'Propal status do not meet requirement '.$this->statut;
2317  dol_syslog(__METHOD__.$error_str, LOG_ERR);
2318  $this->error = $error_str;
2319  $this->errors[] = $this->error;
2320  return -2;
2321  }
2322  }
2323 
2324  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2333  public function set_demand_reason($user, $id, $notrigger = 0)
2334  {
2335  // phpcs:enable
2336  if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) {
2337  $error = 0;
2338 
2339  $this->db->begin();
2340 
2341  $sql = "UPDATE ".MAIN_DB_PREFIX."propal ";
2342  $sql .= " SET fk_input_reason = ".((int) $id);
2343  $sql .= " WHERE rowid = ".((int) $this->id);
2344 
2345  dol_syslog(__METHOD__, LOG_DEBUG);
2346  $resql = $this->db->query($sql);
2347  if (!$resql) {
2348  $this->errors[] = $this->db->error();
2349  $error++;
2350  }
2351 
2352 
2353  if (!$error) {
2354  $this->oldcopy = clone $this;
2355  $this->fk_input_reason = $id;
2356  $this->demand_reason_id = $id;
2357  }
2358 
2359 
2360  if (!$notrigger && empty($error)) {
2361  // Call trigger
2362  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2363  if ($result < 0) {
2364  $error++;
2365  }
2366  // End call triggers
2367  }
2368 
2369  if (!$error) {
2370  $this->db->commit();
2371  return 1;
2372  } else {
2373  foreach ($this->errors as $errmsg) {
2374  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2375  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2376  }
2377  $this->db->rollback();
2378  return -1 * $error;
2379  }
2380  } else {
2381  $error_str = 'Propal status do not meet requirement '.$this->statut;
2382  dol_syslog(__METHOD__.$error_str, LOG_ERR);
2383  $this->error = $error_str;
2384  $this->errors[] = $this->error;
2385  return -2;
2386  }
2387  }
2388 
2389  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2398  public function set_ref_client($user, $ref_client, $notrigger = 0)
2399  {
2400  // phpcs:enable
2401  if (!empty($user->rights->propal->creer)) {
2402  $error = 0;
2403 
2404  $this->db->begin();
2405 
2406  $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET ref_client = ".(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
2407  $sql .= " WHERE rowid = ".((int) $this->id);
2408 
2409  dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2410  $resql = $this->db->query($sql);
2411  if (!$resql) {
2412  $this->errors[] = $this->db->error();
2413  $error++;
2414  }
2415 
2416  if (!$error) {
2417  $this->oldcopy = clone $this;
2418  $this->ref_client = $ref_client;
2419  }
2420 
2421  if (!$notrigger && empty($error)) {
2422  // Call trigger
2423  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2424  if ($result < 0) {
2425  $error++;
2426  }
2427  // End call triggers
2428  }
2429 
2430  if (!$error) {
2431  $this->db->commit();
2432  return 1;
2433  } else {
2434  foreach ($this->errors as $errmsg) {
2435  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2436  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2437  }
2438  $this->db->rollback();
2439  return -1 * $error;
2440  }
2441  }
2442 
2443  return -1;
2444  }
2445 
2446  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2455  public function set_remise_percent($user, $remise, $notrigger = 0)
2456  {
2457  // phpcs:enable
2458  $remise = trim($remise) ?trim($remise) : 0;
2459 
2460  if (!empty($user->rights->propal->creer)) {
2461  $remise = price2num($remise, 2);
2462 
2463  $error = 0;
2464 
2465  $this->db->begin();
2466 
2467  $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".((float) $remise);
2468  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
2469 
2470  dol_syslog(__METHOD__, LOG_DEBUG);
2471  $resql = $this->db->query($sql);
2472  if (!$resql) {
2473  $this->errors[] = $this->db->error();
2474  $error++;
2475  }
2476 
2477  if (!$error) {
2478  $this->oldcopy = clone $this;
2479  $this->remise_percent = $remise;
2480  $this->update_price(1);
2481  }
2482 
2483  if (!$notrigger && empty($error)) {
2484  // Call trigger
2485  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2486  if ($result < 0) {
2487  $error++;
2488  }
2489  // End call triggers
2490  }
2491 
2492  if (!$error) {
2493  $this->db->commit();
2494  return 1;
2495  } else {
2496  foreach ($this->errors as $errmsg) {
2497  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2498  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2499  }
2500  $this->db->rollback();
2501  return -1 * $error;
2502  }
2503  }
2504 
2505  return -1;
2506  }
2507 
2508 
2509  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2518  public function set_remise_absolue($user, $remise, $notrigger = 0)
2519  {
2520  // phpcs:enable
2521  if (empty($remise)) {
2522  $remise = 0;
2523  }
2525 
2526  if (!empty($user->rights->propal->creer)) {
2527  $error = 0;
2528 
2529  $this->db->begin();
2530 
2531  $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2532  $sql .= " SET remise_absolue = ".((float) $remise);
2533  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
2534 
2535  dol_syslog(__METHOD__, LOG_DEBUG);
2536  $resql = $this->db->query($sql);
2537  if (!$resql) {
2538  $this->errors[] = $this->db->error();
2539  $error++;
2540  }
2541 
2542  if (!$error) {
2543  $this->oldcopy = clone $this;
2544  $this->update_price(1);
2545  }
2546 
2547  if (!$notrigger && empty($error)) {
2548  // Call trigger
2549  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2550  if ($result < 0) {
2551  $error++;
2552  }
2553  // End call triggers
2554  }
2555 
2556  if (!$error) {
2557  $this->db->commit();
2558  return 1;
2559  } else {
2560  foreach ($this->errors as $errmsg) {
2561  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2562  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2563  }
2564  $this->db->rollback();
2565  return -1 * $error;
2566  }
2567  }
2568 
2569  return -1;
2570  }
2571 
2572 
2573 
2583  public function reopen($user, $status, $note = '', $notrigger = 0)
2584  {
2585  $error = 0;
2586 
2587  $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2588  $sql .= " SET fk_statut = ".((int) $status).",";
2589  if (!empty($note)) {
2590  $sql .= " note_private = '".$this->db->escape($note)."',";
2591  }
2592  $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
2593  $sql .= " WHERE rowid = ".((int) $this->id);
2594 
2595  $this->db->begin();
2596 
2597  dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
2598  $resql = $this->db->query($sql);
2599  if (!$resql) {
2600  $error++;
2601  $this->errors[] = "Error ".$this->db->lasterror();
2602  }
2603  if (!$error) {
2604  if (!$notrigger) {
2605  // Call trigger
2606  $result = $this->call_trigger('PROPAL_REOPEN', $user);
2607  if ($result < 0) {
2608  $error++;
2609  }
2610  // End call triggers
2611  }
2612  }
2613 
2614  // Commit or rollback
2615  if ($error) {
2616  if (!empty($this->errors)) {
2617  foreach ($this->errors as $errmsg) {
2618  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2619  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2620  }
2621  }
2622  $this->db->rollback();
2623  return -1 * $error;
2624  } else {
2625  $this->statut = $status;
2626  $this->status = $status;
2627 
2628  $this->db->commit();
2629  return 1;
2630  }
2631  }
2632 
2642  public function closeProposal($user, $status, $note = '', $notrigger = 0)
2643  {
2644  global $langs,$conf;
2645 
2646  $error = 0;
2647  $now = dol_now();
2648 
2649  $this->db->begin();
2650 
2651  $newprivatenote = dol_concatdesc($this->note_private, $note);
2652 
2653  if (empty($conf->global->PROPALE_KEEP_OLD_SIGNATURE_INFO)) {
2654  $date_signature = $now;
2655  $fk_user_signature = $user->id;
2656  } else {
2657  $this->info($this->id);
2658  if (!isset($this->date_signature) || $this->date_signature == '') {
2659  $date_signature = $now;
2660  $fk_user_signature = $user->id;
2661  } else {
2662  $date_signature = $this->date_signature;
2663  $fk_user_signature = $this->user_signature->id;
2664  }
2665  }
2666 
2667  $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2668  $sql .= " SET fk_statut = ".((int) $status).", note_private = '".$this->db->escape($newprivatenote)."', date_signature='".$this->db->idate($date_signature)."', fk_user_signature=".$fk_user_signature;
2669  $sql .= " WHERE rowid = ".((int) $this->id);
2670 
2671  $resql = $this->db->query($sql);
2672  if ($resql) {
2673  // Status self::STATUS_REFUSED by default
2674  $modelpdf = !empty($conf->global->PROPALE_ADDON_PDF_ODT_CLOSED) ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->model_pdf;
2675  $trigger_name = 'PROPAL_CLOSE_REFUSED'; // used later in call_trigger()
2676 
2677  if ($status == self::STATUS_SIGNED) { // Status self::STATUS_SIGNED
2678  $trigger_name = 'PROPAL_CLOSE_SIGNED'; // used later in call_trigger()
2679  $modelpdf = !empty($conf->global->PROPALE_ADDON_PDF_ODT_TOBILL) ? $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL : $this->model_pdf;
2680 
2681  // The connected company is classified as a client
2682  $soc=new Societe($this->db);
2683  $soc->id = $this->socid;
2684  $result = $soc->set_as_client();
2685 
2686  if ($result < 0) {
2687  $this->error=$this->db->lasterror();
2688  $this->db->rollback();
2689  return -2;
2690  }
2691  }
2692 
2693  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
2694  // Define output language
2695  $outputlangs = $langs;
2696  if (getDolGlobalInt('MAIN_MULTILANGS')) {
2697  $outputlangs = new Translate("", $conf);
2698  $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2699  $outputlangs->setDefaultLang($newlang);
2700  }
2701 
2702  // PDF
2703  $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
2704  $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
2705  $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
2706 
2707  //$ret=$object->fetch($id); // Reload to get new records
2708  $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2709  }
2710 
2711  if (!$error) {
2712  $this->oldcopy= clone $this;
2713  $this->statut = $status;
2714  $this->status = $status;
2715  $this->date_signature = $date_signature;
2716  $this->note_private = $newprivatenote;
2717  }
2718 
2719  if (!$notrigger && empty($error)) {
2720  // Call trigger
2721  $result=$this->call_trigger($trigger_name, $user);
2722  if ($result < 0) {
2723  $error++;
2724  }
2725  // End call triggers
2726  }
2727 
2728  if (!$error ) {
2729  $this->db->commit();
2730  return 1;
2731  } else {
2732  $this->statut = $this->oldcopy->statut;
2733  $this->status = $this->oldcopy->statut;
2734  $this->date_signature = $this->oldcopy->date_signature;
2735  $this->note_private = $this->oldcopy->note_private;
2736 
2737  $this->db->rollback();
2738  return -1;
2739  }
2740  } else {
2741  $this->error = $this->db->lasterror();
2742  $this->db->rollback();
2743  return -1;
2744  }
2745  }
2746 
2755  public function classifyBilled(User $user, $notrigger = 0, $note = '')
2756  {
2757  global $conf, $langs;
2758 
2759  $error = 0;
2760 
2761  $now = dol_now();
2762  $num = 0;
2763 
2764  $triggerName = 'PROPAL_CLASSIFY_BILLED';
2765 
2766  $this->db->begin();
2767 
2768  $newprivatenote = dol_concatdesc($this->note_private, $note);
2769 
2770  $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED.", ";
2771  $sql .= " note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".((int) $user->id);
2772  $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_SIGNED);
2773 
2774  dol_syslog(__METHOD__, LOG_DEBUG);
2775  $resql = $this->db->query($sql);
2776  if (!$resql) {
2777  $this->errors[] = $this->db->error();
2778  $error++;
2779  } else {
2780  $num = $this->db->affected_rows($resql);
2781  }
2782 
2783  if (!$error) {
2784  $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->model_pdf;
2785 
2786  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
2787  // Define output language
2788  $outputlangs = $langs;
2789  if (getDolGlobalInt('MAIN_MULTILANGS')) {
2790  $outputlangs = new Translate("", $conf);
2791  $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2792  $outputlangs->setDefaultLang($newlang);
2793  }
2794 
2795  // PDF
2796  $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
2797  $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
2798  $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
2799 
2800  //$ret=$object->fetch($id); // Reload to get new records
2801  $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2802  }
2803 
2804  $this->oldcopy = clone $this;
2805  $this->statut = self::STATUS_BILLED;
2806  $this->date_cloture = $now;
2807  $this->note_private = $newprivatenote;
2808  }
2809 
2810  if (!$notrigger && empty($error)) {
2811  // Call trigger
2812  $result = $this->call_trigger($triggerName, $user);
2813  if ($result < 0) {
2814  $error++;
2815  }
2816  // End call triggers
2817  }
2818 
2819  if (!$error) {
2820  $this->db->commit();
2821  return $num;
2822  } else {
2823  foreach ($this->errors as $errmsg) {
2824  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2825  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2826  }
2827  $this->db->rollback();
2828  return -1 * $error;
2829  }
2830  }
2831 
2832  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2840  public function setDraft($user, $notrigger = 0)
2841  {
2842  // phpcs:enable
2843  $error = 0;
2844 
2845  // Protection
2846  if ($this->statut <= self::STATUS_DRAFT) {
2847  return 0;
2848  }
2849 
2850  dol_syslog(get_class($this)."::setDraft", LOG_DEBUG);
2851 
2852  $this->db->begin();
2853 
2854  $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
2855  $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2856  $sql .= ", online_sign_ip = NULL , online_sign_name = NULL";
2857  $sql .= " WHERE rowid = ".((int) $this->id);
2858 
2859  $resql = $this->db->query($sql);
2860  if (!$resql) {
2861  $this->errors[] = $this->db->error();
2862  $error++;
2863  }
2864 
2865  if (!$error) {
2866  $this->oldcopy = clone $this;
2867  }
2868 
2869  if (!$notrigger && empty($error)) {
2870  // Call trigger
2871  $result = $this->call_trigger('PROPAL_MODIFY', $user);
2872  if ($result < 0) {
2873  $error++;
2874  }
2875  // End call triggers
2876  }
2877 
2878  if (!$error) {
2879  $this->statut = self::STATUS_DRAFT;
2880  $this->brouillon = 1;
2881 
2882  $this->db->commit();
2883  return 1;
2884  } else {
2885  foreach ($this->errors as $errmsg) {
2886  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2887  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2888  }
2889  $this->db->rollback();
2890  return -1 * $error;
2891  }
2892  }
2893 
2894 
2895  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2909  public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datep', $sortorder = 'DESC')
2910  {
2911  // phpcs:enable
2912  global $user;
2913 
2914  $ga = array();
2915 
2916  $sql = "SELECT s.rowid, s.nom as name, s.client,";
2917  $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
2918  $sql .= " p.datep as dp, p.fin_validite as datelimite";
2919  if (empty($user->rights->societe->client->voir) && !$socid) {
2920  $sql .= ", sc.fk_soc, sc.fk_user";
2921  }
2922  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
2923  if (empty($user->rights->societe->client->voir) && !$socid) {
2924  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2925  }
2926  $sql .= " WHERE p.entity IN (".getEntity('propal').")";
2927  $sql .= " AND p.fk_soc = s.rowid";
2928  $sql .= " AND p.fk_statut = c.id";
2929  if (empty($user->rights->societe->client->voir) && !$socid) { //restriction
2930  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2931  }
2932  if ($socid) {
2933  $sql .= " AND s.rowid = ".((int) $socid);
2934  }
2935  if ($draft) {
2936  $sql .= " AND p.fk_statut = ".self::STATUS_DRAFT;
2937  }
2938  if ($notcurrentuser > 0) {
2939  $sql .= " AND p.fk_user_author <> ".((int) $user->id);
2940  }
2941  $sql .= $this->db->order($sortfield, $sortorder);
2942  $sql .= $this->db->plimit($limit, $offset);
2943 
2944  $result = $this->db->query($sql);
2945  if ($result) {
2946  $num = $this->db->num_rows($result);
2947  if ($num) {
2948  $i = 0;
2949  while ($i < $num) {
2950  $obj = $this->db->fetch_object($result);
2951 
2952  if ($shortlist == 1) {
2953  $ga[$obj->propalid] = $obj->ref;
2954  } elseif ($shortlist == 2) {
2955  $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
2956  } else {
2957  $ga[$i]['id'] = $obj->propalid;
2958  $ga[$i]['ref'] = $obj->ref;
2959  $ga[$i]['name'] = $obj->name;
2960  }
2961 
2962  $i++;
2963  }
2964  }
2965  return $ga;
2966  } else {
2967  dol_print_error($this->db);
2968  return -1;
2969  }
2970  }
2971 
2977  public function getInvoiceArrayList()
2978  {
2979  return $this->InvoiceArrayList($this->id);
2980  }
2981 
2982  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2989  public function InvoiceArrayList($id)
2990  {
2991  // phpcs:enable
2992  $ga = array();
2993  $linkedInvoices = array();
2994 
2995  $this->fetchObjectLinked($id, $this->element);
2996  foreach ($this->linkedObjectsIds as $objecttype => $objectid) {
2997  // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n
2998  // On parcourt donc une liste d'objets en tant qu'objet unique
2999  foreach ($objectid as $key => $object) {
3000  // Cas des factures liees directement
3001  if ($objecttype == 'facture') {
3002  $linkedInvoices[] = $object;
3003  } else {
3004  // Cas des factures liees par un autre objet (ex: commande)
3005  $this->fetchObjectLinked($object, $objecttype);
3006  foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) {
3007  foreach ($subobjectid as $subkey => $subobject) {
3008  if ($subobjecttype == 'facture') {
3009  $linkedInvoices[] = $subobject;
3010  }
3011  }
3012  }
3013  }
3014  }
3015  }
3016 
3017  if (count($linkedInvoices) > 0) {
3018  $sql = "SELECT rowid as facid, ref, total_ht as total, datef as df, fk_user_author, fk_statut, paye";
3019  $sql .= " FROM ".MAIN_DB_PREFIX."facture";
3020  $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $linkedInvoices)).")";
3021 
3022  dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
3023  $resql = $this->db->query($sql);
3024 
3025  if ($resql) {
3026  $tab_sqlobj = array();
3027  $nump = $this->db->num_rows($resql);
3028  for ($i = 0; $i < $nump; $i++) {
3029  $sqlobj = $this->db->fetch_object($resql);
3030  $tab_sqlobj[] = $sqlobj;
3031  }
3032  $this->db->free($resql);
3033 
3034  $nump = count($tab_sqlobj);
3035 
3036  if ($nump) {
3037  $i = 0;
3038  while ($i < $nump) {
3039  $obj = array_shift($tab_sqlobj);
3040 
3041  $ga[$i] = $obj;
3042 
3043  $i++;
3044  }
3045  }
3046  return $ga;
3047  } else {
3048  return -1;
3049  }
3050  } else {
3051  return $ga;
3052  }
3053  }
3054 
3062  public function delete($user, $notrigger = 0)
3063  {
3064  global $conf;
3065  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3066 
3067  $error = 0;
3068 
3069  $this->db->begin();
3070 
3071  if (!$notrigger) {
3072  // Call trigger
3073  $result = $this->call_trigger('PROPAL_DELETE', $user);
3074  if ($result < 0) {
3075  $error++;
3076  }
3077  // End call triggers
3078  }
3079 
3080  // Delete extrafields of lines and lines
3081  if (!$error && !empty($this->table_element_line)) {
3082  $tabletodelete = $this->table_element_line;
3083  $sqlef = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete."_extrafields WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id).")";
3084  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
3085  if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
3086  $error++;
3087  $this->error = $this->db->lasterror();
3088  $this->errors[] = $this->error;
3089  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3090  }
3091  }
3092 
3093  if (!$error) {
3094  // Delete linked object
3095  $res = $this->deleteObjectLinked();
3096  if ($res < 0) {
3097  $error++;
3098  }
3099  }
3100 
3101  if (!$error) {
3102  // Delete linked contacts
3103  $res = $this->delete_linked_contact();
3104  if ($res < 0) {
3105  $error++;
3106  }
3107  }
3108 
3109  // Removed extrafields of object
3110  if (!$error) {
3111  $result = $this->deleteExtraFields();
3112  if ($result < 0) {
3113  $error++;
3114  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3115  }
3116  }
3117 
3118  // Delete main record
3119  if (!$error) {
3120  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
3121  $res = $this->db->query($sql);
3122  if (!$res) {
3123  $error++;
3124  $this->error = $this->db->lasterror();
3125  $this->errors[] = $this->error;
3126  dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3127  }
3128  }
3129 
3130  // Delete record into ECM index and physically
3131  if (!$error) {
3132  $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
3133  if (!$res) {
3134  $error++;
3135  }
3136  }
3137 
3138  if (!$error) {
3139  // We remove directory
3140  $ref = dol_sanitizeFileName($this->ref);
3141  if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref)) {
3142  $dir = $conf->propal->multidir_output[$this->entity]."/".$ref;
3143  $file = $dir."/".$ref.".pdf";
3144  if (file_exists($file)) {
3145  dol_delete_preview($this);
3146 
3147  if (!dol_delete_file($file, 0, 0, 0, $this)) {
3148  $this->error = 'ErrorFailToDeleteFile';
3149  $this->errors[] = $this->error;
3150  $this->db->rollback();
3151  return 0;
3152  }
3153  }
3154  if (file_exists($dir)) {
3155  $res = @dol_delete_dir_recursive($dir);
3156  if (!$res) {
3157  $this->error = 'ErrorFailToDeleteDir';
3158  $this->errors[] = $this->error;
3159  $this->db->rollback();
3160  return 0;
3161  }
3162  }
3163  }
3164  }
3165 
3166  if (!$error) {
3167  dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
3168  $this->db->commit();
3169  return 1;
3170  } else {
3171  $this->db->rollback();
3172  return -1;
3173  }
3174  }
3175 
3184  public function availability($availability_id, $notrigger = 0)
3185  {
3186  global $user;
3187 
3188  if ($this->statut >= self::STATUS_DRAFT) {
3189  $error = 0;
3190 
3191  $this->db->begin();
3192 
3193  $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
3194  $sql .= ' SET fk_availability = '.((int) $availability_id);
3195  $sql .= ' WHERE rowid='.((int) $this->id);
3196 
3197  dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
3198  $resql = $this->db->query($sql);
3199  if (!$resql) {
3200  $this->errors[] = $this->db->error();
3201  $error++;
3202  }
3203 
3204  if (!$error) {
3205  $this->oldcopy = clone $this;
3206  $this->availability_id = $availability_id;
3207  }
3208 
3209  if (!$notrigger && empty($error)) {
3210  // Call trigger
3211  $result = $this->call_trigger('PROPAL_MODIFY', $user);
3212  if ($result < 0) {
3213  $error++;
3214  }
3215  // End call triggers
3216  }
3217 
3218  if (!$error) {
3219  $this->db->commit();
3220  return 1;
3221  } else {
3222  foreach ($this->errors as $errmsg) {
3223  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3224  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3225  }
3226  $this->db->rollback();
3227  return -1 * $error;
3228  }
3229  } else {
3230  $error_str = 'Propal status do not meet requirement '.$this->statut;
3231  dol_syslog(__METHOD__.$error_str, LOG_ERR);
3232  $this->error = $error_str;
3233  $this->errors[] = $this->error;
3234  return -2;
3235  }
3236  }
3237 
3238  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3247  public function demand_reason($demand_reason_id, $notrigger = 0)
3248  {
3249  // phpcs:enable
3250  global $user;
3251 
3252  if ($this->statut >= self::STATUS_DRAFT) {
3253  $error = 0;
3254 
3255  $this->db->begin();
3256 
3257  $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal';
3258  $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
3259  $sql .= ' WHERE rowid='.((int) $this->id);
3260 
3261  dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
3262  $resql = $this->db->query($sql);
3263  if (!$resql) {
3264  $this->errors[] = $this->db->error();
3265  $error++;
3266  }
3267 
3268  if (!$error) {
3269  $this->oldcopy = clone $this;
3270  $this->demand_reason_id = $demand_reason_id;
3271  }
3272 
3273  if (!$notrigger && empty($error)) {
3274  // Call trigger
3275  $result = $this->call_trigger('PROPAL_MODIFY', $user);
3276  if ($result < 0) {
3277  $error++;
3278  }
3279  // End call triggers
3280  }
3281 
3282  if (!$error) {
3283  $this->db->commit();
3284  return 1;
3285  } else {
3286  foreach ($this->errors as $errmsg) {
3287  dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3288  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3289  }
3290  $this->db->rollback();
3291  return -1 * $error;
3292  }
3293  } else {
3294  $error_str = 'Propal status do not meet requirement '.$this->statut;
3295  dol_syslog(__METHOD__.$error_str, LOG_ERR);
3296  $this->error = $error_str;
3297  $this->errors[] = $this->error;
3298  return -2;
3299  }
3300  }
3301 
3302 
3309  public function info($id)
3310  {
3311  $sql = "SELECT c.rowid, ";
3312  $sql .= " c.datec, c.date_valid as datev, c.date_signature, c.date_cloture,";
3313  $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_signature, c.fk_user_cloture";
3314  $sql .= " FROM ".MAIN_DB_PREFIX."propal as c";
3315  $sql .= " WHERE c.rowid = ".((int) $id);
3316 
3317  $result = $this->db->query($sql);
3318 
3319  if ($result) {
3320  if ($this->db->num_rows($result)) {
3321  $obj = $this->db->fetch_object($result);
3322 
3323  $this->id = $obj->rowid;
3324 
3325  $this->date_creation = $this->db->jdate($obj->datec);
3326  $this->date_validation = $this->db->jdate($obj->datev);
3327  $this->date_signature = $this->db->jdate($obj->date_signature);
3328  $this->date_cloture = $this->db->jdate($obj->date_cloture);
3329 
3330  $cuser = new User($this->db);
3331  $cuser->fetch($obj->fk_user_author);
3332  $this->user_creation = $cuser;
3333 
3334  if ($obj->fk_user_valid) {
3335  $vuser = new User($this->db);
3336  $vuser->fetch($obj->fk_user_valid);
3337  $this->user_validation = $vuser;
3338  }
3339 
3340  if ($obj->fk_user_signature) {
3341  $user_signature = new User($this->db);
3342  $user_signature->fetch($obj->fk_user_signature);
3343  $this->user_signature = $user_signature;
3344  }
3345 
3346  if ($obj->fk_user_cloture) {
3347  $cluser = new User($this->db);
3348  $cluser->fetch($obj->fk_user_cloture);
3349  $this->user_cloture = $cluser;
3350  }
3351  }
3352  $this->db->free($result);
3353  } else {
3354  dol_print_error($this->db);
3355  }
3356  }
3357 
3358 
3365  public function getLibStatut($mode = 0)
3366  {
3367  return $this->LibStatut($this->statut, $mode);
3368  }
3369 
3370  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3378  public function LibStatut($status, $mode = 1)
3379  {
3380  // phpcs:enable
3381  global $conf, $hookmanager;
3382 
3383  // Init/load array of translation of status
3384  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3385  global $langs;
3386  $langs->load("propal");
3387  $this->labelStatus[0] = $langs->transnoentitiesnoconv("PropalStatusDraft");
3388  $this->labelStatus[1] = $langs->transnoentitiesnoconv("PropalStatusValidated");
3389  $this->labelStatus[2] = $langs->transnoentitiesnoconv("PropalStatusSigned");
3390  $this->labelStatus[3] = $langs->transnoentitiesnoconv("PropalStatusNotSigned");
3391  $this->labelStatus[4] = $langs->transnoentitiesnoconv("PropalStatusBilled");
3392  $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("PropalStatusDraftShort");
3393  $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("PropalStatusValidatedShort");
3394  $this->labelStatusShort[2] = $langs->transnoentitiesnoconv("PropalStatusSignedShort");
3395  $this->labelStatusShort[3] = $langs->transnoentitiesnoconv("PropalStatusNotSignedShort");
3396  $this->labelStatusShort[4] = $langs->transnoentitiesnoconv("PropalStatusBilledShort");
3397  }
3398 
3399  $statusType = '';
3400  if ($status == self::STATUS_DRAFT) {
3401  $statusType = 'status0';
3402  } elseif ($status == self::STATUS_VALIDATED) {
3403  $statusType = 'status1';
3404  } elseif ($status == self::STATUS_SIGNED) {
3405  $statusType = 'status4';
3406  } elseif ($status == self::STATUS_NOTSIGNED) {
3407  $statusType = 'status9';
3408  } elseif ($status == self::STATUS_BILLED) {
3409  $statusType = 'status6';
3410  }
3411 
3412 
3413  $parameters = array('status' => $status, 'mode' => $mode);
3414  $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
3415 
3416  if ($reshook > 0) {
3417  return $hookmanager->resPrint;
3418  }
3419 
3420  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3421  }
3422 
3423 
3424  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3432  public function load_board($user, $mode)
3433  {
3434  // phpcs:enable
3435  global $conf, $langs;
3436 
3437  $clause = " WHERE";
3438 
3439  $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin, p.total_ht";
3440  $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
3441  if (empty($user->rights->societe->client->voir) && !$user->socid) {
3442  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3443  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3444  $clause = " AND";
3445  }
3446  $sql .= $clause." p.entity IN (".getEntity('propal').")";
3447  if ($mode == 'opened') {
3448  $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3449  }
3450  if ($mode == 'signed') {
3451  $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED;
3452  }
3453  if ($user->socid) {
3454  $sql .= " AND p.fk_soc = ".((int) $user->socid);
3455  }
3456 
3457  $resql = $this->db->query($sql);
3458  if ($resql) {
3459  $langs->load("propal");
3460  $now = dol_now();
3461 
3462  $delay_warning = 0;
3463  $status = 0;
3464  $label = $labelShort = '';
3465  if ($mode == 'opened') {
3466  $delay_warning = $conf->propal->cloture->warning_delay;
3467  $status = self::STATUS_VALIDATED;
3468  $label = $langs->transnoentitiesnoconv("PropalsToClose");
3469  $labelShort = $langs->transnoentitiesnoconv("ToAcceptRefuse");
3470  }
3471  if ($mode == 'signed') {
3472  $delay_warning = $conf->propal->facturation->warning_delay;
3473  $status = self::STATUS_SIGNED;
3474  $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered
3475  $labelShort = $langs->trans("ToBill");
3476  }
3477 
3478  $response = new WorkboardResponse();
3479  $response->warning_delay = $delay_warning / 60 / 60 / 24;
3480  $response->label = $label;
3481  $response->labelShort = $labelShort;
3482  $response->url = DOL_URL_ROOT.'/comm/propal/list.php?search_status='.$status.'&mainmenu=commercial&leftmenu=propals';
3483  $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?search_status='.$status.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc';
3484  $response->img = img_object('', "propal");
3485 
3486  // This assignment in condition is not a bug. It allows walking the results.
3487  while ($obj = $this->db->fetch_object($resql)) {
3488  $response->nbtodo++;
3489  $response->total += $obj->total_ht;
3490 
3491  if ($mode == 'opened') {
3492  $datelimit = $this->db->jdate($obj->datefin);
3493  if ($datelimit < ($now - $delay_warning)) {
3494  $response->nbtodolate++;
3495  }
3496  }
3497  // TODO Definir regle des propales a facturer en retard
3498  // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
3499  }
3500 
3501  return $response;
3502  } else {
3503  $this->error = $this->db->error();
3504  return -1;
3505  }
3506  }
3507 
3508 
3516  public function initAsSpecimen()
3517  {
3518  global $conf, $langs;
3519 
3520  // Load array of products prodids
3521  $num_prods = 0;
3522  $prodids = array();
3523  $sql = "SELECT rowid";
3524  $sql .= " FROM ".MAIN_DB_PREFIX."product";
3525  $sql .= " WHERE entity IN (".getEntity('product').")";
3526  $sql .= $this->db->plimit(100);
3527 
3528  $resql = $this->db->query($sql);
3529  if ($resql) {
3530  $num_prods = $this->db->num_rows($resql);
3531  $i = 0;
3532  while ($i < $num_prods) {
3533  $i++;
3534  $row = $this->db->fetch_row($resql);
3535  $prodids[$i] = $row[0];
3536  }
3537  }
3538 
3539  // Initialise parametres
3540  $this->id = 0;
3541  $this->ref = 'SPECIMEN';
3542  $this->ref_client = 'NEMICEPS';
3543  $this->specimen = 1;
3544  $this->socid = 1;
3545  $this->date = time();
3546  $this->fin_validite = $this->date + 3600 * 24 * 30;
3547  $this->cond_reglement_id = 1;
3548  $this->cond_reglement_code = 'RECEP';
3549  $this->mode_reglement_id = 7;
3550  $this->mode_reglement_code = 'CHQ';
3551  $this->availability_id = 1;
3552  $this->availability_code = 'AV_NOW';
3553  $this->demand_reason_id = 1;
3554  $this->demand_reason_code = 'SRC_00';
3555  $this->note_public = 'This is a comment (public)';
3556  $this->note_private = 'This is a comment (private)';
3557 
3558  $this->multicurrency_tx = 1;
3559  $this->multicurrency_code = $conf->currency;
3560 
3561  // Lines
3562  $nbp = 5;
3563  $xnbp = 0;
3564  while ($xnbp < $nbp) {
3565  $line = new PropaleLigne($this->db);
3566  $line->desc = $langs->trans("Description")." ".$xnbp;
3567  $line->qty = 1;
3568  $line->subprice = 100;
3569  $line->price = 100;
3570  $line->tva_tx = 20;
3571  $line->localtax1_tx = 0;
3572  $line->localtax2_tx = 0;
3573  if ($xnbp == 2) {
3574  $line->total_ht = 50;
3575  $line->total_ttc = 60;
3576  $line->total_tva = 10;
3577  $line->remise_percent = 50;
3578  } else {
3579  $line->total_ht = 100;
3580  $line->total_ttc = 120;
3581  $line->total_tva = 20;
3582  $line->remise_percent = 00;
3583  }
3584 
3585  if ($num_prods > 0) {
3586  $prodid = mt_rand(1, $num_prods);
3587  $line->fk_product = $prodids[$prodid];
3588  $line->product_ref = 'SPECIMEN';
3589  }
3590 
3591  $this->lines[$xnbp] = $line;
3592 
3593  $this->total_ht += $line->total_ht;
3594  $this->total_tva += $line->total_tva;
3595  $this->total_ttc += $line->total_ttc;
3596 
3597  $xnbp++;
3598  }
3599  }
3600 
3601  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3607  public function load_state_board()
3608  {
3609  // phpcs:enable
3610  global $user;
3611 
3612  $this->nb = array();
3613  $clause = "WHERE";
3614 
3615  $sql = "SELECT count(p.rowid) as nb";
3616  $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
3617  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3618  if (empty($user->rights->societe->client->voir) && !$user->socid) {
3619  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
3620  $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3621  $clause = "AND";
3622  }
3623  $sql .= " ".$clause." p.entity IN (".getEntity('propal').")";
3624 
3625  $resql = $this->db->query($sql);
3626  if ($resql) {
3627  // This assignment in condition is not a bug. It allows walking the results.
3628  while ($obj = $this->db->fetch_object($resql)) {
3629  $this->nb["proposals"] = $obj->nb;
3630  }
3631  $this->db->free($resql);
3632  return 1;
3633  } else {
3634  dol_print_error($this->db);
3635  $this->error = $this->db->error();
3636  return -1;
3637  }
3638  }
3639 
3640 
3648  public function getNextNumRef($soc)
3649  {
3650  global $conf, $langs;
3651  $langs->load("propal");
3652 
3653  $classname = $conf->global->PROPALE_ADDON;
3654 
3655  if (!empty($classname)) {
3656  $mybool = false;
3657 
3658  $file = $classname.".php";
3659 
3660  // Include file with class
3661  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3662  foreach ($dirmodels as $reldir) {
3663  $dir = dol_buildpath($reldir."core/modules/propale/");
3664 
3665  // Load file with numbering class (if found)
3666  $mybool |= @include_once $dir.$file;
3667  }
3668 
3669  if (!$mybool) {
3670  dol_print_error('', "Failed to include file ".$file);
3671  return '';
3672  }
3673 
3674  $obj = new $classname();
3675  $numref = "";
3676  $numref = $obj->getNextValue($soc, $this);
3677 
3678  if ($numref != "") {
3679  return $numref;
3680  } else {
3681  $this->error = $obj->error;
3682  //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3683  return "";
3684  }
3685  } else {
3686  $langs->load("errors");
3687  print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Proposal"));
3688  return "";
3689  }
3690  }
3691 
3698  public function getTooltipContentArray($params)
3699  {
3700  global $conf, $langs, $user;
3701 
3702  $datas = [];
3703 
3704  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
3705  return ['optimize' => $langs->trans("Proposal")];
3706  }
3707  if ($user->hasRight('propal', 'lire')) {
3708  $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Proposal").'</u>';
3709  if (isset($this->statut)) {
3710  $datas['status'] = ' '.$this->getLibStatut(5);
3711  }
3712  if (!empty($this->ref)) {
3713  $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3714  }
3715  if (!empty($this->ref_client)) {
3716  $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
3717  }
3718  if (!empty($this->total_ht)) {
3719  $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3720  }
3721  if (!empty($this->total_tva)) {
3722  $datas['vat'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3723  }
3724  if (!empty($this->total_ttc)) {
3725  $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3726  }
3727  if (!empty($this->date)) {
3728  $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
3729  }
3730  if (!empty($this->delivery_date)) {
3731  $datas['deliverydate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
3732  }
3733  }
3734 
3735  return $datas;
3736  }
3737 
3749  public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = -1)
3750  {
3751  global $langs, $conf, $user, $hookmanager;
3752 
3753  if (!empty($conf->dol_no_mouse_hover)) {
3754  $notooltip = 1; // Force disable tooltips
3755  }
3756 
3757  $result = '';
3758  $params = [
3759  'id' => $this->id,
3760  'objecttype' => $this->element,
3761  'option' => $option,
3762  ];
3763  $classfortooltip = 'classfortooltip';
3764  $dataparams = '';
3765  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3766  $classfortooltip = 'classforajaxtooltip';
3767  $dataparams = ' data-params='.json_encode($params);
3768  // $label = $langs->trans('Loading');
3769  }
3770  $label = implode($this->getTooltipContentArray($params));
3771 
3772  $url = '';
3773  if ($user->rights->propal->lire) {
3774  if ($option == '') {
3775  $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params;
3776  } elseif ($option == 'compta') { // deprecated
3777  $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params;
3778  } elseif ($option == 'expedition') {
3779  $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id.$get_params;
3780  } elseif ($option == 'document') {
3781  $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id.$get_params;
3782  }
3783 
3784  if ($option != 'nolink') {
3785  // Add param to save lastsearch_values or not
3786  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3787  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3788  $add_save_lastsearch_values = 1;
3789  }
3790  if ($add_save_lastsearch_values) {
3791  $url .= '&save_lastsearch_values=1';
3792  }
3793  }
3794  }
3795 
3796  $linkclose = '';
3797  if (empty($notooltip) && $user->hasRight('propal', 'lire')) {
3798  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
3799  $label = $langs->trans("Proposal");
3800  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
3801  }
3802  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
3803  $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
3804  }
3805 
3806  $linkstart = '<a href="'.$url.'"';
3807  $linkstart .= $linkclose.'>';
3808  $linkend = '</a>';
3809 
3810  $result .= $linkstart;
3811  if ($withpicto) {
3812  $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams.' class="'.(($withpicto != 2) ? 'paddingright ' : '').$classfortooltip.'"'), 0, 0, $notooltip ? 0 : 1);
3813  }
3814  if ($withpicto != 2) {
3815  $result .= $this->ref;
3816  }
3817  $result .= $linkend;
3818 
3819  if ($addlinktonotes >= 0) {
3820  $txttoshow = '';
3821 
3822  if ($addlinktonotes == 0) {
3823  if (!empty($this->note_private) || !empty($this->note_public)) {
3824  $txttoshow = $langs->trans('ViewPrivateNote');
3825  }
3826  } elseif ($addlinktonotes == 1) {
3827  if (!empty($this->note_private)) {
3828  $txttoshow .= ($user->socid > 0 ? '' : dol_string_nohtmltag($this->note_private, 1));
3829  }
3830  } elseif ($addlinktonotes == 2) {
3831  if (!empty($this->note_public)) {
3832  $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
3833  }
3834  } elseif ($addlinktonotes == 3) {
3835  if ($user->socid > 0) {
3836  if (!empty($this->note_public)) {
3837  $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
3838  }
3839  } else {
3840  if (!empty($this->note_public)) {
3841  $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
3842  }
3843  if (!empty($this->note_private)) {
3844  if (!empty($txttoshow)) {
3845  $txttoshow .= '<br><br>';
3846  }
3847  $txttoshow .= dol_string_nohtmltag($this->note_private, 1);
3848  }
3849  }
3850  }
3851 
3852  if ($txttoshow) {
3853  $result .= ' <span class="note inline-block">';
3854  $result .= '<a href="'.DOL_URL_ROOT.'/comm/propal/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($txttoshow).'">';
3855  $result .= img_picto('', 'note');
3856  $result .= '</a>';
3857  $result .= '</span>';
3858  }
3859  }
3860 
3861  global $action;
3862  $hookmanager->initHooks(array($this->element . 'dao'));
3863  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
3864  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3865  if ($reshook > 0) {
3866  $result = $hookmanager->resPrint;
3867  } else {
3868  $result .= $hookmanager->resPrint;
3869  }
3870  return $result;
3871  }
3872 
3879  public function getLinesArray($filters = '')
3880  {
3881  return $this->fetch_lines(0, 0, $filters);
3882  }
3883 
3895  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3896  {
3897  global $conf, $langs;
3898 
3899  $langs->load("propale");
3900  $outputlangs->load("products");
3901 
3902  if (!dol_strlen($modele)) {
3903  $modele = 'azur';
3904 
3905  if ($this->model_pdf) {
3906  $modele = $this->model_pdf;
3907  } elseif (!empty($conf->global->PROPALE_ADDON_PDF)) {
3908  $modele = $conf->global->PROPALE_ADDON_PDF;
3909  }
3910  }
3911 
3912  $modelpath = "core/modules/propale/doc/";
3913 
3914  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3915  }
3916 
3925  public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
3926  {
3927  $tables = array(
3928  'propal'
3929  );
3930 
3931  return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
3932  }
3933 
3942  public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
3943  {
3944  $tables = array(
3945  'propaldet'
3946  );
3947 
3948  return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
3949  }
3950 
3958  public function getKanbanView($option = '', $arraydata = null)
3959  {
3960  global $langs;
3961  $return = '<div class="box-flex-item box-flex-grow-zero">';
3962  $return .= '<div class="info-box info-box-sm">';
3963  $return .= '<span class="info-box-icon bg-infobox-action">';
3964  $return .= img_picto('', $this->picto);
3965  //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
3966  $return .= '</span>';
3967  $return .= '<div class="info-box-content">';
3968  $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
3969  if (property_exists($this, 'fk_project')) {
3970  $return .= '<span class="info-box-ref"> | '.$this->fk_project.'</span>';
3971  }
3972  if (property_exists($this, 'author')) {
3973  $return .= '<br><span class="info-box-label">'.$this->author.'</span>';
3974  }
3975  if (property_exists($this, 'total_ht')) {
3976  $return .='<br><span class="" >'.$langs->trans("AmountHT").' : </span><span class="info-box-label amount">'.price($this->total_ht).'</span>';
3977  }
3978  if (method_exists($this, 'getLibStatut')) {
3979  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
3980  }
3981  $return .= '</div>';
3982  $return .= '</div>';
3983  $return .= '</div>';
3984  return $return;
3985  }
3986 }
3987 
3992 {
3996  public $element = 'propaldet';
3997 
4001  public $table_element = 'propaldet';
4002 
4003  public $oldline;
4004 
4005  // From llx_propaldet
4006  public $fk_propal;
4007  public $fk_parent_line;
4008  public $desc; // Description ligne
4009  public $fk_product; // Id produit predefini
4020  public $product_type = Product::TYPE_PRODUCT;
4021 
4022  public $qty;
4023 
4024  public $tva_tx;
4025  public $vat_src_code;
4026 
4027  public $subprice;
4028  public $remise_percent;
4029  public $fk_remise_except;
4030 
4031  public $rang = 0;
4032 
4033  public $fk_fournprice;
4034  public $pa_ht;
4035  public $marge_tx;
4036  public $marque_tx;
4037 
4038  public $special_code; // Tag for special lines (exlusive tags)
4039  // 1: frais de port
4040  // 2: ecotaxe
4041  // 3: option line (when qty = 0)
4042 
4043  public $info_bits = 0; // Some other info:
4044  // Bit 0: 0 si TVA normal - 1 si TVA NPR
4045  // Bit 1: 0 ligne normale - 1 si ligne de remise fixe
4046 
4047  public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne
4048  public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne
4049  public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne
4050 
4055  public $remise;
4060  public $price;
4061 
4062  // From llx_product
4067  public $ref;
4072  public $product_ref;
4077  public $libelle;
4082  public $label;
4087  public $product_label;
4092  public $product_desc;
4093 
4098  public $product_tobatch;
4099 
4104  public $product_barcode;
4105 
4106  public $localtax1_tx; // Local tax 1
4107  public $localtax2_tx; // Local tax 2
4108  public $localtax1_type; // Local tax 1 type
4109  public $localtax2_type; // Local tax 2 type
4110  public $total_localtax1; // Line total local tax 1
4111  public $total_localtax2; // Line total local tax 2
4112 
4113  public $date_start;
4114  public $date_end;
4115 
4116  public $skip_update_total; // Skip update price total for special lines
4117 
4118  // Multicurrency
4119  public $fk_multicurrency;
4120  public $multicurrency_code;
4121  public $multicurrency_subprice;
4122  public $multicurrency_total_ht;
4123  public $multicurrency_total_tva;
4124  public $multicurrency_total_ttc;
4125 
4126 
4132  public function __construct($db)
4133  {
4134  $this->db = $db;
4135  }
4136 
4143  public function fetch($rowid)
4144  {
4145  $sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,';
4146  $sql .= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,';
4147  $sql .= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,';
4148  $sql .= ' pd.fk_unit,';
4149  $sql .= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,';
4150  $sql .= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc,';
4151  $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,';
4152  $sql .= ' pd.date_start, pd.date_end, pd.product_type';
4153  $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as pd';
4154  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid';
4155  $sql .= ' WHERE pd.rowid = '.((int) $rowid);
4156 
4157  $result = $this->db->query($sql);
4158  if ($result) {
4159  $objp = $this->db->fetch_object($result);
4160 
4161  if ($objp) {
4162  $this->id = $objp->rowid;
4163  $this->rowid = $objp->rowid; // deprecated
4164  $this->fk_propal = $objp->fk_propal;
4165  $this->fk_parent_line = $objp->fk_parent_line;
4166  $this->label = $objp->custom_label;
4167  $this->desc = $objp->description;
4168  $this->qty = $objp->qty;
4169  $this->price = $objp->price; // deprecated
4170  $this->subprice = $objp->subprice;
4171  $this->vat_src_code = $objp->vat_src_code;
4172  $this->tva_tx = $objp->tva_tx;
4173  $this->remise = $objp->remise; // deprecated
4174  $this->remise_percent = $objp->remise_percent;
4175  $this->fk_remise_except = $objp->fk_remise_except;
4176  $this->fk_product = $objp->fk_product;
4177  $this->info_bits = $objp->info_bits;
4178 
4179  $this->total_ht = $objp->total_ht;
4180  $this->total_tva = $objp->total_tva;
4181  $this->total_ttc = $objp->total_ttc;
4182 
4183  $this->fk_fournprice = $objp->fk_fournprice;
4184 
4185  $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
4186  $this->pa_ht = $marginInfos[0];
4187  $this->marge_tx = $marginInfos[1];
4188  $this->marque_tx = $marginInfos[2];
4189 
4190  $this->special_code = $objp->special_code;
4191  $this->product_type = $objp->product_type;
4192  $this->rang = $objp->rang;
4193 
4194  $this->ref = $objp->product_ref; // deprecated
4195  $this->product_ref = $objp->product_ref;
4196  $this->libelle = $objp->product_label; // deprecated
4197  $this->product_label = $objp->product_label;
4198  $this->product_desc = $objp->product_desc;
4199  $this->fk_unit = $objp->fk_unit;
4200 
4201  $this->date_start = $this->db->jdate($objp->date_start);
4202  $this->date_end = $this->db->jdate($objp->date_end);
4203 
4204  // Multicurrency
4205  $this->fk_multicurrency = $objp->fk_multicurrency;
4206  $this->multicurrency_code = $objp->multicurrency_code;
4207  $this->multicurrency_subprice = $objp->multicurrency_subprice;
4208  $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
4209  $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
4210  $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
4211 
4212  $this->fetch_optionals();
4213 
4214  $this->db->free($result);
4215 
4216  return 1;
4217  } else {
4218  return 0;
4219  }
4220  } else {
4221  return -1;
4222  }
4223  }
4224 
4231  public function insert($notrigger = 0)
4232  {
4233  global $conf, $user;
4234 
4235  $error = 0;
4236 
4237  dol_syslog(get_class($this)."::insert rang=".$this->rang);
4238 
4239  $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4240 
4241  // Clean parameters
4242  if (empty($this->tva_tx)) {
4243  $this->tva_tx = 0;
4244  }
4245  if (empty($this->localtax1_tx)) {
4246  $this->localtax1_tx = 0;
4247  }
4248  if (empty($this->localtax2_tx)) {
4249  $this->localtax2_tx = 0;
4250  }
4251  if (empty($this->localtax1_type)) {
4252  $this->localtax1_type = 0;
4253  }
4254  if (empty($this->localtax2_type)) {
4255  $this->localtax2_type = 0;
4256  }
4257  if (empty($this->total_localtax1)) {
4258  $this->total_localtax1 = 0;
4259  }
4260  if (empty($this->total_localtax2)) {
4261  $this->total_localtax2 = 0;
4262  }
4263  if (empty($this->rang)) {
4264  $this->rang = 0;
4265  }
4266  if (empty($this->remise_percent) || !is_numeric($this->remise_percent)) {
4267  $this->remise_percent = 0;
4268  }
4269  if (empty($this->info_bits)) {
4270  $this->info_bits = 0;
4271  }
4272  if (empty($this->special_code)) {
4273  $this->special_code = 0;
4274  }
4275  if (empty($this->fk_parent_line)) {
4276  $this->fk_parent_line = 0;
4277  }
4278  if (empty($this->fk_fournprice)) {
4279  $this->fk_fournprice = 0;
4280  }
4281  if (!is_numeric($this->qty)) {
4282  $this->qty = 0;
4283  }
4284  if (empty($this->pa_ht)) {
4285  $this->pa_ht = 0;
4286  }
4287  if (empty($this->multicurrency_subprice)) {
4288  $this->multicurrency_subprice = 0;
4289  }
4290  if (empty($this->multicurrency_total_ht)) {
4291  $this->multicurrency_total_ht = 0;
4292  }
4293  if (empty($this->multicurrency_total_tva)) {
4294  $this->multicurrency_total_tva = 0;
4295  }
4296  if (empty($this->multicurrency_total_ttc)) {
4297  $this->multicurrency_total_ttc = 0;
4298  }
4299 
4300  // if buy price not defined, define buyprice as configured in margin admin
4301  if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
4302  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
4303  return $result;
4304  } else {
4305  $this->pa_ht = $result;
4306  }
4307  }
4308 
4309  // Check parameters
4310  if ($this->product_type < 0) {
4311  return -1;
4312  }
4313 
4314  $this->db->begin();
4315 
4316  // Insert line into database
4317  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet';
4318  $sql .= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,';
4319  $sql .= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4320  $sql .= ' subprice, remise_percent, ';
4321  $sql .= ' info_bits, ';
4322  $sql .= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
4323  $sql .= ' fk_unit,';
4324  $sql .= ' date_start, date_end';
4325  $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)';
4326  $sql .= " VALUES (".$this->fk_propal.",";
4327  $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
4328  $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
4329  $sql .= " '".$this->db->escape($this->desc)."',";
4330  $sql .= " ".($this->fk_product ? "'".$this->db->escape($this->fk_product)."'" : "null").",";
4331  $sql .= " '".$this->db->escape($this->product_type)."',";
4332  $sql .= " ".($this->fk_remise_except ? "'".$this->db->escape($this->fk_remise_except)."'" : "null").",";
4333  $sql .= " ".price2num($this->qty, 'MS').",";
4334  $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
4335  $sql .= " ".price2num($this->tva_tx).",";
4336  $sql .= " ".price2num($this->localtax1_tx).",";
4337  $sql .= " ".price2num($this->localtax2_tx).",";
4338  $sql .= " '".$this->db->escape($this->localtax1_type)."',";
4339  $sql .= " '".$this->db->escape($this->localtax2_type)."',";
4340  $sql .= " ".(price2num($this->subprice) !== '' ? price2num($this->subprice, 'MU') : "null").",";
4341  $sql .= " ".price2num($this->remise_percent, 3).",";
4342  $sql .= " ".(isset($this->info_bits) ? ((int) $this->info_bits) : "null").",";
4343  $sql .= " ".price2num($this->total_ht, 'MT').",";
4344  $sql .= " ".price2num($this->total_tva, 'MT').",";
4345  $sql .= " ".price2num($this->total_localtax1, 'MT').",";
4346  $sql .= " ".price2num($this->total_localtax2, 'MT').",";
4347  $sql .= " ".price2num($this->total_ttc, 'MT').",";
4348  $sql .= " ".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null").",";
4349  $sql .= " ".(isset($this->pa_ht) ? "'".price2num($this->pa_ht)."'" : "null").",";
4350  $sql .= ' '.((int) $this->special_code).',';
4351  $sql .= ' '.((int) $this->rang).',';
4352  $sql .= ' '.(empty($this->fk_unit) ? 'NULL' : ((int) $this->fk_unit)).',';
4353  $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").',';
4354  $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
4355  $sql .= ", ".($this->fk_multicurrency > 0 ? ((int) $this->fk_multicurrency) : 'null');
4356  $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
4357  $sql .= ", ".price2num($this->multicurrency_subprice, 'CU');
4358  $sql .= ", ".price2num($this->multicurrency_total_ht, 'CT');
4359  $sql .= ", ".price2num($this->multicurrency_total_tva, 'CT');
4360  $sql .= ", ".price2num($this->multicurrency_total_ttc, 'CT');
4361  $sql .= ')';
4362 
4363  dol_syslog(get_class($this).'::insert', LOG_DEBUG);
4364  $resql = $this->db->query($sql);
4365  if ($resql) {
4366  $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet');
4367 
4368  if (!$error) {
4369  $this->id = $this->rowid;
4370  $result = $this->insertExtraFields();
4371  if ($result < 0) {
4372  $error++;
4373  }
4374  }
4375 
4376  if (!$error && !$notrigger) {
4377  // Call trigger
4378  $result = $this->call_trigger('LINEPROPAL_INSERT', $user);
4379  if ($result < 0) {
4380  $this->db->rollback();
4381  return -1;
4382  }
4383  // End call triggers
4384  }
4385 
4386  $this->db->commit();
4387  return 1;
4388  } else {
4389  $this->error = $this->db->error()." sql=".$sql;
4390  $this->db->rollback();
4391  return -1;
4392  }
4393  }
4394 
4402  public function delete(User $user, $notrigger = 0)
4403  {
4404  global $conf;
4405 
4406  $error = 0;
4407  $this->db->begin();
4408 
4409  if (!$notrigger) {
4410  // Call trigger
4411  $result = $this->call_trigger('LINEPROPAL_DELETE', $user);
4412  if ($result < 0) {
4413  $error++;
4414  }
4415  }
4416  // End call triggers
4417 
4418  if (!$error) {
4419  $sql = "DELETE FROM " . MAIN_DB_PREFIX . "propaldet WHERE rowid = " . ((int) $this->rowid);
4420  dol_syslog("PropaleLigne::delete", LOG_DEBUG);
4421  if ($this->db->query($sql)) {
4422  // Remove extrafields
4423  if (!$error) {
4424  $this->id = $this->rowid;
4425  $result = $this->deleteExtraFields();
4426  if ($result < 0) {
4427  $error++;
4428  dol_syslog(get_class($this) . "::delete error -4 " . $this->error, LOG_ERR);
4429  }
4430  }
4431  } else {
4432  $this->error = $this->db->error() . " sql=" . $sql;
4433  $error++;
4434  }
4435  }
4436 
4437  if ($error) {
4438  $this->db->rollback();
4439  return -1;
4440  } else {
4441  $this->db->commit();
4442  return 1;
4443  }
4444  }
4445 
4452  public function update($notrigger = 0)
4453  {
4454  global $conf, $user;
4455 
4456  $error = 0;
4457 
4458  $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
4459 
4460  if (empty($this->id) && !empty($this->rowid)) {
4461  $this->id = $this->rowid;
4462  }
4463 
4464  // Clean parameters
4465  if (empty($this->tva_tx)) {
4466  $this->tva_tx = 0;
4467  }
4468  if (empty($this->localtax1_tx)) {
4469  $this->localtax1_tx = 0;
4470  }
4471  if (empty($this->localtax2_tx)) {
4472  $this->localtax2_tx = 0;
4473  }
4474  if (empty($this->total_localtax1)) {
4475  $this->total_localtax1 = 0;
4476  }
4477  if (empty($this->total_localtax2)) {
4478  $this->total_localtax2 = 0;
4479  }
4480  if (empty($this->localtax1_type)) {
4481  $this->localtax1_type = 0;
4482  }
4483  if (empty($this->localtax2_type)) {
4484  $this->localtax2_type = 0;
4485  }
4486  if (empty($this->marque_tx)) {
4487  $this->marque_tx = 0;
4488  }
4489  if (empty($this->marge_tx)) {
4490  $this->marge_tx = 0;
4491  }
4492  if (empty($this->price)) {
4493  $this->price = 0; // TODO A virer
4494  }
4495  if (empty($this->remise_percent)) {
4496  $this->remise_percent = 0;
4497  }
4498  if (empty($this->info_bits)) {
4499  $this->info_bits = 0;
4500  }
4501  if (empty($this->special_code)) {
4502  $this->special_code = 0;
4503  }
4504  if (empty($this->fk_parent_line)) {
4505  $this->fk_parent_line = 0;
4506  }
4507  if (empty($this->fk_fournprice)) {
4508  $this->fk_fournprice = 0;
4509  }
4510  if (empty($this->subprice)) {
4511  $this->subprice = 0;
4512  }
4513  if (empty($this->pa_ht)) {
4514  $this->pa_ht = 0;
4515  }
4516 
4517  // if buy price not defined, define buyprice as configured in margin admin
4518  if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
4519  if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
4520  return $result;
4521  } else {
4522  $this->pa_ht = $result;
4523  }
4524  }
4525 
4526  $this->db->begin();
4527 
4528  // Mise a jour ligne en base
4529  $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
4530  $sql .= " description='".$this->db->escape($this->desc)."'";
4531  $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
4532  $sql .= ", product_type=".$this->product_type;
4533  $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'";
4534  $sql .= ", tva_tx='".price2num($this->tva_tx)."'";
4535  $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
4536  $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
4537  $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
4538  $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
4539  $sql .= ", qty='".price2num($this->qty)."'";
4540  $sql .= ", subprice=".price2num($this->subprice);
4541  $sql .= ", remise_percent=".price2num($this->remise_percent);
4542  $sql .= ", price=".(float) price2num($this->price); // TODO A virer
4543  $sql .= ", remise=".(float) price2num($this->remise); // TODO A virer
4544  $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
4545  if (empty($this->skip_update_total)) {
4546  $sql .= ", total_ht=".price2num($this->total_ht);
4547  $sql .= ", total_tva=".price2num($this->total_tva);
4548  $sql .= ", total_ttc=".price2num($this->total_ttc);
4549  $sql .= ", total_localtax1=".price2num($this->total_localtax1);
4550  $sql .= ", total_localtax2=".price2num($this->total_localtax2);
4551  }
4552  $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
4553  $sql .= ", buy_price_ht=".price2num($this->pa_ht);
4554  if (strlen($this->special_code)) {
4555  $sql .= ", special_code=".$this->special_code;
4556  }
4557  $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
4558  if (!empty($this->rang)) {
4559  $sql .= ", rang=".((int) $this->rang);
4560  }
4561  $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
4562  $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
4563  $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
4564 
4565  // Multicurrency
4566  $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice);
4567  $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
4568  $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
4569  $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
4570 
4571  $sql .= " WHERE rowid = ".((int) $this->id);
4572 
4573  dol_syslog(get_class($this)."::update", LOG_DEBUG);
4574  $resql = $this->db->query($sql);
4575  if ($resql) {
4576  if (!$error) {
4577  $result = $this->insertExtraFields();
4578  if ($result < 0) {
4579  $error++;
4580  }
4581  }
4582 
4583  if (!$error && !$notrigger) {
4584  // Call trigger
4585  $result = $this->call_trigger('LINEPROPAL_MODIFY', $user);
4586  if ($result < 0) {
4587  $this->db->rollback();
4588  return -1;
4589  }
4590  // End call triggers
4591  }
4592 
4593  $this->db->commit();
4594  return 1;
4595  } else {
4596  $this->error = $this->db->error();
4597  $this->db->rollback();
4598  return -2;
4599  }
4600  }
4601 
4602  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4609  public function update_total()
4610  {
4611  // phpcs:enable
4612  $this->db->begin();
4613 
4614  // Mise a jour ligne en base
4615  $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET";
4616  $sql .= " total_ht=".price2num($this->total_ht, 'MT');
4617  $sql .= ",total_tva=".price2num($this->total_tva, 'MT');
4618  $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT');
4619  $sql .= " WHERE rowid = ".((int) $this->rowid);
4620 
4621  dol_syslog("PropaleLigne::update_total", LOG_DEBUG);
4622 
4623  $resql = $this->db->query($sql);
4624  if ($resql) {
4625  $this->db->commit();
4626  return 1;
4627  } else {
4628  $this->error = $this->db->error();
4629  $this->db->rollback();
4630  return -2;
4631  }
4632  }
4633 }
Propal\closeProposal
closeProposal($user, $status, $note='', $notrigger=0)
Close/set the commercial proposal to status signed or refused (fill also date signature)
Definition: propal.class.php:2642
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:50
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:6275
Propal\STATUS_SIGNED
const STATUS_SIGNED
Signed quote.
Definition: propal.class.php:365
db
$conf db
API class for accounts.
Definition: inc.php:41
Propal\setDeliveryDate
setDeliveryDate($user, $delivery_date, $notrigger=0)
Set delivery date.
Definition: propal.class.php:2212
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:1504
Propal\getLinesArray
getLinesArray($filters='')
Retrieve an array of proposal lines.
Definition: propal.class.php:3879
Propal\getTooltipContentArray
getTooltipContentArray($params)
getTooltipContentArray
Definition: propal.class.php:3698
Propal\InvoiceArrayList
InvoiceArrayList($id)
Returns an array with id and ref of related invoices.
Definition: propal.class.php:2989
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1236
Propal\demand_reason
demand_reason($demand_reason_id, $notrigger=0)
Change source demand.
Definition: propal.class.php:3247
Propal\LibStatut
LibStatut($status, $mode=1)
Return label of a status (draft, validated, ...)
Definition: propal.class.php:3378
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:1412
Propal\reopen
reopen($user, $status, $note='', $notrigger=0)
Reopen the commercial proposal.
Definition: propal.class.php:2583
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
Productcustomerprice
File of class to manage predefined price products or services by customer.
Definition: productcustomerprice.class.php:29
Propal\set_demand_reason
set_demand_reason($user, $id, $notrigger=0)
Set source of demand.
Definition: propal.class.php:2333
$sql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("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->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:745
Propal\liste_array
liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC')
Return list of proposal (eventually filtered on user) into an array.
Definition: propal.class.php:2909
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:530
PropaleLigne\update_total
update_total()
Update DB line fields total_xxx Used by migration.
Definition: propal.class.php:4609
CommonObject\updateRangOfLine
updateRangOfLine($rowid, $rang)
Update position of line (rang)
Definition: commonobject.class.php:3270
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:3963
PropaleLigne
Class to manage commercial proposal lines.
Definition: propal.class.php:3991
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:4994
CommonObject\setErrorsFromObject
setErrorsFromObject($object)
setErrorsFromObject
Definition: commonobject.class.php:679
Propal\getNextNumRef
getNextNumRef($soc)
Returns the reference to the following non used Proposal used depending on the active numbering modul...
Definition: propal.class.php:3648
Propal\$table_ref_field
$table_ref_field
{}
Definition: propal.class.php:101
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1043
Translate
Class to manage translations.
Definition: translate.class.php:30
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1072
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, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:61
MultiCurrency\getIdFromCode
static getIdFromCode($dbs, $code)
Get id of currency from code.
Definition: multicurrency.class.php:501
PropaleLigne\$fk_product_type
$fk_product_type
Definition: propal.class.php:4014
CommonIncoterm
trait CommonIncoterm
Superclass for incoterm classes.
Definition: commonincoterm.class.php:29
Propal\$remise
$remise
Definition: propal.class.php:221
Propal\$price
$price
Definition: propal.class.php:201
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:4275
Propal\replaceThirdparty
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: propal.class.php:3925
PropaleLigne\__construct
__construct($db)
Class line Contructor.
Definition: propal.class.php:4132
Propal\load_board
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: propal.class.php:3432
Propal\$datep
$datep
Definition: propal.class.php:177
Propal\getNomUrl
getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=-1)
Return clicable link of object (with eventually picto)
Definition: propal.class.php:3749
CommonObjectLine
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Definition: commonobjectline.class.php:32
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:45
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5834
Propal\insert_discount
insert_discount($idremise)
Adding line of fixed discount in the proposal in DB.
Definition: propal.class.php:468
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:2566
WorkboardResponse
Definition: workboardresponse.class.php:24
CommonObject\fetch_thirdparty
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
Definition: commonobject.class.php:1785
Propal\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: propal.class.php:357
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:7590
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:4025
Propal\set_echeance
set_echeance($user, $date_end_validity, $notrigger=0)
Define end validity date.
Definition: propal.class.php:2139
Propal\updateline
updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $desc='', $price_base_type='HT', $info_bits=0, $special_code=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=0, $pa_ht=0, $label='', $type=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $rang=0)
Update a proposal line.
Definition: propal.class.php:817
Propal\__construct
__construct($db, $socid=0, $propalid=0)
Constructor.
Definition: propal.class.php:383
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
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:5460
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:1261
Propal\setDraft
setDraft($user, $notrigger=0)
Set draft status.
Definition: propal.class.php:2840
Propal\getLibStatut
getLibStatut($mode=0)
Return label of status of proposal (draft, validated, ...)
Definition: propal.class.php:3365
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:3582
Propal\set_remise_percent
set_remise_percent($user, $remise, $notrigger=0)
Set an overall discount on the proposal.
Definition: propal.class.php:2455
Propal\$datev
$datev
Definition: propal.class.php:151
Propal\classifyBilled
classifyBilled(User $user, $notrigger=0, $note='')
Classify the proposal to status Billed.
Definition: propal.class.php:2755
Propal\STATUS_BILLED
const STATUS_BILLED
Billed or processed quote.
Definition: propal.class.php:373
get_default_npr
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that returns whether VAT must be recoverable collected VAT (e.g.
Definition: functions.lib.php:6613
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:190
Propal\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: propal.class.php:3895
get_localtax
get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate,...
Definition: functions.lib.php:6015
PropaleLigne\$libelle
$libelle
Definition: propal.class.php:4077
Propal\fetch
fetch($rowid, $ref='', $ref_ext='', $forceentity=0)
Load a proposal from database.
Definition: propal.class.php:1535
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6229
CommonObject\isExistingObject
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check an object id/ref exists If you don't need/want to instantiate object and just need to know if o...
Definition: commonobject.class.php:637
PropaleLigne\$price
$price
Definition: propal.class.php:4060
CommonObject\delete_linked_contact
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
Definition: commonobject.class.php:1361
Propal\STATUS_VALIDATED
const STATUS_VALIDATED
Validated status.
Definition: propal.class.php:361
PropaleLigne\$label
$label
Definition: propal.class.php:4082
CommonObject\defineBuyPrice
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
Definition: commonobject.class.php:8628
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:6921
Propal\fetch_lines
fetch_lines($only_product=0, $loadalsotranslation=0, $filters='')
Load array lines.
Definition: propal.class.php:1823
CommonObject\commonReplaceProduct
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
Definition: commonobject.class.php:8599
CommonObject\deleteEcmFiles
deleteEcmFiles($mode=0)
Delete related files of object in database.
Definition: commonobject.class.php:10189
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1639
DiscountAbsolute
Class to manage absolute discounts.
Definition: discount.class.php:29
Propal\getKanbanView
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
Definition: propal.class.php:3958
Propal\$remise_absolue
$remise_absolue
Definition: propal.class.php:225
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:3428
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:6080
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3888
get_default_tva
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
Definition: functions.lib.php:6499
Propal\$total
$total
Definition: propal.class.php:211
Propal\deleteline
deleteline($lineid, $id=0)
Delete detail line.
Definition: propal.class.php:989
Propal\createFromClone
createFromClone(User $user, $socid=0, $forceentity=null, $update_prices=false)
Load an object from its id and create a new one in database.
Definition: propal.class.php:1359
ref
$object ref
Definition: info.php:78
User
Class to manage Dolibarr users.
Definition: user.class.php:44
Propal\create
create($user, $notrigger=0)
Create commercial proposal into database this->ref can be set or empty.
Definition: propal.class.php:1038
Propal\getInvoiceArrayList
getInvoiceArrayList()
Returns an array with the numbers of related invoices.
Definition: propal.class.php:2977
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6189
Propal\set_availability
set_availability($user, $id, $notrigger=0)
Set delivery.
Definition: propal.class.php:2270
CommonObject\$note
$note
Definition: commonobject.class.php:446
Propal\set_remise_absolue
set_remise_absolue($user, $remise, $notrigger=0)
Set an absolute overall discount on the proposal.
Definition: propal.class.php:2518
Product
Class to manage products or services.
Definition: product.class.php:46
getMarginInfos
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
Definition: margins.lib.php:118
PropaleLigne\fetch
fetch($rowid)
Retrieve the propal line object.
Definition: propal.class.php:4143
dol_delete_preview
dol_delete_preview($object)
Delete all preview files linked to object instance.
Definition: files.lib.php:1464
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:3865
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10767
Propal\addline
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='', $date_start='', $date_end='', $array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $fk_remise_except=0, $noupdateafterinsertline=0)
Add a proposal line into database (linked to product/service or not) The parameters are already suppo...
Definition: propal.class.php:570
Propal\$tva
$tva
Definition: propal.class.php:206
PropaleLigne\$ref
$ref
Definition: propal.class.php:4067
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:4361
Propal\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: propal.class.php:3516
Propal\info
info($id)
Object Proposal Information.
Definition: propal.class.php:3309
PropaleLigne\$remise
$remise
Definition: propal.class.php:4055
Propal\update
update(User $user, $notrigger=0)
Update database.
Definition: propal.class.php:1711
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2947
Propal\replaceProduct
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
Definition: propal.class.php:3942
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:5708
Propal\valid
valid($user, $notrigger=0)
Set status to validated.
Definition: propal.class.php:1956
Propal\load_state_board
load_state_board()
Charge indicateurs this->nb de tableau de bord.
Definition: propal.class.php:3607
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5864
PropaleLigne\insert
insert($notrigger=0)
Insert object line propal in database.
Definition: propal.class.php:4231
Product\TYPE_PRODUCT
const TYPE_PRODUCT
Regular product.
Definition: product.class.php:542
Propal
Class to manage proposals.
Definition: propal.class.php:52
Propal\add_product
add_product($idproduct, $qty, $remise_percent=0)
Add line into array ->lines $this->thirdparty should be loaded.
Definition: propal.class.php:408
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:96
Propal\set_date_livraison
set_date_livraison($user, $delivery_date, $notrigger=0)
Set delivery date.
Definition: propal.class.php:2198
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:3106
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8570
Propal\set_ref_client
set_ref_client($user, $ref_client, $notrigger=0)
Set customer reference number.
Definition: propal.class.php:2398
Propal\$datec
$datec
Definition: propal.class.php:140
Propal\STATUS_NOTSIGNED
const STATUS_NOTSIGNED
Not signed quote.
Definition: propal.class.php:369
PropaleLigne\update
update($notrigger=0)
Update propal line object into DB.
Definition: propal.class.php:4452
Propal\set_date
set_date($user, $date, $notrigger=0)
Define proposal date.
Definition: propal.class.php:2075
Propal\availability
availability($availability_id, $notrigger=0)
Change the delivery time.
Definition: propal.class.php:3184
float
div float
Buy price without taxes.
Definition: style.css.php:920