Passed
Push — GENERAL_BUG_REVIEW_240911 ( 776d89...c757bd )
by Rafael
50:33
created

Tva::getNomUrl()   F

Complexity

Conditions 21
Paths 864

Size

Total Lines 58
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 36
nc 864
nop 5
dl 0
loc 58
rs 0.1888
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) 2002-2003  Rodolphe Quiedeville    <[email protected]>
4
 * Copyright (C) 2004-2008  Laurent Destailleur     <[email protected]>
5
 * Copyright (C) 2011-2017  Alexandre Spangaro      <[email protected]>
6
 * Copyright (C) 2018       Philippe Grand          <[email protected]>
7
 * Copyright (C) 2018-2024  Frédéric France         <[email protected]>
8
 * Copyright (C) 2021       Gauthier VERDOL         <[email protected]>
9
 * Copyright (C) 2024		MDW							<[email protected]>
10
 * Copyright (C) 2024       Rafael San José             <[email protected]>
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 3 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24
 */
25
26
namespace Dolibarr\Code\Compta\Classes;
27
28
/**
29
 *      \file       htdocs/compta/tva/class/tva.class.php
30
 *      \ingroup    tax
31
 */
32
33
// Put here all includes required by your class file
34
use Dolibarr\Core\Base\CommonObject;
35
36
37
/**
38
 *  Put here description of your class
39
 */
40
class Tva extends CommonObject
41
{
42
    /**
43
     * @var string ID to identify managed object
44
     */
45
    public $element = 'tva';
46
47
    /**
48
     * @var string Name of table without prefix where object is stored
49
     */
50
    public $table_element = 'tva';
51
52
    /**
53
     * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
54
     */
55
    public $picto = 'payment';
56
57
    /**
58
     * @deprecated
59
     * @see $amount
60
     */
61
    public $total;
62
63
    public $datep;
64
    public $datev;
65
    public $amount;
66
    public $type_payment;
67
68
    /**
69
     * @var string      Payment reference
70
     *                  (Cheque or bank transfer reference. Can be "ABC123")
71
     */
72
    public $num_payment;
73
74
    /**
75
     * @var int     Creation date
76
     */
77
    public $datec;
78
79
    /**
80
     * @var int ID
81
     */
82
    public $fk_type;
83
84
    /**
85
     * @var int
86
     */
87
    public $paye;
88
89
    /**
90
     * @var int
91
     */
92
    public $rappro;
93
94
    /**
95
     * @var string label
96
     */
97
    public $label;
98
99
    /**
100
     * @var int ID
101
     */
102
    public $fk_bank;
103
104
    /**
105
     * @var int accountid
106
     */
107
    public $accountid;
108
109
    /**
110
     * @var int ID
111
     */
112
    public $fk_user_creat;
113
114
    /**
115
     * @var int ID
116
     */
117
    public $fk_user_modif;
118
119
    /**
120
     * @var integer|string paiementtype
121
     */
122
    public $paiementtype;
123
124
125
    const STATUS_UNPAID = 0;
126
    const STATUS_PAID = 1;
127
128
    /**
129
     *  Constructor
130
     *
131
     *  @param      DoliDB      $db      Database handler
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Compta\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
132
     */
133
    public function __construct($db)
134
    {
135
        $this->db = $db;
136
    }
137
138
139
    /**
140
     *  Create in database
141
     *
142
     *  @param      User    $user       User that create
143
     *  @return     int                 Return integer <0 if KO, >0 if OK
144
     */
145
    public function create($user)
146
    {
147
        global $conf, $langs;
148
149
        $error = 0;
150
        $now = dol_now();
151
152
        // Clean parameters
153
        $this->amount = trim($this->amount);
154
        $this->label = trim($this->label);
155
        $this->type_payment = (int) $this->type_payment;
156
        $this->note = trim($this->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

156
        /** @scrutinizer ignore-deprecated */ $this->note = trim($this->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...
157
        $this->fk_account = (int) $this->fk_account;
158
        $this->fk_user_creat = (int) $this->fk_user_creat;
159
        $this->fk_user_modif = (int) $this->fk_user_modif;
160
161
        // Check parameters
162
        // Put here code to add control on parameters values
163
164
        $this->db->begin();
165
166
        // Insert request
167
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "tva(";
168
        $sql .= "entity,";
169
        $sql .= "datec,";
170
        $sql .= "datep,";
171
        $sql .= "datev,";
172
        $sql .= "amount,";
173
        $sql .= "label,";
174
        $sql .= "note,";
175
        $sql .= "fk_account,";
176
        $sql .= "fk_typepayment,";
177
        $sql .= "fk_user_creat,";
178
        $sql .= "fk_user_modif";
179
        $sql .= ") VALUES (";
180
        $sql .= " " . ((int) $conf->entity) . ", ";
181
        $sql .= " '" . $this->db->idate($now) . "',";
182
        $sql .= " '" . $this->db->idate($this->datep) . "',";
183
        $sql .= " '" . $this->db->idate($this->datev) . "',";
184
        $sql .= " '" . $this->db->escape($this->amount) . "',";
185
        $sql .= " '" . $this->db->escape($this->label) . "',";
186
        $sql .= " '" . $this->db->escape($this->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

186
        $sql .= " '" . $this->db->escape(/** @scrutinizer ignore-deprecated */ $this->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...
187
        $sql .= " '" . $this->db->escape($this->fk_account) . "',";
188
        $sql .= " '" . $this->db->escape($this->type_payment) . "',";
189
        $sql .= " " . ($this->fk_user_creat > 0 ? (int) $this->fk_user_creat : (int) $user->id) . ",";
190
        $sql .= " " . ($this->fk_user_modif > 0 ? (int) $this->fk_user_modif : (int) $user->id);
191
        $sql .= ")";
192
193
        dol_syslog(get_class($this) . "::create", LOG_DEBUG);
194
        $resql = $this->db->query($sql);
195
        if ($resql) {
196
            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "tva");
197
198
            // Call trigger
199
            $result = $this->call_trigger('TVA_CREATE', $user);
200
            if ($result < 0) {
201
                $error++;
202
            }
203
            // End call triggers
204
205
            if (!$error) {
206
                $this->db->commit();
207
                return $this->id;
208
            } else {
209
                $this->db->rollback();
210
                return -1;
211
            }
212
        } else {
213
            $this->error = "Error " . $this->db->lasterror();
214
            $this->db->rollback();
215
            return -1;
216
        }
217
    }
218
219
    /**
220
     * Update database
221
     *
222
     * @param   User    $user           User that modify
223
     * @param   int     $notrigger      0=no, 1=yes (no update trigger)
224
     * @return  int                     Return integer <0 if KO, >0 if OK
225
     */
226
    public function update($user, $notrigger = 0)
227
    {
228
        global $conf, $langs;
229
230
        $error = 0;
231
232
        // Clean parameters
233
        $this->amount = trim($this->amount);
234
        $this->label = trim($this->label);
235
        $this->note = trim($this->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

235
        $this->note = trim(/** @scrutinizer ignore-deprecated */ $this->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...
236
        $this->fk_user_creat = (int) $this->fk_user_creat;
237
        $this->fk_user_modif = (int) $this->fk_user_modif;
238
239
        // Check parameters
240
        // Put here code to add control on parameters values
241
242
        $this->db->begin();
243
244
        // Update request
245
        $sql = "UPDATE " . MAIN_DB_PREFIX . "tva SET";
246
        $sql .= " tms='" . $this->db->idate($this->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

246
        $sql .= " tms='" . $this->db->idate(/** @scrutinizer ignore-deprecated */ $this->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...
247
        $sql .= " datep='" . $this->db->idate($this->datep) . "',";
248
        $sql .= " datev='" . $this->db->idate($this->datev) . "',";
249
        $sql .= " amount=" . price2num($this->amount) . ",";
250
        $sql .= " label='" . $this->db->escape($this->label) . "',";
251
        $sql .= " note='" . $this->db->escape($this->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

251
        $sql .= " note='" . $this->db->escape(/** @scrutinizer ignore-deprecated */ $this->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...
252
        $sql .= " fk_user_creat=" . ((int) $this->fk_user_creat) . ",";
253
        $sql .= " fk_user_modif=" . ((int) ($this->fk_user_modif > 0 ? $this->fk_user_modif : $user->id));
254
        $sql .= " WHERE rowid=" . ((int) $this->id);
255
256
        dol_syslog(get_class($this) . "::update", LOG_DEBUG);
257
        $resql = $this->db->query($sql);
258
        if (!$resql) {
259
            $this->error = "Error " . $this->db->lasterror();
260
            $error++;
261
        }
262
263
        if (!$error && !$notrigger) {
264
            // Call trigger
265
            $result = $this->call_trigger('TVA_MODIFY', $user);
266
            if ($result < 0) {
267
                $error++;
268
            }
269
            // End call triggers
270
        }
271
272
        if (!$error) {
273
            $this->db->commit();
274
            return 1;
275
        } else {
276
            $this->db->rollback();
277
            return -1;
278
        }
279
    }
280
281
    /**
282
     *    Tag TVA as paid completely
283
     *
284
     *    @param    User    $user       Object user making change
285
     *    @return   int                 Return integer <0 if KO, >0 if OK
286
     */
287
    public function setPaid($user)
288
    {
289
        // phpcs:enable
290
        $sql = "UPDATE " . MAIN_DB_PREFIX . "tva SET";
291
        $sql .= " paye = 1";
292
        $sql .= " WHERE rowid = " . ((int) $this->id);
293
        $resql = $this->db->query($sql);
294
        if ($resql) {
295
            return 1;
296
        } else {
297
            return -1;
298
        }
299
    }
300
301
    /**
302
     *    Remove tag paid on TVA
303
     *
304
     *    @param    User    $user       Object user making change
305
     *    @return   int                 Return integer <0 if KO, >0 if OK
306
     */
307
    public function setUnpaid($user)
308
    {
309
        // phpcs:enable
310
        $sql = "UPDATE " . MAIN_DB_PREFIX . "tva SET";
311
        $sql .= " paye = 0";
312
        $sql .= " WHERE rowid = " . ((int) $this->id);
313
        $resql = $this->db->query($sql);
314
        if ($resql) {
315
            return 1;
316
        } else {
317
            return -1;
318
        }
319
    }
320
321
322
    /**
323
     *  Load object in memory from database
324
     *
325
     *  @param  int     $id         id object
326
     *  @param  string  $ref        Ref of VAT (not used yet)
327
     *  @return int                 Return integer <0 if KO, >0 if OK
328
     */
329
    public function fetch($id, $ref = '')
330
    {
331
        $sql = "SELECT";
332
        $sql .= " t.rowid,";
333
        $sql .= " t.tms,";
334
        $sql .= " t.datep,";
335
        $sql .= " t.datev,";
336
        $sql .= " t.amount,";
337
        $sql .= " t.fk_typepayment,";
338
        $sql .= " t.num_payment,";
339
        $sql .= " t.label,";
340
        $sql .= " t.note,";
341
        $sql .= " t.paye,";
342
        $sql .= " t.fk_user_creat,";
343
        $sql .= " t.fk_user_modif,";
344
        $sql .= " t.fk_account";
345
        $sql .= " FROM " . MAIN_DB_PREFIX . "tva as t";
346
        $sql .= " WHERE t.rowid = " . ((int) $id);
347
348
        dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
349
350
        $resql = $this->db->query($sql);
351
        if ($resql) {
352
            if ($this->db->num_rows($resql)) {
353
                $obj = $this->db->fetch_object($resql);
354
355
                $this->id    = $obj->rowid;
356
                $this->ref   = $obj->rowid;
357
                $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

357
                /** @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...
Documentation Bug introduced by
It seems like $this->db->jdate($obj->tms) can also be of type string. However, the property $tms 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...
358
                $this->datep = $this->db->jdate($obj->datep);
359
                $this->datev = $this->db->jdate($obj->datev);
360
                $this->amount = $obj->amount;
361
                $this->type_payment = $obj->fk_typepayment;
362
                $this->num_payment = $obj->num_payment;
363
                $this->label = $obj->label;
364
                $this->paye  = $obj->paye;
365
                $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

365
                /** @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...
366
                $this->fk_user_creat = $obj->fk_user_creat;
367
                $this->fk_user_modif = $obj->fk_user_modif;
368
                $this->fk_account = $obj->fk_account;
369
                $this->fk_type = empty($obj->fk_type) ? "" : $obj->fk_type;
0 ignored issues
show
Documentation Bug introduced by
It seems like empty($obj->fk_type) ? '' : $obj->fk_type can also be of type string. However, the property $fk_type 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...
370
                $this->rappro  = empty($obj->rappro) ? "" : $obj->rappro;
0 ignored issues
show
Documentation Bug introduced by
It seems like empty($obj->rappro) ? '' : $obj->rappro can also be of type string. However, the property $rappro 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...
371
            }
372
            $this->db->free($resql);
373
374
            return 1;
375
        } else {
376
            $this->error = "Error " . $this->db->lasterror();
377
            return -1;
378
        }
379
    }
380
381
382
    /**
383
     *  Delete object in database
384
     *
385
     *  @param  User    $user       User that delete
386
     *  @return int                 Return integer <0 if KO, >0 if OK
387
     */
388
    public function delete($user)
389
    {
390
        global $conf, $langs;
391
392
        $error = 0;
393
394
        // Call trigger
395
        $result = $this->call_trigger('TVA_DELETE', $user);
396
        if ($result < 0) {
397
            return -1;
398
        }
399
        // End call triggers
400
401
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "tva";
402
        $sql .= " WHERE rowid=" . ((int) $this->id);
403
404
        dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
405
        $resql = $this->db->query($sql);
406
        if (!$resql) {
407
            $this->error = "Error " . $this->db->lasterror();
408
            return -1;
409
        }
410
411
412
        return 1;
413
    }
414
415
416
    /**
417
     *  Initialise an instance with random values.
418
     *  Used to build previews or test instances.
419
     *  id must be 0 if object instance is a specimen.
420
     *
421
     *  @return int
422
     */
423
    public function initAsSpecimen()
424
    {
425
        $this->id = 0;
426
427
        $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

427
        /** @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...
428
        $this->datep = '';
429
        $this->datev = '';
430
        $this->amount = '';
431
        $this->label = '';
432
        $this->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

432
        /** @scrutinizer ignore-deprecated */ $this->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...
433
        $this->fk_bank = 0;
434
        $this->fk_user_creat = 0;
435
        $this->fk_user_modif = 0;
436
437
        return 1;
438
    }
439
440
441
    /**
442
     *  Balance of VAT
443
     *
444
     *  @param  int     $year       Year
445
     *  @return double              Amount
446
     */
447
    public function solde($year = 0)
448
    {
449
        $reglee = $this->tva_sum_reglee($year);
450
451
        $payee = $this->tva_sum_payee($year);
452
        $collectee = $this->tva_sum_collectee($year);
453
454
        $solde = $reglee - ($collectee - $payee);
455
456
        return $solde;
457
    }
458
459
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
460
    /**
461
     *  Total of the VAT from invoices emitted by the thirdparty.
462
     *
463
     *  @param  int     $year       Year
464
     *  @return double              Amount
465
     */
466
    public function tva_sum_collectee($year = 0)
467
    {
468
		// phpcs:enable
469
470
        $sql = "SELECT sum(f.total_tva) as amount";
471
        $sql .= " FROM " . MAIN_DB_PREFIX . "facture as f WHERE f.paye = 1";
472
        if ($year) {
473
            $sql .= " AND f.datef >= '" . $this->db->escape($year) . "-01-01' AND f.datef <= '" . $this->db->escape($year) . "-12-31' ";
474
        }
475
476
        $result = $this->db->query($sql);
477
        if ($result) {
478
            if ($this->db->num_rows($result)) {
479
                $obj = $this->db->fetch_object($result);
480
                $ret = $obj->amount;
481
                $this->db->free($result);
482
                return $ret;
483
            } else {
484
                $this->db->free($result);
485
                return 0;
486
            }
487
        } else {
488
            print $this->db->lasterror();
489
            return -1;
490
        }
491
    }
492
493
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
494
    /**
495
     *  VAT paid
496
     *
497
     *  @param  int     $year       Year
498
     *  @return double              Amount
499
     */
500
    public function tva_sum_payee($year = 0)
501
    {
502
		// phpcs:enable
503
504
        $sql = "SELECT sum(f.total_tva) as total_tva";
505
        $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn as f";
506
        if ($year) {
507
            $sql .= " WHERE f.datef >= '" . $this->db->escape($year) . "-01-01' AND f.datef <= '" . $this->db->escape($year) . "-12-31' ";
508
        }
509
510
        $result = $this->db->query($sql);
511
        if ($result) {
512
            if ($this->db->num_rows($result)) {
513
                $obj = $this->db->fetch_object($result);
514
                $ret = $obj->total_tva;
515
                $this->db->free($result);
516
                return $ret;
517
            } else {
518
                $this->db->free($result);
519
                return 0;
520
            }
521
        } else {
522
            print $this->db->lasterror();
523
            return -1;
524
        }
525
    }
526
527
528
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
529
    /**
530
     *  Total of the VAT paid
531
     *
532
     *  @param  int     $year       Year
533
     *  @return double              Amount
534
     */
535
    public function tva_sum_reglee($year = 0)
536
    {
537
		// phpcs:enable
538
539
        $sql = "SELECT sum(f.amount) as amount";
540
        $sql .= " FROM " . MAIN_DB_PREFIX . "tva as f";
541
542
        if ($year) {
543
            $sql .= " WHERE f.datev >= '" . $this->db->escape($year) . "-01-01' AND f.datev <= '" . $this->db->escape($year) . "-12-31' ";
544
        }
545
546
        $result = $this->db->query($sql);
547
        if ($result) {
548
            if ($this->db->num_rows($result)) {
549
                $obj = $this->db->fetch_object($result);
550
                $ret = $obj->amount;
551
                $this->db->free($result);
552
                return $ret;
553
            } else {
554
                $this->db->free($result);
555
                return 0;
556
            }
557
        } else {
558
            print $this->db->lasterror();
559
            return -1;
560
        }
561
    }
562
563
564
    /**
565
     *  Create in database
566
     *
567
     *  @param  User    $user       Object user that insert
568
     *  @return int                 Return integer <0 if KO, rowid in tva table if OK
569
     */
570
    public function addPayment($user)
571
    {
572
        global $conf, $langs;
573
574
        $this->db->begin();
575
576
        // Clean parameters
577
        $this->amount = price2num(trim($this->amount));
578
        $this->label = trim($this->label);
579
        $this->note = trim($this->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

579
        $this->note = trim(/** @scrutinizer ignore-deprecated */ $this->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...
580
        $this->num_payment = trim($this->num_payment);
581
        $this->fk_bank = (int) $this->fk_bank;
582
        $this->fk_user_creat = (int) $this->fk_user_creat;
583
        $this->fk_user_modif = (int) $this->fk_user_modif;
584
        if (empty($this->datec)) {
585
            $this->datec = dol_now();
586
        }
587
588
        // Check parameters
589
        if (!$this->label) {
590
            $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label"));
591
            return -3;
592
        }
593
        if ($this->amount == '') {
594
            $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount"));
595
            return -4;
596
        }
597
        if (isModEnabled("bank") && (empty($this->accountid) || $this->accountid <= 0)) {
598
            $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("BankAccount"));
599
            return -5;
600
        }
601
        if (isModEnabled("bank") && (empty($this->type_payment) || $this->type_payment <= 0)) {
602
            $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode"));
603
            return -5;
604
        }
605
606
        // Insert into llx_tva
607
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "tva (";
608
        $sql .= "datec";
609
        $sql .= ", datep";
610
        $sql .= ", datev";
611
        $sql .= ", amount";
612
        $sql .= ", fk_typepayment";
613
        $sql .= ", num_payment";
614
        if ($this->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

614
        if (/** @scrutinizer ignore-deprecated */ $this->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...
615
            $sql .= ", note";
616
        }
617
        if ($this->label) {
618
            $sql .= ", label";
619
        }
620
        $sql .= ", fk_user_creat";
621
        $sql .= ", fk_bank";
622
        $sql .= ", entity";
623
        $sql .= ") ";
624
        $sql .= " VALUES (";
625
        $sql .= " '" . $this->db->idate($this->datec) . "'";
626
        $sql .= ", '" . $this->db->idate($this->datep) . "'";
627
        $sql .= ", '" . $this->db->idate($this->datev) . "'";
628
        $sql .= ", " . ((float) $this->amount);
629
        $sql .= ", '" . $this->db->escape($this->type_payment) . "'";
630
        $sql .= ", '" . $this->db->escape($this->num_payment) . "'";
631
        if ($this->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

631
        if (/** @scrutinizer ignore-deprecated */ $this->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...
632
            $sql .= ", '" . $this->db->escape($this->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

632
            $sql .= ", '" . $this->db->escape(/** @scrutinizer ignore-deprecated */ $this->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...
633
        }
634
        if ($this->label) {
635
            $sql .= ", '" . $this->db->escape($this->label) . "'";
636
        }
637
        $sql .= ", '" . $this->db->escape($user->id) . "'";
638
        $sql .= ", NULL";
639
        $sql .= ", " . ((int) $conf->entity);
640
        $sql .= ")";
641
642
        dol_syslog(get_class($this) . "::addPayment", LOG_DEBUG);
643
        $result = $this->db->query($sql);
644
        if ($result) {
645
            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "tva"); // TODO should be called 'payment_vat'
646
647
            // Call trigger
648
            //XXX: Should be done just before commit no ?
649
            $result = $this->call_trigger('TVA_ADDPAYMENT', $user);
650
            if ($result < 0) {
651
                $this->id = 0;
652
                $ok = 0;
653
            }
654
            // End call triggers
655
656
            if ($this->id > 0) {
657
                $ok = 1;
658
                if (isModEnabled("bank") && !empty($this->amount)) {
659
                    // Insert into llx_bank
660
661
                    $acc = new Account($this->db);
662
                    $result = $acc->fetch($this->accountid);
663
                    if ($result <= 0) {
664
                        dol_print_error($this->db);
665
                    }
666
667
                    if ($this->amount > 0) {
668
                        $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, -abs((float) $this->amount), $this->num_payment, '', $user);
669
                    } else {
670
                        $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, abs((float) $this->amount), $this->num_payment, '', $user);
671
                    }
672
673
                    // Update fk_bank into llx_tva. So we know vat line used to generate bank transaction
674
                    if ($bank_line_id > 0) {
675
                        $this->update_fk_bank($bank_line_id);
676
                    } else {
677
                        $this->error = $acc->error;
678
                        $ok = 0;
679
                    }
680
681
                    // Update links
682
                    $result = $acc->add_url_line($bank_line_id, $this->id, constant('BASE_URL') . '/compta/tva/card.php?id=', "(VATPayment)", "payment_vat");
683
                    if ($result < 0) {
684
                        $this->error = $acc->error;
685
                        $ok = 0;
686
                    }
687
                }
688
689
                if ($ok) {
690
                    $this->db->commit();
691
                    return $this->id;
692
                } else {
693
                    $this->db->rollback();
694
                    return -3;
695
                }
696
            } else {
697
                $this->db->rollback();
698
                return -2;
699
            }
700
        } else {
701
            $this->error = $this->db->error();
702
            $this->db->rollback();
703
            return -1;
704
        }
705
    }
706
707
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
708
    /**
709
     *  Update link between payment tva and line generate into llx_bank
710
     *
711
     *  @param  int     $id_bank    Id bank account
712
     *  @return int                 Return integer <0 if KO, >0 if OK
713
     */
714
    public function update_fk_bank($id_bank)
715
    {
716
		// phpcs:enable
717
        $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'tva SET fk_bank = ' . (int) $id_bank;
718
        $sql .= ' WHERE rowid = ' . (int) $this->id;
719
        $result = $this->db->query($sql);
720
        if ($result) {
721
            return 1;
722
        } else {
723
            dol_print_error($this->db);
724
            return -1;
725
        }
726
    }
727
728
    /**
729
     *  Send name clicable (with possibly the picto)
730
     *
731
     *  @param  int     $withpicto      0=No picto, 1=Include picto into link, 2=Only picto
732
     *  @param  string  $option         link option
733
     *  @param  int     $notooltip      1=Disable tooltip
734
     *  @param  string  $morecss        More CSS
735
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
736
     *  @return string                  Chaine with URL
737
     */
738
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
739
    {
740
        global $langs, $conf;
741
742
        if (!empty($conf->dol_no_mouse_hover)) {
743
            $notooltip = 1; // Force disable tooltips
744
        }
745
746
        $result = '';
747
748
        $label = '<u>' . $langs->trans("ShowVatPayment") . '</u>';
749
        $label .= '<br>';
750
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
751
        if (!empty($this->label)) {
752
            $label .= '<br><b>' . $langs->trans('Label') . ':</b> ' . $this->label;
753
        }
754
755
        $url = constant('BASE_URL') . '/compta/tva/card.php?id=' . $this->id;
756
757
        if ($option != 'nolink') {
758
            // Add param to save lastsearch_values or not
759
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
760
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
761
                $add_save_lastsearch_values = 1;
762
            }
763
            if ($add_save_lastsearch_values) {
764
                $url .= '&save_lastsearch_values=1';
765
            }
766
        }
767
768
        $linkclose = '';
769
        if (empty($notooltip)) {
770
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
771
                $label = $langs->trans("ShowMyObject");
772
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
773
            }
774
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
775
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
776
        } else {
777
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
778
        }
779
780
        $linkstart = '<a href="' . $url . '"';
781
        $linkstart .= $linkclose . '>';
782
        $linkend = '</a>';
783
784
        $picto = 'payment';
785
786
        $result .= $linkstart;
787
        if ($withpicto) {
788
            $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
789
        }
790
        if ($withpicto != 2) {
791
            $result .= $this->ref;
792
        }
793
        $result .= $linkend;
794
795
        return $result;
796
    }
797
798
    /**
799
     *  Return amount of payments already done
800
     *
801
     *  @return     int     Amount of payment already done, <0 if KO
802
     */
803
    public function getSommePaiement()
804
    {
805
        $table = 'payment_vat';
806
        $field = 'fk_tva';
807
808
        $sql = 'SELECT sum(amount) as amount';
809
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $table;
810
        $sql .= " WHERE " . $field . " = " . ((int) $this->id);
811
812
        dol_syslog(get_class($this) . "::getSommePaiement", LOG_DEBUG);
813
        $resql = $this->db->query($sql);
814
        if ($resql) {
815
            $amount = 0;
816
817
            $obj = $this->db->fetch_object($resql);
818
            if ($obj) {
819
                $amount = $obj->amount ? $obj->amount : 0;
820
            }
821
822
            $this->db->free($resql);
823
            return $amount;
824
        } else {
825
            return -1;
826
        }
827
    }
828
829
    /**
830
     *  Information of vat payment object
831
     *
832
     *  @param  int     $id     Id of vat payment
833
     *  @return void
834
     */
835
    public function info($id)
836
    {
837
        $sql = "SELECT t.rowid, t.tms, t.fk_user_modif, t.datec, t.fk_user_creat";
838
        $sql .= " FROM " . MAIN_DB_PREFIX . "tva as t";
839
        $sql .= " WHERE t.rowid = " . (int) $id;
840
841
        dol_syslog(get_class($this) . "::info", LOG_DEBUG);
842
        $result = $this->db->query($sql);
843
        if ($result) {
844
            if ($this->db->num_rows($result)) {
845
                $obj = $this->db->fetch_object($result);
846
847
                $this->id = $obj->rowid;
848
849
                $this->user_creation_id = $obj->fk_user_creat;
850
                $this->user_modification_id = $obj->fk_user_modif;
851
                $this->date_creation     = $this->db->jdate($obj->datec);
852
                $this->date_modification = $this->db->jdate($obj->tms);
853
            }
854
855
            $this->db->free($result);
856
        } else {
857
            dol_print_error($this->db);
858
        }
859
    }
860
861
    /**
862
     *  Return the label of the VAT status f object
863
     *
864
     *  @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
865
     *  @param  double  $alreadypaid    0=No payment already done, >0=Some payments were already done (we recommend to put here amount paid if you have it, 1 otherwise)
866
     *  @return string                  Label
867
     */
868
    public function getLibStatut($mode = 0, $alreadypaid = -1)
869
    {
870
        return $this->LibStatut($this->paye, $mode, $alreadypaid);
871
    }
872
873
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
874
    /**
875
     *  Return the label of a given VAT status
876
     *
877
     *  @param  int     $status         Id status
878
     *  @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
879
     *  @param  double  $alreadypaid    0=No payment already done, >0=Some payments were already done (we recommend to put here amount paid if you have it, 1 otherwise)
880
     *  @return string                  Label
881
     */
882
    public function LibStatut($status, $mode = 0, $alreadypaid = -1)
883
    {
884
		// phpcs:enable
885
        global $langs;
886
887
        // Load translation files required by the page
888
        $langs->loadLangs(array("customers", "bills"));
889
890
        // We reinit status array to force to redefine them because label may change according to properties values.
891
        $this->labelStatus = array();
892
        $this->labelStatusShort = array();
893
894
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
895
            global $langs;
896
            //$langs->load("mymodule");
897
            $this->labelStatus[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv('BillStatusNotPaid');
898
            $this->labelStatus[self::STATUS_PAID] = $langs->transnoentitiesnoconv('BillStatusPaid');
899
            if ($status == self::STATUS_UNPAID && $alreadypaid != 0) {
900
                $this->labelStatus[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv("BillStatusStarted");
901
            }
902
            $this->labelStatusShort[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv('BillStatusNotPaid');
903
            $this->labelStatusShort[self::STATUS_PAID] = $langs->transnoentitiesnoconv('BillStatusPaid');
904
            if ($status == self::STATUS_UNPAID && $alreadypaid != 0) {
905
                $this->labelStatusShort[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv("BillStatusStarted");
906
            }
907
        }
908
909
        $statusType = 'status1';
910
        if ($status == 0 && $alreadypaid != 0) {
911
            $statusType = 'status3';
912
        }
913
        if ($status == 1) {
914
            $statusType = 'status6';
915
        }
916
917
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
918
    }
919
920
    /**
921
     *  Return clicable link of object (with eventually picto)
922
     *
923
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
924
     *  @param      array       $arraydata              Array of data
925
     *  @return     string                              HTML Code for Kanban thumb.
926
     */
927
    public function getKanbanView($option = '', $arraydata = null)
928
    {
929
        global $langs;
930
931
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
932
933
        $return = '<div class="box-flex-item box-flex-grow-zero">';
934
        $return .= '<div class="info-box info-box-sm">';
935
        $return .= '<span class="info-box-icon bg-infobox-action">';
936
        $return .= img_picto('', $this->picto);
937
        //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
938
        $return .= '</span>';
939
        $return .= '<div class="info-box-content">';
940
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref) . '</span>';
941
        if ($selected >= 0) {
942
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
943
        }
944
        if (property_exists($this, 'amount')) {
945
            $return .= ' | <span class="opacitymedium">' . $langs->trans("Amount") . '</span> : <span class="info-box-label amount">' . price($this->amount) . '</span>';
946
        }
947
        if (property_exists($this, 'type_payment')) {
948
            $return .= '<br><span class="opacitymedium">' . $langs->trans("Payement") . '</span> : <span class="info-box-label">' . $this->type_payment . '</span>';
949
        }
950
        if (property_exists($this, 'datev')) {
951
            $return .= '<br><span class="opacitymedium">' . $langs->trans("DateEnd") . '</span> : <span class="info-box-label" >' . dol_print_date($this->datev) . '</span>';
952
        }
953
        if (method_exists($this, 'LibStatut')) {
954
            $return .= '<br><div class="info-box-status margintoponly">' . $this->getLibStatut(3, $this->alreadypaid) . '</div>';
0 ignored issues
show
Bug Best Practice introduced by
The property $alreadypaid is declared private in Dolibarr\Core\Base\CommonObject. Since you implement __get, consider adding a @property or @property-read.
Loading history...
955
        }
956
        $return .= '</div>';
957
        $return .= '</div>';
958
        $return .= '</div>';
959
        return $return;
960
    }
961
}
962