2018-03-19 09:37:35 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Models\Observers;
|
|
|
|
|
|
|
|
use App\Models\JournalTransaction;
|
|
|
|
|
2018-03-20 09:50:40 +08:00
|
|
|
/**
|
|
|
|
* Class JournalTransactionObserver
|
|
|
|
* @package App\Models\Observers
|
|
|
|
*/
|
2018-03-19 09:37:35 +08:00
|
|
|
class JournalTransactionObserver
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Set the ID to a UUID
|
|
|
|
* @param JournalTransaction $transaction
|
|
|
|
*/
|
|
|
|
public function creating(JournalTransaction $transaction): void
|
|
|
|
{
|
|
|
|
if (!$transaction->id) {
|
|
|
|
$transaction->id = \Ramsey\Uuid\Uuid::uuid4()->toString();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* After transaction is saved, adjust the journal balance
|
|
|
|
* @param JournalTransaction $transaction
|
|
|
|
*/
|
|
|
|
public function saved(JournalTransaction $transaction): void
|
|
|
|
{
|
|
|
|
$journal = $transaction->journal;
|
|
|
|
if ($transaction['credit']) {
|
|
|
|
$balance = $journal->balance->toAmount();
|
|
|
|
$journal->balance = (int) $balance + $transaction->credit;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($transaction['debit']) {
|
|
|
|
$balance = $journal->balance->toAmount();
|
|
|
|
$journal->balance = (int) $balance - $transaction->debit;
|
|
|
|
}
|
|
|
|
|
|
|
|
$journal->save();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* After transaction is deleted, adjust the balance on the journal
|
|
|
|
* @param JournalTransaction $transaction
|
|
|
|
*/
|
|
|
|
public function deleted(JournalTransaction $transaction): void
|
|
|
|
{
|
|
|
|
$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();
|
|
|
|
}
|
|
|
|
}
|