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