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
;
40 use Laminas\Db\Sql\Expression
;
42 use Galette\Core\Login
;
43 use Galette\IO\ExternalScript
;
44 use Galette\IO\PdfContribution
;
45 use Galette\Repository\PaymentTypes
;
48 * Contribution class for galette
53 * @author Johan Cwiklinski <johan@x-tnd.be>
54 * @copyright 2010-2014 The Galette Team
55 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
56 * @link http://galette.tuxfamily.org
57 * @since Available since 0.7dev - 2010-03-11
63 public const TABLE
= 'cotisations';
64 public const PK
= 'id_cotis';
71 private $_payment_type;
72 private $_orig_amount;
76 private $_transaction = null;
80 //fields list and their translation
88 private $sendmail = false;
93 * @param Db $zdb Database
94 * @param Login $login Login instance
95 * @param null|int|ResultSet $args Either a ResultSet row to load
96 * a specific contribution, or an type id
97 * to just instanciate object
99 public function __construct(Db
$zdb, Login
$login, $args = null)
102 $this->login
= $login;
105 * Fields configuration. Each field is an array and must reflect:
111 * I'd prefer a static private variable for this...
112 * But call to the _T function does not seem to be allowed there :/
114 $this->_fields
= array(
116 'label' => null, //not a field in the form
119 Adherent
::PK
=> array(
120 'label' => _T("Contributor:"),
121 'propname' => 'member'
123 ContributionsTypes
::PK
=> array(
124 'label' => _T("Contribution type:"),
127 'montant_cotis' => array(
128 'label' => _T("Amount:"),
129 'propname' => 'amount'
131 'type_paiement_cotis' => array(
132 'label' => _T("Payment type:"),
133 'propname' => 'payment_type'
135 'info_cotis' => array(
136 'label' => _T("Comments:"),
139 'date_enreg' => array(
140 'label' => null, //not a field in the form
143 'date_debut_cotis' => array(
144 'label' => _T("Date of contribution:"),
145 'cotlabel' => _T("Start date of membership:"), //if contribution is a cotisation, label differs
146 'propname' => 'begin_date'
148 'date_fin_cotis' => array(
149 'label' => _T("End date of membership:"),
150 'propname' => 'end_date'
152 Transaction
::PK
=> array(
153 'label' => null, //not a field in the form
154 'propname' => 'transaction'
156 //this one is not really a field, but is required in some cases...
157 //adding it here make simplier to check required fields
158 'duree_mois_cotis' => array(
159 'label' => _T("Membership extension:"),
160 'propname' => 'extension'
165 } elseif (is_array($args)) {
166 $this->_date
= date("Y-m-d");
167 if (isset($args['adh']) && $args['adh'] != '') {
168 $this->_member
= (int)$args['adh'];
170 if (isset($args['trans'])) {
171 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
172 if (!isset($this->_member
)) {
173 $this->_member
= (int)$this->_transaction
->member
;
175 $this->_amount
= $this->_transaction
->getMissingAmount();
177 $this->type
= (int)$args['type'];
178 //calculate begin date for cotisation
179 $this->_begin_date
= $this->_date
;
180 if ($this->_is_cotis
) {
181 $curend = self
::getDueDate($this->zdb
, $this->_member
);
183 $dend = new \
DateTime($curend);
184 $now = date('Y-m-d');
185 $dnow = new \
DateTime($now);
187 // Member didn't renew on time
188 $this->_begin_date
= $now;
190 $this->_begin_date
= $curend;
193 $this->retrieveEndDate();
195 if (isset($args['payment_type'])) {
196 $this->_payment_type
= $args['payment_type'];
198 } elseif (is_object($args)) {
199 $this->loadFromRS($args);
202 $this->loadDynamicFields();
206 * Sets end contribution date
210 private function retrieveEndDate()
214 $bdate = new \
DateTime($this->_begin_date
);
215 if ($preferences->pref_beg_membership
!= '') {
216 //case beginning of membership
217 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
218 $edate = new \
DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
219 while ($edate <= $bdate) {
220 $edate->modify('+1 year');
223 if ($preferences->pref_membership_offermonths
> 0) {
224 //count days until end of membership date
225 $diff1 = (int)$bdate->diff($edate)->format('%a');
227 //count days beetween end of membership date and offered months
228 $tdate = clone $edate;
229 $tdate->modify('-' . $preferences->pref_membership_offermonths
. ' month');
230 $diff2 = (int)$edate->diff($tdate)->format('%a');
232 //when number of days until end of membership is less than for offered months, it's free :)
233 if ($diff1 <= $diff2) {
234 $edate->modify('+1 year');
238 $this->_end_date
= $edate->format('Y-m-d');
239 } elseif ($preferences->pref_membership_ext
!= '') {
240 //case membership extension
241 if ($this->_extension
== null) {
242 $this->_extension
= $preferences->pref_membership_ext
;
244 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
245 $edate = $bdate->add($dext);
246 $this->_end_date
= $edate->format('Y-m-d');
248 throw new \
RuntimeException(
249 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
255 * Loads a contribution from its id
257 * @param int $id the identifiant for the contribution to load
259 * @return bool true if query succeed, false otherwise
261 public function load($id)
264 $select = $this->zdb
->select(self
::TABLE
);
265 $select->where(self
::PK
. ' = ' . $id);
266 //restrict query on current member id if he's not admin nor staff member
267 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
268 $select->where(Adherent
::PK
. ' = ' . $this->login
->id
);
271 $results = $this->zdb
->execute($select);
272 if ($results->count() > 0) {
273 $row = $results->current();
274 $this->loadFromRS($row);
277 throw new \
Exception(
278 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')'
281 } catch (\Exception
$e) {
283 'An error occurred attempting to load contribution #' . $id .
292 * Populate object from a resultset row
294 * @param ResultSet $r the resultset row
298 private function loadFromRS($r)
301 $this->_id
= (int)$r->$pk;
302 $this->_date
= $r->date_enreg
;
303 $this->_amount
= $r->montant_cotis
;
304 //save original amount, we need it for transactions parts calulations
305 $this->_orig_amount
= $r->montant_cotis
;
306 $this->_payment_type
= $r->type_paiement_cotis
;
307 $this->_info
= $r->info_cotis
;
308 $this->_begin_date
= $r->date_debut_cotis
;
309 $enddate = $r->date_fin_cotis
;
310 //do not work with knows bad dates...
311 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
312 //strange date? dont know :(
314 $enddate !== '0000-00-00'
315 && $enddate !== '1901-01-01'
316 && $enddate !== '0001-01-01 BC'
318 $this->_end_date
= $r->date_fin_cotis
;
320 $adhpk = Adherent
::PK
;
321 $this->_member
= (int)$r->$adhpk;
323 $transpk = Transaction
::PK
;
324 if ($r->$transpk != '') {
325 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
328 $this->type
= (int)$r->id_type_cotis
;
329 $this->loadDynamicFields();
333 * Check posted values validity
335 * @param array $values All values to check, basically the $_POST array
336 * after sending the form
337 * @param array $required Array of required fields
338 * @param array $disabled Array of disabled fields
342 public function check($values, $required, $disabled)
345 $this->errors
= array();
347 $fields = array_keys($this->_fields
);
348 foreach ($fields as $key) {
349 //first of all, let's sanitize values
350 $key = strtolower($key);
351 $prop = '_' . $this->_fields
[$key]['propname'];
353 if (isset($values[$key])) {
354 $value = trim($values[$key]);
359 // if the field is enabled, check it
360 if (!isset($disabled[$key])) {
361 // fill up the adherent structure
362 //$this->$prop = stripslashes($value); //not relevant here!
364 // now, check validity
368 case 'date_debut_cotis':
369 case 'date_fin_cotis':
372 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
374 throw new \
Exception('Incorrect format');
376 $this->$prop = $d->format('Y-m-d');
377 } catch (\Exception
$e) {
379 'Wrong date format. field: ' . $key .
380 ', value: ' . $value . ', expected fmt: ' .
381 __("Y-m-d") . ' | ' . $e->getMessage(),
384 $this->errors
[] = str_replace(
391 $this->_fields
[$key]['label']
393 _T("- Wrong date format (%date_format) for %field!")
400 $this->_member
= (int)$value;
403 case ContributionsTypes
::PK
:
405 $this->type
= (int)$value;
408 case 'montant_cotis':
409 $this->_amount
= $value;
410 $value = strtr($value, ',', '.');
411 if (!is_numeric($value) && $value !== '') {
412 $this->errors
[] = _T("- The amount must be an integer!");
415 case 'type_paiement_cotis':
416 $ptypes = new PaymentTypes(
421 $ptlist = $ptypes->getList();
422 if (isset($ptlist[$value])) {
423 $this->_payment_type
= $value;
425 $this->errors
[] = _T("- Unknown payment type");
429 $this->_info
= $value;
431 case Transaction
::PK
:
433 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
436 case 'duree_mois_cotis':
438 if (!is_numeric($value) ||
$value <= 0) {
439 $this->errors
[] = _T("- The duration must be a positive integer!");
441 $this->$prop = $value;
442 $this->retrieveEndDate();
449 // missing required fields?
450 foreach ($required as $key => $val) {
452 $prop = '_' . $this->_fields
[$key]['propname'];
454 !isset($disabled[$key])
455 && (!isset($this->$prop)
456 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
457 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
459 $this->errors
[] = str_replace(
461 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
462 _T("- Mandatory field %field empty.")
468 if ($this->_transaction
!= null && $this->_amount
!= null) {
469 $missing = $this->_transaction
->getMissingAmount();
470 //calculate new missing amount
471 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
473 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
477 if ($this->isCotis() && count($this->errors
) == 0) {
478 $overlap = $this->checkOverlap();
479 if ($overlap !== true) {
480 if ($overlap === false) {
481 $this->errors
[] = _T("An error occurred checking overlaping fees :(");
483 //method directly return error message
484 $this->errors
[] = $overlap;
489 $this->dynamicsCheck($values, $required, $disabled);
491 if (count($this->errors
) > 0) {
493 'Some errors has been throwed attempting to edit/store a contribution' .
494 print_r($this->errors
, true),
497 return $this->errors
;
500 'Contribution checked successfully.',
508 * Check that membership fees does not overlap
510 * @return boolean|string True if all is ok, false if error,
511 * error message if overlap
513 public function checkOverlap()
516 $select = $this->zdb
->select(self
::TABLE
, 'c');
518 array('date_debut_cotis', 'date_fin_cotis')
520 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
521 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
523 )->where(Adherent
::PK
. ' = ' . $this->_member
)
524 ->where(array('cotis_extension' => new Expression('true')))
526 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
527 ->lessThan('date_debut_cotis', $this->_end_date
)
530 ->greaterThan('date_fin_cotis', $this->_begin_date
)
531 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
533 if ($this->id
!= '') {
534 $select->where(self
::PK
. ' != ' . $this->id
);
537 $results = $this->zdb
->execute($select);
538 if ($results->count() > 0) {
539 $result = $results->current();
540 $d = new \
DateTime($result->date_debut_cotis
);
542 return _T("- Membership period overlaps period starting at ") .
543 $d->format(__("Y-m-d"));
546 } catch (\Exception
$e) {
548 'An error occurred checking overlaping fee. ' . $e->getMessage(),
556 * Store the contribution
560 public function store()
562 global $hist, $emitter;
566 if (count($this->errors
) > 0) {
567 throw new \
RuntimeException(
568 'Existing errors prevents storing contribution: ' .
569 print_r($this->errors
, true)
574 $this->zdb
->connection
->beginTransaction();
576 $fields = self
::getDbFields($this->zdb
);
577 foreach ($fields as $field) {
578 $prop = '_' . $this->_fields
[$field]['propname'];
580 case ContributionsTypes
::PK
:
581 case Transaction
::PK
:
582 if (isset($this->$prop)) {
583 $values[$field] = $this->$prop->id
;
587 $values[$field] = $this->$prop;
592 //no end date, let's take database defaults
593 if (!$this->isCotis() && !$this->_end_date
) {
594 unset($values['date_fin_cotis']);
598 if (!isset($this->_id
) ||
$this->_id
== '') {
599 //we're inserting a new contribution
600 unset($values[self
::PK
]);
602 $insert = $this->zdb
->insert(self
::TABLE
);
603 $insert->values($values);
604 $add = $this->zdb
->execute($insert);
606 if ($add->count() > 0) {
607 if ($this->zdb
->isPostgres()) {
608 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
609 PREFIX_DB
. 'cotisations_id_seq'
612 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
617 _T("Contribution added"),
618 Adherent
::getSName($this->zdb
, $this->_member
)
621 $event = 'contribution.add';
623 $hist->add(_T("Fail to add new contribution."));
624 throw new \
Exception(
625 'An error occurred inserting new contribution!'
629 //we're editing an existing contribution
630 $update = $this->zdb
->update(self
::TABLE
);
631 $update->set($values)->where(
632 self
::PK
. '=' . $this->_id
634 $edit = $this->zdb
->execute($update);
636 //edit == 0 does not mean there were an error, but that there
637 //were nothing to change
638 if ($edit->count() > 0) {
640 _T("Contribution updated"),
641 Adherent
::getSName($this->zdb
, $this->_member
)
645 if ($edit === false) {
646 throw new \
Exception(
647 'An error occurred updating contribution # ' . $this->_id
. '!'
651 $event = 'contribution.edit';
654 if ($this->isCotis()) {
655 $deadline = $this->updateDeadline();
656 if ($deadline !== true) {
657 //if something went wrong, we rollback transaction
658 throw new \
Exception('An error occurred updating member\'s deadline');
664 $success = $this->dynamicsStore(true);
667 $this->zdb
->connection
->commit();
668 $this->_orig_amount
= $this->_amount
;
670 //send event at the end of process, once all has been stored
671 if ($event !== null) {
672 $emitter->emit($event, $this);
676 } catch (\Exception
$e) {
677 $this->zdb
->connection
->rollBack();
679 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
680 $e->getTraceAsString(),
688 * Update member dead line
692 private function updateDeadline()
695 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
697 if ($due_date != '') {
698 $date_fin_update = $due_date;
700 $date_fin_update = new Expression('NULL');
703 $update = $this->zdb
->update(Adherent
::TABLE
);
705 array('date_echeance' => $date_fin_update)
707 Adherent
::PK
. '=' . $this->_member
709 $this->zdb
->execute($update);
711 } catch (\Exception
$e) {
713 'An error occurred updating member ' . $this->_member
.
723 * Remove contribution from database
725 * @param boolean $transaction Activate transaction mode (defaults to true)
729 public function remove($transaction = true)
735 $this->zdb
->connection
->beginTransaction();
738 $delete = $this->zdb
->delete(self
::TABLE
);
739 $delete->where(self
::PK
. ' = ' . $this->_id
);
740 $del = $this->zdb
->execute($delete);
741 if ($del->count() > 0) {
742 $this->updateDeadline();
743 $this->dynamicsRemove(true);
745 throw new \
RuntimeException(
746 'Contribution has not been removed!'
750 $this->zdb
->connection
->commit();
752 $emitter->emit('contribution.remove', $this);
754 } catch (\Exception
$e) {
756 $this->zdb
->connection
->rollBack();
759 'An error occurred trying to remove contribution #' .
760 $this->_id
. ' | ' . $e->getMessage(),
770 * @param string $field Field name
774 public function getFieldLabel($field)
776 $label = $this->_fields
[$field]['label'];
777 if ($this->isCotis() && $field == 'date_debut_cotis') {
778 $label = $this->_fields
[$field]['cotlabel'];
781 $label = str_replace(' ', ' ', $label);
782 //remove trailing ':' and then trim
783 $label = trim(trim($label, ':'));
788 * Retrieve fields from database
790 * @param Db $zdb Database instance
794 public static function getDbFields(Db
$zdb)
796 $columns = $zdb->getColumns(self
::TABLE
);
798 foreach ($columns as $col) {
799 $fields[] = $col->getName();
805 * Get the relevant CSS class for current contribution
807 * @return string current contribution row class
809 public function getRowClass()
811 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
812 'cotis-normal' : 'cotis-give';
816 * Retrieve member due date
818 * @param Db $zdb Database instance
819 * @param integer $member_id Member identifier
823 public static function getDueDate(Db
$zdb, $member_id)
829 $select = $zdb->select(self
::TABLE
, 'c');
832 'max_date' => new Expression('MAX(date_fin_cotis)')
835 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
836 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
839 Adherent
::PK
. ' = ' . $member_id
841 array('cotis_extension' => new Expression('true'))
844 $results = $zdb->execute($select);
845 $result = $results->current();
846 $due_date = $result->max_date
;
848 //avoid bad dates in postgres and bad mysql return from zenddb
849 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
853 } catch (\Exception
$e) {
855 'An error occurred trying to retrieve member\'s due date',
863 * Detach a contribution from a transaction
865 * @param Db $zdb Database instance
866 * @param Login $login Login instance
867 * @param int $trans_id Transaction identifier
868 * @param int $contrib_id Contribution identifier
872 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
875 //first, we check if contribution is part of transaction
876 $c = new Contribution($zdb, $login, (int)$contrib_id);
877 if ($c->isTransactionPartOf($trans_id)) {
878 $update = $zdb->update(self
::TABLE
);
880 array(Transaction
::PK
=> null)
882 self
::PK
. ' = ' . $contrib_id
884 $zdb->execute($update);
888 'Contribution #' . $contrib_id .
889 ' is not actually part of transaction #' . $trans_id,
894 } catch (\Exception
$e) {
896 'Unable to detach contribution #' . $contrib_id .
897 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
905 * Set a contribution as a transaction part
907 * @param Db $zdb Database instance
908 * @param int $trans_id Transaction identifier
909 * @param int $contrib_id Contribution identifier
913 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
916 $update = $zdb->update(self
::TABLE
);
918 array(Transaction
::PK
=> $trans_id)
919 )->where(self
::PK
. ' = ' . $contrib_id);
921 $zdb->execute($update);
923 } catch (\Exception
$e) {
925 'Unable to attach contribution #' . $contrib_id .
926 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
934 * Is current contribution a cotisation
938 public function isCotis()
940 return $this->_is_cotis
;
944 * Is current contribution part of specified transaction
946 * @param int $id Transaction identifier
950 public function isTransactionPartOf($id)
952 if ($this->isTransactionPart()) {
953 return $id == $this->_transaction
->id
;
960 * Is current contribution part of transaction
964 public function isTransactionPart()
966 return $this->_transaction
!= null;
970 * Execute post contribution script
972 * @param ExternalScript $es External script to execute
973 * @param array $extra Extra information on contribution
975 * @param array $pextra Extra information on payment
978 * @return mixed Script return value on success, values and script output on fail
980 public function executePostScript(
988 'type' => $this->getPaymentType()
991 if ($pextra !== null && is_array($pextra)) {
992 $payment = array_merge($payment, $pextra);
995 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
996 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
999 $voucher_path = null;
1000 if ($this->_id
!== null) {
1001 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
1002 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1003 $voucher_path = $voucher->getPath();
1007 'id' => (int)$this->_id
,
1008 'date' => $this->_date
,
1009 'type' => $this->getRawType(),
1010 'amount' => $this->amount
,
1011 'voucher' => $voucher_path,
1012 'category' => array(
1013 'id' => $this->type
->id
,
1014 'label' => $this->type
->libelle
1016 'payment' => $payment
1019 if ($this->_member
!== null) {
1020 $m = new Adherent($this->zdb
, (int)$this->_member
);
1022 'id' => (int)$this->_member
,
1023 'name' => $m->sfullname
,
1024 'email' => $m->email
,
1025 'organization' => ($m->isCompany() ?
1 : 0),
1028 'label' => $m->sstatus
1030 'country' => $m->country
1033 if ($m->isCompany()) {
1034 $member['organization_name'] = $m->company_name
;
1037 $contrib['member'] = $member;
1040 if ($extra !== null && is_array($extra)) {
1041 $contrib = array_merge($contrib, $extra);
1044 $res = $es->send($contrib);
1046 if ($res !== true) {
1048 'An error occurred calling post contribution ' .
1049 "script:\n" . $es->getOutput(),
1052 $res = _T("Contribution information") . "\n";
1053 $res .= print_r($contrib, true);
1054 $res .= "\n\n" . _T("Script output") . "\n";
1055 $res .= $es->getOutput();
1061 * Get raw contribution type
1065 public function getRawType()
1067 if ($this->isCotis()) {
1068 return 'membership';
1075 * Get contribution type label
1079 public function getTypeLabel()
1081 if ($this->isCotis()) {
1082 return _T("Membership");
1084 return _T("Donation");
1089 * Get payment type label
1093 public function getPaymentType()
1095 if ($this->_payment_type
=== null) {
1099 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1100 return $ptype->getName(false);
1104 * Global getter method
1106 * @param string $name name of the property we want to retrive
1108 * @return false|object the called property
1110 public function __get($name)
1113 $forbidden = array('is_cotis');
1114 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1115 'raw_begin_date', 'raw_end_date'
1118 $rname = '_' . $name;
1120 if (in_array($name, $forbidden)) {
1122 "Call to __get for '$name' is forbidden!",
1128 return $this->isCotis();
1131 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1134 property_exists($this, $rname)
1135 ||
in_array($name, $virtuals)
1139 case 'raw_begin_date':
1140 case 'raw_end_date':
1141 $rname = '_' . substr($name, 4);
1142 if ($this->$rname != '') {
1144 $d = new \
DateTime($this->$rname);
1146 } catch (\Exception
$e) {
1147 //oops, we've got a bad date :/
1149 'Bad date (' . $this->$rname . ') | ' .
1160 if ($this->$rname != '') {
1162 $d = new \
DateTime($this->$rname);
1163 return $d->format(__("Y-m-d"));
1164 } catch (\Exception
$e) {
1165 //oops, we've got a bad date :/
1167 'Bad date (' . $this->$rname . ') | ' .
1171 return $this->$rname;
1176 if ($this->_is_cotis
) {
1177 $date_end = new \
DateTime($this->_end_date
);
1178 $date_start = new \
DateTime($this->_begin_date
);
1179 $diff = $date_end->diff($date_start);
1180 return $diff->format('%y') * 12 +
$diff->format('%m');
1185 case 'spayment_type':
1186 if ($this->_payment_type
=== null) {
1190 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1191 return $ptype->getName();
1195 if ($this->_is_cotis
=== null) {
1198 return ($this->isCotis()) ?
1199 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1202 return $this->$rname;
1207 "Unknown property '$rname'",
1215 * Global setter method
1217 * @param string $name name of the property we want to assign a value to
1218 * @param object $value a relevant value for the property
1222 public function __set($name, $value)
1224 global $preferences;
1226 $forbidden = array('fields', 'is_cotis', 'end_date');
1228 if (!in_array($name, $forbidden)) {
1229 $rname = '_' . $name;
1232 if (is_int($value)) {
1233 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1236 'Trying to set a transaction from an id that is not an integer.',
1242 if (is_int($value)) {
1244 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1245 //set is_cotis according to type
1246 if ($this->$rname->extension
== 1) {
1247 $this->_is_cotis
= true;
1249 $this->_is_cotis
= false;
1253 'Trying to set a type from an id that is not an integer.',
1260 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1262 throw new \
Exception('Incorrect format');
1264 $this->_begin_date
= $d->format('Y-m-d');
1265 } catch (\Exception
$e) {
1267 'Wrong date format. field: ' . $name .
1268 ', value: ' . $value . ', expected fmt: ' .
1269 __("Y-m-d") . ' | ' . $e->getMessage(),
1272 $this->errors
[] = str_replace(
1279 $this->_fields
['date_debut_cotis']['label']
1281 _T("- Wrong date format (%date_format) for %field!")
1286 if (is_numeric($value) && $value > 0) {
1287 $this->$rname = $value;
1290 'Trying to set an amount with a non numeric value, ' .
1291 'or with a zero value',
1297 if (is_int($value)) {
1299 $this->$rname = $value;
1302 case 'payment_type':
1303 $ptypes = new PaymentTypes(
1308 $list = $ptypes->getList();
1309 if (isset($list[$value])) {
1310 $this->_payment_type
= $value;
1313 'Unknown payment type ' . $value,
1320 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1330 * Flag creation mail sending
1332 * @param boolean $send True (default) to send creation email
1334 * @return Contribution
1336 public function setSendmail($send = true)
1338 $this->sendmail
= $send;
1343 * Should we send administrative emails to member?
1347 public function sendEMail()
1349 return $this->sendmail
;