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