]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Contribution.php
Fix CS
[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-2021 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-2021 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 Throwable;
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-2021 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 public const TABLE = 'cotisations';
65 public 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 private $sendmail = false;
90
91 /**
92 * Default constructor
93 *
94 * @param Db $zdb Database
95 * @param Login $login Login instance
96 * @param null|int|ResultSet $args Either a ResultSet row to load
97 * a specific contribution, or an type id
98 * to just instanciate object
99 */
100 public function __construct(Db $zdb, Login $login, $args = null)
101 {
102 $this->zdb = $zdb;
103 $this->login = $login;
104
105 /*
106 * Fields configuration. Each field is an array and must reflect:
107 * array(
108 * (string)label,
109 * (string) propname
110 * )
111 *
112 * I'd prefer a static private variable for this...
113 * But call to the _T function does not seem to be allowed there :/
114 */
115 $this->_fields = array(
116 'id_cotis' => array(
117 'label' => null, //not a field in the form
118 'propname' => 'id'
119 ),
120 Adherent::PK => array(
121 'label' => _T("Contributor:"),
122 'propname' => 'member'
123 ),
124 ContributionsTypes::PK => array(
125 'label' => _T("Contribution type:"),
126 'propname' => 'type'
127 ),
128 'montant_cotis' => array(
129 'label' => _T("Amount:"),
130 'propname' => 'amount'
131 ),
132 'type_paiement_cotis' => array(
133 'label' => _T("Payment type:"),
134 'propname' => 'payment_type'
135 ),
136 'info_cotis' => array(
137 'label' => _T("Comments:"),
138 'propname' => 'info'
139 ),
140 'date_enreg' => array(
141 'label' => null, //not a field in the form
142 'propname' => 'date'
143 ),
144 'date_debut_cotis' => array(
145 'label' => _T("Date of contribution:"),
146 'cotlabel' => _T("Start date of membership:"), //if contribution is a cotisation, label differs
147 'propname' => 'begin_date'
148 ),
149 'date_fin_cotis' => array(
150 'label' => _T("End date of membership:"),
151 'propname' => 'end_date'
152 ),
153 Transaction::PK => array(
154 'label' => null, //not a field in the form
155 'propname' => 'transaction'
156 ),
157 //this one is not really a field, but is required in some cases...
158 //adding it here make simplier to check required fields
159 'duree_mois_cotis' => array(
160 'label' => _T("Membership extension:"),
161 'propname' => 'extension'
162 )
163 );
164 if (is_int($args)) {
165 $this->load($args);
166 } elseif (is_array($args)) {
167 $this->_date = date("Y-m-d");
168 if (isset($args['adh']) && $args['adh'] != '') {
169 $this->_member = (int)$args['adh'];
170 }
171 if (isset($args['trans'])) {
172 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$args['trans']);
173 if (!isset($this->_member)) {
174 $this->_member = (int)$this->_transaction->member;
175 }
176 $this->_amount = $this->_transaction->getMissingAmount();
177 }
178 $this->type = (int)$args['type'];
179 //calculate begin date for cotisation
180 $this->_begin_date = $this->_date;
181 if ($this->_is_cotis) {
182 $curend = self::getDueDate($this->zdb, $this->_member);
183 if ($curend != '') {
184 $dend = new \DateTime($curend);
185 $now = date('Y-m-d');
186 $dnow = new \DateTime($now);
187 if ($dend < $dnow) {
188 // Member didn't renew on time
189 $this->_begin_date = $now;
190 } else {
191 $this->_begin_date = $curend;
192 }
193 }
194 $this->retrieveEndDate();
195 }
196 if (isset($args['payment_type'])) {
197 $this->_payment_type = $args['payment_type'];
198 }
199 } elseif (is_object($args)) {
200 $this->loadFromRS($args);
201 }
202
203 $this->loadDynamicFields();
204 }
205
206 /**
207 * Sets end contribution date
208 *
209 * @return void
210 */
211 private function retrieveEndDate()
212 {
213 global $preferences;
214
215 $bdate = new \DateTime($this->_begin_date);
216 if ($preferences->pref_beg_membership != '') {
217 //case beginning of membership
218 list($j, $m) = explode('/', $preferences->pref_beg_membership);
219 $edate = new \DateTime($bdate->format('Y') . '-' . $m . '-' . $j);
220 while ($edate <= $bdate) {
221 $edate->modify('+1 year');
222 }
223
224 if ($preferences->pref_membership_offermonths > 0) {
225 //count days until end of membership date
226 $diff1 = (int)$bdate->diff($edate)->format('%a');
227
228 //count days beetween end of membership date and offered months
229 $tdate = clone $edate;
230 $tdate->modify('-' . $preferences->pref_membership_offermonths . ' month');
231 $diff2 = (int)$edate->diff($tdate)->format('%a');
232
233 //when number of days until end of membership is less than for offered months, it's free :)
234 if ($diff1 <= $diff2) {
235 $edate->modify('+1 year');
236 }
237 }
238
239 $this->_end_date = $edate->format('Y-m-d');
240 } elseif ($preferences->pref_membership_ext != '') {
241 //case membership extension
242 if ($this->_extension == null) {
243 $this->_extension = $preferences->pref_membership_ext;
244 }
245 $dext = new \DateInterval('P' . $this->_extension . 'M');
246 $edate = $bdate->add($dext);
247 $this->_end_date = $edate->format('Y-m-d');
248 } else {
249 throw new \RuntimeException(
250 'Unable to define end date; none of pref_beg_membership nor pref_membership_ext are defined!'
251 );
252 }
253 }
254
255 /**
256 * Loads a contribution from its id
257 *
258 * @param int $id the identifiant for the contribution to load
259 *
260 * @return bool true if query succeed, false otherwise
261 */
262 public function load($id)
263 {
264 try {
265 $select = $this->zdb->select(self::TABLE);
266 $select->where(self::PK . ' = ' . $id);
267 //restrict query on current member id if he's not admin nor staff member
268 if (!$this->login->isAdmin() && !$this->login->isStaff()) {
269 $select->where(Adherent::PK . ' = ' . $this->login->id);
270 }
271
272 $results = $this->zdb->execute($select);
273 if ($results->count() > 0) {
274 $row = $results->current();
275 $this->loadFromRS($row);
276 return true;
277 } else {
278 throw new \Exception(
279 'No contribution #' . $id . ' (user ' . $this->login->id . ')'
280 );
281 }
282 } catch (Throwable $e) {
283 Analog::log(
284 'An error occurred attempting to load contribution #' . $id .
285 $e->getMessage(),
286 Analog::ERROR
287 );
288 return false;
289 }
290 }
291
292 /**
293 * Populate object from a resultset row
294 *
295 * @param ResultSet $r the resultset row
296 *
297 * @return void
298 */
299 private function loadFromRS($r)
300 {
301 $pk = self::PK;
302 $this->_id = (int)$r->$pk;
303 $this->_date = $r->date_enreg;
304 $this->_amount = $r->montant_cotis;
305 //save original amount, we need it for transactions parts calulations
306 $this->_orig_amount = $r->montant_cotis;
307 $this->_payment_type = $r->type_paiement_cotis;
308 $this->_info = $r->info_cotis;
309 $this->_begin_date = $r->date_debut_cotis;
310 $enddate = $r->date_fin_cotis;
311 //do not work with knows bad dates...
312 //the one with BC comes from 0.63/pgsl demo... Why the hell a so
313 //strange date? dont know :(
314 if (
315 $enddate !== '0000-00-00'
316 && $enddate !== '1901-01-01'
317 && $enddate !== '0001-01-01 BC'
318 ) {
319 $this->_end_date = $r->date_fin_cotis;
320 }
321 $adhpk = Adherent::PK;
322 $this->_member = (int)$r->$adhpk;
323
324 $transpk = Transaction::PK;
325 if ($r->$transpk != '') {
326 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$r->$transpk);
327 }
328
329 $this->type = (int)$r->id_type_cotis;
330 $this->loadDynamicFields();
331 }
332
333 /**
334 * Check posted values validity
335 *
336 * @param array $values All values to check, basically the $_POST array
337 * after sending the form
338 * @param array $required Array of required fields
339 * @param array $disabled Array of disabled fields
340 *
341 * @return true|array
342 */
343 public function check($values, $required, $disabled)
344 {
345 global $preferences;
346 $this->errors = array();
347
348 $fields = array_keys($this->_fields);
349 foreach ($fields as $key) {
350 //first of all, let's sanitize values
351 $key = strtolower($key);
352 $prop = '_' . $this->_fields[$key]['propname'];
353
354 if (isset($values[$key])) {
355 $value = trim($values[$key]);
356 } else {
357 $value = '';
358 }
359
360 // if the field is enabled, check it
361 if (!isset($disabled[$key])) {
362 // fill up the adherent structure
363 //$this->$prop = stripslashes($value); //not relevant here!
364
365 // now, check validity
366 switch ($key) {
367 // dates
368 case 'date_enreg':
369 case 'date_debut_cotis':
370 case 'date_fin_cotis':
371 if ($value != '') {
372 try {
373 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
374 if ($d === false) {
375 throw new \Exception('Incorrect format');
376 }
377 $this->$prop = $d->format('Y-m-d');
378 } catch (Throwable $e) {
379 Analog::log(
380 'Wrong date format. field: ' . $key .
381 ', value: ' . $value . ', expected fmt: ' .
382 __("Y-m-d") . ' | ' . $e->getMessage(),
383 Analog::INFO
384 );
385 $this->errors[] = str_replace(
386 array(
387 '%date_format',
388 '%field'
389 ),
390 array(
391 __("Y-m-d"),
392 $this->_fields[$key]['label']
393 ),
394 _T("- Wrong date format (%date_format) for %field!")
395 );
396 }
397 }
398 break;
399 case Adherent::PK:
400 if ($value != '') {
401 $this->_member = (int)$value;
402 }
403 break;
404 case ContributionsTypes::PK:
405 if ($value != '') {
406 $this->type = (int)$value;
407 }
408 break;
409 case 'montant_cotis':
410 $this->_amount = $value;
411 $value = strtr($value, ',', '.');
412 if (!is_numeric($value) && $value !== '') {
413 $this->errors[] = _T("- The amount must be an integer!");
414 }
415 break;
416 case 'type_paiement_cotis':
417 $ptypes = new PaymentTypes(
418 $this->zdb,
419 $preferences,
420 $this->login
421 );
422 $ptlist = $ptypes->getList();
423 if (isset($ptlist[$value])) {
424 $this->_payment_type = $value;
425 } else {
426 $this->errors[] = _T("- Unknown payment type");
427 }
428 break;
429 case 'info_cotis':
430 $this->_info = $value;
431 break;
432 case Transaction::PK:
433 if ($value != '') {
434 $this->_transaction = new Transaction($this->zdb, $this->login, (int)$value);
435 }
436 break;
437 case 'duree_mois_cotis':
438 if ($value != '') {
439 if (!is_numeric($value) || $value <= 0) {
440 $this->errors[] = _T("- The duration must be a positive integer!");
441 }
442 $this->$prop = $value;
443 $this->retrieveEndDate();
444 }
445 break;
446 }
447 }
448 }
449
450 // missing required fields?
451 foreach ($required as $key => $val) {
452 if ($val === 1) {
453 $prop = '_' . $this->_fields[$key]['propname'];
454 if (
455 !isset($disabled[$key])
456 && (!isset($this->$prop)
457 || (!is_object($this->$prop) && trim($this->$prop) == '')
458 || (is_object($this->$prop) && trim($this->$prop->id) == ''))
459 ) {
460 $this->errors[] = str_replace(
461 '%field',
462 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
463 _T("- Mandatory field %field empty.")
464 );
465 }
466 }
467 }
468
469 if ($this->_transaction != null && $this->_amount != null) {
470 $missing = $this->_transaction->getMissingAmount();
471 //calculate new missing amount
472 $missing = $missing + $this->_orig_amount - $this->_amount;
473 if ($missing < 0) {
474 $this->errors[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
475 }
476 }
477
478 if ($this->isCotis() && count($this->errors) == 0) {
479 $overlap = $this->checkOverlap();
480 if ($overlap !== true) {
481 if ($overlap === false) {
482 $this->errors[] = _T("An error occurred checking overlaping fees :(");
483 } else {
484 //method directly return error message
485 $this->errors[] = $overlap;
486 }
487 }
488 }
489
490 $this->dynamicsCheck($values, $required, $disabled);
491
492 if (count($this->errors) > 0) {
493 Analog::log(
494 'Some errors has been throwed attempting to edit/store a contribution' .
495 print_r($this->errors, true),
496 Analog::ERROR
497 );
498 return $this->errors;
499 } else {
500 Analog::log(
501 'Contribution checked successfully.',
502 Analog::DEBUG
503 );
504 return true;
505 }
506 }
507
508 /**
509 * Check that membership fees does not overlap
510 *
511 * @return boolean|string True if all is ok, false if error,
512 * error message if overlap
513 */
514 public function checkOverlap()
515 {
516 try {
517 $select = $this->zdb->select(self::TABLE, 'c');
518 $select->columns(
519 array('date_debut_cotis', 'date_fin_cotis')
520 )->join(
521 array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
522 'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
523 array()
524 )->where(Adherent::PK . ' = ' . $this->_member)
525 ->where(array('cotis_extension' => new Expression('true')))
526 ->where->nest->nest
527 ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date)
528 ->lessThan('date_debut_cotis', $this->_end_date)
529 ->unnest
530 ->or->nest
531 ->greaterThan('date_fin_cotis', $this->_begin_date)
532 ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date);
533
534 if ($this->id != '') {
535 $select->where(self::PK . ' != ' . $this->id);
536 }
537
538 $results = $this->zdb->execute($select);
539 if ($results->count() > 0) {
540 $result = $results->current();
541 $d = new \DateTime($result->date_debut_cotis);
542
543 return _T("- Membership period overlaps period starting at ") .
544 $d->format(__("Y-m-d"));
545 }
546 return true;
547 } catch (Throwable $e) {
548 Analog::log(
549 'An error occurred checking overlaping fee. ' . $e->getMessage(),
550 Analog::ERROR
551 );
552 return false;
553 }
554 }
555
556 /**
557 * Store the contribution
558 *
559 * @return boolean
560 */
561 public function store()
562 {
563 global $hist, $emitter;
564
565 $event = null;
566
567 if (count($this->errors) > 0) {
568 throw new \RuntimeException(
569 'Existing errors prevents storing contribution: ' .
570 print_r($this->errors, true)
571 );
572 }
573
574 try {
575 $this->zdb->connection->beginTransaction();
576 $values = array();
577 $fields = self::getDbFields($this->zdb);
578 foreach ($fields as $field) {
579 $prop = '_' . $this->_fields[$field]['propname'];
580 switch ($field) {
581 case ContributionsTypes::PK:
582 case Transaction::PK:
583 if (isset($this->$prop)) {
584 $values[$field] = $this->$prop->id;
585 }
586 break;
587 default:
588 $values[$field] = $this->$prop;
589 break;
590 }
591 }
592
593 //no end date, let's take database defaults
594 if (!$this->isCotis() && !$this->_end_date) {
595 unset($values['date_fin_cotis']);
596 }
597
598 $success = false;
599 if (!isset($this->_id) || $this->_id == '') {
600 //we're inserting a new contribution
601 unset($values[self::PK]);
602
603 $insert = $this->zdb->insert(self::TABLE);
604 $insert->values($values);
605 $add = $this->zdb->execute($insert);
606
607 if ($add->count() > 0) {
608 $this->_id = $this->zdb->getLastGeneratedValue($this);
609
610 // logging
611 $hist->add(
612 _T("Contribution added"),
613 Adherent::getSName($this->zdb, $this->_member)
614 );
615 $success = true;
616 $event = 'contribution.add';
617 } else {
618 $hist->add(_T("Fail to add new contribution."));
619 throw new \Exception(
620 'An error occurred inserting new contribution!'
621 );
622 }
623 } else {
624 //we're editing an existing contribution
625 $update = $this->zdb->update(self::TABLE);
626 $update->set($values)->where(
627 self::PK . '=' . $this->_id
628 );
629 $edit = $this->zdb->execute($update);
630
631 //edit == 0 does not mean there were an error, but that there
632 //were nothing to change
633 if ($edit->count() > 0) {
634 $hist->add(
635 _T("Contribution updated"),
636 Adherent::getSName($this->zdb, $this->_member)
637 );
638 }
639
640 if ($edit === false) {
641 throw new \Exception(
642 'An error occurred updating contribution # ' . $this->_id . '!'
643 );
644 }
645 $success = true;
646 $event = 'contribution.edit';
647 }
648 //update deadline
649 if ($this->isCotis()) {
650 $deadline = $this->updateDeadline();
651 if ($deadline !== true) {
652 //if something went wrong, we rollback transaction
653 throw new \Exception('An error occurred updating member\'s deadline');
654 }
655 }
656
657 //dynamic fields
658 if ($success) {
659 $success = $this->dynamicsStore(true);
660 }
661
662 $this->zdb->connection->commit();
663 $this->_orig_amount = $this->_amount;
664
665 //send event at the end of process, once all has been stored
666 if ($event !== null) {
667 $emitter->emit($event, $this);
668 }
669
670 return true;
671 } catch (Throwable $e) {
672 if ($this->zdb->connection->inTransaction()) {
673 $this->zdb->connection->rollBack();
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 (Throwable $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 (Throwable $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 (Throwable $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 (Throwable $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 (Throwable $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 (
1126 property_exists($this, $rname)
1127 || in_array($name, $virtuals)
1128 ) {
1129 switch ($name) {
1130 case 'raw_date':
1131 case 'raw_begin_date':
1132 case 'raw_end_date':
1133 $rname = '_' . substr($name, 4);
1134 if ($this->$rname != '') {
1135 try {
1136 $d = new \DateTime($this->$rname);
1137 return $d;
1138 } catch (Throwable $e) {
1139 //oops, we've got a bad date :/
1140 Analog::log(
1141 'Bad date (' . $this->$rname . ') | ' .
1142 $e->getMessage(),
1143 Analog::INFO
1144 );
1145 throw $e;
1146 }
1147 }
1148 break;
1149 case 'date':
1150 case 'begin_date':
1151 case 'end_date':
1152 if ($this->$rname != '') {
1153 try {
1154 $d = new \DateTime($this->$rname);
1155 return $d->format(__("Y-m-d"));
1156 } catch (Throwable $e) {
1157 //oops, we've got a bad date :/
1158 Analog::log(
1159 'Bad date (' . $this->$rname . ') | ' .
1160 $e->getMessage(),
1161 Analog::INFO
1162 );
1163 return $this->$rname;
1164 }
1165 }
1166 break;
1167 case 'duration':
1168 if ($this->_is_cotis) {
1169 $date_end = new \DateTime($this->_end_date);
1170 $date_start = new \DateTime($this->_begin_date);
1171 $diff = $date_end->diff($date_start);
1172 return $diff->format('%y') * 12 + $diff->format('%m');
1173 } else {
1174 return '';
1175 }
1176 break;
1177 case 'spayment_type':
1178 if ($this->_payment_type === null) {
1179 return '-';
1180 }
1181
1182 $ptype = new PaymentType($this->zdb, (int)$this->payment_type);
1183 return $ptype->getName();
1184
1185 break;
1186 case 'model':
1187 if ($this->_is_cotis === null) {
1188 return null;
1189 }
1190 return ($this->isCotis()) ?
1191 PdfModel::INVOICE_MODEL : PdfModel::RECEIPT_MODEL;
1192 break;
1193 default:
1194 return $this->$rname;
1195 break;
1196 }
1197 } else {
1198 Analog::log(
1199 "Unknown property '$rname'",
1200 Analog::WARNING
1201 );
1202 return null;
1203 }
1204 }
1205
1206 /**
1207 * Global setter method
1208 *
1209 * @param string $name name of the property we want to assign a value to
1210 * @param object $value a relevant value for the property
1211 *
1212 * @return void
1213 */
1214 public function __set($name, $value)
1215 {
1216 global $preferences;
1217
1218 $forbidden = array('fields', 'is_cotis', 'end_date');
1219
1220 if (!in_array($name, $forbidden)) {
1221 $rname = '_' . $name;
1222 switch ($name) {
1223 case 'transaction':
1224 if (is_int($value)) {
1225 $this->$rname = new Transaction($this->zdb, $this->login, $value);
1226 } else {
1227 Analog::log(
1228 'Trying to set a transaction from an id that is not an integer.',
1229 Analog::WARNING
1230 );
1231 }
1232 break;
1233 case 'type':
1234 if (is_int($value)) {
1235 //set type
1236 $this->$rname = new ContributionsTypes($this->zdb, $value);
1237 //set is_cotis according to type
1238 if ($this->$rname->extension == 1) {
1239 $this->_is_cotis = true;
1240 } else {
1241 $this->_is_cotis = false;
1242 }
1243 } else {
1244 Analog::log(
1245 'Trying to set a type from an id that is not an integer.',
1246 Analog::WARNING
1247 );
1248 }
1249 break;
1250 case 'begin_date':
1251 try {
1252 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1253 if ($d === false) {
1254 throw new \Exception('Incorrect format');
1255 }
1256 $this->_begin_date = $d->format('Y-m-d');
1257 } catch (Throwable $e) {
1258 Analog::log(
1259 'Wrong date format. field: ' . $name .
1260 ', value: ' . $value . ', expected fmt: ' .
1261 __("Y-m-d") . ' | ' . $e->getMessage(),
1262 Analog::INFO
1263 );
1264 $this->errors[] = str_replace(
1265 array(
1266 '%date_format',
1267 '%field'
1268 ),
1269 array(
1270 __("Y-m-d"),
1271 $this->_fields['date_debut_cotis']['label']
1272 ),
1273 _T("- Wrong date format (%date_format) for %field!")
1274 );
1275 }
1276 break;
1277 case 'amount':
1278 if (is_numeric($value) && $value > 0) {
1279 $this->$rname = $value;
1280 } else {
1281 Analog::log(
1282 'Trying to set an amount with a non numeric value, ' .
1283 'or with a zero value',
1284 Analog::WARNING
1285 );
1286 }
1287 break;
1288 case 'member':
1289 if (is_int($value)) {
1290 //set type
1291 $this->$rname = $value;
1292 }
1293 break;
1294 case 'payment_type':
1295 $ptypes = new PaymentTypes(
1296 $this->zdb,
1297 $preferences,
1298 $this->login
1299 );
1300 $list = $ptypes->getList();
1301 if (isset($list[$value])) {
1302 $this->_payment_type = $value;
1303 } else {
1304 Analog::log(
1305 'Unknown payment type ' . $value,
1306 Analog::WARNING
1307 );
1308 }
1309 break;
1310 default:
1311 Analog::log(
1312 '[' . __CLASS__ . ']: Trying to set an unknown property (' .
1313 $name . ')',
1314 Analog::WARNING
1315 );
1316 break;
1317 }
1318 }
1319 }
1320
1321 /**
1322 * Flag creation mail sending
1323 *
1324 * @param boolean $send True (default) to send creation email
1325 *
1326 * @return Contribution
1327 */
1328 public function setSendmail($send = true)
1329 {
1330 $this->sendmail = $send;
1331 return $this;
1332 }
1333
1334 /**
1335 * Should we send administrative emails to member?
1336 *
1337 * @return boolean
1338 */
1339 public function sendEMail()
1340 {
1341 return $this->sendmail;
1342 }
1343
1344 /**
1345 * Handle files (dynamics files)
1346 *
1347 * @param array $files Files sent
1348 *
1349 * @return array|true
1350 */
1351 public function handleFiles($files)
1352 {
1353 $this->errors = [];
1354
1355 $this->dynamicsFiles($files);
1356
1357 if (count($this->errors) > 0) {
1358 Analog::log(
1359 'Some errors has been throwed attempting to edit/store a contribution files' . "\n" .
1360 print_r($this->errors, true),
1361 Analog::ERROR
1362 );
1363 return $this->errors;
1364 } else {
1365 return true;
1366 }
1367 }
1368 }