3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Contribution class for galette
10 * Copyright © 2010-2014 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2010-2014 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2010-03-11
37 namespace Galette\Entity
;
41 use Laminas\Db\Sql\Expression
;
43 use Galette\Core\Login
;
44 use Galette\IO\ExternalScript
;
45 use Galette\IO\PdfContribution
;
46 use Galette\Repository\PaymentTypes
;
49 * Contribution class for galette
54 * @author Johan Cwiklinski <johan@x-tnd.be>
55 * @copyright 2010-2014 The Galette Team
56 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
57 * @link http://galette.tuxfamily.org
58 * @since Available since 0.7dev - 2010-03-11
64 public const TABLE
= 'cotisations';
65 public const PK
= 'id_cotis';
72 private $_payment_type;
73 private $_orig_amount;
77 private $_transaction = null;
81 //fields list and their translation
89 private $sendmail = false;
94 * @param Db $zdb Database
95 * @param Login $login Login instance
96 * @param null|int|ResultSet $args Either a ResultSet row to load
97 * a specific contribution, or an type id
98 * to just instanciate object
100 public function __construct(Db
$zdb, Login
$login, $args = null)
103 $this->login
= $login;
106 * Fields configuration. Each field is an array and must reflect:
112 * I'd prefer a static private variable for this...
113 * But call to the _T function does not seem to be allowed there :/
115 $this->_fields
= array(
117 'label' => null, //not a field in the form
120 Adherent
::PK
=> array(
121 'label' => _T("Contributor:"),
122 'propname' => 'member'
124 ContributionsTypes
::PK
=> array(
125 'label' => _T("Contribution type:"),
128 'montant_cotis' => array(
129 'label' => _T("Amount:"),
130 'propname' => 'amount'
132 'type_paiement_cotis' => array(
133 'label' => _T("Payment type:"),
134 'propname' => 'payment_type'
136 'info_cotis' => array(
137 'label' => _T("Comments:"),
140 'date_enreg' => array(
141 'label' => null, //not a field in the form
144 'date_debut_cotis' => array(
145 'label' => _T("Date of contribution:"),
146 'cotlabel' => _T("Start date of membership:"), //if contribution is a cotisation, label differs
147 'propname' => 'begin_date'
149 'date_fin_cotis' => array(
150 'label' => _T("End date of membership:"),
151 'propname' => 'end_date'
153 Transaction
::PK
=> array(
154 'label' => null, //not a field in the form
155 'propname' => 'transaction'
157 //this one is not really a field, but is required in some cases...
158 //adding it here make simplier to check required fields
159 'duree_mois_cotis' => array(
160 'label' => _T("Membership extension:"),
161 'propname' => 'extension'
166 } elseif (is_array($args)) {
167 $this->_date
= date("Y-m-d");
168 if (isset($args['adh']) && $args['adh'] != '') {
169 $this->_member
= (int)$args['adh'];
171 if (isset($args['trans'])) {
172 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
173 if (!isset($this->_member
)) {
174 $this->_member
= (int)$this->_transaction
->member
;
176 $this->_amount
= $this->_transaction
->getMissingAmount();
178 $this->type
= (int)$args['type'];
179 //calculate begin date for cotisation
180 $this->_begin_date
= $this->_date
;
181 if ($this->_is_cotis
) {
182 $curend = self
::getDueDate($this->zdb
, $this->_member
);
184 $dend = new \
DateTime($curend);
185 $now = date('Y-m-d');
186 $dnow = new \
DateTime($now);
188 // Member didn't renew on time
189 $this->_begin_date
= $now;
191 $this->_begin_date
= $curend;
194 $this->retrieveEndDate();
196 if (isset($args['payment_type'])) {
197 $this->_payment_type
= $args['payment_type'];
199 } elseif (is_object($args)) {
200 $this->loadFromRS($args);
203 $this->loadDynamicFields();
207 * Sets end contribution date
211 private function retrieveEndDate()
215 $bdate = new \
DateTime($this->_begin_date
);
216 if ($preferences->pref_beg_membership
!= '') {
217 //case beginning of membership
218 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
219 $edate = new \
DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
220 while ($edate <= $bdate) {
221 $edate->modify('+1 year');
224 if ($preferences->pref_membership_offermonths
> 0) {
225 //count days until end of membership date
226 $diff1 = (int)$bdate->diff($edate)->format('%a');
228 //count days beetween end of membership date and offered months
229 $tdate = clone $edate;
230 $tdate->modify('-' . $preferences->pref_membership_offermonths
. ' month');
231 $diff2 = (int)$edate->diff($tdate)->format('%a');
233 //when number of days until end of membership is less than for offered months, it's free :)
234 if ($diff1 <= $diff2) {
235 $edate->modify('+1 year');
239 $this->_end_date
= $edate->format('Y-m-d');
240 } elseif ($preferences->pref_membership_ext
!= '') {
241 //case membership extension
242 if ($this->_extension
== null) {
243 $this->_extension
= $preferences->pref_membership_ext
;
245 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
246 $edate = $bdate->add($dext);
247 $this->_end_date
= $edate->format('Y-m-d');
249 throw new \
RuntimeException(
250 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
256 * Loads a contribution from its id
258 * @param int $id the identifiant for the contribution to load
260 * @return bool true if query succeed, false otherwise
262 public function load($id)
265 $select = $this->zdb
->select(self
::TABLE
);
266 $select->where(self
::PK
. ' = ' . $id);
267 //restrict query on current member id if he's not admin nor staff member
268 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
269 $select->where(Adherent
::PK
. ' = ' . $this->login
->id
);
272 $results = $this->zdb
->execute($select);
273 if ($results->count() > 0) {
274 $row = $results->current();
275 $this->loadFromRS($row);
278 throw new \
Exception(
279 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')'
282 } catch (Throwable
$e) {
284 'An error occurred attempting to load contribution #' . $id .
293 * Populate object from a resultset row
295 * @param ResultSet $r the resultset row
299 private function loadFromRS($r)
302 $this->_id
= (int)$r->$pk;
303 $this->_date
= $r->date_enreg
;
304 $this->_amount
= $r->montant_cotis
;
305 //save original amount, we need it for transactions parts calulations
306 $this->_orig_amount
= $r->montant_cotis
;
307 $this->_payment_type
= $r->type_paiement_cotis
;
308 $this->_info
= $r->info_cotis
;
309 $this->_begin_date
= $r->date_debut_cotis
;
310 $enddate = $r->date_fin_cotis
;
311 //do not work with knows bad dates...
312 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
313 //strange date? dont know :(
315 $enddate !== '0000-00-00'
316 && $enddate !== '1901-01-01'
317 && $enddate !== '0001-01-01 BC'
319 $this->_end_date
= $r->date_fin_cotis
;
321 $adhpk = Adherent
::PK
;
322 $this->_member
= (int)$r->$adhpk;
324 $transpk = Transaction
::PK
;
325 if ($r->$transpk != '') {
326 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
329 $this->type
= (int)$r->id_type_cotis
;
330 $this->loadDynamicFields();
334 * Check posted values validity
336 * @param array $values All values to check, basically the $_POST array
337 * after sending the form
338 * @param array $required Array of required fields
339 * @param array $disabled Array of disabled fields
343 public function check($values, $required, $disabled)
346 $this->errors
= array();
348 $fields = array_keys($this->_fields
);
349 foreach ($fields as $key) {
350 //first of all, let's sanitize values
351 $key = strtolower($key);
352 $prop = '_' . $this->_fields
[$key]['propname'];
354 if (isset($values[$key])) {
355 $value = trim($values[$key]);
360 // if the field is enabled, check it
361 if (!isset($disabled[$key])) {
362 // fill up the adherent structure
363 //$this->$prop = stripslashes($value); //not relevant here!
365 // now, check validity
369 case 'date_debut_cotis':
370 case 'date_fin_cotis':
373 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
375 throw new \
Exception('Incorrect format');
377 $this->$prop = $d->format('Y-m-d');
378 } catch (Throwable
$e) {
380 'Wrong date format. field: ' . $key .
381 ', value: ' . $value . ', expected fmt: ' .
382 __("Y-m-d") . ' | ' . $e->getMessage(),
385 $this->errors
[] = str_replace(
392 $this->_fields
[$key]['label']
394 _T("- Wrong date format (%date_format) for %field!")
401 $this->_member
= (int)$value;
404 case ContributionsTypes
::PK
:
406 $this->type
= (int)$value;
409 case 'montant_cotis':
410 $this->_amount
= $value;
411 $value = strtr($value, ',', '.');
412 if (!is_numeric($value) && $value !== '') {
413 $this->errors
[] = _T("- The amount must be an integer!");
416 case 'type_paiement_cotis':
417 $ptypes = new PaymentTypes(
422 $ptlist = $ptypes->getList();
423 if (isset($ptlist[$value])) {
424 $this->_payment_type
= $value;
426 $this->errors
[] = _T("- Unknown payment type");
430 $this->_info
= $value;
432 case Transaction
::PK
:
434 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
437 case 'duree_mois_cotis':
439 if (!is_numeric($value) ||
$value <= 0) {
440 $this->errors
[] = _T("- The duration must be a positive integer!");
442 $this->$prop = $value;
443 $this->retrieveEndDate();
450 // missing required fields?
451 foreach ($required as $key => $val) {
453 $prop = '_' . $this->_fields
[$key]['propname'];
455 !isset($disabled[$key])
456 && (!isset($this->$prop)
457 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
458 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
460 $this->errors
[] = str_replace(
462 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
463 _T("- Mandatory field %field empty.")
469 if ($this->_transaction
!= null && $this->_amount
!= null) {
470 $missing = $this->_transaction
->getMissingAmount();
471 //calculate new missing amount
472 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
474 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
478 if ($this->isCotis() && count($this->errors
) == 0) {
479 $overlap = $this->checkOverlap();
480 if ($overlap !== true) {
481 if ($overlap === false) {
482 $this->errors
[] = _T("An error occurred checking overlaping fees :(");
484 //method directly return error message
485 $this->errors
[] = $overlap;
490 $this->dynamicsCheck($values, $required, $disabled);
492 if (count($this->errors
) > 0) {
494 'Some errors has been throwed attempting to edit/store a contribution' .
495 print_r($this->errors
, true),
498 return $this->errors
;
501 'Contribution checked successfully.',
509 * Check that membership fees does not overlap
511 * @return boolean|string True if all is ok, false if error,
512 * error message if overlap
514 public function checkOverlap()
517 $select = $this->zdb
->select(self
::TABLE
, 'c');
519 array('date_debut_cotis', 'date_fin_cotis')
521 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
522 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
524 )->where(Adherent
::PK
. ' = ' . $this->_member
)
525 ->where(array('cotis_extension' => new Expression('true')))
527 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
528 ->lessThan('date_debut_cotis', $this->_end_date
)
531 ->greaterThan('date_fin_cotis', $this->_begin_date
)
532 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
534 if ($this->id
!= '') {
535 $select->where(self
::PK
. ' != ' . $this->id
);
538 $results = $this->zdb
->execute($select);
539 if ($results->count() > 0) {
540 $result = $results->current();
541 $d = new \
DateTime($result->date_debut_cotis
);
543 return _T("- Membership period overlaps period starting at ") .
544 $d->format(__("Y-m-d"));
547 } catch (Throwable
$e) {
549 'An error occurred checking overlaping fee. ' . $e->getMessage(),
557 * Store the contribution
561 public function store()
563 global $hist, $emitter;
567 if (count($this->errors
) > 0) {
568 throw new \
RuntimeException(
569 'Existing errors prevents storing contribution: ' .
570 print_r($this->errors
, true)
575 $this->zdb
->connection
->beginTransaction();
577 $fields = self
::getDbFields($this->zdb
);
578 foreach ($fields as $field) {
579 $prop = '_' . $this->_fields
[$field]['propname'];
581 case ContributionsTypes
::PK
:
582 case Transaction
::PK
:
583 if (isset($this->$prop)) {
584 $values[$field] = $this->$prop->id
;
588 $values[$field] = $this->$prop;
593 //no end date, let's take database defaults
594 if (!$this->isCotis() && !$this->_end_date
) {
595 unset($values['date_fin_cotis']);
599 if (!isset($this->_id
) ||
$this->_id
== '') {
600 //we're inserting a new contribution
601 unset($values[self
::PK
]);
603 $insert = $this->zdb
->insert(self
::TABLE
);
604 $insert->values($values);
605 $add = $this->zdb
->execute($insert);
607 if ($add->count() > 0) {
608 if ($this->zdb
->isPostgres()) {
609 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
610 PREFIX_DB
. 'cotisations_id_seq'
613 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
618 _T("Contribution added"),
619 Adherent
::getSName($this->zdb
, $this->_member
)
622 $event = 'contribution.add';
624 $hist->add(_T("Fail to add new contribution."));
625 throw new \
Exception(
626 'An error occurred inserting new contribution!'
630 //we're editing an existing contribution
631 $update = $this->zdb
->update(self
::TABLE
);
632 $update->set($values)->where(
633 self
::PK
. '=' . $this->_id
635 $edit = $this->zdb
->execute($update);
637 //edit == 0 does not mean there were an error, but that there
638 //were nothing to change
639 if ($edit->count() > 0) {
641 _T("Contribution updated"),
642 Adherent
::getSName($this->zdb
, $this->_member
)
646 if ($edit === false) {
647 throw new \
Exception(
648 'An error occurred updating contribution # ' . $this->_id
. '!'
652 $event = 'contribution.edit';
655 if ($this->isCotis()) {
656 $deadline = $this->updateDeadline();
657 if ($deadline !== true) {
658 //if something went wrong, we rollback transaction
659 throw new \
Exception('An error occurred updating member\'s deadline');
665 $success = $this->dynamicsStore(true);
668 $this->zdb
->connection
->commit();
669 $this->_orig_amount
= $this->_amount
;
671 //send event at the end of process, once all has been stored
672 if ($event !== null) {
673 $emitter->emit($event, $this);
677 } catch (Throwable
$e) {
678 $this->zdb
->connection
->rollBack();
680 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
681 $e->getTraceAsString(),
689 * Update member dead line
693 private function updateDeadline()
696 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
698 if ($due_date != '') {
699 $date_fin_update = $due_date;
701 $date_fin_update = new Expression('NULL');
704 $update = $this->zdb
->update(Adherent
::TABLE
);
706 array('date_echeance' => $date_fin_update)
708 Adherent
::PK
. '=' . $this->_member
710 $this->zdb
->execute($update);
712 } catch (Throwable
$e) {
714 'An error occurred updating member ' . $this->_member
.
724 * Remove contribution from database
726 * @param boolean $transaction Activate transaction mode (defaults to true)
730 public function remove($transaction = true)
736 $this->zdb
->connection
->beginTransaction();
739 $delete = $this->zdb
->delete(self
::TABLE
);
740 $delete->where(self
::PK
. ' = ' . $this->_id
);
741 $del = $this->zdb
->execute($delete);
742 if ($del->count() > 0) {
743 $this->updateDeadline();
744 $this->dynamicsRemove(true);
746 throw new \
RuntimeException(
747 'Contribution has not been removed!'
751 $this->zdb
->connection
->commit();
753 $emitter->emit('contribution.remove', $this);
755 } catch (Throwable
$e) {
757 $this->zdb
->connection
->rollBack();
760 'An error occurred trying to remove contribution #' .
761 $this->_id
. ' | ' . $e->getMessage(),
771 * @param string $field Field name
775 public function getFieldLabel($field)
777 $label = $this->_fields
[$field]['label'];
778 if ($this->isCotis() && $field == 'date_debut_cotis') {
779 $label = $this->_fields
[$field]['cotlabel'];
782 $label = str_replace(' ', ' ', $label);
783 //remove trailing ':' and then trim
784 $label = trim(trim($label, ':'));
789 * Retrieve fields from database
791 * @param Db $zdb Database instance
795 public static function getDbFields(Db
$zdb)
797 $columns = $zdb->getColumns(self
::TABLE
);
799 foreach ($columns as $col) {
800 $fields[] = $col->getName();
806 * Get the relevant CSS class for current contribution
808 * @return string current contribution row class
810 public function getRowClass()
812 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
813 'cotis-normal' : 'cotis-give';
817 * Retrieve member due date
819 * @param Db $zdb Database instance
820 * @param integer $member_id Member identifier
824 public static function getDueDate(Db
$zdb, $member_id)
830 $select = $zdb->select(self
::TABLE
, 'c');
833 'max_date' => new Expression('MAX(date_fin_cotis)')
836 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
837 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
840 Adherent
::PK
. ' = ' . $member_id
842 array('cotis_extension' => new Expression('true'))
845 $results = $zdb->execute($select);
846 $result = $results->current();
847 $due_date = $result->max_date
;
849 //avoid bad dates in postgres and bad mysql return from zenddb
850 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
854 } catch (Throwable
$e) {
856 'An error occurred trying to retrieve member\'s due date',
864 * Detach a contribution from a transaction
866 * @param Db $zdb Database instance
867 * @param Login $login Login instance
868 * @param int $trans_id Transaction identifier
869 * @param int $contrib_id Contribution identifier
873 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
876 //first, we check if contribution is part of transaction
877 $c = new Contribution($zdb, $login, (int)$contrib_id);
878 if ($c->isTransactionPartOf($trans_id)) {
879 $update = $zdb->update(self
::TABLE
);
881 array(Transaction
::PK
=> null)
883 self
::PK
. ' = ' . $contrib_id
885 $zdb->execute($update);
889 'Contribution #' . $contrib_id .
890 ' is not actually part of transaction #' . $trans_id,
895 } catch (Throwable
$e) {
897 'Unable to detach contribution #' . $contrib_id .
898 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
906 * Set a contribution as a transaction part
908 * @param Db $zdb Database instance
909 * @param int $trans_id Transaction identifier
910 * @param int $contrib_id Contribution identifier
914 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
917 $update = $zdb->update(self
::TABLE
);
919 array(Transaction
::PK
=> $trans_id)
920 )->where(self
::PK
. ' = ' . $contrib_id);
922 $zdb->execute($update);
924 } catch (Throwable
$e) {
926 'Unable to attach contribution #' . $contrib_id .
927 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
935 * Is current contribution a cotisation
939 public function isCotis()
941 return $this->_is_cotis
;
945 * Is current contribution part of specified transaction
947 * @param int $id Transaction identifier
951 public function isTransactionPartOf($id)
953 if ($this->isTransactionPart()) {
954 return $id == $this->_transaction
->id
;
961 * Is current contribution part of transaction
965 public function isTransactionPart()
967 return $this->_transaction
!= null;
971 * Execute post contribution script
973 * @param ExternalScript $es External script to execute
974 * @param array $extra Extra information on contribution
976 * @param array $pextra Extra information on payment
979 * @return mixed Script return value on success, values and script output on fail
981 public function executePostScript(
989 'type' => $this->getPaymentType()
992 if ($pextra !== null && is_array($pextra)) {
993 $payment = array_merge($payment, $pextra);
996 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
997 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
1000 $voucher_path = null;
1001 if ($this->_id
!== null) {
1002 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1003 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1004 $voucher_path = $voucher->getPath();
1008 'id' => (int)$this->_id
,
1009 'date' => $this->_date
,
1010 'type' => $this->getRawType(),
1011 'amount' => $this->amount
,
1012 'voucher' => $voucher_path,
1013 'category' => array(
1014 'id' => $this->type
->id
,
1015 'label' => $this->type
->libelle
1017 'payment' => $payment
1020 if ($this->_member
!== null) {
1021 $m = new Adherent($this->zdb
, (int)$this->_member
);
1023 'id' => (int)$this->_member
,
1024 'name' => $m->sfullname
,
1025 'email' => $m->email
,
1026 'organization' => ($m->isCompany() ?
1 : 0),
1029 'label' => $m->sstatus
1031 'country' => $m->country
1034 if ($m->isCompany()) {
1035 $member['organization_name'] = $m->company_name
;
1038 $contrib['member'] = $member;
1041 if ($extra !== null && is_array($extra)) {
1042 $contrib = array_merge($contrib, $extra);
1045 $res = $es->send($contrib);
1047 if ($res !== true) {
1049 'An error occurred calling post contribution ' .
1050 "script:\n" . $es->getOutput(),
1053 $res = _T("Contribution information") . "\n";
1054 $res .= print_r($contrib, true);
1055 $res .= "\n\n" . _T("Script output") . "\n";
1056 $res .= $es->getOutput();
1062 * Get raw contribution type
1066 public function getRawType()
1068 if ($this->isCotis()) {
1069 return 'membership';
1076 * Get contribution type label
1080 public function getTypeLabel()
1082 if ($this->isCotis()) {
1083 return _T("Membership");
1085 return _T("Donation");
1090 * Get payment type label
1094 public function getPaymentType()
1096 if ($this->_payment_type
=== null) {
1100 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1101 return $ptype->getName(false);
1105 * Global getter method
1107 * @param string $name name of the property we want to retrive
1109 * @return false|object the called property
1111 public function __get($name)
1114 $forbidden = array('is_cotis');
1115 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1116 'raw_begin_date', 'raw_end_date'
1119 $rname = '_' . $name;
1121 if (in_array($name, $forbidden)) {
1123 "Call to __get for '$name' is forbidden!",
1129 return $this->isCotis();
1132 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1135 property_exists($this, $rname)
1136 ||
in_array($name, $virtuals)
1140 case 'raw_begin_date':
1141 case 'raw_end_date':
1142 $rname = '_' . substr($name, 4);
1143 if ($this->$rname != '') {
1145 $d = new \
DateTime($this->$rname);
1147 } catch (Throwable
$e) {
1148 //oops, we've got a bad date :/
1150 'Bad date (' . $this->$rname . ') | ' .
1161 if ($this->$rname != '') {
1163 $d = new \
DateTime($this->$rname);
1164 return $d->format(__("Y-m-d"));
1165 } catch (Throwable
$e) {
1166 //oops, we've got a bad date :/
1168 'Bad date (' . $this->$rname . ') | ' .
1172 return $this->$rname;
1177 if ($this->_is_cotis
) {
1178 $date_end = new \
DateTime($this->_end_date
);
1179 $date_start = new \
DateTime($this->_begin_date
);
1180 $diff = $date_end->diff($date_start);
1181 return $diff->format('%y') * 12 +
$diff->format('%m');
1186 case 'spayment_type':
1187 if ($this->_payment_type
=== null) {
1191 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1192 return $ptype->getName();
1196 if ($this->_is_cotis
=== null) {
1199 return ($this->isCotis()) ?
1200 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1203 return $this->$rname;
1208 "Unknown property '$rname'",
1216 * Global setter method
1218 * @param string $name name of the property we want to assign a value to
1219 * @param object $value a relevant value for the property
1223 public function __set($name, $value)
1225 global $preferences;
1227 $forbidden = array('fields', 'is_cotis', 'end_date');
1229 if (!in_array($name, $forbidden)) {
1230 $rname = '_' . $name;
1233 if (is_int($value)) {
1234 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1237 'Trying to set a transaction from an id that is not an integer.',
1243 if (is_int($value)) {
1245 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1246 //set is_cotis according to type
1247 if ($this->$rname->extension
== 1) {
1248 $this->_is_cotis
= true;
1250 $this->_is_cotis
= false;
1254 'Trying to set a type from an id that is not an integer.',
1261 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1263 throw new \
Exception('Incorrect format');
1265 $this->_begin_date
= $d->format('Y-m-d');
1266 } catch (Throwable
$e) {
1268 'Wrong date format. field: ' . $name .
1269 ', value: ' . $value . ', expected fmt: ' .
1270 __("Y-m-d") . ' | ' . $e->getMessage(),
1273 $this->errors
[] = str_replace(
1280 $this->_fields
['date_debut_cotis']['label']
1282 _T("- Wrong date format (%date_format) for %field!")
1287 if (is_numeric($value) && $value > 0) {
1288 $this->$rname = $value;
1291 'Trying to set an amount with a non numeric value, ' .
1292 'or with a zero value',
1298 if (is_int($value)) {
1300 $this->$rname = $value;
1303 case 'payment_type':
1304 $ptypes = new PaymentTypes(
1309 $list = $ptypes->getList();
1310 if (isset($list[$value])) {
1311 $this->_payment_type
= $value;
1314 'Unknown payment type ' . $value,
1321 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1331 * Flag creation mail sending
1333 * @param boolean $send True (default) to send creation email
1335 * @return Contribution
1337 public function setSendmail($send = true)
1339 $this->sendmail
= $send;
1344 * Should we send administrative emails to member?
1348 public function sendEMail()
1350 return $this->sendmail
;