67 lines
2.4 KiB
PHP
67 lines
2.4 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Observers;
|
||
|
|
|
||
|
|
use App\Models\Medicine;
|
||
|
|
use App\Models\User;
|
||
|
|
use App\Models\Setting;
|
||
|
|
use App\Helpers\WhatsappHelper;
|
||
|
|
use Illuminate\Support\Facades\Mail;
|
||
|
|
use App\Mail\LowStockNotification;
|
||
|
|
use Illuminate\Support\Facades\Log;
|
||
|
|
|
||
|
|
class MedicineObserver
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Handle the Medicine "updated" event.
|
||
|
|
*/
|
||
|
|
public function updated(Medicine $medicine)
|
||
|
|
{
|
||
|
|
// 1. Validasi: Hanya jalankan jika kolom 'qty' berubah
|
||
|
|
if (!$medicine->wasChanged('qty')) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 2. Cek apakah stok di bawah ambang batas (5)
|
||
|
|
if ($medicine->qty < 5) {
|
||
|
|
|
||
|
|
// 3. Ambil status Master Switch dari tabel settings
|
||
|
|
$settings = Setting::where('group', 'notification')->pluck('value', 'key');
|
||
|
|
$isEmailActive = ($settings['notif_email_status'] ?? 'inactive') === 'active';
|
||
|
|
$isWaActive = ($settings['notif_wa_status'] ?? 'inactive') === 'active';
|
||
|
|
|
||
|
|
// 4. Cari Admin (Bisa lebih dari satu jika diperlukan)
|
||
|
|
$admins = User::where('role', 'admin')->get();
|
||
|
|
|
||
|
|
if ($admins->isEmpty()) {
|
||
|
|
Log::warning("Notifikasi stok rendah gagal dikirim: Tidak ada user dengan role admin.");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
$msg = "⚠️ *STOK KRITIS (earrin cats)*\n\n";
|
||
|
|
$msg .= "Obat: {$medicine->nama_obat}\n";
|
||
|
|
$msg .= "Sisa: *{$medicine->qty} {$medicine->unit}*\n";
|
||
|
|
$msg .= "Segera lakukan restock untuk pasien cattery.";
|
||
|
|
|
||
|
|
foreach ($admins as $admin) {
|
||
|
|
// Kirim Email jika aktif
|
||
|
|
if ($isEmailActive && $admin->email) {
|
||
|
|
try {
|
||
|
|
Mail::to($admin->email)->send(new LowStockNotification($medicine));
|
||
|
|
} catch (\Exception $e) {
|
||
|
|
Log::error("Gagal mengirim email stok rendah ke {$admin->email}: " . $e->getMessage());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Kirim WhatsApp jika aktif & nomor tersedia
|
||
|
|
if ($isWaActive && $admin->phone) {
|
||
|
|
try {
|
||
|
|
WhatsappHelper::send($admin->phone, $msg);
|
||
|
|
} catch (\Exception $e) {
|
||
|
|
Log::error("Gagal mengirim WA stok rendah ke {$admin->phone}: " . $e->getMessage());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|