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