3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Transaction class for galette
10 * Copyright © 2011-2014 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-2014 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
34 * @link http://galette.tuxfamily.org
35 * @since Available since 0.7dev - 2011-07-31
38 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-2014 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 const TABLE
= 'transactions';
64 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 (\Exception
$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();
210 $emitter->emit('transaction.remove', $this);
212 } catch (\Exception
$e) {
214 $this->zdb
->connection
->rollBack();
217 'An error occurred trying to remove transaction #' .
218 $this->_id
. ' | ' . $e->getMessage(),
226 * Populate object from a resultset row
228 * @param ResultSet $r the resultset row
232 private function loadFromRS($r)
235 $this->_id
= $r->$pk;
236 $this->_date
= $r->trans_date
;
237 $this->_amount
= $r->trans_amount
;
238 $this->_description
= $r->trans_desc
;
239 $adhpk = Adherent
::PK
;
240 $this->_member
= (int)$r->$adhpk;
242 $this->loadDynamicFields();
246 * Check posted values validity
248 * @param array $values All values to check, basically the $_POST array
249 * after sending the form
250 * @param array $required Array of required fields
251 * @param array $disabled Array of disabled fields
255 public function check($values, $required, $disabled)
257 $this->errors
= array();
259 $fields = array_keys($this->_fields
);
260 foreach ($fields as $key) {
261 //first of all, let's sanitize values
262 $key = strtolower($key);
263 $prop = '_' . $this->_fields
[$key]['propname'];
265 if (isset($values[$key])) {
266 $value = trim($values[$key]);
271 // if the field is enabled, check it
272 if (!isset($disabled[$key])) {
273 // now, check validity
279 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
281 throw new \
Exception('Incorrect format');
283 $this->$prop = $d->format('Y-m-d');
284 } catch (\Exception
$e) {
286 'Wrong date format. field: ' . $key .
287 ', value: ' . $value . ', expected fmt: ' .
288 __("Y-m-d") . ' | ' . $e->getMessage(),
291 $this->errors
[] = str_replace(
298 $this->_fields
[$key]['label']
300 _T("- Wrong date format (%date_format) for %field!")
305 $this->_member
= (int)$value;
308 $this->_amount
= $value;
309 $value = strtr($value, ',', '.');
310 if (!is_numeric($value)) {
311 $this->errors
[] = _T("- The amount must be an integer!");
315 /** TODO: retrieve field length from database and check that */
316 $this->_description
= $value;
317 if (trim($value) == '') {
318 $this->errors
[] = _T("- Empty transaction description!");
319 } elseif (mb_strlen($value) > 150) {
320 $this->errors
[] = _T("- Transaction description must be 150 characters long maximum.");
328 // missing required fields?
329 foreach ($required as $key => $val) {
331 $prop = '_' . $this->_fields
[$key]['propname'];
332 if (!isset($disabled[$key]) && !isset($this->$prop)) {
333 $this->errors
[] = str_replace(
335 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
336 _T("- Mandatory field %field empty.")
342 if ($this->_id
!= '') {
343 $dispatched = $this->getDispatchedAmount();
344 if ($dispatched > $this->_amount
) {
345 $this->errors
[] = _T("- Sum of all contributions exceed corresponding transaction amount.");
349 $this->dynamicsCheck($values);
351 if (count($this->errors
) > 0) {
353 'Some errors has been throwed attempting to edit/store a transaction' .
354 print_r($this->errors
, true),
357 return $this->errors
;
360 'Transaction checked successfully.',
368 * Store the transaction
370 * @param History $hist History
374 public function store(History
$hist)
379 $this->zdb
->connection
->beginTransaction();
381 $fields = $this->getDbFields($this->zdb
);
383 foreach ($fields as $field) {
384 $prop = '_' . $this->_fields
[$field]['propname'];
385 $values[$field] = $this->$prop;
389 if (!isset($this->_id
) ||
$this->_id
== '') {
390 //we're inserting a new transaction
391 unset($values[self
::PK
]);
392 $insert = $this->zdb
->insert(self
::TABLE
);
393 $insert->values($values);
394 $add = $this->zdb
->execute($insert);
395 if ($add->count() > 0) {
396 if ($this->zdb
->isPostgres()) {
397 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
398 PREFIX_DB
. 'transactions_id_seq'
401 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
406 _T("Transaction added"),
407 Adherent
::getSName($this->zdb
, $this->_member
)
411 $emitter->emit('transaction.add', $this);
413 $hist->add(_T("Fail to add new transaction."));
414 throw new \
Exception(
415 'An error occurred inserting new transaction!'
419 //we're editing an existing transaction
420 $update = $this->zdb
->update(self
::TABLE
);
421 $update->set($values)->where(
422 self
::PK
. '=' . $this->_id
424 $edit = $this->zdb
->execute($update);
425 //edit == 0 does not mean there were an error, but that there
426 //were nothing to change
427 if ($edit->count() > 0) {
429 _T("Transaction updated"),
430 Adherent
::getSName($this->zdb
, $this->_member
)
435 $emitter->emit('transaction.edit', $this);
440 $success = $this->dynamicsStore(true);
443 $this->zdb
->connection
->commit();
445 } catch (\Exception
$e) {
446 $this->zdb
->connection
->rollBack();
448 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
449 $e->getTraceAsString(),
457 * Retrieve amount that has already been dispatched into contributions
461 public function getDispatchedAmount()
464 $select = $this->zdb
->select(Contribution
::TABLE
);
467 'sum' => new Expression('SUM(montant_cotis)')
469 )->where(self
::PK
. ' = ' . $this->_id
);
471 $results = $this->zdb
->execute($select);
472 $result = $results->current();
473 $dispatched_amount = $result->sum
;
474 return (double)$dispatched_amount;
475 } catch (\Exception
$e) {
477 'An error occurred retrieving dispatched amounts | ' .
485 * Retrieve amount that has not yet been dispatched into contributions
489 public function getMissingAmount()
492 $select = $this->zdb
->select(Contribution
::TABLE
);
495 'sum' => new Expression('SUM(montant_cotis)')
497 )->where(self
::PK
. ' = ' . $this->_id
);
499 $results = $this->zdb
->execute($select);
500 $result = $results->current();
501 $dispatched_amount = $result->sum
;
502 return (double)$this->_amount
- (double)$dispatched_amount;
503 } catch (\Exception
$e) {
505 'An error occurred retrieving missing amounts | ' .
513 * Retrieve fields from database
515 * @param Db $zdb Database instance
519 public function getDbFields(Db
$zdb)
521 $columns = $zdb->getColumns(self
::TABLE
);
523 foreach ($columns as $col) {
524 $fields[] = $col->getName();
530 * Get the relevant CSS class for current transaction
532 * @return string current transaction row class
534 public function getRowClass()
536 return ($this->getMissingAmount() == 0) ?
537 'transaction-normal' : 'transaction-uncomplete';
541 * Global getter method
543 * @param string $name name of the property we want to retrive
545 * @return false|object the called property
547 public function __get($name)
549 $forbidden = array();
551 $rname = '_' . $name;
552 if (!in_array($name, $forbidden) && isset($this->$rname)) {
555 if ($this->$rname != '') {
557 $d = new \
DateTime($this->$rname);
558 return $d->format(__("Y-m-d"));
559 } catch (\Exception
$e) {
560 //oops, we've got a bad date :/
562 'Bad date (' . $this->$rname . ') | ' .
566 return $this->$rname;
571 return $this->$rname;
580 * Global setter method
582 * @param string $name name of the property we want to assign a value to
583 * @param object $value a relevant value for the property
587 public function __set($name, $value)
589 /*$forbidden = array('fields');*/
590 /** TODO: What to do ? :-) */
596 * @param string $field Field name
600 private function getFieldLabel($field)
602 $label = $this->_fields
[$field]['label'];
603 //remove trailing ':' and then nbsp (for french at least)
604 $label = trim(trim($label, ':'), ' ');