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 $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()) {
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 throw new \
Exception('Incorrect format');
439 $this->$prop = $d->format('Y-m-d');
440 } catch (Throwable
$e) {
442 'Wrong date format. field: ' . $key .
443 ', value: ' . $value . ', expected fmt: ' .
444 __("Y-m-d") . ' | ' . $e->getMessage(),
447 $this->errors
[] = str_replace(
454 $this->_fields
[$key]['label']
456 _T("- Wrong date format (%date_format) for %field!")
463 $this->_member
= (int)$value;
466 case ContributionsTypes
::PK
:
468 $this->type
= (int)$value;
471 case 'montant_cotis':
472 $value = strtr($value, ',', '.');
473 if (!empty($value)) {
474 $this->_amount
= $value;
476 if (!is_numeric($value) && $value !== '') {
477 $this->errors
[] = _T("- The amount must be an integer!");
480 case 'type_paiement_cotis':
481 $ptypes = new PaymentTypes(
486 $ptlist = $ptypes->getList();
487 if (isset($ptlist[$value])) {
488 $this->_payment_type
= $value;
490 $this->errors
[] = _T("- Unknown payment type");
494 $this->_info
= $value;
496 case Transaction
::PK
:
498 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
501 case 'duree_mois_cotis':
503 if (!is_numeric($value) ||
$value <= 0) {
504 $this->errors
[] = _T("- The duration must be a positive integer!");
506 $this->$prop = $value;
507 $this->retrieveEndDate();
514 // missing required fields?
515 foreach ($required as $key => $val) {
517 $prop = '_' . $this->_fields
[$key]['propname'];
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
) == ''))
524 $this->errors
[] = str_replace(
526 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
527 _T("- Mandatory field %field empty.")
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
;
538 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
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;
550 $this->dynamicsCheck($values, $required, $disabled);
552 if (count($this->errors
) > 0) {
554 'Some errors has been threw attempting to edit/store a contribution' .
555 print_r($this->errors
, true),
558 return $this->errors
;
561 'Contribution checked successfully.',
569 * Check that membership fees does not overlap
571 * @return boolean|string True if all is ok, false if error,
572 * error message if overlap
574 public function checkOverlap()
577 $select = $this->zdb
->select(self
::TABLE
, 'c');
578 //@phpstan-ignore-next-line
580 array('date_debut_cotis', 'date_fin_cotis')
582 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
583 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
585 )->where([Adherent
::PK
=> $this->_member
])
586 ->where(array('cotis_extension' => new Expression('true')))
588 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
589 ->lessThanOrEqualTo('date_debut_cotis', $this->_end_date
)
592 ->greaterThanOrEqualTo('date_fin_cotis', $this->_begin_date
)
593 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
595 if ($this->id
!= '') {
596 $select->where
->notEqualTo(self
::PK
, $this->id
);
599 $results = $this->zdb
->execute($select);
600 if ($results->count() > 0) {
601 $result = $results->current();
602 $d = new \
DateTime($result->date_debut_cotis
);
604 return _T("- Membership period overlaps period starting at ") .
605 $d->format(__("Y-m-d"));
608 } catch (Throwable
$e) {
610 'An error occurred checking overlapping fee. ' . $e->getMessage(),
618 * Store the contribution
622 public function store()
624 global $hist, $emitter;
628 if (count($this->errors
) > 0) {
629 throw new \
RuntimeException(
630 'Existing errors prevents storing contribution: ' .
631 print_r($this->errors
, true)
636 $this->zdb
->connection
->beginTransaction();
638 $fields = self
::getDbFields($this->zdb
);
639 foreach ($fields as $field) {
640 $prop = '_' . $this->_fields
[$field]['propname'];
642 case ContributionsTypes
::PK
:
643 case Transaction
::PK
:
644 if (isset($this->$prop)) {
645 $values[$field] = $this->$prop->id
;
649 $values[$field] = $this->$prop;
654 //no end date, let's take database defaults
655 if (!$this->isFee() && !$this->_end_date
) {
656 unset($values['date_fin_cotis']);
660 if (!isset($this->_id
) ||
$this->_id
== '') {
661 //we're inserting a new contribution
662 unset($values[self
::PK
]);
664 $insert = $this->zdb
->insert(self
::TABLE
);
665 $insert->values($values);
666 $add = $this->zdb
->execute($insert);
668 if ($add->count() > 0) {
669 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
673 _T("Contribution added"),
674 Adherent
::getSName($this->zdb
, $this->_member
)
677 $event = 'contribution.add';
679 $hist->add(_T("Fail to add new contribution."));
680 throw new \
Exception(
681 'An error occurred inserting new contribution!'
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);
690 //edit == 0 does not mean there were an error, but that there
691 //were nothing to change
692 if ($edit->count() > 0) {
694 _T("Contribution updated"),
695 Adherent
::getSName($this->zdb
, $this->_member
)
699 if ($edit === false) {
700 throw new \
Exception(
701 'An error occurred updating contribution # ' . $this->_id
. '!'
705 $event = 'contribution.edit';
708 if ($this->isFee()) {
709 $this->updateDeadline();
714 $success = $this->dynamicsStore(true);
717 $this->zdb
->connection
->commit();
718 $this->_orig_amount
= $this->_amount
;
720 //send event at the end of process, once all has been stored
721 if ($event !== null) {
722 $emitter->dispatch(new GaletteEvent($event, $this));
726 } catch (Throwable
$e) {
727 if ($this->zdb
->connection
->inTransaction()) {
728 $this->zdb
->connection
->rollBack();
735 * Update member dead line
739 private function updateDeadline()
742 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
744 if ($due_date != '') {
745 $due_date_update = $due_date;
747 $due_date_update = new Expression('NULL');
750 $update = $this->zdb
->update(Adherent
::TABLE
);
752 array('date_echeance' => $due_date_update)
754 [Adherent
::PK
=> $this->_member
]
756 $this->zdb
->execute($update);
758 } catch (Throwable
$e) {
760 'An error occurred updating member ' . $this->_member
.
770 * Remove contribution from database
772 * @param boolean $transaction Activate transaction mode (defaults to true)
776 public function remove($transaction = true)
782 $this->zdb
->connection
->beginTransaction();
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);
793 'Contribution has not been removed!',
799 $this->zdb
->connection
->commit();
801 $emitter->dispatch(new GaletteEvent('contribution.remove', $this));
803 } catch (Throwable
$e) {
805 $this->zdb
->connection
->rollBack();
808 'An error occurred trying to remove contribution #' .
809 $this->_id
. ' | ' . $e->getMessage(),
819 * @param string $field Field name
823 public function getFieldLabel($field)
825 $label = $this->_fields
[$field]['label'];
826 if ($this->isFee() && $field == 'date_debut_cotis') {
827 $label = $this->_fields
[$field]['cotlabel'];
830 $label = str_replace(' ', ' ', $label);
831 //remove trailing ':' and then trim
832 $label = trim(trim($label, ':'));
837 * Retrieve fields from database
839 * @param Db $zdb Database instance
843 public static function getDbFields(Db
$zdb)
845 $columns = $zdb->getColumns(self
::TABLE
);
847 foreach ($columns as $col) {
848 $fields[] = $col->getName();
854 * Get the relevant CSS class for current contribution
856 * @return string current contribution row class
858 public function getRowClass()
860 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
861 'cotis-normal' : 'cotis-give';
865 * Retrieve member due date
867 * @param Db $zdb Database instance
868 * @param integer $member_id Member identifier
872 public static function getDueDate(Db
$zdb, $member_id)
878 $select = $zdb->select(self
::TABLE
, 'c');
881 'max_date' => new Expression('MAX(date_fin_cotis)')
884 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
885 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
888 [Adherent
::PK
=> $member_id]
890 array('cotis_extension' => new Expression('true'))
893 $results = $zdb->execute($select);
894 $result = $results->current();
895 $due_date = $result->max_date
;
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') {
902 } catch (Throwable
$e) {
904 'An error occurred trying to retrieve member\'s due date',
912 * Detach a contribution from a transaction
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
921 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
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
);
929 array(Transaction
::PK
=> null)
931 [self
::PK
=> $contrib_id]
933 $zdb->execute($update);
937 'Contribution #' . $contrib_id .
938 ' is not actually part of transaction #' . $trans_id,
943 } catch (Throwable
$e) {
945 'Unable to detach contribution #' . $contrib_id .
946 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
954 * Set a contribution as a transaction part
956 * @param Db $zdb Database instance
957 * @param int $trans_id Transaction identifier
958 * @param int $contrib_id Contribution identifier
962 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
965 $update = $zdb->update(self
::TABLE
);
967 array(Transaction
::PK
=> $trans_id)
968 )->where([self
::PK
=> $contrib_id]);
970 $zdb->execute($update);
972 } catch (Throwable
$e) {
974 'Unable to attach contribution #' . $contrib_id .
975 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
983 * Is current contribution a membership fee
987 public function isFee()
989 return $this->_is_cotis
;
993 * Is current contribution part of specified transaction
995 * @param int $id Transaction identifier
999 public function isTransactionPartOf($id)
1001 if ($this->isTransactionPart()) {
1002 return $id == $this->_transaction
->id
;
1009 * Is current contribution part of transaction
1013 public function isTransactionPart()
1015 return $this->_transaction
!= null;
1019 * Execute post contribution script
1021 * @param ExternalScript $es External script to execute
1022 * @param array $extra Extra information on contribution
1024 * @param array $pextra Extra information on payment
1027 * @return mixed Script return value on success, values and script output on fail
1029 public function executePostScript(
1034 global $preferences;
1037 'type' => $this->getPaymentType()
1040 if ($pextra !== null && is_array($pextra)) {
1041 $payment = array_merge($payment, $pextra);
1044 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1045 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
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();
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
1065 'payment' => $payment
1068 if ($this->_member
!== null) {
1069 $m = new Adherent($this->zdb
, (int)$this->_member
);
1071 'id' => (int)$this->_member
,
1072 'name' => $m->sfullname
,
1073 'email' => $m->email
,
1074 'organization' => ($m->isCompany() ?
1 : 0),
1077 'label' => $m->sstatus
1079 'country' => $m->country
1082 if ($m->isCompany()) {
1083 $member['organization_name'] = $m->company_name
;
1086 $contrib['member'] = $member;
1089 if ($extra !== null && is_array($extra)) {
1090 $contrib = array_merge($contrib, $extra);
1093 $res = $es->send($contrib);
1095 if ($res !== true) {
1097 'An error occurred calling post contribution ' .
1098 "script:\n" . $es->getOutput(),
1101 $res = _T("Contribution information") . "\n";
1102 $res .= print_r($contrib, true);
1103 $res .= "\n\n" . _T("Script output") . "\n";
1104 $res .= $es->getOutput();
1110 * Get raw contribution type
1114 public function getRawType()
1116 if ($this->isFee()) {
1117 return 'membership';
1124 * Get contribution type label
1128 public function getTypeLabel()
1130 if ($this->isFee()) {
1131 return _T("Membership");
1133 return _T("Donation");
1138 * Get payment type label
1140 * @param boolean $translated Whether to translate
1144 public function getPaymentType(bool $translated = false): string
1146 if ($this->_payment_type
=== null) {
1150 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1151 return $ptype->getName($translated);
1155 * Global getter method
1157 * @param string $name name of the property we want to retrieve
1159 * @return mixed the called property
1161 public function __get($name)
1164 $forbidden = array('is_cotis');
1165 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1166 'raw_begin_date', 'raw_end_date'
1169 $rname = '_' . $name;
1171 if (in_array($name, $forbidden)) {
1173 "Call to __get for '$name' is forbidden!",
1179 return $this->isFee();
1181 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1184 property_exists($this, $rname)
1185 ||
in_array($name, $virtuals)
1189 case 'raw_begin_date':
1190 case 'raw_end_date':
1191 $rname = '_' . substr($name, 4);
1192 if ($this->$rname !== null && $this->$rname != '') {
1194 $d = new \
DateTime($this->$rname);
1196 } catch (Throwable
$e) {
1197 //oops, we've got a bad date :/
1199 'Bad date (' . $this->$rname . ') | ' .
1210 if ($this->$rname !== null && $this->$rname != '') {
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 :/
1217 'Bad date (' . $this->$rname . ') | ' .
1221 return $this->$rname;
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');
1238 case 'spayment_type':
1239 return $this->getPaymentType(true);
1241 if ($this->_is_cotis
=== null) {
1244 return ($this->isFee()) ?
1245 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1247 return $this->$rname;
1251 "Unknown property '$rname'",
1259 * Global isset method
1260 * Required for twig to access properties via __get
1262 * @param string $name name of the property we want to retrieve
1264 * @return false|object the called property
1266 public function __isset($name)
1268 $forbidden = array('is_cotis');
1269 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1270 'raw_begin_date', 'raw_end_date'
1273 $rname = '_' . $name;
1275 if (in_array($name, $forbidden)) {
1281 property_exists($this, $rname)
1282 ||
in_array($name, $virtuals)
1292 * Global setter method
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
1299 public function __set($name, $value)
1301 global $preferences;
1303 $forbidden = array('fields', 'is_cotis', 'end_date');
1305 if (!in_array($name, $forbidden)) {
1306 $rname = '_' . $name;
1309 if (is_int($value)) {
1310 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1313 'Trying to set a transaction from an id that is not an integer.',
1319 if (is_int($value)) {
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;
1326 $this->_is_cotis
= false;
1330 'Trying to set a type from an id that is not an integer.',
1337 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1339 throw new \
Exception('Incorrect format');
1341 $this->_begin_date
= $d->format('Y-m-d');
1342 } catch (Throwable
$e) {
1344 'Wrong date format. field: ' . $name .
1345 ', value: ' . $value . ', expected fmt: ' .
1346 __("Y-m-d") . ' | ' . $e->getMessage(),
1349 $this->errors
[] = str_replace(
1356 $this->_fields
['date_debut_cotis']['label']
1358 _T("- Wrong date format (%date_format) for %field!")
1363 if (is_numeric($value) && $value > 0) {
1364 $this->$rname = $value;
1367 'Trying to set an amount with a non numeric value, ' .
1368 'or with a zero value',
1374 if (is_int($value)) {
1376 $this->$rname = $value;
1379 case 'payment_type':
1380 $ptypes = new PaymentTypes(
1385 $list = $ptypes->getList();
1386 if (isset($list[$value])) {
1387 $this->_payment_type
= $value;
1390 'Unknown payment type ' . $value,
1397 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1407 * Flag creation mail sending
1409 * @param boolean $send True (default) to send creation email
1411 * @return Contribution
1413 public function setSendmail(bool $send = true)
1415 $this->sendmail
= $send;
1420 * Should we send administrative emails to member?
1424 public function sendEMail()
1426 return $this->sendmail
;
1430 * Handle files (dynamics files)
1432 * @param array $files Files sent
1434 * @return array|true
1436 public function handleFiles($files)
1440 $this->dynamicsFiles($files);
1442 if (count($this->errors
) > 0) {
1444 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1445 print_r($this->errors
, true),
1448 return $this->errors
;
1455 * Get required fields list
1459 public function getRequired(): array
1462 'id_type_cotis' => 1,
1465 'date_debut_cotis' => 1,
1466 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1467 'montant_cotis' => $this->isFee() ?
1 : 0
1472 * Can current logged-in user display contribution
1474 * @param Login $login Login instance
1478 public function canShow(Login
$login): bool
1480 //non-logged-in members cannot show contributions
1481 if (!$login->isLogged()) {
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()) {
1490 //parent can see their children contributions
1491 $parent = new Adherent($this->zdb
);
1494 ->enableDep('children')
1495 ->load($this->login
->id
);
1496 if ($parent->hasChildren()) {
1497 foreach ($parent->children
as $child) {
1498 if ($child->id
=== $this->_member
) {