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