]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Transaction.php
08caee36c5379e7b7f0d4c35dbddfb66bd67c704
[galette.git] / galette / lib / Galette / Entity / Transaction.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Transaction class for galette
7 *
8 * PHP version 5
9 *
10 * Copyright © 2011-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 2011-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 - 2011-07-31
35 */
36
37 namespace Galette\Entity;
38
39 use Throwable;
40 use Analog\Analog;
41 use Laminas\Db\Sql\Expression;
42 use Galette\Repository\Contributions;
43 use Galette\Core\Db;
44 use Galette\Core\History;
45 use Galette\Core\Login;
46 use Galette\Features\Dynamics;
47
48 /**
49 * Transaction class for galette
50 *
51 * @category Entity
52 * @name Transaction
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 * @property integer $id
61 * @property date $date
62 * @property integer $amount
63 * @property string $description
64 * @property integer $member
65 */
66 class Transaction
67 {
68 use Dynamics;
69
70 public const TABLE = 'transactions';
71 public const PK = 'trans_id';
72
73 private $_id;
74 private $_date;
75 private $_amount;
76 private $_description;
77 private $_member;
78
79 //fields list and their translation
80 private $_fields;
81
82 private $zdb;
83 private $login;
84
85 private $errors;
86
87 /**
88 * Default constructor
89 *
90 * @param Db $zdb Database instance
91 * @param Login $login Login instance
92 * @param null|int|ResultSet $args Either a ResultSet row or its id for to load
93 * a specific transaction, or null to just
94 * instantiate object
95 */
96 public function __construct(Db $zdb, Login $login, $args = null)
97 {
98 $this->zdb = $zdb;
99 $this->login = $login;
100
101 /*
102 * Fields configuration. Each field is an array and must reflect:
103 * array(
104 * (string)label,
105 * (string) propname
106 * )
107 *
108 * I'd prefer a static private variable for this...
109 * But call to the _T function does not seem to be allowed there :/
110 */
111 $this->_fields = array(
112 self::PK => array(
113 'label' => null, //not a field in the form
114 'propname' => 'id'
115 ),
116 'trans_date' => array(
117 'label' => _T("Date:"), //not a field in the form
118 'propname' => 'date'
119 ),
120 'trans_amount' => array(
121 'label' => _T("Amount:"),
122 'propname' => 'amount'
123 ),
124 'trans_desc' => array(
125 'label' => _T("Description:"),
126 'propname' => 'description'
127 ),
128 Adherent::PK => array(
129 'label' => _T("Originator:"),
130 'propname' => 'member'
131 )
132 );
133 if ($args == null || is_int($args)) {
134 $this->_date = date("Y-m-d");
135
136 if (is_int($args) && $args > 0) {
137 $this->load($args);
138 }
139 } elseif (is_object($args)) {
140 $this->loadFromRS($args);
141 }
142
143 $this->loadDynamicFields();
144 }
145
146 /**
147 * Loads a transaction from its id
148 *
149 * @param int $id the identifier for the transaction to load
150 *
151 * @return bool true if query succeed, false otherwise
152 */
153 public function load($id)
154 {
155 try {
156 $select = $this->zdb->select(self::TABLE, 't');
157 $select->where([self::PK => $id]);
158 $select->join(
159 array('a' => PREFIX_DB . Adherent::TABLE),
160 't.' . Adherent::PK . '=a.' . Adherent::PK,
161 array()
162 );
163
164 //restrict query on current member id if he's not admin nor staff member
165 if (!$this->login->isAdmin() && !$this->login->isStaff() && !$this->login->isGroupManager()) {
166 if (!$this->login->isLogged()) {
167 Analog::log(
168 'Non-logged-in users cannot load transaction id `' . $id,
169 Analog::ERROR
170 );
171 return false;
172 }
173 $select->where
174 ->nest()
175 ->equalTo('a.' . Adherent::PK, $this->login->id)
176 ->or
177 ->equalTo('a.parent_id', $this->login->id)
178 ->unnest()
179 ->and
180 ->equalTo('t.' . self::PK, $id)
181 ;
182 } else {
183 $select->where->equalTo(self::PK, $id);
184 }
185
186 $results = $this->zdb->execute($select);
187 $result = $results->current();
188 if ($result) {
189 $this->loadFromRS($result);
190 return true;
191 } else {
192 Analog::log(
193 'Transaction id `' . $id . '` does not exists',
194 Analog::WARNING
195 );
196 return false;
197 }
198 } catch (Throwable $e) {
199 Analog::log(
200 'Cannot load transaction form id `' . $id . '` | ' .
201 $e->getMessage(),
202 Analog::WARNING
203 );
204 throw $e;
205 }
206 }
207
208 /**
209 * Remove transaction (and all associated contributions) from database
210 *
211 * @param History $hist History
212 * @param boolean $transaction Activate transaction mode (defaults to true)
213 *
214 * @return boolean
215 */
216 public function remove(History $hist, $transaction = true)
217 {
218 global $emitter;
219
220 try {
221 if ($transaction) {
222 $this->zdb->connection->beginTransaction();
223 }
224
225 //remove associated contributions if needeed
226 if ($this->getDispatchedAmount() > 0) {
227 $c = new Contributions($this->zdb, $this->login);
228 $clist = $c->getListFromTransaction($this->_id);
229 $cids = array();
230 foreach ($clist as $cid) {
231 $cids[] = $cid->id;
232 }
233 $rem = $c->remove($cids, $hist, false);
234 }
235
236 //remove transaction itself
237 $delete = $this->zdb->delete(self::TABLE);
238 $delete->where([self::PK => $this->_id]);
239 $del = $this->zdb->execute($delete);
240 if ($del->count() > 0) {
241 $this->dynamicsRemove(true);
242 } else {
243 Analog::log(
244 'Transaction has not been removed!',
245 Analog::WARNING
246 );
247 return false;
248 }
249
250 if ($transaction) {
251 $this->zdb->connection->commit();
252 }
253
254 $emitter->emit('transaction.remove', $this);
255 return true;
256 } catch (Throwable $e) {
257 if ($transaction) {
258 $this->zdb->connection->rollBack();
259 }
260 Analog::log(
261 'An error occurred trying to remove transaction #' .
262 $this->_id . ' | ' . $e->getMessage(),
263 Analog::ERROR
264 );
265 throw $e;
266 }
267 }
268
269 /**
270 * Populate object from a resultset row
271 *
272 * @param ResultSet $r the resultset row
273 *
274 * @return void
275 */
276 private function loadFromRS($r)
277 {
278 $pk = self::PK;
279 $this->_id = $r->$pk;
280 $this->_date = $r->trans_date;
281 $this->_amount = $r->trans_amount;
282 $this->_description = $r->trans_desc;
283 $adhpk = Adherent::PK;
284 $this->_member = (int)$r->$adhpk;
285
286 $this->loadDynamicFields();
287 }
288
289 /**
290 * Check posted values validity
291 *
292 * @param array $values All values to check, basically the $_POST array
293 * after sending the form
294 * @param array $required Array of required fields
295 * @param array $disabled Array of disabled fields
296 *
297 * @return true|array
298 */
299 public function check($values, $required, $disabled)
300 {
301 $this->errors = array();
302
303 $fields = array_keys($this->_fields);
304 foreach ($fields as $key) {
305 //first, let's sanitize values
306 $key = strtolower($key);
307 $prop = '_' . $this->_fields[$key]['propname'];
308
309 if (isset($values[$key])) {
310 $value = trim($values[$key]);
311 } else {
312 $value = '';
313 }
314
315 // if the field is enabled, check it
316 if (!isset($disabled[$key])) {
317 // now, check validity
318 if ($value != '') {
319 switch ($key) {
320 // dates
321 case 'trans_date':
322 try {
323 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
324 if ($d === false) {
325 throw new \Exception('Incorrect format');
326 }
327 $this->$prop = $d->format('Y-m-d');
328 } catch (Throwable $e) {
329 Analog::log(
330 'Wrong date format. field: ' . $key .
331 ', value: ' . $value . ', expected fmt: ' .
332 __("Y-m-d") . ' | ' . $e->getMessage(),
333 Analog::INFO
334 );
335 $this->errors[] = str_replace(
336 array(
337 '%date_format',
338 '%field'
339 ),
340 array(
341 __("Y-m-d"),
342 $this->getFieldLabel($key)
343 ),
344 _T("- Wrong date format (%date_format) for %field!")
345 );
346 }
347 break;
348 case Adherent::PK:
349 $this->_member = (int)$value;
350 break;
351 case 'trans_amount':
352 $this->_amount = $value;
353 $value = strtr($value, ',', '.');
354 if (!is_numeric($value)) {
355 $this->errors[] = _T("- The amount must be an integer!");
356 }
357 break;
358 case 'trans_desc':
359 /** TODO: retrieve field length from database and check that */
360 $this->_description = $value;
361 if (mb_strlen($value) > 150) {
362 $this->errors[] = _T("- Transaction description must be 150 characters long maximum.");
363 }
364 break;
365 }
366 }
367 }
368 }
369
370 // missing required fields?
371 foreach ($required as $key => $val) {
372 if ($val === 1) {
373 $prop = '_' . $this->_fields[$key]['propname'];
374 if (!isset($disabled[$key]) && !isset($this->$prop)) {
375 $this->errors[] = str_replace(
376 '%field',
377 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
378 _T("- Mandatory field %field empty.")
379 );
380 }
381 }
382 }
383
384 if ($this->_id != '') {
385 $dispatched = $this->getDispatchedAmount();
386 if ($dispatched > $this->_amount) {
387 $this->errors[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
388 }
389 }
390
391 $this->dynamicsCheck($values, $required, $disabled);
392
393 if (count($this->errors) > 0) {
394 Analog::log(
395 'Some errors has been thew attempting to edit/store a transaction' .
396 print_r($this->errors, true),
397 Analog::DEBUG
398 );
399 return $this->errors;
400 } else {
401 Analog::log(
402 'Transaction checked successfully.',
403 Analog::DEBUG
404 );
405 return true;
406 }
407 }
408
409 /**
410 * Store the transaction
411 *
412 * @param History $hist History
413 *
414 * @return boolean
415 */
416 public function store(History $hist)
417 {
418 global $emitter;
419
420 $event = null;
421
422 try {
423 $this->zdb->connection->beginTransaction();
424 $values = array();
425 $fields = $this->getDbFields($this->zdb);
426 /** FIXME: quote? */
427 foreach ($fields as $field) {
428 $prop = '_' . $this->_fields[$field]['propname'];
429 $values[$field] = $this->$prop;
430 }
431
432 $success = false;
433 if (!isset($this->_id) || $this->_id == '') {
434 //we're inserting a new transaction
435 unset($values[self::PK]);
436 $insert = $this->zdb->insert(self::TABLE);
437 $insert->values($values);
438 $add = $this->zdb->execute($insert);
439 if ($add->count() > 0) {
440 $this->_id = $this->zdb->getLastGeneratedValue($this);
441
442 // logging
443 $hist->add(
444 _T("Transaction added"),
445 Adherent::getSName($this->zdb, $this->_member)
446 );
447 $success = true;
448 $event = 'transaction.add';
449 } else {
450 $hist->add(_T("Fail to add new transaction."));
451 throw new \RuntimeException(
452 'An error occurred inserting new transaction!'
453 );
454 }
455 } else {
456 //we're editing an existing transaction
457 $update = $this->zdb->update(self::TABLE);
458 $update->set($values)->where([self::PK => $this->_id]);
459 $edit = $this->zdb->execute($update);
460 //edit == 0 does not mean there were an error, but that there
461 //were nothing to change
462 if ($edit->count() > 0) {
463 $hist->add(
464 _T("Transaction updated"),
465 Adherent::getSName($this->zdb, $this->_member)
466 );
467 }
468 $success = true;
469 $event = 'transaction.edit';
470 }
471
472 //dynamic fields
473 if ($success) {
474 $success = $this->dynamicsStore(true);
475 }
476
477 $this->zdb->connection->commit();
478
479 //send event at the end of process, once all has been stored
480 if ($event !== null) {
481 $emitter->emit($event, $this);
482 }
483
484 return true;
485 } catch (Throwable $e) {
486 $this->zdb->connection->rollBack();
487 Analog::log(
488 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
489 $e->getTraceAsString(),
490 Analog::ERROR
491 );
492 throw $e;
493 }
494 }
495
496 /**
497 * Retrieve amount that has already been dispatched into contributions
498 *
499 * @return double
500 */
501 public function getDispatchedAmount(): float
502 {
503 if (empty($this->_id)) {
504 return (double)0;
505 }
506
507 try {
508 $select = $this->zdb->select(Contribution::TABLE);
509 $select->columns(
510 array(
511 'sum' => new Expression('SUM(montant_cotis)')
512 )
513 )->where([self::PK => $this->_id]);
514
515 $results = $this->zdb->execute($select);
516 $result = $results->current();
517 $dispatched_amount = $result->sum;
518 return (double)$dispatched_amount;
519 } catch (Throwable $e) {
520 Analog::log(
521 'An error occurred retrieving dispatched amounts | ' .
522 $e->getMessage(),
523 Analog::ERROR
524 );
525 throw $e;
526 }
527 }
528
529 /**
530 * Retrieve amount that has not yet been dispatched into contributions
531 *
532 * @return double
533 */
534 public function getMissingAmount()
535 {
536 if (empty($this->_id)) {
537 return (double)$this->amount;
538 }
539
540 try {
541 $select = $this->zdb->select(Contribution::TABLE);
542 $select->columns(
543 array(
544 'sum' => new Expression('SUM(montant_cotis)')
545 )
546 )->where([self::PK => $this->_id]);
547
548 $results = $this->zdb->execute($select);
549 $result = $results->current();
550 $dispatched_amount = $result->sum;
551 return (double)$this->_amount - (double)$dispatched_amount;
552 } catch (Throwable $e) {
553 Analog::log(
554 'An error occurred retrieving missing amounts | ' .
555 $e->getMessage(),
556 Analog::ERROR
557 );
558 throw $e;
559 }
560 }
561
562 /**
563 * Retrieve fields from database
564 *
565 * @param Db $zdb Database instance
566 *
567 * @return array
568 */
569 public function getDbFields(Db $zdb)
570 {
571 $columns = $zdb->getColumns(self::TABLE);
572 $fields = array();
573 foreach ($columns as $col) {
574 $fields[] = $col->getName();
575 }
576 return $fields;
577 }
578
579 /**
580 * Get the relevant CSS class for current transaction
581 *
582 * @return string current transaction row class
583 */
584 public function getRowClass()
585 {
586 return ($this->getMissingAmount() == 0) ?
587 'transaction-normal' : 'transaction-uncomplete';
588 }
589
590 /**
591 * Global getter method
592 *
593 * @param string $name name of the property we want to retrive
594 *
595 * @return false|object the called property
596 */
597 public function __get($name)
598 {
599 $forbidden = array();
600
601 $rname = '_' . $name;
602 if (!in_array($name, $forbidden) && property_exists($this, $rname)) {
603 switch ($name) {
604 case 'date':
605 if ($this->$rname != '') {
606 try {
607 $d = new \DateTime($this->$rname);
608 return $d->format(__("Y-m-d"));
609 } catch (Throwable $e) {
610 //oops, we've got a bad date :/
611 Analog::log(
612 'Bad date (' . $this->$rname . ') | ' .
613 $e->getMessage(),
614 Analog::INFO
615 );
616 return $this->$rname;
617 }
618 }
619 break;
620 case 'id':
621 if ($this->$rname !== null) {
622 return (int)$this->$rname;
623 }
624 return null;
625 case 'amount':
626 if ($this->$rname !== null) {
627 return (double)$this->$rname;
628 }
629 return null;
630 default:
631 return $this->$rname;
632 }
633 } else {
634 Analog::log(
635 sprintf(
636 'Property %1$s does not exists for transaction',
637 $name
638 ),
639 Analog::WARNING
640 );
641 return false;
642 }
643 }
644
645 /**
646 * Get field label
647 *
648 * @param string $field Field name
649 *
650 * @return string
651 */
652 public function getFieldLabel($field)
653 {
654 $label = $this->_fields[$field]['label'];
655 //replace "&nbsp;"
656 $label = str_replace('&nbsp;', ' ', $label);
657 //remove trailing ':' and then trim
658 $label = trim(trim($label, ':'));
659 return $label;
660 }
661
662 /**
663 * Handle files (dynamics files)
664 *
665 * @param array $files Files sent
666 *
667 * @return array|true
668 */
669 public function handleFiles($files)
670 {
671 $this->errors = [];
672
673 $this->dynamicsFiles($files);
674
675 if (count($this->errors) > 0) {
676 Analog::log(
677 'Some errors has been thew attempting to edit/store a transaction files' . "\n" .
678 print_r($this->errors, true),
679 Analog::ERROR
680 );
681 return $this->errors;
682 } else {
683 return true;
684 }
685 }
686
687 /**
688 * Can current logged-in user display transaction
689 *
690 * @param Login $login Login instance
691 *
692 * @return boolean
693 */
694 public function canShow(Login $login): bool
695 {
696 //non-logged-in members cannot show contributions
697 if (!$login->isLogged()) {
698 return false;
699 }
700
701 //admin and staff users can edit, as well as member itself
702 if (!$this->id || $this->id && $login->id == $this->_member || $login->isAdmin() || $login->isStaff()) {
703 return true;
704 }
705
706 //parent can see their children transactions
707 $parent = new Adherent($this->zdb);
708 $parent
709 ->disableAllDeps()
710 ->enableDep('children')
711 ->load($this->login->id);
712 if ($parent->hasChildren()) {
713 foreach ($parent->children as $child) {
714 if ($child->id === $this->_member) {
715 return true;
716 }
717 }
718 return false;
719 }
720
721 return false;
722 }
723 }