dolibarr 24.0.3
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-2026 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-2026 MDW <mdeweerd@users.noreply.github.com>
22 * Copyright (C) 2025 William Mead <william@m34d.com>
23 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
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; // Line Description
574 $line->vat_src_code = $remise->vat_src_code;
575 $line->tva_tx = $remise->tva_tx;
576 $line->localtax1_tx = $remise->localtax1_tx;
577 $line->localtax1_type = $remise->localtax1_type;
578 $line->localtax2_tx = $remise->localtax1_tx;
579 $line->localtax2_type = $remise->localtax1_type;
580 $line->subprice = -(float) $remise->amount_ht;
581 $line->fk_product = 0; // Product Id predefined
582 $line->qty = 1;
583 $line->remise_percent = 0;
584 $line->rang = -1;
585 $line->info_bits = 2;
586
587 $line->total_ht = -(float) $remise->amount_ht;
588 $line->total_tva = -(float) $remise->amount_tva;
589 $line->total_ttc = -(float) $remise->amount_ttc;
590 $line->total_localtax1 = -(float) $remise->total_localtax1;
591 $line->total_localtax2 = -(float) $remise->total_localtax2;
592
593 $result = $line->insert();
594 if ($result > 0) {
595 $result = $this->update_price(1);
596 if ($result > 0) {
597 $this->db->commit();
598 return 1;
599 } else {
600 $this->db->rollback();
601 return -1;
602 }
603 } else {
604 $this->setErrorsFromObject($line);
605 $this->db->rollback();
606 return -2;
607 }
608 } else {
609 $this->db->rollback();
610 return -2;
611 }
612 }
613
651 public function addline(
652 $desc,
653 $pu_ht,
654 $qty,
655 $txtva,
656 $txlocaltax1 = 0.0,
657 $txlocaltax2 = 0.0,
658 $fk_product = 0,
659 $remise_percent = 0.0,
660 $price_base_type = 'HT',
661 $pu_ttc = 0.0,
662 $info_bits = 0,
663 $type = 0,
664 $rang = -1,
665 $special_code = 0,
666 $fk_parent_line = 0,
667 $fk_fournprice = 0,
668 $pa_ht = 0,
669 $label = '',
670 $date_start = '',
671 $date_end = '',
672 $array_options = array(),
673 $fk_unit = null,
674 $origin = '',
675 $origin_id = 0,
676 $pu_ht_devise = 0,
677 $fk_remise_except = 0,
678 $noupdateafterinsertline = 0
679 ) {
680 global $mysoc, $langs;
681
682 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);
683
684 if ($this->status == self::STATUS_DRAFT) {
685 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
686
687 // Clean parameters
688 if (empty($remise_percent)) {
689 $remise_percent = 0;
690 }
691 if (empty($qty)) {
692 $qty = 0;
693 }
694 if (empty($info_bits)) {
695 $info_bits = 0;
696 }
697 if (empty($rang)) {
698 $rang = 0;
699 }
700 if (empty($fk_parent_line) || $fk_parent_line < 0) {
701 $fk_parent_line = 0;
702 }
703
704 $remise_percent = price2num($remise_percent);
705 $qty = (float) price2num($qty, 'MS');
706 $pu_ht = price2num($pu_ht);
707 $pu_ht_devise = price2num($pu_ht_devise);
708 $pu_ttc = price2num($pu_ttc);
709 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
710 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
711 }
712 $txlocaltax1 = price2num($txlocaltax1);
713 $txlocaltax2 = price2num($txlocaltax2);
714 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht is empty string
715 if ($price_base_type == 'HT') {
716 $pu = $pu_ht;
717 } else {
718 $pu = $pu_ttc;
719 }
720
721 // Check parameters
722 if ($type < 0) {
723 return -1;
724 }
725
726 if ($date_start && $date_end && $date_start > $date_end) {
727 $langs->load("errors");
728 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
729 return -1;
730 }
731
732 $this->db->begin();
733
734 $product_type = $type;
735 if (!empty($fk_product) && $fk_product > 0) {
736 $product = new Product($this->db);
737 $result = $product->fetch($fk_product);
738 $product_type = $product->type;
739
740 if ($product->isStockManaged() && $product->stock_reel < $qty && getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL')) {
741 $langs->load("errors");
742 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
743 $this->db->rollback();
744 return -3;
745 }
746 }
747
748 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
749 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
750 // and this is done at the line level, which has its own VAT rate
751
752 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
753
754 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
755 $tmpproduct = new Product($this->db);
756 $result = $tmpproduct->fetch($fk_product);
757 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
758 if ($newqty != $qty) {
759 $qty = $newqty;
760 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
761 }
762 }
763
764 // Clean vat code
765 $reg = array();
766 $vat_src_code = '';
767 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
768 $vat_src_code = $reg[1];
769 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
770 }
771
772 $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);
773
774 $total_ht = $tabprice[0];
775 $total_tva = $tabprice[1];
776 $total_ttc = $tabprice[2];
777 $total_localtax1 = $tabprice[9];
778 $total_localtax2 = $tabprice[10];
779 $pu_ht = $tabprice[3];
780 $pu_tva = $tabprice[4];
781 $pu_ttc = $tabprice[5];
782
783 // MultiCurrency
784 $multicurrency_total_ht = $tabprice[16];
785 $multicurrency_total_tva = $tabprice[17];
786 $multicurrency_total_ttc = $tabprice[18];
787 $pu_ht_devise = $tabprice[19];
788
789 // Rang to use
790 $ranktouse = $rang;
791 if (empty($ranktouse) || $ranktouse == -1) {
792 $rangmax = $this->line_max($fk_parent_line);
793 $ranktouse = $rangmax + 1;
794 }
795
796 // Insert line
797 $this->line = new PropaleLigne($this->db);
798
799 $this->line->context = $this->context;
800
801 $this->line->fk_propal = $this->id;
802 $this->line->label = $label;
803 $this->line->desc = $desc;
804 $this->line->qty = (float) $qty;
805
806 $this->line->vat_src_code = $vat_src_code;
807 $this->line->tva_tx = $txtva;
808 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
809 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
810 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
811 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
812 $this->line->fk_product = $fk_product;
813 $this->line->product_type = $type;
814 $this->line->fk_remise_except = $fk_remise_except;
815 $this->line->remise_percent = $remise_percent;
816 $this->line->subprice = (float) $pu_ht;
817 // Persist the original entry mode of the line so updateline() can preserve it later.
818 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
819 $this->line->rang = $ranktouse;
820 $this->line->info_bits = $info_bits;
821 $this->line->total_ht = (float) $total_ht;
822 $this->line->total_tva = (float) $total_tva;
823 $this->line->total_localtax1 = (float) $total_localtax1;
824 $this->line->total_localtax2 = (float) $total_localtax2;
825 $this->line->total_ttc = (float) $total_ttc;
826 $this->line->special_code = $special_code;
827 $this->line->fk_parent_line = $fk_parent_line;
828 $this->line->fk_unit = $fk_unit;
829
830 $this->line->date_start = $date_start;
831 $this->line->date_end = $date_end;
832
833 $this->line->fk_fournprice = $fk_fournprice;
834 $this->line->pa_ht = $pa_ht;
835
836 $this->line->origin_id = $origin_id;
837 $this->line->origin = $origin;
838
839 // Multicurrency
840 $this->line->fk_multicurrency = $this->fk_multicurrency;
841 $this->line->multicurrency_code = $this->multicurrency_code;
842 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
843 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
844 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
845 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
846
847 // Set the line as optional
848 if (empty($qty) && empty($special_code)) {
849 $this->line->special_code = 3;
850 }
851
852 if (is_array($array_options) && count($array_options) > 0) {
853 $this->line->array_options = $array_options;
854 }
855
856 $result = $this->line->insert();
857 if ($result > 0) {
858 if (!isset($this->context['createfromclone'])) {
859 if (!empty($fk_parent_line)) {
860 // Always reorder if child line
861 $this->line_order(true, 'DESC');
862 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
863 // Update all rank of all other lines starting from the same $ranktouse
864 foreach ($this->lines as $tmpline) {
865 if ($tmpline->rang >= $ranktouse) {
866 if (!empty($tmpline->id)) {
867 $this->updateRangOfLine($tmpline->id, $tmpline->rang + 1);
868 }
869 }
870 }
871 }
872
873 $this->lines[] = $this->line;
874 } else {
875 // Loop on all lines of parent object
876 foreach ($this->lines as $tmpline) {
877 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
878 $this->line->extraparams = $tmpline->extraparams;
879 $this->line->setExtraParameters();
880 }
881 }
882 }
883
884 // Update denormalized fields at the order level
885 if (empty($noupdateafterinsertline)) {
886 $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.
887 }
888
889 if ($result > 0) {
890 $this->db->commit();
891 return $this->line->id;
892 } else {
893 $this->error = $this->db->error();
894 $this->db->rollback();
895 return -1;
896 }
897 } else {
898 $this->setErrorsFromObject($this->line);
899 $this->db->rollback();
900 return -2;
901 }
902 } else {
903 dol_syslog(get_class($this)."::addline status of proposal must be Draft to allow use of ->addline()", LOG_ERR);
904 return -3;
905 }
906 }
907
908
938 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)
939 {
940 global $mysoc, $langs;
941
942 if (!$this->isLineOfObject($rowid)) {
943 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
944 return -1;
945 }
946
947 dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent,
948 txtva=$txtva, desc=".dol_trunc($desc, 16).", 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");
949 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
950
951 // Clean parameters
952 $remise_percent = price2num($remise_percent);
953 $qty = (float) price2num($qty);
954 $pu = price2num($pu);
955 $pu_ht_devise = price2num($pu_ht_devise);
956 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
957 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
958 }
959 $txlocaltax1 = price2num($txlocaltax1);
960 $txlocaltax2 = price2num($txlocaltax2);
961 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
962 if (empty($qty) && empty($special_code)) {
963 $special_code = 3; // Set option tag
964 }
965 if (!empty($qty) && $special_code == 3) {
966 $special_code = 0; // Remove option tag
967 }
968 if (empty($type)) {
969 $type = 0;
970 }
971
972 if ($date_start && $date_end && $date_start > $date_end) {
973 $langs->load("errors");
974 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
975 return -1;
976 }
977
978 if ($this->status == self::STATUS_DRAFT) {
979 $this->db->begin();
980
981 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
982 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
983 // and this is done at the line level, which has its own VAT rate
984
985 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
986
987 // Clean vat code
988 $reg = array();
989 $vat_src_code = '';
990 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
991 $vat_src_code = $reg[1];
992 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
993 }
994
995 // TODO Implement if (getDolGlobalInt('MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES')) ?
996
997 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
998 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
999 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
1000 $tmpline = new PropaleLigne($this->db);
1001 if ($tmpline->fetch($rowid) > 0) {
1002 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
1003 if ($newqty != $qty) {
1004 $qty = $newqty;
1005 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
1006 }
1007 }
1008 }
1009
1010 $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);
1011 $total_ht = $tabprice[0];
1012 $total_tva = $tabprice[1];
1013 $total_ttc = $tabprice[2];
1014 $total_localtax1 = $tabprice[9];
1015 $total_localtax2 = $tabprice[10];
1016 $pu_ht = $tabprice[3];
1017 $pu_tva = $tabprice[4];
1018 $pu_ttc = $tabprice[5];
1019
1020 // MultiCurrency
1021 $multicurrency_total_ht = $tabprice[16];
1022 $multicurrency_total_tva = $tabprice[17];
1023 $multicurrency_total_ttc = $tabprice[18];
1024 $pu_ht_devise = $tabprice[19];
1025
1026 // Fetch current line from the database and then clone the object and set it in $oldline property
1027 $line = new PropaleLigne($this->db);
1028 $line->fetch($rowid);
1029
1030 $staticline = clone $line;
1031
1032 $line->oldline = $staticline;
1033 $this->line = $line;
1034 $this->line->context = $this->context;
1035 $this->line->rang = $rang;
1036
1037 // Reorder if fk_parent_line change
1038 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
1039 $rangmax = $this->line_max($fk_parent_line);
1040 $this->line->rang = $rangmax + 1;
1041 }
1042
1043
1044 $this->line->id = $rowid;
1045 $this->line->label = $label;
1046 $this->line->desc = $desc;
1047 $this->line->qty = $qty;
1048 $this->line->product_type = $type;
1049 $this->line->vat_src_code = $vat_src_code;
1050 $this->line->tva_tx = $txtva;
1051 $this->line->localtax1_tx = $txlocaltax1;
1052 $this->line->localtax2_tx = $txlocaltax2;
1053 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
1054 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
1055 $this->line->remise_percent = $remise_percent;
1056 $this->line->subprice = (float) $pu_ht;
1057 // Persist the original entry mode of the line so a no-op edit can preserve it later.
1058 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
1059 $this->line->info_bits = $info_bits;
1060
1061 $this->line->total_ht = (float) $total_ht;
1062 $this->line->total_tva = (float) $total_tva;
1063 $this->line->total_localtax1 = (float) $total_localtax1;
1064 $this->line->total_localtax2 = (float) $total_localtax2;
1065 $this->line->total_ttc = (float) $total_ttc;
1066 $this->line->special_code = $special_code;
1067 $this->line->fk_parent_line = $fk_parent_line;
1068 $this->line->skip_update_total = $skip_update_total;
1069 $this->line->fk_unit = $fk_unit;
1070
1071 $this->line->fk_fournprice = $fk_fournprice;
1072 $this->line->pa_ht = $pa_ht;
1073
1074 $this->line->date_start = $date_start;
1075 $this->line->date_end = $date_end;
1076
1077 if (is_array($array_options) && count($array_options) > 0) {
1078 // We replace values in this->line->array_options only for entries defined into $array_options
1079 foreach ($array_options as $key => $value) {
1080 $this->line->array_options[$key] = $array_options[$key];
1081 }
1082 }
1083
1084 // Multicurrency
1085 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
1086 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
1087 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
1088 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
1089
1090 $result = $this->line->update($notrigger);
1091 if ($result > 0) {
1092 // Reorder if child line
1093 if (!empty($fk_parent_line)) {
1094 $this->line_order(true, 'DESC');
1095 }
1096
1097 $this->update_price(1, 'auto');
1098
1099 // $this is Propal
1100 // $this->fk_propal = $this->id;
1101 // $this->rowid = $rowid;
1102
1103 $this->db->commit();
1104 return $result;
1105 } else {
1106 $this->setErrorsFromObject($this->line);
1107 $this->db->rollback();
1108 return -1;
1109 }
1110 } else {
1111 dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
1112 return -2;
1113 }
1114 }
1115
1116
1124 public function deleteLine($lineid, $id = 0)
1125 {
1126 global $user;
1127
1128 if ($this->status == self::STATUS_DRAFT) {
1129 $this->db->begin();
1130
1131 $line = new PropaleLigne($this->db);
1132
1133 $line->context = $this->context;
1134
1135 // Load data
1136 $line->fetch($lineid);
1137
1138 if ($id <= 0) {
1139 $id = $this->id;
1140 }
1141 if ($id > 0 && (int) $line->fk_propal !== (int) $id) {
1142 $this->db->rollback();
1143 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1144 return -1;
1145 }
1146
1147 // Memorize previous line for triggers
1148 $staticline = clone $line;
1149 $line->oldline = $staticline;
1150
1151 if ($line->delete($user) > 0) {
1152 $this->update_price(1);
1153
1154 $this->db->commit();
1155 return 1;
1156 } else {
1157 $this->setErrorsFromObject($line);
1158 $this->db->rollback();
1159 return -1;
1160 }
1161 } else {
1162 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1163 return -2;
1164 }
1165 }
1166
1167
1176 public function create($user, $notrigger = 0)
1177 {
1178 global $mysoc;
1179
1180 $error = 0;
1181
1182 $now = dol_now();
1183
1184 // Clean parameters
1185 if (empty($this->date)) {
1186 $this->date = $this->datep;
1187 }
1188 $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1189 if (empty($this->availability_id)) {
1190 $this->availability_id = 0;
1191 }
1192 if (empty($this->demand_reason_id)) {
1193 $this->demand_reason_id = 0;
1194 }
1195
1196 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1197 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1198 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
1199 } else {
1200 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1201 }
1202 if (empty($this->fk_multicurrency)) {
1203 $this->multicurrency_code = getDolCurrency();
1204 $this->fk_multicurrency = 0;
1205 $this->multicurrency_tx = 1;
1206 }
1207 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
1208 $this->entity = setEntity($this);
1209
1210 // Set tmp vars
1211 $delivery_date = $this->delivery_date;
1212
1213 dol_syslog(get_class($this)."::create");
1214
1215 // Check parameters
1216 $result = $this->fetch_thirdparty();
1217 if ($result < 0) {
1218 $this->error = "Failed to fetch company";
1219 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1220 return -3;
1221 }
1222
1223 // Check parameters
1224 if (!empty($this->ref)) { // We check that ref is not already used
1225 $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
1226 if ($result > 0) {
1227 $this->error = 'ErrorRefAlreadyExists';
1228 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1229 $this->db->rollback();
1230 return -1;
1231 }
1232 }
1233
1234 if (empty($this->date)) {
1235 $this->error = "Date of proposal is required";
1236 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1237 return -4;
1238 }
1239
1240
1241 $this->db->begin();
1242
1243 // Insert into database
1244 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1245 $sql .= "fk_soc";
1246 $sql .= ", price";
1247 $sql .= ", total_tva";
1248 $sql .= ", total_ttc";
1249 $sql .= ", datep";
1250 $sql .= ", datec";
1251 $sql .= ", ref";
1252 $sql .= ", fk_user_author";
1253 $sql .= ", note_private";
1254 $sql .= ", note_public";
1255 $sql .= ", model_pdf";
1256 $sql .= ", fin_validite";
1257 $sql .= ", fk_cond_reglement";
1258 $sql .= ", deposit_percent";
1259 $sql .= ", fk_mode_reglement";
1260 $sql .= ", fk_account";
1261 $sql .= ", ref_client";
1262 $sql .= ", ref_ext";
1263 $sql .= ", date_livraison";
1264 $sql .= ", fk_shipping_method";
1265 $sql .= ", fk_warehouse";
1266 $sql .= ", fk_availability";
1267 $sql .= ", fk_input_reason";
1268 $sql .= ", fk_projet";
1269 $sql .= ", fk_incoterms";
1270 $sql .= ", location_incoterms";
1271 $sql .= ", entity";
1272 $sql .= ", fk_multicurrency";
1273 $sql .= ", multicurrency_code";
1274 $sql .= ", multicurrency_tx";
1275 $sql .= ") ";
1276 $sql .= " VALUES (";
1277 $sql .= ((int) $this->socid);
1278 $sql .= ", 0";
1279 $sql .= ", 0";
1280 $sql .= ", 0";
1281 $sql .= ", '".$this->db->idate($this->date)."'";
1282 $sql .= ", '".$this->db->idate($now)."'";
1283 $sql .= ", '(PROV)'";
1284 $sql .= ", ".($user->id > 0 ? ((int) $user->id) : "NULL");
1285 $sql .= ", '".$this->db->escape($this->note_private)."'";
1286 $sql .= ", '".$this->db->escape($this->note_public)."'";
1287 $sql .= ", '".$this->db->escape($this->model_pdf)."'";
1288 $sql .= ", ".($this->fin_validite != '' ? "'".$this->db->idate($this->fin_validite)."'" : "NULL");
1289 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'NULL');
1290 $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : 'NULL');
1291 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'NULL');
1292 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1293 $sql .= ", '".$this->db->escape((string) $this->ref_client)."'";
1294 $sql .= ", '".$this->db->escape((string) $this->ref_ext)."'";
1295 $sql .= ", ".(!isDolTms($delivery_date) ? "NULL" : "'".$this->db->idate($delivery_date)."'");
1296 $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
1297 $sql .= ", ".($this->warehouse_id > 0 ? ((int) $this->warehouse_id) : 'NULL');
1298 $sql .= ", ".((int) $this->availability_id);
1299 $sql .= ", ".((int) $this->demand_reason_id);
1300 $sql .= ", ".($this->fk_project ? ((int) $this->fk_project) : "null");
1301 $sql .= ", ".(int) $this->fk_incoterms;
1302 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1303 $sql .= ", ".(int) $this->entity;
1304 $sql .= ", ".(int) $this->fk_multicurrency;
1305 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1306 $sql .= ", ".(float) $this->multicurrency_tx;
1307 $sql .= ")";
1308
1309 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1310 $resql = $this->db->query($sql);
1311 if ($resql) {
1312 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
1313
1314 if ($this->id) {
1315 $this->ref = '(PROV'.$this->id.')';
1316 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
1317
1318 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1319 $resql = $this->db->query($sql);
1320 if (!$resql) {
1321 $error++;
1322 }
1323
1324 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1325 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1326 }
1327
1328 // Add object linked
1329 if (!$error && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1330 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1331 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, ...))
1332 foreach ($tmp_origin_id as $origin_id) {
1333 $ret = $this->add_object_linked($origin, $origin_id);
1334 if (!$ret) {
1335 $this->error = $this->db->lasterror();
1336 $error++;
1337 }
1338 }
1339 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1340 $origin_id = $tmp_origin_id;
1341 $ret = $this->add_object_linked($origin, $origin_id);
1342 if (!$ret) {
1343 $this->error = $this->db->lasterror();
1344 $error++;
1345 }
1346 }
1347 }
1348 }
1349
1350 /*
1351 * Insert products detail in database
1352 */
1353 if (!$error) {
1354 $fk_parent_line = 0;
1355 $num = count($this->lines);
1356
1357 // Convert all lines into PropaleLigne objects before inserting the first one: when coming from REST API, they are still arrays, and addline() reads the whole of this->lines
1358 for ($i = 0; $i < $num; $i++) {
1359 if (!is_object($this->lines[$i])) {
1360 $lineobj = new PropaleLigne($this->db);
1361 foreach ($this->lines[$i] as $key => $val) {
1362 $lineobj->$key = $val;
1363 }
1364 $this->lines[$i] = $lineobj;
1365 }
1366 }
1367
1368 for ($i = 0; $i < $num; $i++) {
1369 $line = $this->lines[$i];
1370
1371 // Reset fk_parent_line for line that are not child lines or special product
1372 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1373 $fk_parent_line = 0;
1374 }
1375 // Complete vat rate with code
1376 $vatrate = $line->tva_tx;
1377 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', $vatrate)) {
1378 $vatrate .= ' ('.$line->vat_src_code.')';
1379 }
1380
1381 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
1382 $originid = $line->origin_id;
1383 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
1384 } else { // old but bugged version (we store id of line and type of parent object)
1385 $originid = $line->id;
1386 $origintype = $this->element;
1387 }
1388
1389 $result = $this->addline(
1390 $line->desc,
1391 $line->subprice,
1392 $line->qty,
1393 $vatrate,
1394 $line->localtax1_tx,
1395 $line->localtax2_tx,
1396 $line->fk_product,
1397 $line->remise_percent,
1398 'HT',
1399 0,
1400 $line->info_bits,
1401 $line->product_type,
1402 $line->rang,
1403 $line->special_code,
1404 $fk_parent_line,
1405 $line->fk_fournprice,
1406 $line->pa_ht,
1407 $line->label,
1408 $line->date_start,
1409 $line->date_end,
1410 $line->array_options,
1411 $line->fk_unit,
1412 (string) $origintype,
1413 $originid,
1414 0,
1415 0,
1416 1
1417 );
1418
1419 if ($result < 0) {
1420 $error++;
1421 $this->error = $this->db->error;
1422 dol_print_error($this->db);
1423 break;
1424 }
1425
1426 // Set the id on created row
1427 $line->id = $result;
1428
1429 // Keep the extra parameters of the source line (for example the options of subtotal lines): addline() can't
1430 // do it when the object is cloned, because the origin it receives is the one of the source line, not the source line
1431 if ($result > 0 && !empty($line->extraparams)) {
1432 $newline = new PropaleLigne($this->db);
1433 $newline->id = $result;
1434 $newline->extraparams = $line->extraparams;
1435 $newline->setExtraParameters();
1436 }
1437
1438 // Defined the new fk_parent_line
1439 if ($result > 0 && $line->product_type == 9) {
1440 $fk_parent_line = $result;
1441 }
1442 }
1443 }
1444
1445 if (!$error) {
1446 // Update denormalized data
1447 $resql = $this->update_price(1, 'auto', 0, $mysoc);
1448 if ($resql) {
1449 // Actions on extra fields
1450 $result = $this->insertExtraFields();
1451 if ($result < 0) {
1452 $error++;
1453 }
1454
1455 if (!$error && !$notrigger) {
1456 // Call trigger
1457 $result = $this->call_trigger('PROPAL_CREATE', $user);
1458 if ($result < 0) {
1459 $error++;
1460 }
1461 // End call triggers
1462 }
1463 } else {
1464 $this->error = $this->db->lasterror();
1465 $error++;
1466 }
1467 }
1468 } else {
1469 $this->error = $this->db->lasterror();
1470 $error++;
1471 }
1472
1473 if (!$error) {
1474 $this->db->commit();
1475 dol_syslog(get_class($this)."::create done id=".$this->id);
1476 return $this->id;
1477 } else {
1478 $this->db->rollback();
1479 return -2;
1480 }
1481 } else {
1482 $this->error = $this->db->lasterror();
1483 $this->db->rollback();
1484 return -1;
1485 }
1486 }
1487
1498 public function createFromClone(User $user, $socid = 0, $forceentity = null, $update_prices = false, $update_desc = false)
1499 {
1500 global $conf, $hookmanager, $mysoc;
1501
1502 dol_include_once('/projet/class/project.class.php');
1503
1504 $error = 0;
1505 $now = dol_now();
1506
1507 dol_syslog(__METHOD__, LOG_DEBUG);
1508
1509 $object = new self($this->db);
1510
1511 $this->db->begin();
1512
1513 // Load source object
1514 $object->fetch($this->id);
1515
1516 $objsoc = new Societe($this->db);
1517
1518 // Change socid if needed
1519 if (!empty($socid) && $socid != $object->socid) {
1520 if ($objsoc->fetch($socid) > 0) {
1521 $object->socid = $objsoc->id;
1522 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1523 $object->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : null);
1524 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1525 $object->fk_delivery_address = 0;
1526
1527 /*if (isModEnabled('project'))
1528 {
1529 $project = new Project($db);
1530 if ($this->fk_project > 0 && $project->fetch($this->fk_project)) {
1531 if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project;
1532 else $clonedObj->fk_project = '';
1533 } else {
1534 $clonedObj->fk_project = '';
1535 }
1536 }*/
1537 $object->fk_project = 0; // A cloned proposal is set by default to no project.
1538 }
1539
1540 // reset ref_client
1541 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1542 $object->ref_client = '';
1543 $object->ref_customer = '';
1544 }
1545
1546 // TODO Change product price if multi-prices
1547 } else {
1548 $objsoc->fetch($object->socid);
1549 }
1550
1551 // update prices
1552 if ($update_prices === true || $update_desc === true) {
1553 if ($objsoc->id > 0 && !empty($object->lines)) {
1554 if ($update_prices === true && getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1555 // If price per customer
1556 require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
1557 }
1558
1559 foreach ($object->lines as $line) {
1560 $line->id = 0;
1561
1562 if ($line->fk_product > 0) {
1563 $prod = new Product($this->db);
1564 $res = $prod->fetch($line->fk_product);
1565 if ($res > 0) {
1566 if ($update_prices === true) {
1567 $pu_ht = $prod->price;
1568 $tva_tx = (string) get_default_tva($mysoc, $objsoc, $prod->id);
1569 $remise_percent = $objsoc->remise_percent;
1570
1571 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $objsoc->price_level > 0) {
1572 $pu_ht = $prod->multiprices[$objsoc->price_level];
1573 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
1574 if (isset($prod->multiprices_tva_tx[$objsoc->price_level])) {
1575 $tva_tx = (string) $prod->multiprices_tva_tx[$objsoc->price_level];
1576 }
1577 }
1578 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1579 $prodcustprice = new ProductCustomerPrice($this->db);
1580 $filter = array('t.fk_product' => (string) $prod->id, 't.fk_soc' => (string) $objsoc->id);
1581 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
1582 if ($result) {
1583 // If there is some prices specific to the customer
1584 if (count($prodcustprice->lines) > 0) {
1585 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
1586 foreach ($prodcustprice->lines as $k => $custprice_line) {
1587 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
1588 $pu_ht = price($custprice_line->price);
1589 $tva_tx = ($custprice_line->default_vat_code ? $custprice_line->tva_tx . ' (' . $custprice_line->default_vat_code . ' )' : $custprice_line->tva_tx);
1590 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
1591 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
1592 }
1593 $remise_percent = $custprice_line->discount_percent;
1594 break;
1595 }
1596 }
1597 }
1598 }
1599 }
1600
1601 $line->subprice = $pu_ht;
1602 $line->tva_tx = $tva_tx;
1603 $line->remise_percent = $remise_percent;
1604 // 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)
1605 $line->pa_ht = '';
1606 if ($line->fk_fournprice > 0) {
1607 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1608 $prodfourn = new ProductFournisseur($this->db);
1609 if ($prodfourn->fetch_product_fournisseur_price($line->fk_fournprice) > 0) {
1610 $line->pa_ht = price2num($prodfourn->fourn_unitprice * (1 - $prodfourn->fourn_remise_percent / 100), 'MU');
1611 } else {
1612 $line->fk_fournprice = 0;
1613 }
1614 }
1615 }
1616 if ($update_desc === true) {
1617 $line->desc = $prod->description;
1618 }
1619 }
1620 }
1621 }
1622 }
1623 }
1624
1625 $object->id = 0;
1626 $object->ref = '';
1627 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1628 $object->statut = self::STATUS_DRAFT;
1629 $object->status = self::STATUS_DRAFT;
1630
1631 // Clear fields
1632 $object->user_creation_id = $user->id;
1633 $object->user_validation_id = 0;
1634 $object->date = $now;
1635 $object->datep = $now; // deprecated
1636 $object->fin_validite = $object->date + (int) ($object->duree_validite * 24 * 3600);
1637 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1638 $object->ref_client = '';
1639 $object->ref_customer = '';
1640 }
1641 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1642 $object->note_private = '';
1643 $object->note_public = '';
1644 }
1645 // Create clone
1646 $object->context['createfromclone'] = 'createfromclone';
1647 $result = $object->create($user);
1648 if ($result < 0) {
1650 $error++;
1651 }
1652
1653 if (!$error && !getDolGlobalInt('MAIN_IGNORE_CONTACTS_ON_CLONING')) {
1654 // copy internal contacts
1655 if ($object->copy_linked_contact($this, 'internal') < 0) {
1656 $error++;
1657 }
1658 }
1659
1660 if (!$error) {
1661 // copy external contacts if same company
1662 if ($this->socid == $object->socid) {
1663 if ($object->copy_linked_contact($this, 'external') < 0) {
1664 $error++;
1665 }
1666 }
1667 }
1668
1669 if (!$error) {
1670 // Hook of thirdparty module
1671 if (is_object($hookmanager)) {
1672 $parameters = array('objFrom' => $this, 'clonedObj' => $object);
1673 $action = '';
1674 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1675 if ($reshook < 0) {
1676 $this->setErrorsFromObject($hookmanager);
1677 $error++;
1678 }
1679 }
1680 }
1681
1682 unset($object->context['createfromclone']);
1683
1684 // End
1685 if (!$error) {
1686 $this->db->commit();
1687 return $object->id;
1688 } else {
1689 $this->db->rollback();
1690 return -1;
1691 }
1692 }
1693
1703 public function fetch($rowid, $ref = '', $ref_ext = '', $forceentity = 0)
1704 {
1705 $sql = "SELECT p.rowid, p.ref, p.entity, p.fk_soc";
1706 $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht";
1707 $sql .= ", p.datec";
1708 $sql .= ", p.date_signature as dates";
1709 $sql .= ", p.date_valid as datev";
1710 $sql .= ", p.date_cloture";
1711 $sql .= ", p.datep as dp";
1712 $sql .= ", p.fin_validite as dfv";
1713 $sql .= ", p.date_livraison as delivery_date";
1714 $sql .= ", p.model_pdf, p.last_main_doc, p.ref_client, ref_ext, p.extraparams";
1715 $sql .= ", p.note_private, p.note_public";
1716 $sql .= ", p.fk_projet as fk_project, p.fk_statut";
1717 $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1718 $sql .= ", p.fk_delivery_address";
1719 $sql .= ", p.fk_availability";
1720 $sql .= ", p.fk_input_reason";
1721 $sql .= ", p.fk_cond_reglement";
1722 $sql .= ", p.fk_mode_reglement";
1723 $sql .= ', p.fk_account';
1724 $sql .= ", p.fk_shipping_method";
1725 $sql .= ", p.fk_warehouse";
1726 $sql .= ", p.fk_incoterms, p.location_incoterms";
1727 $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1728 $sql .= ", p.tms as date_modification";
1729 $sql .= ", i.libelle as label_incoterms";
1730 $sql .= ", c.label as statut_label";
1731 $sql .= ", ca.code as availability_code, ca.label as availability";
1732 $sql .= ", dr.code as demand_reason_code, dr.label as demand_reason";
1733 $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc, p.deposit_percent";
1734 $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1735 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
1736 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id';
1737 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')';
1738 $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').')';
1739 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1740 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1741 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1742
1743 if (!empty($ref)) {
1744 if (!empty($forceentity)) {
1745 $sql .= " WHERE p.entity = ".(int) $forceentity; // Check only the current entity because we may have the same reference in several entities
1746 } else {
1747 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
1748 }
1749 $sql .= " AND p.ref='".$this->db->escape($ref)."'";
1750 } else {
1751 // Don't use entity if you use rowid
1752 $sql .= " WHERE p.rowid = ".((int) $rowid);
1753 }
1754
1755 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1756 $resql = $this->db->query($sql);
1757 if ($resql) {
1758 if ($this->db->num_rows($resql)) {
1759 $obj = $this->db->fetch_object($resql);
1760
1761 $this->id = $obj->rowid;
1762 $this->entity = $obj->entity;
1763
1764 $this->ref = $obj->ref;
1765 $this->ref_client = $obj->ref_client;
1766 $this->ref_customer = $obj->ref_client;
1767 $this->ref_ext = $obj->ref_ext;
1768
1769 $this->total = $obj->total_ttc; // TODO deprecated
1770 $this->total_ttc = $obj->total_ttc;
1771 $this->total_ht = $obj->total_ht;
1772 $this->total_tva = $obj->total_tva;
1773 $this->total_localtax1 = $obj->localtax1;
1774 $this->total_localtax2 = $obj->localtax2;
1775
1776 $this->socid = $obj->fk_soc;
1777 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
1778
1779 $this->fk_project = $obj->fk_project;
1780 $this->project = null; // Clear if another value was already set by fetchProject
1781
1782 $this->model_pdf = $obj->model_pdf;
1783 $this->last_main_doc = $obj->last_main_doc;
1784 $this->note = $obj->note_private; // TODO deprecated
1785 $this->note_private = $obj->note_private;
1786 $this->note_public = $obj->note_public;
1787
1788 $this->status = (int) $obj->fk_statut;
1789 $this->statut = $this->status; // deprecated
1790
1791 $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
1792 $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
1793 $this->date_creation = $this->db->jdate($obj->datec); //Creation date
1794 $this->date_validation = $this->db->jdate($obj->datev); //Validation date
1795 $this->date_modification = $this->db->jdate($obj->date_modification); // tms
1796 $this->date_signature = $this->db->jdate($obj->dates); // Signature date
1797 $this->date_cloture = $this->db->jdate($obj->date_cloture); // Closing date
1798 $this->date = $this->db->jdate($obj->dp); // Proposal date
1799 $this->datep = $this->db->jdate($obj->dp); // deprecated
1800 $this->fin_validite = $this->db->jdate($obj->dfv);
1801 $this->delivery_date = $this->db->jdate($obj->delivery_date);
1802 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1803 $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
1804 $this->availability_id = $obj->fk_availability;
1805 $this->availability_code = $obj->availability_code;
1806 $this->availability = $obj->availability;
1807 $this->demand_reason_id = $obj->fk_input_reason;
1808 $this->demand_reason_code = $obj->demand_reason_code;
1809 $this->demand_reason = $obj->demand_reason;
1810 $this->fk_address = $obj->fk_delivery_address;
1811
1812 $this->mode_reglement_id = $obj->fk_mode_reglement;
1813 $this->mode_reglement_code = $obj->mode_reglement_code;
1814 $this->mode_reglement = $obj->mode_reglement;
1815 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
1816 $this->cond_reglement_id = $obj->fk_cond_reglement;
1817 $this->cond_reglement_code = $obj->cond_reglement_code;
1818 $this->cond_reglement = $obj->cond_reglement;
1819 $this->cond_reglement_label = $obj->cond_reglement;
1820 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1821 $this->deposit_percent = $obj->deposit_percent;
1822
1823 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
1824
1825 $this->user_author_id = $obj->fk_user_author;
1826 $this->user_validation_id = $obj->fk_user_valid;
1827 $this->user_closing_id = $obj->fk_user_cloture;
1828
1829 //Incoterms
1830 $this->fk_incoterms = $obj->fk_incoterms;
1831 $this->location_incoterms = $obj->location_incoterms;
1832 $this->label_incoterms = $obj->label_incoterms;
1833
1834 // Multicurrency
1835 $this->fk_multicurrency = $obj->fk_multicurrency;
1836 $this->multicurrency_code = $obj->multicurrency_code;
1837 $this->multicurrency_tx = $obj->multicurrency_tx;
1838 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1839 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1840 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1841
1842 // Retrieve all extrafield
1843 // fetch optionals attributes and labels
1844 $this->fetch_optionals();
1845
1846 $this->db->free($resql);
1847
1848 $this->lines = array();
1849
1850 // Lines
1851 $result = $this->fetch_lines();
1852 if ($result < 0) {
1853 return -3;
1854 }
1855
1856 return 1;
1857 }
1858
1859 $this->error = "Record Not Found";
1860 return 0;
1861 } else {
1862 $this->error = $this->db->lasterror();
1863 return -1;
1864 }
1865 }
1866
1874 public function update(User $user, $notrigger = 0)
1875 {
1876 $error = 0;
1877
1878 // Clean parameters
1879 if (isset($this->ref)) {
1880 $this->ref = trim($this->ref);
1881 }
1882 if (isset($this->ref_client)) {
1883 $this->ref_client = trim($this->ref_client);
1884 }
1885 if (isset($this->note) || isset($this->note_private)) {
1886 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1887 }
1888 if (isset($this->note_public)) {
1889 $this->note_public = trim($this->note_public);
1890 }
1891 if (isset($this->model_pdf)) {
1892 $this->model_pdf = trim($this->model_pdf);
1893 }
1894 if (isset($this->import_key)) {
1895 $this->import_key = trim($this->import_key);
1896 }
1897 if (!empty($this->duree_validite) && is_numeric($this->duree_validite)) {
1898 $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1899 }
1900
1901 // Check parameters
1902 // Put here code to add control on parameters values
1903
1904 // Update request
1905 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1906 $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET";
1907 $sql .= " ref = ".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1908 $sql .= " ref_client = ".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
1909 $sql .= " ref_ext = ".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1910 $sql .= " fk_soc = ".(!empty($this->socid) ? (int) $this->socid : "null").",";
1911 $sql .= " datep = ".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
1912 if (!empty($this->fin_validite)) {
1913 $sql .= " fin_validite = ".(strval($this->fin_validite) != '' ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1914 }
1915 $sql .= " date_valid = ".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1916 $sql .= " total_tva = ".(isset($this->total_tva) ? (float) $this->total_tva : "null").",";
1917 $sql .= " localtax1 = ".(isset($this->total_localtax1) ? (float) $this->total_localtax1 : "null").",";
1918 $sql .= " localtax2 = ".(isset($this->total_localtax2) ? (float) $this->total_localtax2 : "null").",";
1919 $sql .= " total_ht = ".(isset($this->total_ht) ? (float) $this->total_ht : "null").",";
1920 $sql .= " total_ttc = ".(isset($this->total_ttc) ? (float) $this->total_ttc : "null").",";
1921 $sql .= " fk_statut = ".(isset($this->status) ? (int) $this->status : "null").",";
1922 $sql .= " fk_user_author = ".(!empty($this->user_author_id) ? (int) $this->user_author_id : "null").",";
1923 $sql .= " fk_user_valid = ".(!empty($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
1924
1925 $sql .= " fk_projet = ".(!empty($this->fk_project) ? (int) $this->fk_project : "null").",";
1926 $sql .= " fk_cond_reglement = ".(!empty($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
1927 $sql .= " deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
1928 $sql .= " fk_mode_reglement = ".(!empty($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
1929 $sql .= " fk_input_reason = ".(!empty($this->demand_reason_id) ? (int) $this->demand_reason_id : "null").",";
1930 $sql .= " fk_shipping_method = ".(isset($this->shipping_method_id) ? (int) $this->shipping_method_id : "null").",";
1931 $sql .= " fk_availability = ".(!empty($this->availability_id) ? (int) $this->availability_id : "null").",";
1932 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1933 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1934 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1935 $sql .= " import_key = ".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1936 $sql .= " WHERE rowid = ".((int) $this->id);
1937
1938 $this->db->begin();
1939
1940 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1941 $resql = $this->db->query($sql);
1942 if (!$resql) {
1943 $error++;
1944 $this->errors[] = "Error ".$this->db->lasterror();
1945 }
1946
1947 if (!$error) {
1948 $result = $this->insertExtraFields();
1949 if ($result < 0) {
1950 $error++;
1951 }
1952 }
1953
1954 if (!$error && !$notrigger) {
1955 // Call trigger
1956 $result = $this->call_trigger('PROPAL_MODIFY', $user);
1957 if ($result < 0) {
1958 $error++;
1959 }
1960 // End call triggers
1961 }
1962
1963 // Commit or rollback
1964 if ($error) {
1965 foreach ($this->errors as $errmsg) {
1966 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1967 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1968 }
1969 $this->db->rollback();
1970 return -1 * $error;
1971 } else {
1972 $this->db->commit();
1973 return 1;
1974 }
1975 }
1976
1977
1978 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1987 public function fetch_lines($only_product = 0, $loadalsotranslation = 0, $sqlforgedfilters = '')
1988 {
1989 // phpcs:enable
1990 $this->lines = array();
1991
1992 $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.subprice_ttc, d.fk_product,';
1993 $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,';
1994 $sql .= ' d.fk_unit,';
1995 $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,';
1996 $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units,';
1997 $sql .= ' p.customcode, p.fk_country as country_id, c.code as country_code,';
1998 $sql .= ' d.date_start, d.date_end, d.extraparams,';
1999 $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
2000 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as d';
2001 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
2002 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON c.rowid = p.fk_country';
2003 $sql .= ' WHERE d.fk_propal = '.((int) $this->id);
2004 if ($only_product) {
2005 $sql .= ' AND p.fk_product_type = 0';
2006 }
2007 if ($sqlforgedfilters) {
2008 $sql .= $sqlforgedfilters;
2009 }
2010 $sql .= ' ORDER BY d.rang, d.rowid';
2011
2012 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
2013 $result = $this->db->query($sql);
2014 if ($result) {
2015 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2016
2017 $num = $this->db->num_rows($result);
2018
2019 $i = 0;
2020 while ($i < $num) {
2021 $objp = $this->db->fetch_object($result);
2022
2023 $line = new PropaleLigne($this->db);
2024
2025 $line->rowid = $objp->rowid; //Deprecated
2026 $line->id = $objp->rowid;
2027 $line->fk_propal = $objp->fk_propal;
2028 $line->fk_parent_line = $objp->fk_parent_line;
2029 $line->label = $objp->custom_label;
2030 $line->desc = $objp->description; // Line description
2031 $line->description = $objp->description; // Line description
2032 $line->qty = $objp->qty;
2033 $line->vat_src_code = $objp->vat_src_code;
2034 $line->tva_tx = $objp->tva_tx;
2035 $line->localtax1_tx = $objp->localtax1_tx;
2036 $line->localtax2_tx = $objp->localtax2_tx;
2037 $line->localtax1_type = $objp->localtax1_type;
2038 $line->localtax2_type = $objp->localtax2_type;
2039 $line->subprice = $objp->subprice;
2040 $line->subprice_ttc = $objp->subprice_ttc;
2041 $line->fk_remise_except = $objp->fk_remise_except;
2042 $line->remise_percent = $objp->remise_percent;
2043
2044 $line->info_bits = $objp->info_bits;
2045 $line->total_ht = $objp->total_ht;
2046 $line->total_tva = $objp->total_tva;
2047 $line->total_localtax1 = $objp->total_localtax1;
2048 $line->total_localtax2 = $objp->total_localtax2;
2049 $line->total_ttc = $objp->total_ttc;
2050 $line->fk_fournprice = $objp->fk_fournprice;
2051 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2052 $line->pa_ht = $marginInfos[0];
2053 $line->marge_tx = $marginInfos[1];
2054 $line->marque_tx = $marginInfos[2];
2055 $line->special_code = $objp->special_code;
2056 $line->rang = $objp->rang;
2057
2058 $line->fk_product = $objp->fk_product;
2059
2060 $line->ref = $objp->product_ref; // deprecated
2061 $line->libelle = $objp->product_label; // deprecated
2062
2063 $line->product_ref = $objp->product_ref;
2064 $line->product_label = $objp->product_label;
2065 $line->product_desc = $objp->product_desc; // Description produit
2066 $line->product_tobatch = $objp->product_tobatch;
2067 $line->product_barcode = $objp->product_barcode;
2068 $line->product_custom_code = $objp->customcode;
2069 $line->product_custom_country_id = $objp->country_id;
2070 $line->product_custom_country_code = $objp->country_code;
2071 $line->product_type = $objp->product_type;
2072 $line->fk_product_type = $objp->fk_product_type; // deprecated
2073
2074 $line->fk_unit = $objp->fk_unit;
2075 $line->weight = $objp->weight;
2076 $line->weight_units = $objp->weight_units;
2077 $line->volume = $objp->volume;
2078 $line->volume_units = $objp->volume_units;
2079
2080 $line->date_start = $this->db->jdate($objp->date_start);
2081 $line->date_end = $this->db->jdate($objp->date_end);
2082
2083 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2084
2085 // Multicurrency
2086 $line->fk_multicurrency = $objp->fk_multicurrency;
2087 $line->multicurrency_code = $objp->multicurrency_code;
2088 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2089 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2090 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2091 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2092
2093 $line->fetch_optionals();
2094
2095 // multilangs
2096 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2097 $tmpproduct = new Product($this->db);
2098 $tmpproduct->fetch($objp->fk_product);
2099 $tmpproduct->getMultiLangs();
2100
2101 $line->multilangs = $tmpproduct->multilangs;
2102 }
2103
2104 $this->lines[$i] = $line;
2105
2106 $i++;
2107 }
2108
2109 $this->db->free($result);
2110
2111 return $num;
2112 } else {
2113 $this->error = $this->db->lasterror();
2114 return -3;
2115 }
2116 }
2117
2125 public function valid($user, $notrigger = 0)
2126 {
2127 global $conf;
2128
2129 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2130
2131 $error = 0;
2132
2133 // Protection
2134 if ($this->status == self::STATUS_VALIDATED) {
2135 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
2136 return 0;
2137 }
2138
2139 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('propal', 'creer'))
2140 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('propal', 'propal_advance', 'validate')))) {
2141 $this->error = 'ErrorPermissionDenied';
2142 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
2143 return -1;
2144 }
2145
2146 if (!getDolGlobalBool('PROPALE_NOCHECK_ONSALE_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines()) {
2147 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
2148 return -1;
2149 }
2150
2151 $now = dol_now();
2152
2153 $this->db->begin();
2154
2155 // Numbering module definition
2156 $soc = new Societe($this->db);
2157 $soc->fetch($this->socid);
2158
2159 // Define new ref
2160 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
2161 $num = $this->getNextNumRef($soc);
2162 } else {
2163 $num = (string) $this->ref;
2164 }
2165 $this->newref = dol_sanitizeFileName($num);
2166
2167 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2168 $sql .= " SET ref = '".$this->db->escape($num)."',";
2169 $sql .= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".((int) $user->id);
2170 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
2171
2172 dol_syslog(get_class($this)."::valid", LOG_DEBUG);
2173 $resql = $this->db->query($sql);
2174 if (!$resql) {
2175 dol_print_error($this->db);
2176 $error++;
2177 }
2178
2179 // Trigger calls
2180 if (!$error && !$notrigger) {
2181 // Call trigger
2182 $result = $this->call_trigger('PROPAL_VALIDATE', $user);
2183 if ($result < 0) {
2184 $error++;
2185 }
2186 // End call triggers
2187 }
2188
2189 if (!$error) {
2190 $this->oldref = $this->ref;
2191
2192 // Rename directory if dir was a temporary ref
2193 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
2194 // Now we rename also files into index
2195 $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)."'";
2196 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
2197 $resql = $this->db->query($sql);
2198 if (!$resql) {
2199 $error++;
2200 $this->error = $this->db->lasterror();
2201 }
2202 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'propale/".$this->db->escape($this->newref)."'";
2203 $sql .= " WHERE filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
2204 $resql = $this->db->query($sql);
2205 if (!$resql) {
2206 $error++;
2207 $this->error = $this->db->lasterror();
2208 }
2209
2210 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
2211 $oldref = dol_sanitizeFileName($this->ref);
2212 $newref = dol_sanitizeFileName($num);
2213 $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref;
2214 $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref;
2215 if (!$error && file_exists($dirsource)) {
2216 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
2217 if (@rename($dirsource, $dirdest)) {
2218 dol_syslog("Rename ok");
2219 // Rename docs starting with $oldref with $newref
2220 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
2221 foreach ($listoffiles as $fileentry) {
2222 $dirsource = $fileentry['name'];
2223 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
2224 $dirsource = $fileentry['path'].'/'.$dirsource;
2225 $dirdest = $fileentry['path'].'/'.$dirdest;
2226 @rename($dirsource, $dirdest);
2227 }
2228 }
2229 }
2230 }
2231
2232 $this->ref = $num;
2233 $this->statut = self::STATUS_VALIDATED; // deprecated
2235 $this->user_validation_id = $user->id;
2236 $this->datev = $now;
2237 $this->date_validation = $now;
2238
2239 $this->db->commit();
2240 return 1;
2241 } else {
2242 $this->db->rollback();
2243 return -1;
2244 }
2245 }
2246
2247
2248 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2257 public function set_date($user, $date, $notrigger = 0)
2258 {
2259 // phpcs:enable
2260 if (empty($date)) {
2261 $this->error = 'ErrorBadParameter';
2262 dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
2263 return -1;
2264 }
2265
2266 if ($user->hasRight('propal', 'creer')) {
2267 $error = 0;
2268
2269 $this->db->begin();
2270
2271 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2272 $sql .= " SET datep = '".$this->db->idate($date)."'";
2273 $sql .= " WHERE rowid = ".((int) $this->id);
2274
2275 dol_syslog(__METHOD__, LOG_DEBUG);
2276 $resql = $this->db->query($sql);
2277 if (!$resql) {
2278 $this->errors[] = $this->db->error();
2279 $error++;
2280 }
2281
2282 if (!$error) {
2283 $this->oldcopy = clone $this;
2284 $this->date = $date;
2285 $this->datep = $date; // deprecated
2286 }
2287
2288 if (!$notrigger && empty($error)) {
2289 // Call trigger
2290 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2291 if ($result < 0) {
2292 $error++;
2293 }
2294 // End call triggers
2295 }
2296
2297 if (!$error) {
2298 $this->db->commit();
2299 return 1;
2300 } else {
2301 foreach ($this->errors as $errmsg) {
2302 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2303 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2304 }
2305 $this->db->rollback();
2306 return -1 * $error;
2307 }
2308 }
2309
2310 return -1;
2311 }
2312
2313 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2322 public function set_echeance($user, $date_end_validity, $notrigger = 0)
2323 {
2324 // phpcs:enable
2325 if ($user->hasRight('propal', 'creer')) {
2326 $error = 0;
2327
2328 $this->db->begin();
2329
2330 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2331 $sql .= " SET fin_validite = ".($date_end_validity != '' ? "'".$this->db->idate($date_end_validity)."'" : 'null');
2332 $sql .= " WHERE rowid = ".((int) $this->id);
2333
2334 dol_syslog(__METHOD__, LOG_DEBUG);
2335
2336 $resql = $this->db->query($sql);
2337 if (!$resql) {
2338 $this->errors[] = $this->db->error();
2339 $error++;
2340 }
2341
2342
2343 if (!$error) {
2344 $this->oldcopy = clone $this;
2345 $this->fin_validite = $date_end_validity;
2346 }
2347
2348 if (!$notrigger && empty($error)) {
2349 // Call trigger
2350 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2351 if ($result < 0) {
2352 $error++;
2353 }
2354 // End call triggers
2355 }
2356
2357 if (!$error) {
2358 $this->db->commit();
2359 return 1;
2360 } else {
2361 foreach ($this->errors as $errmsg) {
2362 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2363 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2364 }
2365 $this->db->rollback();
2366 return -1 * $error;
2367 }
2368 }
2369
2370 return -1;
2371 }
2372
2373 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2383 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2384 {
2385 // phpcs:enable
2386 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2387 }
2388
2397 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2398 {
2399 if ($user->hasRight('propal', 'creer')) {
2400 $error = 0;
2401
2402 $this->db->begin();
2403
2404 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2405 $sql .= " SET date_livraison = ".(isDolTms($delivery_date) ? "'".$this->db->idate($delivery_date)."'" : 'null');
2406 $sql .= " WHERE rowid = ".((int) $this->id);
2407
2408 dol_syslog(__METHOD__, LOG_DEBUG);
2409 $resql = $this->db->query($sql);
2410 if (!$resql) {
2411 $this->errors[] = $this->db->error();
2412 $error++;
2413 }
2414
2415 if (!$error) {
2416 $this->oldcopy = clone $this;
2417 $this->delivery_date = $delivery_date;
2418 }
2419
2420 if (!$notrigger && empty($error)) {
2421 // Call trigger
2422 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2423 if ($result < 0) {
2424 $error++;
2425 }
2426 // End call triggers
2427 }
2428
2429 if (!$error) {
2430 $this->db->commit();
2431 return 1;
2432 } else {
2433 foreach ($this->errors as $errmsg) {
2434 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2435 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2436 }
2437 $this->db->rollback();
2438 return -1 * $error;
2439 }
2440 }
2441
2442 return -1;
2443 }
2444
2445 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2454 public function set_availability($user, $id, $notrigger = 0)
2455 {
2456 // phpcs:enable
2457 if ($this->status >= self::STATUS_DRAFT) {
2458 $error = 0;
2459
2460 $this->db->begin();
2461
2462 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2463 $sql .= " SET fk_availability = ".((int) ($id > 0 ? ((int) $id) : 0));
2464 $sql .= " WHERE rowid = ".((int) $this->id);
2465
2466 dol_syslog(__METHOD__.' availability('.$id.')', LOG_DEBUG);
2467 $resql = $this->db->query($sql);
2468 if (!$resql) {
2469 $this->errors[] = $this->db->error();
2470 $error++;
2471 }
2472
2473 if (!$error) {
2474 $this->oldcopy = clone $this;
2475 $this->fk_availability = $id;
2476 $this->availability_id = $id;
2477 }
2478
2479 if (!$notrigger && empty($error)) {
2480 // Call trigger
2481 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2482 if ($result < 0) {
2483 $error++;
2484 }
2485 // End call triggers
2486 }
2487
2488 if (!$error) {
2489 $this->db->commit();
2490 return 1;
2491 } else {
2492 foreach ($this->errors as $errmsg) {
2493 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2494 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2495 }
2496 $this->db->rollback();
2497 return -1 * $error;
2498 }
2499 } else {
2500 $error_str = 'Propal status do not meet requirement '.$this->status;
2501 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2502 $this->error = $error_str;
2503 $this->errors[] = $this->error;
2504 return -2;
2505 }
2506 }
2507
2508 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2517 public function set_demand_reason($user, $id, $notrigger = 0)
2518 {
2519 // phpcs:enable
2520 if ($user->hasRight('propal', 'creer') && $this->status >= self::STATUS_DRAFT) {
2521 $error = 0;
2522
2523 $this->db->begin();
2524
2525 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2526 $sql .= " SET fk_input_reason = ".((int) $id);
2527 $sql .= " WHERE rowid = ".((int) $this->id);
2528
2529 dol_syslog(__METHOD__, LOG_DEBUG);
2530 $resql = $this->db->query($sql);
2531 if (!$resql) {
2532 $this->errors[] = $this->db->error();
2533 $error++;
2534 }
2535
2536
2537 if (!$error) {
2538 $this->oldcopy = clone $this;
2539
2540 $this->demand_reason_id = $id;
2541 }
2542
2543
2544 if (!$notrigger && empty($error)) {
2545 // Call trigger
2546 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2547 if ($result < 0) {
2548 $error++;
2549 }
2550 // End call triggers
2551 }
2552
2553 if (!$error) {
2554 $this->db->commit();
2555 return 1;
2556 } else {
2557 foreach ($this->errors as $errmsg) {
2558 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2559 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2560 }
2561 $this->db->rollback();
2562 return -1 * $error;
2563 }
2564 } else {
2565 $error_str = 'Propal status do not meet requirement '.$this->status;
2566 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2567 $this->error = $error_str;
2568 $this->errors[] = $this->error;
2569 return -2;
2570 }
2571 }
2572
2573 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2582 public function set_ref_client($user, $ref_client, $notrigger = 0)
2583 {
2584 // phpcs:enable
2585 if ($user->hasRight('propal', 'creer')) {
2586 $error = 0;
2587
2588 $this->db->begin();
2589
2590 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2591 $sql .= " SET ref_client = ".(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
2592 $sql .= " WHERE rowid = ".((int) $this->id);
2593
2594 dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2595 $resql = $this->db->query($sql);
2596 if (!$resql) {
2597 $this->errors[] = $this->db->error();
2598 $error++;
2599 }
2600
2601 if (!$error) {
2602 $this->oldcopy = clone $this;
2603 $this->ref_customer = $ref_client;
2604 $this->ref_client = $ref_client;
2605 }
2606
2607 if (!$notrigger && empty($error)) {
2608 // Call trigger
2609 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2610 if ($result < 0) {
2611 $error++;
2612 }
2613 // End call triggers
2614 }
2615
2616 if (!$error) {
2617 $this->db->commit();
2618 return 1;
2619 } else {
2620 foreach ($this->errors as $errmsg) {
2621 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2622 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2623 }
2624 $this->db->rollback();
2625 return -1 * $error;
2626 }
2627 }
2628
2629 return -1;
2630 }
2631
2632
2642 public function reopen($user, $status, $note = '', $notrigger = 0)
2643 {
2644 $error = 0;
2645
2646 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2647 $sql .= " SET fk_statut = ".((int) $status).",";
2648 if (!empty($note)) {
2649 $sql .= " note_private = '".$this->db->escape($note)."',";
2650 }
2651 $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
2652 $sql .= " WHERE rowid = ".((int) $this->id);
2653
2654 $this->db->begin();
2655
2656 dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
2657 $resql = $this->db->query($sql);
2658 if (!$resql) {
2659 $error++;
2660 $this->errors[] = "Error ".$this->db->lasterror();
2661 }
2662 if (!$error) {
2663 if (!$notrigger) {
2664 // Call trigger
2665 $result = $this->call_trigger('PROPAL_REOPEN', $user);
2666 if ($result < 0) {
2667 $error++;
2668 }
2669 // End call triggers
2670 }
2671 }
2672
2673 // Commit or rollback
2674 if ($error) {
2675 if (!empty($this->errors)) {
2676 foreach ($this->errors as $errmsg) {
2677 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2678 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2679 }
2680 }
2681 $this->db->rollback();
2682 return -1 * $error;
2683 } else {
2684 $this->statut = $status;
2685 $this->status = $status;
2686
2687 $this->db->commit();
2688 return 1;
2689 }
2690 }
2691
2702 public function closeProposal($user, $status, $note_private = '', $notrigger = 0, $note_public = '')
2703 {
2704 global $langs,$conf;
2705
2706 $error = 0;
2707 $now = dol_now();
2708
2709 $this->db->begin();
2710
2711 $newprivatenote = dol_concatdesc($this->note_private, $note_private);
2712 $newpublicnote = dol_concatdesc($this->note_public, $note_public);
2713
2714 if (!getDolGlobalString('PROPALE_KEEP_OLD_SIGNATURE_INFO')) {
2715 $date_signature = $now;
2716 $fk_user_signature = $user->id;
2717 } else {
2718 $this->info($this->id);
2719 if (!isset($this->date_signature) || $this->date_signature == '') {
2720 $date_signature = $now;
2721 $fk_user_signature = $user->id;
2722 } else {
2723 $date_signature = $this->date_signature;
2724 $fk_user_signature = $this->user_signature->id;
2725 }
2726 }
2727
2728 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2729 $sql .= " SET fk_statut = ".((int) $status).", note_private = '".$this->db->escape($newprivatenote)."', note_public = '".$this->db->escape($newpublicnote)."'";
2730 if ($status == self::STATUS_SIGNED) {
2731 $sql .= ", date_signature='".$this->db->idate($now)."', fk_user_signature = ".((int) $fk_user_signature);
2732 }
2733 $sql .= " WHERE rowid = ".((int) $this->id);
2734
2735 $resql = $this->db->query($sql);
2736 if ($resql) {
2737 // Status self::STATUS_REFUSED by default
2738 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_CLOSED', $this->model_pdf);
2739 $triggerName = 'PROPAL_CLOSE_REFUSED'; // used later in call_trigger()
2740
2741 if ($status == self::STATUS_SIGNED) { // Status self::STATUS_SIGNED
2742 $triggerName = 'PROPAL_CLOSE_SIGNED'; // used later in call_trigger()
2743 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_TOBILL', $this->model_pdf);
2744
2745 // The connected company is classified as a client
2746 $soc = new Societe($this->db);
2747 $soc->fetch($this->socid);
2748 $result = $soc->setAsCustomer();
2749
2750 if ($result < 0) {
2751 $this->error = $this->db->lasterror();
2752 $this->db->rollback();
2753 return -2;
2754 }
2755 }
2756
2757 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE') && !getDolGlobalInt('PROPAL_DISABLE_AUTOUPDATE_ON_CLOSE')) {
2758 // Define output language
2759 $outputlangs = $langs;
2760 if (getDolGlobalInt('MAIN_MULTILANGS')) {
2761 $outputlangs = new Translate("", $conf);
2762 $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2763 $outputlangs->setDefaultLang($newlang);
2764 }
2765
2766 // PDF
2767 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
2768 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
2769 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
2770
2771 //$ret=$object->fetch($id); // Reload to get new records
2772 $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2773 }
2774
2775 $this->oldcopy = clone $this;
2776 $this->statut = $status; // deprecated
2777 $this->status = $status;
2778 $this->date_signature = $date_signature;
2779 $this->note_private = $newprivatenote;
2780
2781 if (!$notrigger && empty($error)) {
2782 // Call trigger
2783 $result = $this->call_trigger($triggerName, $user);
2784 if ($result < 0) {
2785 $error++;
2786 }
2787 // End call triggers
2788 }
2789
2790 if (!$error) {
2791 $this->db->commit();
2792 return 1;
2793 } else {
2794 foreach ($this->errors as $errmsg) {
2795 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2796 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2797 }
2798 if (!empty($this->oldcopy)) {
2799 $this->statut = $this->oldcopy->status; // deprecated
2800 $this->status = $this->oldcopy->status;
2801 $this->date_signature = $this->oldcopy->date_signature;
2802 $this->note_private = $this->oldcopy->note_private;
2803 }
2804
2805 $this->db->rollback();
2806 return -1;
2807 }
2808 } else {
2809 $this->error = $this->db->lasterror();
2810 $this->db->rollback();
2811 return -1;
2812 }
2813 }
2814
2823 public function classifyBilled(User $user, $notrigger = 0, $note = '')
2824 {
2825 global $conf, $langs;
2826
2827 $error = 0;
2828
2829 $now = dol_now();
2830 $num = 0;
2831
2832 $triggerName = 'PROPAL_CLASSIFY_BILLED';
2833
2834 $this->db->begin();
2835
2836 $newprivatenote = dol_concatdesc($this->note_private, $note);
2837
2838 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2839 $sql .= " SET fk_statut = ".self::STATUS_BILLED.", ";
2840 $sql .= " note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".((int) $user->id);
2841 $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_SIGNED);
2842
2843 dol_syslog(__METHOD__, LOG_DEBUG);
2844 $resql = $this->db->query($sql);
2845 if (!$resql) {
2846 $this->errors[] = $this->db->error();
2847 $error++;
2848 } else {
2849 $num = $this->db->affected_rows($resql);
2850 }
2851
2852 if (!$error) {
2853 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_CLOSED', $this->model_pdf);
2854
2855 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2856 // Define output language
2857 $outputlangs = $langs;
2858 if (getDolGlobalInt('MAIN_MULTILANGS')) {
2859 $outputlangs = new Translate("", $conf);
2860 $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2861 $outputlangs->setDefaultLang($newlang);
2862 }
2863
2864 // PDF
2865 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
2866 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
2867 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
2868
2869 //$ret=$object->fetch($id); // Reload to get new records
2870 $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2871 }
2872
2873 $this->oldcopy = clone $this;
2874 $this->statut = self::STATUS_BILLED;
2875 $this->status = self::STATUS_BILLED;
2876 $this->date_cloture = $now;
2877 $this->note_private = $newprivatenote;
2878 }
2879
2880 if (!$notrigger && empty($error)) {
2881 // Call trigger
2882 $result = $this->call_trigger($triggerName, $user);
2883 if ($result < 0) {
2884 $error++;
2885 }
2886 // End call triggers
2887 }
2888
2889 if (!$error) {
2890 $this->db->commit();
2891 return $num;
2892 } else {
2893 foreach ($this->errors as $errmsg) {
2894 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2895 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2896 }
2897 $this->db->rollback();
2898 return -1 * $error;
2899 }
2900 }
2901
2908 public function setCancel(User $user)
2909 {
2910 $error = 0;
2911
2912 $this->db->begin();
2913
2914 $sql = "UPDATE ". MAIN_DB_PREFIX . $this->table_element;
2915 $sql .= " SET fk_statut = " . self::STATUS_CANCELED . ",";
2916 $sql .= " fk_user_modif = " . ((int) $user->id);
2917 $sql .= " WHERE rowid = " . ((int) $this->id);
2918
2919 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
2920 if ($this->db->query($sql)) {
2921 // Call trigger
2922 $result = $this->call_trigger('PROPAL_CANCEL', $user);
2923 if ($result < 0) {
2924 $error++;
2925 }
2926 // End call triggers
2927
2928 if (!$error) {
2929 $this->statut = self::STATUS_CANCELED; // deprecated
2931 $this->db->commit();
2932 return 1;
2933 } else {
2934 foreach ($this->errors as $errmsg) {
2935 dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
2936 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2937 }
2938 $this->db->rollback();
2939 return -1;
2940 }
2941 } else {
2942 $this->error = $this->db->error();
2943 $this->db->rollback();
2944 return -1;
2945 }
2946 }
2947
2948 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2956 public function setDraft($user, $notrigger = 0)
2957 {
2958 // phpcs:enable
2959 $error = 0;
2960
2961 // Protection
2962 if ($this->status <= self::STATUS_DRAFT) {
2963 return 0;
2964 }
2965
2966 dol_syslog(get_class($this)."::setDraft", LOG_DEBUG);
2967
2968 $this->db->begin();
2969
2970 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2971 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2972 $sql .= ", online_sign_ip = NULL , online_sign_name = NULL";
2973 $sql .= " WHERE rowid = ".((int) $this->id);
2974
2975 $resql = $this->db->query($sql);
2976 if (!$resql) {
2977 $this->errors[] = $this->db->error();
2978 $error++;
2979 }
2980
2981 if (!$error) {
2982 $this->oldcopy = clone $this;
2983 }
2984
2985 if (!$notrigger && empty($error)) {
2986 // Call trigger
2987 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2988 if ($result < 0) {
2989 $error++;
2990 }
2991 // End call triggers
2992 }
2993
2994 if (!$error) {
2995 $this->statut = self::STATUS_DRAFT; // deprecated
2996 $this->status = self::STATUS_DRAFT;
2997
2998 $this->db->commit();
2999 return 1;
3000 } else {
3001 foreach ($this->errors as $errmsg) {
3002 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3003 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3004 }
3005 $this->db->rollback();
3006 return -1 * $error;
3007 }
3008 }
3009
3010
3011 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3025 public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datep', $sortorder = 'DESC')
3026 {
3027 // phpcs:enable
3028 global $user;
3029
3030 $ga = array();
3031
3032 $sql = "SELECT s.rowid, s.nom as name, s.client,";
3033 $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
3034 $sql .= " p.datep as dp, p.fin_validite as datelimite";
3035 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX.$this->table_element." as p, ".MAIN_DB_PREFIX."c_propalst as c";
3036 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3037 $sql .= " AND p.fk_soc = s.rowid";
3038 $sql .= " AND p.fk_statut = c.id";
3039
3040 // If the internal user must only see his customers, force searching by him
3041 $search_sale = 0;
3042 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3043 $search_sale = $user->id;
3044 }
3045 // Search on sale representative
3046 if ($search_sale && $search_sale != '-1') {
3047 if ($search_sale == -2) {
3048 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3049 } elseif ($search_sale > 0) {
3050 $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).")";
3051 }
3052 }
3053 // Search on socid
3054 if ($socid) {
3055 $sql .= " AND p.fk_soc = ".((int) $socid);
3056 }
3057 if ($draft) {
3058 $sql .= " AND p.fk_statut = ".((int) self::STATUS_DRAFT);
3059 }
3060 if ($notcurrentuser > 0) {
3061 $sql .= " AND p.fk_user_author <> ".((int) $user->id);
3062 }
3063 $sql .= $this->db->order($sortfield, $sortorder);
3064 $sql .= $this->db->plimit($limit, $offset);
3065
3066 $result = $this->db->query($sql);
3067 if ($result) {
3068 $num = $this->db->num_rows($result);
3069 if ($num) {
3070 $i = 0;
3071 while ($i < $num) {
3072 $obj = $this->db->fetch_object($result);
3073
3074 if ($shortlist == 1) {
3075 $ga[$obj->propalid] = $obj->ref;
3076 } elseif ($shortlist == 2) {
3077 $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
3078 } else {
3079 $ga[$i]['id'] = $obj->propalid;
3080 $ga[$i]['ref'] = $obj->ref;
3081 $ga[$i]['name'] = $obj->name;
3082 }
3083
3084 $i++;
3085 }
3086 }
3087 return $ga;
3088 } else {
3089 dol_print_error($this->db);
3090 return -1;
3091 }
3092 }
3093
3099 public function getInvoiceArrayList()
3100 {
3101 return $this->InvoiceArrayList($this->id);
3102 }
3103
3104 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3111 public function InvoiceArrayList($id)
3112 {
3113 // phpcs:enable
3114 $ga = array();
3115 $linkedInvoices = array();
3116
3117 $this->fetchObjectLinked($id, $this->element);
3118 foreach ($this->linkedObjectsIds as $objecttype => $objectid) {
3119 // New system of common object return rowids and no linear id from 1 to n
3120 // We are therefore traversing a list of objects as a single object
3121 foreach ($objectid as $key => $object) {
3122 // Case of invoices directly linked
3123 if ($objecttype == 'facture') {
3124 $linkedInvoices[] = $object;
3125 } else {
3126 // Case of invoices linked by another object (e.g., order)
3127 $this->fetchObjectLinked($object, $objecttype);
3128 foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) {
3129 foreach ($subobjectid as $subkey => $subobject) {
3130 if ($subobjecttype == 'facture') {
3131 $linkedInvoices[] = $subobject;
3132 }
3133 }
3134 }
3135 }
3136 }
3137 }
3138
3139 if (count($linkedInvoices) > 0) {
3140 $sql = "SELECT rowid as facid, ref, total_ht as total, datef as df, fk_user_author, fk_statut, paye";
3141 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
3142 $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $linkedInvoices)).")";
3143
3144 dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
3145 $resql = $this->db->query($sql);
3146
3147 if ($resql) {
3148 $tab_sqlobj = array();
3149 $nump = $this->db->num_rows($resql);
3150 for ($i = 0; $i < $nump; $i++) {
3151 $obj = $this->db->fetch_object($resql);
3152 $tab_sqlobj[] = $obj;
3153 }
3154 $this->db->free($resql);
3155
3156 $nump = count($tab_sqlobj);
3157
3158 if ($nump) {
3159 $i = 0;
3160 while ($i < $nump) {
3161 $obj = array_shift($tab_sqlobj);
3162
3163 $ga[$i] = $obj;
3164
3165 $i++;
3166 }
3167 }
3168 return $ga;
3169 } else {
3170 return -1;
3171 }
3172 } else {
3173 return $ga;
3174 }
3175 }
3176
3184 public function delete($user, $notrigger = 0)
3185 {
3186 global $conf;
3187 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3188
3189 $error = 0;
3190
3191 $this->db->begin();
3192
3193 if (!$notrigger) {
3194 // Call trigger
3195 $result = $this->call_trigger('PROPAL_DELETE', $user);
3196 if ($result < 0) {
3197 $error++;
3198 }
3199 // End call triggers
3200 }
3201
3202 // Remove linked categories.
3203 if (!$error) {
3204 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_propal";
3205 $sql .= " WHERE fk_propal = ".((int) $this->id);
3206
3207 $result = $this->db->query($sql);
3208 if (!$result) {
3209 $error++;
3210 $this->error = $this->db->lasterror();
3211 $this->errors[] = $this->error;
3212 }
3213 }
3214
3215 // Delete extrafields of lines and lines
3216 if (!$error && !empty($this->table_element_line)) {
3217 $tabletodelete = $this->table_element_line;
3218 $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).")";
3219 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
3220 if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
3221 $error++;
3222 $this->error = $this->db->lasterror();
3223 $this->errors[] = $this->error;
3224 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3225 }
3226 }
3227
3228 if (!$error) {
3229 // Delete linked object
3230 $res = $this->deleteObjectLinked();
3231 if ($res < 0) {
3232 $error++;
3233 }
3234 }
3235
3236 if (!$error) {
3237 // Delete linked contacts
3238 $res = $this->delete_linked_contact();
3239 if ($res < 0) {
3240 $error++;
3241 }
3242 }
3243
3244 // Removed extrafields of object
3245 if (!$error) {
3246 $result = $this->deleteExtraFields();
3247 if ($result < 0) {
3248 $error++;
3249 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3250 }
3251 }
3252
3253 // Delete main record
3254 if (!$error) {
3255 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
3256 $res = $this->db->query($sql);
3257 if (!$res) {
3258 $error++;
3259 $this->error = $this->db->lasterror();
3260 $this->errors[] = $this->error;
3261 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3262 }
3263 }
3264
3265 // Delete record into ECM index and physically
3266 if (!$error) {
3267 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
3268 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3269 if (!$res) {
3270 $error++;
3271 }
3272 }
3273
3274 if (!$error) {
3275 // We remove directory
3276 $ref = dol_sanitizeFileName($this->ref);
3277 if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref)) {
3278 $dir = $conf->propal->multidir_output[$this->entity]."/".$ref;
3279 $file = $dir."/".$ref.".pdf";
3280 if (file_exists($file)) {
3281 dol_delete_preview($this);
3282
3283 if (!dol_delete_file($file, 0, 0, 0, $this)) {
3284 $this->error = 'ErrorFailToDeleteFile';
3285 $this->errors[] = $this->error;
3286 $this->db->rollback();
3287 return 0;
3288 }
3289 }
3290 if (file_exists($dir)) {
3291 $res = @dol_delete_dir_recursive($dir); // delete files physically + into ecm tables
3292 if (!$res) {
3293 $this->error = 'ErrorFailToDeleteDir';
3294 $this->errors[] = $this->error;
3295 $this->db->rollback();
3296 return 0;
3297 }
3298 }
3299 }
3300 }
3301
3302 if (!$error) {
3303 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
3304 $this->db->commit();
3305 return 1;
3306 } else {
3307 $this->db->rollback();
3308 return -1;
3309 }
3310 }
3311
3320 public function availability($availability_id, $notrigger = 0)
3321 {
3322 global $user;
3323
3324 if ($this->status >= self::STATUS_DRAFT) {
3325 $error = 0;
3326
3327 $this->db->begin();
3328
3329 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
3330 $sql .= ' SET fk_availability = '.((int) $availability_id);
3331 $sql .= ' WHERE rowid='.((int) $this->id);
3332
3333 dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
3334 $resql = $this->db->query($sql);
3335 if (!$resql) {
3336 $this->errors[] = $this->db->error();
3337 $error++;
3338 }
3339
3340 if (!$error) {
3341 $this->oldcopy = clone $this;
3342 $this->availability_id = $availability_id;
3343 }
3344
3345 if (!$notrigger && empty($error)) {
3346 // Call trigger
3347 $result = $this->call_trigger('PROPAL_MODIFY', $user);
3348 if ($result < 0) {
3349 $error++;
3350 }
3351 // End call triggers
3352 }
3353
3354 if (!$error) {
3355 $this->db->commit();
3356 return 1;
3357 } else {
3358 foreach ($this->errors as $errmsg) {
3359 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3360 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3361 }
3362 $this->db->rollback();
3363 return -1 * $error;
3364 }
3365 } else {
3366 $error_str = 'Propal status do not meet requirement '.$this->status;
3367 dol_syslog(__METHOD__.$error_str, LOG_ERR);
3368 $this->error = $error_str;
3369 $this->errors[] = $this->error;
3370 return -2;
3371 }
3372 }
3373
3374 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3383 public function demand_reason($demand_reason_id, $notrigger = 0)
3384 {
3385 // phpcs:enable
3386 global $user;
3387
3388 if ($this->status >= self::STATUS_DRAFT) {
3389 $error = 0;
3390
3391 $this->db->begin();
3392
3393 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
3394 $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
3395 $sql .= ' WHERE rowid='.((int) $this->id);
3396
3397 dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
3398 $resql = $this->db->query($sql);
3399 if (!$resql) {
3400 $this->errors[] = $this->db->error();
3401 $error++;
3402 }
3403
3404 if (!$error) {
3405 $this->oldcopy = clone $this;
3406 $this->demand_reason_id = $demand_reason_id;
3407 }
3408
3409 if (!$notrigger && empty($error)) {
3410 // Call trigger
3411 $result = $this->call_trigger('PROPAL_MODIFY', $user);
3412 if ($result < 0) {
3413 $error++;
3414 }
3415 // End call triggers
3416 }
3417
3418 if (!$error) {
3419 $this->db->commit();
3420 return 1;
3421 } else {
3422 foreach ($this->errors as $errmsg) {
3423 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3424 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3425 }
3426 $this->db->rollback();
3427 return -1 * $error;
3428 }
3429 } else {
3430 $error_str = 'Propal status do not meet requirement '.$this->status;
3431 dol_syslog(__METHOD__.$error_str, LOG_ERR);
3432 $this->error = $error_str;
3433 $this->errors[] = $this->error;
3434 return -2;
3435 }
3436 }
3437
3438
3445 public function info($id)
3446 {
3447 $sql = "SELECT c.rowid, ";
3448 $sql .= " c.datec, c.date_valid as datev, c.date_signature, c.date_cloture,";
3449 $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_signature, c.fk_user_cloture";
3450 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
3451 $sql .= " WHERE c.rowid = ".((int) $id);
3452
3453 $result = $this->db->query($sql);
3454
3455 if ($result) {
3456 if ($this->db->num_rows($result)) {
3457 $obj = $this->db->fetch_object($result);
3458
3459 $this->id = $obj->rowid;
3460
3461 $this->date_creation = $this->db->jdate($obj->datec);
3462 $this->date_validation = $this->db->jdate($obj->datev);
3463 $this->date_signature = $this->db->jdate($obj->date_signature);
3464 $this->date_cloture = $this->db->jdate($obj->date_cloture);
3465
3466 $this->user_creation_id = $obj->fk_user_author;
3467 $this->user_validation_id = $obj->fk_user_valid;
3468
3469 if ($obj->fk_user_signature) {
3470 $user_signature = new User($this->db);
3471 $user_signature->fetch($obj->fk_user_signature);
3472 $this->user_signature = $user_signature;
3473 }
3474
3475 $this->user_closing_id = $obj->fk_user_cloture;
3476 }
3477 $this->db->free($result);
3478 } else {
3479 dol_print_error($this->db);
3480 }
3481 }
3482
3483
3490 public function getLibStatut($mode = 0)
3491 {
3492 return $this->LibStatut($this->status, $mode);
3493 }
3494
3495 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3503 public function LibStatut($status, $mode = 1)
3504 {
3505 // phpcs:enable
3506 global $hookmanager;
3507
3508 // Init/load array of translation of status
3509 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3510 global $langs;
3511 $langs->load("propal");
3512 $this->labelStatus[-1] = $langs->transnoentitiesnoconv("PropalStatusCanceled");
3513 $this->labelStatus[0] = $langs->transnoentitiesnoconv("PropalStatusDraft");
3514 $this->labelStatus[1] = $langs->transnoentitiesnoconv("PropalStatusValidated");
3515 $this->labelStatus[2] = $langs->transnoentitiesnoconv("PropalStatusSigned");
3516 $this->labelStatus[3] = $langs->transnoentitiesnoconv("PropalStatusNotSigned");
3517 $this->labelStatus[4] = $langs->transnoentitiesnoconv("PropalStatusBilled");
3518 $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv("PropalStatusCanceledShort");
3519 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("PropalStatusDraftShort");
3520 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("PropalStatusValidatedShort");
3521 $this->labelStatusShort[2] = $langs->transnoentitiesnoconv("PropalStatusSignedShort");
3522 $this->labelStatusShort[3] = $langs->transnoentitiesnoconv("PropalStatusNotSignedShort");
3523 $this->labelStatusShort[4] = $langs->transnoentitiesnoconv("PropalStatusBilledShort");
3524 }
3525
3526 $statusType = '';
3527 if ($status == self::STATUS_CANCELED) {
3528 $statusType = 'status9';
3529 } elseif ($status == self::STATUS_DRAFT) {
3530 $statusType = 'status0';
3531 } elseif ($status == self::STATUS_VALIDATED) {
3532 $statusType = 'status1';
3533 } elseif ($status == self::STATUS_SIGNED) {
3534 $statusType = 'status4';
3535 } elseif ($status == self::STATUS_NOTSIGNED) {
3536 $statusType = 'status9';
3537 } elseif ($status == self::STATUS_BILLED) {
3538 $statusType = 'status6';
3539 }
3540
3541 $parameters = array('status' => $status, 'mode' => $mode);
3542 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
3543
3544 if ($reshook > 0) {
3545 return $hookmanager->resPrint;
3546 }
3547
3548 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3549 }
3550
3551
3552 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3560 public function load_board($user, $mode)
3561 {
3562 // phpcs:enable
3563 global $langs, $hookmanager;
3564
3565 $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin, p.total_ht";
3566 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3567 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
3568 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3569 } else {
3570 $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
3571 }
3572 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3573 if ($mode == 'opened') {
3574 $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3575 }
3576 if ($mode == 'signed') {
3577 $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED;
3578 }
3579
3580 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3581 $sql .= " AND sc.fk_user = ".((int) $user->id);
3582 }
3583 if ($user->socid) {
3584 $sql .= " AND p.fk_soc = ".((int) $user->socid);
3585 }
3586
3587 // If the internal user must only see his customers, force searching by him
3588 $search_sale = 0;
3589 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3590 $search_sale = $user->id;
3591 }
3592 // Search on sale representative
3593 if ($search_sale && $search_sale != '-1') {
3594 if ($search_sale == -2) {
3595 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3596 } elseif ($search_sale > 0) {
3597 $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).")";
3598 }
3599 }
3600 if ($user->socid) {
3601 $sql .= " AND p.fk_soc = ".((int) $user->socid);
3602 }
3603 // Add where from hooks
3604 $parameters = array('socid' => $user->socid);
3605 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3606 $sql .= $hookmanager->resPrint;
3607
3608 $resql = $this->db->query($sql);
3609 if ($resql) {
3610 $langs->load("propal");
3611 $now = dol_now();
3612
3613 $delay_warning = 0;
3614 $status = 0;
3615 $label = $labelShort = '';
3616 if ($mode == 'opened') {
3617 $delay_warning = getWarningDelay('propal', 'cloture');
3618 $status = self::STATUS_VALIDATED;
3619 $label = $langs->transnoentitiesnoconv("PropalsToClose");
3620 $labelShort = $langs->transnoentitiesnoconv("ToAcceptRefuse");
3621 }
3622 if ($mode == 'signed') {
3623 $delay_warning = getWarningDelay('propal', 'facturation');
3624 $status = self::STATUS_SIGNED;
3625 $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered
3626 $labelShort = $langs->trans("ToBill");
3627 }
3628
3629 $response = new WorkboardResponse();
3630 $response->warning_delay = $delay_warning / 60 / 60 / 24;
3631 $response->label = $label;
3632 $response->labelShort = $labelShort;
3633 $response->url = dolBuildUrl(DOL_URL_ROOT.'/comm/propal/list.php', ['search_status' => $status, 'mainmenu' => 'commercial', 'leftmenu' => 'propals']);
3634 $response->url_late = dolBuildUrl(DOL_URL_ROOT.'/comm/propal/list.php', ['search_option' => 'late', 'mainmenu' => 'commercial', 'leftmenu' => 'propals', 'sortfield' => 'p.datep', 'sortorder' => 'asc']);
3635 $response->img = img_object('', "propal");
3636
3637 // This assignment in condition is not a bug. It allows walking the results.
3638 while ($obj = $this->db->fetch_object($resql)) {
3639 $response->nbtodo++;
3640 $response->total += $obj->total_ht;
3641
3642 if ($mode == 'opened') {
3643 $datelimit = $this->db->jdate($obj->datefin);
3644 if ($datelimit < ($now - $delay_warning)) {
3645 $response->nbtodolate++;
3646 }
3647 }
3648 // TODO Definir regle des propales a facturer en retard
3649 // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
3650 }
3651
3652 return $response;
3653 } else {
3654 $this->error = $this->db->error();
3655 return -1;
3656 }
3657 }
3658
3659
3668 public function initAsSpecimen($param = array())
3669 {
3670 global $conf, $langs;
3671
3672 // Load array of products prodids
3673 $num_prods = 0;
3674 $prodids = array();
3675 $sql = "SELECT rowid";
3676 $sql .= " FROM ".MAIN_DB_PREFIX."product";
3677 $sql .= " WHERE entity IN (".getEntity('product').")";
3678 if (array_key_exists('tosell', $param)) {
3679 $sql .= " AND tosell = ".((int) $param['tosell']);
3680 }
3681 $sql .= $this->db->plimit(100);
3682
3683 $resql = $this->db->query($sql);
3684 if ($resql) {
3685 $num_prods = $this->db->num_rows($resql);
3686 $i = 0;
3687 while ($i < $num_prods) {
3688 $i++;
3689 $row = $this->db->fetch_row($resql);
3690 $prodids[$i] = $row[0];
3691 }
3692 }
3693
3694 // Initialise parameters
3695 $this->id = 0;
3696 $this->ref = 'SPECIMEN';
3697 $this->ref_customer = 'NEMICEPS';
3698 $this->ref_client = 'NEMICEPS';
3699 $this->specimen = 1;
3700 $this->socid = 1;
3701 $this->date = time();
3702 $this->fin_validite = $this->date + 3600 * 24 * 30;
3703 $this->cond_reglement_id = 1;
3704 $this->cond_reglement_code = 'RECEP';
3705 $this->mode_reglement_id = 7;
3706 $this->mode_reglement_code = 'CHQ';
3707 $this->availability_id = 1;
3708 $this->availability_code = 'AV_NOW';
3709 $this->demand_reason_id = 1;
3710 $this->demand_reason_code = 'SRC_00';
3711 $this->note_public = 'This is a comment (public)';
3712 $this->note_private = 'This is a comment (private)';
3713
3714 $this->multicurrency_tx = 1;
3715 $this->multicurrency_code = getDolCurrency();
3716
3717 // Lines
3718 $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)
3719 $xnbp = 0;
3720 while ($xnbp < $nbp) {
3721 $line = new PropaleLigne($this->db);
3722 $line->desc = $langs->trans("Description")." ".$xnbp;
3723 $line->qty = 1;
3724 $line->subprice = 100;
3725 $line->tva_tx = 20;
3726 $line->localtax1_tx = 0;
3727 $line->localtax2_tx = 0;
3728 if ($xnbp == 2) {
3729 $line->total_ht = 50;
3730 $line->total_ttc = 60;
3731 $line->total_tva = 10;
3732 $line->remise_percent = 50;
3733 } else {
3734 $line->total_ht = 100;
3735 $line->total_ttc = 120;
3736 $line->total_tva = 20;
3737 $line->remise_percent = 00;
3738 }
3739
3740 if ($num_prods > 0) {
3741 $prodid = mt_rand(1, $num_prods);
3742 $line->fk_product = $prodids[$prodid];
3743 $line->product_ref = 'SPECIMEN';
3744 }
3745
3746 $this->lines[$xnbp] = $line;
3747
3748 $this->total_ht += $line->total_ht;
3749 $this->total_tva += $line->total_tva;
3750 $this->total_ttc += $line->total_ttc;
3751
3752 $xnbp++;
3753 }
3754
3755 return 1;
3756 }
3757
3763 public function loadStateBoard()
3764 {
3765 global $user, $hookmanager;
3766
3767 $this->nb = array();
3768
3769 $sql = "SELECT count(p.rowid) as nb";
3770 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
3771 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3772 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3773
3774 // If the internal user must only see his customers, force searching by him
3775 $search_sale = 0;
3776 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3777 $search_sale = $user->id;
3778 }
3779 // Search on sale representative
3780 if ($search_sale && $search_sale != '-1') {
3781 if ($search_sale == -2) {
3782 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3783 } elseif ($search_sale > 0) {
3784 $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).")";
3785 }
3786 }
3787
3788 // Add where from hooks
3789 $parameters = array();
3790 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3791 $sql .= $hookmanager->resPrint;
3792 $resql = $this->db->query($sql);
3793 if ($resql) {
3794 // This assignment in condition is not a bug. It allows walking the results.
3795 while ($obj = $this->db->fetch_object($resql)) {
3796 $this->nb["proposals"] = $obj->nb;
3797 }
3798 $this->db->free($resql);
3799 return 1;
3800 } else {
3801 dol_print_error($this->db);
3802 $this->error = $this->db->error();
3803 return -1;
3804 }
3805 }
3806
3807
3815 public function getNextNumRef($soc)
3816 {
3817 global $conf, $langs;
3818 $langs->load("propal");
3819
3820 $classname = getDolGlobalString('PROPALE_ADDON');
3821
3822 if (!empty($classname)) {
3823 $mybool = false;
3824
3825 $file = $classname.".php";
3826
3827 // Include file with class
3828 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3829 foreach ($dirmodels as $reldir) {
3830 $dir = dol_buildpath($reldir."core/modules/propale/");
3831
3832 // Load file with numbering class (if found)
3833 $mybool = ((bool) @include_once $dir.$file) || $mybool;
3834 }
3835
3836 if (!$mybool) {
3837 dol_print_error(null, "Failed to include file ".$file);
3838 return '';
3839 }
3840
3841 $obj = new $classname();
3842 '@phan-var-force ModeleNumRefPropales $obj';
3845 $numref = $obj->getNextValue($soc, $this);
3846
3847 if ($numref != "") {
3848 return $numref;
3849 } else {
3850 $this->error = $obj->error;
3851 //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3852 return "";
3853 }
3854 } else {
3855 $langs->load("errors");
3856 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Proposal"));
3857 return "";
3858 }
3859 }
3860
3867 public function getTooltipContentArray($params)
3868 {
3869 global $conf, $langs, $user;
3870
3871 $langs->load('propal');
3872 $datas = [];
3873 $nofetch = !empty($params['nofetch']);
3874
3875 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3876 return ['optimize' => $langs->trans("Proposal")];
3877 }
3878 if ($user->hasRight('propal', 'lire')) {
3879 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').'<u>'.$langs->trans("Proposal").'</u>';
3880 if (isset($this->status)) {
3881 $datas['status'] = ' '.$this->getLibStatut(5);
3882 }
3883 if (!empty($this->ref)) {
3884 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3885 }
3886 if (!$nofetch) {
3887 $langs->load('companies');
3888 if (empty($this->thirdparty)) {
3889 $this->fetch_thirdparty();
3890 }
3891 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
3892 }
3893 if (!empty($this->ref_customer)) {
3894 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
3895 }
3896 if (!$nofetch) {
3897 $langs->load('project');
3898 if (is_null($this->project) || (is_object($this->project) && empty($this->project->id))) {
3899 $res = $this->fetchProject();
3900 if ($res > 0 && $this->project instanceof Project) {
3901 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
3902 }
3903 }
3904 }
3905 if (!empty($this->total_ht)) {
3906 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3907 }
3908 if (!empty($this->total_tva)) {
3909 $datas['vat'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3910 }
3911 if (!empty($this->total_ttc)) {
3912 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3913 }
3914 if (!empty($this->date)) {
3915 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
3916 }
3917 if (!empty($this->date_signature)) {
3918 $datas['datesignature'] = '<br><b>'.$langs->trans('DateSigning').':</b> '.dol_print_date($this->date_signature, 'day');
3919 }
3920 if (!empty($this->delivery_date)) {
3921 $datas['deliverydate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
3922 }
3923 }
3924
3925 return $datas;
3926 }
3927
3939 public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = -1)
3940 {
3941 global $langs, $conf, $user, $hookmanager;
3942
3943 if (!empty($conf->dol_no_mouse_hover)) {
3944 $notooltip = 1; // Force disable tooltips
3945 }
3946
3947 $result = '';
3948 $params = [
3949 'id' => $this->id,
3950 'objecttype' => $this->element,
3951 'option' => $option,
3952 'nofetch' => 1,
3953 ];
3954 $classfortooltip = 'classfortooltip';
3955 $dataparams = '';
3956 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3957 $classfortooltip = 'classforajaxtooltip';
3958 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3959 $label = '';
3960 } else {
3961 $label = implode($this->getTooltipContentArray($params));
3962 }
3963
3964 $baseurl = '';
3965 $query = [];
3966 if ($user->hasRight('propal', 'lire')) {
3967 parse_str($get_params, $query);
3968 $query = array_merge($query, ['id' => $this->id]);
3969 if ($option == '') {
3970 $baseurl = DOL_URL_ROOT . '/comm/propal/card.php';
3971 } elseif ($option == 'compta') { // deprecated
3972 $baseurl = DOL_URL_ROOT . '/comm/propal/card.php';
3973 } elseif ($option == 'expedition') {
3974 $baseurl = DOL_URL_ROOT . '/expedition/propal.php';
3975 } elseif ($option == 'document') {
3976 $baseurl = DOL_URL_ROOT . '/comm/propal/document.php';
3977 }
3978
3979 if ($option != 'nolink') {
3980 // Add param to save lastsearch_values or not
3981 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3982 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3983 $add_save_lastsearch_values = 1;
3984 }
3985 if ($add_save_lastsearch_values) {
3986 $query = array_merge($query, ['save_lastsearch_values' => 1]);
3987 }
3988 }
3989 }
3990 $url = dolBuildUrl($baseurl, $query);
3991
3992 $linkclose = '';
3993 if (empty($notooltip) && $user->hasRight('propal', 'lire')) {
3994 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3995 $label = $langs->trans("Proposal");
3996 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3997 }
3998 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3999 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
4000 }
4001
4002 $linkstart = '<a href="'.$url.'"';
4003 $linkstart .= $linkclose.'>';
4004 $linkend = '</a>';
4005
4006 $result .= $linkstart;
4007 if ($withpicto) {
4008 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
4009 }
4010 if ($withpicto != 2) {
4011 $result .= $this->ref;
4012 }
4013 $result .= $linkend;
4014
4015 if ($addlinktonotes >= 0) {
4016 $txttoshow = '';
4017
4018 if ($addlinktonotes == 0) {
4019 if (!empty($this->note_private) || !empty($this->note_public)) {
4020 $txttoshow = $langs->trans('ViewPrivateNote');
4021 }
4022 } elseif ($addlinktonotes == 1) {
4023 if (!empty($this->note_private)) {
4024 $txttoshow .= ($user->socid > 0 ? '' : dol_string_nohtmltag($this->note_private, 1));
4025 }
4026 } elseif ($addlinktonotes == 2) {
4027 if (!empty($this->note_public)) {
4028 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
4029 }
4030 } elseif ($addlinktonotes == 3) {
4031 if ($user->socid > 0) {
4032 if (!empty($this->note_public)) {
4033 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
4034 }
4035 } else {
4036 if (!empty($this->note_public)) {
4037 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
4038 }
4039 if (!empty($this->note_private)) {
4040 if (!empty($txttoshow)) {
4041 $txttoshow .= '<br><br>';
4042 }
4043 $txttoshow .= dol_string_nohtmltag($this->note_private, 1);
4044 }
4045 }
4046 }
4047
4048 if ($txttoshow) {
4049 $result .= ' <span class="note inline-block">';
4050 $result .= '<a href="'.dolBuildUrl(DOL_URL_ROOT.'/comm/propal/note.php', ['id' => $this->id]).'" class="classfortooltip" title="'.dol_escape_htmltag($txttoshow).'">';
4051 $result .= img_picto('', 'note');
4052 $result .= '</a>';
4053 $result .= '</span>';
4054 }
4055 }
4056
4057 global $action;
4058 $hookmanager->initHooks(array($this->element . 'dao'));
4059 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
4060 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4061 if ($reshook > 0) {
4062 $result = $hookmanager->resPrint;
4063 } else {
4064 $result .= $hookmanager->resPrint;
4065 }
4066 return $result;
4067 }
4068
4075 public function getLinesArray($sqlforgedfilters = '')
4076 {
4077 return $this->fetch_lines(0, 0, $sqlforgedfilters);
4078 }
4079
4091 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4092 {
4093 $outputlangs->loadLangs(array("propale", "products"));
4094
4095 if (!dol_strlen($modele)) {
4096 $modele = getDolGlobalString('PROPALE_ADDON_PDF', 'cyan');
4097
4098 if ($this->model_pdf) {
4099 $modele = $this->model_pdf;
4100 }
4101 }
4102
4103 $modelpath = "core/modules/propale/doc/";
4104
4105 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4106 }
4107
4116 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4117 {
4118 $tables = array(
4119 'propal'
4120 );
4121
4122 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4123 }
4124
4133 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
4134 {
4135 $tables = array(
4136 'propaldet'
4137 );
4138
4139 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
4140 }
4141
4149 public function getKanbanView($option = '', $arraydata = null)
4150 {
4151 global $langs;
4152
4153 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
4154
4155 $return = '<div class="box-flex-item box-flex-grow-zero">';
4156 $return .= '<div class="info-box info-box-sm">';
4157 $return .= '<div class="info-box-icon bg-infobox-action">';
4158 $return .= img_picto('', $this->picto);
4159 $return .= '</div>';
4160 $return .= '<div class="info-box-content">';
4161 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
4162 if ($selected >= 0) {
4163 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
4164 }
4165 if (!empty($arraydata['projectlink'])) {
4166 $return .= '<span class="info-box-ref"> | '.$arraydata['projectlink'].'</span>';
4167 }
4168 $return .= '<br>';
4169 if (is_object($this->thirdparty)) {
4170 $return .= '<div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
4171 }
4172 $return .= '<span class="info-box-label amount" title="'.$langs->trans("AmountHT").'">'.price($this->total_ht).'</span>';
4173 if (!empty($arraydata['authorlink'])) {
4174 $return .= ' &nbsp; <span class="info-box-label">'.$arraydata['authorlink'].'</span>';
4175 }
4176 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
4177 $return .= '</div>';
4178 $return .= '</div>';
4179 $return .= '</div>';
4180 return $return;
4181 }
4182
4193 public function setCategories($categories)
4194 {
4195 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4196 return parent::setCategoriesCommon($categories, Categorie::TYPE_PROPOSAL);
4197 }
4198}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
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:169
global $mysoc
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
$date_start
Variables from include:
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)
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 '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
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.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
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...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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, $notused, $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
print $langs trans('Date')." left Ref 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 Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492