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