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