Passed
Push — EXTRACT_CLASSES ( c25e41...9f3ede )
by Rafael
55:18
created

ProductFournisseur::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* Copyright (C) 2005       Rodolphe Quiedeville        <[email protected]>
4
 * Copyright (C) 2006-2011	Laurent Destailleur	        <[email protected]>
5
 * Copyright (C) 2009-2014	Regis Houssin		        <[email protected]>
6
 * Copyright (C) 2011		Juanjo Menent		        <[email protected]>
7
 * Copyright (C) 2012		Christophe Battarel	        <[email protected]>
8
 * Copyright (C) 2015		Marcos García               <[email protected]>
9
 * Copyright (C) 2016-2023	Charlene Benke              <[email protected]>
10
 * Copyright (C) 2019-2024  Frédéric France             <[email protected]>
11
 * Copyright (C) 2020       Pierre Ardoin               <[email protected]>
12
 * Copyright (C) 2024		MDW							<[email protected]>
13
 * Copyright (C) 2024       Rafael San José             <[email protected]>
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 3 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27
 */
28
29
namespace Dolibarr\Code\Fourn\Classes;
30
31
use DoliDB;
32
33
/**
34
 *  \file       htdocs/fourn/class/fournisseur.product.class.php
35
 *  \ingroup    produit
36
 *  \brief      File of class to manage predefined suppliers products
37
 */
38
39
require_once constant('DOL_DOCUMENT_ROOT') . '/product/class/product.class.php';
40
require_once constant('DOL_DOCUMENT_ROOT') . '/fourn/class/fournisseur.class.php';
41
require_once constant('DOL_DOCUMENT_ROOT') . '/product/class/productfournisseurprice.class.php';
42
43
44
/**
45
 *  Class to manage predefined suppliers products
46
 */
47
class ProductFournisseur extends Product
48
{
49
    /**
50
     * @var DoliDB      Database handler.
51
     */
52
    public $db;
53
54
    /**
55
     * @var string      Error code (or message)
56
     */
57
    public $error = '';
58
59
    /**
60
     * @var int         ID of ligne product-supplier
61
     */
62
    public $product_fourn_price_id;
63
64
    /**
65
     * @var int         ID
66
     */
67
    public $id;
68
69
    /**
70
     * @deprecated
71
     * @see $ref_supplier
72
     */
73
    public $fourn_ref;
74
75
    /**
76
     * @var int         The product lead time in days.
77
     */
78
    public $delivery_time_days;
79
80
    /**
81
     * @var string      The product reference of the supplier. Can be set by get_buyprice().
82
     */
83
    public $ref_supplier;
84
85
    /**
86
     * @var string      The product description of the supplier.
87
     */
88
    public $desc_supplier;
89
90
    /**
91
     * @var float       The VAT rate by default for this {supplier, qty, product}. Can be set by get_buyprice().
92
     */
93
    public $vatrate_supplier;
94
95
    /**
96
     * @deprecated
97
     * @see $product_id
98
     */
99
    public $fk_product;
100
101
    /**
102
     * @var int         The product ID.
103
     */
104
    public $product_id;
105
106
    /**
107
     * @var string      The product reference.
108
     */
109
    public $product_ref;
110
111
    /**
112
     * @var int         The supplier ID.
113
     */
114
    public $fourn_id;
115
116
    /**
117
     * @var string      The supplier name.
118
     */
119
    public $fourn_name;
120
121
    /**
122
     * @var float       The Minimum Order Quantity (MOQ) for a given unit price. Can be set by get_buyprice().
123
     */
124
    public $fourn_qty;
125
126
    /**
127
     * @var float       The unit price for a given Minimum Order Quantity (MOQ). Can be set by get_buyprice().
128
     */
129
    public $fourn_pu;
130
131
    /**
132
     * @var float       The total price for a given Minimum Order Quantity (MOQ).
133
     */
134
    public $fourn_price;
135
136
    /**
137
     * @var float       The discount in percentage for a given Minimum Order Quantity (MOQ).
138
     */
139
    public $fourn_remise_percent;
140
141
    /**
142
     * @var float       The discount in value for a given Minimum Order Quantity (MOQ).
143
     */
144
    public $fourn_remise;
145
146
    public $fourn_charges;  // when getDolGlobalString('PRODUCT_CHARGES') is set
147
148
    /**
149
     * @var int     product-supplier id
150
     */
151
    public $product_fourn_id;
152
153
    public $product_fourn_entity;
154
155
    /**
156
     * @var int ID user_id - user who created/updated supplier price
157
     */
158
    public $user_id;
159
160
    /**
161
     * @var int ID availability delay - visible/used if option FOURN_PRODUCT_AVAILABILITY is on (duplicate information compared to delivery delay)
162
     */
163
    public $fk_availability;
164
165
    public $fourn_unitprice;
166
    public $fourn_unitprice_with_discount;  // not saved into database
167
    public $fourn_tva_tx;
168
    public $fourn_tva_npr;
169
170
    /**
171
     * @var int ID
172
     */
173
    public $fk_supplier_price_expression;
174
175
    /**
176
     * @var string reputation of supplier
177
     */
178
    public $supplier_reputation;
179
180
    /**
181
     * @var string[] list of available supplier reputations
182
     */
183
    public $reputations = array();
184
185
    // Multicurreny
186
    public $fourn_multicurrency_id;
187
    public $fourn_multicurrency_code;
188
    public $fourn_multicurrency_tx;
189
    public $fourn_multicurrency_price;
190
    public $fourn_multicurrency_unitprice;
191
192
    /**
193
     * @deprecated
194
     * @see $supplier_barcode
195
     */
196
    public $fourn_barcode;
197
198
    /**
199
     * @var string $supplier_barcode - Supplier barcode
200
     */
201
    public $supplier_barcode;
202
203
    /**
204
     * @deprecated
205
     * @see $supplier_fk_barcode_type
206
     */
207
    public $fourn_fk_barcode_type;
208
209
    /**
210
     * @var string $supplier_fk_barcode_type - Supplier barcode type
211
     */
212
    public $supplier_fk_barcode_type;
213
214
    public $packaging;
215
216
    public $labelStatusShort;
217
    public $labelStatus;
218
219
    const STATUS_OPEN = 1;
220
    const STATUS_CANCELED = 0;
221
222
223
    /**
224
     *  Constructor
225
     *
226
     *  @param      DoliDB      $db      Database handler
227
     */
228
    public function __construct($db)
229
    {
230
        global $langs;
231
232
        $this->db = $db;
233
        $langs->load("suppliers");
234
        $this->reputations = array('-1' => '', 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
235
    }
236
237
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
238
    /**
239
     *    Remove all prices for this couple supplier-product
240
     *
241
     *    @param    int     $id_fourn   Supplier Id
242
     *    @return   int                 Return integer < 0 if error, > 0 if ok
243
     */
244
    public function remove_fournisseur($id_fourn)
245
    {
246
		// phpcs:enable
247
        $ok = 1;
248
249
        $this->db->begin();
250
251
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_fournisseur_price";
252
        $sql .= " WHERE fk_product = " . ((int) $this->id) . " AND fk_soc = " . ((int) $id_fourn);
253
254
        dol_syslog(get_class($this) . "::remove_fournisseur", LOG_DEBUG);
255
        $resql2 = $this->db->query($sql);
256
        if (!$resql2) {
257
            $this->error = $this->db->lasterror();
258
            $ok = 0;
259
        }
260
261
        if ($ok) {
262
            $this->db->commit();
263
            return 1;
264
        } else {
265
            $this->db->rollback();
266
            return -1;
267
        }
268
    }
269
270
271
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
272
    /**
273
     *  Remove a price for a couple supplier-product
274
     *
275
     *  @param  int     $rowid      Line id of price
276
     *  @return int                 Return integer <0 if KO, >0 if OK
277
     */
278
    public function remove_product_fournisseur_price($rowid)
279
    {
280
		// phpcs:enable
281
        global $conf, $user;
282
283
        $error = 0;
284
285
        $this->db->begin();
286
287
        // Call trigger
288
        $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user);
289
        if ($result < 0) {
290
            $error++;
291
        }
292
        // End call triggers
293
294
        if (empty($error)) {
295
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_fournisseur_price";
296
            $sql .= " WHERE rowid = " . ((int) $rowid);
297
298
            dol_syslog(get_class($this) . "::remove_product_fournisseur_price", LOG_DEBUG);
299
            $resql = $this->db->query($sql);
300
            if (!$resql) {
301
                $this->error = $this->db->lasterror();
302
                $error++;
303
            }
304
        }
305
306
        if (empty($error)) {
307
            $this->db->commit();
308
            return 1;
309
        } else {
310
            $this->db->rollback();
311
            return -1;
312
        }
313
    }
314
315
316
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
317
    /**
318
     *    Modify the purchase price for a supplier
319
     *
320
     *    @param    float       $qty                            Min quantity for which price is valid
321
     *    @param    float       $buyprice                       Purchase price for the quantity min
322
     *    @param    User        $user                           Object user user made changes
323
     *    @param    string      $price_base_type                HT or TTC
324
     *    @param    Societe     $fourn                          Supplier
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Fourn\Classes\Societe was not found. Did you mean Societe? If so, make sure to prefix the type with \.
Loading history...
325
     *    @param    int         $availability                   Product availability
326
     *    @param    string      $ref_fourn                      Supplier ref
327
     *    @param    float       $tva_tx                         New VAT Rate (For example 8.5. Should not be a string)
328
     *    @param    string|float $charges                       costs affering to product
329
     *    @param    float       $remise_percent                 Discount  regarding qty (percent)
330
     *    @param    float       $remise                         Discount  regarding qty (amount)
331
     *    @param    int         $newnpr                         Set NPR or not
332
     *    @param    int         $delivery_time_days             Delay in days for delivery (max). May be '' if not defined.
333
     *    @param    string      $supplier_reputation            Reputation with this product to the defined supplier (empty, FAVORITE, DONOTORDER)
334
     *    @param    array       $localtaxes_array               Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function).
335
     *    @param    string      $newdefaultvatcode              Default vat code
336
     *    @param    float       $multicurrency_buyprice         Purchase price for the quantity min in currency
337
     *    @param    string      $multicurrency_price_base_type  HT or TTC in currency
338
     *    @param    float       $multicurrency_tx               Rate currency
339
     *    @param    string      $multicurrency_code             Currency code
340
     *    @param    string      $desc_fourn                     Custom description for product_fourn_price
341
     *    @param    string      $barcode                        Barcode
342
     *    @param    int         $fk_barcode_type                Barcode type
343
     *    @param    array       $options                        Extrafields of product fourn price
344
     *    @return   int                                         Return integer <0 if KO, >=0 if OK
345
     */
346
    public function update_buyprice(
347
        $qty,
348
        $buyprice,
349
        $user,
350
        $price_base_type,
351
        $fourn,
352
        $availability,
353
        $ref_fourn,
354
        $tva_tx,
355
        $charges = 0,
356
        $remise_percent = 0,
357
        $remise = 0,
358
        $newnpr = 0,
359
        $delivery_time_days = 0,
360
        $supplier_reputation = '',
361
        $localtaxes_array = array(),
362
        $newdefaultvatcode = '',
363
        $multicurrency_buyprice = 0,
364
        $multicurrency_price_base_type = 'HT',
365
        $multicurrency_tx = 1,
366
        $multicurrency_code = '',
367
        $desc_fourn = '',
368
        $barcode = '',
369
        $fk_barcode_type = 0,
370
        $options = array()
371
    ) {
372
		// phpcs:enable
373
        global $conf, $langs;
374
        //global $mysoc;
375
376
        // Clean parameter
377
        if (empty($qty)) {
378
            $qty = 0;
379
        }
380
        if (empty($buyprice)) {
381
            $buyprice = 0;
382
        }
383
        if (empty($charges)) {
384
            $charges = 0;
385
        }
386
        if (empty($availability)) {
387
            $availability = 0;
388
        }
389
        if (empty($remise_percent)) {
390
            $remise_percent = 0;
391
        }
392
        if (empty($supplier_reputation) || $supplier_reputation == -1) {
393
            $supplier_reputation = '';
394
        }
395
        if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) {
396
            $delivery_time_days = 0;
397
        }
398
        if ($price_base_type == 'TTC') {
399
            $ttx = $tva_tx;
400
            $buyprice = $buyprice / (1 + ($ttx / 100));
401
        }
402
403
        // Multicurrency
404
        $multicurrency_unitBuyPrice = null;
405
        $fk_multicurrency = null;
406
        if (isModEnabled("multicurrency")) {
407
            if (empty($multicurrency_tx)) {
408
                $multicurrency_tx = 1;
409
            }
410
            if (empty($multicurrency_buyprice)) {
411
                $multicurrency_buyprice = 0;
412
            }
413
            if ($multicurrency_price_base_type == 'TTC') {
414
                $ttx = $tva_tx;
415
                $multicurrency_buyprice = $multicurrency_buyprice / (1 + ($ttx / 100));
416
            }
417
            $multicurrency_buyprice = price2num($multicurrency_buyprice, 'MU');
418
            $multicurrency_unitBuyPrice = price2num($multicurrency_buyprice / $qty, 'MU');
419
420
            $buyprice = $multicurrency_buyprice / $multicurrency_tx;
421
            $fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $multicurrency_code);
422
        }
423
424
        $buyprice = (float) price2num($buyprice, 'MU');
425
        $charges = (float) price2num($charges, 'MU');
426
        $qty = (float) price2num($qty, 'MS');
427
        $unitBuyPrice = (float) price2num($buyprice / $qty, 'MU');
428
429
        // We can have a purchase ref that need to buy 100 min for a given price and with a packaging of 50.
430
        //$packaging = price2num(((empty($this->packaging) || $this->packaging < $qty) ? $qty : $this->packaging), 'MS');
431
        $packaging = price2num((empty($this->packaging) ? $qty : $this->packaging), 'MS');
432
433
        $error = 0;
434
        $now = dol_now();
435
436
        $newvat = $tva_tx;
437
438
        if (count($localtaxes_array) > 0) {
439
            $localtaxtype1 = $localtaxes_array['0'];
440
            $localtax1 = $localtaxes_array['1'];
441
            $localtaxtype2 = $localtaxes_array['2'];
442
            $localtax2 = $localtaxes_array['3'];
443
        } else { // old method. deprecated because it can't retrieve type
444
            $localtaxtype1 = '0';
445
            $localtax1 = get_localtax($newvat, 1);
446
            $localtaxtype2 = '0';
447
            $localtax2 = get_localtax($newvat, 2);
448
        }
449
        if (empty($localtax1)) {
450
            $localtax1 = 0; // If = '' then = 0
451
        }
452
        if (empty($localtax2)) {
453
            $localtax2 = 0; // If = '' then = 0
454
        }
455
456
        $this->db->begin();
457
458
        if ($this->product_fourn_price_id > 0) {
459
            // check if price already logged, if not first log current price
460
            $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id);
461
            if (is_array($logPrices) && count($logPrices) == 0) {
462
                $currentPfp = new self($this->db);
463
                $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id);
464
                if ($result > 0 && $currentPfp->fourn_price != 0) {
465
                    $currentPfpUser = new User($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Fourn\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
466
                    $result = $currentPfpUser->fetch($currentPfp->user_id);
467
                    if ($result > 0) {
468
                        $currentPfp->logPrice(
469
                            $currentPfpUser,
470
                            $currentPfp->date_creation,
471
                            $currentPfp->fourn_price,
472
                            $currentPfp->fourn_qty,
473
                            $currentPfp->fourn_multicurrency_price,
474
                            $currentPfp->fourn_multicurrency_unitprice,
475
                            $currentPfp->fourn_multicurrency_tx,
476
                            $currentPfp->fourn_multicurrency_id,
477
                            $currentPfp->fourn_multicurrency_code
478
                        );
479
                    }
480
                }
481
            }
482
            $sql = "UPDATE " . MAIN_DB_PREFIX . "product_fournisseur_price";
483
            $sql .= " SET fk_user = " . ((int) $user->id) . " ,";
484
            $sql .= " datec = '" . $this->db->idate($now) . "' ,";  // Note: Even if this is an update, we update the creation date as the log of each change is tracked into product_fournisseur_log.
485
            $sql .= " ref_fourn = '" . $this->db->escape($ref_fourn) . "',";
486
            $sql .= " desc_fourn = '" . $this->db->escape($desc_fourn) . "',";
487
            $sql .= " price = " . ((float) $buyprice) . ",";
488
            $sql .= " quantity = " . ((float) $qty) . ",";
489
            $sql .= " remise_percent = " . ((float) $remise_percent) . ",";
490
            $sql .= " remise = " . ((float) $remise) . ",";
491
            $sql .= " unitprice = " . ((float) $unitBuyPrice) . ",";
492
            $sql .= " fk_availability = " . ((int) $availability) . ",";
493
            $sql .= " multicurrency_price = " . (isset($multicurrency_buyprice) ? "'" . $this->db->escape(price2num($multicurrency_buyprice)) . "'" : 'null') . ",";
494
            $sql .= " multicurrency_unitprice = " . (isset($multicurrency_unitBuyPrice) ? "'" . $this->db->escape(price2num($multicurrency_unitBuyPrice)) . "'" : 'null') . ",";
495
            $sql .= " multicurrency_tx = " . (isset($multicurrency_tx) ? "'" . $this->db->escape($multicurrency_tx) . "'" : '1') . ",";
496
            $sql .= " fk_multicurrency = " . (isset($fk_multicurrency) ? "'" . $this->db->escape($fk_multicurrency) . "'" : 'null') . ",";
497
            $sql .= " multicurrency_code = " . (isset($multicurrency_code) ? "'" . $this->db->escape($multicurrency_code) . "'" : 'null') . ",";
498
            $sql .= " entity = " . $conf->entity . ",";
499
            $sql .= " tva_tx = " . price2num($tva_tx) . ",";
500
            // TODO Add localtax1 and localtax2
501
            //$sql.= " localtax1_tx=".($localtax1>=0?$localtax1:'NULL').",";
502
            //$sql.= " localtax2_tx=".($localtax2>=0?$localtax2:'NULL').",";
503
            //$sql.= " localtax1_type=".($localtaxtype1!=''?"'".$this->db->escape($localtaxtype1)."'":"'0'").",";
504
            //$sql.= " localtax2_type=".($localtaxtype2!=''?"'".$this->db->escape($localtaxtype2)."'":"'0'").",";
505
            $sql .= " default_vat_code=" . ($newdefaultvatcode ? "'" . $this->db->escape($newdefaultvatcode) . "'" : "null") . ",";
506
            $sql .= " info_bits = " . ((int) $newnpr) . ",";
507
            $sql .= " charges = " . ((float) $charges) . ","; // deprecated
508
            $sql .= " delivery_time_days = " . ($delivery_time_days != '' ? ((int) $delivery_time_days) : 'null') . ",";
509
            $sql .= " supplier_reputation = " . (empty($supplier_reputation) ? 'NULL' : "'" . $this->db->escape($supplier_reputation) . "'") . ",";
510
            $sql .= " barcode = " . (empty($barcode) ? 'NULL' : "'" . $this->db->escape($barcode) . "'") . ",";
511
            $sql .= " fk_barcode_type = " . (empty($fk_barcode_type) ? 'NULL' : "'" . $this->db->escape($fk_barcode_type) . "'");
512
            if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
513
                $sql .= ", packaging = " . (empty($packaging) ? 1 : $packaging);
514
            }
515
            $sql .= " WHERE rowid = " . ((int) $this->product_fourn_price_id);
516
517
            if (!$error) {
518
                if (!empty($options) && is_array($options)) {
519
                    $productfournisseurprice = new ProductFournisseurPrice($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Fourn\Clas...ProductFournisseurPrice was not found. Did you mean ProductFournisseurPrice? If so, make sure to prefix the type with \.
Loading history...
520
                    $res = $productfournisseurprice->fetch($this->product_fourn_price_id);
521
                    if ($res > 0) {
522
                        foreach ($options as $key => $value) {
523
                            $productfournisseurprice->array_options[$key] = $value;
524
                        }
525
                        $res = $productfournisseurprice->update($user);
526
                        if ($res < 0) {
527
                            $this->error = $productfournisseurprice->error;
528
                            $this->errors = $productfournisseurprice->errors;
529
                            $error++;
530
                        }
531
                    }
532
                }
533
            }
534
535
            // TODO Add price_base_type and price_ttc
536
537
            dol_syslog(get_class($this) . '::update_buyprice update knowing id of line = product_fourn_price_id = ' . $this->product_fourn_price_id, LOG_DEBUG);
538
            $resql = $this->db->query($sql);
539
            if ($resql) {
540
                // Call trigger
541
                $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_MODIFY', $user);
542
                if ($result < 0) {
543
                    $error++;
544
                }
545
                // End call triggers
546
                if (!$error && !getDolGlobalString('PRODUCT_PRICE_SUPPLIER_NO_LOG')) {
547
                    $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
548
                    if ($result < 0) {
549
                        $error++;
550
                    }
551
                }
552
                if (empty($error)) {
553
                    $this->db->commit();
554
                    return $this->product_fourn_price_id;
555
                } else {
556
                    $this->db->rollback();
557
                    return -1;
558
                }
559
            } else {
560
                $this->error = $this->db->error() . " sql=" . $sql;
561
                $this->db->rollback();
562
                return -2;
563
            }
564
        } else {
565
            dol_syslog(get_class($this) . '::update_buyprice without knowing id of line, so we delete from company, quantity and supplier_ref and insert again', LOG_DEBUG);
566
567
            // Delete price for this quantity
568
            $sql = "DELETE FROM  " . MAIN_DB_PREFIX . "product_fournisseur_price";
569
            $sql .= " WHERE fk_soc = " . ((int) $fourn->id) . " AND ref_fourn = '" . $this->db->escape($ref_fourn) . "' AND quantity = " . ((float) $qty) . " AND entity = " . ((int) $conf->entity);
570
            $resql = $this->db->query($sql);
571
            if ($resql) {
572
                // Add price for this quantity to supplier
573
                $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_fournisseur_price(";
574
                $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
575
                $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type";
576
                if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
577
                    $sql .= ", packaging";
578
                }
579
                $sql .= ") values(";
580
                $sql .= (isset($multicurrency_buyprice) ? "'" . $this->db->escape(price2num($multicurrency_buyprice)) . "'" : 'null') . ",";
581
                $sql .= (isset($multicurrency_unitBuyPrice) ? "'" . $this->db->escape(price2num($multicurrency_unitBuyPrice)) . "'" : 'null') . ",";
582
                $sql .= (isset($multicurrency_tx) ? "'" . $this->db->escape($multicurrency_tx) . "'" : '1') . ",";
583
                $sql .= (isset($fk_multicurrency) ? "'" . $this->db->escape($fk_multicurrency) . "'" : 'null') . ",";
584
                $sql .= (isset($multicurrency_code) ? "'" . $this->db->escape($multicurrency_code) . "'" : 'null') . ",";
585
                $sql .= " '" . $this->db->idate($now) . "',";
586
                $sql .= " " . ((int) $this->id) . ",";
587
                $sql .= " " . ((int) $fourn->id) . ",";
588
                $sql .= " '" . $this->db->escape($ref_fourn) . "',";
589
                $sql .= " '" . $this->db->escape($desc_fourn) . "',";
590
                $sql .= " " . ((int) $user->id) . ",";
591
                $sql .= " " . price2num($buyprice) . ",";
592
                $sql .= " " . ((float) $qty) . ",";
593
                $sql .= " " . ((float) $remise_percent) . ",";
594
                $sql .= " " . ((float) $remise) . ",";
595
                $sql .= " " . price2num($unitBuyPrice) . ",";
596
                $sql .= " " . price2num($tva_tx) . ",";
597
                $sql .= " " . price2num($charges) . ",";
598
                $sql .= " " . ((int) $availability) . ",";
599
                $sql .= " " . ($newdefaultvatcode ? "'" . $this->db->escape($newdefaultvatcode) . "'" : "null") . ",";
600
                $sql .= " " . ((int) $newnpr) . ",";
601
                $sql .= $conf->entity . ",";
602
                $sql .= ($delivery_time_days != '' ? ((int) $delivery_time_days) : 'null') . ",";
603
                $sql .= (empty($supplier_reputation) ? 'NULL' : "'" . $this->db->escape($supplier_reputation) . "'") . ",";
604
                $sql .= (empty($barcode) ? 'NULL' : "'" . $this->db->escape($barcode) . "'") . ",";
605
                $sql .= (empty($fk_barcode_type) ? 'NULL' : "'" . $this->db->escape($fk_barcode_type) . "'");
606
                if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
607
                    $sql .= ", " . (empty($this->packaging) ? '1' : "'" . $this->db->escape($this->packaging) . "'");
608
                }
609
                $sql .= ")";
610
611
                $this->product_fourn_price_id = 0;
612
613
                $resql = $this->db->query($sql);
614
                if ($resql) {
615
                    $this->product_fourn_price_id = $this->db->last_insert_id(MAIN_DB_PREFIX . "product_fournisseur_price");
616
                } else {
617
                    $this->error = $this->db->lasterror();
618
                    $error++;
619
                }
620
621
                if (!$error) {
622
                    if (!empty($options) && is_array($options)) {
623
                        $productfournisseurprice = new ProductFournisseurPrice($this->db);
624
                        $res = $productfournisseurprice->fetch($this->product_fourn_price_id);
625
                        if ($res > 0) {
626
                            foreach ($options as $key => $value) {
627
                                $productfournisseurprice->array_options[$key] = $value;
628
                            }
629
                            $res = $productfournisseurprice->update($user);
630
                            if ($res < 0) {
631
                                $this->error = $productfournisseurprice->error;
632
                                $this->errors = $productfournisseurprice->errors;
633
                                $error++;
634
                            }
635
                        }
636
                    }
637
                }
638
639
                if (!$error && !getDolGlobalString('PRODUCT_PRICE_SUPPLIER_NO_LOG')) {
640
                    // Add record into log table
641
                    // $this->product_fourn_price_id must be set
642
                    $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
643
                    if ($result < 0) {
644
                        $error++;
645
                    }
646
                }
647
648
                if (!$error) {
649
                    // Call trigger
650
                    $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE', $user);
651
                    if ($result < 0) {
652
                        $error++;
653
                    }
654
                    // End call triggers
655
656
                    if (empty($error)) {
657
                        $this->db->commit();
658
                        return $this->product_fourn_price_id;
659
                    } else {
660
                        $this->db->rollback();
661
                        return -1;
662
                    }
663
                } else {
664
                    $this->error = $this->db->lasterror() . " sql=" . $sql;
665
                    $this->db->rollback();
666
                    return -2;
667
                }
668
            } else {
669
                $this->error = $this->db->lasterror() . " sql=" . $sql;
670
                $this->db->rollback();
671
                return -1;
672
            }
673
        }
674
    }
675
676
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
677
    /**
678
     *    Loads the price information of a provider
679
     *
680
     *    @param    int     $rowid              Line id
681
     *    @param    int     $ignore_expression  Ignores the math expression for calculating price and uses the db value instead
682
     *    @return   int                         Return integer < 0 if KO, 0 if OK but not found, > 0 if OK
683
     */
684
    public function fetch_product_fournisseur_price($rowid, $ignore_expression = 0)
685
    {
686
		// phpcs:enable
687
        global $conf;
688
689
        $sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.default_vat_code, pfp.info_bits as fourn_tva_npr, pfp.fk_availability,";
690
        $sql .= " pfp.fk_soc, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product, pfp.charges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,";
691
        $sql .= " pfp.supplier_reputation, pfp.fk_user, pfp.datec,";
692
        $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
693
        $sql .= " pfp.barcode, pfp.fk_barcode_type, pfp.packaging,";
694
        $sql .= " p.ref as product_ref, p.tosell as status, p.tobuy as status_buy";
695
        $sql .= " FROM " . MAIN_DB_PREFIX . "product_fournisseur_price as pfp, " . MAIN_DB_PREFIX . "product as p";
696
        $sql .= " WHERE pfp.rowid = " . (int) $rowid;
697
        $sql .= " AND pfp.fk_product = p.rowid";
698
699
        dol_syslog(get_class($this) . "::fetch_product_fournisseur_price", LOG_DEBUG);
700
        $resql = $this->db->query($sql);
701
        if ($resql) {
702
            $obj = $this->db->fetch_object($resql);
703
            if ($obj) {
704
                $this->product_fourn_price_id = $rowid;
705
                $this->id = $obj->fk_product;
706
707
                $this->fk_product               = $obj->fk_product;
708
                $this->product_id               = $obj->fk_product;
709
                $this->product_ref              = $obj->product_ref;
710
                $this->status                   = $obj->status;
711
                $this->status_buy               = $obj->status_buy;
712
                $this->fourn_id                 = $obj->fk_soc;
713
                $this->fourn_ref                = $obj->ref_fourn; // deprecated
714
                $this->ref_supplier             = $obj->ref_fourn;
715
                $this->desc_supplier            = $obj->desc_fourn;
716
                $this->fourn_price = $obj->price;
717
                $this->fourn_charges            = $obj->charges; // when getDolGlobalString('PRODUCT_CHARGES') is set
718
                $this->fourn_qty                = $obj->quantity;
719
                $this->fourn_remise_percent     = $obj->remise_percent;
720
                $this->fourn_remise             = $obj->remise;
721
                $this->fourn_unitprice          = $obj->unitprice;
722
                $this->fourn_tva_tx             = $obj->tva_tx;
723
                $this->fourn_tva_npr            = $obj->fourn_tva_npr;
724
                // Add also localtaxes
725
                $this->fk_availability = $obj->fk_availability;
726
                $this->delivery_time_days = $obj->delivery_time_days;
727
                $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
728
                $this->supplier_reputation      = $obj->supplier_reputation;
729
                $this->default_vat_code         = $obj->default_vat_code;
730
                $this->user_id                  = $obj->fk_user;
731
                $this->date_creation            = $this->db->jdate($obj->datec);
732
                $this->fourn_multicurrency_price       = $obj->multicurrency_price;
733
                $this->fourn_multicurrency_unitprice   = $obj->multicurrency_unitprice;
734
                $this->fourn_multicurrency_tx          = $obj->multicurrency_tx;
735
                $this->fourn_multicurrency_id          = $obj->fk_multicurrency;
736
                $this->fourn_multicurrency_code        = $obj->multicurrency_code;
737
                if (isModEnabled('barcode')) {
738
                    $this->fourn_barcode = $obj->barcode; // deprecated
739
                    $this->fourn_fk_barcode_type = $obj->fk_barcode_type; // deprecated
740
                    $this->supplier_barcode = $obj->barcode;
741
                    $this->supplier_fk_barcode_type = $obj->fk_barcode_type;
742
                }
743
                $this->packaging = $obj->packaging;
744
745
                if (isModEnabled('dynamicprices') && empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) {
746
                    require_once constant('DOL_DOCUMENT_ROOT') . '/product/dynamic_price/class/price_parser.class.php';
747
                    $priceparser = new PriceParser($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Fourn\Classes\PriceParser was not found. Did you mean PriceParser? If so, make sure to prefix the type with \.
Loading history...
748
                    $price_result = $priceparser->parseProductSupplier($this);
749
                    if ($price_result >= 0) {
750
                        $this->fourn_price = $price_result;
751
                        //recalculation of unitprice, as probably the price changed...
752
                        if ($this->fourn_qty != 0) {
753
                            $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU');
754
                        } else {
755
                            $this->fourn_unitprice = "";
756
                        }
757
                    }
758
                }
759
760
                return 1;
761
            } else {
762
                return 0;
763
            }
764
        } else {
765
            $this->error = $this->db->lasterror();
766
            return -1;
767
        }
768
    }
769
770
771
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
772
    /**
773
     *    List all supplier prices of a product
774
     *
775
     *    @param    int         $prodid     Id of product
776
     *    @param    string      $sortfield  Sort field
777
     *    @param    string      $sortorder  Sort order
778
     *    @param    int         $limit      Limit
779
     *    @param    int         $offset     Offset
780
     *    @param    int         $socid      Filter on a third party id
781
     *    @return   array|int               Array of ProductFournisseur with new properties to define supplier price
782
     *    @see find_min_price_product_fournisseur()
783
     */
784
    public function list_product_fournisseur_price($prodid, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0, $socid = 0)
785
    {
786
		// phpcs:enable
787
        global $conf;
788
789
        $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id, p.ref as product_ref, p.tosell as status, p.tobuy as status_buy, ";
790
        $sql .= " pfp.rowid as product_fourn_pri_id, pfp.entity, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product as product_fourn_id, pfp.fk_supplier_price_expression,";
791
        $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability, pfp.charges, pfp.info_bits, pfp.delivery_time_days, pfp.supplier_reputation,";
792
        $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code, pfp.datec, pfp.tms,";
793
        $sql .= " pfp.barcode, pfp.fk_barcode_type, pfp.packaging, pfp.status as pfstatus";
794
        $sql .= " FROM " . MAIN_DB_PREFIX . "product_fournisseur_price as pfp, " . MAIN_DB_PREFIX . "product as p, " . MAIN_DB_PREFIX . "societe as s";
795
        $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
796
        $sql .= " AND pfp.fk_soc = s.rowid AND pfp.fk_product = p.rowid";
797
        $sql .= ($socid > 0 ? ' AND pfp.fk_soc = ' . ((int) $socid) : '');
798
        $sql .= " AND s.status = 1"; // only enabled company selected
799
        $sql .= " AND pfp.fk_product = " . ((int) $prodid);
800
        if (empty($sortfield)) {
801
            $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price";
802
        } else {
803
            $sql .= $this->db->order($sortfield, $sortorder);
804
        }
805
        $sql .= $this->db->plimit($limit, $offset);
806
        dol_syslog(get_class($this) . "::list_product_fournisseur_price", LOG_DEBUG);
807
808
        $resql = $this->db->query($sql);
809
        if ($resql) {
810
            $retarray = array();
811
812
            while ($record = $this->db->fetch_array($resql)) {
813
                //define base attribute
814
                $prodfourn = new ProductFournisseur($this->db);
815
816
                $prodfourn->product_ref = $record["product_ref"];
817
                $prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"];
818
                $prodfourn->status                  = $record["status"];
819
                $prodfourn->status_buy              = $record["status_buy"];
820
                $prodfourn->product_fourn_id = $record["product_fourn_id"];
821
                $prodfourn->product_fourn_entity = $record["entity"];
822
                $prodfourn->ref_supplier            = $record["ref_fourn"];
823
                $prodfourn->fourn_ref = $record["ref_fourn"];
824
                $prodfourn->desc_supplier = $record["desc_fourn"];
825
                $prodfourn->fourn_price             = $record["price"];
826
                $prodfourn->fourn_qty = $record["quantity"];
827
                $prodfourn->fourn_remise_percent = $record["remise_percent"];
828
                $prodfourn->fourn_remise = $record["remise"];
829
                $prodfourn->fourn_unitprice = $record["unitprice"];
830
                $prodfourn->fourn_charges = $record["charges"]; // when getDolGlobalString('PRODUCT_CHARGES') is set
831
                $prodfourn->fourn_tva_tx = $record["tva_tx"];
832
                $prodfourn->fourn_id = $record["fourn_id"];
833
                $prodfourn->fourn_name = $record["supplier_name"];
834
                $prodfourn->fk_availability         = $record["fk_availability"];
835
                $prodfourn->delivery_time_days = $record["delivery_time_days"];
836
                $prodfourn->id = $prodid;
837
                $prodfourn->fourn_tva_npr                   = $record["info_bits"];
838
                $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
839
                $prodfourn->supplier_reputation = $record["supplier_reputation"];
840
                $prodfourn->fourn_date_creation          = $this->db->jdate($record['datec']);
841
                $prodfourn->fourn_date_modification      = $this->db->jdate($record['tms']);
842
843
                $prodfourn->fourn_multicurrency_price       = $record["multicurrency_price"];
844
                $prodfourn->fourn_multicurrency_unitprice   = $record["multicurrency_unitprice"];
845
                $prodfourn->fourn_multicurrency_tx          = $record["multicurrency_tx"];
846
                $prodfourn->fourn_multicurrency_id          = $record["fk_multicurrency"];
847
                $prodfourn->fourn_multicurrency_code        = $record["multicurrency_code"];
848
849
                $prodfourn->packaging = $record["packaging"];
850
                $prodfourn->status = $record["pfstatus"];
851
852
                if (isModEnabled('barcode')) {
853
                    $prodfourn->supplier_barcode = $record["barcode"];
854
                    $prodfourn->supplier_fk_barcode_type = $record["fk_barcode_type"];
855
                }
856
857
                if (isModEnabled('dynamicprices') && !empty($prodfourn->fk_supplier_price_expression)) {
858
                    require_once constant('DOL_DOCUMENT_ROOT') . '/product/dynamic_price/class/price_parser.class.php';
859
                    $priceparser = new PriceParser($this->db);
860
                    $price_result = $priceparser->parseProductSupplier($prodfourn);
861
                    if ($price_result >= 0) {
862
                        $prodfourn->fourn_price = $price_result;
863
                        $prodfourn->fourn_unitprice = null; //force recalculation of unitprice, as probably the price changed...
864
                    }
865
                }
866
867
                if (!isset($prodfourn->fourn_unitprice)) {
868
                    if ($prodfourn->fourn_qty != 0) {
869
                        $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU');
870
                    } else {
871
                        $prodfourn->fourn_unitprice = "";
872
                    }
873
                }
874
875
                $retarray[] = $prodfourn;
876
            }
877
878
            $this->db->free($resql);
879
            return $retarray;
880
        } else {
881
            $this->error = $this->db->error();
882
            return -1;
883
        }
884
    }
885
886
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
887
    /**
888
     *  Load properties for minimum price
889
     *
890
     *  @param  int     $prodid     Product id
891
     *  @param  float   $qty        Minimum quantity
892
     *  @param  int     $socid      get min price for specific supplier
893
     *  @return int                 Return integer <0 if KO, 0=Not found of no product id provided, >0 if OK
894
     *  @see list_product_fournisseur_price()
895
     */
896
    public function find_min_price_product_fournisseur($prodid, $qty = 0, $socid = 0)
897
    {
898
		// phpcs:enable
899
        global $conf;
900
901
        if (empty($prodid)) {
902
            dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING);
903
            return 0;
904
        }
905
906
        $this->product_fourn_price_id = 0;
907
        $this->product_fourn_id       = 0;
908
        $this->fourn_ref              = '';
909
        $this->fourn_price            = 0;
910
        $this->fourn_qty              = 0;
911
        $this->fourn_remise_percent   = 0;
912
        $this->fourn_remise           = 0;
913
        $this->fourn_unitprice        = 0;
914
        $this->fourn_id               = 0;
915
        $this->fourn_name             = '';
916
        $this->delivery_time_days     = 0;
917
        $this->id                     = 0;
918
919
        $this->fourn_multicurrency_price       = 0;
920
        $this->fourn_multicurrency_unitprice   = 0;
921
        $this->fourn_multicurrency_tx          = 0;
922
        $this->fourn_multicurrency_id          = '';
923
        $this->fourn_multicurrency_code        = '';
924
925
        $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
926
        $sql .= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,";
927
        $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges,";
928
        $sql .= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression, pfp.delivery_time_days";
929
        $sql .= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
930
        $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s, " . MAIN_DB_PREFIX . "product_fournisseur_price as pfp";
931
        $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
932
        $sql .= " AND pfp.entity IN (" . getEntity('productsupplierprice') . ")";
933
        $sql .= " AND pfp.fk_product = " . ((int) $prodid);
934
        $sql .= " AND pfp.fk_soc = s.rowid";
935
        $sql .= " AND s.status = 1"; // only enabled society
936
        if ($qty > 0) {
937
            $sql .= " AND pfp.quantity <= " . ((float) $qty);
938
        }
939
        if ($socid > 0) {
940
            $sql .= ' AND pfp.fk_soc = ' . ((int) $socid);
941
        }
942
943
        dol_syslog(get_class($this) . "::find_min_price_product_fournisseur", LOG_DEBUG);
944
945
        $resql = $this->db->query($sql);
946
        if ($resql) {
947
            $record_array = array();
948
949
            //Store each record to array for later search of min
950
            while ($record = $this->db->fetch_array($resql)) {
951
                $record_array[] = $record;
952
            }
953
954
            if (count($record_array) == 0) {
955
                $this->db->free($resql);
956
                return 0;
957
            } else {
958
                $min = -1;
959
                foreach ($record_array as $record) {
960
                    $fourn_price = $record["price"];
961
                    // calculate unit price for quantity 1
962
                    $fourn_unitprice = $record["unitprice"];
963
                    $fourn_unitprice_with_discount = $record["unitprice"] * (1 - $record["remise_percent"] / 100);
964
965
                    if (isModEnabled('dynamicprices') && !empty($record["fk_supplier_price_expression"])) {
966
                        $prod_supplier = new ProductFournisseur($this->db);
967
                        $prod_supplier->product_fourn_price_id = $record["product_fourn_price_id"];
968
                        $prod_supplier->id = $prodid;
969
                        $prod_supplier->fourn_qty = $record["quantity"];
970
                        $prod_supplier->fourn_tva_tx = $record["tva_tx"];
971
                        $prod_supplier->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
972
973
                        require_once constant('DOL_DOCUMENT_ROOT') . '/product/dynamic_price/class/price_parser.class.php';
974
                        $priceparser = new PriceParser($this->db);
975
                        $price_result = $priceparser->parseProductSupplier($prod_supplier);
976
                        if ($price_result >= 0) {
977
                            $fourn_price = price2num($price_result, 'MU');
978
                            if ($record["quantity"] != 0) {
979
                                $fourn_unitprice = price2num($fourn_price / $record["quantity"], 'MU');
980
                            } else {
981
                                $fourn_unitprice = $fourn_price;
982
                            }
983
                            $fourn_unitprice_with_discount = $fourn_unitprice * (1 - $record["remise_percent"] / 100);
984
                        }
985
                    }
986
                    if ($fourn_unitprice < $min || $min == -1) {
987
                        $this->product_fourn_price_id   = $record["product_fourn_price_id"];
988
                        $this->ref_supplier             = $record["ref_fourn"];
989
                        $this->ref_fourn                = $record["ref_fourn"]; // deprecated
990
                        $this->fourn_ref                = $record["ref_fourn"]; // deprecated
991
                        $this->fourn_price              = $fourn_price;
992
                        $this->fourn_qty                = $record["quantity"];
993
                        $this->fourn_remise_percent     = $record["remise_percent"];
994
                        $this->fourn_remise             = $record["remise"];
995
                        $this->fourn_unitprice          = $fourn_unitprice;
996
                        $this->fourn_unitprice_with_discount = $fourn_unitprice_with_discount;
997
                        $this->fourn_charges            = $record["charges"]; // when getDolGlobalString('PRODUCT_CHARGES') is set
998
                        $this->fourn_tva_tx             = $record["tva_tx"];
999
                        $this->fourn_id                 = $record["fourn_id"];
1000
                        $this->fourn_name               = $record["supplier_name"];
1001
                        $this->delivery_time_days = $record["delivery_time_days"];
1002
                        $this->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
1003
                        $this->id                       = $prodid;
1004
                        $this->fourn_multicurrency_price       = $record["multicurrency_price"];
1005
                        $this->fourn_multicurrency_unitprice   = $record["multicurrency_unitprice"];
1006
                        $this->fourn_multicurrency_tx          = $record["multicurrency_tx"];
1007
                        $this->fourn_multicurrency_id          = $record["fk_multicurrency"];
1008
                        $this->fourn_multicurrency_code        = $record["multicurrency_code"];
1009
                        $min = $fourn_unitprice;
1010
                    }
1011
                }
1012
            }
1013
1014
            $this->db->free($resql);
1015
            return 1;
1016
        } else {
1017
            $this->error = $this->db->error();
1018
            return -1;
1019
        }
1020
    }
1021
1022
    /**
1023
     *  Sets the supplier price expression
1024
     *
1025
     *  @param  int     $expression_id  Expression
1026
     *  @return int                     Return integer <0 if KO, >0 if OK
1027
     */
1028
    public function setSupplierPriceExpression($expression_id)
1029
    {
1030
        global $conf;
1031
1032
        // Clean parameters
1033
        $this->db->begin();
1034
        $expression_id = $expression_id != 0 ? $expression_id : 'NULL';
1035
1036
        $sql = "UPDATE " . MAIN_DB_PREFIX . "product_fournisseur_price";
1037
        $sql .= " SET fk_supplier_price_expression = " . ((int) $expression_id);
1038
        $sql .= " WHERE rowid = " . ((int) $this->product_fourn_price_id);
1039
1040
        dol_syslog(get_class($this) . "::setSupplierPriceExpression", LOG_DEBUG);
1041
1042
        $resql = $this->db->query($sql);
1043
        if ($resql) {
1044
            $this->db->commit();
1045
            return 1;
1046
        } else {
1047
            $this->error = $this->db->error() . " sql=" . $sql;
1048
            $this->db->rollback();
1049
            return -1;
1050
        }
1051
    }
1052
1053
    /**
1054
     *  Display supplier of product
1055
     *
1056
     *  @param  int     $withpicto      Add picto
1057
     *  @param  string  $option         Target of link ('', 'customer', 'prospect', 'supplier')
1058
     *  @param  int     $maxlen         Max length of name
1059
     *  @param  integer $notooltip      1=Disable tooltip
1060
     *  @return string                  String with supplier price
1061
     *  TODO Remove this method. Use getNomUrl directly.
1062
     */
1063
    public function getSocNomUrl($withpicto = 0, $option = 'supplier', $maxlen = 0, $notooltip = 0)
1064
    {
1065
        $thirdparty = new Fournisseur($this->db);
1066
        $thirdparty->fetch($this->fourn_id);
1067
1068
        return $thirdparty->getNomUrl($withpicto, $option, $maxlen, $notooltip);
1069
    }
1070
1071
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1072
    /**
1073
     *  Display price of product
1074
     *
1075
     *  @param  int     $showunitprice    Show "Unit price" into output string
1076
     *  @param  int     $showsuptitle     Show "Supplier" into output string
1077
     *  @param  int     $maxlen           Max length of name
1078
     *  @param  integer $notooltip        1=Disable tooltip
1079
     *  @param  array   $productFournList list of ProductFournisseur objects
1080
     *                                    to display in table format.
1081
     *  @return string                    String with supplier price
1082
     */
1083
    public function display_price_product_fournisseur($showunitprice = 1, $showsuptitle = 1, $maxlen = 0, $notooltip = 0, $productFournList = array())
1084
    {
1085
		// phpcs:enable
1086
        global $conf, $langs;
1087
1088
        $out = '';
1089
        $langs->load("suppliers");
1090
        if (count($productFournList) > 0) {
1091
            $out .= '<table class="nobordernopadding" width="100%">';
1092
            $out .= '<tr><td class="liste_titre right">' . ($showunitprice ? $langs->trans("Price") . ' ' . $langs->trans("HT") : '') . '</td>';
1093
            $out .= '<td class="liste_titre right">' . ($showunitprice ? $langs->trans("QtyMin") : '') . '</td>';
1094
            $out .= '<td class="liste_titre">' . $langs->trans("Supplier") . '</td>';
1095
            $out .= '<td class="liste_titre">' . $langs->trans("SupplierRef") . '</td></tr>';
1096
            foreach ($productFournList as $productFourn) {
1097
                $out .= '<tr><td class="right">' . ($showunitprice ? price($productFourn->fourn_unitprice * (1 - $productFourn->fourn_remise_percent / 100) - $productFourn->fourn_remise) : '') . '</td>';
1098
                $out .= '<td class="right">' . ($showunitprice ? $productFourn->fourn_qty : '') . '</td>';
1099
                $out .= '<td>' . $productFourn->getSocNomUrl(1, 'supplier', $maxlen, $notooltip) . '</td>';
1100
                $out .= '<td>' . $productFourn->fourn_ref . '<td></tr>';
1101
            }
1102
            $out .= '</table>';
1103
        } else {
1104
            $out = ($showunitprice ? price($this->fourn_unitprice * (1 - $this->fourn_remise_percent / 100) + $this->fourn_remise, 0, $langs, 1, -1, -1, $conf->currency) . ' ' . $langs->trans("HT") . ' &nbsp; <span class="opacitymedium">(</span>' : '');
1105
            $out .= ($showsuptitle ? '<span class="opacitymedium">' . $langs->trans("Supplier") . '</span>: ' : '') . $this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip) . ' / <span class="opacitymedium">' . $langs->trans("SupplierRef") . '</span>: ' . $this->ref_supplier;
1106
            $out .= ($showunitprice ? '<span class="opacitymedium">)</span>' : '');
1107
        }
1108
        return $out;
1109
    }
1110
1111
    /**
1112
     * Function used to replace a thirdparty id with another one.
1113
     *
1114
     * @param   DoliDB  $dbs        Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
1115
     * @param   int     $origin_id  Old thirdparty id
1116
     * @param   int     $dest_id    New thirdparty id
1117
     * @return  bool
1118
     */
1119
    public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
1120
    {
1121
        $tables = array(
1122
            'product_fournisseur_price'
1123
        );
1124
1125
        return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
1126
    }
1127
1128
    /**
1129
     * Function used to replace a product id with another one.
1130
     *
1131
     * @param   DoliDB  $dbs        Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
1132
     * @param   int     $origin_id  Old thirdparty id
1133
     * @param   int     $dest_id    New thirdparty id
1134
     * @return  bool
1135
     */
1136
    public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
1137
    {
1138
        $tables = array(
1139
            'product_fournisseur_price'
1140
        );
1141
1142
        return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
1143
    }
1144
1145
    /**
1146
     *    List supplier prices log of a supplier price
1147
     *
1148
     *    @param    int     $product_fourn_price_id Id of supplier price
1149
     *    @param    string  $sortfield              Sort field
1150
     *    @param    string  $sortorder              Sort order
1151
     *    @param    int     $limit                  Limit
1152
     *    @param    int     $offset                 Offset
1153
     *    @return   array|int   Array of Log prices
1154
     */
1155
    public function listProductFournisseurPriceLog($product_fourn_price_id, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0)
1156
    {
1157
        $sql = "SELECT";
1158
        $sql .= " u.lastname,";
1159
        $sql .= " pfpl.rowid, pfp.ref_fourn as supplier_ref, pfpl.datec,";
1160
        $sql .= " pfpl.price, pfpl.quantity,";
1161
        $sql .= " pfpl.fk_multicurrency, pfpl.multicurrency_code, pfpl.multicurrency_tx, pfpl.multicurrency_price, pfpl.multicurrency_unitprice";
1162
        $sql .= " FROM " . MAIN_DB_PREFIX . "product_fournisseur_price_log as pfpl,";
1163
        $sql .= " " . MAIN_DB_PREFIX . "product_fournisseur_price as pfp,";
1164
        $sql .= " " . MAIN_DB_PREFIX . "user as u";
1165
        $sql .= " WHERE pfp.entity IN (" . getEntity('productprice') . ")";
1166
        $sql .= " AND pfpl.fk_user = u.rowid";
1167
        $sql .= " AND pfp.rowid = pfpl.fk_product_fournisseur";
1168
        $sql .= " AND pfpl.fk_product_fournisseur = " . ((int) $product_fourn_price_id);
1169
        if (empty($sortfield)) {
1170
            $sql .= " ORDER BY pfpl.datec";
1171
        } else {
1172
            $sql .= $this->db->order($sortfield, $sortorder);
1173
        }
1174
        $sql .= $this->db->plimit($limit, $offset);
1175
        dol_syslog(get_class($this) . "::list_product_fournisseur_price_log", LOG_DEBUG);
1176
1177
        $resql = $this->db->query($sql);
1178
        if ($resql) {
1179
            $retarray = array();
1180
1181
            while ($obj = $this->db->fetch_object($resql)) {
1182
                $tmparray = array();
1183
                $tmparray['rowid'] = $obj->rowid;
1184
                $tmparray['supplier_ref'] = $obj->supplier_ref;
1185
                $tmparray['datec'] = $this->db->jdate($obj->datec);
1186
                $tmparray['lastname'] = $obj->lastname;
1187
                $tmparray['price'] = $obj->price;
1188
                $tmparray['quantity'] = $obj->quantity;
1189
                $tmparray['fk_multicurrency'] = $obj->fk_multicurrency;
1190
                $tmparray['multicurrency_code'] = $obj->multicurrency_code;
1191
                $tmparray['multicurrency_tx'] = $obj->multicurrency_tx;
1192
                $tmparray['multicurrency_price'] = $obj->multicurrency_price;
1193
                $tmparray['multicurrency_unitprice'] = $obj->multicurrency_unitprice;
1194
1195
                $retarray[] = $tmparray;
1196
            }
1197
1198
            $this->db->free($resql);
1199
            return $retarray;
1200
        } else {
1201
            $this->error = $this->db->error();
1202
            return -1;
1203
        }
1204
    }
1205
1206
    /**
1207
     *  Display log price of product supplier price
1208
     *
1209
     *  @param  array   $productFournLogList    list of ProductFournisseur price log objects
1210
     *                                          to display in table format.
1211
     *  @return string  HTML String with supplier price
1212
     */
1213
    public function displayPriceProductFournisseurLog($productFournLogList = array())
1214
    {
1215
        global $conf, $langs;
1216
1217
        $out = '';
1218
        $langs->load("suppliers");
1219
        if (count($productFournLogList) > 0) {
1220
            $out .= '<table class="noborder centpercent">';
1221
            $out .= '<tr class="liste_titre"><td class="liste_titre">' . $langs->trans("Date") . '</td>';
1222
            $out .= '<td class="liste_titre right">' . $langs->trans("Price") . '</td>';
1223
            //$out .= '<td class="liste_titre right">'.$langs->trans("QtyMin").'</td>';
1224
            $out .= '<td class="liste_titre">' . $langs->trans("User") . '</td></tr>';
1225
            foreach ($productFournLogList as $productFournLog) {
1226
                $out .= '<tr><td>' . dol_print_date($productFournLog['datec'], 'dayhour', 'tzuser') . '</td>';
1227
                $out .= '<td class="right">' . price($productFournLog['price'], 0, $langs, 1, -1, -1, $conf->currency);
1228
                if ($productFournLog['multicurrency_code'] != $conf->currency) {
1229
                    $out .= ' (' . price($productFournLog['multicurrency_price'], 0, $langs, 1, -1, -1, $productFournLog['multicurrency_code']) . ')';
1230
                }
1231
                $out .= '</td>';
1232
                //$out.= '<td class="right">'.$productFournLog['quantity'].'</td>';
1233
                $out .= '<td>' . $productFournLog['lastname'] . '</td></tr>';
1234
            }
1235
            $out .= '</table>';
1236
        }
1237
        return $out;
1238
    }
1239
1240
1241
    /**
1242
     *  Return a link to the object card (with optionally the picto).
1243
     *  Used getNomUrl of ProductFournisseur if a specific supplier ref is loaded. Otherwise use Product->getNomUrl().
1244
     *
1245
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
1246
     *  @param  string  $option                     On what the link point to ('nolink', ...)
1247
     *  @param  int     $maxlength                  Maxlength of ref
1248
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1249
     *  @param  int     $notooltip                  No tooltip
1250
     *  @param  string  $morecss                    ''=Add more css on link
1251
     *  @param  int     $add_label                  0=Default, 1=Add label into string, >1=Add first chars into string
1252
     *  @param  string  $sep                        ' - '=Separator between ref and label if option 'add_label' is set
1253
     *  @return string                              String with URL
1254
     */
1255
    public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ')
1256
    {
1257
        global $db, $conf, $langs, $hookmanager;
1258
1259
        if (!empty($conf->dol_no_mouse_hover)) {
1260
            $notooltip = 1; // Force disable tooltips
1261
        }
1262
1263
        $result = '';
1264
        $label = '';
1265
1266
        $newref = $this->ref;
1267
        if ($maxlength) {
1268
            $newref = dol_trunc($newref, $maxlength, 'middle');
1269
        }
1270
1271
        if (!empty($this->entity)) {
1272
            $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
1273
            if ($this->nbphoto > 0) {
1274
                $label .= '<div class="photointooltip">';
1275
                $label .= $tmpphoto;
1276
                $label .= '</div><div style="clear: both;"></div>';
1277
            }
1278
        }
1279
1280
        if ($this->type == Product::TYPE_PRODUCT) {
1281
            $label .= img_picto('', 'product') . ' <u class="paddingrightonly">' . $langs->trans("Product") . '</u>';
1282
        } elseif ($this->type == Product::TYPE_SERVICE) {
1283
            $label .= img_picto('', 'service') . ' <u class="paddingrightonly">' . $langs->trans("Service") . '</u>';
1284
        }
1285
        if (isset($this->status) && isset($this->status_buy)) {
1286
            $label .= ' ' . $this->getLibStatut(5, 0);
1287
            $label .= ' ' . $this->getLibStatut(5, 1);
1288
        }
1289
1290
        if (!empty($this->ref)) {
1291
            $label .= '<br><b>' . $langs->trans('ProductRef') . ':</b> ' . ($this->ref ? $this->ref : $this->product_ref);
1292
        }
1293
        if (!empty($this->label)) {
1294
            $label .= '<br><b>' . $langs->trans('ProductLabel') . ':</b> ' . $this->label;
1295
        }
1296
        $label .= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
1297
1298
        if ($this->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1299
            if (isModEnabled('productbatch')) {
1300
                $langs->load("productbatch");
1301
                $label .= "<br><b>" . $langs->trans("ManageLotSerial") . '</b>: ' . $this->getLibStatut(0, 2);
1302
            }
1303
        }
1304
        if (isModEnabled('barcode')) {
1305
            $label .= '<br><b>' . $langs->trans('BarCode') . ':</b> ' . $this->barcode;
1306
        }
1307
1308
        if ($this->type == Product::TYPE_PRODUCT) {
1309
            if ($this->weight) {
1310
                $label .= "<br><b>" . $langs->trans("Weight") . '</b>: ' . $this->weight . ' ' . measuringUnitString(0, "weight", $this->weight_units);
1311
            }
1312
            $labelsize = "";
1313
            if ($this->length) {
1314
                $labelsize .= ($labelsize ? " - " : "") . "<b>" . $langs->trans("Length") . '</b>: ' . $this->length . ' ' . measuringUnitString(0, 'size', $this->length_units);
1315
            }
1316
            if ($this->width) {
1317
                $labelsize .= ($labelsize ? " - " : "") . "<b>" . $langs->trans("Width") . '</b>: ' . $this->width . ' ' . measuringUnitString(0, 'size', $this->width_units);
1318
            }
1319
            if ($this->height) {
1320
                $labelsize .= ($labelsize ? " - " : "") . "<b>" . $langs->trans("Height") . '</b>: ' . $this->height . ' ' . measuringUnitString(0, 'size', $this->height_units);
1321
            }
1322
            if ($labelsize) {
1323
                $label .= "<br>" . $labelsize;
1324
            }
1325
1326
            $labelsurfacevolume = "";
1327
            if ($this->surface) {
1328
                $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "") . "<b>" . $langs->trans("Surface") . '</b>: ' . $this->surface . ' ' . measuringUnitString(0, 'surface', $this->surface_units);
1329
            }
1330
            if ($this->volume) {
1331
                $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "") . "<b>" . $langs->trans("Volume") . '</b>: ' . $this->volume . ' ' . measuringUnitString(0, 'volume', $this->volume_units);
1332
            }
1333
            if ($labelsurfacevolume) {
1334
                $label .= "<br>" . $labelsurfacevolume;
1335
            }
1336
        }
1337
1338
        if (isModEnabled('accounting') && $this->status) {
1339
            include_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
1340
            $label .= '<br><b>' . $langs->trans('ProductAccountancySellCode') . ':</b> ' . length_accountg($this->accountancy_code_sell);
1341
            $label .= '<br><b>' . $langs->trans('ProductAccountancySellIntraCode') . ':</b> ' . length_accountg($this->accountancy_code_sell_intra);
1342
            $label .= '<br><b>' . $langs->trans('ProductAccountancySellExportCode') . ':</b> ' . length_accountg($this->accountancy_code_sell_export);
1343
        }
1344
        if (isModEnabled('accounting') && $this->status_buy) {
1345
            include_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
1346
            $label .= '<br><b>' . $langs->trans('ProductAccountancyBuyCode') . ':</b> ' . length_accountg($this->accountancy_code_buy);
1347
            $label .= '<br><b>' . $langs->trans('ProductAccountancyBuyIntraCode') . ':</b> ' . length_accountg($this->accountancy_code_buy_intra);
1348
            $label .= '<br><b>' . $langs->trans('ProductAccountancyBuyExportCode') . ':</b> ' . length_accountg($this->accountancy_code_buy_export);
1349
        }
1350
1351
        $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id, 'pfpl.datec', 'DESC'); // set sort order here
1352
        if (is_array($logPrices) && count($logPrices) > 0) {
1353
            $label .= '<br><br>';
1354
            $label .= '<u>' . $langs->trans("History") . '</u>';
1355
            $label .= $this->displayPriceProductFournisseurLog($logPrices);
1356
        }
1357
1358
        $url = constant('BASE_URL') . '/product/price_suppliers.php?id=' . ((int) $this->id) . '&action=create_price&token=' . newToken() . '&socid=' . ((int) $this->fourn_id) . '&rowid=' . ((int) $this->product_fourn_price_id);
1359
1360
        if ($option != 'nolink') {
1361
            // Add param to save lastsearch_values or not
1362
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1363
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1364
                $add_save_lastsearch_values = 1;
1365
            }
1366
            if ($add_save_lastsearch_values) {
1367
                $url .= '&save_lastsearch_values=1';
1368
            }
1369
        }
1370
1371
        $linkclose = '';
1372
        if (empty($notooltip)) {
1373
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1374
                $label = $langs->trans("SupplierRef");
1375
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
1376
            }
1377
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
1378
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
1379
        } else {
1380
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
1381
        }
1382
1383
        $linkstart = '<a href="' . $url . '"';
1384
        $linkstart .= $linkclose . '>';
1385
        $linkend = '</a>';
1386
1387
        $result .= $linkstart;
1388
        if ($withpicto) {
1389
            $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1390
        }
1391
        if ($withpicto != 2) {
1392
            $result .= $newref . ($this->ref_supplier ? ' (' . $this->ref_supplier . ')' : '');
1393
        }
1394
        $result .= $linkend;
1395
        if ($withpicto != 2) {
1396
            $result .= (($add_label && $this->label) ? $sep . dol_trunc($this->label, ($add_label > 1 ? $add_label : 0)) : '');
1397
        }
1398
1399
        global $action;
1400
        $hookmanager->initHooks(array($this->element . 'dao'));
1401
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1402
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1403
        if ($reshook > 0) {
1404
            $result = $hookmanager->resPrint;
1405
        } else {
1406
            $result .= $hookmanager->resPrint;
1407
        }
1408
        return $result;
1409
    }
1410
1411
    /**
1412
     *  Return the label of the status
1413
     *
1414
     *  @param  int     $mode           0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
1415
     *  @param  int     $type           Type of product
1416
     *  @return string                  Label of status
1417
     */
1418
    public function getLibStatut($mode = 0, $type = 0)      // must be compatible with getLibStatut of inherited Product
1419
    {
1420
        return $this->LibStatut($this->status, $mode);
1421
    }
1422
1423
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1424
    /**
1425
     *  Return the status
1426
     *
1427
     *  @param  int     $status         Id status
1428
     *  @param  int     $mode           0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
1429
     *  @param  int     $type           Type of product
1430
     *  @return string                  Label of status
1431
     */
1432
    public function LibStatut($status, $mode = 0, $type = 0)
1433
    {
1434
		// phpcs:enable
1435
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1436
            global $langs;
1437
            //$langs->load("mymodule@mymodule");
1438
            $this->labelStatus[self::STATUS_OPEN] = $langs->transnoentitiesnoconv('Enabled');
1439
            $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
1440
            $this->labelStatusShort[self::STATUS_OPEN] = $langs->transnoentitiesnoconv('Enabled');
1441
            $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
1442
        }
1443
1444
        $statusType = 'status4';
1445
        //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
1446
        if ($status == self::STATUS_CANCELED) {
1447
            $statusType = 'status6';
1448
        }
1449
1450
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1451
    }
1452
1453
    /**
1454
     * Private function to log price history
1455
     *
1456
     * @param User      $user                           Object user who adds/changes price
1457
     * @param integer   $datec                          date create
1458
     * @param float     $buyprice                       price for qty
1459
     * @param float     $qty                            qty for price
1460
     * @param float     $multicurrency_buyprice         Purchase price for the quantity min in currency
1461
     * @param float     $multicurrency_unitBuyPrice     Unit Purchase price in currency
1462
     * @param float     $multicurrency_tx               Rate currency
1463
     * @param int       $fk_multicurrency               key multi currency
1464
     * @param string    $multicurrency_code             Currency code
1465
     *
1466
     * @return int Return integer < 0 NOK > 0 OK
1467
     */
1468
    private function logPrice($user, $datec, $buyprice, $qty, $multicurrency_buyprice = null, $multicurrency_unitBuyPrice = null, $multicurrency_tx = null, $fk_multicurrency = null, $multicurrency_code = null)
1469
    {
1470
        // Add record into log table
1471
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_fournisseur_price_log(";
1472
        $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
1473
        $sql .= "datec, fk_product_fournisseur,fk_user,price,quantity)";
1474
        $sql .= "values(";
1475
        $sql .= (isset($multicurrency_buyprice) ? "'" . $this->db->escape(price2num($multicurrency_buyprice)) . "'" : 'null') . ",";
1476
        $sql .= (isset($multicurrency_unitBuyPrice) ? "'" . $this->db->escape(price2num($multicurrency_unitBuyPrice)) . "'" : 'null') . ",";
1477
        $sql .= (isset($multicurrency_tx) ? "'" . $this->db->escape($multicurrency_tx) . "'" : '1') . ",";
1478
        $sql .= (isset($fk_multicurrency) ? "'" . $this->db->escape($fk_multicurrency) . "'" : 'null') . ",";
1479
        $sql .= (isset($multicurrency_code) ? "'" . $this->db->escape($multicurrency_code) . "'" : 'null') . ",";
1480
        $sql .= "'" . $this->db->idate($datec) . "',";
1481
        $sql .= " " . ((int) $this->product_fourn_price_id) . ",";
1482
        $sql .= " " . $user->id . ",";
1483
        $sql .= " " . price2num($buyprice) . ",";
1484
        $sql .= " " . price2num($qty);
1485
        $sql .= ")";
1486
1487
        $resql = $this->db->query($sql);
1488
        if (!$resql) {
1489
            return -1;
1490
        } else {
1491
            return 1;
1492
        }
1493
    }
1494
}
1495