using System.Net; using System.Text.Json; using System.Text.Json.Nodes; using AttendanceHub.Sync.Configuration; using AttendanceHub.Sync.Domain; using AttendanceHub.Sync.Host; using AttendanceHub.Sync.Persistence.Sqlite; using AttendanceHub.Sync.Upload; using Xunit; namespace AttendanceHub.Sync.Tests; /// /// Upload-layer device identity mapping (upload.deviceId): /// acquisition/canonical identity stays the local device id (phase1-test-01), /// only the outgoing Laravel payload records[].device_id is rewritten (172.24.30.9), /// ACK echoes of the payload identity are mapped back to the local record. /// No store/schema/worker/COM change is exercised here. /// public class UploadDeviceIdentityTests : IAsyncLifetime { private const string LocalDevice = "phase1-test-01"; private const string LaravelDevice = "172.24.30.9"; private string _dbPath = null!; private SQLiteSyncStore _store = null!; public async Task InitializeAsync() { _dbPath = Path.Combine(Path.GetTempPath(), "ahub-upload-identity", Guid.NewGuid().ToString("N") + ".db"); Directory.CreateDirectory(Path.GetDirectoryName(_dbPath)!); _store = new SQLiteSyncStore(_dbPath); await _store.InitializeAsync(); } public async Task DisposeAsync() { await _store.DisposeAsync(); try { Directory.Delete(Path.GetDirectoryName(_dbPath)!, true); } catch { /* temp */ } } private static string FindRepoConfig() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { var p = Path.Combine(dir.FullName, "config", "phase1.device.json"); if (File.Exists(p)) return p; dir = dir.Parent; } throw new FileNotFoundException("config/phase1.device.json not found above " + AppContext.BaseDirectory); } private static NormalizedPunch Punch(string pin, int hour, string device = LocalDevice) { var t = new DateTimeOffset(2026, 9, 24, hour, 0, 0, TimeSpan.Zero); return new NormalizedPunch(new PunchIdentity(device, pin, t), PunchSource.Reconciliation, 0, 1, 0, false, 1, "SSR", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1, PunchTimeStatus.Acceptable, 2026, 9, 24, hour, 0, 0); } private static string WriteTmpConfig(string? uploadDeviceId) { var tmp = Path.Combine(Path.GetTempPath(), "ahub-upload-identity", Guid.NewGuid().ToString("N") + ".json"); Directory.CreateDirectory(Path.GetDirectoryName(tmp)!); var deviceLine = uploadDeviceId is null ? "" : $"\"deviceId\": \"{uploadDeviceId}\","; File.WriteAllText(tmp, $$""" { "device": { "deviceId": "phase1-test-01", "displayName": "t", "ip": "172.24.30.9", "port": 4370, "machineNumber": 1, "commKey": 0 }, "sdk": { "commTimeoutSeconds": 5, "expectedSdkVersion": "6.3.1.45" }, "session": { "operationTimeoutMs": 30000, "connectTimeoutMs": 15000 }, "realtime": { "eventMask": 1, "channelCapacity": 256 }, "read": { "mode": "Auto", "lookbackMinutes": 1440, "maxRecordsPerRead": 1000000, "failureRetryLimit": 3, "failureRetryBackoffMs": 15000 }, "supervisor": { "reconnectDelayMs": 5000, "healthIntervalMs": 30000, "readIntervalMs": 60000 }, "upload": { "enabled": true, "baseAddress": "http://localhost/AttendanceHub/public", "batchPath": "/api/v1/sync/punches", "apiToken": "unit-only-token", {{deviceLine}} "timeoutSeconds": 30, "batchSize": 200, "maxConcurrency": 1, "pollingIntervalMs": 15000 } } """); return tmp; } /// Captures the exact wire JSON and echoes a Laravel-shaped ACK (identity = payload device_id). private sealed class CaptureHandler : HttpMessageHandler { public string? LastBody; public Func? AckBodyFactory; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { LastBody = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct); var body = AckBodyFactory?.Invoke(LastBody ?? "{}") ?? """{"batch_id":"b","accepted":[],"already_exists":[],"rejected":[],"processed_at":"2026-09-30T00:00:00Z"}"""; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, System.Text.Encoding.UTF8, "application/json") }; } } /// Laravel PunchUploadController-style ACK: echo each record's identity with its device_id. private static string LaravelAck(string requestBody, bool authorize) { using var doc = JsonDocument.Parse(requestBody); var accepted = new JsonArray(); var rejected = new JsonArray(); foreach (var rec in doc.RootElement.GetProperty("records").EnumerateArray()) { var identity = new JsonObject { ["device_id"] = rec.GetProperty("device_id").GetString(), ["personnel_code"] = rec.GetProperty("personnel_code").GetString(), ["punch_time"] = rec.GetProperty("punch_time").GetString() }; if (authorize) { identity["server_receipt_id"] = "r:" + rec.GetProperty("local_id").GetRawText(); identity["processed_at"] = "2026-09-30T00:00:00Z"; accepted.Add(identity); } else { identity["reason"] = "device_not_authorized"; identity["retryable"] = false; rejected.Add(identity); } } return new JsonObject { ["batch_id"] = "b", ["accepted"] = accepted, ["already_exists"] = new JsonArray(), ["rejected"] = rejected, ["processed_at"] = "2026-09-30T00:00:00Z" }.ToJsonString(); } // ---------- 1) acquisition identity remains the local device id ---------- [Fact] public void Repo_Config_Keeps_Acquisition_Identity_And_Upload_Disabled() { var cfg = Phase1ConfigLoader.Load(FindRepoConfig()); Assert.Equal(LocalDevice, cfg.Device.DeviceId); var upload = UploadRuntime.ParseFromFile(FindRepoConfig()); Assert.Null(upload); // upload.enabled=false in the source config } [Fact] public void Upload_DeviceId_Parsed_When_Configured() { var tmp = WriteTmpConfig(LaravelDevice); try { var cfg = UploadRuntime.ParseFromFile(tmp); Assert.NotNull(cfg); Assert.Equal(LaravelDevice, cfg!.DeviceId); // acquisition identity is parsed by a different loader, unaffected by upload section var acq = Phase1ConfigLoader.Load(tmp); Assert.Equal(LocalDevice, acq.Device.DeviceId); } finally { try { File.Delete(tmp); } catch { } } } [Fact] public void Missing_Upload_DeviceId_Falls_Back_To_Null() { var tmp = WriteTmpConfig(uploadDeviceId: null); try { var cfg = UploadRuntime.ParseFromFile(tmp); Assert.NotNull(cfg); Assert.Null(cfg!.DeviceId); // => client keeps the local device identity } finally { try { File.Delete(tmp); } catch { } } } // ---------- 2) wire payload identity can be the Laravel identity ---------- [Fact] public async Task Payload_Uses_Upload_DeviceId_While_Local_Records_Keep_Acquisition_Identity() { await _store.UpsertPunchAsync(Punch("96625", 6)); var handler = new CaptureHandler { AckBodyFactory = body => LaravelAck(body, authorize: true) }; var client = new HttpUploadApiClient(new HttpClient(handler), new UploadClientOptions { BaseAddress = new Uri("http://localhost/AttendanceHub/public"), ApiToken = "unit-only-token", PayloadDeviceId = LaravelDevice }); var worker = new UploadWorker(_store, client, RetryPolicy.Default); var cycle = await worker.RunOnceAsync([LocalDevice], 100); Assert.Equal(1, cycle.TotalSuccess); // wire: records[].device_id rewritten, everything else untouched Assert.NotNull(handler.LastBody); using var wire = JsonDocument.Parse(handler.LastBody!); var rec = wire.RootElement.GetProperty("records")[0]; Assert.Equal(LaravelDevice, rec.GetProperty("device_id").GetString()); Assert.Equal("96625", rec.GetProperty("personnel_code").GetString()); Assert.Equal("2026-09-24 06:00:00", rec.GetProperty("punch_time").GetString()); Assert.True(rec.TryGetProperty("local_id", out _)); // local: canonical identity unchanged after successful upload var rows = await _store.ListPunchesAsync(LocalDevice); var row = Assert.Single(rows); Assert.Equal(LocalDevice, row.Identity.DeviceId); Assert.Equal("Sent", row.UploadState); Assert.NotNull(await _store.FindPunchAsync(new PunchIdentity(LocalDevice, "96625", new DateTimeOffset(2026, 9, 24, 6, 0, 0, TimeSpan.Zero)))); } // ---------- 4) no override => existing behavior (local device id on the wire) ---------- [Fact] public async Task Payload_Falls_Back_To_Local_DeviceId_Without_Override() { await _store.UpsertPunchAsync(Punch("5140", 7)); var handler = new CaptureHandler { AckBodyFactory = body => LaravelAck(body, authorize: true) }; var client = new HttpUploadApiClient(new HttpClient(handler), new UploadClientOptions { BaseAddress = new Uri("http://localhost/AttendanceHub/public"), ApiToken = "unit-only-token" // PayloadDeviceId intentionally omitted => null }); var worker = new UploadWorker(_store, client, RetryPolicy.Default); var cycle = await worker.RunOnceAsync([LocalDevice], 100); Assert.Equal(1, cycle.TotalSuccess); Assert.NotNull(handler.LastBody); using var wire = JsonDocument.Parse(handler.LastBody!); Assert.Equal(LocalDevice, wire.RootElement.GetProperty("records")[0].GetProperty("device_id").GetString()); } // ---------- 5) Laravel IP lookup resolves the override; root-cause string stays rejected without it ---------- [Fact] public async Task Laravel_Device_Lookup_Resolves_Payload_DeviceId_Not_Acquisition_Id() { await _store.UpsertPunchAsync(Punch("7083", 8)); // PunchUploadController.php:85 — non-digit device_id resolved against devices.ip keys var devicesIp = new Dictionary(StringComparer.Ordinal) { [LaravelDevice] = 1 }; object? Lookup(string deviceId) => int.TryParse(deviceId, out var id) ? (devicesIp.ContainsValue(id) ? id : null) : devicesIp.TryGetValue(deviceId, out var row) ? row : null; // WITHOUT override: acquisition id misses the ip map => device_not_authorized => permanent DLQ var denyHandler = new CaptureHandler { AckBodyFactory = body => LaravelAck(body, authorize: false) }; var denyClient = new HttpUploadApiClient(new HttpClient(denyHandler), new UploadClientOptions { BaseAddress = new Uri("http://localhost/AttendanceHub/public"), ApiToken = "unit-only-token" }); var denyWorker = new UploadWorker(_store, denyClient, RetryPolicy.Default); var denyCycle = await denyWorker.RunOnceAsync([LocalDevice], 100); Assert.Equal(1, denyCycle.TotalDlq); Assert.Equal(0, denyCycle.TotalSuccess); // the wire identity that Laravel would have rejected is the acquisition id using (var wire = JsonDocument.Parse(denyHandler.LastBody!)) { var wireDeviceId = wire.RootElement.GetProperty("records")[0].GetProperty("device_id").GetString(); Assert.Equal(LocalDevice, wireDeviceId); Assert.Null(Lookup(wireDeviceId!)); // => controller returns device_not_authorized } // WITH override: payload identity resolves => authorized => accepted var rows = await _store.ListPunchesAsync(LocalDevice, 10); foreach (var r in rows) await _store.SetUploadStateAsync(r.LocalId, OutboxUploadState.Pending); var allowHandler = new CaptureHandler { AckBodyFactory = body => LaravelAck(body, authorize: true) }; var allowClient = new HttpUploadApiClient(new HttpClient(allowHandler), new UploadClientOptions { BaseAddress = new Uri("http://localhost/AttendanceHub/public"), ApiToken = "unit-only-token", PayloadDeviceId = LaravelDevice }); var allowWorker = new UploadWorker(_store, allowClient, RetryPolicy.Default); using (var wire = JsonDocument.Parse( """{"batch_id":"x","records":[{"device_id":"172.24.30.9","personnel_code":"7083","punch_time":"2026-09-24 08:00:00","local_id":1}]}""")) { var wireDeviceId = wire.RootElement.GetProperty("records")[0].GetProperty("device_id").GetString(); Assert.NotNull(Lookup(wireDeviceId!)); } var allowCycle = await allowWorker.RunOnceAsync([LocalDevice], 100); Assert.Equal(1, allowCycle.TotalSuccess); Assert.Equal(0, allowCycle.TotalDlq); using (var wire = JsonDocument.Parse(allowHandler.LastBody!)) { var wireDeviceId = wire.RootElement.GetProperty("records")[0].GetProperty("device_id").GetString(); Assert.Equal(LaravelDevice, wireDeviceId); Assert.NotNull(Lookup(wireDeviceId!)); } // canonical local identity still the acquisition id var finalRows = await _store.ListPunchesAsync(LocalDevice); Assert.All(finalRows, r => Assert.Equal(LocalDevice, r.Identity.DeviceId)); } // ---------- ACK echo of the payload identity maps back to the local record (no missing_ack_identity retry) ---------- [Fact] public async Task Ack_Echoing_Payload_DeviceId_Maps_Back_To_Local_Record() { await _store.UpsertPunchAsync(Punch("96625", 9)); var handler = new CaptureHandler { AckBodyFactory = body => LaravelAck(body, authorize: true) }; var client = new HttpUploadApiClient(new HttpClient(handler), new UploadClientOptions { BaseAddress = new Uri("http://localhost/AttendanceHub/public"), ApiToken = "unit-only-token", PayloadDeviceId = LaravelDevice }); var worker = new UploadWorker(_store, client, RetryPolicy.Default); var cycle = await worker.RunOnceAsync([LocalDevice], 100); // If ACK identity (device_id=172.24.30.9) failed to map back, the record would be // counted retryable via missing_ack_identity instead of terminal success. Assert.Equal(1, cycle.TotalSuccess); Assert.Equal(0, cycle.TotalRetry); var stats = await _store.GetUploadStatsAsync(LocalDevice); Assert.Equal(1, stats.Sent); Assert.Equal(0, stats.Retry); Assert.Equal(0, stats.Dlq); } }