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