dolibarr 23.0.4
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-2025 Frédéric France <frederic.france@free.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 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
22 * Copyright (C) 2025 William Mead <william@m34d.com>
23 *
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation; either version 3 of the License, or
27 * (at your option) any later version.
28 *
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
33 *
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <https://www.gnu.org/licenses/>.
36 */
37
44require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
45require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propaleligne.class.php';
46require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
47require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
48require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
49require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
50require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
51
55class Propal extends CommonObject
56{
57 use CommonIncoterm;
58 use CommonSubtotal;
59
63 public $code = "";
64
68 public $element = 'propal';
69
73 public $table_element = 'propal';
74
78 public $table_element_line = 'propaldet';
79
83 public $fk_element = 'fk_propal';
84
88 public $picto = 'propal';
89
94 public $TRIGGER_PREFIX = 'PROPAL';
95
100 public $restrictiononfksoc = 1;
101
105 protected $table_ref_field = 'ref';
106
111 public $socid;
112
117 public $contactid;
118
125 public $ref_client;
126
131 public $ref_customer;
132
139 public $statut;
140
146 public $status;
147
153 public $datec;
154
160 public $datev;
161
165 public $date_validation;
166
170 public $date_signature;
171
175 public $user_signature;
176
180 public $date;
181
187 public $datep;
188
192 public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
193
194
198 public $fin_validite;
199
203 public $user_author_id;
204
209 public $author;
210
216 public $price;
217
223 public $tva;
229 public $total;
230
234 public $cond_reglement_code;
235
239 public $cond_reglement;
240
244 public $cond_reglement_doc;
245
249 public $cond_reglement_label;
250
254 public $mode_reglement_code;
255
259 public $mode_reglement;
260
266 public $deposit_percent;
267
272 public $fk_address;
273
278 public $address_type;
279
284 public $address;
285
289 public $availability_id;
290
296 public $fk_availability;
297
301 public $availability_code;
302
306 public $availability;
307
311 public $duree_validite;
312
316 public $demand_reason_id;
317
321 public $demand_reason_code;
322
326 public $demand_reason;
327
331 public $warehouse_id;
332
336 public $lines = array();
337
341 public $line;
342
343 public $labelStatus = array();
344 public $labelStatusShort = array();
345
346
371 // BEGIN MODULEBUILDER PROPERTIES
375 public $fields = array(
376 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
377 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 15, 'index' => 1),
378 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 20),
379 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 22),
380 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 40),
381 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'position' => 23),
382 '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),
383 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
384 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 55),
385 'datep' => array('type' => 'date', 'label' => 'Date', 'enabled' => 1, 'visible' => -1, 'position' => 60),
386 'fin_validite' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => -1, 'position' => 65),
387 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 70),
388 'date_cloture' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 75),
389 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 80),
390 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 85),
391 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 90),
392 'fk_user_cloture' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 95),
393 'price' => array('type' => 'double', 'label' => 'Price', 'enabled' => 1, 'visible' => -1, 'position' => 105),
394 'total_ht' => array('type' => 'double(24,8)', 'label' => 'TotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 125, 'isameasure' => 1),
395 'total_tva' => array('type' => 'double(24,8)', 'label' => 'VAT', 'enabled' => 1, 'visible' => -1, 'position' => 130, 'isameasure' => 1),
396 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LocalTax1', 'enabled' => 1, 'visible' => -1, 'position' => 135, 'isameasure' => 1),
397 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LocalTax2', 'enabled' => 1, 'visible' => -1, 'position' => 140, 'isameasure' => 1),
398 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'TotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 145, 'isameasure' => 1),
399 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 150),
400 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 155),
401 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 160),
402 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 161),
403 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 165),
404 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 170),
405 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 175),
406 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'PDFTemplate', 'enabled' => 1, 'visible' => 0, 'position' => 180),
407 'date_livraison' => array('type' => 'date', 'label' => 'DateDeliveryPlanned', 'enabled' => 1, 'visible' => -1, 'position' => 185),
408 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMethod', 'enabled' => 1, 'visible' => -1, 'position' => 190),
409 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'Fk warehouse', 'enabled' => 'isModEnabled("stock")', 'visible' => -1, 'position' => 191),
410 'fk_availability' => array('type' => 'integer', 'label' => 'Availability', 'enabled' => 1, 'visible' => -1, 'position' => 195),
411 'fk_delivery_address' => array('type' => 'integer', 'label' => 'DeliveryAddress', 'enabled' => 1, 'visible' => 0, 'position' => 200), // deprecated
412 'fk_input_reason' => array('type' => 'integer', 'label' => 'InputReason', 'enabled' => 1, 'visible' => -1, 'position' => 205),
413 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 215),
414 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 220),
415 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 225),
416 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyID', 'enabled' => 1, 'visible' => -1, 'position' => 230),
417 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 235),
418 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240, 'isameasure' => 1),
419 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 245, 'isameasure' => 1),
420 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 250, 'isameasure' => 1),
421 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 255, 'isameasure' => 1),
422 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 260),
423 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 500),
424 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
425 );
426 // END MODULEBUILDER PROPERTIES
427
431 const STATUS_CANCELED = -1;
435 const STATUS_DRAFT = 0;
443 const STATUS_SIGNED = 2;
451 const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ?
452
453
461 public function __construct($db, $socid = 0, $propalid = 0)
462 {
463 $this->db = $db;
464
465 $this->ismultientitymanaged = 1;
466 $this->socid = $socid;
467 $this->id = $propalid;
468
469 $this->duree_validite = getDolGlobalInt('PROPALE_VALIDITY_DURATION');
470
471 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
472 }
473
474
475 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
487 public function add_product($idproduct, $qty, $remise_percent = 0)
488 {
489 // phpcs:enable
490 global $mysoc;
491
492 if (!$qty) {
493 $qty = 1;
494 }
495
496 dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
497 if ($idproduct > 0) {
498 $prod = new Product($this->db);
499 $prod->fetch($idproduct);
500
501 $productdesc = $prod->description;
502
503 $tva_tx = (string) get_default_tva($mysoc, $this->thirdparty, $prod->id);
504 $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
505 if (empty($tva_tx)) {
506 $tva_npr = 0;
507 }
508 $vat_src_code = ''; // May be defined into tva_tx
509
510 $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr);
511 $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr);
512
513 // multiprices
514 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $this->thirdparty->price_level) {
515 $price = $prod->multiprices[$this->thirdparty->price_level];
516 } else {
517 $price = $prod->price;
518 }
519
520 $line = new PropaleLigne($this->db);
521
522 $line->fk_product = $idproduct;
523 $line->desc = $productdesc;
524 $line->qty = $qty;
525 $line->subprice = $price;
526 $line->remise_percent = $remise_percent;
527 $line->vat_src_code = $vat_src_code;
528 $line->tva_tx = $tva_tx;
529 $line->fk_unit = $prod->fk_unit;
530 if ($tva_npr) {
531 $line->info_bits = 1;
532 }
533
534 $this->lines[] = $line;
535 }
536
537 return 1;
538 }
539
540 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
547 public function insert_discount($idremise)
548 {
549 // phpcs:enable
550 global $langs;
551
552 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
553 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
554
555 $this->db->begin();
556
557 $remise = new DiscountAbsolute($this->db);
558 $result = $remise->fetch($idremise);
559
560 if ($result > 0) {
561 if ($remise->fk_facture) { // Protection against multiple submission
562 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
563 $this->db->rollback();
564 return -5;
565 }
566
567 $line = new PropaleLigne($this->db);
568
569 $line->context = $this->context;
570
571 $line->fk_propal = $this->id;
572 $line->fk_remise_except = $remise->id;
573 $line->desc = $remise->description; // Description ligne
574 $line->vat_src_code = $remise->vat_src_code;
575 $line->tva_tx = $remise->tva_tx;
576 $line->subprice = -(float) $remise->amount_ht;
577 $line->fk_product = 0; // Id produit predefined
578 $line->qty = 1;
579 $line->remise_percent = 0;
580 $line->rang = -1;
581 $line->info_bits = 2;
582
583 $line->total_ht = -(float) $remise->amount_ht;
584 $line->total_tva = -(float) $remise->amount_tva;
585 $line->total_ttc = -(float) $remise->amount_ttc;
586
587 $result = $line->insert();
588 if ($result > 0) {
589 $result = $this->update_price(1);
590 if ($result > 0) {
591 $this->db->commit();
592 return 1;
593 } else {
594 $this->db->rollback();
595 return -1;
596 }
597 } else {
598 $this->setErrorsFromObject($line);
599 $this->db->rollback();
600 return -2;
601 }
602 } else {
603 $this->db->rollback();
604 return -2;
605 }
606 }
607
645 public function addline(
646 $desc,
647 $pu_ht,
648 $qty,
649 $txtva,
650 $txlocaltax1 = 0.0,
651 $txlocaltax2 = 0.0,
652 $fk_product = 0,
653 $remise_percent = 0.0,
654 $price_base_type = 'HT',
655 $pu_ttc = 0.0,
656 $info_bits = 0,
657 $type = 0,
658 $rang = -1,
659 $special_code = 0,
660 $fk_parent_line = 0,
661 $fk_fournprice = 0,
662 $pa_ht = 0,
663 $label = '',
664 $date_start = '',
665 $date_end = '',
666 $array_options = array(),
667 $fk_unit = null,
668 $origin = '',
669 $origin_id = 0,
670 $pu_ht_devise = 0,
671 $fk_remise_except = 0,
672 $noupdateafterinsertline = 0
673 ) {
674 global $mysoc, $langs;
675
676 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);
677
678 if ($this->status == self::STATUS_DRAFT) {
679 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
680
681 // Clean parameters
682 if (empty($remise_percent)) {
683 $remise_percent = 0;
684 }
685 if (empty($qty)) {
686 $qty = 0;
687 }
688 if (empty($info_bits)) {
689 $info_bits = 0;
690 }
691 if (empty($rang)) {
692 $rang = 0;
693 }
694 if (empty($fk_parent_line) || $fk_parent_line < 0) {
695 $fk_parent_line = 0;
696 }
697
698 $remise_percent = price2num($remise_percent);
699 $qty = (float) price2num($qty, 'MS');
700 $pu_ht = price2num($pu_ht);
701 $pu_ht_devise = price2num($pu_ht_devise);
702 $pu_ttc = price2num($pu_ttc);
703 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
704 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
705 }
706 $txlocaltax1 = price2num($txlocaltax1);
707 $txlocaltax2 = price2num($txlocaltax2);
708 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht is empty string
709 if ($price_base_type == 'HT') {
710 $pu = $pu_ht;
711 } else {
712 $pu = $pu_ttc;
713 }
714
715 // Check parameters
716 if ($type < 0) {
717 return -1;
718 }
719
720 if ($date_start && $date_end && $date_start > $date_end) {
721 $langs->load("errors");
722 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
723 return -1;
724 }
725
726 $this->db->begin();
727
728 $product_type = $type;
729 if (!empty($fk_product) && $fk_product > 0) {
730 $product = new Product($this->db);
731 $result = $product->fetch($fk_product);
732 $product_type = $product->type;
733
734 if ($product->isStockManaged() && $product->stock_reel < $qty && getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL')) {
735 $langs->load("errors");
736 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
737 $this->db->rollback();
738 return -3;
739 }
740 }
741
742 // Calcul du total TTC et de la TVA pour la ligne a partir de
743 // qty, pu, remise_percent et txtva
744 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
745 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
746
747 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
748
749 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
750 $tmpproduct = new Product($this->db);
751 $result = $tmpproduct->fetch($fk_product);
752 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
753 if ($newqty != $qty) {
754 $qty = $newqty;
755 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
756 }
757 }
758
759 // Clean vat code
760 $reg = array();
761 $vat_src_code = '';
762 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
763 $vat_src_code = $reg[1];
764 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
765 }
766
767 $tabprice = calcul_price_total($qty, (float) $pu, (float) $remise_percent, $txtva, (float) $txlocaltax1, (float) $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise);
768
769 $total_ht = $tabprice[0];
770 $total_tva = $tabprice[1];
771 $total_ttc = $tabprice[2];
772 $total_localtax1 = $tabprice[9];
773 $total_localtax2 = $tabprice[10];
774 $pu_ht = $tabprice[3];
775 $pu_tva = $tabprice[4];
776 $pu_ttc = $tabprice[5];
777
778 // MultiCurrency
779 $multicurrency_total_ht = $tabprice[16];
780 $multicurrency_total_tva = $tabprice[17];
781 $multicurrency_total_ttc = $tabprice[18];
782 $pu_ht_devise = $tabprice[19];
783
784 // Rang to use
785 $ranktouse = $rang;
786 if (empty($ranktouse) || $ranktouse == -1) {
787 $rangmax = $this->line_max($fk_parent_line);
788 $ranktouse = $rangmax + 1;
789 }
790
791 // Insert line
792 $this->line = new PropaleLigne($this->db);
793
794 $this->line->context = $this->context;
795
796 $this->line->fk_propal = $this->id;
797 $this->line->label = $label;
798 $this->line->desc = $desc;
799 $this->line->qty = (float) $qty;
800
801 $this->line->vat_src_code = $vat_src_code;
802 $this->line->tva_tx = $txtva;
803 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
804 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
805 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
806 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
807 $this->line->fk_product = $fk_product;
808 $this->line->product_type = $type;
809 $this->line->fk_remise_except = $fk_remise_except;
810 $this->line->remise_percent = $remise_percent;
811 $this->line->subprice = (float) $pu_ht;
812 $this->line->rang = $ranktouse;
813 $this->line->info_bits = $info_bits;
814 $this->line->total_ht = (float) $total_ht;
815 $this->line->total_tva = (float) $total_tva;
816 $this->line->total_localtax1 = (float) $total_localtax1;
817 $this->line->total_localtax2 = (float) $total_localtax2;
818 $this->line->total_ttc = (float) $total_ttc;
819 $this->line->special_code = $special_code;
820 $this->line->fk_parent_line = $fk_parent_line;
821 $this->line->fk_unit = $fk_unit;
822
823 $this->line->date_start = $date_start;
824 $this->line->date_end = $date_end;
825
826 $this->line->fk_fournprice = $fk_fournprice;
827 $this->line->pa_ht = $pa_ht;
828
829 $this->line->origin_id = $origin_id;
830 $this->line->origin = $origin;
831
832 // Multicurrency
833 $this->line->fk_multicurrency = $this->fk_multicurrency;
834 $this->line->multicurrency_code = $this->multicurrency_code;
835 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
836 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
837 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
838 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
839
840 // Mise en option de la ligne
841 if (empty($qty) && empty($special_code)) {
842 $this->line->special_code = 3;
843 }
844
845 if (is_array($array_options) && count($array_options) > 0) {
846 $this->line->array_options = $array_options;
847 }
848
849 $result = $this->line->insert();
850 if ($result > 0) {
851 if (!isset($this->context['createfromclone'])) {
852 if (!empty($fk_parent_line)) {
853 // Always reorder if child line
854 $this->line_order(true, 'DESC');
855 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
856 // Update all rank of all other lines starting from the same $ranktouse
857 $linecount = count($this->lines);
858 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
859 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
860 }
861 }
862
863 $this->lines[] = $this->line;
864 } else {
865 foreach ($this->lines as $line) {
866 if ($line->id == $origin_id) {
867 $this->line->extraparams = $line->extraparams;
868 $this->line->setExtraParameters();
869 }
870 }
871 }
872
873 // Update denormalized fields at the order level
874 if (empty($noupdateafterinsertline)) {
875 $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.
876 }
877
878 if ($result > 0) {
879 $this->db->commit();
880 return $this->line->id;
881 } else {
882 $this->error = $this->db->error();
883 $this->db->rollback();
884 return -1;
885 }
886 } else {
887 $this->setErrorsFromObject($this->line);
888 $this->db->rollback();
889 return -2;
890 }
891 } else {
892 dol_syslog(get_class($this)."::addline status of proposal must be Draft to allow use of ->addline()", LOG_ERR);
893 return -3;
894 }
895 }
896
897
927 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 = array(), $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $rang = 0)
928 {
929 global $mysoc, $langs;
930
931 if (!$this->isLineOfObject($rowid)) {
932 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
933 return -1;
934 }
935
936 dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent,
937 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");
938 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
939
940 // Clean parameters
941 $remise_percent = price2num($remise_percent);
942 $qty = (float) price2num($qty);
943 $pu = price2num($pu);
944 $pu_ht_devise = price2num($pu_ht_devise);
945 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
946 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
947 }
948 $txlocaltax1 = price2num($txlocaltax1);
949 $txlocaltax2 = price2num($txlocaltax2);
950 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
951 if (empty($qty) && empty($special_code)) {
952 $special_code = 3; // Set option tag
953 }
954 if (!empty($qty) && $special_code == 3) {
955 $special_code = 0; // Remove option tag
956 }
957 if (empty($type)) {
958 $type = 0;
959 }
960
961 if ($date_start && $date_end && $date_start > $date_end) {
962 $langs->load("errors");
963 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
964 return -1;
965 }
966
967 if ($this->status == self::STATUS_DRAFT) {
968 $this->db->begin();
969
970 // Calcul du total TTC et de la TVA pour la ligne a partir de
971 // qty, pu, remise_percent et txtva
972 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
973 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
974
975 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
976
977 // Clean vat code
978 $reg = array();
979 $vat_src_code = '';
980 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
981 $vat_src_code = $reg[1];
982 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
983 }
984
985 // TODO Implement if (getDolGlobalInt('MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES')) ?
986
987 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
988 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
989 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
990 $tmpline = new PropaleLigne($this->db);
991 if ($tmpline->fetch($rowid) > 0) {
992 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
993 if ($newqty != $qty) {
994 $qty = $newqty;
995 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
996 }
997 }
998 }
999
1000 $tabprice = calcul_price_total($qty, (float) $pu, (float) $remise_percent, $txtva, (float) $txlocaltax1, (float) $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise);
1001 $total_ht = $tabprice[0];
1002 $total_tva = $tabprice[1];
1003 $total_ttc = $tabprice[2];
1004 $total_localtax1 = $tabprice[9];
1005 $total_localtax2 = $tabprice[10];
1006 $pu_ht = $tabprice[3];
1007 $pu_tva = $tabprice[4];
1008 $pu_ttc = $tabprice[5];
1009
1010 // MultiCurrency
1011 $multicurrency_total_ht = $tabprice[16];
1012 $multicurrency_total_tva = $tabprice[17];
1013 $multicurrency_total_ttc = $tabprice[18];
1014 $pu_ht_devise = $tabprice[19];
1015
1016 // Fetch current line from the database and then clone the object and set it in $oldline property
1017 $line = new PropaleLigne($this->db);
1018 $line->fetch($rowid);
1019
1020 $staticline = clone $line;
1021
1022 $line->oldline = $staticline;
1023 $this->line = $line;
1024 $this->line->context = $this->context;
1025 $this->line->rang = $rang;
1026
1027 // Reorder if fk_parent_line change
1028 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
1029 $rangmax = $this->line_max($fk_parent_line);
1030 $this->line->rang = $rangmax + 1;
1031 }
1032
1033
1034 $this->line->id = $rowid;
1035 $this->line->label = $label;
1036 $this->line->desc = $desc;
1037 $this->line->qty = $qty;
1038 $this->line->product_type = $type;
1039 $this->line->vat_src_code = $vat_src_code;
1040 $this->line->tva_tx = $txtva;
1041 $this->line->localtax1_tx = $txlocaltax1;
1042 $this->line->localtax2_tx = $txlocaltax2;
1043 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
1044 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
1045 $this->line->remise_percent = $remise_percent;
1046 $this->line->subprice = (float) $pu_ht;
1047 $this->line->info_bits = $info_bits;
1048
1049 $this->line->total_ht = (float) $total_ht;
1050 $this->line->total_tva = (float) $total_tva;
1051 $this->line->total_localtax1 = (float) $total_localtax1;
1052 $this->line->total_localtax2 = (float) $total_localtax2;
1053 $this->line->total_ttc = (float) $total_ttc;
1054 $this->line->special_code = $special_code;
1055 $this->line->fk_parent_line = $fk_parent_line;
1056 $this->line->skip_update_total = $skip_update_total;
1057 $this->line->fk_unit = $fk_unit;
1058
1059 $this->line->fk_fournprice = $fk_fournprice;
1060 $this->line->pa_ht = $pa_ht;
1061
1062 $this->line->date_start = $date_start;
1063 $this->line->date_end = $date_end;
1064
1065 if (is_array($array_options) && count($array_options) > 0) {
1066 // We replace values in this->line->array_options only for entries defined into $array_options
1067 foreach ($array_options as $key => $value) {
1068 $this->line->array_options[$key] = $array_options[$key];
1069 }
1070 }
1071
1072 // Multicurrency
1073 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
1074 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
1075 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
1076 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
1077
1078 $result = $this->line->update($notrigger);
1079 if ($result > 0) {
1080 // Reorder if child line
1081 if (!empty($fk_parent_line)) {
1082 $this->line_order(true, 'DESC');
1083 }
1084
1085 $this->update_price(1, 'auto');
1086
1087 // $this is Propal
1088 // $this->fk_propal = $this->id;
1089 // $this->rowid = $rowid;
1090
1091 $this->db->commit();
1092 return $result;
1093 } else {
1094 $this->setErrorsFromObject($this->line);
1095 $this->db->rollback();
1096 return -1;
1097 }
1098 } else {
1099 dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
1100 return -2;
1101 }
1102 }
1103
1104
1112 public function deleteLine($lineid, $id = 0)
1113 {
1114 global $user;
1115
1116 if ($this->status == self::STATUS_DRAFT) {
1117 $this->db->begin();
1118
1119 $line = new PropaleLigne($this->db);
1120
1121 $line->context = $this->context;
1122
1123 // Load data
1124 $line->fetch($lineid);
1125
1126 if ($id <= 0) {
1127 $id = $this->id;
1128 }
1129 if ($id > 0 && (int) $line->fk_propal !== (int) $id) {
1130 $this->db->rollback();
1131 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1132 return -1;
1133 }
1134
1135 // Memorize previous line for triggers
1136 $staticline = clone $line;
1137 $line->oldline = $staticline;
1138
1139 if ($line->delete($user) > 0) {
1140 $this->update_price(1);
1141
1142 $this->db->commit();
1143 return 1;
1144 } else {
1145 $this->setErrorsFromObject($line);
1146 $this->db->rollback();
1147 return -1;
1148 }
1149 } else {
1150 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1151 return -2;
1152 }
1153 }
1154
1155
1164 public function create($user, $notrigger = 0)
1165 {
1166 global $mysoc;
1167
1168 $error = 0;
1169
1170 $now = dol_now();
1171
1172 // Clean parameters
1173 if (empty($this->date)) {
1174 $this->date = $this->datep;
1175 }
1176 $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1177 if (empty($this->availability_id)) {
1178 $this->availability_id = 0;
1179 }
1180 if (empty($this->demand_reason_id)) {
1181 $this->demand_reason_id = 0;
1182 }
1183
1184 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1185 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1186 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
1187 } else {
1188 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1189 }
1190 if (empty($this->fk_multicurrency)) {
1191 $this->multicurrency_code = getDolCurrency();
1192 $this->fk_multicurrency = 0;
1193 $this->multicurrency_tx = 1;
1194 }
1195 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
1196 $this->entity = setEntity($this);
1197
1198 // Set tmp vars
1199 $delivery_date = $this->delivery_date;
1200
1201 dol_syslog(get_class($this)."::create");
1202
1203 // Check parameters
1204 $result = $this->fetch_thirdparty();
1205 if ($result < 0) {
1206 $this->error = "Failed to fetch company";
1207 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1208 return -3;
1209 }
1210
1211 // Check parameters
1212 if (!empty($this->ref)) { // We check that ref is not already used
1213 $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
1214 if ($result > 0) {
1215 $this->error = 'ErrorRefAlreadyExists';
1216 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1217 $this->db->rollback();
1218 return -1;
1219 }
1220 }
1221
1222 if (empty($this->date)) {
1223 $this->error = "Date of proposal is required";
1224 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1225 return -4;
1226 }
1227
1228
1229 $this->db->begin();
1230
1231 // Insert into database
1232 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1233 $sql .= "fk_soc";
1234 $sql .= ", price";
1235 $sql .= ", total_tva";
1236 $sql .= ", total_ttc";
1237 $sql .= ", datep";
1238 $sql .= ", datec";
1239 $sql .= ", ref";
1240 $sql .= ", fk_user_author";
1241 $sql .= ", note_private";
1242 $sql .= ", note_public";
1243 $sql .= ", model_pdf";
1244 $sql .= ", fin_validite";
1245 $sql .= ", fk_cond_reglement";
1246 $sql .= ", deposit_percent";
1247 $sql .= ", fk_mode_reglement";
1248 $sql .= ", fk_account";
1249 $sql .= ", ref_client";
1250 $sql .= ", ref_ext";
1251 $sql .= ", date_livraison";
1252 $sql .= ", fk_shipping_method";
1253 $sql .= ", fk_warehouse";
1254 $sql .= ", fk_availability";
1255 $sql .= ", fk_input_reason";
1256 $sql .= ", fk_projet";
1257 $sql .= ", fk_incoterms";
1258 $sql .= ", location_incoterms";
1259 $sql .= ", entity";
1260 $sql .= ", fk_multicurrency";
1261 $sql .= ", multicurrency_code";
1262 $sql .= ", multicurrency_tx";
1263 $sql .= ") ";
1264 $sql .= " VALUES (";
1265 $sql .= $this->socid;
1266 $sql .= ", 0";
1267 $sql .= ", 0";
1268 $sql .= ", 0";
1269 $sql .= ", '".$this->db->idate($this->date)."'";
1270 $sql .= ", '".$this->db->idate($now)."'";
1271 $sql .= ", '(PROV)'";
1272 $sql .= ", ".($user->id > 0 ? ((int) $user->id) : "NULL");
1273 $sql .= ", '".$this->db->escape($this->note_private)."'";
1274 $sql .= ", '".$this->db->escape($this->note_public)."'";
1275 $sql .= ", '".$this->db->escape($this->model_pdf)."'";
1276 $sql .= ", ".($this->fin_validite != '' ? "'".$this->db->idate($this->fin_validite)."'" : "NULL");
1277 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'NULL');
1278 $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : 'NULL');
1279 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'NULL');
1280 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1281 $sql .= ", '".$this->db->escape((string) $this->ref_client)."'";
1282 $sql .= ", '".$this->db->escape((string) $this->ref_ext)."'";
1283 $sql .= ", ".(!isDolTms($delivery_date) ? "NULL" : "'".$this->db->idate($delivery_date)."'");
1284 $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
1285 $sql .= ", ".($this->warehouse_id > 0 ? $this->warehouse_id : 'NULL');
1286 $sql .= ", ".((int) $this->availability_id);
1287 $sql .= ", ".((int) $this->demand_reason_id);
1288 $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
1289 $sql .= ", ".(int) $this->fk_incoterms;
1290 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1291 $sql .= ", ".(int) $this->entity;
1292 $sql .= ", ".(int) $this->fk_multicurrency;
1293 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1294 $sql .= ", ".(float) $this->multicurrency_tx;
1295 $sql .= ")";
1296
1297 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1298 $resql = $this->db->query($sql);
1299 if ($resql) {
1300 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
1301
1302 if ($this->id) {
1303 $this->ref = '(PROV'.$this->id.')';
1304 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
1305
1306 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1307 $resql = $this->db->query($sql);
1308 if (!$resql) {
1309 $error++;
1310 }
1311
1312 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1313 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1314 }
1315
1316 // Add object linked
1317 if (!$error && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1318 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1319 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, ...))
1320 foreach ($tmp_origin_id as $origin_id) {
1321 $ret = $this->add_object_linked($origin, $origin_id);
1322 if (!$ret) {
1323 $this->error = $this->db->lasterror();
1324 $error++;
1325 }
1326 }
1327 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1328 $origin_id = $tmp_origin_id;
1329 $ret = $this->add_object_linked($origin, $origin_id);
1330 if (!$ret) {
1331 $this->error = $this->db->lasterror();
1332 $error++;
1333 }
1334 }
1335 }
1336 }
1337
1338 /*
1339 * Insertion du detail des produits dans la base
1340 * Insert products detail in database
1341 */
1342 if (!$error) {
1343 $fk_parent_line = 0;
1344 $num = count($this->lines);
1345
1346 for ($i = 0; $i < $num; $i++) {
1347 if (!is_object($this->lines[$i])) { // If this->lines is not array of objects, coming from REST API
1348 // Convert into object this->lines[$i].
1349 $line = (object) $this->lines[$i];
1350 } else {
1351 $line = $this->lines[$i];
1352 }
1353 // Reset fk_parent_line for line that are not child lines or special product
1354 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1355 $fk_parent_line = 0;
1356 }
1357 // Complete vat rate with code
1358 $vatrate = $line->tva_tx;
1359 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', $vatrate)) {
1360 $vatrate .= ' ('.$line->vat_src_code.')';
1361 }
1362
1363 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
1364 $originid = $line->origin_id;
1365 $origintype = $line->origin;
1366 } else {
1367 $originid = $line->id;
1368 $origintype = $this->element;
1369 }
1370
1371 $result = $this->addline(
1372 $line->desc,
1373 $line->subprice,
1374 $line->qty,
1375 $vatrate,
1376 $line->localtax1_tx,
1377 $line->localtax2_tx,
1378 $line->fk_product,
1379 $line->remise_percent,
1380 'HT',
1381 0,
1382 $line->info_bits,
1383 $line->product_type,
1384 $line->rang,
1385 $line->special_code,
1386 $fk_parent_line,
1387 $line->fk_fournprice,
1388 $line->pa_ht,
1389 $line->label,
1390 $line->date_start,
1391 $line->date_end,
1392 $line->array_options,
1393 $line->fk_unit,
1394 (string) $origintype,
1395 $originid,
1396 0,
1397 0,
1398 1
1399 );
1400
1401 if ($result < 0) {
1402 $error++;
1403 $this->error = $this->db->error;
1404 dol_print_error($this->db);
1405 break;
1406 }
1407
1408 // Set the id on created row
1409 $line->id = $result;
1410
1411 // Defined the new fk_parent_line
1412 if ($result > 0 && $line->product_type == 9) {
1413 $fk_parent_line = $result;
1414 }
1415 }
1416 }
1417
1418 if (!$error) {
1419 // Update denormalized data
1420 $resql = $this->update_price(1, 'auto', 0, $mysoc);
1421 if ($resql) {
1422 // Actions on extra fields
1423 $result = $this->insertExtraFields();
1424 if ($result < 0) {
1425 $error++;
1426 }
1427
1428 if (!$error && !$notrigger) {
1429 // Call trigger
1430 $result = $this->call_trigger('PROPAL_CREATE', $user);
1431 if ($result < 0) {
1432 $error++;
1433 }
1434 // End call triggers
1435 }
1436 } else {
1437 $this->error = $this->db->lasterror();
1438 $error++;
1439 }
1440 }
1441 } else {
1442 $this->error = $this->db->lasterror();
1443 $error++;
1444 }
1445
1446 if (!$error) {
1447 $this->db->commit();
1448 dol_syslog(get_class($this)."::create done id=".$this->id);
1449 return $this->id;
1450 } else {
1451 $this->db->rollback();
1452 return -2;
1453 }
1454 } else {
1455 $this->error = $this->db->lasterror();
1456 $this->db->rollback();
1457 return -1;
1458 }
1459 }
1460
1471 public function createFromClone(User $user, $socid = 0, $forceentity = null, $update_prices = false, $update_desc = false)
1472 {
1473 global $conf, $hookmanager, $mysoc;
1474
1475 dol_include_once('/projet/class/project.class.php');
1476
1477 $error = 0;
1478 $now = dol_now();
1479
1480 dol_syslog(__METHOD__, LOG_DEBUG);
1481
1482 $object = new self($this->db);
1483
1484 $this->db->begin();
1485
1486 // Load source object
1487 $object->fetch($this->id);
1488
1489 $objsoc = new Societe($this->db);
1490
1491 // Change socid if needed
1492 if (!empty($socid) && $socid != $object->socid) {
1493 if ($objsoc->fetch($socid) > 0) {
1494 $object->socid = $objsoc->id;
1495 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1496 $object->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : null);
1497 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1498 $object->fk_delivery_address = 0;
1499
1500 /*if (isModEnabled('project'))
1501 {
1502 $project = new Project($db);
1503 if ($this->fk_project > 0 && $project->fetch($this->fk_project)) {
1504 if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project;
1505 else $clonedObj->fk_project = '';
1506 } else {
1507 $clonedObj->fk_project = '';
1508 }
1509 }*/
1510 $object->fk_project = 0; // A cloned proposal is set by default to no project.
1511 }
1512
1513 // reset ref_client
1514 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1515 $object->ref_client = '';
1516 $object->ref_customer = '';
1517 }
1518
1519 // TODO Change product price if multi-prices
1520 } else {
1521 $objsoc->fetch($object->socid);
1522 }
1523
1524 // update prices
1525 if ($update_prices === true || $update_desc === true) {
1526 if ($objsoc->id > 0 && !empty($object->lines)) {
1527 if ($update_prices === true && getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1528 // If price per customer
1529 require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
1530 }
1531
1532 foreach ($object->lines as $line) {
1533 $line->id = 0;
1534
1535 if ($line->fk_product > 0) {
1536 $prod = new Product($this->db);
1537 $res = $prod->fetch($line->fk_product);
1538 if ($res > 0) {
1539 if ($update_prices === true) {
1540 $pu_ht = $prod->price;
1541 $tva_tx = (string) get_default_tva($mysoc, $objsoc, $prod->id);
1542 $remise_percent = $objsoc->remise_percent;
1543
1544 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $objsoc->price_level > 0) {
1545 $pu_ht = $prod->multiprices[$objsoc->price_level];
1546 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
1547 if (isset($prod->multiprices_tva_tx[$objsoc->price_level])) {
1548 $tva_tx = (string) $prod->multiprices_tva_tx[$objsoc->price_level];
1549 }
1550 }
1551 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1552 $prodcustprice = new ProductCustomerPrice($this->db);
1553 $filter = array('t.fk_product' => (string) $prod->id, 't.fk_soc' => (string) $objsoc->id);
1554 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
1555 if ($result) {
1556 // If there is some prices specific to the customer
1557 if (count($prodcustprice->lines) > 0) {
1558 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
1559 foreach ($prodcustprice->lines as $k => $custprice_line) {
1560 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
1561 $pu_ht = price($custprice_line->price);
1562 $tva_tx = ($custprice_line->default_vat_code ? $custprice_line->tva_tx . ' (' . $custprice_line->default_vat_code . ' )' : $custprice_line->tva_tx);
1563 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
1564 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
1565 }
1566 $remise_percent = $custprice_line->discount_percent;
1567 break;
1568 }
1569 }
1570 }
1571 }
1572 }
1573
1574 $line->subprice = $pu_ht;
1575 $line->tva_tx = $tva_tx;
1576 $line->remise_percent = $remise_percent;
1577 // Refresh the buying price too: current supplier price if one was selected on the line, otherwise let PropaleLigne::insert() recompute it (defineBuyPrice(), according to MARGIN_TYPE)
1578 $line->pa_ht = '';
1579 if ($line->fk_fournprice > 0) {
1580 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1581 $prodfourn = new ProductFournisseur($this->db);
1582 if ($prodfourn->fetch_product_fournisseur_price($line->fk_fournprice) > 0) {
1583 $line->pa_ht = price2num($prodfourn->fourn_unitprice * (1 - $prodfourn->fourn_remise_percent / 100), 'MU');
1584 } else {
1585 $line->fk_fournprice = 0;
1586 }
1587 }
1588 }
1589 if ($update_desc === true) {
1590 $line->desc = $prod->description;
1591 }
1592 }
1593 }
1594 }
1595 }
1596 }
1597
1598 $object->id = 0;
1599 $object->ref = '';
1600 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1601 $object->statut = self::STATUS_DRAFT;
1602 $object->status = self::STATUS_DRAFT;
1603
1604 // Clear fields
1605 $object->user_creation_id = $user->id;
1606 $object->user_validation_id = 0;
1607 $object->date = $now;
1608 $object->datep = $now; // deprecated
1609 $object->fin_validite = $object->date + ($object->duree_validite * 24 * 3600);
1610 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1611 $object->ref_client = '';
1612 $object->ref_customer = '';
1613 }
1614 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1615 $object->note_private = '';
1616 $object->note_public = '';
1617 }
1618 // Create clone
1619 $object->context['createfromclone'] = 'createfromclone';
1620 $result = $object->create($user);
1621 if ($result < 0) {
1623 $error++;
1624 }
1625
1626 if (!$error && !getDolGlobalInt('MAIN_IGNORE_CONTACTS_ON_CLONING')) {
1627 // copy internal contacts
1628 if ($object->copy_linked_contact($this, 'internal') < 0) {
1629 $error++;
1630 }
1631 }
1632
1633 if (!$error) {
1634 // copy external contacts if same company
1635 if ($this->socid == $object->socid) {
1636 if ($object->copy_linked_contact($this, 'external') < 0) {
1637 $error++;
1638 }
1639 }
1640 }
1641
1642 if (!$error) {
1643 // Hook of thirdparty module
1644 if (is_object($hookmanager)) {
1645 $parameters = array('objFrom' => $this, 'clonedObj' => $object);
1646 $action = '';
1647 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1648 if ($reshook < 0) {
1649 $this->setErrorsFromObject($hookmanager);
1650 $error++;
1651 }
1652 }
1653 }
1654
1655 unset($object->context['createfromclone']);
1656
1657 // End
1658 if (!$error) {
1659 $this->db->commit();
1660 return $object->id;
1661 } else {
1662 $this->db->rollback();
1663 return -1;
1664 }
1665 }
1666
1676 public function fetch($rowid, $ref = '', $ref_ext = '', $forceentity = 0)
1677 {
1678 $sql = "SELECT p.rowid, p.ref, p.entity, p.fk_soc";
1679 $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht";
1680 $sql .= ", p.datec";
1681 $sql .= ", p.date_signature as dates";
1682 $sql .= ", p.date_valid as datev";
1683 $sql .= ", p.datep as dp";
1684 $sql .= ", p.fin_validite as dfv";
1685 $sql .= ", p.date_livraison as delivery_date";
1686 $sql .= ", p.model_pdf, p.last_main_doc, p.ref_client, ref_ext, p.extraparams";
1687 $sql .= ", p.note_private, p.note_public";
1688 $sql .= ", p.fk_projet as fk_project, p.fk_statut";
1689 $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1690 $sql .= ", p.fk_delivery_address";
1691 $sql .= ", p.fk_availability";
1692 $sql .= ", p.fk_input_reason";
1693 $sql .= ", p.fk_cond_reglement";
1694 $sql .= ", p.fk_mode_reglement";
1695 $sql .= ', p.fk_account';
1696 $sql .= ", p.fk_shipping_method";
1697 $sql .= ", p.fk_warehouse";
1698 $sql .= ", p.fk_incoterms, p.location_incoterms";
1699 $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1700 $sql .= ", p.tms as date_modification";
1701 $sql .= ", i.libelle as label_incoterms";
1702 $sql .= ", c.label as statut_label";
1703 $sql .= ", ca.code as availability_code, ca.label as availability";
1704 $sql .= ", dr.code as demand_reason_code, dr.label as demand_reason";
1705 $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc, p.deposit_percent";
1706 $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1707 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
1708 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id';
1709 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')';
1710 $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').')';
1711 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1712 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1713 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1714
1715 if (!empty($ref)) {
1716 if (!empty($forceentity)) {
1717 $sql .= " WHERE p.entity = ".(int) $forceentity; // Check only the current entity because we may have the same reference in several entities
1718 } else {
1719 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
1720 }
1721 $sql .= " AND p.ref='".$this->db->escape($ref)."'";
1722 } else {
1723 // Don't use entity if you use rowid
1724 $sql .= " WHERE p.rowid = ".((int) $rowid);
1725 }
1726
1727 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1728 $resql = $this->db->query($sql);
1729 if ($resql) {
1730 if ($this->db->num_rows($resql)) {
1731 $obj = $this->db->fetch_object($resql);
1732
1733 $this->id = $obj->rowid;
1734 $this->entity = $obj->entity;
1735
1736 $this->ref = $obj->ref;
1737 $this->ref_client = $obj->ref_client;
1738 $this->ref_customer = $obj->ref_client;
1739 $this->ref_ext = $obj->ref_ext;
1740
1741 $this->total = $obj->total_ttc; // TODO deprecated
1742 $this->total_ttc = $obj->total_ttc;
1743 $this->total_ht = $obj->total_ht;
1744 $this->total_tva = $obj->total_tva;
1745 $this->total_localtax1 = $obj->localtax1;
1746 $this->total_localtax2 = $obj->localtax2;
1747
1748 $this->socid = $obj->fk_soc;
1749 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
1750
1751 $this->fk_project = $obj->fk_project;
1752 $this->project = null; // Clear if another value was already set by fetchProject
1753
1754 $this->model_pdf = $obj->model_pdf;
1755 $this->last_main_doc = $obj->last_main_doc;
1756 $this->note = $obj->note_private; // TODO deprecated
1757 $this->note_private = $obj->note_private;
1758 $this->note_public = $obj->note_public;
1759
1760 $this->status = (int) $obj->fk_statut;
1761 $this->statut = $this->status; // deprecated
1762
1763 $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
1764 $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
1765 $this->date_creation = $this->db->jdate($obj->datec); //Creation date
1766 $this->date_validation = $this->db->jdate($obj->datev); //Validation date
1767 $this->date_modification = $this->db->jdate($obj->date_modification); // tms
1768 $this->date_signature = $this->db->jdate($obj->dates); // Signature date
1769 $this->date = $this->db->jdate($obj->dp); // Proposal date
1770 $this->datep = $this->db->jdate($obj->dp); // deprecated
1771 $this->fin_validite = $this->db->jdate($obj->dfv);
1772 $this->delivery_date = $this->db->jdate($obj->delivery_date);
1773 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1774 $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
1775 $this->availability_id = $obj->fk_availability;
1776 $this->availability_code = $obj->availability_code;
1777 $this->availability = $obj->availability;
1778 $this->demand_reason_id = $obj->fk_input_reason;
1779 $this->demand_reason_code = $obj->demand_reason_code;
1780 $this->demand_reason = $obj->demand_reason;
1781 $this->fk_address = $obj->fk_delivery_address;
1782
1783 $this->mode_reglement_id = $obj->fk_mode_reglement;
1784 $this->mode_reglement_code = $obj->mode_reglement_code;
1785 $this->mode_reglement = $obj->mode_reglement;
1786 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
1787 $this->cond_reglement_id = $obj->fk_cond_reglement;
1788 $this->cond_reglement_code = $obj->cond_reglement_code;
1789 $this->cond_reglement = $obj->cond_reglement;
1790 $this->cond_reglement_label = $obj->cond_reglement;
1791 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1792 $this->deposit_percent = $obj->deposit_percent;
1793
1794 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
1795
1796 $this->user_author_id = $obj->fk_user_author;
1797 $this->user_validation_id = $obj->fk_user_valid;
1798 $this->user_closing_id = $obj->fk_user_cloture;
1799
1800 //Incoterms
1801 $this->fk_incoterms = $obj->fk_incoterms;
1802 $this->location_incoterms = $obj->location_incoterms;
1803 $this->label_incoterms = $obj->label_incoterms;
1804
1805 // Multicurrency
1806 $this->fk_multicurrency = $obj->fk_multicurrency;
1807 $this->multicurrency_code = $obj->multicurrency_code;
1808 $this->multicurrency_tx = $obj->multicurrency_tx;
1809 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1810 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1811 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1812
1813 // Retrieve all extrafield
1814 // fetch optionals attributes and labels
1815 $this->fetch_optionals();
1816
1817 $this->db->free($resql);
1818
1819 $this->lines = array();
1820
1821 // Lines
1822 $result = $this->fetch_lines();
1823 if ($result < 0) {
1824 return -3;
1825 }
1826
1827 return 1;
1828 }
1829
1830 $this->error = "Record Not Found";
1831 return 0;
1832 } else {
1833 $this->error = $this->db->lasterror();
1834 return -1;
1835 }
1836 }
1837
1845 public function update(User $user, $notrigger = 0)
1846 {
1847 global $conf;
1848
1849 $error = 0;
1850
1851 // Clean parameters
1852 if (isset($this->ref)) {
1853 $this->ref = trim($this->ref);
1854 }
1855 if (isset($this->ref_client)) {
1856 $this->ref_client = trim($this->ref_client);
1857 }
1858 if (isset($this->note) || isset($this->note_private)) {
1859 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1860 }
1861 if (isset($this->note_public)) {
1862 $this->note_public = trim($this->note_public);
1863 }
1864 if (isset($this->model_pdf)) {
1865 $this->model_pdf = trim($this->model_pdf);
1866 }
1867 if (isset($this->import_key)) {
1868 $this->import_key = trim($this->import_key);
1869 }
1870 if (!empty($this->duree_validite) && is_numeric($this->duree_validite)) {
1871 $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1872 }
1873
1874 // Check parameters
1875 // Put here code to add control on parameters values
1876
1877 // Update request
1878 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1879 $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET";
1880 $sql .= " ref = ".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1881 $sql .= " ref_client = ".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
1882 $sql .= " ref_ext = ".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1883 $sql .= " fk_soc = ".(!empty($this->socid) ? (int) $this->socid : "null").",";
1884 $sql .= " datep = ".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
1885 if (!empty($this->fin_validite)) {
1886 $sql .= " fin_validite = ".(strval($this->fin_validite) != '' ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1887 }
1888 $sql .= " date_valid = ".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1889 $sql .= " total_tva = ".(isset($this->total_tva) ? (float) $this->total_tva : "null").",";
1890 $sql .= " localtax1 = ".(isset($this->total_localtax1) ? (float) $this->total_localtax1 : "null").",";
1891 $sql .= " localtax2 = ".(isset($this->total_localtax2) ? (float) $this->total_localtax2 : "null").",";
1892 $sql .= " total_ht = ".(isset($this->total_ht) ? (float) $this->total_ht : "null").",";
1893 $sql .= " total_ttc = ".(isset($this->total_ttc) ? (float) $this->total_ttc : "null").",";
1894 $sql .= " fk_statut = ".(isset($this->status) ? (int) $this->status : "null").",";
1895 $sql .= " fk_user_author = ".(!empty($this->user_author_id) ? (int) $this->user_author_id : "null").",";
1896 $sql .= " fk_user_valid = ".(!empty($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
1897
1898 $sql .= " fk_projet = ".(!empty($this->fk_project) ? (int) $this->fk_project : "null").",";
1899 $sql .= " fk_cond_reglement = ".(!empty($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
1900 $sql .= " deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
1901 $sql .= " fk_mode_reglement = ".(!empty($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
1902 $sql .= " fk_input_reason = ".(!empty($this->demand_reason_id) ? (int) $this->demand_reason_id : "null").",";
1903 $sql .= " fk_shipping_method = ".(isset($this->shipping_method_id) ? (int) $this->shipping_method_id : "null").",";
1904 $sql .= " fk_availability = ".(!empty($this->availability_id) ? (int) $this->availability_id : "null").",";
1905 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1906 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1907 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1908 $sql .= " import_key = ".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1909 $sql .= " WHERE rowid = ".((int) $this->id);
1910
1911 $this->db->begin();
1912
1913 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1914 $resql = $this->db->query($sql);
1915 if (!$resql) {
1916 $error++;
1917 $this->errors[] = "Error ".$this->db->lasterror();
1918 }
1919
1920 if (!$error) {
1921 $result = $this->insertExtraFields();
1922 if ($result < 0) {
1923 $error++;
1924 }
1925 }
1926
1927 if (!$error && !$notrigger) {
1928 // Call trigger
1929 $result = $this->call_trigger('PROPAL_MODIFY', $user);
1930 if ($result < 0) {
1931 $error++;
1932 }
1933 // End call triggers
1934 }
1935
1936 // Commit or rollback
1937 if ($error) {
1938 foreach ($this->errors as $errmsg) {
1939 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1940 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1941 }
1942 $this->db->rollback();
1943 return -1 * $error;
1944 } else {
1945 $this->db->commit();
1946 return 1;
1947 }
1948 }
1949
1950
1951 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1960 public function fetch_lines($only_product = 0, $loadalsotranslation = 0, $sqlforgedfilters = '')
1961 {
1962 // phpcs:enable
1963 $this->lines = array();
1964
1965 $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,';
1966 $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,';
1967 $sql .= ' d.fk_unit,';
1968 $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,';
1969 $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units,';
1970 $sql .= ' p.customcode, p.fk_country as country_id, c.code as country_code,';
1971 $sql .= ' d.date_start, d.date_end, d.extraparams,';
1972 $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
1973 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as d';
1974 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
1975 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON c.rowid = p.fk_country';
1976 $sql .= ' WHERE d.fk_propal = '.((int) $this->id);
1977 if ($only_product) {
1978 $sql .= ' AND p.fk_product_type = 0';
1979 }
1980 if ($sqlforgedfilters) {
1981 $sql .= $sqlforgedfilters;
1982 }
1983 $sql .= ' ORDER BY d.rang, d.rowid';
1984
1985 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
1986 $result = $this->db->query($sql);
1987 if ($result) {
1988 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
1989
1990 $num = $this->db->num_rows($result);
1991
1992 $i = 0;
1993 while ($i < $num) {
1994 $objp = $this->db->fetch_object($result);
1995
1996 $line = new PropaleLigne($this->db);
1997
1998 $line->rowid = $objp->rowid; //Deprecated
1999 $line->id = $objp->rowid;
2000 $line->fk_propal = $objp->fk_propal;
2001 $line->fk_parent_line = $objp->fk_parent_line;
2002 $line->label = $objp->custom_label;
2003 $line->desc = $objp->description; // Description ligne
2004 $line->description = $objp->description; // Description ligne
2005 $line->qty = $objp->qty;
2006 $line->vat_src_code = $objp->vat_src_code;
2007 $line->tva_tx = $objp->tva_tx;
2008 $line->localtax1_tx = $objp->localtax1_tx;
2009 $line->localtax2_tx = $objp->localtax2_tx;
2010 $line->localtax1_type = $objp->localtax1_type;
2011 $line->localtax2_type = $objp->localtax2_type;
2012 $line->subprice = $objp->subprice;
2013 $line->fk_remise_except = $objp->fk_remise_except;
2014 $line->remise_percent = $objp->remise_percent;
2015
2016 $line->info_bits = $objp->info_bits;
2017 $line->total_ht = $objp->total_ht;
2018 $line->total_tva = $objp->total_tva;
2019 $line->total_localtax1 = $objp->total_localtax1;
2020 $line->total_localtax2 = $objp->total_localtax2;
2021 $line->total_ttc = $objp->total_ttc;
2022 $line->fk_fournprice = $objp->fk_fournprice;
2023 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2024 $line->pa_ht = $marginInfos[0];
2025 $line->marge_tx = $marginInfos[1];
2026 $line->marque_tx = $marginInfos[2];
2027 $line->special_code = $objp->special_code;
2028 $line->rang = $objp->rang;
2029
2030 $line->fk_product = $objp->fk_product;
2031
2032 $line->ref = $objp->product_ref; // deprecated
2033 $line->libelle = $objp->product_label; // deprecated
2034
2035 $line->product_ref = $objp->product_ref;
2036 $line->product_label = $objp->product_label;
2037 $line->product_desc = $objp->product_desc; // Description produit
2038 $line->product_tobatch = $objp->product_tobatch;
2039 $line->product_barcode = $objp->product_barcode;
2040 $line->product_custom_code = $objp->customcode;
2041 $line->product_custom_country_id = $objp->country_id;
2042 $line->product_custom_country_code = $objp->country_code;
2043 $line->product_type = $objp->product_type;
2044 $line->fk_product_type = $objp->fk_product_type; // deprecated
2045
2046 $line->fk_unit = $objp->fk_unit;
2047 $line->weight = $objp->weight;
2048 $line->weight_units = $objp->weight_units;
2049 $line->volume = $objp->volume;
2050 $line->volume_units = $objp->volume_units;
2051
2052 $line->date_start = $this->db->jdate($objp->date_start);
2053 $line->date_end = $this->db->jdate($objp->date_end);
2054
2055 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2056
2057 // Multicurrency
2058 $line->fk_multicurrency = $objp->fk_multicurrency;
2059 $line->multicurrency_code = $objp->multicurrency_code;
2060 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2061 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2062 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2063 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2064
2065 $line->fetch_optionals();
2066
2067 // multilangs
2068 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2069 $tmpproduct = new Product($this->db);
2070 $tmpproduct->fetch($objp->fk_product);
2071 $tmpproduct->getMultiLangs();
2072
2073 $line->multilangs = $tmpproduct->multilangs;
2074 }
2075
2076 $this->lines[$i] = $line;
2077
2078 $i++;
2079 }
2080
2081 $this->db->free($result);
2082
2083 return $num;
2084 } else {
2085 $this->error = $this->db->lasterror();
2086 return -3;
2087 }
2088 }
2089
2097 public function valid($user, $notrigger = 0)
2098 {
2099 global $conf;
2100
2101 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2102
2103 $error = 0;
2104
2105 // Protection
2106 if ($this->status == self::STATUS_VALIDATED) {
2107 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
2108 return 0;
2109 }
2110
2111 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('propal', 'creer'))
2112 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('propal', 'propal_advance', 'validate')))) {
2113 $this->error = 'ErrorPermissionDenied';
2114 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
2115 return -1;
2116 }
2117
2118 if (!getDolGlobalBool('PROPALE_NOCHECK_ONSALE_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines()) {
2119 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
2120 return -1;
2121 }
2122
2123 $now = dol_now();
2124
2125 $this->db->begin();
2126
2127 // Numbering module definition
2128 $soc = new Societe($this->db);
2129 $soc->fetch($this->socid);
2130
2131 // Define new ref
2132 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
2133 $num = $this->getNextNumRef($soc);
2134 } else {
2135 $num = (string) $this->ref;
2136 }
2137 $this->newref = dol_sanitizeFileName($num);
2138
2139 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2140 $sql .= " SET ref = '".$this->db->escape($num)."',";
2141 $sql .= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".((int) $user->id);
2142 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
2143
2144 dol_syslog(get_class($this)."::valid", LOG_DEBUG);
2145 $resql = $this->db->query($sql);
2146 if (!$resql) {
2147 dol_print_error($this->db);
2148 $error++;
2149 }
2150
2151 // Trigger calls
2152 if (!$error && !$notrigger) {
2153 // Call trigger
2154 $result = $this->call_trigger('PROPAL_VALIDATE', $user);
2155 if ($result < 0) {
2156 $error++;
2157 }
2158 // End call triggers
2159 }
2160
2161 if (!$error) {
2162 $this->oldref = $this->ref;
2163
2164 // Rename directory if dir was a temporary ref
2165 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
2166 // Now we rename also files into index
2167 $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)."'";
2168 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
2169 $resql = $this->db->query($sql);
2170 if (!$resql) {
2171 $error++;
2172 $this->error = $this->db->lasterror();
2173 }
2174 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'propale/".$this->db->escape($this->newref)."'";
2175 $sql .= " WHERE filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
2176 $resql = $this->db->query($sql);
2177 if (!$resql) {
2178 $error++;
2179 $this->error = $this->db->lasterror();
2180 }
2181
2182 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
2183 $oldref = dol_sanitizeFileName($this->ref);
2184 $newref = dol_sanitizeFileName($num);
2185 $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref;
2186 $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref;
2187 if (!$error && file_exists($dirsource)) {
2188 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
2189 if (@rename($dirsource, $dirdest)) {
2190 dol_syslog("Rename ok");
2191 // Rename docs starting with $oldref with $newref
2192 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
2193 foreach ($listoffiles as $fileentry) {
2194 $dirsource = $fileentry['name'];
2195 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
2196 $dirsource = $fileentry['path'].'/'.$dirsource;
2197 $dirdest = $fileentry['path'].'/'.$dirdest;
2198 @rename($dirsource, $dirdest);
2199 }
2200 }
2201 }
2202 }
2203
2204 $this->ref = $num;
2205 $this->statut = self::STATUS_VALIDATED;
2206 $this->user_validation_id = $user->id;
2207 $this->datev = $now;
2208 $this->date_validation = $now;
2209
2210 $this->db->commit();
2211 return 1;
2212 } else {
2213 $this->db->rollback();
2214 return -1;
2215 }
2216 }
2217
2218
2219 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2228 public function set_date($user, $date, $notrigger = 0)
2229 {
2230 // phpcs:enable
2231 if (empty($date)) {
2232 $this->error = 'ErrorBadParameter';
2233 dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
2234 return -1;
2235 }
2236
2237 if ($user->hasRight('propal', 'creer')) {
2238 $error = 0;
2239
2240 $this->db->begin();
2241
2242 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2243 $sql .= " SET datep = '".$this->db->idate($date)."'";
2244 $sql .= " WHERE rowid = ".((int) $this->id);
2245
2246 dol_syslog(__METHOD__, LOG_DEBUG);
2247 $resql = $this->db->query($sql);
2248 if (!$resql) {
2249 $this->errors[] = $this->db->error();
2250 $error++;
2251 }
2252
2253 if (!$error) {
2254 $this->oldcopy = clone $this;
2255 $this->date = $date;
2256 $this->datep = $date; // deprecated
2257 }
2258
2259 if (!$notrigger && empty($error)) {
2260 // Call trigger
2261 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2262 if ($result < 0) {
2263 $error++;
2264 }
2265 // End call triggers
2266 }
2267
2268 if (!$error) {
2269 $this->db->commit();
2270 return 1;
2271 } else {
2272 foreach ($this->errors as $errmsg) {
2273 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2274 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2275 }
2276 $this->db->rollback();
2277 return -1 * $error;
2278 }
2279 }
2280
2281 return -1;
2282 }
2283
2284 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2293 public function set_echeance($user, $date_end_validity, $notrigger = 0)
2294 {
2295 // phpcs:enable
2296 if ($user->hasRight('propal', 'creer')) {
2297 $error = 0;
2298
2299 $this->db->begin();
2300
2301 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2302 $sql .= " SET fin_validite = ".($date_end_validity != '' ? "'".$this->db->idate($date_end_validity)."'" : 'null');
2303 $sql .= " WHERE rowid = ".((int) $this->id);
2304
2305 dol_syslog(__METHOD__, LOG_DEBUG);
2306
2307 $resql = $this->db->query($sql);
2308 if (!$resql) {
2309 $this->errors[] = $this->db->error();
2310 $error++;
2311 }
2312
2313
2314 if (!$error) {
2315 $this->oldcopy = clone $this;
2316 $this->fin_validite = $date_end_validity;
2317 }
2318
2319 if (!$notrigger && empty($error)) {
2320 // Call trigger
2321 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2322 if ($result < 0) {
2323 $error++;
2324 }
2325 // End call triggers
2326 }
2327
2328 if (!$error) {
2329 $this->db->commit();
2330 return 1;
2331 } else {
2332 foreach ($this->errors as $errmsg) {
2333 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2334 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2335 }
2336 $this->db->rollback();
2337 return -1 * $error;
2338 }
2339 }
2340
2341 return -1;
2342 }
2343
2344 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2354 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2355 {
2356 // phpcs:enable
2357 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2358 }
2359
2368 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2369 {
2370 if ($user->hasRight('propal', 'creer')) {
2371 $error = 0;
2372
2373 $this->db->begin();
2374
2375 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2376 $sql .= " SET date_livraison = ".(isDolTms($delivery_date) ? "'".$this->db->idate($delivery_date)."'" : 'null');
2377 $sql .= " WHERE rowid = ".((int) $this->id);
2378
2379 dol_syslog(__METHOD__, LOG_DEBUG);
2380 $resql = $this->db->query($sql);
2381 if (!$resql) {
2382 $this->errors[] = $this->db->error();
2383 $error++;
2384 }
2385
2386 if (!$error) {
2387 $this->oldcopy = clone $this;
2388 $this->delivery_date = $delivery_date;
2389 }
2390
2391 if (!$notrigger && empty($error)) {
2392 // Call trigger
2393 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2394 if ($result < 0) {
2395 $error++;
2396 }
2397 // End call triggers
2398 }
2399
2400 if (!$error) {
2401 $this->db->commit();
2402 return 1;
2403 } else {
2404 foreach ($this->errors as $errmsg) {
2405 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2406 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2407 }
2408 $this->db->rollback();
2409 return -1 * $error;
2410 }
2411 }
2412
2413 return -1;
2414 }
2415
2416 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2425 public function set_availability($user, $id, $notrigger = 0)
2426 {
2427 // phpcs:enable
2428 if ($user->hasRight('propal', 'creer') && $this->status >= self::STATUS_DRAFT) {
2429 $error = 0;
2430
2431 $this->db->begin();
2432
2433 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2434 $sql .= " SET fk_availability = ".((int) $id);
2435 $sql .= " WHERE rowid = ".((int) $this->id);
2436
2437 dol_syslog(__METHOD__.' availability('.$id.')', LOG_DEBUG);
2438 $resql = $this->db->query($sql);
2439 if (!$resql) {
2440 $this->errors[] = $this->db->error();
2441 $error++;
2442 }
2443
2444 if (!$error) {
2445 $this->oldcopy = clone $this;
2446 $this->fk_availability = $id;
2447 $this->availability_id = $id;
2448 }
2449
2450 if (!$notrigger && empty($error)) {
2451 // Call trigger
2452 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2453 if ($result < 0) {
2454 $error++;
2455 }
2456 // End call triggers
2457 }
2458
2459 if (!$error) {
2460 $this->db->commit();
2461 return 1;
2462 } else {
2463 foreach ($this->errors as $errmsg) {
2464 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2465 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2466 }
2467 $this->db->rollback();
2468 return -1 * $error;
2469 }
2470 } else {
2471 $error_str = 'Propal status do not meet requirement '.$this->status;
2472 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2473 $this->error = $error_str;
2474 $this->errors[] = $this->error;
2475 return -2;
2476 }
2477 }
2478
2479 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2488 public function set_demand_reason($user, $id, $notrigger = 0)
2489 {
2490 // phpcs:enable
2491 if ($user->hasRight('propal', 'creer') && $this->status >= self::STATUS_DRAFT) {
2492 $error = 0;
2493
2494 $this->db->begin();
2495
2496 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2497 $sql .= " SET fk_input_reason = ".((int) $id);
2498 $sql .= " WHERE rowid = ".((int) $this->id);
2499
2500 dol_syslog(__METHOD__, LOG_DEBUG);
2501 $resql = $this->db->query($sql);
2502 if (!$resql) {
2503 $this->errors[] = $this->db->error();
2504 $error++;
2505 }
2506
2507
2508 if (!$error) {
2509 $this->oldcopy = clone $this;
2510
2511 $this->demand_reason_id = $id;
2512 }
2513
2514
2515 if (!$notrigger && empty($error)) {
2516 // Call trigger
2517 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2518 if ($result < 0) {
2519 $error++;
2520 }
2521 // End call triggers
2522 }
2523
2524 if (!$error) {
2525 $this->db->commit();
2526 return 1;
2527 } else {
2528 foreach ($this->errors as $errmsg) {
2529 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2530 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2531 }
2532 $this->db->rollback();
2533 return -1 * $error;
2534 }
2535 } else {
2536 $error_str = 'Propal status do not meet requirement '.$this->status;
2537 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2538 $this->error = $error_str;
2539 $this->errors[] = $this->error;
2540 return -2;
2541 }
2542 }
2543
2544 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2553 public function set_ref_client($user, $ref_client, $notrigger = 0)
2554 {
2555 // phpcs:enable
2556 if ($user->hasRight('propal', 'creer')) {
2557 $error = 0;
2558
2559 $this->db->begin();
2560
2561 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2562 $sql .= " SET ref_client = ".(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
2563 $sql .= " WHERE rowid = ".((int) $this->id);
2564
2565 dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2566 $resql = $this->db->query($sql);
2567 if (!$resql) {
2568 $this->errors[] = $this->db->error();
2569 $error++;
2570 }
2571
2572 if (!$error) {
2573 $this->oldcopy = clone $this;
2574 $this->ref_customer = $ref_client;
2575 $this->ref_client = $ref_client;
2576 }
2577
2578 if (!$notrigger && empty($error)) {
2579 // Call trigger
2580 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2581 if ($result < 0) {
2582 $error++;
2583 }
2584 // End call triggers
2585 }
2586
2587 if (!$error) {
2588 $this->db->commit();
2589 return 1;
2590 } else {
2591 foreach ($this->errors as $errmsg) {
2592 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2593 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2594 }
2595 $this->db->rollback();
2596 return -1 * $error;
2597 }
2598 }
2599
2600 return -1;
2601 }
2602
2603
2613 public function reopen($user, $status, $note = '', $notrigger = 0)
2614 {
2615 $error = 0;
2616
2617 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2618 $sql .= " SET fk_statut = ".((int) $status).",";
2619 if (!empty($note)) {
2620 $sql .= " note_private = '".$this->db->escape($note)."',";
2621 }
2622 $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
2623 $sql .= " WHERE rowid = ".((int) $this->id);
2624
2625 $this->db->begin();
2626
2627 dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
2628 $resql = $this->db->query($sql);
2629 if (!$resql) {
2630 $error++;
2631 $this->errors[] = "Error ".$this->db->lasterror();
2632 }
2633 if (!$error) {
2634 if (!$notrigger) {
2635 // Call trigger
2636 $result = $this->call_trigger('PROPAL_REOPEN', $user);
2637 if ($result < 0) {
2638 $error++;
2639 }
2640 // End call triggers
2641 }
2642 }
2643
2644 // Commit or rollback
2645 if ($error) {
2646 if (!empty($this->errors)) {
2647 foreach ($this->errors as $errmsg) {
2648 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2649 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2650 }
2651 }
2652 $this->db->rollback();
2653 return -1 * $error;
2654 } else {
2655 $this->statut = $status;
2656 $this->status = $status;
2657
2658 $this->db->commit();
2659 return 1;
2660 }
2661 }
2662
2673 public function closeProposal($user, $status, $note_private = '', $notrigger = 0, $note_public = '')
2674 {
2675 global $langs,$conf;
2676
2677 $error = 0;
2678 $now = dol_now();
2679
2680 $this->db->begin();
2681
2682 $newprivatenote = dol_concatdesc($this->note_private, $note_private);
2683 $newpublicnote = dol_concatdesc($this->note_public, $note_public);
2684
2685 if (!getDolGlobalString('PROPALE_KEEP_OLD_SIGNATURE_INFO')) {
2686 $date_signature = $now;
2687 $fk_user_signature = $user->id;
2688 } else {
2689 $this->info($this->id);
2690 if (!isset($this->date_signature) || $this->date_signature == '') {
2691 $date_signature = $now;
2692 $fk_user_signature = $user->id;
2693 } else {
2694 $date_signature = $this->date_signature;
2695 $fk_user_signature = $this->user_signature->id;
2696 }
2697 }
2698
2699 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2700 $sql .= " SET fk_statut = ".((int) $status).", note_private = '".$this->db->escape($newprivatenote)."', note_public = '".$this->db->escape($newpublicnote)."'";
2701 if ($status == self::STATUS_SIGNED) {
2702 $sql .= ", date_signature='".$this->db->idate($now)."', fk_user_signature = ".($fk_user_signature);
2703 }
2704 $sql .= " WHERE rowid = ".((int) $this->id);
2705
2706 $resql = $this->db->query($sql);
2707 if ($resql) {
2708 // Status self::STATUS_REFUSED by default
2709 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_CLOSED', $this->model_pdf);
2710 $triggerName = 'PROPAL_CLOSE_REFUSED'; // used later in call_trigger()
2711
2712 if ($status == self::STATUS_SIGNED) { // Status self::STATUS_SIGNED
2713 $triggerName = 'PROPAL_CLOSE_SIGNED'; // used later in call_trigger()
2714 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_TOBILL', $this->model_pdf);
2715
2716 // The connected company is classified as a client
2717 $soc = new Societe($this->db);
2718 $soc->id = $this->socid;
2719 $result = $soc->setAsCustomer();
2720
2721 if ($result < 0) {
2722 $this->error = $this->db->lasterror();
2723 $this->db->rollback();
2724 return -2;
2725 }
2726 }
2727
2728 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE') && !getDolGlobalInt('PROPAL_DISABLE_AUTOUPDATE_ON_CLOSE')) {
2729 // Define output language
2730 $outputlangs = $langs;
2731 if (getDolGlobalInt('MAIN_MULTILANGS')) {
2732 $outputlangs = new Translate("", $conf);
2733 $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2734 $outputlangs->setDefaultLang($newlang);
2735 }
2736
2737 // PDF
2738 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
2739 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
2740 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
2741
2742 //$ret=$object->fetch($id); // Reload to get new records
2743 $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2744 }
2745
2746 $this->oldcopy = clone $this;
2747 $this->statut = $status; // deprecated
2748 $this->status = $status;
2749 $this->date_signature = $date_signature;
2750 $this->note_private = $newprivatenote;
2751
2752 if (!$notrigger && empty($error)) {
2753 // Call trigger
2754 $result = $this->call_trigger($triggerName, $user);
2755 if ($result < 0) {
2756 $error++;
2757 }
2758 // End call triggers
2759 }
2760
2761 if (!$error) {
2762 $this->db->commit();
2763 return 1;
2764 } else {
2765 foreach ($this->errors as $errmsg) {
2766 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2767 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2768 }
2769 if (!empty($this->oldcopy)) {
2770 $this->statut = $this->oldcopy->status; // deprecated
2771 $this->status = $this->oldcopy->status;
2772 $this->date_signature = $this->oldcopy->date_signature;
2773 $this->note_private = $this->oldcopy->note_private;
2774 }
2775
2776 $this->db->rollback();
2777 return -1;
2778 }
2779 } else {
2780 $this->error = $this->db->lasterror();
2781 $this->db->rollback();
2782 return -1;
2783 }
2784 }
2785
2794 public function classifyBilled(User $user, $notrigger = 0, $note = '')
2795 {
2796 global $conf, $langs;
2797
2798 $error = 0;
2799
2800 $now = dol_now();
2801 $num = 0;
2802
2803 $triggerName = 'PROPAL_CLASSIFY_BILLED';
2804
2805 $this->db->begin();
2806
2807 $newprivatenote = dol_concatdesc($this->note_private, $note);
2808
2809 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2810 $sql .= " SET fk_statut = ".self::STATUS_BILLED.", ";
2811 $sql .= " note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".((int) $user->id);
2812 $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_SIGNED);
2813
2814 dol_syslog(__METHOD__, LOG_DEBUG);
2815 $resql = $this->db->query($sql);
2816 if (!$resql) {
2817 $this->errors[] = $this->db->error();
2818 $error++;
2819 } else {
2820 $num = $this->db->affected_rows($resql);
2821 }
2822
2823 if (!$error) {
2824 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_CLOSED', $this->model_pdf);
2825
2826 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2827 // Define output language
2828 $outputlangs = $langs;
2829 if (getDolGlobalInt('MAIN_MULTILANGS')) {
2830 $outputlangs = new Translate("", $conf);
2831 $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2832 $outputlangs->setDefaultLang($newlang);
2833 }
2834
2835 // PDF
2836 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
2837 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
2838 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
2839
2840 //$ret=$object->fetch($id); // Reload to get new records
2841 $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2842 }
2843
2844 $this->oldcopy = clone $this;
2845 $this->statut = self::STATUS_BILLED;
2846 $this->status = self::STATUS_BILLED;
2847 $this->date_cloture = $now;
2848 $this->note_private = $newprivatenote;
2849 }
2850
2851 if (!$notrigger && empty($error)) {
2852 // Call trigger
2853 $result = $this->call_trigger($triggerName, $user);
2854 if ($result < 0) {
2855 $error++;
2856 }
2857 // End call triggers
2858 }
2859
2860 if (!$error) {
2861 $this->db->commit();
2862 return $num;
2863 } else {
2864 foreach ($this->errors as $errmsg) {
2865 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2866 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2867 }
2868 $this->db->rollback();
2869 return -1 * $error;
2870 }
2871 }
2872
2879 public function setCancel(User $user)
2880 {
2881 $error = 0;
2882
2883 $this->db->begin();
2884
2885 $sql = "UPDATE ". MAIN_DB_PREFIX . $this->table_element;
2886 $sql .= " SET fk_statut = " . self::STATUS_CANCELED . ",";
2887 $sql .= " fk_user_modif = " . ((int) $user->id);
2888 $sql .= " WHERE rowid = " . ((int) $this->id);
2889
2890 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
2891 if ($this->db->query($sql)) {
2892 // Call trigger
2893 $result = $this->call_trigger('PROPAL_CANCEL', $user);
2894 if ($result < 0) {
2895 $error++;
2896 }
2897 // End call triggers
2898
2899 if (!$error) {
2900 $this->statut = self::STATUS_CANCELED; // deprecated
2902 $this->db->commit();
2903 return 1;
2904 } else {
2905 foreach ($this->errors as $errmsg) {
2906 dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
2907 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2908 }
2909 $this->db->rollback();
2910 return -1;
2911 }
2912 } else {
2913 $this->error = $this->db->error();
2914 $this->db->rollback();
2915 return -1;
2916 }
2917 }
2918
2919 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2927 public function setDraft($user, $notrigger = 0)
2928 {
2929 // phpcs:enable
2930 $error = 0;
2931
2932 // Protection
2933 if ($this->status <= self::STATUS_DRAFT) {
2934 return 0;
2935 }
2936
2937 dol_syslog(get_class($this)."::setDraft", LOG_DEBUG);
2938
2939 $this->db->begin();
2940
2941 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2942 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2943 $sql .= ", online_sign_ip = NULL , online_sign_name = NULL";
2944 $sql .= " WHERE rowid = ".((int) $this->id);
2945
2946 $resql = $this->db->query($sql);
2947 if (!$resql) {
2948 $this->errors[] = $this->db->error();
2949 $error++;
2950 }
2951
2952 if (!$error) {
2953 $this->oldcopy = clone $this;
2954 }
2955
2956 if (!$notrigger && empty($error)) {
2957 // Call trigger
2958 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2959 if ($result < 0) {
2960 $error++;
2961 }
2962 // End call triggers
2963 }
2964
2965 if (!$error) {
2966 $this->statut = self::STATUS_DRAFT; // deprecated
2967 $this->status = self::STATUS_DRAFT;
2968
2969 $this->db->commit();
2970 return 1;
2971 } else {
2972 foreach ($this->errors as $errmsg) {
2973 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2974 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2975 }
2976 $this->db->rollback();
2977 return -1 * $error;
2978 }
2979 }
2980
2981
2982 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2996 public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datep', $sortorder = 'DESC')
2997 {
2998 // phpcs:enable
2999 global $user;
3000
3001 $ga = array();
3002
3003 $sql = "SELECT s.rowid, s.nom as name, s.client,";
3004 $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
3005 $sql .= " p.datep as dp, p.fin_validite as datelimite";
3006 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX.$this->table_element." as p, ".MAIN_DB_PREFIX."c_propalst as c";
3007 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3008 $sql .= " AND p.fk_soc = s.rowid";
3009 $sql .= " AND p.fk_statut = c.id";
3010
3011 // If the internal user must only see his customers, force searching by him
3012 $search_sale = 0;
3013 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3014 $search_sale = $user->id;
3015 }
3016 // Search on sale representative
3017 if ($search_sale && $search_sale != '-1') {
3018 if ($search_sale == -2) {
3019 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3020 } elseif ($search_sale > 0) {
3021 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
3022 }
3023 }
3024 // Search on socid
3025 if ($socid) {
3026 $sql .= " AND p.fk_soc = ".((int) $socid);
3027 }
3028 if ($draft) {
3029 $sql .= " AND p.fk_statut = ".((int) self::STATUS_DRAFT);
3030 }
3031 if ($notcurrentuser > 0) {
3032 $sql .= " AND p.fk_user_author <> ".((int) $user->id);
3033 }
3034 $sql .= $this->db->order($sortfield, $sortorder);
3035 $sql .= $this->db->plimit($limit, $offset);
3036
3037 $result = $this->db->query($sql);
3038 if ($result) {
3039 $num = $this->db->num_rows($result);
3040 if ($num) {
3041 $i = 0;
3042 while ($i < $num) {
3043 $obj = $this->db->fetch_object($result);
3044
3045 if ($shortlist == 1) {
3046 $ga[$obj->propalid] = $obj->ref;
3047 } elseif ($shortlist == 2) {
3048 $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
3049 } else {
3050 $ga[$i]['id'] = $obj->propalid;
3051 $ga[$i]['ref'] = $obj->ref;
3052 $ga[$i]['name'] = $obj->name;
3053 }
3054
3055 $i++;
3056 }
3057 }
3058 return $ga;
3059 } else {
3060 dol_print_error($this->db);
3061 return -1;
3062 }
3063 }
3064
3070 public function getInvoiceArrayList()
3071 {
3072 return $this->InvoiceArrayList($this->id);
3073 }
3074
3075 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3082 public function InvoiceArrayList($id)
3083 {
3084 // phpcs:enable
3085 $ga = array();
3086 $linkedInvoices = array();
3087
3088 $this->fetchObjectLinked($id, $this->element);
3089 foreach ($this->linkedObjectsIds as $objecttype => $objectid) {
3090 // Nouveau système du common object renvoi des rowid et non un id linéaire de 1 à n
3091 // On parcourt donc une liste d'objets en tant qu'objet unique
3092 foreach ($objectid as $key => $object) {
3093 // Cas des factures liees directement
3094 if ($objecttype == 'facture') {
3095 $linkedInvoices[] = $object;
3096 } else {
3097 // Cas des factures liees par un autre object (ex: commande)
3098 $this->fetchObjectLinked($object, $objecttype);
3099 foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) {
3100 foreach ($subobjectid as $subkey => $subobject) {
3101 if ($subobjecttype == 'facture') {
3102 $linkedInvoices[] = $subobject;
3103 }
3104 }
3105 }
3106 }
3107 }
3108 }
3109
3110 if (count($linkedInvoices) > 0) {
3111 $sql = "SELECT rowid as facid, ref, total_ht as total, datef as df, fk_user_author, fk_statut, paye";
3112 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
3113 $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $linkedInvoices)).")";
3114
3115 dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
3116 $resql = $this->db->query($sql);
3117
3118 if ($resql) {
3119 $tab_sqlobj = array();
3120 $nump = $this->db->num_rows($resql);
3121 for ($i = 0; $i < $nump; $i++) {
3122 $sqlobj = $this->db->fetch_object($resql);
3123 $tab_sqlobj[] = $sqlobj;
3124 }
3125 $this->db->free($resql);
3126
3127 $nump = count($tab_sqlobj);
3128
3129 if ($nump) {
3130 $i = 0;
3131 while ($i < $nump) {
3132 $obj = array_shift($tab_sqlobj);
3133
3134 $ga[$i] = $obj;
3135
3136 $i++;
3137 }
3138 }
3139 return $ga;
3140 } else {
3141 return -1;
3142 }
3143 } else {
3144 return $ga;
3145 }
3146 }
3147
3155 public function delete($user, $notrigger = 0)
3156 {
3157 global $conf;
3158 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3159
3160 $error = 0;
3161
3162 $this->db->begin();
3163
3164 if (!$notrigger) {
3165 // Call trigger
3166 $result = $this->call_trigger('PROPAL_DELETE', $user);
3167 if ($result < 0) {
3168 $error++;
3169 }
3170 // End call triggers
3171 }
3172
3173 // Remove linked categories.
3174 if (!$error) {
3175 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_propal";
3176 $sql .= " WHERE fk_propal = ".((int) $this->id);
3177
3178 $result = $this->db->query($sql);
3179 if (!$result) {
3180 $error++;
3181 $this->error = $this->db->lasterror();
3182 $this->errors[] = $this->error;
3183 }
3184 }
3185
3186 // Delete extrafields of lines and lines
3187 if (!$error && !empty($this->table_element_line)) {
3188 $tabletodelete = $this->table_element_line;
3189 $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).")";
3190 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
3191 if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
3192 $error++;
3193 $this->error = $this->db->lasterror();
3194 $this->errors[] = $this->error;
3195 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3196 }
3197 }
3198
3199 if (!$error) {
3200 // Delete linked object
3201 $res = $this->deleteObjectLinked();
3202 if ($res < 0) {
3203 $error++;
3204 }
3205 }
3206
3207 if (!$error) {
3208 // Delete linked contacts
3209 $res = $this->delete_linked_contact();
3210 if ($res < 0) {
3211 $error++;
3212 }
3213 }
3214
3215 // Removed extrafields of object
3216 if (!$error) {
3217 $result = $this->deleteExtraFields();
3218 if ($result < 0) {
3219 $error++;
3220 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3221 }
3222 }
3223
3224 // Delete main record
3225 if (!$error) {
3226 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
3227 $res = $this->db->query($sql);
3228 if (!$res) {
3229 $error++;
3230 $this->error = $this->db->lasterror();
3231 $this->errors[] = $this->error;
3232 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3233 }
3234 }
3235
3236 // Delete record into ECM index and physically
3237 if (!$error) {
3238 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
3239 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3240 if (!$res) {
3241 $error++;
3242 }
3243 }
3244
3245 if (!$error) {
3246 // We remove directory
3247 $ref = dol_sanitizeFileName($this->ref);
3248 if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref)) {
3249 $dir = $conf->propal->multidir_output[$this->entity]."/".$ref;
3250 $file = $dir."/".$ref.".pdf";
3251 if (file_exists($file)) {
3252 dol_delete_preview($this);
3253
3254 if (!dol_delete_file($file, 0, 0, 0, $this)) {
3255 $this->error = 'ErrorFailToDeleteFile';
3256 $this->errors[] = $this->error;
3257 $this->db->rollback();
3258 return 0;
3259 }
3260 }
3261 if (file_exists($dir)) {
3262 $res = @dol_delete_dir_recursive($dir); // delete files physically + into ecm tables
3263 if (!$res) {
3264 $this->error = 'ErrorFailToDeleteDir';
3265 $this->errors[] = $this->error;
3266 $this->db->rollback();
3267 return 0;
3268 }
3269 }
3270 }
3271 }
3272
3273 if (!$error) {
3274 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
3275 $this->db->commit();
3276 return 1;
3277 } else {
3278 $this->db->rollback();
3279 return -1;
3280 }
3281 }
3282
3291 public function availability($availability_id, $notrigger = 0)
3292 {
3293 global $user;
3294
3295 if ($this->status >= self::STATUS_DRAFT) {
3296 $error = 0;
3297
3298 $this->db->begin();
3299
3300 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
3301 $sql .= ' SET fk_availability = '.((int) $availability_id);
3302 $sql .= ' WHERE rowid='.((int) $this->id);
3303
3304 dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
3305 $resql = $this->db->query($sql);
3306 if (!$resql) {
3307 $this->errors[] = $this->db->error();
3308 $error++;
3309 }
3310
3311 if (!$error) {
3312 $this->oldcopy = clone $this;
3313 $this->availability_id = $availability_id;
3314 }
3315
3316 if (!$notrigger && empty($error)) {
3317 // Call trigger
3318 $result = $this->call_trigger('PROPAL_MODIFY', $user);
3319 if ($result < 0) {
3320 $error++;
3321 }
3322 // End call triggers
3323 }
3324
3325 if (!$error) {
3326 $this->db->commit();
3327 return 1;
3328 } else {
3329 foreach ($this->errors as $errmsg) {
3330 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3331 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3332 }
3333 $this->db->rollback();
3334 return -1 * $error;
3335 }
3336 } else {
3337 $error_str = 'Propal status do not meet requirement '.$this->status;
3338 dol_syslog(__METHOD__.$error_str, LOG_ERR);
3339 $this->error = $error_str;
3340 $this->errors[] = $this->error;
3341 return -2;
3342 }
3343 }
3344
3345 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3354 public function demand_reason($demand_reason_id, $notrigger = 0)
3355 {
3356 // phpcs:enable
3357 global $user;
3358
3359 if ($this->status >= self::STATUS_DRAFT) {
3360 $error = 0;
3361
3362 $this->db->begin();
3363
3364 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
3365 $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
3366 $sql .= ' WHERE rowid='.((int) $this->id);
3367
3368 dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
3369 $resql = $this->db->query($sql);
3370 if (!$resql) {
3371 $this->errors[] = $this->db->error();
3372 $error++;
3373 }
3374
3375 if (!$error) {
3376 $this->oldcopy = clone $this;
3377 $this->demand_reason_id = $demand_reason_id;
3378 }
3379
3380 if (!$notrigger && empty($error)) {
3381 // Call trigger
3382 $result = $this->call_trigger('PROPAL_MODIFY', $user);
3383 if ($result < 0) {
3384 $error++;
3385 }
3386 // End call triggers
3387 }
3388
3389 if (!$error) {
3390 $this->db->commit();
3391 return 1;
3392 } else {
3393 foreach ($this->errors as $errmsg) {
3394 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3395 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3396 }
3397 $this->db->rollback();
3398 return -1 * $error;
3399 }
3400 } else {
3401 $error_str = 'Propal status do not meet requirement '.$this->status;
3402 dol_syslog(__METHOD__.$error_str, LOG_ERR);
3403 $this->error = $error_str;
3404 $this->errors[] = $this->error;
3405 return -2;
3406 }
3407 }
3408
3409
3416 public function info($id)
3417 {
3418 $sql = "SELECT c.rowid, ";
3419 $sql .= " c.datec, c.date_valid as datev, c.date_signature, c.date_cloture,";
3420 $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_signature, c.fk_user_cloture";
3421 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
3422 $sql .= " WHERE c.rowid = ".((int) $id);
3423
3424 $result = $this->db->query($sql);
3425
3426 if ($result) {
3427 if ($this->db->num_rows($result)) {
3428 $obj = $this->db->fetch_object($result);
3429
3430 $this->id = $obj->rowid;
3431
3432 $this->date_creation = $this->db->jdate($obj->datec);
3433 $this->date_validation = $this->db->jdate($obj->datev);
3434 $this->date_signature = $this->db->jdate($obj->date_signature);
3435 $this->date_cloture = $this->db->jdate($obj->date_cloture);
3436
3437 $this->user_creation_id = $obj->fk_user_author;
3438 $this->user_validation_id = $obj->fk_user_valid;
3439
3440 if ($obj->fk_user_signature) {
3441 $user_signature = new User($this->db);
3442 $user_signature->fetch($obj->fk_user_signature);
3443 $this->user_signature = $user_signature;
3444 }
3445
3446 $this->user_closing_id = $obj->fk_user_cloture;
3447 }
3448 $this->db->free($result);
3449 } else {
3450 dol_print_error($this->db);
3451 }
3452 }
3453
3454
3461 public function getLibStatut($mode = 0)
3462 {
3463 return $this->LibStatut($this->status, $mode);
3464 }
3465
3466 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3474 public function LibStatut($status, $mode = 1)
3475 {
3476 // phpcs:enable
3477 global $hookmanager;
3478
3479 // Init/load array of translation of status
3480 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3481 global $langs;
3482 $langs->load("propal");
3483 $this->labelStatus[-1] = $langs->transnoentitiesnoconv("PropalStatusCanceled");
3484 $this->labelStatus[0] = $langs->transnoentitiesnoconv("PropalStatusDraft");
3485 $this->labelStatus[1] = $langs->transnoentitiesnoconv("PropalStatusValidated");
3486 $this->labelStatus[2] = $langs->transnoentitiesnoconv("PropalStatusSigned");
3487 $this->labelStatus[3] = $langs->transnoentitiesnoconv("PropalStatusNotSigned");
3488 $this->labelStatus[4] = $langs->transnoentitiesnoconv("PropalStatusBilled");
3489 $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv("PropalStatusCanceledShort");
3490 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("PropalStatusDraftShort");
3491 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("PropalStatusValidatedShort");
3492 $this->labelStatusShort[2] = $langs->transnoentitiesnoconv("PropalStatusSignedShort");
3493 $this->labelStatusShort[3] = $langs->transnoentitiesnoconv("PropalStatusNotSignedShort");
3494 $this->labelStatusShort[4] = $langs->transnoentitiesnoconv("PropalStatusBilledShort");
3495 }
3496
3497 $statusType = '';
3498 if ($status == self::STATUS_CANCELED) {
3499 $statusType = 'status9';
3500 } elseif ($status == self::STATUS_DRAFT) {
3501 $statusType = 'status0';
3502 } elseif ($status == self::STATUS_VALIDATED) {
3503 $statusType = 'status1';
3504 } elseif ($status == self::STATUS_SIGNED) {
3505 $statusType = 'status4';
3506 } elseif ($status == self::STATUS_NOTSIGNED) {
3507 $statusType = 'status9';
3508 } elseif ($status == self::STATUS_BILLED) {
3509 $statusType = 'status6';
3510 }
3511
3512 $parameters = array('status' => $status, 'mode' => $mode);
3513 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
3514
3515 if ($reshook > 0) {
3516 return $hookmanager->resPrint;
3517 }
3518
3519 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3520 }
3521
3522
3523 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3531 public function load_board($user, $mode)
3532 {
3533 // phpcs:enable
3534 global $conf, $langs, $hookmanager;
3535
3536 $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin, p.total_ht";
3537 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
3538 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3539 if ($mode == 'opened') {
3540 $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3541 }
3542 if ($mode == 'signed') {
3543 $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED;
3544 }
3545 // If the internal user must only see his customers, force searching by him
3546 $search_sale = 0;
3547 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3548 $search_sale = $user->id;
3549 }
3550 // Search on sale representative
3551 if ($search_sale && $search_sale != '-1') {
3552 if ($search_sale == -2) {
3553 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3554 } elseif ($search_sale > 0) {
3555 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
3556 }
3557 }
3558 if ($user->socid) {
3559 $sql .= " AND p.fk_soc = ".((int) $user->socid);
3560 }
3561 // Add where from hooks
3562 $parameters = array('socid' => $user->socid);
3563 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3564 $sql .= $hookmanager->resPrint;
3565
3566 $resql = $this->db->query($sql);
3567 if ($resql) {
3568 $langs->load("propal");
3569 $now = dol_now();
3570
3571 $delay_warning = 0;
3572 $status = 0;
3573 $label = $labelShort = '';
3574 if ($mode == 'opened') {
3575 $delay_warning = getWarningDelay('propal', 'cloture');
3576 $status = self::STATUS_VALIDATED;
3577 $label = $langs->transnoentitiesnoconv("PropalsToClose");
3578 $labelShort = $langs->transnoentitiesnoconv("ToAcceptRefuse");
3579 }
3580 if ($mode == 'signed') {
3581 $delay_warning = getWarningDelay('propal', 'facturation');
3582 $status = self::STATUS_SIGNED;
3583 $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered
3584 $labelShort = $langs->trans("ToBill");
3585 }
3586
3587 $response = new WorkboardResponse();
3588 $response->warning_delay = $delay_warning / 60 / 60 / 24;
3589 $response->label = $label;
3590 $response->labelShort = $labelShort;
3591 $response->url = DOL_URL_ROOT.'/comm/propal/list.php?search_status='.$status.'&mainmenu=commercial&leftmenu=propals';
3592 $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?search_option=late&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc';
3593 $response->img = img_object('', "propal");
3594
3595 // This assignment in condition is not a bug. It allows walking the results.
3596 while ($obj = $this->db->fetch_object($resql)) {
3597 $response->nbtodo++;
3598 $response->total += $obj->total_ht;
3599
3600 if ($mode == 'opened') {
3601 $datelimit = $this->db->jdate($obj->datefin);
3602 if ($datelimit < ($now - $delay_warning)) {
3603 $response->nbtodolate++;
3604 }
3605 }
3606 // TODO Definir regle des propales a facturer en retard
3607 // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
3608 }
3609
3610 return $response;
3611 } else {
3612 $this->error = $this->db->error();
3613 return -1;
3614 }
3615 }
3616
3617
3626 public function initAsSpecimen($param = array())
3627 {
3628 global $conf, $langs;
3629
3630 // Load array of products prodids
3631 $num_prods = 0;
3632 $prodids = array();
3633 $sql = "SELECT rowid";
3634 $sql .= " FROM ".MAIN_DB_PREFIX."product";
3635 $sql .= " WHERE entity IN (".getEntity('product').")";
3636 if (array_key_exists('tosell', $param)) {
3637 $sql .= " AND tosell = ".((int) $param['tosell']);
3638 }
3639 $sql .= $this->db->plimit(100);
3640
3641 $resql = $this->db->query($sql);
3642 if ($resql) {
3643 $num_prods = $this->db->num_rows($resql);
3644 $i = 0;
3645 while ($i < $num_prods) {
3646 $i++;
3647 $row = $this->db->fetch_row($resql);
3648 $prodids[$i] = $row[0];
3649 }
3650 }
3651
3652 // Initialise parameters
3653 $this->id = 0;
3654 $this->ref = 'SPECIMEN';
3655 $this->ref_customer = 'NEMICEPS';
3656 $this->ref_client = 'NEMICEPS';
3657 $this->specimen = 1;
3658 $this->socid = 1;
3659 $this->date = time();
3660 $this->fin_validite = $this->date + 3600 * 24 * 30;
3661 $this->cond_reglement_id = 1;
3662 $this->cond_reglement_code = 'RECEP';
3663 $this->mode_reglement_id = 7;
3664 $this->mode_reglement_code = 'CHQ';
3665 $this->availability_id = 1;
3666 $this->availability_code = 'AV_NOW';
3667 $this->demand_reason_id = 1;
3668 $this->demand_reason_code = 'SRC_00';
3669 $this->note_public = 'This is a comment (public)';
3670 $this->note_private = 'This is a comment (private)';
3671
3672 $this->multicurrency_tx = 1;
3673 $this->multicurrency_code = getDolCurrency();
3674
3675 // Lines
3676 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
3677 $xnbp = 0;
3678 while ($xnbp < $nbp) {
3679 $line = new PropaleLigne($this->db);
3680 $line->desc = $langs->trans("Description")." ".$xnbp;
3681 $line->qty = 1;
3682 $line->subprice = 100;
3683 $line->tva_tx = 20;
3684 $line->localtax1_tx = 0;
3685 $line->localtax2_tx = 0;
3686 if ($xnbp == 2) {
3687 $line->total_ht = 50;
3688 $line->total_ttc = 60;
3689 $line->total_tva = 10;
3690 $line->remise_percent = 50;
3691 } else {
3692 $line->total_ht = 100;
3693 $line->total_ttc = 120;
3694 $line->total_tva = 20;
3695 $line->remise_percent = 00;
3696 }
3697
3698 if ($num_prods > 0) {
3699 $prodid = mt_rand(1, $num_prods);
3700 $line->fk_product = $prodids[$prodid];
3701 $line->product_ref = 'SPECIMEN';
3702 }
3703
3704 $this->lines[$xnbp] = $line;
3705
3706 $this->total_ht += $line->total_ht;
3707 $this->total_tva += $line->total_tva;
3708 $this->total_ttc += $line->total_ttc;
3709
3710 $xnbp++;
3711 }
3712
3713 return 1;
3714 }
3715
3721 public function loadStateBoard()
3722 {
3723 global $user, $hookmanager;
3724
3725 $this->nb = array();
3726
3727 $sql = "SELECT count(p.rowid) as nb";
3728 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
3729 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3730 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3731
3732 // If the internal user must only see his customers, force searching by him
3733 $search_sale = 0;
3734 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3735 $search_sale = $user->id;
3736 }
3737 // Search on sale representative
3738 if ($search_sale && $search_sale != '-1') {
3739 if ($search_sale == -2) {
3740 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3741 } elseif ($search_sale > 0) {
3742 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
3743 }
3744 }
3745
3746 // Add where from hooks
3747 $parameters = array();
3748 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3749 $sql .= $hookmanager->resPrint;
3750 $resql = $this->db->query($sql);
3751 if ($resql) {
3752 // This assignment in condition is not a bug. It allows walking the results.
3753 while ($obj = $this->db->fetch_object($resql)) {
3754 $this->nb["proposals"] = $obj->nb;
3755 }
3756 $this->db->free($resql);
3757 return 1;
3758 } else {
3759 dol_print_error($this->db);
3760 $this->error = $this->db->error();
3761 return -1;
3762 }
3763 }
3764
3765
3773 public function getNextNumRef($soc)
3774 {
3775 global $conf, $langs;
3776 $langs->load("propal");
3777
3778 $classname = getDolGlobalString('PROPALE_ADDON');
3779
3780 if (!empty($classname)) {
3781 $mybool = false;
3782
3783 $file = $classname.".php";
3784
3785 // Include file with class
3786 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3787 foreach ($dirmodels as $reldir) {
3788 $dir = dol_buildpath($reldir."core/modules/propale/");
3789
3790 // Load file with numbering class (if found)
3791 $mybool = ((bool) @include_once $dir.$file) || $mybool;
3792 }
3793
3794 if (!$mybool) {
3795 dol_print_error(null, "Failed to include file ".$file);
3796 return '';
3797 }
3798
3799 $obj = new $classname();
3800 '@phan-var-force ModeleNumRefPropales $obj';
3803 $numref = $obj->getNextValue($soc, $this);
3804
3805 if ($numref != "") {
3806 return $numref;
3807 } else {
3808 $this->error = $obj->error;
3809 //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3810 return "";
3811 }
3812 } else {
3813 $langs->load("errors");
3814 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Proposal"));
3815 return "";
3816 }
3817 }
3818
3825 public function getTooltipContentArray($params)
3826 {
3827 global $conf, $langs, $user;
3828
3829 $langs->load('propal');
3830 $datas = [];
3831 $nofetch = !empty($params['nofetch']);
3832
3833 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3834 return ['optimize' => $langs->trans("Proposal")];
3835 }
3836 if ($user->hasRight('propal', 'lire')) {
3837 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').'<u>'.$langs->trans("Proposal").'</u>';
3838 if (isset($this->status)) {
3839 $datas['status'] = ' '.$this->getLibStatut(5);
3840 }
3841 if (!empty($this->ref)) {
3842 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3843 }
3844 if (!$nofetch) {
3845 $langs->load('companies');
3846 if (empty($this->thirdparty)) {
3847 $this->fetch_thirdparty();
3848 }
3849 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
3850 }
3851 if (!empty($this->ref_customer)) {
3852 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
3853 }
3854 if (!$nofetch) {
3855 $langs->load('project');
3856 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
3857 $res = $this->fetchProject();
3858 if ($res > 0 && $this->project instanceof Project) {
3859 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
3860 }
3861 }
3862 }
3863 if (!empty($this->total_ht)) {
3864 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3865 }
3866 if (!empty($this->total_tva)) {
3867 $datas['vat'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3868 }
3869 if (!empty($this->total_ttc)) {
3870 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3871 }
3872 if (!empty($this->date)) {
3873 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
3874 }
3875 if (!empty($this->date_signature)) {
3876 $datas['datesignature'] = '<br><b>'.$langs->trans('DateSigning').':</b> '.dol_print_date($this->date_signature, 'day');
3877 }
3878 if (!empty($this->delivery_date)) {
3879 $datas['deliverydate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
3880 }
3881 }
3882
3883 return $datas;
3884 }
3885
3897 public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = -1)
3898 {
3899 global $langs, $conf, $user, $hookmanager;
3900
3901 if (!empty($conf->dol_no_mouse_hover)) {
3902 $notooltip = 1; // Force disable tooltips
3903 }
3904
3905 $result = '';
3906 $params = [
3907 'id' => $this->id,
3908 'objecttype' => $this->element,
3909 'option' => $option,
3910 'nofetch' => 1,
3911 ];
3912 $classfortooltip = 'classfortooltip';
3913 $dataparams = '';
3914 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3915 $classfortooltip = 'classforajaxtooltip';
3916 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3917 $label = '';
3918 } else {
3919 $label = implode($this->getTooltipContentArray($params));
3920 }
3921
3922 $baseurl = '';
3923 $query = [];
3924 if ($user->hasRight('propal', 'lire')) {
3925 parse_str($get_params, $query);
3926 $query = array_merge($query, ['id' => $this->id]);
3927 if ($option == '') {
3928 $baseurl = DOL_URL_ROOT . '/comm/propal/card.php';
3929 } elseif ($option == 'compta') { // deprecated
3930 $baseurl = DOL_URL_ROOT . '/comm/propal/card.php';
3931 } elseif ($option == 'expedition') {
3932 $baseurl = DOL_URL_ROOT . '/expedition/propal.php';
3933 } elseif ($option == 'document') {
3934 $baseurl = DOL_URL_ROOT . '/comm/propal/document.php';
3935 }
3936
3937 if ($option != 'nolink') {
3938 // Add param to save lastsearch_values or not
3939 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3940 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3941 $add_save_lastsearch_values = 1;
3942 }
3943 if ($add_save_lastsearch_values) {
3944 $query = array_merge($query, ['save_lastsearch_values' => 1]);
3945 }
3946 }
3947 }
3948 $url = dolBuildUrl($baseurl, $query);
3949
3950 $linkclose = '';
3951 if (empty($notooltip) && $user->hasRight('propal', 'lire')) {
3952 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3953 $label = $langs->trans("Proposal");
3954 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3955 }
3956 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3957 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
3958 }
3959
3960 $linkstart = '<a href="'.$url.'"';
3961 $linkstart .= $linkclose.'>';
3962 $linkend = '</a>';
3963
3964 $result .= $linkstart;
3965 if ($withpicto) {
3966 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
3967 }
3968 if ($withpicto != 2) {
3969 $result .= $this->ref;
3970 }
3971 $result .= $linkend;
3972
3973 if ($addlinktonotes >= 0) {
3974 $txttoshow = '';
3975
3976 if ($addlinktonotes == 0) {
3977 if (!empty($this->note_private) || !empty($this->note_public)) {
3978 $txttoshow = $langs->trans('ViewPrivateNote');
3979 }
3980 } elseif ($addlinktonotes == 1) {
3981 if (!empty($this->note_private)) {
3982 $txttoshow .= ($user->socid > 0 ? '' : dol_string_nohtmltag($this->note_private, 1));
3983 }
3984 } elseif ($addlinktonotes == 2) {
3985 if (!empty($this->note_public)) {
3986 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
3987 }
3988 } elseif ($addlinktonotes == 3) {
3989 if ($user->socid > 0) {
3990 if (!empty($this->note_public)) {
3991 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
3992 }
3993 } else {
3994 if (!empty($this->note_public)) {
3995 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
3996 }
3997 if (!empty($this->note_private)) {
3998 if (!empty($txttoshow)) {
3999 $txttoshow .= '<br><br>';
4000 }
4001 $txttoshow .= dol_string_nohtmltag($this->note_private, 1);
4002 }
4003 }
4004 }
4005
4006 if ($txttoshow) {
4007 $result .= ' <span class="note inline-block">';
4008 $result .= '<a href="'.DOL_URL_ROOT.'/comm/propal/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($txttoshow).'">';
4009 $result .= img_picto('', 'note');
4010 $result .= '</a>';
4011 $result .= '</span>';
4012 }
4013 }
4014
4015 global $action;
4016 $hookmanager->initHooks(array($this->element . 'dao'));
4017 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
4018 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4019 if ($reshook > 0) {
4020 $result = $hookmanager->resPrint;
4021 } else {
4022 $result .= $hookmanager->resPrint;
4023 }
4024 return $result;
4025 }
4026
4033 public function getLinesArray($sqlforgedfilters = '')
4034 {
4035 return $this->fetch_lines(0, 0, $sqlforgedfilters);
4036 }
4037
4049 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4050 {
4051 $outputlangs->loadLangs(array("propale", "products"));
4052
4053 if (!dol_strlen($modele)) {
4054 $modele = 'azur';
4055
4056 if ($this->model_pdf) {
4057 $modele = $this->model_pdf;
4058 } elseif (getDolGlobalString('PROPALE_ADDON_PDF')) {
4059 $modele = getDolGlobalString('PROPALE_ADDON_PDF');
4060 }
4061 }
4062
4063 $modelpath = "core/modules/propale/doc/";
4064
4065 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4066 }
4067
4076 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4077 {
4078 $tables = array(
4079 'propal'
4080 );
4081
4082 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4083 }
4084
4093 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
4094 {
4095 $tables = array(
4096 'propaldet'
4097 );
4098
4099 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
4100 }
4101
4109 public function getKanbanView($option = '', $arraydata = null)
4110 {
4111 global $langs;
4112
4113 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
4114
4115 $return = '<div class="box-flex-item box-flex-grow-zero">';
4116 $return .= '<div class="info-box info-box-sm">';
4117 $return .= '<div class="info-box-icon bg-infobox-action">';
4118 $return .= img_picto('', $this->picto);
4119 $return .= '</div>';
4120 $return .= '<div class="info-box-content">';
4121 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
4122 if ($selected >= 0) {
4123 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
4124 }
4125 if (!empty($arraydata['projectlink'])) {
4126 $return .= '<span class="info-box-ref"> | '.$arraydata['projectlink'].'</span>';
4127 }
4128 $return .= '<br>';
4129 if (is_object($this->thirdparty)) {
4130 $return .= '<div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
4131 }
4132 $return .= '<span class="info-box-label amount" title="'.$langs->trans("AmountHT").'">'.price($this->total_ht).'</span>';
4133 if (!empty($arraydata['authorlink'])) {
4134 $return .= ' &nbsp; <span class="info-box-label">'.$arraydata['authorlink'].'</span>';
4135 }
4136 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
4137 $return .= '</div>';
4138 $return .= '</div>';
4139 $return .= '</div>';
4140 return $return;
4141 }
4142
4153 public function setCategories($categories)
4154 {
4155 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4156 return parent::setCategoriesCommon($categories, Categorie::TYPE_PROPOSAL);
4157 }
4158}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
updateRangOfLine($rowid, $rang)
Update position of line (rang)
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
deleteExtraFields()
Delete all extra fields values for the current object.
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).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
File of class to manage predefined price products or services by customer.
Class to manage predefined suppliers products.
Class to manage products or services.
Class to manage projects.
Class to manage proposals.
getTooltipContentArray($params)
getTooltipContentArray
const STATUS_DRAFT
Draft status.
set_date($user, $date, $notrigger=0)
Define proposal date.
const STATUS_SIGNED
Signed quote.
getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=-1)
Return clickable link of object (with eventually picto)
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
InvoiceArrayList($id)
Returns an array with id and ref of related invoices.
availability($availability_id, $notrigger=0)
Change the delivery time.
const STATUS_NOTSIGNED
Not signed quote.
$table_ref_field
{}
setDeliveryDate($user, $delivery_date, $notrigger=0)
Set delivery date.
classifyBilled(User $user, $notrigger=0, $note='')
Classify the proposal to status Billed.
getLinesArray($sqlforgedfilters='')
Retrieve an array of proposal lines.
fetch($rowid, $ref='', $ref_ext='', $forceentity=0)
Load a proposal from database.
set_availability($user, $id, $notrigger=0)
Set delivery.
fetch_lines($only_product=0, $loadalsotranslation=0, $sqlforgedfilters='')
Load array lines.
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=array(), $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $rang=0)
Update a proposal line.
update(User $user, $notrigger=0)
Update database.
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=array(), $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...
closeProposal($user, $status, $note_private='', $notrigger=0, $note_public='')
Close/set the commercial proposal to status signed or refused (fill also date signature)
demand_reason($demand_reason_id, $notrigger=0)
Change source demand.
info($id)
Object Proposal Information.
const STATUS_BILLED
Billed or processed quote.
initAsSpecimen($param=array())
Initialise an instance with random values.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getLibStatut($mode=0)
Return label of status of proposal (draft, validated, ...)
const STATUS_CANCELED
Canceled status.
insert_discount($idremise)
Add a discount line into an proposal (as a proposal line) using an existing absolute discount (Consum...
LibStatut($status, $mode=1)
Return label of a status (draft, validated, ...)
valid($user, $notrigger=0)
Set status to validated.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
set_ref_client($user, $ref_client, $notrigger=0)
Set customer reference number.
setDraft($user, $notrigger=0)
Set draft status.
set_echeance($user, $date_end_validity, $notrigger=0)
Define end validity date.
set_demand_reason($user, $id, $notrigger=0)
Set source of demand.
setCategories($categories)
Sets object to supplied categories.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
create($user, $notrigger=0)
Create commercial proposal into database this->ref can be set or empty.
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.
add_product($idproduct, $qty, $remise_percent=0)
Add line into array ->lines $this->thirdparty should be loaded.
reopen($user, $status, $note='', $notrigger=0)
Reopen the commercial proposal.
deleteLine($lineid, $id=0)
Delete detail line.
__construct($db, $socid=0, $propalid=0)
Constructor.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
setCancel(User $user)
Cancel the proposal.
getInvoiceArrayList()
Returns an array with the numbers of related invoices.
set_date_livraison($user, $delivery_date, $notrigger=0)
Set delivery date.
const STATUS_VALIDATED
Validated status.
loadStateBoard()
Load the indicators this->nb for the state board.
createFromClone(User $user, $socid=0, $forceentity=null, $update_prices=false, $update_desc=false)
Load an object from its id and create a new one in database.
Class to manage commercial proposal lines.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
global $mysoc
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.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_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:64
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
isDolTms($timestamp)
isDolTms check if a timestamp is valid.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
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.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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.: VAT NPR in France)
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...
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
getWarningDelay($module, $parmlevel1, $parmlevel2='')
Return a warning delay You can use it like this: if (getWarningDelay('module', 'paramlevel1')) It rep...
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...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
if(getDolGlobalString( 'TAKEPOS_SHOW_CUSTOMER')) print $langs trans('Date')." left Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:469