3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Contribution class for galette
7 * Manage membership fees and donations.
11 * Copyright © 2010-2023 The Galette Team
13 * This file is part of Galette (http://galette.tuxfamily.org).
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.
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.
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/>.
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
38 namespace Galette\Entity
;
42 use Galette\Events\GaletteEvent
;
43 use Galette\Features\HasEvent
;
46 use Laminas\Db\Sql\Expression
;
48 use Galette\Core\Login
;
49 use Galette\IO\ExternalScript
;
50 use Galette\IO\PdfContribution
;
51 use Galette\Repository\PaymentTypes
;
52 use Galette\Features\Dynamics
;
55 * Contribution class for galette
56 * Manage membership fees and donations.
61 * @author Johan Cwiklinski <johan@x-tnd.be>
62 * @copyright 2010-2023 The Galette Team
63 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
64 * @link http://galette.tuxfamily.org
65 * @since Available since 0.7dev - 2010-03-11
67 * @property integer $id
68 * @property string $date
69 * @property DateTime $raw_date
70 * @property integer $member
71 * @property ContributionsTypes|int $type
72 * @property double $amount
73 * @property integer $payment_type
74 * @property double $orig_amount
75 * @property string $info
76 * @property string $begin_date
77 * @property DateTime $raw_begin_date
78 * @property string $end_date
79 * @property DateTime $raw_end_date
80 * @property Transaction|null $transaction
81 * @property integer $extension
82 * @property integer $duration
83 * @property string $spayment_type
84 * @property integer $model
91 public const TABLE
= 'cotisations';
92 public const PK
= 'id_cotis';
94 public const TYPE_FEE
= 'fee';
95 public const TYPE_DONATION
= 'donation';
102 private $_payment_type;
103 private $_orig_amount;
105 private $_begin_date;
107 private $_transaction = null;
111 //fields list and their translation
121 private $sendmail = false;
124 * Default constructor
126 * @param Db $zdb Database
127 * @param Login $login Login instance
128 * @param null|int|array|ArrayObject $args Either a ResultSet row to load
129 * a specific contribution, or a type id
130 * to just instantiate object
132 public function __construct(Db
$zdb, Login
$login, $args = null)
135 $this->login
= $login;
138 $this->_payment_type
= (int)$preferences->pref_default_paymenttype
;
143 ->withoutDeleteEvent()
147 * Fields configuration. Each field is an array and must reflect:
150 * (string) property name
153 * I'd prefer a static private variable for this...
154 * But call to the _T function does not seem to be allowed there :/
156 $this->_fields
= array(
158 'label' => _T('Contribution id'), //not a field in the form
161 Adherent
::PK
=> array(
162 'label' => _T("Contributor:"),
163 'propname' => 'member'
165 ContributionsTypes
::PK
=> array(
166 'label' => _T("Contribution type:"),
169 'montant_cotis' => array(
170 'label' => _T("Amount:"),
171 'propname' => 'amount'
173 'type_paiement_cotis' => array(
174 'label' => _T("Payment type:"),
175 'propname' => 'payment_type'
177 'info_cotis' => array(
178 'label' => _T("Comments:"),
181 'date_enreg' => array(
182 'label' => _T('Date'), //not a field in the form
185 'date_debut_cotis' => array(
186 'label' => _T("Date of contribution:"),
187 'cotlabel' => _T("Start date of membership:"), //if contribution is a membership fee, label differs
188 'propname' => 'begin_date'
190 'date_fin_cotis' => array(
191 'label' => _T("End date of membership:"),
192 'propname' => 'end_date'
194 Transaction
::PK
=> array(
195 'label' => _T('Transaction ID'), //not a field in the form
196 'propname' => 'transaction'
198 //this one is not really a field, but is required in some cases...
199 //adding it here make more simple to check required fields
200 'duree_mois_cotis' => array(
201 'label' => _T("Membership extension:"),
202 'propname' => 'extension'
207 } elseif (is_array($args)) {
208 $this->_date
= date("Y-m-d");
209 if (isset($args['adh']) && $args['adh'] != '') {
210 $this->_member
= (int)$args['adh'];
212 if (isset($args['trans'])) {
213 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
214 if (!isset($this->_member
)) {
215 $this->_member
= (int)$this->_transaction
->member
;
217 $this->_amount
= $this->_transaction
->getMissingAmount();
219 $this->type
= (int)$args['type'];
220 //calculate begin date for membership fee
221 $this->_begin_date
= $this->_date
;
222 if ($this->_is_cotis
) {
223 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
224 if ($due_date != '') {
225 $now = new \
DateTime();
226 $due_date = new \
DateTime($due_date);
227 if ($due_date < $now) {
228 // Member didn't renew on time
229 $this->_begin_date
= $now->format('Y-m-d');
231 // Caution : the next_begin_date is the day after the due_date.
232 $next_begin_date = clone $due_date;
233 $next_begin_date->add(new \
DateInterval('P1D'));
234 $this->_begin_date
= $next_begin_date->format('Y-m-d');
237 $this->retrieveEndDate();
239 if (isset($args['payment_type'])) {
240 $this->_payment_type
= $args['payment_type'];
242 } elseif (is_object($args)) {
243 $this->loadFromRS($args);
246 $this->loadDynamicFields();
250 * Sets end contribution date
254 private function retrieveEndDate()
258 $now = new \
DateTime();
259 $begin_date = new \
DateTime($this->_begin_date
);
260 if ($preferences->pref_beg_membership
!= '') {
261 //case beginning of membership
262 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
263 $next_begin_date = new \
DateTime($begin_date->format('Y') . '-' . $m . '-' . $j);
264 while ($next_begin_date <= $begin_date) {
265 $next_begin_date->add(new \
DateInterval('P1Y'));
268 if ($preferences->pref_membership_offermonths
> 0) {
269 //count days until next membership begin date
270 $diff1 = (int)$now->diff($next_begin_date)->format('%a');
272 //count days between next membership begin date and offered months
273 $tdate = clone $next_begin_date;
274 $tdate->sub(new \
DateInterval('P' . $preferences->pref_membership_offermonths
. 'M'));
275 $diff2 = (int)$next_begin_date->diff($tdate)->format('%a');
277 //when number of days until next membership begin date is less than or equal to the offered months, it's free :)
278 if ($diff1 <= $diff2) {
279 $next_begin_date->add(new \
DateInterval('P1Y'));
283 // Caution : the end_date to retrieve is the day before the next_begin_date.
284 $end_date = clone $next_begin_date;
285 $end_date->sub(new \
DateInterval('P1D'));
286 $this->_end_date
= $end_date->format('Y-m-d');
287 } elseif ($preferences->pref_membership_ext
!= '') {
288 //case membership extension
289 if ($this->_extension
== null) {
290 $this->_extension
= $preferences->pref_membership_ext
;
292 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
293 // Caution : the end_date to retrieve is the day before the next_begin_date.
294 $next_begin_date = $begin_date->add($dext);
295 $end_date = clone $next_begin_date;
296 $end_date->sub(new \
DateInterval('P1D'));
297 $this->_end_date
= $end_date->format('Y-m-d');
299 throw new \
RuntimeException(
300 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
306 * Loads a contribution from its id
308 * @param int $id the identifier for the contribution to load
310 * @return bool true if query succeed, false otherwise
312 public function load($id)
314 if (!$this->login
->isLogged() && $this->login
->id
== '') {
319 $select = $this->zdb
->select(self
::TABLE
, 'c');
321 array('a' => PREFIX_DB
. Adherent
::TABLE
),
322 'c.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
325 //restrict query on current member id if he's not admin nor staff member
326 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
329 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
331 ->equalTo('a.parent_id', $this->login
->id
)
334 ->equalTo('c.' . self
::PK
, $id)
337 $select->where
->equalTo(self
::PK
, $id);
340 $results = $this->zdb
->execute($select);
341 if ($results->count() > 0) {
342 $row = $results->current();
343 $this->loadFromRS($row);
347 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')',
352 } catch (Throwable
$e) {
354 'An error occurred attempting to load contribution #' . $id .
363 * Populate object from a resultset row
365 * @param ArrayObject $r the resultset row
369 private function loadFromRS(ArrayObject
$r)
372 $this->_id
= (int)$r->$pk;
373 $this->_date
= $r->date_enreg
;
374 $this->_amount
= (double)$r->montant_cotis
;
375 //save original amount, we need it for transactions parts calculations
376 $this->_orig_amount
= (double)$r->montant_cotis
;
377 $this->_payment_type
= $r->type_paiement_cotis
;
378 $this->_info
= $r->info_cotis
;
379 $this->_begin_date
= $r->date_debut_cotis
;
380 $end_date = $r->date_fin_cotis
;
381 //do not work with knows bad dates...
382 //the one with BC comes from 0.63/pgsql demo... Why the hell a so
383 //strange date? don't know :(
385 $end_date !== '0000-00-00'
386 && $end_date !== '1901-01-01'
387 && $end_date !== '0001-01-01 BC'
389 $this->_end_date
= $r->date_fin_cotis
;
391 $adhpk = Adherent
::PK
;
392 $this->_member
= (int)$r->$adhpk;
394 $transpk = Transaction
::PK
;
395 if ($r->$transpk != '') {
396 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
399 $this->type
= (int)$r->id_type_cotis
;
400 $this->loadDynamicFields();
404 * Check posted values validity
406 * @param array $values All values to check, basically the $_POST array
407 * after sending the form
408 * @param array $required Array of required fields
409 * @param array $disabled Array of disabled fields
413 public function check($values, $required, $disabled)
416 $this->errors
= array();
418 $fields = array_keys($this->_fields
);
419 foreach ($fields as $key) {
420 //first, let's sanitize values
421 $key = strtolower($key);
422 $prop = '_' . $this->_fields
[$key]['propname'];
424 if (isset($values[$key])) {
425 $value = trim($values[$key]);
430 // if the field is enabled, check it
431 if (!isset($disabled[$key])) {
432 // fill up the adherent structure
433 //$this->$prop = stripslashes($value); //not relevant here!
435 // now, check validity
439 case 'date_debut_cotis':
440 case 'date_fin_cotis':
443 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
445 //try with non localized date
446 $d = \DateTime
::createFromFormat("Y-m-d", $value);
448 throw new \
Exception('Incorrect format');
451 $this->$prop = $d->format('Y-m-d');
452 } catch (Throwable
$e) {
454 'Wrong date format. field: ' . $key .
455 ', value: ' . $value . ', expected fmt: ' .
456 __("Y-m-d") . ' | ' . $e->getMessage(),
459 $this->errors
[] = str_replace(
466 $this->_fields
[$key]['label']
468 _T("- Wrong date format (%date_format) for %field!")
475 $this->_member
= (int)$value;
478 case ContributionsTypes
::PK
:
480 $this->type
= (int)$value;
483 case 'montant_cotis':
484 $value = strtr($value, ',', '.');
485 if (!empty($value) ||
$value === '0') {
486 $this->_amount
= (double)$value;
488 if (!is_numeric($value) && $value !== '') {
489 $this->errors
[] = _T("- The amount must be an integer!");
492 case 'type_paiement_cotis':
493 $ptypes = new PaymentTypes(
498 $ptlist = $ptypes->getList();
499 if (isset($ptlist[$value])) {
500 $this->_payment_type
= $value;
502 $this->errors
[] = _T("- Unknown payment type");
506 $this->_info
= $value;
508 case Transaction
::PK
:
510 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
513 case 'duree_mois_cotis':
515 if (!is_numeric($value) ||
$value <= 0) {
516 $this->errors
[] = _T("- The duration must be a positive integer!");
518 $this->$prop = $value;
519 $this->retrieveEndDate();
526 // missing required fields?
527 foreach ($required as $key => $val) {
529 $prop = '_' . $this->_fields
[$key]['propname'];
531 !isset($disabled[$key])
532 && (!isset($this->$prop)
533 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
534 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
536 $this->errors
[] = str_replace(
538 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
539 _T("- Mandatory field %field empty.")
545 if ($this->_transaction
!= null && $this->_amount
!= null) {
546 $missing = $this->_transaction
->getMissingAmount();
547 //calculate new missing amount
548 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
550 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
554 if ($this->isFee() && count($this->errors
) == 0) {
555 $overlap = $this->checkOverlap();
556 if ($overlap !== true) {
557 //method directly return error message
558 $this->errors
[] = $overlap;
562 $this->dynamicsCheck($values, $required, $disabled);
564 if (count($this->errors
) > 0) {
566 'Some errors has been threw attempting to edit/store a contribution' .
567 print_r($this->errors
, true),
570 return $this->errors
;
573 'Contribution checked successfully.',
581 * Check that membership fees does not overlap
583 * @return boolean|string True if all is ok, false if error,
584 * error message if overlap
586 public function checkOverlap()
589 $select = $this->zdb
->select(self
::TABLE
, 'c');
590 //@phpstan-ignore-next-line
592 array('date_debut_cotis', 'date_fin_cotis')
594 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
595 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
597 )->where([Adherent
::PK
=> $this->_member
])
598 ->where(array('cotis_extension' => new Expression('true')))
600 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
601 ->lessThanOrEqualTo('date_debut_cotis', $this->_end_date
)
604 ->greaterThanOrEqualTo('date_fin_cotis', $this->_begin_date
)
605 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
607 if ($this->id
!= '') {
608 $select->where
->notEqualTo(self
::PK
, $this->id
);
611 $results = $this->zdb
->execute($select);
612 if ($results->count() > 0) {
613 $result = $results->current();
615 $d_begin = new \
DateTime($result->date_debut_cotis
);
616 $d_end = new \
DateTime($result->date_fin_cotis
);
618 if ($d_begin->format('m-d') == $d_end->format('m-d') && $result->date_fin_cotis
== $this->_begin_date
) {
619 //see https://bugs.galette.eu/issues/1762
623 return _T("- Membership period overlaps period starting at ") .
624 $d_begin->format(__("Y-m-d"));
627 } catch (Throwable
$e) {
629 'An error occurred checking overlapping fee. ' . $e->getMessage(),
637 * Store the contribution
641 public function store()
643 global $hist, $emitter;
647 if (count($this->errors
) > 0) {
648 throw new \
RuntimeException(
649 'Existing errors prevents storing contribution: ' .
650 print_r($this->errors
, true)
655 $this->zdb
->connection
->beginTransaction();
657 $fields = self
::getDbFields($this->zdb
);
658 foreach ($fields as $field) {
659 $prop = '_' . $this->_fields
[$field]['propname'];
661 case ContributionsTypes
::PK
:
662 case Transaction
::PK
:
663 if (isset($this->$prop)) {
664 $values[$field] = $this->$prop->id
;
668 $values[$field] = $this->$prop;
673 //no end date, let's take database defaults
674 if (!$this->isFee() && !$this->_end_date
) {
675 unset($values['date_fin_cotis']);
678 if (!isset($this->_id
) ||
$this->_id
== '') {
679 //we're inserting a new contribution
680 unset($values[self
::PK
]);
682 $insert = $this->zdb
->insert(self
::TABLE
);
683 $insert->values($values);
684 $add = $this->zdb
->execute($insert);
686 if ($add->count() > 0) {
687 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
691 _T("Contribution added"),
692 Adherent
::getSName($this->zdb
, $this->_member
)
694 $event = $this->getAddEventName();
696 $hist->add(_T("Fail to add new contribution."));
697 throw new \
Exception(
698 'An error occurred inserting new contribution!'
702 //we're editing an existing contribution
703 $update = $this->zdb
->update(self
::TABLE
);
704 $update->set($values)->where([self
::PK
=> $this->_id
]);
705 $edit = $this->zdb
->execute($update);
707 //edit == 0 does not mean there were an error, but that there
708 //were nothing to change
709 if ($edit->count() > 0) {
711 _T("Contribution updated"),
712 Adherent
::getSName($this->zdb
, $this->_member
)
716 $event = $this->getEditEventName();
719 if ($this->isFee()) {
720 $this->updateDeadline();
724 $this->dynamicsStore(true);
726 $this->zdb
->connection
->commit();
727 $this->_orig_amount
= $this->_amount
;
729 //send event at the end of process, once all has been stored
730 if ($event !== null && $this->areEventsEnabled()) {
731 $emitter->dispatch(new GaletteEvent($event, $this));
735 } catch (Throwable
$e) {
736 if ($this->zdb
->connection
->inTransaction()) {
737 $this->zdb
->connection
->rollBack();
744 * Update member dead line
748 private function updateDeadline()
751 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
753 if ($due_date != '') {
754 $due_date_update = $due_date;
756 $due_date_update = new Expression('NULL');
759 $update = $this->zdb
->update(Adherent
::TABLE
);
761 array('date_echeance' => $due_date_update)
763 [Adherent
::PK
=> $this->_member
]
765 $this->zdb
->execute($update);
767 } catch (Throwable
$e) {
769 'An error occurred updating member ' . $this->_member
.
779 * Remove contribution from database
781 * @param boolean $transaction Activate transaction mode (defaults to true)
785 public function remove($transaction = true)
791 $this->zdb
->connection
->beginTransaction();
794 $delete = $this->zdb
->delete(self
::TABLE
);
795 $delete->where([self
::PK
=> $this->_id
]);
796 $del = $this->zdb
->execute($delete);
797 if ($del->count() > 0) {
798 $this->updateDeadline();
799 $this->dynamicsRemove(true);
802 'Contribution has not been removed!',
808 $this->zdb
->connection
->commit();
810 $emitter->dispatch(new GaletteEvent('contribution.remove', $this));
812 } catch (Throwable
$e) {
814 $this->zdb
->connection
->rollBack();
817 'An error occurred trying to remove contribution #' .
818 $this->_id
. ' | ' . $e->getMessage(),
828 * @param string $field Field name
832 public function getFieldLabel($field)
834 $label = $this->_fields
[$field]['label'];
835 if ($this->isFee() && $field == 'date_debut_cotis') {
836 $label = $this->_fields
[$field]['cotlabel'];
839 $label = str_replace(' ', ' ', $label);
840 //remove trailing ':' and then trim
841 $label = trim(trim($label, ':'));
846 * Retrieve fields from database
848 * @param Db $zdb Database instance
852 public static function getDbFields(Db
$zdb)
854 $columns = $zdb->getColumns(self
::TABLE
);
856 foreach ($columns as $col) {
857 $fields[] = $col->getName();
863 * Get the relevant CSS class for current contribution
865 * @return string current contribution row class
867 public function getRowClass()
869 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
870 'cotis-normal' : 'cotis-give';
874 * Retrieve member due date
876 * @param Db $zdb Database instance
877 * @param integer $member_id Member identifier
881 public static function getDueDate(Db
$zdb, $member_id)
887 $select = $zdb->select(self
::TABLE
, 'c');
890 'max_date' => new Expression('MAX(date_fin_cotis)')
893 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
894 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
897 [Adherent
::PK
=> $member_id]
899 array('cotis_extension' => new Expression('true'))
902 $results = $zdb->execute($select);
903 $result = $results->current();
904 $due_date = $result->max_date
;
906 //avoid bad dates in postgres and bad mysql return from zenddb
907 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
911 } catch (Throwable
$e) {
913 'An error occurred trying to retrieve member\'s due date',
921 * Detach a contribution from a transaction
923 * @param Db $zdb Database instance
924 * @param Login $login Login instance
925 * @param int $trans_id Transaction identifier
926 * @param int $contrib_id Contribution identifier
930 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
933 //first, we check if contribution is part of transaction
934 $c = new Contribution($zdb, $login, (int)$contrib_id);
935 if ($c->isTransactionPartOf($trans_id)) {
936 $update = $zdb->update(self
::TABLE
);
938 array(Transaction
::PK
=> null)
940 [self
::PK
=> $contrib_id]
942 $zdb->execute($update);
946 'Contribution #' . $contrib_id .
947 ' is not actually part of transaction #' . $trans_id,
952 } catch (Throwable
$e) {
954 'Unable to detach contribution #' . $contrib_id .
955 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
963 * Set a contribution as a transaction part
965 * @param Db $zdb Database instance
966 * @param int $trans_id Transaction identifier
967 * @param int $contrib_id Contribution identifier
971 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
974 $update = $zdb->update(self
::TABLE
);
976 array(Transaction
::PK
=> $trans_id)
977 )->where([self
::PK
=> $contrib_id]);
979 $zdb->execute($update);
981 } catch (Throwable
$e) {
983 'Unable to attach contribution #' . $contrib_id .
984 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
992 * Is current contribution a membership fee
996 public function isFee()
998 return $this->_is_cotis
;
1002 * Is current contribution part of specified transaction
1004 * @param int $id Transaction identifier
1008 public function isTransactionPartOf($id)
1010 if ($this->isTransactionPart()) {
1011 return $id == $this->_transaction
->id
;
1018 * Is current contribution part of transaction
1022 public function isTransactionPart()
1024 return $this->_transaction
!= null;
1028 * Execute post contribution script
1030 * @param ExternalScript $es External script to execute
1031 * @param array $extra Extra information on contribution
1033 * @param array $pextra Extra information on payment
1036 * @return mixed Script return value on success, values and script output on fail
1038 public function executePostScript(
1043 global $preferences;
1046 'type' => $this->getPaymentType()
1049 if ($pextra !== null && is_array($pextra)) {
1050 $payment = array_merge($payment, $pextra);
1053 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1054 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1057 $voucher_path = null;
1058 if ($this->_id
!== null) {
1059 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1060 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1061 $voucher_path = $voucher->getPath();
1065 'id' => (int)$this->_id
,
1066 'date' => $this->_date
,
1067 'type' => $this->getRawType(),
1068 'amount' => $this->amount
,
1069 'voucher' => $voucher_path,
1070 'category' => array(
1071 'id' => $this->type
->id
,
1072 'label' => $this->type
->libelle
1074 'payment' => $payment
1077 if ($this->_member
!== null) {
1078 $m = new Adherent($this->zdb
, (int)$this->_member
);
1080 'id' => (int)$this->_member
,
1081 'name' => $m->sfullname
,
1082 'email' => $m->email
,
1083 'organization' => ($m->isCompany() ?
1 : 0),
1086 'label' => $m->sstatus
1088 'country' => $m->country
1091 if ($m->isCompany()) {
1092 $member['organization_name'] = $m->company_name
;
1095 $contrib['member'] = $member;
1098 if ($extra !== null && is_array($extra)) {
1099 $contrib = array_merge($contrib, $extra);
1102 $res = $es->send($contrib);
1104 if ($res !== true) {
1106 'An error occurred calling post contribution ' .
1107 "script:\n" . $es->getOutput(),
1110 $res = _T("Contribution information") . "\n";
1111 $res .= print_r($contrib, true);
1112 $res .= "\n\n" . _T("Script output") . "\n";
1113 $res .= $es->getOutput();
1119 * Get raw contribution type
1123 public function getRawType()
1125 if ($this->isFee()) {
1126 return 'membership';
1133 * Get contribution type label
1137 public function getTypeLabel()
1139 if ($this->isFee()) {
1140 return _T("Membership");
1142 return _T("Donation");
1147 * Get payment type label
1149 * @param boolean $translated Whether to translate
1153 public function getPaymentType(bool $translated = false): string
1155 if ($this->_payment_type
=== null) {
1159 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1160 return $ptype->getName($translated);
1164 * Global getter method
1166 * @param string $name name of the property we want to retrieve
1168 * @return mixed the called property
1170 public function __get($name)
1173 $forbidden = array('is_cotis');
1174 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1175 'raw_begin_date', 'raw_end_date'
1178 $rname = '_' . $name;
1180 if (in_array($name, $forbidden)) {
1182 "Call to __get for '$name' is forbidden!",
1188 return $this->isFee();
1190 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1193 property_exists($this, $rname)
1194 ||
in_array($name, $virtuals)
1198 case 'raw_begin_date':
1199 case 'raw_end_date':
1200 $rname = '_' . substr($name, 4);
1201 if ($this->$rname !== null && $this->$rname != '') {
1203 $d = new \
DateTime($this->$rname);
1205 } catch (Throwable
$e) {
1206 //oops, we've got a bad date :/
1208 'Bad date (' . $this->$rname . ') | ' .
1219 if ($this->$rname !== null && $this->$rname != '') {
1221 $d = new \
DateTime($this->$rname);
1222 return $d->format(__("Y-m-d"));
1223 } catch (Throwable
$e) {
1224 //oops, we've got a bad date :/
1226 'Bad date (' . $this->$rname . ') | ' .
1230 return $this->$rname;
1235 if ($this->_is_cotis
) {
1236 // Caution : the end_date stored is actually the due date.
1237 // Adding a day to compute the next_begin_date is required
1238 // to return the right number of months.
1239 $next_begin_date = new \
DateTime($this->_end_date ??
$this->_begin_date
);
1240 $next_begin_date->add(new \
DateInterval('P1D'));
1241 $begin_date = new \
DateTime($this->_begin_date
);
1242 $diff = $next_begin_date->diff($begin_date);
1243 return (int)$diff->format('%y') * 12 +
(int)$diff->format('%m');
1247 case 'spayment_type':
1248 return $this->getPaymentType(true);
1250 if ($this->_is_cotis
=== null) {
1253 return ($this->isFee()) ?
1254 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1256 return $this->$rname;
1260 "Unknown property '$rname'",
1268 * Global isset method
1269 * Required for twig to access properties via __get
1271 * @param string $name name of the property we want to retrieve
1275 public function __isset($name)
1277 $forbidden = array('is_cotis');
1278 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1279 'raw_begin_date', 'raw_end_date'
1282 $rname = '_' . $name;
1284 if (in_array($name, $forbidden)) {
1290 property_exists($this, $rname)
1291 ||
in_array($name, $virtuals)
1301 * Global setter method
1303 * @param string $name name of the property we want to assign a value to
1304 * @param mixed $value a relevant value for the property
1308 public function __set($name, $value)
1310 global $preferences;
1312 $forbidden = array('fields', 'is_cotis', 'end_date');
1314 if (!in_array($name, $forbidden)) {
1315 $rname = '_' . $name;
1318 if (is_int($value)) {
1319 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1322 'Trying to set a transaction from an id that is not an integer.',
1328 if (is_int($value)) {
1330 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1331 //set is_cotis according to type
1332 if ($this->$rname->extension
== 1) {
1333 $this->_is_cotis
= true;
1335 $this->_is_cotis
= false;
1339 'Trying to set a type from an id that is not an integer.',
1346 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1348 throw new \
Exception('Incorrect format');
1350 $this->_begin_date
= $d->format('Y-m-d');
1351 } catch (Throwable
$e) {
1353 'Wrong date format. field: ' . $name .
1354 ', value: ' . $value . ', expected fmt: ' .
1355 __("Y-m-d") . ' | ' . $e->getMessage(),
1358 $this->errors
[] = str_replace(
1365 $this->_fields
['date_debut_cotis']['label']
1367 _T("- Wrong date format (%date_format) for %field!")
1372 if (is_numeric($value) && $value > 0) {
1373 $this->$rname = $value;
1376 'Trying to set an amount with a non numeric value, ' .
1377 'or with a zero value',
1383 if (is_int($value)) {
1385 $this->$rname = $value;
1388 case 'payment_type':
1389 $ptypes = new PaymentTypes(
1394 $list = $ptypes->getList();
1395 if (isset($list[$value])) {
1396 $this->_payment_type
= $value;
1399 'Unknown payment type ' . $value,
1406 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1416 * Flag creation mail sending
1418 * @param boolean $send True (default) to send creation email
1420 * @return Contribution
1422 public function setSendmail(bool $send = true)
1424 $this->sendmail
= $send;
1429 * Should we send administrative emails to member?
1433 public function sendEMail()
1435 return $this->sendmail
;
1439 * Handle files (dynamics files)
1441 * @param array $files Files sent
1443 * @return array|true
1445 public function handleFiles($files)
1449 $this->dynamicsFiles($files);
1451 if (count($this->errors
) > 0) {
1453 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1454 print_r($this->errors
, true),
1457 return $this->errors
;
1464 * Get required fields list
1468 public function getRequired(): array
1471 'id_type_cotis' => 1,
1474 'date_debut_cotis' => 1,
1475 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1476 'montant_cotis' => $this->isFee() ?
1 : 0
1481 * Can current logged-in user display contribution
1483 * @param Login $login Login instance
1487 public function canShow(Login
$login): bool
1489 //non-logged-in members cannot show contributions
1490 if (!$login->isLogged()) {
1494 //admin and staff users can edit, as well as member itself
1495 if (!$this->id ||
$login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1499 //parent can see their children contributions
1500 $parent = new Adherent($this->zdb
);
1503 ->enableDep('children')
1504 ->load($this->login
->id
);
1505 if ($parent->hasChildren()) {
1506 foreach ($parent->children
as $child) {
1507 if ($child->id
=== $this->_member
) {
1518 * Get prefix for events
1522 protected function getEventsPrefix(): string
1524 return 'contribution';