Test Failed
Branch main (fda838)
by Rafael
54:38 queued 11s
created

AccountingClosingController::index()   F

Complexity

Conditions 60
Paths > 20000

Size

Total Lines 373
Code Lines 250

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 60
eloc 250
nc 17833152
nop 0
dl 0
loc 373
rs 0
c 0
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) 2019-2023  Open-DSI                <[email protected]>
4
 * Copyright (C) 2024       Rafael San José         <[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace DoliModules\Accounting\Controller;
21
22
global $conf;
23
global $db;
24
global $user;
25
global $hookmanager;
26
global $user;
27
global $menumanager;
28
global $langs;
29
global $mysoc;
30
31
// Load Dolibarr environment
32
require BASE_PATH . '/main.inc.php';
33
require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
34
require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
35
require_once DOL_DOCUMENT_ROOT . '/core/class/fiscalyear.class.php';
36
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php';
37
38
use DoliCore\Base\DolibarrController;
39
40
class AccountingClosingController extends DolibarrController
0 ignored issues
show
Deprecated Code introduced by
The class DoliCore\Base\DolibarrController has been deprecated: This class is only needed for compatibility with Dolibarr. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

40
class AccountingClosingController extends /** @scrutinizer ignore-deprecated */ DolibarrController
Loading history...
41
{
42
    /**
43
     * \file        htdocs/accountancy/closure/index.php
44
     * \ingroup     Accountancy
45
     * \brief       Home closure page
46
     */
47
    public function index()
48
    {
49
        global $conf;
50
        global $db;
51
        global $user;
52
        global $hookmanager;
53
        global $user;
54
        global $menumanager;
55
        global $langs;
56
        global $mysoc;
57
58
// Load translation files required by the page
59
        $langs->loadLangs(["compta", "bills", "other", "accountancy"]);
60
61
        $action = GETPOST('action', 'aZ09');
62
        $confirm = GETPOST('confirm', 'aZ09');
63
        $fiscal_period_id = GETPOSTINT('fiscal_period_id');
64
        $validatemonth = GETPOSTINT('validatemonth');
65
        $validateyear = GETPOSTINT('validateyear');
66
67
// Security check
68
        if (!isModEnabled('accounting')) {
69
            accessforbidden();
70
        }
71
        if ($user->socid > 0) {
72
            accessforbidden();
73
        }
74
        if (!$user->hasRight('accounting', 'fiscalyear', 'write')) {
75
            accessforbidden();
76
        }
77
78
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
79
        $hookmanager->initHooks(['accountancyclosure']);
80
81
        $object = new BookKeeping($db);
82
83
        $now = dol_now();
84
        $fiscal_periods = $object->getFiscalPeriods();
85
        if (!is_array($fiscal_periods)) {
86
            setEventMessages($object->error, $object->errors, 'errors');
87
        }
88
89
        $active_fiscal_periods = [];
90
        $last_fiscal_period = null;
91
        $current_fiscal_period = null;
92
        $next_fiscal_period = null;
93
        $next_active_fiscal_period = null;
94
        if (is_array($fiscal_periods)) {
95
            foreach ($fiscal_periods as $fiscal_period) {
96
                if (empty($fiscal_period['status'])) {
97
                    $active_fiscal_periods[] = $fiscal_period;
98
                }
99
                if (isset($current_fiscal_period)) {
100
                    if (!isset($next_fiscal_period)) {
101
                        $next_fiscal_period = $fiscal_period;
102
                    }
103
                    if (!isset($next_active_fiscal_period) && empty($fiscal_period['status'])) {
104
                        $next_active_fiscal_period = $fiscal_period;
105
                    }
106
                } else {
107
                    if ($fiscal_period_id == $fiscal_period['id'] || (empty($fiscal_period_id) && $fiscal_period['date_start'] <= $now && $now <= $fiscal_period['date_end'])) {
108
                        $current_fiscal_period = $fiscal_period;
109
                    } else {
110
                        $last_fiscal_period = $fiscal_period;
111
                    }
112
                }
113
            }
114
        }
115
116
        $accounting_groups_used_for_balance_sheet_account = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT'))), 'strlen');
117
        $accounting_groups_used_for_income_statement = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT'))), 'strlen');
118
119
120
        /*
121
         * Actions
122
         */
123
124
        $parameters = ['fiscal_periods' => $fiscal_periods, 'last_fiscal_period' => $last_fiscal_period, 'current_fiscal_period' => $current_fiscal_period, 'next_fiscal_period' => $next_fiscal_period];
125
        $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
126
        if ($reshook < 0) {
127
            setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
128
        }
129
130
        if (empty($reshook)) {
131
            if (isset($current_fiscal_period) && $user->hasRight('accounting', 'fiscalyear', 'write')) {
132
                if ($action == 'confirm_step_1' && $confirm == "yes") {
133
                    $date_start = dol_mktime(0, 0, 0, GETPOSTINT('date_startmonth'), GETPOSTINT('date_startday'), GETPOSTINT('date_startyear'));
134
                    $date_end = dol_mktime(23, 59, 59, GETPOSTINT('date_endmonth'), GETPOSTINT('date_endday'), GETPOSTINT('date_endyear'));
135
136
                    $result = $object->validateMovementForFiscalPeriod($date_start, $date_end);
137
                    if ($result > 0) {
138
                        setEventMessages($langs->trans("AllMovementsWereRecordedAsValidated"), null, 'mesgs');
139
140
                        header("Location: " . $_SERVER['PHP_SELF'] . (isset($current_fiscal_period) ? '?fiscal_period_id=' . $current_fiscal_period['id'] : ''));
141
                        exit;
142
                    } else {
143
                        setEventMessages($langs->trans("NotAllMovementsCouldBeRecordedAsValidated"), null, 'errors');
144
                        setEventMessages($object->error, $object->errors, 'errors');
145
                        $action = '';
146
                    }
147
                } elseif ($action == 'confirm_step_2' && $confirm == "yes") {
148
                    $new_fiscal_period_id = GETPOSTINT('new_fiscal_period_id');
149
                    $separate_auxiliary_account = GETPOST('separate_auxiliary_account', 'aZ09');
150
                    $generate_bookkeeping_records = GETPOST('generate_bookkeeping_records', 'aZ09');
151
152
                    $result = $object->closeFiscalPeriod($current_fiscal_period['id'], $new_fiscal_period_id, $separate_auxiliary_account, $generate_bookkeeping_records);
153
                    if ($result < 0) {
154
                        setEventMessages($object->error, $object->errors, 'errors');
155
                    } else {
156
                        setEventMessages($langs->trans("AccountancyClosureCloseSuccessfully"), null, 'mesgs');
157
158
                        header("Location: " . $_SERVER['PHP_SELF'] . (isset($current_fiscal_period) ? '?fiscal_period_id=' . $current_fiscal_period['id'] : ''));
159
                        exit;
160
                    }
161
                } elseif ($action == 'confirm_step_3' && $confirm == "yes") {
162
                    $inventory_journal_id = GETPOSTINT('inventory_journal_id');
163
                    $new_fiscal_period_id = GETPOSTINT('new_fiscal_period_id');
164
                    $date_start = dol_mktime(0, 0, 0, GETPOSTINT('date_startmonth'), GETPOSTINT('date_startday'), GETPOSTINT('date_startyear'));
165
                    $date_end = dol_mktime(23, 59, 59, GETPOSTINT('date_endmonth'), GETPOSTINT('date_endday'), GETPOSTINT('date_endyear'));
166
167
                    $result = $object->insertAccountingReversal($current_fiscal_period['id'], $inventory_journal_id, $new_fiscal_period_id, $date_start, $date_end);
168
                    if ($result < 0) {
169
                        setEventMessages($object->error, $object->errors, 'errors');
170
                    } else {
171
                        setEventMessages($langs->trans("AccountancyClosureInsertAccountingReversalSuccessfully"), null, 'mesgs');
172
173
                        header("Location: " . $_SERVER['PHP_SELF'] . (isset($current_fiscal_period) ? '?fiscal_period_id=' . $current_fiscal_period['id'] : ''));
174
                        exit;
175
                    }
176
                }
177
            }
178
        }
179
180
181
        /*
182
         * View
183
         */
184
185
        $form = new Form($db);
0 ignored issues
show
Bug introduced by
The type DoliModules\Accounting\Controller\Form was not found. Did you mean Form? If so, make sure to prefix the type with \.
Loading history...
186
        $formaccounting = new FormAccounting($db);
0 ignored issues
show
Bug introduced by
The type DoliModules\Accounting\Controller\FormAccounting was not found. Did you mean FormAccounting? If so, make sure to prefix the type with \.
Loading history...
187
188
        $title = $langs->trans('Closure');
189
190
        $help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#Cl.C3.B4ture_annuelle';
191
192
        llxHeader('', $title, $help_url);
193
194
        $formconfirm = '';
195
196
        if (isset($current_fiscal_period)) {
197
            if ($action == 'step_1') {
198
                $form_question = [];
199
200
                $form_question['date_start'] = [
201
                    'name' => 'date_start',
202
                    'type' => 'date',
203
                    'label' => $langs->trans('DateStart'),
204
                    'value' => $current_fiscal_period['date_start'],
205
                ];
206
                $form_question['date_end'] = [
207
                    'name' => 'date_end',
208
                    'type' => 'date',
209
                    'label' => $langs->trans('DateEnd'),
210
                    'value' => $current_fiscal_period['date_end'],
211
                ];
212
213
                $formconfirm = $form->formconfirm(
214
                    $_SERVER['PHP_SELF'] . '?fiscal_period_id=' . $current_fiscal_period['id'],
215
                    $langs->trans('ValidateMovements'),
216
                    $langs->trans('DescValidateMovements', $langs->transnoentitiesnoconv("RegistrationInAccounting")),
217
                    'confirm_step_1',
218
                    $form_question,
219
                    '',
220
                    1,
221
                    300
222
                );
223
            } elseif ($action == 'step_2') {
224
                $form_question = [];
225
226
                $fiscal_period_arr = [];
227
                foreach ($active_fiscal_periods as $info) {
228
                    $fiscal_period_arr[$info['id']] = $info['label'];
229
                }
230
                $form_question['new_fiscal_period_id'] = [
231
                    'name' => 'new_fiscal_period_id',
232
                    'type' => 'select',
233
                    'label' => $langs->trans('AccountancyClosureStep3NewFiscalPeriod'),
234
                    'values' => $fiscal_period_arr,
235
                    'default' => isset($next_active_fiscal_period) ? $next_active_fiscal_period['id'] : '',
236
                ];
237
                $form_question['generate_bookkeeping_records'] = [
238
                    'name' => 'generate_bookkeeping_records',
239
                    'type' => 'checkbox',
240
                    'label' => $langs->trans('AccountancyClosureGenerateClosureBookkeepingRecords'),
241
                    'value' => 1,
242
                ];
243
                $form_question['separate_auxiliary_account'] = [
244
                    'name' => 'separate_auxiliary_account',
245
                    'type' => 'checkbox',
246
                    'label' => $langs->trans('AccountancyClosureSeparateAuxiliaryAccounts'),
247
                    'value' => 0,
248
                ];
249
250
                $formconfirm = $form->formconfirm(
251
                    $_SERVER['PHP_SELF'] . '?fiscal_period_id=' . $current_fiscal_period['id'],
252
                    $langs->trans('AccountancyClosureClose'),
253
                    $langs->trans('AccountancyClosureConfirmClose'),
254
                    'confirm_step_2',
255
                    $form_question,
256
                    '',
257
                    1,
258
                    300
259
                );
260
            } elseif ($action == 'step_3') {
261
                $form_question = [];
262
263
                $form_question['inventory_journal_id'] = [
264
                    'name' => 'inventory_journal_id',
265
                    'type' => 'other',
266
                    'label' => $langs->trans('InventoryJournal'),
267
                    'value' => $formaccounting->select_journal(0, "inventory_journal_id", 8, 1, 0, 0),
268
                ];
269
                $fiscal_period_arr = [];
270
                foreach ($active_fiscal_periods as $info) {
271
                    $fiscal_period_arr[$info['id']] = $info['label'];
272
                }
273
                $form_question['new_fiscal_period_id'] = [
274
                    'name' => 'new_fiscal_period_id',
275
                    'type' => 'select',
276
                    'label' => $langs->trans('AccountancyClosureStep3NewFiscalPeriod'),
277
                    'values' => $fiscal_period_arr,
278
                    'default' => isset($next_active_fiscal_period) ? $next_active_fiscal_period['id'] : '',
279
                ];
280
                $form_question['date_start'] = [
281
                    'name' => 'date_start',
282
                    'type' => 'date',
283
                    'label' => $langs->trans('DateStart'),
284
                    'value' => dol_time_plus_duree($current_fiscal_period['date_end'], -1, 'm'),
285
                ];
286
                $form_question['date_end'] = [
287
                    'name' => 'date_end',
288
                    'type' => 'date',
289
                    'label' => $langs->trans('DateEnd'),
290
                    'value' => $current_fiscal_period['date_end'],
291
                ];
292
293
                $formconfirm = $form->formconfirm(
294
                    $_SERVER['PHP_SELF'] . '?fiscal_period_id=' . $current_fiscal_period['id'],
295
                    $langs->trans('AccountancyClosureAccountingReversal'),
296
                    $langs->trans('AccountancyClosureConfirmAccountingReversal'),
297
                    'confirm_step_3',
298
                    $form_question,
299
                    '',
300
                    1,
301
                    300
302
                );
303
            }
304
        }
305
306
// Call Hook formConfirm
307
        $parameters = ['formConfirm' => $formconfirm, 'fiscal_periods' => $fiscal_periods, 'last_fiscal_period' => $last_fiscal_period, 'current_fiscal_period' => $current_fiscal_period, 'next_fiscal_period' => $next_fiscal_period];
308
        $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
309
        if (empty($reshook)) {
310
            $formconfirm .= $hookmanager->resPrint;
311
        } elseif ($reshook > 0) {
312
            $formconfirm = $hookmanager->resPrint;
313
        }
314
315
// Print form confirm
316
        print $formconfirm;
317
318
        $fiscal_period_nav_text = $langs->trans("FiscalPeriod");
319
320
        $fiscal_period_nav_text .= '&nbsp;<a href="' . (isset($last_fiscal_period) ? $_SERVER['PHP_SELF'] . '?fiscal_period_id=' . $last_fiscal_period['id'] : '#" class="disabled') . '">' . img_previous() . '</a>';
321
        $fiscal_period_nav_text .= '&nbsp;<a href="' . (isset($next_fiscal_period) ? $_SERVER['PHP_SELF'] . '?fiscal_period_id=' . $next_fiscal_period['id'] : '#" class="disabled') . '">' . img_next() . '</a>';
322
        if (!empty($current_fiscal_period)) {
323
            $fiscal_period_nav_text .= $current_fiscal_period['label'] . ' &nbsp;(' . (isset($current_fiscal_period) ? dol_print_date($current_fiscal_period['date_start'], 'day') . '&nbsp;-&nbsp;' . dol_print_date($current_fiscal_period['date_end'], 'day') . ')' : '');
324
        }
325
326
        print load_fiche_titre($langs->trans("Closure") . " - " . $fiscal_period_nav_text, '', 'title_accountancy');
327
328
        if (empty($current_fiscal_period)) {
329
            print $langs->trans('ErrorNoFiscalPeriodActiveFound');
330
        }
331
332
        if (isset($current_fiscal_period)) {
333
            // Step 1
334
            $head = [];
335
            $head[0][0] = DOL_URL_ROOT . '/accountancy/closure/index.php?fiscal_period_id=' . $current_fiscal_period['id'];
336
            $head[0][1] = $langs->trans("AccountancyClosureStep1");
337
            $head[0][2] = 'step1';
338
            print dol_get_fiche_head($head, 'step1', '', -1, 'title_accountancy');
339
340
            print '<span class="opacitymedium">' . $langs->trans("AccountancyClosureStep1Desc") . '</span><br>';
341
342
            $count_by_month = $object->getCountByMonthForFiscalPeriod($current_fiscal_period['date_start'], $current_fiscal_period['date_end']);
343
            if (!is_array($count_by_month)) {
344
                setEventMessages($object->error, $object->errors, 'errors');
345
            }
346
347
            if (empty($count_by_month['total'])) {
348
                $buttonvalidate = '<a class="butActionRefused classfortooltip" href="#">' . $langs->trans("ValidateMovements") . '</a>';
349
            } else {
350
                $buttonvalidate = '<a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=step_1&fiscal_period_id=' . $current_fiscal_period['id'] . '">' . $langs->trans("ValidateMovements") . '</a>';
351
            }
352
            print_barre_liste($langs->trans("OverviewOfMovementsNotValidated"), '', '', '', '', '', '', -1, '', '', 0, $buttonvalidate, '', 0, 1, 0);
353
354
            print '<div class="div-table-responsive-no-min">';
355
            print '<table class="noborder centpercent">';
356
357
            print '<tr class="liste_titre">';
358
            $nb_years = is_array($count_by_month['list']) ? count($count_by_month['list']) : 0;
359
            if ($nb_years > 1) {
360
                print '<td class="right">' . $langs->trans("Year") . '</td>';
361
            }
362
            for ($i = 1; $i <= 12; $i++) {
363
                print '<td class="right">' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '</td>';
364
            }
365
            print '<td class="right"><b>' . $langs->trans("Total") . '</b></td>';
366
            print '</tr>';
367
368
            if (is_array($count_by_month['list'])) {
369
                foreach ($count_by_month['list'] as $info) {
370
                    print '<tr class="oddeven">';
371
                    if ($nb_years > 1) {
372
                        print '<td class="right">' . $info['year'] . '</td>';
373
                    }
374
                    for ($i = 1; $i <= 12; $i++) {
375
                        print '<td class="right">' . ((int) $info['count'][$i]) . '</td>';
376
                    }
377
                    print '<td class="right"><b>' . $info['total'] . '</b></td></tr>';
378
                }
379
            }
380
381
            print "</table>\n";
382
            print '</div>';
383
384
            // Step 2
385
            $head = [];
386
            $head[0][0] = DOL_URL_ROOT . '/accountancy/closure/index.php?fiscal_period_id=' . $current_fiscal_period['id'];
387
            $head[0][1] = $langs->trans("AccountancyClosureStep2");
388
            $head[0][2] = 'step2';
389
            print dol_get_fiche_head($head, 'step2', '', -1, 'title_accountancy');
390
391
            // print '<span class="opacitymedium">' . $langs->trans("AccountancyClosureStep2Desc") . '</span><br>';
392
393
            if (empty($count_by_month['total']) && empty($current_fiscal_period['status'])) {
394
                $button = '<a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=step_2&fiscal_period_id=' . $current_fiscal_period['id'] . '">' . $langs->trans("AccountancyClosureClose") . '</a>';
395
            } else {
396
                $button = '<a class="butActionRefused classfortooltip" href="#">' . $langs->trans("AccountancyClosureClose") . '</a>';
397
            }
398
            print_barre_liste('', '', '', '', '', '', '', -1, '', '', 0, $button, '', 0, 1, 0);
399
400
            // Step 3
401
            $head = [];
402
            $head[0][0] = DOL_URL_ROOT . '/accountancy/closure/index.php?fiscal_period_id=' . $current_fiscal_period['id'];
403
            $head[0][1] = $langs->trans("AccountancyClosureStep3");
404
            $head[0][2] = 'step3';
405
            print dol_get_fiche_head($head, 'step3', '', -1, 'title_accountancy');
406
407
            // print '<span class="opacitymedium">' . $langs->trans("AccountancyClosureStep3Desc") . '</span><br>';
408
409
            if (empty($current_fiscal_period['status'])) {
410
                $button = '<a class="butActionRefused classfortooltip" href="#">' . $langs->trans("AccountancyClosureAccountingReversal") . '</a>';
411
            } else {
412
                $button = '<a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=step_3&fiscal_period_id=' . $current_fiscal_period['id'] . '">' . $langs->trans("AccountancyClosureAccountingReversal") . '</a>';
413
            }
414
            print_barre_liste('', '', '', '', '', '', '', -1, '', '', 0, $button, '', 0, 1, 0);
415
        }
416
417
// End of page
418
        llxFooter();
419
        $db->close();
420
    }
421
}
422