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