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
63 public const TABLE
= 'transactions';
64 public const PK
= 'trans_id';
69 private $_description;
72 //fields list and their translation
83 * @param Db $zdb Database instance
84 * @param Login $login Login instance
85 * @param null|int|ResultSet $args Either a ResultSet row or its id for to load
86 * a specific transaction, or null to just
89 public function __construct(Db
$zdb, Login
$login, $args = null)
92 $this->login
= $login;
95 * Fields configuration. Each field is an array and must reflect:
101 * I'd prefer a static private variable for this...
102 * But call to the _T function does not seem to be allowed there :/
104 $this->_fields
= array(
106 'label' => null, //not a field in the form
109 'trans_date' => array(
110 'label' => _T("Date:"), //not a field in the form
113 'trans_amount' => array(
114 'label' => _T("Amount:"),
115 'propname' => 'amount'
117 'trans_desc' => array(
118 'label' => _T("Description:"),
119 'propname' => 'description'
121 Adherent
::PK
=> array(
122 'label' => _T("Originator:"),
123 'propname' => 'member'
126 if ($args == null ||
is_int($args)) {
127 $this->_date
= date("Y-m-d");
129 if (is_int($args) && $args > 0) {
132 } elseif (is_object($args)) {
133 $this->loadFromRS($args);
136 $this->loadDynamicFields();
140 * Loads a transaction from its id
142 * @param int $id the identifier for the transaction to load
144 * @return bool true if query succeed, false otherwise
146 public function load($id)
149 $select = $this->zdb
->select(self
::TABLE
);
150 $select->where(self
::PK
. ' = ' . $id);
152 $results = $this->zdb
->execute($select);
153 $result = $results->current();
155 $this->loadFromRS($result);
158 throw new \
Exception();
160 } catch (Throwable
$e) {
162 'Cannot load transaction form id `' . $id . '` | ' .
171 * Remove transaction (and all associated contributions) from database
173 * @param History $hist History
174 * @param boolean $transaction Activate transaction mode (defaults to true)
178 public function remove(History
$hist, $transaction = true)
184 $this->zdb
->connection
->beginTransaction();
187 //remove associated contributions if needeed
188 if ($this->getDispatchedAmount() > 0) {
189 $c = new Contributions($this->zdb
, $this->login
);
190 $clist = $c->getListFromTransaction($this->_id
);
192 foreach ($clist as $cid) {
195 $rem = $c->remove($cids, $hist, false);
198 //remove transaction itself
199 $delete = $this->zdb
->delete(self
::TABLE
);
201 self
::PK
. ' = ' . $this->_id
203 $this->zdb
->execute($delete);
205 $this->dynamicsRemove(true);
208 $this->zdb
->connection
->commit();
211 $emitter->emit('transaction.remove', $this);
213 } catch (Throwable
$e) {
215 $this->zdb
->connection
->rollBack();
218 'An error occurred trying to remove transaction #' .
219 $this->_id
. ' | ' . $e->getMessage(),
227 * Populate object from a resultset row
229 * @param ResultSet $r the resultset row
233 private function loadFromRS($r)
236 $this->_id
= $r->$pk;
237 $this->_date
= $r->trans_date
;
238 $this->_amount
= $r->trans_amount
;
239 $this->_description
= $r->trans_desc
;
240 $adhpk = Adherent
::PK
;
241 $this->_member
= (int)$r->$adhpk;
243 $this->loadDynamicFields();
247 * Check posted values validity
249 * @param array $values All values to check, basically the $_POST array
250 * after sending the form
251 * @param array $required Array of required fields
252 * @param array $disabled Array of disabled fields
256 public function check($values, $required, $disabled)
258 $this->errors
= array();
260 $fields = array_keys($this->_fields
);
261 foreach ($fields as $key) {
262 //first of all, let's sanitize values
263 $key = strtolower($key);
264 $prop = '_' . $this->_fields
[$key]['propname'];
266 if (isset($values[$key])) {
267 $value = trim($values[$key]);
272 // if the field is enabled, check it
273 if (!isset($disabled[$key])) {
274 // now, check validity
280 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
282 throw new \
Exception('Incorrect format');
284 $this->$prop = $d->format('Y-m-d');
285 } catch (Throwable
$e) {
287 'Wrong date format. field: ' . $key .
288 ', value: ' . $value . ', expected fmt: ' .
289 __("Y-m-d") . ' | ' . $e->getMessage(),
292 $this->errors
[] = str_replace(
299 $this->_fields
[$key]['label']
301 _T("- Wrong date format (%date_format) for %field!")
306 $this->_member
= (int)$value;
309 $this->_amount
= $value;
310 $value = strtr($value, ',', '.');
311 if (!is_numeric($value)) {
312 $this->errors
[] = _T("- The amount must be an integer!");
316 /** TODO: retrieve field length from database and check that */
317 $this->_description
= $value;
318 if (trim($value) == '') {
319 $this->errors
[] = _T("- Empty transaction description!");
320 } elseif (mb_strlen($value) > 150) {
321 $this->errors
[] = _T("- Transaction description must be 150 characters long maximum.");
329 // missing required fields?
330 foreach ($required as $key => $val) {
332 $prop = '_' . $this->_fields
[$key]['propname'];
333 if (!isset($disabled[$key]) && !isset($this->$prop)) {
334 $this->errors
[] = str_replace(
336 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
337 _T("- Mandatory field %field empty.")
343 if ($this->_id
!= '') {
344 $dispatched = $this->getDispatchedAmount();
345 if ($dispatched > $this->_amount
) {
346 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
350 $this->dynamicsCheck($values, $required, $disabled);
352 if (count($this->errors
) > 0) {
354 'Some errors has been thew attempting to edit/store a transaction' .
355 print_r($this->errors
, true),
358 return $this->errors
;
361 'Transaction checked successfully.',
369 * Store the transaction
371 * @param History $hist History
375 public function store(History
$hist)
382 $this->zdb
->connection
->beginTransaction();
384 $fields = $this->getDbFields($this->zdb
);
386 foreach ($fields as $field) {
387 $prop = '_' . $this->_fields
[$field]['propname'];
388 $values[$field] = $this->$prop;
392 if (!isset($this->_id
) ||
$this->_id
== '') {
393 //we're inserting a new transaction
394 unset($values[self
::PK
]);
395 $insert = $this->zdb
->insert(self
::TABLE
);
396 $insert->values($values);
397 $add = $this->zdb
->execute($insert);
398 if ($add->count() > 0) {
399 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
403 _T("Transaction added"),
404 Adherent
::getSName($this->zdb
, $this->_member
)
407 $event = 'transaction.add';
409 $hist->add(_T("Fail to add new transaction."));
410 throw new \
RuntimeException(
411 'An error occurred inserting new transaction!'
415 //we're editing an existing transaction
416 $update = $this->zdb
->update(self
::TABLE
);
417 $update->set($values)->where(
418 self
::PK
. '=' . $this->_id
420 $edit = $this->zdb
->execute($update);
421 //edit == 0 does not mean there were an error, but that there
422 //were nothing to change
423 if ($edit->count() > 0) {
425 _T("Transaction updated"),
426 Adherent
::getSName($this->zdb
, $this->_member
)
430 $event = 'transaction.edit';
435 $success = $this->dynamicsStore(true);
438 $this->zdb
->connection
->commit();
440 //send event at the end of process, once all has been stored
441 if ($event !== null) {
442 $emitter->emit($event, $this);
446 } catch (Throwable
$e) {
447 $this->zdb
->connection
->rollBack();
449 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
450 $e->getTraceAsString(),
458 * Retrieve amount that has already been dispatched into contributions
462 public function getDispatchedAmount()
465 $select = $this->zdb
->select(Contribution
::TABLE
);
468 'sum' => new Expression('SUM(montant_cotis)')
470 )->where(self
::PK
. ' = ' . $this->_id
);
472 $results = $this->zdb
->execute($select);
473 $result = $results->current();
474 $dispatched_amount = $result->sum
;
475 return (double)$dispatched_amount;
476 } catch (Throwable
$e) {
478 'An error occurred retrieving dispatched amounts | ' .
486 * Retrieve amount that has not yet been dispatched into contributions
490 public function getMissingAmount()
493 $select = $this->zdb
->select(Contribution
::TABLE
);
496 'sum' => new Expression('SUM(montant_cotis)')
498 )->where(self
::PK
. ' = ' . $this->_id
);
500 $results = $this->zdb
->execute($select);
501 $result = $results->current();
502 $dispatched_amount = $result->sum
;
503 return (double)$this->_amount
- (double)$dispatched_amount;
504 } catch (Throwable
$e) {
506 'An error occurred retrieving missing amounts | ' .
514 * Retrieve fields from database
516 * @param Db $zdb Database instance
520 public function getDbFields(Db
$zdb)
522 $columns = $zdb->getColumns(self
::TABLE
);
524 foreach ($columns as $col) {
525 $fields[] = $col->getName();
531 * Get the relevant CSS class for current transaction
533 * @return string current transaction row class
535 public function getRowClass()
537 return ($this->getMissingAmount() == 0) ?
538 'transaction-normal' : 'transaction-uncomplete';
542 * Global getter method
544 * @param string $name name of the property we want to retrive
546 * @return false|object the called property
548 public function __get($name)
550 $forbidden = array();
552 $rname = '_' . $name;
553 if (!in_array($name, $forbidden) && isset($this->$rname)) {
556 if ($this->$rname != '') {
558 $d = new \
DateTime($this->$rname);
559 return $d->format(__("Y-m-d"));
560 } catch (Throwable
$e) {
561 //oops, we've got a bad date :/
563 'Bad date (' . $this->$rname . ') | ' .
567 return $this->$rname;
572 return $this->$rname;
581 * Global setter method
583 * @param string $name name of the property we want to assign a value to
584 * @param object $value a relevant value for the property
588 public function __set($name, $value)
590 /*$forbidden = array('fields');*/
591 /** TODO: What to do ? :-) */
597 * @param string $field Field name
601 private function getFieldLabel($field)
603 $label = $this->_fields
[$field]['label'];
604 //remove trailing ':' and then nbsp (for french at least)
605 $label = trim(trim($label, ':'), ' ');
610 * Handle files (dynamics files)
612 * @param array $files Files sent
616 public function handleFiles($files)
620 $this->dynamicsFiles($files);
622 if (count($this->errors
) > 0) {
624 'Some errors has been thew attempting to edit/store a transaction files' . "\n" .
625 print_r($this->errors
, true),
628 return $this->errors
;