]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
Merge branch 'release/0.9.5.2'
[galette.git] / galette / lib / Galette / Entity / Contribution.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Contribution class for galette
7 * Manage membership fees and donations.
8 *
9 * PHP version 5
10 *
11 * Copyright © 2010-2021 The Galette Team
12 *
13 * This file is part of Galette (http://galette.tuxfamily.org).
14 *
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.
19 *
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.
24 *
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/>.
27 *
28 * @category Entity
29 * @package Galette
30 *
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
36 */
37
38 namespace Galette\Entity;
39
40 use Throwable;
41 use Analog\Analog;
42 use Laminas\Db\Sql\Expression;
43 use Galette\Core\Db;
44 use Galette\Core\Login;
45 use Galette\IO\ExternalScript;
46 use Galette\IO\PdfContribution;
47 use Galette\Repository\PaymentTypes;
48 use Galette\Features\Dynamics;
49
50 /**
51 * Contribution class for galette
52 * Manage membership fees and donations.
53 *
54 * @category Entity
55 * @name Contribution
56 * @package Galette
57 * @author Johan Cwiklinski <johan@x-tnd.be>
58 * @copyright 2010-2021 The Galette Team
59 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
60 * @link http://galette.tuxfamily.org
61 * @since Available since 0.7dev - 2010-03-11
62 *
63 * @property integer $id
64 * @property string $date
65 * @property DateTime $raw_date
66 * @property integer $member
67 * @property ContributionsTypes $type
68 * @property integer $amount
69 * @property integer $payment_type
70 * @property integer $orig_amount
71 * @property string $info
72 * @property string $begin_date
73 * @property DateTime $raw_begin_date
74 * @property string $end_date
75 * @property DateTime $raw_end_date
76 * @property Transaction|null $transaction
77 * @property integer $extension
78 * @property integer $duration
79 * @property string $spayment_type
80 * @property integer $model
81 */
82 class Contribution
83 {
84 use Dynamics;
85
86 public const TABLE = 'cotisations';
87 public const PK = 'id_cotis';
88
89 public const TYPE_FEE = 'fee';
90 public const TYPE_DONATION = 'donation';
91
92 private $_id;
93 private $_date;
94 private $_member;
95 private $_type;
96 private $_amount;
97 private $_payment_type;
98 private $_orig_amount;
99 private $_info;
100 private $_begin_date;
101 private $_end_date;
102 private $_transaction = null;
103 private $_is_cotis;
104 private $_extension;
105
106 //fields list and their translation
107 private $_fields;
108
109 /** @var Db */
110 private $zdb;
111 /** @var Login */
112 private $login;
113 /** @var array */
114 private $errors;
115
116 private $sendmail = false;
117
118 /**
119 * Default constructor
120 *
121 * @param Db $zdb Database
122 * @param Login $login Login instance
123 * @param null|int|ResultSet $args Either a ResultSet row to load
124 * a specific contribution, or an type id
125 * to just instantiate object
126 */
127 public function __construct(Db $zdb, Login $login, $args = null)
128 {
129 $this->zdb = $zdb;
130 $this->login = $login;
131
132 global $preferences;
133 $this->_payment_type = (int)$preferences->pref_default_paymenttype;
134
135 /*
136 * Fields configuration. Each field is an array and must reflect:
137 * array(
138 * (string)label,
139 * (string) property name
140 * )
141 *
142 * I'd prefer a static private variable for this...
143 * But call to the _T function does not seem to be allowed there :/
144 */
145 $this->_fields = array(
146 'id_cotis' => array(
147 'label' => null, //not a field in the form
148 'propname' => 'id'
149 ),
150 Adherent::PK => array(
151 'label' => _T("Contributor:"),
152 'propname' => 'member'
153 ),
154 ContributionsTypes::PK => array(
155 'label' => _T("Contribution type:"),
156 'propname' => 'type'
157 ),
158 'montant_cotis' => array(
159 'label' => _T("Amount:"),
160 'propname' => 'amount'
161 ),
162 'type_paiement_cotis' => array(
163 'label' => _T("Payment type:"),
164 'propname' => 'payment_type'
165 ),
166 'info_cotis' => array(
167 'label' => _T("Comments:"),
168 'propname' => 'info'
169 ),
170 'date_enreg' => array(
171 'label' => null, //not a field in the form
172 'propname' => 'date'
173 ),
174 'date_debut_cotis' => array(
175 'label' => _T("Date of contribution:"),
176 'cotlabel' => _T("Start date of membership:"), //if contribution is a membership fee, label differs
177 'propname' => 'begin_date'
178 ),
179 'date_fin_cotis' => array(
180 'label' => _T("End date of membership:"),
181 'propname' => 'end_date'
182 ),
183 Transaction::PK => array(
184 'label' => null, //not a field in the form
185 'propname' => 'transaction'
186 ),
187 //this one is not really a field, but is required in some cases...
188 //adding it here make simplier to check required fields
189 'duree_mois_cotis' => array(
190 'label' => _T("Membership extension:"),
191 'propname' => 'extension'
192 )
193 );
194 if (is_int($args)) {
195 $this->load($args);
196 } elseif (is_array($args)) {
197 $this->_date = date("Y-m-d");
198 if (isset($args['adh']) && $args['adh'] != '') {
199 $this->_member = (int)$args['adh'];
200 }
201 if (isset($args['trans'])) {
202 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$args['trans']);
203 if (!isset($this->_member)) {
204 $this->_member = (int)$this->_transaction->member;
205 }
206 $this->_amount = $this->_transaction->getMissingAmount();
207 }
208 $this->type = (int)$args['type'];
209 //calculate begin date for membership fee
210 $this->_begin_date = $this->_date;
211 if ($this->_is_cotis) {
212 $curend = self::getDueDate($this->zdb, $this->_member);
213 if ($curend != '') {
214 $dend = new \DateTime($curend);
215 $now = date('Y-m-d');
216 $dnow = new \DateTime($now);
217 if ($dend < $dnow) {
218 // Member didn't renew on time
219 $this->_begin_date = $now;
220 } else {
221 $this->_begin_date = $curend;
222 }
223 }
224 $this->retrieveEndDate();
225 }
226 if (isset($args['payment_type'])) {
227 $this->_payment_type = $args['payment_type'];
228 }
229 } elseif (is_object($args)) {
230 $this->loadFromRS($args);
231 }
232
233 $this->loadDynamicFields();
234 }
235
236 /**
237 * Sets end contribution date
238 *
239 * @return void
240 */
241 private function retrieveEndDate()
242 {
243 global $preferences;
244
245 $bdate = new \DateTime($this->_begin_date);
246 if ($preferences->pref_beg_membership != '') {
247 //case beginning of membership
248 list($j, $m) = explode('/', $preferences->pref_beg_membership);
249 $edate = new \DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
250 while ($edate <= $bdate) {
251 $edate->modify('+1 year');
252 }
253
254 if ($preferences->pref_membership_offermonths > 0) {
255 //count days until end of membership date
256 $diff1 = (int)$bdate->diff($edate)->format('%a');
257
258 //count days beetween end of membership date and offered months
259 $tdate = clone $edate;
260 $tdate->modify('-' . $preferences->pref_membership_offermonths . ' month');
261 $diff2 = (int)$edate->diff($tdate)->format('%a');
262
263 //when number of days until end of membership is less than for offered months, it's free :)
264 if ($diff1 <= $diff2) {
265 $edate->modify('+1 year');
266 }
267 }
268
269 $this->_end_date = $edate->format('Y-m-d');
270 } elseif ($preferences->pref_membership_ext != '') {
271 //case membership extension
272 if ($this->_extension == null) {
273 $this->_extension = $preferences->pref_membership_ext;
274 }
275 $dext = new \DateInterval('P' . $this->_extension . 'M');
276 $edate = $bdate->add($dext);
277 $this->_end_date = $edate->format('Y-m-d');
278 } else {
279 throw new \RuntimeException(
280 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
281 );
282 }
283 }
284
285 /**
286 * Loads a contribution from its id
287 *
288 * @param int $id the identifier for the contribution to load
289 *
290 * @return bool true if query succeed, false otherwise
291 */
292 public function load($id)
293 {
294 try {
295 $select = $this->zdb->select(self::TABLE, 'c');
296 $select->join(
297 array('a' => PREFIX_DB . Adherent::TABLE),
298 'c.' . Adherent::PK . '=a.' . Adherent::PK,
299 array()
300 );
301 //restrict query on current member id if he's not admin nor staff member
302 if (!$this->login->isAdmin() && !$this->login->isStaff()) {
303 if (!$this->login->isLogged()) {
304 Analog::log(
305 'Non-logged-in users cannot load contribution id `' . $id,
306 Analog::ERROR
307 );
308 return false;
309 }
310 if (!$this->login->isGroupManager()) {
311 $select->where
312 ->nest()
313 ->equalTo('a.' . Adherent::PK, $this->login->id)
314 ->or
315 ->equalTo('a.parent_id', $this->login->id)
316 ->unnest()
317 ->and
318 ->equalTo('c.' . self::PK, $id)
319 ;
320 } else {
321 $select->where([
322 Adherent::PK => $this->login->id,
323 self::PK => $id
324 ]);
325 }
326 } else {
327 $select->where->equalTo(self::PK, $id);
328 }
329
330 $results = $this->zdb->execute($select);
331 if ($results->count() > 0) {
332 $row = $results->current();
333 $this->loadFromRS($row);
334 return true;
335 } else {
336 Analog::log(
337 'No contribution #' . $id . ' (user ' . $this->login->id . ')',
338 Analog::ERROR
339 );
340 return false;
341 }
342 } catch (Throwable $e) {
343 Analog::log(
344 'An error occurred attempting to load contribution #' . $id .
345 $e->getMessage(),
346 Analog::ERROR
347 );
348 throw $e;
349 }
350 }
351
352 /**
353 * Populate object from a resultset row
354 *
355 * @param ResultSet $r the resultset row
356 *
357 * @return void
358 */
359 private function loadFromRS($r)
360 {
361 $pk = self::PK;
362 $this->_id = (int)$r->$pk;
363 $this->_date = $r->date_enreg;
364 $this->_amount = (int)$r->montant_cotis;
365 //save original amount, we need it for transactions parts calculations
366 $this->_orig_amount = (int)$r->montant_cotis;
367 $this->_payment_type = $r->type_paiement_cotis;
368 $this->_info = $r->info_cotis;
369 $this->_begin_date = $r->date_debut_cotis;
370 $enddate = $r->date_fin_cotis;
371 //do not work with knows bad dates...
372 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
373 //strange date? don't know :(
374 if (
375 $enddate !== '0000-00-00'
376 && $enddate !== '1901-01-01'
377 && $enddate !== '0001-01-01 BC'
378 ) {
379 $this->_end_date = $r->date_fin_cotis;
380 }
381 $adhpk = Adherent::PK;
382 $this->_member = (int)$r->$adhpk;
383
384 $transpk = Transaction::PK;
385 if ($r->$transpk != '') {
386 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$r->$transpk);
387 }
388
389 $this->type = (int)$r->id_type_cotis;
390 $this->loadDynamicFields();
391 }
392
393 /**
394 * Check posted values validity
395 *
396 * @param array $values All values to check, basically the $_POST array
397 * after sending the form
398 * @param array $required Array of required fields
399 * @param array $disabled Array of disabled fields
400 *
401 * @return true|array
402 */
403 public function check($values, $required, $disabled)
404 {
405 global $preferences;
406 $this->errors = array();
407
408 $fields = array_keys($this->_fields);
409 foreach ($fields as $key) {
410 //first, let's sanitize values
411 $key = strtolower($key);
412 $prop = '_' . $this->_fields[$key]['propname'];
413
414 if (isset($values[$key])) {
415 $value = trim($values[$key]);
416 } else {
417 $value = '';
418 }
419
420 // if the field is enabled, check it
421 if (!isset($disabled[$key])) {
422 // fill up the adherent structure
423 //$this->$prop = stripslashes($value); //not relevant here!
424
425 // now, check validity
426 switch ($key) {
427 // dates
428 case 'date_enreg':
429 case 'date_debut_cotis':
430 case 'date_fin_cotis':
431 if ($value != '') {
432 try {
433 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
434 if ($d === false) {
435 throw new \Exception('Incorrect format');
436 }
437 $this->$prop = $d->format('Y-m-d');
438 } catch (Throwable $e) {
439 Analog::log(
440 'Wrong date format. field: ' . $key .
441 ', value: ' . $value . ', expected fmt: ' .
442 __("Y-m-d") . ' | ' . $e->getMessage(),
443 Analog::INFO
444 );
445 $this->errors[] = str_replace(
446 array(
447 '%date_format',
448 '%field'
449 ),
450 array(
451 __("Y-m-d"),
452 $this->_fields[$key]['label']
453 ),
454 _T("- Wrong date format (%date_format) for %field!")
455 );
456 }
457 }
458 break;
459 case Adherent::PK:
460 if ($value != '') {
461 $this->_member = (int)$value;
462 }
463 break;
464 case ContributionsTypes::PK:
465 if ($value != '') {
466 $this->type = (int)$value;
467 }
468 break;
469 case 'montant_cotis':
470 $this->_amount = $value;
471 $value = strtr($value, ',', '.');
472 if (!is_numeric($value) && $value !== '') {
473 $this->errors[] = _T("- The amount must be an integer!");
474 }
475 break;
476 case 'type_paiement_cotis':
477 $ptypes = new PaymentTypes(
478 $this->zdb,
479 $preferences,
480 $this->login
481 );
482 $ptlist = $ptypes->getList();
483 if (isset($ptlist[$value])) {
484 $this->_payment_type = $value;
485 } else {
486 $this->errors[] = _T("- Unknown payment type");
487 }
488 break;
489 case 'info_cotis':
490 $this->_info = $value;
491 break;
492 case Transaction::PK:
493 if ($value != '') {
494 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$value);
495 }
496 break;
497 case 'duree_mois_cotis':
498 if ($value != '') {
499 if (!is_numeric($value) || $value <= 0) {
500 $this->errors[] = _T("- The duration must be a positive integer!");
501 }
502 $this->$prop = $value;
503 $this->retrieveEndDate();
504 }
505 break;
506 }
507 }
508 }
509
510 // missing required fields?
511 foreach ($required as $key => $val) {
512 if ($val === 1) {
513 $prop = '_' . $this->_fields[$key]['propname'];
514 if (
515 !isset($disabled[$key])
516 && (!isset($this->$prop)
517 || (!is_object($this->$prop) && trim($this->$prop) == '')
518 || (is_object($this->$prop) && trim($this->$prop->id) == ''))
519 ) {
520 $this->errors[] = str_replace(
521 '%field',
522 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
523 _T("- Mandatory field %field empty.")
524 );
525 }
526 }
527 }
528
529 if ($this->_transaction != null && $this->_amount != null) {
530 $missing = $this->_transaction->getMissingAmount();
531 //calculate new missing amount
532 $missing = $missing + $this->_orig_amount - $this->_amount;
533 if ($missing < 0) {
534 $this->errors[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
535 }
536 }
537
538 if ($this->isFee() && count($this->errors) == 0) {
539 $overlap = $this->checkOverlap();
540 if ($overlap !== true) {
541 //method directly return error message
542 $this->errors[] = $overlap;
543 }
544 }
545
546 $this->dynamicsCheck($values, $required, $disabled);
547
548 if (count($this->errors) > 0) {
549 Analog::log(
550 'Some errors has been threw attempting to edit/store a contribution' .
551 print_r($this->errors, true),
552 Analog::ERROR
553 );
554 return $this->errors;
555 } else {
556 Analog::log(
557 'Contribution checked successfully.',
558 Analog::DEBUG
559 );
560 return true;
561 }
562 }
563
564 /**
565 * Check that membership fees does not overlap
566 *
567 * @return boolean|string True if all is ok, false if error,
568 * error message if overlap
569 */
570 public function checkOverlap()
571 {
572 try {
573 $select = $this->zdb->select(self::TABLE, 'c');
574 $select->columns(
575 array('date_debut_cotis', 'date_fin_cotis')
576 )->join(
577 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
578 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
579 array()
580 )->where(Adherent::PK . ' = ' . $this->_member)
581 ->where(array('cotis_extension' => new Expression('true')))
582 ->where->nest->nest
583 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date)
584 ->lessThan('date_debut_cotis', $this->_end_date)
585 ->unnest
586 ->or->nest
587 ->greaterThan('date_fin_cotis', $this->_begin_date)
588 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date);
589
590 if ($this->id != '') {
591 $select->where(self::PK . ' != ' . $this->id);
592 }
593
594 $results = $this->zdb->execute($select);
595 if ($results->count() > 0) {
596 $result = $results->current();
597 $d = new \DateTime($result->date_debut_cotis);
598
599 return _T("- Membership period overlaps period starting at ") .
600 $d->format(__("Y-m-d"));
601 }
602 return true;
603 } catch (Throwable $e) {
604 Analog::log(
605 'An error occurred checking overlapping fee. ' . $e->getMessage(),
606 Analog::ERROR
607 );
608 throw $e;
609 }
610 }
611
612 /**
613 * Store the contribution
614 *
615 * @return boolean
616 */
617 public function store()
618 {
619 global $hist, $emitter;
620
621 $event = null;
622
623 if (count($this->errors) > 0) {
624 throw new \RuntimeException(
625 'Existing errors prevents storing contribution: ' .
626 print_r($this->errors, true)
627 );
628 }
629
630 try {
631 $this->zdb->connection->beginTransaction();
632 $values = array();
633 $fields = self::getDbFields($this->zdb);
634 foreach ($fields as $field) {
635 $prop = '_' . $this->_fields[$field]['propname'];
636 switch ($field) {
637 case ContributionsTypes::PK:
638 case Transaction::PK:
639 if (isset($this->$prop)) {
640 $values[$field] = $this->$prop->id;
641 }
642 break;
643 default:
644 $values[$field] = $this->$prop;
645 break;
646 }
647 }
648
649 //no end date, let's take database defaults
650 if (!$this->isFee() && !$this->_end_date) {
651 unset($values['date_fin_cotis']);
652 }
653
654 $success = false;
655 if (!isset($this->_id) || $this->_id == '') {
656 //we're inserting a new contribution
657 unset($values[self::PK]);
658
659 $insert = $this->zdb->insert(self::TABLE);
660 $insert->values($values);
661 $add = $this->zdb->execute($insert);
662
663 if ($add->count() > 0) {
664 $this->_id = $this->zdb->getLastGeneratedValue($this);
665
666 // logging
667 $hist->add(
668 _T("Contribution added"),
669 Adherent::getSName($this->zdb, $this->_member)
670 );
671 $success = true;
672 $event = 'contribution.add';
673 } else {
674 $hist->add(_T("Fail to add new contribution."));
675 throw new \Exception(
676 'An error occurred inserting new contribution!'
677 );
678 }
679 } else {
680 //we're editing an existing contribution
681 $update = $this->zdb->update(self::TABLE);
682 $update->set($values)->where(
683 self::PK . '=' . $this->_id
684 );
685 $edit = $this->zdb->execute($update);
686
687 //edit == 0 does not mean there were an error, but that there
688 //were nothing to change
689 if ($edit->count() > 0) {
690 $hist->add(
691 _T("Contribution updated"),
692 Adherent::getSName($this->zdb, $this->_member)
693 );
694 }
695
696 if ($edit === false) {
697 throw new \Exception(
698 'An error occurred updating contribution # ' . $this->_id . '!'
699 );
700 }
701 $success = true;
702 $event = 'contribution.edit';
703 }
704 //update deadline
705 if ($this->isFee()) {
706 $this->updateDeadline();
707 }
708
709 //dynamic fields
710 if ($success) {
711 $success = $this->dynamicsStore(true);
712 }
713
714 $this->zdb->connection->commit();
715 $this->_orig_amount = $this->_amount;
716
717 //send event at the end of process, once all has been stored
718 if ($event !== null) {
719 $emitter->emit($event, $this);
720 }
721
722 return true;
723 } catch (Throwable $e) {
724 if ($this->zdb->connection->inTransaction()) {
725 $this->zdb->connection->rollBack();
726 }
727 throw $e;
728 }
729 }
730
731 /**
732 * Update member dead line
733 *
734 * @return boolean
735 */
736 private function updateDeadline()
737 {
738 try {
739 $due_date = self::getDueDate($this->zdb, $this->_member);
740
741 if ($due_date != '') {
742 $date_fin_update = $due_date;
743 } else {
744 $date_fin_update = new Expression('NULL');
745 }
746
747 $update = $this->zdb->update(Adherent::TABLE);
748 $update->set(
749 array('date_echeance' => $date_fin_update)
750 )->where(
751 Adherent::PK . '=' . $this->_member
752 );
753 $this->zdb->execute($update);
754 return true;
755 } catch (Throwable $e) {
756 Analog::log(
757 'An error occurred updating member ' . $this->_member .
758 '\'s deadline |' .
759 $e->getMessage(),
760 Analog::ERROR
761 );
762 throw $e;
763 }
764 }
765
766 /**
767 * Remove contribution from database
768 *
769 * @param boolean $transaction Activate transaction mode (defaults to true)
770 *
771 * @return boolean
772 */
773 public function remove($transaction = true)
774 {
775 global $emitter;
776
777 try {
778 if ($transaction) {
779 $this->zdb->connection->beginTransaction();
780 }
781
782 $delete = $this->zdb->delete(self::TABLE);
783 $delete->where(self::PK . ' = ' . $this->_id);
784 $del = $this->zdb->execute($delete);
785 if ($del->count() > 0) {
786 $this->updateDeadline();
787 $this->dynamicsRemove(true);
788 } else {
789 Analog::log(
790 'Contribution has not been removed!',
791 Analog::WARNING
792 );
793 return false;
794 }
795 if ($transaction) {
796 $this->zdb->connection->commit();
797 }
798 $emitter->emit('contribution.remove', $this);
799 return true;
800 } catch (Throwable $e) {
801 if ($transaction) {
802 $this->zdb->connection->rollBack();
803 }
804 Analog::log(
805 'An error occurred trying to remove contribution #' .
806 $this->_id . ' | ' . $e->getMessage(),
807 Analog::ERROR
808 );
809 throw $e;
810 }
811 }
812
813 /**
814 * Get field label
815 *
816 * @param string $field Field name
817 *
818 * @return string
819 */
820 public function getFieldLabel($field)
821 {
822 $label = $this->_fields[$field]['label'];
823 if ($this->isFee() && $field == 'date_debut_cotis') {
824 $label = $this->_fields[$field]['cotlabel'];
825 }
826 //replace "&nbsp;"
827 $label = str_replace('&nbsp;', ' ', $label);
828 //remove trailing ':' and then trim
829 $label = trim(trim($label, ':'));
830 return $label;
831 }
832
833 /**
834 * Retrieve fields from database
835 *
836 * @param Db $zdb Database instance
837 *
838 * @return array
839 */
840 public static function getDbFields(Db $zdb)
841 {
842 $columns = $zdb->getColumns(self::TABLE);
843 $fields = array();
844 foreach ($columns as $col) {
845 $fields[] = $col->getName();
846 }
847 return $fields;
848 }
849
850 /**
851 * Get the relevant CSS class for current contribution
852 *
853 * @return string current contribution row class
854 */
855 public function getRowClass()
856 {
857 return ($this->_end_date != $this->_begin_date && $this->_is_cotis) ?
858 'cotis-normal' : 'cotis-give';
859 }
860
861 /**
862 * Retrieve member due date
863 *
864 * @param Db $zdb Database instance
865 * @param integer $member_id Member identifier
866 *
867 * @return date
868 */
869 public static function getDueDate(Db $zdb, $member_id)
870 {
871 if (!$member_id) {
872 return '';
873 }
874 try {
875 $select = $zdb->select(self::TABLE, 'c');
876 $select->columns(
877 array(
878 'max_date' => new Expression('MAX(date_fin_cotis)')
879 )
880 )->join(
881 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
882 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
883 array()
884 )->where(
885 Adherent::PK . ' = ' . $member_id
886 )->where(
887 array('cotis_extension' => new Expression('true'))
888 );
889
890 $results = $zdb->execute($select);
891 $result = $results->current();
892 $due_date = $result->max_date;
893
894 //avoid bad dates in postgres and bad mysql return from zenddb
895 if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
896 $due_date = '';
897 }
898 return $due_date;
899 } catch (Throwable $e) {
900 Analog::log(
901 'An error occurred trying to retrieve member\'s due date',
902 Analog::ERROR
903 );
904 throw $e;
905 }
906 }
907
908 /**
909 * Detach a contribution from a transaction
910 *
911 * @param Db $zdb Database instance
912 * @param Login $login Login instance
913 * @param int $trans_id Transaction identifier
914 * @param int $contrib_id Contribution identifier
915 *
916 * @return boolean
917 */
918 public static function unsetTransactionPart(Db $zdb, Login $login, $trans_id, $contrib_id)
919 {
920 try {
921 //first, we check if contribution is part of transaction
922 $c = new Contribution($zdb, $login, (int)$contrib_id);
923 if ($c->isTransactionPartOf($trans_id)) {
924 $update = $zdb->update(self::TABLE);
925 $update->set(
926 array(Transaction::PK => null)
927 )->where(
928 self::PK . ' = ' . $contrib_id
929 );
930 $zdb->execute($update);
931 return true;
932 } else {
933 Analog::log(
934 'Contribution #' . $contrib_id .
935 ' is not actually part of transaction #' . $trans_id,
936 Analog::WARNING
937 );
938 return false;
939 }
940 } catch (Throwable $e) {
941 Analog::log(
942 'Unable to detach contribution #' . $contrib_id .
943 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
944 Analog::ERROR
945 );
946 throw $e;
947 }
948 }
949
950 /**
951 * Set a contribution as a transaction part
952 *
953 * @param Db $zdb Database instance
954 * @param int $trans_id Transaction identifier
955 * @param int $contrib_id Contribution identifier
956 *
957 * @return boolean
958 */
959 public static function setTransactionPart(Db $zdb, $trans_id, $contrib_id)
960 {
961 try {
962 $update = $zdb->update(self::TABLE);
963 $update->set(
964 array(Transaction::PK => $trans_id)
965 )->where(self::PK . ' = ' . $contrib_id);
966
967 $zdb->execute($update);
968 return true;
969 } catch (Throwable $e) {
970 Analog::log(
971 'Unable to attach contribution #' . $contrib_id .
972 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
973 Analog::ERROR
974 );
975 throw $e;
976 }
977 }
978
979 /**
980 * Is current contribution a membership fee
981 *
982 * @return boolean
983 */
984 public function isFee()
985 {
986 return $this->_is_cotis;
987 }
988
989 /**
990 * Is current contribution part of specified transaction
991 *
992 * @param int $id Transaction identifier
993 *
994 * @return boolean
995 */
996 public function isTransactionPartOf($id)
997 {
998 if ($this->isTransactionPart()) {
999 return $id == $this->_transaction->id;
1000 } else {
1001 return false;
1002 }
1003 }
1004
1005 /**
1006 * Is current contribution part of transaction
1007 *
1008 * @return boolean
1009 */
1010 public function isTransactionPart()
1011 {
1012 return $this->_transaction != null;
1013 }
1014
1015 /**
1016 * Execute post contribution script
1017 *
1018 * @param ExternalScript $es External script to execute
1019 * @param array $extra Extra information on contribution
1020 * Defaults to null
1021 * @param array $pextra Extra information on payment
1022 * Defaults to null
1023 *
1024 * @return mixed Script return value on success, values and script output on fail
1025 */
1026 public function executePostScript(
1027 ExternalScript $es,
1028 $extra = null,
1029 $pextra = null
1030 ) {
1031 global $preferences;
1032
1033 $payment = array(
1034 'type' => $this->getPaymentType()
1035 );
1036
1037 if ($pextra !== null && is_array($pextra)) {
1038 $payment = array_merge($payment, $pextra);
1039 }
1040
1041 if (!file_exists(GALETTE_CACHE_DIR . '/pdf_contribs')) {
1042 @mkdir(GALETTE_CACHE_DIR . '/pdf_contribs');
1043 }
1044
1045 $voucher_path = null;
1046 if ($this->_id !== null) {
1047 $voucher = new PdfContribution($this, $this->zdb, $preferences);
1048 $voucher->store(GALETTE_CACHE_DIR . '/pdf_contribs');
1049 $voucher_path = $voucher->getPath();
1050 }
1051
1052 $contrib = array(
1053 'id' => (int)$this->_id,
1054 'date' => $this->_date,
1055 'type' => $this->getRawType(),
1056 'amount' => $this->amount,
1057 'voucher' => $voucher_path,
1058 'category' => array(
1059 'id' => $this->type->id,
1060 'label' => $this->type->libelle
1061 ),
1062 'payment' => $payment
1063 );
1064
1065 if ($this->_member !== null) {
1066 $m = new Adherent($this->zdb, (int)$this->_member);
1067 $member = array(
1068 'id' => (int)$this->_member,
1069 'name' => $m->sfullname,
1070 'email' => $m->email,
1071 'organization' => ($m->isCompany() ? 1 : 0),
1072 'status' => array(
1073 'id' => $m->status,
1074 'label' => $m->sstatus
1075 ),
1076 'country' => $m->country
1077 );
1078
1079 if ($m->isCompany()) {
1080 $member['organization_name'] = $m->company_name;
1081 }
1082
1083 $contrib['member'] = $member;
1084 }
1085
1086 if ($extra !== null && is_array($extra)) {
1087 $contrib = array_merge($contrib, $extra);
1088 }
1089
1090 $res = $es->send($contrib);
1091
1092 if ($res !== true) {
1093 Analog::log(
1094 'An error occurred calling post contribution ' .
1095 "script:\n" . $es->getOutput(),
1096 Analog::ERROR
1097 );
1098 $res = _T("Contribution information") . "\n";
1099 $res .= print_r($contrib, true);
1100 $res .= "\n\n" . _T("Script output") . "\n";
1101 $res .= $es->getOutput();
1102 }
1103
1104 return $res;
1105 }
1106 /**
1107 * Get raw contribution type
1108 *
1109 * @return string
1110 */
1111 public function getRawType()
1112 {
1113 if ($this->isFee()) {
1114 return 'membership';
1115 } else {
1116 return 'donation';
1117 }
1118 }
1119
1120 /**
1121 * Get contribution type label
1122 *
1123 * @return string
1124 */
1125 public function getTypeLabel()
1126 {
1127 if ($this->isFee()) {
1128 return _T("Membership");
1129 } else {
1130 return _T("Donation");
1131 }
1132 }
1133
1134 /**
1135 * Get payment type label
1136 *
1137 * @return string
1138 */
1139 public function getPaymentType()
1140 {
1141 if ($this->_payment_type === null) {
1142 return '-';
1143 }
1144
1145 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1146 return $ptype->getName(false);
1147 }
1148
1149 /**
1150 * Global getter method
1151 *
1152 * @param string $name name of the property we want to retrieve
1153 *
1154 * @return false|object the called property
1155 */
1156 public function __get($name)
1157 {
1158
1159 $forbidden = array('is_cotis');
1160 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1161 'raw_begin_date', 'raw_end_date'
1162 );
1163
1164 $rname = '_' . $name;
1165
1166 if (in_array($name, $forbidden)) {
1167 Analog::log(
1168 "Call to __get for '$name' is forbidden!",
1169 Analog::WARNING
1170 );
1171
1172 switch ($name) {
1173 case 'is_cotis':
1174 return $this->isFee();
1175 break;
1176 default:
1177 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1178 }
1179 } elseif (
1180 property_exists($this, $rname)
1181 || in_array($name, $virtuals)
1182 ) {
1183 switch ($name) {
1184 case 'raw_date':
1185 case 'raw_begin_date':
1186 case 'raw_end_date':
1187 $rname = '_' . substr($name, 4);
1188 if ($this->$rname != '') {
1189 try {
1190 $d = new \DateTime($this->$rname);
1191 return $d;
1192 } catch (Throwable $e) {
1193 //oops, we've got a bad date :/
1194 Analog::log(
1195 'Bad date (' . $this->$rname . ') | ' .
1196 $e->getMessage(),
1197 Analog::INFO
1198 );
1199 throw $e;
1200 }
1201 }
1202 break;
1203 case 'date':
1204 case 'begin_date':
1205 case 'end_date':
1206 if ($this->$rname != '') {
1207 try {
1208 $d = new \DateTime($this->$rname);
1209 return $d->format(__("Y-m-d"));
1210 } catch (Throwable $e) {
1211 //oops, we've got a bad date :/
1212 Analog::log(
1213 'Bad date (' . $this->$rname . ') | ' .
1214 $e->getMessage(),
1215 Analog::INFO
1216 );
1217 return $this->$rname;
1218 }
1219 }
1220 break;
1221 case 'duration':
1222 if ($this->_is_cotis) {
1223 $date_end = new \DateTime($this->_end_date);
1224 $date_start = new \DateTime($this->_begin_date);
1225 $diff = $date_end->diff($date_start);
1226 return $diff->format('%y') * 12 + $diff->format('%m');
1227 } else {
1228 return '';
1229 }
1230 break;
1231 case 'spayment_type':
1232 if ($this->_payment_type === null) {
1233 return '-';
1234 }
1235
1236 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1237 return $ptype->getName();
1238
1239 break;
1240 case 'model':
1241 if ($this->_is_cotis === null) {
1242 return null;
1243 }
1244 return ($this->isFee()) ?
1245 PdfModel::INVOICE_MODEL : PdfModel::RECEIPT_MODEL;
1246 break;
1247 default:
1248 return $this->$rname;
1249 break;
1250 }
1251 } else {
1252 Analog::log(
1253 "Unknown property '$rname'",
1254 Analog::WARNING
1255 );
1256 return null;
1257 }
1258 }
1259
1260 /**
1261 * Global setter method
1262 *
1263 * @param string $name name of the property we want to assign a value to
1264 * @param object $value a relevant value for the property
1265 *
1266 * @return void
1267 */
1268 public function __set($name, $value)
1269 {
1270 global $preferences;
1271
1272 $forbidden = array('fields', 'is_cotis', 'end_date');
1273
1274 if (!in_array($name, $forbidden)) {
1275 $rname = '_' . $name;
1276 switch ($name) {
1277 case 'transaction':
1278 if (is_int($value)) {
1279 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1280 } else {
1281 Analog::log(
1282 'Trying to set a transaction from an id that is not an integer.',
1283 Analog::WARNING
1284 );
1285 }
1286 break;
1287 case 'type':
1288 if (is_int($value)) {
1289 //set type
1290 $this->$rname = new ContributionsTypes($this->zdb, $value);
1291 //set is_cotis according to type
1292 if ($this->$rname->extension == 1) {
1293 $this->_is_cotis = true;
1294 } else {
1295 $this->_is_cotis = false;
1296 }
1297 } else {
1298 Analog::log(
1299 'Trying to set a type from an id that is not an integer.',
1300 Analog::WARNING
1301 );
1302 }
1303 break;
1304 case 'begin_date':
1305 try {
1306 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1307 if ($d === false) {
1308 throw new \Exception('Incorrect format');
1309 }
1310 $this->_begin_date = $d->format('Y-m-d');
1311 } catch (Throwable $e) {
1312 Analog::log(
1313 'Wrong date format. field: ' . $name .
1314 ', value: ' . $value . ', expected fmt: ' .
1315 __("Y-m-d") . ' | ' . $e->getMessage(),
1316 Analog::INFO
1317 );
1318 $this->errors[] = str_replace(
1319 array(
1320 '%date_format',
1321 '%field'
1322 ),
1323 array(
1324 __("Y-m-d"),
1325 $this->_fields['date_debut_cotis']['label']
1326 ),
1327 _T("- Wrong date format (%date_format) for %field!")
1328 );
1329 }
1330 break;
1331 case 'amount':
1332 if (is_numeric($value) && $value > 0) {
1333 $this->$rname = $value;
1334 } else {
1335 Analog::log(
1336 'Trying to set an amount with a non numeric value, ' .
1337 'or with a zero value',
1338 Analog::WARNING
1339 );
1340 }
1341 break;
1342 case 'member':
1343 if (is_int($value)) {
1344 //set type
1345 $this->$rname = $value;
1346 }
1347 break;
1348 case 'payment_type':
1349 $ptypes = new PaymentTypes(
1350 $this->zdb,
1351 $preferences,
1352 $this->login
1353 );
1354 $list = $ptypes->getList();
1355 if (isset($list[$value])) {
1356 $this->_payment_type = $value;
1357 } else {
1358 Analog::log(
1359 'Unknown payment type ' . $value,
1360 Analog::WARNING
1361 );
1362 }
1363 break;
1364 default:
1365 Analog::log(
1366 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1367 $name . ')',
1368 Analog::WARNING
1369 );
1370 break;
1371 }
1372 }
1373 }
1374
1375 /**
1376 * Flag creation mail sending
1377 *
1378 * @param boolean $send True (default) to send creation email
1379 *
1380 * @return Contribution
1381 */
1382 public function setSendmail($send = true)
1383 {
1384 $this->sendmail = $send;
1385 return $this;
1386 }
1387
1388 /**
1389 * Should we send administrative emails to member?
1390 *
1391 * @return boolean
1392 */
1393 public function sendEMail()
1394 {
1395 return $this->sendmail;
1396 }
1397
1398 /**
1399 * Handle files (dynamics files)
1400 *
1401 * @param array $files Files sent
1402 *
1403 * @return array|true
1404 */
1405 public function handleFiles($files)
1406 {
1407 $this->errors = [];
1408
1409 $this->dynamicsFiles($files);
1410
1411 if (count($this->errors) > 0) {
1412 Analog::log(
1413 'Some errors has been threw attempting to edit/store a contribution files' . "\n" .
1414 print_r($this->errors, true),
1415 Analog::ERROR
1416 );
1417 return $this->errors;
1418 } else {
1419 return true;
1420 }
1421 }
1422
1423 /**
1424 * Get required fields list
1425 *
1426 * @return array
1427 */
1428 public function getRequired(): array
1429 {
1430 return [
1431 'id_type_cotis' => 1,
1432 'id_adh' => 1,
1433 'date_enreg' => 1,
1434 'date_debut_cotis' => 1,
1435 'date_fin_cotis' => $this->isFee() ? 1 : 0,
1436 'montant_cotis' => $this->isFee() ? 1 : 0
1437 ];
1438 }
1439
1440 /**
1441 * Can current logged-in user display contribution
1442 *
1443 * @param Login $login Login instance
1444 *
1445 * @return boolean
1446 */
1447 public function canShow(Login $login): bool
1448 {
1449 //non-logged-in members cannot show contributions
1450 if (!$login->isLogged()) {
1451 return false;
1452 }
1453
1454 //admin and staff users can edit, as well as member itself
1455 if (!$this->id || $this->id && $login->id == $this->_member || $login->isAdmin() || $login->isStaff()) {
1456 return true;
1457 }
1458
1459 //parent can see their children contributions
1460 $parent = new Adherent($this->zdb);
1461 $parent
1462 ->disableAllDeps()
1463 ->enableDep('children')
1464 ->load($this->login->id);
1465 if ($parent->hasChildren()) {
1466 foreach ($parent->children as $child) {
1467 if ($child->id === $this->_member) {
1468 return true;
1469 }
1470 }
1471 return false;
1472 }
1473
1474 return false;
1475 }
1476 }