# DATABASE.md — Struktur Database

## Koneksi
- **Development & Production**: PostgreSQL 13 via XAMPP (berjalan di `127.0.0.1:5432`)
- **Inspeksi data**: phpPgAdmin (`http://localhost/phppgadmin`)
- **Config file**: `config/database.php`
- **Driver aktif**: `pgsql` (set di `.env` → `DB_CONNECTION=pgsql`)
- **Database**: `company_postgre`, **username** `root`, **password** kosong
- **Pemisahan schema**: `public` (framework Laravel + tabel ERP inti) / `core` (identitas & ERP bersama) / `selfcheck` (modul Selfcheck) — lihat bagian *Pemisahan Schema* di bawah
- **Foreign key constraints**: aktif
- **Charset**: UTF-8 (default PostgreSQL)

> Aturan lengkap pengelolaan database → `docs/DATABASE-RULES.md`

### Konfigurasi `.env` yang Diperlukan
```dotenv
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=company_postgre
DB_USERNAME=root
DB_PASSWORD=
DB_SEARCH_PATH="public,selfcheck,core"

SESSION_DRIVER=database
CACHE_STORE=database
FILESYSTEM_DISK=local
```

> **Nama database = `company_postgre`** (PostgreSQL 13, bukan MySQL). URL dev: `APP_URL=http://localhost`.
> Storage: disk default `local`; `storage/app/public` dihubungkan ke `public/storage` via **Junction** (Windows).

---

## Pemisahan Schema (PostgreSQL)
Semua tabel di database `company_postgre` dipisahkan per tanggung jawab lewat **schema** (bukan lewat prefix nama tabel). `search_path` diatur ke **`public,selfcheck,core`** (`DB_SEARCH_PATH`) sehingga query runtime memakai nama tabel polos; hanya **`Schema::create()`** yang mengkualifikasi schema lewat helper **`erp_schema_table($schema, $table)`** (`app/Support/helpers.php`).

| Schema | Isi |
|--------|-----|
| `public` | Tabel framework Laravel (`users`, `sessions`, `cache`, `jobs`, `migrations`, …) + tabel ERP inti (`departments`, `applications`, `roles`, `user_application_roles`, `media_settings`) |
| `core` | Identitas & data ERP bersama (disiapkan untuk modul lintas-aplikasi) |
| `selfcheck` | **Semua** tabel modul Selfcheck (`selfcheck_*`) |

Schema `core` & `selfcheck` dibuat oleh migrasi `0000_01_01_000000_create_erp_schemas.php` (`CREATE SCHEMA IF NOT EXISTS ...`; hanya berefek pada driver `pgsql`).

> Aplikasi/modul baru sebaiknya memakai **schema tersendiri** (mis. `tool`, `material`, `absensi`) agar tidak berantakan saat proyek membesar.

---

## Daftar Tabel Aktual (database `company_postgre`)

**Schema `public`** (framework Laravel + ERP inti):
```
applications, application_department, cache, cache_locks, departments,
failed_jobs, job_batches, jobs, media_settings, migrations,
password_reset_tokens, roles, sessions, user_application_roles, users
```

**Schema `selfcheck`** (modul Selfcheck):
```
selfcheck_projects, selfcheck_trainsets, selfcheck_project_cars,
selfcheck_trainset_cars, selfcheck_teams, selfcheck_batches,
selfcheck_execution_types, selfcheck_components, selfcheck_component_cars,
selfcheck_component_execution_types, selfcheck_executions,
selfcheck_execution_logs, selfcheck_presences, selfcheck_execution_type_states,
selfcheck_work_notes
```

---

## Tabel yang Sudah Ada (dari migrasi aktual)

> Semua tabel di bawah ini sudah dibuat via `php artisan migrate` dan tersedia di database.

### `users`
> Migrasi: `0001_01_01_000000_create_users_table.php`

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK, auto-increment | |
| `name` | string | Nama lengkap |
| `email` | string, unique | Email login |
| `email_verified_at` | timestamp, nullable | Waktu verifikasi email |
| `password` | string | Hash bcrypt |
| `remember_token` | string, nullable | Token "ingat saya" |
| `created_at` | timestamp | |
| `updated_at` | timestamp | |

---

### `password_reset_tokens`
> Migrasi: `0001_01_01_000000_create_users_table.php`

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `email` | string, PK | |
| `token` | string | Token reset |
| `created_at` | timestamp, nullable | |

---

### `sessions`
> Migrasi: `0001_01_01_000000_create_users_table.php`

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | string, PK | |
| `user_id` | bigint, nullable, index | FK ke `users.id` (soft reference) |
| `ip_address` | string(45), nullable | |
| `user_agent` | text, nullable | |
| `payload` | longtext | Data session |
| `last_activity` | integer, index | Unix timestamp |

---

### `cache`
> Migrasi: `0001_01_01_000001_create_cache_table.php`

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `key` | string, PK | |
| `value` | mediumtext | |
| `expiration` | integer, index | Unix timestamp |

---

### `cache_locks`
> Migrasi: `0001_01_01_000001_create_cache_table.php`

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `key` | string, PK | |
| `owner` | string | |
| `expiration` | integer, index | |

---

### `jobs`
> Migrasi: `0001_01_01_000002_create_jobs_table.php`

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `queue` | string, index | Nama antrian |
| `payload` | longtext | Data job |
| `attempts` | tinyint unsigned | |
| `reserved_at` | int unsigned, nullable | |
| `available_at` | int unsigned | |
| `created_at` | int unsigned | |

---

### `job_batches`
| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | string, PK | |
| `name` | string | |
| `total_jobs` | integer | |
| `pending_jobs` | integer | |
| `failed_jobs` | integer | |
| `failed_job_ids` | longtext | |
| `options` | mediumtext, nullable | |
| `cancelled_at` | integer, nullable | |
| `created_at` | integer | |
| `finished_at` | integer, nullable | |

---

### `failed_jobs`
| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `uuid` | string, unique | |
| `connection` | text | |
| `queue` | text | |
| `payload` | longtext | |
| `exception` | longtext | |
| `failed_at` | timestamp, default CURRENT | |

---

## Tabel ERP (Sudah Dibuat)

> Migrasi: `2026_10_28_152457` s/d `2026_10_28_152520`

### `departments`
| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `name` | string | Nama departemen |
| `slug` | string, unique | Identifier URL-friendly |
| `description` | text, nullable | |
| `is_active` | boolean, default true | |
| `created_at` | timestamp | |
| `updated_at` | timestamp | |

Data awal (seeder `DepartmentSeeder`): Elektrik, Mekanik, Interior, HR
**Data di DB `company_postgre` (fresh, dari `DepartmentSeeder`)**: 4 baris — `id=1 Elektrik`, `id=2 Mekanik`, `id=3 Interior`, `id=4 HR`.

---

### `applications`
| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `name` | string | Nama modul ERP |
| `slug` | string, unique | Identifier untuk middleware |
| `description` | text, nullable | |
| `icon` | string, nullable | Nama icon |
| `route` | string, nullable | Nama route utama modul |
| `logo` | string, nullable | Path logo aplikasi (disk `public` → `asset('storage/'.$logo)`); diunggah di `/admin/applications`. Migrasi `2026_11_06_000001_add_logo_and_departments_to_applications` |
| `is_active` | boolean, default true | |
| `sort_order` | integer, default 0 | Urutan tampil di menu |
| `created_at` | timestamp | |
| `updated_at` | timestamp | |

Data awal (seeder): user-management, tool, material, selfcheck, generate, absensi, finance

**Pivot `application_department`** (migrasi `2026_11_06_000001`): pemetaan aplikasi ↔ departemen (banyak-ke-banyak) sehingga tiap departemen hanya melihat aplikasi "room"-nya. Aplikasi **tanpa** pemetaan tetap tampil ke semua departemen.
| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `application_id` | bigint, FK → applications, cascade | |
| `department_id` | bigint, FK → departments, cascade | |
Unique `app_dept_unique (application_id, department_id)`

---

### `roles`
| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `name` | string | Nama role |
| `slug` | string, unique | |
| `description` | text, nullable | |
| `created_at` | timestamp | |
| `updated_at` | timestamp | |

Data awal (seeder `RoleSeeder`): super-admin, admin, petugas, qc, user
**Data di DB `company_postgre` (fresh, dari `RoleSeeder`)**: 6 baris — super-admin, admin, petugas, qc, user, **view**.

---

### `users` (diperbarui dari default Laravel)
> Migrasi dasar: `0001_01_01_000000_create_users_table.php` + migrasi ERP `2026_10_28_*`

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `username` | string(50), unique, nullable | Kolom warisan identifier login. **Form input Username dihapus** (6 Nov 2026) di `/admin/users` & `/register` — user baru tidak mengisi ini; login memakai `email`/`nip`. Kolom tetap ada untuk data lama |
| `name` | string | Nama lengkap |
| `phone` | string(20), nullable | Nomor telepon |
| `nip` | string(50), nullable | NIP karyawan |
| `group_name` | string(100), nullable | Golongan/group |
| `line` | string(100), nullable | Line/area kerja |
| `jabatan` | string(100), nullable | Jabatan |
| `alamat` | text, nullable | Alamat |
| `photo` | string, nullable | Path foto (relatif ke disk `public` → `asset('storage/'.$photo)`) |
| `email` | string, unique | Identifier ganda: **Email atau NIP** (validasi tanpa aturan `'email'`) |
| `department_id` | bigint, FK → departments, nullable | Departemen utama |
| `unit` | string(100), nullable | Unit kerja (teks bebas) — migrasi `2026_10_31_000000_add_unit_to_users_table` |
| `is_active` | boolean, default true | Status akun |
| `is_valid` | boolean, default false | Penanda karyawan tervalidasi (mis. pendaftar mandiri = false) — migrasi `2026_10_30_000000_add_access_flags_to_users_table` |
| `allow_multi_department` | boolean, default false | Izin login/pindah lintas departemen — migrasi `2026_10_30_000000_add_access_flags_to_users_table` |
| `last_login_at` | timestamp, nullable | Waktu login terakhir |
| `email_verified_at` | timestamp, nullable | |
| `password` | string | Hash bcrypt (cast `'hashed'` — jangan hash manual) |
| `remember_token` | string, nullable | |
| `deleted_at` | timestamp, nullable | Soft delete (`SoftDeletes`) |
| `created_at` | timestamp | |
| `updated_at` | timestamp | |

FK policy: `department_id` → `nullOnDelete` (user tetap ada saat departemen dihapus)

---

### `media_settings`
> Migrasi ERP (`2026_10_28_*`) — menyimpan pengaturan media & teks portal (key-value)

| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `key` | string(100), unique | Kunci pengaturan, mis. `bg_login`, `logo_login`, `logo_sidebar`, `logo_print`, `portal_text` |
| `value` | string(500), nullable | Path file (disk `public`) atau teks (untuk `portal_text`) |
| `type` | string(20), default `'file'` | `file` atau `text` |
| `created_at` | timestamp | |
| `updated_at` | timestamp | |

Kunci yang dipakai aplikasi: `bg_login`, `logo_login`, `logo_sidebar`, `logo_print` (file/gambar), `portal_text` (teks identitas/copyright kecil di footer), dan `copyright_note` (teks bebas "Catatan Bebas" — bukan judul/cetak, hanya catatan referensi).
URL file diakses via `MediaSetting::fileUrl($key)` → `asset('storage/'.$path)`.

---

### `user_application_roles`
| Kolom | Tipe | Keterangan |
|-------|------|------------|
| `id` | bigint, PK | |
| `user_id` | bigint, FK → users | |
| `application_id` | bigint, FK → applications | |
| `role_id` | bigint, FK → roles | Role saat berada di **departemen utama** |
| `switch_role_id` | bigint, FK → roles, nullable | Role saat user **pindah ke departemen lain** (multi departemen). NULL = ikut `role_id`. Ditambahkan `2026_11_02_000000_add_switch_role_to_user_application_roles_table` |
| `is_active` | boolean, default true | Akses bisa dimatikan tanpa hapus record |
| `created_at` | timestamp | |
| `updated_at` | timestamp | |

Constraint: `UNIQUE(user_id, application_id)` — satu user hanya boleh satu role per aplikasi
FK policy: `user_id` → `cascadeOnDelete`, `application_id` → `cascadeOnDelete`, `role_id` → `cascadeOnDelete`, `switch_role_id` → `nullOnDelete`

---

## Tabel Selfcheck (Sudah Dibuat)

> Modul Selfcheck — Portal 3. Migrasi: `2026_11_05_000001`–`000004` + `2026_11_06_000002` (department) & `2026_11_06_000003` (qc_kendala/qc_note) + `2026_11_08_000001` (kendala_note/kendala_photo + qc_kendala_note/qc_kendala_photo).
> Unit pekerjaan terkecil = **(trainset × komponen × car)**. Relasi komponen (mis. tirai) via self-reference `parent_id`; relasi dianggap ada bila **team + batch + kode komponen sama persis**.

### Master Data — `2026_11_05_000001_create_selfcheck_master_tables.php`
> Diperbarui via migrasi `2026_11_06_000002_add_department_to_selfcheck_master_tables.php`

| Tabel | Kolom Penting | Keterangan |
|-------|---------------|------------|
| `selfcheck_projects` | `department_id` (FK→departments, nullOnDelete), `name`, `description`, `is_active` | Proyek. Hanya Super Admin yang boleh membuat |
| `selfcheck_trainsets` | `department_id` (FK), `project_id` (FK, cascade), `name`, `description` | Unique `(project_id, name)` |
| `selfcheck_project_cars` | `department_id` (FK), `project_id` (FK, cascade), `sort_order` (uint), `firstname` | Slot car per **proyek**. Unique `(project_id, sort_order)` |
| `selfcheck_trainset_cars` | `department_id` (FK), `trainset_id` (FK, cascade), `project_car_id` (FK, cascade), `code` (nullable) | Penamaan car per trainset. Unique `(trainset_id, project_car_id)` |
| `selfcheck_teams` | `department_id` (FK), `project_id` (FK, cascade), `name`, `description` | Unique `(project_id, name)` |
| `selfcheck_batches` | `department_id` (FK), `project_id` (FK, cascade), `team_id` (FK, cascade), `name`, `description` | Unique `(team_id, name)` |
| `selfcheck_execution_types` | `department_id` (FK), `project_id` (FK, cascade), `name`, `description` | Type eksekusi. Unique `(project_id, name)` |

### Komponen & Relasi — `2026_11_05_000002_create_selfcheck_component_tables.php`
> Diperbarui via migrasi `2026_11_06_000002`

| Tabel | Kolom Penting | Keterangan |
|-------|---------------|------------|
| `selfcheck_components` | `department_id` (FK), `project_id`, `team_id`, `batch_id` (FK, cascade), `parent_id` (FK→selfcheck_components, nullable, cascade), `sort_order`, `code`, `name`, `description`, `note`, `link`(500), `photo`, `is_active` | `parent_id` NULL = komponen utama; lainnya = komponen relasi (anak). |
| `selfcheck_component_cars` | `component_id` (FK, cascade), `project_car_id` (FK, cascade) | Checklist "komponen tersedia di car mana". Unique `scc_component_car_unique` |
| `selfcheck_component_execution_types` | `component_id` (FK, cascade), `execution_type_id` (FK, cascade), `is_active` | Toggle type eksekusi per komponen. Unique `scc_component_type_unique` |

### Eksekusi — `2026_11_05_000003_create_selfcheck_execution_tables.php`

| Tabel | Kolom Penting | Keterangan |
|-------|---------------|------------|
| `selfcheck_executions` | `project_id`, `trainset_id`, `component_id`, `project_car_id` (FK, cascade), `status` enum(`belum`,`proses`,`ok`,`kendala`), `note` (catatan bebas eksekutor), `kendala_note`/`kendala_photo` (kendala eksekutor), `link`(500), `photo`, `executed_by`/`executed_at`, `is_validated`/`validated_by`/`validated_at`, `qc_kendala` (boolean, default false), `qc_note` (catatan bebas QC), `qc_kendala_note`/`qc_kendala_photo` (kendala QC), `locked_by`/`locked_at` | Satu baris = satu unit pekerjaan. **Catatan bebas & kendala DIPISAH**: `note` = catatan bebas eksekutor, `kendala_note`/`kendala_photo` = keterangan + foto bukti kendala eksekutor; `qc_note` = catatan bebas QC, `qc_kendala` + `qc_kendala_note`/`qc_kendala_photo` = kendala QC (migrasi `2026_11_06_000003` + `2026_11_08_000001`). Mematikan indikator kendala **tidak** menghapus catatan bebas. Unique `sc_exec_unique (trainset_id, component_id, project_car_id)`. Index `(project_id, status)` |
| `selfcheck_execution_logs` | `execution_id` (FK, cascade), `user_id` (FK, nullOnDelete), `action`(50), `from_status`(20), `to_status`(20), `message`(500) | Log history perubahan. Index `(execution_id, created_at)` |
| `selfcheck_presences` | `user_id` (FK, unique, cascade), `department_id` (FK, nullOnDelete), `page`(30, default `eksekusi`), `last_seen_at` | Presence personil online via heartbeat/polling (jendela 60 detik) |

### Checklist Type Eksekusi — `2026_11_05_000004_create_selfcheck_execution_type_states_table.php`

| Tabel | Kolom Penting | Keterangan |
|-------|---------------|------------|
| `selfcheck_execution_type_states` | `execution_id` (FK, cascade), `execution_type_id` (FK, cascade), `is_done` (default false), `done_by` (FK, nullOnDelete), `done_at` | Status penyelesaian tiap Type Eksekusi pada satu unit pekerjaan. **Status eksekusi diturunkan dari sini**: 0 selesai → `belum`, sebagian → `proses`, semua selesai → `ok` (kendala manual). Unique `sc_exec_type_unique (execution_id, execution_type_id)` |

FK policy umum: mayoritas `cascadeOnDelete` (data anak tidak bermakna tanpa induk); kolom pelaku (`executed_by`, `validated_by`, `locked_by`, `done_by`, `user_id`) memakai `nullOnDelete` agar riwayat tetap ada saat user dihapus.

---

## Tabel yang BELUM Ada (TODO — Perlu Dibuat)

Semua tabel berikut **belum ada migrasinya**. Harus dibuat sebelum implementasi modul terkait.
Lihat prosedur pembuatan di `docs/DATABASE-RULES.md` sebelum membuat migration baru.

> Modul **Selfcheck** sudah tidak ada di daftar ini — skemanya sudah dibuat (lihat bagian **Tabel Selfcheck** di atas).

### Rencana Tabel per Modul

```
-- Modul Absensi
attendances         → id, user_id (FK, RESTRICT), date, check_in, check_out,
                       status (hadir/izin/sakit/alpha), notes, timestamps

-- Modul Tool
tools               → id, name, code (unique), department_id (FK, SET NULL),
                       status (tersedia/dipakai/rusak), description, location,
                       is_active, deleted_at (soft delete), timestamps

tool_usages         → id, tool_id (FK, RESTRICT), user_id (FK, SET NULL),
                       borrowed_at, returned_at, notes, timestamps

-- Modul Material
materials           → id, name, code (unique), unit, stock, min_stock,
                       department_id (FK, SET NULL), is_active,
                       deleted_at (soft delete), timestamps

material_transactions → id, material_id (FK, RESTRICT), user_id (FK, SET NULL),
                         type (masuk/keluar), qty, notes, transacted_at, timestamps

-- Modul Finance (TODO — desain lebih detail sebelum buat migration)
```

> **Penting**: Desain tabel di atas adalah rencana awal. Finalisasi bersama tim sebelum migration dibuat.
> Perhatikan kebijakan FK yang tercantum — gunakan RESTRICT untuk tabel transaksi agar data historis tidak hilang.

---

## Model Aktual
- `App\Models\User` — fields lengkap + relasi ke `Department` dan `UserApplicationRole`; `SoftDeletes`; cast `'password' => 'hashed'`
- `App\Models\Department` — dengan relasi `users()`
- `App\Models\Application` — dengan relasi `userRoles()`, `departments()` (belongsToMany via pivot `application_department`), helper `logoUrl()`
- `App\Models\Role` — dengan relasi `userRoles()`
- `App\Models\UserApplicationRole` — pivot dengan relasi ke User, Application, Role
- `App\Models\MediaSetting` — key-value media/teks portal; helper `fileUrl($key)` → `asset('storage/'.$path)`

**Model Selfcheck** (`App\Models\Selfcheck*`):
- `SelfcheckProject`, `SelfcheckTrainset`, `SelfcheckProjectCar`, `SelfcheckTrainsetCar`, `SelfcheckTeam`, `SelfcheckBatch`, `SelfcheckExecutionType` — master data
- `SelfcheckComponent` — komponen + relasi (`parent_id` self-reference: `parent()`, `children()`), relasi `cars()` (pivot `selfcheck_component_cars`), `executionTypes()`, helper `photoUrl()`
- `SelfcheckExecution` — unit pekerjaan; `const LOCK_MINUTES = 15`, `const STATUSES = ['belum','proses','ok','kendala']`; relasi project/trainset/component/car/executedBy/validatedBy/lockedBy/logs/typeStates; `photoUrl()`, `kendalaPhotoUrl()`, `qcKendalaPhotoUrl()`, `isLockedFresh()`, `isLockedByOther()`, `statusLabel()`
- `SelfcheckExecutionLog` — log history (relasi execution, user)
- `SelfcheckExecutionTypeState` — state penyelesaian per Type Eksekusi (relasi execution, executionType, doneBy); penentu status `belum/proses/ok`
- `SelfcheckPresence` — `const ONLINE_WINDOW = 60`; helper statis `markSeen($user, $page)` & `onlineList()` (dipakai Eksekusi & Visualisasi)

## Seeder
- `DepartmentSeeder` — 4 departemen awal, idempotent (`firstOrCreate`)
- `ApplicationSeeder` — 7 modul ERP, idempotent
- `RoleSeeder` — 6 role (super-admin, admin, petugas, qc, user, view), idempotent
- `DatabaseSeeder` — memanggil semua seeder + buat Super Admin default (login **`super`** / **`super`**; username `super`, email `superadmin@company.local`)

> Modul Selfcheck **tidak memiliki seeder** (data dibuat lewat UI Master Data).
