# ATTENDANCE ENGINE — DESIGN AUDIT **Date:** 2026-08-29 **Status:** READ-ONLY AUDIT — NO CODE CHANGES **Phase:** 2 — Attendance Engine Redesign --- ## A) CURRENT ATTENDANCE ARCHITECTURE ### A1. Components | Component | File | Lines | Role | |-----------|------|-------|------| | AttendanceService | `app/Domain/Attendance/Services/AttendanceService.php` | 1431 | Core calculation engine | | CalculateDailyAttendanceJob | `app/Domain/Attendance/Jobs/CalculateDailyAttendanceJob.php` | 50 | Async dispatch wrapper | | DailyAttendance | `app/Domain/Attendance/Models/DailyAttendance.php` | 146 | Output model (1 row/person/day) | | AttendanceRule | `app/Domain/Attendance/Models/AttendanceRule.php` | 44 | Configurable rules | | DeviceSyncService | `app/Domain/Device/Services/DeviceSyncService.php` | — | Triggers calculation after ingestion | | LeaveService | `app/Domain/Leave/Services/LeaveService.php` | — | Writes leave records to daily_attendances | | MissionService | `app/Domain/Mission/Services/MissionService.php` | — | Writes mission records to daily_attendances | | CalendarService | `app/Domain/Shift/Services/CalendarService.php` | — | isWorkday() determination | | ShiftService | `app/Domain/Shift/Services/ShiftService.php` | — | Shift resolution | | TodayOverviewService | `app/Domain/Reporting/Services/TodayOverviewService.php` | — | Real-time dashboard (from raw_logs) | ### A2. Data Flow (Current) ``` ZKTeco Device │ ▼ C# Collector (SQLite buffer) │ ▼ Laravel Sync API ──► raw_attendance_logs (INSERT OR IGNORE) │ │ │ is_processed = false │ │ ▼ │ CalculateDailyAttendanceJob ◄─┘ (dispatched per date) │ ▼ AttendanceService::calculateDailyAttendance() │ ├── Read ALL raw_logs in window [date 00:00, date+1 12:00] ├── Resolve personnel (personnel_code → Personnel) ├── Resolve shift (ShiftAssignment → Personnel.defaultShift) ├── Load leaves (LeaveRequest where status=approved) ├── Load missions (MissionRequest where status=approved) ├── Load corrections (CorrectionRequest where status=approved, applied=true) │ ├── For each personnel_code: │ ├── autoDetectPunchTypes() — if all same type, first=in rest=out │ ├── excludeClockSkewLogs() — remove clock_skew flagged punches │ ├── computeCoreDay() — pair punches, calculate metrics │ ├── apply leave/mission deduction │ ├── calculateNightMinutes() │ ├── isHolidayWork() │ └── preserveCorrectionFields() — override with approved corrections │ ├── Upsert daily_attendances (chunks of 500) ├── Mark raw_logs as is_processed (with retry) └── backfillAbsentRecords() — after 23:30 for current day ``` ### A3. Core Algorithm — PairPunches (Current) ``` Input: Sorted list of punches (IN and OUT mixed) Output: Collection of [in, out] pairs Algorithm: 1. Walk punches in time order 2. If punch is IN: - If pendingIn exists → push [pendingIn, null] (incomplete pair) - Set pendingIn = punch 3. If punch is OUT: - If pendingIn exists: - If pair duration ≤ maxPairDuration (960 min) → push [pendingIn, punch] - Else → push [pendingIn, null] (too far apart) - Else → ignore OUT without IN 4. After loop: if pendingIn → push [pendingIn, null] Duplicate detection: - Same type, same person, within 2 minutes → dropped ``` ### A4. Status Determination (Current) ``` if pairs empty AND punches exist: status = INCOMPLETE (OUT without IN) elif pairs not empty: if last pair has no OUT: status = INCOMPLETE else: status = PRESENT (or LATE if late_minutes > 0) if early_leave_minutes > 0: status = EARLY_LEAVE Full-day leave overrides → status = LEAVE Full-day mission overrides → status = MISSION ``` --- ## B) TARGET ATTENDANCE ARCHITECTURE ### B1. Architectural Rules 1. **Attendance calculation is ALWAYS downstream from raw_attendance_logs** 2. **Calculation NEVER modifies or blocks ingestion** 3. **All writes to daily_attendances go through AttendanceService** 4. **Leave/Mission services write to daily_attendances ONLY via approved workflow** 5. **Corrections preserve their fields during recalculation** 6. **backfillAbsentRecords only runs after 23:30** ### B2. Target Components | Component | Role | Changes from Current | |-----------|------|---------------------| | AttendanceService | Core calculation | Refactor pairPunches, add multi-punch logic | | PunchPairer | Extracted pairing algorithm | NEW — extract from AttendanceService | | ShiftResolver | Shift resolution | Extract from AttendanceService | | LeaveApplier | Leave/mission deduction | Extract from AttendanceService | | NightCalculator | Night work minutes | Extract from AttendanceService | | StatusDeterminator | Status determination | Extract — add comprehensive truth table | | MonthlyAggregator | Monthly summary | NEW — dedicated service | | AttendanceCalculator (orchestrator) | Coordinates all steps | NEW — replace monolithic service | --- ## C) BUSINESS RULES MATRIX ### C1. Punch Pairing Rules | # | Rule | Current | Required | Status | |---|------|---------|----------|--------| | B1 | Odd punches = IN (last punch is unpaired IN) | ✅ | ✅ | OK | | B2 | Even punches = full pairs | ✅ | ✅ | OK | | B3 | IN→OUT ordering enforced | ✅ | ✅ | OK | | B4 | Duplicate punches within 2 min dropped | ✅ | ✅ | OK | | B5 | Max pair duration 16h prevents cross-day pairing | ✅ | ✅ | OK | | B6 | Tail OUTs for crossing-midnight shifts | ✅ | ✅ | OK | | B7 | OUT without IN → ignored (no error) | ✅ | ✅ | OK | | B8 | IN without OUT → incomplete pair | ✅ | ✅ | OK | | B9 | Multiple IN/OUT pairs per day allowed | ✅ | ✅ | OK | | B10 | 3 punches = 1 pair + 1 unpaired IN | ✅ | ✅ | OK | | B11 | 4 punches = 2 pairs | ✅ | ✅ | OK | | B12 | Auto-detect when all same type | ✅ | ✅ | OK | | B13 | Clock skew punches excluded from calc | ✅ | ✅ | OK | ### C2. Shift Resolution Rules | # | Rule | Current | Required | Status | |---|------|---------|----------|--------| | S1 | ShiftAssignment.forDate wins over default | ✅ | ✅ | OK | | S2 | Personnel.defaultShift is fallback | ✅ | ✅ | OK | | S3 | No shift → skip personnel (no record) | ✅ | ✅ | OK | | S4 | Crossing-midnight detection: end_time ≤ start_time | ✅ | ✅ | OK | | S5 | Expected end = start + 1 day if crossing | ✅ | ✅ | OK | | S6 | Multiple ShiftAssignments for same person → latest wins | ✅ | ✅ | OK | ### C3. Status Determination Rules | # | Rule | Current | Required | Status | |---|------|---------|----------|--------| | ST1 | 0 punches → ABSENT (after 23:30) | ✅ | ✅ | OK | | ST2 | 1 IN only → INCOMPLETE | ✅ | ✅ | OK | | ST3 | 1 OUT only → INCOMPLETE (or ignored?) | ⚠️ | ❓ | AMBIGUOUS | | ST4 | 2 punches (IN+OUT) → PRESENT/LATE/EARLY_LEAVE | ✅ | ✅ | OK | | ST5 | 3 punches (IN+OUT+IN) → INCOMPLETE (last IN unpaired) | ✅ | ✅ | OK | | ST6 | 4 punches (IN+OUT+IN+OUT) → PRESENT | ✅ | ✅ | OK | | ST7 | Late: actualStart > expectedStart + grace | ✅ | ✅ | OK | | ST8 | Early: actualEnd < expectedEnd - grace | ✅ | ✅ | OK | | ST9 | Late + Early → EARLY_LEAVE (early overrides) | ⚠️ | ❓ | AMBIGUOUS | | ST10 | Full-day leave → status = LEAVE | ✅ | ✅ | OK | | ST11 | Full-day mission → status = MISSION | ✅ | ✅ | OK | | ST2 | Half-day leave → deduct from work_minutes | ✅ | ✅ | OK | | ST13 | Holiday work → is_holiday_work = true | ✅ | ✅ | OK | | ST14 | Sick leave type → STATUS_SICK_LEAVE | ✅ | ✅ | OK | ### C4. Leave/Mission Rules | # | Rule | Current | Required | Status | |---|------|---------|----------|--------| | L1 | Only approved leaves affect attendance | ✅ | ✅ | OK | | L2 | Full-day: start_period=full AND end_period=full | ✅ | ✅ | OK | | L3 | Half-day morning: 08:00 to 12:00 | ✅ | ✅ | OK | | L4 | Half-day afternoon: 12:00 to 17:00 | ✅ | ✅ | OK | | L5 | Multi-day: first day morning, last day afternoon | ✅ | ✅ | OK | | L6 | Sick leave → STATUS_SICK_LEAVE (not LEAVE) | ✅ | ✅ | OK | | L7 | Mission always uses Personnel.defaultShift (not assigned) | ⚠️ | ❓ | AMBIGUOUS | | L8 | LeaveService writes to daily_attendances directly | ⚠️ | ❌ | CONFLICT | | L9 | AttendanceService also reads leaves and applies | ⚠️ | ❓ | AMBIGUOUS | | L10 | Double-write: LeaveService AND AttendanceService both write | ⚠️ | ❌ | BUG | ### C5. Night Work Rules | # | Rule | Current | Required | Status | |---|------|---------|----------|--------| | N1 | Night hours: 22:00–06:00 (configurable) | ✅ | ✅ | OK | | N2 | Calculates per pair, per hour block | ✅ | ✅ | OK | | N3 | Only paired punches count (OUT without IN ignored) | ✅ | ✅ | OK | | N4 | Night minutes stored in daily_attendances.night_minutes | ✅ | ✅ | OK | ### C6. Overtime Rules | # | Rule | Current | Required | Status | |---|------|---------|----------|--------| | OT1 | Overtime = actualEnd - expectedEnd (if positive) | ✅ | ✅ | OK | | OT2 | Only when overtime_calculation = 'auto' | ✅ | ✅ | OK | | OT3 | Capped by max_overtime_minutes (0 = unlimited) | ✅ | ✅ | OK | | OT4 | overtime_needs_approval sets is_overtime_approved | ✅ | ✅ | OK | | OT5 | Overtime from breaks? | ❌ | ❓ | MISSING | ### C7. Correction Rules | # | Rule | Current | Required | Status | |---|------|---------|----------|--------| | C1 | Only approved corrections applied | ✅ | ✅ | OK | | C2 | Correction fields override calculated fields | ✅ | ✅ | OK | | C3 | Recalculation preserves corrected fields | ✅ | ✅ | OK | | C4 | Correction metadata preserved | ✅ | ✅ | OK | | C5 | Multiple corrections merged (latest wins per field) | ✅ | ✅ | OK | --- ## D) DATA FLOW ### D1. Current Data Flow ``` raw_attendance_logs │ ├── [is_processed=false] ──► CalculateDailyAttendanceJob │ │ │ ▼ │ AttendanceService.calculateDailyAttendance() │ │ │ ┌──────────┼──────────────┐ │ ▼ ▼ ▼ │ Personnel ShiftAssignment LeaveRequest │ │ │ │ │ ▼ ▼ ▼ │ Shift CalendarService MissionRequest │ │ │ ▼ │ computeCoreDay() │ │ │ ▼ │ pairPunches() │ │ │ ▼ │ daily_attendances (UPSERT) │ └── [is_processed=true] (marked after calc) LeaveService (on approval) ──► daily_attendances (INSERT/UPDATE) MissionService (on approval) ──► daily_attendances (INSERT/UPDATE) ``` ### D2. Double-Write Problem ``` PROBLEM: Two independent paths write to daily_attendances: Path A: LeaveService::applyToAttendance() - On leave approval - Writes STATUS_LEAVE / STATUS_SICK_LEAVE - Sets notes = "مرخصی خودکار" Path B: AttendanceService::calculateDailyAttendance() - On each recalculation - Reads LeaveRequest → applies leave deduction - Overwrites the entire row (UPSERT) CONFLICT: 1. LeaveService writes row 2. AttendanceService recalculates → overwrites row 3. LeaveService's notes field is lost 4. If recalculation happens BEFORE approval → leave not applied 5. If recalculation happens AFTER approval → leave correctly applied 6. But if leave is cancelled → LeaveService::removeFromAttendance() reverts to ABSENT → Then next recalculation overwrites again ``` --- ## E) STATE TRANSITIONS ### E1. DailyAttendance Status Transitions ``` ┌─────────────┐ │ ABSENT │ (initial, after 23:30) └──────┬──────┘ │ ┌────────────┼────────────┐ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ PRESENT │ │ LATE │ │EARLY_LEAVE│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ │ └────────────┼────────────┘ │ ┌─────┴─────┐ │INCOMPLETE │ (last IN unpaired) └─────┬─────┘ │ ┌───────────┼───────────┐ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ LEAVE │ │ MISSION │ │ SICK │ └──────────┘ └──────────┘ │ LEAVE │ └──────────┘ CORRECTION: Any status can be overridden by approved correction RECALCULATION: Status can change on each recalculation ``` ### E2. Correction State Machine ``` CorrectionRequest: PENDING ──approve──► APPROVED ──applied──► applied_to_attendance=true │ │ └──reject──► REJECTED └──cancel──► CANCELLED When APPROVED + applied_to_attendance=true: - AttendanceService preserves corrected fields during recalculation - metadata: is_corrected, correction_request_id, corrected_by, corrected_at ``` --- ## F) CRITICAL AMBIGUITIES ### F1. Punch Counting Ambiguities | # | Ambiguity | Current Behavior | Required Clarification | |---|-----------|-----------------|----------------------| | A1 | **1 OUT without IN** — what status? | Treated as INCOMPLETE (punches exist, no pairs) | Should this be INCOMPLETE or ABSENT? | | A2 | **5 punches (IN+OUT+IN+OUT+IN)** — last IN unpaired | INCOMPLETE | Correct per business rule B1 | | A3 | **6+ punches** — all paired | PRESENT (or LATE/EARLY_LEAVE) | Correct per business rule | | A4 | **Late + Early Leave simultaneously** | Status = EARLY_LEAVE (early overrides late) | Should be LATE + EARLY_LEAVE? Or just EARLY_LEAVE? | | A5 | **IN at 07:55, OUT at 17:05** — 5 min overtime + on time | Status = PRESENT, overtime = 5 min | Correct — overtime doesn't affect status | | A6 | **IN at 08:20, OUT at 16:30** — late + early | Status = EARLY_LEAVE (20 late, 30 early) | Should BOTH late and early be shown? | | A7 | **Multiple IN without OUT** — e.g., 3 INs, 0 OUTs | First IN → incomplete, second IN → incomplete, third IN → incomplete | All treated as incomplete pairs | | A8 | **Gap between pairs > 16h** | Second pair starts fresh (first IN marked incomplete) | Correct — prevents cross-day pairing | ### F2. Shift Ambiguities | # | Ambiguity | Current Behavior | Required Clarification | |---|-----------|-----------------|----------------------| | S1 | **No ShiftAssignment AND no defaultShift** | Personnel skipped (no record) | Correct — can't calculate without shift | | S2 | **ShiftAssignment changes mid-day** | Uses assignment active on the date | Which shift's expected times to use? | | S3 | **Night shift: IN at 20:00, OUT at 06:00+1** | Expected: 20:00–08:00 (crossing) | Correct — tail OUT consumed | | S4 | **Night shift: IN at 20:00, OUT at 08:00+1 (12h later)** | Pair duration 12h < 960max → valid pair | Correct | | S5 | **Flexible shift** | Same algorithm as regular | Should flexible shifts skip expected times? | ### F3. Leave/Mission Ambiguities | # | Ambiguity | Current Behavior | Required Clarification | |---|-----------|-----------------|----------------------| | L1 | **Half-day leave + punches exist** | Leave deducted from work_minutes, punches still paired | Should punches be IGNORED during leave hours? | | L2 | **Full-day leave + punches exist** | Status = LEAVE, work_minutes = 0, punches ignored | Correct — leave overrides | | L3 | **Mission uses Personnel.defaultShift** | Shift not from ShiftAssignment | Should mission use assigned shift? | | L4 | **Leave approval AFTER recalculation** | LeaveService writes to daily_attendances, next recalc overwrites | Double-write conflict | | L5 | **Leave AND mission on same day** | Both applied, total deduction = leave + mission minutes | Should one override the other? | | L6 | **Half-day leave morning, half-day mission afternoon** | Both deducted → work_minutes = 0 | Correct — full day covered | | L7 | **Sick leave = STATUS_SICK_LEAVE** | Correct per B14 | But sick leave also shows as "leave" in monthly stats? | ### F4. Correction Ambiguities | # | Ambiguity | Current Behavior | Required Clarification | |---|-----------|-----------------|----------------------| | C1 | **Correction AFTER recalculation** | Correction fields preserved on next recalc | Correct | | C2 | **Correction BEFORE any punches** | Correction applied, but no raw_logs | Should correction work without punches? | | C3 | **Multiple corrections for same field** | Latest wins (by ID order) | Correct | | C4 | **Correction on leave day** | Leave overrides, correction metadata preserved | Correct | ### F5. Overtime Ambiguities | # | Ambiguity | Current Behavior | Required Clarification | |---|-----------|-----------------|----------------------| | OT1 | **Overtime from break time?** | No — break time is not counted as overtime | Should breaks during overtime be counted? | | OT2 | **Overtime on holiday?** | is_holiday_work = true, overtime still calculated | Correct | | OT3 | **Overtime needs approval** | is_overtime_approved flag set | But overtime_minutes still stored regardless | ### F6. Recalculation Ambiguities | # | Ambiguity | Current Behavior | Required Correction | |---|-----------|-----------------|-------------------| | R1 | **Recalculation overwrites ALL fields** | Yes — UPSERT replaces entire row | Correction fields preserved via preserveCorrectionFields | | R2 | **Recalculation triggered on every punch** | Job dispatched per punch (debounced 10min) | Correct — job uniqueness prevents floods | | R3 | **Recalculation after 23:30** | backfillAbsentRecords runs | Correct — prevents premature absent | | R4 | **Recalculation of historical dates** | Works — reads ALL logs in window | Correct | --- ## G) REQUIRED SCHEMA CHANGES ### G1. Existing Schema (no changes needed) | Table | Status | Notes | |-------|--------|-------| | raw_attendance_logs | ✅ OK | Source of truth, immutable | | daily_attendances | ✅ OK | All fields present | | shifts | ✅ OK | Supports regular/night/flexible | | shift_assignments | ✅ OK | Date range assignment | | personnel | ✅ OK | Has default_shift_id | | attendance_rules | ✅ OK | Grace periods, overtime config | | holidays | ✅ OK | Per-date holidays | | work_calendars | ✅ OK | Per-date override | | leave_requests | ✅ OK | Has type, period, status | | mission_requests | ✅ OK | Has period, status | | correction_requests | ✅ OK | Has type, status, applied_to_attendance | ### G2. Potential Schema Additions | Table | Purpose | Priority | |-------|---------|----------| | `attendance_calculations` | Audit log: when calc ran, inputs, outputs, duration | MEDIUM | | `attendance_pair_logs` | Store parsed pairs for debugging | LOW | ### G3. Schema Issues to Fix | # | Issue | Current | Fix | |---|-------|---------|-----| | 1 | LeaveService writes directly to daily_attendances | Double-write conflict | Remove direct writes; let AttendanceService handle | | 2 | MissionService writes directly to daily_attendances | Same conflict | Remove direct writes; let AttendanceService handle | | 3 | daily_attendances.break_minutes not populated for absent/incomplete | Missing | Ensure 0 for all non-present statuses | | 4 | daily_attendances.night_minutes not populated for absent/incomplete | Missing | Ensure 0 for all non-present statuses | --- ## H) REQUIRED SERVICES/CLASSES ### H1. Refactored AttendanceService (Orchestrator) ```php class AttendanceCalculator { public function calculateDay(string $date): array { // 1. Fetch raw logs // 2. Resolve personnel // 3. Resolve shifts // 4. Load leaves, missions, corrections // 5. For each personnel: calculatePersonnelDay() // 6. Upsert daily_attendances // 7. Mark processed // 8. Backfill absent } public function calculatePersonnelDay(...): array { // 1. autoDetectPunchTypes // 2. excludeClockSkewLogs // 3. pairPunches → PunchPairer // 4. calculateMetrics → MetricsCalculator // 5. applyLeaveDeduction → LeaveApplier // 6. determineStatus → StatusDeterminator // 7. preserveCorrections } } ``` ### H2. Extracted Classes | Class | Responsibility | Extracted From | |-------|---------------|----------------| | `PunchPairer` | IN/OUT pairing algorithm | `AttendanceService::pairPunches()` | | `MetricsCalculator` | work_minutes, break_minutes, late, early, overtime, night | `AttendanceService::computeCoreDay()` | | `StatusDeterminator` | Final status based on all inputs | `AttendanceService::computeCoreDay()` | | `ShiftResolver` | Personnel → Shift mapping | `AttendanceService::resolveShiftMap()` | | `LeaveApplier` | Leave/mission deduction | `AttendanceService::buildDailyRecord()` | | `NightCalculator` | Night work minutes | `AttendanceService::calculateNightMinutes()` | | `AbsentBackfiller` | Create ABSENT records | `AttendanceService::backfillAbsentRecords()` | | `CorrectionPreserver` | Protect corrected fields | `AttendanceService::preserveCorrectionFields()` | ### H3. Services to Modify | Service | Change | Reason | |---------|--------|--------| | `LeaveService` | Remove `applyToAttendance()` and `removeFromAttendance()` | Double-write conflict | | `MissionService` | Remove `applyToAttendance()` and `removeFromAttendance()` | Double-write conflict | | `AttendanceService` | Keep as orchestrator, delegate to extracted classes | Single Responsibility | --- ## I) REQUIRED TESTS ### I1. Punch Pairing Tests | # | Test | Punches | Expected Pairs | Status | |---|------|---------|----------------|--------| | P1 | 0 punches | [] | 0 pairs | ABSENT | | P2 | 1 IN | [08:00 IN] | 1 pair (incomplete) | INCOMPLETE | | P3 | 1 OUT | [17:00 OUT] | 0 pairs | INCOMPLETE | | P4 | 2 punches | [08:00 IN, 17:00 OUT] | 1 pair | PRESENT | | P5 | 3 punches | [08:00 IN, 12:00 OUT, 13:00 IN] | 2 pairs (1 incomplete) | INCOMPLETE | | P6 | 4 punches | [08:00 IN, 12:00 OUT, 13:00 IN, 17:00 OUT] | 2 pairs | PRESENT | | P7 | 5 punches | [08:00 IN, 12:00 OUT, 13:00 IN, 17:00 OUT, 17:30 IN] | 3 pairs (1 incomplete) | INCOMPLETE | | P8 | 6 punches | [08:00 IN, 12:00 OUT, 13:00 IN, 17:00 OUT, 18:00 IN, 20:00 OUT] | 3 pairs | PRESENT | | P9 | Duplicate IN within 2 min | [08:00 IN, 08:01 IN, 17:00 OUT] | 1 pair | PRESENT | | P10 | Duplicate OUT within 2 min | [08:00 IN, 17:00 OUT, 17:01 OUT] | 1 pair | PRESENT | | P11 | Gap > 16h between IN and OUT | [08:00 IN, next_day 10:00 OUT] | 1 pair (incomplete) | INCOMPLETE | | P12 | All same type (all IN) | [08:00 IN, 12:00 IN, 17:00 IN] | Auto-detect: 1 pair + 1 incomplete | INCOMPLETE | | P13 | All same type (all OUT) | [08:00 OUT, 12:00 OUT, 17:00 OUT] | Auto-detect: 1 pair + 1 incomplete | INCOMPLETE | ### I2. Status Determination Tests | # | Test | Punches | Shift | Expected Status | |---|------|---------|-------|-----------------| | S1 | On time | [08:00 IN, 17:00 OUT] | 08:00–17:00 | PRESENT | | S2 | Late (beyond grace) | [08:20 IN, 17:00 OUT] | 08:00–17:00 | LATE (20 min) | | S3 | Late (within grace) | [08:10 IN, 17:00 OUT] | 08:00–17:00 | PRESENT (0 late) | | S4 | Early leave | [08:00 IN, 16:30 OUT] | 08:00–17:00 | EARLY_LEAVE (30 min) | | S5 | Late + Early | [08:20 IN, 16:30 OUT] | 08:00–17:00 | EARLY_LEAVE? LATE? | | S6 | Overtime | [08:00 IN, 18:00 OUT] | 08:00–17:00 | PRESENT (60 OT) | | S7 | Incomplete (1 IN) | [08:00 IN] | 08:00–17:00 | INCOMPLETE | | S8 | Incomplete (1 OUT) | [17:00 OUT] | 08:00–17:00 | INCOMPLETE | | S9 | Full-day leave | leave=approved+full | 08:00–17:00 | LEAVE | | S10 | Half-day leave AM | leave=approved+morning | 08:00–17:00 | work -= 240 min | | S11 | Half-day leave PM | leave=approved+afternoon | 08:00–17:00 | work -= 300 min | | S12 | Full-day mission | mission=approved+full | 08:00–17:00 | MISSION | | S13 | Holiday work | holiday, punches exist | any | PRESENT + is_holiday_work | | S14 | Sick leave | leave=sick+approved | 08:00–17:00 | SICK_LEAVE | | S15 | No shift assigned | [08:00 IN, 17:00 OUT] | null | SKIP (no record) | ### I3. Night Shift Tests | # | Test | Shift | Punches | Expected night_minutes | |---|------|-------|---------|----------------------| | N1 | Normal night | 20:00–08:00 | [20:00 IN, 08:00 OUT] | 480 (22:00–06:00) | | N2 | Partial night | 08:00–22:00 | [08:00 IN, 22:00 OUT] | 120 (22:00–00:00) | | N3 | No night | 08:00–17:00 | [08:00 IN, 17:00 OUT] | 0 | | N4 | Full night crossing | 22:00–06:00 | [22:00 IN, 06:00 OUT] | 480 | ### I4. Leave/Mission Tests | # | Test | Leave | Punches | Expected | |---|------|-------|---------|----------| | L1 | Full-day leave, no punches | approved, full/full | [] | LEAVE, work=0 | | L2 | Full-day leave, with punches | approved, full/full | [08:00, 17:00] | LEAVE, work=0 | | L3 | Half-day AM leave | approved, morning/morning | [08:00, 17:00] | work = shift - 240 | | L4 | Half-day PM leave | approved, afternoon/afternoon | [08:00, 17:00] | work = shift - 300 | | L5 | Multi-day leave, first day | approved, morning/full | [08:00, 17:00] | work = shift - 240 | | L6 | Multi-day leave, last day | approved, full/afternoon | [08:00, 17:00] | work = shift - 300 | | L7 | Multi-day leave, middle day | approved, full/full | [08:00, 17:00] | LEAVE, work=0 | | L8 | Sick leave | approved, sick | [] | SICK_LEAVE | | L9 | Full-day mission | approved, full | [] | MISSION, work=0 | | L10 | Half-day mission | approved, morning | [08:00, 17:00] | work = shift - 240 | | L11 | Leave + mission same day | both approved | [] | LEAVE + MISSION deduction | ### I5. Correction Tests | # | Test | Correction | Expected | |---|------|-----------|----------| | CR1 | Time IN correction | TYPE_TIME_IN, actual_start=09:00 | actual_start=09:00 on recalc | | CR2 | Time OUT correction | TYPE_TIME_OUT, actual_end=18:00 | actual_end=18:00 on recalc | | CR3 | Status correction | TYPE_STATUS, status=leave | status=leave on recalc | | CR4 | Full day correction | TYPE_FULL_DAY, start+end+status | All three preserved | | CR5 | Overtime correction | TYPE_OVERTIME, minutes=120 | overtime=120 on recalc | | CR6 | Multiple corrections merged | 2 corrections for same person | Latest per field wins | ### I6. Monthly Aggregation Tests | # | Test | Input | Expected | |---|------|-------|----------| | M1 | Full month present | 22 workdays, all present | present_days=22 | | M2 | Mixed month | present+late+absent | Correct counts | | M3 | Month with holidays | holidays excluded from total_days | Correct | | M4 | Month with leave | leave counted separately | Correct | | M5 | Night minutes total | Multiple night shifts | Sum of night_minutes | --- ## J) TRUTH TABLE — PUNCH COUNT ### J1. Normal Shift (08:00–17:00, 540 min) | Punches | Pattern | Pairs | Status | work_min | late_min | early_min | ot_min | break_min | needs_review | |---------|---------|-------|--------|----------|----------|-----------|--------|-----------|-------------| | 0 | [] | 0 | ABSENT | 0 | 0 | 0 | 0 | 0 | 0 | | 1 | [IN] | 1 (incomplete) | INCOMPLETE | 0 | 0 | 0 | 0 | 0 | 1 | | 1 | [OUT] | 0 | INCOMPLETE | 0 | 0 | 0 | 0 | 0 | 1 | | 2 | [IN,OUT] | 1 | PRESENT/LATE/EARLY | ∑pair | calc | calc | calc | 0 | 0 | | 3 | [IN,OUT,IN] | 2 (1 incomplete) | INCOMPLETE | pair1 | calc | calc | 0 | 0 | 1 | | 4 | [IN,OUT,IN,OUT] | 2 | PRESENT/LATE/EARLY | ∑pairs | calc | calc | calc | gap | 0 | | 5 | [IN,OUT,IN,OUT,IN] | 3 (1 incomplete) | INCOMPLETE | ∑pairs-1 | calc | calc | 0 | gaps | 1 | | 6 | [IN,OUT,IN,OUT,IN,OUT] | 3 | PRESENT/LATE/EARLY | ∑pairs | calc | calc | calc | gaps | 0 | | 7 | [IN,OUT,IN,OUT,IN,OUT,IN] | 4 (1 incomplete) | INCOMPLETE | ∑pairs-1 | calc | calc | 0 | gaps | 1 | | 8 | [IN,OUT,IN,OUT,IN,OUT,IN,OUT] | 4 | PRESENT/LATE/EARLY | ∑pairs | calc | calc | calc | gaps | 0 | ### J2. Night Shift (20:00–08:00+1, 720 min) | Punches | Pattern | Pairs | Tail OUTs | Status | work_min | |---------|---------|-------|-----------|--------|----------| | 0 | [] | 0 | 0 | ABSENT | 0 | | 1 | [20:00 IN] | 1 (incomplete) | 0 | INCOMPLETE | 0 | | 2 | [20:00 IN, 06:00+1 OUT] | 1 | 0 | PRESENT | 600 | | 3 | [20:00 IN, 00:00 OUT, 02:00 IN] | 2 (1 incomplete) | 0 | INCOMPLETE | 240 | | 4 | [20:00 IN, 00:00 OUT, 02:00 IN, 08:00+1 OUT] | 2 | 0 | PRESENT | 480 | ### J3. Holiday | Punches | Status | is_holiday_work | work_min | |---------|--------|-----------------|----------| | 0 | ABSENT (or HOLIDAY?) | false | 0 | | 2 | PRESENT + is_holiday_work=true | true | calc | ### J4. Leave | Punches | Leave Type | Status | work_min | |---------|-----------|--------|----------| | 0 | full-day annual | LEAVE | 0 | | 2 | full-day annual | LEAVE | 0 | | 0 | half-day AM | LEAVE (half) | 0 | | 2 | half-day AM | work - 240 | calc | | 0 | half-day PM | LEAVE (half) | 0 | | 2 | half-day PM | work - 300 | calc | ### J5. Mission | Punches | Mission Type | Status | work_min | |---------|-------------|--------|----------| | 0 | full-day | MISSION | 0 | | 2 | full-day | MISSION | 0 | | 0 | half-day AM | work - 240 | calc | | 2 | half-day AM | work - 240 | calc | ### J6. Shift Change (same day) | Scenario | Behavior | |----------|----------| | ShiftAssignment changes from A to B on date | Uses shift B (latest assignment wins) | | Two assignments overlap | Uses the one with latest start_date | ### J7. Correction | Scenario | Behavior | |----------|----------| | Correction on IN time | actual_start overridden, work_minutes recalculated | | Correction on OUT time | actual_end overridden, work_minutes recalculated | | Correction on status | status overridden, other fields recalculated | | Correction on overtime | overtime_minutes overridden | | Correction + recalculation | Corrected fields preserved, others recalculated | --- ## K) RECOMMENDED IMPLEMENTATION ORDER | Phase | Task | Priority | |-------|------|----------| | 2.1 | Fix double-write: Remove LeaveService/MissionService direct writes | HIGH | | 2.2 | Fix status ambiguity: Late+Early → which status? | HIGH | | 2.3 | Fix OUT-only punch handling | HIGH | | 2.4 | Extract PunchPairer class | MEDIUM | | 2.5 | Extract MetricsCalculator class | MEDIUM | | 2.6 | Extract StatusDeterminator class | MEDIUM | | 2.7 | Extract ShiftResolver class | LOW | | 2.8 | Extract LeaveApplier class | LOW | | 2.9 | Extract NightCalculator class | LOW | | 2.10 | Add MonthlyAggregator service | LOW | | 2.11 | Write comprehensive tests (I1–I6) | HIGH | | 2.12 | Add attendance_calculations audit log | LOW | --- ## L) CRITICAL DECISIONS NEEDED | # | Decision | Options | Recommendation | |---|----------|---------|----------------| | D1 | Late + Early = which status? | A: EARLY_LEAVE overrides, B: LATE overrides, C: Both shown, D: New status | C — show both in separate fields, status = LATE if late>0, else EARLY_LEAVE | | D2 | OUT-only punch = what status? | A: INCOMPLETE, B: ABSENT, C: Ignore | A: INCOMPLETE (punch exists, needs review) | | D3 | Holiday with 0 punches = ? | A: ABSENT, B: HOLIDAY | B: HOLIDAY (no absence on holiday) | | D4 | LeaveService direct writes | A: Keep, B: Remove | B: Remove — let AttendanceService handle via LeaveRequest reads | | D5 | Mission uses defaultShift or assigned? | A: defaultShift, B: assigned | B: assigned (mission should respect shift assignment) | | D6 | Half-day leave + punches outside leave hours | A: Count normally, B: Ignore all punches | A: Count normally, only deduct leave hours |