57 lines
1.7 KiB
PHP
57 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Concerns;
|
|
|
|
use App\Enums\CashTransactionType;
|
|
use App\Models\CashAccount;
|
|
use App\Models\CashTransaction;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
trait HandlesCashTransactions
|
|
{
|
|
private function getCashAccount(): CashAccount
|
|
{
|
|
return CashAccount::firstOrFail();
|
|
}
|
|
|
|
private function creditCash(int $amount, string $description, CashTransactionType $type = CashTransactionType::DEPOSIT): CashTransaction
|
|
{
|
|
$cashAccount = $this->getCashAccount();
|
|
$newBalance = $cashAccount->balance + $amount;
|
|
|
|
$cashAccount->update(['balance' => $newBalance]);
|
|
|
|
return CashTransaction::create([
|
|
'cash_account_id' => $cashAccount->id,
|
|
'created_by_id' => auth()->id(),
|
|
'amount' => $amount,
|
|
'balance_after' => $newBalance,
|
|
'type' => $type,
|
|
'description' => $description,
|
|
]);
|
|
}
|
|
|
|
private function debitCash(int $amount, string $description, CashTransactionType $type = CashTransactionType::EXPENSE): CashTransaction
|
|
{
|
|
$cashAccount = $this->getCashAccount();
|
|
|
|
if ($cashAccount->balance < $amount) {
|
|
throw ValidationException::withMessages([
|
|
'amount' => 'Saldo tidak mencukupi.',
|
|
]);
|
|
}
|
|
|
|
$newBalance = $cashAccount->balance - $amount;
|
|
$cashAccount->update(['balance' => $newBalance]);
|
|
|
|
return CashTransaction::create([
|
|
'cash_account_id' => $cashAccount->id,
|
|
'created_by_id' => auth()->id(),
|
|
'amount' => $amount,
|
|
'balance_after' => $newBalance,
|
|
'type' => $type,
|
|
'description' => $description,
|
|
]);
|
|
}
|
|
}
|