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