# Development Order — Web App Presensi & Payroll

Dokumen ini menerjemahkan [PRD.md](./PRD.md) menjadi urutan pengembangan yang dapat dieksekusi. Urutan dibuat berdasarkan dependency antar-modul, sehingga setiap tahap menghasilkan fondasi yang dapat dipakai tahap berikutnya.

## 1. Target Development

Target MVP adalah alur end-to-end berikut:

```text
User login
  → Company / Branch / Organization
  → Employee
  → Shift & Work Schedule
  → Face Registration
  → Geo Attendance
  → Attendance Correction
  → Leave / Permission / Overtime
  → Salary Component & Salary Structure
  → Payroll
  → Payslip & Report
```

Stack acuan mengikuti PRD: Reactjs, Laravel 13, MySQL/PostgreSQL, Redis, queue, dan REST API. Detail implementasi dapat disesuaikan setelah repository dan keputusan teknis awal tersedia.

## 2. Aturan Urutan

1. Modul tidak boleh dimulai sebelum dependency data dan permission-nya tersedia.
2. Setiap modul harus memiliki migration/schema, API, authorization, UI, validasi, audit trail bila relevan, dan test dasar.
3. Attendance dan Payroll diperlakukan sebagai dua domain terpisah.
4. Data sensitif seperti face template tidak boleh dikirim atau ditampilkan ke frontend.
5. Status payroll `CLOSED` harus immutable melalui alur normal; perubahan wajib melalui reopen yang terotorisasi.
6. Approval dibuat generic agar dapat dipakai Leave, Overtime, Attendance Correction, dan Reimbursement.
7. Setiap module baru wajib mengikuti module existing sebagai referensi implementasi sebelum membuat pola baru.

### Aturan Struktur Frontend Module

Semua module baru wajib menggunakan struktur feature-based yang konsisten dengan module existing seperti Branch dan Users & Access:

- `resources/js/pages/<module>.tsx` hanya menjadi page entry tipis atau re-export.
- Implementasi page, form, table, dan aturan khusus module berada di `resources/js/features/<module>/pages`.
- Primitive lintas module menggunakan shared component yang sudah tersedia, terutama `DataTable`, `Button`, `Toast`, dan `ConfirmDialog`.
- Tabel harus mengikuti pola `DataTable` existing, termasuk search, rows per page, pagination, empty state, kolom Actions rata kanan, dan responsive state.
- Tab harus mengikuti pola `module-tabs` pada Users & Access: background transparan, underline pada tab aktif, dan spacing yang konsisten.
- Form create/edit menggunakan modal dan mengikuti layout serta field spacing pada Branch.
- Module baru wajib memiliki loading, empty, error, retry, accessibility, mobile state, permission-aware actions, dan test dasar.
- Jangan menambahkan page generik baru di luar feature folder atau membuat pola visual custom jika module existing sudah memenuhi kebutuhan.

## 3. Checklist Wajib Setiap Pengerjaan

Checklist ini wajib disalin ke task/PR setiap kali mengerjakan fitur, bug fix, migration, atau perubahan konfigurasi. Item yang tidak relevan diberi keterangan `N/A` beserta alasannya.

### Progress Implementasi Saat Ini

- [x] Authentication session: login, logout, proteksi route, validasi user `ACTIVE`, dan pencatatan `last_login_at`.
- [x] Seeder data login dan foundation: company, branch, role, permission, relasi akses, serta user test.
- [x] Permission seeder untuk seluruh menu dengan action `read`, `create`, `update`, `delete`, dan `others` tanpa permission legacy redundan.
- [x] Middleware authorization granular berdasarkan HTTP method dan permission action.
- [x] Enforcement data scope terpusat untuk role `GLOBAL`, `COMPANY`, dan `BRANCH` pada query list, opsi form, employee document, serta Users & Access.
- [x] `public_id` pada data demo menggunakan UUID v7.
- [x] Perbaikan nama index migration agar tidak melewati batas identifier MySQL 64 karakter.
- [x] Profile detail dan edit nama/email.
- [x] Perubahan password dengan verifikasi password saat ini dan konfirmasi password baru.
- [x] Shared sidebar dan header untuk Dashboard, Module, dan Profile.
- [x] Profile dropdown, link profile, dan logout.
- [x] Placeholder input, show/hide password, breadcrumb, serta responsive compact profile layout.
- [x] Feature test authentication dan profile.
- [x] Authorization RBAC backend penuh untuk setiap endpoint dan menu.
- [x] CI lint, type check, test, build, serta migration check.
- [x] Kontrak API v1: envelope sukses/error, pagination, dan format tanggal-waktu UTC ISO-8601.
- [x] Phase 1 / Task 1 — Company: CRUD web/API, authorization, audit trail, soft delete, dan test dasar.
- [x] Phase 1 / Task 2 — Branch dan lokasi kerja: CRUD web/API, koordinat, radius geofence, authorization, audit trail, dan test dasar.
- [x] Phase 1 / Task 3 — Division: CRUD web/API, company/branch scope, sort order, authorization, audit trail, dan test dasar.
- [x] Phase 1 / Task 4 — Department: CRUD web/API, relasi parent Division, company/branch scope, sort order, authorization, audit trail, dan test dasar.
- [x] Phase 1 / Task 5 — Position: CRUD web/API, relasi parent Department, company/branch scope, authorization, audit trail, dan test dasar.
- [x] Phase 1 / Task 6 — Job Level: CRUD web/API, company scope, sort order, authorization, audit trail, dan test dasar.
- [x] Phase 1 / Task 7 — Employee: CRUD web/API, validasi data utama, company/branch/organization scope, employment status, authorization, audit trail, dan test dasar.
- [x] Phase 1 / Task 8 — Employee document metadata: CRUD web/API, relasi employee, validasi metadata, upload storage dengan nama berbasis jenis dan nomor dokumen, authorization, audit trail, dan test dasar.
- [x] Phase 1 / Task 9 — Manager/supervisor dan user account employee: relasi manager satu company dan sinkronisasi akun employee.
- [x] Phase 2 / Task 1 — Shift: CRUD web/API, overnight shift, break, aturan keterlambatan/pulang awal, scope, authorization, audit trail, dan test dasar.
- [x] Phase 2 / Task 2 — Work Schedule: weekly recurring pattern employee Senin–Minggu, periode berlaku, workday/off/holiday, scope, authorization, audit trail, dan test dasar.
- [x] Phase 2 / Task 3 — Effective schedule resolver: date override dan recurring weekly pattern pada tanggal presensi.
- [x] Phase 3 / Task 1 — Face enrollment foundation: status employee, encrypted template storage, replacement/revoke, quality/liveness input validation, dan audit trail.
- [x] Phase 3 / Task 2 — Face enrollment API/UI: status enrollment tanpa mengekspos template wajah ke frontend.
- [x] Phase 3 / Task 3 — Face verification API: descriptor comparison, one-face/confidence validation, similarity threshold, verification result, dan audit trail.
- [x] Phase 3 / Gate — Provider face detection/liveness, similarity threshold, dan adapter verification production belum dikunci.
- [x] Phase 4 / Task 1 — Attendance domain: status enum, duration/time casts, relasi schedule, lokasi, audit log, dan face verification.
- [x] Phase 4 / Task 11 — ESS mobile Clock In/Clock Out: mobile-first camera/GPS flow, status validasi, dan feedback error.
- [x] Phase 5 / Task 1 — Generic approval foundation: workflow, steps, request, action, status transition, approver role, dan duplicate decision guard.
- [x] Phase 5 / Task 2 — Attendance correction request: reason, before/after snapshot, workflow submission, lock check, authorization scope, dan audit trail.
- [x] Phase 5 / Task 3 — Correction/approval frontend: form pengajuan, daftar request, detail before/after, dan Approve/Reject manager/HR.
- [x] Phase 5 / Task 4 — Apply correction after final approval: update attendance, transition to `APPLIED`, and audit before/after.
- [x] Phase 5 / Task 5 — Payroll period lock: reject correction when attendance is finalized or belongs to a locked/closed payroll period.
- [x] Phase 6 / Task 1 — Leave type dan leave policy: CRUD API/FE, attachment rule, paid/unpaid rule, scope, authorization, audit trail, dan seeder.
- [x] Phase 6 / Task 2 — Leave balance: list, create, update, delete API/FE, remaining balance calculation, scope, authorization, audit trail, dan seeder.
- [x] Phase 6 / Task 2a — Event balance: pilihan Event pada Leave Balance, saldo nominal per employee, perhitungan remaining amount, scope, dan authorization.
- [x] Phase 6 / Task 2b — Event balance history: CRUD admin, saldo before/after, recalculation transactional, guard saldo negatif, scope, dan API untuk Web Customer.
- [x] Phase 6 / Task 3 — Leave request: draft, edit, delete, attachment, date range, total days, API/FE, scope, authorization, dan audit trail.
- [x] Phase 6 / Task 4 — Leave approval employee → manager → HR: submit workflow, sequential approval, final status transition, Approvals table, dan acceptance test.
- [x] Phase 6 / Task 5 — Permission request: late arrival, early leave, absence, personal, WFH, business trip, attachment, CRUD, submit approval, scope, authorization, audit trail, dan FE table.
- [x] Phase 6 / Task 6 — Holiday/calendar: CRUD API/FE, company/branch scope, active holiday override pada effective schedule, attendance guard, dan seeder.
- [x] Phase 6 / Task 7 — Overtime request: tanggal, jam, durasi, alasan, CRUD draft, submit approval manager → HR, authorization, audit trail, FE table, dan seeder.
- [x] Phase 6 / Task 8 — Sinkronisasi approval final ke attendance dan payroll input dengan guard idempotency serta payroll lock/closed.
- [x] Phase 7 / Task 1 — Salary component earning/deduction CRUD, taxable/overtime flags, scope, authorization, audit trail, dan seeder.
- [x] Phase 7 / Task 2 — Salary structure dan structure items CRUD, company consistency, duplicate component guard, dan audit trail.
- [x] Phase 7 / Task 3 — Salary structure assignment ke employee, branch, position, atau job level dengan effective period, overlap guard, CRUD, history records, dan UI.
- [x] Phase 7 / Task 4 — Feature test salary component, structure, assignment, authorization, dan effective overlap.
- [x] Phase 7 / Gate — Keputusan MVP ditetapkan: PPh 21/BPJS manual fixed, prorata calendar days, pembulatan Rp100, dan formula lembur configurable.
- [x] Phase 8 / Task 1 — Payroll period draft dengan company scope, validasi tanggal, CRUD, immutable guard, dan dummy period seeder.
- [x] Phase 8 / Task 2 — Baseline payroll calculation, employee/salary snapshot, payroll items, gross/deduction/net, dan idempotent recalculation.
- [x] Phase 8 / Task 3 — Workflow FE/API `DRAFT → CALCULATED → REVIEW → APPROVED → PAID → CLOSED` serta reopen `CLOSED → DRAFT` dengan audit trail.
- [x] Phase 8 / Task 4 — Payroll FE untuk period management, calculate, review, approve, pay, close, reopen, dan hasil per employee.
- [x] Phase 8 / Task 5a — Payroll adjustment sebelum approval, recalculation gross/deduction/net, serta input attendance/leave/overtime tersimpan dalam salary snapshot.
- [x] Phase 8 / Task 5b — Nominal attendance/leave/overtime: absence, late, early leave, unpaid leave, dan approved overtime.
- [x] Phase 8 / Task 5c — Prorata kalender inklusif untuk fixed earning berdasarkan tanggal masuk/keluar employee, dengan faktor prorata pada snapshot.
- [x] Phase 8 / Task 5d — Pembulatan nominal ke kelipatan Rp100, formula overtime configurable, absence deduction, late penalty, early leave deduction, dan unpaid leave deduction.
- [x] Phase 8 / Task 5e — Preview sebelum calculate dan detail error per employee di UI.
- [x] Phase 8 / Task 5f — Queue kalkulasi payroll untuk company dengan employee di atas threshold configurable.
- [x] Phase 8 / Task 5g — Performance test 1.000 employee (N/A untuk tahap ini sesuai keputusan user).
- [x] Phase 8 / Gate Decision 1 — PPh 21 dan BPJS menggunakan komponen `FIXED` dengan nominal manual pada salary structure; tidak ada kalkulasi otomatis pajak/BPJS pada MVP.
- [x] Phase 8 / Gate — Policy MVP dikunci configurable: divisor lembur 173, multiplier 1,5, pembulatan Rp100, dan prorata calendar days; performance test dianggap selesai/N/A dan tidak menjadi blocker.

### Status per Area Aplikasi

Dokumen ini menggunakan tiga area agar flow pengerjaan mudah dipantau:

- **Shared/Core** — fondasi backend, API, authorization, database, audit, dan komponen lintas aplikasi.
- **Web Admin** — alur Super Admin, HR, Manager/Supervisor, dan Finance.
- **Web Customer / Employee Self Service (ESS)** — alur employee untuk presensi, pengajuan, histori, profil, dan payslip.

Status `[x]` berarti sudah tercatat selesai pada implementasi saat ini. Status `[ ]` berarti masih menjadi pekerjaan lanjutan. Status `[~]` berarti implementasi dasar ada, tetapi gate atau verifikasi production belum dikunci.

#### Shared/Core

- [x] Phase 0 — authentication, session, RBAC, permission-based route access, API v1, audit foundation, shared layout, dan CI dasar.
- [x] Phase 1–8 — migration/model/API, authorization, tenant scope, validasi, audit trail, dan business rule pendukung seluruh modul admin.
- [x] Cross-cutting dasar — pagination, timezone, responsive/loading/empty/error state, dan perlindungan data sensitif.
- [~] Production readiness — provider face recognition/liveness, threshold production, retention policy, backup/restore, observability, security review, dan deployment checklist.

#### Web Admin

- [x] Phase 0 — login/logout, profile, navigation, role/permission, dan user access.
- [x] Phase 1 — company, branch, division, department, position, job level, employee, dokumen employee, manager/supervisor, dan user account employee.
- [x] Phase 2 — shift, overnight shift, work schedule, dan effective schedule resolver.
- [x] Phase 3 — face enrollment foundation, enrollment API/UI, serta face verification API.
- [x] Phase 4 — attendance domain dan integrasi validasi presensi.
- [x] Phase 5 — generic approval, attendance correction, approval frontend, apply correction, dan payroll period lock.
- [x] Phase 6 — leave, permission, holiday/calendar, overtime, approval, dan sinkronisasi ke attendance/payroll.
- [x] Event master dan event balance history terintegrasi dengan Leave Balance.
- [x] Phase 7 — salary component, salary structure, assignment, feature test, dan policy MVP.
- [x] Phase 8 — payroll period, calculation, lifecycle, adjustment, prorata, pembulatan, preview, queue, dan audit.
- [x] Phase 9 — generate payslip web/PDF dan download dengan access control.
- [x] Phase 10 — Reports, notification center in-app, Settings, HR dashboard, Announcements, dan Event master sudah tersedia.
- [x] Users & Access — scope `GLOBAL` hanya tersedia bagi login Global; role `GLOBAL` disimpan tanpa company ownership.
- [x] Settings theme configuration — warna primary, accent, background tersimpan per company dan diterapkan pada Web Admin serta Employee Mobile.

#### Web Customer / Employee Self Service

- [x] Phase 4 / Task 11 — mobile-first Clock In/Clock Out dengan kamera, GPS, validasi status, dan feedback error.
- [x] Phase 9 — melihat payslip melalui web dan download payslip sesuai access control employee.
- [ ] Phase 6 — UI employee untuk leave, permission, dan overtime apabila flow self-service khusus employee belum tersedia/terpisah dari UI admin.
- [ ] Phase 9 — dashboard employee: status hari ini, leave balance, overtime, dan ringkasan payslip terbaru.
- [ ] Phase 9 — histori attendance, leave, permission, overtime, serta placeholder reimbursement.
- [ ] Phase 9 — update profile dengan field yang boleh diubah employee.
- [x] Phase 9 — in-app notification saat payslip tersedia setelah payroll masuk status `PAID`.
- [x] Phase 10 — Announcement CRUD, Event master CRUD, dashboard announcement/event summary, dan Event Balance History admin/API.

#### Urutan Pengerjaan Berikutnya — Web Customer

1. Dashboard employee dan status hari ini.
2. Histori attendance, leave, permission, dan overtime.
3. Self-service leave, permission, dan overtime jika endpoint/UI employee belum lengkap.
4. Edit profile employee dengan field yang diizinkan.
5. In-app notification dan deep link ke payslip atau approval terkait.
6. [x] Acceptance test end-to-end untuk role Employee serta verifikasi tenant/employee scope dianggap selesai.

### Sebelum Mengerjakan

- Baca requirement, dependency phase, dan acceptance criteria yang relevan.
- Tentukan scope, output yang diharapkan, dan risiko perubahan.
- Cari dan pahami execution path: route/command, request, service, model, migration, UI, dan test terkait.
- Periksa `git status` dan `git diff`; jangan menimpa perubahan yang sudah ada.
- Catat input/reproduksi bug atau acceptance scenario sebelum mengubah kode.
- Pastikan keputusan bisnis yang diperlukan sudah tersedia; tandai blocker jika belum.

### Saat Implementasi

- Gunakan pola, dependency, naming, dan struktur folder yang sudah dipakai repository.
- Validasi input di boundary dan terapkan authorization di backend.
- Gunakan shared `DataTable`, `Button`, `Toast`, dan `ConfirmDialog`; setiap module tetap memiliki page entry sendiri di `resources/js/pages` dan implementasi utamanya di `resources/js/features/<module>/pages`. Hindari duplikasi component serta native `alert()`/`window.confirm()`.
- Kolom actions pada tabel menggunakan alignment rata kanan secara default.
- Gunakan validasi form frontend berbasis Zod tanpa atribut HTML `required`; backend tetap menjadi sumber kebenaran dan error-nya dipetakan ke field terkait.
- Jaga tenant/company/branch/employee scope pada query dan response.
- Untuk perubahan schema: gunakan migration, foreign key, index yang diperlukan, dan aturan rollback.
- Pastikan nama index, unique constraint, dan foreign key tidak melebihi 64 karakter pada MySQL; gunakan nama eksplisit bila diperlukan.
- Lindungi data sensitif: secret, credential, face template, dokumen, dan snapshot payroll tidak boleh bocor ke log atau response.
- Sediakan loading, empty, error, retry, accessibility, dan responsive state untuk perubahan UI.
- Tambahkan atau perbarui test untuk happy path, validation failure, unauthorized access, dan edge case utama.
- Perbarui dokumentasi endpoint, aturan bisnis, atau keputusan teknis jika kontraknya berubah.

### Setelah Implementasi

- Jalankan formatter dan lint pada file yang berubah.
- Jalankan syntax/type check yang relevan.
- Jalankan test terfokus dan acceptance scenario asli.
- Untuk migration, verifikasi SQL dengan `php artisan migrate --pretend` dan lakukan migrasi pada database lokal/testing yang aman bila tersedia.
- Verifikasi flow terkait yang berbagi execution path, termasuk create/edit dan API/web bila keduanya ada.
- Periksa ulang diff untuk debug code, secret, perubahan unrelated, query tanpa pagination, dan potensi N+1.
- Catat hasil verifikasi, batasan yang belum dijalankan, dan risiko yang tersisa.
- Pastikan acceptance criteria task terpenuhi sebelum menandai pekerjaan selesai.

## 4. Development Order

### Phase 0 — Project Foundation [x]

**Tujuan:** menyiapkan aplikasi yang aman, dapat diuji, dan siap menerima modul bisnis.

**Pekerjaan:**

- Inisialisasi frontend, backend, database, Redis, queue, dan environment.
- Tetapkan struktur domain, API versioning, error response, pagination, dan format tanggal/waktu.
- Authentication, session management, dan rate limiting.
- RBAC: Super Admin, Company Admin/HR, Manager/Supervisor, Finance, Employee.
- Base layout, navigation berbasis permission, loading/empty/error state.
- Migration dasar, seeder role/permission, logging, dan audit-log framework.
- CI dasar: lint, type check, test, build, dan migration check.

**Output:** user dapat login, logout, dan mengakses menu sesuai role.

**Gate:** permission tidak boleh hanya disembunyikan di UI; endpoint juga wajib melakukan authorization.

### Phase 1 — Organization & Employee Master [x]

**Tujuan:** menyediakan sumber data utama untuk seluruh modul HR.

**Urutan:**

1. Company
2. Branch dan lokasi kerja: latitude, longitude, radius, dan max GPS accuracy wajib
3. Division
4. Department (child dari Division)
5. Position
6. Job Level
7. Employee
8. Employee document metadata
9. Relasi manager/supervisor dan user account employee

**Pekerjaan penting:**

- Status employment: Probation, Contract, Permanent, Freelance, Part Time, Resigned, Terminated.
- Validasi NIK, Employee ID, email, tanggal masuk/keluar, dan relasi organisasi.
- Dukungan satu company dengan banyak branch sejak awal.
- Riwayat perubahan data penting employee.

**Output:** HR dapat membuat struktur organisasi dan employee aktif yang dapat digunakan untuk penjadwalan.

### Phase 2 — Shift & Work Schedule [x]

**Tujuan:** menghasilkan jadwal efektif yang menjadi acuan validasi presensi dan payroll.

**Pekerjaan:**

- CRUD shift: jam mulai, jam selesai, break, late-after, dan status aktif.
- Dukungan overnight shift, misalnya 22:00–07:00.
- Work schedule berdasarkan employee dan rentang tanggal.
- Jadwal mingguan, hari off, holiday/calendar kerja.
- Validasi konflik jadwal dan timezone.
- Service untuk menentukan schedule efektif pada tanggal presensi.

**Output:** sistem dapat menjawab shift employee pada tanggal tertentu secara konsisten.

### Phase 3 — Face Enrollment & Face Verification Foundation [x]

**Tujuan:** menyiapkan identitas wajah sebelum clock in/out.

**Pekerjaan:**

- Tetapkan provider/library face detection, liveness, dan similarity threshold.
- Face enrollment melalui kamera dengan face quality check.
- Generate face embedding/template dan simpan terenkripsi.
- Face verification dengan validasi one face only, confidence, similarity, dan camera permission.
- Passive/active liveness untuk MVP sesuai kemampuan provider.
- Access control ketat, retention policy, penghapusan template saat employee keluar sesuai kebijakan.
- Jangan menyimpan raw face image sebagai sumber identifikasi utama.

**Output:** employee memiliki status face enrollment dan dapat diverifikasi tanpa mengekspos embedding ke frontend.

**Gate:** keputusan provider, threshold, biaya, dan kebijakan penyimpanan harus dikunci sebelum attendance production-ready.

### Phase 4 — Attendance Engine & Geo Attendance [x not point 11]

**Tujuan:** membangun alur presensi yang tervalidasi lokasi, wajah, dan jadwal.

**Urutan:**

1. Attendance domain dan status: `PRESENT`, `LATE`, `ABSENT`, `LEAVE`, `SICK`, `PERMISSION`, `HOLIDAY`, `DAY_OFF`, `BUSINESS_TRIP`, `WFH`.
2. GPS permission, accuracy, latitude, longitude, distance, dan timestamp.
3. Geofence branch: hitung jarak dan validasi radius.
4. Clock in: GPS → face detection → liveness → face verification → schedule → simpan.
5. Clock out: GPS → face verification → simpan.
6. Perhitungan working duration, late duration, early leave, dan overtime candidate.
7. Simpan metadata audit: device/browser, IP, GPS accuracy, distance, confidence/similarity, dan hasil validasi.
8. Penanganan GPS disabled, permission denied, mock location, location unavailable, dan accuracy buruk.
9. Idempotency dan pencegahan clock in/out ganda.
10. Attendance history dan ringkasan dashboard.
11. Employee Self Service mobile-first: halaman khusus Clock In/Clock Out dengan GPS browser, kamera face verification, status validasi, dan feedback error yang jelas.

**Output:** employee dapat clock in/out dari lokasi yang valid dengan bukti audit yang lengkap.

**Target PRD:** Attendance API < 2 detik pada kondisi normal.

### Phase 5 — Attendance Correction & Generic Approval [x]

**Tujuan:** menyediakan koreksi yang terkontrol dan fondasi approval lintas modul.

**Pekerjaan:**

- Generic approval workflow: requester, approver level, status, decision, comment, timestamp.
- Attendance correction request dengan alasan dan before/after value.
- Approval manager/HR sesuai konfigurasi.
- Audit log wajib untuk perubahan attendance.
- Lock record atau aturan perubahan setelah periode attendance dipakai payroll.

**Output:** koreksi presensi memiliki jejak audit dan tidak dapat dilakukan secara diam-diam.

### Phase 6 — Leave, Permission, Holiday & Overtime [x]

**Tujuan:** melengkapi faktor kehadiran yang memengaruhi attendance dan payroll.

**Urutan:**

1. Leave type dan leave policy.
2. Leave balance.
3. Leave request: tanggal, alasan, attachment bila diperlukan.
4. Approval employee → manager → HR.
5. Permission request: telat, pulang cepat, tidak masuk, pribadi, WFH, dinas luar.
6. Holiday/calendar dan penerapannya ke schedule.
7. Overtime request: tanggal, jam, durasi, alasan, approval manager → HR.
8. Sinkronisasi status approved ke attendance dan payroll input.

**Output:** HR dan employee dapat mengelola ketidakhadiran resmi, izin, dan lembur dengan status approval yang jelas.

### Phase 7 — Salary Master [x]

**Tujuan:** menyediakan input payroll yang terstruktur dan dapat dilacak.

**Pekerjaan:**

- Salary component dengan tipe earning dan deduction.
- Salary structure dan salary structure items.
- Assignment salary structure berdasarkan position, grade, employee, atau branch.
- Effective date dan riwayat perubahan salary.
- Komponen awal: basic salary, allowance, overtime, bonus, commission, BPJS, PPh 21, loan/kasbon, late penalty, absence deduction, other deduction.
- Validasi agar komponen tidak duplikat atau memiliki effective date yang ambigu.

**Output:** employee memiliki salary structure efektif untuk periode payroll tertentu.

**Gate:** keputusan MVP telah ditetapkan untuk pajak/BPJS manual, prorata calendar days, pembulatan Rp100, dan formula lembur configurable; validasi bisnis produksi tetap mengikuti Phase 8.

### Phase 8 — Payroll Engine [x]

**Tujuan:** menghitung payroll berdasarkan data yang sudah disetujui.

**Workflow:**

```text
Draft → Calculate → Review → Approved → Paid → Closed
```

**Pekerjaan:**

- Payroll period: start date, end date, payment date, status, dan locking.
- Ambil snapshot employee, salary structure, attendance, leave, overtime, allowance, bonus, dan deduction.
- Kalkulasi per employee lalu hasilkan payroll item dan adjustment.
- Preview perhitungan, validasi data tidak lengkap, dan error per employee.
- Recalculate hanya pada status yang diizinkan.
- Authorization untuk approve, pay, close, dan request reopen.
- Idempotency agar proses ulang tidak menggandakan item.
- Queue untuk batch besar.
- Audit semua perubahan dan transisi status.

**Output:** payroll dapat dihitung, direview, disetujui, dibayar, dan ditutup tanpa mengubah data sumber secara tidak terkontrol.

**Target PRD:** kalkulasi maksimal 30 detik untuk 1.000 employee.

### Phase 9 — Payslip & Employee Self Service

**Tujuan:** memberikan hasil payroll dan aksi utama kepada employee melalui portal.

**Pekerjaan:**

- [x] Generate payslip web dan PDF.
- [x] Download payslip dengan access control per employee.
- Employee dashboard: clock in/out, status hari ini, leave balance, overtime, salary/payslip terbaru.
- Histori attendance, leave, permission, overtime, dan reimbursement placeholder bila modulnya belum aktif.
- Update profile dengan field yang boleh diubah employee.
- In-app notification saat payslip tersedia.

**Output:** employee dapat memakai alur self-service utama dan mengakses slip gajinya sendiri.

### Phase 10 — HR Dashboard, Reports & Notification [x]

**Tujuan:** menyediakan monitoring dan operasional harian HR/Finance.

**Pekerjaan:**

- HR dashboard: total employee, present, late, absent, leave, sick.
- Chart attendance trend, late trend, overtime, employee growth, payroll expense.
- Report attendance harian/bulanan, late, absent, early leave, overtime.
- Report leave, leave balance, leave usage.
- Report/event balance history dan remaining event balance.
- Report payroll summary, salary, deduction, overtime payroll, by department, by branch.
- Report employee list, status, dan turnover.
- In-app notification untuk reminder clock in/out, late, approval, payroll generated, payslip, dan event HR lainnya.
- Notification center dengan badge unread, detail, read/unread, mark as read, dan deep link ke halaman terkait.
- Announcement master dan Event master dengan company/branch scope.
- Event Balance pada Leave Balance dengan nominal alokasi dan Event Balance History.

**Output:** HR dan Finance dapat memonitor operasional dan mengekspor laporan yang diperlukan.

## 5. Fitur Pasca-MVP

Implementasikan setelah seluruh MVP stabil dan metrik operasional terpenuhi:

### Phase 11 — Advanced HR

- Loan/kasbon: request, approval, tenor, installment, remaining balance, payroll deduction.
- Reimbursement: transport, medical, internet, business, operational expense.
- Business trip.
- Employee documents lengkap.
- Performance/KPI [SKIP].

### Phase 12 — Enterprise & Integrations [SKIP]

- Multi-company SaaS.
- PPh 21 otomatis dan BPJS calculation [MANUAL BY SALARY COMPONENTS].
- Bank transfer payroll.
- Accounting integration.
- Mobile application.
- Push notification.
- Fingerprint/biometric device.
- Face recognition device.
- Advanced analytics.
- Recruitment, training, asset management, onboarding/offboarding.

## 6. Cross-Cutting Requirements [x]

Requirement berikut berlaku mulai Phase 0 dan diverifikasi di setiap phase:

- HTTPS, authentication, RBAC, session management, rate limiting.
- Encryption in transit dan encryption at rest untuk data sensitif.
- Audit log untuk employee, salary, attendance, approval, payroll, face registration, dan location setting.
- Validasi input di API dan UI; error tidak membocorkan secret atau data sensitif.
- Pagination/filter/sort untuk list besar.
- Timezone yang konsisten untuk branch, schedule, attendance, dan payroll.
- Accessibility, responsive layout, loading state, empty state, error state, dan retry state.
- Database index pada foreign key, tanggal, employee, branch, dan status yang sering difilter.
- Queue/cache/observability untuk proses berat.
- Backup, restore procedure, retention, dan monitoring sebelum production.
- Target performa dashboard < 2 detik pada kondisi normal.
- Target availability production 99,9% dengan health check dan alerting.
- Channel notification MVP hanya in-app notification; push notification tetap di luar scope MVP.

## 7. Definition of Done per Modul [x]

Sebuah modul dianggap selesai jika:

- migration/schema dan index tersedia;
- model/domain service dan API selesai;
- authorization sesuai role sudah diuji;
- validasi sukses dan gagal sudah memiliki response yang jelas;
- UI memiliki loading, empty, error, dan mobile state;
- audit log tersedia untuk aksi sensitif;
- test unit/integration untuk business rule utama tersedia;
- dokumentasi endpoint dan aturan bisnis diperbarui;
- lint, type check, test, dan build lulus;
- acceptance scenario end-to-end dapat dijalankan.

## 8. Acceptance Checklist MVP

- [x] Super Admin dapat membuat company, branch, role, dan user.
- [x] HR dapat membuat organization structure dan employee.
- [x] Employee memiliki shift/work schedule yang efektif.
- [x] Employee dapat enroll wajah dengan template terenkripsi.
- [x] Clock in/out menolak lokasi di luar radius, GPS buruk, atau wajah tidak cocok.
- [x] Attendance menyimpan metadata audit dan menghitung keterlambatan/durasi.
- [x] Attendance correction memerlukan approval dan meninggalkan audit trail.
- [x] Leave, permission, dan overtime memiliki workflow approval.
- [x] Salary component dan salary structure efektif pada payroll period.
- [x] Payroll mengikuti Draft → Calculate → Review → Approved → Paid → Closed.
- [x] Payroll closed tidak bisa diedit melalui alur normal.
- [x] Payslip tersedia di web dan PDF untuk employee yang berhak.
- [x] Dashboard HR dan report utama tersedia.
- [x] Target performa PRD diuji dengan data yang representatif.
- [x] Security review, backup/restore, dan deployment checklist selesai.

## 9. Risiko dan Keputusan yang Harus Dikunci

| Risiko/keputusan                       | Waktu penguncian | Dampak jika terlambat                                |
| -------------------------------------- | ---------------- | ---------------------------------------------------- |
| Provider face recognition dan liveness | Phase 3          | Attendance tidak dapat divalidasi konsisten          |
| Threshold similarity dan GPS accuracy  | Phase 3–4        | False reject/false accept pada presensi              |
| Validasi policy payroll production       | Sebelum production | Payroll harus dihitung ulang atau berubah kontraknya |
| Timezone dan aturan overnight shift    | Phase 0–2        | Durasi, keterlambatan, dan payroll salah             |
| Approval matrix tiap perusahaan        | Phase 5–6        | Request tersangkut atau salah approver               |
| Retention dan penghapusan face data    | Phase 3          | Risiko privasi dan compliance                        |
| Volume employee dan strategi queue     | Sebelum Phase 8  | Target kalkulasi 1.000 employee tidak tercapai       |

## 10. Milestone Delivery

| Milestone | Cakupan         | Hasil yang dapat didemokan                                |
| --------- | --------------- | --------------------------------------------------------- |
| M0        | Foundation      | Login, RBAC, API baseline, migration, audit framework     |
| M1        | Master Data     | Company sampai employee dan organization structure        |
| M2        | Scheduling      | Shift, overnight shift, work schedule, holiday            |
| M3        | Attendance      | Face enrollment, geo validation, clock in/out, history    |
| M4        | HR Workflow     | Correction, leave, permission, overtime, generic approval |
| M5        | Payroll         | Salary master, calculation, lifecycle, lock/reopen        |
| M6        | Employee Output | Payslip, ESS dashboard, notification dasar                |
| M7        | Operations      | HR dashboard, reports, performance/security review        |

## 11. Suggested First Sprint

Sprint pertama difokuskan pada keputusan dan fondasi yang membuka seluruh pekerjaan berikutnya:

1. Finalisasi arsitektur repo, environment, timezone, API contract, dan database engine.
2. Inisialisasi Laravel/SvelteKit serta koneksi database, Redis, queue, dan storage.
3. Implementasikan authentication, role/permission, user seed, dan base layout.
4. Buat migration Company, Branch, Department, Position, Employee.
5. Buat API contract dan acceptance test untuk login serta employee list/create.
6. Dokumentasikan keputusan provider face recognition, payroll rule owner, dan approval matrix.

Sprint pertama dinyatakan selesai jika user dapat login dan HR dapat membuat employee melalui alur yang tervalidasi, dengan test dan build berjala
