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
34 * @link http://galette.tuxfamily.org
35 * @since Available since 0.7dev - 2010-03-11
38 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 const TABLE
= 'cotisations';
65 const PK
= 'id_cotis';
72 private $_payment_type;
73 private $_orig_amount;
77 private $_transaction = null;
81 //fields list and their translation
92 * @param Db $zdb Database
93 * @param Login $login Login instance
94 * @param null|int|ResultSet $args Either a ResultSet row to load
95 * a specific contribution, or an type id
96 * to just instanciate object
98 public function __construct(Db
$zdb, Login
$login, $args = null)
101 $this->login
= $login;
104 * Fields configuration. Each field is an array and must reflect:
110 * I'd prefer a static private variable for this...
111 * But call to the _T function does not seem to be allowed there :/
113 $this->_fields
= array(
115 'label' => null, //not a field in the form
118 Adherent
::PK
=> array(
119 'label' => _T("Contributor:"),
120 'propname' => 'member'
122 ContributionsTypes
::PK
=> array(
123 'label' => _T("Contribution type:"),
126 'montant_cotis' => array(
127 'label' => _T("Amount:"),
128 'propname' => 'amount'
130 'type_paiement_cotis' => array(
131 'label' => _T("Payment type:"),
132 'propname' => 'payment_type'
134 'info_cotis' => array(
135 'label' => _T("Comments:"),
138 'date_enreg' => array(
139 'label' => null, //not a field in the form
142 'date_debut_cotis' => array(
143 'label' => _T("Date of contribution:"),
144 'cotlabel' => _T("Start date of membership:"), //if contribution is a cotisation, label differs
145 'propname' => 'begin_date'
147 'date_fin_cotis' => array(
148 'label' => _T("End date of membership:"),
149 'propname' => 'end_date'
151 Transaction
::PK
=> array(
152 'label' => null, //not a field in the form
153 'propname' => 'transaction'
155 //this one is not really a field, but is required in some cases...
156 //adding it here make simplier to check required fields
157 'duree_mois_cotis' => array(
158 'label' => _T("Membership extension:"),
159 'propname' => 'extension'
164 } elseif (is_array($args)) {
165 $this->_date
= date("Y-m-d");
166 if (isset($args['adh']) && $args['adh'] != '') {
167 $this->_member
= (int)$args['adh'];
169 if (isset($args['trans'])) {
170 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
171 if (!isset($this->_member
)) {
172 $this->_member
= (int)$this->_transaction
->member
;
174 $this->_amount
= $this->_transaction
->getMissingAmount();
176 $this->type
= (int)$args['type'];
177 //calculate begin date for cotisation
178 $this->_begin_date
= $this->_date
;
179 if ($this->_is_cotis
) {
180 $curend = self
::getDueDate($this->zdb
, $this->_member
);
182 $dend = new \
DateTime($curend);
183 $now = date('Y-m-d');
184 $dnow = new \
DateTime($now);
186 // Member didn't renew on time
187 $this->_begin_date
= $now;
189 $this->_begin_date
= $curend;
192 $this->retrieveEndDate();
194 if (isset($args['payment_type'])) {
195 $this->_payment_type
= $args['payment_type'];
197 } elseif (is_object($args)) {
198 $this->loadFromRS($args);
201 $this->loadDynamicFields();
205 * Sets end contribution date
209 private function retrieveEndDate()
213 $bdate = new \
DateTime($this->_begin_date
);
214 if ($preferences->pref_beg_membership
!= '') {
215 //case beginning of membership
216 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
217 $edate = new \
DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
218 while ($edate <= $bdate) {
219 $edate->modify('+1 year');
222 if ($preferences->pref_membership_offermonths
> 0) {
223 //count days until end of membership date
224 $diff1 = (int)$bdate->diff($edate)->format('%a');
226 //count days beetween end of membership date and offered months
227 $tdate = clone $edate;
228 $tdate->modify('-' . $preferences->pref_membership_offermonths
. ' month');
229 $diff2 = (int)$edate->diff($tdate)->format('%a');
231 //when number of days until end of membership is less than for offered months, it's free :)
232 if ($diff1 <= $diff2) {
233 $edate->modify('+1 year');
237 $this->_end_date
= $edate->format('Y-m-d');
238 } elseif ($preferences->pref_membership_ext
!= '') {
239 //case membership extension
240 if ($this->_extension
== null) {
241 $this->_extension
= $preferences->pref_membership_ext
;
243 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
244 $edate = $bdate->add($dext);
245 $this->_end_date
= $edate->format('Y-m-d');
247 throw new \
RuntimeException(
248 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
254 * Loads a contribution from its id
256 * @param int $id the identifiant for the contribution to load
258 * @return bool true if query succeed, false otherwise
260 public function load($id)
263 $select = $this->zdb
->select(self
::TABLE
);
264 $select->where(self
::PK
. ' = ' . $id);
265 //restrict query on current member id if he's not admin nor staff member
266 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
267 $select->where(Adherent
::PK
. ' = ' . $this->login
->id
);
270 $results = $this->zdb
->execute($select);
271 if ($results->count() > 0) {
272 $row = $results->current();
273 $this->loadFromRS($row);
276 throw new \
Exception(
277 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')'
280 } catch (\Exception
$e) {
282 'An error occurred attempting to load contribution #' . $id .
291 * Populate object from a resultset row
293 * @param ResultSet $r the resultset row
297 private function loadFromRS($r)
300 $this->_id
= (int)$r->$pk;
301 $this->_date
= $r->date_enreg
;
302 $this->_amount
= $r->montant_cotis
;
303 //save original amount, we need it for transactions parts calulations
304 $this->_orig_amount
= $r->montant_cotis
;
305 $this->_payment_type
= $r->type_paiement_cotis
;
306 $this->_info
= $r->info_cotis
;
307 $this->_begin_date
= $r->date_debut_cotis
;
308 $enddate = $r->date_fin_cotis
;
309 //do not work with knows bad dates...
310 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
311 //strange date? dont know :(
313 $enddate !== '0000-00-00'
314 && $enddate !== '1901-01-01'
315 && $enddate !== '0001-01-01 BC'
317 $this->_end_date
= $r->date_fin_cotis
;
319 $adhpk = Adherent
::PK
;
320 $this->_member
= (int)$r->$adhpk;
322 $transpk = Transaction
::PK
;
323 if ($r->$transpk != '') {
324 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
327 $this->type
= (int)$r->id_type_cotis
;
328 $this->loadDynamicFields();
332 * Check posted values validity
334 * @param array $values All values to check, basically the $_POST array
335 * after sending the form
336 * @param array $required Array of required fields
337 * @param array $disabled Array of disabled fields
341 public function check($values, $required, $disabled)
344 $this->errors
= array();
346 $fields = array_keys($this->_fields
);
347 foreach ($fields as $key) {
348 //first of all, let's sanitize values
349 $key = strtolower($key);
350 $prop = '_' . $this->_fields
[$key]['propname'];
352 if (isset($values[$key])) {
353 $value = trim($values[$key]);
358 // if the field is enabled, check it
359 if (!isset($disabled[$key])) {
360 // fill up the adherent structure
361 //$this->$prop = stripslashes($value); //not relevant here!
363 // now, check validity
367 case 'date_debut_cotis':
368 case 'date_fin_cotis':
371 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
373 throw new \
Exception('Incorrect format');
375 $this->$prop = $d->format('Y-m-d');
376 } catch (\Exception
$e) {
378 'Wrong date format. field: ' . $key .
379 ', value: ' . $value . ', expected fmt: ' .
380 __("Y-m-d") . ' | ' . $e->getMessage(),
383 $this->errors
[] = str_replace(
390 $this->_fields
[$key]['label']
392 _T("- Wrong date format (%date_format) for %field!")
399 $this->_member
= (int)$value;
402 case ContributionsTypes
::PK
:
404 $this->type
= (int)$value;
407 case 'montant_cotis':
408 $this->_amount
= $value;
409 $value = strtr($value, ',', '.');
410 if (!is_numeric($value) && $value !== '') {
411 $this->errors
[] = _T("- The amount must be an integer!");
414 case 'type_paiement_cotis':
415 $ptypes = new PaymentTypes(
420 $ptlist = $ptypes->getList();
421 if (isset($ptlist[$value])) {
422 $this->_payment_type
= $value;
424 $this->errors
[] = _T("- Unknown payment type");
428 $this->_info
= $value;
430 case Transaction
::PK
:
432 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
435 case 'duree_mois_cotis':
437 if (!is_numeric($value) ||
$value <= 0) {
438 $this->errors
[] = _T("- The duration must be a positive integer!");
440 $this->$prop = $value;
441 $this->retrieveEndDate();
448 // missing required fields?
449 foreach ($required as $key => $val) {
451 $prop = '_' . $this->_fields
[$key]['propname'];
453 !isset($disabled[$key])
454 && (!isset($this->$prop)
455 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
456 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
458 $this->errors
[] = str_replace(
460 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
461 _T("- Mandatory field %field empty.")
467 if ($this->_transaction
!= null && $this->_amount
!= null) {
468 $missing = $this->_transaction
->getMissingAmount();
469 //calculate new missing amount
470 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
472 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
476 if ($this->isCotis() && count($this->errors
) == 0) {
477 $overlap = $this->checkOverlap();
478 if ($overlap !== true) {
479 if ($overlap === false) {
480 $this->errors
[] = _T("An error occurred checking overlaping fees :(");
482 //method directly return error message
483 $this->errors
[] = $overlap;
488 $this->dynamicsCheck($values);
490 if (count($this->errors
) > 0) {
492 'Some errors has been throwed attempting to edit/store a contribution' .
493 print_r($this->errors
, true),
496 return $this->errors
;
499 'Contribution checked successfully.',
507 * Check that membership fees does not overlap
509 * @return boolean|string True if all is ok, false if error,
510 * error message if overlap
512 public function checkOverlap()
515 $select = $this->zdb
->select(self
::TABLE
, 'c');
517 array('date_debut_cotis', 'date_fin_cotis')
519 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
520 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
522 )->where(Adherent
::PK
. ' = ' . $this->_member
)
523 ->where(array('cotis_extension' => new Expression('true')))
525 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
526 ->lessThan('date_debut_cotis', $this->_end_date
)
529 ->greaterThan('date_fin_cotis', $this->_begin_date
)
530 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
532 if ($this->id
!= '') {
533 $select->where(self
::PK
. ' != ' . $this->id
);
536 $results = $this->zdb
->execute($select);
537 if ($results->count() > 0) {
538 $result = $results->current();
539 $d = new \
DateTime($result->date_debut_cotis
);
541 return _T("- Membership period overlaps period starting at ") .
542 $d->format(__("Y-m-d"));
545 } catch (\Exception
$e) {
547 'An error occurred checking overlaping fee. ' . $e->getMessage(),
555 * Store the contribution
559 public function store()
561 global $hist, $emitter;
563 if (count($this->errors
) > 0) {
564 throw new \
RuntimeException(
565 'Existing errors prevents storing contribution: ' .
566 print_r($this->errors
, true)
572 $this->zdb
->connection
->beginTransaction();
574 $fields = self
::getDbFields($this->zdb
);
575 foreach ($fields as $field) {
576 $prop = '_' . $this->_fields
[$field]['propname'];
578 case ContributionsTypes
::PK
:
579 case Transaction
::PK
:
580 if (isset($this->$prop)) {
581 $values[$field] = $this->$prop->id
;
585 $values[$field] = $this->$prop;
590 //no end date, let's take database defaults
591 if (!$this->isCotis() && !$this->_end_date
) {
592 unset($values['date_fin_cotis']);
596 if (!isset($this->_id
) ||
$this->_id
== '') {
597 //we're inserting a new contribution
598 unset($values[self
::PK
]);
600 $insert = $this->zdb
->insert(self
::TABLE
);
601 $insert->values($values);
602 $add = $this->zdb
->execute($insert);
604 if ($add->count() > 0) {
605 if ($this->zdb
->isPostgres()) {
606 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
607 PREFIX_DB
. 'cotisations_id_seq'
610 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
615 _T("Contribution added"),
616 Adherent
::getSName($this->zdb
, $this->_member
)
620 $emitter->emit('contribution.add', $this);
622 $hist->add(_T("Fail to add new contribution."));
623 throw new \
Exception(
624 'An error occurred inserting new contribution!'
628 //we're editing an existing contribution
629 $update = $this->zdb
->update(self
::TABLE
);
630 $update->set($values)->where(
631 self
::PK
. '=' . $this->_id
633 $edit = $this->zdb
->execute($update);
635 //edit == 0 does not mean there were an error, but that there
636 //were nothing to change
637 if ($edit->count() > 0) {
639 _T("Contribution updated"),
640 Adherent
::getSName($this->zdb
, $this->_member
)
644 if ($edit === false) {
645 throw new \
Exception(
646 'An error occurred updating contribution # ' . $this->_id
. '!'
651 $emitter->emit('contribution.edit', $this);
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 } catch (\Exception
$e) {
671 $this->zdb
->connection
->rollBack();
673 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
674 $e->getTraceAsString(),
682 * Update member dead line
686 private function updateDeadline()
689 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
691 if ($due_date != '') {
692 $date_fin_update = $due_date;
694 $date_fin_update = new Expression('NULL');
697 $update = $this->zdb
->update(Adherent
::TABLE
);
699 array('date_echeance' => $date_fin_update)
701 Adherent
::PK
. '=' . $this->_member
703 $this->zdb
->execute($update);
705 } catch (\Exception
$e) {
707 'An error occurred updating member ' . $this->_member
.
717 * Remove contribution from database
719 * @param boolean $transaction Activate transaction mode (defaults to true)
723 public function remove($transaction = true)
729 $this->zdb
->connection
->beginTransaction();
732 $delete = $this->zdb
->delete(self
::TABLE
);
733 $delete->where(self
::PK
. ' = ' . $this->_id
);
734 $del = $this->zdb
->execute($delete);
735 if ($del->count() > 0) {
736 $this->updateDeadline();
737 $this->dynamicsRemove(true);
739 throw new \
RuntimeException(
740 'Contribution has not been removed!'
744 $this->zdb
->connection
->commit();
746 $emitter->emit('contribution.remove', $this);
748 } catch (\Exception
$e) {
750 $this->zdb
->connection
->rollBack();
753 'An error occurred trying to remove contribution #' .
754 $this->_id
. ' | ' . $e->getMessage(),
764 * @param string $field Field name
768 public function getFieldLabel($field)
770 $label = $this->_fields
[$field]['label'];
771 if ($this->isCotis() && $field == 'date_debut_cotis') {
772 $label = $this->_fields
[$field]['cotlabel'];
775 $label = str_replace(' ', ' ', $label);
776 //remove trailing ':' and then trim
777 $label = trim(trim($label, ':'));
782 * Retrieve fields from database
784 * @param Db $zdb Database instance
788 public static function getDbFields(Db
$zdb)
790 $columns = $zdb->getColumns(self
::TABLE
);
792 foreach ($columns as $col) {
793 $fields[] = $col->getName();
799 * Get the relevant CSS class for current contribution
801 * @return string current contribution row class
803 public function getRowClass()
805 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
806 'cotis-normal' : 'cotis-give';
810 * Retrieve member due date
812 * @param Db $zdb Database instance
813 * @param integer $member_id Member identifier
817 public static function getDueDate(Db
$zdb, $member_id)
823 $select = $zdb->select(self
::TABLE
, 'c');
826 'max_date' => new Expression('MAX(date_fin_cotis)')
829 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
830 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
833 Adherent
::PK
. ' = ' . $member_id
835 array('cotis_extension' => new Expression('true'))
838 $results = $zdb->execute($select);
839 $result = $results->current();
840 $due_date = $result->max_date
;
842 //avoid bad dates in postgres and bad mysql return from zenddb
843 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
847 } catch (\Exception
$e) {
849 'An error occurred trying to retrieve member\'s due date',
857 * Detach a contribution from a transaction
859 * @param Db $zdb Database instance
860 * @param Login $login Login instance
861 * @param int $trans_id Transaction identifier
862 * @param int $contrib_id Contribution identifier
866 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
869 //first, we check if contribution is part of transaction
870 $c = new Contribution($zdb, $login, (int)$contrib_id);
871 if ($c->isTransactionPartOf($trans_id)) {
872 $update = $zdb->update(self
::TABLE
);
874 array(Transaction
::PK
=> null)
876 self
::PK
. ' = ' . $contrib_id
878 $zdb->execute($update);
882 'Contribution #' . $contrib_id .
883 ' is not actually part of transaction #' . $trans_id,
888 } catch (\Exception
$e) {
890 'Unable to detach contribution #' . $contrib_id .
891 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
899 * Set a contribution as a transaction part
901 * @param Db $zdb Database instance
902 * @param int $trans_id Transaction identifier
903 * @param int $contrib_id Contribution identifier
907 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
910 $update = $zdb->update(self
::TABLE
);
912 array(Transaction
::PK
=> $trans_id)
913 )->where(self
::PK
. ' = ' . $contrib_id);
915 $zdb->execute($update);
917 } catch (\Exception
$e) {
919 'Unable to attach contribution #' . $contrib_id .
920 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
928 * Is current contribution a cotisation
932 public function isCotis()
934 return $this->_is_cotis
;
938 * Is current contribution part of specified transaction
940 * @param int $id Transaction identifier
944 public function isTransactionPartOf($id)
946 if ($this->isTransactionPart()) {
947 return $id == $this->_transaction
->id
;
954 * Is current contribution part of transaction
958 public function isTransactionPart()
960 return $this->_transaction
!= null;
964 * Execute post contribution script
966 * @param ExternalScript $es External script to execute
967 * @param array $extra Extra information on contribution
969 * @param array $pextra Extra information on payment
972 * @return mixed Script return value on success, values and script output on fail
974 public function executePostScript(
982 'type' => $this->getPaymentType()
985 if ($pextra !== null && is_array($pextra)) {
986 $payment = array_merge($payment, $pextra);
989 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
990 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
993 $voucher_path = null;
994 if ($this->_id
!== null) {
995 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
996 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
997 $voucher_path = $voucher->getPath();
1001 'id' => (int)$this->_id
,
1002 'date' => $this->_date
,
1003 'type' => $this->getRawType(),
1004 'amount' => $this->amount
,
1005 'voucher' => $voucher_path,
1006 'category' => array(
1007 'id' => $this->type
->id
,
1008 'label' => $this->type
->libelle
1010 'payment' => $payment
1013 if ($this->_member
!== null) {
1014 $m = new Adherent($this->zdb
, (int)$this->_member
);
1016 'id' => (int)$this->_member
,
1017 'name' => $m->sfullname
,
1018 'email' => $m->email
,
1019 'organization' => ($m->isCompany() ?
1 : 0),
1022 'label' => $m->sstatus
1024 'country' => $m->country
1027 if ($m->isCompany()) {
1028 $member['organization_name'] = $m->company_name
;
1031 $contrib['member'] = $member;
1034 if ($extra !== null && is_array($extra)) {
1035 $contrib = array_merge($contrib, $extra);
1038 $res = $es->send($contrib);
1040 if ($res !== true) {
1042 'An error occurred calling post contribution ' .
1043 "script:\n" . $es->getOutput(),
1046 $res = _T("Contribution information") . "\n";
1047 $res .= print_r($contrib, true);
1048 $res .= "\n\n" . _T("Script output") . "\n";
1049 $res .= $es->getOutput();
1055 * Get raw contribution type
1059 public function getRawType()
1061 if ($this->isCotis()) {
1062 return 'membership';
1069 * Get contribution type label
1073 public function getTypeLabel()
1075 if ($this->isCotis()) {
1076 return _T("Membership");
1078 return _T("Donation");
1083 * Get payment type label
1087 public function getPaymentType()
1089 if ($this->_payment_type
=== null) {
1093 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1094 return $ptype->getName(false);
1098 * Global getter method
1100 * @param string $name name of the property we want to retrive
1102 * @return false|object the called property
1104 public function __get($name)
1107 $forbidden = array('is_cotis');
1108 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1109 'raw_begin_date', 'raw_end_date'
1112 $rname = '_' . $name;
1114 if (in_array($name, $forbidden)) {
1116 "Call to __get for '$name' is forbidden!",
1122 return $this->isCotis();
1125 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1128 property_exists($this, $rname)
1129 ||
in_array($name, $virtuals)
1133 case 'raw_begin_date':
1134 case 'raw_end_date':
1135 $rname = '_' . substr($name, 4);
1136 if ($this->$rname != '') {
1138 $d = new \
DateTime($this->$rname);
1140 } catch (\Exception
$e) {
1141 //oops, we've got a bad date :/
1143 'Bad date (' . $this->$rname . ') | ' .
1154 if ($this->$rname != '') {
1156 $d = new \
DateTime($this->$rname);
1157 return $d->format(__("Y-m-d"));
1158 } catch (\Exception
$e) {
1159 //oops, we've got a bad date :/
1161 'Bad date (' . $this->$rname . ') | ' .
1165 return $this->$rname;
1170 if ($this->_is_cotis
) {
1171 $date_end = new \
DateTime($this->_end_date
);
1172 $date_start = new \
DateTime($this->_begin_date
);
1173 $diff = $date_end->diff($date_start);
1174 return $diff->format('%y') * 12 +
$diff->format('%m');
1179 case 'spayment_type':
1180 if ($this->_payment_type
=== null) {
1184 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1185 return $ptype->getName();
1189 if ($this->_is_cotis
=== null) {
1192 return ($this->isCotis()) ?
1193 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1196 return $this->$rname;
1201 "Unknown property '$rname'",
1209 * Global setter method
1211 * @param string $name name of the property we want to assign a value to
1212 * @param object $value a relevant value for the property
1216 public function __set($name, $value)
1218 global $preferences;
1220 $forbidden = array('fields', 'is_cotis', 'end_date');
1222 if (!in_array($name, $forbidden)) {
1223 $rname = '_' . $name;
1226 if (is_int($value)) {
1227 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1230 'Trying to set a transaction from an id that is not an integer.',
1236 if (is_int($value)) {
1238 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1239 //set is_cotis according to type
1240 if ($this->$rname->extension
== 1) {
1241 $this->_is_cotis
= true;
1243 $this->_is_cotis
= false;
1247 'Trying to set a type from an id that is not an integer.',
1254 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1256 throw new \
Exception('Incorrect format');
1258 $this->_begin_date
= $d->format('Y-m-d');
1259 } catch (\Exception
$e) {
1261 'Wrong date format. field: ' . $name .
1262 ', value: ' . $value . ', expected fmt: ' .
1263 __("Y-m-d") . ' | ' . $e->getMessage(),
1266 $this->errors
[] = str_replace(
1273 $this->_fields
['date_debut_cotis']['label']
1275 _T("- Wrong date format (%date_format) for %field!")
1280 if (is_numeric($value) && $value > 0) {
1281 $this->$rname = $value;
1284 'Trying to set an amount with a non numeric value, ' .
1285 'or with a zero value',
1291 if (is_int($value)) {
1293 $this->$rname = $value;
1296 case 'payment_type':
1297 $ptypes = new PaymentTypes(
1302 $list = $ptypes->getList();
1303 if (isset($list[$value])) {
1304 $this->_payment_type
= $value;
1307 'Unknown payment type ' . $value,
1314 '[' . __CLASS__
. ']: Trying to set an unknown property (' .