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