Test Failed
Branch main (fda838)
by Rafael
50:22
created

ExpeditionLigne::insert()   F

Complexity

Conditions 17
Paths 305

Size

Total Lines 74
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 48
nc 305
nop 2
dl 0
loc 74
rs 3.0708
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* Copyright (C) 2003-2008  Rodolphe Quiedeville    <[email protected]>
4
 * Copyright (C) 2005-2012	Regis Houssin			<[email protected]>
5
 * Copyright (C) 2007		Franky Van Liedekerke	<[email protected]>
6
 * Copyright (C) 2006-2012	Laurent Destailleur		<[email protected]>
7
 * Copyright (C) 2011-2020	Juanjo Menent			<[email protected]>
8
 * Copyright (C) 2013       Florian Henry		  	<[email protected]>
9
 * Copyright (C) 2014		Cedric GROSS			<[email protected]>
10
 * Copyright (C) 2014-2015  Marcos García           <[email protected]>
11
 * Copyright (C) 2014-2017  Francis Appels          <[email protected]>
12
 * Copyright (C) 2015       Claudio Aschieri        <[email protected]>
13
 * Copyright (C) 2016-2024	Ferran Marcet			<[email protected]>
14
 * Copyright (C) 2018       Nicolas ZABOURI			<[email protected]>
15
 * Copyright (C) 2018-2024  Frédéric France         <[email protected]>
16
 * Copyright (C) 2020       Lenin Rivas         	<[email protected]>
17
 * Copyright (C) 2024		MDW						<[email protected]>
18
 * Copyright (C) 2024       Rafael San José         <[email protected]>
19
 *
20
 * This program is free software; you can redistribute it and/or modify
21
 * it under the terms of the GNU General Public License as published by
22
 * the Free Software Foundation; either version 3 of the License, or
23
 * (at your option) any later version.
24
 *
25
 * This program is distributed in the hope that it will be useful,
26
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28
 * GNU General Public License for more details.
29
 *
30
 * You should have received a copy of the GNU General Public License
31
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
32
 */
33
34
/**
35
 *  \file       htdocs/expedition/class/expedition.class.php
36
 *  \ingroup    expedition
37
 *  \brief      File of class managing the shipments
38
 */
39
40
use DoliCore\Base\GenericDocument;
41
use DoliModules\Billing\Trait\CommonIncoterm;
42
43
require_once DOL_DOCUMENT_ROOT . '/core/class/commonincoterm.class.php';
44
if (isModEnabled("propal")) {
45
    require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php';
46
}
47
if (isModEnabled('order')) {
48
    require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
49
}
50
require_once DOL_DOCUMENT_ROOT . '/expedition/class/expeditionlinebatch.class.php';
51
52
class ExpeditionLigne extends GenericDocumentLine
53
{
54
    /**
55
     * @var string ID to identify managed object
56
     */
57
    public $element = 'expeditiondet';
58
59
    /**
60
     * @var string Name of table without prefix where object is stored
61
     */
62
    public $table_element = 'expeditiondet';
63
64
65
    /**
66
     * Id of the line. Duplicate of $id.
67
     *
68
     * @var int
69
     * @deprecated
70
     */
71
    public $line_id;    // deprecated
72
73
    /**
74
     * @deprecated
75
     * @see $fk_origin_line
76
     */
77
    public $origin_line_id;
78
79
    /**
80
     * Code of object line that is origin of the shipment line.
81
     *
82
     * @var string
83
     */
84
    public $fk_origin;          // Example: 'orderline'
85
86
    /**
87
     * @var int ID
88
     */
89
    public $fk_origin_line;
90
91
    /**
92
     * @var int Id of shipment
93
     */
94
    public $fk_expedition;
95
96
    /**
97
     * @var DoliDB Database handler.
98
     */
99
    public $db;
100
101
    /**
102
     * @var float qty asked From llx_expeditiondet
103
     */
104
    public $qty;
105
106
    /**
107
     * @var float qty shipped
108
     */
109
    public $qty_shipped;
110
111
    /**
112
     * @var int Id of product
113
     */
114
    public $fk_product;
115
116
    // detail of lot and qty = array(id in llx_expeditiondet_batch, fk_expeditiondet, batch, qty, fk_origin_stock)
117
    // We can use this to know warehouse planned to be used for each lot.
118
    public $detail_batch;
119
120
    // detail of warehouses and qty
121
    // We can use this to know warehouse when there is no lot.
122
    public $details_entrepot;
123
124
125
    /**
126
     * @var int Id of warehouse
127
     */
128
    public $entrepot_id;
129
130
131
    /**
132
     * @var float qty asked From llx_commandedet or llx_propaldet
133
     */
134
    public $qty_asked;
135
136
    /**
137
     * @deprecated
138
     * @see $product_ref
139
     */
140
    public $ref;
141
142
    /**
143
     * @var string product ref
144
     */
145
    public $product_ref;
146
147
    /**
148
     * @deprecated
149
     * @see $product_label
150
     */
151
    public $libelle;
152
153
    /**
154
     * @var string product label
155
     */
156
    public $product_label;
157
158
    /**
159
     * @var string product description
160
     * @deprecated
161
     * @see $product_desc
162
     */
163
    public $desc;
164
165
    /**
166
     * @var string product description
167
     */
168
    public $product_desc;
169
170
    /**
171
     * Type of the product. 0 for product, 1 for service
172
     * @var int
173
     */
174
    public $product_type = 0;
175
176
    /**
177
    * @var int rang of line
178
    */
179
    public $rang;
180
181
    /**
182
    * @var float weight
183
    */
184
    public $weight;
185
    public $weight_units;
186
187
    /**
188
    * @var float length
189
    */
190
    public $length;
191
    public $length_units;
192
193
    /**
194
    * @var float width
195
    */
196
    public $width;
197
    public $width_units;
198
199
    /**
200
    * @var float height
201
    */
202
    public $height;
203
    public $height_units;
204
205
    /**
206
    * @var float surface
207
    */
208
    public $surface;
209
    public $surface_units;
210
211
    /**
212
    * @var float volume
213
    */
214
    public $volume;
215
    public $volume_units;
216
217
    // Invoicing
218
    public $remise_percent;
219
    public $tva_tx;
220
221
    /**
222
     * @var float total without tax
223
     */
224
    public $total_ht;
225
226
    /**
227
     * @var float total with tax
228
     */
229
    public $total_ttc;
230
231
    /**
232
     * @var float total vat
233
     */
234
    public $total_tva;
235
236
    /**
237
     * @var float total localtax 1
238
     */
239
    public $total_localtax1;
240
241
    /**
242
     * @var float total localtax 2
243
     */
244
    public $total_localtax2;
245
246
247
    /**
248
     *  Constructor
249
     *
250
     *  @param      DoliDB      $db      Database handler
251
     */
252
    public function __construct($db)
253
    {
254
        $this->db = $db;
255
    }
256
257
    /**
258
     *  Load line expedition
259
     *
260
     *  @param  int     $rowid          Id line order
261
     *  @return int                     Return integer <0 if KO, >0 if OK
262
     */
263
    public function fetch($rowid)
264
    {
265
        $sql = 'SELECT ed.rowid, ed.fk_expedition, ed.fk_entrepot, ed.fk_origin_line, ed.qty, ed.rang';
266
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as ed';
267
        $sql .= ' WHERE ed.rowid = ' . ((int) $rowid);
268
        $result = $this->db->query($sql);
269
        if ($result) {
270
            $objp = $this->db->fetch_object($result);
271
            $this->id = $objp->rowid;
272
            $this->fk_expedition = $objp->fk_expedition;
273
            $this->entrepot_id = $objp->fk_entrepot;
274
            $this->fk_origin_line = $objp->fk_origin_line;
275
            $this->qty = $objp->qty;
276
            $this->rang = $objp->rang;
277
278
            $this->db->free($result);
279
280
            return 1;
281
        } else {
282
            $this->errors[] = $this->db->lasterror();
283
            $this->error = $this->db->lasterror();
284
            return -1;
285
        }
286
    }
287
288
    /**
289
     *  Insert line into database
290
     *
291
     *  @param      User    $user           User that modify
292
     *  @param      int     $notrigger      1 = disable triggers
293
     *  @return     int                     Return integer <0 if KO, line id >0 if OK
294
     */
295
    public function insert($user, $notrigger = 0)
296
    {
297
        $error = 0;
298
299
        // Check parameters
300
        if (empty($this->fk_expedition) || empty($this->fk_origin_line) || !is_numeric($this->qty)) {
301
            $this->error = 'ErrorMandatoryParametersNotProvided';
302
            return -1;
303
        }
304
305
        $this->db->begin();
306
307
        if (empty($this->rang)) {
308
            $this->rang = 0;
309
        }
310
311
        // Rank to use
312
        $ranktouse = $this->rang;
313
        if ($ranktouse == -1) {
314
            $rangmax = $this->line_max($this->fk_expedition);
315
            $ranktouse = $rangmax + 1;
316
        }
317
318
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "expeditiondet (";
319
        $sql .= "fk_expedition";
320
        $sql .= ", fk_entrepot";
321
        $sql .= ", fk_origin_line";
322
        $sql .= ", qty";
323
        $sql .= ", rang";
324
        $sql .= ") VALUES (";
325
        $sql .= $this->fk_expedition;
326
        $sql .= ", " . (empty($this->entrepot_id) ? 'NULL' : $this->entrepot_id);
327
        $sql .= ", " . ((int) $this->fk_origin_line);
328
        $sql .= ", " . price2num($this->qty, 'MS');
329
        $sql .= ", " . ((int) $ranktouse);
330
        $sql .= ")";
331
332
        dol_syslog(get_class($this) . "::insert", LOG_DEBUG);
333
        $resql = $this->db->query($sql);
334
        if ($resql) {
335
            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "expeditiondet");
336
337
            if (!$error) {
338
                $result = $this->insertExtraFields();
339
                if ($result < 0) {
340
                    $error++;
341
                }
342
            }
343
344
            if (!$error && !$notrigger) {
345
                // Call trigger
346
                $result = $this->call_trigger('LINESHIPPING_INSERT', $user);
347
                if ($result < 0) {
348
                    $error++;
349
                }
350
                // End call triggers
351
            }
352
353
            if ($error) {
354
                foreach ($this->errors as $errmsg) {
355
                    dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
356
                    $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
357
                }
358
            }
359
        } else {
360
            $error++;
361
        }
362
363
        if ($error) {
364
            $this->db->rollback();
365
            return -1;
366
        } else {
367
            $this->db->commit();
368
            return $this->id;
369
        }
370
    }
371
372
    /**
373
     *  Delete shipment line.
374
     *
375
     *  @param      User    $user           User that modify
376
     *  @param      int     $notrigger      0=launch triggers after, 1=disable triggers
377
     *  @return     int     >0 if OK, <0 if KO
378
     */
379
    public function delete($user = null, $notrigger = 0)
380
    {
381
        $error = 0;
382
383
        $this->db->begin();
384
385
        // delete batch expedition line
386
        if (isModEnabled('productbatch')) {
387
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "expeditiondet_batch";
388
            $sql .= " WHERE fk_expeditiondet = " . ((int) $this->id);
389
390
            if (!$this->db->query($sql)) {
391
                $this->errors[] = $this->db->lasterror() . " - sql=$sql";
392
                $error++;
393
            }
394
        }
395
396
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "expeditiondet";
397
        $sql .= " WHERE rowid = " . ((int) $this->id);
398
399
        if (!$error && $this->db->query($sql)) {
400
            // Remove extrafields
401
            if (!$error) {
402
                $result = $this->deleteExtraFields();
403
                if ($result < 0) {
404
                    $this->errors[] = $this->error;
405
                    $error++;
406
                }
407
            }
408
            if (!$error && !$notrigger) {
409
                // Call trigger
410
                $result = $this->call_trigger('LINESHIPPING_DELETE', $user);
411
                if ($result < 0) {
412
                    $this->errors[] = $this->error;
413
                    $error++;
414
                }
415
                // End call triggers
416
            }
417
        } else {
418
            $this->errors[] = $this->db->lasterror() . " - sql=$sql";
419
            $error++;
420
        }
421
422
        if (!$error) {
423
            $this->db->commit();
424
            return 1;
425
        } else {
426
            foreach ($this->errors as $errmsg) {
427
                dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
428
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
429
            }
430
            $this->db->rollback();
431
            return -1 * $error;
432
        }
433
    }
434
435
    /**
436
     *  Update a line in database
437
     *
438
     *  @param      User    $user           User that modify
439
     *  @param      int     $notrigger      1 = disable triggers
440
     *  @return     int                 Return integer < 0 if KO, > 0 if OK
441
     */
442
    public function update($user = null, $notrigger = 0)
443
    {
444
        $error = 0;
445
446
        dol_syslog(get_class($this) . "::update id=$this->id, entrepot_id=$this->entrepot_id, product_id=$this->fk_product, qty=$this->qty");
447
448
        $this->db->begin();
449
450
        // Clean parameters
451
        if (empty($this->qty)) {
452
            $this->qty = 0;
453
        }
454
        $qty = price2num($this->qty);
455
        $remainingQty = 0;
456
        $batch = null;
457
        $batch_id = null;
458
        $expedition_batch_id = null;
459
        if (is_array($this->detail_batch)) {    // array of ExpeditionLineBatch
460
            if (count($this->detail_batch) > 1) {
461
                dol_syslog(get_class($this) . '::update only possible for one batch', LOG_ERR);
462
                $this->errors[] = 'ErrorBadParameters';
463
                $error++;
464
            } else {
465
                $batch = $this->detail_batch[0]->batch;
466
                $batch_id = $this->detail_batch[0]->fk_origin_stock;
467
                $expedition_batch_id = $this->detail_batch[0]->id;
468
                if ($this->entrepot_id != $this->detail_batch[0]->entrepot_id) {
469
                    dol_syslog(get_class($this) . '::update only possible for batch of same warehouse', LOG_ERR);
470
                    $this->errors[] = 'ErrorBadParameters';
471
                    $error++;
472
                }
473
                $qty = price2num($this->detail_batch[0]->qty);
474
            }
475
        } elseif (!empty($this->detail_batch)) {
476
            $batch = $this->detail_batch->batch;
477
            $batch_id = $this->detail_batch->fk_origin_stock;
478
            $expedition_batch_id = $this->detail_batch->id;
479
            if ($this->entrepot_id != $this->detail_batch->entrepot_id) {
480
                dol_syslog(get_class($this) . '::update only possible for batch of same warehouse', LOG_ERR);
481
                $this->errors[] = 'ErrorBadParameters';
482
                $error++;
483
            }
484
            $qty = price2num($this->detail_batch->qty);
485
        }
486
487
        // check parameters
488
        if (!isset($this->id) || !isset($this->entrepot_id)) {
489
            dol_syslog(get_class($this) . '::update missing line id and/or warehouse id', LOG_ERR);
490
            $this->errors[] = 'ErrorMandatoryParametersNotProvided';
491
            $error++;
492
            return -1;
493
        }
494
495
        // update lot
496
497
        if (!empty($batch) && isModEnabled('productbatch')) {
498
            dol_syslog(get_class($this) . "::update expedition batch id=$expedition_batch_id, batch_id=$batch_id, batch=$batch");
499
500
            if (empty($batch_id) || empty($this->fk_product)) {
501
                dol_syslog(get_class($this) . '::update missing fk_origin_stock (batch_id) and/or fk_product', LOG_ERR);
502
                $this->errors[] = 'ErrorMandatoryParametersNotProvided';
503
                $error++;
504
            }
505
506
            // fetch remaining lot qty
507
            $shipmentlinebatch = new ExpeditionLineBatch($this->db);
508
509
            if (!$error && ($lotArray = $shipmentlinebatch->fetchAll($this->id)) < 0) {
510
                $this->errors[] = $this->db->lasterror() . " - ExpeditionLineBatch::fetchAll";
511
                $error++;
512
            } else {
513
                // calculate new total line qty
514
                foreach ($lotArray as $lot) {
515
                    if ($expedition_batch_id != $lot->id) {
516
                        $remainingQty += $lot->qty;
517
                    }
518
                }
519
                $qty += $remainingQty;
520
521
                //fetch lot details
522
523
                // fetch from product_lot
524
                require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php';
525
                $lot = new Productlot($this->db);
526
                if ($lot->fetch(0, $this->fk_product, $batch) < 0) {
527
                    $this->errors[] = $lot->errors;
528
                    $error++;
529
                }
530
                if (!$error && !empty($expedition_batch_id)) {
531
                    // delete lot expedition line
532
                    $sql = "DELETE FROM " . MAIN_DB_PREFIX . "expeditiondet_batch";
533
                    $sql .= " WHERE fk_expeditiondet = " . ((int) $this->id);
534
                    $sql .= " AND rowid = " . ((int) $expedition_batch_id);
535
536
                    if (!$this->db->query($sql)) {
537
                        $this->errors[] = $this->db->lasterror() . " - sql=$sql";
538
                        $error++;
539
                    }
540
                }
541
                if (!$error && $this->detail_batch->qty > 0) {
542
                    // create lot expedition line
543
                    if (isset($lot->id)) {
544
                        $shipmentLot = new ExpeditionLineBatch($this->db);
545
                        $shipmentLot->batch = $lot->batch;
546
                        $shipmentLot->eatby = $lot->eatby;
547
                        $shipmentLot->sellby = $lot->sellby;
548
                        $shipmentLot->entrepot_id = $this->detail_batch->entrepot_id;
549
                        $shipmentLot->qty = $this->detail_batch->qty;
550
                        $shipmentLot->fk_origin_stock = $batch_id;
551
                        if ($shipmentLot->create($this->id) < 0) {
552
                            $this->errors = $shipmentLot->errors;
553
                            $error++;
554
                        }
555
                    }
556
                }
557
            }
558
        }
559
        if (!$error) {
560
            // update line
561
            $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET";
562
            $sql .= " fk_entrepot = " . ($this->entrepot_id > 0 ? $this->entrepot_id : 'null');
563
            $sql .= " , qty = " . ((float) price2num($qty, 'MS'));
564
            $sql .= " WHERE rowid = " . ((int) $this->id);
565
566
            if (!$this->db->query($sql)) {
567
                $this->errors[] = $this->db->lasterror() . " - sql=$sql";
568
                $error++;
569
            }
570
        }
571
572
        if (!$error) {
573
            if (!$error) {
574
                $result = $this->insertExtraFields();
575
                if ($result < 0) {
576
                    $this->errors[] = $this->error;
577
                    $error++;
578
                }
579
            }
580
        }
581
582
        if (!$error && !$notrigger) {
583
            // Call trigger
584
            $result = $this->call_trigger('LINESHIPPING_MODIFY', $user);
585
            if ($result < 0) {
586
                $this->errors[] = $this->error;
587
                $error++;
588
            }
589
            // End call triggers
590
        }
591
        if (!$error) {
592
            $this->db->commit();
593
            return 1;
594
        } else {
595
            foreach ($this->errors as $errmsg) {
596
                dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR);
597
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
598
            }
599
            $this->db->rollback();
600
            return -1 * $error;
601
        }
602
    }
603
}
604