# 🏛️ ENTERPRISE SYSTEM ARCHITECTURE DOCUMENTATION
### **Sistem Absensi Fingerprint Terintegrasi (SMK Negeri 1 Gunung Agung)**

---

## 1. High Level Architecture

High Level Architecture menggambarkan alur komunikasi utama antara pengguna (Admin, Kepala Sekolah, Guru, Siswa), aplikasi web berbasis Laravel & Livewire, database relasional MySQL, serta 6 unit mesin biometrik fingerprint (Fingerspot Revo W-230N) melalui jaringan lokal (LAN) via TCP Socket Port 4370.

```mermaid
flowchart TD
    subgraph Clients["Perangkat Klien"]
        Admin[Admin TU Desktop/Laptop]
        Kepsek[Kepala Sekolah Tablet/PC]
        Guru[Guru & Siswa Mobile/PC]
    end

    subgraph ServerApp["Server Aplikasi Web On-Premise / Cloud Shared Hosting"]
        WebNginx[Nginx / Apache Web Server]
        LaravelApp["Laravel 11 App Engine\n(Livewire 3 + Service Layer)"]
        CronDaemon["cPanel / Linux Cron Daemon\n(php artisan schedule:run)"]
        DB[(MySQL / MariaDB Database)]
        Storage[Storage Uploads & ZIP Backups]
    end

    subgraph BiometricLAN["Jaringan LAN Biometrik Sekolah"]
        Router[Router Sekolah / Mikrotik LAN]
        FP1["Mesin FP 1: Lobby (192.168.1.201:4370)"]
        FP2["Mesin FP 2: Lab Komputer (192.168.1.202:4370)"]
        FP3["Mesin FP 3: Ruang Guru (192.168.1.203:4370)"]
        FP4["Mesin FP 4: Perpustakaan (192.168.1.204:4370)"]
        FP5["Mesin FP 5: Bengkel (192.168.1.205:4370)"]
        FP6["Mesin FP 6: Kantin (192.168.1.206:4370)"]
    end

    Admin -->|HTTPS Request| WebNginx
    Kepsek -->|HTTPS Request| WebNginx
    Guru -->|HTTPS Request| WebNginx

    WebNginx <-->|PHP-FPM| LaravelApp
    LaravelApp <-->|SQL Query / PDO| DB
    LaravelApp <-->|File Stream| Storage
    CronDaemon -.->|Trigger tiap 1 menit| LaravelApp

    LaravelApp <==>|TCP Socket Port 4370 / ZK Protocol| Router
    Router <==> FP1
    Router <==> FP2
    Router <==> FP3
    Router <==> FP4
    Router <==> FP5
    Router <==> FP6
```

---

## 2. Logical Architecture

Logical Architecture memisahkan tanggung jawab sistem secara terstruktur antara modul antarmuka pengguna (Livewire), logika bisnis (Service Layer), transaksi data (Repository Layer), dan pemrosesan latar belakang.

```mermaid
graph TD
    subgraph UI_Layer["UI & Presentation Layer"]
        L_Auth[Livewire Auth & Force Change Password]
        L_Dash[Livewire Dashboard & Analytics]
        L_Personnel[Livewire Personnel Management]
        L_Machines[Livewire Machine Management]
        L_Sync[Livewire Biometric Sync GUI]
        L_Reports[Livewire Reports & PDF Print]
        L_Leave[Livewire Leave Approval Workflow]
        L_Backup[Livewire Web Backup & Restore]
        L_Search[Livewire Header Global Search]
    end

    subgraph Business_Layer["Domain Service Layer"]
        S_ZKTeco[ZKTeco Binary Protocol Service]
        S_Processor[Attendance Processor Engine]
        S_Sync[Biometric Sync Service]
        S_Leave[Leave Application Service]
        S_Backup[Native PHP Backup Service]
        S_Audit[Audit Log & Entity History Service]
        S_Report[Report & Export Service]
    end

    subgraph Action_Layer["Action Layer (Single Responsibility)"]
        A_ApproveLeave[ApproveLeaveAction]
        A_RejectLeave[RejectLeaveAction]
        A_CreateBackup[CreateDatabaseBackupAction]
        A_RestoreBackup[RestoreDatabaseBackupAction]
    end

    subgraph Data_Layer["Repository & Data Access Layer"]
        R_User[UserRepository]
        R_Attendance[AttendanceRecordRepository]
        R_Machine[FingerprintMachineRepository]
        R_Leave[LeaveRepository]
        R_Academic[AcademicCalendarRepository]
    end

    UI_Layer --> Business_Layer
    Business_Layer --> Action_Layer
    Business_Layer --> Data_Layer
    Action_Layer --> Data_Layer
```

---

## 3. Physical Architecture

Physical Architecture memperlihatkan topologi infrastruktur keras (*hardware deployment*), batas jaringan (*firewall & router*), dan port komunikasi yang digunakan.

```mermaid
graph LR
    subgraph ClientZone["Client Zone (Browser)"]
        UserDevice["Web Browser / Smartphone\n(HTTPS Port 443)"]
    end

    subgraph DMZ["DMZ / Cloud Hosting Zone"]
        WebServer["Apache / Nginx Web Server\n(PHP 8.2+ Runtime)"]
        MySQLServer["MySQL / MariaDB Server\n(Port 3306)"]
    end

    subgraph LocalSchoolZone["Local School Infrastructure Zone (LAN 192.168.1.0/24)"]
        SchoolRouter["Router / Gateway SMKN 1 Gunung Agung\n(Port Forwarding 4370 / VPN Tunnel)"]
        FPMachines["6x Fingerspot Revo W-230N\n(IP: 192.168.1.201-206:4370)"]
    end

    UserDevice <==>|HTTPS SSL Port 443| WebServer
    WebServer <==>|Internal Socket / Port 3306| MySQLServer
    WebServer <==>|TCP Socket Port 4370 (ZK Protocol)| SchoolRouter
    SchoolRouter <==>|LAN Cable Cat6| FPMachines
```

---

## 4. Layer Architecture

Aplikasi dibangun berbasis **Clean Layered Architecture 4-Tier**:

```mermaid
graph TB
    subgraph Tier1["1. Presentation Tier (UI & Controllers)"]
        LivewireComponents["Livewire 3 Components"]
        BladeViews["Blade View Templates & Tailwind CSS"]
        Routes["Laravel Routes & Middleware"]
    end

    subgraph Tier2["2. Application & Action Tier"]
        ActionClasses["Single Responsibility Actions"]
        EventsListeners["Events & Listeners"]
        JobsCron["Scheduled Commands & Jobs"]
    end

    subgraph Tier3["3. Domain & Service Tier"]
        DomainServices["Domain Services (Business Logic)"]
        HardwareDrivers["ZKTeco Biometric Socket Driver"]
        DTOs["Data Transfer Objects (DTOs)"]
    end

    subgraph Tier4["4. Infrastructure & Data Tier"]
        Repositories["Repository Pattern Interfaces & Impl"]
        EloquentModels["Eloquent Models & Soft Deletes"]
        MySQLDB[(MySQL / MariaDB Database)]
    end

    Tier1 --> Tier2
    Tier2 --> Tier3
    Tier3 --> Tier4
```

---

## 5. Module Architecture

Sistem terbagi ke dalam **12 Modul Core Enterprise**:

```mermaid
graph LR
    M1[1. Auth & Password Enforcement]
    M2[2. Shift Management]
    M3[3. Personnel Management]
    M4[4. Fingerprint Machine Management]
    M5[5. Biometric Sync Engine]
    M6[6. Reports & PDF/Excel Export]
    M7[7. Role & Permission Matrix]
    M8[8. Academic Calendar & Holidays]
    M9[9. Leave Approval Workflow]
    M10[10. Notification Center]
    M11[11. System Health Monitoring]
    M12[12. Web Backup & Restore]

    M1 --> M3
    M2 --> M3
    M4 --> M5
    M3 --> M5
    M8 --> M5
    M9 --> M5
    M5 --> M6
    M7 --> M1
    M10 --> M9
    M11 --> M4
    M12 --> M6
```

---

## 6. Database Architecture (ERD Diagram)

Skema database relasional relasi penuh (*Fully Normalized relational schema*):

```mermaid
erDiagram
    ROLES ||--o{ USERS : "memiliki"
    SHIFTS ||--o{ USERS : "diterapkan pada"
    PERMISSIONS ||--o{ ROLE_HAS_PERMISSIONS : "diatur dalam"
    ROLES ||--o{ ROLE_HAS_PERMISSIONS : "memiliki permission"
    
    USERS ||--o{ ATTENDANCE_LOGS : "mencatat log mentah"
    FINGERPRINT_MACHINES ||--o{ ATTENDANCE_LOGS : "menghasilkan log"
    FINGERPRINT_MACHINES ||--o{ SYNC_LOGS : "mencatat sync"
    
    USERS ||--o{ ATTENDANCE_RECORDS : "memiliki rekord presensi"
    USERS ||--o{ LEAVE_APPLICATIONS : "mengajukan izin"
    LEAVE_APPLICATIONS ||--o{ LEAVE_APPROVAL_HISTORIES : "mencatat riwayat approval"
    
    USERS ||--o{ AUDIT_LOGS : "melakukan aktivitas"
    USERS ||--o{ ENTITY_HISTORIES : "diubah oleh"
    USERS ||--o{ BACKUPS : "dibuat oleh"
    USERS ||--o{ NOTIFICATIONS : "menerima notifikasi"

    ACADEMIC_YEARS ||--o{ SCHOOL_HOLIDAYS : "memiliki libur"
    ACADEMIC_YEARS ||--o{ ACADEMIC_EVENTS : "memiliki agenda"

    USERS {
        bigint id PK
        bigint role_id FK
        bigint shift_id FK
        string name
        string nip_nis
        string email
        string password
        boolean force_password_change
        timestamp deleted_at
    }

    ROLES {
        bigint id PK
        string name
        string label
    }

    SHIFTS {
        bigint id PK
        string name
        time start_time
        time end_time
    }

    PERMISSIONS {
        bigint id PK
        string name
        string module
    }

    FINGERPRINT_MACHINES {
        bigint id PK
        string name
        string ip_address
        string port
        string status
        timestamp last_sync
    }

    ATTENDANCE_LOGS {
        bigint id PK
        bigint machine_id FK
        string raw_user_id
        datetime timestamp
        boolean is_processed
    }

    ATTENDANCE_RECORDS {
        bigint id PK
        bigint user_id FK
        date date
        time check_in
        time check_out
        string status
    }

    LEAVE_APPLICATIONS {
        bigint id PK
        bigint user_id FK
        string type
        date start_date
        date end_date
        string proof_file
        string status
    }

    BACKUPS {
        bigint id PK
        string file_name
        string file_path
        bigint file_size
        string type
        string status
    }
```

---

## 7. Security Architecture

Prinsip Keamanan Sistem Berlapis (*Defense in Depth*):

```mermaid
graph TD
    subgraph Layer1["1. Network & Protocol Layer"]
        HTTPS[HTTPS SSL / TLS Enforced]
        SocketSec[Socket Latency Timeout 2s]
    end

    subgraph Layer2["2. HTTP & Session Protection"]
        CSRF[CSRF Token Validation]
        SessionSec[Session Timeout 2 Hours & Regenerate ID]
        RateLimit[Rate Limiter: 5 Requests / Min Login]
    end

    subgraph Layer3["3. Auth & Authorization"]
        PwdChangeMiddleware[EnsurePasswordIsChanged Middleware]
        PolicyGuard[Policy Authorization Gates]
        ArgonHash[Argon2id / Bcrypt Hashing]
    end

    subgraph Layer4["4. Audit & Integrity"]
        AuditTrail[AuditLog Activity Recorder]
        EntityHistory[EntityHistory Before vs After Observer]
        SqlXssProtect[PDO Prepared Statements & HTML Purifier]
    end

    HTTPS --> CSRF
    CSRF --> PwdChangeMiddleware
    PwdChangeMiddleware --> PolicyGuard
    PolicyGuard --> AuditTrail
```

---

## 8. Integration Architecture

Integrasi perangkat keras biometrik ZK Protocol & Notifikasi Multi-Channel:

```mermaid
sequenceDiagram
    autonumber
    participant Engine as AttendanceProcessorEngine
    participant Socket as ZKTecoService (TCP 4370)
    participant Machine as Mesin Fingerprint (Fingerspot)
    participant DB as MySQL Database
    participant Channel as NotificationService

    Engine->>Socket: Init TCP Connection (IP: 192.168.1.201, Port: 4370)
    Socket->>Machine: Connect Socket & Send ZK Connect Command
    Machine-->>Socket: ACK Session ID Response
    Socket->>Machine: Send Read Log Command (CMD_ATTLOG_RRQ)
    Machine-->>Socket: Stream Biometric Raw Packets
    Socket->>Socket: Parse Binary Bit Stream to Data Structure
    Socket->>DB: Bulk Insert to attendance_logs
    Engine->>DB: Process Raw Logs -> Generate attendance_records
    Engine->>Channel: Trigger LeaveStatusUpdatedEvent / Notification
    Channel->>DB: Save Database Notification
```

---

## 9. Deployment Architecture

Topologi Deployment berbasis **Shared Web Hosting / cPanel On-Premise**:

```mermaid
graph TD
    subgraph cPanel["cPanel / Web Server Environment"]
        PublicHTML["public_html (Laravel Public Directory)"]
        AppCore["app_core (Private Laravel Code Base)"]
        PHPRuntime["PHP 8.2 Executable"]
        Cron["cPanel Cron Job Daemon"]
        StorageSymlink["public/storage -> storage/app/public"]
    end

    Cron -->|Setiap 1 menit| PHPRuntime
    PHPRuntime -->|Executes| AppCore
    AppCore --> PublicHTML
    AppCore --> StorageSymlink
```

---

## 10. Backup Strategy

1. **Web-GUI Native Backup (Shared Hosting Friendly)**:
   - Dibuat murni menggunakan dumper native PHP PDO stream & `ZipArchive` tanpa butuh CLI `mysqldump` yang sering di-disable di shared hosting.
2. **Kategori Backup**:
   - **Database Only (ZIP)**: Berisi file `database_dump.sql` (struktur + data).
   - **Uploads Only (ZIP)**: Berisi seluruh file lampiran fisik & foto di `storage/app/public`.
   - **Full Backup (ZIP)**: Penggabungan paket Database SQL & Uploads Storage.
3. **Frekuensi Backup**:
   - Backup mingguan terjadwal otomatis via Cron `php artisan schedule:run`.

---

## 11. Recovery Strategy (Disaster Recovery Plan)

```mermaid
flowchart LR
    A[Terjadi System Failure / Data Corruption] --> B[Masuk ke Web UI Backup & Restore /backup-restore]
    B --> C{Ada File Backup di Server?}
    C -- Ya --> D[Pilih File Backup & Klik Restore]
    C -- Tidak --> E[Klik Upload & Restore File ZIP dari Komputer Lokal]
    D --> F[Execute RestoreDatabaseBackupAction]
    E --> F
    F --> G[Extract ZIP & Execute SQL Dump via PDO Transaction]
    G --> H[System Normal & Database Restored 100%]
```

---

## 12. Scalability Strategy

1. **Query Chunking & Streaming**: Penggunaan `Query::chunk(500)` dan `fputcsv('php://output')` pada ekspor data absensi puluhan ribu baris agar RAM server tidak melampaui limit.
2. **Indexing Strategis**: Pengindeksan kolom kueri frekuensi tinggi (`user_id`, `date`, `timestamp`, `is_processed`, `status`, `deleted_at`).
3. **Decoupling Raw Logs vs Processed Records**: Memisahkan `attendance_logs` (jutaan log mentah biometrik) dari `attendance_records` (rekord olahan harian) sehingga kueri laporan bulanan tetap responsif.

---

## 13. Coding Flow (Standard Workflow)

```mermaid
flowchart TD
    Request([User Request via Livewire Component]) --> AuthCheck{Otorisasi Policy?}
    AuthCheck -- Tidak (403) --> Deny[Tampilkan Notification Error]
    AuthCheck -- Ya --> CallService[Panggil Domain Service Layer]
    CallService --> ValidateDTO[Validasi Data via DTO]
    ValidateDTO --> CallAction[Jalankan Action / Repository Query]
    CallAction --> DBTransaction[Eksekusi Database Transaction]
    DBTransaction --> AuditObserver[EntityHistoryObserver Record Changes]
    AuditObserver --> TriggerEvent[Dispatch Event & Notifikasi]
    TriggerEvent --> RenderUI[Render Livewire View Update & Toast]
```

---

## 14. Folder Architecture

```text
/opt/lampp/htdocs/sistem_absensi_fingerprint
├── app/
│   ├── Actions/
│   │   └── Backup/ (CreateDatabaseBackupAction, RestoreDatabaseBackupAction)
│   │   └── Leave/ (ApproveLeaveAction, RejectLeaveAction)
│   ├── Console/ (Commands: fingerprint:sync)
│   ├── Contracts/ (Interfaces for Repositories & Services)
│   ├── DTO/ (AcademicCalendarDTO, LeaveApplicationDTO, UserDTO, etc.)
│   ├── Enums/ (AttendanceStatusEnum, LeaveStatusEnum, LeaveTypeEnum)
│   ├── Events/ (LeaveStatusUpdatedEvent)
│   ├── Exceptions/ (BackupFailedException)
│   ├── Helpers/ (SystemHealthHelper)
│   ├── Http/ (Middleware: EnsurePasswordIsChanged)
│   ├── Listeners/ (SendLeaveStatusNotificationListener)
│   ├── Livewire/ (Domain-grouped Livewire 3 Components)
│   ├── Models/ (17 Eloquent Models)
│   ├── Observers/ (EntityHistoryObserver)
│   ├── Policies/ (9 Policy Classes)
│   ├── Repositories/ (Eloquent Repositories Impl)
│   ├── Services/ (18 Domain Service Classes)
│   └── Support/ (Notification Channels: Database, Email, WA)
├── database/
│   ├── factories/ (UserFactory, ShiftFactory, MachineFactory)
│   ├── migrations/ (18 Database Migration Files)
│   └── seeders/ (RoleSeeder, ShiftSeeder, UserSeeder, DatabaseSeeder)
├── resources/
│   └── views/
│       ├── components/layouts/app.blade.php
│       ├── livewire/ (Blade Templates for Components)
│       └── reports/print-pdf.blade.php
├── routes/
│   ├── console.php
│   └── web.php
├── storage/app/
│   ├── backups/ (Zip Backup Storage)
│   └── public/ (Uploads: Photos & Proof Docs)
└── tests/ (Unit & Feature Test Suites - 52 Tests PASS 100%)
```

---

## 15. Dependency Graph

```mermaid
graph TD
    UserUI[Livewire Presentation Layer]
    ServiceLayer[Domain Service Layer]
    ActionLayer[Action Layer]
    RepoLayer[Repository Access Layer]
    EloquentModels[Eloquent Models Layer]
    Database[(MySQL Database)]

    UserUI --> ServiceLayer
    UserUI --> ActionLayer
    ServiceLayer --> ActionLayer
    ServiceLayer --> RepoLayer
    ActionLayer --> RepoLayer
    RepoLayer --> EloquentModels
    EloquentModels --> Database
```

---

## 16. Sequence Diagram (Workflow Approval Izin & Auto Update Absensi)

```mermaid
sequenceDiagram
    autonumber
    actor Admin as Admin TU / KepSek
    participant UI as LeaveApplicationIndex (Livewire)
    participant Action as ApproveLeaveAction
    participant Service as LeaveService
    participant Repo as LeaveRepository & AttendanceRecordRepository
    participant Event as LeaveStatusUpdatedEvent
    participant DB as MySQL Database

    Admin->>UI: Klik Tombol Setujui Izin (ID: 5)
    UI->>Action: execute(LeaveApplication, AdminUser)
    Action->>DB: Begin DB Transaction
    Action->>Repo: Update status = 'approved' on leave_applications
    Action->>Repo: Create/Update attendance_records (status = 'Izin' / 'Sakit')
    Action->>DB: Commit Transaction
    Action->>Event: dispatch(LeaveStatusUpdatedEvent)
    Event-->>UI: Trigger Toast Success & Render Livewire
```

---

## 17. Activity Diagram (Proses Penarikan Absensi Sync Engine)

```mermaid
stateDiagram-v2
    [*] --> InisiasiSync: Manual Trigger / Cron Schedule
    InisiasiSync --> CekMesinOnline: Loop 6 Mesin Fingerprint
    CekMesinOnline --> TestSocket: fsockopen(ip, 4370, timeout=2s)
    
    state TestSocket {
        [*] --> SocketCheck
        SocketCheck --> Online: Terhubung
        SocketCheck --> Offline: Timeout / Unreachable
    }

    Offline --> LogGagal: Catat SyncLog Status Failed
    Online --> ConnectZK: Init ZKTeco Binary Protocol Connection
    ConnectZK --> DownloadLog: Read Raw Logs (CMD_ATTLOG_RRQ)
    DownloadLog --> SaveRaw: Bulk Insert to attendance_logs
    SaveRaw --> ProcessRecord: AttendanceProcessorEngine Execute
    ProcessRecord --> MatchShift: Match User Shift & Academic Calendar Holiday
    MatchShift --> SaveRecord: Insert/Update attendance_records (Hadir/Terlambat/Alpha)
    SaveRecord --> LogSukses: Catat SyncLog Status Success
    LogSukses --> [*]
    LogGagal --> [*]
```

---

## 18. Component Diagram

```mermaid
componentDefinition
component [Livewire UI Component] as UI
component [Service Layer Engine] as Service
component [Action Executable] as Action
component [Repository Data Access] as Repo
component [ZKTeco Biometric Driver] as ZKDriver
component [Notification Multi-Channel] as NotifChannel
database "MySQL Storage" as DB

UI ..> Service : uses
UI ..> Action : invokes
Service ..> Repo : queries
Action ..> Repo : updates
Service ..> ZKDriver : communicates
Service ..> NotifChannel : dispatches
Repo ..> DB : SQL
```

---

## 19. Package Diagram

```mermaid
graph TD
    subgraph AppPackage["App Package Namespace"]
        HttpPkg[App\Http\Middleware]
        LivewirePkg[App\Livewire\*]
        ServicesPkg[App\Services\*]
        ActionsPkg[App\Actions\*]
        ReposPkg[App\Repositories\*]
        ModelsPkg[App\Models\*]
        ContractsPkg[App\Contracts\*]
    end

    LivewirePkg --> ServicesPkg
    LivewirePkg --> ActionsPkg
    ServicesPkg --> ContractsPkg
    ReposPkg ..|> ContractsPkg
    ServicesPkg --> ReposPkg
    ReposPkg --> ModelsPkg
```

---

## 20. Class Diagram (Core Domain Model & Service Relational Class)

```mermaid
classDiagram
    class User {
        +bigint id
        +string name
        +string nip_nis
        +string email
        +boolean force_password_change
        +role() BelongsTo
        +shift() BelongsTo
        +attendanceRecords() HasMany
    }

    class AttendanceRecord {
        +bigint id
        +bigint user_id
        +date date
        +time check_in
        +time check_out
        +string status
        +user() BelongsTo
    }

    class FingerprintMachine {
        +bigint id
        +string name
        +string ip_address
        +string port
        +string status
        +last_sync timestamp
    }

    class LeaveApplication {
        +bigint id
        +bigint user_id
        +string type
        +date start_date
        +date end_date
        +string status
    }

    class AttendanceProcessorService {
        +processLogsForDate(date) void
        +calculateStatus(checkIn, shiftStart) string
    }

    class BackupService {
        +createBackup(type) Backup
        +restoreBackup(backup) bool
    }

    User "1" -- "0..*" AttendanceRecord : owns
    User "1" -- "0..*" LeaveApplication : applies
    AttendanceProcessorService ..> AttendanceRecord : manages
    BackupService ..> User : logs Audit
```
