Move the model callbacks into Observables; reduce caching since it held balances incorrectly

This commit is contained in:
Nabeel Shahzad
2018-03-18 20:37:35 -05:00
parent 6b002f24a8
commit 36ea12e135
25 changed files with 336 additions and 266 deletions

View File

@@ -7,6 +7,7 @@
namespace App\Models;
/**
* @property string id UUID type
* @property string currency
* @property string memo
* @property string transaction_group
@@ -15,6 +16,7 @@ namespace App\Models;
* @property integer debit
* @property string ref_class
* @property integer ref_class_id
* @property Journal journal
*/
class JournalTransaction extends BaseModel
{
@@ -48,59 +50,6 @@ class JournalTransaction extends BaseModel
'post_date',
];
/**
* Callbacks
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
*/
protected static function boot()
{
static::creating(function ($transaction) {
if(!$transaction->id) {
$transaction->id = \Ramsey\Uuid\Uuid::uuid4()->toString();
}
});
/**
* Adjust the balance according to credits and debits
*/
static::saved(function ($transaction) {
//$transaction->journal->resetCurrentBalances();
$journal = $transaction->journal;
if($transaction['credit']) {
$balance = $journal->balance->toAmount();
$journal->balance = $balance + $transaction['credit'];
}
if($transaction['debit']) {
$balance = $journal->balance->toAmount();
$journal->balance = $balance - $transaction['debit'];
}
$journal->save();
});
/**
* Deleting a transaction reverses the credits and debits
*/
static::deleted(function ($transaction) {
$journal = $transaction->journal;
if ($transaction['credit']) {
$balance = $journal->balance->toAmount();
$journal->balance = $balance - $transaction['credit'];
}
if ($transaction['debit']) {
$balance = $journal->balance->toAmount();
$journal->balance = $balance + $transaction['debit'];
}
$journal->save();
});
parent::boot();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/