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' => null, //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' => null, //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' => null, //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 simplier 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 beetween 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()) {
303 if (!$this->login
->isLogged()) {
305 'Non-logged-in users cannot load contribution id `' . $id,
310 if (!$this->login
->isGroupManager()) {
313 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
315 ->equalTo('a.parent_id', $this->login
->id
)
318 ->equalTo('c.' . self
::PK
, $id)
322 Adherent
::PK
=> $this->login
->id
,
327 $select->where
->equalTo(self
::PK
, $id);
330 $results = $this->zdb
->execute($select);
331 if ($results->count() > 0) {
332 $row = $results->current();
333 $this->loadFromRS($row);
337 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')',
342 } catch (Throwable
$e) {
344 'An error occurred attempting to load contribution #' . $id .
353 * Populate object from a resultset row
355 * @param ResultSet $r the resultset row
359 private function loadFromRS($r)
362 $this->_id
= (int)$r->$pk;
363 $this->_date
= $r->date_enreg
;
364 $this->_amount
= (int)$r->montant_cotis
;
365 //save original amount, we need it for transactions parts calculations
366 $this->_orig_amount
= (int)$r->montant_cotis
;
367 $this->_payment_type
= $r->type_paiement_cotis
;
368 $this->_info
= $r->info_cotis
;
369 $this->_begin_date
= $r->date_debut_cotis
;
370 $enddate = $r->date_fin_cotis
;
371 //do not work with knows bad dates...
372 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
373 //strange date? don't know :(
375 $enddate !== '0000-00-00'
376 && $enddate !== '1901-01-01'
377 && $enddate !== '0001-01-01 BC'
379 $this->_end_date
= $r->date_fin_cotis
;
381 $adhpk = Adherent
::PK
;
382 $this->_member
= (int)$r->$adhpk;
384 $transpk = Transaction
::PK
;
385 if ($r->$transpk != '') {
386 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
389 $this->type
= (int)$r->id_type_cotis
;
390 $this->loadDynamicFields();
394 * Check posted values validity
396 * @param array $values All values to check, basically the $_POST array
397 * after sending the form
398 * @param array $required Array of required fields
399 * @param array $disabled Array of disabled fields
403 public function check($values, $required, $disabled)
406 $this->errors
= array();
408 $fields = array_keys($this->_fields
);
409 foreach ($fields as $key) {
410 //first, let's sanitize values
411 $key = strtolower($key);
412 $prop = '_' . $this->_fields
[$key]['propname'];
414 if (isset($values[$key])) {
415 $value = trim($values[$key]);
420 // if the field is enabled, check it
421 if (!isset($disabled[$key])) {
422 // fill up the adherent structure
423 //$this->$prop = stripslashes($value); //not relevant here!
425 // now, check validity
429 case 'date_debut_cotis':
430 case 'date_fin_cotis':
433 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
435 throw new \
Exception('Incorrect format');
437 $this->$prop = $d->format('Y-m-d');
438 } catch (Throwable
$e) {
440 'Wrong date format. field: ' . $key .
441 ', value: ' . $value . ', expected fmt: ' .
442 __("Y-m-d") . ' | ' . $e->getMessage(),
445 $this->errors
[] = str_replace(
452 $this->_fields
[$key]['label']
454 _T("- Wrong date format (%date_format) for %field!")
461 $this->_member
= (int)$value;
464 case ContributionsTypes
::PK
:
466 $this->type
= (int)$value;
469 case 'montant_cotis':
470 $this->_amount
= $value;
471 $value = strtr($value, ',', '.');
472 if (!is_numeric($value) && $value !== '') {
473 $this->errors
[] = _T("- The amount must be an integer!");
476 case 'type_paiement_cotis':
477 $ptypes = new PaymentTypes(
482 $ptlist = $ptypes->getList();
483 if (isset($ptlist[$value])) {
484 $this->_payment_type
= $value;
486 $this->errors
[] = _T("- Unknown payment type");
490 $this->_info
= $value;
492 case Transaction
::PK
:
494 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
497 case 'duree_mois_cotis':
499 if (!is_numeric($value) ||
$value <= 0) {
500 $this->errors
[] = _T("- The duration must be a positive integer!");
502 $this->$prop = $value;
503 $this->retrieveEndDate();
510 // missing required fields?
511 foreach ($required as $key => $val) {
513 $prop = '_' . $this->_fields
[$key]['propname'];
515 !isset($disabled[$key])
516 && (!isset($this->$prop)
517 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
518 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
520 $this->errors
[] = str_replace(
522 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
523 _T("- Mandatory field %field empty.")
529 if ($this->_transaction
!= null && $this->_amount
!= null) {
530 $missing = $this->_transaction
->getMissingAmount();
531 //calculate new missing amount
532 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
534 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
538 if ($this->isFee() && count($this->errors
) == 0) {
539 $overlap = $this->checkOverlap();
540 if ($overlap !== true) {
541 if ($overlap === false) {
542 $this->errors
[] = _T("An error occurred checking overlapping fees :(");
544 //method directly return error message
545 $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');
579 array('date_debut_cotis', 'date_fin_cotis')
581 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
582 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
584 )->where(Adherent
::PK
. ' = ' . $this->_member
)
585 ->where(array('cotis_extension' => new Expression('true')))
587 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
588 ->lessThan('date_debut_cotis', $this->_end_date
)
591 ->greaterThan('date_fin_cotis', $this->_begin_date
)
592 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
594 if ($this->id
!= '') {
595 $select->where(self
::PK
. ' != ' . $this->id
);
598 $results = $this->zdb
->execute($select);
599 if ($results->count() > 0) {
600 $result = $results->current();
601 $d = new \
DateTime($result->date_debut_cotis
);
603 return _T("- Membership period overlaps period starting at ") .
604 $d->format(__("Y-m-d"));
607 } catch (Throwable
$e) {
609 'An error occurred checking overlapping fee. ' . $e->getMessage(),
617 * Store the contribution
621 public function store()
623 global $hist, $emitter;
627 if (count($this->errors
) > 0) {
628 throw new \
RuntimeException(
629 'Existing errors prevents storing contribution: ' .
630 print_r($this->errors
, true)
635 $this->zdb
->connection
->beginTransaction();
637 $fields = self
::getDbFields($this->zdb
);
638 foreach ($fields as $field) {
639 $prop = '_' . $this->_fields
[$field]['propname'];
641 case ContributionsTypes
::PK
:
642 case Transaction
::PK
:
643 if (isset($this->$prop)) {
644 $values[$field] = $this->$prop->id
;
648 $values[$field] = $this->$prop;
653 //no end date, let's take database defaults
654 if (!$this->isFee() && !$this->_end_date
) {
655 unset($values['date_fin_cotis']);
659 if (!isset($this->_id
) ||
$this->_id
== '') {
660 //we're inserting a new contribution
661 unset($values[self
::PK
]);
663 $insert = $this->zdb
->insert(self
::TABLE
);
664 $insert->values($values);
665 $add = $this->zdb
->execute($insert);
667 if ($add->count() > 0) {
668 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
672 _T("Contribution added"),
673 Adherent
::getSName($this->zdb
, $this->_member
)
676 $event = 'contribution.add';
678 $hist->add(_T("Fail to add new contribution."));
679 throw new \
Exception(
680 'An error occurred inserting new contribution!'
684 //we're editing an existing contribution
685 $update = $this->zdb
->update(self
::TABLE
);
686 $update->set($values)->where(
687 self
::PK
. '=' . $this->_id
689 $edit = $this->zdb
->execute($update);
691 //edit == 0 does not mean there were an error, but that there
692 //were nothing to change
693 if ($edit->count() > 0) {
695 _T("Contribution updated"),
696 Adherent
::getSName($this->zdb
, $this->_member
)
700 if ($edit === false) {
701 throw new \
Exception(
702 'An error occurred updating contribution # ' . $this->_id
. '!'
706 $event = 'contribution.edit';
709 if ($this->isFee()) {
710 $deadline = $this->updateDeadline();
711 if ($deadline !== true) {
712 //if something went wrong, we roll back transaction
713 throw new \
Exception('An error occurred updating member\'s deadline');
719 $success = $this->dynamicsStore(true);
722 $this->zdb
->connection
->commit();
723 $this->_orig_amount
= $this->_amount
;
725 //send event at the end of process, once all has been stored
726 if ($event !== null) {
727 $emitter->emit($event, $this);
731 } catch (Throwable
$e) {
732 if ($this->zdb
->connection
->inTransaction()) {
733 $this->zdb
->connection
->rollBack();
740 * Update member dead line
744 private function updateDeadline()
747 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
749 if ($due_date != '') {
750 $date_fin_update = $due_date;
752 $date_fin_update = new Expression('NULL');
755 $update = $this->zdb
->update(Adherent
::TABLE
);
757 array('date_echeance' => $date_fin_update)
759 Adherent
::PK
. '=' . $this->_member
761 $this->zdb
->execute($update);
763 } catch (Throwable
$e) {
765 'An error occurred updating member ' . $this->_member
.
775 * Remove contribution from database
777 * @param boolean $transaction Activate transaction mode (defaults to true)
781 public function remove($transaction = true)
787 $this->zdb
->connection
->beginTransaction();
790 $delete = $this->zdb
->delete(self
::TABLE
);
791 $delete->where(self
::PK
. ' = ' . $this->_id
);
792 $del = $this->zdb
->execute($delete);
793 if ($del->count() > 0) {
794 $this->updateDeadline();
795 $this->dynamicsRemove(true);
798 'Contribution has not been removed!',
804 $this->zdb
->connection
->commit();
806 $emitter->emit('contribution.remove', $this);
808 } catch (Throwable
$e) {
810 $this->zdb
->connection
->rollBack();
813 'An error occurred trying to remove contribution #' .
814 $this->_id
. ' | ' . $e->getMessage(),
824 * @param string $field Field name
828 public function getFieldLabel($field)
830 $label = $this->_fields
[$field]['label'];
831 if ($this->isFee() && $field == 'date_debut_cotis') {
832 $label = $this->_fields
[$field]['cotlabel'];
835 $label = str_replace(' ', ' ', $label);
836 //remove trailing ':' and then trim
837 $label = trim(trim($label, ':'));
842 * Retrieve fields from database
844 * @param Db $zdb Database instance
848 public static function getDbFields(Db
$zdb)
850 $columns = $zdb->getColumns(self
::TABLE
);
852 foreach ($columns as $col) {
853 $fields[] = $col->getName();
859 * Get the relevant CSS class for current contribution
861 * @return string current contribution row class
863 public function getRowClass()
865 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
866 'cotis-normal' : 'cotis-give';
870 * Retrieve member due date
872 * @param Db $zdb Database instance
873 * @param integer $member_id Member identifier
877 public static function getDueDate(Db
$zdb, $member_id)
883 $select = $zdb->select(self
::TABLE
, 'c');
886 'max_date' => new Expression('MAX(date_fin_cotis)')
889 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
890 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
893 Adherent
::PK
. ' = ' . $member_id
895 array('cotis_extension' => new Expression('true'))
898 $results = $zdb->execute($select);
899 $result = $results->current();
900 $due_date = $result->max_date
;
902 //avoid bad dates in postgres and bad mysql return from zenddb
903 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
907 } catch (Throwable
$e) {
909 'An error occurred trying to retrieve member\'s due date',
917 * Detach a contribution from a transaction
919 * @param Db $zdb Database instance
920 * @param Login $login Login instance
921 * @param int $trans_id Transaction identifier
922 * @param int $contrib_id Contribution identifier
926 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
929 //first, we check if contribution is part of transaction
930 $c = new Contribution($zdb, $login, (int)$contrib_id);
931 if ($c->isTransactionPartOf($trans_id)) {
932 $update = $zdb->update(self
::TABLE
);
934 array(Transaction
::PK
=> null)
936 self
::PK
. ' = ' . $contrib_id
938 $zdb->execute($update);
942 'Contribution #' . $contrib_id .
943 ' is not actually part of transaction #' . $trans_id,
948 } catch (Throwable
$e) {
950 'Unable to detach contribution #' . $contrib_id .
951 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
959 * Set a contribution as a transaction part
961 * @param Db $zdb Database instance
962 * @param int $trans_id Transaction identifier
963 * @param int $contrib_id Contribution identifier
967 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
970 $update = $zdb->update(self
::TABLE
);
972 array(Transaction
::PK
=> $trans_id)
973 )->where(self
::PK
. ' = ' . $contrib_id);
975 $zdb->execute($update);
977 } catch (Throwable
$e) {
979 'Unable to attach contribution #' . $contrib_id .
980 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
988 * Is current contribution a membership fee
992 public function isFee()
994 return $this->_is_cotis
;
998 * Is current contribution part of specified transaction
1000 * @param int $id Transaction identifier
1004 public function isTransactionPartOf($id)
1006 if ($this->isTransactionPart()) {
1007 return $id == $this->_transaction
->id
;
1014 * Is current contribution part of transaction
1018 public function isTransactionPart()
1020 return $this->_transaction
!= null;
1024 * Execute post contribution script
1026 * @param ExternalScript $es External script to execute
1027 * @param array $extra Extra information on contribution
1029 * @param array $pextra Extra information on payment
1032 * @return mixed Script return value on success, values and script output on fail
1034 public function executePostScript(
1039 global $preferences;
1042 'type' => $this->getPaymentType()
1045 if ($pextra !== null && is_array($pextra)) {
1046 $payment = array_merge($payment, $pextra);
1049 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1050 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1053 $voucher_path = null;
1054 if ($this->_id
!== null) {
1055 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1056 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1057 $voucher_path = $voucher->getPath();
1061 'id' => (int)$this->_id
,
1062 'date' => $this->_date
,
1063 'type' => $this->getRawType(),
1064 'amount' => $this->amount
,
1065 'voucher' => $voucher_path,
1066 'category' => array(
1067 'id' => $this->type
->id
,
1068 'label' => $this->type
->libelle
1070 'payment' => $payment
1073 if ($this->_member
!== null) {
1074 $m = new Adherent($this->zdb
, (int)$this->_member
);
1076 'id' => (int)$this->_member
,
1077 'name' => $m->sfullname
,
1078 'email' => $m->email
,
1079 'organization' => ($m->isCompany() ?
1 : 0),
1082 'label' => $m->sstatus
1084 'country' => $m->country
1087 if ($m->isCompany()) {
1088 $member['organization_name'] = $m->company_name
;
1091 $contrib['member'] = $member;
1094 if ($extra !== null && is_array($extra)) {
1095 $contrib = array_merge($contrib, $extra);
1098 $res = $es->send($contrib);
1100 if ($res !== true) {
1102 'An error occurred calling post contribution ' .
1103 "script:\n" . $es->getOutput(),
1106 $res = _T("Contribution information") . "\n";
1107 $res .= print_r($contrib, true);
1108 $res .= "\n\n" . _T("Script output") . "\n";
1109 $res .= $es->getOutput();
1115 * Get raw contribution type
1119 public function getRawType()
1121 if ($this->isFee()) {
1122 return 'membership';
1129 * Get contribution type label
1133 public function getTypeLabel()
1135 if ($this->isFee()) {
1136 return _T("Membership");
1138 return _T("Donation");
1143 * Get payment type label
1147 public function getPaymentType()
1149 if ($this->_payment_type
=== null) {
1153 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1154 return $ptype->getName(false);
1158 * Global getter method
1160 * @param string $name name of the property we want to retrieve
1162 * @return false|object the called property
1164 public function __get($name)
1167 $forbidden = array('is_cotis');
1168 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1169 'raw_begin_date', 'raw_end_date'
1172 $rname = '_' . $name;
1174 if (in_array($name, $forbidden)) {
1176 "Call to __get for '$name' is forbidden!",
1182 return $this->isFee();
1185 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1188 property_exists($this, $rname)
1189 ||
in_array($name, $virtuals)
1193 case 'raw_begin_date':
1194 case 'raw_end_date':
1195 $rname = '_' . substr($name, 4);
1196 if ($this->$rname != '') {
1198 $d = new \
DateTime($this->$rname);
1200 } catch (Throwable
$e) {
1201 //oops, we've got a bad date :/
1203 'Bad date (' . $this->$rname . ') | ' .
1214 if ($this->$rname != '') {
1216 $d = new \
DateTime($this->$rname);
1217 return $d->format(__("Y-m-d"));
1218 } catch (Throwable
$e) {
1219 //oops, we've got a bad date :/
1221 'Bad date (' . $this->$rname . ') | ' .
1225 return $this->$rname;
1230 if ($this->_is_cotis
) {
1231 $date_end = new \
DateTime($this->_end_date
);
1232 $date_start = new \
DateTime($this->_begin_date
);
1233 $diff = $date_end->diff($date_start);
1234 return $diff->format('%y') * 12 +
$diff->format('%m');
1239 case 'spayment_type':
1240 if ($this->_payment_type
=== null) {
1244 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1245 return $ptype->getName();
1249 if ($this->_is_cotis
=== null) {
1252 return ($this->isFee()) ?
1253 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1256 return $this->$rname;
1261 "Unknown property '$rname'",
1269 * Global setter method
1271 * @param string $name name of the property we want to assign a value to
1272 * @param object $value a relevant value for the property
1276 public function __set($name, $value)
1278 global $preferences;
1280 $forbidden = array('fields', 'is_cotis', 'end_date');
1282 if (!in_array($name, $forbidden)) {
1283 $rname = '_' . $name;
1286 if (is_int($value)) {
1287 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1290 'Trying to set a transaction from an id that is not an integer.',
1296 if (is_int($value)) {
1298 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1299 //set is_cotis according to type
1300 if ($this->$rname->extension
== 1) {
1301 $this->_is_cotis
= true;
1303 $this->_is_cotis
= false;
1307 'Trying to set a type from an id that is not an integer.',
1314 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1316 throw new \
Exception('Incorrect format');
1318 $this->_begin_date
= $d->format('Y-m-d');
1319 } catch (Throwable
$e) {
1321 'Wrong date format. field: ' . $name .
1322 ', value: ' . $value . ', expected fmt: ' .
1323 __("Y-m-d") . ' | ' . $e->getMessage(),
1326 $this->errors
[] = str_replace(
1333 $this->_fields
['date_debut_cotis']['label']
1335 _T("- Wrong date format (%date_format) for %field!")
1340 if (is_numeric($value) && $value > 0) {
1341 $this->$rname = $value;
1344 'Trying to set an amount with a non numeric value, ' .
1345 'or with a zero value',
1351 if (is_int($value)) {
1353 $this->$rname = $value;
1356 case 'payment_type':
1357 $ptypes = new PaymentTypes(
1362 $list = $ptypes->getList();
1363 if (isset($list[$value])) {
1364 $this->_payment_type
= $value;
1367 'Unknown payment type ' . $value,
1374 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1384 * Flag creation mail sending
1386 * @param boolean $send True (default) to send creation email
1388 * @return Contribution
1390 public function setSendmail($send = true)
1392 $this->sendmail
= $send;
1397 * Should we send administrative emails to member?
1401 public function sendEMail()
1403 return $this->sendmail
;
1407 * Handle files (dynamics files)
1409 * @param array $files Files sent
1411 * @return array|true
1413 public function handleFiles($files)
1417 $this->dynamicsFiles($files);
1419 if (count($this->errors
) > 0) {
1421 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1422 print_r($this->errors
, true),
1425 return $this->errors
;
1432 * Get required fields list
1436 public function getRequired(): array
1439 'id_type_cotis' => 1,
1442 'date_debut_cotis' => 1,
1443 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1444 'montant_cotis' => $this->isFee() ?
1 : 0
1449 * Can current logged-in user display contribution
1451 * @param Login $login Login instance
1455 public function canShow(Login
$login): bool
1457 //non-logged-in members cannot show contributions
1458 if (!$login->isLogged()) {
1462 //admin and staff users can edit, as well as member itself
1463 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1467 //parent can see their children contributions
1468 $parent = new Adherent($this->zdb
);
1471 ->enableDep('children')
1472 ->load($this->login
->id
);
1473 if ($parent->hasChildren()) {
1474 foreach ($parent->children
as $child) {
1475 if ($child->id
=== $this->_member
) {