Fiscalyear::getNomUrl()   F
last analyzed

Complexity

Conditions 22
Paths 3456

Size

Total Lines 73
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 49
nc 3456
nop 3
dl 0
loc 73
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) 2014-2020  Alexandre Spangaro          <[email protected]>
4
 * Copyright (C) 2020       OScss-Shop                  <[email protected]>
5
 * Copyright (C) 2023-2024  Frédéric France             <[email protected]>
6
 * Copyright (C) 2024		MDW							<[email protected]>
7
 * Copyright (C) 2024       Rafael San José             <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 */
22
23
namespace Dolibarr\Code\Core\Classes;
24
25
use Dolibarr\Code\User\Classes\User;
26
use Dolibarr\Core\Base\CommonObject;
27
use DoliDB;
28
29
/**
30
 *      \file       htdocs/core/class/fiscalyear.class.php
31
 *      \ingroup    fiscal year
32
 *      \brief      File of class to manage fiscal years
33
 */
34
35
/**
36
 * Class to manage fiscal year
37
 */
38
class Fiscalyear extends CommonObject
39
{
40
    /**
41
     * @var string ID to identify managed object
42
     */
43
    public $element = 'fiscalyear';
44
45
    /**
46
     * @var string picto
47
     */
48
    public $picto = 'calendar';
49
50
    /**
51
     * @var string Name of table without prefix where object is stored
52
     */
53
    public $table_element = 'accounting_fiscalyear';
54
55
    /**
56
     * @var string    Name of subtable line
57
     */
58
    public $table_element_line = '';
59
60
    /**
61
     * @var string Field with ID of parent key if this field has a parent
62
     */
63
    public $fk_element = '';
64
65
    /**
66
     * @var int ID
67
     */
68
    public $rowid;
69
70
    /**
71
     * @var string fiscal year label
72
     */
73
    public $label;
74
75
    /**
76
     * Date start (date_start)
77
     *
78
     * @var integer
79
     */
80
    public $date_start;
81
82
    /**
83
     * Date end (date_end)
84
     *
85
     * @var integer
86
     */
87
    public $date_end;
88
89
    /**
90
     * Date creation record (datec)
91
     *
92
     * @var integer
93
     */
94
    public $datec;
95
96
    /**
97
     * @var int status 0=open, 1=closed
98
     * @deprecated
99
     * @see $status
100
     */
101
    public $statut;
102
103
    /**
104
     * @var int status 0=open, 1=closed
105
     */
106
    public $status;
107
108
    /**
109
     * @var int Entity
110
     */
111
    public $entity;
112
113
114
    const STATUS_OPEN = 0;
115
    const STATUS_CLOSED = 1;
116
117
118
    /**
119
     * Constructor
120
     *
121
     * @param   DoliDB      $db     Database handler
122
     */
123
    public function __construct(DoliDB $db)
124
    {
125
        $this->db = $db;
126
127
        $this->ismultientitymanaged = 1;
128
        $this->labelStatusShort = array(self::STATUS_OPEN => 'Opened', self::STATUS_CLOSED => 'Closed');
129
        $this->labelStatus = array(self::STATUS_OPEN => 'Opened', self::STATUS_CLOSED => 'Closed');
130
    }
131
132
    /**
133
     *  Create object in database
134
     *
135
     *  @param      User    $user   User making creation
136
     *  @return     int             Return integer <0 if KO, >0 if OK
137
     */
138
    public function create($user)
139
    {
140
        global $conf;
141
142
        $error = 0;
143
144
        $now = dol_now();
145
146
        $this->db->begin();
147
148
        $sql = "INSERT INTO " . $this->db->prefix() . "accounting_fiscalyear (";
149
        $sql .= "label";
150
        $sql .= ", date_start";
151
        $sql .= ", date_end";
152
        $sql .= ", statut";
153
        $sql .= ", entity";
154
        $sql .= ", datec";
155
        $sql .= ", fk_user_author";
156
        $sql .= ") VALUES (";
157
        $sql .= " '" . $this->db->escape($this->label) . "'";
158
        $sql .= ", '" . $this->db->idate($this->date_start) . "'";
159
        $sql .= ", " . ($this->date_end ? "'" . $this->db->idate($this->date_end) . "'" : "null");
160
        $sql .= ", 0";
161
        $sql .= ", " . ((int) $conf->entity);
162
        $sql .= ", '" . $this->db->idate($now) . "'";
163
        $sql .= ", " . ((int) $user->id);
164
        $sql .= ")";
165
166
        dol_syslog(get_only_class($this) . "::create", LOG_DEBUG);
167
        $result = $this->db->query($sql);
168
        if ($result) {
169
            $this->id = $this->db->last_insert_id($this->db->prefix() . "accounting_fiscalyear");
170
171
            $result = $this->update($user);
172
            if ($result > 0) {
173
                $this->db->commit();
174
                return $this->id;
175
            } else {
176
                $this->error = $this->db->lasterror();
177
                $this->db->rollback();
178
                return $result;
179
            }
180
        } else {
181
            $this->error = $this->db->lasterror() . " sql=" . $sql;
182
            $this->db->rollback();
183
            return -1;
184
        }
185
    }
186
187
    /**
188
     *  Update record
189
     *
190
     *  @param  User    $user       User making update
191
     *  @return int                 Return integer <0 if KO, >0 if OK
192
     */
193
    public function update($user)
194
    {
195
        // Check parameters
196
        if (empty($this->date_start) && empty($this->date_end)) {
197
            $this->error = 'ErrorBadParameter';
198
            return -1;
199
        }
200
201
        $this->db->begin();
202
203
        $sql = "UPDATE " . $this->db->prefix() . "accounting_fiscalyear";
204
        $sql .= " SET label = '" . $this->db->escape($this->label) . "'";
205
        $sql .= ", date_start = '" . $this->db->idate($this->date_start) . "'";
206
        $sql .= ", date_end = " . ($this->date_end ? "'" . $this->db->idate($this->date_end) . "'" : "null");
207
        $sql .= ", statut = '" . $this->db->escape($this->status ? $this->status : 0) . "'";
208
        $sql .= ", fk_user_modif = " . ((int) $user->id);
209
        $sql .= " WHERE rowid = " . ((int) $this->id);
210
211
        dol_syslog(get_only_class($this) . "::update", LOG_DEBUG);
212
        $result = $this->db->query($sql);
213
        if ($result) {
214
            $this->db->commit();
215
            return 1;
216
        } else {
217
            $this->error = $this->db->lasterror();
218
            dol_syslog($this->error, LOG_ERR);
219
            $this->db->rollback();
220
            return -1;
221
        }
222
    }
223
224
    /**
225
     * Load an object from database
226
     *
227
     * @param   int     $id     Id of record to load
228
     * @return  int             Return integer <0 if KO, >0 if OK
229
     */
230
    public function fetch($id)
231
    {
232
        $sql = "SELECT rowid, label, date_start, date_end, statut as status";
233
        $sql .= " FROM " . $this->db->prefix() . "accounting_fiscalyear";
234
        $sql .= " WHERE rowid = " . ((int) $id);
235
236
        dol_syslog(get_only_class($this) . "::fetch", LOG_DEBUG);
237
        $result = $this->db->query($sql);
238
        if ($result) {
239
            $obj = $this->db->fetch_object($result);
240
241
            $this->id = $obj->rowid;
242
            $this->ref = $obj->rowid;
243
            $this->date_start   = $this->db->jdate($obj->date_start);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->db->jdate($obj->date_start) can also be of type string. However, the property $date_start is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
244
            $this->date_end = $this->db->jdate($obj->date_end);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->db->jdate($obj->date_end) can also be of type string. However, the property $date_end is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
245
            $this->label = $obj->label;
246
            $this->statut = $obj->status;
247
            $this->status = $obj->status;
248
249
            return 1;
250
        } else {
251
            $this->error = $this->db->lasterror();
252
            return -1;
253
        }
254
    }
255
256
    /**
257
     *  Delete record
258
     *
259
     *  @param  User    $user   User that delete
260
     *  @return int             Return integer <0 if KO, >0 if OK
261
     */
262
    public function delete($user)
263
    {
264
        $this->db->begin();
265
266
        $sql = "DELETE FROM " . $this->db->prefix() . "accounting_fiscalyear";
267
        $sql .= " WHERE rowid = " . ((int) $this->id);
268
269
        $result = $this->db->query($sql);
270
        if ($result) {
271
            $this->db->commit();
272
            return 1;
273
        } else {
274
            $this->error = $this->db->lasterror();
275
            $this->db->rollback();
276
            return -1;
277
        }
278
    }
279
280
    /**
281
     * getTooltipContentArray
282
     *
283
     * @param array $params ex option, infologin
284
     * @since v18
285
     * @return array
286
     */
287
    public function getTooltipContentArray($params)
288
    {
289
        global $langs;
290
291
        $langs->load('compta');
292
293
        $datas = [];
294
        $datas['picto'] = img_picto('', $this->picto) . ' <b><u>' . $langs->trans("FiscalPeriod") . '</u></b>';
295
        if (isset($this->status)) {
296
            $datas['picto'] .= ' ' . $this->getLibStatut(5);
297
        }
298
        $datas['ref'] = '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
299
        if (isset($this->date_start)) {
300
            $datas['date_start'] = '<br><b>' . $langs->trans('DateStart') . ':</b> ' . dol_print_date($this->date_start, 'day');
301
        }
302
        if (isset($this->date_start)) {
303
            $datas['date_end'] = '<br><b>' . $langs->trans('DateEnd') . ':</b> ' . dol_print_date($this->date_end, 'day');
304
        }
305
306
        return $datas;
307
    }
308
309
    /**
310
     *  Return clicable link of object (with eventually picto)
311
     *
312
     *  @param      int         $withpicto                Add picto into link
313
     *  @param      int         $notooltip                1=Disable tooltip
314
     *  @param      int         $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
315
     *  @return     string                                String with URL
316
     */
317
    public function getNomUrl($withpicto = 0, $notooltip = 0, $save_lastsearch_value = -1)
318
    {
319
        global $conf, $langs, $user;
320
321
        if (empty($this->ref)) {
322
            $this->ref = (string) $this->id;
323
        }
324
325
        if (!empty($conf->dol_no_mouse_hover)) {
326
            $notooltip = 1; // Force disable tooltips
327
        }
328
        $option = '';
329
        if (!$user->hasRight('accounting', 'fiscalyear', 'write')) {
330
            $option = 'nolink';
331
        }
332
        $result = '';
333
        $params = [
334
            'id' => $this->id,
335
            'objecttype' => $this->element,
336
            'option' => $option,
337
            'nofetch' => 1,
338
        ];
339
        $classfortooltip = 'classfortooltip';
340
        $dataparams = '';
341
        if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
342
            $classfortooltip = 'classforajaxtooltip';
343
            $dataparams = ' data-params="' . dol_escape_htmltag(json_encode($params)) . '"';
344
            $label = 'ToComplete';
345
        } else {
346
            $label = implode($this->getTooltipContentArray($params));
347
        }
348
        $url = constant('BASE_URL') . '/accountancy/admin/fiscalyear_card.php?id=' . $this->id;
349
350
        if ($option !== 'nolink') {
351
            // Add param to save lastsearch_values or not
352
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
353
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
354
                $add_save_lastsearch_values = 1;
355
            }
356
            if ($add_save_lastsearch_values) {
357
                $url .= '&save_lastsearch_values=1';
358
            }
359
        }
360
361
        $linkclose = '';
362
        if (empty($notooltip) && $user->hasRight('accounting', 'fiscalyear', 'write')) {
363
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
364
                $label = $langs->trans("FiscalPeriod");
365
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
366
            }
367
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
368
            $linkclose .= $dataparams . ' class="' . $classfortooltip . '"';
369
        }
370
371
        $linkstart = '<a href="' . $url . '"';
372
        $linkstart .= $linkclose . '>';
373
        $linkend = '</a>';
374
375
        if ($option === 'nolink') {
376
            $linkstart = '';
377
            $linkend = '';
378
        }
379
380
        $result .= $linkstart;
381
        if ($withpicto) {
382
            $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams . ' class="' . (($withpicto != 2) ? 'paddingright ' : '') . $classfortooltip . '"'), 0, 0, $notooltip ? 0 : 1);
383
        }
384
        if ($withpicto != 2) {
385
            $result .= $this->ref;
386
        }
387
        $result .= $linkend;
388
389
        return $result;
390
    }
391
392
    /**
393
     * Give a label from a status
394
     *
395
     * @param   int     $mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
396
     * @return  string              Label
397
     */
398
    public function getLibStatut($mode = 0)
399
    {
400
        return $this->LibStatut($this->status, $mode);
401
    }
402
403
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
404
    /**
405
     *  Give a label from a status
406
     *
407
     *  @param  int     $status     Id status
408
     *  @param  int     $mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
409
     *  @return string              Label
410
     */
411
    public function LibStatut($status, $mode = 0)
412
    {
413
		// phpcs:enable
414
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
415
            global $langs;
416
            //$langs->load("mymodule@mymodule");
417
            $this->labelStatus[self::STATUS_OPEN] = $langs->transnoentitiesnoconv('Draft');
418
            $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('Enabled');
419
            $this->labelStatusShort[self::STATUS_OPEN] = $langs->transnoentitiesnoconv('Enabled');
420
            $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('Disabled');
421
        }
422
423
        $statusType = 'status4';
424
        //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
425
        if ($status == self::STATUS_CLOSED) {
426
            $statusType = 'status6';
427
        }
428
429
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
430
    }
431
432
    /**
433
     * Information on record
434
     *
435
     * @param   int     $id      Id of record
436
     * @return  void
437
     */
438
    public function info($id)
439
    {
440
        $sql = "SELECT fy.rowid, fy.datec, fy.fk_user_author, fy.fk_user_modif,";
441
        $sql .= " fy.tms as datem";
442
        $sql .= " FROM " . $this->db->prefix() . "accounting_fiscalyear as fy";
443
        $sql .= " WHERE fy.rowid = " . ((int) $id);
444
445
        dol_syslog(get_only_class($this) . "::fetch info", LOG_DEBUG);
446
        $result = $this->db->query($sql);
447
448
        if ($result) {
449
            if ($this->db->num_rows($result)) {
450
                $obj = $this->db->fetch_object($result);
451
452
                $this->id = $obj->rowid;
453
454
                $this->user_creation_id = $obj->fk_user_author;
455
                $this->user_modification_id = $obj->fk_user_modif;
456
                $this->date_creation     = $this->db->jdate($obj->datec);
457
                $this->date_modification = $this->db->jdate($obj->datem);
458
            }
459
            $this->db->free($result);
460
        } else {
461
            dol_print_error($this->db);
462
        }
463
    }
464
465
    /**
466
     *  Return the number of entries by fiscal year
467
     *
468
     *  @param  int|string      $datestart  Date start to scan
469
     *  @param  int|string      $dateend    Date end to scan
470
     *  @return string          Number of entries
471
     */
472
    public function getAccountancyEntriesByFiscalYear($datestart = '', $dateend = '')
473
    {
474
        global $conf;
475
476
        if (empty($datestart)) {
477
            $datestart = $this->date_start;
478
        }
479
        if (empty($dateend)) {
480
            $dateend = $this->date_end;
481
        }
482
483
        $sql = "SELECT count(DISTINCT piece_num) as nb";
484
        $sql .= " FROM " . $this->db->prefix() . "accounting_bookkeeping";
485
        $sql .= " WHERE entity IN (" . getEntity('bookkeeping', 0) . ")";
486
        $sql .= " AND doc_date >= '" . $this->db->idate($datestart) . "' and doc_date <= '" . $this->db->idate($dateend) . "'";
487
488
        $resql = $this->db->query($sql);
489
        if ($resql) {
490
            $obj = $this->db->fetch_object($resql);
491
            $nb = $obj->nb;
492
        } else {
493
            dol_print_error($this->db);
494
        }
495
496
        return $nb;
497
    }
498
499
    /**
500
     *  Return the number of movements by fiscal year
501
     *
502
     *  @param  int|string      $datestart  Date start to scan
503
     *  @param  int|string      $dateend    Date end to scan
504
     *  @return string              Number of movements
505
     */
506
    public function getAccountancyMovementsByFiscalYear($datestart = '', $dateend = '')
507
    {
508
        global $conf;
509
510
        if (empty($datestart)) {
511
            $datestart = $this->date_start;
512
        }
513
        if (empty($dateend)) {
514
            $dateend = $this->date_end;
515
        }
516
517
        $sql = "SELECT count(rowid) as nb";
518
        $sql .= " FROM " . $this->db->prefix() . "accounting_bookkeeping ";
519
        $sql .= " WHERE entity IN (" . getEntity('bookkeeping', 0) . ")";
520
        $sql .= " AND doc_date >= '" . $this->db->idate($datestart) . "' and doc_date <= '" . $this->db->idate($dateend) . "'";
521
522
        $resql = $this->db->query($sql);
523
        if ($resql) {
524
            $obj = $this->db->fetch_object($resql);
525
            $nb = $obj->nb;
526
        } else {
527
            dol_print_error($this->db);
528
        }
529
530
        return $nb;
531
    }
532
}
533