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