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
);
239 self
::PK
. ' = ' . $this->_id
241 $del = $this->zdb
->execute($delete);
242 if ($del->count() > 0) {
243 $this->dynamicsRemove(true);
246 'Transaction has not been removed!',
253 $this->zdb
->connection
->commit();
256 $emitter->emit('transaction.remove', $this);
258 } catch (Throwable
$e) {
260 $this->zdb
->connection
->rollBack();
263 'An error occurred trying to remove transaction #' .
264 $this->_id
. ' | ' . $e->getMessage(),
272 * Populate object from a resultset row
274 * @param ResultSet $r the resultset row
278 private function loadFromRS($r)
281 $this->_id
= $r->$pk;
282 $this->_date
= $r->trans_date
;
283 $this->_amount
= $r->trans_amount
;
284 $this->_description
= $r->trans_desc
;
285 $adhpk = Adherent
::PK
;
286 $this->_member
= (int)$r->$adhpk;
288 $this->loadDynamicFields();
292 * Check posted values validity
294 * @param array $values All values to check, basically the $_POST array
295 * after sending the form
296 * @param array $required Array of required fields
297 * @param array $disabled Array of disabled fields
301 public function check($values, $required, $disabled)
303 $this->errors
= array();
305 $fields = array_keys($this->_fields
);
306 foreach ($fields as $key) {
307 //first, let's sanitize values
308 $key = strtolower($key);
309 $prop = '_' . $this->_fields
[$key]['propname'];
311 if (isset($values[$key])) {
312 $value = trim($values[$key]);
317 // if the field is enabled, check it
318 if (!isset($disabled[$key])) {
319 // now, check validity
325 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
327 throw new \
Exception('Incorrect format');
329 $this->$prop = $d->format('Y-m-d');
330 } catch (Throwable
$e) {
332 'Wrong date format. field: ' . $key .
333 ', value: ' . $value . ', expected fmt: ' .
334 __("Y-m-d") . ' | ' . $e->getMessage(),
337 $this->errors
[] = str_replace(
344 $this->getFieldLabel($key)
346 _T("- Wrong date format (%date_format) for %field!")
351 $this->_member
= (int)$value;
354 $this->_amount
= $value;
355 $value = strtr($value, ',', '.');
356 if (!is_numeric($value)) {
357 $this->errors
[] = _T("- The amount must be an integer!");
361 /** TODO: retrieve field length from database and check that */
362 $this->_description
= $value;
363 if (mb_strlen($value) > 150) {
364 $this->errors
[] = _T("- Transaction description must be 150 characters long maximum.");
372 // missing required fields?
373 foreach ($required as $key => $val) {
375 $prop = '_' . $this->_fields
[$key]['propname'];
376 if (!isset($disabled[$key]) && !isset($this->$prop)) {
377 $this->errors
[] = str_replace(
379 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
380 _T("- Mandatory field %field empty.")
386 if ($this->_id
!= '') {
387 $dispatched = $this->getDispatchedAmount();
388 if ($dispatched > $this->_amount
) {
389 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
393 $this->dynamicsCheck($values, $required, $disabled);
395 if (count($this->errors
) > 0) {
397 'Some errors has been thew attempting to edit/store a transaction' .
398 print_r($this->errors
, true),
401 return $this->errors
;
404 'Transaction checked successfully.',
412 * Store the transaction
414 * @param History $hist History
418 public function store(History
$hist)
425 $this->zdb
->connection
->beginTransaction();
427 $fields = $this->getDbFields($this->zdb
);
429 foreach ($fields as $field) {
430 $prop = '_' . $this->_fields
[$field]['propname'];
431 $values[$field] = $this->$prop;
435 if (!isset($this->_id
) ||
$this->_id
== '') {
436 //we're inserting a new transaction
437 unset($values[self
::PK
]);
438 $insert = $this->zdb
->insert(self
::TABLE
);
439 $insert->values($values);
440 $add = $this->zdb
->execute($insert);
441 if ($add->count() > 0) {
442 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
446 _T("Transaction added"),
447 Adherent
::getSName($this->zdb
, $this->_member
)
450 $event = 'transaction.add';
452 $hist->add(_T("Fail to add new transaction."));
453 throw new \
RuntimeException(
454 'An error occurred inserting new transaction!'
458 //we're editing an existing transaction
459 $update = $this->zdb
->update(self
::TABLE
);
460 $update->set($values)->where(
461 self
::PK
. '=' . $this->_id
463 $edit = $this->zdb
->execute($update);
464 //edit == 0 does not mean there were an error, but that there
465 //were nothing to change
466 if ($edit->count() > 0) {
468 _T("Transaction updated"),
469 Adherent
::getSName($this->zdb
, $this->_member
)
473 $event = 'transaction.edit';
478 $success = $this->dynamicsStore(true);
481 $this->zdb
->connection
->commit();
483 //send event at the end of process, once all has been stored
484 if ($event !== null) {
485 $emitter->emit($event, $this);
489 } catch (Throwable
$e) {
490 $this->zdb
->connection
->rollBack();
492 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
493 $e->getTraceAsString(),
501 * Retrieve amount that has already been dispatched into contributions
505 public function getDispatchedAmount(): float
507 if (empty($this->_id
)) {
512 $select = $this->zdb
->select(Contribution
::TABLE
);
515 'sum' => new Expression('SUM(montant_cotis)')
517 )->where(self
::PK
. ' = ' . $this->_id
);
519 $results = $this->zdb
->execute($select);
520 $result = $results->current();
521 $dispatched_amount = $result->sum
;
522 return (double)$dispatched_amount;
523 } catch (Throwable
$e) {
525 'An error occurred retrieving dispatched amounts | ' .
534 * Retrieve amount that has not yet been dispatched into contributions
538 public function getMissingAmount()
540 if (empty($this->_id
)) {
541 return (double)$this->amount
;
545 $select = $this->zdb
->select(Contribution
::TABLE
);
548 'sum' => new Expression('SUM(montant_cotis)')
550 )->where(self
::PK
. ' = ' . $this->_id
);
552 $results = $this->zdb
->execute($select);
553 $result = $results->current();
554 $dispatched_amount = $result->sum
;
555 return (double)$this->_amount
- (double)$dispatched_amount;
556 } catch (Throwable
$e) {
558 'An error occurred retrieving missing amounts | ' .
567 * Retrieve fields from database
569 * @param Db $zdb Database instance
573 public function getDbFields(Db
$zdb)
575 $columns = $zdb->getColumns(self
::TABLE
);
577 foreach ($columns as $col) {
578 $fields[] = $col->getName();
584 * Get the relevant CSS class for current transaction
586 * @return string current transaction row class
588 public function getRowClass()
590 return ($this->getMissingAmount() == 0) ?
591 'transaction-normal' : 'transaction-uncomplete';
595 * Global getter method
597 * @param string $name name of the property we want to retrive
599 * @return false|object the called property
601 public function __get($name)
603 $forbidden = array();
605 $rname = '_' . $name;
606 if (!in_array($name, $forbidden) && property_exists($this, $rname)) {
609 if ($this->$rname != '') {
611 $d = new \
DateTime($this->$rname);
612 return $d->format(__("Y-m-d"));
613 } catch (Throwable
$e) {
614 //oops, we've got a bad date :/
616 'Bad date (' . $this->$rname . ') | ' .
620 return $this->$rname;
625 if ($this->$rname !== null) {
626 return (int)$this->$rname;
630 if ($this->$rname !== null) {
631 return (double)$this->$rname;
635 return $this->$rname;
640 'Property %1$s does not exists for transaction',
652 * @param string $field Field name
656 public function getFieldLabel($field)
658 $label = $this->_fields
[$field]['label'];
660 $label = str_replace(' ', ' ', $label);
661 //remove trailing ':' and then trim
662 $label = trim(trim($label, ':'));
667 * Handle files (dynamics files)
669 * @param array $files Files sent
673 public function handleFiles($files)
677 $this->dynamicsFiles($files);
679 if (count($this->errors
) > 0) {
681 'Some errors has been thew attempting to edit/store a transaction files' . "\n" .
682 print_r($this->errors
, true),
685 return $this->errors
;
692 * Can current logged-in user display transaction
694 * @param Login $login Login instance
698 public function canShow(Login
$login): bool
700 //non-logged-in members cannot show contributions
701 if (!$login->isLogged()) {
705 //admin and staff users can edit, as well as member itself
706 if (!$this->id ||
$this->id
&& $login->id
== $this->_member ||
$login->isAdmin() ||
$login->isStaff()) {
710 //parent can see their children transactions
711 $parent = new Adherent($this->zdb
);
714 ->enableDep('children')
715 ->load($this->login
->id
);
716 if ($parent->hasChildren()) {
717 foreach ($parent->children
as $child) {
718 if ($child->id
=== $this->_member
) {