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
|
|
|
|
*/
|
2018-03-19 09:37:35 +08:00
|
|
|
class JournalTransactionObserver
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Set the ID to a UUID
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-03-19 09:37:35 +08:00
|
|
|
* @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
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-03-19 09:37:35 +08:00
|
|
|
* @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
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-03-19 09:37:35 +08:00
|
|
|
* @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();
|
|
|
|
}
|
|
|
|
}
|