]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
Catch Throwables instead of Exceptions
[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-2014 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-2014 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-2014 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 if ($this->zdb->isPostgres()) {
609 $this->_id = $this->zdb->driver->getLastGeneratedValue(
610 PREFIX_DB . 'cotisations_id_seq'
611 );
612 } else {
613 $this->_id = $this->zdb->driver->getLastGeneratedValue();
614 }
615
616 // logging
617 $hist->add(
618 _T("Contribution added"),
619 Adherent::getSName($this->zdb, $this->_member)
620 );
621 $success = true;
622 $event = 'contribution.add';
623 } else {
624 $hist->add(_T("Fail to add new contribution."));
625 throw new \Exception(
626 'An error occurred inserting new contribution!'
627 );
628 }
629 } else {
630 //we're editing an existing contribution
631 $update = $this->zdb->update(self::TABLE);
632 $update->set($values)->where(
633 self::PK . '=' . $this->_id
634 );
635 $edit = $this->zdb->execute($update);
636
637 //edit == 0 does not mean there were an error, but that there
638 //were nothing to change
639 if ($edit->count() > 0) {
640 $hist->add(
641 _T("Contribution updated"),
642 Adherent::getSName($this->zdb, $this->_member)
643 );
644 }
645
646 if ($edit === false) {
647 throw new \Exception(
648 'An error occurred updating contribution # ' . $this->_id . '!'
649 );
650 }
651 $success = true;
652 $event = 'contribution.edit';
653 }
654 //update deadline
655 if ($this->isCotis()) {
656 $deadline = $this->updateDeadline();
657 if ($deadline !== true) {
658 //if something went wrong, we rollback transaction
659 throw new \Exception('An error occurred updating member\'s deadline');
660 }
661 }
662
663 //dynamic fields
664 if ($success) {
665 $success = $this->dynamicsStore(true);
666 }
667
668 $this->zdb->connection->commit();
669 $this->_orig_amount = $this->_amount;
670
671 //send event at the end of process, once all has been stored
672 if ($event !== null) {
673 $emitter->emit($event, $this);
674 }
675
676 return true;
677 } catch (Throwable $e) {
678 $this->zdb->connection->rollBack();
679 Analog::log(
680 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
681 $e->getTraceAsString(),
682 Analog::ERROR
683 );
684 return false;
685 }
686 }
687
688 /**
689 * Update member dead line
690 *
691 * @return boolean
692 */
693 private function updateDeadline()
694 {
695 try {
696 $due_date = self::getDueDate($this->zdb, $this->_member);
697
698 if ($due_date != '') {
699 $date_fin_update = $due_date;
700 } else {
701 $date_fin_update = new Expression('NULL');
702 }
703
704 $update = $this->zdb->update(Adherent::TABLE);
705 $update->set(
706 array('date_echeance' => $date_fin_update)
707 )->where(
708 Adherent::PK . '=' . $this->_member
709 );
710 $this->zdb->execute($update);
711 return true;
712 } catch (Throwable $e) {
713 Analog::log(
714 'An error occurred updating member ' . $this->_member .
715 '\'s deadline |' .
716 $e->getMessage(),
717 Analog::ERROR
718 );
719 return false;
720 }
721 }
722
723 /**
724 * Remove contribution from database
725 *
726 * @param boolean $transaction Activate transaction mode (defaults to true)
727 *
728 * @return boolean
729 */
730 public function remove($transaction = true)
731 {
732 global $emitter;
733
734 try {
735 if ($transaction) {
736 $this->zdb->connection->beginTransaction();
737 }
738
739 $delete = $this->zdb->delete(self::TABLE);
740 $delete->where(self::PK . ' = ' . $this->_id);
741 $del = $this->zdb->execute($delete);
742 if ($del->count() > 0) {
743 $this->updateDeadline();
744 $this->dynamicsRemove(true);
745 } else {
746 throw new \RuntimeException(
747 'Contribution has not been removed!'
748 );
749 }
750 if ($transaction) {
751 $this->zdb->connection->commit();
752 }
753 $emitter->emit('contribution.remove', $this);
754 return true;
755 } catch (Throwable $e) {
756 if ($transaction) {
757 $this->zdb->connection->rollBack();
758 }
759 Analog::log(
760 'An error occurred trying to remove contribution #' .
761 $this->_id . ' | ' . $e->getMessage(),
762 Analog::ERROR
763 );
764 return false;
765 }
766 }
767
768 /**
769 * Get field label
770 *
771 * @param string $field Field name
772 *
773 * @return string
774 */
775 public function getFieldLabel($field)
776 {
777 $label = $this->_fields[$field]['label'];
778 if ($this->isCotis() && $field == 'date_debut_cotis') {
779 $label = $this->_fields[$field]['cotlabel'];
780 }
781 //replace "&nbsp;"
782 $label = str_replace('&nbsp;', ' ', $label);
783 //remove trailing ':' and then trim
784 $label = trim(trim($label, ':'));
785 return $label;
786 }
787
788 /**
789 * Retrieve fields from database
790 *
791 * @param Db $zdb Database instance
792 *
793 * @return array
794 */
795 public static function getDbFields(Db $zdb)
796 {
797 $columns = $zdb->getColumns(self::TABLE);
798 $fields = array();
799 foreach ($columns as $col) {
800 $fields[] = $col->getName();
801 }
802 return $fields;
803 }
804
805 /**
806 * Get the relevant CSS class for current contribution
807 *
808 * @return string current contribution row class
809 */
810 public function getRowClass()
811 {
812 return ($this->_end_date != $this->_begin_date && $this->_is_cotis) ?
813 'cotis-normal' : 'cotis-give';
814 }
815
816 /**
817 * Retrieve member due date
818 *
819 * @param Db $zdb Database instance
820 * @param integer $member_id Member identifier
821 *
822 * @return date
823 */
824 public static function getDueDate(Db $zdb, $member_id)
825 {
826 if (!$member_id) {
827 return '';
828 }
829 try {
830 $select = $zdb->select(self::TABLE, 'c');
831 $select->columns(
832 array(
833 'max_date' => new Expression('MAX(date_fin_cotis)')
834 )
835 )->join(
836 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
837 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
838 array()
839 )->where(
840 Adherent::PK . ' = ' . $member_id
841 )->where(
842 array('cotis_extension' => new Expression('true'))
843 );
844
845 $results = $zdb->execute($select);
846 $result = $results->current();
847 $due_date = $result->max_date;
848
849 //avoid bad dates in postgres and bad mysql return from zenddb
850 if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
851 $due_date = '';
852 }
853 return $due_date;
854 } catch (Throwable $e) {
855 Analog::log(
856 'An error occurred trying to retrieve member\'s due date',
857 Analog::ERROR
858 );
859 return false;
860 }
861 }
862
863 /**
864 * Detach a contribution from a transaction
865 *
866 * @param Db $zdb Database instance
867 * @param Login $login Login instance
868 * @param int $trans_id Transaction identifier
869 * @param int $contrib_id Contribution identifier
870 *
871 * @return boolean
872 */
873 public static function unsetTransactionPart(Db $zdb, Login $login, $trans_id, $contrib_id)
874 {
875 try {
876 //first, we check if contribution is part of transaction
877 $c = new Contribution($zdb, $login, (int)$contrib_id);
878 if ($c->isTransactionPartOf($trans_id)) {
879 $update = $zdb->update(self::TABLE);
880 $update->set(
881 array(Transaction::PK => null)
882 )->where(
883 self::PK . ' = ' . $contrib_id
884 );
885 $zdb->execute($update);
886 return true;
887 } else {
888 Analog::log(
889 'Contribution #' . $contrib_id .
890 ' is not actually part of transaction #' . $trans_id,
891 Analog::WARNING
892 );
893 return false;
894 }
895 } catch (Throwable $e) {
896 Analog::log(
897 'Unable to detach contribution #' . $contrib_id .
898 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
899 Analog::ERROR
900 );
901 return false;
902 }
903 }
904
905 /**
906 * Set a contribution as a transaction part
907 *
908 * @param Db $zdb Database instance
909 * @param int $trans_id Transaction identifier
910 * @param int $contrib_id Contribution identifier
911 *
912 * @return boolean
913 */
914 public static function setTransactionPart(Db $zdb, $trans_id, $contrib_id)
915 {
916 try {
917 $update = $zdb->update(self::TABLE);
918 $update->set(
919 array(Transaction::PK => $trans_id)
920 )->where(self::PK . ' = ' . $contrib_id);
921
922 $zdb->execute($update);
923 return true;
924 } catch (Throwable $e) {
925 Analog::log(
926 'Unable to attach contribution #' . $contrib_id .
927 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
928 Analog::ERROR
929 );
930 return false;
931 }
932 }
933
934 /**
935 * Is current contribution a cotisation
936 *
937 * @return boolean
938 */
939 public function isCotis()
940 {
941 return $this->_is_cotis;
942 }
943
944 /**
945 * Is current contribution part of specified transaction
946 *
947 * @param int $id Transaction identifier
948 *
949 * @return boolean
950 */
951 public function isTransactionPartOf($id)
952 {
953 if ($this->isTransactionPart()) {
954 return $id == $this->_transaction->id;
955 } else {
956 return false;
957 }
958 }
959
960 /**
961 * Is current contribution part of transaction
962 *
963 * @return boolean
964 */
965 public function isTransactionPart()
966 {
967 return $this->_transaction != null;
968 }
969
970 /**
971 * Execute post contribution script
972 *
973 * @param ExternalScript $es External script to execute
974 * @param array $extra Extra information on contribution
975 * Defaults to null
976 * @param array $pextra Extra information on payment
977 * Defaults to null
978 *
979 * @return mixed Script return value on success, values and script output on fail
980 */
981 public function executePostScript(
982 ExternalScript $es,
983 $extra = null,
984 $pextra = null
985 ) {
986 global $preferences;
987
988 $payment = array(
989 'type' => $this->getPaymentType()
990 );
991
992 if ($pextra !== null && is_array($pextra)) {
993 $payment = array_merge($payment, $pextra);
994 }
995
996 if (!file_exists(GALETTE_CACHE_DIR . '/pdf_contribs')) {
997 @mkdir(GALETTE_CACHE_DIR . '/pdf_contribs');
998 }
999
1000 $voucher_path = null;
1001 if ($this->_id !== null) {
1002 $voucher = new PdfContribution($this, $this->zdb, $preferences);
1003 $voucher->store(GALETTE_CACHE_DIR . '/pdf_contribs');
1004 $voucher_path = $voucher->getPath();
1005 }
1006
1007 $contrib = array(
1008 'id' => (int)$this->_id,
1009 'date' => $this->_date,
1010 'type' => $this->getRawType(),
1011 'amount' => $this->amount,
1012 'voucher' => $voucher_path,
1013 'category' => array(
1014 'id' => $this->type->id,
1015 'label' => $this->type->libelle
1016 ),
1017 'payment' => $payment
1018 );
1019
1020 if ($this->_member !== null) {
1021 $m = new Adherent($this->zdb, (int)$this->_member);
1022 $member = array(
1023 'id' => (int)$this->_member,
1024 'name' => $m->sfullname,
1025 'email' => $m->email,
1026 'organization' => ($m->isCompany() ? 1 : 0),
1027 'status' => array(
1028 'id' => $m->status,
1029 'label' => $m->sstatus
1030 ),
1031 'country' => $m->country
1032 );
1033
1034 if ($m->isCompany()) {
1035 $member['organization_name'] = $m->company_name;
1036 }
1037
1038 $contrib['member'] = $member;
1039 }
1040
1041 if ($extra !== null && is_array($extra)) {
1042 $contrib = array_merge($contrib, $extra);
1043 }
1044
1045 $res = $es->send($contrib);
1046
1047 if ($res !== true) {
1048 Analog::log(
1049 'An error occurred calling post contribution ' .
1050 "script:\n" . $es->getOutput(),
1051 Analog::ERROR
1052 );
1053 $res = _T("Contribution information") . "\n";
1054 $res .= print_r($contrib, true);
1055 $res .= "\n\n" . _T("Script output") . "\n";
1056 $res .= $es->getOutput();
1057 }
1058
1059 return $res;
1060 }
1061 /**
1062 * Get raw contribution type
1063 *
1064 * @return string
1065 */
1066 public function getRawType()
1067 {
1068 if ($this->isCotis()) {
1069 return 'membership';
1070 } else {
1071 return 'donation';
1072 }
1073 }
1074
1075 /**
1076 * Get contribution type label
1077 *
1078 * @return string
1079 */
1080 public function getTypeLabel()
1081 {
1082 if ($this->isCotis()) {
1083 return _T("Membership");
1084 } else {
1085 return _T("Donation");
1086 }
1087 }
1088
1089 /**
1090 * Get payment type label
1091 *
1092 * @return string
1093 */
1094 public function getPaymentType()
1095 {
1096 if ($this->_payment_type === null) {
1097 return '-';
1098 }
1099
1100 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1101 return $ptype->getName(false);
1102 }
1103
1104 /**
1105 * Global getter method
1106 *
1107 * @param string $name name of the property we want to retrive
1108 *
1109 * @return false|object the called property
1110 */
1111 public function __get($name)
1112 {
1113
1114 $forbidden = array('is_cotis');
1115 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1116 'raw_begin_date', 'raw_end_date'
1117 );
1118
1119 $rname = '_' . $name;
1120
1121 if (in_array($name, $forbidden)) {
1122 Analog::log(
1123 "Call to __get for '$name' is forbidden!",
1124 Analog::WARNING
1125 );
1126
1127 switch ($name) {
1128 case 'is_cotis':
1129 return $this->isCotis();
1130 break;
1131 default:
1132 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1133 }
1134 } elseif (
1135 property_exists($this, $rname)
1136 || in_array($name, $virtuals)
1137 ) {
1138 switch ($name) {
1139 case 'raw_date':
1140 case 'raw_begin_date':
1141 case 'raw_end_date':
1142 $rname = '_' . substr($name, 4);
1143 if ($this->$rname != '') {
1144 try {
1145 $d = new \DateTime($this->$rname);
1146 return $d;
1147 } catch (Throwable $e) {
1148 //oops, we've got a bad date :/
1149 Analog::log(
1150 'Bad date (' . $this->$rname . ') | ' .
1151 $e->getMessage(),
1152 Analog::INFO
1153 );
1154 throw $e;
1155 }
1156 }
1157 break;
1158 case 'date':
1159 case 'begin_date':
1160 case 'end_date':
1161 if ($this->$rname != '') {
1162 try {
1163 $d = new \DateTime($this->$rname);
1164 return $d->format(__("Y-m-d"));
1165 } catch (Throwable $e) {
1166 //oops, we've got a bad date :/
1167 Analog::log(
1168 'Bad date (' . $this->$rname . ') | ' .
1169 $e->getMessage(),
1170 Analog::INFO
1171 );
1172 return $this->$rname;
1173 }
1174 }
1175 break;
1176 case 'duration':
1177 if ($this->_is_cotis) {
1178 $date_end = new \DateTime($this->_end_date);
1179 $date_start = new \DateTime($this->_begin_date);
1180 $diff = $date_end->diff($date_start);
1181 return $diff->format('%y') * 12 + $diff->format('%m');
1182 } else {
1183 return '';
1184 }
1185 break;
1186 case 'spayment_type':
1187 if ($this->_payment_type === null) {
1188 return '-';
1189 }
1190
1191 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1192 return $ptype->getName();
1193
1194 break;
1195 case 'model':
1196 if ($this->_is_cotis === null) {
1197 return null;
1198 }
1199 return ($this->isCotis()) ?
1200 PdfModel::INVOICE_MODEL : PdfModel::RECEIPT_MODEL;
1201 break;
1202 default:
1203 return $this->$rname;
1204 break;
1205 }
1206 } else {
1207 Analog::log(
1208 "Unknown property '$rname'",
1209 Analog::WARNING
1210 );
1211 return null;
1212 }
1213 }
1214
1215 /**
1216 * Global setter method
1217 *
1218 * @param string $name name of the property we want to assign a value to
1219 * @param object $value a relevant value for the property
1220 *
1221 * @return void
1222 */
1223 public function __set($name, $value)
1224 {
1225 global $preferences;
1226
1227 $forbidden = array('fields', 'is_cotis', 'end_date');
1228
1229 if (!in_array($name, $forbidden)) {
1230 $rname = '_' . $name;
1231 switch ($name) {
1232 case 'transaction':
1233 if (is_int($value)) {
1234 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1235 } else {
1236 Analog::log(
1237 'Trying to set a transaction from an id that is not an integer.',
1238 Analog::WARNING
1239 );
1240 }
1241 break;
1242 case 'type':
1243 if (is_int($value)) {
1244 //set type
1245 $this->$rname = new ContributionsTypes($this->zdb, $value);
1246 //set is_cotis according to type
1247 if ($this->$rname->extension == 1) {
1248 $this->_is_cotis = true;
1249 } else {
1250 $this->_is_cotis = false;
1251 }
1252 } else {
1253 Analog::log(
1254 'Trying to set a type from an id that is not an integer.',
1255 Analog::WARNING
1256 );
1257 }
1258 break;
1259 case 'begin_date':
1260 try {
1261 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1262 if ($d === false) {
1263 throw new \Exception('Incorrect format');
1264 }
1265 $this->_begin_date = $d->format('Y-m-d');
1266 } catch (Throwable $e) {
1267 Analog::log(
1268 'Wrong date format. field: ' . $name .
1269 ', value: ' . $value . ', expected fmt: ' .
1270 __("Y-m-d") . ' | ' . $e->getMessage(),
1271 Analog::INFO
1272 );
1273 $this->errors[] = str_replace(
1274 array(
1275 '%date_format',
1276 '%field'
1277 ),
1278 array(
1279 __("Y-m-d"),
1280 $this->_fields['date_debut_cotis']['label']
1281 ),
1282 _T("- Wrong date format (%date_format) for %field!")
1283 );
1284 }
1285 break;
1286 case 'amount':
1287 if (is_numeric($value) && $value > 0) {
1288 $this->$rname = $value;
1289 } else {
1290 Analog::log(
1291 'Trying to set an amount with a non numeric value, ' .
1292 'or with a zero value',
1293 Analog::WARNING
1294 );
1295 }
1296 break;
1297 case 'member':
1298 if (is_int($value)) {
1299 //set type
1300 $this->$rname = $value;
1301 }
1302 break;
1303 case 'payment_type':
1304 $ptypes = new PaymentTypes(
1305 $this->zdb,
1306 $preferences,
1307 $this->login
1308 );
1309 $list = $ptypes->getList();
1310 if (isset($list[$value])) {
1311 $this->_payment_type = $value;
1312 } else {
1313 Analog::log(
1314 'Unknown payment type ' . $value,
1315 Analog::WARNING
1316 );
1317 }
1318 break;
1319 default:
1320 Analog::log(
1321 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1322 $name . ')',
1323 Analog::WARNING
1324 );
1325 break;
1326 }
1327 }
1328 }
1329
1330 /**
1331 * Flag creation mail sending
1332 *
1333 * @param boolean $send True (default) to send creation email
1334 *
1335 * @return Contribution
1336 */
1337 public function setSendmail($send = true)
1338 {
1339 $this->sendmail = $send;
1340 return $this;
1341 }
1342
1343 /**
1344 * Should we send administrative emails to member?
1345 *
1346 * @return boolean
1347 */
1348 public function sendEMail()
1349 {
1350 return $this->sendmail;
1351 }
1352 }