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