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();
607 $d_begin = new \
DateTime($result->date_debut_cotis
);
608 $d_end = new \
DateTime($result->date_fin_cotis
);
610 if ($d_begin->format('m-d') == $d_end->format('m-d') && $result->date_fin_cotis
== $this->_begin_date
) {
611 //see https://bugs.galette.eu/issues/1762
615 return _T("- Membership period overlaps period starting at ") .
616 $d_begin->format(__("Y-m-d"));
619 } catch (Throwable
$e) {
621 'An error occurred checking overlapping fee. ' . $e->getMessage(),
629 * Store the contribution
633 public function store()
635 global $hist, $emitter;
639 if (count($this->errors
) > 0) {
640 throw new \
RuntimeException(
641 'Existing errors prevents storing contribution: ' .
642 print_r($this->errors
, true)
647 $this->zdb
->connection
->beginTransaction();
649 $fields = self
::getDbFields($this->zdb
);
650 foreach ($fields as $field) {
651 $prop = '_' . $this->_fields
[$field]['propname'];
653 case ContributionsTypes
::PK
:
654 case Transaction
::PK
:
655 if (isset($this->$prop)) {
656 $values[$field] = $this->$prop->id
;
660 $values[$field] = $this->$prop;
665 //no end date, let's take database defaults
666 if (!$this->isFee() && !$this->_end_date
) {
667 unset($values['date_fin_cotis']);
670 if (!isset($this->_id
) ||
$this->_id
== '') {
671 //we're inserting a new contribution
672 unset($values[self
::PK
]);
674 $insert = $this->zdb
->insert(self
::TABLE
);
675 $insert->values($values);
676 $add = $this->zdb
->execute($insert);
678 if ($add->count() > 0) {
679 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
683 _T("Contribution added"),
684 Adherent
::getSName($this->zdb
, $this->_member
)
686 $event = 'contribution.add';
688 $hist->add(_T("Fail to add new contribution."));
689 throw new \
Exception(
690 'An error occurred inserting new contribution!'
694 //we're editing an existing contribution
695 $update = $this->zdb
->update(self
::TABLE
);
696 $update->set($values)->where([self
::PK
=> $this->_id
]);
697 $edit = $this->zdb
->execute($update);
699 //edit == 0 does not mean there were an error, but that there
700 //were nothing to change
701 if ($edit->count() > 0) {
703 _T("Contribution updated"),
704 Adherent
::getSName($this->zdb
, $this->_member
)
708 $event = 'contribution.edit';
711 if ($this->isFee()) {
712 $this->updateDeadline();
716 $this->dynamicsStore(true);
718 $this->zdb
->connection
->commit();
719 $this->_orig_amount
= $this->_amount
;
721 //send event at the end of process, once all has been stored
722 if ($event !== null) {
723 $emitter->dispatch(new GaletteEvent($event, $this));
727 } catch (Throwable
$e) {
728 if ($this->zdb
->connection
->inTransaction()) {
729 $this->zdb
->connection
->rollBack();
736 * Update member dead line
740 private function updateDeadline()
743 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
745 if ($due_date != '') {
746 $due_date_update = $due_date;
748 $due_date_update = new Expression('NULL');
751 $update = $this->zdb
->update(Adherent
::TABLE
);
753 array('date_echeance' => $due_date_update)
755 [Adherent
::PK
=> $this->_member
]
757 $this->zdb
->execute($update);
759 } catch (Throwable
$e) {
761 'An error occurred updating member ' . $this->_member
.
771 * Remove contribution from database
773 * @param boolean $transaction Activate transaction mode (defaults to true)
777 public function remove($transaction = true)
783 $this->zdb
->connection
->beginTransaction();
786 $delete = $this->zdb
->delete(self
::TABLE
);
787 $delete->where([self
::PK
=> $this->_id
]);
788 $del = $this->zdb
->execute($delete);
789 if ($del->count() > 0) {
790 $this->updateDeadline();
791 $this->dynamicsRemove(true);
794 'Contribution has not been removed!',
800 $this->zdb
->connection
->commit();
802 $emitter->dispatch(new GaletteEvent('contribution.remove', $this));
804 } catch (Throwable
$e) {
806 $this->zdb
->connection
->rollBack();
809 'An error occurred trying to remove contribution #' .
810 $this->_id
. ' | ' . $e->getMessage(),
820 * @param string $field Field name
824 public function getFieldLabel($field)
826 $label = $this->_fields
[$field]['label'];
827 if ($this->isFee() && $field == 'date_debut_cotis') {
828 $label = $this->_fields
[$field]['cotlabel'];
831 $label = str_replace(' ', ' ', $label);
832 //remove trailing ':' and then trim
833 $label = trim(trim($label, ':'));
838 * Retrieve fields from database
840 * @param Db $zdb Database instance
844 public static function getDbFields(Db
$zdb)
846 $columns = $zdb->getColumns(self
::TABLE
);
848 foreach ($columns as $col) {
849 $fields[] = $col->getName();
855 * Get the relevant CSS class for current contribution
857 * @return string current contribution row class
859 public function getRowClass()
861 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
862 'cotis-normal' : 'cotis-give';
866 * Retrieve member due date
868 * @param Db $zdb Database instance
869 * @param integer $member_id Member identifier
873 public static function getDueDate(Db
$zdb, $member_id)
879 $select = $zdb->select(self
::TABLE
, 'c');
882 'max_date' => new Expression('MAX(date_fin_cotis)')
885 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
886 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
889 [Adherent
::PK
=> $member_id]
891 array('cotis_extension' => new Expression('true'))
894 $results = $zdb->execute($select);
895 $result = $results->current();
896 $due_date = $result->max_date
;
898 //avoid bad dates in postgres and bad mysql return from zenddb
899 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
903 } catch (Throwable
$e) {
905 'An error occurred trying to retrieve member\'s due date',
913 * Detach a contribution from a transaction
915 * @param Db $zdb Database instance
916 * @param Login $login Login instance
917 * @param int $trans_id Transaction identifier
918 * @param int $contrib_id Contribution identifier
922 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
925 //first, we check if contribution is part of transaction
926 $c = new Contribution($zdb, $login, (int)$contrib_id);
927 if ($c->isTransactionPartOf($trans_id)) {
928 $update = $zdb->update(self
::TABLE
);
930 array(Transaction
::PK
=> null)
932 [self
::PK
=> $contrib_id]
934 $zdb->execute($update);
938 'Contribution #' . $contrib_id .
939 ' is not actually part of transaction #' . $trans_id,
944 } catch (Throwable
$e) {
946 'Unable to detach contribution #' . $contrib_id .
947 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
955 * Set a contribution as a transaction part
957 * @param Db $zdb Database instance
958 * @param int $trans_id Transaction identifier
959 * @param int $contrib_id Contribution identifier
963 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
966 $update = $zdb->update(self
::TABLE
);
968 array(Transaction
::PK
=> $trans_id)
969 )->where([self
::PK
=> $contrib_id]);
971 $zdb->execute($update);
973 } catch (Throwable
$e) {
975 'Unable to attach contribution #' . $contrib_id .
976 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
984 * Is current contribution a membership fee
988 public function isFee()
990 return $this->_is_cotis
;
994 * Is current contribution part of specified transaction
996 * @param int $id Transaction identifier
1000 public function isTransactionPartOf($id)
1002 if ($this->isTransactionPart()) {
1003 return $id == $this->_transaction
->id
;
1010 * Is current contribution part of transaction
1014 public function isTransactionPart()
1016 return $this->_transaction
!= null;
1020 * Execute post contribution script
1022 * @param ExternalScript $es External script to execute
1023 * @param array $extra Extra information on contribution
1025 * @param array $pextra Extra information on payment
1028 * @return mixed Script return value on success, values and script output on fail
1030 public function executePostScript(
1035 global $preferences;
1038 'type' => $this->getPaymentType()
1041 if ($pextra !== null && is_array($pextra)) {
1042 $payment = array_merge($payment, $pextra);
1045 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1046 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1049 $voucher_path = null;
1050 if ($this->_id
!== null) {
1051 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1052 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1053 $voucher_path = $voucher->getPath();
1057 'id' => (int)$this->_id
,
1058 'date' => $this->_date
,
1059 'type' => $this->getRawType(),
1060 'amount' => $this->amount
,
1061 'voucher' => $voucher_path,
1062 'category' => array(
1063 'id' => $this->type
->id
,
1064 'label' => $this->type
->libelle
1066 'payment' => $payment
1069 if ($this->_member
!== null) {
1070 $m = new Adherent($this->zdb
, (int)$this->_member
);
1072 'id' => (int)$this->_member
,
1073 'name' => $m->sfullname
,
1074 'email' => $m->email
,
1075 'organization' => ($m->isCompany() ?
1 : 0),
1078 'label' => $m->sstatus
1080 'country' => $m->country
1083 if ($m->isCompany()) {
1084 $member['organization_name'] = $m->company_name
;
1087 $contrib['member'] = $member;
1090 if ($extra !== null && is_array($extra)) {
1091 $contrib = array_merge($contrib, $extra);
1094 $res = $es->send($contrib);
1096 if ($res !== true) {
1098 'An error occurred calling post contribution ' .
1099 "script:\n" . $es->getOutput(),
1102 $res = _T("Contribution information") . "\n";
1103 $res .= print_r($contrib, true);
1104 $res .= "\n\n" . _T("Script output") . "\n";
1105 $res .= $es->getOutput();
1111 * Get raw contribution type
1115 public function getRawType()
1117 if ($this->isFee()) {
1118 return 'membership';
1125 * Get contribution type label
1129 public function getTypeLabel()
1131 if ($this->isFee()) {
1132 return _T("Membership");
1134 return _T("Donation");
1139 * Get payment type label
1141 * @param boolean $translated Whether to translate
1145 public function getPaymentType(bool $translated = false): string
1147 if ($this->_payment_type
=== null) {
1151 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1152 return $ptype->getName($translated);
1156 * Global getter method
1158 * @param string $name name of the property we want to retrieve
1160 * @return mixed the called property
1162 public function __get($name)
1165 $forbidden = array('is_cotis');
1166 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1167 'raw_begin_date', 'raw_end_date'
1170 $rname = '_' . $name;
1172 if (in_array($name, $forbidden)) {
1174 "Call to __get for '$name' is forbidden!",
1180 return $this->isFee();
1182 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1185 property_exists($this, $rname)
1186 ||
in_array($name, $virtuals)
1190 case 'raw_begin_date':
1191 case 'raw_end_date':
1192 $rname = '_' . substr($name, 4);
1193 if ($this->$rname !== null && $this->$rname != '') {
1195 $d = new \
DateTime($this->$rname);
1197 } catch (Throwable
$e) {
1198 //oops, we've got a bad date :/
1200 'Bad date (' . $this->$rname . ') | ' .
1211 if ($this->$rname !== null && $this->$rname != '') {
1213 $d = new \
DateTime($this->$rname);
1214 return $d->format(__("Y-m-d"));
1215 } catch (Throwable
$e) {
1216 //oops, we've got a bad date :/
1218 'Bad date (' . $this->$rname . ') | ' .
1222 return $this->$rname;
1227 if ($this->_is_cotis
) {
1228 // Caution : the end_date stored is actually the due date.
1229 // Adding a day to compute the next_begin_date is required
1230 // to return the right number of months.
1231 $next_begin_date = new \
DateTime($this->_end_date ??
$this->_begin_date
);
1232 $next_begin_date->add(new \
DateInterval('P1D'));
1233 $begin_date = new \
DateTime($this->_begin_date
);
1234 $diff = $next_begin_date->diff($begin_date);
1235 return (int)$diff->format('%y') * 12 +
(int)$diff->format('%m');
1239 case 'spayment_type':
1240 return $this->getPaymentType(true);
1242 if ($this->_is_cotis
=== null) {
1245 return ($this->isFee()) ?
1246 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1248 return $this->$rname;
1252 "Unknown property '$rname'",
1260 * Global isset method
1261 * Required for twig to access properties via __get
1263 * @param string $name name of the property we want to retrieve
1267 public function __isset($name)
1269 $forbidden = array('is_cotis');
1270 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1271 'raw_begin_date', 'raw_end_date'
1274 $rname = '_' . $name;
1276 if (in_array($name, $forbidden)) {
1282 property_exists($this, $rname)
1283 ||
in_array($name, $virtuals)
1293 * Global setter method
1295 * @param string $name name of the property we want to assign a value to
1296 * @param mixed $value a relevant value for the property
1300 public function __set($name, $value)
1302 global $preferences;
1304 $forbidden = array('fields', 'is_cotis', 'end_date');
1306 if (!in_array($name, $forbidden)) {
1307 $rname = '_' . $name;
1310 if (is_int($value)) {
1311 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1314 'Trying to set a transaction from an id that is not an integer.',
1320 if (is_int($value)) {
1322 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1323 //set is_cotis according to type
1324 if ($this->$rname->extension
== 1) {
1325 $this->_is_cotis
= true;
1327 $this->_is_cotis
= false;
1331 'Trying to set a type from an id that is not an integer.',
1338 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1340 throw new \
Exception('Incorrect format');
1342 $this->_begin_date
= $d->format('Y-m-d');
1343 } catch (Throwable
$e) {
1345 'Wrong date format. field: ' . $name .
1346 ', value: ' . $value . ', expected fmt: ' .
1347 __("Y-m-d") . ' | ' . $e->getMessage(),
1350 $this->errors
[] = str_replace(
1357 $this->_fields
['date_debut_cotis']['label']
1359 _T("- Wrong date format (%date_format) for %field!")
1364 if (is_numeric($value) && $value > 0) {
1365 $this->$rname = $value;
1368 'Trying to set an amount with a non numeric value, ' .
1369 'or with a zero value',
1375 if (is_int($value)) {
1377 $this->$rname = $value;
1380 case 'payment_type':
1381 $ptypes = new PaymentTypes(
1386 $list = $ptypes->getList();
1387 if (isset($list[$value])) {
1388 $this->_payment_type
= $value;
1391 'Unknown payment type ' . $value,
1398 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1408 * Flag creation mail sending
1410 * @param boolean $send True (default) to send creation email
1412 * @return Contribution
1414 public function setSendmail(bool $send = true)
1416 $this->sendmail
= $send;
1421 * Should we send administrative emails to member?
1425 public function sendEMail()
1427 return $this->sendmail
;
1431 * Handle files (dynamics files)
1433 * @param array $files Files sent
1435 * @return array|true
1437 public function handleFiles($files)
1441 $this->dynamicsFiles($files);
1443 if (count($this->errors
) > 0) {
1445 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1446 print_r($this->errors
, true),
1449 return $this->errors
;
1456 * Get required fields list
1460 public function getRequired(): array
1463 'id_type_cotis' => 1,
1466 'date_debut_cotis' => 1,
1467 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1468 'montant_cotis' => $this->isFee() ?
1 : 0
1473 * Can current logged-in user display contribution
1475 * @param Login $login Login instance
1479 public function canShow(Login
$login): bool
1481 //non-logged-in members cannot show contributions
1482 if (!$login->isLogged()) {
1486 //admin and staff users can edit, as well as member itself
1487 if (!$this->id ||
$login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1491 //parent can see their children contributions
1492 $parent = new Adherent($this->zdb
);
1495 ->enableDep('children')
1496 ->load($this->login
->id
);
1497 if ($parent->hasChildren()) {
1498 foreach ($parent->children
as $child) {
1499 if ($child->id
=== $this->_member
) {