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
;
50 * Contribution class for galette
51 * Manage membership fees and donations.
56 * @author Johan Cwiklinski <johan@x-tnd.be>
57 * @copyright 2010-2021 The Galette Team
58 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
59 * @link http://galette.tuxfamily.org
60 * @since Available since 0.7dev - 2010-03-11
66 public const TABLE
= 'cotisations';
67 public const PK
= 'id_cotis';
69 public const TYPE_FEE
= 'fee';
70 public const TYPE_DONATION
= 'donation';
77 private $_payment_type;
78 private $_orig_amount;
82 private $_transaction = null;
86 //fields list and their translation
94 private $sendmail = false;
99 * @param Db $zdb Database
100 * @param Login $login Login instance
101 * @param null|int|ResultSet $args Either a ResultSet row to load
102 * a specific contribution, or an type id
103 * to just instantiate object
105 public function __construct(Db
$zdb, Login
$login, $args = null)
108 $this->login
= $login;
111 * Fields configuration. Each field is an array and must reflect:
114 * (string) property name
117 * I'd prefer a static private variable for this...
118 * But call to the _T function does not seem to be allowed there :/
120 $this->_fields
= array(
122 'label' => null, //not a field in the form
125 Adherent
::PK
=> array(
126 'label' => _T("Contributor:"),
127 'propname' => 'member'
129 ContributionsTypes
::PK
=> array(
130 'label' => _T("Contribution type:"),
133 'montant_cotis' => array(
134 'label' => _T("Amount:"),
135 'propname' => 'amount'
137 'type_paiement_cotis' => array(
138 'label' => _T("Payment type:"),
139 'propname' => 'payment_type'
141 'info_cotis' => array(
142 'label' => _T("Comments:"),
145 'date_enreg' => array(
146 'label' => null, //not a field in the form
149 'date_debut_cotis' => array(
150 'label' => _T("Date of contribution:"),
151 'cotlabel' => _T("Start date of membership:"), //if contribution is a membership fee, label differs
152 'propname' => 'begin_date'
154 'date_fin_cotis' => array(
155 'label' => _T("End date of membership:"),
156 'propname' => 'end_date'
158 Transaction
::PK
=> array(
159 'label' => null, //not a field in the form
160 'propname' => 'transaction'
162 //this one is not really a field, but is required in some cases...
163 //adding it here make simplier to check required fields
164 'duree_mois_cotis' => array(
165 'label' => _T("Membership extension:"),
166 'propname' => 'extension'
171 } elseif (is_array($args)) {
172 $this->_date
= date("Y-m-d");
173 if (isset($args['adh']) && $args['adh'] != '') {
174 $this->_member
= (int)$args['adh'];
176 if (isset($args['trans'])) {
177 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$args['trans']);
178 if (!isset($this->_member
)) {
179 $this->_member
= (int)$this->_transaction
->member
;
181 $this->_amount
= $this->_transaction
->getMissingAmount();
183 $this->type
= (int)$args['type'];
184 //calculate begin date for membership fee
185 $this->_begin_date
= $this->_date
;
186 if ($this->_is_cotis
) {
187 $curend = self
::getDueDate($this->zdb
, $this->_member
);
189 $dend = new \
DateTime($curend);
190 $now = date('Y-m-d');
191 $dnow = new \
DateTime($now);
193 // Member didn't renew on time
194 $this->_begin_date
= $now;
196 $this->_begin_date
= $curend;
199 $this->retrieveEndDate();
201 if (isset($args['payment_type'])) {
202 $this->_payment_type
= $args['payment_type'];
204 } elseif (is_object($args)) {
205 $this->loadFromRS($args);
208 $this->loadDynamicFields();
212 * Sets end contribution date
216 private function retrieveEndDate()
220 $bdate = new \
DateTime($this->_begin_date
);
221 if ($preferences->pref_beg_membership
!= '') {
222 //case beginning of membership
223 list($j, $m) = explode('/', $preferences->pref_beg_membership
);
224 $edate = new \
DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
225 while ($edate <= $bdate) {
226 $edate->modify('+1 year');
229 if ($preferences->pref_membership_offermonths
> 0) {
230 //count days until end of membership date
231 $diff1 = (int)$bdate->diff($edate)->format('%a');
233 //count days beetween end of membership date and offered months
234 $tdate = clone $edate;
235 $tdate->modify('-' . $preferences->pref_membership_offermonths
. ' month');
236 $diff2 = (int)$edate->diff($tdate)->format('%a');
238 //when number of days until end of membership is less than for offered months, it's free :)
239 if ($diff1 <= $diff2) {
240 $edate->modify('+1 year');
244 $this->_end_date
= $edate->format('Y-m-d');
245 } elseif ($preferences->pref_membership_ext
!= '') {
246 //case membership extension
247 if ($this->_extension
== null) {
248 $this->_extension
= $preferences->pref_membership_ext
;
250 $dext = new \
DateInterval('P' . $this->_extension
. 'M');
251 $edate = $bdate->add($dext);
252 $this->_end_date
= $edate->format('Y-m-d');
254 throw new \
RuntimeException(
255 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
261 * Loads a contribution from its id
263 * @param int $id the identifier for the contribution to load
265 * @return bool true if query succeed, false otherwise
267 public function load($id)
270 $select = $this->zdb
->select(self
::TABLE
);
271 $select->where(self
::PK
. ' = ' . $id);
272 //restrict query on current member id if he's not admin nor staff member
273 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
274 $select->where(Adherent
::PK
. ' = ' . $this->login
->id
);
277 $results = $this->zdb
->execute($select);
278 if ($results->count() > 0) {
279 $row = $results->current();
280 $this->loadFromRS($row);
283 throw new \
Exception(
284 'No contribution #' . $id . ' (user ' . $this->login
->id
. ')'
287 } catch (Throwable
$e) {
289 'An error occurred attempting to load contribution #' . $id .
298 * Populate object from a resultset row
300 * @param ResultSet $r the resultset row
304 private function loadFromRS($r)
307 $this->_id
= (int)$r->$pk;
308 $this->_date
= $r->date_enreg
;
309 $this->_amount
= $r->montant_cotis
;
310 //save original amount, we need it for transactions parts calculations
311 $this->_orig_amount
= $r->montant_cotis
;
312 $this->_payment_type
= $r->type_paiement_cotis
;
313 $this->_info
= $r->info_cotis
;
314 $this->_begin_date
= $r->date_debut_cotis
;
315 $enddate = $r->date_fin_cotis
;
316 //do not work with knows bad dates...
317 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
318 //strange date? don't know :(
320 $enddate !== '0000-00-00'
321 && $enddate !== '1901-01-01'
322 && $enddate !== '0001-01-01 BC'
324 $this->_end_date
= $r->date_fin_cotis
;
326 $adhpk = Adherent
::PK
;
327 $this->_member
= (int)$r->$adhpk;
329 $transpk = Transaction
::PK
;
330 if ($r->$transpk != '') {
331 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$r->$transpk);
334 $this->type
= (int)$r->id_type_cotis
;
335 $this->loadDynamicFields();
339 * Check posted values validity
341 * @param array $values All values to check, basically the $_POST array
342 * after sending the form
343 * @param array $required Array of required fields
344 * @param array $disabled Array of disabled fields
348 public function check($values, $required, $disabled)
351 $this->errors
= array();
353 $fields = array_keys($this->_fields
);
354 foreach ($fields as $key) {
355 //first, let's sanitize values
356 $key = strtolower($key);
357 $prop = '_' . $this->_fields
[$key]['propname'];
359 if (isset($values[$key])) {
360 $value = trim($values[$key]);
365 // if the field is enabled, check it
366 if (!isset($disabled[$key])) {
367 // fill up the adherent structure
368 //$this->$prop = stripslashes($value); //not relevant here!
370 // now, check validity
374 case 'date_debut_cotis':
375 case 'date_fin_cotis':
378 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
380 throw new \
Exception('Incorrect format');
382 $this->$prop = $d->format('Y-m-d');
383 } catch (Throwable
$e) {
385 'Wrong date format. field: ' . $key .
386 ', value: ' . $value . ', expected fmt: ' .
387 __("Y-m-d") . ' | ' . $e->getMessage(),
390 $this->errors
[] = str_replace(
397 $this->_fields
[$key]['label']
399 _T("- Wrong date format (%date_format) for %field!")
406 $this->_member
= (int)$value;
409 case ContributionsTypes
::PK
:
411 $this->type
= (int)$value;
414 case 'montant_cotis':
415 $this->_amount
= $value;
416 $value = strtr($value, ',', '.');
417 if (!is_numeric($value) && $value !== '') {
418 $this->errors
[] = _T("- The amount must be an integer!");
421 case 'type_paiement_cotis':
422 $ptypes = new PaymentTypes(
427 $ptlist = $ptypes->getList();
428 if (isset($ptlist[$value])) {
429 $this->_payment_type
= $value;
431 $this->errors
[] = _T("- Unknown payment type");
435 $this->_info
= $value;
437 case Transaction
::PK
:
439 $this->_transaction
= new Transaction($this->zdb
, $this->login
, (int)$value);
442 case 'duree_mois_cotis':
444 if (!is_numeric($value) ||
$value <= 0) {
445 $this->errors
[] = _T("- The duration must be a positive integer!");
447 $this->$prop = $value;
448 $this->retrieveEndDate();
455 // missing required fields?
456 foreach ($required as $key => $val) {
458 $prop = '_' . $this->_fields
[$key]['propname'];
460 !isset($disabled[$key])
461 && (!isset($this->$prop)
462 ||
(!is_object($this->$prop) && trim($this->$prop) == '')
463 ||
(is_object($this->$prop) && trim($this->$prop->id
) == ''))
465 $this->errors
[] = str_replace(
467 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
468 _T("- Mandatory field %field empty.")
474 if ($this->_transaction
!= null && $this->_amount
!= null) {
475 $missing = $this->_transaction
->getMissingAmount();
476 //calculate new missing amount
477 $missing = $missing +
$this->_orig_amount
- $this->_amount
;
479 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
483 if ($this->isFee() && count($this->errors
) == 0) {
484 $overlap = $this->checkOverlap();
485 if ($overlap !== true) {
486 if ($overlap === false) {
487 $this->errors
[] = _T("An error occurred checking overlapping fees :(");
489 //method directly return error message
490 $this->errors
[] = $overlap;
495 $this->dynamicsCheck($values, $required, $disabled);
497 if (count($this->errors
) > 0) {
499 'Some errors has been threw attempting to edit/store a contribution' .
500 print_r($this->errors
, true),
503 return $this->errors
;
506 'Contribution checked successfully.',
514 * Check that membership fees does not overlap
516 * @return boolean|string True if all is ok, false if error,
517 * error message if overlap
519 public function checkOverlap()
522 $select = $this->zdb
->select(self
::TABLE
, 'c');
524 array('date_debut_cotis', 'date_fin_cotis')
526 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
527 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
529 )->where(Adherent
::PK
. ' = ' . $this->_member
)
530 ->where(array('cotis_extension' => new Expression('true')))
532 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date
)
533 ->lessThan('date_debut_cotis', $this->_end_date
)
536 ->greaterThan('date_fin_cotis', $this->_begin_date
)
537 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date
);
539 if ($this->id
!= '') {
540 $select->where(self
::PK
. ' != ' . $this->id
);
543 $results = $this->zdb
->execute($select);
544 if ($results->count() > 0) {
545 $result = $results->current();
546 $d = new \
DateTime($result->date_debut_cotis
);
548 return _T("- Membership period overlaps period starting at ") .
549 $d->format(__("Y-m-d"));
552 } catch (Throwable
$e) {
554 'An error occurred checking overlapping fee. ' . $e->getMessage(),
562 * Store the contribution
566 public function store()
568 global $hist, $emitter;
572 if (count($this->errors
) > 0) {
573 throw new \
RuntimeException(
574 'Existing errors prevents storing contribution: ' .
575 print_r($this->errors
, true)
580 $this->zdb
->connection
->beginTransaction();
582 $fields = self
::getDbFields($this->zdb
);
583 foreach ($fields as $field) {
584 $prop = '_' . $this->_fields
[$field]['propname'];
586 case ContributionsTypes
::PK
:
587 case Transaction
::PK
:
588 if (isset($this->$prop)) {
589 $values[$field] = $this->$prop->id
;
593 $values[$field] = $this->$prop;
598 //no end date, let's take database defaults
599 if (!$this->isFee() && !$this->_end_date
) {
600 unset($values['date_fin_cotis']);
604 if (!isset($this->_id
) ||
$this->_id
== '') {
605 //we're inserting a new contribution
606 unset($values[self
::PK
]);
608 $insert = $this->zdb
->insert(self
::TABLE
);
609 $insert->values($values);
610 $add = $this->zdb
->execute($insert);
612 if ($add->count() > 0) {
613 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
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->isFee()) {
655 $deadline = $this->updateDeadline();
656 if ($deadline !== true) {
657 //if something went wrong, we roll back 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 (Throwable
$e) {
677 if ($this->zdb
->connection
->inTransaction()) {
678 $this->zdb
->connection
->rollBack();
685 * Update member dead line
689 private function updateDeadline()
692 $due_date = self
::getDueDate($this->zdb
, $this->_member
);
694 if ($due_date != '') {
695 $date_fin_update = $due_date;
697 $date_fin_update = new Expression('NULL');
700 $update = $this->zdb
->update(Adherent
::TABLE
);
702 array('date_echeance' => $date_fin_update)
704 Adherent
::PK
. '=' . $this->_member
706 $this->zdb
->execute($update);
708 } catch (Throwable
$e) {
710 'An error occurred updating member ' . $this->_member
.
720 * Remove contribution from database
722 * @param boolean $transaction Activate transaction mode (defaults to true)
726 public function remove($transaction = true)
732 $this->zdb
->connection
->beginTransaction();
735 $delete = $this->zdb
->delete(self
::TABLE
);
736 $delete->where(self
::PK
. ' = ' . $this->_id
);
737 $del = $this->zdb
->execute($delete);
738 if ($del->count() > 0) {
739 $this->updateDeadline();
740 $this->dynamicsRemove(true);
742 throw new \
RuntimeException(
743 'Contribution has not been removed!'
747 $this->zdb
->connection
->commit();
749 $emitter->emit('contribution.remove', $this);
751 } catch (Throwable
$e) {
753 $this->zdb
->connection
->rollBack();
756 'An error occurred trying to remove contribution #' .
757 $this->_id
. ' | ' . $e->getMessage(),
767 * @param string $field Field name
771 public function getFieldLabel($field)
773 $label = $this->_fields
[$field]['label'];
774 if ($this->isFee() && $field == 'date_debut_cotis') {
775 $label = $this->_fields
[$field]['cotlabel'];
778 $label = str_replace(' ', ' ', $label);
779 //remove trailing ':' and then trim
780 $label = trim(trim($label, ':'));
785 * Retrieve fields from database
787 * @param Db $zdb Database instance
791 public static function getDbFields(Db
$zdb)
793 $columns = $zdb->getColumns(self
::TABLE
);
795 foreach ($columns as $col) {
796 $fields[] = $col->getName();
802 * Get the relevant CSS class for current contribution
804 * @return string current contribution row class
806 public function getRowClass()
808 return ($this->_end_date
!= $this->_begin_date
&& $this->_is_cotis
) ?
809 'cotis-normal' : 'cotis-give';
813 * Retrieve member due date
815 * @param Db $zdb Database instance
816 * @param integer $member_id Member identifier
820 public static function getDueDate(Db
$zdb, $member_id)
826 $select = $zdb->select(self
::TABLE
, 'c');
829 'max_date' => new Expression('MAX(date_fin_cotis)')
832 array('ct' => PREFIX_DB
. ContributionsTypes
::TABLE
),
833 'c.' . ContributionsTypes
::PK
. '=ct.' . ContributionsTypes
::PK
,
836 Adherent
::PK
. ' = ' . $member_id
838 array('cotis_extension' => new Expression('true'))
841 $results = $zdb->execute($select);
842 $result = $results->current();
843 $due_date = $result->max_date
;
845 //avoid bad dates in postgres and bad mysql return from zenddb
846 if ($due_date == '0001-01-01 BC' ||
$due_date == '1901-01-01') {
850 } catch (Throwable
$e) {
852 'An error occurred trying to retrieve member\'s due date',
860 * Detach a contribution from a transaction
862 * @param Db $zdb Database instance
863 * @param Login $login Login instance
864 * @param int $trans_id Transaction identifier
865 * @param int $contrib_id Contribution identifier
869 public static function unsetTransactionPart(Db
$zdb, Login
$login, $trans_id, $contrib_id)
872 //first, we check if contribution is part of transaction
873 $c = new Contribution($zdb, $login, (int)$contrib_id);
874 if ($c->isTransactionPartOf($trans_id)) {
875 $update = $zdb->update(self
::TABLE
);
877 array(Transaction
::PK
=> null)
879 self
::PK
. ' = ' . $contrib_id
881 $zdb->execute($update);
885 'Contribution #' . $contrib_id .
886 ' is not actually part of transaction #' . $trans_id,
891 } catch (Throwable
$e) {
893 'Unable to detach contribution #' . $contrib_id .
894 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
902 * Set a contribution as a transaction part
904 * @param Db $zdb Database instance
905 * @param int $trans_id Transaction identifier
906 * @param int $contrib_id Contribution identifier
910 public static function setTransactionPart(Db
$zdb, $trans_id, $contrib_id)
913 $update = $zdb->update(self
::TABLE
);
915 array(Transaction
::PK
=> $trans_id)
916 )->where(self
::PK
. ' = ' . $contrib_id);
918 $zdb->execute($update);
920 } catch (Throwable
$e) {
922 'Unable to attach contribution #' . $contrib_id .
923 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
931 * Is current contribution a membership fee
935 public function isFee()
937 return $this->_is_cotis
;
941 * Is current contribution part of specified transaction
943 * @param int $id Transaction identifier
947 public function isTransactionPartOf($id)
949 if ($this->isTransactionPart()) {
950 return $id == $this->_transaction
->id
;
957 * Is current contribution part of transaction
961 public function isTransactionPart()
963 return $this->_transaction
!= null;
967 * Execute post contribution script
969 * @param ExternalScript $es External script to execute
970 * @param array $extra Extra information on contribution
972 * @param array $pextra Extra information on payment
975 * @return mixed Script return value on success, values and script output on fail
977 public function executePostScript(
985 'type' => $this->getPaymentType()
988 if ($pextra !== null && is_array($pextra)) {
989 $payment = array_merge($payment, $pextra);
992 if (!file_exists(GALETTE_CACHE_DIR
. '/pdf_contribs')) {
993 @mkdir
(GALETTE_CACHE_DIR
. '/pdf_contribs');
996 $voucher_path = null;
997 if ($this->_id
!== null) {
998 $voucher = new PdfContribution($this, $this->zdb
, $preferences);
999 $voucher->store(GALETTE_CACHE_DIR
. '/pdf_contribs');
1000 $voucher_path = $voucher->getPath();
1004 'id' => (int)$this->_id
,
1005 'date' => $this->_date
,
1006 'type' => $this->getRawType(),
1007 'amount' => $this->amount
,
1008 'voucher' => $voucher_path,
1009 'category' => array(
1010 'id' => $this->type
->id
,
1011 'label' => $this->type
->libelle
1013 'payment' => $payment
1016 if ($this->_member
!== null) {
1017 $m = new Adherent($this->zdb
, (int)$this->_member
);
1019 'id' => (int)$this->_member
,
1020 'name' => $m->sfullname
,
1021 'email' => $m->email
,
1022 'organization' => ($m->isCompany() ?
1 : 0),
1025 'label' => $m->sstatus
1027 'country' => $m->country
1030 if ($m->isCompany()) {
1031 $member['organization_name'] = $m->company_name
;
1034 $contrib['member'] = $member;
1037 if ($extra !== null && is_array($extra)) {
1038 $contrib = array_merge($contrib, $extra);
1041 $res = $es->send($contrib);
1043 if ($res !== true) {
1045 'An error occurred calling post contribution ' .
1046 "script:\n" . $es->getOutput(),
1049 $res = _T("Contribution information") . "\n";
1050 $res .= print_r($contrib, true);
1051 $res .= "\n\n" . _T("Script output") . "\n";
1052 $res .= $es->getOutput();
1058 * Get raw contribution type
1062 public function getRawType()
1064 if ($this->isFee()) {
1065 return 'membership';
1072 * Get contribution type label
1076 public function getTypeLabel()
1078 if ($this->isFee()) {
1079 return _T("Membership");
1081 return _T("Donation");
1086 * Get payment type label
1090 public function getPaymentType()
1092 if ($this->_payment_type
=== null) {
1096 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1097 return $ptype->getName(false);
1101 * Global getter method
1103 * @param string $name name of the property we want to retrieve
1105 * @return false|object the called property
1107 public function __get($name)
1110 $forbidden = array('is_cotis');
1111 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1112 'raw_begin_date', 'raw_end_date'
1115 $rname = '_' . $name;
1117 if (in_array($name, $forbidden)) {
1119 "Call to __get for '$name' is forbidden!",
1125 return $this->isFee();
1128 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1131 property_exists($this, $rname)
1132 ||
in_array($name, $virtuals)
1136 case 'raw_begin_date':
1137 case 'raw_end_date':
1138 $rname = '_' . substr($name, 4);
1139 if ($this->$rname != '') {
1141 $d = new \
DateTime($this->$rname);
1143 } catch (Throwable
$e) {
1144 //oops, we've got a bad date :/
1146 'Bad date (' . $this->$rname . ') | ' .
1157 if ($this->$rname != '') {
1159 $d = new \
DateTime($this->$rname);
1160 return $d->format(__("Y-m-d"));
1161 } catch (Throwable
$e) {
1162 //oops, we've got a bad date :/
1164 'Bad date (' . $this->$rname . ') | ' .
1168 return $this->$rname;
1173 if ($this->_is_cotis
) {
1174 $date_end = new \
DateTime($this->_end_date
);
1175 $date_start = new \
DateTime($this->_begin_date
);
1176 $diff = $date_end->diff($date_start);
1177 return $diff->format('%y') * 12 +
$diff->format('%m');
1182 case 'spayment_type':
1183 if ($this->_payment_type
=== null) {
1187 $ptype = new PaymentType($this->zdb
, (int)$this->payment_type
);
1188 return $ptype->getName();
1192 if ($this->_is_cotis
=== null) {
1195 return ($this->isFee()) ?
1196 PdfModel
::INVOICE_MODEL
: PdfModel
::RECEIPT_MODEL
;
1199 return $this->$rname;
1204 "Unknown property '$rname'",
1212 * Global setter method
1214 * @param string $name name of the property we want to assign a value to
1215 * @param object $value a relevant value for the property
1219 public function __set($name, $value)
1221 global $preferences;
1223 $forbidden = array('fields', 'is_cotis', 'end_date');
1225 if (!in_array($name, $forbidden)) {
1226 $rname = '_' . $name;
1229 if (is_int($value)) {
1230 $this->$rname = new Transaction($this->zdb
, $this->login
, $value);
1233 'Trying to set a transaction from an id that is not an integer.',
1239 if (is_int($value)) {
1241 $this->$rname = new ContributionsTypes($this->zdb
, $value);
1242 //set is_cotis according to type
1243 if ($this->$rname->extension
== 1) {
1244 $this->_is_cotis
= true;
1246 $this->_is_cotis
= false;
1250 'Trying to set a type from an id that is not an integer.',
1257 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1259 throw new \
Exception('Incorrect format');
1261 $this->_begin_date
= $d->format('Y-m-d');
1262 } catch (Throwable
$e) {
1264 'Wrong date format. field: ' . $name .
1265 ', value: ' . $value . ', expected fmt: ' .
1266 __("Y-m-d") . ' | ' . $e->getMessage(),
1269 $this->errors
[] = str_replace(
1276 $this->_fields
['date_debut_cotis']['label']
1278 _T("- Wrong date format (%date_format) for %field!")
1283 if (is_numeric($value) && $value > 0) {
1284 $this->$rname = $value;
1287 'Trying to set an amount with a non numeric value, ' .
1288 'or with a zero value',
1294 if (is_int($value)) {
1296 $this->$rname = $value;
1299 case 'payment_type':
1300 $ptypes = new PaymentTypes(
1305 $list = $ptypes->getList();
1306 if (isset($list[$value])) {
1307 $this->_payment_type
= $value;
1310 'Unknown payment type ' . $value,
1317 '[' . __CLASS__
. ']: Trying to set an unknown property (' .
1327 * Flag creation mail sending
1329 * @param boolean $send True (default) to send creation email
1331 * @return Contribution
1333 public function setSendmail($send = true)
1335 $this->sendmail
= $send;
1340 * Should we send administrative emails to member?
1344 public function sendEMail()
1346 return $this->sendmail
;
1350 * Handle files (dynamics files)
1352 * @param array $files Files sent
1354 * @return array|true
1356 public function handleFiles($files)
1360 $this->dynamicsFiles($files);
1362 if (count($this->errors
) > 0) {
1364 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1365 print_r($this->errors
, true),
1368 return $this->errors
;
1375 * Get required fields list
1379 public function getRequired(): array
1382 'id_type_cotis' => 1,
1385 'date_debut_cotis' => 1,
1386 'date_fin_cotis' => $this->isFee(),
1387 'montant_cotis' => $this->isFee() ?
1 : 0