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