3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Contribution class for galette
7 * Manage membership fees and donations.
11 * Copyright © 2010-2021 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-2021 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 Laminas\Db\Sql\Expression
;
44 use Galette\Core\Login
;
45 use Galette\IO\ExternalScript
;
46 use Galette\IO\PdfContribution
;
47 use Galette\Repository\PaymentTypes
;
48 use Galette\Features\Dynamics
;
51 * Contribution class for galette
52 * Manage membership fees and donations.
57 * @author Johan Cwiklinski <johan@x-tnd.be>
58 * @copyright 2010-2021 The Galette Team
59 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
60 * @link http://galette.tuxfamily.org
61 * @since Available since 0.7dev - 2010-03-11
63 * @property integer $id
64 * @property string $date
65 * @property DateTime $raw_date
66 * @property integer $member
67 * @property ContributionsTypes $type
68 * @property integer $amount
69 * @property integer $payment_type
70 * @property integer $orig_amount
71 * @property string $info
72 * @property string $begin_date
73 * @property DateTime $raw_begin_date
74 * @property string $end_date
75 * @property DateTime $raw_end_date
76 * @property Transaction|null $transaction
77 * @property integer $extension
78 * @property integer $duration
79 * @property string $spayment_type
80 * @property integer $model
86 public const TABLE
= 'cotisations';
87 public const PK
= 'id_cotis';
89 public const TYPE_FEE
= 'fee';
90 public const TYPE_DONATION
= 'donation';
97 private $_payment_type;
98 private $_orig_amount;
100 private $_begin_date;
102 private $_transaction = null;
106 //fields list and their translation
116 private $sendmail = false;
119 * Default constructor
121 * @param Db $zdb Database
122 * @param Login $login Login instance
123 * @param null|int|ResultSet $args Either a ResultSet row to load
124 * a specific contribution, or an type id
125 * to just instantiate object
127 public function __construct(Db
$zdb, Login
$login, $args = null)
130 $this->login
= $login;
133 $this->_payment_type
= (int)$preferences->pref_default_paymenttype
;
136 * Fields configuration. Each field is an array and must reflect:
139 * (string) property name
142 * I'd prefer a static private variable for this...
143 * But call to the _T function does not seem to be allowed there :/
145 $this->_fields
= array(
147 'label' => _T('Contribution id'), //not a field in the form
150 Adherent
::PK
=> array(
151 'label' => _T("Contributor:"),
152 'propname' => 'member'
154 ContributionsTypes
::PK
=> array(
155 'label' => _T("Contribution type:"),
158 'montant_cotis' => array(
159 'label' => _T("Amount:"),
160 'propname' => 'amount'
162 'type_paiement_cotis' => array(
163 'label' => _T("Payment type:"),
164 'propname' => 'payment_type'
166 'info_cotis' => array(
167 'label' => _T("Comments:"),
170 'date_enreg' => array(
171 'label' => _T('Date'), //not a field in the form
174 'date_debut_cotis' => array(
175 'label' => _T("Date of contribution:"),
176 'cotlabel' => _T("Start date of membership:"), //if contribution is a membership fee, label differs
177 'propname' => 'begin_date'
179 'date_fin_cotis' => array(
180 'label' => _T("End date of membership:"),
181 'propname' => 'end_date'
183 Transaction
::PK
=> array(
184 'label' => _T('Transaction ID'), //not a field in the form
185 'propname' => 'transaction'
187 //this one is not really a field, but is required in some cases...
188 //adding it here make more simple to check required fields
189 'duree_mois_cotis' => array(
190 'label' => _T("Membership extension:"),
191 'propname' => 'extension'
196 } elseif (is_array($args)) {
197 $this->_date
= date("Y-m-d");
198 if (isset($args['adh']) && $args['adh'] != '') {
199 $this->_member
= (int)$args['adh'];
201 if (isset($args['trans'])) {
202 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
203 if (!isset($this->_member
)) {
204 $this->_member
= (int)$this->_transaction
->member
;
206 $this->_amount
= $this->_transaction
->getMissingAmount();
208 $this->type
= (int)$args['type'];
209 //calculate begin date for membership fee
210 $this->_begin_date
= $this->_date
;
211 if ($this->_is_cotis
) {
212 $curend = self
::getDueDate($this->zdb
, $this->_member
);
214 $dend = new \
DateTime($curend);
215 $now = date('Y-m-d');
216 $dnow = new \
DateTime($now);
218 // Member didn't renew on time
219 $this->_begin_date
= $now;
221 $this->_begin_date
= $curend;
224 $this->retrieveEndDate();
226 if (isset($args['payment_type'])) {
227 $this->_payment_type
= $args['payment_type'];
229 } elseif (is_object($args)) {
230 $this->loadFromRS($args);
233 $this->loadDynamicFields();
237 * Sets end contribution date
241 private function retrieveEndDate()
245 $bdate = new \
DateTime($this->_begin_date
);
246 if ($preferences->pref_beg_membership
!= '') {
247 //case beginning of membership
248 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
249 $edate = new \
DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
250 while ($edate <= $bdate) {
251 $edate->modify('+1 year');
254 if ($preferences->pref_membership_offermonths
> 0) {
255 //count days until end of membership date
256 $diff1 = (int)$bdate->diff($edate)->format('%a');
258 //count days between end of membership date and offered months
259 $tdate = clone $edate;
260 $tdate->modify('-' . $preferences->pref_membership_offermonths
. ' month');
261 $diff2 = (int)$edate->diff($tdate)->format('%a');
263 //when number of days until end of membership is less than for offered months, it's free :)
264 if ($diff1 <= $diff2) {
265 $edate->modify('+1 year');
269 $this->_end_date
= $edate->format('Y-m-d');
270 } elseif ($preferences->pref_membership_ext
!= '') {
271 //case membership extension
272 if ($this->_extension
== null) {
273 $this->_extension
= $preferences->pref_membership_ext
;
275 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
276 $edate = $bdate->add($dext);
277 $this->_end_date
= $edate->format('Y-m-d');
279 throw new \
RuntimeException(
280 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
286 * Loads a contribution from its id
288 * @param int $id the identifier for the contribution to load
290 * @return bool true if query succeed, false otherwise
292 public function load($id)
295 $select = $this->zdb
->select(self
::TABLE
, 'c');
297 array('a' => PREFIX_DB
. Adherent
::TABLE
),
298 'c.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
301 //restrict query on current member id if he's not admin nor staff member
302 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
305 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
307 ->equalTo('a.parent_id', $this->login
->id
)
310 ->equalTo('c.' . self
::PK
, $id)
313 $select->where
->equalTo(self
::PK
, $id);
316 $results = $this->zdb
->execute($select);
317 if ($results->count() > 0) {
318 $row = $results->current();
319 $this->loadFromRS($row);
323 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')',
328 } catch (Throwable
$e) {
330 'An error occurred attempting to load contribution #' . $id .
339 * Populate object from a resultset row
341 * @param ResultSet $r the resultset row
345 private function loadFromRS($r)
348 $this->_id
= (int)$r->$pk;
349 $this->_date
= $r->date_enreg
;
350 $this->_amount
= (int)$r->montant_cotis
;
351 //save original amount, we need it for transactions parts calculations
352 $this->_orig_amount
= (int)$r->montant_cotis
;
353 $this->_payment_type
= $r->type_paiement_cotis
;
354 $this->_info
= $r->info_cotis
;
355 $this->_begin_date
= $r->date_debut_cotis
;
356 $enddate = $r->date_fin_cotis
;
357 //do not work with knows bad dates...
358 //the one with BC comes from 0.63/pgsql demo... Why the hell a so
359 //strange date? don't know :(
361 $enddate !== '0000-00-00'
362 && $enddate !== '1901-01-01'
363 && $enddate !== '0001-01-01 BC'
365 $this->_end_date
= $r->date_fin_cotis
;
367 $adhpk = Adherent
::PK
;
368 $this->_member
= (int)$r->$adhpk;
370 $transpk = Transaction
::PK
;
371 if ($r->$transpk != '') {
372 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
375 $this->type
= (int)$r->id_type_cotis
;
376 $this->loadDynamicFields();
380 * Check posted values validity
382 * @param array $values All values to check, basically the $_POST array
383 * after sending the form
384 * @param array $required Array of required fields
385 * @param array $disabled Array of disabled fields
389 public function check($values, $required, $disabled)
392 $this->errors
= array();
394 $fields = array_keys($this->_fields
);
395 foreach ($fields as $key) {
396 //first, let's sanitize values
397 $key = strtolower($key);
398 $prop = '_' . $this->_fields
[$key]['propname'];
400 if (isset($values[$key])) {
401 $value = trim($values[$key]);
406 // if the field is enabled, check it
407 if (!isset($disabled[$key])) {
408 // fill up the adherent structure
409 //$this->$prop = stripslashes($value); //not relevant here!
411 // now, check validity
415 case 'date_debut_cotis':
416 case 'date_fin_cotis':
419 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
421 throw new \
Exception('Incorrect format');
423 $this->$prop = $d->format('Y-m-d');
424 } catch (Throwable
$e) {
426 'Wrong date format. field: ' . $key .
427 ', value: ' . $value . ', expected fmt: ' .
428 __("Y-m-d") . ' | ' . $e->getMessage(),
431 $this->errors
[] = str_replace(
438 $this->_fields
[$key]['label']
440 _T("- Wrong date format (%date_format) for %field!")
447 $this->_member
= (int)$value;
450 case ContributionsTypes
::PK
:
452 $this->type
= (int)$value;
455 case 'montant_cotis':
456 if (!empty($value)) {
457 $this->_amount
= $value;
459 $value = strtr($value, ',', '.');
460 if (!is_numeric($value) && $value !== '') {
461 $this->errors
[] = _T("- The amount must be an integer!");
464 case 'type_paiement_cotis':
465 $ptypes = new PaymentTypes(
470 $ptlist = $ptypes->getList();
471 if (isset($ptlist[$value])) {
472 $this->_payment_type
= $value;
474 $this->errors
[] = _T("- Unknown payment type");
478 $this->_info
= $value;
480 case Transaction
::PK
:
482 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
485 case 'duree_mois_cotis':
487 if (!is_numeric($value) ||
$value <= 0) {
488 $this->errors
[] = _T("- The duration must be a positive integer!");
490 $this->$prop = $value;
491 $this->retrieveEndDate();
498 // missing required fields?
499 foreach ($required as $key => $val) {
501 $prop = '_' . $this->_fields
[$key]['propname'];
503 !isset($disabled[$key])
504 && (!isset($this->$prop)
505 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
506 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
508 $this->errors
[] = str_replace(
510 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
511 _T("- Mandatory field %field empty.")
517 if ($this->_transaction
!= null && $this->_amount
!= null) {
518 $missing = $this->_transaction
->getMissingAmount();
519 //calculate new missing amount
520 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
522 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
526 if ($this->isFee() && count($this->errors
) == 0) {
527 $overlap = $this->checkOverlap();
528 if ($overlap !== true) {
529 //method directly return error message
530 $this->errors
[] = $overlap;
534 $this->dynamicsCheck($values, $required, $disabled);
536 if (count($this->errors
) > 0) {
538 'Some errors has been threw attempting to edit/store a contribution' .
539 print_r($this->errors
, true),
542 return $this->errors
;
545 'Contribution checked successfully.',
553 * Check that membership fees does not overlap
555 * @return boolean|string True if all is ok, false if error,
556 * error message if overlap
558 public function checkOverlap()
561 $select = $this->zdb
->select(self
::TABLE
, 'c');
563 array('date_debut_cotis', 'date_fin_cotis')
565 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
566 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
568 )->where([Adherent
::PK
=> $this->_member
])
569 ->where(array('cotis_extension' => new Expression('true')))
571 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
572 ->lessThan('date_debut_cotis', $this->_end_date
)
575 ->greaterThan('date_fin_cotis', $this->_begin_date
)
576 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
578 if ($this->id
!= '') {
579 $select->where
->notEqualTo(self
::PK
, $this->id
);
582 $results = $this->zdb
->execute($select);
583 if ($results->count() > 0) {
584 $result = $results->current();
585 $d = new \
DateTime($result->date_debut_cotis
);
587 return _T("- Membership period overlaps period starting at ") .
588 $d->format(__("Y-m-d"));
591 } catch (Throwable
$e) {
593 'An error occurred checking overlapping fee. ' . $e->getMessage(),
601 * Store the contribution
605 public function store()
607 global $hist, $emitter;
611 if (count($this->errors
) > 0) {
612 throw new \
RuntimeException(
613 'Existing errors prevents storing contribution: ' .
614 print_r($this->errors
, true)
619 $this->zdb
->connection
->beginTransaction();
621 $fields = self
::getDbFields($this->zdb
);
622 foreach ($fields as $field) {
623 $prop = '_' . $this->_fields
[$field]['propname'];
625 case ContributionsTypes
::PK
:
626 case Transaction
::PK
:
627 if (isset($this->$prop)) {
628 $values[$field] = $this->$prop->id
;
632 $values[$field] = $this->$prop;
637 //no end date, let's take database defaults
638 if (!$this->isFee() && !$this->_end_date
) {
639 unset($values['date_fin_cotis']);
643 if (!isset($this->_id
) ||
$this->_id
== '') {
644 //we're inserting a new contribution
645 unset($values[self
::PK
]);
647 $insert = $this->zdb
->insert(self
::TABLE
);
648 $insert->values($values);
649 $add = $this->zdb
->execute($insert);
651 if ($add->count() > 0) {
652 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
656 _T("Contribution added"),
657 Adherent
::getSName($this->zdb
, $this->_member
)
660 $event = 'contribution.add';
662 $hist->add(_T("Fail to add new contribution."));
663 throw new \
Exception(
664 'An error occurred inserting new contribution!'
668 //we're editing an existing contribution
669 $update = $this->zdb
->update(self
::TABLE
);
670 $update->set($values)->where([self
::PK
=> $this->_id
]);
671 $edit = $this->zdb
->execute($update);
673 //edit == 0 does not mean there were an error, but that there
674 //were nothing to change
675 if ($edit->count() > 0) {
677 _T("Contribution updated"),
678 Adherent
::getSName($this->zdb
, $this->_member
)
682 if ($edit === false) {
683 throw new \
Exception(
684 'An error occurred updating contribution # ' . $this->_id
. '!'
688 $event = 'contribution.edit';
691 if ($this->isFee()) {
692 $this->updateDeadline();
697 $success = $this->dynamicsStore(true);
700 $this->zdb
->connection
->commit();
701 $this->_orig_amount
= $this->_amount
;
703 //send event at the end of process, once all has been stored
704 if ($event !== null) {
705 $emitter->emit($event, $this);
709 } catch (Throwable
$e) {
710 if ($this->zdb
->connection
->inTransaction()) {
711 $this->zdb
->connection
->rollBack();
718 * Update member dead line
722 private function updateDeadline()
725 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
727 if ($due_date != '') {
728 $date_fin_update = $due_date;
730 $date_fin_update = new Expression('NULL');
733 $update = $this->zdb
->update(Adherent
::TABLE
);
735 array('date_echeance' => $date_fin_update)
737 [Adherent
::PK
=> $this->_member
]
739 $this->zdb
->execute($update);
741 } catch (Throwable
$e) {
743 'An error occurred updating member ' . $this->_member
.
753 * Remove contribution from database
755 * @param boolean $transaction Activate transaction mode (defaults to true)
759 public function remove($transaction = true)
765 $this->zdb
->connection
->beginTransaction();
768 $delete = $this->zdb
->delete(self
::TABLE
);
769 $delete->where([self
::PK
=> $this->_id
]);
770 $del = $this->zdb
->execute($delete);
771 if ($del->count() > 0) {
772 $this->updateDeadline();
773 $this->dynamicsRemove(true);
776 'Contribution has not been removed!',
782 $this->zdb
->connection
->commit();
784 $emitter->emit('contribution.remove', $this);
786 } catch (Throwable
$e) {
788 $this->zdb
->connection
->rollBack();
791 'An error occurred trying to remove contribution #' .
792 $this->_id
. ' | ' . $e->getMessage(),
802 * @param string $field Field name
806 public function getFieldLabel($field)
808 $label = $this->_fields
[$field]['label'];
809 if ($this->isFee() && $field == 'date_debut_cotis') {
810 $label = $this->_fields
[$field]['cotlabel'];
813 $label = str_replace(' ', ' ', $label);
814 //remove trailing ':' and then trim
815 $label = trim(trim($label, ':'));
820 * Retrieve fields from database
822 * @param Db $zdb Database instance
826 public static function getDbFields(Db
$zdb)
828 $columns = $zdb->getColumns(self
::TABLE
);
830 foreach ($columns as $col) {
831 $fields[] = $col->getName();
837 * Get the relevant CSS class for current contribution
839 * @return string current contribution row class
841 public function getRowClass()
843 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
844 'cotis-normal' : 'cotis-give';
848 * Retrieve member due date
850 * @param Db $zdb Database instance
851 * @param integer $member_id Member identifier
855 public static function getDueDate(Db
$zdb, $member_id)
861 $select = $zdb->select(self
::TABLE
, 'c');
864 'max_date' => new Expression('MAX(date_fin_cotis)')
867 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
868 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
871 [Adherent
::PK
=> $member_id]
873 array('cotis_extension' => new Expression('true'))
876 $results = $zdb->execute($select);
877 $result = $results->current();
878 $due_date = $result->max_date
;
880 //avoid bad dates in postgres and bad mysql return from zenddb
881 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
885 } catch (Throwable
$e) {
887 'An error occurred trying to retrieve member\'s due date',
895 * Detach a contribution from a transaction
897 * @param Db $zdb Database instance
898 * @param Login $login Login instance
899 * @param int $trans_id Transaction identifier
900 * @param int $contrib_id Contribution identifier
904 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
907 //first, we check if contribution is part of transaction
908 $c = new Contribution($zdb, $login, (int)$contrib_id);
909 if ($c->isTransactionPartOf($trans_id)) {
910 $update = $zdb->update(self
::TABLE
);
912 array(Transaction
::PK
=> null)
914 [self
::PK
=> $contrib_id]
916 $zdb->execute($update);
920 'Contribution #' . $contrib_id .
921 ' is not actually part of transaction #' . $trans_id,
926 } catch (Throwable
$e) {
928 'Unable to detach contribution #' . $contrib_id .
929 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
937 * Set a contribution as a transaction part
939 * @param Db $zdb Database instance
940 * @param int $trans_id Transaction identifier
941 * @param int $contrib_id Contribution identifier
945 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
948 $update = $zdb->update(self
::TABLE
);
950 array(Transaction
::PK
=> $trans_id)
951 )->where([self
::PK
=> $contrib_id]);
953 $zdb->execute($update);
955 } catch (Throwable
$e) {
957 'Unable to attach contribution #' . $contrib_id .
958 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
966 * Is current contribution a membership fee
970 public function isFee()
972 return $this->_is_cotis
;
976 * Is current contribution part of specified transaction
978 * @param int $id Transaction identifier
982 public function isTransactionPartOf($id)
984 if ($this->isTransactionPart()) {
985 return $id == $this->_transaction
->id
;
992 * Is current contribution part of transaction
996 public function isTransactionPart()
998 return $this->_transaction
!= null;
1002 * Execute post contribution script
1004 * @param ExternalScript $es External script to execute
1005 * @param array $extra Extra information on contribution
1007 * @param array $pextra Extra information on payment
1010 * @return mixed Script return value on success, values and script output on fail
1012 public function executePostScript(
1017 global $preferences;
1020 'type' => $this->getPaymentType()
1023 if ($pextra !== null && is_array($pextra)) {
1024 $payment = array_merge($payment, $pextra);
1027 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1028 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1031 $voucher_path = null;
1032 if ($this->_id
!== null) {
1033 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1034 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1035 $voucher_path = $voucher->getPath();
1039 'id' => (int)$this->_id
,
1040 'date' => $this->_date
,
1041 'type' => $this->getRawType(),
1042 'amount' => $this->amount
,
1043 'voucher' => $voucher_path,
1044 'category' => array(
1045 'id' => $this->type
->id
,
1046 'label' => $this->type
->libelle
1048 'payment' => $payment
1051 if ($this->_member
!== null) {
1052 $m = new Adherent($this->zdb
, (int)$this->_member
);
1054 'id' => (int)$this->_member
,
1055 'name' => $m->sfullname
,
1056 'email' => $m->email
,
1057 'organization' => ($m->isCompany() ?
1 : 0),
1060 'label' => $m->sstatus
1062 'country' => $m->country
1065 if ($m->isCompany()) {
1066 $member['organization_name'] = $m->company_name
;
1069 $contrib['member'] = $member;
1072 if ($extra !== null && is_array($extra)) {
1073 $contrib = array_merge($contrib, $extra);
1076 $res = $es->send($contrib);
1078 if ($res !== true) {
1080 'An error occurred calling post contribution ' .
1081 "script:\n" . $es->getOutput(),
1084 $res = _T("Contribution information") . "\n";
1085 $res .= print_r($contrib, true);
1086 $res .= "\n\n" . _T("Script output") . "\n";
1087 $res .= $es->getOutput();
1093 * Get raw contribution type
1097 public function getRawType()
1099 if ($this->isFee()) {
1100 return 'membership';
1107 * Get contribution type label
1111 public function getTypeLabel()
1113 if ($this->isFee()) {
1114 return _T("Membership");
1116 return _T("Donation");
1121 * Get payment type label
1125 public function getPaymentType()
1127 if ($this->_payment_type
=== null) {
1131 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1132 return $ptype->getName(false);
1136 * Global getter method
1138 * @param string $name name of the property we want to retrieve
1140 * @return false|object the called property
1142 public function __get($name)
1145 $forbidden = array('is_cotis');
1146 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1147 'raw_begin_date', 'raw_end_date'
1150 $rname = '_' . $name;
1152 if (in_array($name, $forbidden)) {
1154 "Call to __get for '$name' is forbidden!",
1160 return $this->isFee();
1163 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1166 property_exists($this, $rname)
1167 ||
in_array($name, $virtuals)
1171 case 'raw_begin_date':
1172 case 'raw_end_date':
1173 $rname = '_' . substr($name, 4);
1174 if ($this->$rname != '') {
1176 $d = new \
DateTime($this->$rname);
1178 } catch (Throwable
$e) {
1179 //oops, we've got a bad date :/
1181 'Bad date (' . $this->$rname . ') | ' .
1192 if ($this->$rname != '') {
1194 $d = new \
DateTime($this->$rname);
1195 return $d->format(__("Y-m-d"));
1196 } catch (Throwable
$e) {
1197 //oops, we've got a bad date :/
1199 'Bad date (' . $this->$rname . ') | ' .
1203 return $this->$rname;
1208 if ($this->_is_cotis
) {
1209 $date_end = new \
DateTime($this->_end_date
);
1210 $date_start = new \
DateTime($this->_begin_date
);
1211 $diff = $date_end->diff($date_start);
1212 return $diff->format('%y') * 12 +
$diff->format('%m');
1217 case 'spayment_type':
1218 return $this->getPaymentType();
1221 if ($this->_is_cotis
=== null) {
1224 return ($this->isFee()) ?
1225 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1228 return $this->$rname;
1233 "Unknown property '$rname'",
1241 * Global setter method
1243 * @param string $name name of the property we want to assign a value to
1244 * @param object $value a relevant value for the property
1248 public function __set($name, $value)
1250 global $preferences;
1252 $forbidden = array('fields', 'is_cotis', 'end_date');
1254 if (!in_array($name, $forbidden)) {
1255 $rname = '_' . $name;
1258 if (is_int($value)) {
1259 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1262 'Trying to set a transaction from an id that is not an integer.',
1268 if (is_int($value)) {
1270 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1271 //set is_cotis according to type
1272 if ($this->$rname->extension
== 1) {
1273 $this->_is_cotis
= true;
1275 $this->_is_cotis
= false;
1279 'Trying to set a type from an id that is not an integer.',
1286 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1288 throw new \
Exception('Incorrect format');
1290 $this->_begin_date
= $d->format('Y-m-d');
1291 } catch (Throwable
$e) {
1293 'Wrong date format. field: ' . $name .
1294 ', value: ' . $value . ', expected fmt: ' .
1295 __("Y-m-d") . ' | ' . $e->getMessage(),
1298 $this->errors
[] = str_replace(
1305 $this->_fields
['date_debut_cotis']['label']
1307 _T("- Wrong date format (%date_format) for %field!")
1312 if (is_numeric($value) && $value > 0) {
1313 $this->$rname = $value;
1316 'Trying to set an amount with a non numeric value, ' .
1317 'or with a zero value',
1323 if (is_int($value)) {
1325 $this->$rname = $value;
1328 case 'payment_type':
1329 $ptypes = new PaymentTypes(
1334 $list = $ptypes->getList();
1335 if (isset($list[$value])) {
1336 $this->_payment_type
= $value;
1339 'Unknown payment type ' . $value,
1346 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1356 * Flag creation mail sending
1358 * @param boolean $send True (default) to send creation email
1360 * @return Contribution
1362 public function setSendmail($send = true)
1364 $this->sendmail
= $send;
1369 * Should we send administrative emails to member?
1373 public function sendEMail()
1375 return $this->sendmail
;
1379 * Handle files (dynamics files)
1381 * @param array $files Files sent
1383 * @return array|true
1385 public function handleFiles($files)
1389 $this->dynamicsFiles($files);
1391 if (count($this->errors
) > 0) {
1393 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1394 print_r($this->errors
, true),
1397 return $this->errors
;
1404 * Get required fields list
1408 public function getRequired(): array
1411 'id_type_cotis' => 1,
1414 'date_debut_cotis' => 1,
1415 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1416 'montant_cotis' => $this->isFee() ?
1 : 0
1421 * Can current logged-in user display contribution
1423 * @param Login $login Login instance
1427 public function canShow(Login
$login): bool
1429 //non-logged-in members cannot show contributions
1430 if (!$login->isLogged()) {
1434 //admin and staff users can edit, as well as member itself
1435 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1439 //parent can see their children contributions
1440 $parent = new Adherent($this->zdb
);
1443 ->enableDep('children')
1444 ->load($this->login
->id
);
1445 if ($parent->hasChildren()) {
1446 foreach ($parent->children
as $child) {
1447 if ($child->id
=== $this->_member
) {