71 lines
2.2 KiB
PHP
71 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Observers;
|
|
|
|
use App\Models\Transaction;
|
|
use App\Services\CallCreditService;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
class TransactionObserver
|
|
{
|
|
/**
|
|
* After a transaction is created, bust balance caches and check credits.
|
|
*/
|
|
public function created(Transaction $transaction): void
|
|
{
|
|
$this->bustBalanceCaches($transaction);
|
|
|
|
$fromAccount = $transaction->accountFrom;
|
|
if (!$fromAccount) {
|
|
return;
|
|
}
|
|
|
|
$accountable = $fromAccount->accountable;
|
|
if (!$accountable) {
|
|
return;
|
|
}
|
|
|
|
$profileType = get_class($accountable);
|
|
$profileId = $accountable->id;
|
|
|
|
if (!CallCreditService::profileHasCredits($profileType, $profileId)) {
|
|
CallCreditService::pauseAllActiveCalls($profileType, $profileId);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Bust account_balance and accounts_info caches for both sides of the transaction.
|
|
* This is the SINGLE SOURCE OF TRUTH for cache invalidation.
|
|
*/
|
|
private function bustBalanceCaches(Transaction $transaction): void
|
|
{
|
|
$accounts = collect([
|
|
$transaction->from_account_id ? $transaction->accountFrom : null,
|
|
$transaction->to_account_id ? $transaction->accountTo : null,
|
|
])->filter();
|
|
|
|
$clearedCaches = [];
|
|
foreach ($accounts as $account) {
|
|
// Bust per-account balance cache
|
|
$balanceKey = "account_balance_{$account->id}";
|
|
Cache::forget($balanceKey);
|
|
$clearedCaches[] = $balanceKey;
|
|
|
|
// Bust accounts_info cache for the owning profile
|
|
$accountable = $account->accountable;
|
|
if ($accountable) {
|
|
$profileType = get_class($accountable);
|
|
$profileId = $accountable->id;
|
|
$accountsInfoKey = "accounts_info_{$profileType}_{$profileId}";
|
|
Cache::forget($accountsInfoKey);
|
|
$clearedCaches[] = $accountsInfoKey;
|
|
}
|
|
}
|
|
|
|
\Log::info('[TRANSACTION-OBSERVER] Caches cleared on transaction creation', [
|
|
'transactionId' => $transaction->id,
|
|
'clearedCaches' => $clearedCaches,
|
|
]);
|
|
}
|
|
}
|