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