Passed
Push — EXTRACT_CLASSES ( ae6b5c...83d77a )
by Rafael
60:14 queued 23:58
created

PaymentSalary   F

Complexity

Total Complexity 136

Size/Duplication

Total Lines 976
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 457
dl 0
loc 976
rs 2
c 0
b 0
f 0
wmc 136

15 Methods

Rating   Name   Duplication   Size   Complexity  
A fetch() 0 58 3
A createFromClone() 0 35 3
F getNomUrl() 0 89 28
B updatePaymentDate() 0 46 6
A __construct() 0 3 1
C getKanbanView() 0 38 11
B delete() 0 41 8
A update_fk_bank() 0 12 2
C addPaymentToBank() 0 92 14
F update() 0 73 25
B getTooltipContentArray() 0 28 7
A LibStatut() 0 42 1
A getLibStatut() 0 3 1
A initAsSpecimen() 0 17 1
F create() 0 121 25

How to fix   Complexity   

Complex Class

Complex classes like PaymentSalary often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PaymentSalary, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2011-2022  Alexandre Spangaro          <[email protected]>
4
 * Copyright (C) 2014       Juanjo Menent               <[email protected]>
5
 * Copyright (C) 2021       Gauthier VERDOL             <[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
namespace Dolibarr\Code\Salaries\Classes;
25
26
use Dolibarr\Core\Base\CommonObject;
27
28
/**
29
 *  \file       htdocs/salaries/class/paymentsalary.class.php
30
 *  \ingroup    salaries
31
 *  \brief      File of class to manage payment of salaries
32
 */
33
34
// Put here all includes required by your class file
35
require_once constant('DOL_DOCUMENT_ROOT') . '/salaries/class/salary.class.php';
36
37
38
/**
39
 *  Class to manage payments of salaries
40
 */
41
class PaymentSalary extends CommonObject
42
{
43
    /**
44
     * @var string          ID to identify managed object
45
     */
46
    public $element = 'payment_salary';
47
48
    /**
49
     * @var string          Name of table without prefix where object is stored
50
     */
51
    public $table_element = 'payment_salary';
52
53
    /**
54
     * @var string          String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
55
     */
56
    public $picto = 'payment';
57
58
    /**
59
     * @var int chid
60
     * @deprecated
61
     * @see $fk_salary
62
     */
63
    public $chid;
64
65
    /**
66
     * @var int             ID of the salary linked to the payment
67
     */
68
    public $fk_salary;
69
70
    /**
71
     * @var int|string              Payment creation date
72
     */
73
    public $datec = '';
74
75
    /**
76
     * @var int|string      Date of payment
77
     * @deprecated
78
     * @see $datep
79
     */
80
    public $datepaye = '';
81
82
    /**
83
     * @var int|string      Date of payment
84
     */
85
    public $datep = '';
86
87
    /**
88
     * @deprecated
89
     * @see $amount
90
     */
91
    public $total;
92
93
    /**
94
     * @var float           Total amount of payment
95
     */
96
    public $amount;
97
98
    /**
99
     * @var array           Array of amounts
100
     */
101
    public $amounts = array();
102
103
    /**
104
     * @var int             Payment type ID
105
     */
106
    public $fk_typepayment;
107
108
    /**
109
     * @var string
110
     * @deprecated
111
     */
112
    public $num_paiement;
113
114
    /**
115
     * @var string      Payment reference
116
     *                  (Cheque or bank transfer reference. Can be "ABC123")
117
     */
118
    public $num_payment;
119
120
    /**
121
     * @inheritdoc
122
     */
123
    public $fk_bank;
124
125
    /**
126
     * @var int             ID of bank_line
127
     */
128
    public $bank_line;
129
130
    /**
131
     * @var int             ID of the user who created the payment
132
     */
133
    public $fk_user_author;
134
135
    /**
136
     * @var int             ID of the user who modified the payment
137
     */
138
    public $fk_user_modif;
139
140
    /**
141
     * @var int             Payment type
142
     */
143
    public $type_code;
144
145
    /**
146
     * @var int             Payment label
147
     */
148
    public $type_label;
149
150
    /**
151
     * @var int             Bank account description
152
     */
153
    public $bank_account;
154
155
    /**
156
     * @var int|string      Payment validation date
157
     */
158
    public $datev = '';
159
160
    /**
161
     * @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}>  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
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...
162
     */
163
    public $fields = array(
164
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'index' => 1, 'position' => 1, 'comment' => 'Id'),
165
    );
166
167
    /**
168
     *  Constructor
169
     *
170
     *  @param      DoliDB      $db      Database handler
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Salaries\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
171
     */
172
    public function __construct($db)
173
    {
174
        $this->db = $db;
175
    }
176
177
    /**
178
     *  Create payment of salary into database.
179
     *  Use this->amounts to have list of lines for the payment
180
     *
181
     *  @param      User    $user                   User making payment
182
     *  @param      int     $closepaidcontrib       1=Also close paid contributions to paid, 0=Do nothing more
183
     *  @return     int                             Return integer <0 if KO, id of payment if OK
184
     */
185
    public function create($user, $closepaidcontrib = 0)
186
    {
187
        global $conf;
188
189
        $error = 0;
190
191
        $now = dol_now();
192
193
        dol_syslog(get_class($this) . "::create", LOG_DEBUG);
194
195
        //deprecatd
196
        if (!empty($this->datepaye) && empty($this->datep)) {
197
            dol_syslog(__METHOD__ . ": using datepaye is deprecated, please use datep instead", LOG_WARNING);
198
            $this->datep = $this->datepaye;
199
        }
200
201
        // Validate parameters
202
        if (empty($this->datep)) {
203
            $this->error = 'ErrorBadValueForParameterCreatePaymentSalary';
204
            return -1;
205
        }
206
207
        // Clean parameters
208
        if (isset($this->fk_salary)) {
209
            $this->fk_salary = (int) $this->fk_salary;
210
        }
211
        if (isset($this->amount)) {
212
            $this->amount = (float) $this->amount;
213
        }
214
        if (isset($this->fk_typepayment)) {
215
            $this->fk_typepayment = (int) $this->fk_typepayment;
216
        }
217
        if (isset($this->num_paiement)) {
218
            $this->num_paiement = trim($this->num_paiement);
219
        } // deprecated
220
        if (isset($this->num_payment)) {
221
            $this->num_payment = trim($this->num_payment);
222
        }
223
        if (isset($this->note)) {
224
            $this->note = trim($this->note);
225
        }
226
        if (isset($this->fk_bank)) {
227
            $this->fk_bank = (int) $this->fk_bank;
228
        }
229
        if (isset($this->fk_user_author)) {
230
            $this->fk_user_author = (int) $this->fk_user_author;
231
        }
232
        if (isset($this->fk_user_modif)) {
233
            $this->fk_user_modif = (int) $this->fk_user_modif;
234
        }
235
236
        $totalamount = 0;
237
        foreach ($this->amounts as $key => $value) {  // How payment is dispatch
238
            $newvalue = (float) price2num($value, 'MT');
239
            $this->amounts[$key] = $newvalue;
240
            $totalamount += $newvalue;
241
        }
242
243
        // Check parameters
244
        $totalamount = (float) price2num($totalamount, 'MT'); // this is to ensure the following test is no biaised by a potential float equal to 0.0000000000001
245
        if ($totalamount == 0) {
246
            return -1;
247
        } // On accepte les montants negatifs pour les rejets de prelevement mais pas null
248
249
250
        $this->db->begin();
251
252
        if ($totalamount != 0) {
253
            // Insert array of amounts
254
            foreach ($this->amounts as $key => $amount) {
255
                $salary_id = $key;
256
                if (is_numeric($amount) && !empty($amount)) {
257
                    // We can have n payments for 1 salary but we can't have 1 payments for n salaries (for invoices link is n-n, not for salaries).
258
                    $sql = "INSERT INTO " . MAIN_DB_PREFIX . "payment_salary (entity, fk_salary, datec, datep, amount,";
259
                    $sql .= " fk_typepayment, num_payment, note, fk_user_author, fk_bank)";
260
                    $sql .= " VALUES (" . ((int) $conf->entity) . ", " . ((int) $salary_id) . ", '" . $this->db->idate($now) . "',";
261
                    $sql .= " '" . $this->db->idate($this->datep) . "',";
262
                    $sql .= " " . ((float) $amount) . ",";
263
                    $sql .= " " . ((int) $this->fk_typepayment) . ", '" . $this->db->escape($this->num_payment) . "', '" . $this->db->escape($this->note) . "', " . ((int) $user->id) . ",";
264
                    $sql .= " 0)";
265
266
                    $resql = $this->db->query($sql);
267
                    if ($resql) {
268
                        $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "payment_salary");
269
                    }
270
271
                    // If we want to closed paid invoices
272
                    if ($closepaidcontrib) {
273
                        $tmpsalary = new Salary($this->db);
274
                        $tmpsalary->fetch($salary_id);
275
                        $paiement = $tmpsalary->getSommePaiement();
276
                        //$creditnotes=$tmpsalary->getSumCreditNotesUsed();
277
                        $creditnotes = 0;
278
                        //$deposits=$tmpsalary->getSumDepositsUsed();
279
                        $deposits = 0;
280
                        $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
281
                        $remaintopay = price2num($tmpsalary->amount - $paiement - $creditnotes - $deposits, 'MT');
282
                        if ($remaintopay == 0) {
283
                            $result = $tmpsalary->setPaid($user);
284
                        } else {
285
                            dol_syslog("Remain to pay for salary id=" . $salary_id . " not null. We do nothing.");
286
                        }
287
                    }
288
                }
289
            }
290
        }
291
292
        $result = $this->call_trigger('PAYMENTSALARY_CREATE', $user);
293
        if ($result < 0) {
294
            $error++;
295
        }
296
297
        if ($totalamount != 0 && !$error) {
298
            $this->amount = $totalamount;
299
            $this->total = $totalamount; // deprecated
300
            $this->db->commit();
301
            return $this->id;   // id of the last payment inserted
302
        } else {
303
            $this->error = $this->db->error();
304
            $this->db->rollback();
305
            return -1;
306
        }
307
    }
308
309
    /**
310
     *  Load object in memory from database
311
     *
312
     *  @param  int     $id         Id object
313
     *  @return int                 Return integer <0 if KO, >0 if OK
314
     */
315
    public function fetch($id)
316
    {
317
        global $langs;
318
        $sql = "SELECT";
319
        $sql .= " t.rowid,";
320
        $sql .= " t.fk_salary,";
321
        $sql .= " t.datec,";
322
        $sql .= " t.tms,";
323
        $sql .= " t.datep,";
324
        $sql .= " t.amount,";
325
        $sql .= " t.fk_typepayment,";
326
        $sql .= " t.num_payment as num_payment,";
327
        $sql .= " t.note,";
328
        $sql .= " t.fk_bank,";
329
        $sql .= " t.fk_user_author,";
330
        $sql .= " t.fk_user_modif,";
331
        $sql .= " pt.code as type_code, pt.libelle as type_label,";
332
        $sql .= ' b.fk_account';
333
        $sql .= " FROM " . MAIN_DB_PREFIX . "payment_salary as t LEFT JOIN " . MAIN_DB_PREFIX . "c_paiement as pt ON t.fk_typepayment = pt.id";
334
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON t.fk_bank = b.rowid';
335
        $sql .= " WHERE t.rowid = " . ((int) $id);
336
        // TODO link on entity of tax;
337
338
        dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
339
        $resql = $this->db->query($sql);
340
        if ($resql) {
341
            if ($this->db->num_rows($resql)) {
342
                $obj = $this->db->fetch_object($resql);
343
344
                $this->id    = $obj->rowid;
345
                $this->ref   = $obj->rowid;
346
347
                $this->fk_salary = $obj->fk_salary;
348
                $this->datec = $this->db->jdate($obj->datec);
349
                $this->tms = $this->db->jdate($obj->tms);
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$tms has been deprecated: Use $date_modification ( Ignorable by Annotation )

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

349
                /** @scrutinizer ignore-deprecated */ $this->tms = $this->db->jdate($obj->tms);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
350
                $this->datepaye = $this->db->jdate($obj->datep);
351
                $this->amount = $obj->amount;
352
                $this->fk_typepayment = $obj->fk_typepayment;
353
                $this->num_paiement = $obj->num_payment;
354
                $this->num_payment = $obj->num_payment;
355
                $this->note = $obj->note;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$note has been deprecated: Use $note_private instead. ( Ignorable by Annotation )

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

355
                /** @scrutinizer ignore-deprecated */ $this->note = $obj->note;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
356
                $this->note_private = $obj->note;
357
                $this->fk_bank = $obj->fk_bank;
358
                $this->fk_user_author = $obj->fk_user_author;
359
                $this->fk_user_modif = $obj->fk_user_modif;
360
361
                $this->type_code = $obj->type_code;
362
                $this->type_label = $obj->type_label;
363
364
                $this->bank_account   = $obj->fk_account;
365
                $this->bank_line      = $obj->fk_bank;
366
            }
367
            $this->db->free($resql);
368
369
            return 1;
370
        } else {
371
            $this->error = "Error " . $this->db->lasterror();
372
            return -1;
373
        }
374
    }
375
376
377
    /**
378
     *  Update database
379
     *
380
     *  @param  User    $user           User that modify
381
     *  @param  int     $notrigger      0=launch triggers after, 1=disable triggers
382
     *  @return int                     Return integer <0 if KO, >0 if OK
383
     */
384
    public function update($user = null, $notrigger = 0)
385
    {
386
        global $conf, $langs;
387
        $error = 0;
388
389
        // Clean parameters
390
391
        if (isset($this->fk_salary)) {
392
            $this->fk_salary = (int) $this->fk_salary;
393
        }
394
        if (isset($this->amount)) {
395
            $this->amount = (float) $this->amount;
396
        }
397
        if (isset($this->fk_typepayment)) {
398
            $this->fk_typepayment = (int) $this->fk_typepayment;
399
        }
400
        if (isset($this->num_paiement)) {
401
            $this->num_paiement = trim($this->num_paiement);
402
        } // deprecated
403
        if (isset($this->num_payment)) {
404
            $this->num_payment = trim($this->num_payment);
405
        }
406
        if (isset($this->note)) {
407
            $this->note = trim($this->note);
408
        }
409
        if (isset($this->fk_bank)) {
410
            $this->fk_bank = (int) $this->fk_bank;
411
        }
412
        if (isset($this->fk_user_author)) {
413
            $this->fk_user_author = (int) $this->fk_user_author;
414
        }
415
        if (isset($this->fk_user_modif)) {
416
            $this->fk_user_modif = (int) $this->fk_user_modif;
417
        }
418
419
        // Check parameters
420
        // Put here code to add control on parameters values
421
422
        // Update request
423
        $sql = "UPDATE " . MAIN_DB_PREFIX . "payment_salary SET";
424
        $sql .= " fk_salary=" . (isset($this->fk_salary) ? $this->fk_salary : "null") . ",";
425
        $sql .= " datec=" . (dol_strlen($this->datec) != 0 ? "'" . $this->db->idate($this->datec) . "'" : 'null') . ",";
426
        $sql .= " tms=" . (dol_strlen($this->tms) != 0 ? "'" . $this->db->idate($this->tms) . "'" : 'null') . ",";
427
        $sql .= " datep=" . (dol_strlen($this->datepaye) != 0 ? "'" . $this->db->idate($this->datepaye) . "'" : 'null') . ",";
428
        $sql .= " amount=" . (isset($this->amount) ? $this->amount : "null") . ",";
429
        $sql .= " fk_typepayment=" . (isset($this->fk_typepayment) ? $this->fk_typepayment : "null") . ",";
430
        $sql .= " num_payment=" . (isset($this->num_payment) ? "'" . $this->db->escape($this->num_payment) . "'" : "null") . ",";
431
        $sql .= " note=" . (isset($this->note) ? "'" . $this->db->escape($this->note) . "'" : "null") . ",";
432
        $sql .= " fk_bank=" . (isset($this->fk_bank) ? ((int) $this->fk_bank) : "null") . ",";
433
        $sql .= " fk_user_author=" . (isset($this->fk_user_author) ? ((int) $this->fk_user_author) : "null") . ",";
434
        $sql .= " fk_user_modif=" . (isset($this->fk_user_modif) ? ((int) $this->fk_user_modif) : "null");
435
        $sql .= " WHERE rowid=" . ((int) $this->id);
436
437
        $this->db->begin();
438
439
        dol_syslog(get_class($this) . "::update", LOG_DEBUG);
440
        $resql = $this->db->query($sql);
441
        if (!$resql) {
442
            $error++;
443
            $this->errors[] = "Error " . $this->db->lasterror();
444
        }
445
446
        // Commit or rollback
447
        if ($error) {
448
            foreach ($this->errors as $errmsg) {
449
                dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR);
450
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
451
            }
452
            $this->db->rollback();
453
            return -1 * $error;
454
        } else {
455
            $this->db->commit();
456
            return 1;
457
        }
458
    }
459
460
461
    /**
462
     *  Delete object in database
463
     *
464
     *  @param  User    $user           User that delete
465
     *  @param  int     $notrigger      0=launch triggers after, 1=disable triggers
466
     *  @return int                     Return integer <0 if KO, >0 if OK
467
     */
468
    public function delete($user, $notrigger = 0)
469
    {
470
        $error = 0;
471
472
        dol_syslog(get_class($this) . "::delete");
473
474
        $this->db->begin();
475
476
        if ($this->bank_line > 0) {
477
            $accline = new AccountLine($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Salaries\Classes\AccountLine was not found. Did you mean AccountLine? If so, make sure to prefix the type with \.
Loading history...
478
            $accline->fetch($this->bank_line);
479
            $result = $accline->delete($user);
480
            if ($result < 0) {
481
                $this->errors[] = $accline->error;
482
                $error++;
483
            }
484
        }
485
486
        if (!$error) {
487
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "payment_salary";
488
            $sql .= " WHERE rowid=" . ((int) $this->id);
489
490
            dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
491
            $resql = $this->db->query($sql);
492
            if (!$resql) {
493
                $error++;
494
                $this->errors[] = "Error " . $this->db->lasterror();
495
            }
496
        }
497
498
        // Commit or rollback
499
        if ($error) {
500
            foreach ($this->errors as $errmsg) {
501
                dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
502
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
503
            }
504
            $this->db->rollback();
505
            return -1 * $error;
506
        } else {
507
            $this->db->commit();
508
            return 1;
509
        }
510
    }
511
512
513
514
    /**
515
     *  Load an object from its id and create a new one in database
516
     *
517
     *  @param  User    $user           User making the clone
518
     *  @param  int     $fromid         Id of object to clone
519
     *  @return int                     New id of clone
520
     */
521
    public function createFromClone(User $user, $fromid)
522
    {
523
        $error = 0;
524
525
        $object = new PaymentSalary($this->db);
526
527
        $this->db->begin();
528
529
        // Load source object
530
        $object->fetch($fromid);
531
        $object->id = 0;
532
        $object->statut = 0;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

532
        /** @scrutinizer ignore-deprecated */ $object->statut = 0;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
533
534
        // Clear fields
535
        // ...
536
537
        // Create clone
538
        $object->context['createfromclone'] = 'createfromclone';
539
        $result = $object->create($user);
540
541
        // Other options
542
        if ($result < 0) {
543
            $this->error = $object->error;
544
            $error++;
545
        }
546
547
        unset($object->context['createfromclone']);
548
549
        // End
550
        if (!$error) {
551
            $this->db->commit();
552
            return $object->id;
553
        } else {
554
            $this->db->rollback();
555
            return -1;
556
        }
557
    }
558
559
560
    /**
561
     *  Initialise an instance with random values.
562
     *  Used to build previews or test instances.
563
     *  id must be 0 if object instance is a specimen.
564
     *
565
     *  @return int
566
     */
567
    public function initAsSpecimen()
568
    {
569
        $this->id = 0;
570
        $this->fk_salary = 0;
571
        $this->datec = '';
572
        $this->tms = dol_now();
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$tms has been deprecated: Use $date_modification ( Ignorable by Annotation )

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

572
        /** @scrutinizer ignore-deprecated */ $this->tms = dol_now();

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
573
        $this->datepaye = dol_now();
574
        $this->amount = 0.0;
575
        $this->fk_typepayment = 0;
576
        $this->num_payment = '';
577
        $this->note_private = '';
578
        $this->note_public = '';
579
        $this->fk_bank = 0;
580
        $this->fk_user_author = 0;
581
        $this->fk_user_modif = 0;
582
583
        return 1;
584
    }
585
586
587
    /**
588
     *      Add record into bank for payment with links between this bank record and invoices of payment.
589
     *      All payment properties must have been set first like after a call to create().
590
     *
591
     *      @param  User    $user               Object of user making payment
592
     *      @param  string  $mode               'payment_salary'
593
     *      @param  string  $label              Label to use in bank record
594
     *      @param  int     $accountid          Id of bank account to do link with
595
     *      @param  string  $emetteur_nom       Name of transmitter
596
     *      @param  string  $emetteur_banque    Name of bank
597
     *      @return int                         Return integer <0 if KO, >0 if OK
598
     */
599
    public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque)
600
    {
601
        global $langs;
602
603
        // Clean data
604
        $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement);
605
606
        $error = 0;
607
608
        if (isModEnabled("bank")) {
609
            include_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
610
611
            $acc = new Account($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Salaries\Classes\Account was not found. Did you mean Account? If so, make sure to prefix the type with \.
Loading history...
612
            $acc->fetch($accountid);
613
614
            $total = $this->amount;
615
616
            // Insert payment into llx_bank
617
            $bank_line_id = $acc->addline(
618
                $this->datep,
619
                $this->fk_typepayment, // Payment mode id or code ("CHQ or VIR for example")
620
                $label,
621
                -$total,
622
                $this->num_payment,
623
                '',
624
                $user,
625
                $emetteur_nom,
626
                $emetteur_banque,
627
                '',
628
                $this->datev
629
            );
630
631
            // Update fk_bank into llx_paiement_salary.
632
            // so we know the payment that was used to generated the bank entry.
633
            if ($bank_line_id > 0) {
634
                $result = $this->update_fk_bank($bank_line_id);
635
                if ($result <= 0) {
636
                    $error++;
637
                    dol_print_error($this->db);
638
                }
639
640
                // Add link 'payment_salary' in bank_url between payment and bank transaction
641
                $url = '';
642
                if ($mode == 'payment_salary') {
643
                    $url = constant('BASE_URL') . '/salaries/payment_salary/card.php?id=';
644
                }
645
646
                if ($url) {
647
                    $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode);
648
                    if ($result <= 0) {
649
                        $error++;
650
                        dol_print_error($this->db);
651
                    }
652
                }
653
654
                // Add link 'user' in bank_url between user and bank transaction
655
                foreach ($this->amounts as $key => $value) {
656
                    if (!$error) {
657
                        if ($mode == 'payment_salary') {
658
                            $salary = new Salary($this->db);
659
                            $salary->fetch($key);
660
                            $salary->fetch_user($salary->fk_user);
661
662
                            $fuser = $salary->user;
663
664
                            if ($fuser->id > 0) {
665
                                $result = $acc->add_url_line(
666
                                    $bank_line_id,
667
                                    $fuser->id,
668
                                    constant('BASE_URL') . '/user/card.php?id=',
669
                                    $fuser->getFullName($langs),
670
                                    'user'
671
                                );
672
                            }
673
                            if ($result <= 0) {
674
                                $this->error = $this->db->lasterror();
675
                                dol_syslog(get_class($this) . '::addPaymentToBank ' . $this->error);
676
                                $error++;
677
                            }
678
                        }
679
                    }
680
                }
681
            } else {
682
                $this->error = $acc->error;
683
                $error++;
684
            }
685
        }
686
687
        if (!$error) {
688
            return 1;
689
        } else {
690
            return -1;
691
        }
692
    }
693
694
695
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
696
    /**
697
     *  Mise a jour du lien entre le paiement de  salaire et la ligne dans llx_bank generee
698
     *
699
     *  @param  int     $id_bank         Id if bank
700
     *  @return int                      >0 if OK, <=0 if KO
701
     */
702
    public function update_fk_bank($id_bank)
703
    {
704
		// phpcs:enable
705
        $sql = "UPDATE " . MAIN_DB_PREFIX . "payment_salary SET fk_bank = " . ((int) $id_bank) . " WHERE rowid = " . ((int) $this->id);
706
707
        dol_syslog(get_class($this) . "::update_fk_bank", LOG_DEBUG);
708
        $result = $this->db->query($sql);
709
        if ($result) {
710
            return 1;
711
        } else {
712
            $this->error = $this->db->error();
713
            return 0;
714
        }
715
    }
716
717
    /**
718
     *  Updates the payment date.
719
     *  Old name of function is update_date()
720
     *
721
     *  @param  int $date           New date
722
     *  @return int                 Return integer <0 if KO, 0 if OK
723
     */
724
    public function updatePaymentDate($date)
725
    {
726
        $error = 0;
727
728
        if (!empty($date)) {
729
            $this->db->begin();
730
731
            dol_syslog(get_class($this) . "::updatePaymentDate with date = " . $date, LOG_DEBUG);
732
733
            $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
734
            $sql .= " SET datep = '" . $this->db->idate($date) . "'";
735
            $sql .= " WHERE rowid = " . ((int) $this->id);
736
737
            $result = $this->db->query($sql);
738
            if (!$result) {
739
                $error++;
740
                $this->error = 'Error -1 ' . $this->db->error();
741
            }
742
743
            $type = $this->element;
744
745
            $sql = "UPDATE " . MAIN_DB_PREFIX . 'bank';
746
            $sql .= " SET dateo = '" . $this->db->idate($date) . "', datev = '" . $this->db->idate($date) . "'";
747
            $sql .= " WHERE rowid IN (SELECT fk_bank FROM " . MAIN_DB_PREFIX . "bank_url WHERE type = '" . $this->db->escape($type) . "' AND url_id = " . ((int) $this->id) . ")";
748
            $sql .= " AND rappro = 0";
749
750
            $result = $this->db->query($sql);
751
            if (!$result) {
752
                $error++;
753
                $this->error = 'Error -1 ' . $this->db->error();
754
            }
755
756
            if (!$error) {
757
            }
758
759
            if (!$error) {
760
                $this->datepaye = $date;
761
762
                $this->db->commit();
763
                return 0;
764
            } else {
765
                $this->db->rollback();
766
                return -2;
767
            }
768
        }
769
        return -1; //no date given or already validated
770
    }
771
772
    /**
773
     *  Return the label of the status
774
     *
775
     *  @param  int     $mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
776
     *  @return string                 Label of status
777
     */
778
    public function getLibStatut($mode = 0)
779
    {
780
        return $this->LibStatut($this->statut, $mode);
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

780
        return $this->LibStatut(/** @scrutinizer ignore-deprecated */ $this->statut, $mode);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
781
    }
782
783
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
784
    /**
785
     *  Return the status
786
     *
787
     *  @param  int     $status        Id status
788
     *  @param  int     $mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
789
     *  @return string                 Label of status
790
     */
791
    public function LibStatut($status, $mode = 0)
792
    {
793
		// phpcs:enable
794
        global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage
795
796
        $langs->load('compta');
797
        /*if ($mode == 0)
798
            {
799
            if ($status == 0) return $langs->trans('ToValidate');
800
            if ($status == 1) return $langs->trans('Validated');
801
            }
802
            if ($mode == 1)
803
            {
804
            if ($status == 0) return $langs->trans('ToValidate');
805
            if ($status == 1) return $langs->trans('Validated');
806
            }
807
            if ($mode == 2)
808
            {
809
            if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
810
            if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
811
            }
812
            if ($mode == 3)
813
            {
814
            if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1');
815
            if ($status == 1) return img_picto($langs->trans('Validated'),'statut4');
816
            }
817
            if ($mode == 4)
818
            {
819
            if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate');
820
            if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated');
821
            }
822
            if ($mode == 5)
823
            {
824
            if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
825
            if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
826
            }
827
            if ($mode == 6)
828
            {
829
            if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1');
830
            if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4');
831
            }*/
832
        return '';
833
    }
834
835
    /**
836
     *  Return clicable name (with picto eventually)
837
     *
838
     *  @param  int     $withpicto                  0=No picto, 1=Include picto into link, 2=Only picto
839
     *  @param  int     $maxlen                     Longueur max libelle
840
     *  @param  int     $notooltip                  1=Disable tooltip
841
     *  @param  string  $morecss                    Add more css on link
842
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
843
     *  @return string                              Chaine avec URL
844
     */
845
    public function getNomUrl($withpicto = 0, $maxlen = 0, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
846
    {
847
        global $conf, $langs, $hookmanager;
848
849
        $option = '';
850
851
        if (!empty($conf->dol_no_mouse_hover)) {
852
            $notooltip = 1; // Force disable tooltips
853
        }
854
855
        $result = '';
856
        $params = [
857
            'id' => $this->id,
858
            'objecttype' => $this->element . ($this->module ? '@' . $this->module : ''),
859
            //'option' => $option,
860
        ];
861
        $classfortooltip = 'classfortooltip';
862
        $dataparams = '';
863
        if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
864
            $classfortooltip = 'classforajaxtooltip';
865
            $dataparams = ' data-params="' . dol_escape_htmltag(json_encode($params)) . '"';
866
            $label = '';
867
        } else {
868
            $label = implode($this->getTooltipContentArray($params));
869
        }
870
871
        $url = constant('BASE_URL') . '/salaries/payment_salary/card.php?id=' . $this->id;
872
873
        if ($option !== 'nolink') {
874
            // Add param to save lastsearch_values or not
875
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
876
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
877
                $add_save_lastsearch_values = 1;
878
            }
879
            if ($url && $add_save_lastsearch_values) {
880
                $url .= '&save_lastsearch_values=1';
881
            }
882
        }
883
884
        $linkclose = '';
885
        if (empty($notooltip)) {
886
            if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
887
                $label = $langs->trans("SalaryPayment");
888
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
889
            }
890
            $linkclose .= ($label ? ' title="' . dol_escape_htmltag($label, 1) . '"' : ' title="tocomplete"');
891
            $linkclose .= $dataparams . ' class="' . $classfortooltip . ($morecss ? ' ' . $morecss : '') . '"';
892
        } else {
893
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
894
        }
895
896
        if ($option == 'nolink' || empty($url)) {
897
            $linkstart = '<span';
898
        } else {
899
            $linkstart = '<a href="' . $url . '"';
900
        }
901
        $linkstart .= $linkclose . '>';
902
        if ($option == 'nolink' || empty($url)) {
903
            $linkend = '</span>';
904
        } else {
905
            $linkend = '</a>';
906
        }
907
908
        $result .= $linkstart;
909
910
        if (empty($this->showphoto_on_popup)) {
911
            if ($withpicto) {
912
                $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
913
            }
914
        }
915
916
        if ($withpicto != 2) {
917
            $result .= $this->ref;
918
        }
919
920
        $result .= $linkend;
921
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
922
923
        global $action, $hookmanager;
924
        $hookmanager->initHooks(array($this->element . 'dao'));
925
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
926
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
927
        if ($reshook > 0) {
928
            $result = $hookmanager->resPrint;
929
        } else {
930
            $result .= $hookmanager->resPrint;
931
        }
932
933
        return $result;
934
    }
935
936
    /**
937
     * getTooltipContentArray
938
     *
939
     * @param array $params params to construct tooltip data
940
     * @return array
941
     */
942
    public function getTooltipContentArray($params)
943
    {
944
        global $conf, $langs, $user;
945
946
        $langs->load('salaries');
947
        $datas = [];
948
949
        if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
950
            return ['optimize' => $langs->trans("SalaryPayment")];
951
        }
952
953
        if ($user->hasRight('salaries', 'read')) {
954
            $datas['picto'] = img_picto('', $this->picto) . ' <u class="paddingrightonly">' . $langs->trans("SalaryPayment") . '</u>';
955
            if (isset($this->status)) {
956
                $datas['status'] = ' ' . $this->getLibStatut(5);
957
            }
958
            $datas['Ref'] = '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
959
            if (!empty($this->total_ttc)) {
960
                $datas['AmountTTC'] = '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
961
            }
962
            if (!empty($this->datep)) {
963
                $datas['Date'] = '<br><b>' . $langs->trans('Date') . ':</b> ' . dol_print_date($this->datep, 'dayhour', 'tzuserrel');
964
            } elseif (!empty($this->datepaye)) {
965
                $datas['Date'] = '<br><b>' . $langs->trans('Date') . ':</b> ' . dol_print_date($this->datepaye, 'dayhour', 'tzuserrel');
966
            }
967
        }
968
969
        return $datas;
970
    }
971
972
    /**
973
     *  Return clicable link of object (with eventually picto)
974
     *
975
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
976
     *  @param      array       $arraydata              Array of data
977
     *  @return     string                              HTML Code for Kanban thumb.
978
     */
979
    public function getKanbanView($option = '', $arraydata = null)
980
    {
981
        global $langs;
982
983
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
984
985
        $return = '<div class="box-flex-item box-flex-grow-zero">';
986
        $return .= '<div class="info-box info-box-sm">';
987
        $return .= '<span class="info-box-icon bg-infobox-action">';
988
        $return .= img_picto('', $this->picto);
989
        $return .= '</span>';
990
        $return .= '<div class="info-box-content">';
991
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref) . '</span>';
992
        if ($selected >= 0) {
993
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
994
        }
995
        if (property_exists($this, 'fk_bank') && is_numeric($this->fk_bank)) {
996
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/bank/class/account.class.php';
997
            $account = new AccountLine($this->db);
998
            $account->fetch($this->fk_bank);
999
            $return .= ' |  <span class="info-box-label">' . $account->getNomUrl(1) . '</span>';
1000
        }
1001
        if (property_exists($this, 'fk_user_author') && is_numeric($this->fk_user_author)) {
1002
            $userstatic = new User($this->db);
1003
            $userstatic->fetch($this->fk_user_author);
1004
            $return .= '<br><span class="info-box-status">' . $userstatic->getNomUrl(1) . '</span>';
1005
        }
1006
1007
        if (property_exists($this, 'fk_typepayment')) {
1008
            $return .= '<br><span class="opacitymedium">' . $langs->trans("PaymentMode") . '</span> : <span class="info-box-label">' . $this->fk_typepayment . '</span>';
1009
        }
1010
        if (property_exists($this, 'amount')) {
1011
            $return .= '<br><span class="opacitymedium">' . $langs->trans("Amount") . '</span> : <span class="info-box-label amount">' . price($this->amount) . '</span>';
1012
        }
1013
        $return .= '</div>';
1014
        $return .= '</div>';
1015
        $return .= '</div>';
1016
        return $return;
1017
    }
1018
}
1019