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 double $amount
69 * @property integer $payment_type
70 * @property double $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 a 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 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
213 if ($due_date != '') {
214 $now = new \
DateTime();
215 $due_date = new \
DateTime($due_date);
216 if ($due_date < $now) {
217 // Member didn't renew on time
218 $this->_begin_date
= $now->format('Y-m-d');
220 // Caution : the next_begin_date is the day after the due_date.
221 $next_begin_date = clone $due_date;
222 $next_begin_date->add(new \
DateInterval('P1D'));
223 $this->_begin_date
= $next_begin_date->format('Y-m-d');
226 $this->retrieveEndDate();
228 if (isset($args['payment_type'])) {
229 $this->_payment_type
= $args['payment_type'];
231 } elseif (is_object($args)) {
232 $this->loadFromRS($args);
235 $this->loadDynamicFields();
239 * Sets end contribution date
243 private function retrieveEndDate()
247 $now = new \
DateTime();
248 $begin_date = new \
DateTime($this->_begin_date
);
249 if ($preferences->pref_beg_membership
!= '') {
250 //case beginning of membership
251 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
252 $next_begin_date = new \
DateTime($begin_date->format('Y') . '-' . $m . '-' . $j);
253 while ($next_begin_date <= $begin_date) {
254 $next_begin_date->add(new \
DateInterval('P1Y'));
257 if ($preferences->pref_membership_offermonths
> 0) {
258 //count days until next membership begin date
259 $diff1 = (int)$now->diff($next_begin_date)->format('%a');
261 //count days between next membership begin date and offered months
262 $tdate = clone $next_begin_date;
263 $tdate->sub(new \
DateInterval('P' . $preferences->pref_membership_offermonths
. 'M'));
264 $diff2 = (int)$next_begin_date->diff($tdate)->format('%a');
266 //when number of days until next membership begin date is less than or equal to the offered months, it's free :)
267 if ($diff1 <= $diff2) {
268 $next_begin_date->add(new \
DateInterval('P1Y'));
272 // Caution : the end_date to retrieve is the day before the next_begin_date.
273 $end_date = clone $next_begin_date;
274 $end_date->sub(new \
DateInterval('P1D'));
275 $this->_end_date
= $end_date->format('Y-m-d');
276 } elseif ($preferences->pref_membership_ext
!= '') {
277 //case membership extension
278 if ($this->_extension
== null) {
279 $this->_extension
= $preferences->pref_membership_ext
;
281 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
282 // Caution : the end_date to retrieve is the day before the next_begin_date.
283 $next_begin_date = $begin_date->add($dext);
284 $end_date = clone $next_begin_date;
285 $end_date->sub(new \
DateInterval('P1D'));
286 $this->_end_date
= $end_date->format('Y-m-d');
288 throw new \
RuntimeException(
289 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
295 * Loads a contribution from its id
297 * @param int $id the identifier for the contribution to load
299 * @return bool true if query succeed, false otherwise
301 public function load($id)
303 if (!$this->login
->isLogged()) {
308 $select = $this->zdb
->select(self
::TABLE
, 'c');
310 array('a' => PREFIX_DB
. Adherent
::TABLE
),
311 'c.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
314 //restrict query on current member id if he's not admin nor staff member
315 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
318 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
320 ->equalTo('a.parent_id', $this->login
->id
)
323 ->equalTo('c.' . self
::PK
, $id)
326 $select->where
->equalTo(self
::PK
, $id);
329 $results = $this->zdb
->execute($select);
330 if ($results->count() > 0) {
331 $row = $results->current();
332 $this->loadFromRS($row);
336 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')',
341 } catch (Throwable
$e) {
343 'An error occurred attempting to load contribution #' . $id .
352 * Populate object from a resultset row
354 * @param ResultSet $r the resultset row
358 private function loadFromRS($r)
361 $this->_id
= (int)$r->$pk;
362 $this->_date
= $r->date_enreg
;
363 $this->_amount
= (double)$r->montant_cotis
;
364 //save original amount, we need it for transactions parts calculations
365 $this->_orig_amount
= (double)$r->montant_cotis
;
366 $this->_payment_type
= $r->type_paiement_cotis
;
367 $this->_info
= $r->info_cotis
;
368 $this->_begin_date
= $r->date_debut_cotis
;
369 $end_date = $r->date_fin_cotis
;
370 //do not work with knows bad dates...
371 //the one with BC comes from 0.63/pgsql demo... Why the hell a so
372 //strange date? don't know :(
374 $end_date !== '0000-00-00'
375 && $end_date !== '1901-01-01'
376 && $end_date !== '0001-01-01 BC'
378 $this->_end_date
= $r->date_fin_cotis
;
380 $adhpk = Adherent
::PK
;
381 $this->_member
= (int)$r->$adhpk;
383 $transpk = Transaction
::PK
;
384 if ($r->$transpk != '') {
385 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
388 $this->type
= (int)$r->id_type_cotis
;
389 $this->loadDynamicFields();
393 * Check posted values validity
395 * @param array $values All values to check, basically the $_POST array
396 * after sending the form
397 * @param array $required Array of required fields
398 * @param array $disabled Array of disabled fields
402 public function check($values, $required, $disabled)
405 $this->errors
= array();
407 $fields = array_keys($this->_fields
);
408 foreach ($fields as $key) {
409 //first, let's sanitize values
410 $key = strtolower($key);
411 $prop = '_' . $this->_fields
[$key]['propname'];
413 if (isset($values[$key])) {
414 $value = trim($values[$key]);
419 // if the field is enabled, check it
420 if (!isset($disabled[$key])) {
421 // fill up the adherent structure
422 //$this->$prop = stripslashes($value); //not relevant here!
424 // now, check validity
428 case 'date_debut_cotis':
429 case 'date_fin_cotis':
432 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
434 throw new \
Exception('Incorrect format');
436 $this->$prop = $d->format('Y-m-d');
437 } catch (Throwable
$e) {
439 'Wrong date format. field: ' . $key .
440 ', value: ' . $value . ', expected fmt: ' .
441 __("Y-m-d") . ' | ' . $e->getMessage(),
444 $this->errors
[] = str_replace(
451 $this->_fields
[$key]['label']
453 _T("- Wrong date format (%date_format) for %field!")
460 $this->_member
= (int)$value;
463 case ContributionsTypes
::PK
:
465 $this->type
= (int)$value;
468 case 'montant_cotis':
469 $value = strtr($value, ',', '.');
470 if (!empty($value)) {
471 $this->_amount
= $value;
473 if (!is_numeric($value) && $value !== '') {
474 $this->errors
[] = _T("- The amount must be an integer!");
477 case 'type_paiement_cotis':
478 $ptypes = new PaymentTypes(
483 $ptlist = $ptypes->getList();
484 if (isset($ptlist[$value])) {
485 $this->_payment_type
= $value;
487 $this->errors
[] = _T("- Unknown payment type");
491 $this->_info
= $value;
493 case Transaction
::PK
:
495 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
498 case 'duree_mois_cotis':
500 if (!is_numeric($value) ||
$value <= 0) {
501 $this->errors
[] = _T("- The duration must be a positive integer!");
503 $this->$prop = $value;
504 $this->retrieveEndDate();
511 // missing required fields?
512 foreach ($required as $key => $val) {
514 $prop = '_' . $this->_fields
[$key]['propname'];
516 !isset($disabled[$key])
517 && (!isset($this->$prop)
518 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
519 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
521 $this->errors
[] = str_replace(
523 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
524 _T("- Mandatory field %field empty.")
530 if ($this->_transaction
!= null && $this->_amount
!= null) {
531 $missing = $this->_transaction
->getMissingAmount();
532 //calculate new missing amount
533 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
535 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
539 if ($this->isFee() && count($this->errors
) == 0) {
540 $overlap = $this->checkOverlap();
541 if ($overlap !== true) {
542 //method directly return error message
543 $this->errors
[] = $overlap;
547 $this->dynamicsCheck($values, $required, $disabled);
549 if (count($this->errors
) > 0) {
551 'Some errors has been threw attempting to edit/store a contribution' .
552 print_r($this->errors
, true),
555 return $this->errors
;
558 'Contribution checked successfully.',
566 * Check that membership fees does not overlap
568 * @return boolean|string True if all is ok, false if error,
569 * error message if overlap
571 public function checkOverlap()
574 $select = $this->zdb
->select(self
::TABLE
, 'c');
576 array('date_debut_cotis', 'date_fin_cotis')
578 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
579 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
581 )->where([Adherent
::PK
=> $this->_member
])
582 ->where(array('cotis_extension' => new Expression('true')))
584 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
585 ->lessThanOrEqualTo('date_debut_cotis', $this->_end_date
)
588 ->greaterThanOrEqualTo('date_fin_cotis', $this->_begin_date
)
589 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
591 if ($this->id
!= '') {
592 $select->where
->notEqualTo(self
::PK
, $this->id
);
595 $results = $this->zdb
->execute($select);
596 if ($results->count() > 0) {
597 $result = $results->current();
598 $d = new \
DateTime($result->date_debut_cotis
);
600 return _T("- Membership period overlaps period starting at ") .
601 $d->format(__("Y-m-d"));
604 } catch (Throwable
$e) {
606 'An error occurred checking overlapping fee. ' . $e->getMessage(),
614 * Store the contribution
618 public function store()
620 global $hist, $emitter;
624 if (count($this->errors
) > 0) {
625 throw new \
RuntimeException(
626 'Existing errors prevents storing contribution: ' .
627 print_r($this->errors
, true)
632 $this->zdb
->connection
->beginTransaction();
634 $fields = self
::getDbFields($this->zdb
);
635 foreach ($fields as $field) {
636 $prop = '_' . $this->_fields
[$field]['propname'];
638 case ContributionsTypes
::PK
:
639 case Transaction
::PK
:
640 if (isset($this->$prop)) {
641 $values[$field] = $this->$prop->id
;
645 $values[$field] = $this->$prop;
650 //no end date, let's take database defaults
651 if (!$this->isFee() && !$this->_end_date
) {
652 unset($values['date_fin_cotis']);
656 if (!isset($this->_id
) ||
$this->_id
== '') {
657 //we're inserting a new contribution
658 unset($values[self
::PK
]);
660 $insert = $this->zdb
->insert(self
::TABLE
);
661 $insert->values($values);
662 $add = $this->zdb
->execute($insert);
664 if ($add->count() > 0) {
665 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
669 _T("Contribution added"),
670 Adherent
::getSName($this->zdb
, $this->_member
)
673 $event = 'contribution.add';
675 $hist->add(_T("Fail to add new contribution."));
676 throw new \
Exception(
677 'An error occurred inserting new contribution!'
681 //we're editing an existing contribution
682 $update = $this->zdb
->update(self
::TABLE
);
683 $update->set($values)->where([self
::PK
=> $this->_id
]);
684 $edit = $this->zdb
->execute($update);
686 //edit == 0 does not mean there were an error, but that there
687 //were nothing to change
688 if ($edit->count() > 0) {
690 _T("Contribution updated"),
691 Adherent
::getSName($this->zdb
, $this->_member
)
695 if ($edit === false) {
696 throw new \
Exception(
697 'An error occurred updating contribution # ' . $this->_id
. '!'
701 $event = 'contribution.edit';
704 if ($this->isFee()) {
705 $this->updateDeadline();
710 $success = $this->dynamicsStore(true);
713 $this->zdb
->connection
->commit();
714 $this->_orig_amount
= $this->_amount
;
716 //send event at the end of process, once all has been stored
717 if ($event !== null) {
718 $emitter->emit($event, $this);
722 } catch (Throwable
$e) {
723 if ($this->zdb
->connection
->inTransaction()) {
724 $this->zdb
->connection
->rollBack();
731 * Update member dead line
735 private function updateDeadline()
738 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
740 if ($due_date != '') {
741 $due_date_update = $due_date;
743 $due_date_update = new Expression('NULL');
746 $update = $this->zdb
->update(Adherent
::TABLE
);
748 array('date_echeance' => $due_date_update)
750 [Adherent
::PK
=> $this->_member
]
752 $this->zdb
->execute($update);
754 } catch (Throwable
$e) {
756 'An error occurred updating member ' . $this->_member
.
766 * Remove contribution from database
768 * @param boolean $transaction Activate transaction mode (defaults to true)
772 public function remove($transaction = true)
778 $this->zdb
->connection
->beginTransaction();
781 $delete = $this->zdb
->delete(self
::TABLE
);
782 $delete->where([self
::PK
=> $this->_id
]);
783 $del = $this->zdb
->execute($delete);
784 if ($del->count() > 0) {
785 $this->updateDeadline();
786 $this->dynamicsRemove(true);
789 'Contribution has not been removed!',
795 $this->zdb
->connection
->commit();
797 $emitter->emit('contribution.remove', $this);
799 } catch (Throwable
$e) {
801 $this->zdb
->connection
->rollBack();
804 'An error occurred trying to remove contribution #' .
805 $this->_id
. ' | ' . $e->getMessage(),
815 * @param string $field Field name
819 public function getFieldLabel($field)
821 $label = $this->_fields
[$field]['label'];
822 if ($this->isFee() && $field == 'date_debut_cotis') {
823 $label = $this->_fields
[$field]['cotlabel'];
826 $label = str_replace(' ', ' ', $label);
827 //remove trailing ':' and then trim
828 $label = trim(trim($label, ':'));
833 * Retrieve fields from database
835 * @param Db $zdb Database instance
839 public static function getDbFields(Db
$zdb)
841 $columns = $zdb->getColumns(self
::TABLE
);
843 foreach ($columns as $col) {
844 $fields[] = $col->getName();
850 * Get the relevant CSS class for current contribution
852 * @return string current contribution row class
854 public function getRowClass()
856 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
857 'cotis-normal' : 'cotis-give';
861 * Retrieve member due date
863 * @param Db $zdb Database instance
864 * @param integer $member_id Member identifier
868 public static function getDueDate(Db
$zdb, $member_id)
874 $select = $zdb->select(self
::TABLE
, 'c');
877 'max_date' => new Expression('MAX(date_fin_cotis)')
880 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
881 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
884 [Adherent
::PK
=> $member_id]
886 array('cotis_extension' => new Expression('true'))
889 $results = $zdb->execute($select);
890 $result = $results->current();
891 $due_date = $result->max_date
;
893 //avoid bad dates in postgres and bad mysql return from zenddb
894 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
898 } catch (Throwable
$e) {
900 'An error occurred trying to retrieve member\'s due date',
908 * Detach a contribution from a transaction
910 * @param Db $zdb Database instance
911 * @param Login $login Login instance
912 * @param int $trans_id Transaction identifier
913 * @param int $contrib_id Contribution identifier
917 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
920 //first, we check if contribution is part of transaction
921 $c = new Contribution($zdb, $login, (int)$contrib_id);
922 if ($c->isTransactionPartOf($trans_id)) {
923 $update = $zdb->update(self
::TABLE
);
925 array(Transaction
::PK
=> null)
927 [self
::PK
=> $contrib_id]
929 $zdb->execute($update);
933 'Contribution #' . $contrib_id .
934 ' is not actually part of transaction #' . $trans_id,
939 } catch (Throwable
$e) {
941 'Unable to detach contribution #' . $contrib_id .
942 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
950 * Set a contribution as a transaction part
952 * @param Db $zdb Database instance
953 * @param int $trans_id Transaction identifier
954 * @param int $contrib_id Contribution identifier
958 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
961 $update = $zdb->update(self
::TABLE
);
963 array(Transaction
::PK
=> $trans_id)
964 )->where([self
::PK
=> $contrib_id]);
966 $zdb->execute($update);
968 } catch (Throwable
$e) {
970 'Unable to attach contribution #' . $contrib_id .
971 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
979 * Is current contribution a membership fee
983 public function isFee()
985 return $this->_is_cotis
;
989 * Is current contribution part of specified transaction
991 * @param int $id Transaction identifier
995 public function isTransactionPartOf($id)
997 if ($this->isTransactionPart()) {
998 return $id == $this->_transaction
->id
;
1005 * Is current contribution part of transaction
1009 public function isTransactionPart()
1011 return $this->_transaction
!= null;
1015 * Execute post contribution script
1017 * @param ExternalScript $es External script to execute
1018 * @param array $extra Extra information on contribution
1020 * @param array $pextra Extra information on payment
1023 * @return mixed Script return value on success, values and script output on fail
1025 public function executePostScript(
1030 global $preferences;
1033 'type' => $this->getPaymentType()
1036 if ($pextra !== null && is_array($pextra)) {
1037 $payment = array_merge($payment, $pextra);
1040 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1041 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1044 $voucher_path = null;
1045 if ($this->_id
!== null) {
1046 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1047 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1048 $voucher_path = $voucher->getPath();
1052 'id' => (int)$this->_id
,
1053 'date' => $this->_date
,
1054 'type' => $this->getRawType(),
1055 'amount' => $this->amount
,
1056 'voucher' => $voucher_path,
1057 'category' => array(
1058 'id' => $this->type
->id
,
1059 'label' => $this->type
->libelle
1061 'payment' => $payment
1064 if ($this->_member
!== null) {
1065 $m = new Adherent($this->zdb
, (int)$this->_member
);
1067 'id' => (int)$this->_member
,
1068 'name' => $m->sfullname
,
1069 'email' => $m->email
,
1070 'organization' => ($m->isCompany() ?
1 : 0),
1073 'label' => $m->sstatus
1075 'country' => $m->country
1078 if ($m->isCompany()) {
1079 $member['organization_name'] = $m->company_name
;
1082 $contrib['member'] = $member;
1085 if ($extra !== null && is_array($extra)) {
1086 $contrib = array_merge($contrib, $extra);
1089 $res = $es->send($contrib);
1091 if ($res !== true) {
1093 'An error occurred calling post contribution ' .
1094 "script:\n" . $es->getOutput(),
1097 $res = _T("Contribution information") . "\n";
1098 $res .= print_r($contrib, true);
1099 $res .= "\n\n" . _T("Script output") . "\n";
1100 $res .= $es->getOutput();
1106 * Get raw contribution type
1110 public function getRawType()
1112 if ($this->isFee()) {
1113 return 'membership';
1120 * Get contribution type label
1124 public function getTypeLabel()
1126 if ($this->isFee()) {
1127 return _T("Membership");
1129 return _T("Donation");
1134 * Get payment type label
1136 * @param boolean $translated Whether to translate
1140 public function getPaymentType(bool $translated = false): string
1142 if ($this->_payment_type
=== null) {
1146 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1147 return $ptype->getName($translated);
1151 * Global getter method
1153 * @param string $name name of the property we want to retrieve
1155 * @return false|object the called property
1157 public function __get($name)
1160 $forbidden = array('is_cotis');
1161 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1162 'raw_begin_date', 'raw_end_date'
1165 $rname = '_' . $name;
1167 if (in_array($name, $forbidden)) {
1169 "Call to __get for '$name' is forbidden!",
1175 return $this->isFee();
1178 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1181 property_exists($this, $rname)
1182 ||
in_array($name, $virtuals)
1186 case 'raw_begin_date':
1187 case 'raw_end_date':
1188 $rname = '_' . substr($name, 4);
1189 if ($this->$rname != '') {
1191 $d = new \
DateTime($this->$rname);
1193 } catch (Throwable
$e) {
1194 //oops, we've got a bad date :/
1196 'Bad date (' . $this->$rname . ') | ' .
1207 if ($this->$rname != '') {
1209 $d = new \
DateTime($this->$rname);
1210 return $d->format(__("Y-m-d"));
1211 } catch (Throwable
$e) {
1212 //oops, we've got a bad date :/
1214 'Bad date (' . $this->$rname . ') | ' .
1218 return $this->$rname;
1223 if ($this->_is_cotis
) {
1224 // Caution : the end_date stored is actually the due date.
1225 // Adding a day to compute the next_begin_date is required
1226 // to return the right number of months.
1227 $next_begin_date = new \
DateTime($this->_end_date
);
1228 $next_begin_date->add(new \
DateInterval('P1D'));
1229 $begin_date = new \
DateTime($this->_begin_date
);
1230 $diff = $next_begin_date->diff($begin_date);
1231 return $diff->format('%y') * 12 +
$diff->format('%m');
1236 case 'spayment_type':
1237 return $this->getPaymentType(true);
1240 if ($this->_is_cotis
=== null) {
1243 return ($this->isFee()) ?
1244 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1247 return $this->$rname;
1252 "Unknown property '$rname'",
1260 * Global isset method
1261 * Required for twig to access properties via __get
1263 * @param string $name name of the property we want to retrieve
1265 * @return false|object the called property
1267 public function __isset($name)
1269 $forbidden = array('is_cotis');
1270 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1271 'raw_begin_date', 'raw_end_date'
1274 $rname = '_' . $name;
1276 if (in_array($name, $forbidden)) {
1282 property_exists($this, $rname)
1283 ||
in_array($name, $virtuals)
1293 * Global setter method
1295 * @param string $name name of the property we want to assign a value to
1296 * @param object $value a relevant value for the property
1300 public function __set($name, $value)
1302 global $preferences;
1304 $forbidden = array('fields', 'is_cotis', 'end_date');
1306 if (!in_array($name, $forbidden)) {
1307 $rname = '_' . $name;
1310 if (is_int($value)) {
1311 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1314 'Trying to set a transaction from an id that is not an integer.',
1320 if (is_int($value)) {
1322 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1323 //set is_cotis according to type
1324 if ($this->$rname->extension
== 1) {
1325 $this->_is_cotis
= true;
1327 $this->_is_cotis
= false;
1331 'Trying to set a type from an id that is not an integer.',
1338 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1340 throw new \
Exception('Incorrect format');
1342 $this->_begin_date
= $d->format('Y-m-d');
1343 } catch (Throwable
$e) {
1345 'Wrong date format. field: ' . $name .
1346 ', value: ' . $value . ', expected fmt: ' .
1347 __("Y-m-d") . ' | ' . $e->getMessage(),
1350 $this->errors
[] = str_replace(
1357 $this->_fields
['date_debut_cotis']['label']
1359 _T("- Wrong date format (%date_format) for %field!")
1364 if (is_numeric($value) && $value > 0) {
1365 $this->$rname = $value;
1368 'Trying to set an amount with a non numeric value, ' .
1369 'or with a zero value',
1375 if (is_int($value)) {
1377 $this->$rname = $value;
1380 case 'payment_type':
1381 $ptypes = new PaymentTypes(
1386 $list = $ptypes->getList();
1387 if (isset($list[$value])) {
1388 $this->_payment_type
= $value;
1391 'Unknown payment type ' . $value,
1398 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1408 * Flag creation mail sending
1410 * @param boolean $send True (default) to send creation email
1412 * @return Contribution
1414 public function setSendmail($send = true)
1416 $this->sendmail
= $send;
1421 * Should we send administrative emails to member?
1425 public function sendEMail()
1427 return $this->sendmail
;
1431 * Handle files (dynamics files)
1433 * @param array $files Files sent
1435 * @return array|true
1437 public function handleFiles($files)
1441 $this->dynamicsFiles($files);
1443 if (count($this->errors
) > 0) {
1445 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1446 print_r($this->errors
, true),
1449 return $this->errors
;
1456 * Get required fields list
1460 public function getRequired(): array
1463 'id_type_cotis' => 1,
1466 'date_debut_cotis' => 1,
1467 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1468 'montant_cotis' => $this->isFee() ?
1 : 0
1473 * Can current logged-in user display contribution
1475 * @param Login $login Login instance
1479 public function canShow(Login
$login): bool
1481 //non-logged-in members cannot show contributions
1482 if (!$login->isLogged()) {
1486 //admin and staff users can edit, as well as member itself
1487 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1491 //parent can see their children contributions
1492 $parent = new Adherent($this->zdb
);
1495 ->enableDep('children')
1496 ->load($this->login
->id
);
1497 if ($parent->hasChildren()) {
1498 foreach ($parent->children
as $child) {
1499 if ($child->id
=== $this->_member
) {