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
;
50 * Contribution class for galette
51 * Manage membership fees and donations.
56 * @author Johan Cwiklinski <johan@x-tnd.be>
57 * @copyright 2010-2021 The Galette Team
58 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
59 * @link http://galette.tuxfamily.org
60 * @since Available since 0.7dev - 2010-03-11
66 public const TABLE
= 'cotisations';
67 public const PK
= 'id_cotis';
69 public const TYPE_FEE
= 'fee';
70 public const TYPE_DONATION
= 'donation';
77 private $_payment_type;
78 private $_orig_amount;
82 private $_transaction = null;
86 //fields list and their translation
96 private $sendmail = false;
101 * @param Db $zdb Database
102 * @param Login $login Login instance
103 * @param null|int|ResultSet $args Either a ResultSet row to load
104 * a specific contribution, or an type id
105 * to just instantiate object
107 public function __construct(Db
$zdb, Login
$login, $args = null)
110 $this->login
= $login;
113 $this->_payment_type
= (int)$preferences->pref_default_paymenttype
;
116 * Fields configuration. Each field is an array and must reflect:
119 * (string) property name
122 * I'd prefer a static private variable for this...
123 * But call to the _T function does not seem to be allowed there :/
125 $this->_fields
= array(
127 'label' => null, //not a field in the form
130 Adherent
::PK
=> array(
131 'label' => _T("Contributor:"),
132 'propname' => 'member'
134 ContributionsTypes
::PK
=> array(
135 'label' => _T("Contribution type:"),
138 'montant_cotis' => array(
139 'label' => _T("Amount:"),
140 'propname' => 'amount'
142 'type_paiement_cotis' => array(
143 'label' => _T("Payment type:"),
144 'propname' => 'payment_type'
146 'info_cotis' => array(
147 'label' => _T("Comments:"),
150 'date_enreg' => array(
151 'label' => null, //not a field in the form
154 'date_debut_cotis' => array(
155 'label' => _T("Date of contribution:"),
156 'cotlabel' => _T("Start date of membership:"), //if contribution is a membership fee, label differs
157 'propname' => 'begin_date'
159 'date_fin_cotis' => array(
160 'label' => _T("End date of membership:"),
161 'propname' => 'end_date'
163 Transaction
::PK
=> array(
164 'label' => null, //not a field in the form
165 'propname' => 'transaction'
167 //this one is not really a field, but is required in some cases...
168 //adding it here make simplier to check required fields
169 'duree_mois_cotis' => array(
170 'label' => _T("Membership extension:"),
171 'propname' => 'extension'
176 } elseif (is_array($args)) {
177 $this->_date
= date("Y-m-d");
178 if (isset($args['adh']) && $args['adh'] != '') {
179 $this->_member
= (int)$args['adh'];
181 if (isset($args['trans'])) {
182 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
183 if (!isset($this->_member
)) {
184 $this->_member
= (int)$this->_transaction
->member
;
186 $this->_amount
= $this->_transaction
->getMissingAmount();
188 $this->type
= (int)$args['type'];
189 //calculate begin date for membership fee
190 $this->_begin_date
= $this->_date
;
191 if ($this->_is_cotis
) {
192 $curend = self
::getDueDate($this->zdb
, $this->_member
);
194 $dend = new \
DateTime($curend);
195 $now = date('Y-m-d');
196 $dnow = new \
DateTime($now);
198 // Member didn't renew on time
199 $this->_begin_date
= $now;
201 $this->_begin_date
= $curend;
204 $this->retrieveEndDate();
206 if (isset($args['payment_type'])) {
207 $this->_payment_type
= $args['payment_type'];
209 } elseif (is_object($args)) {
210 $this->loadFromRS($args);
213 $this->loadDynamicFields();
217 * Sets end contribution date
221 private function retrieveEndDate()
225 $bdate = new \
DateTime($this->_begin_date
);
226 if ($preferences->pref_beg_membership
!= '') {
227 //case beginning of membership
228 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
229 $edate = new \
DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
230 while ($edate <= $bdate) {
231 $edate->modify('+1 year');
234 if ($preferences->pref_membership_offermonths
> 0) {
235 //count days until end of membership date
236 $diff1 = (int)$bdate->diff($edate)->format('%a');
238 //count days beetween end of membership date and offered months
239 $tdate = clone $edate;
240 $tdate->modify('-' . $preferences->pref_membership_offermonths
. ' month');
241 $diff2 = (int)$edate->diff($tdate)->format('%a');
243 //when number of days until end of membership is less than for offered months, it's free :)
244 if ($diff1 <= $diff2) {
245 $edate->modify('+1 year');
249 $this->_end_date
= $edate->format('Y-m-d');
250 } elseif ($preferences->pref_membership_ext
!= '') {
251 //case membership extension
252 if ($this->_extension
== null) {
253 $this->_extension
= $preferences->pref_membership_ext
;
255 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
256 $edate = $bdate->add($dext);
257 $this->_end_date
= $edate->format('Y-m-d');
259 throw new \
RuntimeException(
260 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
266 * Loads a contribution from its id
268 * @param int $id the identifier for the contribution to load
270 * @return bool true if query succeed, false otherwise
272 public function load($id)
275 $select = $this->zdb
->select(self
::TABLE
, 'c');
277 array('a' => PREFIX_DB
. Adherent
::TABLE
),
278 'c.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
281 //restrict query on current member id if he's not admin nor staff member
282 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
283 if (!$this->login
->isGroupManager()) {
286 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
288 ->equalTo('a.parent_id', $this->login
->id
)
291 ->equalTo('c.' . self
::PK
, $id)
295 Adherent
::PK
=> $this->login
->id
,
300 $select->where
->equalTo(self
::PK
, $id);
303 $results = $this->zdb
->execute($select);
304 if ($results->count() > 0) {
305 $row = $results->current();
306 $this->loadFromRS($row);
309 throw new \
Exception(
310 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')'
313 } catch (Throwable
$e) {
315 'An error occurred attempting to load contribution #' . $id .
324 * Populate object from a resultset row
326 * @param ResultSet $r the resultset row
330 private function loadFromRS($r)
333 $this->_id
= (int)$r->$pk;
334 $this->_date
= $r->date_enreg
;
335 $this->_amount
= $r->montant_cotis
;
336 //save original amount, we need it for transactions parts calculations
337 $this->_orig_amount
= $r->montant_cotis
;
338 $this->_payment_type
= $r->type_paiement_cotis
;
339 $this->_info
= $r->info_cotis
;
340 $this->_begin_date
= $r->date_debut_cotis
;
341 $enddate = $r->date_fin_cotis
;
342 //do not work with knows bad dates...
343 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
344 //strange date? don't know :(
346 $enddate !== '0000-00-00'
347 && $enddate !== '1901-01-01'
348 && $enddate !== '0001-01-01 BC'
350 $this->_end_date
= $r->date_fin_cotis
;
352 $adhpk = Adherent
::PK
;
353 $this->_member
= (int)$r->$adhpk;
355 $transpk = Transaction
::PK
;
356 if ($r->$transpk != '') {
357 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
360 $this->type
= (int)$r->id_type_cotis
;
361 $this->loadDynamicFields();
365 * Check posted values validity
367 * @param array $values All values to check, basically the $_POST array
368 * after sending the form
369 * @param array $required Array of required fields
370 * @param array $disabled Array of disabled fields
374 public function check($values, $required, $disabled)
377 $this->errors
= array();
379 $fields = array_keys($this->_fields
);
380 foreach ($fields as $key) {
381 //first, let's sanitize values
382 $key = strtolower($key);
383 $prop = '_' . $this->_fields
[$key]['propname'];
385 if (isset($values[$key])) {
386 $value = trim($values[$key]);
391 // if the field is enabled, check it
392 if (!isset($disabled[$key])) {
393 // fill up the adherent structure
394 //$this->$prop = stripslashes($value); //not relevant here!
396 // now, check validity
400 case 'date_debut_cotis':
401 case 'date_fin_cotis':
404 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
406 throw new \
Exception('Incorrect format');
408 $this->$prop = $d->format('Y-m-d');
409 } catch (Throwable
$e) {
411 'Wrong date format. field: ' . $key .
412 ', value: ' . $value . ', expected fmt: ' .
413 __("Y-m-d") . ' | ' . $e->getMessage(),
416 $this->errors
[] = str_replace(
423 $this->_fields
[$key]['label']
425 _T("- Wrong date format (%date_format) for %field!")
432 $this->_member
= (int)$value;
435 case ContributionsTypes
::PK
:
437 $this->type
= (int)$value;
440 case 'montant_cotis':
441 $this->_amount
= $value;
442 $value = strtr($value, ',', '.');
443 if (!is_numeric($value) && $value !== '') {
444 $this->errors
[] = _T("- The amount must be an integer!");
447 case 'type_paiement_cotis':
448 $ptypes = new PaymentTypes(
453 $ptlist = $ptypes->getList();
454 if (isset($ptlist[$value])) {
455 $this->_payment_type
= $value;
457 $this->errors
[] = _T("- Unknown payment type");
461 $this->_info
= $value;
463 case Transaction
::PK
:
465 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
468 case 'duree_mois_cotis':
470 if (!is_numeric($value) ||
$value <= 0) {
471 $this->errors
[] = _T("- The duration must be a positive integer!");
473 $this->$prop = $value;
474 $this->retrieveEndDate();
481 // missing required fields?
482 foreach ($required as $key => $val) {
484 $prop = '_' . $this->_fields
[$key]['propname'];
486 !isset($disabled[$key])
487 && (!isset($this->$prop)
488 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
489 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
491 $this->errors
[] = str_replace(
493 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
494 _T("- Mandatory field %field empty.")
500 if ($this->_transaction
!= null && $this->_amount
!= null) {
501 $missing = $this->_transaction
->getMissingAmount();
502 //calculate new missing amount
503 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
505 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
509 if ($this->isFee() && count($this->errors
) == 0) {
510 $overlap = $this->checkOverlap();
511 if ($overlap !== true) {
512 if ($overlap === false) {
513 $this->errors
[] = _T("An error occurred checking overlapping fees :(");
515 //method directly return error message
516 $this->errors
[] = $overlap;
521 $this->dynamicsCheck($values, $required, $disabled);
523 if (count($this->errors
) > 0) {
525 'Some errors has been threw attempting to edit/store a contribution' .
526 print_r($this->errors
, true),
529 return $this->errors
;
532 'Contribution checked successfully.',
540 * Check that membership fees does not overlap
542 * @return boolean|string True if all is ok, false if error,
543 * error message if overlap
545 public function checkOverlap()
548 $select = $this->zdb
->select(self
::TABLE
, 'c');
550 array('date_debut_cotis', 'date_fin_cotis')
552 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
553 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
555 )->where(Adherent
::PK
. ' = ' . $this->_member
)
556 ->where(array('cotis_extension' => new Expression('true')))
558 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
559 ->lessThan('date_debut_cotis', $this->_end_date
)
562 ->greaterThan('date_fin_cotis', $this->_begin_date
)
563 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
565 if ($this->id
!= '') {
566 $select->where(self
::PK
. ' != ' . $this->id
);
569 $results = $this->zdb
->execute($select);
570 if ($results->count() > 0) {
571 $result = $results->current();
572 $d = new \
DateTime($result->date_debut_cotis
);
574 return _T("- Membership period overlaps period starting at ") .
575 $d->format(__("Y-m-d"));
578 } catch (Throwable
$e) {
580 'An error occurred checking overlapping fee. ' . $e->getMessage(),
588 * Store the contribution
592 public function store()
594 global $hist, $emitter;
598 if (count($this->errors
) > 0) {
599 throw new \
RuntimeException(
600 'Existing errors prevents storing contribution: ' .
601 print_r($this->errors
, true)
606 $this->zdb
->connection
->beginTransaction();
608 $fields = self
::getDbFields($this->zdb
);
609 foreach ($fields as $field) {
610 $prop = '_' . $this->_fields
[$field]['propname'];
612 case ContributionsTypes
::PK
:
613 case Transaction
::PK
:
614 if (isset($this->$prop)) {
615 $values[$field] = $this->$prop->id
;
619 $values[$field] = $this->$prop;
624 //no end date, let's take database defaults
625 if (!$this->isFee() && !$this->_end_date
) {
626 unset($values['date_fin_cotis']);
630 if (!isset($this->_id
) ||
$this->_id
== '') {
631 //we're inserting a new contribution
632 unset($values[self
::PK
]);
634 $insert = $this->zdb
->insert(self
::TABLE
);
635 $insert->values($values);
636 $add = $this->zdb
->execute($insert);
638 if ($add->count() > 0) {
639 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
643 _T("Contribution added"),
644 Adherent
::getSName($this->zdb
, $this->_member
)
647 $event = 'contribution.add';
649 $hist->add(_T("Fail to add new contribution."));
650 throw new \
Exception(
651 'An error occurred inserting new contribution!'
655 //we're editing an existing contribution
656 $update = $this->zdb
->update(self
::TABLE
);
657 $update->set($values)->where(
658 self
::PK
. '=' . $this->_id
660 $edit = $this->zdb
->execute($update);
662 //edit == 0 does not mean there were an error, but that there
663 //were nothing to change
664 if ($edit->count() > 0) {
666 _T("Contribution updated"),
667 Adherent
::getSName($this->zdb
, $this->_member
)
671 if ($edit === false) {
672 throw new \
Exception(
673 'An error occurred updating contribution # ' . $this->_id
. '!'
677 $event = 'contribution.edit';
680 if ($this->isFee()) {
681 $deadline = $this->updateDeadline();
682 if ($deadline !== true) {
683 //if something went wrong, we roll back transaction
684 throw new \
Exception('An error occurred updating member\'s deadline');
690 $success = $this->dynamicsStore(true);
693 $this->zdb
->connection
->commit();
694 $this->_orig_amount
= $this->_amount
;
696 //send event at the end of process, once all has been stored
697 if ($event !== null) {
698 $emitter->emit($event, $this);
702 } catch (Throwable
$e) {
703 if ($this->zdb
->connection
->inTransaction()) {
704 $this->zdb
->connection
->rollBack();
711 * Update member dead line
715 private function updateDeadline()
718 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
720 if ($due_date != '') {
721 $date_fin_update = $due_date;
723 $date_fin_update = new Expression('NULL');
726 $update = $this->zdb
->update(Adherent
::TABLE
);
728 array('date_echeance' => $date_fin_update)
730 Adherent
::PK
. '=' . $this->_member
732 $this->zdb
->execute($update);
734 } catch (Throwable
$e) {
736 'An error occurred updating member ' . $this->_member
.
746 * Remove contribution from database
748 * @param boolean $transaction Activate transaction mode (defaults to true)
752 public function remove($transaction = true)
758 $this->zdb
->connection
->beginTransaction();
761 $delete = $this->zdb
->delete(self
::TABLE
);
762 $delete->where(self
::PK
. ' = ' . $this->_id
);
763 $del = $this->zdb
->execute($delete);
764 if ($del->count() > 0) {
765 $this->updateDeadline();
766 $this->dynamicsRemove(true);
768 throw new \
RuntimeException(
769 'Contribution has not been removed!'
773 $this->zdb
->connection
->commit();
775 $emitter->emit('contribution.remove', $this);
777 } catch (Throwable
$e) {
779 $this->zdb
->connection
->rollBack();
782 'An error occurred trying to remove contribution #' .
783 $this->_id
. ' | ' . $e->getMessage(),
793 * @param string $field Field name
797 public function getFieldLabel($field)
799 $label = $this->_fields
[$field]['label'];
800 if ($this->isFee() && $field == 'date_debut_cotis') {
801 $label = $this->_fields
[$field]['cotlabel'];
804 $label = str_replace(' ', ' ', $label);
805 //remove trailing ':' and then trim
806 $label = trim(trim($label, ':'));
811 * Retrieve fields from database
813 * @param Db $zdb Database instance
817 public static function getDbFields(Db
$zdb)
819 $columns = $zdb->getColumns(self
::TABLE
);
821 foreach ($columns as $col) {
822 $fields[] = $col->getName();
828 * Get the relevant CSS class for current contribution
830 * @return string current contribution row class
832 public function getRowClass()
834 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
835 'cotis-normal' : 'cotis-give';
839 * Retrieve member due date
841 * @param Db $zdb Database instance
842 * @param integer $member_id Member identifier
846 public static function getDueDate(Db
$zdb, $member_id)
852 $select = $zdb->select(self
::TABLE
, 'c');
855 'max_date' => new Expression('MAX(date_fin_cotis)')
858 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
859 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
862 Adherent
::PK
. ' = ' . $member_id
864 array('cotis_extension' => new Expression('true'))
867 $results = $zdb->execute($select);
868 $result = $results->current();
869 $due_date = $result->max_date
;
871 //avoid bad dates in postgres and bad mysql return from zenddb
872 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
876 } catch (Throwable
$e) {
878 'An error occurred trying to retrieve member\'s due date',
886 * Detach a contribution from a transaction
888 * @param Db $zdb Database instance
889 * @param Login $login Login instance
890 * @param int $trans_id Transaction identifier
891 * @param int $contrib_id Contribution identifier
895 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
898 //first, we check if contribution is part of transaction
899 $c = new Contribution($zdb, $login, (int)$contrib_id);
900 if ($c->isTransactionPartOf($trans_id)) {
901 $update = $zdb->update(self
::TABLE
);
903 array(Transaction
::PK
=> null)
905 self
::PK
. ' = ' . $contrib_id
907 $zdb->execute($update);
911 'Contribution #' . $contrib_id .
912 ' is not actually part of transaction #' . $trans_id,
917 } catch (Throwable
$e) {
919 'Unable to detach contribution #' . $contrib_id .
920 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
928 * Set a contribution as a transaction part
930 * @param Db $zdb Database instance
931 * @param int $trans_id Transaction identifier
932 * @param int $contrib_id Contribution identifier
936 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
939 $update = $zdb->update(self
::TABLE
);
941 array(Transaction
::PK
=> $trans_id)
942 )->where(self
::PK
. ' = ' . $contrib_id);
944 $zdb->execute($update);
946 } catch (Throwable
$e) {
948 'Unable to attach contribution #' . $contrib_id .
949 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
957 * Is current contribution a membership fee
961 public function isFee()
963 return $this->_is_cotis
;
967 * Is current contribution part of specified transaction
969 * @param int $id Transaction identifier
973 public function isTransactionPartOf($id)
975 if ($this->isTransactionPart()) {
976 return $id == $this->_transaction
->id
;
983 * Is current contribution part of transaction
987 public function isTransactionPart()
989 return $this->_transaction
!= null;
993 * Execute post contribution script
995 * @param ExternalScript $es External script to execute
996 * @param array $extra Extra information on contribution
998 * @param array $pextra Extra information on payment
1001 * @return mixed Script return value on success, values and script output on fail
1003 public function executePostScript(
1008 global $preferences;
1011 'type' => $this->getPaymentType()
1014 if ($pextra !== null && is_array($pextra)) {
1015 $payment = array_merge($payment, $pextra);
1018 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1019 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1022 $voucher_path = null;
1023 if ($this->_id
!== null) {
1024 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1025 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1026 $voucher_path = $voucher->getPath();
1030 'id' => (int)$this->_id
,
1031 'date' => $this->_date
,
1032 'type' => $this->getRawType(),
1033 'amount' => $this->amount
,
1034 'voucher' => $voucher_path,
1035 'category' => array(
1036 'id' => $this->type
->id
,
1037 'label' => $this->type
->libelle
1039 'payment' => $payment
1042 if ($this->_member
!== null) {
1043 $m = new Adherent($this->zdb
, (int)$this->_member
);
1045 'id' => (int)$this->_member
,
1046 'name' => $m->sfullname
,
1047 'email' => $m->email
,
1048 'organization' => ($m->isCompany() ?
1 : 0),
1051 'label' => $m->sstatus
1053 'country' => $m->country
1056 if ($m->isCompany()) {
1057 $member['organization_name'] = $m->company_name
;
1060 $contrib['member'] = $member;
1063 if ($extra !== null && is_array($extra)) {
1064 $contrib = array_merge($contrib, $extra);
1067 $res = $es->send($contrib);
1069 if ($res !== true) {
1071 'An error occurred calling post contribution ' .
1072 "script:\n" . $es->getOutput(),
1075 $res = _T("Contribution information") . "\n";
1076 $res .= print_r($contrib, true);
1077 $res .= "\n\n" . _T("Script output") . "\n";
1078 $res .= $es->getOutput();
1084 * Get raw contribution type
1088 public function getRawType()
1090 if ($this->isFee()) {
1091 return 'membership';
1098 * Get contribution type label
1102 public function getTypeLabel()
1104 if ($this->isFee()) {
1105 return _T("Membership");
1107 return _T("Donation");
1112 * Get payment type label
1116 public function getPaymentType()
1118 if ($this->_payment_type
=== null) {
1122 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1123 return $ptype->getName(false);
1127 * Global getter method
1129 * @param string $name name of the property we want to retrieve
1131 * @return false|object the called property
1133 public function __get($name)
1136 $forbidden = array('is_cotis');
1137 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1138 'raw_begin_date', 'raw_end_date'
1141 $rname = '_' . $name;
1143 if (in_array($name, $forbidden)) {
1145 "Call to __get for '$name' is forbidden!",
1151 return $this->isFee();
1154 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1157 property_exists($this, $rname)
1158 ||
in_array($name, $virtuals)
1162 case 'raw_begin_date':
1163 case 'raw_end_date':
1164 $rname = '_' . substr($name, 4);
1165 if ($this->$rname != '') {
1167 $d = new \
DateTime($this->$rname);
1169 } catch (Throwable
$e) {
1170 //oops, we've got a bad date :/
1172 'Bad date (' . $this->$rname . ') | ' .
1183 if ($this->$rname != '') {
1185 $d = new \
DateTime($this->$rname);
1186 return $d->format(__("Y-m-d"));
1187 } catch (Throwable
$e) {
1188 //oops, we've got a bad date :/
1190 'Bad date (' . $this->$rname . ') | ' .
1194 return $this->$rname;
1199 if ($this->_is_cotis
) {
1200 $date_end = new \
DateTime($this->_end_date
);
1201 $date_start = new \
DateTime($this->_begin_date
);
1202 $diff = $date_end->diff($date_start);
1203 return $diff->format('%y') * 12 +
$diff->format('%m');
1208 case 'spayment_type':
1209 if ($this->_payment_type
=== null) {
1213 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1214 return $ptype->getName();
1218 if ($this->_is_cotis
=== null) {
1221 return ($this->isFee()) ?
1222 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1225 return $this->$rname;
1230 "Unknown property '$rname'",
1238 * Global setter method
1240 * @param string $name name of the property we want to assign a value to
1241 * @param object $value a relevant value for the property
1245 public function __set($name, $value)
1247 global $preferences;
1249 $forbidden = array('fields', 'is_cotis', 'end_date');
1251 if (!in_array($name, $forbidden)) {
1252 $rname = '_' . $name;
1255 if (is_int($value)) {
1256 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1259 'Trying to set a transaction from an id that is not an integer.',
1265 if (is_int($value)) {
1267 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1268 //set is_cotis according to type
1269 if ($this->$rname->extension
== 1) {
1270 $this->_is_cotis
= true;
1272 $this->_is_cotis
= false;
1276 'Trying to set a type from an id that is not an integer.',
1283 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1285 throw new \
Exception('Incorrect format');
1287 $this->_begin_date
= $d->format('Y-m-d');
1288 } catch (Throwable
$e) {
1290 'Wrong date format. field: ' . $name .
1291 ', value: ' . $value . ', expected fmt: ' .
1292 __("Y-m-d") . ' | ' . $e->getMessage(),
1295 $this->errors
[] = str_replace(
1302 $this->_fields
['date_debut_cotis']['label']
1304 _T("- Wrong date format (%date_format) for %field!")
1309 if (is_numeric($value) && $value > 0) {
1310 $this->$rname = $value;
1313 'Trying to set an amount with a non numeric value, ' .
1314 'or with a zero value',
1320 if (is_int($value)) {
1322 $this->$rname = $value;
1325 case 'payment_type':
1326 $ptypes = new PaymentTypes(
1331 $list = $ptypes->getList();
1332 if (isset($list[$value])) {
1333 $this->_payment_type
= $value;
1336 'Unknown payment type ' . $value,
1343 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1353 * Flag creation mail sending
1355 * @param boolean $send True (default) to send creation email
1357 * @return Contribution
1359 public function setSendmail($send = true)
1361 $this->sendmail
= $send;
1366 * Should we send administrative emails to member?
1370 public function sendEMail()
1372 return $this->sendmail
;
1376 * Handle files (dynamics files)
1378 * @param array $files Files sent
1380 * @return array|true
1382 public function handleFiles($files)
1386 $this->dynamicsFiles($files);
1388 if (count($this->errors
) > 0) {
1390 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1391 print_r($this->errors
, true),
1394 return $this->errors
;
1401 * Get required fields list
1405 public function getRequired(): array
1408 'id_type_cotis' => 1,
1411 'date_debut_cotis' => 1,
1412 'date_fin_cotis' => $this->isFee(),
1413 'montant_cotis' => $this->isFee() ?
1 : 0
1418 * Can current logged-in user display contribution
1420 * @param Login $login Login instance
1424 public function canShow(Login
$login): bool
1426 //admin and staff users can edit, as well as member itself
1427 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
1431 //parent can see their children contributions
1432 $parent = new Adherent($this->zdb
);
1435 ->enableDep('children')
1436 ->load($this->login
->id
);
1437 if ($parent->hasChildren()) {