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
->isGroupManager()) {
306 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
308 ->equalTo('a.parent_id', $this->login
->id
)
311 ->equalTo('c.' . self
::PK
, $id)
315 Adherent
::PK
=> $this->login
->id
,
320 $select->where
->equalTo(self
::PK
, $id);
323 $results = $this->zdb
->execute($select);
324 if ($results->count() > 0) {
325 $row = $results->current();
326 $this->loadFromRS($row);
329 throw new \
Exception(
330 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')'
333 } catch (Throwable
$e) {
335 'An error occurred attempting to load contribution #' . $id .
344 * Populate object from a resultset row
346 * @param ResultSet $r the resultset row
350 private function loadFromRS($r)
353 $this->_id
= (int)$r->$pk;
354 $this->_date
= $r->date_enreg
;
355 $this->_amount
= (int)$r->montant_cotis
;
356 //save original amount, we need it for transactions parts calculations
357 $this->_orig_amount
= (int)$r->montant_cotis
;
358 $this->_payment_type
= $r->type_paiement_cotis
;
359 $this->_info
= $r->info_cotis
;
360 $this->_begin_date
= $r->date_debut_cotis
;
361 $enddate = $r->date_fin_cotis
;
362 //do not work with knows bad dates...
363 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
364 //strange date? don't know :(
366 $enddate !== '0000-00-00'
367 && $enddate !== '1901-01-01'
368 && $enddate !== '0001-01-01 BC'
370 $this->_end_date
= $r->date_fin_cotis
;
372 $adhpk = Adherent
::PK
;
373 $this->_member
= (int)$r->$adhpk;
375 $transpk = Transaction
::PK
;
376 if ($r->$transpk != '') {
377 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
380 $this->type
= (int)$r->id_type_cotis
;
381 $this->loadDynamicFields();
385 * Check posted values validity
387 * @param array $values All values to check, basically the $_POST array
388 * after sending the form
389 * @param array $required Array of required fields
390 * @param array $disabled Array of disabled fields
394 public function check($values, $required, $disabled)
397 $this->errors
= array();
399 $fields = array_keys($this->_fields
);
400 foreach ($fields as $key) {
401 //first, let's sanitize values
402 $key = strtolower($key);
403 $prop = '_' . $this->_fields
[$key]['propname'];
405 if (isset($values[$key])) {
406 $value = trim($values[$key]);
411 // if the field is enabled, check it
412 if (!isset($disabled[$key])) {
413 // fill up the adherent structure
414 //$this->$prop = stripslashes($value); //not relevant here!
416 // now, check validity
420 case 'date_debut_cotis':
421 case 'date_fin_cotis':
424 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
426 throw new \
Exception('Incorrect format');
428 $this->$prop = $d->format('Y-m-d');
429 } catch (Throwable
$e) {
431 'Wrong date format. field: ' . $key .
432 ', value: ' . $value . ', expected fmt: ' .
433 __("Y-m-d") . ' | ' . $e->getMessage(),
436 $this->errors
[] = str_replace(
443 $this->_fields
[$key]['label']
445 _T("- Wrong date format (%date_format) for %field!")
452 $this->_member
= (int)$value;
455 case ContributionsTypes
::PK
:
457 $this->type
= (int)$value;
460 case 'montant_cotis':
461 $this->_amount
= $value;
462 $value = strtr($value, ',', '.');
463 if (!is_numeric($value) && $value !== '') {
464 $this->errors
[] = _T("- The amount must be an integer!");
467 case 'type_paiement_cotis':
468 $ptypes = new PaymentTypes(
473 $ptlist = $ptypes->getList();
474 if (isset($ptlist[$value])) {
475 $this->_payment_type
= $value;
477 $this->errors
[] = _T("- Unknown payment type");
481 $this->_info
= $value;
483 case Transaction
::PK
:
485 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
488 case 'duree_mois_cotis':
490 if (!is_numeric($value) ||
$value <= 0) {
491 $this->errors
[] = _T("- The duration must be a positive integer!");
493 $this->$prop = $value;
494 $this->retrieveEndDate();
501 // missing required fields?
502 foreach ($required as $key => $val) {
504 $prop = '_' . $this->_fields
[$key]['propname'];
506 !isset($disabled[$key])
507 && (!isset($this->$prop)
508 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
509 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
511 $this->errors
[] = str_replace(
513 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
514 _T("- Mandatory field %field empty.")
520 if ($this->_transaction
!= null && $this->_amount
!= null) {
521 $missing = $this->_transaction
->getMissingAmount();
522 //calculate new missing amount
523 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
525 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
529 if ($this->isFee() && count($this->errors
) == 0) {
530 $overlap = $this->checkOverlap();
531 if ($overlap !== true) {
532 if ($overlap === false) {
533 $this->errors
[] = _T("An error occurred checking overlapping fees :(");
535 //method directly return error message
536 $this->errors
[] = $overlap;
541 $this->dynamicsCheck($values, $required, $disabled);
543 if (count($this->errors
) > 0) {
545 'Some errors has been threw attempting to edit/store a contribution' .
546 print_r($this->errors
, true),
549 return $this->errors
;
552 'Contribution checked successfully.',
560 * Check that membership fees does not overlap
562 * @return boolean|string True if all is ok, false if error,
563 * error message if overlap
565 public function checkOverlap()
568 $select = $this->zdb
->select(self
::TABLE
, 'c');
570 array('date_debut_cotis', 'date_fin_cotis')
572 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
573 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
575 )->where(Adherent
::PK
. ' = ' . $this->_member
)
576 ->where(array('cotis_extension' => new Expression('true')))
578 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
579 ->lessThan('date_debut_cotis', $this->_end_date
)
582 ->greaterThan('date_fin_cotis', $this->_begin_date
)
583 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
585 if ($this->id
!= '') {
586 $select->where(self
::PK
. ' != ' . $this->id
);
589 $results = $this->zdb
->execute($select);
590 if ($results->count() > 0) {
591 $result = $results->current();
592 $d = new \
DateTime($result->date_debut_cotis
);
594 return _T("- Membership period overlaps period starting at ") .
595 $d->format(__("Y-m-d"));
598 } catch (Throwable
$e) {
600 'An error occurred checking overlapping fee. ' . $e->getMessage(),
608 * Store the contribution
612 public function store()
614 global $hist, $emitter;
618 if (count($this->errors
) > 0) {
619 throw new \
RuntimeException(
620 'Existing errors prevents storing contribution: ' .
621 print_r($this->errors
, true)
626 $this->zdb
->connection
->beginTransaction();
628 $fields = self
::getDbFields($this->zdb
);
629 foreach ($fields as $field) {
630 $prop = '_' . $this->_fields
[$field]['propname'];
632 case ContributionsTypes
::PK
:
633 case Transaction
::PK
:
634 if (isset($this->$prop)) {
635 $values[$field] = $this->$prop->id
;
639 $values[$field] = $this->$prop;
644 //no end date, let's take database defaults
645 if (!$this->isFee() && !$this->_end_date
) {
646 unset($values['date_fin_cotis']);
650 if (!isset($this->_id
) ||
$this->_id
== '') {
651 //we're inserting a new contribution
652 unset($values[self
::PK
]);
654 $insert = $this->zdb
->insert(self
::TABLE
);
655 $insert->values($values);
656 $add = $this->zdb
->execute($insert);
658 if ($add->count() > 0) {
659 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
663 _T("Contribution added"),
664 Adherent
::getSName($this->zdb
, $this->_member
)
667 $event = 'contribution.add';
669 $hist->add(_T("Fail to add new contribution."));
670 throw new \
Exception(
671 'An error occurred inserting new contribution!'
675 //we're editing an existing contribution
676 $update = $this->zdb
->update(self
::TABLE
);
677 $update->set($values)->where(
678 self
::PK
. '=' . $this->_id
680 $edit = $this->zdb
->execute($update);
682 //edit == 0 does not mean there were an error, but that there
683 //were nothing to change
684 if ($edit->count() > 0) {
686 _T("Contribution updated"),
687 Adherent
::getSName($this->zdb
, $this->_member
)
691 if ($edit === false) {
692 throw new \
Exception(
693 'An error occurred updating contribution # ' . $this->_id
. '!'
697 $event = 'contribution.edit';
700 if ($this->isFee()) {
701 $deadline = $this->updateDeadline();
702 if ($deadline !== true) {
703 //if something went wrong, we roll back transaction
704 throw new \
Exception('An error occurred updating member\'s deadline');
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 $date_fin_update = $due_date;
743 $date_fin_update = new Expression('NULL');
746 $update = $this->zdb
->update(Adherent
::TABLE
);
748 array('date_echeance' => $date_fin_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);
788 throw new \
RuntimeException(
789 'Contribution has not been removed!'
793 $this->zdb
->connection
->commit();
795 $emitter->emit('contribution.remove', $this);
797 } catch (Throwable
$e) {
799 $this->zdb
->connection
->rollBack();
802 'An error occurred trying to remove contribution #' .
803 $this->_id
. ' | ' . $e->getMessage(),
813 * @param string $field Field name
817 public function getFieldLabel($field)
819 $label = $this->_fields
[$field]['label'];
820 if ($this->isFee() && $field == 'date_debut_cotis') {
821 $label = $this->_fields
[$field]['cotlabel'];
824 $label = str_replace(' ', ' ', $label);
825 //remove trailing ':' and then trim
826 $label = trim(trim($label, ':'));
831 * Retrieve fields from database
833 * @param Db $zdb Database instance
837 public static function getDbFields(Db
$zdb)
839 $columns = $zdb->getColumns(self
::TABLE
);
841 foreach ($columns as $col) {
842 $fields[] = $col->getName();
848 * Get the relevant CSS class for current contribution
850 * @return string current contribution row class
852 public function getRowClass()
854 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
855 'cotis-normal' : 'cotis-give';
859 * Retrieve member due date
861 * @param Db $zdb Database instance
862 * @param integer $member_id Member identifier
866 public static function getDueDate(Db
$zdb, $member_id)
872 $select = $zdb->select(self
::TABLE
, 'c');
875 'max_date' => new Expression('MAX(date_fin_cotis)')
878 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
879 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
882 Adherent
::PK
. ' = ' . $member_id
884 array('cotis_extension' => new Expression('true'))
887 $results = $zdb->execute($select);
888 $result = $results->current();
889 $due_date = $result->max_date
;
891 //avoid bad dates in postgres and bad mysql return from zenddb
892 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
896 } catch (Throwable
$e) {
898 'An error occurred trying to retrieve member\'s due date',
906 * Detach a contribution from a transaction
908 * @param Db $zdb Database instance
909 * @param Login $login Login instance
910 * @param int $trans_id Transaction identifier
911 * @param int $contrib_id Contribution identifier
915 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
918 //first, we check if contribution is part of transaction
919 $c = new Contribution($zdb, $login, (int)$contrib_id);
920 if ($c->isTransactionPartOf($trans_id)) {
921 $update = $zdb->update(self
::TABLE
);
923 array(Transaction
::PK
=> null)
925 self
::PK
. ' = ' . $contrib_id
927 $zdb->execute($update);
931 'Contribution #' . $contrib_id .
932 ' is not actually part of transaction #' . $trans_id,
937 } catch (Throwable
$e) {
939 'Unable to detach contribution #' . $contrib_id .
940 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
948 * Set a contribution as a transaction part
950 * @param Db $zdb Database instance
951 * @param int $trans_id Transaction identifier
952 * @param int $contrib_id Contribution identifier
956 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
959 $update = $zdb->update(self
::TABLE
);
961 array(Transaction
::PK
=> $trans_id)
962 )->where(self
::PK
. ' = ' . $contrib_id);
964 $zdb->execute($update);
966 } catch (Throwable
$e) {
968 'Unable to attach contribution #' . $contrib_id .
969 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
977 * Is current contribution a membership fee
981 public function isFee()
983 return $this->_is_cotis
;
987 * Is current contribution part of specified transaction
989 * @param int $id Transaction identifier
993 public function isTransactionPartOf($id)
995 if ($this->isTransactionPart()) {
996 return $id == $this->_transaction
->id
;
1003 * Is current contribution part of transaction
1007 public function isTransactionPart()
1009 return $this->_transaction
!= null;
1013 * Execute post contribution script
1015 * @param ExternalScript $es External script to execute
1016 * @param array $extra Extra information on contribution
1018 * @param array $pextra Extra information on payment
1021 * @return mixed Script return value on success, values and script output on fail
1023 public function executePostScript(
1028 global $preferences;
1031 'type' => $this->getPaymentType()
1034 if ($pextra !== null && is_array($pextra)) {
1035 $payment = array_merge($payment, $pextra);
1038 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1039 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1042 $voucher_path = null;
1043 if ($this->_id
!== null) {
1044 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1045 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1046 $voucher_path = $voucher->getPath();
1050 'id' => (int)$this->_id
,
1051 'date' => $this->_date
,
1052 'type' => $this->getRawType(),
1053 'amount' => $this->amount
,
1054 'voucher' => $voucher_path,
1055 'category' => array(
1056 'id' => $this->type
->id
,
1057 'label' => $this->type
->libelle
1059 'payment' => $payment
1062 if ($this->_member
!== null) {
1063 $m = new Adherent($this->zdb
, (int)$this->_member
);
1065 'id' => (int)$this->_member
,
1066 'name' => $m->sfullname
,
1067 'email' => $m->email
,
1068 'organization' => ($m->isCompany() ?
1 : 0),
1071 'label' => $m->sstatus
1073 'country' => $m->country
1076 if ($m->isCompany()) {
1077 $member['organization_name'] = $m->company_name
;
1080 $contrib['member'] = $member;
1083 if ($extra !== null && is_array($extra)) {
1084 $contrib = array_merge($contrib, $extra);
1087 $res = $es->send($contrib);
1089 if ($res !== true) {
1091 'An error occurred calling post contribution ' .
1092 "script:\n" . $es->getOutput(),
1095 $res = _T("Contribution information") . "\n";
1096 $res .= print_r($contrib, true);
1097 $res .= "\n\n" . _T("Script output") . "\n";
1098 $res .= $es->getOutput();
1104 * Get raw contribution type
1108 public function getRawType()
1110 if ($this->isFee()) {
1111 return 'membership';
1118 * Get contribution type label
1122 public function getTypeLabel()
1124 if ($this->isFee()) {
1125 return _T("Membership");
1127 return _T("Donation");
1132 * Get payment type label
1136 public function getPaymentType()
1138 if ($this->_payment_type
=== null) {
1142 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1143 return $ptype->getName(false);
1147 * Global getter method
1149 * @param string $name name of the property we want to retrieve
1151 * @return false|object the called property
1153 public function __get($name)
1156 $forbidden = array('is_cotis');
1157 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1158 'raw_begin_date', 'raw_end_date'
1161 $rname = '_' . $name;
1163 if (in_array($name, $forbidden)) {
1165 "Call to __get for '$name' is forbidden!",
1171 return $this->isFee();
1174 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1177 property_exists($this, $rname)
1178 ||
in_array($name, $virtuals)
1182 case 'raw_begin_date':
1183 case 'raw_end_date':
1184 $rname = '_' . substr($name, 4);
1185 if ($this->$rname != '') {
1187 $d = new \
DateTime($this->$rname);
1189 } catch (Throwable
$e) {
1190 //oops, we've got a bad date :/
1192 'Bad date (' . $this->$rname . ') | ' .
1203 if ($this->$rname != '') {
1205 $d = new \
DateTime($this->$rname);
1206 return $d->format(__("Y-m-d"));
1207 } catch (Throwable
$e) {
1208 //oops, we've got a bad date :/
1210 'Bad date (' . $this->$rname . ') | ' .
1214 return $this->$rname;
1219 if ($this->_is_cotis
) {
1220 $date_end = new \
DateTime($this->_end_date
);
1221 $date_start = new \
DateTime($this->_begin_date
);
1222 $diff = $date_end->diff($date_start);
1223 return $diff->format('%y') * 12 +
$diff->format('%m');
1228 case 'spayment_type':
1229 if ($this->_payment_type
=== null) {
1233 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1234 return $ptype->getName();
1238 if ($this->_is_cotis
=== null) {
1241 return ($this->isFee()) ?
1242 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1245 return $this->$rname;
1250 "Unknown property '$rname'",
1258 * Global setter method
1260 * @param string $name name of the property we want to assign a value to
1261 * @param object $value a relevant value for the property
1265 public function __set($name, $value)
1267 global $preferences;
1269 $forbidden = array('fields', 'is_cotis', 'end_date');
1271 if (!in_array($name, $forbidden)) {
1272 $rname = '_' . $name;
1275 if (is_int($value)) {
1276 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1279 'Trying to set a transaction from an id that is not an integer.',
1285 if (is_int($value)) {
1287 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1288 //set is_cotis according to type
1289 if ($this->$rname->extension
== 1) {
1290 $this->_is_cotis
= true;
1292 $this->_is_cotis
= false;
1296 'Trying to set a type from an id that is not an integer.',
1303 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1305 throw new \
Exception('Incorrect format');
1307 $this->_begin_date
= $d->format('Y-m-d');
1308 } catch (Throwable
$e) {
1310 'Wrong date format. field: ' . $name .
1311 ', value: ' . $value . ', expected fmt: ' .
1312 __("Y-m-d") . ' | ' . $e->getMessage(),
1315 $this->errors
[] = str_replace(
1322 $this->_fields
['date_debut_cotis']['label']
1324 _T("- Wrong date format (%date_format) for %field!")
1329 if (is_numeric($value) && $value > 0) {
1330 $this->$rname = $value;
1333 'Trying to set an amount with a non numeric value, ' .
1334 'or with a zero value',
1340 if (is_int($value)) {
1342 $this->$rname = $value;
1345 case 'payment_type':
1346 $ptypes = new PaymentTypes(
1351 $list = $ptypes->getList();
1352 if (isset($list[$value])) {
1353 $this->_payment_type
= $value;
1356 'Unknown payment type ' . $value,
1363 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1373 * Flag creation mail sending
1375 * @param boolean $send True (default) to send creation email
1377 * @return Contribution
1379 public function setSendmail($send = true)
1381 $this->sendmail
= $send;
1386 * Should we send administrative emails to member?
1390 public function sendEMail()
1392 return $this->sendmail
;
1396 * Handle files (dynamics files)
1398 * @param array $files Files sent
1400 * @return array|true
1402 public function handleFiles($files)
1406 $this->dynamicsFiles($files);
1408 if (count($this->errors
) > 0) {
1410 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1411 print_r($this->errors
, true),
1414 return $this->errors
;
1421 * Get required fields list
1425 public function getRequired(): array
1428 'id_type_cotis' => 1,
1431 'date_debut_cotis' => 1,
1432 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1433 'montant_cotis' => $this->isFee() ?
1 : 0
1438 * Can current logged-in user display contribution
1440 * @param Login $login Login instance
1444 public function canShow(Login
$login): bool
1446 //admin and staff users can edit, as well as member itself
1447 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1451 //parent can see their children contributions
1452 $parent = new Adherent($this->zdb
);
1455 ->enableDep('children')
1456 ->load($this->login
->id
);
1457 if ($parent->hasChildren()) {
1458 foreach ($parent->children
as $child) {
1459 if ($child->id
=== $this->_member
) {