]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
Do not run query if there is no member id; closes #1364
[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 if (!$member_id) {
796 return '';
797 }
798 try {
799 $select = $zdb->select(self::TABLE, 'c');
800 $select->columns(
801 array(
802 'max_date' => new Expression('MAX(date_fin_cotis)')
803 )
804 )->join(
805 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
806 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
807 array()
808 )->where(
809 Adherent::PK . ' = ' . $member_id
810 )->where(
811 array('cotis_extension' => new Expression('true'))
812 );
813
814 $results = $zdb->execute($select);
815 $result = $results->current();
816 $due_date = $result->max_date;
817
818 //avoid bad dates in postgres and bad mysql return from zenddb
819 if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
820 $due_date = '';
821 }
822 return $due_date;
823 } catch (\Exception $e) {
824 Analog::log(
825 'An error occurred trying to retrieve member\'s due date',
826 Analog::ERROR
827 );
828 return false;
829 }
830 }
831
832 /**
833 * Detach a contribution from a transaction
834 *
835 * @param Db $zdb Database instance
836 * @param Login $login Login instance
837 * @param int $trans_id Transaction identifier
838 * @param int $contrib_id Contribution identifier
839 *
840 * @return boolean
841 */
842 public static function unsetTransactionPart(Db $zdb, Login $login, $trans_id, $contrib_id)
843 {
844 try {
845 //first, we check if contribution is part of transaction
846 $c = new Contribution($zdb, $login, (int)$contrib_id);
847 if ($c->isTransactionPartOf($trans_id)) {
848 $update = $zdb->update(self::TABLE);
849 $update->set(
850 array(Transaction::PK => null)
851 )->where(
852 self::PK . ' = ' . $contrib_id
853 );
854 $zdb->execute($update);
855 return true;
856 } else {
857 Analog::log(
858 'Contribution #' . $contrib_id .
859 ' is not actually part of transaction #' . $trans_id,
860 Analog::WARNING
861 );
862 return false;
863 }
864 } catch (\Exception $e) {
865 Analog::log(
866 'Unable to detach contribution #' . $contrib_id .
867 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
868 Analog::ERROR
869 );
870 return false;
871 }
872 }
873
874 /**
875 * Set a contribution as a transaction part
876 *
877 * @param Db $zdb Database instance
878 * @param int $trans_id Transaction identifier
879 * @param int $contrib_id Contribution identifier
880 *
881 * @return boolean
882 */
883 public static function setTransactionPart(Db $zdb, $trans_id, $contrib_id)
884 {
885 try {
886 $update = $zdb->update(self::TABLE);
887 $update->set(
888 array(Transaction::PK => $trans_id)
889 )->where(self::PK . ' = ' . $contrib_id);
890
891 $zdb->execute($update);
892 return true;
893 } catch (\Exception $e) {
894 Analog::log(
895 'Unable to attach contribution #' . $contrib_id .
896 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
897 Analog::ERROR
898 );
899 return false;
900 }
901 }
902
903 /**
904 * Is current contribution a cotisation
905 *
906 * @return boolean
907 */
908 public function isCotis()
909 {
910 return $this->_is_cotis;
911 }
912
913 /**
914 * Is current contribution part of specified transaction
915 *
916 * @param int $id Transaction identifier
917 *
918 * @return boolean
919 */
920 public function isTransactionPartOf($id)
921 {
922 if ($this->isTransactionPart()) {
923 return $id == $this->_transaction->id;
924 } else {
925 return false;
926 }
927 }
928
929 /**
930 * Is current contribution part of transaction
931 *
932 * @return boolean
933 */
934 public function isTransactionPart()
935 {
936 return $this->_transaction != null;
937 }
938
939 /**
940 * Execute post contribution script
941 *
942 * @param ExternalScript $es External script to execute
943 * @param array $extra Extra informations on contribution
944 * Defaults to null
945 * @param array $pextra Extra information on payment
946 * Defaults to null
947 *
948 * @return mixed Script return value on success, values and script output on fail
949 */
950 public function executePostScript(
951 ExternalScript $es,
952 $extra = null,
953 $pextra = null
954 ) {
955 global $preferences;
956
957 $payment = array(
958 'type' => $this->getPaymentType()
959 );
960
961 if ($pextra !== null && is_array($pextra)) {
962 $payment = array_merge($payment, $pextra);
963 }
964
965 if (!file_exists(GALETTE_CACHE_DIR . '/pdf_contribs')) {
966 @mkdir(GALETTE_CACHE_DIR . '/pdf_contribs');
967 }
968
969 $voucher_path = null;
970 if ($this->_id !== null) {
971 $voucher = new PdfContribution($this, $this->zdb, $preferences);
972 $voucher->store(GALETTE_CACHE_DIR . '/pdf_contribs');
973 $voucher_path = $voucher->getPath();
974 }
975
976 $contrib = array(
977 'date' => $this->_date,
978 'type' => $this->getRawType(),
979 'amount' => $this->amount,
980 'voucher' => $voucher_path,
981 'category' => array(
982 'id' => $this->type->id,
983 'label' => $this->type->libelle
984 ),
985 'payment' => $payment
986 );
987
988 if ($this->_member !== null) {
989 $m = new Adherent($this->zdb, (int)$this->_member);
990 $member = array(
991 'name' => $m->sfullname,
992 'email' => $m->email,
993 'organization' => ($m->isCompany() ? 1 : 0),
994 'status' => array(
995 'id' => $m->status,
996 'label' => $m->sstatus
997 ),
998 'country' => $m->country
999 );
1000
1001 if ($m->isCompany()) {
1002 $member['organization_name'] = $m->company_name;
1003 }
1004
1005 $contrib['member'] = $member;
1006 }
1007
1008 if ($extra !== null && is_array($extra)) {
1009 $contrib = array_merge($contrib, $extra);
1010 }
1011
1012 $res = $es->send($contrib);
1013
1014 if ($res !== true) {
1015 Analog::log(
1016 'An error occurred calling post contribution ' .
1017 "script:\n" . $es->getOutput(),
1018 Analog::ERROR
1019 );
1020 $res = _T("Contribution informations") . "\n";
1021 $res .= print_r($contrib, true);
1022 $res .= "\n\n" . _T("Script output") . "\n";
1023 $res .= $es->getOutput();
1024 }
1025
1026 return $res;
1027 }
1028 /**
1029 * Get raw contribution type
1030 *
1031 * @return string
1032 */
1033 public function getRawType()
1034 {
1035 if ($this->isCotis()) {
1036 return 'membership';
1037 } else {
1038 return 'donation';
1039 }
1040 }
1041
1042 /**
1043 * Get contribution type label
1044 *
1045 * @return string
1046 */
1047 public function getTypeLabel()
1048 {
1049 if ($this->isCotis()) {
1050 return _T("Membership");
1051 } else {
1052 return _T("Donation");
1053 }
1054 }
1055
1056 /**
1057 * Get payment type label
1058 *
1059 * @return string
1060 */
1061 public function getPaymentType()
1062 {
1063 if ($this->_payment_type === null) {
1064 return '-';
1065 }
1066
1067 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1068 return $ptype->getName(false);
1069 }
1070
1071 /**
1072 * Global getter method
1073 *
1074 * @param string $name name of the property we want to retrive
1075 *
1076 * @return false|object the called property
1077 */
1078 public function __get($name)
1079 {
1080
1081 $forbidden = array('is_cotis');
1082 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1083 'raw_begin_date', 'raw_end_date'
1084 );
1085
1086 $rname = '_' . $name;
1087
1088 if (in_array($name, $forbidden)) {
1089 Analog::log(
1090 "Call to __get for '$name' is forbidden!",
1091 Analog::WARNING
1092 );
1093
1094 switch ($name) {
1095 case 'is_cotis':
1096 return $this->isCotis();
1097 break;
1098 default:
1099 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1100 }
1101 } elseif (property_exists($this, $rname)
1102 || in_array($name, $virtuals)
1103 ) {
1104 switch ($name) {
1105 case 'raw_date':
1106 case 'raw_begin_date':
1107 case 'raw_end_date':
1108 $rname = '_' . substr($name, 4);
1109 if ($this->$rname != '') {
1110 try {
1111 $d = new \DateTime($this->$rname);
1112 return $d;
1113 } catch (\Exception $e) {
1114 //oops, we've got a bad date :/
1115 Analog::log(
1116 'Bad date (' . $this->$rname . ') | ' .
1117 $e->getMessage(),
1118 Analog::INFO
1119 );
1120 throw $e;
1121 }
1122 }
1123 break;
1124 case 'date':
1125 case 'begin_date':
1126 case 'end_date':
1127 if ($this->$rname != '') {
1128 try {
1129 $d = new \DateTime($this->$rname);
1130 return $d->format(__("Y-m-d"));
1131 } catch (\Exception $e) {
1132 //oops, we've got a bad date :/
1133 Analog::log(
1134 'Bad date (' . $this->$rname . ') | ' .
1135 $e->getMessage(),
1136 Analog::INFO
1137 );
1138 return $this->$rname;
1139 }
1140 }
1141 break;
1142 case 'duration':
1143 if ($this->_is_cotis) {
1144 $date_end = new \DateTime($this->_end_date);
1145 $date_start = new \DateTime($this->_begin_date);
1146 $diff = $date_end->diff($date_start);
1147 return $diff->format('%y') * 12 + $diff->format('%m');
1148 } else {
1149 return '';
1150 }
1151 break;
1152 case 'spayment_type':
1153 if ($this->_payment_type === null) {
1154 return '-';
1155 }
1156
1157 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1158 return $ptype->getName();
1159
1160 break;
1161 case 'model':
1162 if ($this->_is_cotis === null) {
1163 return null;
1164 }
1165 return ($this->isCotis()) ?
1166 PdfModel::INVOICE_MODEL :
1167 PdfModel::RECEIPT_MODEL;
1168 break;
1169 default:
1170 return $this->$rname;
1171 break;
1172 }
1173 } else {
1174 Analog::log(
1175 "Unknown property '$rname'",
1176 Analog::WARNING
1177 );
1178 return null;
1179 }
1180 }
1181
1182 /**
1183 * Global setter method
1184 *
1185 * @param string $name name of the property we want to assign a value to
1186 * @param object $value a relevant value for the property
1187 *
1188 * @return void
1189 */
1190 public function __set($name, $value)
1191 {
1192 global $preferences;
1193
1194 $forbidden = array('fields', 'is_cotis', 'end_date');
1195
1196 if (!in_array($name, $forbidden)) {
1197 $rname = '_' . $name;
1198 switch ($name) {
1199 case 'transaction':
1200 if (is_int($value)) {
1201 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1202 } else {
1203 Analog::log(
1204 'Trying to set a transaction from an id that is not an integer.',
1205 Analog::WARNING
1206 );
1207 }
1208 break;
1209 case 'type':
1210 if (is_int($value)) {
1211 //set type
1212 $this->$rname = new ContributionsTypes($this->zdb, $value);
1213 //set is_cotis according to type
1214 if ($this->$rname->extension == 1) {
1215 $this->_is_cotis = true;
1216 } else {
1217 $this->_is_cotis = false;
1218 }
1219 } else {
1220 Analog::log(
1221 'Trying to set a type from an id that is not an integer.',
1222 Analog::WARNING
1223 );
1224 }
1225 break;
1226 case 'begin_date':
1227 try {
1228 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1229 if ($d === false) {
1230 throw new \Exception('Incorrect format');
1231 }
1232 $this->_begin_date = $d->format('Y-m-d');
1233 } catch (\Exception $e) {
1234 Analog::log(
1235 'Wrong date format. field: ' . $name .
1236 ', value: ' . $value . ', expected fmt: ' .
1237 __("Y-m-d") . ' | ' . $e->getMessage(),
1238 Analog::INFO
1239 );
1240 $this->errors[] = str_replace(
1241 array(
1242 '%date_format',
1243 '%field'
1244 ),
1245 array(
1246 __("Y-m-d"),
1247 $this->_fields['date_debut_cotis']['label']
1248 ),
1249 _T("- Wrong date format (%date_format) for %field!")
1250 );
1251 }
1252 break;
1253 case 'amount':
1254 if (is_numeric($value) && $value > 0) {
1255 $this->$rname = $value;
1256 } else {
1257 Analog::log(
1258 'Trying to set an amount with a non numeric value, ' .
1259 'or with a zero value',
1260 Analog::WARNING
1261 );
1262 }
1263 break;
1264 case 'member':
1265 if (is_int($value)) {
1266 //set type
1267 $this->$rname = $value;
1268 }
1269 break;
1270 case 'payment_type':
1271 $ptypes = new PaymentTypes(
1272 $this->zdb,
1273 $preferences,
1274 $this->login
1275 );
1276 $list = $ptypes->getList();
1277 if (isset($list[$value])) {
1278 $this->_payment_type = $value;
1279 } else {
1280 Analog::log(
1281 'Unknown payment type ' . $value,
1282 Analog::WARNING
1283 );
1284 }
1285 break;
1286 default:
1287 Analog::log(
1288 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1289 $name . ')',
1290 Analog::WARNING
1291 );
1292 break;
1293 }
1294 }
1295 }
1296 }