| Server IP : 35.80.110.71 / Your IP : 216.73.216.221 Web Server : Apache/2.4.58 (Ubuntu) System : Linux ip-172-31-21-44 6.17.0-1019-aws #19~24.04.1-Ubuntu SMP Tue Jun 23 18:53:06 UTC 2026 x86_64 User : ubuntu ( 1000) PHP Version : 8.3.31 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/client-portal-laravel/releases/20260626120707/app/Observers/ |
Upload File : |
<?php
declare(strict_types=1);
namespace App\Observers;
use App\Events\DashboardStatsUpdated;
use App\Events\InvoiceStatusChanged;
use App\Models\Invoicing\Invoice;
use App\Services\CacheService;
use App\Services\DashboardService;
use App\Services\Events\EventDispatcher;
class InvoiceObserver
{
public function __construct(
private CacheService $cache,
private EventDispatcher $eventDispatcher,
) {}
/**
* Handle the Invoice "created" event.
*/
public function created(Invoice $invoice): void
{
$this->invalidateCache($invoice);
$this->broadcastDashboardStats();
}
/**
* Handle the Invoice "updated" event.
*/
public function updated(Invoice $invoice): void
{
$this->invalidateCache($invoice);
// Broadcast status change if status was updated
if ($invoice->wasChanged('status')) {
$previousStatus = $invoice->getOriginal('status');
$this->eventDispatcher->dispatch(new InvoiceStatusChanged(
$invoice,
$previousStatus instanceof \App\Enums\InvoiceStatus ? $previousStatus->value : (string) $previousStatus,
auth()->id()
));
}
$this->broadcastDashboardStats();
}
/**
* Handle the Invoice "deleted" event.
*/
public function deleted(Invoice $invoice): void
{
$this->invalidateCache($invoice);
$this->broadcastDashboardStats();
}
/**
* Handle the Invoice "restored" event.
*/
public function restored(Invoice $invoice): void
{
$this->invalidateCache($invoice);
$this->broadcastDashboardStats();
}
/**
* Handle the Invoice "force deleted" event.
*/
public function forceDeleted(Invoice $invoice): void
{
$this->invalidateCache($invoice);
$this->broadcastDashboardStats();
}
/**
* Invalidate related cache entries.
*/
protected function invalidateCache(Invoice $invoice): void
{
$this->cache->invalidateDashboard();
$this->cache->invalidateClient($invoice->client_id);
}
/**
* Broadcast updated dashboard stats to admin users.
*/
protected function broadcastDashboardStats(): void
{
try {
$stats = app(DashboardService::class)->getStats();
$this->eventDispatcher->dispatch(new DashboardStatsUpdated($stats));
} catch (\Throwable) {
// Ignore broadcast failures
}
}
}