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