# Sinkronisasi Lab Tests Snapshot

## Masalah yang Diselesaikan

Terjadi ketidaksinkronan antara checklist lab di paket MCU dengan form input hasil lab, dimana:
- Admin mengubah checklist lab di halaman paket MCU (misalnya: unchecklist "Anti HAV")
- Appointment yang sudah ada masih menggunakan snapshot lama
- Field lab yang sudah diunchecklist masih muncul di form input hasil lab

## Solusi yang Diimplementasikan

### 1. Sistem Snapshot Otomatis

**File:** `app/Models/Appointment.php`

Appointment menggunakan kolom `lab_tests_snapshot` yang menyimpan snapshot dari `lab_tests_included` paket MCU pada saat:
- Appointment dibuat (event `creating`)
- `mcu_package_id` diubah (event `updating`)

Method `getLabTestsIncluded()` mengutamakan data dari snapshot untuk menjaga konsistensi rekam medis historis.

### 2. Observer Auto-Sync (Solusi Otomatis)

**File:** `app/Observers/McuPackageObserver.php`

Observer yang otomatis mendeteksi perubahan `lab_tests_included` di paket MCU dan melakukan sinkronisasi ke appointment yang:
- Menggunakan paket tersebut
- Belum di-finalize (`final_signed_at IS NULL`)
- Lab result belum di-verify atau masih dalam proses

**Registered di:** `app/Providers/AppServiceProvider.php`

### 3. Command Manual Sync (Solusi Manual)

**File:** `app/Console/Commands/SyncLabTestsSnapshot.php`

Command Artisan untuk sinkronisasi manual dengan berbagai opsi.

## Cara Menggunakan

### A. Sinkronisasi Otomatis (Default)

Observer akan otomatis berjalan setiap kali admin mengubah checklist lab di paket MCU. Tidak perlu aksi manual.

**Log:** Cek di `storage/logs/laravel.log` untuk melihat log sinkronisasi otomatis.

### B. Sinkronisasi Manual

#### 1. Dry Run (Cek Perubahan Tanpa Menyimpan)

```bash
php artisan lab:sync-snapshot --dry-run
```

Berguna untuk:
- Melihat appointment mana saja yang akan diupdate
- Melihat perbedaan antara snapshot lama dan baru
- Memastikan tidak ada kesalahan sebelum eksekusi sebenarnya

#### 2. Sync Semua Appointment

```bash
php artisan lab:sync-snapshot
```

Melakukan sinkronisasi untuk semua appointment yang:
- Memiliki `mcu_package_id`
- Belum di-finalize (`final_signed_at IS NULL`)

#### 3. Sync Appointment Spesifik

```bash
php artisan lab:sync-snapshot --appointment-id=123
```

Atau multiple IDs:

```bash
php artisan lab:sync-snapshot --appointment-id=123 --appointment-id=456 --appointment-id=789
```

#### 4. Force Sync (Tanpa Konfirmasi)

```bash
php artisan lab:sync-snapshot --force
```

## Output Command

Command akan menampilkan:

```
🔍 Memulai sinkronisasi lab tests snapshot...

📋 Filter: Appointment yang belum di-finalize
📊 Ditemukan 15 appointment

🔄 [ID: 123] Reg: REG-202606-0123 - Perlu update
   ❌ Dihapus dari [imunoserologi]: anti_hav
   ✅ Berhasil disinkronkan

✓  [ID: 124] Reg: REG-202606-0124 - Sudah sinkron

...

📈 Ringkasan Sinkronisasi:
+------------------+--------+
| Status           | Jumlah |
+------------------+--------+
| ✅ Berhasil      | 5      |
| ✓  Sudah sinkron | 9      |
| ❌ Error         | 1      |
| 📊 Total         | 15     |
+------------------+--------+
```

## Kapan Perlu Manual Sync?

1. **Migration Data Historis**
   - Setelah upgrade sistem yang menambahkan fitur snapshot
   - Sinkronisasi appointment lama yang dibuat sebelum observer aktif

2. **Troubleshooting**
   - Ada issue dengan observer
   - Perlu force sync untuk appointment tertentu

3. **Bulk Update**
   - Admin melakukan banyak perubahan paket MCU sekaligus
   - Ingin memastikan semua appointment tersinkronisasi

## Flow Lengkap

```
┌─────────────────────────────────────────────────────────┐
│ Admin Unchecklist "Anti HAV" di Paket MCU               │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│ McuPackageObserver::updated() terdeteksi               │
│ - Cek apakah lab_tests_included berubah                │
│ - Ya, lanjut ke auto-sync                                │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│ Update lab_tests_snapshot di Appointments               │
│ - Yang menggunakan paket tersebut                        │
│ - Yang belum di-finalize                                 │
│ - Yang lab result belum di-verify                        │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│ Petugas Lab Buka Form Input Hasil                       │
│ - $appointment->getLabTestsIncluded()                    │
│ - Baca dari lab_tests_snapshot (sudah terupdate)        │
│ - Field "Anti HAV" TIDAK MUNCUL ✅                       │
└─────────────────────────────────────────────────────────┘
```

## Best Practices

1. **Untuk Development/Testing:**
   - Selalu gunakan `--dry-run` terlebih dahulu
   - Cek output sebelum eksekusi sebenarnya

2. **Untuk Production:**
   - Observer auto-sync sudah cukup untuk operasional normal
   - Manual sync hanya untuk kasus khusus (migration, troubleshooting)
   - Backup database sebelum bulk sync

3. **Monitoring:**
   - Cek log di `storage/logs/laravel.log`
   - Perhatikan jumlah appointment yang ter-update
   - Report jika ada error count yang tinggi

## Troubleshooting

### Field lab masih muncul setelah unchecklist

1. Cek apakah observer terdaftar:
   ```bash
   # Di AppServiceProvider.php harus ada:
   McuPackage::observe(McuPackageObserver::class);
   ```

2. Cek log untuk error:
   ```bash
   tail -f storage/logs/laravel.log | grep McuPackageObserver
   ```

3. Manual sync appointment yang bermasalah:
   ```bash
   php artisan lab:sync-snapshot --appointment-id=<ID>
   ```

### Observer tidak jalan

1. Clear cache:
   ```bash
   php artisan config:clear
   php artisan cache:clear
   ```

2. Restart server jika menggunakan queue/worker

3. Cek database apakah kolom `lab_tests_snapshot` ada:
   ```bash
   php artisan migrate:status
   ```

## Related Files

- Model: `app/Models/Appointment.php`
- Observer: `app/Observers/McuPackageObserver.php`
- Command: `app/Console/Commands/SyncLabTestsSnapshot.php`
- Provider: `app/Providers/AppServiceProvider.php`
- Migration: `database/migrations/2026_05_01_180600_add_lab_tests_snapshot_to_appointments_table.php`
- View: `resources/views/lab/process.blade.php`

## Changelog

- **2024-06-10**: Implementasi awal snapshot system, observer, dan manual sync command
