dolibarr 25.0.0-alpha
propal.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
4 * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2005 Marc Barilley <marc@ocebo.com>
6 * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
7 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
8 * Copyright (C) 2008 Raphael Bertrand <raphael.bertrand@resultic.fr>
9 * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
10 * Copyright (C) 2010-2022 Philippe Grand <philippe.grand@atoo-net.com>
11 * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
12 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
13 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
14 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
15 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
16 * Copyright (C) 2018-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 * Copyright (C) 2026 Nick Fragoulis
25 *
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 3 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <https://www.gnu.org/licenses/>.
38 */
39
46require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
47require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propaleligne.class.php';
48require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
49require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
50require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
51require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
52require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
53
57class Propal extends CommonObject
58{
59 use CommonIncoterm;
60 use CommonSubtotal;
61
65 public $code = "";
66
70 public $element = 'propal';
71
75 public $table_element = 'propal';
76
80 public $table_element_line = 'propaldet';
81
85 public $fk_element = 'fk_propal';
86
90 public $picto = 'propal';
91
96 public $TRIGGER_PREFIX = 'PROPAL';
97
102 public $restrictiononfksoc = 1;
103
107 protected $table_ref_field = 'ref';
108
113 public $socid;
114
119 public $contactid;
120
127 public $ref_client;
128
133 public $ref_customer;
134
141 public $statut;
142
148 public $status;
149
155 public $datec;
156
162 public $datev;
163
167 public $date_validation;
168
172 public $date_signature;
173
177 public $user_signature;
178
182 public $date;
183
189 public $datep;
190
194 public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
195
196
200 public $fin_validite;
201
205 public $user_author_id;
206
211 public $author;
212
218 public $price;
219
225 public $tva;
231 public $total;
232
236 public $cond_reglement_code;
237
241 public $cond_reglement;
242
246 public $cond_reglement_doc;
247
251 public $cond_reglement_label;
252
256 public $mode_reglement_code;
257
261 public $mode_reglement;
262
268 public $deposit_percent;
269
274 public $fk_address;
275
280 public $address_type;
281
286 public $address;
287
291 public $availability_id;
292
298 public $fk_availability;
299
303 public $availability_code;
304
308 public $availability;
309
313 public $duree_validite;
314
318 public $demand_reason_id;
319
323 public $demand_reason_code;
324
328 public $demand_reason;
329
333 public $warehouse_id;
334
338 public $lines = array();
339
343 public $line;
344
345 public $labelStatus = array();
346 public $labelStatusShort = array();
347
348
373 // BEGIN MODULEBUILDER PROPERTIES
377 public $fields = array(
378 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
379 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 15, 'index' => 1),
380 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 20),
381 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 22, 'uieditable' => 1, 'alwayseditable' => 1),
382 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 40),
383 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'position' => 23),
384 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 24),
385 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
386 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 55),
387 'datep' => array('type' => 'date', 'label' => 'Date', 'enabled' => 1, 'visible' => -1, 'position' => 60),
388 'fin_validite' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => -1, 'position' => 65),
389 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 70),
390 'date_cloture' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 75),
391 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 80),
392 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 85),
393 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 90),
394 'fk_user_cloture' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 95),
395 'price' => array('type' => 'double', 'label' => 'Price', 'enabled' => 1, 'visible' => -1, 'position' => 105),
396 'total_ht' => array('type' => 'double(24,8)', 'label' => 'TotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 125, 'isameasure' => 1),
397 'total_tva' => array('type' => 'double(24,8)', 'label' => 'VAT', 'enabled' => 1, 'visible' => -1, 'position' => 130, 'isameasure' => 1),
398 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LocalTax1', 'enabled' => 1, 'visible' => -1, 'position' => 135, 'isameasure' => 1),
399 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LocalTax2', 'enabled' => 1, 'visible' => -1, 'position' => 140, 'isameasure' => 1),
400 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'TotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 145, 'isameasure' => 1),
401 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 150),
402 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 155),
403 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 160),
404 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 161),
405 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 165),
406 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 170, 'uieditable' => 1, 'alwayseditable' => 1),
407 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 175, 'uieditable' => 1, 'alwayseditable' => 1),
408 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'PDFTemplate', 'enabled' => 1, 'visible' => 0, 'position' => 180),
409 'date_livraison' => array('type' => 'date', 'label' => 'DateDeliveryPlanned', 'enabled' => 1, 'visible' => -1, 'position' => 185),
410 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMethod', 'enabled' => 1, 'visible' => -1, 'position' => 190),
411 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'DefaultWarehouse', 'enabled' => 'isModEnabled("stock")', 'visible' => -1, 'position' => 191),
412 'fk_availability' => array('type' => 'integer', 'label' => 'Availability', 'enabled' => 1, 'visible' => -1, 'position' => 195),
413 'fk_delivery_address' => array('type' => 'integer', 'label' => 'DeliveryAddress', 'enabled' => 1, 'visible' => 0, 'position' => 200), // deprecated
414 'fk_input_reason' => array('type' => 'integer', 'label' => 'InputReason', 'enabled' => 1, 'visible' => -1, 'position' => 205),
415 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 215),
416 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 220),
417 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 225),
418 'fk_multicurrency' => array('type' => 'integer', 'label' => 'MulticurrencyID', 'enabled' => 1, 'visible' => -1, 'position' => 230),
419 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 235),
420 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240, 'isameasure' => 1),
421 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 245, 'isameasure' => 1),
422 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 250, 'isameasure' => 1),
423 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 255, 'isameasure' => 1),
424 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 260),
425 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 500),
426 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 900),
427 );
428 // END MODULEBUILDER PROPERTIES
429
433 const STATUS_CANCELED = -1;
437 const STATUS_DRAFT = 0;
445 const STATUS_SIGNED = 2;
453 const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ?
454
455
463 public function __construct($db, $socid = 0, $propalid = 0)
464 {
465 $this->db = $db;
466
467 $this->ismultientitymanaged = 1;
468 $this->socid = $socid;
469 $this->id = $propalid;
470
471 $this->duree_validite = getDolGlobalInt('PROPALE_VALIDITY_DURATION');
472
473 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
474 }
475
484 protected function persistFieldValue(User $user, $field)
485 {
486 if ($field == 'ref_client') {
487 return $this->set_ref_client($user, (string) $this->ref_client);
488 }
489
490 return parent::persistFieldValue($user, $field);
491 }
492
493 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
505 public function add_product($idproduct, $qty, $remise_percent = 0)
506 {
507 // phpcs:enable
508 global $mysoc;
509
510 if (!$qty) {
511 $qty = 1;
512 }
513
514 dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
515 if ($idproduct > 0) {
516 $prod = new Product($this->db);
517 $prod->fetch($idproduct);
518
519 $productdesc = $prod->description;
520
521 $tva_tx = (string) get_default_tva($mysoc, $this->thirdparty, $prod->id);
522 $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
523 if (empty($tva_tx)) {
524 $tva_npr = 0;
525 }
526 $vat_src_code = ''; // May be defined into tva_tx
527
528 $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr);
529 $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr);
530
531 // multiprices
532 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $this->thirdparty->price_level) {
533 $price = $prod->multiprices[$this->thirdparty->price_level];
534 } else {
535 $price = $prod->price;
536 }
537
538 $line = new PropaleLigne($this->db);
539
540 $line->fk_product = $idproduct;
541 $line->desc = $productdesc;
542 $line->qty = $qty;
543 $line->subprice = $price;
544 $line->remise_percent = $remise_percent;
545 $line->vat_src_code = $vat_src_code;
546 $line->tva_tx = $tva_tx;
547 $line->fk_unit = $prod->fk_unit;
548 if ($tva_npr) {
549 $line->info_bits = 1;
550 }
551
552 $this->lines[] = $line;
553 }
554
555 return 1;
556 }
557
558 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
565 public function insert_discount($idremise)
566 {
567 // phpcs:enable
568 global $langs;
569
570 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
571 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
572
573 $this->db->begin();
574
575 $remise = new DiscountAbsolute($this->db);
576 $result = $remise->fetch($idremise);
577
578 if ($result > 0) {
579 if ($remise->fk_facture) { // Protection against multiple submission
580 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
581 $this->db->rollback();
582 return -5;
583 }
584
585 $line = new PropaleLigne($this->db);
586
587 $line->context = $this->context;
588
589 $line->fk_propal = $this->id;
590 $line->fk_remise_except = $remise->id;
591 $line->desc = $remise->description; // Line Description
592 $line->vat_src_code = $remise->vat_src_code;
593 $line->tva_tx = $remise->tva_tx;
594 $line->localtax1_tx = $remise->localtax1_tx;
595 $line->localtax1_type = $remise->localtax1_type;
596 $line->localtax2_tx = $remise->localtax1_tx;
597 $line->localtax2_type = $remise->localtax1_type;
598 $line->subprice = -(float) $remise->amount_ht;
599 $line->fk_product = 0; // Product Id predefined
600 $line->qty = 1;
601 $line->remise_percent = 0;
602 $line->rang = -1;
603 $line->info_bits = 2;
604
605 $line->total_ht = -(float) $remise->amount_ht;
606 $line->total_tva = -(float) $remise->amount_tva;
607 $line->total_ttc = -(float) $remise->amount_ttc;
608 $line->total_localtax1 = -(float) $remise->total_localtax1;
609 $line->total_localtax2 = -(float) $remise->total_localtax2;
610
611 $result = $line->insert();
612 if ($result > 0) {
613 $result = $this->update_price(1);
614 if ($result > 0) {
615 $this->db->commit();
616 return 1;
617 } else {
618 $this->db->rollback();
619 return -1;
620 }
621 } else {
622 $this->setErrorsFromObject($line);
623 $this->db->rollback();
624 return -2;
625 }
626 } else {
627 $this->db->rollback();
628 return -2;
629 }
630 }
631
669 public function addline(
670 $desc,
671 $pu_ht,
672 $qty,
673 $txtva,
674 $txlocaltax1 = 0.0,
675 $txlocaltax2 = 0.0,
676 $fk_product = 0,
677 $remise_percent = 0.0,
678 $price_base_type = 'HT',
679 $pu_ttc = 0.0,
680 $info_bits = 0,
681 $type = 0,
682 $rang = -1,
683 $special_code = 0,
684 $fk_parent_line = 0,
685 $fk_fournprice = 0,
686 $pa_ht = 0,
687 $label = '',
688 $date_start = '',
689 $date_end = '',
690 $array_options = array(),
691 $fk_unit = null,
692 $origin = '',
693 $origin_id = 0,
694 $pu_ht_devise = 0,
695 $fk_remise_except = 0,
696 $noupdateafterinsertline = 0
697 ) {
698 global $mysoc, $langs;
699
700 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);
701
702 if ($this->status == self::STATUS_DRAFT) {
703 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
704
705 // Clean parameters
706 if (empty($remise_percent)) {
707 $remise_percent = 0;
708 }
709 if (empty($qty)) {
710 $qty = 0;
711 }
712 if (empty($info_bits)) {
713 $info_bits = 0;
714 }
715 if (empty($rang)) {
716 $rang = 0;
717 }
718 if (empty($fk_parent_line) || $fk_parent_line < 0) {
719 $fk_parent_line = 0;
720 }
721
722 $remise_percent = price2num($remise_percent);
723 $qty = (float) price2num($qty, 'MS');
724 $pu_ht = price2num($pu_ht);
725 $pu_ht_devise = price2num($pu_ht_devise);
726 $pu_ttc = price2num($pu_ttc);
727 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
728 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
729 }
730 $txlocaltax1 = price2num($txlocaltax1);
731 $txlocaltax2 = price2num($txlocaltax2);
732 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht is empty string
733 if ($price_base_type == 'HT') {
734 $pu = $pu_ht;
735 } else {
736 $pu = $pu_ttc;
737 }
738
739 // Check parameters
740 if ($type < 0) {
741 return -1;
742 }
743
744 if ($date_start && $date_end && $date_start > $date_end) {
745 $langs->load("errors");
746 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
747 return -1;
748 }
749
750 $this->db->begin();
751
752 $product_type = $type;
753 if (!empty($fk_product) && $fk_product > 0) {
754 $product = new Product($this->db);
755 $result = $product->fetch($fk_product);
756 $product_type = $product->type;
757
758 if ($product->isStockManaged() && $product->stock_reel < $qty && getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL')) {
759 $langs->load("errors");
760 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref);
761 $this->db->rollback();
762 return -3;
763 }
764 }
765
766 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
767 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
768 // and this is done at the line level, which has its own VAT rate
769
770 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
771
772 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
773 $tmpproduct = new Product($this->db);
774 $result = $tmpproduct->fetch($fk_product);
775 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
776 if ($newqty != $qty) {
777 $qty = $newqty;
778 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
779 }
780 }
781
782 // Clean vat code
783 $reg = array();
784 $vat_src_code = '';
785 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
786 $vat_src_code = $reg[1];
787 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
788 }
789
790 $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, $this->multicurrency_code);
791
792 $total_ht = $tabprice[0];
793 $total_tva = $tabprice[1];
794 $total_ttc = $tabprice[2];
795 $total_localtax1 = $tabprice[9];
796 $total_localtax2 = $tabprice[10];
797 $pu_ht = $tabprice[3];
798 $pu_tva = $tabprice[4];
799 $pu_ttc = $tabprice[5];
800
801 // MultiCurrency
802 $multicurrency_total_ht = $tabprice[16];
803 $multicurrency_total_tva = $tabprice[17];
804 $multicurrency_total_ttc = $tabprice[18];
805 $pu_ht_devise = $tabprice[19];
806
807 // Rang to use
808 $ranktouse = $rang;
809 if (empty($ranktouse) || $ranktouse == -1) {
810 $rangmax = $this->line_max($fk_parent_line);
811 $ranktouse = $rangmax + 1;
812 }
813
814 // Insert line
815 $this->line = new PropaleLigne($this->db);
816
817 $this->line->context = $this->context;
818
819 $this->line->fk_propal = $this->id;
820 $this->line->label = $label;
821 $this->line->desc = $desc;
822 $this->line->qty = (float) $qty;
823
824 $this->line->vat_src_code = $vat_src_code;
825 $this->line->tva_tx = $txtva;
826 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
827 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
828 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
829 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
830 $this->line->fk_product = $fk_product;
831 $this->line->product_type = $type;
832 $this->line->fk_remise_except = $fk_remise_except;
833 $this->line->remise_percent = $remise_percent;
834 $this->line->subprice = (float) $pu_ht;
835 // Persist the original entry mode of the line so updateline() can preserve it later.
836 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
837 $this->line->rang = $ranktouse;
838 $this->line->info_bits = $info_bits;
839 $this->line->total_ht = (float) $total_ht;
840 $this->line->total_tva = (float) $total_tva;
841 $this->line->total_localtax1 = (float) $total_localtax1;
842 $this->line->total_localtax2 = (float) $total_localtax2;
843 $this->line->total_ttc = (float) $total_ttc;
844 $this->line->special_code = $special_code;
845 $this->line->fk_parent_line = $fk_parent_line;
846 $this->line->fk_unit = $fk_unit;
847
848 $this->line->date_start = $date_start;
849 $this->line->date_end = $date_end;
850
851 $this->line->fk_fournprice = $fk_fournprice;
852 $this->line->pa_ht = $pa_ht;
853
854 $this->line->origin_id = $origin_id;
855 $this->line->origin = $origin;
856
857 // Multicurrency
858 $this->line->fk_multicurrency = $this->fk_multicurrency;
859 $this->line->multicurrency_code = $this->multicurrency_code;
860 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
861 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
862 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
863 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
864
865 // Set the line as optional
866 if (empty($qty) && empty($special_code)) {
867 $this->line->special_code = 3;
868 }
869
870 if (is_array($array_options) && count($array_options) > 0) {
871 $this->line->array_options = $array_options;
872 }
873
874 $result = $this->line->insert();
875 if ($result > 0) {
876 if (!isset($this->context['createfromclone'])) {
877 if (!empty($fk_parent_line)) {
878 // Always reorder if child line
879 $this->line_order(true, 'DESC');
880 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
881 // Update all rank of all other lines starting from the same $ranktouse
882 foreach ($this->lines as $tmpline) {
883 if ($tmpline->rang >= $ranktouse) {
884 if (!empty($tmpline->id)) {
885 $this->updateRangOfLine($tmpline->id, $tmpline->rang + 1);
886 }
887 }
888 }
889 }
890
891 $this->lines[] = $this->line;
892 } else {
893 // Loop on all lines of parent object
894 foreach ($this->lines as $tmpline) {
895 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
896 $this->line->extraparams = $tmpline->extraparams;
897 $this->line->setExtraParameters();
898 }
899 }
900 }
901
902 // Update denormalized fields at the order level
903 if (empty($noupdateafterinsertline)) {
904 $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.
905 }
906
907 if ($result > 0) {
908 $this->db->commit();
909 return $this->line->id;
910 } else {
911 $this->error = $this->db->error();
912 $this->db->rollback();
913 return -1;
914 }
915 } else {
916 $this->setErrorsFromObject($this->line);
917 $this->db->rollback();
918 return -2;
919 }
920 } else {
921 dol_syslog(get_class($this)."::addline status of proposal must be Draft to allow use of ->addline()", LOG_ERR);
922 return -3;
923 }
924 }
925
926
956 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)
957 {
958 global $mysoc, $langs;
959
960 if (!$this->isLineOfObject($rowid)) {
961 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
962 return -1;
963 }
964
965 dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent,
966 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");
967 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
968
969 // Clean parameters
970 $remise_percent = price2num($remise_percent);
971 $qty = (float) price2num($qty);
972 $pu = price2num($pu);
973 $pu_ht_devise = price2num($pu_ht_devise);
974 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
975 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
976 }
977 $txlocaltax1 = price2num($txlocaltax1);
978 $txlocaltax2 = price2num($txlocaltax2);
979 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
980 if (empty($qty) && empty($special_code)) {
981 $special_code = 3; // Set option tag
982 }
983 if (!empty($qty) && $special_code == 3) {
984 $special_code = 0; // Remove option tag
985 }
986 if (empty($type)) {
987 $type = 0;
988 }
989
990 if ($date_start && $date_end && $date_start > $date_end) {
991 $langs->load("errors");
992 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
993 return -1;
994 }
995
996 if ($this->status == self::STATUS_DRAFT) {
997 $this->db->begin();
998
999 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1000 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1001 // and this is done at the line level, which has its own VAT rate
1002
1003 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1004
1005 // Clean vat code
1006 $reg = array();
1007 $vat_src_code = '';
1008 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1009 $vat_src_code = $reg[1];
1010 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1011 }
1012
1013 // TODO Implement if (getDolGlobalInt('MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES')) ?
1014
1015 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
1016 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
1017 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
1018 $tmpline = new PropaleLigne($this->db);
1019 if ($tmpline->fetch($rowid) > 0) {
1020 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
1021 if ($newqty != $qty) {
1022 $qty = $newqty;
1023 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
1024 }
1025 }
1026 }
1027
1028 $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, $this->multicurrency_code);
1029 $total_ht = $tabprice[0];
1030 $total_tva = $tabprice[1];
1031 $total_ttc = $tabprice[2];
1032 $total_localtax1 = $tabprice[9];
1033 $total_localtax2 = $tabprice[10];
1034 $pu_ht = $tabprice[3];
1035 $pu_tva = $tabprice[4];
1036 $pu_ttc = $tabprice[5];
1037
1038 // MultiCurrency
1039 $multicurrency_total_ht = $tabprice[16];
1040 $multicurrency_total_tva = $tabprice[17];
1041 $multicurrency_total_ttc = $tabprice[18];
1042 $pu_ht_devise = $tabprice[19];
1043
1044 // Fetch current line from the database and then clone the object and set it in $oldline property
1045 $line = new PropaleLigne($this->db);
1046 $line->fetch($rowid);
1047
1048 $staticline = clone $line;
1049
1050 $line->oldline = $staticline;
1051 $this->line = $line;
1052 $this->line->context = $this->context;
1053 $this->line->rang = $rang;
1054
1055 // Reorder if fk_parent_line change
1056 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
1057 $rangmax = $this->line_max($fk_parent_line);
1058 $this->line->rang = $rangmax + 1;
1059 }
1060
1061
1062 $this->line->id = $rowid;
1063 $this->line->label = $label;
1064 $this->line->desc = $desc;
1065 $this->line->qty = $qty;
1066 $this->line->product_type = $type;
1067 $this->line->vat_src_code = $vat_src_code;
1068 $this->line->tva_tx = $txtva;
1069 $this->line->localtax1_tx = $txlocaltax1;
1070 $this->line->localtax2_tx = $txlocaltax2;
1071 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
1072 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
1073 $this->line->remise_percent = $remise_percent;
1074 $this->line->subprice = (float) $pu_ht;
1075 // Persist the original entry mode of the line so a no-op edit can preserve it later.
1076 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
1077 $this->line->info_bits = $info_bits;
1078
1079 $this->line->total_ht = (float) $total_ht;
1080 $this->line->total_tva = (float) $total_tva;
1081 $this->line->total_localtax1 = (float) $total_localtax1;
1082 $this->line->total_localtax2 = (float) $total_localtax2;
1083 $this->line->total_ttc = (float) $total_ttc;
1084 $this->line->special_code = $special_code;
1085 $this->line->fk_parent_line = $fk_parent_line;
1086 $this->line->skip_update_total = $skip_update_total;
1087 $this->line->fk_unit = $fk_unit;
1088
1089 $this->line->fk_fournprice = $fk_fournprice;
1090 $this->line->pa_ht = $pa_ht;
1091
1092 $this->line->date_start = $date_start;
1093 $this->line->date_end = $date_end;
1094
1095 if (is_array($array_options) && count($array_options) > 0) {
1096 // We replace values in this->line->array_options only for entries defined into $array_options
1097 foreach ($array_options as $key => $value) {
1098 $this->line->array_options[$key] = $array_options[$key];
1099 }
1100 }
1101
1102 // Multicurrency
1103 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
1104 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
1105 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
1106 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
1107
1108 $result = $this->line->update($notrigger);
1109 if ($result > 0) {
1110 // Reorder if child line
1111 if (!empty($fk_parent_line)) {
1112 $this->line_order(true, 'DESC');
1113 }
1114
1115 $this->update_price(1, 'auto');
1116
1117 // $this is Propal
1118 // $this->fk_propal = $this->id;
1119 // $this->rowid = $rowid;
1120
1121 $this->db->commit();
1122 return $result;
1123 } else {
1124 $this->setErrorsFromObject($this->line);
1125 $this->db->rollback();
1126 return -1;
1127 }
1128 } else {
1129 dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action");
1130 return -2;
1131 }
1132 }
1133
1134
1142 public function deleteLine($lineid, $id = 0)
1143 {
1144 global $user;
1145
1146 if ($this->status == self::STATUS_DRAFT) {
1147 $this->db->begin();
1148
1149 $line = new PropaleLigne($this->db);
1150
1151 $line->context = $this->context;
1152
1153 // Load data
1154 $line->fetch($lineid);
1155
1156 if ($id <= 0) {
1157 $id = $this->id;
1158 }
1159 if ($id > 0 && (int) $line->fk_propal !== (int) $id) {
1160 $this->db->rollback();
1161 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1162 return -1;
1163 }
1164
1165 // Memorize previous line for triggers
1166 $staticline = clone $line;
1167 $line->oldline = $staticline;
1168
1169 if ($line->delete($user) > 0) {
1170 $this->update_price(1);
1171
1172 $this->db->commit();
1173 return 1;
1174 } else {
1175 $this->setErrorsFromObject($line);
1176 $this->db->rollback();
1177 return -1;
1178 }
1179 } else {
1180 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1181 return -2;
1182 }
1183 }
1184
1185
1194 public function create($user, $notrigger = 0)
1195 {
1196 global $mysoc;
1197
1198 $error = 0;
1199
1200 $now = dol_now();
1201
1202 // Clean parameters
1203 if (empty($this->date)) {
1204 $this->date = $this->datep;
1205 }
1206 $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1207 if (empty($this->availability_id)) {
1208 $this->availability_id = 0;
1209 }
1210 if (empty($this->demand_reason_id)) {
1211 $this->demand_reason_id = 0;
1212 }
1213
1214 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1215 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1216 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
1217 } else {
1218 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1219 }
1220 if (empty($this->fk_multicurrency)) {
1221 $this->multicurrency_code = getDolCurrency();
1222 $this->fk_multicurrency = 0;
1223 $this->multicurrency_tx = 1;
1224 }
1225 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
1226 $this->entity = setEntity($this);
1227
1228 // Set tmp vars
1229 $delivery_date = $this->delivery_date;
1230
1231 dol_syslog(get_class($this)."::create");
1232
1233 // Check parameters
1234 $result = $this->fetch_thirdparty();
1235 if ($result < 0) {
1236 $this->error = "Failed to fetch company";
1237 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1238 return -3;
1239 }
1240
1241 // Check parameters
1242 if (!empty($this->ref)) { // We check that ref is not already used
1243 $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
1244 if ($result > 0) {
1245 $this->error = 'ErrorRefAlreadyExists';
1246 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1247 $this->db->rollback();
1248 return -1;
1249 }
1250 }
1251
1252 if (empty($this->date)) {
1253 $this->error = "Date of proposal is required";
1254 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1255 return -4;
1256 }
1257
1258
1259 $this->db->begin();
1260
1261 // Insert into database
1262 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1263 $sql .= "fk_soc";
1264 $sql .= ", price";
1265 $sql .= ", total_tva";
1266 $sql .= ", total_ttc";
1267 $sql .= ", datep";
1268 $sql .= ", datec";
1269 $sql .= ", ref";
1270 $sql .= ", fk_user_author";
1271 $sql .= ", note_private";
1272 $sql .= ", note_public";
1273 $sql .= ", model_pdf";
1274 $sql .= ", fin_validite";
1275 $sql .= ", fk_cond_reglement";
1276 $sql .= ", deposit_percent";
1277 $sql .= ", fk_mode_reglement";
1278 $sql .= ", fk_account";
1279 $sql .= ", ref_client";
1280 $sql .= ", ref_ext";
1281 $sql .= ", date_livraison";
1282 $sql .= ", fk_shipping_method";
1283 $sql .= ", fk_warehouse";
1284 $sql .= ", fk_availability";
1285 $sql .= ", fk_input_reason";
1286 $sql .= ", fk_projet";
1287 $sql .= ", fk_incoterms";
1288 $sql .= ", location_incoterms";
1289 $sql .= ", entity";
1290 $sql .= ", fk_multicurrency";
1291 $sql .= ", multicurrency_code";
1292 $sql .= ", multicurrency_tx";
1293 $sql .= ") ";
1294 $sql .= " VALUES (";
1295 $sql .= ((int) $this->socid);
1296 $sql .= ", 0";
1297 $sql .= ", 0";
1298 $sql .= ", 0";
1299 $sql .= ", '".$this->db->idate($this->date)."'";
1300 $sql .= ", '".$this->db->idate($now)."'";
1301 $sql .= ", '(PROV)'";
1302 $sql .= ", ".($user->id > 0 ? ((int) $user->id) : "NULL");
1303 $sql .= ", '".$this->db->escape((string) $this->note_private)."'";
1304 $sql .= ", '".$this->db->escape((string) $this->note_public)."'";
1305 $sql .= ", '".$this->db->escape((string) $this->model_pdf)."'";
1306 $sql .= ", ".($this->fin_validite != '' ? "'".$this->db->idate($this->fin_validite)."'" : "NULL");
1307 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'NULL');
1308 $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : 'NULL');
1309 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'NULL');
1310 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1311 $sql .= ", '".$this->db->escape((string) $this->ref_client)."'";
1312 $sql .= ", '".$this->db->escape((string) $this->ref_ext)."'";
1313 $sql .= ", ".(!isDolTms($delivery_date) ? "NULL" : "'".$this->db->idate($delivery_date)."'");
1314 $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
1315 $sql .= ", ".($this->warehouse_id > 0 ? ((int) $this->warehouse_id) : 'NULL');
1316 $sql .= ", ".((int) $this->availability_id);
1317 $sql .= ", ".((int) $this->demand_reason_id);
1318 $sql .= ", ".($this->fk_project ? ((int) $this->fk_project) : "null");
1319 $sql .= ", ".(int) $this->fk_incoterms;
1320 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1321 $sql .= ", ".(int) $this->entity;
1322 $sql .= ", ".(int) $this->fk_multicurrency;
1323 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1324 $sql .= ", ".(float) $this->multicurrency_tx;
1325 $sql .= ")";
1326
1327 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1328 $resql = $this->db->query($sql);
1329 if ($resql) {
1330 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
1331
1332 if ($this->id) {
1333 $this->ref = '(PROV'.$this->id.')';
1334 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
1335
1336 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1337 $resql = $this->db->query($sql);
1338 if (!$resql) {
1339 $error++;
1340 }
1341
1342 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1343 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1344 }
1345
1346 // Add object linked
1347 if (!$error && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1348 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1349 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, ...))
1350 foreach ($tmp_origin_id as $origin_id) {
1351 $ret = $this->add_object_linked($origin, $origin_id);
1352 if (!$ret) {
1353 $this->error = $this->db->lasterror();
1354 $error++;
1355 }
1356 }
1357 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1358 $origin_id = $tmp_origin_id;
1359 $ret = $this->add_object_linked($origin, $origin_id);
1360 if (!$ret) {
1361 $this->error = $this->db->lasterror();
1362 $error++;
1363 }
1364 }
1365 }
1366 }
1367
1368 /*
1369 * Insert products detail in database
1370 */
1371 if (!$error) {
1372 $fk_parent_line = 0;
1373 $num = count($this->lines);
1374
1375 // 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
1376 for ($i = 0; $i < $num; $i++) {
1377 if (!is_object($this->lines[$i])) { // If this->lines is not array of objects, coming from REST API
1378 // Build a real line object: the loop below calls methods on it
1379 // (getPriceBaseType), which a cast to stdClass cannot answer.
1380 $lineobj = new PropaleLigne($this->db);
1381 foreach ($this->lines[$i] as $key => $val) {
1382 $lineobj->$key = $val;
1383 }
1384 $this->lines[$i] = $lineobj;
1385 }
1386 }
1387
1388 for ($i = 0; $i < $num; $i++) {
1389 $line = $this->lines[$i];
1390
1391 // Reset fk_parent_line for line that are not child lines or special product
1392 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1393 $fk_parent_line = 0;
1394 }
1395 // Complete vat rate with code
1396 $vatrate = $line->tva_tx;
1397 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', $vatrate)) {
1398 $vatrate .= ' ('.$line->vat_src_code.')';
1399 }
1400
1401 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
1402 $originid = $line->origin_id;
1403 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
1404 } else { // old but bugged version (we store id of line and type of parent object)
1405 $originid = $line->id;
1406 $origintype = $this->element;
1407 }
1408
1409 // Preserve the original entry mode of the line so the total is computed from the typed value (no rounding drift).
1410 $line_price_base_type = $line->getPriceBaseType();
1411 $result = $this->addline(
1412 $line->desc,
1413 (float) $line->subprice,
1414 $line->qty,
1415 $vatrate,
1416 $line->localtax1_tx,
1417 $line->localtax2_tx,
1418 $line->fk_product,
1419 $line->remise_percent,
1420 $line_price_base_type,
1421 (float) $line->subprice_ttc,
1422 $line->info_bits,
1423 $line->product_type,
1424 $line->rang,
1425 $line->special_code,
1426 $fk_parent_line,
1427 $line->fk_fournprice,
1428 $line->pa_ht,
1429 $line->label,
1430 $line->date_start,
1431 $line->date_end,
1432 $line->array_options,
1433 $line->fk_unit,
1434 (string) $origintype,
1435 $originid,
1436 0,
1437 0,
1438 1
1439 );
1440
1441 if ($result < 0) {
1442 $error++;
1443 $this->error = $this->db->error;
1444 dol_print_error($this->db);
1445 break;
1446 }
1447
1448 // Set the id on created row
1449 $line->id = $result;
1450
1451 // Keep the extra parameters of the source line (for example the options of subtotal lines): addline() can't
1452 // do it when the object is cloned, because the origin it receives is the one of the source line, not the source line
1453 if ($result > 0 && !empty($line->extraparams)) {
1454 $newline = new PropaleLigne($this->db);
1455 $newline->id = $result;
1456 $newline->extraparams = $line->extraparams;
1457 $newline->setExtraParameters();
1458 }
1459
1460 // Defined the new fk_parent_line
1461 if ($result > 0 && $line->product_type == 9) {
1462 $fk_parent_line = $result;
1463 }
1464 }
1465 }
1466
1467 if (!$error) {
1468 // Update denormalized data
1469 $resql = $this->update_price(1, 'auto', 0, $mysoc);
1470 if ($resql) {
1471 // Actions on extra fields
1472 $result = $this->insertExtraFields();
1473 if ($result < 0) {
1474 $error++;
1475 }
1476
1477 if (!$error && !$notrigger) {
1478 // Call trigger
1479 $result = $this->call_trigger('PROPAL_CREATE', $user);
1480 if ($result < 0) {
1481 $error++;
1482 }
1483 // End call triggers
1484 }
1485 } else {
1486 $this->error = $this->db->lasterror();
1487 $error++;
1488 }
1489 }
1490 } else {
1491 $this->error = $this->db->lasterror();
1492 $error++;
1493 }
1494
1495 if (!$error) {
1496 $this->db->commit();
1497 dol_syslog(get_class($this)."::create done id=".$this->id);
1498 return $this->id;
1499 } else {
1500 $this->db->rollback();
1501 return -2;
1502 }
1503 } else {
1504 $this->error = $this->db->lasterror();
1505 $this->db->rollback();
1506 return -1;
1507 }
1508 }
1509
1520 public function createFromClone(User $user, $socid = 0, $forceentity = null, $update_prices = false, $update_desc = false)
1521 {
1522 global $conf, $hookmanager, $mysoc;
1523
1524 dol_include_once('/projet/class/project.class.php');
1525
1526 $error = 0;
1527 $now = dol_now();
1528
1529 dol_syslog(__METHOD__, LOG_DEBUG);
1530
1531 $object = new self($this->db);
1532
1533 $this->db->begin();
1534
1535 // Load source object
1536 $object->fetch($this->id);
1537
1538 $objsoc = new Societe($this->db);
1539
1540 // Change socid if needed
1541 if (!empty($socid) && $socid != $object->socid) {
1542 if ($objsoc->fetch($socid) > 0) {
1543 $object->socid = $objsoc->id;
1544 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1545 $object->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : null);
1546 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1547 $object->fk_delivery_address = 0;
1548
1549 /*if (isModEnabled('project'))
1550 {
1551 $project = new Project($db);
1552 if ($this->fk_project > 0 && $project->fetch($this->fk_project)) {
1553 if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project;
1554 else $clonedObj->fk_project = '';
1555 } else {
1556 $clonedObj->fk_project = '';
1557 }
1558 }*/
1559 $object->fk_project = 0; // A cloned proposal is set by default to no project.
1560 }
1561
1562 // reset ref_client
1563 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1564 $object->ref_client = '';
1565 $object->ref_customer = '';
1566 }
1567
1568 // TODO Change product price if multi-prices
1569 } else {
1570 $objsoc->fetch($object->socid);
1571 }
1572
1573 // update prices
1574 if ($update_prices === true || $update_desc === true) {
1575 if ($objsoc->id > 0 && !empty($object->lines)) {
1576 if ($update_prices === true && getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1577 // If price per customer
1578 require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
1579 }
1580
1581 foreach ($object->lines as $line) {
1582 $line->id = 0;
1583
1584 if ($line->fk_product > 0) {
1585 $prod = new Product($this->db);
1586 $res = $prod->fetch($line->fk_product);
1587 if ($res > 0) {
1588 if ($update_prices === true) {
1589 $pu_ht = $prod->price;
1590 $tva_tx = (string) get_default_tva($mysoc, $objsoc, $prod->id);
1591 $remise_percent = $objsoc->remise_percent;
1592
1593 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $objsoc->price_level > 0) {
1594 $pu_ht = $prod->multiprices[$objsoc->price_level];
1595 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
1596 if (isset($prod->multiprices_tva_tx[$objsoc->price_level])) {
1597 $tva_tx = (string) $prod->multiprices_tva_tx[$objsoc->price_level];
1598 }
1599 }
1600 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1601 $prodcustprice = new ProductCustomerPrice($this->db);
1602 $filter = array('t.fk_product' => (string) $prod->id, 't.fk_soc' => (string) $objsoc->id);
1603 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
1604 if ($result) {
1605 // If there is some prices specific to the customer
1606 if (count($prodcustprice->lines) > 0) {
1607 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
1608 foreach ($prodcustprice->lines as $k => $custprice_line) {
1609 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
1610 $pu_ht = price($custprice_line->price);
1611 $tva_tx = ($custprice_line->default_vat_code ? $custprice_line->tva_tx . ' (' . $custprice_line->default_vat_code . ' )' : $custprice_line->tva_tx);
1612 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
1613 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
1614 }
1615 $remise_percent = $custprice_line->discount_percent;
1616 break;
1617 }
1618 }
1619 }
1620 }
1621 }
1622
1623 $line->subprice = $pu_ht;
1624 $line->tva_tx = $tva_tx;
1625 $line->remise_percent = $remise_percent;
1626
1627 // Also update the buy price (margin) with the same fallback logic used when a line is added or updated
1628 // (cost price, or PMP, or best supplier price, depending on MARGIN_TYPE). Keep line->pa_ht unchanged if nothing better is found.
1629 $buyPrice = $this->defineBuyPrice($pu_ht, $remise_percent, $prod->id);
1630 if ($buyPrice > 0) {
1631 $line->pa_ht = $buyPrice;
1632 }
1633 }
1634 if ($update_desc === true) {
1635 $line->desc = $prod->description;
1636 }
1637 }
1638 }
1639 }
1640 }
1641 }
1642
1643 $object->id = 0;
1644 $object->ref = '';
1645 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1646 $object->statut = self::STATUS_DRAFT;
1647 $object->status = self::STATUS_DRAFT;
1648
1649 // Clear fields
1650 $object->user_creation_id = $user->id;
1651 $object->user_validation_id = 0;
1652 $object->date = $now;
1653 $object->datep = $now; // deprecated
1654 $object->fin_validite = $object->date + (int) ($object->duree_validite * 24 * 3600);
1655 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1656 $object->ref_client = '';
1657 $object->ref_customer = '';
1658 }
1659 if (getDolGlobalInt('MAIN_DONT_KEEP_NOTE_ON_CLONING') == 1) {
1660 $object->note_private = '';
1661 $object->note_public = '';
1662 }
1663 // Create clone
1664 $object->context['createfromclone'] = 'createfromclone';
1665 $object->context['createfromclone_fromid'] = $this->id;
1666 $object->context['createfromclone_fromref'] = $this->ref;
1667 $result = $object->create($user);
1668 if ($result < 0) {
1670 $error++;
1671 }
1672
1673 if (!$error && !getDolGlobalInt('MAIN_IGNORE_CONTACTS_ON_CLONING')) {
1674 // copy internal contacts
1675 if ($object->copy_linked_contact($this, 'internal') < 0) {
1676 $error++;
1677 }
1678 }
1679
1680 if (!$error) {
1681 // copy external contacts if same company
1682 if ($this->socid == $object->socid) {
1683 if ($object->copy_linked_contact($this, 'external') < 0) {
1684 $error++;
1685 }
1686 }
1687 }
1688
1689 if (!$error) {
1690 // Hook of thirdparty module
1691 if (is_object($hookmanager)) {
1692 $parameters = array('objFrom' => $this, 'clonedObj' => $object);
1693 $action = '';
1694 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1695 if ($reshook < 0) {
1696 $this->setErrorsFromObject($hookmanager);
1697 $error++;
1698 }
1699 }
1700 }
1701
1702 unset($object->context['createfromclone']);
1703 unset($object->context['createfromclone_fromid']);
1704 unset($object->context['createfromclone_fromref']);
1705
1706 // End
1707 if (!$error) {
1708 $this->db->commit();
1709 return $object->id;
1710 } else {
1711 $this->db->rollback();
1712 return -1;
1713 }
1714 }
1715
1725 public function fetch($rowid, $ref = '', $ref_ext = '', $forceentity = 0)
1726 {
1727 $sql = "SELECT p.rowid, p.ref, p.entity, p.fk_soc";
1728 $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht";
1729 $sql .= ", p.datec";
1730 $sql .= ", p.date_signature as dates";
1731 $sql .= ", p.date_valid as datev";
1732 $sql .= ", p.date_cloture";
1733 $sql .= ", p.datep as dp";
1734 $sql .= ", p.fin_validite as dfv";
1735 $sql .= ", p.date_livraison as delivery_date";
1736 $sql .= ", p.model_pdf, p.last_main_doc, p.ref_client, ref_ext, p.extraparams";
1737 $sql .= ", p.note_private, p.note_public";
1738 $sql .= ", p.fk_projet as fk_project, p.fk_statut";
1739 $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
1740 $sql .= ", p.fk_delivery_address";
1741 $sql .= ", p.fk_availability";
1742 $sql .= ", p.fk_input_reason";
1743 $sql .= ", p.fk_cond_reglement";
1744 $sql .= ", p.fk_mode_reglement";
1745 $sql .= ', p.fk_account';
1746 $sql .= ", p.fk_shipping_method";
1747 $sql .= ", p.fk_warehouse";
1748 $sql .= ", p.fk_incoterms, p.location_incoterms";
1749 $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1750 $sql .= ", p.tms as date_modification";
1751 $sql .= ", i.libelle as label_incoterms";
1752 $sql .= ", c.label as statut_label";
1753 $sql .= ", ca.code as availability_code, ca.label as availability";
1754 $sql .= ", dr.code as demand_reason_code, dr.label as demand_reason";
1755 $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc, p.deposit_percent";
1756 $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1757 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
1758 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id';
1759 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')';
1760 $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').')';
1761 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid';
1762 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid';
1763 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid';
1764
1765 if (!empty($ref)) {
1766 if (!empty($forceentity)) {
1767 $sql .= " WHERE p.entity = ".(int) $forceentity; // Check only the current entity because we may have the same reference in several entities
1768 } else {
1769 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
1770 }
1771 $sql .= " AND p.ref='".$this->db->escape($ref)."'";
1772 } else {
1773 // Don't use entity if you use rowid
1774 $sql .= " WHERE p.rowid = ".((int) $rowid);
1775 }
1776
1777 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1778 $resql = $this->db->query($sql);
1779 if ($resql) {
1780 if ($this->db->num_rows($resql)) {
1781 $obj = $this->db->fetch_object($resql);
1782
1783 $this->id = $obj->rowid;
1784 $this->entity = $obj->entity;
1785
1786 $this->ref = $obj->ref;
1787 $this->ref_client = $obj->ref_client;
1788 $this->ref_customer = $obj->ref_client;
1789 $this->ref_ext = $obj->ref_ext;
1790
1791 $this->total = $obj->total_ttc; // TODO deprecated
1792 $this->total_ttc = $obj->total_ttc;
1793 $this->total_ht = $obj->total_ht;
1794 $this->total_tva = $obj->total_tva;
1795 $this->total_localtax1 = $obj->localtax1;
1796 $this->total_localtax2 = $obj->localtax2;
1797
1798 $this->socid = $obj->fk_soc;
1799 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
1800
1801 $this->fk_project = $obj->fk_project;
1802 $this->project = null; // Clear if another value was already set by fetchProject
1803
1804 $this->model_pdf = $obj->model_pdf;
1805 $this->last_main_doc = $obj->last_main_doc;
1806 $this->note = $obj->note_private; // TODO deprecated
1807 $this->note_private = $obj->note_private;
1808 $this->note_public = $obj->note_public;
1809
1810 $this->status = (int) $obj->fk_statut;
1811 $this->statut = $this->status; // deprecated
1812
1813 $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
1814 $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
1815 $this->date_creation = $this->db->jdate($obj->datec); //Creation date
1816 $this->date_validation = $this->db->jdate($obj->datev); //Validation date
1817 $this->date_modification = $this->db->jdate($obj->date_modification); // tms
1818 $this->date_signature = $this->db->jdate($obj->dates); // Signature date
1819 $this->date_cloture = $this->db->jdate($obj->date_cloture); // Closing date
1820 $this->date = $this->db->jdate($obj->dp); // Proposal date
1821 $this->datep = $this->db->jdate($obj->dp); // deprecated
1822 $this->fin_validite = $this->db->jdate($obj->dfv);
1823 $this->delivery_date = $this->db->jdate($obj->delivery_date);
1824 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1825 $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
1826 $this->availability_id = $obj->fk_availability;
1827 $this->availability_code = $obj->availability_code;
1828 $this->availability = $obj->availability;
1829 $this->demand_reason_id = $obj->fk_input_reason;
1830 $this->demand_reason_code = $obj->demand_reason_code;
1831 $this->demand_reason = $obj->demand_reason;
1832 $this->fk_address = $obj->fk_delivery_address;
1833
1834 $this->mode_reglement_id = $obj->fk_mode_reglement;
1835 $this->mode_reglement_code = $obj->mode_reglement_code;
1836 $this->mode_reglement = $obj->mode_reglement;
1837 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
1838 $this->cond_reglement_id = $obj->fk_cond_reglement;
1839 $this->cond_reglement_code = $obj->cond_reglement_code;
1840 $this->cond_reglement = $obj->cond_reglement;
1841 $this->cond_reglement_label = $obj->cond_reglement;
1842 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1843 $this->deposit_percent = $obj->deposit_percent;
1844
1845 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
1846
1847 $this->user_author_id = $obj->fk_user_author;
1848 $this->user_validation_id = $obj->fk_user_valid;
1849 $this->user_closing_id = $obj->fk_user_cloture;
1850
1851 //Incoterms
1852 $this->fk_incoterms = $obj->fk_incoterms;
1853 $this->location_incoterms = $obj->location_incoterms;
1854 $this->label_incoterms = $obj->label_incoterms;
1855
1856 // Multicurrency
1857 $this->fk_multicurrency = $obj->fk_multicurrency;
1858 $this->multicurrency_code = $obj->multicurrency_code;
1859 $this->multicurrency_tx = $obj->multicurrency_tx;
1860 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1861 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1862 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1863
1864 // Retrieve all extrafield
1865 // fetch optionals attributes and labels
1866 $this->fetch_optionals();
1867
1868 $this->db->free($resql);
1869
1870 $this->lines = array();
1871
1872 // Lines
1873 $result = $this->fetch_lines();
1874 if ($result < 0) {
1875 return -3;
1876 }
1877
1878 return 1;
1879 }
1880
1881 $this->error = "Record Not Found";
1882 return 0;
1883 } else {
1884 $this->error = $this->db->lasterror();
1885 return -1;
1886 }
1887 }
1888
1896 public function update(User $user, $notrigger = 0)
1897 {
1898 $error = 0;
1899
1900 // Clean parameters
1901 if (isset($this->ref)) {
1902 $this->ref = trim($this->ref);
1903 }
1904 if (isset($this->ref_client)) {
1905 $this->ref_client = trim($this->ref_client);
1906 }
1907 if (isset($this->note) || isset($this->note_private)) {
1908 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
1909 }
1910 if (isset($this->note_public)) {
1911 $this->note_public = trim($this->note_public);
1912 }
1913 if (isset($this->model_pdf)) {
1914 $this->model_pdf = trim($this->model_pdf);
1915 }
1916 if (isset($this->import_key)) {
1917 $this->import_key = trim($this->import_key);
1918 }
1919 if (!empty($this->duree_validite) && is_numeric($this->duree_validite)) {
1920 $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600);
1921 }
1922
1923 // Check parameters
1924 // Put here code to add control on parameters values
1925
1926 // Update request
1927 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
1928 $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET";
1929 $sql .= " ref = ".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1930 $sql .= " ref_client = ".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
1931 $sql .= " ref_ext = ".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1932 $sql .= " fk_soc = ".(!empty($this->socid) ? (int) $this->socid : "null").",";
1933 $sql .= " datep = ".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
1934 if (!empty($this->fin_validite)) {
1935 $sql .= " fin_validite = ".(strval($this->fin_validite) != '' ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1936 }
1937 $sql .= " date_valid = ".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
1938 $sql .= " total_tva = ".(isset($this->total_tva) ? (float) $this->total_tva : "null").",";
1939 $sql .= " localtax1 = ".(isset($this->total_localtax1) ? (float) $this->total_localtax1 : "null").",";
1940 $sql .= " localtax2 = ".(isset($this->total_localtax2) ? (float) $this->total_localtax2 : "null").",";
1941 $sql .= " total_ht = ".(isset($this->total_ht) ? (float) $this->total_ht : "null").",";
1942 $sql .= " total_ttc = ".(isset($this->total_ttc) ? (float) $this->total_ttc : "null").",";
1943 $sql .= " fk_statut = ".(isset($this->status) ? (int) $this->status : "null").",";
1944 $sql .= " fk_user_author = ".(!empty($this->user_author_id) ? (int) $this->user_author_id : "null").",";
1945 $sql .= " fk_user_valid = ".(!empty($this->user_validation_id) ? (int) $this->user_validation_id : "null").",";
1946
1947 $sql .= " fk_projet = ".(!empty($this->fk_project) ? (int) $this->fk_project : "null").",";
1948 $sql .= " fk_cond_reglement = ".(!empty($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
1949 $sql .= " deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
1950 $sql .= " fk_mode_reglement = ".(!empty($this->mode_reglement_id) ? (int) $this->mode_reglement_id : "null").",";
1951 $sql .= " fk_input_reason = ".(!empty($this->demand_reason_id) ? (int) $this->demand_reason_id : "null").",";
1952 $sql .= " fk_shipping_method = ".(isset($this->shipping_method_id) ? (int) $this->shipping_method_id : "null").",";
1953 $sql .= " fk_availability = ".(!empty($this->availability_id) ? (int) $this->availability_id : "null").",";
1954 $sql .= " note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1955 $sql .= " note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1956 $sql .= " model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
1957 $sql .= " import_key = ".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
1958 $sql .= " WHERE rowid = ".((int) $this->id);
1959
1960 $this->db->begin();
1961
1962 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1963 $resql = $this->db->query($sql);
1964 if (!$resql) {
1965 $error++;
1966 $this->errors[] = "Error ".$this->db->lasterror();
1967 }
1968
1969 if (!$error) {
1970 $result = $this->insertExtraFields();
1971 if ($result < 0) {
1972 $error++;
1973 }
1974 }
1975
1976 if (!$error && !$notrigger) {
1977 // Call trigger
1978 $result = $this->call_trigger('PROPAL_MODIFY', $user);
1979 if ($result < 0) {
1980 $error++;
1981 }
1982 // End call triggers
1983 }
1984
1985 // Commit or rollback
1986 if ($error) {
1987 foreach ($this->errors as $errmsg) {
1988 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1989 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1990 }
1991 $this->db->rollback();
1992 return -1 * $error;
1993 } else {
1994 $this->db->commit();
1995 return 1;
1996 }
1997 }
1998
1999
2000 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2009 public function fetch_lines($only_product = 0, $loadalsotranslation = 0, $sqlforgedfilters = '')
2010 {
2011 // phpcs:enable
2012 $this->lines = array();
2013
2014 $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,';
2015 $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,';
2016 $sql .= ' d.fk_unit,';
2017 $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,';
2018 $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units,';
2019 $sql .= ' p.customcode, p.fk_country as country_id, c.code as country_code,';
2020 $sql .= ' d.date_start, d.date_end, d.extraparams,';
2021 $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc';
2022 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as d';
2023 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)';
2024 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON c.rowid = p.fk_country';
2025 $sql .= ' WHERE d.fk_propal = '.((int) $this->id);
2026 if ($only_product) {
2027 $sql .= ' AND p.fk_product_type = 0';
2028 }
2029 if ($sqlforgedfilters) {
2030 $sql .= $sqlforgedfilters;
2031 }
2032 $sql .= ' ORDER BY d.rang, d.rowid';
2033
2034 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
2035 $result = $this->db->query($sql);
2036 if ($result) {
2037 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
2038
2039 $num = $this->db->num_rows($result);
2040
2041 $i = 0;
2042 while ($i < $num) {
2043 $objp = $this->db->fetch_object($result);
2044
2045 $line = new PropaleLigne($this->db);
2046
2047 $line->rowid = $objp->rowid; //Deprecated
2048 $line->id = $objp->rowid;
2049 $line->fk_propal = $objp->fk_propal;
2050 $line->fk_parent_line = $objp->fk_parent_line;
2051 $line->label = $objp->custom_label;
2052 $line->desc = $objp->description; // Line description
2053 $line->description = $objp->description; // Line description
2054 $line->qty = $objp->qty;
2055 $line->vat_src_code = $objp->vat_src_code;
2056 $line->tva_tx = $objp->tva_tx;
2057 $line->localtax1_tx = $objp->localtax1_tx;
2058 $line->localtax2_tx = $objp->localtax2_tx;
2059 $line->localtax1_type = $objp->localtax1_type;
2060 $line->localtax2_type = $objp->localtax2_type;
2061 $line->subprice = $objp->subprice;
2062 $line->subprice_ttc = $objp->subprice_ttc;
2063 $line->fk_remise_except = $objp->fk_remise_except;
2064 $line->remise_percent = $objp->remise_percent;
2065
2066 $line->info_bits = $objp->info_bits;
2067 $line->total_ht = $objp->total_ht;
2068 $line->total_tva = $objp->total_tva;
2069 $line->total_localtax1 = $objp->total_localtax1;
2070 $line->total_localtax2 = $objp->total_localtax2;
2071 $line->total_ttc = $objp->total_ttc;
2072 $line->fk_fournprice = $objp->fk_fournprice;
2073 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2074 $line->pa_ht = $marginInfos[0];
2075 $line->marge_tx = $marginInfos[1];
2076 $line->marque_tx = $marginInfos[2];
2077 $line->special_code = $objp->special_code;
2078 $line->rang = $objp->rang;
2079
2080 $line->fk_product = $objp->fk_product;
2081
2082 $line->ref = $objp->product_ref; // deprecated
2083 $line->libelle = $objp->product_label; // deprecated
2084
2085 $line->product_ref = $objp->product_ref;
2086 $line->product_label = $objp->product_label;
2087 $line->product_desc = $objp->product_desc; // Description produit
2088 $line->product_tobatch = $objp->product_tobatch;
2089 $line->product_barcode = $objp->product_barcode;
2090 $line->product_custom_code = $objp->customcode;
2091 $line->product_custom_country_id = $objp->country_id;
2092 $line->product_custom_country_code = $objp->country_code;
2093 $line->product_type = $objp->product_type;
2094 $line->fk_product_type = $objp->fk_product_type; // deprecated
2095
2096 $line->fk_unit = $objp->fk_unit;
2097 $line->weight = $objp->weight;
2098 $line->weight_units = $objp->weight_units;
2099 $line->volume = $objp->volume;
2100 $line->volume_units = $objp->volume_units;
2101
2102 $line->date_start = $this->db->jdate($objp->date_start);
2103 $line->date_end = $this->db->jdate($objp->date_end);
2104
2105 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2106
2107 // Multicurrency
2108 $line->fk_multicurrency = $objp->fk_multicurrency;
2109 $line->multicurrency_code = $objp->multicurrency_code;
2110 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2111 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2112 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2113 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2114
2115 $line->fetch_optionals();
2116
2117 // multilangs
2118 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2119 $tmpproduct = new Product($this->db);
2120 $tmpproduct->fetch($objp->fk_product);
2121 $tmpproduct->getMultiLangs();
2122
2123 $line->multilangs = $tmpproduct->multilangs;
2124 }
2125
2126 $this->lines[$i] = $line;
2127
2128 $i++;
2129 }
2130
2131 $this->db->free($result);
2132
2133 return $num;
2134 } else {
2135 $this->error = $this->db->lasterror();
2136 return -3;
2137 }
2138 }
2139
2147 public function valid($user, $notrigger = 0)
2148 {
2149 global $conf;
2150
2151 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2152
2153 $error = 0;
2154
2155 // Protection
2156 if ($this->status == self::STATUS_VALIDATED) {
2157 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
2158 return 0;
2159 }
2160
2161 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('propal', 'creer'))
2162 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('propal', 'propal_advance', 'validate')))) {
2163 $this->error = 'ErrorPermissionDenied';
2164 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
2165 return -1;
2166 }
2167
2168 if (!getDolGlobalBool('PROPALE_NOCHECK_ONSALE_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines()) {
2169 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
2170 return -1;
2171 }
2172
2173 $now = dol_now();
2174
2175 $this->db->begin();
2176
2177 // Numbering module definition
2178 $soc = new Societe($this->db);
2179 $soc->fetch($this->socid);
2180
2181 // Define new ref
2182 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
2183 $num = $this->getNextNumRef($soc);
2184 } else {
2185 $num = (string) $this->ref;
2186 }
2187 $this->newref = dol_sanitizeFileName($num);
2188
2189 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2190 $sql .= " SET ref = '".$this->db->escape($num)."',";
2191 $sql .= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".((int) $user->id);
2192 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".self::STATUS_DRAFT;
2193
2194 dol_syslog(get_class($this)."::valid", LOG_DEBUG);
2195 $resql = $this->db->query($sql);
2196 if (!$resql) {
2197 dol_print_error($this->db);
2198 $error++;
2199 }
2200
2201 // Trigger calls
2202 if (!$error && !$notrigger) {
2203 // Call trigger
2204 $result = $this->call_trigger('PROPAL_VALIDATE', $user);
2205 if ($result < 0) {
2206 $error++;
2207 }
2208 // End call triggers
2209 }
2210
2211 if (!$error) {
2212 $this->oldref = $this->ref;
2213
2214 // Rename directory if dir was a temporary ref
2215 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
2216 // Now we rename also files into index
2217 $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)."'";
2218 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
2219 $resql = $this->db->query($sql);
2220 if (!$resql) {
2221 $error++;
2222 $this->error = $this->db->lasterror();
2223 }
2224 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'propale/".$this->db->escape($this->newref)."'";
2225 $sql .= " WHERE filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
2226 $resql = $this->db->query($sql);
2227 if (!$resql) {
2228 $error++;
2229 $this->error = $this->db->lasterror();
2230 }
2231
2232 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
2233 $oldref = dol_sanitizeFileName($this->ref);
2234 $newref = dol_sanitizeFileName($num);
2235 $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref;
2236 $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref;
2237 if (!$error && file_exists($dirsource)) {
2238 dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
2239 if (@rename($dirsource, $dirdest)) {
2240 dol_syslog("Rename ok");
2241 // Rename docs starting with $oldref with $newref
2242 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
2243 foreach ($listoffiles as $fileentry) {
2244 $dirsource = $fileentry['name'];
2245 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
2246 $dirsource = $fileentry['path'].'/'.$dirsource;
2247 $dirdest = $fileentry['path'].'/'.$dirdest;
2248 @rename($dirsource, $dirdest);
2249 }
2250 }
2251 }
2252 }
2253
2254 $this->ref = $num;
2255 $this->statut = self::STATUS_VALIDATED; // deprecated
2257 $this->user_validation_id = $user->id;
2258 $this->datev = $now;
2259 $this->date_validation = $now;
2260
2261 $this->db->commit();
2262 return 1;
2263 } else {
2264 $this->db->rollback();
2265 return -1;
2266 }
2267 }
2268
2269
2270 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2279 public function set_date($user, $date, $notrigger = 0)
2280 {
2281 // phpcs:enable
2282 if (empty($date)) {
2283 $this->error = 'ErrorBadParameter';
2284 dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR);
2285 return -1;
2286 }
2287
2288 if ($user->hasRight('propal', 'creer')) {
2289 $error = 0;
2290
2291 $this->db->begin();
2292
2293 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2294 $sql .= " SET datep = '".$this->db->idate($date)."'";
2295 $sql .= " WHERE rowid = ".((int) $this->id);
2296
2297 dol_syslog(__METHOD__, LOG_DEBUG);
2298 $resql = $this->db->query($sql);
2299 if (!$resql) {
2300 $this->errors[] = $this->db->error();
2301 $error++;
2302 }
2303
2304 if (!$error) {
2305 $this->oldcopy = clone $this;
2306 $this->date = $date;
2307 $this->datep = $date; // deprecated
2308 }
2309
2310 if (!$notrigger && empty($error)) {
2311 // Call trigger
2312 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2313 if ($result < 0) {
2314 $error++;
2315 }
2316 // End call triggers
2317 }
2318
2319 if (!$error) {
2320 $this->db->commit();
2321 return 1;
2322 } else {
2323 foreach ($this->errors as $errmsg) {
2324 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2325 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2326 }
2327 $this->db->rollback();
2328 return -1 * $error;
2329 }
2330 }
2331
2332 return -1;
2333 }
2334
2335 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2344 public function set_echeance($user, $date_end_validity, $notrigger = 0)
2345 {
2346 // phpcs:enable
2347 if ($user->hasRight('propal', 'creer')) {
2348 $error = 0;
2349
2350 $this->db->begin();
2351
2352 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2353 $sql .= " SET fin_validite = ".($date_end_validity != '' ? "'".$this->db->idate($date_end_validity)."'" : 'null');
2354 $sql .= " WHERE rowid = ".((int) $this->id);
2355
2356 dol_syslog(__METHOD__, LOG_DEBUG);
2357
2358 $resql = $this->db->query($sql);
2359 if (!$resql) {
2360 $this->errors[] = $this->db->error();
2361 $error++;
2362 }
2363
2364
2365 if (!$error) {
2366 $this->oldcopy = clone $this;
2367 $this->fin_validite = $date_end_validity;
2368 }
2369
2370 if (!$notrigger && empty($error)) {
2371 // Call trigger
2372 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2373 if ($result < 0) {
2374 $error++;
2375 }
2376 // End call triggers
2377 }
2378
2379 if (!$error) {
2380 $this->db->commit();
2381 return 1;
2382 } else {
2383 foreach ($this->errors as $errmsg) {
2384 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2385 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2386 }
2387 $this->db->rollback();
2388 return -1 * $error;
2389 }
2390 }
2391
2392 return -1;
2393 }
2394
2395 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2405 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2406 {
2407 // phpcs:enable
2408 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2409 }
2410
2419 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2420 {
2421 if ($user->hasRight('propal', 'creer')) {
2422 $error = 0;
2423
2424 $this->db->begin();
2425
2426 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2427 $sql .= " SET date_livraison = ".(isDolTms($delivery_date) ? "'".$this->db->idate($delivery_date)."'" : 'null');
2428 $sql .= " WHERE rowid = ".((int) $this->id);
2429
2430 dol_syslog(__METHOD__, LOG_DEBUG);
2431 $resql = $this->db->query($sql);
2432 if (!$resql) {
2433 $this->errors[] = $this->db->error();
2434 $error++;
2435 }
2436
2437 if (!$error) {
2438 $this->oldcopy = clone $this;
2439 $this->delivery_date = $delivery_date;
2440 }
2441
2442 if (!$notrigger && empty($error)) {
2443 // Call trigger
2444 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2445 if ($result < 0) {
2446 $error++;
2447 }
2448 // End call triggers
2449 }
2450
2451 if (!$error) {
2452 $this->db->commit();
2453 return 1;
2454 } else {
2455 foreach ($this->errors as $errmsg) {
2456 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2457 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2458 }
2459 $this->db->rollback();
2460 return -1 * $error;
2461 }
2462 }
2463
2464 return -1;
2465 }
2466
2467 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2476 public function set_availability($user, $id, $notrigger = 0)
2477 {
2478 // phpcs:enable
2479 if ($this->status >= self::STATUS_DRAFT) {
2480 $error = 0;
2481
2482 $this->db->begin();
2483
2484 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2485 $sql .= " SET fk_availability = ".((int) ($id > 0 ? ((int) $id) : 0));
2486 $sql .= " WHERE rowid = ".((int) $this->id);
2487
2488 dol_syslog(__METHOD__.' availability('.$id.')', LOG_DEBUG);
2489 $resql = $this->db->query($sql);
2490 if (!$resql) {
2491 $this->errors[] = $this->db->error();
2492 $error++;
2493 }
2494
2495 if (!$error) {
2496 $this->oldcopy = clone $this;
2497 $this->fk_availability = $id;
2498 $this->availability_id = $id;
2499 }
2500
2501 if (!$notrigger && empty($error)) {
2502 // Call trigger
2503 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2504 if ($result < 0) {
2505 $error++;
2506 }
2507 // End call triggers
2508 }
2509
2510 if (!$error) {
2511 $this->db->commit();
2512 return 1;
2513 } else {
2514 foreach ($this->errors as $errmsg) {
2515 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2516 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2517 }
2518 $this->db->rollback();
2519 return -1 * $error;
2520 }
2521 } else {
2522 $error_str = 'Propal status do not meet requirement '.$this->status;
2523 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2524 $this->error = $error_str;
2525 $this->errors[] = $this->error;
2526 return -2;
2527 }
2528 }
2529
2530 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2539 public function set_demand_reason($user, $id, $notrigger = 0)
2540 {
2541 // phpcs:enable
2542 if ($user->hasRight('propal', 'creer') && $this->status >= self::STATUS_DRAFT) {
2543 $error = 0;
2544
2545 $this->db->begin();
2546
2547 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2548 $sql .= " SET fk_input_reason = ".((int) $id);
2549 $sql .= " WHERE rowid = ".((int) $this->id);
2550
2551 dol_syslog(__METHOD__, LOG_DEBUG);
2552 $resql = $this->db->query($sql);
2553 if (!$resql) {
2554 $this->errors[] = $this->db->error();
2555 $error++;
2556 }
2557
2558
2559 if (!$error) {
2560 $this->oldcopy = clone $this;
2561
2562 $this->demand_reason_id = $id;
2563 }
2564
2565
2566 if (!$notrigger && empty($error)) {
2567 // Call trigger
2568 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2569 if ($result < 0) {
2570 $error++;
2571 }
2572 // End call triggers
2573 }
2574
2575 if (!$error) {
2576 $this->db->commit();
2577 return 1;
2578 } else {
2579 foreach ($this->errors as $errmsg) {
2580 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2581 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2582 }
2583 $this->db->rollback();
2584 return -1 * $error;
2585 }
2586 } else {
2587 $error_str = 'Propal status do not meet requirement '.$this->status;
2588 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2589 $this->error = $error_str;
2590 $this->errors[] = $this->error;
2591 return -2;
2592 }
2593 }
2594
2595 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2604 public function set_ref_client($user, $ref_client, $notrigger = 0)
2605 {
2606 // phpcs:enable
2607 if ($user->hasRight('propal', 'creer')) {
2608 $error = 0;
2609
2610 $this->db->begin();
2611
2612 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2613 $sql .= " SET ref_client = ".(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
2614 $sql .= " WHERE rowid = ".((int) $this->id);
2615
2616 dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2617 $resql = $this->db->query($sql);
2618 if (!$resql) {
2619 $this->errors[] = $this->db->error();
2620 $error++;
2621 }
2622
2623 if (!$error) {
2624 $this->oldcopy = clone $this;
2625 $this->ref_customer = $ref_client;
2626 $this->ref_client = $ref_client;
2627 }
2628
2629 if (!$notrigger && empty($error)) {
2630 // Call trigger
2631 $result = $this->call_trigger('PROPAL_MODIFY', $user);
2632 if ($result < 0) {
2633 $error++;
2634 }
2635 // End call triggers
2636 }
2637
2638 if (!$error) {
2639 $this->db->commit();
2640 return 1;
2641 } else {
2642 foreach ($this->errors as $errmsg) {
2643 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2644 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2645 }
2646 $this->db->rollback();
2647 return -1 * $error;
2648 }
2649 }
2650
2651 return -1;
2652 }
2653
2654
2664 public function reopen($user, $status, $note = '', $notrigger = 0)
2665 {
2666 $error = 0;
2667
2668 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2669 $sql .= " SET fk_statut = ".((int) $status).",";
2670 if (!empty($note)) {
2671 $sql .= " note_private = '".$this->db->escape($note)."',";
2672 }
2673 $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
2674 $sql .= " WHERE rowid = ".((int) $this->id);
2675
2676 $this->db->begin();
2677
2678 dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
2679 $resql = $this->db->query($sql);
2680 if (!$resql) {
2681 $error++;
2682 $this->errors[] = "Error ".$this->db->lasterror();
2683 }
2684 if (!$error) {
2685 if (!$notrigger) {
2686 // Call trigger
2687 $result = $this->call_trigger('PROPAL_REOPEN', $user);
2688 if ($result < 0) {
2689 $error++;
2690 }
2691 // End call triggers
2692 }
2693 }
2694
2695 // Commit or rollback
2696 if ($error) {
2697 if (!empty($this->errors)) {
2698 foreach ($this->errors as $errmsg) {
2699 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
2700 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2701 }
2702 }
2703 $this->db->rollback();
2704 return -1 * $error;
2705 } else {
2706 $this->statut = $status;
2707 $this->status = $status;
2708
2709 $this->db->commit();
2710 return 1;
2711 }
2712 }
2713
2724 public function closeProposal($user, $status, $note_private = '', $notrigger = 0, $note_public = '')
2725 {
2726 global $langs,$conf;
2727
2728 $error = 0;
2729 $now = dol_now();
2730
2731 $this->db->begin();
2732
2733 $newprivatenote = dol_concatdesc($this->note_private, $note_private);
2734 $newpublicnote = dol_concatdesc($this->note_public, $note_public);
2735
2736 if (!getDolGlobalString('PROPALE_KEEP_OLD_SIGNATURE_INFO')) {
2737 $date_signature = $now;
2738 $fk_user_signature = $user->id;
2739 } else {
2740 $this->info($this->id);
2741 if (!isset($this->date_signature) || $this->date_signature == '') {
2742 $date_signature = $now;
2743 $fk_user_signature = $user->id;
2744 } else {
2745 $date_signature = $this->date_signature;
2746 $fk_user_signature = $this->user_signature->id;
2747 }
2748 }
2749
2750 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2751 $sql .= " SET fk_statut = ".((int) $status).", note_private = '".$this->db->escape($newprivatenote)."', note_public = '".$this->db->escape($newpublicnote)."'";
2752 if ($status == self::STATUS_SIGNED) {
2753 $sql .= ", date_signature='".$this->db->idate($now)."', fk_user_signature = ".((int) $fk_user_signature);
2754 }
2755 $sql .= " WHERE rowid = ".((int) $this->id);
2756
2757 $resql = $this->db->query($sql);
2758 if ($resql) {
2759 // Status self::STATUS_REFUSED by default
2760 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_CLOSED', $this->model_pdf);
2761 $triggerName = 'PROPAL_CLOSE_REFUSED'; // used later in call_trigger()
2762
2763 if ($status == self::STATUS_SIGNED) { // Status self::STATUS_SIGNED
2764 $triggerName = 'PROPAL_CLOSE_SIGNED'; // used later in call_trigger()
2765 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_TOBILL', $this->model_pdf);
2766
2767 // The connected company is classified as a client
2768 $soc = new Societe($this->db);
2769 $soc->fetch($this->socid);
2770 $result = $soc->setAsCustomer();
2771
2772 if ($result < 0) {
2773 $this->error = $this->db->lasterror();
2774 $this->db->rollback();
2775 return -2;
2776 }
2777 }
2778
2779 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE') && !getDolGlobalInt('PROPAL_DISABLE_AUTOUPDATE_ON_CLOSE')) {
2780 // Define output language
2781 $outputlangs = $langs;
2782 if (getDolGlobalInt('MAIN_MULTILANGS')) {
2783 $outputlangs = new Translate("", $conf);
2784 $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2785 $outputlangs->setDefaultLang($newlang);
2786 }
2787
2788 // PDF
2789 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
2790 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
2791 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
2792
2793 //$ret=$object->fetch($id); // Reload to get new records
2794 $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2795 }
2796
2797 $this->oldcopy = clone $this;
2798 $this->statut = $status; // deprecated
2799 $this->status = $status;
2800 $this->date_signature = $date_signature;
2801 $this->note_private = $newprivatenote;
2802
2803 if (!$notrigger && empty($error)) {
2804 // Call trigger
2805 $result = $this->call_trigger($triggerName, $user);
2806 if ($result < 0) {
2807 $error++;
2808 }
2809 // End call triggers
2810 }
2811
2812 if (!$error) {
2813 $this->db->commit();
2814 return 1;
2815 } else {
2816 foreach ($this->errors as $errmsg) {
2817 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2818 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2819 }
2820 if (!empty($this->oldcopy)) {
2821 $this->statut = $this->oldcopy->status; // deprecated
2822 $this->status = $this->oldcopy->status;
2823 $this->date_signature = $this->oldcopy->date_signature;
2824 $this->note_private = $this->oldcopy->note_private;
2825 }
2826
2827 $this->db->rollback();
2828 return -1;
2829 }
2830 } else {
2831 $this->error = $this->db->lasterror();
2832 $this->db->rollback();
2833 return -1;
2834 }
2835 }
2836
2845 public function classifyBilled(User $user, $notrigger = 0, $note = '')
2846 {
2847 global $conf, $langs;
2848
2849 $error = 0;
2850
2851 $now = dol_now();
2852 $num = 0;
2853
2854 $triggerName = 'PROPAL_CLASSIFY_BILLED';
2855
2856 $this->db->begin();
2857
2858 $newprivatenote = dol_concatdesc($this->note_private, $note);
2859
2860 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2861 $sql .= " SET fk_statut = ".self::STATUS_BILLED.", ";
2862 $sql .= " note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".((int) $user->id);
2863 $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_SIGNED);
2864
2865 dol_syslog(__METHOD__, LOG_DEBUG);
2866 $resql = $this->db->query($sql);
2867 if (!$resql) {
2868 $this->errors[] = $this->db->error();
2869 $error++;
2870 } else {
2871 $num = $this->db->affected_rows($resql);
2872 }
2873
2874 if (!$error) {
2875 $modelpdf = getDolGlobalString('PROPALE_ADDON_PDF_ODT_CLOSED', $this->model_pdf);
2876
2877 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2878 // Define output language
2879 $outputlangs = $langs;
2880 if (getDolGlobalInt('MAIN_MULTILANGS')) {
2881 $outputlangs = new Translate("", $conf);
2882 $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
2883 $outputlangs->setDefaultLang($newlang);
2884 }
2885
2886 // PDF
2887 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
2888 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
2889 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
2890
2891 //$ret=$object->fetch($id); // Reload to get new records
2892 $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2893 }
2894
2895 $this->oldcopy = clone $this;
2896 $this->statut = self::STATUS_BILLED;
2897 $this->status = self::STATUS_BILLED;
2898 $this->date_cloture = $now;
2899 $this->note_private = $newprivatenote;
2900 }
2901
2902 if (!$notrigger && empty($error)) {
2903 // Call trigger
2904 $result = $this->call_trigger($triggerName, $user);
2905 if ($result < 0) {
2906 $error++;
2907 }
2908 // End call triggers
2909 }
2910
2911 if (!$error) {
2912 $this->db->commit();
2913 return $num;
2914 } else {
2915 foreach ($this->errors as $errmsg) {
2916 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2917 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2918 }
2919 $this->db->rollback();
2920 return -1 * $error;
2921 }
2922 }
2923
2930 public function setCancel(User $user)
2931 {
2932 $error = 0;
2933
2934 $this->db->begin();
2935
2936 $sql = "UPDATE ". MAIN_DB_PREFIX . $this->table_element;
2937 $sql .= " SET fk_statut = " . self::STATUS_CANCELED . ",";
2938 $sql .= " fk_user_modif = " . ((int) $user->id);
2939 $sql .= " WHERE rowid = " . ((int) $this->id);
2940
2941 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
2942 if ($this->db->query($sql)) {
2943 // Call trigger
2944 $result = $this->call_trigger('PROPAL_CANCEL', $user);
2945 if ($result < 0) {
2946 $error++;
2947 }
2948 // End call triggers
2949
2950 if (!$error) {
2951 $this->statut = self::STATUS_CANCELED; // deprecated
2953 $this->db->commit();
2954 return 1;
2955 } else {
2956 foreach ($this->errors as $errmsg) {
2957 dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
2958 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2959 }
2960 $this->db->rollback();
2961 return -1;
2962 }
2963 } else {
2964 $this->error = $this->db->error();
2965 $this->db->rollback();
2966 return -1;
2967 }
2968 }
2969
2970 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2978 public function setDraft($user, $notrigger = 0)
2979 {
2980 // phpcs:enable
2981 $error = 0;
2982
2983 // Protection
2984 if ($this->status <= self::STATUS_DRAFT) {
2985 return 0;
2986 }
2987
2988 dol_syslog(get_class($this)."::setDraft", LOG_DEBUG);
2989
2990 $this->db->begin();
2991
2992 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2993 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2994 $sql .= ", online_sign_ip = NULL , online_sign_name = NULL";
2995 $sql .= " WHERE rowid = ".((int) $this->id);
2996
2997 $resql = $this->db->query($sql);
2998 if (!$resql) {
2999 $this->errors[] = $this->db->error();
3000 $error++;
3001 }
3002
3003 if (!$error) {
3004 $this->oldcopy = clone $this;
3005 }
3006
3007 if (!$notrigger && empty($error)) {
3008 // Call trigger
3009 $result = $this->call_trigger('PROPAL_MODIFY', $user);
3010 if ($result < 0) {
3011 $error++;
3012 }
3013 // End call triggers
3014 }
3015
3016 if (!$error) {
3017 $this->statut = self::STATUS_DRAFT; // deprecated
3018 $this->status = self::STATUS_DRAFT;
3019
3020 $this->db->commit();
3021 return 1;
3022 } else {
3023 foreach ($this->errors as $errmsg) {
3024 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3025 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3026 }
3027 $this->db->rollback();
3028 return -1 * $error;
3029 }
3030 }
3031
3032
3033 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3047 public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datep', $sortorder = 'DESC')
3048 {
3049 // phpcs:enable
3050 global $user;
3051
3052 $ga = array();
3053
3054 $sql = "SELECT s.rowid, s.nom as name, s.client,";
3055 $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
3056 $sql .= " p.datep as dp, p.fin_validite as datelimite";
3057 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX.$this->table_element." as p, ".MAIN_DB_PREFIX."c_propalst as c";
3058 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3059 $sql .= " AND p.fk_soc = s.rowid";
3060 $sql .= " AND p.fk_statut = c.id";
3061
3062 // If the internal user must only see his customers, force searching by him
3063 $search_sale = 0;
3064 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3065 $search_sale = $user->id;
3066 }
3067 // Search on sale representative
3068 if ($search_sale && $search_sale != '-1') {
3069 if ($search_sale == -2) {
3070 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3071 } elseif ($search_sale > 0) {
3072 $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).")";
3073 }
3074 }
3075 // Search on socid
3076 if ($socid) {
3077 $sql .= " AND p.fk_soc = ".((int) $socid);
3078 }
3079 if ($draft) {
3080 $sql .= " AND p.fk_statut = ".((int) self::STATUS_DRAFT);
3081 }
3082 if ($notcurrentuser > 0) {
3083 $sql .= " AND p.fk_user_author <> ".((int) $user->id);
3084 }
3085 $sql .= $this->db->order($sortfield, $sortorder);
3086 $sql .= $this->db->plimit($limit, $offset);
3087
3088 $result = $this->db->query($sql);
3089 if ($result) {
3090 $num = $this->db->num_rows($result);
3091 if ($num) {
3092 $i = 0;
3093 while ($i < $num) {
3094 $obj = $this->db->fetch_object($result);
3095
3096 if ($shortlist == 1) {
3097 $ga[$obj->propalid] = $obj->ref;
3098 } elseif ($shortlist == 2) {
3099 $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')';
3100 } else {
3101 $ga[$i]['id'] = $obj->propalid;
3102 $ga[$i]['ref'] = $obj->ref;
3103 $ga[$i]['name'] = $obj->name;
3104 }
3105
3106 $i++;
3107 }
3108 }
3109 return $ga;
3110 } else {
3111 dol_print_error($this->db);
3112 return -1;
3113 }
3114 }
3115
3121 public function getInvoiceArrayList()
3122 {
3123 return $this->InvoiceArrayList($this->id);
3124 }
3125
3126 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3133 public function InvoiceArrayList($id)
3134 {
3135 // phpcs:enable
3136 $ga = array();
3137 $linkedInvoices = array();
3138
3139 $this->fetchObjectLinked($id, $this->element);
3140 foreach ($this->linkedObjectsIds as $objecttype => $objectid) {
3141 // New system of common object return rowids and no linear id from 1 to n
3142 // We are therefore traversing a list of objects as a single object
3143 foreach ($objectid as $key => $object) {
3144 // Case of invoices directly linked
3145 if ($objecttype == 'facture') {
3146 $linkedInvoices[] = $object;
3147 } else {
3148 // Case of invoices linked by another object (e.g., order)
3149 $this->fetchObjectLinked($object, $objecttype);
3150 foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) {
3151 foreach ($subobjectid as $subkey => $subobject) {
3152 if ($subobjecttype == 'facture') {
3153 $linkedInvoices[] = $subobject;
3154 }
3155 }
3156 }
3157 }
3158 }
3159 }
3160
3161 if (count($linkedInvoices) > 0) {
3162 $sql = "SELECT rowid as facid, ref, total_ht as total, datef as df, fk_user_author, fk_statut, paye";
3163 $sql .= " FROM ".MAIN_DB_PREFIX."facture";
3164 $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $linkedInvoices)).")";
3165
3166 dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG);
3167 $resql = $this->db->query($sql);
3168
3169 if ($resql) {
3170 $tab_sqlobj = array();
3171 $nump = $this->db->num_rows($resql);
3172 for ($i = 0; $i < $nump; $i++) {
3173 $obj = $this->db->fetch_object($resql);
3174 $tab_sqlobj[] = $obj;
3175 }
3176 $this->db->free($resql);
3177
3178 $nump = count($tab_sqlobj);
3179
3180 if ($nump) {
3181 $i = 0;
3182 while ($i < $nump) {
3183 $obj = array_shift($tab_sqlobj);
3184
3185 $ga[$i] = $obj;
3186
3187 $i++;
3188 }
3189 }
3190 return $ga;
3191 } else {
3192 return -1;
3193 }
3194 } else {
3195 return $ga;
3196 }
3197 }
3198
3206 public function delete($user, $notrigger = 0)
3207 {
3208 global $conf;
3209 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3210
3211 $error = 0;
3212
3213 $this->db->begin();
3214
3215 if (!$notrigger) {
3216 // Call trigger
3217 $result = $this->call_trigger('PROPAL_DELETE', $user);
3218 if ($result < 0) {
3219 $error++;
3220 }
3221 // End call triggers
3222 }
3223
3224 // Remove linked categories.
3225 if (!$error) {
3226 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_propal";
3227 $sql .= " WHERE fk_propal = ".((int) $this->id);
3228
3229 $result = $this->db->query($sql);
3230 if (!$result) {
3231 $error++;
3232 $this->error = $this->db->lasterror();
3233 $this->errors[] = $this->error;
3234 }
3235 }
3236
3237 // Delete extrafields of lines and lines
3238 if (!$error && !empty($this->table_element_line)) {
3239 $tabletodelete = $this->table_element_line;
3240 $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).")";
3241 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
3242 if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
3243 $error++;
3244 $this->error = $this->db->lasterror();
3245 $this->errors[] = $this->error;
3246 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3247 }
3248 }
3249
3250 if (!$error) {
3251 // Delete linked object
3252 $res = $this->deleteObjectLinked();
3253 if ($res < 0) {
3254 $error++;
3255 }
3256 }
3257
3258 if (!$error) {
3259 // Delete linked contacts
3260 $res = $this->delete_linked_contact();
3261 if ($res < 0) {
3262 $error++;
3263 }
3264 }
3265
3266 // Removed extrafields of object
3267 if (!$error) {
3268 $result = $this->deleteExtraFields();
3269 if ($result < 0) {
3270 $error++;
3271 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3272 }
3273 }
3274
3275 // Delete main record
3276 if (!$error) {
3277 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
3278 $res = $this->db->query($sql);
3279 if (!$res) {
3280 $error++;
3281 $this->error = $this->db->lasterror();
3282 $this->errors[] = $this->error;
3283 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3284 }
3285 }
3286
3287 // Delete record into ECM index and physically
3288 if (!$error) {
3289 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
3290 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3291 if (!$res) {
3292 $error++;
3293 }
3294 }
3295
3296 if (!$error) {
3297 // We remove directory
3298 $ref = dol_sanitizeFileName($this->ref);
3299 if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref)) {
3300 $dir = $conf->propal->multidir_output[$this->entity]."/".$ref;
3301 $file = $dir."/".$ref.".pdf";
3302 if (file_exists($file)) {
3303 dol_delete_preview($this);
3304
3305 if (!dol_delete_file($file, 0, 0, 0, $this)) {
3306 $this->error = 'ErrorFailToDeleteFile';
3307 $this->errors[] = $this->error;
3308 $this->db->rollback();
3309 return 0;
3310 }
3311 }
3312 if (file_exists($dir)) {
3313 $res = @dol_delete_dir_recursive($dir); // delete files physically + into ecm tables
3314 if (!$res) {
3315 $this->error = 'ErrorFailToDeleteDir';
3316 $this->errors[] = $this->error;
3317 $this->db->rollback();
3318 return 0;
3319 }
3320 }
3321 }
3322 }
3323
3324 if (!$error) {
3325 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
3326 $this->db->commit();
3327 return 1;
3328 } else {
3329 $this->db->rollback();
3330 return -1;
3331 }
3332 }
3333
3342 public function availability($availability_id, $notrigger = 0)
3343 {
3344 global $user;
3345
3346 if ($this->status >= self::STATUS_DRAFT) {
3347 $error = 0;
3348
3349 $this->db->begin();
3350
3351 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
3352 $sql .= ' SET fk_availability = '.((int) $availability_id);
3353 $sql .= ' WHERE rowid='.((int) $this->id);
3354
3355 dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG);
3356 $resql = $this->db->query($sql);
3357 if (!$resql) {
3358 $this->errors[] = $this->db->error();
3359 $error++;
3360 }
3361
3362 if (!$error) {
3363 $this->oldcopy = clone $this;
3364 $this->availability_id = $availability_id;
3365 }
3366
3367 if (!$notrigger && empty($error)) {
3368 // Call trigger
3369 $result = $this->call_trigger('PROPAL_MODIFY', $user);
3370 if ($result < 0) {
3371 $error++;
3372 }
3373 // End call triggers
3374 }
3375
3376 if (!$error) {
3377 $this->db->commit();
3378 return 1;
3379 } else {
3380 foreach ($this->errors as $errmsg) {
3381 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3382 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3383 }
3384 $this->db->rollback();
3385 return -1 * $error;
3386 }
3387 } else {
3388 $error_str = 'Propal status do not meet requirement '.$this->status;
3389 dol_syslog(__METHOD__.$error_str, LOG_ERR);
3390 $this->error = $error_str;
3391 $this->errors[] = $this->error;
3392 return -2;
3393 }
3394 }
3395
3396 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3405 public function demand_reason($demand_reason_id, $notrigger = 0)
3406 {
3407 // phpcs:enable
3408 global $user;
3409
3410 if ($this->status >= self::STATUS_DRAFT) {
3411 $error = 0;
3412
3413 $this->db->begin();
3414
3415 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
3416 $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
3417 $sql .= ' WHERE rowid='.((int) $this->id);
3418
3419 dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG);
3420 $resql = $this->db->query($sql);
3421 if (!$resql) {
3422 $this->errors[] = $this->db->error();
3423 $error++;
3424 }
3425
3426 if (!$error) {
3427 $this->oldcopy = clone $this;
3428 $this->demand_reason_id = $demand_reason_id;
3429 }
3430
3431 if (!$notrigger && empty($error)) {
3432 // Call trigger
3433 $result = $this->call_trigger('PROPAL_MODIFY', $user);
3434 if ($result < 0) {
3435 $error++;
3436 }
3437 // End call triggers
3438 }
3439
3440 if (!$error) {
3441 $this->db->commit();
3442 return 1;
3443 } else {
3444 foreach ($this->errors as $errmsg) {
3445 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3446 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3447 }
3448 $this->db->rollback();
3449 return -1 * $error;
3450 }
3451 } else {
3452 $error_str = 'Propal status do not meet requirement '.$this->status;
3453 dol_syslog(__METHOD__.$error_str, LOG_ERR);
3454 $this->error = $error_str;
3455 $this->errors[] = $this->error;
3456 return -2;
3457 }
3458 }
3459
3460
3467 public function info($id)
3468 {
3469 $sql = "SELECT c.rowid, ";
3470 $sql .= " c.datec, c.date_valid as datev, c.date_signature, c.date_cloture,";
3471 $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_signature, c.fk_user_cloture";
3472 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
3473 $sql .= " WHERE c.rowid = ".((int) $id);
3474
3475 $result = $this->db->query($sql);
3476
3477 if ($result) {
3478 if ($this->db->num_rows($result)) {
3479 $obj = $this->db->fetch_object($result);
3480
3481 $this->id = $obj->rowid;
3482
3483 $this->date_creation = $this->db->jdate($obj->datec);
3484 $this->date_validation = $this->db->jdate($obj->datev);
3485 $this->date_signature = $this->db->jdate($obj->date_signature);
3486 $this->date_cloture = $this->db->jdate($obj->date_cloture);
3487
3488 $this->user_creation_id = $obj->fk_user_author;
3489 $this->user_validation_id = $obj->fk_user_valid;
3490
3491 if ($obj->fk_user_signature) {
3492 $user_signature = new User($this->db);
3493 $user_signature->fetch($obj->fk_user_signature);
3494 $this->user_signature = $user_signature;
3495 }
3496
3497 $this->user_closing_id = $obj->fk_user_cloture;
3498 }
3499 $this->db->free($result);
3500 } else {
3501 dol_print_error($this->db);
3502 }
3503 }
3504
3505
3512 public function getLibStatut($mode = 0)
3513 {
3514 return $this->LibStatut($this->status, $mode);
3515 }
3516
3517 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3525 public function LibStatut($status, $mode = 1)
3526 {
3527 // phpcs:enable
3528 global $hookmanager;
3529
3530 // Init/load array of translation of status
3531 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
3532 global $langs;
3533 $langs->load("propal");
3534 $this->labelStatus[-1] = $langs->transnoentitiesnoconv("PropalStatusCanceled");
3535 $this->labelStatus[0] = $langs->transnoentitiesnoconv("PropalStatusDraft");
3536 $this->labelStatus[1] = $langs->transnoentitiesnoconv("PropalStatusValidated");
3537 $this->labelStatus[2] = $langs->transnoentitiesnoconv("PropalStatusSigned");
3538 $this->labelStatus[3] = $langs->transnoentitiesnoconv("PropalStatusNotSigned");
3539 $this->labelStatus[4] = $langs->transnoentitiesnoconv("PropalStatusBilled");
3540 $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv("PropalStatusCanceledShort");
3541 $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("PropalStatusDraftShort");
3542 $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("PropalStatusValidatedShort");
3543 $this->labelStatusShort[2] = $langs->transnoentitiesnoconv("PropalStatusSignedShort");
3544 $this->labelStatusShort[3] = $langs->transnoentitiesnoconv("PropalStatusNotSignedShort");
3545 $this->labelStatusShort[4] = $langs->transnoentitiesnoconv("PropalStatusBilledShort");
3546 }
3547
3548 $statusType = '';
3549 if ($status == self::STATUS_CANCELED) {
3550 $statusType = 'status9';
3551 } elseif ($status == self::STATUS_DRAFT) {
3552 $statusType = 'status0';
3553 } elseif ($status == self::STATUS_VALIDATED) {
3554 $statusType = 'status1';
3555 } elseif ($status == self::STATUS_SIGNED) {
3556 $statusType = 'status4';
3557 } elseif ($status == self::STATUS_NOTSIGNED) {
3558 $statusType = 'status9';
3559 } elseif ($status == self::STATUS_BILLED) {
3560 $statusType = 'status6';
3561 }
3562
3563 $parameters = array('status' => $status, 'mode' => $mode);
3564 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
3565
3566 if ($reshook > 0) {
3567 return $hookmanager->resPrint;
3568 }
3569
3570 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
3571 }
3572
3573
3574 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3582 public function load_board($user, $mode)
3583 {
3584 // phpcs:enable
3585 global $langs, $hookmanager;
3586
3587 $now = dol_now();
3588 $delay_warning = 0;
3589 if ($mode == 'opened') {
3590 $delay_warning = getWarningDelay('propal', 'cloture');
3591 }
3592 if ($mode == 'signed') {
3593 $delay_warning = getWarningDelay('propal', 'facturation');
3594 }
3595
3596 // The count, the total and the number of late proposals are computed by the database instead of reading every proposal.
3597 // An open proposal is late when its validity end date is before now minus the warning delay (a proposal without validity
3598 // end date was counted as late, this is kept); nothing is late in the 'signed' mode.
3599 $sql = "SELECT COUNT(p.rowid) as nb, SUM(p.total_ht) as total,";
3600 if ($mode == 'opened') {
3601 $sql .= " SUM(CASE WHEN p.fin_validite IS NULL OR p.fin_validite < '".$this->db->idate($now - $delay_warning)."' THEN 1 ELSE 0 END) as nblate";
3602 } else {
3603 $sql .= " 0 as nblate";
3604 }
3605 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3606 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
3607 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
3608 } else {
3609 $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
3610 }
3611 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3612 if ($mode == 'opened') {
3613 $sql .= " AND p.fk_statut = ".self::STATUS_VALIDATED;
3614 }
3615 if ($mode == 'signed') {
3616 $sql .= " AND p.fk_statut = ".self::STATUS_SIGNED;
3617 }
3618
3619 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3620 $sql .= " AND sc.fk_user = ".((int) $user->id);
3621 }
3622 if ($user->socid) {
3623 $sql .= " AND p.fk_soc = ".((int) $user->socid);
3624 }
3625
3626 // If the internal user must only see his customers, force searching by him
3627 $search_sale = 0;
3628 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3629 $search_sale = $user->id;
3630 }
3631 // Search on sale representative
3632 if ($search_sale && $search_sale != '-1') {
3633 if ($search_sale == -2) {
3634 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3635 } elseif ($search_sale > 0) {
3636 $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).")";
3637 }
3638 }
3639 if ($user->socid) {
3640 $sql .= " AND p.fk_soc = ".((int) $user->socid);
3641 }
3642 // Add where from hooks
3643 $parameters = array('socid' => $user->socid);
3644 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3645 $sql .= $hookmanager->resPrint;
3646
3647 $resql = $this->db->query($sql);
3648 if ($resql) {
3649 $langs->load("propal");
3650
3651 $status = 0;
3652 $label = $labelShort = '';
3653 if ($mode == 'opened') {
3654 $status = self::STATUS_VALIDATED;
3655 $label = $langs->transnoentitiesnoconv("PropalsToClose");
3656 $labelShort = $langs->transnoentitiesnoconv("ToAcceptRefuse");
3657 }
3658 if ($mode == 'signed') {
3659 $status = self::STATUS_SIGNED;
3660 $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered
3661 $labelShort = $langs->trans("ToBill");
3662 }
3663
3664 $response = new WorkboardResponse();
3665 $response->warning_delay = $delay_warning / 60 / 60 / 24;
3666 $response->label = $label;
3667 $response->labelShort = $labelShort;
3668 $response->url = dolBuildUrl(DOL_URL_ROOT.'/comm/propal/list.php', ['search_status' => $status, 'mainmenu' => 'commercial', 'leftmenu' => 'propals']);
3669 $response->url_late = dolBuildUrl(DOL_URL_ROOT.'/comm/propal/list.php', ['search_option' => 'late', 'mainmenu' => 'commercial', 'leftmenu' => 'propals', 'sortfield' => 'p.datep', 'sortorder' => 'asc']);
3670 $response->img = img_object('', "propal");
3671
3672 // This assignment in condition is not a bug. It allows walking the results.
3673 // TODO Definir regle des propales a facturer en retard (mode 'signed')
3674 $obj = $this->db->fetch_object($resql);
3675 if ($obj) {
3676 $response->nbtodo = (int) $obj->nb;
3677 $response->total = (float) $obj->total;
3678 $response->nbtodolate = (int) $obj->nblate;
3679 }
3680
3681 return $response;
3682 } else {
3683 $this->error = $this->db->error();
3684 return -1;
3685 }
3686 }
3687
3688
3697 public function initAsSpecimen($param = array())
3698 {
3699 global $conf, $langs;
3700
3701 // Load array of products prodids
3702 $num_prods = 0;
3703 $prodids = array();
3704 $sql = "SELECT rowid";
3705 $sql .= " FROM ".MAIN_DB_PREFIX."product";
3706 $sql .= " WHERE entity IN (".getEntity('product').")";
3707 if (array_key_exists('tosell', $param)) {
3708 $sql .= " AND tosell = ".((int) $param['tosell']);
3709 }
3710 $sql .= $this->db->plimit(100);
3711
3712 $resql = $this->db->query($sql);
3713 if ($resql) {
3714 $num_prods = $this->db->num_rows($resql);
3715 $i = 0;
3716 while ($i < $num_prods) {
3717 $i++;
3718 $row = $this->db->fetch_row($resql);
3719 $prodids[$i] = $row[0];
3720 }
3721 }
3722
3723 // Initialise parameters
3724 $this->id = 0;
3725 $this->ref = 'SPECIMEN';
3726 $this->ref_customer = 'NEMICEPS';
3727 $this->ref_client = 'NEMICEPS';
3728 $this->specimen = 1;
3729 $this->socid = 1;
3730 $this->date = dol_now();
3731 $this->fin_validite = $this->date + 3600 * 24 * 30;
3732 $this->cond_reglement_id = 1;
3733 $this->cond_reglement_code = 'RECEP';
3734 $this->mode_reglement_id = 7;
3735 $this->mode_reglement_code = 'CHQ';
3736 $this->availability_id = 1;
3737 $this->availability_code = 'AV_NOW';
3738 $this->demand_reason_id = 1;
3739 $this->demand_reason_code = 'SRC_00';
3740 $this->note_public = 'This is a comment (public)';
3741 $this->note_private = 'This is a comment (private)';
3742
3743 $this->multicurrency_tx = 1;
3744 $this->multicurrency_code = getDolCurrency();
3745
3746 // Lines
3747 $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)
3748 $xnbp = 0;
3749 while ($xnbp < $nbp) {
3750 $line = new PropaleLigne($this->db);
3751 $line->desc = $langs->trans("Description")." ".$xnbp;
3752 $line->qty = 1;
3753 $line->subprice = 100;
3754 $line->tva_tx = 20;
3755 $line->localtax1_tx = 0;
3756 $line->localtax2_tx = 0;
3757 if ($xnbp == 2) {
3758 $line->total_ht = 50;
3759 $line->total_ttc = 60;
3760 $line->total_tva = 10;
3761 $line->remise_percent = 50;
3762 } else {
3763 $line->total_ht = 100;
3764 $line->total_ttc = 120;
3765 $line->total_tva = 20;
3766 $line->remise_percent = 00;
3767 }
3768
3769 if ($num_prods > 0) {
3770 $prodid = mt_rand(1, $num_prods);
3771 $line->fk_product = $prodids[$prodid];
3772 $line->product_ref = 'SPECIMEN';
3773 }
3774
3775 $this->lines[$xnbp] = $line;
3776
3777 $this->total_ht += $line->total_ht;
3778 $this->total_tva += $line->total_tva;
3779 $this->total_ttc += $line->total_ttc;
3780
3781 $xnbp++;
3782 }
3783
3784 return 1;
3785 }
3786
3792 public function loadStateBoard()
3793 {
3794 global $user, $hookmanager;
3795
3796 $this->nb = array();
3797
3798 $sql = "SELECT count(p.rowid) as nb";
3799 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
3800 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
3801 $sql .= " WHERE p.entity IN (".getEntity('propal').")";
3802
3803 // If the internal user must only see his customers, force searching by him
3804 $search_sale = 0;
3805 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3806 $search_sale = $user->id;
3807 }
3808 // Search on sale representative
3809 if ($search_sale && $search_sale != '-1') {
3810 if ($search_sale == -2) {
3811 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
3812 } elseif ($search_sale > 0) {
3813 $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).")";
3814 }
3815 }
3816
3817 // Add where from hooks
3818 $parameters = array();
3819 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3820 $sql .= $hookmanager->resPrint;
3821 $resql = $this->db->query($sql);
3822 if ($resql) {
3823 // This assignment in condition is not a bug. It allows walking the results.
3824 while ($obj = $this->db->fetch_object($resql)) {
3825 $this->nb["proposals"] = $obj->nb;
3826 }
3827 $this->db->free($resql);
3828 return 1;
3829 } else {
3830 dol_print_error($this->db);
3831 $this->error = $this->db->error();
3832 return -1;
3833 }
3834 }
3835
3836
3844 public function getNextNumRef($soc)
3845 {
3846 global $conf, $langs;
3847 $langs->load("propal");
3848
3849 $classname = getDolGlobalString('PROPALE_ADDON');
3850
3851 if (!empty($classname)) {
3852 $mybool = false;
3853
3854 $file = $classname.".php";
3855
3856 // Include file with class
3857 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3858 foreach ($dirmodels as $reldir) {
3859 $dir = dol_buildpath($reldir."core/modules/propale/");
3860
3861 // Load file with numbering class (if found)
3862 $mybool = ((bool) @include_once $dir.$file) || $mybool;
3863 }
3864
3865 if (!$mybool) {
3866 dol_print_error(null, "Failed to include file ".$file);
3867 return '';
3868 }
3869
3870 $obj = new $classname();
3871 '@phan-var-force ModeleNumRefPropales $obj';
3874 $numref = $obj->getNextValue($soc, $this);
3875
3876 if ($numref != "") {
3877 return $numref;
3878 } else {
3879 $this->error = $obj->error;
3880 //dol_print_error($db,"Propale::getNextNumRef ".$obj->error);
3881 return "";
3882 }
3883 } else {
3884 $langs->load("errors");
3885 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Proposal"));
3886 return "";
3887 }
3888 }
3889
3896 public function getTooltipContentArray($params)
3897 {
3898 global $conf, $langs, $user;
3899
3900 $langs->load('propal');
3901 $datas = [];
3902 $nofetch = !empty($params['nofetch']);
3903
3904 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3905 return ['optimize' => $langs->trans("Proposal")];
3906 }
3907 if ($user->hasRight('propal', 'lire')) {
3908 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').'<u>'.$langs->trans("Proposal").'</u>';
3909 if (isset($this->status)) {
3910 $datas['status'] = ' '.$this->getLibStatut(5);
3911 }
3912 if (!empty($this->ref)) {
3913 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3914 }
3915 if (!$nofetch) {
3916 $langs->load('companies');
3917 if (empty($this->thirdparty)) {
3918 $this->fetch_thirdparty();
3919 }
3920 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
3921 }
3922 if (!empty($this->ref_customer)) {
3923 $datas['refcustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_customer;
3924 }
3925 if (!$nofetch) {
3926 $langs->load('project');
3927 if (is_null($this->project) || (is_object($this->project) && empty($this->project->id))) {
3928 $res = $this->fetchProject();
3929 if ($res > 0 && $this->project instanceof Project) {
3930 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
3931 }
3932 }
3933 }
3934 if (!empty($this->total_ht)) {
3935 $datas['amountht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3936 }
3937 if (!empty($this->total_tva)) {
3938 $datas['vat'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3939 }
3940 if (!empty($this->total_ttc)) {
3941 $datas['amountttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3942 }
3943 if (!empty($this->date)) {
3944 $datas['date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
3945 }
3946 if (!empty($this->date_signature)) {
3947 $datas['datesignature'] = '<br><b>'.$langs->trans('DateSigning').':</b> '.dol_print_date($this->date_signature, 'day');
3948 }
3949 if (!empty($this->delivery_date)) {
3950 $datas['deliverydate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
3951 }
3952 }
3953
3954 return $datas;
3955 }
3956
3968 public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = -1)
3969 {
3970 global $langs, $conf, $user, $hookmanager;
3971
3972 if (!empty($conf->dol_no_mouse_hover)) {
3973 $notooltip = 1; // Force disable tooltips
3974 }
3975
3976 $result = '';
3977 $params = [
3978 'id' => $this->id,
3979 'objecttype' => $this->element,
3980 'option' => $option,
3981 'nofetch' => 1,
3982 ];
3983 $classfortooltip = 'classfortooltip';
3984 $dataparams = '';
3985 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3986 $classfortooltip = 'classforajaxtooltip';
3987 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3988 $label = '';
3989 } else {
3990 $label = implode($this->getTooltipContentArray($params));
3991 }
3992
3993 $baseurl = '';
3994 $query = [];
3995 if ($user->hasRight('propal', 'lire')) {
3996 parse_str($get_params, $query);
3997 $query = array_merge($query, ['id' => $this->id]);
3998 if ($option == '') {
3999 $baseurl = DOL_URL_ROOT . '/comm/propal/card.php';
4000 } elseif ($option == 'compta') { // deprecated
4001 $baseurl = DOL_URL_ROOT . '/comm/propal/card.php';
4002 } elseif ($option == 'expedition') {
4003 $baseurl = DOL_URL_ROOT . '/expedition/propal.php';
4004 } elseif ($option == 'document') {
4005 $baseurl = DOL_URL_ROOT . '/comm/propal/document.php';
4006 }
4007
4008 if ($option != 'nolink') {
4009 // Add param to save lastsearch_values or not
4010 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
4011 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
4012 $add_save_lastsearch_values = 1;
4013 }
4014 if ($add_save_lastsearch_values) {
4015 $query = array_merge($query, ['save_lastsearch_values' => 1]);
4016 }
4017 }
4018 }
4019 $url = dolBuildUrl($baseurl, $query);
4020
4021 $linkclose = '';
4022 if (empty($notooltip) && $user->hasRight('propal', 'lire')) {
4023 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
4024 $label = $langs->trans("Proposal");
4025 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
4026 }
4027 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
4028 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
4029 }
4030
4031 $linkstart = '<a href="'.$url.'"';
4032 $linkstart .= $linkclose.'>';
4033 $linkend = '</a>';
4034
4035 $result .= $linkstart;
4036 if ($withpicto) {
4037 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
4038 }
4039 if ($withpicto != 2) {
4040 $result .= $this->ref;
4041 }
4042 $result .= $linkend;
4043
4044 if ($addlinktonotes >= 0) {
4045 $txttoshow = '';
4046
4047 if ($addlinktonotes == 0) {
4048 if (!empty($this->note_private) || !empty($this->note_public)) {
4049 $txttoshow = $langs->trans('ViewPrivateNote');
4050 }
4051 } elseif ($addlinktonotes == 1) {
4052 if (!empty($this->note_private)) {
4053 $txttoshow .= ($user->socid > 0 ? '' : dol_string_nohtmltag($this->note_private, 1));
4054 }
4055 } elseif ($addlinktonotes == 2) {
4056 if (!empty($this->note_public)) {
4057 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
4058 }
4059 } elseif ($addlinktonotes == 3) {
4060 if ($user->socid > 0) {
4061 if (!empty($this->note_public)) {
4062 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
4063 }
4064 } else {
4065 if (!empty($this->note_public)) {
4066 $txttoshow .= dol_string_nohtmltag($this->note_public, 1);
4067 }
4068 if (!empty($this->note_private)) {
4069 if (!empty($txttoshow)) {
4070 $txttoshow .= '<br><br>';
4071 }
4072 $txttoshow .= dol_string_nohtmltag($this->note_private, 1);
4073 }
4074 }
4075 }
4076
4077 if ($txttoshow) {
4078 $result .= ' <span class="note inline-block">';
4079 $result .= '<a href="'.dolBuildUrl(DOL_URL_ROOT.'/comm/propal/note.php', ['id' => $this->id]).'" class="classfortooltip" title="'.dol_escape_htmltag($txttoshow).'">';
4080 $result .= img_picto('', 'note');
4081 $result .= '</a>';
4082 $result .= '</span>';
4083 }
4084 }
4085
4086 global $action;
4087 $hookmanager->initHooks(array($this->element . 'dao'));
4088 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
4089 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4090 if ($reshook > 0) {
4091 $result = $hookmanager->resPrint;
4092 } else {
4093 $result .= $hookmanager->resPrint;
4094 }
4095 return $result;
4096 }
4097
4104 {
4105 $context = parent::getObjectLinesDisplayContext();
4106 $context['inputalsopricewithtax'] = 1;
4107
4108 return $context;
4109 }
4110
4117 public function getLinesArray($sqlforgedfilters = '')
4118 {
4119 return $this->fetch_lines(0, 0, $sqlforgedfilters);
4120 }
4121
4133 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4134 {
4135 $outputlangs->loadLangs(array("propale", "products"));
4136
4137 if (!dol_strlen($modele)) {
4138 $modele = getDolGlobalString('PROPALE_ADDON_PDF', 'cyan');
4139
4140 if ($this->model_pdf) {
4141 $modele = $this->model_pdf;
4142 }
4143 }
4144
4145 $modelpath = "core/modules/propale/doc/";
4146
4147 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4148 }
4149
4158 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4159 {
4160 $tables = array(
4161 'propal'
4162 );
4163
4164 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4165 }
4166
4175 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
4176 {
4177 $tables = array(
4178 'propaldet'
4179 );
4180
4181 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
4182 }
4183
4191 public function getKanbanView($option = '', $arraydata = null)
4192 {
4193 global $langs;
4194
4195 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
4196
4197 $return = '<div class="box-flex-item box-flex-grow-zero">';
4198 $return .= '<div class="info-box info-box-sm">';
4199 $return .= '<div class="info-box-icon bg-infobox-action">';
4200 $return .= img_picto('', $this->picto);
4201 $return .= '</div>';
4202 $return .= '<div class="info-box-content">';
4203 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
4204 if ($selected >= 0) {
4205 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
4206 }
4207 if (!empty($arraydata['projectlink'])) {
4208 $return .= '<span class="info-box-ref"> | '.$arraydata['projectlink'].'</span>';
4209 }
4210 $return .= '<br>';
4211 if (is_object($this->thirdparty)) {
4212 $return .= '<div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
4213 }
4214 $return .= '<span class="info-box-label amount" title="'.$langs->trans("AmountHT").'">'.price($this->total_ht).'</span>';
4215 if (!empty($arraydata['authorlink'])) {
4216 $return .= ' &nbsp; <span class="info-box-label">'.$arraydata['authorlink'].'</span>';
4217 }
4218 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
4219 $return .= '</div>';
4220 $return .= '</div>';
4221 $return .= '</div>';
4222 return $return;
4223 }
4224
4235 public function setCategories($categories)
4236 {
4237 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4238 return parent::setCategoriesCommon($categories, Categorie::TYPE_PROPOSAL);
4239 }
4240
4256 public function sendReminderForExpiringProposals($daysbeforeendlist = '10')
4257 {
4258 global $conf, $langs, $mysoc, $user;
4259
4260 $error = 0;
4261 $this->output = '';
4262 $this->error = '';
4263
4264 $blockingerrormsg = '';
4265
4266 if (!isModEnabled('propal')) { // Should not happen. If module disabled, cron job should not be visible.
4267 $langs->load("agenda");
4268 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Proposals"));
4269 return 0;
4270 }
4271
4272 $now = dol_now();
4273 $nbok = 0;
4274 $nbko = 0;
4275
4276 $listofpropalsok = array();
4277 $listofpropalsko = array();
4278
4279 $arraydaysbeforeend = explode(';', $daysbeforeendlist);
4280 foreach ($arraydaysbeforeend as $daysbeforeend) { // Loop on each delay
4281 dol_syslog(__METHOD__.' - Process delta = '.$daysbeforeend, LOG_DEBUG);
4282
4283 if (!is_numeric($daysbeforeend)) {
4284 $blockingerrormsg = "Value for delta is not a numeric value";
4285 $nbko++;
4286 break;
4287 }
4288
4289 // Label of the event recorded once a reminder is sent for a given delay. Also used to not send the same reminder twice the same day.
4290 $labelreminderok = 'sendReminderForExpiringProposalsOK (daysbeforeend='.$daysbeforeend.')';
4291
4292 $tmp = dol_getdate($now);
4293 $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
4294 $datetosearchforend = dol_time_plus_duree(dol_mktime(23, 59, 59, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
4295
4296 $sql = "SELECT p.rowid";
4297 $sql .= " FROM ".MAIN_DB_PREFIX."propal as p";
4298 $sql .= " WHERE p.entity = ".((int) $conf->entity); // Do not use getEntity('propal') here, we want the batch to be on its entity only
4299 $sql .= " AND p.fk_statut = ".((int) self::STATUS_VALIDATED);
4300 $sql .= " AND p.fin_validite >= '".$this->db->idate($datetosearchfor)."'";
4301 $sql .= " AND p.fin_validite <= '".$this->db->idate($datetosearchforend)."'";
4302 $sql .= " AND NOT EXISTS (SELECT a.id FROM ".MAIN_DB_PREFIX."actioncomm as a";
4303 $sql .= " WHERE a.elementtype = 'propal' AND a.fk_element = p.rowid AND a.code = 'AC_EMAIL'";
4304 $sql .= " AND a.label = '".$this->db->escape($labelreminderok)."'";
4305 $sql .= " AND a.datep >= '".$this->db->idate(dol_get_first_hour($now))."')";
4306
4307 $resql = $this->db->query($sql);
4308 if ($resql) {
4309 $num_rows = $this->db->num_rows($resql);
4310
4311 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
4312 $formmail = new FormMail($this->db);
4313
4314 $i = 0;
4315 while ($i < $num_rows) {
4316 $obj = $this->db->fetch_object($resql);
4317
4318 $propalstatic = new Propal($this->db);
4319 $propalstatic->fetch($obj->rowid);
4320 $thirdpartyres = $propalstatic->fetch_thirdparty();
4321
4322 if ($thirdpartyres <= 0 || empty($propalstatic->thirdparty->email)) {
4323 $nbko++;
4324 $listofpropalsko[$propalstatic->id] = $propalstatic->id;
4325 } else {
4326 $languagefromcountrycode = getLanguageCodeFromCountryCode($propalstatic->thirdparty->country_code);
4327 $languagecodetouse = (empty($propalstatic->thirdparty->default_lang) ? ($languagefromcountrycode ? $languagefromcountrycode : $mysoc->default_lang) : $propalstatic->thirdparty->default_lang);
4328
4329 $outputlangs = new Translate('', $conf);
4330 $outputlangs->setDefaultLang($languagecodetouse);
4331 $outputlangs->loadLangs(array("main", "propal"));
4332 dol_syslog("sendReminderForExpiringProposals Language for thirdparty id ".$propalstatic->thirdparty->id." set to ".$outputlangs->defaultlang." mysoc->default_lang=".$mysoc->default_lang);
4333
4334 $arraydefaultmessage = null;
4335 $labeltouse = getDolGlobalString('PROPOSAL_EMAIL_TEMPLATE_REMIND_EXPIRATION');
4336
4337 if (!empty($labeltouse)) {
4338 $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'propal', $user, $outputlangs, 0, 1, $labeltouse);
4339 }
4340
4341 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
4342 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $propalstatic);
4343 complete_substitutions_array($substitutionarray, $outputlangs, $propalstatic);
4344
4345 $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
4346 $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
4347 $email_from = getDolGlobalString('PROPOSAL_MAIL_FROM', $conf->email_from);
4348 $to = (string) $propalstatic->thirdparty->email;
4349 $cc = getDolGlobalString('PROPOSAL_CC_MAIL_FROM');
4350
4351 $trackid = 'pro'.$propalstatic->id;
4352 $moreinheader = 'X-Dolibarr-Info: sendReminderForExpiringProposals'."\r\n";
4353
4354 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
4355 $cmail = new CMailFile($subject, $to, $email_from, $msg, array(), array(), array(), $cc, '', 0, 1, '', '', $trackid, $moreinheader);
4356 $result = $cmail->sendfile();
4357 if (!$result) {
4358 $error++;
4359 $this->error .= $cmail->error.' ';
4360 if (!is_null($cmail->errors)) {
4361 $this->errors = array_merge($this->errors, $cmail->errors);
4362 }
4363 $nbko++;
4364 $listofpropalsko[$propalstatic->id] = $propalstatic->id;
4365 } else {
4366 $nbok++;
4367 $listofpropalsok[$propalstatic->id] = $propalstatic->id;
4368
4369 // Insert record of email sent, as an agenda event on the proposal (same convention as other automated reminder emails)
4370 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
4371
4372 $actioncomm = new ActionComm($this->db);
4373 $actioncomm->type_code = 'AC_OTH_AUTO';
4374 $actioncomm->code = 'AC_EMAIL';
4375 $actioncomm->label = $labelreminderok;
4376 $actioncomm->note_private = $msg;
4377 $actioncomm->fk_project = $propalstatic->fk_project;
4378 $actioncomm->datep = $now;
4379 $actioncomm->datef = $now;
4380 $actioncomm->percentage = -1; // Not applicable
4381 $actioncomm->socid = $propalstatic->thirdparty->id;
4382 $actioncomm->contact_id = 0;
4383 $actioncomm->authorid = $user->id;
4384 $actioncomm->userownerid = $user->id;
4385 $actioncomm->email_msgid = $cmail->msgid;
4386 $actioncomm->email_from = $email_from;
4387 $actioncomm->email_sender = '';
4388 $actioncomm->email_to = $to;
4389 $actioncomm->email_subject = $subject;
4390
4391 $actioncomm->fk_element = $propalstatic->id;
4392 $actioncomm->elementid = $propalstatic->id;
4393 $actioncomm->elementtype = $propalstatic->element;
4394
4395 $actioncomm->create($user);
4396 }
4397 } else {
4398 $error++;
4399 $this->error .= "Can't find email template with label=".$labeltouse.", to use for the reminding email ";
4400
4401 $nbko++;
4402 $listofpropalsko[$propalstatic->id] = $propalstatic->id;
4403
4404 // Do not break here: a template issue for one proposal (ex: not found for its language) must not
4405 // prevent the reminder from being sent for the other proposals due the same day.
4406 }
4407 }
4408
4409 $i++;
4410 }
4411 } else {
4412 $this->error = $this->db->lasterror();
4413 return 1;
4414 }
4415 }
4416
4417 if ($blockingerrormsg) {
4418 $this->error = $blockingerrormsg;
4419 return 1;
4420 } else {
4421 $this->output = 'Found '.($nbok + $nbko).' proposals to send reminder for.';
4422 $this->output .= ' Sent email successfully for '.$nbok.' proposals';
4423 if ($nbko) {
4424 $this->output .= ' - Canceled for '.$nbko.' proposal(s) (no thirdparty email, missing template, or send error)';
4425 }
4426 }
4427
4428 if ($error) {
4429 return 1;
4430 }
4431 return 0;
4432 }
4433}
$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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0, $qty=0)
Get buy price to use for margin calculation.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
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 products or services.
Class to manage projects.
Class to manage proposals.
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card before printObjectLines() and formAdd...
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...
persistFieldValue(User $user, $field)
Save into database the current value of one field, called by updateFieldFromUi().
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.
sendReminderForExpiringProposals($daysbeforeendlist='10')
Send reminders by email before a validated commercial proposal expires.
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
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:686
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
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:66
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.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
getLanguageCodeFromCountryCode($countrycode)
Return default language from country code.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
isDolTms($timestamp)
isDolTms check if a timestamp is valid.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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', ...)
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
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_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.
isModEnabled($module)
Is Dolibarr module enabled.
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_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
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