]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
Some phpstan lvl 4 checks
[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()) {
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)) {
478 $this->_amount = $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 $d = new \DateTime($result->date_debut_cotis);
607
608 return _T("- Membership period overlaps period starting at ") .
609 $d->format(__("Y-m-d"));
610 }
611 return true;
612 } catch (Throwable $e) {
613 Analog::log(
614 'An error occurred checking overlapping fee. ' . $e->getMessage(),
615 Analog::ERROR
616 );
617 throw $e;
618 }
619 }
620
621 /**
622 * Store the contribution
623 *
624 * @return boolean
625 */
626 public function store()
627 {
628 global $hist, $emitter;
629
630 $event = null;
631
632 if (count($this->errors) > 0) {
633 throw new \RuntimeException(
634 'Existing errors prevents storing contribution: ' .
635 print_r($this->errors, true)
636 );
637 }
638
639 try {
640 $this->zdb->connection->beginTransaction();
641 $values = array();
642 $fields = self::getDbFields($this->zdb);
643 foreach ($fields as $field) {
644 $prop = '_' . $this->_fields[$field]['propname'];
645 switch ($field) {
646 case ContributionsTypes::PK:
647 case Transaction::PK:
648 if (isset($this->$prop)) {
649 $values[$field] = $this->$prop->id;
650 }
651 break;
652 default:
653 $values[$field] = $this->$prop;
654 break;
655 }
656 }
657
658 //no end date, let's take database defaults
659 if (!$this->isFee() && !$this->_end_date) {
660 unset($values['date_fin_cotis']);
661 }
662
663 if (!isset($this->_id) || $this->_id == '') {
664 //we're inserting a new contribution
665 unset($values[self::PK]);
666
667 $insert = $this->zdb->insert(self::TABLE);
668 $insert->values($values);
669 $add = $this->zdb->execute($insert);
670
671 if ($add->count() > 0) {
672 $this->_id = $this->zdb->getLastGeneratedValue($this);
673
674 // logging
675 $hist->add(
676 _T("Contribution added"),
677 Adherent::getSName($this->zdb, $this->_member)
678 );
679 $event = 'contribution.add';
680 } else {
681 $hist->add(_T("Fail to add new contribution."));
682 throw new \Exception(
683 'An error occurred inserting new contribution!'
684 );
685 }
686 } else {
687 //we're editing an existing contribution
688 $update = $this->zdb->update(self::TABLE);
689 $update->set($values)->where([self::PK => $this->_id]);
690 $edit = $this->zdb->execute($update);
691
692 //edit == 0 does not mean there were an error, but that there
693 //were nothing to change
694 if ($edit->count() > 0) {
695 $hist->add(
696 _T("Contribution updated"),
697 Adherent::getSName($this->zdb, $this->_member)
698 );
699 }
700
701 if ($edit === false) {
702 throw new \Exception(
703 'An error occurred updating contribution # ' . $this->_id . '!'
704 );
705 }
706 $event = 'contribution.edit';
707 }
708 //update deadline
709 if ($this->isFee()) {
710 $this->updateDeadline();
711 }
712
713 //dynamic fields
714 $this->dynamicsStore(true);
715
716 $this->zdb->connection->commit();
717 $this->_orig_amount = $this->_amount;
718
719 //send event at the end of process, once all has been stored
720 if ($event !== null) {
721 $emitter->dispatch(new GaletteEvent($event, $this));
722 }
723
724 return true;
725 } catch (Throwable $e) {
726 if ($this->zdb->connection->inTransaction()) {
727 $this->zdb->connection->rollBack();
728 }
729 throw $e;
730 }
731 }
732
733 /**
734 * Update member dead line
735 *
736 * @return boolean
737 */
738 private function updateDeadline()
739 {
740 try {
741 $due_date = self::getDueDate($this->zdb, $this->_member);
742
743 if ($due_date != '') {
744 $due_date_update = $due_date;
745 } else {
746 $due_date_update = new Expression('NULL');
747 }
748
749 $update = $this->zdb->update(Adherent::TABLE);
750 $update->set(
751 array('date_echeance' => $due_date_update)
752 )->where(
753 [Adherent::PK => $this->_member]
754 );
755 $this->zdb->execute($update);
756 return true;
757 } catch (Throwable $e) {
758 Analog::log(
759 'An error occurred updating member ' . $this->_member .
760 '\'s deadline |' .
761 $e->getMessage(),
762 Analog::ERROR
763 );
764 throw $e;
765 }
766 }
767
768 /**
769 * Remove contribution from database
770 *
771 * @param boolean $transaction Activate transaction mode (defaults to true)
772 *
773 * @return boolean
774 */
775 public function remove($transaction = true)
776 {
777 global $emitter;
778
779 try {
780 if ($transaction) {
781 $this->zdb->connection->beginTransaction();
782 }
783
784 $delete = $this->zdb->delete(self::TABLE);
785 $delete->where([self::PK => $this->_id]);
786 $del = $this->zdb->execute($delete);
787 if ($del->count() > 0) {
788 $this->updateDeadline();
789 $this->dynamicsRemove(true);
790 } else {
791 Analog::log(
792 'Contribution has not been removed!',
793 Analog::WARNING
794 );
795 return false;
796 }
797 if ($transaction) {
798 $this->zdb->connection->commit();
799 }
800 $emitter->dispatch(new GaletteEvent('contribution.remove', $this));
801 return true;
802 } catch (Throwable $e) {
803 if ($transaction) {
804 $this->zdb->connection->rollBack();
805 }
806 Analog::log(
807 'An error occurred trying to remove contribution #' .
808 $this->_id . ' | ' . $e->getMessage(),
809 Analog::ERROR
810 );
811 throw $e;
812 }
813 }
814
815 /**
816 * Get field label
817 *
818 * @param string $field Field name
819 *
820 * @return string
821 */
822 public function getFieldLabel($field)
823 {
824 $label = $this->_fields[$field]['label'];
825 if ($this->isFee() && $field == 'date_debut_cotis') {
826 $label = $this->_fields[$field]['cotlabel'];
827 }
828 //replace "&nbsp;"
829 $label = str_replace('&nbsp;', ' ', $label);
830 //remove trailing ':' and then trim
831 $label = trim(trim($label, ':'));
832 return $label;
833 }
834
835 /**
836 * Retrieve fields from database
837 *
838 * @param Db $zdb Database instance
839 *
840 * @return array
841 */
842 public static function getDbFields(Db $zdb)
843 {
844 $columns = $zdb->getColumns(self::TABLE);
845 $fields = array();
846 foreach ($columns as $col) {
847 $fields[] = $col->getName();
848 }
849 return $fields;
850 }
851
852 /**
853 * Get the relevant CSS class for current contribution
854 *
855 * @return string current contribution row class
856 */
857 public function getRowClass()
858 {
859 return ($this->_end_date != $this->_begin_date && $this->_is_cotis) ?
860 'cotis-normal' : 'cotis-give';
861 }
862
863 /**
864 * Retrieve member due date
865 *
866 * @param Db $zdb Database instance
867 * @param integer $member_id Member identifier
868 *
869 * @return string
870 */
871 public static function getDueDate(Db $zdb, $member_id)
872 {
873 if (!$member_id) {
874 return '';
875 }
876 try {
877 $select = $zdb->select(self::TABLE, 'c');
878 $select->columns(
879 array(
880 'max_date' => new Expression('MAX(date_fin_cotis)')
881 )
882 )->join(
883 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
884 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
885 array()
886 )->where(
887 [Adherent::PK => $member_id]
888 )->where(
889 array('cotis_extension' => new Expression('true'))
890 );
891
892 $results = $zdb->execute($select);
893 $result = $results->current();
894 $due_date = $result->max_date;
895
896 //avoid bad dates in postgres and bad mysql return from zenddb
897 if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
898 $due_date = '';
899 }
900 return $due_date;
901 } catch (Throwable $e) {
902 Analog::log(
903 'An error occurred trying to retrieve member\'s due date',
904 Analog::ERROR
905 );
906 throw $e;
907 }
908 }
909
910 /**
911 * Detach a contribution from a transaction
912 *
913 * @param Db $zdb Database instance
914 * @param Login $login Login instance
915 * @param int $trans_id Transaction identifier
916 * @param int $contrib_id Contribution identifier
917 *
918 * @return boolean
919 */
920 public static function unsetTransactionPart(Db $zdb, Login $login, $trans_id, $contrib_id)
921 {
922 try {
923 //first, we check if contribution is part of transaction
924 $c = new Contribution($zdb, $login, (int)$contrib_id);
925 if ($c->isTransactionPartOf($trans_id)) {
926 $update = $zdb->update(self::TABLE);
927 $update->set(
928 array(Transaction::PK => null)
929 )->where(
930 [self::PK => $contrib_id]
931 );
932 $zdb->execute($update);
933 return true;
934 } else {
935 Analog::log(
936 'Contribution #' . $contrib_id .
937 ' is not actually part of transaction #' . $trans_id,
938 Analog::WARNING
939 );
940 return false;
941 }
942 } catch (Throwable $e) {
943 Analog::log(
944 'Unable to detach contribution #' . $contrib_id .
945 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
946 Analog::ERROR
947 );
948 throw $e;
949 }
950 }
951
952 /**
953 * Set a contribution as a transaction part
954 *
955 * @param Db $zdb Database instance
956 * @param int $trans_id Transaction identifier
957 * @param int $contrib_id Contribution identifier
958 *
959 * @return boolean
960 */
961 public static function setTransactionPart(Db $zdb, $trans_id, $contrib_id)
962 {
963 try {
964 $update = $zdb->update(self::TABLE);
965 $update->set(
966 array(Transaction::PK => $trans_id)
967 )->where([self::PK => $contrib_id]);
968
969 $zdb->execute($update);
970 return true;
971 } catch (Throwable $e) {
972 Analog::log(
973 'Unable to attach contribution #' . $contrib_id .
974 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
975 Analog::ERROR
976 );
977 throw $e;
978 }
979 }
980
981 /**
982 * Is current contribution a membership fee
983 *
984 * @return boolean
985 */
986 public function isFee()
987 {
988 return $this->_is_cotis;
989 }
990
991 /**
992 * Is current contribution part of specified transaction
993 *
994 * @param int $id Transaction identifier
995 *
996 * @return boolean
997 */
998 public function isTransactionPartOf($id)
999 {
1000 if ($this->isTransactionPart()) {
1001 return $id == $this->_transaction->id;
1002 } else {
1003 return false;
1004 }
1005 }
1006
1007 /**
1008 * Is current contribution part of transaction
1009 *
1010 * @return boolean
1011 */
1012 public function isTransactionPart()
1013 {
1014 return $this->_transaction != null;
1015 }
1016
1017 /**
1018 * Execute post contribution script
1019 *
1020 * @param ExternalScript $es External script to execute
1021 * @param array $extra Extra information on contribution
1022 * Defaults to null
1023 * @param array $pextra Extra information on payment
1024 * Defaults to null
1025 *
1026 * @return mixed Script return value on success, values and script output on fail
1027 */
1028 public function executePostScript(
1029 ExternalScript $es,
1030 $extra = null,
1031 $pextra = null
1032 ) {
1033 global $preferences;
1034
1035 $payment = array(
1036 'type' => $this->getPaymentType()
1037 );
1038
1039 if ($pextra !== null && is_array($pextra)) {
1040 $payment = array_merge($payment, $pextra);
1041 }
1042
1043 if (!file_exists(GALETTE_CACHE_DIR . '/pdf_contribs')) {
1044 @mkdir(GALETTE_CACHE_DIR . '/pdf_contribs');
1045 }
1046
1047 $voucher_path = null;
1048 if ($this->_id !== null) {
1049 $voucher = new PdfContribution($this, $this->zdb, $preferences);
1050 $voucher->store(GALETTE_CACHE_DIR . '/pdf_contribs');
1051 $voucher_path = $voucher->getPath();
1052 }
1053
1054 $contrib = array(
1055 'id' => (int)$this->_id,
1056 'date' => $this->_date,
1057 'type' => $this->getRawType(),
1058 'amount' => $this->amount,
1059 'voucher' => $voucher_path,
1060 'category' => array(
1061 'id' => $this->type->id,
1062 'label' => $this->type->libelle
1063 ),
1064 'payment' => $payment
1065 );
1066
1067 if ($this->_member !== null) {
1068 $m = new Adherent($this->zdb, (int)$this->_member);
1069 $member = array(
1070 'id' => (int)$this->_member,
1071 'name' => $m->sfullname,
1072 'email' => $m->email,
1073 'organization' => ($m->isCompany() ? 1 : 0),
1074 'status' => array(
1075 'id' => $m->status,
1076 'label' => $m->sstatus
1077 ),
1078 'country' => $m->country
1079 );
1080
1081 if ($m->isCompany()) {
1082 $member['organization_name'] = $m->company_name;
1083 }
1084
1085 $contrib['member'] = $member;
1086 }
1087
1088 if ($extra !== null && is_array($extra)) {
1089 $contrib = array_merge($contrib, $extra);
1090 }
1091
1092 $res = $es->send($contrib);
1093
1094 if ($res !== true) {
1095 Analog::log(
1096 'An error occurred calling post contribution ' .
1097 "script:\n" . $es->getOutput(),
1098 Analog::ERROR
1099 );
1100 $res = _T("Contribution information") . "\n";
1101 $res .= print_r($contrib, true);
1102 $res .= "\n\n" . _T("Script output") . "\n";
1103 $res .= $es->getOutput();
1104 }
1105
1106 return $res;
1107 }
1108 /**
1109 * Get raw contribution type
1110 *
1111 * @return string
1112 */
1113 public function getRawType()
1114 {
1115 if ($this->isFee()) {
1116 return 'membership';
1117 } else {
1118 return 'donation';
1119 }
1120 }
1121
1122 /**
1123 * Get contribution type label
1124 *
1125 * @return string
1126 */
1127 public function getTypeLabel()
1128 {
1129 if ($this->isFee()) {
1130 return _T("Membership");
1131 } else {
1132 return _T("Donation");
1133 }
1134 }
1135
1136 /**
1137 * Get payment type label
1138 *
1139 * @param boolean $translated Whether to translate
1140 *
1141 * @return string
1142 */
1143 public function getPaymentType(bool $translated = false): string
1144 {
1145 if ($this->_payment_type === null) {
1146 return '-';
1147 }
1148
1149 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1150 return $ptype->getName($translated);
1151 }
1152
1153 /**
1154 * Global getter method
1155 *
1156 * @param string $name name of the property we want to retrieve
1157 *
1158 * @return mixed the called property
1159 */
1160 public function __get($name)
1161 {
1162
1163 $forbidden = array('is_cotis');
1164 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1165 'raw_begin_date', 'raw_end_date'
1166 );
1167
1168 $rname = '_' . $name;
1169
1170 if (in_array($name, $forbidden)) {
1171 Analog::log(
1172 "Call to __get for '$name' is forbidden!",
1173 Analog::WARNING
1174 );
1175
1176 switch ($name) {
1177 case 'is_cotis':
1178 return $this->isFee();
1179 default:
1180 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1181 }
1182 } elseif (
1183 property_exists($this, $rname)
1184 || in_array($name, $virtuals)
1185 ) {
1186 switch ($name) {
1187 case 'raw_date':
1188 case 'raw_begin_date':
1189 case 'raw_end_date':
1190 $rname = '_' . substr($name, 4);
1191 if ($this->$rname !== null && $this->$rname != '') {
1192 try {
1193 $d = new \DateTime($this->$rname);
1194 return $d;
1195 } catch (Throwable $e) {
1196 //oops, we've got a bad date :/
1197 Analog::log(
1198 'Bad date (' . $this->$rname . ') | ' .
1199 $e->getMessage(),
1200 Analog::INFO
1201 );
1202 throw $e;
1203 }
1204 }
1205 break;
1206 case 'date':
1207 case 'begin_date':
1208 case 'end_date':
1209 if ($this->$rname !== null && $this->$rname != '') {
1210 try {
1211 $d = new \DateTime($this->$rname);
1212 return $d->format(__("Y-m-d"));
1213 } catch (Throwable $e) {
1214 //oops, we've got a bad date :/
1215 Analog::log(
1216 'Bad date (' . $this->$rname . ') | ' .
1217 $e->getMessage(),
1218 Analog::INFO
1219 );
1220 return $this->$rname;
1221 }
1222 }
1223 break;
1224 case 'duration':
1225 if ($this->_is_cotis) {
1226 // Caution : the end_date stored is actually the due date.
1227 // Adding a day to compute the next_begin_date is required
1228 // to return the right number of months.
1229 $next_begin_date = new \DateTime($this->_end_date ?? $this->_begin_date);
1230 $next_begin_date->add(new \DateInterval('P1D'));
1231 $begin_date = new \DateTime($this->_begin_date);
1232 $diff = $next_begin_date->diff($begin_date);
1233 return (int)$diff->format('%y') * 12 + (int)$diff->format('%m');
1234 } else {
1235 return '';
1236 }
1237 case 'spayment_type':
1238 return $this->getPaymentType(true);
1239 case 'model':
1240 if ($this->_is_cotis === null) {
1241 return null;
1242 }
1243 return ($this->isFee()) ?
1244 PdfModel::INVOICE_MODEL : PdfModel::RECEIPT_MODEL;
1245 default:
1246 return $this->$rname;
1247 }
1248 } else {
1249 Analog::log(
1250 "Unknown property '$rname'",
1251 Analog::WARNING
1252 );
1253 return null;
1254 }
1255 }
1256
1257 /**
1258 * Global isset method
1259 * Required for twig to access properties via __get
1260 *
1261 * @param string $name name of the property we want to retrieve
1262 *
1263 * @return bool
1264 */
1265 public function __isset($name)
1266 {
1267 $forbidden = array('is_cotis');
1268 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1269 'raw_begin_date', 'raw_end_date'
1270 );
1271
1272 $rname = '_' . $name;
1273
1274 if (in_array($name, $forbidden)) {
1275 switch ($name) {
1276 case 'is_cotis':
1277 return true;
1278 }
1279 } elseif (
1280 property_exists($this, $rname)
1281 || in_array($name, $virtuals)
1282 ) {
1283 return true;
1284 }
1285
1286 return false;
1287 }
1288
1289
1290 /**
1291 * Global setter method
1292 *
1293 * @param string $name name of the property we want to assign a value to
1294 * @param mixed $value a relevant value for the property
1295 *
1296 * @return void
1297 */
1298 public function __set($name, $value)
1299 {
1300 global $preferences;
1301
1302 $forbidden = array('fields', 'is_cotis', 'end_date');
1303
1304 if (!in_array($name, $forbidden)) {
1305 $rname = '_' . $name;
1306 switch ($name) {
1307 case 'transaction':
1308 if (is_int($value)) {
1309 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1310 } else {
1311 Analog::log(
1312 'Trying to set a transaction from an id that is not an integer.',
1313 Analog::WARNING
1314 );
1315 }
1316 break;
1317 case 'type':
1318 if (is_int($value)) {
1319 //set type
1320 $this->$rname = new ContributionsTypes($this->zdb, $value);
1321 //set is_cotis according to type
1322 if ($this->$rname->extension == 1) {
1323 $this->_is_cotis = true;
1324 } else {
1325 $this->_is_cotis = false;
1326 }
1327 } else {
1328 Analog::log(
1329 'Trying to set a type from an id that is not an integer.',
1330 Analog::WARNING
1331 );
1332 }
1333 break;
1334 case 'begin_date':
1335 try {
1336 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1337 if ($d === false) {
1338 throw new \Exception('Incorrect format');
1339 }
1340 $this->_begin_date = $d->format('Y-m-d');
1341 } catch (Throwable $e) {
1342 Analog::log(
1343 'Wrong date format. field: ' . $name .
1344 ', value: ' . $value . ', expected fmt: ' .
1345 __("Y-m-d") . ' | ' . $e->getMessage(),
1346 Analog::INFO
1347 );
1348 $this->errors[] = str_replace(
1349 array(
1350 '%date_format',
1351 '%field'
1352 ),
1353 array(
1354 __("Y-m-d"),
1355 $this->_fields['date_debut_cotis']['label']
1356 ),
1357 _T("- Wrong date format (%date_format) for %field!")
1358 );
1359 }
1360 break;
1361 case 'amount':
1362 if (is_numeric($value) && $value > 0) {
1363 $this->$rname = $value;
1364 } else {
1365 Analog::log(
1366 'Trying to set an amount with a non numeric value, ' .
1367 'or with a zero value',
1368 Analog::WARNING
1369 );
1370 }
1371 break;
1372 case 'member':
1373 if (is_int($value)) {
1374 //set type
1375 $this->$rname = $value;
1376 }
1377 break;
1378 case 'payment_type':
1379 $ptypes = new PaymentTypes(
1380 $this->zdb,
1381 $preferences,
1382 $this->login
1383 );
1384 $list = $ptypes->getList();
1385 if (isset($list[$value])) {
1386 $this->_payment_type = $value;
1387 } else {
1388 Analog::log(
1389 'Unknown payment type ' . $value,
1390 Analog::WARNING
1391 );
1392 }
1393 break;
1394 default:
1395 Analog::log(
1396 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1397 $name . ')',
1398 Analog::WARNING
1399 );
1400 break;
1401 }
1402 }
1403 }
1404
1405 /**
1406 * Flag creation mail sending
1407 *
1408 * @param boolean $send True (default) to send creation email
1409 *
1410 * @return Contribution
1411 */
1412 public function setSendmail(bool $send = true)
1413 {
1414 $this->sendmail = $send;
1415 return $this;
1416 }
1417
1418 /**
1419 * Should we send administrative emails to member?
1420 *
1421 * @return boolean
1422 */
1423 public function sendEMail()
1424 {
1425 return $this->sendmail;
1426 }
1427
1428 /**
1429 * Handle files (dynamics files)
1430 *
1431 * @param array $files Files sent
1432 *
1433 * @return array|true
1434 */
1435 public function handleFiles($files)
1436 {
1437 $this->errors = [];
1438
1439 $this->dynamicsFiles($files);
1440
1441 if (count($this->errors) > 0) {
1442 Analog::log(
1443 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1444 print_r($this->errors, true),
1445 Analog::ERROR
1446 );
1447 return $this->errors;
1448 } else {
1449 return true;
1450 }
1451 }
1452
1453 /**
1454 * Get required fields list
1455 *
1456 * @return array
1457 */
1458 public function getRequired(): array
1459 {
1460 return [
1461 'id_type_cotis' => 1,
1462 'id_adh' => 1,
1463 'date_enreg' => 1,
1464 'date_debut_cotis' => 1,
1465 'date_fin_cotis' => $this->isFee() ? 1 : 0,
1466 'montant_cotis' => $this->isFee() ? 1 : 0
1467 ];
1468 }
1469
1470 /**
1471 * Can current logged-in user display contribution
1472 *
1473 * @param Login $login Login instance
1474 *
1475 * @return boolean
1476 */
1477 public function canShow(Login $login): bool
1478 {
1479 //non-logged-in members cannot show contributions
1480 if (!$login->isLogged()) {
1481 return false;
1482 }
1483
1484 //admin and staff users can edit, as well as member itself
1485 if (!$this->id || $this->id && $login->id == $this->_member || $login->isAdmin() || $login->isStaff()) {
1486 return true;
1487 }
1488
1489 //parent can see their children contributions
1490 $parent = new Adherent($this->zdb);
1491 $parent
1492 ->disableAllDeps()
1493 ->enableDep('children')
1494 ->load($this->login->id);
1495 if ($parent->hasChildren()) {
1496 foreach ($parent->children as $child) {
1497 if ($child->id === $this->_member) {
1498 return true;
1499 }
1500 }
1501 return false;
1502 }
1503
1504 return false;
1505 }
1506 }