]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
Add contribution and members in post script; closes #1406
[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 'id' => (int)$this->_id,
978 'date' => $this->_date,
979 'type' => $this->getRawType(),
980 'amount' => $this->amount,
981 'voucher' => $voucher_path,
982 'category' => array(
983 'id' => $this->type->id,
984 'label' => $this->type->libelle
985 ),
986 'payment' => $payment
987 );
988
989 if ($this->_member !== null) {
990 $m = new Adherent($this->zdb, (int)$this->_member);
991 $member = array(
992 'id' => (int)$this->_member,
993 'name' => $m->sfullname,
994 'email' => $m->email,
995 'organization' => ($m->isCompany() ? 1 : 0),
996 'status' => array(
997 'id' => $m->status,
998 'label' => $m->sstatus
999 ),
1000 'country' => $m->country
1001 );
1002
1003 if ($m->isCompany()) {
1004 $member['organization_name'] = $m->company_name;
1005 }
1006
1007 $contrib['member'] = $member;
1008 }
1009
1010 if ($extra !== null && is_array($extra)) {
1011 $contrib = array_merge($contrib, $extra);
1012 }
1013
1014 $res = $es->send($contrib);
1015
1016 if ($res !== true) {
1017 Analog::log(
1018 'An error occurred calling post contribution ' .
1019 "script:\n" . $es->getOutput(),
1020 Analog::ERROR
1021 );
1022 $res = _T("Contribution informations") . "\n";
1023 $res .= print_r($contrib, true);
1024 $res .= "\n\n" . _T("Script output") . "\n";
1025 $res .= $es->getOutput();
1026 }
1027
1028 return $res;
1029 }
1030 /**
1031 * Get raw contribution type
1032 *
1033 * @return string
1034 */
1035 public function getRawType()
1036 {
1037 if ($this->isCotis()) {
1038 return 'membership';
1039 } else {
1040 return 'donation';
1041 }
1042 }
1043
1044 /**
1045 * Get contribution type label
1046 *
1047 * @return string
1048 */
1049 public function getTypeLabel()
1050 {
1051 if ($this->isCotis()) {
1052 return _T("Membership");
1053 } else {
1054 return _T("Donation");
1055 }
1056 }
1057
1058 /**
1059 * Get payment type label
1060 *
1061 * @return string
1062 */
1063 public function getPaymentType()
1064 {
1065 if ($this->_payment_type === null) {
1066 return '-';
1067 }
1068
1069 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1070 return $ptype->getName(false);
1071 }
1072
1073 /**
1074 * Global getter method
1075 *
1076 * @param string $name name of the property we want to retrive
1077 *
1078 * @return false|object the called property
1079 */
1080 public function __get($name)
1081 {
1082
1083 $forbidden = array('is_cotis');
1084 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1085 'raw_begin_date', 'raw_end_date'
1086 );
1087
1088 $rname = '_' . $name;
1089
1090 if (in_array($name, $forbidden)) {
1091 Analog::log(
1092 "Call to __get for '$name' is forbidden!",
1093 Analog::WARNING
1094 );
1095
1096 switch ($name) {
1097 case 'is_cotis':
1098 return $this->isCotis();
1099 break;
1100 default:
1101 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1102 }
1103 } elseif (property_exists($this, $rname)
1104 || in_array($name, $virtuals)
1105 ) {
1106 switch ($name) {
1107 case 'raw_date':
1108 case 'raw_begin_date':
1109 case 'raw_end_date':
1110 $rname = '_' . substr($name, 4);
1111 if ($this->$rname != '') {
1112 try {
1113 $d = new \DateTime($this->$rname);
1114 return $d;
1115 } catch (\Exception $e) {
1116 //oops, we've got a bad date :/
1117 Analog::log(
1118 'Bad date (' . $this->$rname . ') | ' .
1119 $e->getMessage(),
1120 Analog::INFO
1121 );
1122 throw $e;
1123 }
1124 }
1125 break;
1126 case 'date':
1127 case 'begin_date':
1128 case 'end_date':
1129 if ($this->$rname != '') {
1130 try {
1131 $d = new \DateTime($this->$rname);
1132 return $d->format(__("Y-m-d"));
1133 } catch (\Exception $e) {
1134 //oops, we've got a bad date :/
1135 Analog::log(
1136 'Bad date (' . $this->$rname . ') | ' .
1137 $e->getMessage(),
1138 Analog::INFO
1139 );
1140 return $this->$rname;
1141 }
1142 }
1143 break;
1144 case 'duration':
1145 if ($this->_is_cotis) {
1146 $date_end = new \DateTime($this->_end_date);
1147 $date_start = new \DateTime($this->_begin_date);
1148 $diff = $date_end->diff($date_start);
1149 return $diff->format('%y') * 12 + $diff->format('%m');
1150 } else {
1151 return '';
1152 }
1153 break;
1154 case 'spayment_type':
1155 if ($this->_payment_type === null) {
1156 return '-';
1157 }
1158
1159 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1160 return $ptype->getName();
1161
1162 break;
1163 case 'model':
1164 if ($this->_is_cotis === null) {
1165 return null;
1166 }
1167 return ($this->isCotis()) ?
1168 PdfModel::INVOICE_MODEL :
1169 PdfModel::RECEIPT_MODEL;
1170 break;
1171 default:
1172 return $this->$rname;
1173 break;
1174 }
1175 } else {
1176 Analog::log(
1177 "Unknown property '$rname'",
1178 Analog::WARNING
1179 );
1180 return null;
1181 }
1182 }
1183
1184 /**
1185 * Global setter method
1186 *
1187 * @param string $name name of the property we want to assign a value to
1188 * @param object $value a relevant value for the property
1189 *
1190 * @return void
1191 */
1192 public function __set($name, $value)
1193 {
1194 global $preferences;
1195
1196 $forbidden = array('fields', 'is_cotis', 'end_date');
1197
1198 if (!in_array($name, $forbidden)) {
1199 $rname = '_' . $name;
1200 switch ($name) {
1201 case 'transaction':
1202 if (is_int($value)) {
1203 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1204 } else {
1205 Analog::log(
1206 'Trying to set a transaction from an id that is not an integer.',
1207 Analog::WARNING
1208 );
1209 }
1210 break;
1211 case 'type':
1212 if (is_int($value)) {
1213 //set type
1214 $this->$rname = new ContributionsTypes($this->zdb, $value);
1215 //set is_cotis according to type
1216 if ($this->$rname->extension == 1) {
1217 $this->_is_cotis = true;
1218 } else {
1219 $this->_is_cotis = false;
1220 }
1221 } else {
1222 Analog::log(
1223 'Trying to set a type from an id that is not an integer.',
1224 Analog::WARNING
1225 );
1226 }
1227 break;
1228 case 'begin_date':
1229 try {
1230 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1231 if ($d === false) {
1232 throw new \Exception('Incorrect format');
1233 }
1234 $this->_begin_date = $d->format('Y-m-d');
1235 } catch (\Exception $e) {
1236 Analog::log(
1237 'Wrong date format. field: ' . $name .
1238 ', value: ' . $value . ', expected fmt: ' .
1239 __("Y-m-d") . ' | ' . $e->getMessage(),
1240 Analog::INFO
1241 );
1242 $this->errors[] = str_replace(
1243 array(
1244 '%date_format',
1245 '%field'
1246 ),
1247 array(
1248 __("Y-m-d"),
1249 $this->_fields['date_debut_cotis']['label']
1250 ),
1251 _T("- Wrong date format (%date_format) for %field!")
1252 );
1253 }
1254 break;
1255 case 'amount':
1256 if (is_numeric($value) && $value > 0) {
1257 $this->$rname = $value;
1258 } else {
1259 Analog::log(
1260 'Trying to set an amount with a non numeric value, ' .
1261 'or with a zero value',
1262 Analog::WARNING
1263 );
1264 }
1265 break;
1266 case 'member':
1267 if (is_int($value)) {
1268 //set type
1269 $this->$rname = $value;
1270 }
1271 break;
1272 case 'payment_type':
1273 $ptypes = new PaymentTypes(
1274 $this->zdb,
1275 $preferences,
1276 $this->login
1277 );
1278 $list = $ptypes->getList();
1279 if (isset($list[$value])) {
1280 $this->_payment_type = $value;
1281 } else {
1282 Analog::log(
1283 'Unknown payment type ' . $value,
1284 Analog::WARNING
1285 );
1286 }
1287 break;
1288 default:
1289 Analog::log(
1290 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1291 $name . ')',
1292 Analog::WARNING
1293 );
1294 break;
1295 }
1296 }
1297 }
1298 }