3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Transaction class for galette
10 * Copyright © 2011-2021 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
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.
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.
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/>.
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
37 namespace Galette\Entity
;
41 use Laminas\Db\Sql\Expression
;
42 use Galette\Repository\Contributions
;
44 use Galette\Core\History
;
45 use Galette\Core\Login
;
46 use Galette\Features\Dynamics
;
49 * Transaction class for 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
60 * @property integer $id
61 * @property date $date
62 * @property integer $amount
63 * @property string $description
64 * @property integer $member
70 public const TABLE
= 'transactions';
71 public const PK
= 'trans_id';
76 private $_description;
79 //fields list and their translation
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
96 public function __construct(Db
$zdb, Login
$login, $args = null)
99 $this->login
= $login;
102 * Fields configuration. Each field is an array and must reflect:
108 * I'd prefer a static private variable for this...
109 * But call to the _T function does not seem to be allowed there :/
111 $this->_fields
= array(
113 'label' => null, //not a field in the form
116 'trans_date' => array(
117 'label' => _T("Date:"), //not a field in the form
120 'trans_amount' => array(
121 'label' => _T("Amount:"),
122 'propname' => 'amount'
124 'trans_desc' => array(
125 'label' => _T("Description:"),
126 'propname' => 'description'
128 Adherent
::PK
=> array(
129 'label' => _T("Originator:"),
130 'propname' => 'member'
133 if ($args == null ||
is_int($args)) {
134 $this->_date
= date("Y-m-d");
136 if (is_int($args) && $args > 0) {
139 } elseif (is_object($args)) {
140 $this->loadFromRS($args);
143 $this->loadDynamicFields();
147 * Loads a transaction from its id
149 * @param int $id the identifier for the transaction to load
151 * @return bool true if query succeed, false otherwise
153 public function load($id)
155 if (!$this->login
->isLogged()) {
157 'Non-logged-in users cannot load transaction id `' . $id,
164 $select = $this->zdb
->select(self
::TABLE
, 't');
165 $select->where([self
::PK
=> $id]);
167 array('a' => PREFIX_DB
. Adherent
::TABLE
),
168 't.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
172 //restrict query on current member id if he's not admin nor staff member
173 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
176 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
178 ->equalTo('a.parent_id', $this->login
->id
)
181 ->equalTo('t.' . self
::PK
, $id)
184 $select->where
->equalTo(self
::PK
, $id);
187 $results = $this->zdb
->execute($select);
188 $result = $results->current();
190 $this->loadFromRS($result);
194 'Transaction id `' . $id . '` does not exists',
199 } catch (Throwable
$e) {
201 'Cannot load transaction form id `' . $id . '` | ' .
210 * Remove transaction (and all associated contributions) from database
212 * @param History $hist History
213 * @param boolean $transaction Activate transaction mode (defaults to true)
217 public function remove(History
$hist, $transaction = true)
223 $this->zdb
->connection
->beginTransaction();
226 //remove associated contributions if needeed
227 if ($this->getDispatchedAmount() > 0) {
228 $c = new Contributions($this->zdb
, $this->login
);
229 $clist = $c->getListFromTransaction($this->_id
);
231 foreach ($clist as $cid) {
234 $rem = $c->remove($cids, $hist, false);
237 //remove transaction itself
238 $delete = $this->zdb
->delete(self
::TABLE
);
239 $delete->where([self
::PK
=> $this->_id
]);
240 $del = $this->zdb
->execute($delete);
241 if ($del->count() > 0) {
242 $this->dynamicsRemove(true);
245 'Transaction has not been removed!',
252 $this->zdb
->connection
->commit();
255 $emitter->emit('transaction.remove', $this);
257 } catch (Throwable
$e) {
259 $this->zdb
->connection
->rollBack();
262 'An error occurred trying to remove transaction #' .
263 $this->_id
. ' | ' . $e->getMessage(),
271 * Populate object from a resultset row
273 * @param ResultSet $r the resultset row
277 private function loadFromRS($r)
280 $this->_id
= $r->$pk;
281 $this->_date
= $r->trans_date
;
282 $this->_amount
= $r->trans_amount
;
283 $this->_description
= $r->trans_desc
;
284 $adhpk = Adherent
::PK
;
285 $this->_member
= (int)$r->$adhpk;
287 $this->loadDynamicFields();
291 * Check posted values validity
293 * @param array $values All values to check, basically the $_POST array
294 * after sending the form
295 * @param array $required Array of required fields
296 * @param array $disabled Array of disabled fields
300 public function check($values, $required, $disabled)
302 $this->errors
= array();
304 $fields = array_keys($this->_fields
);
305 foreach ($fields as $key) {
306 //first, let's sanitize values
307 $key = strtolower($key);
308 $prop = '_' . $this->_fields
[$key]['propname'];
310 if (isset($values[$key])) {
311 $value = trim($values[$key]);
316 // if the field is enabled, check it
317 if (!isset($disabled[$key])) {
318 // now, check validity
324 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
326 throw new \
Exception('Incorrect format');
328 $this->$prop = $d->format('Y-m-d');
329 } catch (Throwable
$e) {
331 'Wrong date format. field: ' . $key .
332 ', value: ' . $value . ', expected fmt: ' .
333 __("Y-m-d") . ' | ' . $e->getMessage(),
336 $this->errors
[] = str_replace(
343 $this->getFieldLabel($key)
345 _T("- Wrong date format (%date_format) for %field!")
350 $this->_member
= (int)$value;
353 $this->_amount
= $value;
354 $value = strtr($value, ',', '.');
355 if (!is_numeric($value)) {
356 $this->errors
[] = _T("- The amount must be an integer!");
360 /** TODO: retrieve field length from database and check that */
361 $this->_description
= strip_tags($value);
362 if (mb_strlen($value) > 150) {
363 $this->errors
[] = _T("- Transaction description must be 150 characters long maximum.");
371 // missing required fields?
372 foreach ($required as $key => $val) {
374 $prop = '_' . $this->_fields
[$key]['propname'];
375 if (!isset($disabled[$key]) && !isset($this->$prop)) {
376 $this->errors
[] = str_replace(
378 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
379 _T("- Mandatory field %field empty.")
385 if ($this->_id
!= '') {
386 $dispatched = $this->getDispatchedAmount();
387 if ($dispatched > $this->_amount
) {
388 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
392 $this->dynamicsCheck($values, $required, $disabled);
394 if (count($this->errors
) > 0) {
396 'Some errors has been thew attempting to edit/store a transaction' .
397 print_r($this->errors
, true),
400 return $this->errors
;
403 'Transaction checked successfully.',
411 * Store the transaction
413 * @param History $hist History
417 public function store(History
$hist)
424 $this->zdb
->connection
->beginTransaction();
426 $fields = $this->getDbFields($this->zdb
);
428 foreach ($fields as $field) {
429 $prop = '_' . $this->_fields
[$field]['propname'];
430 $values[$field] = $this->$prop;
434 if (!isset($this->_id
) ||
$this->_id
== '') {
435 //we're inserting a new transaction
436 unset($values[self
::PK
]);
437 $insert = $this->zdb
->insert(self
::TABLE
);
438 $insert->values($values);
439 $add = $this->zdb
->execute($insert);
440 if ($add->count() > 0) {
441 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
445 _T("Transaction added"),
446 Adherent
::getSName($this->zdb
, $this->_member
)
449 $event = 'transaction.add';
451 $hist->add(_T("Fail to add new transaction."));
452 throw new \
RuntimeException(
453 'An error occurred inserting new transaction!'
457 //we're editing an existing transaction
458 $update = $this->zdb
->update(self
::TABLE
);
459 $update->set($values)->where([self
::PK
=> $this->_id
]);
460 $edit = $this->zdb
->execute($update);
461 //edit == 0 does not mean there were an error, but that there
462 //were nothing to change
463 if ($edit->count() > 0) {
465 _T("Transaction updated"),
466 Adherent
::getSName($this->zdb
, $this->_member
)
470 $event = 'transaction.edit';
475 $success = $this->dynamicsStore(true);
478 $this->zdb
->connection
->commit();
480 //send event at the end of process, once all has been stored
481 if ($event !== null) {
482 $emitter->emit($event, $this);
486 } catch (Throwable
$e) {
487 $this->zdb
->connection
->rollBack();
489 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
490 $e->getTraceAsString(),
498 * Retrieve amount that has already been dispatched into contributions
502 public function getDispatchedAmount(): float
504 if (empty($this->_id
)) {
509 $select = $this->zdb
->select(Contribution
::TABLE
);
512 'sum' => new Expression('SUM(montant_cotis)')
514 )->where([self
::PK
=> $this->_id
]);
516 $results = $this->zdb
->execute($select);
517 $result = $results->current();
518 $dispatched_amount = $result->sum
;
519 return (double)$dispatched_amount;
520 } catch (Throwable
$e) {
522 'An error occurred retrieving dispatched amounts | ' .
531 * Retrieve amount that has not yet been dispatched into contributions
535 public function getMissingAmount()
537 if (empty($this->_id
)) {
538 return (double)$this->amount
;
542 $select = $this->zdb
->select(Contribution
::TABLE
);
545 'sum' => new Expression('SUM(montant_cotis)')
547 )->where([self
::PK
=> $this->_id
]);
549 $results = $this->zdb
->execute($select);
550 $result = $results->current();
551 $dispatched_amount = $result->sum
;
552 return (double)$this->_amount
- (double)$dispatched_amount;
553 } catch (Throwable
$e) {
555 'An error occurred retrieving missing amounts | ' .
564 * Retrieve fields from database
566 * @param Db $zdb Database instance
570 public function getDbFields(Db
$zdb)
572 $columns = $zdb->getColumns(self
::TABLE
);
574 foreach ($columns as $col) {
575 $fields[] = $col->getName();
581 * Get the relevant CSS class for current transaction
583 * @return string current transaction row class
585 public function getRowClass()
587 return ($this->getMissingAmount() == 0) ?
588 'transaction-normal' : 'transaction-uncomplete';
592 * Global getter method
594 * @param string $name name of the property we want to retrive
596 * @return false|object the called property
598 public function __get($name)
600 $forbidden = array();
602 $rname = '_' . $name;
603 if (!in_array($name, $forbidden) && property_exists($this, $rname)) {
606 if ($this->$rname != '') {
608 $d = new \
DateTime($this->$rname);
609 return $d->format(__("Y-m-d"));
610 } catch (Throwable
$e) {
611 //oops, we've got a bad date :/
613 'Bad date (' . $this->$rname . ') | ' .
617 return $this->$rname;
622 if ($this->$rname !== null) {
623 return (int)$this->$rname;
627 if ($this->$rname !== null) {
628 return (double)$this->$rname;
632 return $this->$rname;
637 'Property %1$s does not exists for transaction',
649 * @param string $field Field name
653 public function getFieldLabel($field)
655 $label = $this->_fields
[$field]['label'];
657 $label = str_replace(' ', ' ', $label);
658 //remove trailing ':' and then trim
659 $label = trim(trim($label, ':'));
664 * Handle files (dynamics files)
666 * @param array $files Files sent
670 public function handleFiles($files)
674 $this->dynamicsFiles($files);
676 if (count($this->errors
) > 0) {
678 'Some errors has been thew attempting to edit/store a transaction files' . "\n" .
679 print_r($this->errors
, true),
682 return $this->errors
;
689 * Can current logged-in user display transaction
691 * @param Login $login Login instance
695 public function canShow(Login
$login): bool
697 //non-logged-in members cannot show contributions
698 if (!$login->isLogged()) {
702 //admin and staff users can edit, as well as member itself
703 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
707 //parent can see their children transactions
708 $parent = new Adherent($this->zdb
);
711 ->enableDep('children')
712 ->load($this->login
->id
);
713 if ($parent->hasChildren()) {
714 foreach ($parent->children
as $child) {
715 if ($child->id
=== $this->_member
) {