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' => _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 $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 between 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)
294 if (!$this->login
->isLogged()) {
296 'Non-logged-in users cannot load contribution id `' . $id,
303 $select = $this->zdb
->select(self
::TABLE
, 'c');
305 array('a' => PREFIX_DB
. Adherent
::TABLE
),
306 'c.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
309 //restrict query on current member id if he's not admin nor staff member
310 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
313 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
315 ->equalTo('a.parent_id', $this->login
->id
)
318 ->equalTo('c.' . self
::PK
, $id)
321 $select->where
->equalTo(self
::PK
, $id);
324 $results = $this->zdb
->execute($select);
325 if ($results->count() > 0) {
326 $row = $results->current();
327 $this->loadFromRS($row);
331 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')',
336 } catch (Throwable
$e) {
338 'An error occurred attempting to load contribution #' . $id .
347 * Populate object from a resultset row
349 * @param ResultSet $r the resultset row
353 private function loadFromRS($r)
356 $this->_id
= (int)$r->$pk;
357 $this->_date
= $r->date_enreg
;
358 $this->_amount
= (int)$r->montant_cotis
;
359 //save original amount, we need it for transactions parts calculations
360 $this->_orig_amount
= (int)$r->montant_cotis
;
361 $this->_payment_type
= $r->type_paiement_cotis
;
362 $this->_info
= $r->info_cotis
;
363 $this->_begin_date
= $r->date_debut_cotis
;
364 $enddate = $r->date_fin_cotis
;
365 //do not work with knows bad dates...
366 //the one with BC comes from 0.63/pgsql demo... Why the hell a so
367 //strange date? don't know :(
369 $enddate !== '0000-00-00'
370 && $enddate !== '1901-01-01'
371 && $enddate !== '0001-01-01 BC'
373 $this->_end_date
= $r->date_fin_cotis
;
375 $adhpk = Adherent
::PK
;
376 $this->_member
= (int)$r->$adhpk;
378 $transpk = Transaction
::PK
;
379 if ($r->$transpk != '') {
380 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
383 $this->type
= (int)$r->id_type_cotis
;
384 $this->loadDynamicFields();
388 * Check posted values validity
390 * @param array $values All values to check, basically the $_POST array
391 * after sending the form
392 * @param array $required Array of required fields
393 * @param array $disabled Array of disabled fields
397 public function check($values, $required, $disabled)
400 $this->errors
= array();
402 $fields = array_keys($this->_fields
);
403 foreach ($fields as $key) {
404 //first, let's sanitize values
405 $key = strtolower($key);
406 $prop = '_' . $this->_fields
[$key]['propname'];
408 if (isset($values[$key])) {
409 $value = trim($values[$key]);
414 // if the field is enabled, check it
415 if (!isset($disabled[$key])) {
416 // fill up the adherent structure
417 //$this->$prop = stripslashes($value); //not relevant here!
419 // now, check validity
423 case 'date_debut_cotis':
424 case 'date_fin_cotis':
427 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
429 throw new \
Exception('Incorrect format');
431 $this->$prop = $d->format('Y-m-d');
432 } catch (Throwable
$e) {
434 'Wrong date format. field: ' . $key .
435 ', value: ' . $value . ', expected fmt: ' .
436 __("Y-m-d") . ' | ' . $e->getMessage(),
439 $this->errors
[] = str_replace(
446 $this->_fields
[$key]['label']
448 _T("- Wrong date format (%date_format) for %field!")
455 $this->_member
= (int)$value;
458 case ContributionsTypes
::PK
:
460 $this->type
= (int)$value;
463 case 'montant_cotis':
464 if (!empty($value)) {
465 $this->_amount
= $value;
467 $value = strtr($value, ',', '.');
468 if (!is_numeric($value) && $value !== '') {
469 $this->errors
[] = _T("- The amount must be an integer!");
472 case 'type_paiement_cotis':
473 $ptypes = new PaymentTypes(
478 $ptlist = $ptypes->getList();
479 if (isset($ptlist[$value])) {
480 $this->_payment_type
= $value;
482 $this->errors
[] = _T("- Unknown payment type");
486 $this->_info
= $value;
488 case Transaction
::PK
:
490 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
493 case 'duree_mois_cotis':
495 if (!is_numeric($value) ||
$value <= 0) {
496 $this->errors
[] = _T("- The duration must be a positive integer!");
498 $this->$prop = $value;
499 $this->retrieveEndDate();
506 // missing required fields?
507 foreach ($required as $key => $val) {
509 $prop = '_' . $this->_fields
[$key]['propname'];
511 !isset($disabled[$key])
512 && (!isset($this->$prop)
513 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
514 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
516 $this->errors
[] = str_replace(
518 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
519 _T("- Mandatory field %field empty.")
525 if ($this->_transaction
!= null && $this->_amount
!= null) {
526 $missing = $this->_transaction
->getMissingAmount();
527 //calculate new missing amount
528 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
530 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
534 if ($this->isFee() && count($this->errors
) == 0) {
535 $overlap = $this->checkOverlap();
536 if ($overlap !== true) {
537 //method directly return error message
538 $this->errors
[] = $overlap;
542 $this->dynamicsCheck($values, $required, $disabled);
544 if (count($this->errors
) > 0) {
546 'Some errors has been threw attempting to edit/store a contribution' .
547 print_r($this->errors
, true),
550 return $this->errors
;
553 'Contribution checked successfully.',
561 * Check that membership fees does not overlap
563 * @return boolean|string True if all is ok, false if error,
564 * error message if overlap
566 public function checkOverlap()
569 $select = $this->zdb
->select(self
::TABLE
, 'c');
571 array('date_debut_cotis', 'date_fin_cotis')
573 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
574 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
576 )->where([Adherent
::PK
=> $this->_member
])
577 ->where(array('cotis_extension' => new Expression('true')))
579 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
580 ->lessThan('date_debut_cotis', $this->_end_date
)
583 ->greaterThan('date_fin_cotis', $this->_begin_date
)
584 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
586 if ($this->id
!= '') {
587 $select->where
->notEqualTo(self
::PK
, $this->id
);
590 $results = $this->zdb
->execute($select);
591 if ($results->count() > 0) {
592 $result = $results->current();
593 $d = new \
DateTime($result->date_debut_cotis
);
595 return _T("- Membership period overlaps period starting at ") .
596 $d->format(__("Y-m-d"));
599 } catch (Throwable
$e) {
601 'An error occurred checking overlapping fee. ' . $e->getMessage(),
609 * Store the contribution
613 public function store()
615 global $hist, $emitter;
619 if (count($this->errors
) > 0) {
620 throw new \
RuntimeException(
621 'Existing errors prevents storing contribution: ' .
622 print_r($this->errors
, true)
627 $this->zdb
->connection
->beginTransaction();
629 $fields = self
::getDbFields($this->zdb
);
630 foreach ($fields as $field) {
631 $prop = '_' . $this->_fields
[$field]['propname'];
633 case ContributionsTypes
::PK
:
634 case Transaction
::PK
:
635 if (isset($this->$prop)) {
636 $values[$field] = $this->$prop->id
;
640 $values[$field] = $this->$prop;
645 //no end date, let's take database defaults
646 if (!$this->isFee() && !$this->_end_date
) {
647 unset($values['date_fin_cotis']);
651 if (!isset($this->_id
) ||
$this->_id
== '') {
652 //we're inserting a new contribution
653 unset($values[self
::PK
]);
655 $insert = $this->zdb
->insert(self
::TABLE
);
656 $insert->values($values);
657 $add = $this->zdb
->execute($insert);
659 if ($add->count() > 0) {
660 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
664 _T("Contribution added"),
665 Adherent
::getSName($this->zdb
, $this->_member
)
668 $event = 'contribution.add';
670 $hist->add(_T("Fail to add new contribution."));
671 throw new \
Exception(
672 'An error occurred inserting new contribution!'
676 //we're editing an existing contribution
677 $update = $this->zdb
->update(self
::TABLE
);
678 $update->set($values)->where([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 $this->updateDeadline();
705 $success = $this->dynamicsStore(true);
708 $this->zdb
->connection
->commit();
709 $this->_orig_amount
= $this->_amount
;
711 //send event at the end of process, once all has been stored
712 if ($event !== null) {
713 $emitter->emit($event, $this);
717 } catch (Throwable
$e) {
718 if ($this->zdb
->connection
->inTransaction()) {
719 $this->zdb
->connection
->rollBack();
726 * Update member dead line
730 private function updateDeadline()
733 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
735 if ($due_date != '') {
736 $date_fin_update = $due_date;
738 $date_fin_update = new Expression('NULL');
741 $update = $this->zdb
->update(Adherent
::TABLE
);
743 array('date_echeance' => $date_fin_update)
745 [Adherent
::PK
=> $this->_member
]
747 $this->zdb
->execute($update);
749 } catch (Throwable
$e) {
751 'An error occurred updating member ' . $this->_member
.
761 * Remove contribution from database
763 * @param boolean $transaction Activate transaction mode (defaults to true)
767 public function remove($transaction = true)
773 $this->zdb
->connection
->beginTransaction();
776 $delete = $this->zdb
->delete(self
::TABLE
);
777 $delete->where([self
::PK
=> $this->_id
]);
778 $del = $this->zdb
->execute($delete);
779 if ($del->count() > 0) {
780 $this->updateDeadline();
781 $this->dynamicsRemove(true);
784 'Contribution has not been removed!',
790 $this->zdb
->connection
->commit();
792 $emitter->emit('contribution.remove', $this);
794 } catch (Throwable
$e) {
796 $this->zdb
->connection
->rollBack();
799 'An error occurred trying to remove contribution #' .
800 $this->_id
. ' | ' . $e->getMessage(),
810 * @param string $field Field name
814 public function getFieldLabel($field)
816 $label = $this->_fields
[$field]['label'];
817 if ($this->isFee() && $field == 'date_debut_cotis') {
818 $label = $this->_fields
[$field]['cotlabel'];
821 $label = str_replace(' ', ' ', $label);
822 //remove trailing ':' and then trim
823 $label = trim(trim($label, ':'));
828 * Retrieve fields from database
830 * @param Db $zdb Database instance
834 public static function getDbFields(Db
$zdb)
836 $columns = $zdb->getColumns(self
::TABLE
);
838 foreach ($columns as $col) {
839 $fields[] = $col->getName();
845 * Get the relevant CSS class for current contribution
847 * @return string current contribution row class
849 public function getRowClass()
851 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
852 'cotis-normal' : 'cotis-give';
856 * Retrieve member due date
858 * @param Db $zdb Database instance
859 * @param integer $member_id Member identifier
863 public static function getDueDate(Db
$zdb, $member_id)
869 $select = $zdb->select(self
::TABLE
, 'c');
872 'max_date' => new Expression('MAX(date_fin_cotis)')
875 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
876 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
879 [Adherent
::PK
=> $member_id]
881 array('cotis_extension' => new Expression('true'))
884 $results = $zdb->execute($select);
885 $result = $results->current();
886 $due_date = $result->max_date
;
888 //avoid bad dates in postgres and bad mysql return from zenddb
889 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
893 } catch (Throwable
$e) {
895 'An error occurred trying to retrieve member\'s due date',
903 * Detach a contribution from a transaction
905 * @param Db $zdb Database instance
906 * @param Login $login Login instance
907 * @param int $trans_id Transaction identifier
908 * @param int $contrib_id Contribution identifier
912 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
915 //first, we check if contribution is part of transaction
916 $c = new Contribution($zdb, $login, (int)$contrib_id);
917 if ($c->isTransactionPartOf($trans_id)) {
918 $update = $zdb->update(self
::TABLE
);
920 array(Transaction
::PK
=> null)
922 [self
::PK
=> $contrib_id]
924 $zdb->execute($update);
928 'Contribution #' . $contrib_id .
929 ' is not actually part of transaction #' . $trans_id,
934 } catch (Throwable
$e) {
936 'Unable to detach contribution #' . $contrib_id .
937 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
945 * Set a contribution as a transaction part
947 * @param Db $zdb Database instance
948 * @param int $trans_id Transaction identifier
949 * @param int $contrib_id Contribution identifier
953 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
956 $update = $zdb->update(self
::TABLE
);
958 array(Transaction
::PK
=> $trans_id)
959 )->where([self
::PK
=> $contrib_id]);
961 $zdb->execute($update);
963 } catch (Throwable
$e) {
965 'Unable to attach contribution #' . $contrib_id .
966 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
974 * Is current contribution a membership fee
978 public function isFee()
980 return $this->_is_cotis
;
984 * Is current contribution part of specified transaction
986 * @param int $id Transaction identifier
990 public function isTransactionPartOf($id)
992 if ($this->isTransactionPart()) {
993 return $id == $this->_transaction
->id
;
1000 * Is current contribution part of transaction
1004 public function isTransactionPart()
1006 return $this->_transaction
!= null;
1010 * Execute post contribution script
1012 * @param ExternalScript $es External script to execute
1013 * @param array $extra Extra information on contribution
1015 * @param array $pextra Extra information on payment
1018 * @return mixed Script return value on success, values and script output on fail
1020 public function executePostScript(
1025 global $preferences;
1028 'type' => $this->getPaymentType()
1031 if ($pextra !== null && is_array($pextra)) {
1032 $payment = array_merge($payment, $pextra);
1035 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
1036 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1039 $voucher_path = null;
1040 if ($this->_id
!== null) {
1041 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1042 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1043 $voucher_path = $voucher->getPath();
1047 'id' => (int)$this->_id
,
1048 'date' => $this->_date
,
1049 'type' => $this->getRawType(),
1050 'amount' => $this->amount
,
1051 'voucher' => $voucher_path,
1052 'category' => array(
1053 'id' => $this->type
->id
,
1054 'label' => $this->type
->libelle
1056 'payment' => $payment
1059 if ($this->_member
!== null) {
1060 $m = new Adherent($this->zdb
, (int)$this->_member
);
1062 'id' => (int)$this->_member
,
1063 'name' => $m->sfullname
,
1064 'email' => $m->email
,
1065 'organization' => ($m->isCompany() ?
1 : 0),
1068 'label' => $m->sstatus
1070 'country' => $m->country
1073 if ($m->isCompany()) {
1074 $member['organization_name'] = $m->company_name
;
1077 $contrib['member'] = $member;
1080 if ($extra !== null && is_array($extra)) {
1081 $contrib = array_merge($contrib, $extra);
1084 $res = $es->send($contrib);
1086 if ($res !== true) {
1088 'An error occurred calling post contribution ' .
1089 "script:\n" . $es->getOutput(),
1092 $res = _T("Contribution information") . "\n";
1093 $res .= print_r($contrib, true);
1094 $res .= "\n\n" . _T("Script output") . "\n";
1095 $res .= $es->getOutput();
1101 * Get raw contribution type
1105 public function getRawType()
1107 if ($this->isFee()) {
1108 return 'membership';
1115 * Get contribution type label
1119 public function getTypeLabel()
1121 if ($this->isFee()) {
1122 return _T("Membership");
1124 return _T("Donation");
1129 * Get payment type label
1133 public function getPaymentType()
1135 if ($this->_payment_type
=== null) {
1139 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1140 return $ptype->getName(false);
1144 * Global getter method
1146 * @param string $name name of the property we want to retrieve
1148 * @return false|object the called property
1150 public function __get($name)
1153 $forbidden = array('is_cotis');
1154 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1155 'raw_begin_date', 'raw_end_date'
1158 $rname = '_' . $name;
1160 if (in_array($name, $forbidden)) {
1162 "Call to __get for '$name' is forbidden!",
1168 return $this->isFee();
1171 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1174 property_exists($this, $rname)
1175 ||
in_array($name, $virtuals)
1179 case 'raw_begin_date':
1180 case 'raw_end_date':
1181 $rname = '_' . substr($name, 4);
1182 if ($this->$rname != '') {
1184 $d = new \
DateTime($this->$rname);
1186 } catch (Throwable
$e) {
1187 //oops, we've got a bad date :/
1189 'Bad date (' . $this->$rname . ') | ' .
1200 if ($this->$rname != '') {
1202 $d = new \
DateTime($this->$rname);
1203 return $d->format(__("Y-m-d"));
1204 } catch (Throwable
$e) {
1205 //oops, we've got a bad date :/
1207 'Bad date (' . $this->$rname . ') | ' .
1211 return $this->$rname;
1216 if ($this->_is_cotis
) {
1217 $date_end = new \
DateTime($this->_end_date
);
1218 $date_start = new \
DateTime($this->_begin_date
);
1219 $diff = $date_end->diff($date_start);
1220 return $diff->format('%y') * 12 +
$diff->format('%m');
1225 case 'spayment_type':
1226 return $this->getPaymentType();
1229 if ($this->_is_cotis
=== null) {
1232 return ($this->isFee()) ?
1233 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1236 return $this->$rname;
1241 "Unknown property '$rname'",
1249 * Global setter method
1251 * @param string $name name of the property we want to assign a value to
1252 * @param object $value a relevant value for the property
1256 public function __set($name, $value)
1258 global $preferences;
1260 $forbidden = array('fields', 'is_cotis', 'end_date');
1262 if (!in_array($name, $forbidden)) {
1263 $rname = '_' . $name;
1266 if (is_int($value)) {
1267 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1270 'Trying to set a transaction from an id that is not an integer.',
1276 if (is_int($value)) {
1278 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1279 //set is_cotis according to type
1280 if ($this->$rname->extension
== 1) {
1281 $this->_is_cotis
= true;
1283 $this->_is_cotis
= false;
1287 'Trying to set a type from an id that is not an integer.',
1294 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1296 throw new \
Exception('Incorrect format');
1298 $this->_begin_date
= $d->format('Y-m-d');
1299 } catch (Throwable
$e) {
1301 'Wrong date format. field: ' . $name .
1302 ', value: ' . $value . ', expected fmt: ' .
1303 __("Y-m-d") . ' | ' . $e->getMessage(),
1306 $this->errors
[] = str_replace(
1313 $this->_fields
['date_debut_cotis']['label']
1315 _T("- Wrong date format (%date_format) for %field!")
1320 if (is_numeric($value) && $value > 0) {
1321 $this->$rname = $value;
1324 'Trying to set an amount with a non numeric value, ' .
1325 'or with a zero value',
1331 if (is_int($value)) {
1333 $this->$rname = $value;
1336 case 'payment_type':
1337 $ptypes = new PaymentTypes(
1342 $list = $ptypes->getList();
1343 if (isset($list[$value])) {
1344 $this->_payment_type
= $value;
1347 'Unknown payment type ' . $value,
1354 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1364 * Flag creation mail sending
1366 * @param boolean $send True (default) to send creation email
1368 * @return Contribution
1370 public function setSendmail($send = true)
1372 $this->sendmail
= $send;
1377 * Should we send administrative emails to member?
1381 public function sendEMail()
1383 return $this->sendmail
;
1387 * Handle files (dynamics files)
1389 * @param array $files Files sent
1391 * @return array|true
1393 public function handleFiles($files)
1397 $this->dynamicsFiles($files);
1399 if (count($this->errors
) > 0) {
1401 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1402 print_r($this->errors
, true),
1405 return $this->errors
;
1412 * Get required fields list
1416 public function getRequired(): array
1419 'id_type_cotis' => 1,
1422 'date_debut_cotis' => 1,
1423 'date_fin_cotis' => $this->isFee() ?
1 : 0,
1424 'montant_cotis' => $this->isFee() ?
1 : 0
1429 * Can current logged-in user display contribution
1431 * @param Login $login Login instance
1435 public function canShow(Login
$login): bool
1437 //non-logged-in members cannot show contributions
1438 if (!$login->isLogged()) {
1442 //admin and staff users can edit, as well as member itself
1443 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
1447 //parent can see their children contributions
1448 $parent = new Adherent($this->zdb
);
1451 ->enableDep('children')
1452 ->load($this->login
->id
);
1453 if ($parent->hasChildren()) {
1454 foreach ($parent->children
as $child) {
1455 if ($child->id
=== $this->_member
) {