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
;
45 use Laminas\Db\Sql\Expression
;
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
;
54 * Contribution class for galette
55 * Manage membership fees and donations.
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
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
89 public const TABLE
= 'cotisations';
90 public const PK
= 'id_cotis';
92 public const TYPE_FEE
= 'fee';
93 public const TYPE_DONATION
= 'donation';
100 private $_payment_type;
101 private $_orig_amount;
103 private $_begin_date;
105 private $_transaction = null;
109 //fields list and their translation
119 private $sendmail = false;
122 * Default constructor
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
130 public function __construct(Db
$zdb, Login
$login, $args = null)
133 $this->login
= $login;
136 $this->_payment_type
= (int)$preferences->pref_default_paymenttype
;
139 * Fields configuration. Each field is an array and must reflect:
142 * (string) property name
145 * I'd prefer a static private variable for this...
146 * But call to the _T function does not seem to be allowed there :/
148 $this->_fields
= array(
150 'label' => _T('Contribution id'), //not a field in the form
153 Adherent
::PK
=> array(
154 'label' => _T("Contributor:"),
155 'propname' => 'member'
157 ContributionsTypes
::PK
=> array(
158 'label' => _T("Contribution type:"),
161 'montant_cotis' => array(
162 'label' => _T("Amount:"),
163 'propname' => 'amount'
165 'type_paiement_cotis' => array(
166 'label' => _T("Payment type:"),
167 'propname' => 'payment_type'
169 'info_cotis' => array(
170 'label' => _T("Comments:"),
173 'date_enreg' => array(
174 'label' => _T('Date'), //not a field in the form
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'
182 'date_fin_cotis' => array(
183 'label' => _T("End date of membership:"),
184 'propname' => 'end_date'
186 Transaction
::PK
=> array(
187 'label' => _T('Transaction ID'), //not a field in the form
188 'propname' => 'transaction'
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'
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'];
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
;
209 $this->_amount
= $this->_transaction
->getMissingAmount();
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');
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');
229 $this->retrieveEndDate();
231 if (isset($args['payment_type'])) {
232 $this->_payment_type
= $args['payment_type'];
234 } elseif (is_object($args)) {
235 $this->loadFromRS($args);
238 $this->loadDynamicFields();
242 * Sets end contribution date
246 private function retrieveEndDate()
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'));
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');
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');
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'));
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
;
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');
291 throw new \
RuntimeException(
292 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
298 * Loads a contribution from its id
300 * @param int $id the identifier for the contribution to load
302 * @return bool true if query succeed, false otherwise
304 public function load($id)
306 if (!$this->login
->isLogged() && $this->login
->id
== '') {
311 $select = $this->zdb
->select(self
::TABLE
, 'c');
313 array('a' => PREFIX_DB
. Adherent
::TABLE
),
314 'c.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
317 //restrict query on current member id if he's not admin nor staff member
318 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
321 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
323 ->equalTo('a.parent_id', $this->login
->id
)
326 ->equalTo('c.' . self
::PK
, $id)
329 $select->where
->equalTo(self
::PK
, $id);
332 $results = $this->zdb
->execute($select);
333 if ($results->count() > 0) {
334 $row = $results->current();
335 $this->loadFromRS($row);
339 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')',
344 } catch (Throwable
$e) {
346 'An error occurred attempting to load contribution #' . $id .
355 * Populate object from a resultset row
357 * @param ArrayObject $r the resultset row
361 private function loadFromRS(ArrayObject
$r)
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 :(
377 $end_date !== '0000-00-00'
378 && $end_date !== '1901-01-01'
379 && $end_date !== '0001-01-01 BC'
381 $this->_end_date
= $r->date_fin_cotis
;
383 $adhpk = Adherent
::PK
;
384 $this->_member
= (int)$r->$adhpk;
386 $transpk = Transaction
::PK
;
387 if ($r->$transpk != '') {
388 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
391 $this->type
= (int)$r->id_type_cotis
;
392 $this->loadDynamicFields();
396 * Check posted values validity
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
405 public function check($values, $required, $disabled)
408 $this->errors
= array();
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'];
416 if (isset($values[$key])) {
417 $value = trim($values[$key]);
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!
427 // now, check validity
431 case 'date_debut_cotis':
432 case 'date_fin_cotis':
435 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
437 //try with non localized date
438 $d = \DateTime
::createFromFormat("Y-m-d", $value);
440 throw new \
Exception('Incorrect format');
443 $this->$prop = $d->format('Y-m-d');
444 } catch (Throwable
$e) {
446 'Wrong date format. field: ' . $key .
447 ', value: ' . $value . ', expected fmt: ' .
448 __("Y-m-d") . ' | ' . $e->getMessage(),
451 $this->errors
[] = str_replace(
458 $this->_fields
[$key]['label']
460 _T("- Wrong date format (%date_format) for %field!")
467 $this->_member
= (int)$value;
470 case ContributionsTypes
::PK
:
472 $this->type
= (int)$value;
475 case 'montant_cotis':
476 $value = strtr($value, ',', '.');
477 if (!empty($value) ||
$value === '0') {
478 $this->_amount
= (double)$value;
480 if (!is_numeric($value) && $value !== '') {
481 $this->errors
[] = _T("- The amount must be an integer!");
484 case 'type_paiement_cotis':
485 $ptypes = new PaymentTypes(
490 $ptlist = $ptypes->getList();
491 if (isset($ptlist[$value])) {
492 $this->_payment_type
= $value;
494 $this->errors
[] = _T("- Unknown payment type");
498 $this->_info
= $value;
500 case Transaction
::PK
:
502 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
505 case 'duree_mois_cotis':
507 if (!is_numeric($value) ||
$value <= 0) {
508 $this->errors
[] = _T("- The duration must be a positive integer!");
510 $this->$prop = $value;
511 $this->retrieveEndDate();
518 // missing required fields?
519 foreach ($required as $key => $val) {
521 $prop = '_' . $this->_fields
[$key]['propname'];
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
) == ''))
528 $this->errors
[] = str_replace(
530 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
531 _T("- Mandatory field %field empty.")
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
;
542 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
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;
554 $this->dynamicsCheck($values, $required, $disabled);
556 if (count($this->errors
) > 0) {
558 'Some errors has been threw attempting to edit/store a contribution' .
559 print_r($this->errors
, true),
562 return $this->errors
;
565 'Contribution checked successfully.',
573 * Check that membership fees does not overlap
575 * @return boolean|string True if all is ok, false if error,
576 * error message if overlap
578 public function checkOverlap()
581 $select = $this->zdb
->select(self
::TABLE
, 'c');
582 //@phpstan-ignore-next-line
584 array('date_debut_cotis', 'date_fin_cotis')
586 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
587 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
589 )->where([Adherent
::PK
=> $this->_member
])
590 ->where(array('cotis_extension' => new Expression('true')))
592 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
593 ->lessThanOrEqualTo('date_debut_cotis', $this->_end_date
)
596 ->greaterThanOrEqualTo('date_fin_cotis', $this->_begin_date
)
597 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
599 if ($this->id
!= '') {
600 $select->where
->notEqualTo(self
::PK
, $this->id
);
603 $results = $this->zdb
->execute($select);
604 if ($results->count() > 0) {
605 $result = $results->current();
606 $d = new \
DateTime($result->date_debut_cotis
);
608 return _T("- Membership period overlaps period starting at ") .
609 $d->format(__("Y-m-d"));
612 } catch (Throwable
$e) {
614 'An error occurred checking overlapping fee. ' . $e->getMessage(),
622 * Store the contribution
626 public function store()
628 global $hist, $emitter;
632 if (count($this->errors
) > 0) {
633 throw new \
RuntimeException(
634 'Existing errors prevents storing contribution: ' .
635 print_r($this->errors
, true)
640 $this->zdb
->connection
->beginTransaction();
642 $fields = self
::getDbFields($this->zdb
);
643 foreach ($fields as $field) {
644 $prop = '_' . $this->_fields
[$field]['propname'];
646 case ContributionsTypes
::PK
:
647 case Transaction
::PK
:
648 if (isset($this->$prop)) {
649 $values[$field] = $this->$prop->id
;
653 $values[$field] = $this->$prop;
658 //no end date, let's take database defaults
659 if (!$this->isFee() && !$this->_end_date
) {
660 unset($values['date_fin_cotis']);
663 if (!isset($this->_id
) ||
$this->_id
== '') {
664 //we're inserting a new contribution
665 unset($values[self
::PK
]);
667 $insert = $this->zdb
->insert(self
::TABLE
);
668 $insert->values($values);
669 $add = $this->zdb
->execute($insert);
671 if ($add->count() > 0) {
672 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
676 _T("Contribution added"),
677 Adherent
::getSName($this->zdb
, $this->_member
)
679 $event = 'contribution.add';
681 $hist->add(_T("Fail to add new contribution."));
682 throw new \
Exception(
683 'An error occurred inserting new contribution!'
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);
692 //edit == 0 does not mean there were an error, but that there
693 //were nothing to change
694 if ($edit->count() > 0) {
696 _T("Contribution updated"),
697 Adherent
::getSName($this->zdb
, $this->_member
)
701 $event = 'contribution.edit';
704 if ($this->isFee()) {
705 $this->updateDeadline();
709 $this->dynamicsStore(true);
711 $this->zdb
->connection
->commit();
712 $this->_orig_amount
= $this->_amount
;
714 //send event at the end of process, once all has been stored
715 if ($event !== null) {
716 $emitter->dispatch(new GaletteEvent($event, $this));
720 } catch (Throwable
$e) {
721 if ($this->zdb
->connection
->inTransaction()) {
722 $this->zdb
->connection
->rollBack();
729 * Update member dead line
733 private function updateDeadline()
736 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
738 if ($due_date != '') {
739 $due_date_update = $due_date;
741 $due_date_update = new Expression('NULL');
744 $update = $this->zdb
->update(Adherent
::TABLE
);
746 array('date_echeance' => $due_date_update)
748 [Adherent
::PK
=> $this->_member
]
750 $this->zdb
->execute($update);
752 } catch (Throwable
$e) {
754 'An error occurred updating member ' . $this->_member
.
764 * Remove contribution from database
766 * @param boolean $transaction Activate transaction mode (defaults to true)
770 public function remove($transaction = true)
776 $this->zdb
->connection
->beginTransaction();
779 $delete = $this->zdb
->delete(self
::TABLE
);
780 $delete->where([self
::PK
=> $this->_id
]);
781 $del = $this->zdb
->execute($delete);
782 if ($del->count() > 0) {
783 $this->updateDeadline();
784 $this->dynamicsRemove(true);
787 'Contribution has not been removed!',
793 $this->zdb
->connection
->commit();
795 $emitter->dispatch(new GaletteEvent('contribution.remove', $this));
797 } catch (Throwable
$e) {
799 $this->zdb
->connection
->rollBack();
802 'An error occurred trying to remove contribution #' .
803 $this->_id
. ' | ' . $e->getMessage(),
813 * @param string $field Field name
817 public function getFieldLabel($field)
819 $label = $this->_fields
[$field]['label'];
820 if ($this->isFee() && $field == 'date_debut_cotis') {
821 $label = $this->_fields
[$field]['cotlabel'];
824 $label = str_replace(' ', ' ', $label);
825 //remove trailing ':' and then trim
826 $label = trim(trim($label, ':'));
831 * Retrieve fields from database
833 * @param Db $zdb Database instance
837 public static function getDbFields(Db
$zdb)
839 $columns = $zdb->getColumns(self
::TABLE
);
841 foreach ($columns as $col) {
842 $fields[] = $col->getName();
848 * Get the relevant CSS class for current contribution
850 * @return string current contribution row class
852 public function getRowClass()
854 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
855 'cotis-normal' : 'cotis-give';
859 * Retrieve member due date
861 * @param Db $zdb Database instance
862 * @param integer $member_id Member identifier
866 public static function getDueDate(Db
$zdb, $member_id)
872 $select = $zdb->select(self
::TABLE
, 'c');
875 'max_date' => new Expression('MAX(date_fin_cotis)')
878 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
879 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
882 [Adherent
::PK
=> $member_id]
884 array('cotis_extension' => new Expression('true'))
887 $results = $zdb->execute($select);
888 $result = $results->current();
889 $due_date = $result->max_date
;
891 //avoid bad dates in postgres and bad mysql return from zenddb
892 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
896 } catch (Throwable
$e) {
898 'An error occurred trying to retrieve member\'s due date',
906 * Detach a contribution from a transaction
908 * @param Db $zdb Database instance
909 * @param Login $login Login instance
910 * @param int $trans_id Transaction identifier
911 * @param int $contrib_id Contribution identifier
915 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
918 //first, we check if contribution is part of transaction
919 $c = new Contribution($zdb, $login, (int)$contrib_id);
920 if ($c->isTransactionPartOf($trans_id)) {
921 $update = $zdb->update(self
::TABLE
);
923 array(Transaction
::PK
=> null)
925 [self
::PK
=> $contrib_id]
927 $zdb->execute($update);
931 'Contribution #' . $contrib_id .
932 ' is not actually part of transaction #' . $trans_id,
937 } catch (Throwable
$e) {
939 'Unable to detach contribution #' . $contrib_id .
940 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
948 * Set a contribution as a transaction part
950 * @param Db $zdb Database instance
951 * @param int $trans_id Transaction identifier
952 * @param int $contrib_id Contribution identifier
956 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
959 $update = $zdb->update(self
::TABLE
);
961 array(Transaction
::PK
=> $trans_id)
962 )->where([self
::PK
=> $contrib_id]);
964 $zdb->execute($update);
966 } catch (Throwable
$e) {
968 'Unable to attach contribution #' . $contrib_id .
969 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
977 * Is current contribution a membership fee
981 public function isFee()
983 return $this->_is_cotis
;
987 * Is current contribution part of specified transaction
989 * @param int $id Transaction identifier
993 public function isTransactionPartOf($id)
995 if ($this->isTransactionPart()) {
996 return $id == $this->_transaction
->id
;
1003 * Is current contribution part of transaction
1007 public function isTransactionPart()
1009 return $this->_transaction
!= null;
1013 * Execute post contribution script
1015 * @param ExternalScript $es External script to execute
1016 * @param array $extra Extra information on contribution
1018 * @param array $pextra Extra information on payment
1021 * @return mixed Script return value on success, values and script output on fail
1023 public function executePostScript(
1028 global $preferences;
1031 'type' => $this->getPaymentType()
1034 if ($pextra !== null && is_array($pextra)) {
1035 $payment = array_merge($payment, $pextra);
1038 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1039 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1042 $voucher_path = null;
1043 if ($this->_id
!== null) {
1044 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1045 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1046 $voucher_path = $voucher->getPath();
1050 'id' => (int)$this->_id
,
1051 'date' => $this->_date
,
1052 'type' => $this->getRawType(),
1053 'amount' => $this->amount
,
1054 'voucher' => $voucher_path,
1055 'category' => array(
1056 'id' => $this->type
->id
,
1057 'label' => $this->type
->libelle
1059 'payment' => $payment
1062 if ($this->_member
!== null) {
1063 $m = new Adherent($this->zdb
, (int)$this->_member
);
1065 'id' => (int)$this->_member
,
1066 'name' => $m->sfullname
,
1067 'email' => $m->email
,
1068 'organization' => ($m->isCompany() ?
1 : 0),
1071 'label' => $m->sstatus
1073 'country' => $m->country
1076 if ($m->isCompany()) {
1077 $member['organization_name'] = $m->company_name
;
1080 $contrib['member'] = $member;
1083 if ($extra !== null && is_array($extra)) {
1084 $contrib = array_merge($contrib, $extra);
1087 $res = $es->send($contrib);
1089 if ($res !== true) {
1091 'An error occurred calling post contribution ' .
1092 "script:\n" . $es->getOutput(),
1095 $res = _T("Contribution information") . "\n";
1096 $res .= print_r($contrib, true);
1097 $res .= "\n\n" . _T("Script output") . "\n";
1098 $res .= $es->getOutput();
1104 * Get raw contribution type
1108 public function getRawType()
1110 if ($this->isFee()) {
1111 return 'membership';
1118 * Get contribution type label
1122 public function getTypeLabel()
1124 if ($this->isFee()) {
1125 return _T("Membership");
1127 return _T("Donation");
1132 * Get payment type label
1134 * @param boolean $translated Whether to translate
1138 public function getPaymentType(bool $translated = false): string
1140 if ($this->_payment_type
=== null) {
1144 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1145 return $ptype->getName($translated);
1149 * Global getter method
1151 * @param string $name name of the property we want to retrieve
1153 * @return mixed the called property
1155 public function __get($name)
1158 $forbidden = array('is_cotis');
1159 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1160 'raw_begin_date', 'raw_end_date'
1163 $rname = '_' . $name;
1165 if (in_array($name, $forbidden)) {
1167 "Call to __get for '$name' is forbidden!",
1173 return $this->isFee();
1175 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1178 property_exists($this, $rname)
1179 ||
in_array($name, $virtuals)
1183 case 'raw_begin_date':
1184 case 'raw_end_date':
1185 $rname = '_' . substr($name, 4);
1186 if ($this->$rname !== null && $this->$rname != '') {
1188 $d = new \
DateTime($this->$rname);
1190 } catch (Throwable
$e) {
1191 //oops, we've got a bad date :/
1193 'Bad date (' . $this->$rname . ') | ' .
1204 if ($this->$rname !== null && $this->$rname != '') {
1206 $d = new \
DateTime($this->$rname);
1207 return $d->format(__("Y-m-d"));
1208 } catch (Throwable
$e) {
1209 //oops, we've got a bad date :/
1211 'Bad date (' . $this->$rname . ') | ' .
1215 return $this->$rname;
1220 if ($this->_is_cotis
) {
1221 // Caution : the end_date stored is actually the due date.
1222 // Adding a day to compute the next_begin_date is required
1223 // to return the right number of months.
1224 $next_begin_date = new \
DateTime($this->_end_date ??
$this->_begin_date
);
1225 $next_begin_date->add(new \
DateInterval('P1D'));
1226 $begin_date = new \
DateTime($this->_begin_date
);
1227 $diff = $next_begin_date->diff($begin_date);
1228 return (int)$diff->format('%y') * 12 +
(int)$diff->format('%m');
1232 case 'spayment_type':
1233 return $this->getPaymentType(true);
1235 if ($this->_is_cotis
=== null) {
1238 return ($this->isFee()) ?
1239 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1241 return $this->$rname;
1245 "Unknown property '$rname'",
1253 * Global isset method
1254 * Required for twig to access properties via __get
1256 * @param string $name name of the property we want to retrieve
1260 public function __isset($name)
1262 $forbidden = array('is_cotis');
1263 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1264 'raw_begin_date', 'raw_end_date'
1267 $rname = '_' . $name;
1269 if (in_array($name, $forbidden)) {
1275 property_exists($this, $rname)
1276 ||
in_array($name, $virtuals)
1286 * Global setter method
1288 * @param string $name name of the property we want to assign a value to
1289 * @param mixed $value a relevant value for the property
1293 public function __set($name, $value)
1295 global $preferences;
1297 $forbidden = array('fields', 'is_cotis', 'end_date');
1299 if (!in_array($name, $forbidden)) {
1300 $rname = '_' . $name;
1303 if (is_int($value)) {
1304 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1307 'Trying to set a transaction from an id that is not an integer.',
1313 if (is_int($value)) {
1315 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1316 //set is_cotis according to type
1317 if ($this->$rname->extension
== 1) {
1318 $this->_is_cotis
= true;
1320 $this->_is_cotis
= false;
1324 'Trying to set a type from an id that is not an integer.',
1331 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1333 throw new \
Exception('Incorrect format');
1335 $this->_begin_date
= $d->format('Y-m-d');
1336 } catch (Throwable
$e) {
1338 'Wrong date format. field: ' . $name .
1339 ', value: ' . $value . ', expected fmt: ' .
1340 __("Y-m-d") . ' | ' . $e->getMessage(),
1343 $this->errors
[] = str_replace(
1350 $this->_fields
['date_debut_cotis']['label']
1352 _T("- Wrong date format (%date_format) for %field!")
1357 if (is_numeric($value) && $value > 0) {
1358 $this->$rname = $value;
1361 'Trying to set an amount with a non numeric value, ' .
1362 'or with a zero value',
1368 if (is_int($value)) {
1370 $this->$rname = $value;
1373 case 'payment_type':
1374 $ptypes = new PaymentTypes(
1379 $list = $ptypes->getList();
1380 if (isset($list[$value])) {
1381 $this->_payment_type
= $value;
1384 'Unknown payment type ' . $value,
1391 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1401 * Flag creation mail sending
1403 * @param boolean $send True (default) to send creation email
1405 * @return Contribution
1407 public function setSendmail(bool $send = true)
1409 $this->sendmail
= $send;
1414 * Should we send administrative emails to member?
1418 public function sendEMail()
1420 return $this->sendmail
;
1424 * Handle files (dynamics files)
1426 * @param array $files Files sent
1428 * @return array|true
1430 public function handleFiles($files)
1434 $this->dynamicsFiles($files);
1436 if (count($this->errors
) > 0) {
1438 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1439 print_r($this->errors
, true),
1442 return $this->errors
;
1449 * Get required fields list
1453 public function getRequired(): array
1456 'id_type_cotis' => 1,
1459 'date_debut_cotis' => 1,
1460 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1461 'montant_cotis' => $this->isFee() ?
1 : 0
1466 * Can current logged-in user display contribution
1468 * @param Login $login Login instance
1472 public function canShow(Login
$login): bool
1474 //non-logged-in members cannot show contributions
1475 if (!$login->isLogged()) {
1479 //admin and staff users can edit, as well as member itself
1480 if (!$this->id ||
$login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1484 //parent can see their children contributions
1485 $parent = new Adherent($this->zdb
);
1488 ->enableDep('children')
1489 ->load($this->login
->id
);
1490 if ($parent->hasChildren()) {
1491 foreach ($parent->children
as $child) {
1492 if ($child->id
=== $this->_member
) {