72 lines
2.0 KiB
PHP
72 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Admin\Finance;
|
|
|
|
use App\Enums\CashTransactionType;
|
|
use App\Models\CashAccount;
|
|
use App\Models\CashTransaction;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class CashAccountService
|
|
{
|
|
public function get(): ?CashAccount
|
|
{
|
|
return CashAccount::first();
|
|
}
|
|
|
|
public function getAllTransactions(): Collection
|
|
{
|
|
$cashAccount = $this->get();
|
|
|
|
if (! $cashAccount) {
|
|
return collect();
|
|
}
|
|
|
|
return $cashAccount->cashTransactions()
|
|
->with('createdBy.userProfile')
|
|
->latest()
|
|
->get();
|
|
}
|
|
|
|
public function deposit(array $data): CashTransaction
|
|
{
|
|
$cashAccount = CashAccount::firstOrFail();
|
|
$newBalance = $cashAccount->balance + $data['amount'];
|
|
|
|
$cashAccount->update(['balance' => $newBalance]);
|
|
|
|
return CashTransaction::create([
|
|
'cash_account_id' => $cashAccount->id,
|
|
'created_by_id' => auth()->id(),
|
|
'amount' => $data['amount'],
|
|
'balance_after' => $newBalance,
|
|
'type' => CashTransactionType::DEPOSIT,
|
|
'description' => $data['description'],
|
|
]);
|
|
}
|
|
|
|
public function withdrawal(array $data): CashTransaction
|
|
{
|
|
$cashAccount = CashAccount::firstOrFail();
|
|
|
|
if ($cashAccount->balance < $data['amount']) {
|
|
throw ValidationException::withMessages([
|
|
'amount' => 'Saldo tidak mencukupi.',
|
|
]);
|
|
}
|
|
|
|
$newBalance = $cashAccount->balance - $data['amount'];
|
|
$cashAccount->update(['balance' => $newBalance]);
|
|
|
|
return CashTransaction::create([
|
|
'cash_account_id' => $cashAccount->id,
|
|
'created_by_id' => auth()->id(),
|
|
'amount' => $data['amount'],
|
|
'balance_after' => $newBalance,
|
|
'type' => CashTransactionType::WITHDRAWAL,
|
|
'description' => $data['description'],
|
|
]);
|
|
}
|
|
}
|