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
;
48 * Transaction class for galette
53 * @author Johan Cwiklinski <johan@x-tnd.be>
54 * @copyright 2010-2021 The Galette Team
55 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
56 * @link http://galette.tuxfamily.org
57 * @since Available since 0.7dev - 2010-03-11
59 * @property integer $id
60 * @property date $date
61 * @property integer $amount
62 * @property string $description
63 * @property integer $member
69 public const TABLE
= 'transactions';
70 public const PK
= 'trans_id';
75 private $_description;
78 //fields list and their translation
89 * @param Db $zdb Database instance
90 * @param Login $login Login instance
91 * @param null|int|ResultSet $args Either a ResultSet row or its id for to load
92 * a specific transaction, or null to just
95 public function __construct(Db
$zdb, Login
$login, $args = null)
98 $this->login
= $login;
101 * Fields configuration. Each field is an array and must reflect:
107 * I'd prefer a static private variable for this...
108 * But call to the _T function does not seem to be allowed there :/
110 $this->_fields
= array(
112 'label' => null, //not a field in the form
115 'trans_date' => array(
116 'label' => _T("Date:"), //not a field in the form
119 'trans_amount' => array(
120 'label' => _T("Amount:"),
121 'propname' => 'amount'
123 'trans_desc' => array(
124 'label' => _T("Description:"),
125 'propname' => 'description'
127 Adherent
::PK
=> array(
128 'label' => _T("Originator:"),
129 'propname' => 'member'
132 if ($args == null ||
is_int($args)) {
133 $this->_date
= date("Y-m-d");
135 if (is_int($args) && $args > 0) {
138 } elseif (is_object($args)) {
139 $this->loadFromRS($args);
142 $this->loadDynamicFields();
146 * Loads a transaction from its id
148 * @param int $id the identifier for the transaction to load
150 * @return bool true if query succeed, false otherwise
152 public function load($id)
155 $select = $this->zdb
->select(self
::TABLE
, 't');
156 $select->where(self
::PK
. ' = ' . $id);
158 array('a' => PREFIX_DB
. Adherent
::TABLE
),
159 't.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
163 //restrict query on current member id if he's not admin nor staff member
164 if (!$this->login
->isAdmin() && !$this->login
->isStaff() && !$this->login
->isGroupManager()) {
167 ->equalTo('a.' . Adherent
::PK
, $this->login
->id
)
169 ->equalTo('a.parent_id', $this->login
->id
)
172 ->equalTo('t.' . self
::PK
, $id)
175 $select->where
->equalTo(self
::PK
, $id);
178 $results = $this->zdb
->execute($select);
179 $result = $results->current();
181 $this->loadFromRS($result);
184 throw new \
Exception();
186 } catch (Throwable
$e) {
188 'Cannot load transaction form id `' . $id . '` | ' .
197 * Remove transaction (and all associated contributions) from database
199 * @param History $hist History
200 * @param boolean $transaction Activate transaction mode (defaults to true)
204 public function remove(History
$hist, $transaction = true)
210 $this->zdb
->connection
->beginTransaction();
213 //remove associated contributions if needeed
214 if ($this->getDispatchedAmount() > 0) {
215 $c = new Contributions($this->zdb
, $this->login
);
216 $clist = $c->getListFromTransaction($this->_id
);
218 foreach ($clist as $cid) {
221 $rem = $c->remove($cids, $hist, false);
224 //remove transaction itself
225 $delete = $this->zdb
->delete(self
::TABLE
);
227 self
::PK
. ' = ' . $this->_id
229 $this->zdb
->execute($delete);
231 $this->dynamicsRemove(true);
234 $this->zdb
->connection
->commit();
237 $emitter->emit('transaction.remove', $this);
239 } catch (Throwable
$e) {
241 $this->zdb
->connection
->rollBack();
244 'An error occurred trying to remove transaction #' .
245 $this->_id
. ' | ' . $e->getMessage(),
253 * Populate object from a resultset row
255 * @param ResultSet $r the resultset row
259 private function loadFromRS($r)
262 $this->_id
= $r->$pk;
263 $this->_date
= $r->trans_date
;
264 $this->_amount
= $r->trans_amount
;
265 $this->_description
= $r->trans_desc
;
266 $adhpk = Adherent
::PK
;
267 $this->_member
= (int)$r->$adhpk;
269 $this->loadDynamicFields();
273 * Check posted values validity
275 * @param array $values All values to check, basically the $_POST array
276 * after sending the form
277 * @param array $required Array of required fields
278 * @param array $disabled Array of disabled fields
282 public function check($values, $required, $disabled)
284 $this->errors
= array();
286 $fields = array_keys($this->_fields
);
287 foreach ($fields as $key) {
288 //first of all, let's sanitize values
289 $key = strtolower($key);
290 $prop = '_' . $this->_fields
[$key]['propname'];
292 if (isset($values[$key])) {
293 $value = trim($values[$key]);
298 // if the field is enabled, check it
299 if (!isset($disabled[$key])) {
300 // now, check validity
306 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
308 throw new \
Exception('Incorrect format');
310 $this->$prop = $d->format('Y-m-d');
311 } catch (Throwable
$e) {
313 'Wrong date format. field: ' . $key .
314 ', value: ' . $value . ', expected fmt: ' .
315 __("Y-m-d") . ' | ' . $e->getMessage(),
318 $this->errors
[] = str_replace(
325 $this->_fields
[$key]['label']
327 _T("- Wrong date format (%date_format) for %field!")
332 $this->_member
= (int)$value;
335 $this->_amount
= $value;
336 $value = strtr($value, ',', '.');
337 if (!is_numeric($value)) {
338 $this->errors
[] = _T("- The amount must be an integer!");
342 /** TODO: retrieve field length from database and check that */
343 $this->_description
= $value;
344 if (trim($value) == '') {
345 $this->errors
[] = _T("- Empty transaction description!");
346 } elseif (mb_strlen($value) > 150) {
347 $this->errors
[] = _T("- Transaction description must be 150 characters long maximum.");
355 // missing required fields?
356 foreach ($required as $key => $val) {
358 $prop = '_' . $this->_fields
[$key]['propname'];
359 if (!isset($disabled[$key]) && !isset($this->$prop)) {
360 $this->errors
[] = str_replace(
362 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
363 _T("- Mandatory field %field empty.")
369 if ($this->_id
!= '') {
370 $dispatched = $this->getDispatchedAmount();
371 if ($dispatched > $this->_amount
) {
372 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
376 $this->dynamicsCheck($values, $required, $disabled);
378 if (count($this->errors
) > 0) {
380 'Some errors has been thew attempting to edit/store a transaction' .
381 print_r($this->errors
, true),
384 return $this->errors
;
387 'Transaction checked successfully.',
395 * Store the transaction
397 * @param History $hist History
401 public function store(History
$hist)
408 $this->zdb
->connection
->beginTransaction();
410 $fields = $this->getDbFields($this->zdb
);
412 foreach ($fields as $field) {
413 $prop = '_' . $this->_fields
[$field]['propname'];
414 $values[$field] = $this->$prop;
418 if (!isset($this->_id
) ||
$this->_id
== '') {
419 //we're inserting a new transaction
420 unset($values[self
::PK
]);
421 $insert = $this->zdb
->insert(self
::TABLE
);
422 $insert->values($values);
423 $add = $this->zdb
->execute($insert);
424 if ($add->count() > 0) {
425 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
429 _T("Transaction added"),
430 Adherent
::getSName($this->zdb
, $this->_member
)
433 $event = 'transaction.add';
435 $hist->add(_T("Fail to add new transaction."));
436 throw new \
RuntimeException(
437 'An error occurred inserting new transaction!'
441 //we're editing an existing transaction
442 $update = $this->zdb
->update(self
::TABLE
);
443 $update->set($values)->where(
444 self
::PK
. '=' . $this->_id
446 $edit = $this->zdb
->execute($update);
447 //edit == 0 does not mean there were an error, but that there
448 //were nothing to change
449 if ($edit->count() > 0) {
451 _T("Transaction updated"),
452 Adherent
::getSName($this->zdb
, $this->_member
)
456 $event = 'transaction.edit';
461 $success = $this->dynamicsStore(true);
464 $this->zdb
->connection
->commit();
466 //send event at the end of process, once all has been stored
467 if ($event !== null) {
468 $emitter->emit($event, $this);
472 } catch (Throwable
$e) {
473 $this->zdb
->connection
->rollBack();
475 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
476 $e->getTraceAsString(),
484 * Retrieve amount that has already been dispatched into contributions
488 public function getDispatchedAmount()
491 $select = $this->zdb
->select(Contribution
::TABLE
);
494 'sum' => new Expression('SUM(montant_cotis)')
496 )->where(self
::PK
. ' = ' . $this->_id
);
498 $results = $this->zdb
->execute($select);
499 $result = $results->current();
500 $dispatched_amount = $result->sum
;
501 return (double)$dispatched_amount;
502 } catch (Throwable
$e) {
504 'An error occurred retrieving dispatched amounts | ' .
512 * Retrieve amount that has not yet been dispatched into contributions
516 public function getMissingAmount()
519 $select = $this->zdb
->select(Contribution
::TABLE
);
522 'sum' => new Expression('SUM(montant_cotis)')
524 )->where(self
::PK
. ' = ' . $this->_id
);
526 $results = $this->zdb
->execute($select);
527 $result = $results->current();
528 $dispatched_amount = $result->sum
;
529 return (double)$this->_amount
- (double)$dispatched_amount;
530 } catch (Throwable
$e) {
532 'An error occurred retrieving missing amounts | ' .
540 * Retrieve fields from database
542 * @param Db $zdb Database instance
546 public function getDbFields(Db
$zdb)
548 $columns = $zdb->getColumns(self
::TABLE
);
550 foreach ($columns as $col) {
551 $fields[] = $col->getName();
557 * Get the relevant CSS class for current transaction
559 * @return string current transaction row class
561 public function getRowClass()
563 return ($this->getMissingAmount() == 0) ?
564 'transaction-normal' : 'transaction-uncomplete';
568 * Global getter method
570 * @param string $name name of the property we want to retrive
572 * @return false|object the called property
574 public function __get($name)
576 $forbidden = array();
578 $rname = '_' . $name;
579 if (!in_array($name, $forbidden) && isset($this->$rname)) {
582 if ($this->$rname != '') {
584 $d = new \
DateTime($this->$rname);
585 return $d->format(__("Y-m-d"));
586 } catch (Throwable
$e) {
587 //oops, we've got a bad date :/
589 'Bad date (' . $this->$rname . ') | ' .
593 return $this->$rname;
598 return $this->$rname;
607 * Global setter method
609 * @param string $name name of the property we want to assign a value to
610 * @param object $value a relevant value for the property
614 public function __set($name, $value)
616 /*$forbidden = array('fields');*/
617 /** TODO: What to do ? :-) */
623 * @param string $field Field name
627 private function getFieldLabel($field)
629 $label = $this->_fields
[$field]['label'];
630 //remove trailing ':' and then nbsp (for french at least)
631 $label = trim(trim($label, ':'), ' ');
636 * Handle files (dynamics files)
638 * @param array $files Files sent
642 public function handleFiles($files)
646 $this->dynamicsFiles($files);
648 if (count($this->errors
) > 0) {
650 'Some errors has been thew attempting to edit/store a transaction files' . "\n" .
651 print_r($this->errors
, true),
654 return $this->errors
;
661 * Can current logged-in user display transaction
663 * @param Login $login Login instance
667 public function canShow(Login
$login): bool
669 //admin and staff users can edit, as well as member itself
670 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
674 //parent can see their children transactions
675 $parent = new Adherent($this->zdb
);
678 ->enableDep('children')
679 ->load($this->login
->id
);
680 if ($parent->hasChildren()) {
681 foreach ($parent->children
as $child) {
682 if ($child->id
=== $this->_member
) {