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

BomListController::index()   F

Complexity

Conditions 53
Paths > 20000

Size

Total Lines 253
Code Lines 152

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 53
eloc 152
c 1
b 0
f 0
nc 12318720
nop 1
dl 0
loc 253
rs 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) 2007-2017  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2024		MDW						<[email protected]>
5
 * Copyright (C) 2024       Rafael San José         <[email protected]>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace DoliModules\Bom\Controller;
22
23
global $conf;
24
global $db;
25
global $user;
26
global $hookmanager;
27
global $user;
28
global $menumanager;
29
global $langs;
30
global $mysoc;
31
32
/**
33
 *    \file       htdocs/bom/bom_list.php
34
 *    \ingroup    bom
35
 *    \brief      List page for BillOfMaterials
36
 */
37
38
use DoliCore\Base\DolibarrController;
39
use DoliCore\Form\Form;
40
use DoliCore\Lib\ExtraFields;
41
use DoliCore\Lib\Fields;
42
use DoliModules\Bom\Model\Bom;
43
44
// Load Dolibarr environment
45
require BASE_PATH . '/main.inc.php';
46
require_once BASE_PATH . '/../Dolibarr/Lib/Date.php';
47
require_once BASE_PATH . '/../Dolibarr/Lib/Company.php';
48
require_once BASE_PATH . '/../Dolibarr/Modules/Bom/Lib/Bom.php';
49
50
class BomListController extends DolibarrController
51
{
52
    public function index(bool $executeActions = true): bool
53
    {
54
        global $conf;
55
        global $db;
56
        global $user;
57
        global $hookmanager;
58
        global $user;
59
        global $menumanager;
60
        global $langs;
61
        global $mysoc;
62
63
        // Load translation files required by the page
64
        $langs->loadLangs(['mrp', 'other']);
65
66
// Get Parameters
67
        $id = GETPOSTINT('id');
68
        $action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
69
        $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
70
        $show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ?
71
        $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
72
        $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
73
        $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
74
        $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'bomlist'; // To manage different context of search
75
        $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
76
        $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
77
        $mode = GETPOST('mode', 'aZ');  // mode view (kanban or common)
78
79
80
// Load variable for pagination
81
        $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
82
        $sortfield = GETPOST('sortfield', 'aZ09comma');
83
        $sortorder = GETPOST('sortorder', 'aZ09comma');
84
        $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT('page');
85
        if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
86
            // If $page is not defined, or '' or -1 or if we click on clear filters
87
            $page = 0;
88
        }
89
        $offset = $limit * $page;
90
        $pageprev = $page - 1;
91
        $pagenext = $page + 1;
92
//if (! $sortfield) $sortfield="p.date_fin";
93
//if (! $sortorder) $sortorder="DESC";
94
95
// Initialize technical objects
96
        $object = new Bom($db);
97
        $extrafields = new ExtraFields($db);
98
        $diroutputmassaction = $conf->bom->dir_output . '/temp/massgeneration/' . $user->id;
99
        $hookmanager->initHooks(['bomlist']); // Note that conf->hooks_modules contains array
100
101
// Fetch optionals attributes and labels
102
        $extrafields->fetch_name_optionals_label($object->table_element);
103
104
        $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
105
106
// Default sort order (if not yet defined by previous GETPOST)
107
        if (!$sortfield) {
108
            reset($object->fields);                 // Reset is required to avoid key() to return null.
109
            $sortfield = "t." . key($object->fields); // Set here default search field. By default 1st field in definition.
110
        }
111
        if (!$sortorder) {
112
            $sortorder = "ASC";
113
        }
114
115
// Initialize array of search criteria
116
        $search_all = trim(GETPOST('search_all', 'alphanohtml'));
117
        $search = [];
118
        foreach ($object->fields as $key => $val) {
119
            if (GETPOST('search_' . $key, 'alpha') !== '') {
120
                $search[$key] = GETPOST('search_' . $key, 'alpha');
121
            }
122
            if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
123
                $search[$key . '_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_' . $key . '_dtstartmonth'), GETPOSTINT('search_' . $key . '_dtstartday'), GETPOSTINT('search_' . $key . '_dtstartyear'));
124
                $search[$key . '_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_' . $key . '_dtendmonth'), GETPOSTINT('search_' . $key . '_dtendday'), GETPOSTINT('search_' . $key . '_dtendyear'));
125
            }
126
        }
127
128
        $fieldstosearchall = [];
129
// List of fields to search into when doing a "search in all"
130
        foreach ($object->fields as $key => $val) {
131
            if (!empty($val['searchall'])) {
132
                $fieldstosearchall['t.' . $key] = $val['label'];
133
            }
134
        }
135
136
// Definition of array of fields for columns
137
        $arrayfields = Fields::getArrayFields($object->fields);
138
139
// Extra fields
140
        include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
141
142
        $object->fields = dol_sort_array($object->fields, 'position');
143
        $arrayfields = dol_sort_array($arrayfields, 'position');
144
145
        $permissiontoread = $user->hasRight('bom', 'read');
146
        $permissiontoadd = $user->hasRight('bom', 'write');
147
        $permissiontodelete = $user->hasRight('bom', 'delete');
148
149
// Security check
150
        if ($user->socid > 0) {
151
            // Protection if external user
152
            accessforbidden();
153
        }
154
        $result = restrictedArea($user, 'bom');
155
156
157
        /*
158
         * Actions
159
         */
160
161
        if (GETPOST('cancel', 'alpha')) {
162
            $action = 'list';
163
            $massaction = '';
164
        }
165
        if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
166
            $massaction = '';
167
        }
168
169
        $parameters = [];
170
        $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
171
        if ($reshook < 0) {
172
            setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
173
        }
174
175
        if (empty($reshook)) {
176
            // Selection of new fields
177
            include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
178
179
            // Purge search criteria
180
            if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
181
                foreach ($object->fields as $key => $val) {
182
                    $search[$key] = '';
183
                    if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
184
                        $search[$key . '_dtstart'] = '';
185
                        $search[$key . '_dtend'] = '';
186
                    }
187
                }
188
                $toselect = [];
189
                $search_array_options = [];
190
            }
191
            if (
192
                GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
193
                || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')
194
            ) {
195
                $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
196
            }
197
198
            // Mass actions
199
            $objectclass = 'BOM';
200
            $objectlabel = 'BillOfMaterials';
201
            $permissiontoread = $user->hasRight('bom', 'read');
202
            $permissiontodelete = $user->hasRight('bom', 'delete');
203
            $uploaddir = $conf->bom->dir_output;
204
            include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
205
206
207
            // Validate records
208
            if (!$error && $massaction == 'disable' && $permissiontoadd) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error seems to be never defined.
Loading history...
209
                $objecttmp = new $objectclass($db);
210
211
                if (!$error) {
212
                    $db->begin();
213
214
                    $nbok = 0;
215
                    foreach ($toselect as $toselectid) {
216
                        $result = $objecttmp->fetch($toselectid);
217
                        if ($result > 0) {
218
                            if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) {
219
                                $langs->load("errors");
220
                                setEventMessages($langs->trans("ErrorObjectMustHaveStatusActiveToBeDisabled", $objecttmp->ref), null, 'errors');
221
                                $error++;
222
                                break;
223
                            }
224
225
                            // Can be 'cancel()' or 'close()'
226
                            $result = $objecttmp->cancel($user);
227
                            if ($result < 0) {
228
                                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
229
                                $error++;
230
                                break;
231
                            } else {
232
                                $nbok++;
233
                            }
234
                        } else {
235
                            setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
236
                            $error++;
237
                            break;
238
                        }
239
                    }
240
241
                    if (!$error) {
242
                        setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
243
                        $db->commit();
244
                    } else {
245
                        $db->rollback();
246
                    }
247
                    //var_dump($listofobjectthirdparties);exit;
248
                }
249
            }
250
251
            // Validate records
252
            if (!$error && $massaction == 'enable' && $permissiontoadd) {
253
                $objecttmp = new $objectclass($db);
254
255
                if (!$error) {
256
                    $db->begin();
257
258
                    $nbok = 0;
259
                    foreach ($toselect as $toselectid) {
260
                        $result = $objecttmp->fetch($toselectid);
261
                        if ($result > 0) {
262
                            if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED) {
263
                                $langs->load("errors");
264
                                setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated", $objecttmp->ref), null, 'errors');
265
                                $error++;
266
                                break;
267
                            }
268
269
                            // Can be 'cancel()' or 'close()'
270
                            $result = $objecttmp->validate($user);
271
                            if ($result < 0) {
272
                                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
273
                                $error++;
274
                                break;
275
                            } else {
276
                                $nbok++;
277
                            }
278
                        } else {
279
                            setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
280
                            $error++;
281
                            break;
282
                        }
283
                    }
284
285
                    if (!$error) {
286
                        setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
287
                        $db->commit();
288
                    } else {
289
                        $db->rollback();
290
                    }
291
                    //var_dump($listofobjectthirdparties);exit;
292
                }
293
            }
294
        }
295
296
297
        /*
298
         * View
299
         */
300
        require_once realpath(BASE_PATH . '/../Dolibarr/Modules/Bom/Views/bom_list.php');
301
302
        $db->close();
303
304
        return true;
305
    }
306
307
}
308
309