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