Passed
Pull Request — dev (#6)
by Rafael
79:24 queued 24:08
created

Don::create()   F

Complexity

Conditions 21
Paths > 20000

Size

Total Lines 109
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 78
nc 24577
nop 2
dl 0
loc 109
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* Copyright (C) 2002       Rodolphe Quiedeville        <[email protected]>
4
 * Copyright (C) 2004-2008  Laurent Destailleur         <[email protected]>
5
 * Copyright (C) 2009       Regis Houssin               <[email protected]>
6
 * Copyright (C) 2014       Florian Henry               <[email protected]>
7
 * Copyright (C) 2015-2017  Alexandre Spangaro          <[email protected]>
8
 * Copyright (C) 2016       Juanjo Menent               <[email protected]>
9
 * Copyright (C) 2019       Thibault FOUCART            <[email protected]>
10
 * Copyright (C) 2019-2024  Frédéric France             <[email protected]>
11
 * Copyright (C) 2021       Maxime DEMAREST             <[email protected]>
12
 * Copyright (C) 2024		MDW							<[email protected]>
13
 * Copyright (C) 2024       Rafael San José             <[email protected]>
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 3 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27
 */
28
29
namespace Dolibarr\Code\Don\Classes;
30
31
use Dolibarr\Code\Core\Traits\CommonPeople;
32
use Dolibarr\Core\Base\CommonObject;
33
use DoliDB;
34
35
/**
36
 *      \file       htdocs/don/class/don.class.php
37
 *      \ingroup    Donation
38
 *      \brief      File of class to manage donations
39
 */
40
41
42
43
/**
44
 *      Class to manage donations
45
 */
46
class Don extends CommonObject
47
{
48
    use CommonPeople;
0 ignored issues
show
introduced by
The trait Dolibarr\Code\Core\Traits\CommonPeople requires some properties which are not provided by Dolibarr\Code\Don\Classes\Don: $phone_pro, $MAIN_SHOW_REGION_IN_STATE_SELECT, $phone_perso, $user_mobile, $office_phone, $attributes, $company, $global, $nom, $fax, $socialnetworks, $civility_code, $use_javascript_ajax, $office_fax
Loading history...
49
50
    /**
51
     * @var string ID to identify managed object
52
     */
53
    public $element = 'don';
54
55
    /**
56
     * @var string Name of table without prefix where object is stored
57
     */
58
    public $table_element = 'don';
59
60
    /**
61
     * @var string Field with ID of parent key if this field has a parent
62
     */
63
    public $fk_element = 'fk_donation';
64
65
    /**
66
     * @var string String with name of icon for object don. Must be the part after the 'object_' into object_myobject.png
67
     */
68
    public $picto = 'donation';
69
70
    /**
71
     * @var int|string Date of the donation
72
     */
73
    public $date;
74
75
    public $datec;
76
    public $datem;
77
78
    /**
79
     * amount of donation
80
     * @var double
81
     */
82
    public $amount;
83
84
    /**
85
     * @var integer Thirdparty ID
86
     */
87
    public $socid;
88
89
    /**
90
     * @var string Thirdparty name
91
     */
92
    public $societe;
93
94
    /**
95
     * @var string Address
96
     */
97
    public $address;
98
99
    /**
100
     * @var string Zipcode
101
     */
102
    public $zip;
103
104
    /**
105
     * @var string Town
106
     */
107
    public $town;
108
109
    /**
110
     * @var string Email
111
     */
112
    public $email;
113
114
    public $phone;
115
    public $phone_mobile;
116
117
118
    /**
119
     * @var string
120
     */
121
    public $mode_reglement;
122
123
    /**
124
     * @var string
125
     */
126
    public $mode_reglement_code;
127
128
    /**
129
     * @var int 0 or 1
130
     */
131
    public $public;
132
133
    /**
134
     * @var int project ID
135
     */
136
    public $fk_project;
137
138
    /**
139
     * @var int type payment ID
140
     */
141
    public $fk_typepayment;
142
143
    /**
144
     * @var string      Payment reference
145
     *                  (Cheque or bank transfer reference. Can be "ABC123")
146
     */
147
    public $num_payment;
148
    public $date_valid;
149
150
    /**
151
     * @var int payment mode id
152
     */
153
    public $modepaymentid = 0;
154
155
    public $paid;
156
157
    const STATUS_DRAFT = 0;
158
    const STATUS_VALIDATED = 1;
159
    const STATUS_PAID = 2;
160
    const STATUS_CANCELED = -1;
161
162
163
    /**
164
     *  Constructor
165
     *
166
     *  @param  DoliDB  $db     Database handler
167
     */
168
    public function __construct($db)
169
    {
170
        $this->db = $db;
171
172
        $this->ismultientitymanaged = 1;
173
    }
174
175
176
    /**
177
     *  Returns the donation status label (draft, valid, abandoned, paid)
178
     *
179
     *  @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
180
     *  @return string                  Label of status
181
     */
182
    public function getLibStatut($mode = 0)
183
    {
184
        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

184
        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...
185
    }
186
187
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
188
    /**
189
     *  Return the label of a given status
190
     *
191
     *  @param  int     $status        Id statut
192
     *  @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
193
     *  @return string                 Label of status
194
     */
195
    public function LibStatut($status, $mode = 0)
196
    {
197
		// phpcs:enable
198
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
199
            global $langs;
200
            $langs->load("donations");
201
            $this->labelStatus[-1] = $langs->transnoentitiesnoconv("Canceled");
202
            $this->labelStatus[0] = $langs->transnoentitiesnoconv("DonationStatusPromiseNotValidated");
203
            $this->labelStatus[1] = $langs->transnoentitiesnoconv("DonationStatusPromiseValidated");
204
            $this->labelStatus[2] = $langs->transnoentitiesnoconv("DonationStatusPaid");
205
            $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv("Canceled");
206
            $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("DonationStatusPromiseNotValidatedShort");
207
            $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("DonationStatusPromiseValidatedShort");
208
            $this->labelStatusShort[2] = $langs->transnoentitiesnoconv("DonationStatusPaidShort");
209
        }
210
211
        $statusType = 'status' . $status;
212
        if ($status == self::STATUS_CANCELED) {
213
            $statusType = 'status9';
214
        }
215
        if ($status == self::STATUS_PAID) {
216
            $statusType = 'status6';
217
        }
218
219
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
220
    }
221
222
223
    /**
224
     *  Initialise an instance with random values.
225
     *  Used to build previews or test instances.
226
     *  id must be 0 if object instance is a specimen.
227
     *
228
     *  @return int
229
     */
230
    public function initAsSpecimen()
231
    {
232
        global $conf;
233
234
        $now = dol_now();
235
236
        // Charge tableau des id de societe socids
237
        $socids = array();
238
239
        $sql = "SELECT rowid";
240
        $sql .= " FROM " . MAIN_DB_PREFIX . "societe";
241
        $sql .= " WHERE client IN (1, 3)";
242
        $sql .= " AND entity = " . $conf->entity;
243
        $sql .= " LIMIT 10";
244
245
        $resql = $this->db->query($sql);
246
        if ($resql) {
247
            $num_socs = $this->db->num_rows($resql);
248
            $i = 0;
249
            while ($i < $num_socs) {
250
                $row = $this->db->fetch_row($resql);
251
                $socids[$i] = $row[0];
252
253
                $i++;
254
            }
255
        }
256
257
        // Initialise parameters
258
        $this->id = 0;
259
        $this->ref = 'SPECIMEN';
260
        $this->specimen = 1;
261
        $this->lastname = 'Doe';
262
        $this->firstname = 'John';
263
        $this->socid = empty($socids[0]) ? 0 : $socids[0];
264
        $this->date = $now;
265
        $this->date_valid = $now;
266
        $this->amount = 100.90;
267
        $this->public = 1;
268
        $this->societe = 'The Company';
269
        $this->address = 'Twist road';
270
        $this->zip = '99999';
271
        $this->town = 'Town';
272
        $this->note_private = 'Private note';
273
        $this->note_public = 'Public note';
274
        $this->email = '[email protected]';
275
        $this->phone = '0123456789';
276
        $this->phone_mobile = '0606060606';
277
        $this->status = 1;
278
279
        return 1;
280
    }
281
282
283
    /**
284
     *  Check params and init ->errors array.
285
     *  TODO This function seems to not be used by core code.
286
     *
287
     *  @param  int $minimum    Minimum
288
     *  @return int             0 if KO, >0 if OK
289
     */
290
    public function check($minimum = 0)
291
    {
292
        global $langs;
293
        $langs->load('main');
294
        $langs->load('companies');
295
296
        $error_string = array();
297
        $err = 0;
298
        $amount_invalid = 0;
299
300
        if (dol_strlen(trim($this->societe)) == 0) {
301
            if ((dol_strlen(trim($this->lastname)) + dol_strlen(trim($this->firstname))) == 0) {
302
                $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Company') . '/' . $langs->transnoentitiesnoconv('Firstname') . '-' . $langs->transnoentitiesnoconv('Lastname'));
303
                $err++;
304
            }
305
        }
306
307
        if (dol_strlen(trim($this->address)) == 0) {
308
            $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Address'));
309
            $err++;
310
        }
311
312
        if (dol_strlen(trim($this->zip)) == 0) {
313
            $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Zip'));
314
            $err++;
315
        }
316
317
        if (dol_strlen(trim($this->town)) == 0) {
318
            $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Town'));
319
            $err++;
320
        }
321
322
        if (dol_strlen(trim($this->email)) == 0) {
323
            $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMail'));
324
            $err++;
325
        }
326
327
        $this->amount = (float) $this->amount;
328
329
        $map = range(0, 9);
330
        $len = dol_strlen((string) $this->amount);
331
        for ($i = 0; $i < $len; $i++) {
332
            if (!isset($map[substr((string) $this->amount, $i, 1)])) {
333
                $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount'));
334
                $err++;
335
                $amount_invalid = 1;
336
                break;
337
            }
338
        }
339
340
        if (!$amount_invalid) {
341
            if ($this->amount == 0) {
342
                $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount'));
343
                $err++;
344
            } else {
345
                if ($this->amount < $minimum && $minimum > 0) {
346
                    $error_string[] = $langs->trans('MinimumAmount', $minimum);
347
                    $err++;
348
                }
349
            }
350
        }
351
352
        if ($err) {
353
            $this->errors = $error_string;
354
            return 0;
355
        } else {
356
            return 1;
357
        }
358
    }
359
360
    /**
361
     * Create donation record into database
362
     *
363
     * @param   User    $user       User who created the donation
364
     * @param   int     $notrigger  Disable triggers
365
     * @return  int                 Return integer <0 if KO, id of created donation if OK
366
     * TODO    add numbering module for Ref
367
     */
368
    public function create($user, $notrigger = 0)
369
    {
370
        global $conf, $langs;
371
372
        $error = 0;
373
        $ret = 0;
374
        $now = dol_now();
375
376
        // Clean parameters
377
        // $this->address = ($this->address > 0 ? $this->address : $this->address);
378
        // $this->zip = ($this->zip > 0 ? $this->zip : $this->zip);
379
        // $this->town = ($this->town > 0 ? $this->town : $this->town);
380
        // $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
381
        // $this->country = ($this->country ? $this->country : $this->country);
382
        $this->amount = (float) price2num($this->amount);
383
384
        // Check parameters
385
        if ($this->amount < 0) {
386
            $this->error = $langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv("Amount"));
387
            return -1;
388
        }
389
390
        $this->db->begin();
391
392
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "don (";
393
        $sql .= "datec";
394
        $sql .= ", entity";
395
        $sql .= ", amount";
396
        $sql .= ", fk_payment";
397
        $sql .= ", fk_soc";
398
        $sql .= ", firstname";
399
        $sql .= ", lastname";
400
        $sql .= ", societe";
401
        $sql .= ", address";
402
        $sql .= ", zip";
403
        $sql .= ", town";
404
        $sql .= ", fk_country";
405
        $sql .= ", public";
406
        $sql .= ", fk_projet";
407
        $sql .= ", note_private";
408
        $sql .= ", note_public";
409
        $sql .= ", fk_user_author";
410
        $sql .= ", fk_user_valid";
411
        $sql .= ", datedon";
412
        $sql .= ", email";
413
        $sql .= ", phone";
414
        $sql .= ", phone_mobile";
415
        $sql .= ") VALUES (";
416
        $sql .= "'" . $this->db->idate($this->date ? $this->date : $now) . "'";
417
        $sql .= ", " . ((int) $conf->entity);
418
        $sql .= ", " . ((float) $this->amount);
419
        $sql .= ", " . ($this->modepaymentid ? $this->modepaymentid : "null");
420
        $sql .= ", " . ($this->socid > 0 ? $this->socid : "null");
421
        $sql .= ", '" . $this->db->escape($this->firstname) . "'";
422
        $sql .= ", '" . $this->db->escape($this->lastname) . "'";
423
        $sql .= ", '" . $this->db->escape($this->societe) . "'";
424
        $sql .= ", '" . $this->db->escape($this->address) . "'";
425
        $sql .= ", '" . $this->db->escape($this->zip) . "'";
426
        $sql .= ", '" . $this->db->escape($this->town) . "'";
427
        $sql .= ", " . (int) ($this->country_id > 0 ? $this->country_id : 0);
428
        $sql .= ", " . (int) $this->public;
429
        $sql .= ", " . ($this->fk_project > 0 ? (int) $this->fk_project : "null");
430
        $sql .= ", " . (!empty($this->note_private) ? ("'" . $this->db->escape($this->note_private) . "'") : "NULL");
431
        $sql .= ", " . (!empty($this->note_public) ? ("'" . $this->db->escape($this->note_public) . "'") : "NULL");
432
        $sql .= ", " . ((int) $user->id);
433
        $sql .= ", null";
434
        $sql .= ", '" . $this->db->idate($this->date) . "'";
435
        $sql .= ", '" . (!empty($this->email) ? $this->db->escape(trim($this->email)) : "") . "'";
436
        $sql .= ", '" . (!empty($this->phone) ? $this->db->escape(trim($this->phone)) : "") . "'";
437
        $sql .= ", '" . (!empty($this->phone_mobile) ? $this->db->escape(trim($this->phone_mobile)) : "") . "'";
438
        $sql .= ")";
439
440
        $resql = $this->db->query($sql);
441
        if ($resql) {
442
            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "don");
443
            $ret = $this->id;
444
445
            if (!$notrigger) {
446
                // Call trigger
447
                $result = $this->call_trigger('DON_CREATE', $user);
448
                if ($result < 0) {
449
                    $error++;
450
                }
451
                // End call triggers
452
            }
453
        } else {
454
            $this->error = $this->db->lasterror();
455
            $error++;
456
        }
457
458
        // Update extrafield
459
        if (!$error) {
460
            $result = $this->insertExtraFields();
461
            if ($result < 0) {
462
                $error++;
463
            }
464
        }
465
466
        if (!$error && (getDolGlobalString('MAIN_DISABLEDRAFTSTATUS') || getDolGlobalString('MAIN_DISABLEDRAFTSTATUS_DONATION'))) {
467
            //$res = $this->setValid($user);
468
            //if ($res < 0) $error++;
469
        }
470
471
        if (!$error) {
472
            $this->db->commit();
473
            return $ret;
474
        } else {
475
            $this->db->rollback();
476
            return -1;
477
        }
478
    }
479
480
    /**
481
     *  Update a donation record
482
     *
483
     *  @param      User    $user   Object utilisateur qui met a jour le don
484
     *  @param      int     $notrigger  Disable triggers
485
     *  @return     int             >0 if OK, <0 if KO
486
     */
487
    public function update($user, $notrigger = 0)
488
    {
489
        global $langs;
490
491
        $error = 0;
492
493
        // Clean parameters
494
        // $this->address = ($this->address > 0 ? $this->address : $this->address);
495
        // $this->zip = ($this->zip > 0 ? $this->zip : $this->zip);
496
        // $this->town = ($this->town > 0 ? $this->town : $this->town);
497
        // $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
498
        // $this->country = ($this->country ? $this->country : $this->country);
499
        $this->amount = (float) price2num($this->amount);
500
501
        // Check parameters
502
        if ($this->amount < 0) {
503
            $this->error = $langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv("Amount"));
504
            return -1;
505
        }
506
507
        $this->db->begin();
508
509
        $sql = "UPDATE " . MAIN_DB_PREFIX . "don SET";
510
        $sql .= " amount = " . ((float) $this->amount);
511
        $sql .= ", fk_payment = " . ($this->modepaymentid ? $this->modepaymentid : "null");
512
        $sql .= ", firstname = '" . $this->db->escape($this->firstname) . "'";
513
        $sql .= ", lastname='" . $this->db->escape($this->lastname) . "'";
514
        $sql .= ", societe='" . $this->db->escape($this->societe) . "'";
515
        $sql .= ", address='" . $this->db->escape($this->address) . "'";
516
        $sql .= ", zip='" . $this->db->escape($this->zip) . "'";
517
        $sql .= ", town='" . $this->db->escape($this->town) . "'";
518
        $sql .= ", fk_country = " . ($this->country_id > 0 ? ((int) $this->country_id) : '0');
519
        $sql .= ", public=" . ((int) $this->public);
520
        $sql .= ", fk_projet=" . ($this->fk_project > 0 ? $this->fk_project : 'null');
521
        $sql .= ", note_private=" . (!empty($this->note_private) ? ("'" . $this->db->escape($this->note_private) . "'") : "NULL");
522
        $sql .= ", note_public=" . (!empty($this->note_public) ? ("'" . $this->db->escape($this->note_public) . "'") : "NULL");
523
        $sql .= ", datedon='" . $this->db->idate($this->date) . "'";
524
        $sql .= ", date_valid=" . ($this->date_valid ? "'" . $this->db->idate($this->date) . "'" : "null");
525
        $sql .= ", email='" . $this->db->escape(trim($this->email)) . "'";
526
        $sql .= ", phone='" . $this->db->escape(trim($this->phone)) . "'";
527
        $sql .= ", phone_mobile='" . $this->db->escape(trim($this->phone_mobile)) . "'";
528
        $sql .= ", fk_statut=" . ((int) $this->statut);
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

528
        $sql .= ", fk_statut=" . ((int) /** @scrutinizer ignore-deprecated */ $this->statut);

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...
529
        $sql .= " WHERE rowid = " . ((int) $this->id);
530
531
        dol_syslog(get_class($this) . "::Update", LOG_DEBUG);
532
        $resql = $this->db->query($sql);
533
        if ($resql) {
534
            if (!$notrigger) {
535
                // Call trigger
536
                $result = $this->call_trigger('DON_MODIFY', $user);
537
                if ($result < 0) {
538
                    $error++;
539
                }
540
                // End call triggers
541
            }
542
543
            // Update extrafield
544
            if (!$error) {
545
                $result = $this->insertExtraFields();
546
                if ($result < 0) {
547
                    $error++;
548
                }
549
            }
550
551
            if (!$error) {
552
                $this->db->commit();
553
                $result = 1;
554
            } else {
555
                $this->db->rollback();
556
                $result = -1;
557
            }
558
        } else {
559
            $this->error = $this->db->lasterror();
560
            $this->errors[] = $this->error;
561
            $this->db->rollback();
562
            dol_syslog(get_class($this) . "::Update error -2 " . $this->error, LOG_ERR);
563
            $result = -2;
564
        }
565
        return $result;
566
    }
567
568
    /**
569
     *    Delete a donation from database
570
     *
571
     *    @param       User     $user            User
572
     *    @param       int      $notrigger       Disable triggers
573
     *    @return      int                        Return integer <0 if KO, 0 if not possible, >0 if OK
574
     */
575
    public function delete($user, $notrigger = 0)
576
    {
577
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
578
579
        $error = 0;
580
581
        $this->db->begin();
582
583
        if (!$error && !$notrigger) {
584
            // Call trigger
585
            $result = $this->call_trigger('DON_DELETE', $user);
586
587
            if ($result < 0) {
588
                $error++;
589
            }
590
            // End call triggers
591
        }
592
593
        // Delete donation
594
        if (!$error) {
595
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "don_extrafields";
596
            $sql .= " WHERE fk_object = " . ((int) $this->id);
597
598
            $resql = $this->db->query($sql);
599
            if (!$resql) {
600
                $this->errors[] = $this->db->lasterror();
601
                $error++;
602
            }
603
        }
604
605
        if (!$error) {
606
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "don";
607
            $sql .= " WHERE rowid=" . ((int) $this->id);
608
609
            $resql = $this->db->query($sql);
610
            if (!$resql) {
611
                $this->errors[] = $this->db->lasterror();
612
                $error++;
613
            } else {
614
                // we delete file with dol_delete_dir_recursive
615
                $this->deleteEcmFiles(1);
616
617
                $dir = DOL_DATA_ROOT . '/' . $this->element . '/' . $this->ref;
618
                // For remove dir
619
                if (dol_is_dir($dir)) {
620
                    if (!dol_delete_dir_recursive($dir)) {
621
                        $this->errors[] = $this->error;
622
                    }
623
                }
624
            }
625
        }
626
627
        if (!$error) {
628
            $this->db->commit();
629
            return 1;
630
        } else {
631
            foreach ($this->errors as $errmsg) {
632
                dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
633
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
634
            }
635
            dol_syslog(get_class($this) . "::delete " . $this->error, LOG_ERR);
636
            $this->db->rollback();
637
            return -1;
638
        }
639
    }
640
641
    /**
642
     *      Load donation from database
643
     *
644
     *      @param      int     $id      Id of donation to load
645
     *      @param      string  $ref        Ref of donation to load
646
     *      @return     int                 Return integer <0 if KO, >0 if OK
647
     */
648
    public function fetch($id, $ref = '')
649
    {
650
        $sql = "SELECT d.rowid, d.datec, d.date_valid, d.tms as datem, d.datedon,";
651
        $sql .= " d.fk_soc as socid, d.firstname, d.lastname, d.societe, d.amount, d.fk_statut as status, d.address, d.zip, d.town, ";
652
        $sql .= " d.fk_country, d.public, d.amount, d.fk_payment, d.paid, d.note_private, d.note_public, d.email, d.phone, ";
653
        $sql .= " d.phone_mobile, d.fk_projet as fk_project, d.model_pdf,";
654
        $sql .= " p.ref as project_ref,";
655
        $sql .= " cp.libelle as payment_label, cp.code as payment_code,";
656
        $sql .= " c.code as country_code, c.label as country";
657
        $sql .= " FROM " . MAIN_DB_PREFIX . "don as d";
658
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "projet as p ON p.rowid = d.fk_projet";
659
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_paiement as cp ON cp.id = d.fk_payment";
660
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as c ON d.fk_country = c.rowid";
661
        $sql .= " WHERE d.entity IN (" . getEntity('donation') . ")";
662
        if (!empty($id)) {
663
            $sql .= " AND d.rowid=" . ((int) $id);
664
        } elseif (!empty($ref)) {
665
            $sql .= " AND d.ref='" . $this->db->escape($ref) . "'";
666
        }
667
668
        dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
669
        $resql = $this->db->query($sql);
670
        if ($resql) {
671
            if ($this->db->num_rows($resql)) {
672
                $obj = $this->db->fetch_object($resql);
673
674
                $this->id                 = $obj->rowid;
675
                $this->ref                = $obj->rowid;
676
                $this->date_creation      = $this->db->jdate($obj->datec);
677
                $this->datec              = $this->db->jdate($obj->datec);
678
                $this->date_validation    = $this->db->jdate($obj->date_valid);
679
                $this->date_valid = $this->db->jdate($obj->date_valid);
680
                $this->date_modification  = $this->db->jdate($obj->datem);
681
                $this->datem              = $this->db->jdate($obj->datem);
682
                $this->date               = $this->db->jdate($obj->datedon);
683
                $this->socid              = $obj->socid;
684
                $this->firstname          = $obj->firstname;
685
                $this->lastname           = $obj->lastname;
686
                $this->societe            = $obj->societe;
687
                $this->status             = $obj->status;
688
                $this->statut             = $obj->status;
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

688
                /** @scrutinizer ignore-deprecated */ $this->statut             = $obj->status;

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...
689
                $this->address            = $obj->address;
690
                $this->zip                = $obj->zip;
691
                $this->town               = $obj->town;
692
                $this->country_id         = $obj->fk_country;
693
                $this->country_code       = $obj->country_code;
694
                $this->country            = $obj->country;
695
                $this->email              = $obj->email;
696
                $this->phone              = $obj->phone;
697
                $this->phone_mobile       = $obj->phone_mobile;
698
                $this->project            = $obj->project_ref;
699
                $this->fk_projet          = $obj->fk_project; // deprecated
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$fk_projet has been deprecated: Use $fk_project instead. ( Ignorable by Annotation )

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

699
                /** @scrutinizer ignore-deprecated */ $this->fk_projet          = $obj->fk_project; // deprecated

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...
700
                $this->fk_project         = $obj->fk_project;
701
                $this->public             = $obj->public;
702
                $this->mode_reglement_id  = $obj->fk_payment;
703
                $this->mode_reglement_code = $obj->payment_code;
704
                $this->mode_reglement     = $obj->payment_label;
705
                $this->paid = $obj->paid;
706
                $this->amount             = $obj->amount;
707
                $this->note_private       = $obj->note_private;
708
                $this->note_public = $obj->note_public;
709
                $this->model_pdf          = $obj->model_pdf;
710
711
                // Retrieve all extrafield
712
                // fetch optionals attributes and labels
713
                $this->fetch_optionals();
714
            }
715
            return 1;
716
        } else {
717
            dol_print_error($this->db);
718
            return -1;
719
        }
720
    }
721
722
    /**
723
     *  Validate a intervention
724
     *
725
     *  @param      User        $user       User that validate
726
     *  @param      int         $notrigger  1=Does not execute triggers, 0= execute triggers
727
     *  @return     int                     Return integer <0 if KO, >0 if OK
728
     */
729
    public function setValid($user, $notrigger = 0)
730
    {
731
        // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
732
        return $this->valid_promesse($this->id, $user->id, $notrigger);
733
    }
734
735
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
736
    /**
737
     *    Validate a promise of donation
738
     *
739
     *    @param    int     $id         id of donation
740
     *    @param    int     $userid     User who validate the donation/promise
741
     *    @param    int     $notrigger  Disable triggers
742
     *    @return   int                 Return integer <0 if KO, >0 if OK
743
     */
744
    public function valid_promesse($id, $userid, $notrigger = 0)
745
    {
746
		// phpcs:enable
747
        global $user;
748
749
        $error = 0;
750
751
        $this->db->begin();
752
753
        $sql = "UPDATE " . MAIN_DB_PREFIX . "don SET fk_statut = 1, fk_user_valid = " . ((int) $userid) . " WHERE rowid = " . ((int) $id) . " AND fk_statut = 0";
754
755
        $resql = $this->db->query($sql);
756
        if ($resql) {
757
            if ($this->db->affected_rows($resql)) {
758
                if (!$notrigger) {
759
                    // Call trigger
760
                    $result = $this->call_trigger('DON_VALIDATE', $user);
761
                    if ($result < 0) {
762
                        $error++;
763
                    }
764
                    // End call triggers
765
                }
766
            }
767
        } else {
768
            $error++;
769
            $this->error = $this->db->lasterror();
770
        }
771
772
        if (!$error) {
773
            $this->statut = 1;
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

773
            /** @scrutinizer ignore-deprecated */ $this->statut = 1;

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...
774
            $this->db->commit();
775
            return 1;
776
        } else {
777
            $this->db->rollback();
778
            return -1;
779
        }
780
    }
781
782
    /**
783
     *    Classify the donation as paid, the donation was received
784
     *
785
     *    @param    int     $id                 id of donation
786
     *    @param    int     $modepayment        mode of payment
787
     *    @return   int                         Return integer <0 if KO, >0 if OK
788
     */
789
    public function setPaid($id, $modepayment = 0)
790
    {
791
        $sql = "UPDATE " . MAIN_DB_PREFIX . "don SET fk_statut = 2, paid = 1";
792
        if ($modepayment) {
793
            $sql .= ", fk_payment = " . ((int) $modepayment);
794
        }
795
        $sql .= " WHERE rowid = " . ((int) $id) . " AND fk_statut = 1";
796
797
        $resql = $this->db->query($sql);
798
        if ($resql) {
799
            if ($this->db->affected_rows($resql)) {
800
                $this->statut = 2;
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

800
                /** @scrutinizer ignore-deprecated */ $this->statut = 2;

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...
801
                $this->paid = 1;
802
                return 1;
803
            } else {
804
                return 0;
805
            }
806
        } else {
807
            dol_print_error($this->db);
808
            return -1;
809
        }
810
    }
811
812
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
813
    /**
814
     *    Set donation to status cancelled
815
     *
816
     *    @param    int     $id         id of donation
817
     *    @return   int                 Return integer <0 if KO, >0 if OK
818
     */
819
    public function set_cancel($id)
820
    {
821
		// phpcs:enable
822
        $sql = "UPDATE " . MAIN_DB_PREFIX . "don SET fk_statut = -1 WHERE rowid = " . ((int) $id);
823
824
        $resql = $this->db->query($sql);
825
        if ($resql) {
826
            if ($this->db->affected_rows($resql)) {
827
                $this->statut = -1;
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

827
                /** @scrutinizer ignore-deprecated */ $this->statut = -1;

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...
828
                return 1;
829
            } else {
830
                return 0;
831
            }
832
        } else {
833
            dol_print_error($this->db);
834
            return -1;
835
        }
836
    }
837
838
    /**
839
     *  Set cancel status
840
     *
841
     *  @param  User    $user           Object user that modify
842
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
843
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
844
     */
845
    public function reopen($user, $notrigger = 0)
846
    {
847
        // Protection
848
        if ($this->statut != self::STATUS_CANCELED) {
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

848
        if (/** @scrutinizer ignore-deprecated */ $this->statut != self::STATUS_CANCELED) {

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...
849
            return 0;
850
        }
851
852
        return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'DON_REOPEN');
853
    }
854
855
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
856
    /**
857
     *  Sum of donations
858
     *
859
     *  @param  string  $param  1=promesses de dons validees , 2=xxx, 3=encaisses
860
     *  @return int             Summ of donations
861
     */
862
    public function sum_donations($param)
863
    {
864
		// phpcs:enable
865
        global $conf;
866
867
        $result = 0;
868
869
        $sql = "SELECT sum(amount) as total";
870
        $sql .= " FROM " . MAIN_DB_PREFIX . "don";
871
        $sql .= " WHERE fk_statut = " . ((int) $param);
872
        $sql .= " AND entity = " . $conf->entity;
873
874
        $resql = $this->db->query($sql);
875
        if ($resql) {
876
            $obj = $this->db->fetch_object($resql);
877
            $result = $obj->total;
878
        }
879
880
        return $result;
881
    }
882
883
    /**
884
     *  Load the indicators this->nb for the state board
885
     *
886
     *  @return     int         Return integer <0 if KO, >0 if OK
887
     */
888
    public function loadStateBoard()
889
    {
890
        $this->nb = array();
891
892
        $sql = "SELECT count(d.rowid) as nb";
893
        $sql .= " FROM " . MAIN_DB_PREFIX . "don as d";
894
        $sql .= " WHERE d.fk_statut > 0";
895
        $sql .= " AND d.entity IN (" . getEntity('donation') . ")";
896
897
        $resql = $this->db->query($sql);
898
        if ($resql) {
899
            while ($obj = $this->db->fetch_object($resql)) {
900
                $this->nb["donations"] = $obj->nb;
901
            }
902
            $this->db->free($resql);
903
            return 1;
904
        } else {
905
            dol_print_error($this->db);
906
            $this->error = $this->db->error();
907
            return -1;
908
        }
909
    }
910
911
    /**
912
     *  Return clicable name (with picto eventually)
913
     *
914
     *  @param  int     $withpicto                  0=No picto, 1=Include picto into link, 2=Only picto
915
     *  @param  int     $notooltip                  1=Disable tooltip
916
     *  @param  string  $moretitle                  Add more text to title tooltip
917
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
918
     *  @return string                              Chaine avec URL
919
     */
920
    public function getNomUrl($withpicto = 0, $notooltip = 0, $moretitle = '', $save_lastsearch_value = -1)
921
    {
922
        global $conf, $langs, $hookmanager;
923
924
        if (!empty($conf->dol_no_mouse_hover)) {
925
            $notooltip = 1; // Force disable tooltips
926
        }
927
928
        $result = '';
929
        $label = img_picto('', $this->picto) . ' <u class="paddingrightonly">' . $langs->trans("Donation") . '</u>';
930
        if (isset($this->status)) {
931
            $label .= ' ' . $this->getLibStatut(5);
932
        }
933
        if (!empty($this->id)) {
934
            $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->id;
935
            $label .= '<br><b>' . $langs->trans('Date') . ':</b> ' . dol_print_date($this->date, 'day');
936
        }
937
        if ($moretitle) {
938
            $label .= ' - ' . $moretitle;
939
        }
940
941
        $url = constant('BASE_URL') . '/don/card.php?id=' . $this->id;
942
943
        $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
944
        if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
945
            $add_save_lastsearch_values = 1;
946
        }
947
        if ($add_save_lastsearch_values) {
948
            $url .= '&save_lastsearch_values=1';
949
        }
950
951
        $linkstart = '<a href="' . $url . '" title="' . dol_escape_htmltag($label, 1) . '" class="classfortooltip">';
952
        $linkend = '</a>';
953
954
        $result .= $linkstart;
955
        if ($withpicto) {
956
            $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
957
        }
958
        if ($withpicto != 2) {
959
            $result .= $this->ref;
960
        }
961
        $result .= $linkend;
962
        global $action;
963
        $hookmanager->initHooks(array($this->element . 'dao'));
964
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
965
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
966
        if ($reshook > 0) {
967
            $result = $hookmanager->resPrint;
968
        } else {
969
            $result .= $hookmanager->resPrint;
970
        }
971
        return $result;
972
    }
973
974
    /**
975
     * Information on record
976
     *
977
     * @param   int     $id      Id of record
978
     * @return  void
979
     */
980
    public function info($id)
981
    {
982
        $sql = 'SELECT d.rowid, d.datec, d.fk_user_author, d.fk_user_valid,';
983
        $sql .= ' d.tms as datem';
984
        $sql .= ' FROM ' . MAIN_DB_PREFIX . 'don as d';
985
        $sql .= ' WHERE d.rowid = ' . ((int) $id);
986
987
        dol_syslog(get_class($this) . '::info', LOG_DEBUG);
988
        $result = $this->db->query($sql);
989
990
        if ($result) {
991
            if ($this->db->num_rows($result)) {
992
                $obj = $this->db->fetch_object($result);
993
                $this->id = $obj->rowid;
994
995
                $this->user_creation_id = $obj->fk_user_author;
996
                $this->user_validation_id = $obj->fk_user_valid;
997
                $this->date_creation     = $this->db->jdate($obj->datec);
998
                $this->date_modification = (!empty($obj->tms) ? $this->db->jdate($obj->tms) : "");
999
            }
1000
            $this->db->free($result);
1001
        } else {
1002
            dol_print_error($this->db);
1003
        }
1004
    }
1005
1006
1007
    /**
1008
     *  Create a document onto disk according to template module.
1009
     *
1010
     *  @param      string      $modele         Force template to use ('' to not force)
1011
     *  @param      Translate   $outputlangs    object lang a utiliser pour traduction
1012
     *  @param      int         $hidedetails    Hide details of lines
1013
     *  @param      int         $hidedesc       Hide description
1014
     *  @param      int         $hideref        Hide ref
1015
     *  @return     int                         0 if KO, 1 if OK
1016
     */
1017
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1018
    {
1019
        global $conf, $langs;
1020
1021
        $langs->load("bills");
1022
1023
        if (!dol_strlen($modele)) {
1024
            $modele = 'html_cerfafr';
1025
1026
            if ($this->model_pdf) {
1027
                $modele = $this->model_pdf;
1028
            } elseif (getDolGlobalString('DON_ADDON_MODEL')) {
1029
                $modele = getDolGlobalString('DON_ADDON_MODEL');
1030
            }
1031
        }
1032
1033
        //$modelpath = "core/modules/dons/";
1034
1035
        // TODO Restore use of commonGenerateDocument instead of dedicated code here
1036
        //return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1037
1038
        // Increase limit for PDF build
1039
        $err = error_reporting();
1040
        error_reporting(0);
1041
        @set_time_limit(120);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1041
        /** @scrutinizer ignore-unhandled */ @set_time_limit(120);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1042
        error_reporting($err);
1043
1044
        $srctemplatepath = '';
1045
1046
        // If selected modele is a filename template (then $modele="modelname:filename")
1047
        $tmp = explode(':', $modele, 2);
1048
        if (!empty($tmp[1])) {
1049
            $modele = $tmp[0];
1050
            $srctemplatepath = $tmp[1];
1051
        }
1052
1053
        // Search template files
1054
        $file = '';
1055
        $classname = '';
1056
        $filefound = 0;
1057
        $dirmodels = array('/');
1058
        if (is_array($conf->modules_parts['models'])) {
1059
            $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
1060
        }
1061
        foreach ($dirmodels as $reldir) {
1062
            foreach (array('html', 'doc', 'pdf') as $prefix) {
1063
                $file = $prefix . "_" . preg_replace('/^html_/', '', $modele) . ".modules.php";
1064
1065
                // Verify the path for the module
1066
                $file = dol_buildpath($reldir . "core/modules/dons/" . $file, 0);
1067
                if (file_exists($file)) {
1068
                    $filefound = 1;
1069
                    $classname = $prefix . '_' . $modele;
1070
                    break;
1071
                }
1072
            }
1073
            if ($filefound) {
1074
                break;
1075
            }
1076
        }
1077
1078
        // Charge le modele
1079
        if ($filefound) {
1080
            require_once $file;
1081
1082
            $object = $this;
1083
1084
            $classname = $modele;
1085
            $obj = new $classname($this->db);
1086
1087
            // We save charset_output to restore it because write_file can change it if needed for
1088
            // output format that does not support UTF8.
1089
            $sav_charset_output = $outputlangs->charset_output;
1090
            if ($obj->write_file($object, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref) > 0) {
1091
                $outputlangs->charset_output = $sav_charset_output;
1092
1093
                // we delete preview files
1094
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
1095
                dol_delete_preview($object);
1096
                return 1;
1097
            } else {
1098
                $outputlangs->charset_output = $sav_charset_output;
1099
                dol_syslog("Erreur dans don_create");
1100
                dol_print_error($this->db, $obj->error);
1101
                return 0;
1102
            }
1103
        } else {
1104
            print $langs->trans("Error") . " " . $langs->trans("ErrorFileDoesNotExists", $file);
1105
            return 0;
1106
        }
1107
    }
1108
1109
    /**
1110
     * Function used to replace a thirdparty id with another one.
1111
     *
1112
     * @param   DoliDB  $dbs        Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
1113
     * @param   int     $origin_id  Old thirdparty id
1114
     * @param   int     $dest_id    New thirdparty id
1115
     * @return  bool
1116
     */
1117
    public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
1118
    {
1119
        $tables = array(
1120
            'don'
1121
        );
1122
1123
        return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
1124
    }
1125
1126
    /**
1127
     * Function to get remaining amount to pay for a donation
1128
     *
1129
     * @return   float|int<-2,-1>                       Return integer <0 if KO, > remaining amount to pay if  OK
1130
     */
1131
    public function getRemainToPay()
1132
    {
1133
        dol_syslog(__METHOD__, LOG_DEBUG);
1134
1135
        if (empty($this->id)) {
1136
            $this->error = 'Missing object id';
1137
            $this->errors[] = $this->error;
1138
            dol_syslog(__METHOD__ . ' : ' . $this->error, LOG_ERR);
1139
            return -1;
1140
        }
1141
1142
        $sql = "SELECT SUM(amount) as sum_amount FROM " . MAIN_DB_PREFIX . "payment_donation WHERE fk_donation = " . ((int) $this->id);
1143
        $resql = $this->db->query($sql);
1144
        if (!$resql) {
1145
            dol_print_error($this->db);
1146
            return -2;
1147
        } else {
1148
            $sum_amount = (float) $this->db->fetch_object($resql)->sum_amount;
1149
            return (float) ($this->amount - $sum_amount);
1150
        }
1151
    }
1152
1153
    /**
1154
     *  Return clicable link of object (with eventually picto)
1155
     *
1156
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
1157
     *  @param      array       $arraydata              Array of data
1158
     *  @return     string                              HTML Code for Kanban thumb.
1159
     */
1160
    public function getKanbanView($option = '', $arraydata = null)
1161
    {
1162
        global $conf, $langs;
1163
1164
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1165
1166
        $return = '<div class="box-flex-item box-flex-grow-zero">';
1167
        $return .= '<div class="info-box info-box-sm">';
1168
        $return .= '<span class="info-box-icon bg-infobox-action">';
1169
        $return .= img_picto('', $this->picto);
1170
        $return .= '</span>';
1171
        $return .= '<div class="info-box-content">';
1172
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref) . '</span>';
1173
        if ($selected >= 0) {
1174
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
1175
        }
1176
        if (property_exists($this, 'date')) {
1177
            $return .= ' &nbsp; | &nbsp; <span class="info-box-label">' . dol_print_date($this->date, 'day', 'tzuserrel') . '</span>';
1178
        }
1179
        if (property_exists($this, 'societe') && !empty($this->societe)) {
1180
            $return .= '<br><span class="opacitymedium">' . $langs->trans("Company") . '</span> : <span class="info-box-label">' . $this->societe . '</span>';
1181
        }
1182
        if (property_exists($this, 'amount')) {
1183
            $return .= '<br><span class="info-box-label amount">' . price($this->amount, 1, $langs, 1, -1, -1, $conf->currency) . '</span>';
1184
        }
1185
        if (method_exists($this, 'LibStatut')) {
1186
            $return .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
1187
        }
1188
        $return .= '</div>';
1189
        $return .= '</div>';
1190
        $return .= '</div>';
1191
        return $return;
1192
    }
1193
}
1194