# CAP Attendance Pro — Production Blueprint & Codex Development Prompt

**Product Name:** CAP Attendance Pro  
**Tagline:** Modern Workforce Management System  
**Project Path:** `C:\xampp82\htdocs\cap-attendance-pro\v1.0`  
**Target Stack:** Laravel + MySQL/MariaDB + Blade + Bootstrap 5 + PWA  
**Primary Goal:** Build a production-ready HRD, mobile attendance, payroll, and project crew management platform.

---

## 0. Executive Summary

CAP Attendance Pro is a modern workforce management system designed to manage employee data, mobile GPS attendance, selfie verification, shifts, work locations, leave requests, overtime, reimbursements, business trips, meal allowance, payroll, digital payslips, and project-based crew management in one professional platform.

The system must start with a stable V1 foundation: HRD master data + mobile attendance. The architecture must be prepared for later payroll, claims, crew scheduling, and SaaS/white-label expansion without requiring major database rewrites.

The first production goal is a working Laravel application that can be deployed on shared hosting/cPanel or VPS, with secure login, role-based access, admin dashboard, mobile employee PWA, attendance GPS capture, selfie upload, attendance reporting, export, and activity logs.

---

## 1. Product Positioning

### 1.1 Positioning Statement

CAP Attendance Pro is a Modern Workforce Management System for companies, HRD teams, field operations, event vendors, production teams, outsourcing teams, restaurants, cafes, clubs, hotels, warehouses, and multi-branch businesses.

### 1.2 Core Value

The software must solve five operational problems:

1. Employee attendance is often manual, inaccurate, and hard to verify.
2. Field/project employees need mobile attendance with GPS and selfie proof.
3. HRD needs clean employee records, shift management, leave data, and reports.
4. Finance needs attendance-connected payroll data.
5. Project-based businesses need crew scheduling, call time, and crew cost tracking.

### 1.3 Product Identity

- Product: **CAP Attendance Pro**
- Tagline: **Modern Workforce Management System**
- Core Modules: HRD + Attendance + Payroll + Project Crew Management
- Platform: Web Admin + Mobile Employee PWA
- Visual Style: premium, clean, professional, dark navy/gold/silver identity

---

## 2. Target Users

### 2.1 Admin / Super Admin
Full system owner. Can configure companies, users, roles, settings, payroll rules, approval workflows, and all modules.

### 2.2 Owner / Director
Reads dashboards, attendance reports, payroll summaries, project cost reports, and approval summaries.

### 2.3 HRD
Manages employee records, attendance correction, leave, shifts, payroll preparation, and HR reports.

### 2.4 Finance
Handles payroll approval, reimbursements, business trip payments, paid status, and export reports.

### 2.5 Supervisor
Approves leave, overtime, correction requests, and monitors team attendance.

### 2.6 Project Manager
Creates projects/events, assigns crew, sets call time, monitors project attendance, checklist, proof of work, and crew cost.

### 2.7 Employee
Uses mobile PWA to check in/out, submit selfie attendance, view history, request correction, request leave, submit reimbursement, view payslip.

---

## 3. Development Philosophy

Build in versioned phases.

Do not build all premium features at once. Build a stable foundation first, then add payroll and project modules in controlled releases.

Critical rules:

1. Database must be normalized and extensible.
2. Role and permission design must be ready from V1.
3. Attendance logic must be inside service classes, not scattered in controllers.
4. GPS and selfie data must be stored with audit trail.
5. Payroll must never overwrite raw attendance data.
6. Every sensitive action must be logged.
7. UI must be premium from the start, not a generic Laravel CRUD template.
8. Employee mobile view must feel like an app, not a desktop page squeezed into mobile.

---

## 4. Recommended Technology Stack

### 4.1 Backend

- Laravel 11 or Laravel 12
- PHP 8.2+
- MySQL/MariaDB
- Laravel validation
- Laravel Storage public disk
- Laravel queues optional for later notification jobs

### 4.2 Frontend

- Blade templates
- Bootstrap 5
- Custom CSS variables for CAP branding
- Minimal JavaScript / vanilla JS for GPS, camera capture, PWA, UI interaction

### 4.3 Mobile Employee App

- Responsive PWA
- Installable shortcut on Android/iOS browser
- Camera capture via browser input or WebRTC where supported
- Geolocation API for GPS capture

### 4.4 Reporting

- Laravel Excel for Excel export
- DomPDF or Browsershot for PDF payslip/report later

### 4.5 Deployment

- Local development: XAMPP PHP 8.2
- Production: cPanel or VPS
- Database: MySQL/MariaDB
- Storage symlink required: `php artisan storage:link`

---

## 5. Local Project Path

Use this path:

```bat
C:\xampp82\htdocs\cap-attendance-pro\v1.0
```

Setup commands:

```bat
cd /d C:\xampp82\htdocs
mkdir cap-attendance-pro
cd cap-attendance-pro
composer create-project laravel/laravel v1.0
cd v1.0
```

Database name:

```text
cap_attendance_pro_v1
```

`.env` database config:

```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cap_attendance_pro_v1
DB_USERNAME=root
DB_PASSWORD=
```

Run development server:

```bat
php artisan serve
```

Open:

```text
http://127.0.0.1:8000
```

---

## 6. Full Product Roadmap

### V1 — Core HRD + Mobile Attendance

Goal: A real usable attendance system.

Features:

1. Login admin and employee
2. Role-based dashboard
3. Employee management
4. Department management
5. Position management
6. Work location + GPS radius
7. Shift schedule
8. Employee mobile dashboard
9. Check in via HP
10. Check out via HP
11. Selfie attendance
12. GPS validation
13. Late calculation
14. Early checkout calculation
15. Attendance history
16. Correction request
17. Attendance report
18. Export Excel
19. Company settings
20. Activity log

### V2 — Leave + Overtime + Payroll Basic

Features:

1. Leave type
2. Leave balance
3. Leave request
4. Leave approval
5. Overtime request
6. Overtime approval
7. Salary setup
8. Payroll period
9. Payroll generation basic
10. Digital payslip

### V3 — Claim, Trip, Meal Allowance, Full Payroll

Features:

1. Reimbursement categories
2. Reimbursement request
3. Receipt upload
4. Claim approval
5. Business trip request
6. Transport, hotel, meal, daily allowance
7. Meal allowance rules
8. Payroll simulation
9. Payroll approval
10. Payroll PDF/export

### V4 — Project Crew Management

Features:

1. Project/event management
2. Project work location
3. Crew scheduling
4. Call time reminder
5. Project attendance
6. Crew role/rate
7. Task checklist
8. Photo report/proof of work
9. Crew cost report
10. Project payroll mapping

### V5 — Enterprise Security & Premium HRIS

Features:

1. Device binding
2. Fake GPS detection
3. Face recognition attendance
4. Attendance risk score
5. Approval workflow builder
6. Multi-branch support
7. Document management
8. Announcement center
9. White-label branding

### V6 — AI + SaaS

Features:

1. AI attendance insight
2. AI payroll anomaly detection
3. AI HR assistant
4. Multi-company tenant management
5. Subscription plans
6. Billing system
7. Company self-registration

---

## 7. V1 Final Scope

Build this first.

### 7.1 Admin V1 Features

- Dashboard
- Employees CRUD
- Departments CRUD
- Positions CRUD
- Work Locations CRUD
- Shifts CRUD
- Employee Shift Assignment
- Daily Attendance
- Attendance Corrections
- Attendance Report
- Export Excel
- Company Settings
- Attendance Rules
- Users
- Activity Logs

### 7.2 Employee Mobile V1 Features

- Mobile dashboard
- Today attendance status
- Check in
- Check out
- Camera/selfie capture
- GPS capture
- Shift info
- Work location info
- Attendance history
- Correction request
- Profile
- Change password

---

## 8. System Roles

Use these roles from V1, even if not all are fully used immediately:

```text
super_admin
owner
admin
hrd
finance
supervisor
project_manager
employee
```

### 8.1 V1 Active Role Behavior

- `super_admin`, `admin`, `hrd`: access admin panel
- `employee`: access employee mobile panel

### 8.2 Future Role Behavior

- `finance`: payroll and payment modules
- `supervisor`: approval modules
- `project_manager`: project crew modules
- `owner`: executive dashboard and final approval

---

## 9. Application Menu Structure

### 9.1 V1 Admin Menu

```text
Dashboard

Master Data
- Employees
- Departments
- Positions
- Work Locations
- Shifts
- Employee Shift Assignment

Attendance
- Daily Attendance
- Attendance Corrections
- Attendance Report

Settings
- Company Profile
- Attendance Rules

System
- Users
- Activity Logs
```

### 9.2 Future Full Admin Menu

```text
Dashboard

HRD Management
- Employees
- Departments
- Positions
- Branches
- Employee Documents
- Contract Management

Attendance
- Daily Attendance
- Attendance Map
- Work Locations
- Shift Schedule
- Attendance Correction
- Suspicious Attendance
- Attendance Report

Leave Management
- Leave Requests
- Leave Balance
- Leave Types
- Holiday Calendar

Overtime
- Overtime Requests
- Overtime Rules
- Overtime Report

Claims & Trip
- Reimbursement Claims
- Claim Categories
- Business Trip
- Trip Allowance
- Payment Status

Meal Allowance
- Meal Rules
- Meal Data
- Manual Adjustment

Payroll
- Salary Setup
- Payroll Period
- Payroll Simulation
- Generate Payroll
- Payroll Approval
- Payslip
- Payroll Report

Project Crew
- Projects / Events
- Crew Scheduling
- Project Attendance
- Crew Rate
- Task Checklist
- Photo Report
- Crew Cost Report

Reports
- HRD Report
- Attendance Report
- Leave Report
- Overtime Report
- Claim Report
- Payroll Report
- Project Cost Report

Settings
- Company Profile
- App Branding
- Roles & Permissions
- Approval Workflow
- Payroll Rules
- Attendance Rules
- Notification Settings
```

### 9.3 V1 Employee Mobile Menu

```text
Home
Check In / Check Out
Attendance History
Correction Request
Profile
```

### 9.4 Future Employee Mobile Menu

```text
Home
My Attendance
Leave
Overtime
Business Trip
Reimbursement
Payroll / Payslip
Project Schedule
Task Checklist
Profile
```

---

## 10. Laravel Architecture

### 10.1 Controller Structure

```text
app/Http/Controllers/
├── Auth/
│   ├── LoginController.php
│   └── LogoutController.php
├── Admin/
│   ├── DashboardController.php
│   ├── EmployeeController.php
│   ├── DepartmentController.php
│   ├── PositionController.php
│   ├── WorkLocationController.php
│   ├── ShiftController.php
│   ├── EmployeeShiftController.php
│   ├── AttendanceController.php
│   ├── AttendanceReportController.php
│   ├── AttendanceCorrectionController.php
│   ├── SettingController.php
│   ├── UserController.php
│   └── ActivityLogController.php
└── Employee/
    ├── HomeController.php
    ├── AttendanceController.php
    ├── AttendanceHistoryController.php
    ├── CorrectionRequestController.php
    └── ProfileController.php
```

### 10.2 Middleware Structure

```text
app/Http/Middleware/
├── AdminMiddleware.php
├── EmployeeMiddleware.php
└── EnsureUserIsActive.php
```

### 10.3 Service Classes

```text
app/Services/
├── AttendanceService.php
├── GeoDistanceService.php
├── ActivityLogService.php
├── UploadService.php
└── SettingService.php
```

Critical rule: attendance calculations must be in `AttendanceService`, distance calculation in `GeoDistanceService`, and activity tracking in `ActivityLogService`.

### 10.4 Models

```text
app/Models/
├── User.php
├── Employee.php
├── Department.php
├── Position.php
├── WorkLocation.php
├── Shift.php
├── EmployeeShift.php
├── Attendance.php
├── AttendanceCorrection.php
├── Setting.php
└── ActivityLog.php
```

---

## 11. View Structure

```text
resources/views/
├── layouts/
│   ├── admin.blade.php
│   ├── employee.blade.php
│   └── auth.blade.php
├── auth/
│   └── login.blade.php
├── admin/
│   ├── dashboard.blade.php
│   ├── employees/
│   │   ├── index.blade.php
│   │   ├── create.blade.php
│   │   ├── edit.blade.php
│   │   └── show.blade.php
│   ├── departments/
│   ├── positions/
│   ├── work-locations/
│   ├── shifts/
│   ├── employee-shifts/
│   ├── attendance/
│   ├── attendance-reports/
│   ├── attendance-corrections/
│   ├── settings/
│   ├── users/
│   └── activity-logs/
└── employee/
    ├── home.blade.php
    ├── attendance/
    │   ├── check-in.blade.php
    │   └── check-out.blade.php
    ├── history/
    │   └── index.blade.php
    ├── corrections/
    │   ├── create.blade.php
    │   └── index.blade.php
    └── profile/
        └── index.blade.php
```

---

## 12. Database Design — V1

### 12.1 Migration Order

```text
001_create_users_table
002_create_departments_table
003_create_positions_table
004_create_employees_table
005_create_work_locations_table
006_create_shifts_table
007_create_employee_shifts_table
008_create_attendances_table
009_create_attendance_corrections_table
010_create_settings_table
011_create_activity_logs_table
```

### 12.2 `users`

Purpose: authentication and role access.

Fields:

```text
id
name
email
password
role
status
last_login_at
remember_token
created_at
updated_at
```

Recommended values:

```text
role: super_admin, owner, admin, hrd, finance, supervisor, project_manager, employee
status: active, inactive
```

Indexes:

```text
email unique
role index
status index
```

### 12.3 `departments`

```text
id
name
description
status
created_at
updated_at
```

Values:

```text
status: active, inactive
```

### 12.4 `positions`

```text
id
department_id
name
description
status
created_at
updated_at
```

Relations:

```text
positions.department_id -> departments.id
```

### 12.5 `employees`

```text
id
user_id
employee_code
full_name
phone
gender
birth_date
address
department_id
position_id
join_date
photo
employment_status
status
created_at
updated_at
```

Values:

```text
gender: male, female, other
employment_status: permanent, contract, freelance, daily_worker, intern
status: active, inactive, resigned, suspended
```

Relations:

```text
employees.user_id -> users.id
employees.department_id -> departments.id
employees.position_id -> positions.id
```

### 12.6 `work_locations`

```text
id
name
address
latitude
longitude
radius_meter
type
status
created_at
updated_at
```

Values:

```text
type: office, warehouse, project, remote, custom
status: active, inactive
```

### 12.7 `shifts`

```text
id
name
start_time
end_time
late_tolerance_minutes
early_checkout_tolerance_minutes
break_start_time
break_end_time
is_overnight
status
created_at
updated_at
```

Values:

```text
is_overnight: boolean
status: active, inactive
```

### 12.8 `employee_shifts`

```text
id
employee_id
shift_id
work_location_id
effective_date
end_date
status
created_at
updated_at
```

Purpose: assign employee to shift and location by date range.

Values:

```text
status: active, inactive
```

### 12.9 `attendances`

```text
id
employee_id
shift_id
work_location_id
attendance_date

check_in_time
check_in_latitude
check_in_longitude
check_in_distance_meter
check_in_photo
check_in_status
check_in_notes

check_out_time
check_out_latitude
check_out_longitude
check_out_distance_meter
check_out_photo
check_out_status
check_out_notes

late_minutes
early_checkout_minutes
work_duration_minutes

device_info
ip_address
status
created_at
updated_at
```

Values:

```text
check_in_status: on_time, late, outside_radius, manual, suspicious
check_out_status: normal, early_checkout, outside_radius, manual, suspicious
status: present, late, absent, incomplete, outside_radius, manual, suspicious
```

Indexes:

```text
employee_id index
attendance_date index
status index
employee_id + attendance_date unique if only one attendance per day is allowed
```

### 12.10 `attendance_corrections`

```text
id
attendance_id
employee_id
request_type
requested_check_in_time
requested_check_out_time
reason
attachment
status
approved_by
approved_at
rejected_reason
created_at
updated_at
```

Values:

```text
request_type: check_in, check_out, both
status: pending, approved, rejected, cancelled
```

### 12.11 `settings`

```text
id
key
value
created_at
updated_at
```

Default keys:

```text
company_name
company_logo
company_address
company_phone
company_email
attendance_default_radius
attendance_allow_outside_radius
attendance_selfie_required
attendance_photo_quality
app_primary_color
app_timezone
```

### 12.12 `activity_logs`

```text
id
user_id
module
action
description
ip_address
user_agent
created_at
updated_at
```

---

## 13. Future Database Expansion

Do not build all of these in V1, but prepare naming and relationships.

### V2 Tables

```text
leave_types
leave_balances
leave_requests
overtime_rules
overtime_requests
salary_setups
payroll_periods
payrolls
payroll_details
```

### V3 Tables

```text
reimbursement_categories
reimbursements
business_trips
meal_allowance_rules
meal_allowances
payroll_approvals
payslips
```

### V4 Tables

```text
projects
project_crews
project_attendances
project_tasks
project_task_reports
project_crew_rates
project_costs
```

### V5 Tables

```text
devices
device_approval_requests
attendance_risk_logs
face_profiles
company_announcements
employee_documents
approval_workflows
approval_steps
approval_logs
branches
```

### V6 Tables

```text
tenants
subscription_plans
tenant_subscriptions
billing_invoices
ai_insight_logs
ai_anomaly_logs
```

---

## 14. Relationships

### 14.1 User and Employee

```text
User hasOne Employee
Employee belongsTo User
```

### 14.2 Department and Position

```text
Department hasMany Position
Position belongsTo Department
```

### 14.3 Department/Position and Employee

```text
Department hasMany Employee
Position hasMany Employee
Employee belongsTo Department
Employee belongsTo Position
```

### 14.4 Employee Shift

```text
Employee hasMany EmployeeShift
Shift hasMany EmployeeShift
WorkLocation hasMany EmployeeShift
EmployeeShift belongsTo Employee
EmployeeShift belongsTo Shift
EmployeeShift belongsTo WorkLocation
```

### 14.5 Attendance

```text
Employee hasMany Attendance
Shift hasMany Attendance
WorkLocation hasMany Attendance
Attendance belongsTo Employee
Attendance belongsTo Shift
Attendance belongsTo WorkLocation
```

### 14.6 Correction

```text
Attendance hasMany AttendanceCorrection
Employee hasMany AttendanceCorrection
AttendanceCorrection belongsTo Attendance
AttendanceCorrection belongsTo Employee
```

---

## 15. Attendance Business Logic

### 15.1 Check In Flow

```text
Employee opens mobile dashboard
System checks authenticated employee
System gets today shift assignment
System gets work location
Browser requests GPS permission
Browser captures latitude and longitude
System calculates distance to assigned location
Employee captures selfie
Employee submits check-in
System validates duplicate attendance
System validates radius mode
System validates late status
System saves attendance
System logs activity
System returns status to mobile dashboard
```

### 15.2 Check Out Flow

```text
Employee opens mobile dashboard
System verifies employee already checked in today
Browser requests GPS permission
Browser captures latitude and longitude
System calculates distance to assigned location
Employee captures selfie
Employee submits check-out
System validates checkout time
System calculates early checkout minutes
System calculates work duration minutes
System updates attendance
System logs activity
System returns status to mobile dashboard
```

### 15.3 GPS Radius Logic

Use Haversine formula.

Input:

```text
work_location.latitude
work_location.longitude
employee_current.latitude
employee_current.longitude
```

Output:

```text
distance_meter
```

Rule:

```text
if distance_meter <= radius_meter:
    GPS is valid
else:
    GPS is outside_radius
```

Recommended V1 mode:

```text
Flexible Mode
Outside radius attendance is still saved but flagged as outside_radius for HRD review.
```

Future strict mode:

```text
Strict Mode
Outside radius attendance is rejected unless admin setting allows it.
```

### 15.4 Late Logic

Example:

```text
Shift start: 08:00
Late tolerance: 10 minutes
On-time deadline: 08:10
```

Rule:

```text
if check_in_time <= start_time + tolerance:
    check_in_status = on_time
    late_minutes = 0
else:
    check_in_status = late
    late_minutes = check_in_time - start_time
```

Important: `late_minutes` must be calculated from original shift start time, not from tolerance deadline.

### 15.5 Early Checkout Logic

Example:

```text
Shift end: 17:00
Early checkout tolerance: 10 minutes
Normal checkout threshold: 16:50
```

Rule:

```text
if check_out_time >= end_time - tolerance:
    check_out_status = normal
    early_checkout_minutes = 0
else:
    check_out_status = early_checkout
    early_checkout_minutes = end_time - check_out_time
```

### 15.6 Attendance Final Status

Rule priority:

```text
if marked manual:
    status = manual
else if check_in or check_out outside radius:
    status = outside_radius
else if check_in exists and check_out is null:
    status = incomplete
else if check_in_status == late:
    status = late
else if check_in exists and check_out exists:
    status = present
else:
    status = absent
```

### 15.7 Overnight Shift

For shifts like 19:00 to 03:00:

```text
is_overnight = true
start_datetime = attendance_date 19:00
end_datetime = attendance_date + 1 day 03:00
```

Attendance date must still refer to shift start date.

---

## 16. Authentication and Access

### 16.1 Login

Use email + password.

After login redirect:

```text
super_admin/admin/hrd -> /admin/dashboard
employee -> /employee/home
```

### 16.2 Admin Middleware

Allow roles:

```text
super_admin
owner
admin
hrd
finance
supervisor
project_manager
```

For V1, only build functional access for `super_admin`, `admin`, `hrd`.

### 16.3 Employee Middleware

Allow role:

```text
employee
```

### 16.4 Active User Check

Reject login/access when `users.status != active`.

---

## 17. Route Blueprint

### 17.1 Auth Routes

```php
Route::get('/', function () {
    return redirect()->route('login');
});

Route::get('/login', [LoginController::class, 'showLogin'])->name('login');
Route::post('/login', [LoginController::class, 'login'])->name('login.submit');
Route::post('/logout', [LogoutController::class, 'logout'])->name('logout');
```

### 17.2 Admin Routes

```php
Route::middleware(['auth', 'active', 'admin'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

        Route::resource('/employees', EmployeeController::class);
        Route::resource('/departments', DepartmentController::class);
        Route::resource('/positions', PositionController::class);
        Route::resource('/work-locations', WorkLocationController::class);
        Route::resource('/shifts', ShiftController::class);
        Route::resource('/employee-shifts', EmployeeShiftController::class);

        Route::get('/attendance/daily', [AttendanceController::class, 'daily'])->name('attendance.daily');
        Route::get('/attendance/report', [AttendanceReportController::class, 'index'])->name('attendance.report');
        Route::get('/attendance/report/export', [AttendanceReportController::class, 'export'])->name('attendance.report.export');

        Route::get('/attendance-corrections', [AttendanceCorrectionController::class, 'index'])->name('corrections.index');
        Route::post('/attendance-corrections/{id}/approve', [AttendanceCorrectionController::class, 'approve'])->name('corrections.approve');
        Route::post('/attendance-corrections/{id}/reject', [AttendanceCorrectionController::class, 'reject'])->name('corrections.reject');

        Route::get('/settings/company', [SettingController::class, 'company'])->name('settings.company');
        Route::post('/settings/company', [SettingController::class, 'saveCompany'])->name('settings.company.save');
        Route::get('/settings/attendance', [SettingController::class, 'attendance'])->name('settings.attendance');
        Route::post('/settings/attendance', [SettingController::class, 'saveAttendance'])->name('settings.attendance.save');

        Route::get('/users', [UserController::class, 'index'])->name('users.index');
        Route::get('/activity-logs', [ActivityLogController::class, 'index'])->name('activity-logs.index');
    });
```

### 17.3 Employee Routes

```php
Route::middleware(['auth', 'active', 'employee'])
    ->prefix('employee')
    ->name('employee.')
    ->group(function () {
        Route::get('/home', [HomeController::class, 'index'])->name('home');

        Route::get('/attendance/check-in', [AttendanceController::class, 'checkInPage'])->name('attendance.checkin');
        Route::post('/attendance/check-in', [AttendanceController::class, 'checkIn'])->name('attendance.checkin.submit');

        Route::get('/attendance/check-out', [AttendanceController::class, 'checkOutPage'])->name('attendance.checkout');
        Route::post('/attendance/check-out', [AttendanceController::class, 'checkOut'])->name('attendance.checkout.submit');

        Route::get('/attendance/history', [AttendanceHistoryController::class, 'index'])->name('attendance.history');

        Route::get('/corrections', [CorrectionRequestController::class, 'index'])->name('corrections.index');
        Route::get('/corrections/create', [CorrectionRequestController::class, 'create'])->name('corrections.create');
        Route::post('/corrections', [CorrectionRequestController::class, 'store'])->name('corrections.store');

        Route::get('/profile', [ProfileController::class, 'index'])->name('profile');
        Route::post('/profile/password', [ProfileController::class, 'changePassword'])->name('profile.password');
    });
```

---

## 18. UI/UX Direction

### 18.1 Visual Identity

Recommended colors:

```text
Dark Navy: #08111F
Deep Blue: #0D1B2A
Gold Accent: #D6A84F
Silver: #C7CBD1
Soft Background: #F4F6F9
Danger: #DC3545
Success: #198754
Warning: #FFC107
Info: #0DCAF0
```

### 18.2 Admin UI Principles

- Premium dark sidebar
- Gold accent for active menu
- Clean topbar
- Statistic cards
- Compact professional tables
- Badge statuses
- Filter bar on top of reports
- No cluttered dashboard
- Use consistent spacing

### 18.3 Employee Mobile UI Principles

- Mobile-first layout
- Large check-in/check-out buttons
- Clear GPS status
- Clear shift and location info
- Selfie preview before submit
- Attendance status card
- Minimal form fields
- Bottom navigation optional
- PWA install-ready

### 18.4 Employee Home Example

```text
Good Morning, Andi
Today: Monday, 9 August 2026

Shift
Regular Office
08:00 - 17:00

Location
Kantor Pusat CAP
Radius: 100m

Status
Not Checked In

[Check In]
[Check Out]

GPS: Waiting / Inside Radius / Outside Radius
Selfie: Required
```

---

## 19. Dashboard Requirements

### 19.1 Admin Dashboard V1 Cards

```text
Total Employees
Present Today
Late Today
Absent Today
Incomplete Attendance
Outside Radius
Pending Corrections
```

### 19.2 Admin Dashboard V1 Widgets

1. Attendance chart for last 7 days
2. Late employees today
3. Outside radius attendance today
4. Pending correction requests
5. Recent activity log

### 19.3 Future Executive Dashboard

```text
Payroll this month
Overtime cost
Reimbursement pending
Active projects
Crew cost this month
Attendance risk trend
Top late departments
```

---

## 20. Seeder Data

### 20.1 Users

```text
Super Admin
HRD Admin
Employee Demo 1
Employee Demo 2
Employee Demo 3
```

Default credentials for local demo:

```text
superadmin@capattendance.test / password
hrd@capattendance.test / password
employee1@capattendance.test / password
employee2@capattendance.test / password
employee3@capattendance.test / password
```

Do not use these credentials in production.

### 20.2 Departments

```text
HRD
Finance
Production
Technical
Event Crew
Sales
```

### 20.3 Positions

```text
HRD Manager
Finance Staff
Project Manager
Lighting Operator
Visual Operator
Technician
Admin Staff
Sales Executive
```

### 20.4 Work Locations

```text
Kantor Pusat CAP
Gudang CAP
Project ICE BSD
Project Hotel Mulia
Remote Work
```

Use dummy coordinates for local demo and allow editing from admin.

### 20.5 Shifts

```text
Regular Office: 08:00 - 17:00
Event Day: 10:00 - 22:00
Night Event: 19:00 - 03:00
Half Day: 08:00 - 12:00
```

---

## 21. Security Requirements

### 21.1 Authentication Security

- Password must be hashed using Laravel Hash.
- Use CSRF protection on all forms.
- Use Laravel validation for all requests.
- Block inactive users.
- Regenerate session on login.
- Logout must invalidate session.

### 21.2 Upload Security

- Selfie upload must validate file type.
- Allowed types: jpg, jpeg, png, webp.
- Limit file size. Recommended max: 3MB.
- Store files in Laravel storage, not raw public uploads.
- Never execute uploaded files.
- Generate unique filenames.

### 21.3 Access Control

- Employee must only access their own attendance data.
- Admin must not access employee mobile routes unless role allows.
- Sensitive payroll future modules must require finance/owner permission.
- Every approval must be logged.

### 21.4 Audit Trail

Log these actions:

```text
login
logout
employee created
employee updated
employee disabled
work location created/updated
shift created/updated
check in
check out
correction requested
correction approved
correction rejected
report exported
settings updated
```

### 21.5 Production Environment

- `APP_DEBUG=false`
- Secure `.env`
- Strong admin password
- HTTPS required for GPS/camera PWA features in production
- Database backup enabled
- Storage folder protected

---

## 22. PWA Requirements

### 22.1 Manifest

Create:

```text
public/manifest.json
```

Required fields:

```json
{
  "name": "CAP Attendance Pro",
  "short_name": "CAP Attendance",
  "start_url": "/employee/home",
  "display": "standalone",
  "background_color": "#08111F",
  "theme_color": "#D6A84F",
  "icons": []
}
```

### 22.2 Service Worker

Create basic service worker for app shell caching later. For V1, keep it simple. Do not cache sensitive attendance POST requests.

### 22.3 Browser Requirements

GPS and camera require HTTPS in most production environments. Localhost works for testing.

---

## 23. Reporting Requirements

### 23.1 Attendance Report Filters

```text
start_date
end_date
employee
department
position
work_location
status
```

### 23.2 Attendance Report Columns

```text
Date
Employee Code
Employee Name
Department
Position
Shift
Work Location
Check In Time
Check In Status
Check In Distance
Check Out Time
Check Out Status
Check Out Distance
Late Minutes
Early Checkout Minutes
Work Duration
Final Status
```

### 23.3 Export

V1 export: Excel.

Future export: PDF summary.

---

## 24. Production Deployment Checklist

### 24.1 Pre-Deployment

```text
composer install --no-dev --optimize-autoloader
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear
php artisan storage:link
php artisan migrate --force
php artisan db:seed --force only if required
```

### 24.2 `.env` Production

```env
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=production_db
DB_USERNAME=production_user
DB_PASSWORD=strong_password

FILESYSTEM_DISK=public
```

### 24.3 cPanel Notes

If deploying to cPanel:

1. Laravel project should be outside public_html if possible.
2. Point domain/subdomain document root to Laravel `public` folder.
3. If not possible, use careful public path setup and protect `.env`.
4. Run `storage:link` or create symlink manually.
5. Ensure PHP extensions are enabled: openssl, pdo_mysql, mbstring, tokenizer, xml, ctype, json, fileinfo.

### 24.4 Final Production Checks

```text
Login works
Admin dashboard works
Employee mobile works
GPS prompt appears
Selfie upload works
Attendance saved
Report filter works
Excel export works
Storage image accessible
Inactive user blocked
Admin/employee route separation works
APP_DEBUG=false
HTTPS active
Database backup configured
```

---

## 25. Testing Plan

### 25.1 Functional Testing

Test cases:

```text
Admin login success
Employee login success
Wrong password rejected
Inactive user rejected
Create department
Create position
Create employee with user account
Create work location
Create shift
Assign employee shift
Employee check in inside radius
Employee check in outside radius
Employee cannot check in twice
Employee cannot check out before check in
Employee check out successfully
Late status calculated
Early checkout status calculated
Correction request submitted
Admin approves correction
Attendance report filtered
Excel export downloaded
```

### 25.2 Mobile Testing

Test on:

```text
Android Chrome
iPhone Safari
Desktop Chrome responsive mode
```

Check:

```text
GPS permission
Camera/selfie upload
Button size
Form usability
PWA install prompt
```

### 25.3 Security Testing

```text
Employee cannot access admin route
Employee cannot view another employee history
Unauthenticated user redirected to login
CSRF protection works
Invalid upload rejected
Inactive user blocked
```

---

## 26. Coding Phase Plan for Codex

### Phase 1 — Laravel Foundation

Build:

1. Laravel project setup
2. Database config
3. Auth controller
4. Login/logout
5. Role middleware
6. Active user middleware
7. Admin layout
8. Employee mobile layout
9. Base dashboard pages

Acceptance criteria:

```text
Super admin can login and see admin dashboard.
Employee can login and see employee home.
Admin cannot open employee-only pages if not allowed.
Employee cannot open admin dashboard.
```

### Phase 2 — Database and Models

Build:

1. All V1 migrations
2. Model relationships
3. Seeder data
4. Factory optional

Acceptance criteria:

```text
php artisan migrate:fresh --seed works without errors.
Demo users can login.
Relationships are functional.
```

### Phase 3 — Master Data CRUD

Build:

1. Departments CRUD
2. Positions CRUD
3. Work Locations CRUD
4. Shifts CRUD
5. Employees CRUD
6. Employee Shift Assignment CRUD

Acceptance criteria:

```text
Admin can fully manage master data from UI.
Employee user account can be created from employee form.
Data validates correctly.
Status badge appears correctly.
```

### Phase 4 — Attendance Core

Build:

1. Employee home status
2. Check-in page
3. Check-out page
4. GPS capture JS
5. Selfie upload
6. GeoDistanceService
7. AttendanceService
8. Duplicate prevention
9. Late calculation
10. Early checkout calculation
11. Outside radius flag

Acceptance criteria:

```text
Employee can check in from mobile.
GPS latitude/longitude saved.
Distance meter saved.
Selfie image saved.
Status calculated correctly.
Employee can check out only after checking in.
Work duration calculated.
```

### Phase 5 — Attendance Report

Build:

1. Daily attendance page
2. Report page with filters
3. Excel export
4. Selfie preview link
5. Map link to Google Maps using saved coordinates

Acceptance criteria:

```text
HRD can filter attendance by date, employee, department, location, status.
HRD can export Excel.
HRD can inspect attendance detail.
```

### Phase 6 — Correction Request

Build:

1. Employee correction request
2. Admin correction list
3. Approve/reject
4. Update attendance when approved
5. Activity log

Acceptance criteria:

```text
Employee can request missing check-in/check-out correction.
Admin can approve or reject.
Attendance updates only after approval.
```

### Phase 7 — Settings, Activity Log, PWA, Polish

Build:

1. Company profile setting
2. Attendance rule setting
3. Activity log page
4. PWA manifest
5. Basic service worker
6. UI polish
7. Responsive testing

Acceptance criteria:

```text
Company logo/name appears in UI.
Attendance radius/default rules can be configured.
Activity log records major actions.
Employee mobile page looks premium and usable.
```

---

## 27. Premium Feature Backlog

Build after V1.

### 27.1 Device Binding

- Store device fingerprint/device name
- First device login is saved
- New device requires admin approval
- HRD can reset device

### 27.2 Fake GPS Detection

- Detect browser mock location where possible
- Flag impossible movement speed
- Flag location mismatch patterns
- Add suspicious status

### 27.3 Face Recognition

- Store face profile
- Compare selfie with employee profile
- Flag mismatch for HRD review

### 27.4 Attendance Risk Score

Score factors:

```text
inside radius
late/early pattern
outside radius
manual correction frequency
device changes
fake GPS flag
face verification result
```

### 27.5 AI Attendance Insight

Examples:

```text
Department Technical has 18% late attendance this month.
Overtime increased 35% compared to last month.
Three employees have repeated correction requests.
```

### 27.6 AI Payroll Anomaly Detection

Examples:

```text
Overtime amount is unusually high.
Reimbursement is above department average.
Meal allowance does not match valid attendance count.
```

---

## 28. Payroll Future Module Blueprint

### 28.1 Payroll Components

```text
Basic salary
Fixed allowance
Meal allowance
Overtime
Business trip
Reimbursement
Bonus
Late deduction
Absence deduction
Other deduction
```

### 28.2 Payroll Formula

```text
Net Salary =
Basic Salary
+ Fixed Allowance
+ Overtime Total
+ Meal Allowance Total
+ Business Trip Total
+ Reimbursement Total
+ Bonus
- Late Deduction
- Absence Deduction
- Other Deduction
```

### 28.3 Payroll Status

```text
Draft
Simulation
Generated
Approved
Paid
Locked
```

### 28.4 Digital Payslip

Features:

```text
PIN protected
PDF download
Monthly history
Seen/unseen status
Detailed component breakdown
```

---

## 29. Project Crew Future Module Blueprint

### 29.1 Project Data

```text
Project name
Client name
Venue/location
Start date
End date
PIC/project manager
Status
```

### 29.2 Crew Scheduling

```text
Project
Employee/Crew
Role
Call time
End time
Rate
Meal allowance
Transport allowance
Notes
```

### 29.3 Project Attendance

```text
Project-specific check-in
Project-specific check-out
GPS venue validation
Selfie proof
Photo report
Task checklist
```

### 29.4 Crew Cost Report

```text
Crew fee
Meal allowance
Transport
Overtime
Accommodation
Other costs
Total project crew cost
```

---

## 30. Codex Master Instruction

Use this instruction in Codex:

```text
You are developing CAP Attendance Pro, a production-ready Laravel-based Modern Workforce Management System.

Local project path:
C:\xampp82\htdocs\cap-attendance-pro\v1.0

Build the project progressively according to this blueprint. Prioritize clean architecture, secure authentication, role-based access, normalized database design, service-based attendance logic, mobile-first employee PWA, and production-ready code.

Do not create a generic CRUD-only app. The UI must feel premium and professional. The admin dashboard should use a dark navy/gold CAP identity. The employee mobile interface must feel like an installable app.

Start with V1 only:
Core HRD + Mobile Attendance.

V1 required modules:
- Auth login/logout
- Role middleware
- Active user middleware
- Admin dashboard
- Employee mobile dashboard
- Employees
- Departments
- Positions
- Work locations
- Shifts
- Employee shift assignment
- Check in
- Check out
- GPS capture
- Selfie upload
- Distance validation
- Late calculation
- Early checkout calculation
- Attendance report
- Export Excel
- Correction request
- Company settings
- Attendance rules
- Activity logs
- PWA manifest

Important technical rules:
- Put attendance calculations in AttendanceService.
- Put Haversine distance calculation in GeoDistanceService.
- Put audit logs in ActivityLogService.
- Validate every form request.
- Hash all passwords.
- Prevent employees from accessing other employees' data.
- Store uploaded selfies securely using Laravel Storage.
- Keep code readable, scalable, and production-safe.

After each coding phase, verify:
php artisan migrate:fresh --seed
php artisan route:list
php artisan serve

Do not move to payroll, leave, reimbursement, or project crew modules until V1 is stable.
```

---

## 31. Immediate Next Coding Task

Start with **Phase 1 + Phase 2**:

1. Create Laravel foundation in `C:\xampp82\htdocs\cap-attendance-pro\v1.0`.
2. Configure `.env` for `cap_attendance_pro_v1`.
3. Create auth controllers.
4. Create role middleware.
5. Create active user middleware.
6. Create migrations for all V1 tables.
7. Create models and relationships.
8. Create seeders for demo users, departments, positions, work locations, shifts, and employees.
9. Create admin and employee base layouts.
10. Create login page and redirect logic.

Success condition:

```text
Super Admin can login and access /admin/dashboard.
Employee Demo can login and access /employee/home.
Role separation works.
Database migrated and seeded successfully.
```

---

## 32. Final Production Definition of Done

CAP Attendance Pro V1 is considered production-ready when:

```text
All V1 modules are complete.
Admin can manage all master data.
Employee can check in/out using mobile GPS and selfie.
Attendance status is calculated correctly.
Reports and Excel export work.
Correction request and approval work.
Activity logs record critical actions.
Company settings work.
PWA is installable.
UI is clean and premium.
Role security is tested.
Upload security is tested.
Production .env is configured.
APP_DEBUG=false.
HTTPS active.
Database backup ready.
```

---

## 33. Recommended Version Naming

Use this internal versioning:

```text
v1.0.0 — Laravel Foundation
v1.1.0 — Auth + Role + Layout
v1.2.0 — Master Data HRD
v1.3.0 — Attendance Core GPS + Selfie
v1.4.0 — Attendance Report + Export
v1.5.0 — Correction Request + Activity Log
v1.6.0 — PWA + UI Polish
v1.7.0 — Production Hardening
v1.8.0 — Production Release Candidate
v1.9.0 — Production Stable
```

---

## 34. Important Product Warning

Do not overbuild early. The biggest risk is trying to build payroll, AI, face recognition, and project crew before the attendance core is stable.

Correct order:

```text
Stable login
Stable employee data
Stable shift/location
Stable attendance GPS/selfie
Stable report
Then payroll and premium modules
```

A broken attendance foundation will make payroll inaccurate. Therefore, V1 must be clean, tested, and production-safe before moving to V2.

---

## 35. Closing Direction

CAP Attendance Pro must be built as a serious commercial product, not a demo script. The architecture must support future SaaS, white-label branding, payroll, approval workflow, field crew operations, and AI insight.

The V1 execution must focus on one outcome:

**A company can use the system tomorrow to manage employee attendance from mobile phones with GPS, selfie, shift, location, and HRD reporting.**
