namespace AttendanceHub.Sync.Domain; /// /// Per-device reconciliation watermark (logical, durable in SQLite). /// Watermark MUST NEVER advance beyond already-durable acceptable punch_time. /// public sealed record ReconciliationWatermark( string DeviceId, DateTimeOffset? LastPersistedPunchTime, TimeSpan Overlap, TimeSpan ClockSkewTolerance, DateTimeOffset? UpdatedAt, int? LastSessionGeneration) { public DateTimeOffset ComputeWindowStart() => LastPersistedPunchTime is null ? DateTimeOffset.MinValue : LastPersistedPunchTime.Value.Add(-Overlap); public DateTimeOffset ComputeWindowEnd(DateTimeOffset hostNow, DateTimeOffset? deviceNow = null) { var device = deviceNow ?? hostNow; var skewed = hostNow.Add(ClockSkewTolerance); var deviceSkewed = device.Add(ClockSkewTolerance); return deviceSkewed < skewed ? deviceSkewed : skewed; } /// /// Candidate watermark from a successful persistence batch. /// Uses MAX acceptable durable punch_time (device rows can be out of order). /// Future-hold rows must not pull the watermark forward — UNLESS they are already durable and /// inside (device-local label of "now" + tolerance). /// Without that horizon a device whose clock is on site-local time (labels run 3.3h ahead of /// host UTC) would keep every recent punch in FutureHold and the watermark would never move. /// public static DateTimeOffset? ComputeAdvanceCandidate( IEnumerable persistedRows, DateTimeOffset? currentWatermark, DateTimeOffset? acceptableHorizon = null) { DateTimeOffset? maxAcceptable = null; foreach (var row in persistedRows) { var eligible = row.TimeStatus == PunchTimeStatus.Acceptable || (acceptableHorizon is not null && row.TimeStatus == PunchTimeStatus.FutureHold && row.PunchTime <= acceptableHorizon.Value); if (!eligible) continue; if (maxAcceptable is null || row.PunchTime > maxAcceptable.Value) maxAcceptable = row.PunchTime; } if (maxAcceptable is null) return currentWatermark; if (currentWatermark is null || maxAcceptable.Value > currentWatermark.Value) return maxAcceptable; return currentWatermark; } }