dolibarr 24.0.3
supplier_proposal.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-2018 Philippe Grand <philippe.grand@atoo-net.com>
11 * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
12 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
13 * Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
14 * Copyright (C) 2016 Ferran Marcet <fmarcet@2byte.es>
15 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
16 * Copyright (C) 2019-2025 Frédéric France <frederic.france@free.fr>
17 * Copyright (C) 2020 Tobias Sekan <tobias.sekan@startmail.com>
18 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
19 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
20 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
21 *
22 * This program is free software; you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation; either version 3 of the License, or
25 * (at your option) any later version.
26 *
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
31 *
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <https://www.gnu.org/licenses/>.
34 */
35
41require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
42require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
43require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
44require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
45require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
46require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
48require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
53{
54 use CommonIncoterm;
55 use CommonSubtotal;
56
60 public $element = 'supplier_proposal';
61
65 public $table_element = 'supplier_proposal';
66
70 public $table_element_line = 'supplier_proposaldet';
71
75 public $class_element_line = 'SupplierProposalLine';
79 public $fk_element = 'fk_supplier_proposal';
80
84 public $picto = 'supplier_proposal';
85
90 public $restrictiononfksoc = 1;
91
95 protected $table_ref_field = 'ref';
96
100 public $socid; // Id client
101
107 public $author;
108
112 public $ref_fourn;
116 public $ref_supplier;
117
122 public $statut; // 0 (draft), 1 (validated), 2 (signed), 3 (not signed), 4 (processed/billed)
123
127 public $date;
128
132 public $delivery_date;
133
139 public $datec;
140
146 public $datev;
147
151 public $user_author_id;
152
158 public $price;
159
165 public $tva;
166
172 public $total;
173
177 public $cond_reglement_code;
181 public $cond_reglement_doc; // label doc
185 public $cond_reglement_label;
186
190 public $mode_reglement_code;
195 public $mode_reglement;
196
202 public $deposit_percent;
203
204
208 public $extraparams = array();
209
213 public $lines = array();
214
218 public $line;
219
220 public $labelStatus = array();
221 public $labelStatusShort = array();
222
226 public $nbtodo;
230 public $nbtodolate;
231
232 // Multicurrency
236 public $fk_multicurrency;
237
241 public $multicurrency_code;
245 public $multicurrency_tx;
249 public $multicurrency_total_ht;
253 public $multicurrency_total_tva;
257 public $multicurrency_total_ttc;
258
259 public $fields = array(
260 'ref' => array('type' => 'varchar(255)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'showoncombobox' => 1, 'position' => 25, 'searchall' => 1),
261 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 750, 'searchall' => 1),
262 );
263
267 const STATUS_DRAFT = 0;
268
273
277 const STATUS_SIGNED = 2;
278
283
287 const STATUS_CLOSE = 4;
288
289
290
298 public function __construct($db, $socid = 0, $supplier_proposalid = 0)
299 {
300 $this->db = $db;
301
302 $this->ismultientitymanaged = 1;
303 $this->socid = $socid;
304 $this->id = $supplier_proposalid;
305 }
306
307
308 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
319 public function add_product($idproduct, $qty, $remise_percent = 0)
320 {
321 // phpcs:enable
322 global $mysoc;
323
324 if (!$qty) {
325 $qty = 1;
326 }
327
328 dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent");
329 if ($idproduct > 0) {
330 $prod = new Product($this->db);
331 $prod->fetch($idproduct);
332
333 $productdesc = $prod->description;
334
335 $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
336 $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
337 if (empty($tva_tx)) {
338 $tva_npr = 0;
339 }
340 $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr);
341 $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr);
342
343 // multiprix
344 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $this->thirdparty->price_level) {
345 $price = $prod->multiprices[$this->thirdparty->price_level];
346 } else {
347 $price = $prod->price;
348 }
349
350 $line = new SupplierProposalLine($this->db);
351
352 $line->fk_product = $idproduct;
353 $line->desc = $productdesc;
354 $line->qty = $qty;
355 $line->subprice = $price;
356 $line->remise_percent = $remise_percent;
357 $line->tva_tx = $tva_tx;
358
359 $this->lines[] = $line;
360 return 1;
361 }
362 return -1;
363 }
364
365 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
372 public function insert_discount($idremise)
373 {
374 // phpcs:enable
375 global $langs;
376
377 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
378 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
379
380 $this->db->begin();
381
382 $remise = new DiscountAbsolute($this->db);
383 $result = $remise->fetch($idremise);
384
385 if ($result > 0) {
386 if ($remise->fk_facture) { // Protection against multiple submission
387 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
388 $this->db->rollback();
389 return -5;
390 }
391
392 $supplier_proposalligne = new SupplierProposalLine($this->db);
393 $supplier_proposalligne->fk_supplier_proposal = $this->id;
394 $supplier_proposalligne->fk_remise_except = $remise->id;
395 $supplier_proposalligne->desc = $remise->description; // Description of the proposal line
396 $supplier_proposalligne->tva_tx = $remise->tva_tx;
397 $supplier_proposalligne->localtax1_tx = $remise->localtax1_tx;
398 $supplier_proposalligne->localtax1_type = $remise->localtax1_type;
399 $supplier_proposalligne->localtax2_tx = $remise->localtax1_tx;
400 $supplier_proposalligne->localtax2_type = $remise->localtax1_type;
401 $supplier_proposalligne->subprice = -(float) $remise->amount_ht;
402 $supplier_proposalligne->fk_product = 0; // Predefined Product ID
403 $supplier_proposalligne->qty = 1;
404 $supplier_proposalligne->remise_percent = 0;
405 $supplier_proposalligne->rang = -1;
406 $supplier_proposalligne->info_bits = 2;
407
408 $supplier_proposalligne->total_ht = -(float) $remise->amount_ht;
409 $supplier_proposalligne->total_tva = -(float) $remise->amount_tva;
410 $supplier_proposalligne->total_ttc = -(float) $remise->amount_ttc;
411 $supplier_proposalligne->total_localtax1 = -(float) $remise->total_localtax1;
412 $supplier_proposalligne->total_localtax2 = -(float) $remise->total_localtax2;
413
414 $result = $supplier_proposalligne->insert();
415 if ($result > 0) {
416 $result = $this->update_price(1);
417 if ($result > 0) {
418 $this->db->commit();
419 return 1;
420 } else {
421 $this->db->rollback();
422 return -1;
423 }
424 } else {
425 $this->setErrorsFromObject($supplier_proposalligne);
426 $this->db->rollback();
427 return -2;
428 }
429 } else {
430 $this->db->rollback();
431 return -2;
432 }
433 }
434
471 public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $pu_ttc = 0, $info_bits = 0, $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $array_options = [], $ref_supplier = '', $fk_unit = 0, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $date_start = 0, $date_end = 0)
472 {
473 global $mysoc, $langs;
474
475 dol_syslog(get_class($this)."::addline supplier_proposalid=$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");
476 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
477
478 // Clean parameters
479 if (empty($remise_percent)) {
480 $remise_percent = 0;
481 }
482 if (empty($qty)) {
483 $qty = 0;
484 }
485 if (empty($info_bits)) {
486 $info_bits = 0;
487 }
488 if (empty($rang)) {
489 $rang = 0;
490 }
491 if (empty($fk_parent_line) || $fk_parent_line < 0) {
492 $fk_parent_line = 0;
493 }
494 if (empty($pu_ht)) {
495 $pu_ht = 0;
496 }
497
498 $remise_percent = price2num($remise_percent);
499 $qty = (float) price2num($qty);
500 $pu_ht = price2num($pu_ht);
501 $pu_ttc = price2num($pu_ttc);
502 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
503 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
504 }
505 $txlocaltax1 = price2num($txlocaltax1);
506 $txlocaltax2 = price2num($txlocaltax2);
507 $pa_ht = price2num($pa_ht);
508 if ($price_base_type == 'HT') {
509 $pu = $pu_ht;
510 } else {
511 $pu = $pu_ttc;
512 }
513
514 // Check parameters
515 if ($type < 0) {
516 return -1;
517 }
518
519 if ($this->status == self::STATUS_DRAFT) {
520 $this->db->begin();
521
522 if ($fk_product > 0) {
523 if (getDolGlobalInt('SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY') == 1) { // Not the common case
524 // Check quantity is enough
525 dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_fournprice=".$fk_fournprice." qty=".$qty." ref_supplier=".$ref_supplier);
526 $productsupplier = new ProductFournisseur($this->db);
527 if ($productsupplier->fetch($fk_product) > 0) {
528 $product_type = $productsupplier->type;
529 $label = $productsupplier->label;
530 $fk_prod_fourn_price = $fk_fournprice;
531
532 // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok.
533 // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price.
534 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
535 $result = $productsupplier->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', $this->socid); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->socid
536 if ($result > 0) {
537 $pu = $productsupplier->fourn_pu; // Unit price supplier price set by get_buyprice
538 $ref_supplier = $productsupplier->ref_supplier; // Ref supplier price set by get_buyprice
539 // is remise percent not keyed but present for the product we add it
540 if ($remise_percent == 0 && $productsupplier->remise_percent != 0) {
541 $remise_percent = $productsupplier->remise_percent;
542 }
543 }
544 if ($result == 0) { // If result == 0, we failed to found the supplier reference price
545 $langs->load("errors");
546 $this->error = "Ref ".$productsupplier->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
547 $this->db->rollback();
548 dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price");
549 //$pu = $productsupplier->fourn_pu; // We do not overwrite unit price
550 //$ref = $productsupplier_fourn; // We do not overwrite ref supplier price
551 return -1;
552 }
553 if ($result == -1) {
554 $langs->load("errors");
555 $this->error = "Ref ".$productsupplier->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier");
556 $this->db->rollback();
557 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG);
558 return -1;
559 }
560 if ($result < -1) {
561 $this->setErrorsFromObject($productsupplier);
562 $this->db->rollback();
563 dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR);
564 return -1;
565 }
566 } else {
567 $this->setErrorsFromObject($productsupplier);
568 $this->db->rollback();
569 return -1;
570 }
571 }
572 } else {
573 $product_type = $type;
574 }
575
576 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
577 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
578 // and this is done at the line level, which has its own VAT rate
579
580 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
581
582 // Clean vat code
583 $reg = array();
584 $vat_src_code = '';
585 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
586 $vat_src_code = $reg[1];
587 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
588 }
589
590 if (isModEnabled("multicurrency") && $pu_ht_devise > 0) {
591 $pu = 0;
592 }
593
594 $tabprice = calcul_price_total(
595 $qty,
596 $pu,
597 (float) $remise_percent,
598 $txtva,
599 (float) $txlocaltax1,
600 (float) $txlocaltax2,
601 0,
602 $price_base_type,
603 $info_bits,
604 $type,
605 $this->thirdparty,
606 $localtaxes_type,
607 100,
608 (float) $this->multicurrency_tx,
609 $pu_ht_devise
610 );
611 $total_ht = $tabprice[0];
612 $total_tva = $tabprice[1];
613 $total_ttc = $tabprice[2];
614 $total_localtax1 = $tabprice[9];
615 $total_localtax2 = $tabprice[10];
616 $pu = $pu_ht = $tabprice[3];
617
618 // MultiCurrency
619 $multicurrency_total_ht = $tabprice[16];
620 $multicurrency_total_tva = $tabprice[17];
621 $multicurrency_total_ttc = $tabprice[18];
622 $pu_ht_devise = $tabprice[19];
623
624 // Rang to use
625 $ranktouse = $rang;
626 if ($ranktouse == -1) {
627 $rangmax = $this->line_max($fk_parent_line);
628 $ranktouse = $rangmax + 1;
629 }
630
631 // Insert line
632 $this->line = new SupplierProposalLine($this->db);
633
634 $this->line->fk_supplier_proposal = $this->id;
635 $this->line->label = $label;
636 $this->line->desc = $desc;
637 $this->line->qty = $qty;
638
639 $this->line->vat_src_code = $vat_src_code;
640 $this->line->tva_tx = $txtva;
641 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
642 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
643 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
644 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
645 $this->line->fk_product = $fk_product;
646 $this->line->remise_percent = $remise_percent;
647 $this->line->subprice = (float) $pu_ht;
648 $this->line->rang = $ranktouse;
649 $this->line->info_bits = $info_bits;
650 $this->line->total_ht = (float) $total_ht;
651 $this->line->total_tva = (float) $total_tva;
652 $this->line->total_localtax1 = (float) $total_localtax1;
653 $this->line->total_localtax2 = (float) $total_localtax2;
654 $this->line->total_ttc = (float) $total_ttc;
655 $this->line->product_type = $type;
656 $this->line->special_code = $special_code;
657 $this->line->fk_parent_line = $fk_parent_line;
658 $this->line->fk_unit = $fk_unit;
659 $this->line->origin = $origin;
660 $this->line->origin_type = $origin;
661 $this->line->origin_id = $origin_id;
662 $this->line->ref_fourn = $this->db->escape($ref_supplier);
663 $this->line->date_start = $date_start;
664 $this->line->date_end = $date_end;
665
666 // infos merge
667 if (!empty($fk_product) && $fk_product > 0 && empty($fk_fournprice) && empty($pa_ht)) {
668 // When fk_fournprice is 0, we take the lowest buying price
669 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
670 $productFournisseur = new ProductFournisseur($this->db);
671 $productFournisseur->find_min_price_product_fournisseur($fk_product);
672 $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id;
673 } else {
674 $this->line->fk_fournprice = ($fk_fournprice > 0 ? $fk_fournprice : 0); // If fk_fournprice is -1, we will not use fk_fournprice
675 }
676 $this->line->pa_ht = $pa_ht;
677 //var_dump($this->line->fk_fournprice);exit;
678
679 // Multicurrency
680 $this->line->fk_multicurrency = $this->fk_multicurrency;
681 $this->line->multicurrency_code = $this->multicurrency_code;
682 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
683 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
684 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
685 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
686
687 // Set the proposal line as optional
688 if (empty($qty) && empty($special_code)) {
689 $this->line->special_code = 3;
690 }
691
692 if (is_array($array_options) && count($array_options) > 0) {
693 $this->line->array_options = $array_options;
694 }
695
696 $result = $this->line->insert();
697 if ($result > 0) {
698 // Reorder if child line
699 if (!empty($fk_parent_line)) {
700 $this->line_order(true, 'DESC');
701 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
702 $linecount = count($this->lines);
703 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
704 $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
705 }
706 }
707
708 // Update denormalized information at the present proposal level
709 $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
710 if ($result > 0) {
711 $this->db->commit();
712 return $this->line->id;
713 } else {
714 $this->db->rollback();
715 return -1;
716 }
717 } else {
718 $this->setErrorsFromObject($this->line);
719 $this->db->rollback();
720 return -2;
721 }
722 } else {
723 $this->error = 'BadStatusOfObjectToAddLine';
724 return -5;
725 }
726 }
727
728
755 public function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 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, $array_options = [], $ref_supplier = '', $fk_unit = 0, $pu_ht_devise = 0)
756 {
757 global $mysoc;
758
759 if (!$this->isLineOfObject($rowid)) {
760 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
761 return -1;
762 }
763
764 dol_syslog(get_class($this)."::updateLine $rowid, $pu, $qty, $remise_percent, $txtva, $desc, $price_base_type, $info_bits");
765 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
766
767 // Clean parameters
768 $remise_percent = price2num($remise_percent);
769 $qty = (float) price2num($qty);
770 $pu = price2num($pu);
771 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
772 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
773 }
774 $txlocaltax1 = price2num($txlocaltax1);
775 $txlocaltax2 = price2num($txlocaltax2);
776 $pa_ht = price2num($pa_ht);
777 if (empty($qty) && empty($special_code)) {
778 $special_code = 3; // Set option tag
779 }
780 if (!empty($qty) && $special_code == 3) {
781 $special_code = 0; // Remove option tag
782 }
783
784 if ($this->status == 0) {
785 $this->db->begin();
786
787 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
788 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
789 // and this is done at the line level, which has its own VAT rate
790
791 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty);
792
793 // Clean vat code
794 $reg = array();
795 $vat_src_code = '';
796 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
797 $vat_src_code = $reg[1];
798 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
799 }
800
801 if (isModEnabled("multicurrency") && $pu_ht_devise > 0) {
802 $pu = 0;
803 }
804
805 $tabprice = calcul_price_total(
806 $qty,
807 $pu,
808 (float) $remise_percent,
809 $txtva,
810 (float) $txlocaltax1,
811 (float) $txlocaltax2,
812 0,
813 $price_base_type,
814 $info_bits,
815 $type,
816 $this->thirdparty,
817 $localtaxes_type,
818 100,
819 (float) $this->multicurrency_tx,
820 $pu_ht_devise
821 );
822 $total_ht = $tabprice[0];
823 $total_tva = $tabprice[1];
824 $total_ttc = $tabprice[2];
825 $total_localtax1 = $tabprice[9];
826 $total_localtax2 = $tabprice[10];
827 $pu_ht = $tabprice[3];
828 $pu_tva = $tabprice[4];
829 $pu_ttc = $tabprice[5];
830
831 // MultiCurrency
832 $multicurrency_total_ht = $tabprice[16];
833 $multicurrency_total_tva = $tabprice[17];
834 $multicurrency_total_ttc = $tabprice[18];
835 $pu_ht_devise = $tabprice[19];
836
837 $pu = $pu_ht;
838 if ($price_base_type == 'TTC') {
839 $pu = $pu_ttc;
840 }
841
842 // Fetch current line from the database and then clone the object and set it in $oldline property
843 $line = new SupplierProposalLine($this->db);
844 $line->fetch($rowid);
845 $line->fetch_optionals();
846
847 $fk_product = $line->fk_product;
848
849 // Stock previous line records
850 $staticline = clone $line;
851
852 $line->oldline = $staticline;
853 $this->line = $line;
854 $this->line->context = $this->context;
855
856 // Reorder if fk_parent_line change
857 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
858 $rangmax = $this->line_max($fk_parent_line);
859 $this->line->rang = $rangmax + 1;
860 }
861
862 $this->line->id = $rowid;
863 $this->line->label = $label;
864 $this->line->desc = $desc;
865 $this->line->qty = $qty;
866 $this->line->product_type = $type;
867
868 $this->line->vat_src_code = $vat_src_code;
869 $this->line->tva_tx = $txtva;
870 $this->line->localtax1_tx = $txlocaltax1;
871 $this->line->localtax2_tx = $txlocaltax2;
872 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
873 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
874 $this->line->remise_percent = $remise_percent;
875 $this->line->subprice = (float) $pu;
876 $this->line->info_bits = $info_bits;
877 $this->line->total_ht = (float) $total_ht;
878 $this->line->total_tva = (float) $total_tva;
879 $this->line->total_localtax1 = (float) $total_localtax1;
880 $this->line->total_localtax2 = (float) $total_localtax2;
881 $this->line->total_ttc = (float) $total_ttc;
882 $this->line->special_code = $special_code;
883 $this->line->fk_parent_line = $fk_parent_line;
884 $this->line->skip_update_total = $skip_update_total;
885 $this->line->ref_fourn = $ref_supplier;
886 $this->line->fk_unit = $fk_unit;
887
888 // infos merge
889 if (!empty($fk_product) && $fk_product > 0 && empty($fk_fournprice) && empty($pa_ht)) {
890 // by external module, take lowest buying price
891 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
892 $productFournisseur = new ProductFournisseur($this->db);
893 $productFournisseur->find_min_price_product_fournisseur($fk_product);
894 $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id;
895 } else {
896 $this->line->fk_fournprice = $fk_fournprice;
897 }
898 $this->line->pa_ht = $pa_ht;
899
900 if (is_array($array_options) && count($array_options) > 0) {
901 // We replace values in this->line->array_options only for entries defined into $array_options
902 foreach ($array_options as $key => $value) {
903 $this->line->array_options[$key] = $array_options[$key];
904 }
905 }
906
907 // Multicurrency
908 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
909 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
910 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
911 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
912
913 $result = $this->line->update();
914 if ($result > 0) {
915 // Reorder if child line
916 if (!empty($fk_parent_line)) {
917 $this->line_order(true, 'DESC');
918 }
919
920 $this->update_price(1);
921
922 $this->db->commit();
923 return $result;
924 } else {
925 $this->error = $this->db->error();
926 $this->db->rollback();
927 return -1;
928 }
929 } else {
930 dol_syslog(get_class($this)."::updateline Erreur -2 SupplierProposal en mode incompatible pour cette action");
931 return -2;
932 }
933 }
934
935
942 public function deleteLine($lineid)
943 {
944 global $user;
945
946 if ($this->status == 0) {
947 $line = new SupplierProposalLine($this->db);
948
949 // For triggers
950 $line->fetch($lineid);
951
952 if ($this->id > 0 && (int) $line->fk_supplier_proposal !== (int) $this->id) {
953 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
954 return -1;
955 }
956
957 if ($line->delete($user) > 0) {
958 $this->update_price(1);
959
960 return 1;
961 } else {
962 return -1;
963 }
964 } else {
965 return -2;
966 }
967 }
968
969
978 public function create($user, $notrigger = 0)
979 {
980 global $conf, $mysoc, $hookmanager;
981 $error = 0;
982
983 $now = dol_now();
984
985 dol_syslog(get_class($this)."::create");
986
987 // Check parameters
988 $result = $this->fetch_thirdparty();
989 if ($result < 0) {
990 $this->error = "Failed to fetch company";
991 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
992 return -3;
993 }
994 if (!empty($this->ref)) { // We check that ref is not already used
995 $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
996 if ($result > 0) {
997 $this->error = 'ErrorRefAlreadyExists';
998 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
999 $this->db->rollback();
1000 return -1;
1001 }
1002 }
1003
1004 // Set tmp vars
1005 $delivery_date = $this->delivery_date;
1006
1007 // Multicurrency
1008 if (!empty($this->multicurrency_code)) {
1009 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now);
1010 }
1011 if (empty($this->fk_multicurrency)) {
1012 $this->multicurrency_code = getDolCurrency();
1013 $this->fk_multicurrency = 0;
1014 $this->multicurrency_tx = 1;
1015 }
1016
1017 $this->db->begin();
1018
1019 // Insert into database
1020 $sql = "INSERT INTO ".MAIN_DB_PREFIX."supplier_proposal (";
1021 $sql .= "fk_soc";
1022 $sql .= ", price";
1023 $sql .= ", total_tva";
1024 $sql .= ", total_ttc";
1025 $sql .= ", datec";
1026 $sql .= ", ref";
1027 $sql .= ", fk_user_author";
1028 $sql .= ", note_private";
1029 $sql .= ", note_public";
1030 $sql .= ", model_pdf";
1031 $sql .= ", fk_cond_reglement";
1032 $sql .= ", deposit_percent";
1033 $sql .= ", fk_mode_reglement";
1034 $sql .= ", fk_account";
1035 $sql .= ", date_livraison";
1036 $sql .= ", fk_shipping_method";
1037 $sql .= ", fk_projet";
1038 $sql .= ", entity";
1039 $sql .= ", fk_multicurrency";
1040 $sql .= ", multicurrency_code";
1041 $sql .= ", multicurrency_tx";
1042 $sql .= ") ";
1043 $sql .= " VALUES (";
1044 $sql .= ((int) $this->socid);
1045 $sql .= ", 0";
1046 $sql .= ", 0";
1047 $sql .= ", 0";
1048 $sql .= ", '".$this->db->idate($now)."'";
1049 $sql .= ", '(PROV)'";
1050 $sql .= ", ".($user->id > 0 ? ((int) $user->id) : "null");
1051 $sql .= ", '".$this->db->escape($this->note_private)."'";
1052 $sql .= ", '".$this->db->escape($this->note_public)."'";
1053 $sql .= ", '".$this->db->escape($this->model_pdf)."'";
1054 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : 'NULL');
1055 $sql .= ", ".(!empty($this->deposit_percent) ? "'" . $this->db->escape($this->deposit_percent) . "'" : 'NULL');
1056 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : 'NULL');
1057 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1058 $sql .= ", ".(isDolTms($delivery_date) ? "'".$this->db->idate($delivery_date)."'" : "null");
1059 $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
1060 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1061 $sql .= ", ".((int) $conf->entity);
1062 $sql .= ", ".((int) $this->fk_multicurrency);
1063 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1064 $sql .= ", ".((float) $this->multicurrency_tx);
1065 $sql .= ")";
1066
1067 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1068 $resql = $this->db->query($sql);
1069 if ($resql) {
1070 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."supplier_proposal");
1071
1072 if ($this->id) {
1073 $this->ref = '(PROV'.$this->id.')';
1074 $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
1075
1076 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1077 $resql = $this->db->query($sql);
1078 if (!$resql) {
1079 $error++;
1080 }
1081
1082 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1083 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1084 }
1085
1086 // Add object linked
1087 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
1088 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1089 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, ...))
1090 foreach ($tmp_origin_id as $origin_id) {
1091 $ret = $this->add_object_linked($origin, $origin_id);
1092 if (!$ret) {
1093 dol_print_error($this->db);
1094 $error++;
1095 }
1096 }
1097 }
1098 }
1099 }
1100
1101 /*
1102 * Insert products details into database
1103 */
1104 if (!$error) {
1105 $fk_parent_line = 0;
1106 $num = count($this->lines);
1107
1108 for ($i = 0; $i < $num; $i++) {
1109 // Reset fk_parent_line for no child products and special product
1110 if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
1111 $fk_parent_line = 0;
1112 }
1113
1114 $result = $this->addline(
1115 $this->lines[$i]->desc,
1116 $this->lines[$i]->subprice,
1117 $this->lines[$i]->qty,
1118 $this->lines[$i]->tva_tx,
1119 $this->lines[$i]->localtax1_tx,
1120 $this->lines[$i]->localtax2_tx,
1121 $this->lines[$i]->fk_product,
1122 $this->lines[$i]->remise_percent,
1123 'HT',
1124 0,
1125 0,
1126 $this->lines[$i]->product_type,
1127 $this->lines[$i]->rang,
1128 $this->lines[$i]->special_code,
1129 $fk_parent_line,
1130 $this->lines[$i]->fk_fournprice,
1131 $this->lines[$i]->pa_ht,
1132 empty($this->lines[$i]->label) ? '' : $this->lines[$i]->label, // deprecated
1133 $this->lines[$i]->array_options,
1134 $this->lines[$i]->ref_fourn,
1135 $this->lines[$i]->fk_unit,
1136 'supplier_proposal',
1137 $this->lines[$i]->rowid
1138 );
1139
1140 if ($result < 0) {
1141 $error++;
1142 $this->error = $this->db->error;
1143 dol_print_error($this->db);
1144 break;
1145 }
1146 // Defined the new fk_parent_line
1147 if ($result > 0 && $this->lines[$i]->product_type == 9) {
1148 $fk_parent_line = $result;
1149 }
1150 }
1151 }
1152
1153 if (!$error) {
1154 // Update denormalized data
1155 $resql = $this->update_price(1);
1156 if ($resql) {
1157 $action = 'update';
1158
1159 // Actions on extra fields
1160 if (!$error) {
1161 $result = $this->insertExtraFields();
1162 if ($result < 0) {
1163 $error++;
1164 }
1165 }
1166
1167 if (!$error && !$notrigger) {
1168 // Call trigger
1169 $result = $this->call_trigger('PROPOSAL_SUPPLIER_CREATE', $user);
1170 if ($result < 0) {
1171 $error++;
1172 }
1173 // End call triggers
1174 }
1175 } else {
1176 $this->error = $this->db->lasterror();
1177 $error++;
1178 }
1179 }
1180 } else {
1181 $this->error = $this->db->lasterror();
1182 $error++;
1183 }
1184
1185 if (!$error) {
1186 $this->db->commit();
1187 dol_syslog(get_class($this)."::create done id=".$this->id);
1188 return $this->id;
1189 } else {
1190 $this->db->rollback();
1191 return -2;
1192 }
1193 } else {
1194 $this->error = $this->db->lasterror();
1195 $this->db->rollback();
1196 return -1;
1197 }
1198 }
1199
1207 public function createFromClone(User $user, $fromid = 0)
1208 {
1209 global $hookmanager;
1210
1211 $error = 0;
1212 $now = dol_now();
1213
1214 $this->db->begin();
1215
1216 // get extrafields so they will be clone
1217 foreach ($this->lines as $line) {
1218 $line->fetch_optionals();
1219 }
1220
1221 // Load source object
1222 $objFrom = clone $this;
1223
1224 $objsoc = new Societe($this->db);
1225
1226 // Change socid if needed
1227 if (!empty($fromid) && $fromid != $this->socid) {
1228 if ($objsoc->fetch($fromid) > 0) {
1229 $this->socid = $objsoc->id;
1230 $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1231 $this->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : 0);
1232 $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1233 unset($this->fk_project);
1234 }
1235
1236 // TODO Change product price if multi-prices
1237 } else {
1238 $objsoc->fetch($this->socid);
1239 }
1240
1241 $this->id = 0;
1242 $this->status = 0;
1243 $this->statut = 0;
1244
1245 if (!getDolGlobalString('SUPPLIER_PROPOSAL_ADDON') || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/" . getDolGlobalString('SUPPLIER_PROPOSAL_ADDON').".php")) {
1246 $this->error = 'ErrorSetupNotComplete';
1247 return -1;
1248 }
1249
1250 // Clear fields
1251 $this->user_author_id = $user->id;
1252 $this->user_validation_id = 0;
1253 $this->date = $now;
1254
1255 // Set ref
1256 require_once DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/" . getDolGlobalString('SUPPLIER_PROPOSAL_ADDON').'.php';
1257 $obj = getDolGlobalString('SUPPLIER_PROPOSAL_ADDON');
1258 $modSupplierProposal = new $obj();
1259 '@phan-var-force ModeleNumRefSupplierProposal $modSupplierProposal';
1260 $this->ref = $modSupplierProposal->getNextValue($objsoc, $this);
1261
1262 // Create clone
1263 $this->context['createfromclone'] = 'createfromclone';
1264 $result = $this->create($user);
1265 if ($result < 0) {
1266 $error++;
1267 }
1268
1269 if (!$error) {
1270 // Hook of thirdparty module
1271 if (is_object($hookmanager)) {
1272 $parameters = array('objFrom' => $objFrom);
1273 $action = '';
1274 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1275 if ($reshook < 0) {
1276 $this->setErrorsFromObject($hookmanager);
1277 $error++;
1278 }
1279 }
1280 }
1281
1282 unset($this->context['createfromclone']);
1283
1284 // End
1285 if (!$error) {
1286 $this->db->commit();
1287 return $this->id;
1288 } else {
1289 $this->db->rollback();
1290 return -1;
1291 }
1292 }
1293
1301 public function fetch($rowid, $ref = '')
1302 {
1303 $sql = "SELECT p.rowid, p.entity, p.ref, p.fk_soc as socid";
1304 $sql .= ", p.total_ttc, p.total_tva, p.localtax1, p.localtax2, p.total_ht";
1305 $sql .= ", p.datec, GREATEST(p.tms, COALESCE(pef.tms, p.tms)) as date_modification";
1306 $sql .= ", p.date_valid as datev";
1307 $sql .= ", p.date_livraison as delivery_date";
1308 $sql .= ", p.model_pdf, p.extraparams";
1309 $sql .= ", p.note_private, p.note_public";
1310 $sql .= ", p.fk_projet as fk_project, p.fk_statut as status";
1311 $sql .= ", p.fk_user_author, p.fk_user_modif, p.fk_user_valid, p.fk_user_cloture";
1312 $sql .= ", p.fk_cond_reglement";
1313 $sql .= ", p.fk_mode_reglement";
1314 $sql .= ', p.fk_account';
1315 $sql .= ", p.fk_shipping_method";
1316 $sql .= ", p.last_main_doc";
1317 $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
1318 $sql .= ", c.label as statut_label";
1319 $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc, p.deposit_percent";
1320 $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
1321 $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p";
1322 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."supplier_proposal_extrafields as pef ON pef.fk_object=p.rowid";
1323 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id';
1324 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid';
1325 $sql .= " WHERE p.fk_statut = c.id";
1326 $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
1327 if ($ref) {
1328 $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
1329 } else {
1330 $sql .= " AND p.rowid = ".((int) $rowid);
1331 }
1332
1333 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1334 $resql = $this->db->query($sql);
1335 if ($resql) {
1336 if ($this->db->num_rows($resql)) {
1337 $obj = $this->db->fetch_object($resql);
1338
1339 $this->id = $obj->rowid;
1340 $this->entity = $obj->entity;
1341
1342 $this->ref = $obj->ref;
1343 $this->total_ht = $obj->total_ht;
1344 $this->total_tva = $obj->total_tva;
1345 $this->total_localtax1 = $obj->localtax1;
1346 $this->total_localtax2 = $obj->localtax2;
1347 $this->total_ttc = $obj->total_ttc;
1348 $this->socid = $obj->socid;
1349 $this->fk_project = $obj->fk_project;
1350 $this->model_pdf = $obj->model_pdf;
1351 $this->note = $obj->note_private; // TODO deprecated
1352 $this->note_private = $obj->note_private;
1353 $this->note_public = $obj->note_public;
1354 $this->statut = (int) $obj->status;
1355 $this->status = (int) $obj->status;
1356 $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
1357 $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
1358 $this->date_creation = $this->db->jdate($obj->datec); // Creation date
1359 $this->date_modification = $this->db->jdate($obj->date_modification); // Modification date
1360 $this->date = $this->date_creation;
1361 $this->date_validation = $this->db->jdate($obj->datev); // Validation date
1362 $this->delivery_date = $this->db->jdate($obj->delivery_date);
1363 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
1364
1365 $this->last_main_doc = $obj->last_main_doc;
1366 $this->mode_reglement_id = $obj->fk_mode_reglement;
1367 $this->mode_reglement_code = $obj->mode_reglement_code;
1368 $this->mode_reglement = $obj->mode_reglement;
1369 $this->deposit_percent = $obj->deposit_percent;
1370 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
1371 $this->cond_reglement_id = $obj->fk_cond_reglement;
1372 $this->cond_reglement_code = $obj->cond_reglement_code;
1373 $this->cond_reglement = $obj->cond_reglement;
1374 $this->cond_reglement_label = $obj->cond_reglement;
1375 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
1376
1377 $this->extraparams = (array) (!empty($obj->extraparams) ? json_decode($obj->extraparams, true) : array());
1378
1379 $this->user_author_id = $obj->fk_user_author;
1380 $this->user_modification_id = $obj->fk_user_modif;
1381 $this->user_validation_id = $obj->fk_user_valid;
1382 $this->user_closing_id = $obj->fk_user_cloture;
1383
1384 // Multicurrency
1385 $this->fk_multicurrency = $obj->fk_multicurrency;
1386 $this->multicurrency_code = $obj->multicurrency_code;
1387 $this->multicurrency_tx = $obj->multicurrency_tx;
1388 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
1389 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
1390 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
1391
1392 $this->db->free($resql);
1393
1394 // Retrieve all extrafield
1395 // fetch optionals attributes and labels
1396 $this->fetch_optionals();
1397
1398 $this->lines = array();
1399
1400 // Lines of supplier proposals
1401 $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,";
1402 $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,";
1403 $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
1404 $sql .= ' d.ref_fourn as ref_produit_fourn, d.extraparams,';
1405 $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit';
1406 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d";
1407 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
1408 $sql .= " WHERE d.fk_supplier_proposal = ".((int) $this->id);
1409 $sql .= " ORDER by d.rang";
1410
1411 $result = $this->db->query($sql);
1412 if ($result) {
1413 $num = $this->db->num_rows($result);
1414 $i = 0;
1415
1416 while ($i < $num) {
1417 $objp = $this->db->fetch_object($result);
1418
1419 $line = new SupplierProposalLine($this->db);
1420
1421 $line->rowid = $objp->rowid; // deprecated
1422 $line->id = $objp->rowid;
1423 $line->fk_supplier_proposal = $objp->fk_supplier_proposal;
1424 $line->fk_parent_line = $objp->fk_parent_line;
1425 $line->product_type = $objp->product_type;
1426 $line->label = $objp->custom_label;
1427 $line->desc = $objp->description; // Description of the line
1428 $line->qty = $objp->qty;
1429 $line->tva_tx = $objp->tva_tx;
1430 $line->localtax1_tx = $objp->localtax1_tx;
1431 $line->localtax2_tx = $objp->localtax2_tx;
1432 $line->subprice = $objp->subprice;
1433 $line->fk_remise_except = $objp->fk_remise_except;
1434 $line->remise_percent = $objp->remise_percent;
1435
1436 $line->info_bits = $objp->info_bits;
1437 $line->total_ht = $objp->total_ht;
1438 $line->total_tva = $objp->total_tva;
1439 $line->total_localtax1 = $objp->total_localtax1;
1440 $line->total_localtax2 = $objp->total_localtax2;
1441 $line->total_ttc = $objp->total_ttc;
1442 $line->fk_fournprice = $objp->fk_fournprice;
1443 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
1444 $line->pa_ht = $marginInfos[0];
1445 $line->marge_tx = $marginInfos[1];
1446 $line->marque_tx = $marginInfos[2];
1447 $line->special_code = $objp->special_code;
1448 $line->rang = $objp->rang;
1449
1450 $line->fk_product = $objp->fk_product;
1451
1452 $line->ref = $objp->product_ref; // deprecated
1453 $line->product_ref = $objp->product_ref;
1454 $line->libelle = $objp->product_label; // deprecated
1455 $line->product_label = $objp->product_label;
1456 $line->product_desc = $objp->product_desc; // Description produit
1457 $line->fk_product_type = $objp->fk_product_type;
1458
1459 $line->ref_fourn = $objp->ref_produit_fourn;
1460
1461 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
1462
1463 // Multicurrency
1464 $line->fk_multicurrency = $objp->fk_multicurrency;
1465 $line->multicurrency_code = $objp->multicurrency_code;
1466 $line->multicurrency_subprice = $objp->multicurrency_subprice;
1467 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
1468 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
1469 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
1470 $line->fk_unit = $objp->fk_unit;
1471
1472 $line->fetch_optionals();
1473
1474 $this->lines[$i] = $line;
1475
1476 $i++;
1477 }
1478 $this->db->free($result);
1479 } else {
1480 $this->error = $this->db->error();
1481 return -1;
1482 }
1483
1484 return 1;
1485 }
1486
1487 $this->error = "Record Not Found";
1488 return 0;
1489 } else {
1490 $this->error = $this->db->error();
1491 return -1;
1492 }
1493 }
1494
1502 public function update($user, $notrigger = 0)
1503 {
1504 $error = 0;
1505
1506 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET";
1507 $sql .= " fk_projet = ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1508 $sql .= ", fk_cond_reglement = ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
1509 $sql .= ", fk_mode_reglement = ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
1510 $sql .= ", fk_account = ".($this->fk_account > 0 ? ((int) $this->fk_account) : "null");
1511 $sql .= ", fk_shipping_method = ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : "null");
1512 $sql .= ", date_livraison = ".($this->delivery_date ? "'".$this->db->idate($this->delivery_date)."'" : "null");
1513 $sql .= ", note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
1514 $sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
1515 $sql .= ", model_pdf = ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
1516 $sql .= ", fk_user_modif = ".((int) $user->id);
1517 $sql .= " WHERE rowid = ".((int) $this->id);
1518
1519 $this->db->begin();
1520
1521 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1522 $resql = $this->db->query($sql);
1523 if (!$resql) {
1524 $error++;
1525 $this->errors[] = "Error ".$this->db->lasterror();
1526 }
1527
1528 if (!$error) {
1529 $result = $this->insertExtraFields();
1530 if ($result < 0) {
1531 $error++;
1532 }
1533 }
1534
1535 if (!$error && !$notrigger) {
1536 // Call trigger
1537 $result = $this->call_trigger('PROPOSAL_SUPPLIER_MODIFY', $user);
1538 if ($result < 0) {
1539 $error++;
1540 }
1541 // End call triggers
1542 }
1543
1544 if ($error) {
1545 $this->error = implode(', ', $this->errors);
1546 $this->db->rollback();
1547 return -1 * $error;
1548 }
1549
1550 $this->db->commit();
1551 return 1;
1552 }
1553
1561 public function valid($user, $notrigger = 0)
1562 {
1563 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1564
1565 global $conf;
1566
1567 $error = 0;
1568 $now = dol_now();
1569
1570 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('supplier_proposal', 'creer'))
1571 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('supplier_proposal', 'validate_advance'))) {
1572 $this->db->begin();
1573
1574 // Numbering module definition
1575 $soc = new Societe($this->db);
1576 $result = $soc->fetch($this->socid);
1577
1578 if ($result < 0) {
1579 return -1;
1580 }
1581 if (!getDolGlobalBool('SUPPLIER_PROPOSAL_NOCHECK_ONBUY_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines('onbuy')) {
1582 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
1583 return -1;
1584 }
1585 // Define new ref
1586 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1587 $num = $this->getNextNumRef($soc);
1588 } else {
1589 $num = (string) $this->ref;
1590 }
1591 $this->newref = dol_sanitizeFileName($num);
1592
1593 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
1594 $sql .= " SET ref = '".$this->db->escape($num)."',";
1595 $sql .= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".((int) $user->id);
1596 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
1597
1598 dol_syslog(get_class($this)."::valid", LOG_DEBUG);
1599 $resql = $this->db->query($sql);
1600 if (!$resql) {
1601 dol_print_error($this->db);
1602 $error++;
1603 }
1604
1605 // Trigger calls
1606 if (!$error && !$notrigger) {
1607 // Call trigger
1608 $result = $this->call_trigger('PROPOSAL_SUPPLIER_VALIDATE', $user);
1609 if ($result < 0) {
1610 $error++;
1611 }
1612 // End call triggers
1613 }
1614
1615 if (!$error) {
1616 $this->oldref = $this->ref;
1617
1618 // Rename directory if dir was a temporary ref
1619 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1620 // Now we rename also files into index
1621 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'";
1622 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1623 $resql = $this->db->query($sql);
1624 if (!$resql) {
1625 $error++;
1626 $this->error = $this->db->lasterror();
1627 }
1628 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'";
1629 $sql .= " WHERE filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1630 $resql = $this->db->query($sql);
1631 if (!$resql) {
1632 $error++;
1633 $this->error = $this->db->lasterror();
1634 }
1635
1636 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1637 $oldref = dol_sanitizeFileName($this->ref);
1638 $newref = dol_sanitizeFileName($num);
1639 $dirsource = $conf->supplier_proposal->dir_output.'/'.$oldref;
1640 $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref;
1641 if (!$error && file_exists($dirsource)) {
1642 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
1643 if (@rename($dirsource, $dirdest)) {
1644 dol_syslog("Rename ok");
1645 // Rename docs starting with $oldref with $newref
1646 $listoffiles = dol_dir_list($conf->supplier_proposal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1647 foreach ($listoffiles as $fileentry) {
1648 $dirsource = $fileentry['name'];
1649 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1650 $dirsource = $fileentry['path'].'/'.$dirsource;
1651 $dirdest = $fileentry['path'].'/'.$dirdest;
1652 @rename($dirsource, $dirdest);
1653 }
1654 }
1655 }
1656 }
1657
1658 $this->ref = $num;
1659 $this->statut = self::STATUS_VALIDATED;
1661 $this->user_validation_id = $user->id;
1662 $this->datev = $now;
1663 $this->date_validation = $now;
1664
1665 if (getDolGlobalString('SUPPLIER_PROPOSAL_AUTOADD_USER_CONTACT')) {
1666 $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
1667 if ($result < 0 && $result != -2) { // -2 means already exists
1668 $error++;
1669 }
1670 }
1671
1672 $this->db->commit();
1673 return 1;
1674 } else {
1675 $this->db->rollback();
1676 return -1;
1677 }
1678 } else {
1679 dol_syslog("You don't have permission to validate supplier proposal", LOG_WARNING);
1680 return -2;
1681 }
1682 }
1683
1684 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1693 public function set_date_livraison($user, $delivery_date)
1694 {
1695 // phpcs:enable
1696 return $this->setDeliveryDate($user, $delivery_date);
1697 }
1698
1706 public function setDeliveryDate($user, $delivery_date)
1707 {
1708 if ($user->hasRight('supplier_proposal', 'creer')) {
1709 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal ";
1710 $sql .= " SET date_livraison = ".(isDolTms($delivery_date) ? "'".$this->db->idate($delivery_date)."'" : 'null');
1711 $sql .= " WHERE rowid = ".((int) $this->id);
1712
1713 if ($this->db->query($sql)) {
1714 $this->delivery_date = $delivery_date;
1715 return 1;
1716 } else {
1717 $this->error = $this->db->error();
1718 dol_syslog(get_class($this)."::setDeliveryDate Erreur SQL");
1719 return -1;
1720 }
1721 }
1722 return 0;
1723 }
1724
1725
1735 public function reopen($user, $status, $note = '', $notrigger = 0)
1736 {
1737 $error = 0;
1738
1739 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
1740 $sql .= " SET fk_statut = ".((int) $status).",";
1741 if (!empty($note)) {
1742 $sql .= " note_private = '".$this->db->escape($note)."',";
1743 }
1744 $sql .= " date_cloture = NULL, fk_user_cloture = NULL";
1745 $sql .= " WHERE rowid = ".((int) $this->id);
1746
1747 $this->db->begin();
1748
1749 dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
1750 $resql = $this->db->query($sql);
1751 if (!$resql) {
1752 $error++;
1753 $this->errors[] = "Error ".$this->db->lasterror();
1754 }
1755 if (!$error) {
1756 if (!$notrigger) {
1757 // Call trigger
1758 $result = $this->call_trigger('PROPOSAL_SUPPLIER_REOPEN', $user);
1759 if ($result < 0) {
1760 $error++;
1761 }
1762 // End call triggers
1763 }
1764 }
1765
1766 // Commit or rollback
1767 if ($error) {
1768 if (!empty($this->errors)) {
1769 foreach ($this->errors as $errmsg) {
1770 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1771 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1772 }
1773 }
1774 $this->db->rollback();
1775 return -1 * $error;
1776 } else {
1777 $this->statut = $status;
1778 $this->status = $status;
1779
1780 $this->db->commit();
1781 return 1;
1782 }
1783 }
1784
1785
1794 public function cloture($user, $status, $note)
1795 {
1796 global $langs, $conf;
1797 $hidedetails = 0;
1798 $hidedesc = 0;
1799 $hideref = 0;
1800
1801 $error = 0;
1802 $now = dol_now();
1803
1804 $this->db->begin();
1805
1806 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
1807 $sql .= " SET fk_statut = ".((int) $status).", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".((int) $user->id);
1808 $sql .= " WHERE rowid = ".((int) $this->id);
1809
1810 $resql = $this->db->query($sql);
1811 if ($resql) {
1812 $this->statut = $status;
1813 $this->status = $status;
1814
1815 $modelpdf = getDolGlobalString('SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED', (empty($this->model_pdf) ? '' : $this->model_pdf));
1816 $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED';
1817
1818 if ($status == 2) {
1819 $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED';
1820 $modelpdf = getDolGlobalString('SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL', (empty($this->model_pdf) ? '' : $this->model_pdf));
1821
1822 if (getDolGlobalString('SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL')) { // TODO This option was not tested correctly. Error if product ref does not exists
1823 $result = $this->updateOrCreatePriceFournisseur($user);
1824 }
1825 }
1826 if ($status == 4) {
1827 $triggerName = 'PROPOSAL_SUPPLIER_CLASSIFY_BILLED';
1828 }
1829
1830 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1831 // Define output language
1832 $outputlangs = $langs;
1833 if (getDolGlobalInt('MAIN_MULTILANGS')) {
1834 $outputlangs = new Translate("", $conf);
1835 $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
1836 $outputlangs->setDefaultLang($newlang);
1837 }
1838
1839 $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1840 }
1841
1842 // Call trigger
1843 $result = $this->call_trigger($triggerName, $user);
1844 if ($result < 0) {
1845 $error++;
1846 }
1847 // End call triggers
1848
1849 if (!$error) {
1850 $this->db->commit();
1851 return 1;
1852 } else {
1853 $this->db->rollback();
1854 return -1;
1855 }
1856 } else {
1857 $this->error = $this->db->lasterror();
1858 $this->errors[] = $this->db->lasterror();
1859 $this->db->rollback();
1860 return -1;
1861 }
1862 }
1863
1870 public function updateOrCreatePriceFournisseur($user)
1871 {
1872 dol_syslog(get_class($this)."::updateOrCreatePriceFournisseur", LOG_DEBUG);
1873
1874 foreach ($this->lines as $product) {
1875 if ($product->subprice <= 0) {
1876 continue;
1877 }
1878 $productsupplier = new ProductFournisseur($this->db);
1879
1880 $multicurrency_tx = 1;
1881 $fk_multicurrency = 0;
1882
1883 if (empty($this->thirdparty)) {
1884 $this->fetch_thirdparty();
1885 }
1886
1887 $ref_fourn = $product->ref_fourn;
1888 if (empty($ref_fourn)) {
1889 $ref_fourn = $product->ref_supplier;
1890 }
1891 if (isModEnabled("multicurrency") && !empty($product->multicurrency_code)) {
1892 list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code);
1893 }
1894 $productsupplier->id = $product->fk_product;
1895
1896 $productsupplier->update_buyprice($product->qty, $product->total_ht, $user, 'HT', $this->thirdparty, 0, $ref_fourn, $product->tva_tx, 0, 0, 0, $product->info_bits, 0, '', array(), '', $product->multicurrency_total_ht, 'HT', $multicurrency_tx, $product->multicurrency_code, '', '', 0);
1897 }
1898
1899 return 1;
1900 }
1901
1910 public function updatePriceFournisseur($idProductFournPrice, $product, $user)
1911 {
1912 $price = price2num($product->subprice * $product->qty, 'MU');
1913 $unitPrice = price2num($product->subprice, 'MU');
1914
1915 $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_fournisseur_price SET '.(!empty($product->ref_fourn) ? 'ref_fourn = "'.$this->db->escape($product->ref_fourn).'", ' : '').' price ='.((float) $price).', unitprice ='.((float) $unitPrice).' WHERE rowid = '.((int) $idProductFournPrice);
1916
1917 $resql = $this->db->query($sql);
1918 if (!$resql) {
1919 $this->error = $this->db->error();
1920 $this->db->rollback();
1921 return -1;
1922 }
1923 return 1;
1924 }
1925
1933 public function createPriceFournisseur($product, $user)
1934 {
1935 $price = price2num($product->subprice * $product->qty, 'MU');
1936 $qty = price2num($product->qty);
1937 $unitPrice = price2num($product->subprice, 'MU');
1938
1939 $now = dol_now();
1940
1941 $sanitized_values = array(
1942 "'".$this->db->idate($now)."'",
1943 (int) $product->fk_product,
1944 (int) $this->thirdparty->id,
1945 "'".$this->db->escape($product->ref_fourn)."'",
1946 (float) $price,
1947 (float) $qty,
1948 (float) $unitPrice,
1949 (float) $product->tva_tx,
1950 (int) $user->id
1951 );
1952 if (isModEnabled("multicurrency")) {
1953 if (!empty($product->multicurrency_code)) {
1954 include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
1955 $multicurrency = new MultiCurrency($this->db); //need to fetch because empty fk_multicurrency and rate
1956 $multicurrency->fetch(0, $product->multicurrency_code);
1957 if (!empty($multicurrency->id)) {
1958 $sanitized_values[] = (int) $multicurrency->id;
1959 $sanitized_values[] = "'".$this->db->escape($product->multicurrency_code)."'";
1960 $sanitized_values[] = (float) $product->multicurrency_subprice;
1961 $sanitized_values[] = (float) $product->multicurrency_total_ht;
1962 $sanitized_values[] = (float) $multicurrency->rate->rate;
1963 } else {
1964 for ($i = 0; $i < 5; $i++) {
1965 $sanitized_values[] = 'NULL';
1966 }
1967 }
1968 }
1969 }
1970
1971 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_fournisseur_price ';
1972 $sql .= '(datec, fk_product, fk_soc, ref_fourn, price, quantity, unitprice, tva_tx, fk_user';
1973 if (isModEnabled("multicurrency") && !empty($product->multicurrency_code)) {
1974 $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx';
1975 }
1976 $sql .= ') VALUES ('.implode(',', $sanitized_values).')';
1977
1978 $resql = $this->db->query($sql);
1979 if (!$resql) {
1980 $this->error = $this->db->error();
1981 $this->db->rollback();
1982 return -1;
1983 }
1984 return 1;
1985 }
1986
1987 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1994 public function setDraft($user)
1995 {
1996 // phpcs:enable
1997 $error = 0;
1998
1999 if ($this->status == self::STATUS_DRAFT) {
2000 dol_syslog(get_class($this)."::setDraft already draft status", LOG_WARNING);
2001 return 0;
2002 }
2003
2004 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
2005 $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
2006 $sql .= " WHERE rowid = ".((int) $this->id);
2007
2008 if ($this->db->query($sql)) {
2009 if (!$error) {
2010 $this->oldcopy = clone $this;
2011 }
2012
2013 if (!$error) {
2014 // Call trigger
2015 $result = $this->call_trigger('PROPOSAL_SUPPLIER_UNVALIDATE', $user);
2016 if ($result < 0) {
2017 $error++;
2018 }
2019 }
2020
2021 if (!$error) {
2022 $this->status = self::STATUS_DRAFT;
2023 $this->statut = self::STATUS_DRAFT; // deprecated
2024 $this->db->commit();
2025 return 1;
2026 } else {
2027 $this->db->rollback();
2028 return -1;
2029 }
2030 } else {
2031 return -1;
2032 }
2033 }
2034
2035
2036 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2050 public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datec', $sortorder = 'DESC')
2051 {
2052 // phpcs:enable
2053 global $user;
2054
2055 $ga = array();
2056
2057 $search_sale = 0;
2058 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2059 $search_sale = $user->id;
2060 }
2061
2062 $sql = "SELECT s.rowid, s.nom as name, s.client,";
2063 $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
2064 $sql .= " p.datep as dp, p.fin_validite as datelimite";
2065 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c";
2066 $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")";
2067 $sql .= " AND p.fk_soc = s.rowid";
2068 $sql .= " AND p.fk_statut = c.id";
2069 if ($socid) {
2070 $sql .= " AND s.rowid = ".((int) $socid);
2071 }
2072 if ($draft) {
2073 $sql .= " AND p.fk_statut = 0";
2074 }
2075 if ($notcurrentuser > 0) {
2076 $sql .= " AND p.fk_user_author <> ".((int) $user->id);
2077 }
2078 // Search on sale representative
2079 if ($search_sale && $search_sale != '-1') {
2080 if ($search_sale == -2) {
2081 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
2082 } elseif ($search_sale > 0) {
2083 $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).")";
2084 }
2085 }
2086 $sql .= $this->db->order($sortfield, $sortorder);
2087 $sql .= $this->db->plimit($limit, $offset);
2088
2089 $result = $this->db->query($sql);
2090 if ($result) {
2091 $num = $this->db->num_rows($result);
2092 if ($num) {
2093 $i = 0;
2094 while ($i < $num) {
2095 $obj = $this->db->fetch_object($result);
2096
2097 if ($shortlist == 1) {
2098 $ga[$obj->supplier_proposalid] = $obj->ref;
2099 } elseif ($shortlist == 2) {
2100 $ga[$obj->supplier_proposalid] = $obj->ref.' ('.$obj->name.')';
2101 } else {
2102 $ga[$i]['id'] = $obj->supplier_proposalid;
2103 $ga[$i]['ref'] = $obj->ref;
2104 $ga[$i]['name'] = $obj->name;
2105 }
2106
2107 $i++;
2108 }
2109 }
2110 return $ga;
2111 } else {
2112 dol_print_error($this->db);
2113 return -1;
2114 }
2115 }
2116
2124 public function delete($user, $notrigger = 0)
2125 {
2126 global $conf;
2127 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2128
2129 $error = 0;
2130
2131 $this->db->begin();
2132
2133 if (!$notrigger) {
2134 // Call trigger
2135 $result = $this->call_trigger('PROPOSAL_SUPPLIER_DELETE', $user);
2136 if ($result < 0) {
2137 $error++;
2138 }
2139 // End call triggers
2140 }
2141
2142 // Remove linked categories.
2143 if (!$error) {
2144 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_supplier_proposal";
2145 $sql .= " WHERE fk_supplier_proposal = ".((int) $this->id);
2146
2147 $result = $this->db->query($sql);
2148 if (!$result) {
2149 $error++;
2150 $this->error = $this->db->lasterror();
2151 $this->errors[] = $this->error;
2152 }
2153 }
2154
2155 if (!$error) {
2156 $sanitized_main = MAIN_DB_PREFIX.'supplier_proposaldet';
2157 $sanitized_ef = $sanitized_main."_extrafields";
2158 $sqlef = "DELETE FROM $sanitized_ef WHERE fk_object IN (SELECT rowid FROM $sanitized_main WHERE fk_supplier_proposal = ".((int) $this->id).")";
2159 $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".((int) $this->id);
2160 if ($this->db->query($sql)) {
2161 $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE rowid = ".((int) $this->id);
2162 if ($this->db->query($sqlef) && $this->db->query($sql)) {
2163 // Delete linked object
2164 $res = $this->deleteObjectLinked();
2165 if ($res < 0) {
2166 $error++;
2167 }
2168
2169 if (!$error) {
2170 // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
2171 $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
2172 $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
2173
2174 // We remove directory
2175 $ref = dol_sanitizeFileName($this->ref);
2176 if ($conf->supplier_proposal->dir_output && !empty($this->ref)) {
2177 $dir = $conf->supplier_proposal->dir_output."/".$ref;
2178 $file = $dir."/".$ref.".pdf";
2179 if (file_exists($file)) {
2180 dol_delete_preview($this);
2181
2182 if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
2183 $this->error = 'ErrorFailToDeleteFile';
2184 $this->errors = array('ErrorFailToDeleteFile');
2185 $this->db->rollback();
2186 return 0;
2187 }
2188 }
2189 if (file_exists($dir)) {
2190 $res = @dol_delete_dir_recursive($dir);
2191 if (!$res) {
2192 $this->error = 'ErrorFailToDeleteDir';
2193 $this->errors = array('ErrorFailToDeleteDir');
2194 $this->db->rollback();
2195 return 0;
2196 }
2197 }
2198 }
2199 }
2200
2201 // Removed extrafields
2202 if (!$error) {
2203 $result = $this->deleteExtraFields();
2204 if ($result < 0) {
2205 $error++;
2206 $errorflag = -4;
2207 dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
2208 }
2209 }
2210
2211 if (!$error) {
2212 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
2213 $this->db->commit();
2214 return 1;
2215 } else {
2216 $this->error = $this->db->lasterror();
2217 $this->db->rollback();
2218 return 0;
2219 }
2220 } else {
2221 $this->error = $this->db->lasterror();
2222 $this->db->rollback();
2223 return -3;
2224 }
2225 } else {
2226 $this->error = $this->db->lasterror();
2227 $this->db->rollback();
2228 return -2;
2229 }
2230 } else {
2231 $this->db->rollback();
2232 return -1;
2233 }
2234 }
2235
2242 public function info($id)
2243 {
2244 $sql = "SELECT c.rowid, GREATEST(c.tms, COALESCE(cef.tms, c.tms)) as date_modification,";
2245 $sql .= " c.datec as date_creation, c.date_valid as date_validation, c.date_cloture as date_closure,";
2246 $sql .= " c.fk_user_author, c.fk_user_modif, c.fk_user_valid, c.fk_user_cloture";
2247 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c";
2248 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."supplier_proposal_extrafields as cef ON cef.fk_object=c.rowid";
2249 $sql .= " WHERE c.rowid = ".((int) $id);
2250
2251 $result = $this->db->query($sql);
2252
2253 if ($result) {
2254 if ($this->db->num_rows($result)) {
2255 $obj = $this->db->fetch_object($result);
2256
2257 $this->id = $obj->rowid;
2258
2259 $this->date_creation = $this->db->jdate($obj->date_creation);
2260 $this->date_modification = empty($obj->date_modification) ? '' : $this->db->jdate($obj->date_modification);
2261 $this->date_validation = $this->db->jdate($obj->date_validation);
2262 $this->date_cloture = $this->db->jdate($obj->date_closure);
2263
2264 $this->user_creation_id = $obj->fk_user_author;
2265 $this->user_modification_id = $obj->fk_user_modif;
2266 $this->user_validation_id = $obj->fk_user_valid;
2267 $this->user_closing_id = $obj->fk_user_cloture;
2268 }
2269 $this->db->free($result);
2270 } else {
2271 dol_print_error($this->db);
2272 }
2273 }
2274
2275
2282 public function getLibStatut($mode = 0)
2283 {
2284 return $this->LibStatut((isset($this->status) ? $this->status : $this->statut), $mode);
2285 }
2286
2287 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2295 public function LibStatut($status, $mode = 1)
2296 {
2297 // phpcs:enable
2298
2299 // Init/load array of translation of status
2300 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
2301 global $langs;
2302 $langs->load("supplier_proposal");
2303 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv("SupplierProposalStatusDraft");
2304 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv("SupplierProposalStatusValidated");
2305 $this->labelStatus[self::STATUS_SIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusSigned");
2306 $this->labelStatus[self::STATUS_NOTSIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusNotSigned");
2307 $this->labelStatus[self::STATUS_CLOSE] = $langs->transnoentitiesnoconv("SupplierProposalStatusClosed");
2308 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv("SupplierProposalStatusDraftShort");
2309 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv("SupplierProposalStatusValidatedShort");
2310 $this->labelStatusShort[self::STATUS_SIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusSignedShort");
2311 $this->labelStatusShort[self::STATUS_NOTSIGNED] = $langs->transnoentitiesnoconv("SupplierProposalStatusNotSignedShort");
2312 $this->labelStatusShort[self::STATUS_CLOSE] = $langs->transnoentitiesnoconv("SupplierProposalStatusClosedShort");
2313 }
2314
2315 $statusnew = '';
2316 if ($status == self::STATUS_DRAFT) {
2317 $statusnew = 'status0';
2318 } elseif ($status == self::STATUS_VALIDATED) {
2319 $statusnew = 'status1';
2320 } elseif ($status == self::STATUS_SIGNED) {
2321 $statusnew = 'status4';
2322 } elseif ($status == self::STATUS_NOTSIGNED) {
2323 $statusnew = 'status9';
2324 } elseif ($status == self::STATUS_CLOSE) {
2325 $statusnew = 'status6';
2326 }
2327
2328 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode);
2329 }
2330
2331
2332 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2340 public function load_board($user, $mode)
2341 {
2342 // phpcs:enable
2343 global $conf, $langs;
2344
2345 $now = dol_now();
2346
2347 $clause = " WHERE";
2348
2349 $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.date_cloture as datefin";
2350 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
2351 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2352 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
2353 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2354 $clause = " AND";
2355 }
2356 $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")";
2357 if ($mode == 'opened') {
2358 $sql .= " AND p.fk_statut = 1";
2359 }
2360 if ($mode == 'signed') {
2361 $sql .= " AND p.fk_statut = 2";
2362 }
2363 if ($user->socid) {
2364 $sql .= " AND p.fk_soc = ".((int) $user->socid);
2365 }
2366
2367 $resql = $this->db->query($sql);
2368 if ($resql) {
2369 $label = $labelShort = '';
2370 $status = '';
2371 $delay_warning = 0;
2372 if ($mode == 'opened') {
2373 $delay_warning = !empty($conf->supplier_proposal->cloture->warning_delay) ? $conf->supplier_proposal->cloture->warning_delay : 0;
2374 $status = self::STATUS_VALIDATED;
2375 $label = $langs->trans("SupplierProposalsToClose");
2376 $labelShort = $langs->trans("ToAcceptRefuse");
2377 }
2378 if ($mode == 'signed') {
2379 $delay_warning = !empty($conf->supplier_proposal->facturation->warning_delay) ? $conf->supplier_proposal->facturation->warning_delay : 0;
2380 $status = self::STATUS_SIGNED;
2381 $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered
2382 $labelShort = $langs->trans("ToClose");
2383 }
2384
2385 $response = new WorkboardResponse();
2386 $response->warning_delay = $delay_warning / 60 / 60 / 24;
2387 $response->label = $label;
2388 $response->labelShort = $labelShort;
2389 $response->url = DOL_URL_ROOT.'/supplier_proposal/list.php?search_status='.$status;
2390 $response->img = img_object('', "propal");
2391
2392 // This assignment in condition is not a bug. It allows walking the results.
2393 while ($obj = $this->db->fetch_object($resql)) {
2394 $response->nbtodo++;
2395 if ($mode == 'opened') {
2396 $datelimit = $this->db->jdate($obj->datefin);
2397 if ($datelimit < ($now - $delay_warning)) {
2398 $response->nbtodolate++;
2399 }
2400 }
2401 // TODO Definir regle des propales a facturer en retard
2402 // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
2403 }
2404 return $response;
2405 } else {
2406 $this->error = $this->db->lasterror();
2407 return -1;
2408 }
2409 }
2410
2411
2420 public function initAsSpecimen($param = array())
2421 {
2422 global $conf, $langs;
2423
2424 // Load array of products prodids
2425 $num_prods = 0;
2426 $prodids = array();
2427 $sql = "SELECT rowid";
2428 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2429 $sql .= " WHERE entity IN (".getEntity('product').")";
2430 if (array_key_exists('tobuy', $param)) {
2431 $sql .= " AND tobuy = ".((int) $param['tobuy']);
2432 }
2433 $sql .= $this->db->plimit(100);
2434
2435 $resql = $this->db->query($sql);
2436 if ($resql) {
2437 $num_prods = $this->db->num_rows($resql);
2438 $i = 0;
2439 while ($i < $num_prods) {
2440 $i++;
2441 $row = $this->db->fetch_row($resql);
2442 $prodids[$i] = $row[0];
2443 }
2444 }
2445
2446 // Initialise parameters
2447 $this->id = 0;
2448 $this->ref = 'SPECIMEN';
2449 $this->ref_supplier = 'NEMICEPS';
2450 $this->specimen = 1;
2451 $this->socid = 1;
2452 $this->date = time();
2453 $this->cond_reglement_id = 1;
2454 $this->cond_reglement_code = 'RECEP';
2455 $this->mode_reglement_id = 7;
2456 $this->mode_reglement_code = 'CHQ';
2457 $this->note_public = 'This is a comment (public)';
2458 $this->note_private = 'This is a comment (private)';
2459
2460 $this->multicurrency_tx = 1;
2461 $this->multicurrency_code = getDolCurrency();
2462
2463 // Lines
2464 $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)
2465 $xnbp = 0;
2466 while ($xnbp < $nbp) {
2467 $line = new SupplierProposalLine($this->db);
2468 $line->desc = $langs->trans("Description")." ".$xnbp;
2469 $line->qty = 1;
2470 $line->subprice = 100;
2471 $line->tva_tx = 19.6;
2472 $line->localtax1_tx = 0;
2473 $line->localtax2_tx = 0;
2474 if ($xnbp == 2) {
2475 $line->total_ht = 50;
2476 $line->total_ttc = 59.8;
2477 $line->total_tva = 9.8;
2478 $line->remise_percent = 50;
2479 } else {
2480 $line->total_ht = 100;
2481 $line->total_ttc = 119.6;
2482 $line->total_tva = 19.6;
2483 $line->remise_percent = 00;
2484 }
2485
2486 if ($num_prods > 0) {
2487 $prodid = mt_rand(1, $num_prods);
2488 $line->fk_product = $prodids[$prodid];
2489 }
2490
2491 $this->lines[$xnbp] = $line;
2492
2493 $this->total_ht += $line->total_ht;
2494 $this->total_tva += $line->total_tva;
2495 $this->total_ttc += $line->total_ttc;
2496
2497 $xnbp++;
2498 }
2499
2500 return 1;
2501 }
2502
2508 public function loadStateBoard()
2509 {
2510 global $user;
2511
2512 $this->nb = array();
2513 $clause = "WHERE";
2514
2515 $sql = "SELECT count(p.rowid) as nb";
2516 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
2517 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
2518 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2519 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2520 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
2521 $clause = "AND";
2522 }
2523 $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")";
2524
2525 $resql = $this->db->query($sql);
2526 if ($resql) {
2527 // This assignment in condition is not a bug. It allows walking the results.
2528 while ($obj = $this->db->fetch_object($resql)) {
2529 $this->nb["supplier_proposals"] = $obj->nb;
2530 }
2531 $this->db->free($resql);
2532 return 1;
2533 } else {
2534 dol_print_error($this->db);
2535 $this->error = $this->db->lasterror();
2536 return -1;
2537 }
2538 }
2539
2540
2548 public function getNextNumRef($soc)
2549 {
2550 global $conf, $db, $langs;
2551 $langs->load("supplier_proposal");
2552
2553 if (getDolGlobalString('SUPPLIER_PROPOSAL_ADDON')) {
2554 $mybool = false;
2555
2556 $file = getDolGlobalString('SUPPLIER_PROPOSAL_ADDON') . ".php";
2557 $classname = getDolGlobalString('SUPPLIER_PROPOSAL_ADDON');
2558
2559 // Include file with class
2560 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2561 foreach ($dirmodels as $reldir) {
2562 $dir = dol_buildpath($reldir."core/modules/supplier_proposal/");
2563
2564 // Load file with numbering class (if found)
2565 $mybool = ((bool) @include_once $dir.$file) || $mybool;
2566 }
2567
2568 if (!$mybool) {
2569 dol_print_error(null, "Failed to include file ".$file);
2570 return '';
2571 }
2572
2573 $obj = new $classname();
2574 '@phan-var-force ModeleNumRefSupplierProposal $obj';
2576 $numref = "";
2577 $numref = $obj->getNextValue($soc, $this);
2578
2579 if ($numref != "") {
2580 return $numref;
2581 } else {
2582 $this->error = $obj->error;
2583 return "";
2584 }
2585 } else {
2586 $langs->load("errors");
2587 print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("SupplierProposal"));
2588 return "";
2589 }
2590 }
2591
2598 public function getTooltipContentArray($params)
2599 {
2600 global $conf, $langs;
2601
2602 $langs->load('supplier_proposal');
2603
2604 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2605 return ['optimize' => $langs->trans("ShowSupplierProposal")];
2606 }
2607
2608 //$option = $params['option'] ?? '';
2609 $datas = [];
2610
2611 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("SupplierProposal").'</u>';
2612 if (isset($this->status)) {
2613 $datas['picto'] .= ' '.$this->getLibStatut(5);
2614 }
2615 if (!empty($this->ref)) {
2616 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2617 }
2618 if (!empty($this->ref_fourn)) {
2619 $datas['ref_supplier'] = '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_fourn;
2620 }
2621 if (!empty($this->total_ht)) {
2622 $datas['amount_ht'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, getDolCurrency());
2623 }
2624 if (!empty($this->total_tva)) {
2625 $datas['amount_vat'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, getDolCurrency());
2626 }
2627 if (!empty($this->total_ttc)) {
2628 $datas['amount_ttc'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, getDolCurrency());
2629 }
2630
2631 return $datas;
2632 }
2633
2645 public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
2646 {
2647 global $langs, $conf, $user, $hookmanager;
2648
2649 if (!empty($conf->dol_no_mouse_hover)) {
2650 $notooltip = 1; // Force disable tooltips
2651 }
2652
2653 $url = '';
2654 $result = '';
2655 $params = [
2656 'id' => $this->id,
2657 'objecttype' => $this->element,
2658 'option' => $option,
2659 ];
2660 $classfortooltip = 'classfortooltip';
2661 $dataparams = '';
2662 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2663 $classfortooltip = 'classforajaxtooltip';
2664 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2665 $label = '';
2666 } else {
2667 $label = implode($this->getTooltipContentArray($params));
2668 }
2669
2670 if ($option == '') {
2671 $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params;
2672 }
2673 if ($option == 'document') {
2674 $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params;
2675 }
2676
2677 if ($option !== 'nolink') {
2678 // Add param to save lastsearch_values or not
2679 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2680 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2681 $add_save_lastsearch_values = 1;
2682 }
2683 if ($add_save_lastsearch_values) {
2684 $url .= '&save_lastsearch_values=1';
2685 }
2686 }
2687
2688 $linkclose = '';
2689 if (empty($notooltip) && $user->hasRight('propal', 'lire')) {
2690 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2691 $label = $langs->trans("ShowSupplierProposal");
2692 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2693 }
2694 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2695 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
2696 }
2697
2698 $linkstart = '<a href="'.$url.'"';
2699 $linkstart .= $linkclose.'>';
2700 $linkend = '</a>';
2701
2702 $result .= $linkstart;
2703 if ($withpicto) {
2704 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
2705 }
2706 if ($withpicto != 2) {
2707 $result .= $this->ref;
2708 }
2709 $result .= $linkend;
2710
2711 if ($addlinktonotes) {
2712 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2713 if ($txttoshow) {
2714 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
2715 $result .= ' <span class="note inline-block">';
2716 $result .= '<a href="'.DOL_URL_ROOT.'/supplier_proposal/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
2717 $result .= img_picto('', 'note');
2718 $result .= '</a>';
2719 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
2720 //$result.='</a>';
2721 $result .= '</span>';
2722 }
2723 }
2724 global $action;
2725 $hookmanager->initHooks(array($this->element . 'dao'));
2726 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2727 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2728 if ($reshook > 0) {
2729 $result = $hookmanager->resPrint;
2730 } else {
2731 $result .= $hookmanager->resPrint;
2732 }
2733 return $result;
2734 }
2735
2741 public function getLinesArray()
2742 {
2743 // For other object, here we call fetch_lines. But fetch_lines does not exists on supplier proposal
2744
2745 $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
2746 $sql .= ' pt.qty, pt.tva_tx, pt.vat_src_code, pt.remise_percent, pt.subprice, pt.info_bits,';
2747 $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,';
2748 $sql .= ' pt.product_type, pt.rang, pt.fk_parent_line, pt.extraparams,';
2749 $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,';
2750 $sql .= ' p.description as product_desc, pt.ref_fourn as ref_supplier,';
2751 $sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit';
2752 $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt';
2753 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
2754 $sql .= ' WHERE pt.fk_supplier_proposal = '.((int) $this->id);
2755 $sql .= ' ORDER BY pt.rang ASC, pt.rowid';
2756
2757 dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG);
2758 $resql = $this->db->query($sql);
2759 if ($resql) {
2760 $num = $this->db->num_rows($resql);
2761 $i = 0;
2762
2763 while ($i < $num) {
2764 $obj = $this->db->fetch_object($resql);
2765
2766 $this->lines[$i] = new SupplierProposalLine($this->db);
2767 $this->lines[$i]->id = $obj->rowid; // for backward compatibility
2768 $this->lines[$i]->rowid = $obj->rowid;
2769
2770 $this->lines[$i]->label = $obj->custom_label;
2771 $this->lines[$i]->description = $obj->description; // deprecated
2772 $this->lines[$i]->desc = $obj->description;
2773
2774 $this->lines[$i]->fk_product = $obj->fk_product;
2775 $this->lines[$i]->ref = $obj->ref;
2776 $this->lines[$i]->product_label = $obj->product_label;
2777 $this->lines[$i]->product_desc = $obj->product_desc;
2778 $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated
2779 $this->lines[$i]->product_type = $obj->product_type;
2780 $this->lines[$i]->qty = $obj->qty;
2781 $this->lines[$i]->subprice = $obj->subprice;
2782 $this->lines[$i]->fk_remise_except = $obj->fk_remise_except;
2783 $this->lines[$i]->remise_percent = $obj->remise_percent;
2784 $this->lines[$i]->tva_tx = $obj->tva_tx;
2785 $this->lines[$i]->vat_src_code = $obj->vat_src_code;
2786 $this->lines[$i]->info_bits = $obj->info_bits;
2787 $this->lines[$i]->total_ht = $obj->total_ht;
2788 $this->lines[$i]->total_tva = $obj->total_tva;
2789 $this->lines[$i]->total_ttc = $obj->total_ttc;
2790 $this->lines[$i]->fk_fournprice = $obj->fk_fournprice;
2791 $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht);
2792 $this->lines[$i]->pa_ht = $marginInfos[0];
2793 $this->lines[$i]->marge_tx = $marginInfos[1];
2794 $this->lines[$i]->marque_tx = $marginInfos[2];
2795 $this->lines[$i]->fk_parent_line = $obj->fk_parent_line;
2796 $this->lines[$i]->special_code = $obj->special_code;
2797 $this->lines[$i]->rang = $obj->rang;
2798
2799 $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated
2800 $this->lines[$i]->ref_supplier = $obj->ref_supplier;
2801
2802 // Multicurrency
2803 $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency;
2804 $this->lines[$i]->multicurrency_code = $obj->multicurrency_code;
2805 $this->lines[$i]->multicurrency_subprice = $obj->multicurrency_subprice;
2806 $this->lines[$i]->multicurrency_total_ht = $obj->multicurrency_total_ht;
2807 $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva;
2808 $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2809 $this->lines[$i]->fk_unit = $obj->fk_unit;
2810 $this->lines[$i]->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2811
2812 $this->lines[$i]->fetch_optionals();
2813
2814 $i++;
2815 }
2816 $this->db->free($resql);
2817
2818 return 1;
2819 } else {
2820 $this->error = $this->db->error();
2821 return -1;
2822 }
2823 }
2824
2836 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2837 {
2838 global $langs;
2839
2840 $langs->load("supplier_proposal");
2841 $outputlangs->load("products");
2842
2843 if (!dol_strlen($modele)) {
2844 $modele = ''; // On supplier documents, template can be empty( no doc generated in this case)
2845
2846 if ($this->model_pdf) {
2847 $modele = $this->model_pdf;
2848 } elseif (getDolGlobalString('SUPPLIER_PROPOSAL_ADDON_PDF')) {
2849 $modele = getDolGlobalString('SUPPLIER_PROPOSAL_ADDON_PDF');
2850 }
2851 }
2852
2853 if (empty($modele)) {
2854 return 1;
2855 }
2856
2857 $modelpath = "core/modules/supplier_proposal/doc/";
2858
2859 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2860 }
2861
2862
2871 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2872 {
2873 $tables = array(
2874 'supplier_proposal'
2875 );
2876
2877 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2878 }
2879
2888 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
2889 {
2890 $tables = array(
2891 'supplier_proposaldet'
2892 );
2893
2894 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2895 }
2896
2897
2905 public function getKanbanView($option = '', $arraydata = null)
2906 {
2907 global $langs;
2908
2909 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2910
2911 $return = '<div class="box-flex-item box-flex-grow-zero">';
2912 $return .= '<div class="info-box info-box-sm">';
2913 $return .= '<span class="info-box-icon bg-infobox-action">';
2914 $return .= img_picto('', $this->picto);
2915 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2916 $return .= '</span>';
2917 $return .= '<div class="info-box-content">';
2918 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2919 if ($selected >= 0) {
2920 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2921 }
2922 if (property_exists($this, 'socid')) {
2923 $return .= '<span class="info-box-ref"> | '.$this->socid.'</span>';
2924 }
2925 if (property_exists($this, 'delivery_date')) {
2926 $return .= '<br><span class="opacitymedium">'.$langs->trans("DateEnd").'</span> : <span class="info-box-label">'.dol_print_date($this->delivery_date).'</span>';
2927 }
2928 if (property_exists($this, 'total_ttc')) {
2929 $return .= '<br><span class="opacitymedium" >'.$langs->trans("AmountHT").' : </span><span class="info-box-label amount">'.price($this->total_ttc).'</span>';
2930 }
2931 if (method_exists($this, 'getLibStatut')) {
2932 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2933 }
2934 $return .= '</div>';
2935 $return .= '</div>';
2936 $return .= '</div>';
2937 return $return;
2938 }
2939
2950 public function setCategories($categories)
2951 {
2952 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2953 return parent::setCategoriesCommon($categories, Categorie::TYPE_SUPPLIER_PROPOSAL);
2954 }
2955}
2956
2957
2962{
2966 public $db;
2967
2971 public $error = '';
2972
2976 public $element = 'supplier_proposaldet';
2977
2981 public $table_element = 'supplier_proposaldet';
2982
2986 public $parent_element = 'supplier_proposal';
2987
2991 public $fk_parent_attribute = 'fk_supplier_proposal';
2992
2996 public $oldline;
2997
3001 public $id;
3002
3006 public $fk_supplier_proposal;
3007
3011 public $fk_parent_line;
3012
3016 public $desc; // Description of the line
3017
3021 public $fk_product; // Predefined Product ID
3022
3028 public $fk_product_type;
3034 public $product_type = Product::TYPE_PRODUCT;
3035
3039 public $qty;
3043 public $tva_tx;
3047 public $vat_src_code;
3048
3052 public $remise_percent;
3053
3057 public $fk_remise_except;
3058
3062 public $rang = 0;
3063
3067 public $fk_fournprice;
3068
3072 public $pa_ht;
3076 public $marge_tx;
3080 public $marque_tx;
3081
3085 public $special_code; // Tag for special lines (exclusive tags)
3086 // 1: frais de port
3087 // 2: ecotaxe
3088 // 3: option line (when qty = 0)
3089
3093 public $info_bits = 0; // Liste d'options cumulables:
3094 // Bit 0: 0 if TVA normal - 1 if TVA NPR
3095 // Bit 1: 0 normal line - 1 if fixed reduction
3096
3100 public $total_ht; // Line Net Total (HT), including all quantity and the line discount
3104 public $total_tva; // Line Net Total (VAT), including all quantity and the line discount
3108 public $total_ttc; // Line Net Total (TTC), including all quantity and the line discount
3109
3113 public $date_start;
3117 public $date_end;
3118
3119 // From llx_product
3125 public $ref;
3126
3131 public $product_ref;
3132
3138 public $libelle;
3139
3144 public $product_label;
3145
3150 public $label;
3151
3156 public $product_desc;
3157
3161 public $localtax1_tx; // Local tax 1
3165 public $localtax2_tx; // Local tax 2
3169 public $localtax1_type; // Local tax 1 type
3173 public $localtax2_type; // Local tax 2 type
3177 public $total_localtax1; // Line total local tax 1
3181 public $total_localtax2; // Line total local tax 2
3182
3186 public $skip_update_total; // Skip update price total for special lines
3187
3191 public $ref_fourn;
3195 public $ref_supplier;
3196
3197 // Multicurrency
3201 public $fk_multicurrency;
3202
3206 public $multicurrency_code;
3210 public $multicurrency_subprice;
3214 public $multicurrency_total_ht;
3218 public $multicurrency_total_tva;
3222 public $multicurrency_total_ttc;
3223
3229 public function __construct($db)
3230 {
3231 $this->db = $db;
3232 }
3233
3240 public function fetch($rowid)
3241 {
3242 $sql = 'SELECT pd.rowid, pd.fk_supplier_proposal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.tva_tx,';
3243 $sql .= ' pd.date_start, pd.date_end,';
3244 $sql .= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice, pd.subprice_ttc,';
3245 $sql .= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,';
3246 $sql .= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,';
3247 $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,';
3248 $sql .= ' pd.product_type, pd.ref_fourn as ref_produit_fourn, pd.extraparams,';
3249 $sql .= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_subprice_ttc, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc, pd.fk_unit';
3250 $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pd';
3251 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid';
3252 $sql .= ' WHERE pd.rowid = '.((int) $rowid);
3253
3254 $result = $this->db->query($sql);
3255 if ($result) {
3256 if ($objp = $this->db->fetch_object($result)) {
3257 $this->id = $objp->rowid;
3258 $this->fk_supplier_proposal = $objp->fk_supplier_proposal;
3259 $this->fk_parent_line = $objp->fk_parent_line;
3260 $this->label = $objp->custom_label;
3261 $this->desc = $objp->description;
3262 $this->qty = $objp->qty;
3263
3264 $this->subprice = $objp->subprice;
3265 $this->subprice_ttc = $objp->subprice_ttc;
3266
3267 $this->tva_tx = $objp->tva_tx;
3268 $this->remise_percent = $objp->remise_percent;
3269 $this->fk_remise_except = $objp->fk_remise_except;
3270 $this->fk_product = $objp->fk_product;
3271 $this->info_bits = $objp->info_bits;
3272 $this->date_start = $this->db->jdate($objp->date_start);
3273 $this->date_end = $this->db->jdate($objp->date_end);
3274
3275 $this->total_ht = $objp->total_ht;
3276 $this->total_tva = $objp->total_tva;
3277 $this->total_ttc = $objp->total_ttc;
3278
3279 $this->fk_fournprice = $objp->fk_fournprice;
3280
3281 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
3282 $this->pa_ht = $marginInfos[0];
3283 $this->marge_tx = $marginInfos[1];
3284 $this->marque_tx = $marginInfos[2];
3285
3286 $this->special_code = $objp->special_code;
3287 $this->product_type = $objp->product_type;
3288 $this->rang = $objp->rang;
3289
3290 $this->product_ref = $objp->product_ref;
3291 $this->product_label = $objp->product_label;
3292 $this->product_desc = $objp->product_desc;
3293
3294 $this->ref_fourn = $objp->ref_produit_fourn;
3295
3296 $this->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
3297
3298 // Multicurrency
3299 $this->fk_multicurrency = $objp->fk_multicurrency;
3300 $this->multicurrency_code = $objp->multicurrency_code;
3301 $this->multicurrency_subprice = $objp->multicurrency_subprice;
3302 $this->multicurrency_subprice_ttc = $objp->multicurrency_subprice_ttc;
3303 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
3304 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
3305 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
3306 $this->fk_unit = $objp->fk_unit;
3307
3308 $this->db->free($result);
3309 return 1;
3310 }
3311 return 0;
3312 } else {
3313 dol_print_error($this->db);
3314 return -1;
3315 }
3316 }
3317
3324 public function insert($notrigger = 0)
3325 {
3326 global $user;
3327
3328 $error = 0;
3329
3330 dol_syslog(get_class($this)."::insert rang=".$this->rang);
3331
3332 // Clean parameters
3333 if (empty($this->tva_tx)) {
3334 $this->tva_tx = 0;
3335 }
3336 if (empty($this->vat_src_code)) {
3337 $this->vat_src_code = '';
3338 }
3339 if (empty($this->localtax1_tx)) {
3340 $this->localtax1_tx = 0;
3341 }
3342 if (empty($this->localtax2_tx)) {
3343 $this->localtax2_tx = 0;
3344 }
3345 if (empty($this->localtax1_type)) {
3346 $this->localtax1_type = '';
3347 }
3348 if (empty($this->localtax2_type)) {
3349 $this->localtax2_type = '';
3350 }
3351 if (empty($this->total_localtax1)) {
3352 $this->total_localtax1 = 0;
3353 }
3354 if (empty($this->total_localtax2)) {
3355 $this->total_localtax2 = 0;
3356 }
3357 if (empty($this->rang)) {
3358 $this->rang = 0;
3359 }
3360 if (empty($this->remise_percent)) {
3361 $this->remise_percent = 0;
3362 }
3363 if (empty($this->info_bits)) {
3364 $this->info_bits = 0;
3365 }
3366 if (empty($this->special_code)) {
3367 $this->special_code = 0;
3368 }
3369 if (empty($this->fk_parent_line)) {
3370 $this->fk_parent_line = 0;
3371 }
3372 if (empty($this->fk_fournprice)) {
3373 $this->fk_fournprice = 0;
3374 }
3375 if (empty($this->fk_unit)) {
3376 $this->fk_unit = 0;
3377 }
3378 if (empty($this->subprice)) {
3379 $this->subprice = 0;
3380 }
3381
3382 if (empty($this->pa_ht)) {
3383 $this->pa_ht = 0;
3384 }
3385
3386 // if buy price not defined, define buyprice as configured in margin admin
3387 if ($this->pa_ht == 0) {
3388 $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product, $this->qty);
3389 if ($result < 0) {
3390 return $result;
3391 } else {
3392 $this->pa_ht = $result;
3393 }
3394 }
3395
3396 // Check parameters
3397 if ($this->product_type < 0) {
3398 return -1;
3399 }
3400
3401 $this->db->begin();
3402
3403 // Insert line into database
3404 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'supplier_proposaldet';
3405 $sql .= ' (fk_supplier_proposal, fk_parent_line, label, description, fk_product, product_type,';
3406 $sql .= ' date_start, date_end,';
3407 $sql .= ' fk_remise_except, qty, tva_tx, vat_src_code, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
3408 $sql .= ' subprice, subprice_ttc, remise_percent, ';
3409 $sql .= ' info_bits, ';
3410 $sql .= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,';
3411 $sql .= ' ref_fourn,';
3412 $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_subprice_ttc, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc, fk_unit)';
3413 $sql .= " VALUES (".((int) $this->fk_supplier_proposal).",";
3414 $sql .= " ".($this->fk_parent_line > 0 ? ((int) $this->fk_parent_line) : "null").",";
3415 $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
3416 $sql .= " '".$this->db->escape($this->desc)."',";
3417 $sql .= " ".($this->fk_product ? ((int) $this->fk_product) : "null").",";
3418 $sql .= " ".((int) $this->product_type).",";
3419 $sql .= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").",";
3420 $sql .= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").",";
3421 $sql .= " ".($this->fk_remise_except ? ((int) $this->fk_remise_except) : "null").",";
3422 $sql .= " ".(float) price2num($this->qty, 'MS').",";
3423 $sql .= " ".(float) price2num($this->tva_tx).",";
3424 $sql .= " '".$this->db->escape($this->vat_src_code)."',";
3425 $sql .= " ".(float) price2num($this->localtax1_tx).",";
3426 $sql .= " ".(float) price2num($this->localtax2_tx).",";
3427 $sql .= " '".$this->db->escape($this->localtax1_type)."',";
3428 $sql .= " '".$this->db->escape($this->localtax2_type)."',";
3429 $sql .= " ".(float) price2num($this->subprice, 'MU') .",";
3430 $sql .= " ".(float) price2num($this->subprice_ttc, 'MU') .",";
3431 $sql .= " ".((float) $this->remise_percent).",";
3432 $sql .= " ".(isset($this->info_bits) ? ((int) $this->info_bits) : "null").",";
3433 $sql .= " ".(float) price2num($this->total_ht, 'MT').",";
3434 $sql .= " ".(float) price2num($this->total_tva, 'MT').",";
3435 $sql .= " ".(float) price2num($this->total_localtax1, 'MT').",";
3436 $sql .= " ".(float) price2num($this->total_localtax2, 'MT').",";
3437 $sql .= " ".(float) price2num($this->total_ttc, 'MT').",";
3438 $sql .= " ".(!empty($this->fk_fournprice) ? ((int) $this->fk_fournprice) : "null").",";
3439 $sql .= " ".(isset($this->pa_ht) ? (float) price2num($this->pa_ht, 'MU') : "null").",";
3440 $sql .= ' '.((int) $this->special_code).',';
3441 $sql .= ' '.((int) $this->rang).',';
3442 $sql .= " '".$this->db->escape($this->ref_fourn)."'";
3443 $sql .= ", ".($this->fk_multicurrency > 0 ? ((int) $this->fk_multicurrency) : 'null');
3444 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
3445 $sql .= ", ".(float) price2num($this->multicurrency_subprice, 'CU');
3446 $sql .= ", ".(float) price2num($this->multicurrency_subprice_ttc, 'CU');
3447 $sql .= ", ".(float) price2num($this->multicurrency_total_ht, 'CT');
3448 $sql .= ", ".(float) price2num($this->multicurrency_total_tva, 'CT');
3449 $sql .= ", ".(float) price2num($this->multicurrency_total_ttc, 'CT');
3450 $sql .= ", ".($this->fk_unit ? ((int) $this->fk_unit) : 'null');
3451 $sql .= ')';
3452
3453 dol_syslog(get_class($this).'::insert', LOG_DEBUG);
3454 $resql = $this->db->query($sql);
3455 if ($resql) {
3456 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'supplier_proposaldet');
3457
3458 if (!$error) {
3459 $result = $this->insertExtraFields();
3460 if ($result < 0) {
3461 $error++;
3462 }
3463 }
3464
3465 if (!$error && !$notrigger) {
3466 // Call trigger
3467 $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_INSERT', $user);
3468 if ($result < 0) {
3469 $this->db->rollback();
3470 return -1;
3471 }
3472 // End call triggers
3473 }
3474
3475 $this->db->commit();
3476 return 1;
3477 } else {
3478 $this->error = $this->db->error()." sql=".$sql;
3479 $this->db->rollback();
3480 return -1;
3481 }
3482 }
3483
3490 public function delete($user)
3491 {
3492 $error = 0;
3493
3494 $this->db->begin();
3495
3496 $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet";
3497 $sql .= " WHERE rowid = ".((int) $this->id);
3498
3499 if ($this->db->query($sql)) {
3500 // Remove extrafields
3501 if (!$error) {
3502 $result = $this->deleteExtraFields();
3503 if ($result < 0) {
3504 $error++;
3505 dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
3506 }
3507 }
3508
3509 // Call trigger
3510 $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_DELETE', $user);
3511 if ($result < 0) {
3512 $this->db->rollback();
3513 return -1;
3514 }
3515 // End call triggers
3516
3517 $this->db->commit();
3518
3519 return 1;
3520 } else {
3521 $this->error = $this->db->error()." sql=".$sql;
3522 $this->db->rollback();
3523 return -1;
3524 }
3525 }
3526
3533 public function update($notrigger = 0)
3534 {
3535 global $user;
3536
3537 $error = 0;
3538
3539 // Clean parameters
3540 if (empty($this->tva_tx)) {
3541 $this->tva_tx = 0;
3542 }
3543 if (empty($this->localtax1_tx)) {
3544 $this->localtax1_tx = 0;
3545 }
3546 if (empty($this->localtax2_tx)) {
3547 $this->localtax2_tx = 0;
3548 }
3549 if (empty($this->total_localtax1)) {
3550 $this->total_localtax1 = 0;
3551 }
3552 if (empty($this->total_localtax2)) {
3553 $this->total_localtax2 = 0;
3554 }
3555 if (empty($this->localtax1_type)) {
3556 $this->localtax1_type = '';
3557 }
3558 if (empty($this->localtax2_type)) {
3559 $this->localtax2_type = '';
3560 }
3561 if (empty($this->marque_tx)) {
3562 $this->marque_tx = 0;
3563 }
3564 if (empty($this->marge_tx)) {
3565 $this->marge_tx = 0;
3566 }
3567 if (empty($this->remise_percent)) {
3568 $this->remise_percent = 0;
3569 }
3570 if (empty($this->info_bits)) {
3571 $this->info_bits = 0;
3572 }
3573 if (empty($this->special_code)) {
3574 $this->special_code = 0;
3575 }
3576 if (empty($this->fk_parent_line)) {
3577 $this->fk_parent_line = 0;
3578 }
3579 if (empty($this->fk_fournprice)) {
3580 $this->fk_fournprice = 0;
3581 }
3582 if (empty($this->fk_unit)) {
3583 $this->fk_unit = 0;
3584 }
3585 if (empty($this->subprice)) {
3586 $this->subprice = 0;
3587 }
3588
3589 if (empty($this->pa_ht)) {
3590 $this->pa_ht = 0;
3591 }
3592
3593 // if buy price not defined, define buyprice as configured in margin admin
3594 if ($this->pa_ht == 0) {
3595 $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product, $this->qty);
3596 if ($result < 0) {
3597 return $result;
3598 } else {
3599 $this->pa_ht = $result;
3600 }
3601 }
3602
3603 $this->db->begin();
3604
3605 // Update line in database
3606 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposaldet SET";
3607 $sql .= " description = '".$this->db->escape($this->desc)."'";
3608 $sql .= " , label = ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
3609 $sql .= " , product_type = ".((int) $this->product_type);
3610 $sql .= " , date_start = ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null");
3611 $sql .= " , date_end = ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null");
3612 $sql .= " , tva_tx = '".price2num($this->tva_tx)."'";
3613 $sql .= " , localtax1_tx = ".(float) price2num($this->localtax1_tx);
3614 $sql .= " , localtax2_tx = ".(float) price2num($this->localtax2_tx);
3615 $sql .= " , localtax1_type = '".$this->db->escape($this->localtax1_type)."'";
3616 $sql .= " , localtax2_type = '".$this->db->escape($this->localtax2_type)."'";
3617 $sql .= " , qty = ".(float) price2num($this->qty);
3618 $sql .= " , subprice = ".(float) price2num($this->subprice);
3619 $sql .= " , subprice_ttc = ".(float) price2num($this->subprice_ttc);
3620 $sql .= " , remise_percent = ".(float) price2num($this->remise_percent);
3621 $sql .= " , info_bits = ".((int) $this->info_bits);
3622 if (empty($this->skip_update_total)) {
3623 $sql .= " , total_ht = ".(float) price2num($this->total_ht);
3624 $sql .= " , total_tva = ".(float) price2num($this->total_tva);
3625 $sql .= " , total_ttc = ".(float) price2num($this->total_ttc);
3626 $sql .= " , total_localtax1 = ".(float) price2num($this->total_localtax1);
3627 $sql .= " , total_localtax2 = ".(float) price2num($this->total_localtax2);
3628 }
3629 $sql .= " , fk_product_fournisseur_price = ".(!empty($this->fk_fournprice) ? "'".$this->db->escape((string) $this->fk_fournprice)."'" : "null");
3630 $sql .= " , buy_price_ht = ".(float) price2num($this->pa_ht);
3631 $sql .= " , special_code = ".((int) $this->special_code);
3632 $sql .= " , fk_parent_line = ".($this->fk_parent_line > 0 ? ((int) $this->fk_parent_line) : "null");
3633 if (!empty($this->rang)) {
3634 $sql .= ", rang = ".((int) $this->rang);
3635 }
3636 $sql .= " , ref_fourn = ".(!empty($this->ref_fourn) ? "'".$this->db->escape($this->ref_fourn)."'" : "null");
3637 $sql .= " , fk_unit = ".($this->fk_unit ? (int) $this->fk_unit : 'null');
3638
3639 // Multicurrency
3640 $sql .= " , multicurrency_subprice = ".(float) price2num($this->multicurrency_subprice);
3641 $sql .= " , multicurrency_subprice_ttc = ".(float) price2num($this->multicurrency_subprice_ttc);
3642 $sql .= " , multicurrency_total_ht = ".(float) price2num($this->multicurrency_total_ht);
3643 $sql .= " , multicurrency_total_tva = ".(float) price2num($this->multicurrency_total_tva);
3644 $sql .= " , multicurrency_total_ttc = ".(float) price2num($this->multicurrency_total_ttc);
3645
3646 $sql .= " WHERE rowid = ".((int) $this->id);
3647
3648 dol_syslog(get_class($this)."::update", LOG_DEBUG);
3649 $resql = $this->db->query($sql);
3650 if ($resql) {
3651 if (!$error) {
3652 $result = $this->insertExtraFields();
3653 if ($result < 0) {
3654 $error++;
3655 }
3656 }
3657
3658 if (!$error && !$notrigger) {
3659 // Call trigger
3660 $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_MODIFY', $user);
3661 if ($result < 0) {
3662 $this->db->rollback();
3663 return -1;
3664 }
3665 // End call triggers
3666 }
3667
3668 $this->db->commit();
3669 return 1;
3670 } else {
3671 $this->error = $this->db->error();
3672 $this->db->rollback();
3673 return -2;
3674 }
3675 }
3676
3677 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3684 public function update_total()
3685 {
3686 // phpcs:enable
3687 $this->db->begin();
3688
3689 // Update line in database
3690 $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposaldet SET";
3691 $sql .= " total_ht = ".(float) price2num($this->total_ht, 'MT');
3692 $sql .= ",total_tva = ".(float) price2num($this->total_tva, 'MT');
3693 $sql .= ",total_ttc = ".(float) price2num($this->total_ttc, 'MT');
3694 $sql .= " WHERE rowid = ".((int) $this->id);
3695
3696 dol_syslog("SupplierProposalLine::update_total", LOG_DEBUG);
3697
3698 $resql = $this->db->query($sql);
3699 if ($resql) {
3700 $this->db->commit();
3701 return 1;
3702 } else {
3703 $this->error = $this->db->error();
3704 $this->db->rollback();
3705 return -2;
3706 }
3707 }
3708}
$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.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
updateRangOfLine($rowid, $rang)
Update position of line (rang)
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
deleteExtraFields()
Delete all extra fields values for the current object.
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0, $qty=0)
Get buy price to use for margin calculation.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class Currency.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_PRODUCT
Regular product.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage price ask supplier.
updatePriceFournisseur($idProductFournPrice, $product, $user)
Update ProductFournisseur.
updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=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, $array_options=[], $ref_supplier='', $fk_unit=0, $pu_ht_devise=0)
Update a proposal line.
cloture($user, $status, $note)
Close the askprice.
initAsSpecimen($param=array())
Initialise an instance with random values.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $pu_ttc=0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='', $array_options=[], $ref_supplier='', $fk_unit=0, $origin='', $origin_id=0, $pu_ht_devise=0, $date_start=0, $date_end=0)
Add a proposal line into database (linked to product/service or not) The parameters are already suppo...
info($id)
Object SupplierProposal Information.
create($user, $notrigger=0)
Create commercial proposal into database this->ref can be set or empty.
insert_discount($idremise)
Adding line of fixed discount in the proposal in DB.
reopen($user, $status, $note='', $notrigger=0)
Reopen the commercial proposal.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
fetch($rowid, $ref='')
Load a proposal from database and its lines array.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
const STATUS_NOTSIGNED
Not signed quote, canceled.
const STATUS_DRAFT
Draft status.
liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datec', $sortorder='DESC')
Return list of askprice (eventually filtered on user) into an array.
update($user, $notrigger=0)
Update the header fields of the price request that can be edited without a dedicated action.
setDeliveryDate($user, $delivery_date)
Set delivery date.
__construct($db, $socid=0, $supplier_proposalid=0)
Constructor.
LibStatut($status, $mode=1)
Return label of a status (draft, validated, ...)
setCategories($categories)
Sets object to supplied categories.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
updateOrCreatePriceFournisseur($user)
Add or update supplier price according to result of proposal.
loadStateBoard()
Load indicator this->nb of global stats widget.
deleteLine($lineid)
Delete detail line.
const STATUS_VALIDATED
Validated status.
createPriceFournisseur($product, $user)
Create Price Fournisseur.
getLibStatut($mode=0)
Return label of status of proposal (draft, validated, ...)
add_product($idproduct, $qty, $remise_percent=0)
Add line into array ->lines.
set_date_livraison($user, $delivery_date)
Set delivery date.
const STATUS_SIGNED
Signed quote.
getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=0)
Return clickable link of object (with eventually picto)
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
getTooltipContentArray($params)
getTooltipContentArray
valid($user, $notrigger=0)
Set status to validated.
const STATUS_CLOSE
Billed or closed/processed quote.
getLinesArray()
Retrieve an array of supplier proposal lines.
setDraft($user)
Set draft status.
Class to manage supplier_proposal lines.
fetch($rowid)
Retrieve the propal line object.
insert($notrigger=0)
Insert object line propal in database.
update_total()
Update DB line fields total_xxx Used by migration.
update($notrigger=0)
Update propal line object into DB.
__construct($db)
Class line Constructor.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492