]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
f8cc8bd0db1e93ca8cf37ee7a0a2e1a896b65759
[galette.git] / galette / lib / Galette / Entity / Contribution.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Contribution class for galette
7 * Manage membership fees and donations.
8 *
9 * PHP version 5
10 *
11 * Copyright © 2010-2023 The Galette Team
12 *
13 * This file is part of Galette (http://galette.tuxfamily.org).
14 *
15 * Galette 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 * Galette 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 Galette. If not, see <http://www.gnu.org/licenses/>.
27 *
28 * @category Entity
29 * @package Galette
30 *
31 * @author Johan Cwiklinski <johan@x-tnd.be>
32 * @copyright 2010-2023 The Galette Team
33 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
34 * @link http://galette.tuxfamily.org
35 * @since Available since 0.7dev - 2010-03-11
36 */
37
38 namespace Galette\Entity;
39
40 use ArrayObject;
41 use DateTime;
42 use Galette\Events\GaletteEvent;
43 use Throwable;
44 use Analog\Analog;
45 use Laminas\Db\Sql\Expression;
46 use Galette\Core\Db;
47 use Galette\Core\Login;
48 use Galette\IO\ExternalScript;
49 use Galette\IO\PdfContribution;
50 use Galette\Repository\PaymentTypes;
51 use Galette\Features\Dynamics;
52
53 /**
54 * Contribution class for galette
55 * Manage membership fees and donations.
56 *
57 * @category Entity
58 * @name Contribution
59 * @package Galette
60 * @author Johan Cwiklinski <johan@x-tnd.be>
61 * @copyright 2010-2023 The Galette Team
62 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
63 * @link http://galette.tuxfamily.org
64 * @since Available since 0.7dev - 2010-03-11
65 *
66 * @property integer $id
67 * @property string $date
68 * @property DateTime $raw_date
69 * @property integer $member
70 * @property ContributionsTypes|int $type
71 * @property double $amount
72 * @property integer $payment_type
73 * @property double $orig_amount
74 * @property string $info
75 * @property string $begin_date
76 * @property DateTime $raw_begin_date
77 * @property string $end_date
78 * @property DateTime $raw_end_date
79 * @property Transaction|null $transaction
80 * @property integer $extension
81 * @property integer $duration
82 * @property string $spayment_type
83 * @property integer $model
84 */
85 class Contribution
86 {
87 use Dynamics;
88
89 public const TABLE = 'cotisations';
90 public const PK = 'id_cotis';
91
92 public const TYPE_FEE = 'fee';
93 public const TYPE_DONATION = 'donation';
94
95 private $_id;
96 private $_date;
97 private $_member;
98 private $_type;
99 private $_amount;
100 private $_payment_type;
101 private $_orig_amount;
102 private $_info;
103 private $_begin_date;
104 private $_end_date;
105 private $_transaction = null;
106 private $_is_cotis;
107 private $_extension;
108
109 //fields list and their translation
110 private $_fields;
111
112 /** @var Db */
113 private $zdb;
114 /** @var Login */
115 private $login;
116 /** @var array */
117 private $errors;
118
119 private $sendmail = false;
120
121 /**
122 * Default constructor
123 *
124 * @param Db $zdb Database
125 * @param Login $login Login instance
126 * @param null|int|array|ArrayObject $args Either a ResultSet row to load
127 * a specific contribution, or a type id
128 * to just instantiate object
129 */
130 public function __construct(Db $zdb, Login $login, $args = null)
131 {
132 $this->zdb = $zdb;
133 $this->login = $login;
134
135 global $preferences;
136 $this->_payment_type = (int)$preferences->pref_default_paymenttype;
137
138 /*
139 * Fields configuration. Each field is an array and must reflect:
140 * array(
141 * (string)label,
142 * (string) property name
143 * )
144 *
145 * I'd prefer a static private variable for this...
146 * But call to the _T function does not seem to be allowed there :/
147 */
148 $this->_fields = array(
149 'id_cotis' => array(
150 'label' => _T('Contribution id'), //not a field in the form
151 'propname' => 'id'
152 ),
153 Adherent::PK => array(
154 'label' => _T("Contributor:"),
155 'propname' => 'member'
156 ),
157 ContributionsTypes::PK => array(
158 'label' => _T("Contribution type:"),
159 'propname' => 'type'
160 ),
161 'montant_cotis' => array(
162 'label' => _T("Amount:"),
163 'propname' => 'amount'
164 ),
165 'type_paiement_cotis' => array(
166 'label' => _T("Payment type:"),
167 'propname' => 'payment_type'
168 ),
169 'info_cotis' => array(
170 'label' => _T("Comments:"),
171 'propname' => 'info'
172 ),
173 'date_enreg' => array(
174 'label' => _T('Date'), //not a field in the form
175 'propname' => 'date'
176 ),
177 'date_debut_cotis' => array(
178 'label' => _T("Date of contribution:"),
179 'cotlabel' => _T("Start date of membership:"), //if contribution is a membership fee, label differs
180 'propname' => 'begin_date'
181 ),
182 'date_fin_cotis' => array(
183 'label' => _T("End date of membership:"),
184 'propname' => 'end_date'
185 ),
186 Transaction::PK => array(
187 'label' => _T('Transaction ID'), //not a field in the form
188 'propname' => 'transaction'
189 ),
190 //this one is not really a field, but is required in some cases...
191 //adding it here make more simple to check required fields
192 'duree_mois_cotis' => array(
193 'label' => _T("Membership extension:"),
194 'propname' => 'extension'
195 )
196 );
197 if (is_int($args)) {
198 $this->load($args);
199 } elseif (is_array($args)) {
200 $this->_date = date("Y-m-d");
201 if (isset($args['adh']) && $args['adh'] != '') {
202 $this->_member = (int)$args['adh'];
203 }
204 if (isset($args['trans'])) {
205 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$args['trans']);
206 if (!isset($this->_member)) {
207 $this->_member = (int)$this->_transaction->member;
208 }
209 $this->_amount = $this->_transaction->getMissingAmount();
210 }
211 $this->type = (int)$args['type'];
212 //calculate begin date for membership fee
213 $this->_begin_date = $this->_date;
214 if ($this->_is_cotis) {
215 $due_date = self::getDueDate($this->zdb, $this->_member);
216 if ($due_date != '') {
217 $now = new \DateTime();
218 $due_date = new \DateTime($due_date);
219 if ($due_date < $now) {
220 // Member didn't renew on time
221 $this->_begin_date = $now->format('Y-m-d');
222 } else {
223 // Caution : the next_begin_date is the day after the due_date.
224 $next_begin_date = clone $due_date;
225 $next_begin_date->add(new \DateInterval('P1D'));
226 $this->_begin_date = $next_begin_date->format('Y-m-d');
227 }
228 }
229 $this->retrieveEndDate();
230 }
231 if (isset($args['payment_type'])) {
232 $this->_payment_type = $args['payment_type'];
233 }
234 } elseif (is_object($args)) {
235 $this->loadFromRS($args);
236 }
237
238 $this->loadDynamicFields();
239 }
240
241 /**
242 * Sets end contribution date
243 *
244 * @return void
245 */
246 private function retrieveEndDate()
247 {
248 global $preferences;
249
250 $now = new \DateTime();
251 $begin_date = new \DateTime($this->_begin_date);
252 if ($preferences->pref_beg_membership != '') {
253 //case beginning of membership
254 list($j, $m) = explode('/', $preferences->pref_beg_membership);
255 $next_begin_date = new \DateTime($begin_date->format('Y') . '-' . $m . '-' . $j);
256 while ($next_begin_date <= $begin_date) {
257 $next_begin_date->add(new \DateInterval('P1Y'));
258 }
259
260 if ($preferences->pref_membership_offermonths > 0) {
261 //count days until next membership begin date
262 $diff1 = (int)$now->diff($next_begin_date)->format('%a');
263
264 //count days between next membership begin date and offered months
265 $tdate = clone $next_begin_date;
266 $tdate->sub(new \DateInterval('P' . $preferences->pref_membership_offermonths . 'M'));
267 $diff2 = (int)$next_begin_date->diff($tdate)->format('%a');
268
269 //when number of days until next membership begin date is less than or equal to the offered months, it's free :)
270 if ($diff1 <= $diff2) {
271 $next_begin_date->add(new \DateInterval('P1Y'));
272 }
273 }
274
275 // Caution : the end_date to retrieve is the day before the next_begin_date.
276 $end_date = clone $next_begin_date;
277 $end_date->sub(new \DateInterval('P1D'));
278 $this->_end_date = $end_date->format('Y-m-d');
279 } elseif ($preferences->pref_membership_ext != '') {
280 //case membership extension
281 if ($this->_extension == null) {
282 $this->_extension = $preferences->pref_membership_ext;
283 }
284 $dext = new \DateInterval('P' . $this->_extension . 'M');
285 // Caution : the end_date to retrieve is the day before the next_begin_date.
286 $next_begin_date = $begin_date->add($dext);
287 $end_date = clone $next_begin_date;
288 $end_date->sub(new \DateInterval('P1D'));
289 $this->_end_date = $end_date->format('Y-m-d');
290 } else {
291 throw new \RuntimeException(
292 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
293 );
294 }
295 }
296
297 /**
298 * Loads a contribution from its id
299 *
300 * @param int $id the identifier for the contribution to load
301 *
302 * @return bool true if query succeed, false otherwise
303 */
304 public function load($id)
305 {
306 if (!$this->login->isLogged() && $this->login->id == '') {
307 return false;
308 }
309
310 try {
311 $select = $this->zdb->select(self::TABLE, 'c');
312 $select->join(
313 array('a' => PREFIX_DB . Adherent::TABLE),
314 'c.' . Adherent::PK . '=a.' . Adherent::PK,
315 array()
316 );
317 //restrict query on current member id if he's not admin nor staff member
318 if (!$this->login->isAdmin() && !$this->login->isStaff()) {
319 $select->where
320 ->nest()
321 ->equalTo('a.' . Adherent::PK, $this->login->id)
322 ->or
323 ->equalTo('a.parent_id', $this->login->id)
324 ->unnest()
325 ->and
326 ->equalTo('c.' . self::PK, $id)
327 ;
328 } else {
329 $select->where->equalTo(self::PK, $id);
330 }
331
332 $results = $this->zdb->execute($select);
333 if ($results->count() > 0) {
334 $row = $results->current();
335 $this->loadFromRS($row);
336 return true;
337 } else {
338 Analog::log(
339 'No contribution #' . $id . ' (user ' . $this->login->id . ')',
340 Analog::ERROR
341 );
342 return false;
343 }
344 } catch (Throwable $e) {
345 Analog::log(
346 'An error occurred attempting to load contribution #' . $id .
347 $e->getMessage(),
348 Analog::ERROR
349 );
350 throw $e;
351 }
352 }
353
354 /**
355 * Populate object from a resultset row
356 *
357 * @param ArrayObject $r the resultset row
358 *
359 * @return void
360 */
361 private function loadFromRS(ArrayObject $r)
362 {
363 $pk = self::PK;
364 $this->_id = (int)$r->$pk;
365 $this->_date = $r->date_enreg;
366 $this->_amount = (double)$r->montant_cotis;
367 //save original amount, we need it for transactions parts calculations
368 $this->_orig_amount = (double)$r->montant_cotis;
369 $this->_payment_type = $r->type_paiement_cotis;
370 $this->_info = $r->info_cotis;
371 $this->_begin_date = $r->date_debut_cotis;
372 $end_date = $r->date_fin_cotis;
373 //do not work with knows bad dates...
374 //the one with BC comes from 0.63/pgsql demo... Why the hell a so
375 //strange date? don't know :(
376 if (
377 $end_date !== '0000-00-00'
378 && $end_date !== '1901-01-01'
379 && $end_date !== '0001-01-01 BC'
380 ) {
381 $this->_end_date = $r->date_fin_cotis;
382 }
383 $adhpk = Adherent::PK;
384 $this->_member = (int)$r->$adhpk;
385
386 $transpk = Transaction::PK;
387 if ($r->$transpk != '') {
388 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$r->$transpk);
389 }
390
391 $this->type = (int)$r->id_type_cotis;
392 $this->loadDynamicFields();
393 }
394
395 /**
396 * Check posted values validity
397 *
398 * @param array $values All values to check, basically the $_POST array
399 * after sending the form
400 * @param array $required Array of required fields
401 * @param array $disabled Array of disabled fields
402 *
403 * @return true|array
404 */
405 public function check($values, $required, $disabled)
406 {
407 global $preferences;
408 $this->errors = array();
409
410 $fields = array_keys($this->_fields);
411 foreach ($fields as $key) {
412 //first, let's sanitize values
413 $key = strtolower($key);
414 $prop = '_' . $this->_fields[$key]['propname'];
415
416 if (isset($values[$key])) {
417 $value = trim($values[$key]);
418 } else {
419 $value = '';
420 }
421
422 // if the field is enabled, check it
423 if (!isset($disabled[$key])) {
424 // fill up the adherent structure
425 //$this->$prop = stripslashes($value); //not relevant here!
426
427 // now, check validity
428 switch ($key) {
429 // dates
430 case 'date_enreg':
431 case 'date_debut_cotis':
432 case 'date_fin_cotis':
433 if ($value != '') {
434 try {
435 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
436 if ($d === false) {
437 //try with non localized date
438 $d = \DateTime::createFromFormat("Y-m-d", $value);
439 if ($d === false) {
440 throw new \Exception('Incorrect format');
441 }
442 }
443 $this->$prop = $d->format('Y-m-d');
444 } catch (Throwable $e) {
445 Analog::log(
446 'Wrong date format. field: ' . $key .
447 ', value: ' . $value . ', expected fmt: ' .
448 __("Y-m-d") . ' | ' . $e->getMessage(),
449 Analog::INFO
450 );
451 $this->errors[] = str_replace(
452 array(
453 '%date_format',
454 '%field'
455 ),
456 array(
457 __("Y-m-d"),
458 $this->_fields[$key]['label']
459 ),
460 _T("- Wrong date format (%date_format) for %field!")
461 );
462 }
463 }
464 break;
465 case Adherent::PK:
466 if ($value != '') {
467 $this->_member = (int)$value;
468 }
469 break;
470 case ContributionsTypes::PK:
471 if ($value != '') {
472 $this->type = (int)$value;
473 }
474 break;
475 case 'montant_cotis':
476 $value = strtr($value, ',', '.');
477 if (!empty($value) || $value === '0') {
478 $this->_amount = (double)$value;
479 }
480 if (!is_numeric($value) && $value !== '') {
481 $this->errors[] = _T("- The amount must be an integer!");
482 }
483 break;
484 case 'type_paiement_cotis':
485 $ptypes = new PaymentTypes(
486 $this->zdb,
487 $preferences,
488 $this->login
489 );
490 $ptlist = $ptypes->getList();
491 if (isset($ptlist[$value])) {
492 $this->_payment_type = $value;
493 } else {
494 $this->errors[] = _T("- Unknown payment type");
495 }
496 break;
497 case 'info_cotis':
498 $this->_info = $value;
499 break;
500 case Transaction::PK:
501 if ($value != '') {
502 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$value);
503 }
504 break;
505 case 'duree_mois_cotis':
506 if ($value != '') {
507 if (!is_numeric($value) || $value <= 0) {
508 $this->errors[] = _T("- The duration must be a positive integer!");
509 }
510 $this->$prop = $value;
511 $this->retrieveEndDate();
512 }
513 break;
514 }
515 }
516 }
517
518 // missing required fields?
519 foreach ($required as $key => $val) {
520 if ($val === 1) {
521 $prop = '_' . $this->_fields[$key]['propname'];
522 if (
523 !isset($disabled[$key])
524 && (!isset($this->$prop)
525 || (!is_object($this->$prop) && trim($this->$prop) == '')
526 || (is_object($this->$prop) && trim($this->$prop->id) == ''))
527 ) {
528 $this->errors[] = str_replace(
529 '%field',
530 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
531 _T("- Mandatory field %field empty.")
532 );
533 }
534 }
535 }
536
537 if ($this->_transaction != null && $this->_amount != null) {
538 $missing = $this->_transaction->getMissingAmount();
539 //calculate new missing amount
540 $missing = $missing + $this->_orig_amount - $this->_amount;
541 if ($missing < 0) {
542 $this->errors[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
543 }
544 }
545
546 if ($this->isFee() && count($this->errors) == 0) {
547 $overlap = $this->checkOverlap();
548 if ($overlap !== true) {
549 //method directly return error message
550 $this->errors[] = $overlap;
551 }
552 }
553
554 $this->dynamicsCheck($values, $required, $disabled);
555
556 if (count($this->errors) > 0) {
557 Analog::log(
558 'Some errors has been threw attempting to edit/store a contribution' .
559 print_r($this->errors, true),
560 Analog::ERROR
561 );
562 return $this->errors;
563 } else {
564 Analog::log(
565 'Contribution checked successfully.',
566 Analog::DEBUG
567 );
568 return true;
569 }
570 }
571
572 /**
573 * Check that membership fees does not overlap
574 *
575 * @return boolean|string True if all is ok, false if error,
576 * error message if overlap
577 */
578 public function checkOverlap()
579 {
580 try {
581 $select = $this->zdb->select(self::TABLE, 'c');
582 //@phpstan-ignore-next-line
583 $select->columns(
584 array('date_debut_cotis', 'date_fin_cotis')
585 )->join(
586 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
587 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
588 array()
589 )->where([Adherent::PK => $this->_member])
590 ->where(array('cotis_extension' => new Expression('true')))
591 ->where->nest->nest
592 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date)
593 ->lessThanOrEqualTo('date_debut_cotis', $this->_end_date)
594 ->unnest
595 ->or->nest
596 ->greaterThanOrEqualTo('date_fin_cotis', $this->_begin_date)
597 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date);
598
599 if ($this->id != '') {
600 $select->where->notEqualTo(self::PK, $this->id);
601 }
602
603 $results = $this->zdb->execute($select);
604 if ($results->count() > 0) {
605 $result = $results->current();
606
607 $d_begin = new \DateTime($result->date_debut_cotis);
608 $d_end = new \DateTime($result->date_fin_cotis);
609
610 if ($d_begin->format('m-d') == $d_end->format('m-d') && $result->date_fin_cotis == $this->_begin_date) {
611 //see https://bugs.galette.eu/issues/1762
612 return true;
613 }
614
615 return _T("- Membership period overlaps period starting at ") .
616 $d_begin->format(__("Y-m-d"));
617 }
618 return true;
619 } catch (Throwable $e) {
620 Analog::log(
621 'An error occurred checking overlapping fee. ' . $e->getMessage(),
622 Analog::ERROR
623 );
624 throw $e;
625 }
626 }
627
628 /**
629 * Store the contribution
630 *
631 * @return boolean
632 */
633 public function store()
634 {
635 global $hist, $emitter;
636
637 $event = null;
638
639 if (count($this->errors) > 0) {
640 throw new \RuntimeException(
641 'Existing errors prevents storing contribution: ' .
642 print_r($this->errors, true)
643 );
644 }
645
646 try {
647 $this->zdb->connection->beginTransaction();
648 $values = array();
649 $fields = self::getDbFields($this->zdb);
650 foreach ($fields as $field) {
651 $prop = '_' . $this->_fields[$field]['propname'];
652 switch ($field) {
653 case ContributionsTypes::PK:
654 case Transaction::PK:
655 if (isset($this->$prop)) {
656 $values[$field] = $this->$prop->id;
657 }
658 break;
659 default:
660 $values[$field] = $this->$prop;
661 break;
662 }
663 }
664
665 //no end date, let's take database defaults
666 if (!$this->isFee() && !$this->_end_date) {
667 unset($values['date_fin_cotis']);
668 }
669
670 if (!isset($this->_id) || $this->_id == '') {
671 //we're inserting a new contribution
672 unset($values[self::PK]);
673
674 $insert = $this->zdb->insert(self::TABLE);
675 $insert->values($values);
676 $add = $this->zdb->execute($insert);
677
678 if ($add->count() > 0) {
679 $this->_id = $this->zdb->getLastGeneratedValue($this);
680
681 // logging
682 $hist->add(
683 _T("Contribution added"),
684 Adherent::getSName($this->zdb, $this->_member)
685 );
686 $event = 'contribution.add';
687 } else {
688 $hist->add(_T("Fail to add new contribution."));
689 throw new \Exception(
690 'An error occurred inserting new contribution!'
691 );
692 }
693 } else {
694 //we're editing an existing contribution
695 $update = $this->zdb->update(self::TABLE);
696 $update->set($values)->where([self::PK => $this->_id]);
697 $edit = $this->zdb->execute($update);
698
699 //edit == 0 does not mean there were an error, but that there
700 //were nothing to change
701 if ($edit->count() > 0) {
702 $hist->add(
703 _T("Contribution updated"),
704 Adherent::getSName($this->zdb, $this->_member)
705 );
706 }
707
708 $event = 'contribution.edit';
709 }
710 //update deadline
711 if ($this->isFee()) {
712 $this->updateDeadline();
713 }
714
715 //dynamic fields
716 $this->dynamicsStore(true);
717
718 $this->zdb->connection->commit();
719 $this->_orig_amount = $this->_amount;
720
721 //send event at the end of process, once all has been stored
722 if ($event !== null) {
723 $emitter->dispatch(new GaletteEvent($event, $this));
724 }
725
726 return true;
727 } catch (Throwable $e) {
728 if ($this->zdb->connection->inTransaction()) {
729 $this->zdb->connection->rollBack();
730 }
731 throw $e;
732 }
733 }
734
735 /**
736 * Update member dead line
737 *
738 * @return boolean
739 */
740 private function updateDeadline()
741 {
742 try {
743 $due_date = self::getDueDate($this->zdb, $this->_member);
744
745 if ($due_date != '') {
746 $due_date_update = $due_date;
747 } else {
748 $due_date_update = new Expression('NULL');
749 }
750
751 $update = $this->zdb->update(Adherent::TABLE);
752 $update->set(
753 array('date_echeance' => $due_date_update)
754 )->where(
755 [Adherent::PK => $this->_member]
756 );
757 $this->zdb->execute($update);
758 return true;
759 } catch (Throwable $e) {
760 Analog::log(
761 'An error occurred updating member ' . $this->_member .
762 '\'s deadline |' .
763 $e->getMessage(),
764 Analog::ERROR
765 );
766 throw $e;
767 }
768 }
769
770 /**
771 * Remove contribution from database
772 *
773 * @param boolean $transaction Activate transaction mode (defaults to true)
774 *
775 * @return boolean
776 */
777 public function remove($transaction = true)
778 {
779 global $emitter;
780
781 try {
782 if ($transaction) {
783 $this->zdb->connection->beginTransaction();
784 }
785
786 $delete = $this->zdb->delete(self::TABLE);
787 $delete->where([self::PK => $this->_id]);
788 $del = $this->zdb->execute($delete);
789 if ($del->count() > 0) {
790 $this->updateDeadline();
791 $this->dynamicsRemove(true);
792 } else {
793 Analog::log(
794 'Contribution has not been removed!',
795 Analog::WARNING
796 );
797 return false;
798 }
799 if ($transaction) {
800 $this->zdb->connection->commit();
801 }
802 $emitter->dispatch(new GaletteEvent('contribution.remove', $this));
803 return true;
804 } catch (Throwable $e) {
805 if ($transaction) {
806 $this->zdb->connection->rollBack();
807 }
808 Analog::log(
809 'An error occurred trying to remove contribution #' .
810 $this->_id . ' | ' . $e->getMessage(),
811 Analog::ERROR
812 );
813 throw $e;
814 }
815 }
816
817 /**
818 * Get field label
819 *
820 * @param string $field Field name
821 *
822 * @return string
823 */
824 public function getFieldLabel($field)
825 {
826 $label = $this->_fields[$field]['label'];
827 if ($this->isFee() && $field == 'date_debut_cotis') {
828 $label = $this->_fields[$field]['cotlabel'];
829 }
830 //replace "&nbsp;"
831 $label = str_replace('&nbsp;', ' ', $label);
832 //remove trailing ':' and then trim
833 $label = trim(trim($label, ':'));
834 return $label;
835 }
836
837 /**
838 * Retrieve fields from database
839 *
840 * @param Db $zdb Database instance
841 *
842 * @return array
843 */
844 public static function getDbFields(Db $zdb)
845 {
846 $columns = $zdb->getColumns(self::TABLE);
847 $fields = array();
848 foreach ($columns as $col) {
849 $fields[] = $col->getName();
850 }
851 return $fields;
852 }
853
854 /**
855 * Get the relevant CSS class for current contribution
856 *
857 * @return string current contribution row class
858 */
859 public function getRowClass()
860 {
861 return ($this->_end_date != $this->_begin_date && $this->_is_cotis) ?
862 'cotis-normal' : 'cotis-give';
863 }
864
865 /**
866 * Retrieve member due date
867 *
868 * @param Db $zdb Database instance
869 * @param integer $member_id Member identifier
870 *
871 * @return string
872 */
873 public static function getDueDate(Db $zdb, $member_id)
874 {
875 if (!$member_id) {
876 return '';
877 }
878 try {
879 $select = $zdb->select(self::TABLE, 'c');
880 $select->columns(
881 array(
882 'max_date' => new Expression('MAX(date_fin_cotis)')
883 )
884 )->join(
885 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
886 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
887 array()
888 )->where(
889 [Adherent::PK => $member_id]
890 )->where(
891 array('cotis_extension' => new Expression('true'))
892 );
893
894 $results = $zdb->execute($select);
895 $result = $results->current();
896 $due_date = $result->max_date;
897
898 //avoid bad dates in postgres and bad mysql return from zenddb
899 if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
900 $due_date = '';
901 }
902 return $due_date;
903 } catch (Throwable $e) {
904 Analog::log(
905 'An error occurred trying to retrieve member\'s due date',
906 Analog::ERROR
907 );
908 throw $e;
909 }
910 }
911
912 /**
913 * Detach a contribution from a transaction
914 *
915 * @param Db $zdb Database instance
916 * @param Login $login Login instance
917 * @param int $trans_id Transaction identifier
918 * @param int $contrib_id Contribution identifier
919 *
920 * @return boolean
921 */
922 public static function unsetTransactionPart(Db $zdb, Login $login, $trans_id, $contrib_id)
923 {
924 try {
925 //first, we check if contribution is part of transaction
926 $c = new Contribution($zdb, $login, (int)$contrib_id);
927 if ($c->isTransactionPartOf($trans_id)) {
928 $update = $zdb->update(self::TABLE);
929 $update->set(
930 array(Transaction::PK => null)
931 )->where(
932 [self::PK => $contrib_id]
933 );
934 $zdb->execute($update);
935 return true;
936 } else {
937 Analog::log(
938 'Contribution #' . $contrib_id .
939 ' is not actually part of transaction #' . $trans_id,
940 Analog::WARNING
941 );
942 return false;
943 }
944 } catch (Throwable $e) {
945 Analog::log(
946 'Unable to detach contribution #' . $contrib_id .
947 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
948 Analog::ERROR
949 );
950 throw $e;
951 }
952 }
953
954 /**
955 * Set a contribution as a transaction part
956 *
957 * @param Db $zdb Database instance
958 * @param int $trans_id Transaction identifier
959 * @param int $contrib_id Contribution identifier
960 *
961 * @return boolean
962 */
963 public static function setTransactionPart(Db $zdb, $trans_id, $contrib_id)
964 {
965 try {
966 $update = $zdb->update(self::TABLE);
967 $update->set(
968 array(Transaction::PK => $trans_id)
969 )->where([self::PK => $contrib_id]);
970
971 $zdb->execute($update);
972 return true;
973 } catch (Throwable $e) {
974 Analog::log(
975 'Unable to attach contribution #' . $contrib_id .
976 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
977 Analog::ERROR
978 );
979 throw $e;
980 }
981 }
982
983 /**
984 * Is current contribution a membership fee
985 *
986 * @return boolean
987 */
988 public function isFee()
989 {
990 return $this->_is_cotis;
991 }
992
993 /**
994 * Is current contribution part of specified transaction
995 *
996 * @param int $id Transaction identifier
997 *
998 * @return boolean
999 */
1000 public function isTransactionPartOf($id)
1001 {
1002 if ($this->isTransactionPart()) {
1003 return $id == $this->_transaction->id;
1004 } else {
1005 return false;
1006 }
1007 }
1008
1009 /**
1010 * Is current contribution part of transaction
1011 *
1012 * @return boolean
1013 */
1014 public function isTransactionPart()
1015 {
1016 return $this->_transaction != null;
1017 }
1018
1019 /**
1020 * Execute post contribution script
1021 *
1022 * @param ExternalScript $es External script to execute
1023 * @param array $extra Extra information on contribution
1024 * Defaults to null
1025 * @param array $pextra Extra information on payment
1026 * Defaults to null
1027 *
1028 * @return mixed Script return value on success, values and script output on fail
1029 */
1030 public function executePostScript(
1031 ExternalScript $es,
1032 $extra = null,
1033 $pextra = null
1034 ) {
1035 global $preferences;
1036
1037 $payment = array(
1038 'type' => $this->getPaymentType()
1039 );
1040
1041 if ($pextra !== null && is_array($pextra)) {
1042 $payment = array_merge($payment, $pextra);
1043 }
1044
1045 if (!file_exists(GALETTE_CACHE_DIR . '/pdf_contribs')) {
1046 @mkdir(GALETTE_CACHE_DIR . '/pdf_contribs');
1047 }
1048
1049 $voucher_path = null;
1050 if ($this->_id !== null) {
1051 $voucher = new PdfContribution($this, $this->zdb, $preferences);
1052 $voucher->store(GALETTE_CACHE_DIR . '/pdf_contribs');
1053 $voucher_path = $voucher->getPath();
1054 }
1055
1056 $contrib = array(
1057 'id' => (int)$this->_id,
1058 'date' => $this->_date,
1059 'type' => $this->getRawType(),
1060 'amount' => $this->amount,
1061 'voucher' => $voucher_path,
1062 'category' => array(
1063 'id' => $this->type->id,
1064 'label' => $this->type->libelle
1065 ),
1066 'payment' => $payment
1067 );
1068
1069 if ($this->_member !== null) {
1070 $m = new Adherent($this->zdb, (int)$this->_member);
1071 $member = array(
1072 'id' => (int)$this->_member,
1073 'name' => $m->sfullname,
1074 'email' => $m->email,
1075 'organization' => ($m->isCompany() ? 1 : 0),
1076 'status' => array(
1077 'id' => $m->status,
1078 'label' => $m->sstatus
1079 ),
1080 'country' => $m->country
1081 );
1082
1083 if ($m->isCompany()) {
1084 $member['organization_name'] = $m->company_name;
1085 }
1086
1087 $contrib['member'] = $member;
1088 }
1089
1090 if ($extra !== null && is_array($extra)) {
1091 $contrib = array_merge($contrib, $extra);
1092 }
1093
1094 $res = $es->send($contrib);
1095
1096 if ($res !== true) {
1097 Analog::log(
1098 'An error occurred calling post contribution ' .
1099 "script:\n" . $es->getOutput(),
1100 Analog::ERROR
1101 );
1102 $res = _T("Contribution information") . "\n";
1103 $res .= print_r($contrib, true);
1104 $res .= "\n\n" . _T("Script output") . "\n";
1105 $res .= $es->getOutput();
1106 }
1107
1108 return $res;
1109 }
1110 /**
1111 * Get raw contribution type
1112 *
1113 * @return string
1114 */
1115 public function getRawType()
1116 {
1117 if ($this->isFee()) {
1118 return 'membership';
1119 } else {
1120 return 'donation';
1121 }
1122 }
1123
1124 /**
1125 * Get contribution type label
1126 *
1127 * @return string
1128 */
1129 public function getTypeLabel()
1130 {
1131 if ($this->isFee()) {
1132 return _T("Membership");
1133 } else {
1134 return _T("Donation");
1135 }
1136 }
1137
1138 /**
1139 * Get payment type label
1140 *
1141 * @param boolean $translated Whether to translate
1142 *
1143 * @return string
1144 */
1145 public function getPaymentType(bool $translated = false): string
1146 {
1147 if ($this->_payment_type === null) {
1148 return '-';
1149 }
1150
1151 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1152 return $ptype->getName($translated);
1153 }
1154
1155 /**
1156 * Global getter method
1157 *
1158 * @param string $name name of the property we want to retrieve
1159 *
1160 * @return mixed the called property
1161 */
1162 public function __get($name)
1163 {
1164
1165 $forbidden = array('is_cotis');
1166 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1167 'raw_begin_date', 'raw_end_date'
1168 );
1169
1170 $rname = '_' . $name;
1171
1172 if (in_array($name, $forbidden)) {
1173 Analog::log(
1174 "Call to __get for '$name' is forbidden!",
1175 Analog::WARNING
1176 );
1177
1178 switch ($name) {
1179 case 'is_cotis':
1180 return $this->isFee();
1181 default:
1182 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1183 }
1184 } elseif (
1185 property_exists($this, $rname)
1186 || in_array($name, $virtuals)
1187 ) {
1188 switch ($name) {
1189 case 'raw_date':
1190 case 'raw_begin_date':
1191 case 'raw_end_date':
1192 $rname = '_' . substr($name, 4);
1193 if ($this->$rname !== null && $this->$rname != '') {
1194 try {
1195 $d = new \DateTime($this->$rname);
1196 return $d;
1197 } catch (Throwable $e) {
1198 //oops, we've got a bad date :/
1199 Analog::log(
1200 'Bad date (' . $this->$rname . ') | ' .
1201 $e->getMessage(),
1202 Analog::INFO
1203 );
1204 throw $e;
1205 }
1206 }
1207 break;
1208 case 'date':
1209 case 'begin_date':
1210 case 'end_date':
1211 if ($this->$rname !== null && $this->$rname != '') {
1212 try {
1213 $d = new \DateTime($this->$rname);
1214 return $d->format(__("Y-m-d"));
1215 } catch (Throwable $e) {
1216 //oops, we've got a bad date :/
1217 Analog::log(
1218 'Bad date (' . $this->$rname . ') | ' .
1219 $e->getMessage(),
1220 Analog::INFO
1221 );
1222 return $this->$rname;
1223 }
1224 }
1225 break;
1226 case 'duration':
1227 if ($this->_is_cotis) {
1228 // Caution : the end_date stored is actually the due date.
1229 // Adding a day to compute the next_begin_date is required
1230 // to return the right number of months.
1231 $next_begin_date = new \DateTime($this->_end_date ?? $this->_begin_date);
1232 $next_begin_date->add(new \DateInterval('P1D'));
1233 $begin_date = new \DateTime($this->_begin_date);
1234 $diff = $next_begin_date->diff($begin_date);
1235 return (int)$diff->format('%y') * 12 + (int)$diff->format('%m');
1236 } else {
1237 return '';
1238 }
1239 case 'spayment_type':
1240 return $this->getPaymentType(true);
1241 case 'model':
1242 if ($this->_is_cotis === null) {
1243 return null;
1244 }
1245 return ($this->isFee()) ?
1246 PdfModel::INVOICE_MODEL : PdfModel::RECEIPT_MODEL;
1247 default:
1248 return $this->$rname;
1249 }
1250 } else {
1251 Analog::log(
1252 "Unknown property '$rname'",
1253 Analog::WARNING
1254 );
1255 return null;
1256 }
1257 }
1258
1259 /**
1260 * Global isset method
1261 * Required for twig to access properties via __get
1262 *
1263 * @param string $name name of the property we want to retrieve
1264 *
1265 * @return bool
1266 */
1267 public function __isset($name)
1268 {
1269 $forbidden = array('is_cotis');
1270 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1271 'raw_begin_date', 'raw_end_date'
1272 );
1273
1274 $rname = '_' . $name;
1275
1276 if (in_array($name, $forbidden)) {
1277 switch ($name) {
1278 case 'is_cotis':
1279 return true;
1280 }
1281 } elseif (
1282 property_exists($this, $rname)
1283 || in_array($name, $virtuals)
1284 ) {
1285 return true;
1286 }
1287
1288 return false;
1289 }
1290
1291
1292 /**
1293 * Global setter method
1294 *
1295 * @param string $name name of the property we want to assign a value to
1296 * @param mixed $value a relevant value for the property
1297 *
1298 * @return void
1299 */
1300 public function __set($name, $value)
1301 {
1302 global $preferences;
1303
1304 $forbidden = array('fields', 'is_cotis', 'end_date');
1305
1306 if (!in_array($name, $forbidden)) {
1307 $rname = '_' . $name;
1308 switch ($name) {
1309 case 'transaction':
1310 if (is_int($value)) {
1311 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1312 } else {
1313 Analog::log(
1314 'Trying to set a transaction from an id that is not an integer.',
1315 Analog::WARNING
1316 );
1317 }
1318 break;
1319 case 'type':
1320 if (is_int($value)) {
1321 //set type
1322 $this->$rname = new ContributionsTypes($this->zdb, $value);
1323 //set is_cotis according to type
1324 if ($this->$rname->extension == 1) {
1325 $this->_is_cotis = true;
1326 } else {
1327 $this->_is_cotis = false;
1328 }
1329 } else {
1330 Analog::log(
1331 'Trying to set a type from an id that is not an integer.',
1332 Analog::WARNING
1333 );
1334 }
1335 break;
1336 case 'begin_date':
1337 try {
1338 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1339 if ($d === false) {
1340 throw new \Exception('Incorrect format');
1341 }
1342 $this->_begin_date = $d->format('Y-m-d');
1343 } catch (Throwable $e) {
1344 Analog::log(
1345 'Wrong date format. field: ' . $name .
1346 ', value: ' . $value . ', expected fmt: ' .
1347 __("Y-m-d") . ' | ' . $e->getMessage(),
1348 Analog::INFO
1349 );
1350 $this->errors[] = str_replace(
1351 array(
1352 '%date_format',
1353 '%field'
1354 ),
1355 array(
1356 __("Y-m-d"),
1357 $this->_fields['date_debut_cotis']['label']
1358 ),
1359 _T("- Wrong date format (%date_format) for %field!")
1360 );
1361 }
1362 break;
1363 case 'amount':
1364 if (is_numeric($value) && $value > 0) {
1365 $this->$rname = $value;
1366 } else {
1367 Analog::log(
1368 'Trying to set an amount with a non numeric value, ' .
1369 'or with a zero value',
1370 Analog::WARNING
1371 );
1372 }
1373 break;
1374 case 'member':
1375 if (is_int($value)) {
1376 //set type
1377 $this->$rname = $value;
1378 }
1379 break;
1380 case 'payment_type':
1381 $ptypes = new PaymentTypes(
1382 $this->zdb,
1383 $preferences,
1384 $this->login
1385 );
1386 $list = $ptypes->getList();
1387 if (isset($list[$value])) {
1388 $this->_payment_type = $value;
1389 } else {
1390 Analog::log(
1391 'Unknown payment type ' . $value,
1392 Analog::WARNING
1393 );
1394 }
1395 break;
1396 default:
1397 Analog::log(
1398 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1399 $name . ')',
1400 Analog::WARNING
1401 );
1402 break;
1403 }
1404 }
1405 }
1406
1407 /**
1408 * Flag creation mail sending
1409 *
1410 * @param boolean $send True (default) to send creation email
1411 *
1412 * @return Contribution
1413 */
1414 public function setSendmail(bool $send = true)
1415 {
1416 $this->sendmail = $send;
1417 return $this;
1418 }
1419
1420 /**
1421 * Should we send administrative emails to member?
1422 *
1423 * @return boolean
1424 */
1425 public function sendEMail()
1426 {
1427 return $this->sendmail;
1428 }
1429
1430 /**
1431 * Handle files (dynamics files)
1432 *
1433 * @param array $files Files sent
1434 *
1435 * @return array|true
1436 */
1437 public function handleFiles($files)
1438 {
1439 $this->errors = [];
1440
1441 $this->dynamicsFiles($files);
1442
1443 if (count($this->errors) > 0) {
1444 Analog::log(
1445 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1446 print_r($this->errors, true),
1447 Analog::ERROR
1448 );
1449 return $this->errors;
1450 } else {
1451 return true;
1452 }
1453 }
1454
1455 /**
1456 * Get required fields list
1457 *
1458 * @return array
1459 */
1460 public function getRequired(): array
1461 {
1462 return [
1463 'id_type_cotis' => 1,
1464 'id_adh' => 1,
1465 'date_enreg' => 1,
1466 'date_debut_cotis' => 1,
1467 'date_fin_cotis' => $this->isFee() ? 1 : 0,
1468 'montant_cotis' => $this->isFee() ? 1 : 0
1469 ];
1470 }
1471
1472 /**
1473 * Can current logged-in user display contribution
1474 *
1475 * @param Login $login Login instance
1476 *
1477 * @return boolean
1478 */
1479 public function canShow(Login $login): bool
1480 {
1481 //non-logged-in members cannot show contributions
1482 if (!$login->isLogged()) {
1483 return false;
1484 }
1485
1486 //admin and staff users can edit, as well as member itself
1487 if (!$this->id || $login->id == $this->_member || $login->isAdmin() || $login->isStaff()) {
1488 return true;
1489 }
1490
1491 //parent can see their children contributions
1492 $parent = new Adherent($this->zdb);
1493 $parent
1494 ->disableAllDeps()
1495 ->enableDep('children')
1496 ->load($this->login->id);
1497 if ($parent->hasChildren()) {
1498 foreach ($parent->children as $child) {
1499 if ($child->id === $this->_member) {
1500 return true;
1501 }
1502 }
1503 return false;
1504 }
1505
1506 return false;
1507 }
1508 }