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)
156 $select = $this->zdb
->select(self
::TABLE
, 't');
157 $select->where([self
::PK
=> $id]);
159 array('a' => PREFIX_DB
. Adherent
::TABLE
),
160 't.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
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()) {
168 'Non-logged-in users cannot load transaction id `' . $id,
175 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
177 ->equalTo('a.parent_id', $this->login
->id
)
180 ->equalTo('t.' . self
::PK
, $id)
183 $select->where
->equalTo(self
::PK
, $id);
186 $results = $this->zdb
->execute($select);
187 $result = $results->current();
189 $this->loadFromRS($result);
193 'Transaction id `' . $id . '` does not exists',
198 } catch (Throwable
$e) {
200 'Cannot load transaction form id `' . $id . '` | ' .
209 * Remove transaction (and all associated contributions) from database
211 * @param History $hist History
212 * @param boolean $transaction Activate transaction mode (defaults to true)
216 public function remove(History
$hist, $transaction = true)
222 $this->zdb
->connection
->beginTransaction();
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
);
230 foreach ($clist as $cid) {
233 $rem = $c->remove($cids, $hist, false);
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);
244 'Transaction has not been removed!',
251 $this->zdb
->connection
->commit();
254 $emitter->emit('transaction.remove', $this);
256 } catch (Throwable
$e) {
258 $this->zdb
->connection
->rollBack();
261 'An error occurred trying to remove transaction #' .
262 $this->_id
. ' | ' . $e->getMessage(),
270 * Populate object from a resultset row
272 * @param ResultSet $r the resultset row
276 private function loadFromRS($r)
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;
286 $this->loadDynamicFields();
290 * Check posted values validity
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
299 public function check($values, $required, $disabled)
301 $this->errors
= array();
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'];
309 if (isset($values[$key])) {
310 $value = trim($values[$key]);
315 // if the field is enabled, check it
316 if (!isset($disabled[$key])) {
317 // now, check validity
323 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
325 throw new \
Exception('Incorrect format');
327 $this->$prop = $d->format('Y-m-d');
328 } catch (Throwable
$e) {
330 'Wrong date format. field: ' . $key .
331 ', value: ' . $value . ', expected fmt: ' .
332 __("Y-m-d") . ' | ' . $e->getMessage(),
335 $this->errors
[] = str_replace(
342 $this->getFieldLabel($key)
344 _T("- Wrong date format (%date_format) for %field!")
349 $this->_member
= (int)$value;
352 $this->_amount
= $value;
353 $value = strtr($value, ',', '.');
354 if (!is_numeric($value)) {
355 $this->errors
[] = _T("- The amount must be an integer!");
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.");
370 // missing required fields?
371 foreach ($required as $key => $val) {
373 $prop = '_' . $this->_fields
[$key]['propname'];
374 if (!isset($disabled[$key]) && !isset($this->$prop)) {
375 $this->errors
[] = str_replace(
377 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
378 _T("- Mandatory field %field empty.")
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.");
391 $this->dynamicsCheck($values, $required, $disabled);
393 if (count($this->errors
) > 0) {
395 'Some errors has been thew attempting to edit/store a transaction' .
396 print_r($this->errors
, true),
399 return $this->errors
;
402 'Transaction checked successfully.',
410 * Store the transaction
412 * @param History $hist History
416 public function store(History
$hist)
423 $this->zdb
->connection
->beginTransaction();
425 $fields = $this->getDbFields($this->zdb
);
427 foreach ($fields as $field) {
428 $prop = '_' . $this->_fields
[$field]['propname'];
429 $values[$field] = $this->$prop;
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);
444 _T("Transaction added"),
445 Adherent
::getSName($this->zdb
, $this->_member
)
448 $event = 'transaction.add';
450 $hist->add(_T("Fail to add new transaction."));
451 throw new \
RuntimeException(
452 'An error occurred inserting new transaction!'
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) {
464 _T("Transaction updated"),
465 Adherent
::getSName($this->zdb
, $this->_member
)
469 $event = 'transaction.edit';
474 $success = $this->dynamicsStore(true);
477 $this->zdb
->connection
->commit();
479 //send event at the end of process, once all has been stored
480 if ($event !== null) {
481 $emitter->emit($event, $this);
485 } catch (Throwable
$e) {
486 $this->zdb
->connection
->rollBack();
488 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
489 $e->getTraceAsString(),
497 * Retrieve amount that has already been dispatched into contributions
501 public function getDispatchedAmount(): float
503 if (empty($this->_id
)) {
508 $select = $this->zdb
->select(Contribution
::TABLE
);
511 'sum' => new Expression('SUM(montant_cotis)')
513 )->where([self
::PK
=> $this->_id
]);
515 $results = $this->zdb
->execute($select);
516 $result = $results->current();
517 $dispatched_amount = $result->sum
;
518 return (double)$dispatched_amount;
519 } catch (Throwable
$e) {
521 'An error occurred retrieving dispatched amounts | ' .
530 * Retrieve amount that has not yet been dispatched into contributions
534 public function getMissingAmount()
536 if (empty($this->_id
)) {
537 return (double)$this->amount
;
541 $select = $this->zdb
->select(Contribution
::TABLE
);
544 'sum' => new Expression('SUM(montant_cotis)')
546 )->where([self
::PK
=> $this->_id
]);
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) {
554 'An error occurred retrieving missing amounts | ' .
563 * Retrieve fields from database
565 * @param Db $zdb Database instance
569 public function getDbFields(Db
$zdb)
571 $columns = $zdb->getColumns(self
::TABLE
);
573 foreach ($columns as $col) {
574 $fields[] = $col->getName();
580 * Get the relevant CSS class for current transaction
582 * @return string current transaction row class
584 public function getRowClass()
586 return ($this->getMissingAmount() == 0) ?
587 'transaction-normal' : 'transaction-uncomplete';
591 * Global getter method
593 * @param string $name name of the property we want to retrive
595 * @return false|object the called property
597 public function __get($name)
599 $forbidden = array();
601 $rname = '_' . $name;
602 if (!in_array($name, $forbidden) && property_exists($this, $rname)) {
605 if ($this->$rname != '') {
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 :/
612 'Bad date (' . $this->$rname . ') | ' .
616 return $this->$rname;
621 if ($this->$rname !== null) {
622 return (int)$this->$rname;
626 if ($this->$rname !== null) {
627 return (double)$this->$rname;
631 return $this->$rname;
636 'Property %1$s does not exists for transaction',
648 * @param string $field Field name
652 public function getFieldLabel($field)
654 $label = $this->_fields
[$field]['label'];
656 $label = str_replace(' ', ' ', $label);
657 //remove trailing ':' and then trim
658 $label = trim(trim($label, ':'));
663 * Handle files (dynamics files)
665 * @param array $files Files sent
669 public function handleFiles($files)
673 $this->dynamicsFiles($files);
675 if (count($this->errors
) > 0) {
677 'Some errors has been thew attempting to edit/store a transaction files' . "\n" .
678 print_r($this->errors
, true),
681 return $this->errors
;
688 * Can current logged-in user display transaction
690 * @param Login $login Login instance
694 public function canShow(Login
$login): bool
696 //non-logged-in members cannot show contributions
697 if (!$login->isLogged()) {
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()) {
706 //parent can see their children transactions
707 $parent = new Adherent($this->zdb
);
710 ->enableDep('children')
711 ->load($this->login
->id
);
712 if ($parent->hasChildren()) {
713 foreach ($parent->children
as $child) {
714 if ($child->id
=== $this->_member
) {