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
62 * @property integer $id
63 * @property string $date
64 * @property DateTime $raw_date
65 * @property integer $member
66 * @property ContributionsTypes $type
67 * @property integer $amount
68 * @property integer $payment_type
69 * @property integer $orig_amount
70 * @property string $info
71 * @property string $begin_date
72 * @property DateTime $raw_begin_date
73 * @property string $end_date
74 * @property DateTime $raw_end_date
75 * @property Transaction|null $transaction
76 * @property integer $extension
77 * @property integer $duration
78 * @property string $spayment_type
79 * @property integer $model
85 public const TABLE
= 'cotisations';
86 public const PK
= 'id_cotis';
88 public const TYPE_FEE
= 'fee';
89 public const TYPE_DONATION
= 'donation';
96 private $_payment_type;
97 private $_orig_amount;
101 private $_transaction = null;
105 //fields list and their translation
115 private $sendmail = false;
118 * Default constructor
120 * @param Db $zdb Database
121 * @param Login $login Login instance
122 * @param null|int|ResultSet $args Either a ResultSet row to load
123 * a specific contribution, or an type id
124 * to just instantiate object
126 public function __construct(Db
$zdb, Login
$login, $args = null)
129 $this->login
= $login;
132 $this->_payment_type
= (int)$preferences->pref_default_paymenttype
;
135 * Fields configuration. Each field is an array and must reflect:
138 * (string) property name
141 * I'd prefer a static private variable for this...
142 * But call to the _T function does not seem to be allowed there :/
144 $this->_fields
= array(
146 'label' => null, //not a field in the form
149 Adherent
::PK
=> array(
150 'label' => _T("Contributor:"),
151 'propname' => 'member'
153 ContributionsTypes
::PK
=> array(
154 'label' => _T("Contribution type:"),
157 'montant_cotis' => array(
158 'label' => _T("Amount:"),
159 'propname' => 'amount'
161 'type_paiement_cotis' => array(
162 'label' => _T("Payment type:"),
163 'propname' => 'payment_type'
165 'info_cotis' => array(
166 'label' => _T("Comments:"),
169 'date_enreg' => array(
170 'label' => null, //not a field in the form
173 'date_debut_cotis' => array(
174 'label' => _T("Date of contribution:"),
175 'cotlabel' => _T("Start date of membership:"), //if contribution is a membership fee, label differs
176 'propname' => 'begin_date'
178 'date_fin_cotis' => array(
179 'label' => _T("End date of membership:"),
180 'propname' => 'end_date'
182 Transaction
::PK
=> array(
183 'label' => null, //not a field in the form
184 'propname' => 'transaction'
186 //this one is not really a field, but is required in some cases...
187 //adding it here make simplier to check required fields
188 'duree_mois_cotis' => array(
189 'label' => _T("Membership extension:"),
190 'propname' => 'extension'
195 } elseif (is_array($args)) {
196 $this->_date
= date("Y-m-d");
197 if (isset($args['adh']) && $args['adh'] != '') {
198 $this->_member
= (int)$args['adh'];
200 if (isset($args['trans'])) {
201 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
202 if (!isset($this->_member
)) {
203 $this->_member
= (int)$this->_transaction
->member
;
205 $this->_amount
= $this->_transaction
->getMissingAmount();
207 $this->type
= (int)$args['type'];
208 //calculate begin date for membership fee
209 $this->_begin_date
= $this->_date
;
210 if ($this->_is_cotis
) {
211 $curend = self
::getDueDate($this->zdb
, $this->_member
);
213 $dend = new \
DateTime($curend);
214 $now = date('Y-m-d');
215 $dnow = new \
DateTime($now);
217 // Member didn't renew on time
218 $this->_begin_date
= $now;
220 $this->_begin_date
= $curend;
223 $this->retrieveEndDate();
225 if (isset($args['payment_type'])) {
226 $this->_payment_type
= $args['payment_type'];
228 } elseif (is_object($args)) {
229 $this->loadFromRS($args);
232 $this->loadDynamicFields();
236 * Sets end contribution date
240 private function retrieveEndDate()
244 $bdate = new \
DateTime($this->_begin_date
);
245 if ($preferences->pref_beg_membership
!= '') {
246 //case beginning of membership
247 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
248 $edate = new \
DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
249 while ($edate <= $bdate) {
250 $edate->modify('+1 year');
253 if ($preferences->pref_membership_offermonths
> 0) {
254 //count days until end of membership date
255 $diff1 = (int)$bdate->diff($edate)->format('%a');
257 //count days beetween end of membership date and offered months
258 $tdate = clone $edate;
259 $tdate->modify('-' . $preferences->pref_membership_offermonths
. ' month');
260 $diff2 = (int)$edate->diff($tdate)->format('%a');
262 //when number of days until end of membership is less than for offered months, it's free :)
263 if ($diff1 <= $diff2) {
264 $edate->modify('+1 year');
268 $this->_end_date
= $edate->format('Y-m-d');
269 } elseif ($preferences->pref_membership_ext
!= '') {
270 //case membership extension
271 if ($this->_extension
== null) {
272 $this->_extension
= $preferences->pref_membership_ext
;
274 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
275 $edate = $bdate->add($dext);
276 $this->_end_date
= $edate->format('Y-m-d');
278 throw new \
RuntimeException(
279 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
285 * Loads a contribution from its id
287 * @param int $id the identifier for the contribution to load
289 * @return bool true if query succeed, false otherwise
291 public function load($id)
294 $select = $this->zdb
->select(self
::TABLE
, 'c');
296 array('a' => PREFIX_DB
. Adherent
::TABLE
),
297 'c.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
300 //restrict query on current member id if he's not admin nor staff member
301 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
302 if (!$this->login
->isGroupManager()) {
305 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
307 ->equalTo('a.parent_id', $this->login
->id
)
310 ->equalTo('c.' . self
::PK
, $id)
314 Adherent
::PK
=> $this->login
->id
,
319 $select->where
->equalTo(self
::PK
, $id);
322 $results = $this->zdb
->execute($select);
323 if ($results->count() > 0) {
324 $row = $results->current();
325 $this->loadFromRS($row);
328 throw new \
Exception(
329 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')'
332 } catch (Throwable
$e) {
334 'An error occurred attempting to load contribution #' . $id .
343 * Populate object from a resultset row
345 * @param ResultSet $r the resultset row
349 private function loadFromRS($r)
352 $this->_id
= (int)$r->$pk;
353 $this->_date
= $r->date_enreg
;
354 $this->_amount
= (int)$r->montant_cotis
;
355 //save original amount, we need it for transactions parts calculations
356 $this->_orig_amount
= (int)$r->montant_cotis
;
357 $this->_payment_type
= $r->type_paiement_cotis
;
358 $this->_info
= $r->info_cotis
;
359 $this->_begin_date
= $r->date_debut_cotis
;
360 $enddate = $r->date_fin_cotis
;
361 //do not work with knows bad dates...
362 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
363 //strange date? don't know :(
365 $enddate !== '0000-00-00'
366 && $enddate !== '1901-01-01'
367 && $enddate !== '0001-01-01 BC'
369 $this->_end_date
= $r->date_fin_cotis
;
371 $adhpk = Adherent
::PK
;
372 $this->_member
= (int)$r->$adhpk;
374 $transpk = Transaction
::PK
;
375 if ($r->$transpk != '') {
376 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
379 $this->type
= (int)$r->id_type_cotis
;
380 $this->loadDynamicFields();
384 * Check posted values validity
386 * @param array $values All values to check, basically the $_POST array
387 * after sending the form
388 * @param array $required Array of required fields
389 * @param array $disabled Array of disabled fields
393 public function check($values, $required, $disabled)
396 $this->errors
= array();
398 $fields = array_keys($this->_fields
);
399 foreach ($fields as $key) {
400 //first, let's sanitize values
401 $key = strtolower($key);
402 $prop = '_' . $this->_fields
[$key]['propname'];
404 if (isset($values[$key])) {
405 $value = trim($values[$key]);
410 // if the field is enabled, check it
411 if (!isset($disabled[$key])) {
412 // fill up the adherent structure
413 //$this->$prop = stripslashes($value); //not relevant here!
415 // now, check validity
419 case 'date_debut_cotis':
420 case 'date_fin_cotis':
423 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
425 throw new \
Exception('Incorrect format');
427 $this->$prop = $d->format('Y-m-d');
428 } catch (Throwable
$e) {
430 'Wrong date format. field: ' . $key .
431 ', value: ' . $value . ', expected fmt: ' .
432 __("Y-m-d") . ' | ' . $e->getMessage(),
435 $this->errors
[] = str_replace(
442 $this->_fields
[$key]['label']
444 _T("- Wrong date format (%date_format) for %field!")
451 $this->_member
= (int)$value;
454 case ContributionsTypes
::PK
:
456 $this->type
= (int)$value;
459 case 'montant_cotis':
460 $this->_amount
= $value;
461 $value = strtr($value, ',', '.');
462 if (!is_numeric($value) && $value !== '') {
463 $this->errors
[] = _T("- The amount must be an integer!");
466 case 'type_paiement_cotis':
467 $ptypes = new PaymentTypes(
472 $ptlist = $ptypes->getList();
473 if (isset($ptlist[$value])) {
474 $this->_payment_type
= $value;
476 $this->errors
[] = _T("- Unknown payment type");
480 $this->_info
= $value;
482 case Transaction
::PK
:
484 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
487 case 'duree_mois_cotis':
489 if (!is_numeric($value) ||
$value <= 0) {
490 $this->errors
[] = _T("- The duration must be a positive integer!");
492 $this->$prop = $value;
493 $this->retrieveEndDate();
500 // missing required fields?
501 foreach ($required as $key => $val) {
503 $prop = '_' . $this->_fields
[$key]['propname'];
505 !isset($disabled[$key])
506 && (!isset($this->$prop)
507 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
508 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
510 $this->errors
[] = str_replace(
512 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
513 _T("- Mandatory field %field empty.")
519 if ($this->_transaction
!= null && $this->_amount
!= null) {
520 $missing = $this->_transaction
->getMissingAmount();
521 //calculate new missing amount
522 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
524 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
528 if ($this->isFee() && count($this->errors
) == 0) {
529 $overlap = $this->checkOverlap();
530 if ($overlap !== true) {
531 if ($overlap === false) {
532 $this->errors
[] = _T("An error occurred checking overlapping fees :(");
534 //method directly return error message
535 $this->errors
[] = $overlap;
540 $this->dynamicsCheck($values, $required, $disabled);
542 if (count($this->errors
) > 0) {
544 'Some errors has been threw attempting to edit/store a contribution' .
545 print_r($this->errors
, true),
548 return $this->errors
;
551 'Contribution checked successfully.',
559 * Check that membership fees does not overlap
561 * @return boolean|string True if all is ok, false if error,
562 * error message if overlap
564 public function checkOverlap()
567 $select = $this->zdb
->select(self
::TABLE
, 'c');
569 array('date_debut_cotis', 'date_fin_cotis')
571 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
572 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
574 )->where(Adherent
::PK
. ' = ' . $this->_member
)
575 ->where(array('cotis_extension' => new Expression('true')))
577 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
578 ->lessThan('date_debut_cotis', $this->_end_date
)
581 ->greaterThan('date_fin_cotis', $this->_begin_date
)
582 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
584 if ($this->id
!= '') {
585 $select->where(self
::PK
. ' != ' . $this->id
);
588 $results = $this->zdb
->execute($select);
589 if ($results->count() > 0) {
590 $result = $results->current();
591 $d = new \
DateTime($result->date_debut_cotis
);
593 return _T("- Membership period overlaps period starting at ") .
594 $d->format(__("Y-m-d"));
597 } catch (Throwable
$e) {
599 'An error occurred checking overlapping fee. ' . $e->getMessage(),
607 * Store the contribution
611 public function store()
613 global $hist, $emitter;
617 if (count($this->errors
) > 0) {
618 throw new \
RuntimeException(
619 'Existing errors prevents storing contribution: ' .
620 print_r($this->errors
, true)
625 $this->zdb
->connection
->beginTransaction();
627 $fields = self
::getDbFields($this->zdb
);
628 foreach ($fields as $field) {
629 $prop = '_' . $this->_fields
[$field]['propname'];
631 case ContributionsTypes
::PK
:
632 case Transaction
::PK
:
633 if (isset($this->$prop)) {
634 $values[$field] = $this->$prop->id
;
638 $values[$field] = $this->$prop;
643 //no end date, let's take database defaults
644 if (!$this->isFee() && !$this->_end_date
) {
645 unset($values['date_fin_cotis']);
649 if (!isset($this->_id
) ||
$this->_id
== '') {
650 //we're inserting a new contribution
651 unset($values[self
::PK
]);
653 $insert = $this->zdb
->insert(self
::TABLE
);
654 $insert->values($values);
655 $add = $this->zdb
->execute($insert);
657 if ($add->count() > 0) {
658 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
662 _T("Contribution added"),
663 Adherent
::getSName($this->zdb
, $this->_member
)
666 $event = 'contribution.add';
668 $hist->add(_T("Fail to add new contribution."));
669 throw new \
Exception(
670 'An error occurred inserting new contribution!'
674 //we're editing an existing contribution
675 $update = $this->zdb
->update(self
::TABLE
);
676 $update->set($values)->where(
677 self
::PK
. '=' . $this->_id
679 $edit = $this->zdb
->execute($update);
681 //edit == 0 does not mean there were an error, but that there
682 //were nothing to change
683 if ($edit->count() > 0) {
685 _T("Contribution updated"),
686 Adherent
::getSName($this->zdb
, $this->_member
)
690 if ($edit === false) {
691 throw new \
Exception(
692 'An error occurred updating contribution # ' . $this->_id
. '!'
696 $event = 'contribution.edit';
699 if ($this->isFee()) {
700 $deadline = $this->updateDeadline();
701 if ($deadline !== true) {
702 //if something went wrong, we roll back transaction
703 throw new \
Exception('An error occurred updating member\'s deadline');
709 $success = $this->dynamicsStore(true);
712 $this->zdb
->connection
->commit();
713 $this->_orig_amount
= $this->_amount
;
715 //send event at the end of process, once all has been stored
716 if ($event !== null) {
717 $emitter->emit($event, $this);
721 } catch (Throwable
$e) {
722 if ($this->zdb
->connection
->inTransaction()) {
723 $this->zdb
->connection
->rollBack();
730 * Update member dead line
734 private function updateDeadline()
737 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
739 if ($due_date != '') {
740 $date_fin_update = $due_date;
742 $date_fin_update = new Expression('NULL');
745 $update = $this->zdb
->update(Adherent
::TABLE
);
747 array('date_echeance' => $date_fin_update)
749 Adherent
::PK
. '=' . $this->_member
751 $this->zdb
->execute($update);
753 } catch (Throwable
$e) {
755 'An error occurred updating member ' . $this->_member
.
765 * Remove contribution from database
767 * @param boolean $transaction Activate transaction mode (defaults to true)
771 public function remove($transaction = true)
777 $this->zdb
->connection
->beginTransaction();
780 $delete = $this->zdb
->delete(self
::TABLE
);
781 $delete->where(self
::PK
. ' = ' . $this->_id
);
782 $del = $this->zdb
->execute($delete);
783 if ($del->count() > 0) {
784 $this->updateDeadline();
785 $this->dynamicsRemove(true);
787 throw new \
RuntimeException(
788 'Contribution has not been removed!'
792 $this->zdb
->connection
->commit();
794 $emitter->emit('contribution.remove', $this);
796 } catch (Throwable
$e) {
798 $this->zdb
->connection
->rollBack();
801 'An error occurred trying to remove contribution #' .
802 $this->_id
. ' | ' . $e->getMessage(),
812 * @param string $field Field name
816 public function getFieldLabel($field)
818 $label = $this->_fields
[$field]['label'];
819 if ($this->isFee() && $field == 'date_debut_cotis') {
820 $label = $this->_fields
[$field]['cotlabel'];
823 $label = str_replace(' ', ' ', $label);
824 //remove trailing ':' and then trim
825 $label = trim(trim($label, ':'));
830 * Retrieve fields from database
832 * @param Db $zdb Database instance
836 public static function getDbFields(Db
$zdb)
838 $columns = $zdb->getColumns(self
::TABLE
);
840 foreach ($columns as $col) {
841 $fields[] = $col->getName();
847 * Get the relevant CSS class for current contribution
849 * @return string current contribution row class
851 public function getRowClass()
853 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
854 'cotis-normal' : 'cotis-give';
858 * Retrieve member due date
860 * @param Db $zdb Database instance
861 * @param integer $member_id Member identifier
865 public static function getDueDate(Db
$zdb, $member_id)
871 $select = $zdb->select(self
::TABLE
, 'c');
874 'max_date' => new Expression('MAX(date_fin_cotis)')
877 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
878 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
881 Adherent
::PK
. ' = ' . $member_id
883 array('cotis_extension' => new Expression('true'))
886 $results = $zdb->execute($select);
887 $result = $results->current();
888 $due_date = $result->max_date
;
890 //avoid bad dates in postgres and bad mysql return from zenddb
891 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
895 } catch (Throwable
$e) {
897 'An error occurred trying to retrieve member\'s due date',
905 * Detach a contribution from a transaction
907 * @param Db $zdb Database instance
908 * @param Login $login Login instance
909 * @param int $trans_id Transaction identifier
910 * @param int $contrib_id Contribution identifier
914 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
917 //first, we check if contribution is part of transaction
918 $c = new Contribution($zdb, $login, (int)$contrib_id);
919 if ($c->isTransactionPartOf($trans_id)) {
920 $update = $zdb->update(self
::TABLE
);
922 array(Transaction
::PK
=> null)
924 self
::PK
. ' = ' . $contrib_id
926 $zdb->execute($update);
930 'Contribution #' . $contrib_id .
931 ' is not actually part of transaction #' . $trans_id,
936 } catch (Throwable
$e) {
938 'Unable to detach contribution #' . $contrib_id .
939 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
947 * Set a contribution as a transaction part
949 * @param Db $zdb Database instance
950 * @param int $trans_id Transaction identifier
951 * @param int $contrib_id Contribution identifier
955 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
958 $update = $zdb->update(self
::TABLE
);
960 array(Transaction
::PK
=> $trans_id)
961 )->where(self
::PK
. ' = ' . $contrib_id);
963 $zdb->execute($update);
965 } catch (Throwable
$e) {
967 'Unable to attach contribution #' . $contrib_id .
968 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
976 * Is current contribution a membership fee
980 public function isFee()
982 return $this->_is_cotis
;
986 * Is current contribution part of specified transaction
988 * @param int $id Transaction identifier
992 public function isTransactionPartOf($id)
994 if ($this->isTransactionPart()) {
995 return $id == $this->_transaction
->id
;
1002 * Is current contribution part of transaction
1006 public function isTransactionPart()
1008 return $this->_transaction
!= null;
1012 * Execute post contribution script
1014 * @param ExternalScript $es External script to execute
1015 * @param array $extra Extra information on contribution
1017 * @param array $pextra Extra information on payment
1020 * @return mixed Script return value on success, values and script output on fail
1022 public function executePostScript(
1027 global $preferences;
1030 'type' => $this->getPaymentType()
1033 if ($pextra !== null && is_array($pextra)) {
1034 $payment = array_merge($payment, $pextra);
1037 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1038 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1041 $voucher_path = null;
1042 if ($this->_id
!== null) {
1043 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1044 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1045 $voucher_path = $voucher->getPath();
1049 'id' => (int)$this->_id
,
1050 'date' => $this->_date
,
1051 'type' => $this->getRawType(),
1052 'amount' => $this->amount
,
1053 'voucher' => $voucher_path,
1054 'category' => array(
1055 'id' => $this->type
->id
,
1056 'label' => $this->type
->libelle
1058 'payment' => $payment
1061 if ($this->_member
!== null) {
1062 $m = new Adherent($this->zdb
, (int)$this->_member
);
1064 'id' => (int)$this->_member
,
1065 'name' => $m->sfullname
,
1066 'email' => $m->email
,
1067 'organization' => ($m->isCompany() ?
1 : 0),
1070 'label' => $m->sstatus
1072 'country' => $m->country
1075 if ($m->isCompany()) {
1076 $member['organization_name'] = $m->company_name
;
1079 $contrib['member'] = $member;
1082 if ($extra !== null && is_array($extra)) {
1083 $contrib = array_merge($contrib, $extra);
1086 $res = $es->send($contrib);
1088 if ($res !== true) {
1090 'An error occurred calling post contribution ' .
1091 "script:\n" . $es->getOutput(),
1094 $res = _T("Contribution information") . "\n";
1095 $res .= print_r($contrib, true);
1096 $res .= "\n\n" . _T("Script output") . "\n";
1097 $res .= $es->getOutput();
1103 * Get raw contribution type
1107 public function getRawType()
1109 if ($this->isFee()) {
1110 return 'membership';
1117 * Get contribution type label
1121 public function getTypeLabel()
1123 if ($this->isFee()) {
1124 return _T("Membership");
1126 return _T("Donation");
1131 * Get payment type label
1135 public function getPaymentType()
1137 if ($this->_payment_type
=== null) {
1141 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1142 return $ptype->getName(false);
1146 * Global getter method
1148 * @param string $name name of the property we want to retrieve
1150 * @return false|object the called property
1152 public function __get($name)
1155 $forbidden = array('is_cotis');
1156 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1157 'raw_begin_date', 'raw_end_date'
1160 $rname = '_' . $name;
1162 if (in_array($name, $forbidden)) {
1164 "Call to __get for '$name' is forbidden!",
1170 return $this->isFee();
1173 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1176 property_exists($this, $rname)
1177 ||
in_array($name, $virtuals)
1181 case 'raw_begin_date':
1182 case 'raw_end_date':
1183 $rname = '_' . substr($name, 4);
1184 if ($this->$rname != '') {
1186 $d = new \
DateTime($this->$rname);
1188 } catch (Throwable
$e) {
1189 //oops, we've got a bad date :/
1191 'Bad date (' . $this->$rname . ') | ' .
1202 if ($this->$rname != '') {
1204 $d = new \
DateTime($this->$rname);
1205 return $d->format(__("Y-m-d"));
1206 } catch (Throwable
$e) {
1207 //oops, we've got a bad date :/
1209 'Bad date (' . $this->$rname . ') | ' .
1213 return $this->$rname;
1218 if ($this->_is_cotis
) {
1219 $date_end = new \
DateTime($this->_end_date
);
1220 $date_start = new \
DateTime($this->_begin_date
);
1221 $diff = $date_end->diff($date_start);
1222 return $diff->format('%y') * 12 +
$diff->format('%m');
1227 case 'spayment_type':
1228 if ($this->_payment_type
=== null) {
1232 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1233 return $ptype->getName();
1237 if ($this->_is_cotis
=== null) {
1240 return ($this->isFee()) ?
1241 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1244 return $this->$rname;
1249 "Unknown property '$rname'",
1257 * Global setter method
1259 * @param string $name name of the property we want to assign a value to
1260 * @param object $value a relevant value for the property
1264 public function __set($name, $value)
1266 global $preferences;
1268 $forbidden = array('fields', 'is_cotis', 'end_date');
1270 if (!in_array($name, $forbidden)) {
1271 $rname = '_' . $name;
1274 if (is_int($value)) {
1275 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1278 'Trying to set a transaction from an id that is not an integer.',
1284 if (is_int($value)) {
1286 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1287 //set is_cotis according to type
1288 if ($this->$rname->extension
== 1) {
1289 $this->_is_cotis
= true;
1291 $this->_is_cotis
= false;
1295 'Trying to set a type from an id that is not an integer.',
1302 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1304 throw new \
Exception('Incorrect format');
1306 $this->_begin_date
= $d->format('Y-m-d');
1307 } catch (Throwable
$e) {
1309 'Wrong date format. field: ' . $name .
1310 ', value: ' . $value . ', expected fmt: ' .
1311 __("Y-m-d") . ' | ' . $e->getMessage(),
1314 $this->errors
[] = str_replace(
1321 $this->_fields
['date_debut_cotis']['label']
1323 _T("- Wrong date format (%date_format) for %field!")
1328 if (is_numeric($value) && $value > 0) {
1329 $this->$rname = $value;
1332 'Trying to set an amount with a non numeric value, ' .
1333 'or with a zero value',
1339 if (is_int($value)) {
1341 $this->$rname = $value;
1344 case 'payment_type':
1345 $ptypes = new PaymentTypes(
1350 $list = $ptypes->getList();
1351 if (isset($list[$value])) {
1352 $this->_payment_type
= $value;
1355 'Unknown payment type ' . $value,
1362 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1372 * Flag creation mail sending
1374 * @param boolean $send True (default) to send creation email
1376 * @return Contribution
1378 public function setSendmail($send = true)
1380 $this->sendmail
= $send;
1385 * Should we send administrative emails to member?
1389 public function sendEMail()
1391 return $this->sendmail
;
1395 * Handle files (dynamics files)
1397 * @param array $files Files sent
1399 * @return array|true
1401 public function handleFiles($files)
1405 $this->dynamicsFiles($files);
1407 if (count($this->errors
) > 0) {
1409 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1410 print_r($this->errors
, true),
1413 return $this->errors
;
1420 * Get required fields list
1424 public function getRequired(): array
1427 'id_type_cotis' => 1,
1430 'date_debut_cotis' => 1,
1431 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1432 'montant_cotis' => $this->isFee() ?
1 : 0
1437 * Can current logged-in user display contribution
1439 * @param Login $login Login instance
1443 public function canShow(Login
$login): bool
1445 //admin and staff users can edit, as well as member itself
1446 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1450 //parent can see their children contributions
1451 $parent = new Adherent($this->zdb
);
1454 ->enableDep('children')
1455 ->load($this->login
->id
);
1456 if ($parent->hasChildren()) {
1457 foreach ($parent->children
as $child) {
1458 if ($child->id
=== $this->_member
) {