# AttendanceHub - AI Context Document > ⚠️ **STALE / SUPERSEDED (2026-08-23):** This document describes the project state from an > earlier phase and is outdated in many areas (device sync, attendance engine, phases status). > **Read `docs/SYNC_AND_CALC_ARCHITECTURE.md` first** — it is the current source of truth for > the device→DB pipeline, calculation engine, completed work, and the F1–F7 roadmap. > This file captures the current state of the project to enable continuing development in a new session. --- ## 1. Project Overview **AttendanceHub** is a multi-tenant attendance management system (سامانه جامع مدیریت حضور و غیاب) built with Laravel 12, Livewire 4, and Tailwind CSS. It manages personnel, organizational structure, shifts, attendance tracking, leave/mission requests, and reporting. --- ## 2. Tech Stack | Layer | Technology | |-------|-----------| | **Backend** | Laravel 12, PHP 8.2+ | | **Frontend** | Livewire 4, Tailwind CSS 4 (via CDN + Vite) | | **Database** | MySQL (XAMPP, database: `attendance_hub`) | | **Auth** | Laravel Auth + Spatie Laravel Permission (roles/permissions) | | **PDF Export** | barryvdh/laravel-dompdf | | **Excel Export** | maatwebsite/excel | | **Build** | Vite 7, laravel-vite-plugin | | **Multi-tenancy** | Custom (column-based `tenant_id` + global scopes) | --- ## 3. Architecture ### 3.1 Domain-Driven Structure The project uses a **Domain-driven folder structure** under `app/Domain/`: ``` app/ ├── Domain/ │ ├── Attendance/ # (empty - not implemented yet) │ ├── Audit/ # ✅ Implemented │ ├── Auth/ # ✅ Implemented │ ├── Correction/ # (empty - not implemented yet) │ ├── Device/ # (empty - not implemented yet) │ ├── Leave/ # (empty - not implemented yet) │ ├── Mission/ # (empty - not implemented yet) │ ├── Organization/ # ✅ Implemented │ ├── Reporting/ # (empty - not implemented yet) │ ├── Shared/ # ✅ Implemented │ ├── Shift/ # (empty - not implemented yet) │ └── Workflow/ # (empty - not implemented yet) ├── Http/ │ ├── Controllers/ # Only base Controller.php (no controllers used) │ ├── Livewire/ # Livewire components │ └── Middleware/ # TenantMiddleware └── Providers/ # AppServiceProvider (empty) ``` ### 3.2 Routing All routes are in `routes/web.php` and `routes/api.php`: - `/login` (guest) → Livewire login form - `/logout` (auth) → POST logout - `/dashboard` (auth + tenant) → Dashboard page - `/organization/tree` → Organization tree management - `/personnel` → Personnel list/management - `/devices` → Device management (Livewire CRUD) - `/shifts` → Shift management (placeholder) - `/attendance` → Attendance view (placeholder) - `/leave` → Leave requests (placeholder) - `/reports/monthly` → Monthly report (placeholder) - `POST /api/attendance/sync` → API endpoint for device sync - `GET /api/attendance/status` → API endpoint for device stats ### 3.3 Multi-Tenancy - **Column-based**: All domain tables have `tenant_id` foreign key - **Global Scope**: `BaseTenantModel` automatically filters by `tenant_id` from authenticated user - **Middleware**: `TenantMiddleware` validates user and tenant are active, shares `$currentTenant` to views - **No Teams feature** in Spatie Permission (teams = false) --- ## 4. Database Schema ### 4.1 Implemented Tables (with migrations) #### `tenants` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | name | string(255) | | | code | string(50) | unique | | settings | json | nullable | | is_active | boolean | default: true | | timestamps | | | #### `users` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | personnel_id | bigint | nullable, FK not defined | | username | string(50) | unique | | name | string(255) | | | password | string | hashed | | is_active | boolean | default: true | | last_login_at | timestamp | nullable | | remember_token | string | | | timestamps | | | Also creates `password_reset_tokens` and `sessions` tables. #### `audit_logs` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | user_id | FK → users | nullable, nullOnDelete | | auditable_type | string | polymorphic | | auditable_id | unsignedBigInteger | polymorphic | | action | string(50) | created/updated/deleted | | old_values | json | nullable | | new_values | json | nullable | | ip_address | string(45) | nullable | | user_agent | string(500) | nullable | | timestamps | | | #### `organization_nodes` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | parent_id | unsignedBigInteger | nullable (self-referencing) | | name | string(255) | | | code | string(100) | | | type | string(50) | organization/division/department/unit/team/position | | level | integer | default: 1 | | path | string(500) | materialized path (e.g., `/1/2/5/`) | | sort_order | integer | default: 0 | | is_active | boolean | default: true | | timestamps | | | #### `personnel` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | organization_node_id | FK → organization_nodes | cascadeOnDelete | | personnel_code | string(50) | unique per tenant | | first_name | string(100) | | | last_name | string(100) | | | national_code | string(20) | nullable | | phone | string(20) | nullable | | email | string(255) | nullable | | default_shift_id | unsignedBigInteger | nullable (FK not yet defined) | | group_id | string(50) | nullable | | device_user_id | string(50) | nullable | | status | enum | active/inactive/suspended | | hire_date | date | | | termination_date | date | nullable | | timestamps | | | #### `devices` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | name | string(255) | | | ip | string(45) | | | port | unsigned integer | default: 4370 | | brand | string(50) | default: zkteco | | model | string(100) | nullable | | serial_number | string(100) | nullable | | location | string(255) | nullable | | is_active | boolean | default: true | | last_sync_at | timestamp | nullable | | settings | json | nullable | | timestamps | | | | unique | (tenant_id, ip, port) | | #### `raw_attendance_logs` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | device_id | FK → devices | cascadeOnDelete | | personnel_code | string(50) | | | punch_time | timestamp | | | punch_type | enum | in/out | | raw_data | json | nullable | | is_processed | boolean | default: false | | processed_at | timestamp | nullable | | verify_mode | string(50) | nullable | | timestamps | | | | indexes | (tenant_id, is_processed), (tenant_id, personnel_code), (tenant_id, punch_time), (device_id, punch_time) | | #### `shifts` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | name | string(255) | | | code | string(50) | unique per tenant | | start_time | time | | | end_time | time | | | type | enum | regular/night/flexible | | grace_minutes_late | unsigned integer | default: 0 | | grace_minutes_early | unsigned integer | default: 0 | | is_active | boolean | default: true | | timestamps | | | #### `shift_assignments` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | personnel_id | FK → personnel | cascadeOnDelete | | shift_id | FK → shifts | cascadeOnDelete | | start_date | date | | | end_date | date | nullable | | is_temporary | boolean | default: false | | reason | text | nullable | | timestamps | | | #### `work_calendars` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | date | date | unique per tenant | | is_workday | boolean | default: true | | description | string(255) | nullable | | timestamps | | | #### `holidays` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | date | date | unique per tenant | | name | string(255) | | | is_recurring | boolean | default: false | | timestamps | | | #### `attendance_rules` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | name | string(255) | | | late_grace_minutes | unsigned integer | default: 15 | | early_grace_minutes | unsigned integer | default: 15 | | late_grace_enabled | boolean | default: true | | early_grace_enabled | boolean | default: true | | overtime_calculation | enum | auto/manual | | overtime_needs_approval | boolean | default: false | | max_overtime_minutes | unsigned integer | default: 0 | | incomplete_entry_default | enum | alert/absent/leave | | is_active | boolean | default: true | | settings | json | nullable | | timestamps | | | #### `daily_attendances` | Column | Type | Notes | |--------|------|-------| | id | bigint PK | | | tenant_id | FK → tenants | cascadeOnDelete | | personnel_id | FK → personnel | cascadeOnDelete | | shift_id | FK → shifts | cascadeOnDelete | | date | date | unique per (tenant, personnel, date) | | expected_start | time | nullable | | expected_end | time | nullable | | actual_start | time | nullable | | actual_end | time | nullable | | status | enum | present/absent/late/early_leave/incomplete/holiday/leave/mission/sick_leave | | late_minutes | integer | default: 0 | | early_leave_minutes | integer | default: 0 | | overtime_minutes | integer | default: 0 | | work_minutes | integer | default: 0 | | is_overtime_approved | boolean | default: false | | needs_review | boolean | default: false | | notes | text | nullable | | raw_logs | json | nullable | | timestamps | | | #### `permissions` / `roles` / `model_has_permissions` / `model_has_roles` / `role_has_permissions` Standard Spatie Permission tables. ### 4.2 Tables NOT Yet Migrated The following tables are referenced in Tenant model relationships but have NO migrations yet: - `leave_requests` (implied by the leave module) - `mission_requests` (implied by the mission module) - `correction_requests` (implied by the correction module) --- ## 5. Implemented Models | Model | Namespace | Extends | Notes | |-------|-----------|---------|-------| | `BaseTenantModel` | `App\Domain\Shared\Models` | `Model` | Abstract. Auto-sets `tenant_id`, global scope | | `User` | `App\Domain\Auth\Models` | `Authenticatable` | Uses `HasRoles`, NOT `BaseTenantModel` | | `Tenant` | `App\Domain\Organization\Models` | `Model` | NOT `BaseTenantModel` (tenants don't filter by tenant) | | `OrganizationNode` | `App\Domain\Organization\Models` | `BaseTenantModel` | Self-referencing tree with materialized path | | `Personnel` | `App\Domain\Organization\Models` | `BaseTenantModel` | Linked to org node and user | | `AuditLog` | `App\Domain\Audit\Models` | `BaseTenantModel` | Polymorphic auditable | | `Device` | `App\Domain\Device\Models` | `BaseTenantModel` | Attendance device (ZKTeco, etc.) | | `RawAttendanceLog` | `App\Domain\Device\Models` | `BaseTenantModel` | Raw punch data from devices | | `Shift` | `App\Domain\Shift\Models` | `BaseTenantModel` | Work shift definition | | `ShiftAssignment` | `App\Domain\Shift\Models` | `BaseTenantModel` | Personnel shift assignment | | `WorkCalendar` | `App\Domain\Shift\Models` | `BaseTenantModel` | Workday/holiday calendar | | `Holiday` | `App\Domain\Shift\Models` | `BaseTenantModel` | Holiday definitions | | `AttendanceRule` | `App\Domain\Attendance\Models` | `BaseTenantModel` | Attendance calculation rules | | `DailyAttendance` | `App\Domain\Attendance\Models` | `BaseTenantModel` | Daily attendance record | --- ## 6. Implemented Services | Service | Namespace | Methods | |---------|-----------|---------| | `OrganizationService` | `App\Domain\Organization\Services` | `getTree()`, `getRootNodes()`, `getChildren()`, `createNode()`, `updateNode()`, `deleteNode()`, `getAllNodes()` | | `PersonnelService` | `App\Domain\Organization\Services` | `paginate()`, `create()`, `update()`, `delete()`, `find()` | | `AuditService` | `App\Domain\Audit\Services` | `log()`, `created()`, `updated()`, `deleted()` (static methods) | | `DeviceService` | `App\Domain\Device\Services` | `paginate()`, `create()`, `update()`, `delete()`, `find()`, `getActiveDevices()`, `syncAttendanceLogs()`, `getDeviceStats()`, `getDeviceStatsForTenant()` | | `ShiftService` | `App\Domain\Shift\Services` | `paginateShifts()`, `createShift()`, `updateShift()`, `deleteShift()`, `findShift()`, `getActiveShifts()`, `assignShift()`, `updateAssignment()`, `deleteAssignment()`, `getPersonnelShiftForDate()`, `getShiftStats()` | | `CalendarService` | `App\Domain\Shift\Services` | `getCalendarForMonth()`, `isWorkday()`, `setWorkday()`, `paginateHolidays()`, `createHoliday()`, `updateHoliday()`, `deleteHoliday()`, `findHoliday()`, `getHolidaysForYear()`, `getUpcomingHolidays()` | | `AttendanceService` | `App\Domain\Attendance\Services` | `getDefaultRule()`, `updateRule()`, `getDailyAttendances()`, `getPersonnelMonthlyAttendance()`, `calculateDailyAttendance()`, `getAttendanceStats()`, `getMonthlyStats()` | | `ReportService` | `App\Domain\Reporting\Services` | `getDailyReport()`, `getMonthlyReport()`, `getPersonnelReport()`, `getSummaryReport()`, `exportToCsv()` | | `MonitoringService` | `App\Domain\Reporting\Services` | `getTodayStats()`, `getPresentList()`, `getAbsentList()`, `getRecentPunches()`, `getDeviceStatus()` | ## 6.1 Implemented Jobs | Job | Namespace | Purpose | |-----|-----------|---------| | `CalculateDailyAttendanceJob` | `App\Domain\Attendance\Jobs` | Queue job: auto-calculate daily attendance after device sync. Sets TenantContext, calls `AttendanceService::calculateDailyAttendance()` | --- ## 7. Implemented Livewire Components | Component | File | Status | |-----------|------|--------| | `Auth\Login` | `app/Http/Livewire/Auth/Login.php` | ✅ Full implementation | | `Auth\Logout` | `app/Http/Livewire/Auth/Logout.php` | ✅ Full implementation | | `Dashboard\Index` | `app/Livewire/Dashboard/Index.php` | ✅ Full dashboard with Chart.js, stats, wire:poll.30s | | `Dashboard\Monitoring` | `app/Livewire/Dashboard/Monitoring.php` | ✅ Live monitoring with tabs, wire:poll.5s | | `Organization\OrganizationTree` | `app/Http/Livewire/Organization/OrganizationTree.php` | ✅ Full CRUD | | `Organization\PersonnelTable` | `app/Http/Livewire/Organization/PersonnelTable.php` | ✅ Full CRUD with pagination/search | | `Device\DeviceList` | `app/Http/Livewire/Device/DeviceList.php` | ✅ Full CRUD with pagination/search | | `Shift\ShiftList` | `app/Http/Livewire/Shift/ShiftList.php` | ✅ Full CRUD with stats | | `Shift\Calendar` | `app/Http/Livewire/Shift/Calendar.php` | ✅ Calendar view + holiday management | | `Attendance\AttendanceView` | `app/Http/Livewire/Attendance/AttendanceView.php` | ✅ Daily/monthly view + calc trigger | | `Reports\MonthlyReport` | `app/Http/Livewire/Reports/MonthlyReport.php` | ✅ Monthly report + CSV export | | `Leave\LeaveRequestList` | `app/Http/Livewire/Leave/LeaveRequestList.php` | ❌ Placeholder | | `Reports\MonthlyReport` | `app/Http/Livewire/Reports/MonthlyReport.php` | ❌ Placeholder | --- ## 8. Implemented Blade Views | View | Status | |------|--------| | `components/layouts/app.blade.php` | ✅ Main layout with RTL sidebar | | `components/layouts/guest.blade.php` | ✅ Guest layout for login | | `livewire/auth/login.blade.php` | ✅ Full login form | | `livewire/auth/logout.blade.php` | ✅ Logout button | | `livewire/dashboard/index.blade.php` | ✅ Full dashboard with Chart.js, stats cards, wire:poll.30s | | `livewire/dashboard/monitoring.blade.php` | ✅ Live monitoring with tabs, wire:poll.5s | | `livewire/organization/organization-tree.blade.php` | ✅ Full tree view with modals | | `livewire/organization/personnel-table.blade.php` | ✅ Full table with modals | | `livewire/device/device-list.blade.php` | ✅ Full table with modals | | `livewire/shift/shift-list.blade.php` | ✅ Full table with stats | | `livewire/shift/calendar.blade.php` | ✅ Calendar view + holiday management | | `livewire/attendance/attendance-view.blade.php` | ✅ Daily/monthly view + calc modal | | `livewire/reports/monthly-report.blade.php` | ✅ Monthly report with stats + CSV export | | `reports/monthly-pdf.blade.php` | ✅ PDF view for monthly report | | `reports/daily-pdf.blade.php` | ✅ PDF view for daily report | | `livewire/leave/leave-request-list.blade.php` | ❌ "در حال توسعه..." | | `livewire/reports/monthly-report.blade.php` | ❌ "در حال توسعه..." | --- ## 9. Permissions (from DatabaseSeeder) ``` view_personnel, create_personnel, update_personnel, delete_personnel, view_organization, manage_organization, view_devices, manage_devices, sync_devices, view_shifts, manage_shifts, view_attendance, manage_attendance, calculate_attendance, view_leave, create_leave, approve_leave, view_mission, create_mission, approve_mission, view_correction, create_correction, approve_correction, view_reports, export_reports, view_rules, manage_rules, view_users, manage_users, manage_tenant ``` ### Roles: - **system_admin**: All permissions - **hr_manager**: Most permissions (no manage_users, manage_tenant) - **department_manager**: View-only + approve leave/mission/correction - **personnel**: view_attendance, create_leave, create_mission, create_correction --- ## 10. Seed Data (DatabaseSeeder) - Default tenant: "سازمان پیش‌فرض" (code: DEFAULT) - Settings: `default_late_grace: 5`, `default_early_grace: 5`, `overtime_calculation: auto`, `work_week_days: [0,1,2,3,6]` - Org structure: سازمان پیش‌فرض → امور اداری - Admin user: `admin` / `123456` (role: system_admin) - HR user: `hr001` / `123456` (role: hr_manager) - Test device: "ورودی اصلی" (IP: 192.168.1.100, port: 4370, brand: zkteco, model: K40) - Default shifts: شیفت صبح (08:00-17:00), شیفت شب (20:00-08:00), شیفت انعطاف‌پذیر (07:00-19:00) - Iranian holidays for current year (نوروز, جمهوری اسلامی, اربعین, تاسوعا, عاشورا) --- ## 11. Key Technical Decisions 1. **Domain-driven folder structure** over standard Laravel `Models/` folder 2. **Column-based multi-tenancy** (not database-per-tenant) via `tenant_id` + global scopes 3. **No traditional controllers** - all UI via Livewire components (except API endpoints) 4. **Spatie Permission** for RBAC (without teams feature) 5. **Custom audit logging** via `Auditable` trait + `AuditService` (not using spatie/activitylog) 6. **Materialized path** pattern for organization tree (`/1/2/5/`) 7. **Tailwind CSS via CDN** in layouts (also has Vite build configured) 8. **Auto-create user account** when creating personnel (username = personnel_code, password = 123456) 9. **Personnel relationship to User** is one-to-one (Personnel hasOne User) 10. **User model** extends `Authenticatable` directly (not `BaseTenantModel`) because users need to access across tenants during auth 11. **API endpoint** for device sync with API key authentication 12. **Hybrid architecture** for device sync: Laravel API receives data, Windows Service polls/pushes from devices --- ## 12. Known Issues & Bugs 1. **Routes reference non-existent views**: `routes/web.php` uses `view('pages.dashboard')`, `view('pages.organization-tree')`, etc. but `resources/views/pages/` directory does not exist. These pages are actually served via Livewire components, so the routes likely work because Livewire intercepts or the views are registered differently. **This needs investigation.** 2. **Personnel→User FK not defined**: `personnel_id` in `users` table has no foreign key constraint defined in the migration. 3. **Default shift_id not FK**: `default_shift_id` in `personnel` table is `unsignedBigInteger` but has no foreign key constraint. 4. **Tenant model not using BaseTenantModel**: `Tenant` extends `Model` directly, which is correct (tenants shouldn't be scoped), but it's worth noting. 5. **Dashboard is static**: Dashboard shows `-` for all stats (no real data queries). 6. **No git commits**: The repo has no commits yet (`main` branch is empty). --- ## 13. What Was Being Worked On (Previous Session) Based on the code analysis, the previous session completed: 1. ✅ Project setup (Laravel 12, packages, configuration) 2. ✅ Database migrations (tenants, users, audit_logs, organization_nodes, personnel, permissions) 3. ✅ Domain layer architecture (folder structure for all modules) 4. ✅ Core models (User, Tenant, OrganizationNode, Personnel, AuditLog, BaseTenantModel) 5. ✅ Services (OrganizationService, PersonnelService, AuditService) 6. ✅ Multi-tenancy middleware and global scopes 7. ✅ Authentication (Login, Logout Livewire components) 8. ✅ Organization management (full CRUD with tree view) 9. ✅ Personnel management (full CRUD with pagination) 10. ✅ Audit logging system (trait + service) 11. ✅ RBAC permissions and roles (seeder) 12. ✅ Main layout with sidebar navigation 13. ✅ Placeholder pages for Device, Shift, Attendance, Leave, Reports --- ## 14. Business Rules & Requirements (from original prompt) ### Device Connector Requirements - Must support multiple device brands (plugin architecture) - ZKTeco is the current device brand - Real-time data collection: Push + Polling modes - UDP protocol on port 4370 - Raw device data stored without transformation, then normalized ### Attendance Calculation Rules - **Grace period**: Configurable by manager, max 15 minutes (can be enabled/disabled) - **Overtime**: Auto-calculated, with option for manual approval per system setting - **Incomplete entries**: System generates alerts for missing punches - **Work week**: Configurable (default: Saturday-Wednesday + Saturday = [0,1,2,3,6]) ### Shift Requirements - Multiple shift types supported - Temporary shift changes allowed (e.g., due to weather/heat) - Shift rules can change for specific days ### Organization Structure - Dynamic, up to 5 levels deep - Types: organization, division, department, unit, team, position - Materialized path pattern for hierarchy ### Leave/Mission/Correction - Hierarchical approval chain (direct manager → up to CEO level) - Leave types: various (to be defined) - Mission (مأموریت): business trips - Correction: attendance correction requests ### Multi-tenancy - Multiple organizations supported from day one - Column-based isolation --- ## 15. Official Roadmap (11 Phases) ``` فاز ۰: Setup + Auth (با کد پرسنلی) + Multi-tenant + Audit ✅ COMPLETED فاز ۱: Organization + Personnel CRUD ✅ COMPLETED فاز ۲: Device + ZKTeco Connector + Raw Data ⚠️ IN PROGRESS (2A done) فاز ۳: Shift + Calendar + Holidays ✅ COMPLETED فاز ۴: Attendance Engine (هسته اصلی) ✅ COMPLETED فاز ۵: Reporting پایه + Export ✅ COMPLETED فاز ۶: Leave + Mission + Workflow ✅ COMPLETED فاز ۷: Correction + Recalculation ✅ COMPLETED فاز ۸: **Real-time Monitoring (مانیتورینگ لحظه‌ای)** ✅ COMPLETED فاز ۹: Reporting پیشرفته + Dashboard ✅ COMPLETED فاز ۱۰: تست + بهینه‌سازی ⬜ NOT STARTED ``` **Each phase follows:** Migration → Model → Service → Action → Livewire → View ### Phase 2 Details: Device + ZKTeco (Split into 2A + 2B) #### Phase 2A (Laravel Side - COMPLETED): - ✅ `devices` migration and model - ✅ `raw_attendance_logs` migration and model - ✅ `DeviceService` with full CRUD and sync logic - ✅ `POST /api/attendance/sync` API endpoint - ✅ `GET /api/attendance/status` API endpoint - ✅ Device management Livewire components (full CRUD) - ✅ Test device seeder #### Phase 2B (Windows Service - NOT STARTED): - Windows Service to poll/push data from ZKTeco device to Laravel API - Can be written in C# or PHP - User has prior experience with this ### Phase 3 Details: Shift + Calendar - Shift model (name, code, start_time, end_time, type) - ShiftAssignment model (personnel_id, shift_id, date range) - WorkCalendar model (tenant_id, date, is_workday) - Holiday model (tenant_id, date, name) - ShiftService, CalendarService ### Phase 4 Details: Attendance Engine - AttendanceRule model (late_grace, early_grace, overtime_rules) - DailyAttendance model (personnel_id, date, expected_in, actual_in, actual_out, status) - AttendanceCalcCommand (process raw logs → daily status) - Statuses: present, absent, late, early_leave, incomplete, holiday, leave, mission --- ## 16. ZKTeco Research Findings | Library | Stars | License | Notes | |---------|-------|---------|-------| | `nurkarim/zkteco-sdk-php` | 54 | GPL-2.0 | UDP protocol, ZKLibrary class | | `coding-libs/zkteco-php` | 19 | MIT | Laravel-ready, **non-production** | | `mlrahman/ZKTeco_Attendance_Access_Using_PHP` | 84 | — | Most popular | **Conclusion:** None are production-ready. Custom connector needed based on ZKTeco UDP protocol. **ZKTeco Protocol:** - UDP port: 4370 (fixed on device) - Operations: connect, disableDevice, enableDevice, getUsers, getAttendances, disconnect - Data format: binary --- ## 17. Next Steps (Immediate) **CURRENT PHASE: فاز ۸ + ۹ — COMPLETED** All phases through 9 are complete. Remaining work: 1. **Phase 2B**: Create Windows Service for device sync (optional, user deferred) 2. **Phase 10**: Tests + optimization 3. Run `php artisan migrate:fresh --seed` to apply all migrations and seed data 4. Start queue worker for auto-calc: `php artisan queue:work` ### API Export Endpoints: ```bash # Export daily report as PDF curl "http://your-domain/api/reports/export/pdf?type=daily&date=2026-08-13" -o daily_report.pdf # Export monthly report as PDF curl "http://your-domain/api/reports/export/pdf?type=monthly&year=1405&month=5" -o monthly_report.pdf # Export as Excel curl "http://your-domain/api/reports/export/excel?year=1405&month=5" -o report.xlsx # Export as CSV curl "http://your-domain/api/reports/export/csv?year=1405&month=5" -o report.csv ``` ### API Usage Example: ```bash # Sync attendance logs curl -X POST http://your-domain/api/attendance/sync \ -H "Content-Type: application/json" \ -d '{ "device_ip": "192.168.1.100", "device_port": 4370, "api_key": "test_api_key_12345", "logs": [ { "personnel_code": "001", "punch_time": "2026-08-13 08:00:00", "punch_type": "in" } ] }' # Check device status curl "http://your-domain/api/attendance/status?api_key=test_api_key_12345" ``` --- ## 18. Environment Configuration ```env APP_NAME=AttendanceHub APP_LOCALE=fa DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=attendance_hub DB_USERNAME=root DB_PASSWORD= DB_SOCKET=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock SESSION_DRIVER=database QUEUE_CONNECTION=database ``` --- ## 19. Composer Scripts - `composer setup` - Full project setup (install, migrate, npm, build) - `composer dev` - Start all dev services (server, queue, logs, vite) - `composer test` - Run tests --- *Last updated: 2026-08-15 (Phase 10: tests + optimization completed)* --- ## 20. Context Management Strategy (جلوگیری از پر شدن Context) ### مشکل در session قبلی، حجم زیاد context (بیش از 14 میلیون token cache read) باعث شد session قابل ادامه نباشد. ### راه‌حل‌ها #### 1. استفاده از این فایل به عنوان Single Source of Truth - **هر session جدید** ابتدا این فایل را بخواند - **هر session جدید** این فایل را به‌روز کند - هرگز کد قبلی را دوباره نخوانید مگر اینکه واقعاً نیاز باشد #### 2. قانون خواندن فایل ``` # در هر session جدید: 1. docs/AI_CONTEXT.md را بخوانید (این فایل) 2. فقط فایل‌هایی که نیاز به تغییر دارند را بخوانید 3. از خواندن فایل‌های بی‌نیاز خودداری کنید 4. بعد از اتمام کار، فایل را به‌روز کنید ``` #### 3. محدودیت حجم هر Session - هر session حداکثر **یک فاز** را پیاده‌سازی کند - بعد از اتمام هر فاز، گزارش دهد و فایل را به‌روز کند - session جدید برای فاز بعدی باز شود #### 4. فشرده‌سازی اطلاعات - از جداول به جای متن طولانی استفاده شود - کدهای تکراری حذف شوند - فقط تغییرات ثبت شود، نه کل کد