# AttendanceHub — Device-to-DB Pipeline & Implementation Log > Single source of truth for HOW attendance data flows from ZKTeco devices into MySQL, > how calculations work, what was implemented and why, and what remains. > Read this BEFORE touching `ZKTecoSyncService/`, `DeviceSyncService`, or `AttendanceService`. > Supersedes stale sections of `docs/AI_CONTEXT.md` (that file predates the 2026-08 rewrite). > > Last updated: 2026-08-23 (v1.4.0 service, calc engine v2) --- ## 1. Component Map ### Windows Service — `ZKTecoSyncService/` (.NET 10 Worker, v1.4.0) Deployed binary lives in `ZKTecoSyncService/publish/` (Windows Service name: `ZKTecoSyncService`, Auto start, recovery = restart after 5s/10s/30s crashes via `sc failure`). | File | Responsibility | |---|---| | `Program.cs` | Host builder. Startup waits for Laravel API (retry every 15s, never hard-exits). `SyncWorker` loops: refresh device list every 30s. | | `Services/ZKTecoProtocol.cs` | zkemkeeper COM wrapper: `Connect_Net`, `EnableDevice(false)` during work, `ReadAllLogs`, `GetLogCount()` (light probe), `GetDeviceInfo()` (heartbeat payload), **Real-Time push**: `RegEvent(machine,65535)` + `OnAttTransactionEx` handler -> callback. | | `Services/DeviceConnectionService.cs` | One `DeviceConnection` thread per device. Live `ConcurrentQueue` + `DrainLiveQueueAsync` (flush every **1.5s**, batch<=500). Polling fallback with log-count check (skip read if count unchanged). `FilterForSend`: only punches newer than `lastSentMax - 72h`. State seeding from server (`device_sync_states`) at startup minus 72h. Full re-sync every **6h** when push active. Backoff 5/15/45/120s on errors. | | `Services/LaravelApiService.cs` | HttpClient with Bearer token. `GET /api/v1/devices`, `POST /api/v1/sync/batch` (chunks of 200), `POST /api/v1/sync/heartbeat`, `GET/PUT /api/v1/sync/state/{id}`. | | `Services/OfflineBufferService.cs` | SQLite (WAL) durable buffer, cap 10000. Cleanup is TWO-STAGE (`DELETE ... LIMIT` is illegal in SQLite — this exact bug crashed the service on 2026-08-22). Stage1 drops oldest synced; stage2 (buffer still full) drops oldest unsynced. | | `appsettings.json` | BaseUrl `http://localhost/AttendanceHub/public`; Bearer token (git-ignored; history scrubbed 2026-10-15; **rotated 2026-10-16 — the database keeps only its sha256**, plaintext column NULL; next rotation: runbook in §9); Poll 30s / Heartbeat 60s. | **Interop gotcha:** `OnAttTransactionEx` delegate signature = `(string EnrollNumber, int IsInValid, int AttState, int VerifyMethod, int Y,int M,int D,int H,int Mi,int S, int WorkCode)`. Never throw inside the COM event handler; it must only enqueue. ### Laravel side | File | Notes | |---|---| | `routes/api.php` | `/api/v1/*` behind `sync.auth` middleware. LEGACY endpoints `/attendance/sync|status` and `/reports/export/*` still exist. The export endpoints are behind the `auth` session guard since 2026-10-15 (F5 closed, covered by `tests/Feature/ReportExportAuthTest.php`). | | `App\Http\Middleware\SyncAuthMiddleware` | Resolves the Bearer against `tenants.api_token_hash` (sha256) when that column exists, else a constant-time `hash_equals` compare of `tenants.api_token` — **both paths work in every intermediate state**, so a half-done deployment can never break ingest (`tests/Feature/SyncAuthMiddlewareTest.php`). Migration `2026_10_16_000001` ran live 2026-10-16: real token 200, wrong token 401, and the running V2 service kept reading through the switch. | | `Domain\Device\Services\DeviceSyncService` | Core ingest (see §3). | | `Domain\Device\Models\RawAttendanceLog` | Table `raw_attendance_logs`, **UNIQUE KEY `uq_device_personnel_time` (device_id, personnel_code, punch_time)`** — the idempotency cornerstone. | | `Domain\Device\Models\DeviceSyncState` | Per-device last_read_time/log_count; survives service restarts. | --- ## 2. Data Flow — Steady State (the "live" path) ``` [Person punches] | device PUSHES event instantly over persistent TCP (RegEvent mode) — NO polling involved v C# handler enqueues (microseconds) | Drain loop flushes queue every 1.5s -> POST /api/v1/sync/batch | Laravel: sanitize row -> INSERT IGNORE (single multi-row stmt) | ^ duplicates silently dropped by unique key v row lands in raw_attendance_logs ................ total latency punch->DB ~= 2-4s | | | +--> Monitoring UI (wire:poll.5s) | reads RAW table directly (live!) +--> Calculation update, two modes: A) INLINE FAST-PATH (v1.5 logic): if batch is small (<=20 imported), single date == today, and unprocessed-today count <= 300 -> AttendanceService::calculateDailyAttendance runs SYNCHRONOUSLY in the same request. daily_attendances updates within the same second. Response carries `"calc":"inline"`. Only the punchers of this batch are recalculated (engine processes unprocessed logs only) so cost is O(batch), not O(organization). B) QUEUED (bulk/history): otherwise CalculateDailyAttendanceJob dispatched per distinct valid date, deduped via cache key `ah:calc:{tenant}:{date}` TTL 10 min. Guard failures / exceptions always fall back to (B). API never fails because of calc. Tests: tests/Unit/DeviceSyncFastPathTest.php locks all four decision branches. ``` Fallback paths (all overlap safely thanks to server-side dedupe): * Device firmware without RegEvent support -> auto-fallback to smart polling (count-check; latency ~30s+read). * ANY device: full memory re-sync every 6h (reconciliation) + after every reconnect/startup. * Full read always filtered client-side: only punches newer than `last_sent_max - 72h` are SENT (protects against device clock rollback; server dedupe covers the rest). ## 3. Ingest Logic — `DeviceSyncService::receiveBatchLogs()` Per-row pipeline: 1. Trim personnel_code; reject empty -> skipped. 2. `punch_time` normalization: Carbon instance passthrough; string; Jalali detection (`year < 1500`) -> converted via Morilog `Jalalian::fromFormat('Y-m-d H:i:s')`; parse failure -> skipped (logged). 3. **Clock-skew guard**: valid window = `[now - 400 days , now + 26 hours]`. Outside window => row IS STORED but `raw_data.clock_skew = true` and its date does NOT participate in calculation-job dispatch (no data loss, no poisoned aggregates). 4. Collect rows -> `INSERT IGNORE` in chunks of 500 (DB table). Returns TRUE imported count. 5. If imported>0: dispatch `CalculateDailyAttendanceJob` per distinct valid date, gated by `Cache::add("ah:calc:{tenant}:{date}", ttl: 10min)` — prevents job storms. 6. `device_sync_log` row per batch (success/failed, received/imported/skipped counters). 7. Heartbeat path updates `devices.connection_status/last_seen_at/firmware/user_count/log_count`. Why INSERT IGNORE (not SELECT-then-INSERT): one statement per batch, uniqueness enforced by the engine's B-tree (no extra query per record, no race conditions, duplicate-safe under concurrency). ## 4. Calculation Engine — `AttendanceService` (rewritten 2026-08-23) ### Batch path: `calculateDailyAttendance(date)` 1. Fetch ALL unprocessed logs in window `[D 00:00 , D+1 12:00)` (the +12h tail serves overnight shifts), grouped by personnel_code. ONE query. 2. Preload once: personnel (+defaultShift), shift assignments for D (`resolveShiftMap`: assignment wins, defaultShift fallback), approved leaves map, approved missions map. No N+1. 3. Per person: `buildDailyRecord()` -> `[row|null, consumedLogIds]`. 4. Bulk `upsert` into `daily_attendances` (unique `tenant_id+personnel_id+date`), chunks 500. 5. Bulk mark processed (`is_processed=1`), chunks 500, retry x3 then per-id fallback (transient MariaDB 1062 possible under concurrent import pressure — self-heals). 6. Errors logged (`Log::warning`, cap 20/run) — NOT silent anymore. 7. `backfillAbsentRecords()`: for PAST dates (or today >= 23:30), active personnel with a resolvable shift and ZERO punches get an `absent` row (upsert, idempotent). ### Shared core: `computeCoreDay()` — used by BOTH batch and realtime paths * Crossing shift (`end_time <= start_time`): expectedEnd += 1 day; actualEnd = last OUT in `[actualStart .. expectedEnd + 4h]` including next-day-morning tails; legacy tolerance: if none, fall back to last same-day OUT even if chronologically before actualStart. * Regular shift: actualStart = first IN of day; actualEnd = last OUT of day. * Late/early via rule grace minutes; overtime = expectedEnd vs actualEnd (cap max_overtime_minutes); NOTE `$workMinutes` param unused in overtime formula (known minor issue). * Full-day leave/mission overrides status & zeroes minutes; half-day deducts from workMinutes. * `autoDetectPunchTypes()`: if all logs share one type, first becomes IN, rest become OUT (mutates model attrs pre-persist; snapshot written to `daily_attendances.raw_logs` reflects detection). ### Realtime path: `calculateRealTimeForDay()/ForPersonnel()` Same helpers (assignment-aware shift + leave/mission aware + midnight-capable). Output shape preserved for existing Blade/Livewire views (`punch_details`, verify-mode counts, etc.). Statuses: present, late, early_leave, incomplete, absent, holiday, leave, mission, sick_leave. --- ## 5. Database Facts * `raw_attendance_logs` secondary indexes (7): `uq_device_personnel_time` (UNIQUE), `(tenant_id,is_processed)`, `idx_personnel_code`, `ral_tenant_processed_time_idx(tenant,is_processed,time)`, `ral_tenant_time_idx(tenant,time)`, `idx_punch_time_date(time,device)`, `idx_device_punch(device,time)`. -> After import stabilizes, drop redundant ones (`(tenant_id,is_processed)` is a prefix of the composite; overlaps elsewhere) — write-heavy table. * `daily_attendances` UNIQUE `(tenant_id,personnel_id,date)` powers the bulk upsert. * Migrations were fixed to be SQLite-portable (tests run sqlite :memory:): `2026_08_16_000001`, `2026_08_16_000002`, `2026_08_21_000001` previously used MySQL-only SQL (`ALTER TABLE ADD INDEX`, `DELETE t1 JOIN`, `SHOW INDEX`) which broke the ENTIRE test suite. * Queue = database driver. Schedule (`routes/console.php`): nightly `attendance:calculate --tenant=1` at 23:59; worker EVERY MINUTE `queue:work --stop-when-empty --max-time=3600 --tries=3 --timeout=800`. `.env`: `DB_QUEUE_RETRY_AFTER=300`. * `phpunit.xml` has a test APP_KEY injected (Feature tests previously died on MissingAppKey). ## 6. Operational Snapshot (2026-08-23) * 41 active devices, ~4774 personnel, single tenant id=1. * DB was TRUNCATED (raw/daily/device_sync_logs/device_sync_states/jobs/failed_jobs/cache) and fully rebuilt from device memories (owner decision — old data had era-garbage). * Initial mass import may take hours; during it: many concurrent multi-row inserts, DB slow for ad-hoc analytical queries. Avoid `COUNT(*) WHERE created_at>=...` scans mid-import (created_at has NO index) — use `ORDER BY id DESC LIMIT n` instead. * **Clock audit method**: `skew_min = AVG(TIMESTAMPDIFF(SECOND,created_at,punch_time))/60 - 210` (created_at is UTC, server TZ = Tehran +3:30; subtract batching delay tolerance). Live-verified OK: dev 11, 33 (~1min), 15, 64. Old-stamp residue (past malfunction eras, current clock likely fine — owner physically verified most): dev 2,5,6,10,12,14,17,19,22,25,27,28,29,35,36,66; definite bad-era stamps incl. year **2033**: dev 4,20,37,38. * No-data-since-restart devices needing field check: 1,3,9,13,16,18,21,23,24,26,30,31,32,34,67. * Windows Event Log provider prints WARNING+ by default — Information logs (Connected / "Real-Time events ENABLED") are invisible there; run `publish\start.bat` in console to see them. ## 7. Completed Phases (chronological) | Phase | Scope | Result | |---|---|---| | **P0 Diagnose** | Root-caused: service crash (OfflineBuffer `DELETE..LIMIT`), queue flood (upsert counted UPDATEs as imported -> job-per-date storm, ~7.5k jobs/7.5k distinct dates), MaxAttemptsExceeded (calc job >90s vs retry_after), night-shift broken, realtime/batch divergence, silent error swallowing, missing indexes, MySQL-only migrations killing tests. | Full diagnosis delivered | | **P1 Ingest rewrite** | `insertOrIgnore` + true counts; per-row sanitize; Jalali kept; clock-skew guard; dispatch dedupe (cache TTL 10min); race-free single-log path. | Flood eliminated structurally | | **P2 Calc engine v2** | Bulk pipeline (no giant transaction / 113k single UPDATEs), N+1 removed, midnight-crossing supported, realtime unified with batch, absent backfill, logged errors, resilient markProcessed. | Verified vs real data (personnel 1626: in,in -> 07:29/12:19/290min correct) | | **P3 Infra & tests** | New indexes migration; 3 portable migrations; MonitoringService fixes (missing `use DB`, ambiguous tenant_id, Carbon type-hint, test fixture connection_status); APP_KEY for tests; worker flags; retry_after=300. | **93/93 tests green** (was 84 errors) | | **P4 C# v1.3 -> v1.4** | Buffer SQL fix + staged cleanup; count-check skip; 72h FilterForSend; state seeding; MarkAsSynced by sent-count; Task.Run guards; API wait-loop; **REAL-TIME PUSH** (RegEvent/OnAttTransactionEx) + 1.5s drain; 6h conditional full-resync; light GetLogCount; republished; restarted; `sc failure` auto-restart configured. | Live punches land in ~2-4s (verified dev 33/15) | | **P5 Verify & handover** | E2E ingest test (inserted + cleaned); clock-audit methodology; this document. | Owner informed | ## 8. Roadmap (agreed priorities) * **F1 — Import completion watch** *(in progress)*: confirm all 41 devices finish history import & deliver today-dated punches; field-fix the offline list (§6). * **F2 — Clock hygiene tool**: one-shot C# utility reusing `ZKTecoProtocol`: connect each device -> `GetDeviceTime` report vs server -> optional `SetDeviceTime` alignment; later schedule monthly. Kills the skew problem permanently (skew-guard stays as belt-and-suspenders). * **F3 — Memory policy**: alert when heartbeat `log_count` > 80% of model capacity; admin-triggered CONDITIONAL clear (requires coverage proof: delivered_max >= device newest AND counts reconcile); SDK delete is all-or-nothing -> execute off-hours. Do NOT clear blindly (memory is the DR source). * **F4 — Backup & ops — nightly dump DONE 2026-10-16**, offsite copy still open: `php artisan backup:database` (scheduled `dailyAt('02:30')` in `routes/console.php`, `--single-transaction` so it never blocks the punch path, gzip, keep 14). Before it, nothing on this machine had ever dumped `attendance_hub` — backups/ held six C# files from September. First dump: `backups/db/attendance_hub_2026-10-16_101724.sql.gz` (131 MB → 7.5 MB in 10.6 s), then **restore-proven**: loaded into a scratch schema, all 71 tables row-for-row identical (260,079 raw punches / 5,079 personnel / 67 devices), scratch dropped afterwards (`tests/Feature/BackupDatabaseCommandTest.php` covers dump content, rotation, failure path). Still open: offsite copy (no remote on this box), disk-space watch, laravel.log rotation. * **F5 — Security hardening** (from full-project audit) — **closed 2026-10-15/16**: * `/api/reports/export/*` behind the `auth` session guard (2026-10-15, verified live: guest 401 for JSON / 302 to `/login` otherwise, signed-in still gets the CSV) plus `throttle:60` per user (`ReportExportAuthTest`, `ExportThrottleTest`). * login brute-force: 5 attempts per username+IP per 60 s, counter cleared on success (`tests/Feature/LoginThrottleTest.php`). * token at rest: `tenants.api_token_hash` (sha256, unique, backfilled by `2026_10_16_000001`) + `hash_equals` fallback (`SyncAuthMiddlewareTest`); verified live after the migration — the running V2 service kept authenticating through the switch. **Rotated 2026-10-16 23:06**: the plaintext column is now NULL and the database keeps only the sha256, so a mysqldump no longer carries a usable credential — the old token returns 401, the new one 200, and the V2 service resumed reading seconds after the restart (all four live devices reading again 25–62 s later). * cross-tenant IDOR: all 33 browser-reachable fetch-by-id sites re-filter on `tenant_id` (Leave/Mission/Shift/Calendar/Organization/Personnel/Device/Workflow/ Attendance + `OrganizationTree::openEditModal`); the 15 unfiltered sites are guarded, filtered on the next line, inner queries of an already-scoped loop, or installation-wide monitor aggregates — `tests/Feature/CrossTenantIsolationTest.php` proves refusal for a foreign tenant *and* unchanged behaviour for a same-tenant one; full-suite failure set before/after was identical (0 regressions). * seeder safety: `TestDataSeeder` refuses production *and* any database already holding a punch (`SEED_TEST_DATA=true` is the escape hatch); roles/permissions extracted into the idempotent `PermissionSeeder`, run live 2026-10-16 — production went from **0 roles / 0 permissions** (which had been hiding the admin's whole sidebar and blocking correction approval, every `can()` returning false) to `system_admin` on the only user (`SeederSafetyTest`, incl. roleless-user-denied). * hardcoded `123456` gone: `PersonnelService::create()` mints a per-account random temporary password shown once (`PersonnelAccountPasswordTest`). * Still open inside F5: policies/`can()` coverage on Livewire actions (the permission model now exists, but choosing which UI needs which gate is a product decision) and mass-assignment of `tenant_id` in update paths. * **F6 — Perf polish (post-import)**: trim redundant raw-log indexes; optionally lower `CALC_DISPATCH_TTL_MINUTES` for fresher aggregates; purge/archive raw logs older than N years. * **F7 — Product completion**: Leave/Mission/Correction modules have backend models/services but Livewire lists are placeholders; Workflow inbox; user management UI; move hardcoded fa strings to translation files. ## 9. Quick Recipes ```powershell # Rebuild & redeploy service after code change cd G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService dotnet publish -c Release -o publish Start-Process powershell -Verb RunAs -ArgumentList '-Command','Restart-Service ZKTecoSyncService' # Watch live ingestion (safe query even mid-import) mysql -u root attendance_hub -e "SELECT id,device_id,personnel_code,punch_time,created_at \ FROM raw_attendance_logs ORDER BY id DESC LIMIT 10" # Run tests (must stay green) php vendor\phpunit\phpunit\phpunit ``` ### Bearer-token rotation runbook (F5 — used 2026-10-16; keep for the next rotation) Three places hold the token and must change together: the `tenants` row (kept as **hash only** after rotation), `ZKTecoSyncService/appsettings.json`, and every `phase1.device.json` — the live V2 reads `ZKTecoSyncService-V2/publish/config/phase1.device.json`, not the source copy. **Rotated 2026-10-16 23:06** by following this runbook: a 26-second window (stop → rotate → patch all 15 discovered config copies byte-for-byte → API gate new=200/old=401 → start → `--check` exit 0). Config snapshots — the rollback path — are in `backups/rotation_20261016/` (they hold the now-dead old token); the window transcript was deleted afterwards because it contained the printed token. One operational fact to remember: the service runs as LocalSystem and its DACL grants interactive users no stop/start rights (`sc sdshow`), so the stop/start half must come from a human-triggered elevated window — a remote agent cannot click the UAC consent for you. ```powershell # 1. Stop the sync so nothing authenticates against a half-changed token Get-Service ZKTecoSyncService | Stop-Service # V1; stop the V2 runner the same way # 2. Mint the replacement: prints the new token ONCE, stores only its sha256, # nulls the plaintext column, and marks every config copy STALE/OK/CHECK cd G:\WEB-SERVER\htdocs\AttendanceHub php artisan tenant:rotate-token # 3. Paste the printed token into each STALE/CHECK file (JSON value only), then # 4. Start the services and confirm database + configs agree (exit 0) Get-Service ZKTecoSyncService | Start-Service php artisan tenant:rotate-token --check ``` `--check`'s exit code is the contract: **0 = the database holds only hashes and every config file verifies against them; 1 = something still needs you.** Never "fix" a non-zero `--check` by re-running the rotation — that mints yet another token over the one you were about to paste. If a token ever leaks, the only recovery is exactly this sequence; the leaked value stops authenticating the moment step 2 commits (monitoring would otherwise flag the 401 within 45–90 min). Rotation is intentionally a stop-services operation, which is why it is run on your word rather than by the scheduler. Rules of thumb: * Never reintroduce SELECT-before-INSERT dedupe; rely on the unique key + INSERT IGNORE. * Never delete device memory without F3 coverage proof. * Any new migration MUST work on SQLite (tests) and MariaDB (prod) — Schema Builder only. * Tenant isolation: every `withoutGlobalScope()` usage MUST be paired with explicit `where('tenant_id', TenantContext::getTenantId())` — enforced across all 33 browser-reachable sites on 2026-10-16 (`tests/Feature/CrossTenantIsolationTest.php`). The 15 sites deliberately left unfiltered are guarded by `assertDeviceBelongsToTenant()`, filtered on the very next line, per-device queries inside an already-tenant-scoped loop, or installation-wide monitor/upload aggregates. Re-run the audit script before adding another `withoutGlobalScope()` call.