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