]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Transaction.php
2c898990f8c629607ae5387e4c9a4cac236c5dbe
[galette.git] / galette / lib / Galette / Entity / Transaction.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Transaction class for galette
7 *
8 * PHP version 5
9 *
10 * Copyright © 2011-2014 The Galette Team
11 *
12 * This file is part of Galette (http://galette.tuxfamily.org).
13 *
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.
18 *
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.
23 *
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/>.
26 *
27 * @category Entity
28 * @package Galette
29 *
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
33 * @version SVN: $Id$
34 * @link http://galette.tuxfamily.org
35 * @since Available since 0.7dev - 2011-07-31
36 */
37
38 namespace Galette\Entity;
39
40 use Analog\Analog;
41 use Laminas\Db\Sql\Expression;
42 use Galette\Repository\Contributions;
43 use Galette\Core\Db;
44 use Galette\Core\History;
45 use Galette\Core\Login;
46
47 /**
48 * Transaction class for galette
49 *
50 * @category Entity
51 * @name Transaction
52 * @package 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
58 */
59 class Transaction
60 {
61 use DynamicsTrait;
62
63 const TABLE = 'transactions';
64 const PK = 'trans_id';
65
66 private $_id;
67 private $_date;
68 private $_amount;
69 private $_description;
70 private $_member;
71
72 //fields list and their translation
73 private $_fields;
74
75 private $zdb;
76 private $login;
77
78 private $errors;
79
80 /**
81 * Default constructor
82 *
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
87 * instanciate object
88 */
89 public function __construct(Db $zdb, Login $login, $args = null)
90 {
91 $this->zdb = $zdb;
92 $this->login = $login;
93
94 /*
95 * Fields configuration. Each field is an array and must reflect:
96 * array(
97 * (string)label,
98 * (string) propname
99 * )
100 *
101 * I'd prefer a static private variable for this...
102 * But call to the _T function does not seem to be allowed there :/
103 */
104 $this->_fields = array(
105 self::PK => array(
106 'label' => null, //not a field in the form
107 'propname' => 'id'
108 ),
109 'trans_date' => array(
110 'label' => _T("Date:"), //not a field in the form
111 'propname' => 'date'
112 ),
113 'trans_amount' => array(
114 'label' => _T("Amount:"),
115 'propname' => 'amount'
116 ),
117 'trans_desc' => array(
118 'label' => _T("Description:"),
119 'propname' => 'description'
120 ),
121 Adherent::PK => array(
122 'label' => _T("Originator:"),
123 'propname' => 'member'
124 )
125 );
126 if ($args == null || is_int($args)) {
127 $this->_date = date("Y-m-d");
128
129 if (is_int($args) && $args > 0) {
130 $this->load($args);
131 }
132 } elseif (is_object($args)) {
133 $this->loadFromRS($args);
134 }
135
136 $this->loadDynamicFields();
137 }
138
139 /**
140 * Loads a transaction from its id
141 *
142 * @param int $id the identifier for the transaction to load
143 *
144 * @return bool true if query succeed, false otherwise
145 */
146 public function load($id)
147 {
148 try {
149 $select = $this->zdb->select(self::TABLE);
150 $select->where(self::PK . ' = ' . $id);
151
152 $results = $this->zdb->execute($select);
153 $result = $results->current();
154 if ($result) {
155 $this->loadFromRS($result);
156 return true;
157 } else {
158 throw new \Exception();
159 }
160 } catch (\Exception $e) {
161 Analog::log(
162 'Cannot load transaction form id `' . $id . '` | ' .
163 $e->getMessage(),
164 Analog::WARNING
165 );
166 return false;
167 }
168 }
169
170 /**
171 * Remove transaction (and all associated contributions) from database
172 *
173 * @param History $hist History
174 * @param boolean $transaction Activate transaction mode (defaults to true)
175 *
176 * @return boolean
177 */
178 public function remove(History $hist, $transaction = true)
179 {
180 global $emitter;
181
182 try {
183 if ($transaction) {
184 $this->zdb->connection->beginTransaction();
185 }
186
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);
191 $cids = array();
192 foreach ($clist as $cid) {
193 $cids[] = $cid->id;
194 }
195 $rem = $c->remove($cids, $hist, false);
196 }
197
198 //remove transaction itself
199 $delete = $this->zdb->delete(self::TABLE);
200 $delete->where(
201 self::PK . ' = ' . $this->_id
202 );
203 $this->zdb->execute($delete);
204
205 $this->dynamicsRemove(true);
206
207 if ($transaction) {
208 $this->zdb->connection->commit();
209 }
210 $emitter->emit('transaction.remove', $this);
211 return true;
212 } catch (\Exception $e) {
213 if ($transaction) {
214 $this->zdb->connection->rollBack();
215 }
216 Analog::log(
217 'An error occurred trying to remove transaction #' .
218 $this->_id . ' | ' . $e->getMessage(),
219 Analog::ERROR
220 );
221 return false;
222 }
223 }
224
225 /**
226 * Populate object from a resultset row
227 *
228 * @param ResultSet $r the resultset row
229 *
230 * @return void
231 */
232 private function loadFromRS($r)
233 {
234 $pk = self::PK;
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;
241
242 $this->loadDynamicFields();
243 }
244
245 /**
246 * Check posted values validity
247 *
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
252 *
253 * @return true|array
254 */
255 public function check($values, $required, $disabled)
256 {
257 $this->errors = array();
258
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'];
264
265 if (isset($values[$key])) {
266 $value = trim($values[$key]);
267 } else {
268 $value = '';
269 }
270
271 // if the field is enabled, check it
272 if (!isset($disabled[$key])) {
273 // now, check validity
274 if ($value != '') {
275 switch ($key) {
276 // dates
277 case 'trans_date':
278 try {
279 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
280 if ($d === false) {
281 throw new \Exception('Incorrect format');
282 }
283 $this->$prop = $d->format('Y-m-d');
284 } catch (\Exception $e) {
285 Analog::log(
286 'Wrong date format. field: ' . $key .
287 ', value: ' . $value . ', expected fmt: ' .
288 __("Y-m-d") . ' | ' . $e->getMessage(),
289 Analog::INFO
290 );
291 $this->errors[] = str_replace(
292 array(
293 '%date_format',
294 '%field'
295 ),
296 array(
297 __("Y-m-d"),
298 $this->_fields[$key]['label']
299 ),
300 _T("- Wrong date format (%date_format) for %field!")
301 );
302 }
303 break;
304 case Adherent::PK:
305 $this->_member = (int)$value;
306 break;
307 case 'trans_amount':
308 $this->_amount = $value;
309 $value = strtr($value, ',', '.');
310 if (!is_numeric($value)) {
311 $this->errors[] = _T("- The amount must be an integer!");
312 }
313 break;
314 case 'trans_desc':
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.");
321 }
322 break;
323 }
324 }
325 }
326 }
327
328 // missing required fields?
329 foreach ($required as $key => $val) {
330 if ($val === 1) {
331 $prop = '_' . $this->_fields[$key]['propname'];
332 if (!isset($disabled[$key]) && !isset($this->$prop)) {
333 $this->errors[] = str_replace(
334 '%field',
335 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
336 _T("- Mandatory field %field empty.")
337 );
338 }
339 }
340 }
341
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.");
346 }
347 }
348
349 $this->dynamicsCheck($values);
350
351 if (count($this->errors) > 0) {
352 Analog::log(
353 'Some errors has been throwed attempting to edit/store a transaction' .
354 print_r($this->errors, true),
355 Analog::DEBUG
356 );
357 return $this->errors;
358 } else {
359 Analog::log(
360 'Transaction checked successfully.',
361 Analog::DEBUG
362 );
363 return true;
364 }
365 }
366
367 /**
368 * Store the transaction
369 *
370 * @param History $hist History
371 *
372 * @return boolean
373 */
374 public function store(History $hist)
375 {
376 global $emitter;
377
378 try {
379 $this->zdb->connection->beginTransaction();
380 $values = array();
381 $fields = $this->getDbFields($this->zdb);
382 /** FIXME: quote? */
383 foreach ($fields as $field) {
384 $prop = '_' . $this->_fields[$field]['propname'];
385 $values[$field] = $this->$prop;
386 }
387
388 $success = false;
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'
399 );
400 } else {
401 $this->_id = $this->zdb->driver->getLastGeneratedValue();
402 }
403
404 // logging
405 $hist->add(
406 _T("Transaction added"),
407 Adherent::getSName($this->zdb, $this->_member)
408 );
409 $success = true;
410
411 $emitter->emit('transaction.add', $this);
412 } else {
413 $hist->add(_T("Fail to add new transaction."));
414 throw new \Exception(
415 'An error occurred inserting new transaction!'
416 );
417 }
418 } else {
419 //we're editing an existing transaction
420 $update = $this->zdb->update(self::TABLE);
421 $update->set($values)->where(
422 self::PK . '=' . $this->_id
423 );
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) {
428 $hist->add(
429 _T("Transaction updated"),
430 Adherent::getSName($this->zdb, $this->_member)
431 );
432 }
433 $success = true;
434
435 $emitter->emit('transaction.edit', $this);
436 }
437
438 //dynamic fields
439 if ($success) {
440 $success = $this->dynamicsStore(true);
441 }
442
443 $this->zdb->connection->commit();
444 return true;
445 } catch (\Exception $e) {
446 $this->zdb->connection->rollBack();
447 Analog::log(
448 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
449 $e->getTraceAsString(),
450 Analog::ERROR
451 );
452 return false;
453 }
454 }
455
456 /**
457 * Retrieve amount that has already been dispatched into contributions
458 *
459 * @return double
460 */
461 public function getDispatchedAmount()
462 {
463 try {
464 $select = $this->zdb->select(Contribution::TABLE);
465 $select->columns(
466 array(
467 'sum' => new Expression('SUM(montant_cotis)')
468 )
469 )->where(self::PK . ' = ' . $this->_id);
470
471 $results = $this->zdb->execute($select);
472 $result = $results->current();
473 $dispatched_amount = $result->sum;
474 return (double)$dispatched_amount;
475 } catch (\Exception $e) {
476 Analog::log(
477 'An error occurred retrieving dispatched amounts | ' .
478 $e->getMessage(),
479 Analog::ERROR
480 );
481 }
482 }
483
484 /**
485 * Retrieve amount that has not yet been dispatched into contributions
486 *
487 * @return double
488 */
489 public function getMissingAmount()
490 {
491 try {
492 $select = $this->zdb->select(Contribution::TABLE);
493 $select->columns(
494 array(
495 'sum' => new Expression('SUM(montant_cotis)')
496 )
497 )->where(self::PK . ' = ' . $this->_id);
498
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) {
504 Analog::log(
505 'An error occurred retrieving missing amounts | ' .
506 $e->getMessage(),
507 Analog::ERROR
508 );
509 }
510 }
511
512 /**
513 * Retrieve fields from database
514 *
515 * @param Db $zdb Database instance
516 *
517 * @return array
518 */
519 public function getDbFields(Db $zdb)
520 {
521 $columns = $zdb->getColumns(self::TABLE);
522 $fields = array();
523 foreach ($columns as $col) {
524 $fields[] = $col->getName();
525 }
526 return $fields;
527 }
528
529 /**
530 * Get the relevant CSS class for current transaction
531 *
532 * @return string current transaction row class
533 */
534 public function getRowClass()
535 {
536 return ($this->getMissingAmount() == 0) ?
537 'transaction-normal' : 'transaction-uncomplete';
538 }
539
540 /**
541 * Global getter method
542 *
543 * @param string $name name of the property we want to retrive
544 *
545 * @return false|object the called property
546 */
547 public function __get($name)
548 {
549 $forbidden = array();
550
551 $rname = '_' . $name;
552 if (!in_array($name, $forbidden) && isset($this->$rname)) {
553 switch ($name) {
554 case 'date':
555 if ($this->$rname != '') {
556 try {
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 :/
561 Analog::log(
562 'Bad date (' . $this->$rname . ') | ' .
563 $e->getMessage(),
564 Analog::INFO
565 );
566 return $this->$rname;
567 }
568 }
569 break;
570 default:
571 return $this->$rname;
572 break;
573 }
574 } else {
575 return false;
576 }
577 }
578
579 /**
580 * Global setter method
581 *
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
584 *
585 * @return void
586 */
587 public function __set($name, $value)
588 {
589 /*$forbidden = array('fields');*/
590 /** TODO: What to do ? :-) */
591 }
592
593 /**
594 * Get field label
595 *
596 * @param string $field Field name
597 *
598 * @return string
599 */
600 private function getFieldLabel($field)
601 {
602 $label = $this->_fields[$field]['label'];
603 //remove trailing ':' and then nbsp (for french at least)
604 $label = trim(trim($label, ':'), '&nbsp;');
605 return $label;
606 }
607 }