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