Passed
Push — main ( 7eb3b3...9a81fe )
by Rafael
42:16
created

BomLine::getNomUrl()   F

Complexity

Conditions 21
Paths 864

Size

Total Lines 64
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 41
c 0
b 0
f 0
nc 864
nop 5
dl 0
loc 64
rs 0.1888

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) 2019       Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2023	    Benjamin Falière	    <[email protected]>
5
 * Copyright (C) 2023	    Charlene Benke		    <[email protected]>
6
 * Copyright (C) 2024       Frédéric France         <[email protected]>
7
 * Copyright (C) 2024		MDW						<[email protected]>
8
 * Copyright (C) 2024       Rafael San José         <[email protected]>
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 3 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22
 */
23
24
/**
25
 * \file        htdocs/bom/class/bom.class.php
26
 * \ingroup     bom
27
 * \brief       This file is a CRUD class file for BOM (Create/Read/Update/Delete)
28
 */
29
30
namespace DoliModules\Bom\Model;
31
32
use DoliCore\Base\GenericDocumentLine;
33
use DoliDB;
34
use User;
35
36
require_once BASE_PATH . '/../Dolibarr/Lib/Date.php';
37
38
if (isModEnabled('workstation')) {
39
    require_once DOL_DOCUMENT_ROOT . '/workstation/class/workstation.class.php';
40
}
41
42
/**
43
 * Class for BOMLine
44
 */
45
class BomLine extends GenericDocumentLine
46
{
47
    /**
48
     * @var string ID to identify managed object
49
     */
50
    public $element = 'bomline';
51
52
    /**
53
     * @var string Name of table without prefix where object is stored
54
     */
55
    public $table_element = 'bom_bomline';
56
57
    /**
58
     * @var int  Does bomline support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with
59
     *      link by societe
60
     */
61
    public $ismultientitymanaged = 0;
62
63
    /**
64
     * @var int  Does bomline support extrafields ? 0=No, 1=Yes
65
     */
66
    public $isextrafieldmanaged = 1;
67
68
    /**
69
     * @var string String with name of icon for bomline. Must be the part after the 'object_' into object_bomline.png
70
     */
71
    public $picto = 'bomline';
72
73
74
    /**
75
     *  'type' if the field format.
76
     *  'label' the translation key.
77
     *  'enabled' is a condition when the field must be managed.
78
     *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view
79
     *  forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be
80
     *  selected for viewing)
81
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
82
     *  'default' is a default value for creation (can still be replaced by the global setup of default values)
83
     *  'index' if we want an index in database.
84
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
85
     *  'position' is the sort order of field.
86
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
87
     *  'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable
88
     *  like integer or double(24,8).
89
     *  'css' is the CSS style to use on field. For example: 'maxwidth200'
90
     *  'help' is a string visible as a tooltip on field
91
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
92
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
93
     *  'arrayofkeyval' to set list of value if type is a list of predefined values. For example:
94
     *  array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
95
     */
96
97
    // BEGIN MODULEBUILDER PROPERTIES
98
    /**
99
     * @var array<string,array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string}>
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string,array{type:...ring>,comment?:string}> at position 16 could not be parsed: Expected '}' at position 16, but found 'int'.
Loading history...
100
     *      Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
101
     */
102
    public $fields = [
103
        'rowid' => ['type' => 'integer', 'label' => 'LineID', 'enabled' => 1, 'visible' => -1, 'position' => 1, 'notnull' => 1, 'index' => 1, 'comment' => "Id",],
104
        'fk_bom' => ['type' => 'integer:BillOfMaterials:societe/class/bom.class.php', 'label' => 'BillOfMaterials', 'enabled' => 1, 'visible' => 1, 'position' => 10, 'notnull' => 1, 'index' => 1,],
105
        'fk_product' => ['type' => 'integer:Product:product/class/product.class.php', 'label' => 'Product', 'enabled' => 1, 'visible' => 1, 'position' => 20, 'notnull' => 1, 'index' => 1,],
106
        'fk_bom_child' => ['type' => 'integer:BOM:bom/class/bom.class.php', 'label' => 'BillOfMaterials', 'enabled' => 1, 'visible' => -1, 'position' => 40, 'notnull' => -1,],
107
        'description' => ['type' => 'text', 'label' => 'Description', 'enabled' => 1, 'visible' => -1, 'position' => 60, 'notnull' => -1,],
108
        'qty' => ['type' => 'double(24,8)', 'label' => 'Quantity', 'enabled' => 1, 'visible' => 1, 'position' => 100, 'notnull' => 1, 'isameasure' => 1,],
109
        'qty_frozen' => ['type' => 'smallint', 'label' => 'QuantityFrozen', 'enabled' => 1, 'visible' => 1, 'default' => '0', 'position' => 105, 'css' => 'maxwidth50imp', 'help' => 'QuantityConsumedInvariable'],
110
        'disable_stock_change' => ['type' => 'smallint', 'label' => 'DisableStockChange', 'enabled' => 1, 'visible' => 1, 'default' => '0', 'position' => 108, 'css' => 'maxwidth50imp', 'help' => 'DisableStockChangeHelp'],
111
        'efficiency' => ['type' => 'double(24,8)', 'label' => 'ManufacturingEfficiency', 'enabled' => 1, 'visible' => 0, 'default' => '1', 'position' => 110, 'notnull' => 1, 'css' => 'maxwidth50imp', 'help' => 'ValueOfEfficiencyConsumedMeans'],
112
        'fk_unit' => ['type' => 'integer', 'label' => 'Unit', 'enabled' => 1, 'visible' => 1, 'position' => 120, 'notnull' => -1,],
113
        'position' => ['type' => 'integer', 'label' => 'Rank', 'enabled' => 1, 'visible' => 0, 'default' => '0', 'position' => 200, 'notnull' => 1,],
114
        'import_key' => ['type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000, 'notnull' => -1,],
115
        'fk_default_workstation' => ['type' => 'integer', 'label' => 'DefaultWorkstation', 'enabled' => 1, 'visible' => 1, 'notnull' => 0, 'position' => 1050],
116
    ];
117
118
    /**
119
     * @var int rowid
120
     */
121
    public $rowid;
122
123
    /**
124
     * @var int fk_bom
125
     */
126
    public $fk_bom;
127
128
    /**
129
     * @var int Id of product
130
     */
131
    public $fk_product;
132
133
    /**
134
     * @var int Id of parent bom
135
     */
136
    public $fk_bom_child;
137
138
    /**
139
     * @var string description
140
     */
141
    public $description;
142
143
    /**
144
     * @var double qty
145
     */
146
    public $qty;
147
148
    /**
149
     * @var int qty frozen
150
     */
151
    public $qty_frozen;
152
153
    /**
154
     * @var int disable stock change
155
     */
156
    public $disable_stock_change;
157
158
    /**
159
     * @var double efficiency
160
     */
161
    public $efficiency;
162
163
    /**
164
     * @var int position of line
165
     */
166
    public $position;
167
168
    /**
169
     * @var string import key
170
     */
171
    public $import_key;
172
    // END MODULEBUILDER PROPERTIES
173
174
    /**
175
     * @var float       Calculated cost for the BOM line
176
     */
177
    public $total_cost = 0;
178
179
    /**
180
     * @var float       Line unit cost based on product cost price or pmp
181
     */
182
    public $unit_cost = 0;
183
184
    /**
185
     * @var array     array of Bom in line
186
     */
187
    public $childBom = [];
188
189
    /**
190
     * @var int|null                ID of the unit of measurement (rowid in llx_c_units table)
191
     * @see measuringUnitString()
192
     * @see getLabelOfUnit()
193
     */
194
    public $fk_unit;
195
196
    /**
197
     * @var int Service Workstation
198
     */
199
    public $fk_default_workstation;
200
201
202
    /**
203
     * Constructor
204
     *
205
     * @param DoliDB $db Database handler
206
     */
207
    public function __construct(DoliDB $db)
208
    {
209
        global $conf, $langs;
210
211
        $this->db = $db;
212
213
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
214
            $this->fields['rowid']['visible'] = 0;
215
        }
216
        if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
217
            $this->fields['entity']['enabled'] = 0;
218
        }
219
220
        // Unset fields that are disabled
221
        foreach ($this->fields as $key => $val) {
222
            if (isset($val['enabled']) && empty($val['enabled'])) {
223
                unset($this->fields[$key]);
224
            }
225
        }
226
227
        // Translate some data of arrayofkeyval
228
        foreach ($this->fields as $key => $val) {
229
            if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
230
                foreach ($val['arrayofkeyval'] as $key2 => $val2) {
231
                    $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
232
                }
233
            }
234
        }
235
    }
236
237
    /**
238
     * Create object into database
239
     *
240
     * @param User $user      User that creates
241
     * @param int  $notrigger 0=launch triggers after, 1=disable triggers
242
     *
243
     * @return int             Return integer <0 if KO, Id of created object if OK
244
     */
245
    public function create(User $user, $notrigger = 0)
246
    {
247
        if ($this->efficiency < 0 || $this->efficiency > 1) {
248
            $this->efficiency = 1;
249
        }
250
251
        return $this->createCommon($user, $notrigger);
252
    }
253
254
    /**
255
     * Load object in memory from the database
256
     *
257
     * @param int    $id  Id object
258
     * @param string $ref Ref
259
     *
260
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
261
     */
262
    public function fetch($id, $ref = null)
263
    {
264
        $result = $this->fetchCommon($id, $ref);
265
        //if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
266
        return $result;
267
    }
268
269
    /**
270
     * Load list of objects in memory from the database.
271
     *
272
     * @param string $sortorder             Sort Order
273
     * @param string $sortfield             Sort field
274
     * @param int    $limit                 limit
275
     * @param int    $offset                Offset
276
     * @param string $filter                Filter as an Universal Search string.
277
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND
278
     *                                      (client:!=:8) AND (nom:like:'a%')'
279
     * @param string $filtermode            No more used
280
     *
281
     * @return array|int                    int <0 if KO, array of pages if OK
282
     */
283
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
284
    {
285
        dol_syslog(__METHOD__, LOG_DEBUG);
286
287
        $records = [];
288
289
        $sql = 'SELECT ';
290
        $sql .= $this->getFieldList();
291
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
292
        if ($this->ismultientitymanaged) {
293
            $sql .= ' WHERE t.entity IN (' . getEntity($this->element) . ')';
294
        } else {
295
            $sql .= ' WHERE 1 = 1';
296
        }
297
298
        // Manage filter
299
        $errormessage = '';
300
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
301
        if ($errormessage) {
302
            $this->errors[] = $errormessage;
303
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
304
            return -1;
305
        }
306
307
        if (!empty($sortfield)) {
308
            $sql .= $this->db->order($sortfield, $sortorder);
309
        }
310
        if (!empty($limit)) {
311
            $sql .= $this->db->plimit($limit, $offset);
312
        }
313
314
        $resql = $this->db->query($sql);
315
        if ($resql) {
316
            $num = $this->db->num_rows($resql);
317
318
            while ($obj = $this->db->fetch_object($resql)) {
319
                $record = new self($this->db);
320
                $record->setVarsFromFetchObj($obj);
321
                $record->fetch_optionals();
322
323
                $records[$record->id] = $record;
324
            }
325
            $this->db->free($resql);
326
327
            return $records;
328
        } else {
329
            $this->errors[] = 'Error ' . $this->db->lasterror();
330
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
331
332
            return -1;
333
        }
334
    }
335
336
    /**
337
     * Update object into database
338
     *
339
     * @param User $user      User that modifies
340
     * @param int  $notrigger 0=launch triggers after, 1=disable triggers
341
     *
342
     * @return int             Return integer <0 if KO, >0 if OK
343
     */
344
    public function update(User $user, $notrigger = 0)
345
    {
346
        if ($this->efficiency < 0 || $this->efficiency > 1) {
347
            $this->efficiency = 1;
348
        }
349
350
        return $this->updateCommon($user, $notrigger);
351
    }
352
353
    /**
354
     * Delete object in database
355
     *
356
     * @param User $user      User that deletes
357
     * @param int  $notrigger 0=launch triggers after, 1=disable triggers
358
     *
359
     * @return int              Return integer <0 if KO, >0 if OK
360
     */
361
    public function delete(User $user, $notrigger = 0)
362
    {
363
        return $this->deleteCommon($user, $notrigger);
364
        //return $this->deleteCommon($user, $notrigger, 1);
365
    }
366
367
    /**
368
     *  Return a link to the object card (with optionally the picto)
369
     *
370
     * @param int    $withpicto             Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
371
     * @param string $option                On what the link point to ('nolink', ...)
372
     * @param int    $notooltip             1=Disable tooltip
373
     * @param string $morecss               Add more css on link
374
     * @param int    $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save
375
     *                                      lastsearch_values whenclicking
376
     *
377
     * @return string                              String with URL
378
     */
379
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
380
    {
381
        global $db, $conf, $langs, $hookmanager;
382
383
        if (!empty($conf->dol_no_mouse_hover)) {
384
            $notooltip = 1; // Force disable tooltips
385
        }
386
387
        $result = '';
388
389
        $label = '<u>' . $langs->trans("BillOfMaterialsLine") . '</u>';
390
        $label .= '<br>';
391
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
392
393
        $url = DOL_URL_ROOT . '/bom/bomline_card.php?id=' . $this->id;
394
395
        if ($option != 'nolink') {
396
            // Add param to save lastsearch_values or not
397
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
398
            if ($save_lastsearch_value == -1 && isset($_SERVER['PHP_SELF']) && preg_match('/list\.php/', $_SERVER['PHP_SELF'])) {
399
                $add_save_lastsearch_values = 1;
400
            }
401
            if ($add_save_lastsearch_values) {
402
                $url .= '&save_lastsearch_values=1';
403
            }
404
        }
405
406
        $linkclose = '';
407
        if (empty($notooltip)) {
408
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
409
                $label = $langs->trans("ShowBillOfMaterialsLine");
410
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
411
            }
412
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
413
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
414
        } else {
415
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
416
        }
417
418
        $linkstart = '<a href="' . $url . '"';
419
        $linkstart .= $linkclose . '>';
420
        $linkend = '</a>';
421
422
        $result .= $linkstart;
423
        if ($withpicto) {
424
            $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);
425
        }
426
        if ($withpicto != 2) {
427
            $result .= $this->ref;
428
        }
429
        $result .= $linkend;
430
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
431
432
        global $action, $hookmanager;
433
        $hookmanager->initHooks(['bomlinedao']);
434
        $parameters = ['id' => $this->id, 'getnomurl' => &$result];
435
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
436
        if ($reshook > 0) {
437
            $result = $hookmanager->resPrint;
438
        } else {
439
            $result .= $hookmanager->resPrint;
440
        }
441
442
        return $result;
443
    }
444
445
    /**
446
     *  Return label of the status
447
     *
448
     * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short
449
     *                  label + Picto, 6=Long label + Picto
450
     *
451
     * @return string                 Label of status
452
     */
453
    public function getLibStatut($mode = 0)
454
    {
455
        return $this->LibStatut($this->status, $mode);
456
    }
457
458
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
459
460
    /**
461
     *  Return the status
462
     *
463
     * @param int $status Id status
464
     * @param int $mode   0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short
465
     *                    label + Picto, 6=Long label + Picto
466
     *
467
     * @return string                 Label of status
468
     */
469
    public function LibStatut($status, $mode = 0)
470
    {
471
        // phpcs:enable
472
        return '';
473
    }
474
475
    /**
476
     *  Load the info information in the object
477
     *
478
     * @param int $id Id of object
479
     *
480
     * @return void
481
     */
482
    public function info($id)
483
    {
484
        $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
485
        $sql .= ' fk_user_creat, fk_user_modif';
486
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
487
        $sql .= ' WHERE t.rowid = ' . ((int) $id);
488
        $result = $this->db->query($sql);
489
        if ($result) {
490
            if ($this->db->num_rows($result)) {
491
                $obj = $this->db->fetch_object($result);
492
493
                $this->id = $obj->rowid;
494
495
                $this->user_creation_id = $obj->fk_user_creat;
496
                $this->user_modification_id = $obj->fk_user_modif;
497
                $this->date_creation = $this->db->jdate($obj->datec);
498
                $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
499
            }
500
            $this->db->free($result);
501
        } else {
502
            dol_print_error($this->db);
503
        }
504
    }
505
506
    /**
507
     * Initialise object with example values
508
     * Id must be 0 if object instance is a specimen
509
     *
510
     * @return int
511
     */
512
    public function initAsSpecimen()
513
    {
514
        return $this->initAsSpecimenCommon();
515
    }
516
}
517