]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
Various texts fixes, from comments on weblate
[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 Laminas\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 = (int)$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, $emitter;
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
602 $emitter->emit('contribution.add', $this);
603 } else {
604 $hist->add(_T("Fail to add new contribution."));
605 throw new \Exception(
606 'An error occurred inserting new contribution!'
607 );
608 }
609 } else {
610 //we're editing an existing contribution
611 $update = $this->zdb->update(self::TABLE);
612 $update->set($values)->where(
613 self::PK . '=' . $this->_id
614 );
615 $edit = $this->zdb->execute($update);
616
617 //edit == 0 does not mean there were an error, but that there
618 //were nothing to change
619 if ($edit->count() > 0) {
620 $hist->add(
621 _T("Contribution updated"),
622 Adherent::getSName($this->zdb, $this->_member)
623 );
624 }
625
626 if ($edit === false) {
627 throw new \Exception(
628 'An error occurred updating contribution # ' . $this->_id . '!'
629 );
630 }
631 $success = true;
632
633 $emitter->emit('contribution.edit', $this);
634 }
635 //update deadline
636 if ($this->isCotis()) {
637 $deadline = $this->updateDeadline();
638 if ($deadline !== true) {
639 //if something went wrong, we rollback transaction
640 throw new \Exception('An error occurred updating member\'s deadline');
641 }
642 }
643
644 //dynamic fields
645 if ($success) {
646 $success = $this->dynamicsStore(true);
647 }
648
649 $this->zdb->connection->commit();
650 $this->_orig_amount = $this->_amount;
651 return true;
652 } catch (\Exception $e) {
653 $this->zdb->connection->rollBack();
654 Analog::log(
655 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
656 $e->getTraceAsString(),
657 Analog::ERROR
658 );
659 return false;
660 }
661 }
662
663 /**
664 * Update member dead line
665 *
666 * @return boolean
667 */
668 private function updateDeadline()
669 {
670 try {
671 $due_date = self::getDueDate($this->zdb, $this->_member);
672
673 if ($due_date != '') {
674 $date_fin_update = $due_date;
675 } else {
676 $date_fin_update = new Expression('NULL');
677 }
678
679 $update = $this->zdb->update(Adherent::TABLE);
680 $update->set(
681 array('date_echeance' => $date_fin_update)
682 )->where(
683 Adherent::PK . '=' . $this->_member
684 );
685 $this->zdb->execute($update);
686 return true;
687 } catch (\Exception $e) {
688 Analog::log(
689 'An error occurred updating member ' . $this->_member .
690 '\'s deadline |' .
691 $e->getMessage(),
692 Analog::ERROR
693 );
694 return false;
695 }
696 }
697
698 /**
699 * Remove contribution from database
700 *
701 * @param boolean $transaction Activate transaction mode (defaults to true)
702 *
703 * @return boolean
704 */
705 public function remove($transaction = true)
706 {
707 global $emitter;
708
709 try {
710 if ($transaction) {
711 $this->zdb->connection->beginTransaction();
712 }
713
714 $delete = $this->zdb->delete(self::TABLE);
715 $delete->where(self::PK . ' = ' . $this->_id);
716 $del = $this->zdb->execute($delete);
717 if ($del->count() > 0) {
718 $this->updateDeadline();
719 $this->dynamicsRemove(true);
720 } else {
721 throw new \RuntimeException(
722 'Contribution has not been removed!'
723 );
724 }
725 if ($transaction) {
726 $this->zdb->connection->commit();
727 }
728 $emitter->emit('contribution.remove', $this);
729 return true;
730 } catch (\Exception $e) {
731 if ($transaction) {
732 $this->zdb->connection->rollBack();
733 }
734 Analog::log(
735 'An error occurred trying to remove contribution #' .
736 $this->_id . ' | ' . $e->getMessage(),
737 Analog::ERROR
738 );
739 return false;
740 }
741 }
742
743 /**
744 * Get field label
745 *
746 * @param string $field Field name
747 *
748 * @return string
749 */
750 public function getFieldLabel($field)
751 {
752 $label = $this->_fields[$field]['label'];
753 if ($this->isCotis() && $field == 'date_debut_cotis') {
754 $label = $this->_fields[$field]['cotlabel'];
755 }
756 //replace "&nbsp;"
757 $label = str_replace('&nbsp;', ' ', $label);
758 //remove trailing ':' and then trim
759 $label = trim(trim($label, ':'));
760 return $label;
761 }
762
763 /**
764 * Retrieve fields from database
765 *
766 * @param Db $zdb Database instance
767 *
768 * @return array
769 */
770 public static function getDbFields(Db $zdb)
771 {
772 $columns = $zdb->getColumns(self::TABLE);
773 $fields = array();
774 foreach ($columns as $col) {
775 $fields[] = $col->getName();
776 }
777 return $fields;
778 }
779
780 /**
781 * Get the relevant CSS class for current contribution
782 *
783 * @return string current contribution row class
784 */
785 public function getRowClass()
786 {
787 return ( $this->_end_date != $this->_begin_date && $this->_is_cotis) ?
788 'cotis-normal' :
789 'cotis-give';
790 }
791
792 /**
793 * Retrieve member due date
794 *
795 * @param Db $zdb Database instance
796 * @param integer $member_id Member identifier
797 *
798 * @return date
799 */
800 public static function getDueDate(Db $zdb, $member_id)
801 {
802 if (!$member_id) {
803 return '';
804 }
805 try {
806 $select = $zdb->select(self::TABLE, 'c');
807 $select->columns(
808 array(
809 'max_date' => new Expression('MAX(date_fin_cotis)')
810 )
811 )->join(
812 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
813 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
814 array()
815 )->where(
816 Adherent::PK . ' = ' . $member_id
817 )->where(
818 array('cotis_extension' => new Expression('true'))
819 );
820
821 $results = $zdb->execute($select);
822 $result = $results->current();
823 $due_date = $result->max_date;
824
825 //avoid bad dates in postgres and bad mysql return from zenddb
826 if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
827 $due_date = '';
828 }
829 return $due_date;
830 } catch (\Exception $e) {
831 Analog::log(
832 'An error occurred trying to retrieve member\'s due date',
833 Analog::ERROR
834 );
835 return false;
836 }
837 }
838
839 /**
840 * Detach a contribution from a transaction
841 *
842 * @param Db $zdb Database instance
843 * @param Login $login Login instance
844 * @param int $trans_id Transaction identifier
845 * @param int $contrib_id Contribution identifier
846 *
847 * @return boolean
848 */
849 public static function unsetTransactionPart(Db $zdb, Login $login, $trans_id, $contrib_id)
850 {
851 try {
852 //first, we check if contribution is part of transaction
853 $c = new Contribution($zdb, $login, (int)$contrib_id);
854 if ($c->isTransactionPartOf($trans_id)) {
855 $update = $zdb->update(self::TABLE);
856 $update->set(
857 array(Transaction::PK => null)
858 )->where(
859 self::PK . ' = ' . $contrib_id
860 );
861 $zdb->execute($update);
862 return true;
863 } else {
864 Analog::log(
865 'Contribution #' . $contrib_id .
866 ' is not actually part of transaction #' . $trans_id,
867 Analog::WARNING
868 );
869 return false;
870 }
871 } catch (\Exception $e) {
872 Analog::log(
873 'Unable to detach contribution #' . $contrib_id .
874 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
875 Analog::ERROR
876 );
877 return false;
878 }
879 }
880
881 /**
882 * Set a contribution as a transaction part
883 *
884 * @param Db $zdb Database instance
885 * @param int $trans_id Transaction identifier
886 * @param int $contrib_id Contribution identifier
887 *
888 * @return boolean
889 */
890 public static function setTransactionPart(Db $zdb, $trans_id, $contrib_id)
891 {
892 try {
893 $update = $zdb->update(self::TABLE);
894 $update->set(
895 array(Transaction::PK => $trans_id)
896 )->where(self::PK . ' = ' . $contrib_id);
897
898 $zdb->execute($update);
899 return true;
900 } catch (\Exception $e) {
901 Analog::log(
902 'Unable to attach contribution #' . $contrib_id .
903 ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
904 Analog::ERROR
905 );
906 return false;
907 }
908 }
909
910 /**
911 * Is current contribution a cotisation
912 *
913 * @return boolean
914 */
915 public function isCotis()
916 {
917 return $this->_is_cotis;
918 }
919
920 /**
921 * Is current contribution part of specified transaction
922 *
923 * @param int $id Transaction identifier
924 *
925 * @return boolean
926 */
927 public function isTransactionPartOf($id)
928 {
929 if ($this->isTransactionPart()) {
930 return $id == $this->_transaction->id;
931 } else {
932 return false;
933 }
934 }
935
936 /**
937 * Is current contribution part of transaction
938 *
939 * @return boolean
940 */
941 public function isTransactionPart()
942 {
943 return $this->_transaction != null;
944 }
945
946 /**
947 * Execute post contribution script
948 *
949 * @param ExternalScript $es External script to execute
950 * @param array $extra Extra information on contribution
951 * Defaults to null
952 * @param array $pextra Extra information on payment
953 * Defaults to null
954 *
955 * @return mixed Script return value on success, values and script output on fail
956 */
957 public function executePostScript(
958 ExternalScript $es,
959 $extra = null,
960 $pextra = null
961 ) {
962 global $preferences;
963
964 $payment = array(
965 'type' => $this->getPaymentType()
966 );
967
968 if ($pextra !== null && is_array($pextra)) {
969 $payment = array_merge($payment, $pextra);
970 }
971
972 if (!file_exists(GALETTE_CACHE_DIR . '/pdf_contribs')) {
973 @mkdir(GALETTE_CACHE_DIR . '/pdf_contribs');
974 }
975
976 $voucher_path = null;
977 if ($this->_id !== null) {
978 $voucher = new PdfContribution($this, $this->zdb, $preferences);
979 $voucher->store(GALETTE_CACHE_DIR . '/pdf_contribs');
980 $voucher_path = $voucher->getPath();
981 }
982
983 $contrib = array(
984 'id' => (int)$this->_id,
985 'date' => $this->_date,
986 'type' => $this->getRawType(),
987 'amount' => $this->amount,
988 'voucher' => $voucher_path,
989 'category' => array(
990 'id' => $this->type->id,
991 'label' => $this->type->libelle
992 ),
993 'payment' => $payment
994 );
995
996 if ($this->_member !== null) {
997 $m = new Adherent($this->zdb, (int)$this->_member);
998 $member = array(
999 'id' => (int)$this->_member,
1000 'name' => $m->sfullname,
1001 'email' => $m->email,
1002 'organization' => ($m->isCompany() ? 1 : 0),
1003 'status' => array(
1004 'id' => $m->status,
1005 'label' => $m->sstatus
1006 ),
1007 'country' => $m->country
1008 );
1009
1010 if ($m->isCompany()) {
1011 $member['organization_name'] = $m->company_name;
1012 }
1013
1014 $contrib['member'] = $member;
1015 }
1016
1017 if ($extra !== null && is_array($extra)) {
1018 $contrib = array_merge($contrib, $extra);
1019 }
1020
1021 $res = $es->send($contrib);
1022
1023 if ($res !== true) {
1024 Analog::log(
1025 'An error occurred calling post contribution ' .
1026 "script:\n" . $es->getOutput(),
1027 Analog::ERROR
1028 );
1029 $res = _T("Contribution information") . "\n";
1030 $res .= print_r($contrib, true);
1031 $res .= "\n\n" . _T("Script output") . "\n";
1032 $res .= $es->getOutput();
1033 }
1034
1035 return $res;
1036 }
1037 /**
1038 * Get raw contribution type
1039 *
1040 * @return string
1041 */
1042 public function getRawType()
1043 {
1044 if ($this->isCotis()) {
1045 return 'membership';
1046 } else {
1047 return 'donation';
1048 }
1049 }
1050
1051 /**
1052 * Get contribution type label
1053 *
1054 * @return string
1055 */
1056 public function getTypeLabel()
1057 {
1058 if ($this->isCotis()) {
1059 return _T("Membership");
1060 } else {
1061 return _T("Donation");
1062 }
1063 }
1064
1065 /**
1066 * Get payment type label
1067 *
1068 * @return string
1069 */
1070 public function getPaymentType()
1071 {
1072 if ($this->_payment_type === null) {
1073 return '-';
1074 }
1075
1076 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1077 return $ptype->getName(false);
1078 }
1079
1080 /**
1081 * Global getter method
1082 *
1083 * @param string $name name of the property we want to retrive
1084 *
1085 * @return false|object the called property
1086 */
1087 public function __get($name)
1088 {
1089
1090 $forbidden = array('is_cotis');
1091 $virtuals = array('duration', 'spayment_type', 'model', 'raw_date',
1092 'raw_begin_date', 'raw_end_date'
1093 );
1094
1095 $rname = '_' . $name;
1096
1097 if (in_array($name, $forbidden)) {
1098 Analog::log(
1099 "Call to __get for '$name' is forbidden!",
1100 Analog::WARNING
1101 );
1102
1103 switch ($name) {
1104 case 'is_cotis':
1105 return $this->isCotis();
1106 break;
1107 default:
1108 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1109 }
1110 } elseif (property_exists($this, $rname)
1111 || in_array($name, $virtuals)
1112 ) {
1113 switch ($name) {
1114 case 'raw_date':
1115 case 'raw_begin_date':
1116 case 'raw_end_date':
1117 $rname = '_' . substr($name, 4);
1118 if ($this->$rname != '') {
1119 try {
1120 $d = new \DateTime($this->$rname);
1121 return $d;
1122 } catch (\Exception $e) {
1123 //oops, we've got a bad date :/
1124 Analog::log(
1125 'Bad date (' . $this->$rname . ') | ' .
1126 $e->getMessage(),
1127 Analog::INFO
1128 );
1129 throw $e;
1130 }
1131 }
1132 break;
1133 case 'date':
1134 case 'begin_date':
1135 case 'end_date':
1136 if ($this->$rname != '') {
1137 try {
1138 $d = new \DateTime($this->$rname);
1139 return $d->format(__("Y-m-d"));
1140 } catch (\Exception $e) {
1141 //oops, we've got a bad date :/
1142 Analog::log(
1143 'Bad date (' . $this->$rname . ') | ' .
1144 $e->getMessage(),
1145 Analog::INFO
1146 );
1147 return $this->$rname;
1148 }
1149 }
1150 break;
1151 case 'duration':
1152 if ($this->_is_cotis) {
1153 $date_end = new \DateTime($this->_end_date);
1154 $date_start = new \DateTime($this->_begin_date);
1155 $diff = $date_end->diff($date_start);
1156 return $diff->format('%y') * 12 + $diff->format('%m');
1157 } else {
1158 return '';
1159 }
1160 break;
1161 case 'spayment_type':
1162 if ($this->_payment_type === null) {
1163 return '-';
1164 }
1165
1166 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1167 return $ptype->getName();
1168
1169 break;
1170 case 'model':
1171 if ($this->_is_cotis === null) {
1172 return null;
1173 }
1174 return ($this->isCotis()) ?
1175 PdfModel::INVOICE_MODEL :
1176 PdfModel::RECEIPT_MODEL;
1177 break;
1178 default:
1179 return $this->$rname;
1180 break;
1181 }
1182 } else {
1183 Analog::log(
1184 "Unknown property '$rname'",
1185 Analog::WARNING
1186 );
1187 return null;
1188 }
1189 }
1190
1191 /**
1192 * Global setter method
1193 *
1194 * @param string $name name of the property we want to assign a value to
1195 * @param object $value a relevant value for the property
1196 *
1197 * @return void
1198 */
1199 public function __set($name, $value)
1200 {
1201 global $preferences;
1202
1203 $forbidden = array('fields', 'is_cotis', 'end_date');
1204
1205 if (!in_array($name, $forbidden)) {
1206 $rname = '_' . $name;
1207 switch ($name) {
1208 case 'transaction':
1209 if (is_int($value)) {
1210 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1211 } else {
1212 Analog::log(
1213 'Trying to set a transaction from an id that is not an integer.',
1214 Analog::WARNING
1215 );
1216 }
1217 break;
1218 case 'type':
1219 if (is_int($value)) {
1220 //set type
1221 $this->$rname = new ContributionsTypes($this->zdb, $value);
1222 //set is_cotis according to type
1223 if ($this->$rname->extension == 1) {
1224 $this->_is_cotis = true;
1225 } else {
1226 $this->_is_cotis = false;
1227 }
1228 } else {
1229 Analog::log(
1230 'Trying to set a type from an id that is not an integer.',
1231 Analog::WARNING
1232 );
1233 }
1234 break;
1235 case 'begin_date':
1236 try {
1237 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1238 if ($d === false) {
1239 throw new \Exception('Incorrect format');
1240 }
1241 $this->_begin_date = $d->format('Y-m-d');
1242 } catch (\Exception $e) {
1243 Analog::log(
1244 'Wrong date format. field: ' . $name .
1245 ', value: ' . $value . ', expected fmt: ' .
1246 __("Y-m-d") . ' | ' . $e->getMessage(),
1247 Analog::INFO
1248 );
1249 $this->errors[] = str_replace(
1250 array(
1251 '%date_format',
1252 '%field'
1253 ),
1254 array(
1255 __("Y-m-d"),
1256 $this->_fields['date_debut_cotis']['label']
1257 ),
1258 _T("- Wrong date format (%date_format) for %field!")
1259 );
1260 }
1261 break;
1262 case 'amount':
1263 if (is_numeric($value) && $value > 0) {
1264 $this->$rname = $value;
1265 } else {
1266 Analog::log(
1267 'Trying to set an amount with a non numeric value, ' .
1268 'or with a zero value',
1269 Analog::WARNING
1270 );
1271 }
1272 break;
1273 case 'member':
1274 if (is_int($value)) {
1275 //set type
1276 $this->$rname = $value;
1277 }
1278 break;
1279 case 'payment_type':
1280 $ptypes = new PaymentTypes(
1281 $this->zdb,
1282 $preferences,
1283 $this->login
1284 );
1285 $list = $ptypes->getList();
1286 if (isset($list[$value])) {
1287 $this->_payment_type = $value;
1288 } else {
1289 Analog::log(
1290 'Unknown payment type ' . $value,
1291 Analog::WARNING
1292 );
1293 }
1294 break;
1295 default:
1296 Analog::log(
1297 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1298 $name . ')',
1299 Analog::WARNING
1300 );
1301 break;
1302 }
1303 }
1304 }
1305 }