# Critical Alerts Alert Bar Implementation

## Overview
Sistem alert bar yang menampilkan notifikasi dengan priority **critical** di bagian atas main content area. Alert ini auto-refresh setiap 30 detik dan dapat di-dismiss oleh user.

## Implementasi

### 1. HTML Alert Container
**File**: `backend/views/layouts/main.php` (line 450)
```html
<!-- Critical Notifications Alert Bar -->
<div id="critical-alerts-container" style="margin-bottom: 15px;"></div>
```

### 2. JavaScript Functionality
**File**: `backend/web/js/notification-bell.js`

#### New Methods:
- `loadCriticalAlerts()` — fetch critical alerts dari API `/backend/notification/dashboard`
- `renderCriticalAlerts(alerts)` — render alerts dengan CTA button dan close button

#### Features:
```javascript
- Auto-load saat page init
- Auto-refresh setiap 30 detik (sama dengan notification bell)
- Tampilkan max 5 critical alerts
- Setiap alert punya:
  * Icon (fa-*)
  * Title
  * Message (preview)
  * Action URL (CTA button "Lihat Detail")
  * Close button ("Tutup") untuk dismiss
```

### 3. CSS Styling
**File**: `backend/web/css/notification-bell.css`

Alert styling:
- **Background**: Merah muda (#f8d7da) dengan border merah
- **Text**: Warna merah tua (#721c24)
- **Button**: 
  - Primary CTA = tombol danger merah
  - Secondary = link text danger
- **Animation**: Slide down effect saat muncul

### 4. API Endpoint
**File**: `backend/controllers/NotificationController.php`

Endpoint: `GET /backend/notification/dashboard`
```php
public function actionDashboard()
{
    // Return max 5 critical notifications dengan priority=critical
    // Field yang di-return: id, title, message, priority, action_url, icon
}
```

---

## Visual Structure

```
┌─────────────────────────────────────────────────────────────────┐
│  🚨 Database Connection Error (Critical)                  [Detail] [Tutup] │
│  Database server tidak merespons sejak 2 menit yang lalu              │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│  🚨 Stock Barang "Ayam Bakar" Habis (Critical)           [Lihat] [Tutup] │
│  Stok barang SKU: ABM-001 sudah mencapai 0 unit                    │
└─────────────────────────────────────────────────────────────────┘

[Main Content Area...]
```

---

## User Interactions

### 1. Click "Lihat Detail" Button
- Navigasi ke `action_url` (e.g., `/backend/barang/view?id=88`)
- Alert tetap tampil

### 2. Click "Tutup" Button
- Trigger `markAsDismissed(notifId)` via AJAX
- Alert slide up dan disappear
- Notifikasi di database di-mark `is_dismissed = 1`

### 3. Auto-Refresh (30 detik)
- Reload critical alerts dari API
- Jika sudah di-dismiss, tidak akan ditampilkan lagi
- Jika ada alert baru, muncul dengan slide down animation

---

## Integration Points

### Dashboard Endpoint Implementation
File: `backend/controllers/NotificationController.php`

```php
public function actionDashboard()
{
    Yii::$app->response->format = Response::FORMAT_JSON;

    $userId = Yii::$app->user->id;
    $user = Yii::$app->user->identity;

    // Notifikasi dashboard yang harus ditampilkan (priority = critical)
    $dashboardCodes = [
        'DASHBOARD_CASHIER_SESSION_OPEN',
        'INV_STOCK_OUT',
        'INV_STOCK_NEGATIVE',
        'PURCHASE_INVOICE_DUE',
        'CUSTOMER_RECEIVABLE_DUE',
        'SALES_PAYLATER_LIMIT_EXCEEDED',
        'RESERVATION_TODAY_UNCONFIRMED',
        'AUTH_SUSPICIOUS_LOGIN',
    ];

    $recipients = NotificationRecipient::find()
        ->with('notification')
        ->where([
            'user_id' => $userId,
            'is_dismissed' => 0,
        ])
        ->andWhere(['in', 'notification.notification_code', $dashboardCodes])
        ->andWhere(['notification.priority' => 'critical'])
        ->orderBy(['notification.created_at' => SORT_DESC])
        ->limit(5)
        ->all();

    $data = [];
    foreach ($recipients as $recipient) {
        $notif = $recipient->notification;
        $data[] = [
            'id' => $notif->id,
            'title' => $notif->title,
            'message' => $notif->message,
            'priority' => $notif->priority,
            'category' => $notif->category,
            'action_url' => $notif->action_url,
            'icon' => $notif->icon,
        ];
    }

    return [
        'success' => true,
        'data' => $data,
    ];
}
```

---

## Testing

### 1. Manual Test - Create Critical Notification
```php
// Backend console atau test script
Yii::$app->services->notification->dispatch(
    'INV_STOCK_OUT',
    3, // cabang_id
    [
        'message' => 'Test critical alert - Stok Ayam Bakar habis',
        'barang_id' => 88,
        'qty' => 0,
    ],
    'barang_stok',
    88
);
```

### 2. Verify in Browser
- Login ke backend
- Buka halaman apa saja (semua halaman pakai main.php)
- Lihat critical alerts tampil di atas content area
- Click "Lihat Detail" → navigasi ke detail page
- Click "Tutup" → alert disappear dan mark as dismissed
- Wait 30 detik → verify alert tidak muncul lagi

### 3. Check Notification Bell
- Critical alert juga tampil di notification bell dropdown
- Unread count di badge include critical alerts

---

## Features Supported

✅ Auto-load pada page load
✅ Auto-refresh setiap 30 detik
✅ Dismiss individual alerts
✅ Click through ke detail page via CTA
✅ Responsive design (mobile-friendly)
✅ Smooth animations (slide down/up)
✅ Multiple alerts support (max 5)
✅ Priority-based filtering (critical only)
✅ HTML escaping untuk security

---

## Customization

### Change Refresh Interval
**File**: `backend/web/js/notification-bell.js`
```javascript
refreshInterval: 30000, // 30 seconds (ubah ke ms yang diinginkan)
```

### Change Max Alerts Displayed
**File**: `backend/controllers/NotificationController.php`
```php
->limit(5)  // Ubah ke jumlah yang diinginkan
```

### Adjust Alert Colors
**File**: `backend/web/css/notification-bell.css`
```css
.alert-danger {
    background-color: #f8d7da;  /* Ubah warna background */
    border-color: #f5c6cb;      /* Ubah warna border */
    color: #721c24;             /* Ubah warna text */
}
```

---

## Performance Notes

- API call hanya untuk authenticated users (`requireLogin()`)
- Cache tidak digunakan (real-time critical alerts)
- AJAX timeout: 5 detik (fallback if API slow)
- No impact pada page load time (async AJAX)
- Memory efficient: max 5 alerts per page

---

Generated: 2026-06-09
Status: **Complete & Ready for Testing**
