move_detect/server/tests/Support/InMemoryRepositories.php
유창욱 d8cef54fe4 feat(report): safety operations report page + event-type filter
The benefit made visible: /report folds everything the system collects into
the one printable page a 안전관리자 takes into the weekly safety meeting.

- GET /api/report?days=N (7/30/90): severity totals, per-type counts,
  worst-camera ranking, response time (TTA - acknowledged critical/high only,
  FP-tagged rows excluded: dismissing a false alarm is not an emergency
  response; clock-skew guarded), the near-miss pyramid (near_fall vs
  fall/no_motion - the Heinrich argument in one ratio), FP rate, summed
  posture-load exposure, occupancy-rule violation counts. ergo_report rows
  feed the sums but are excluded from "감지 N건" (bookkeeping, not detection).
  Fail-closed site scoping throughout.
- /report view: KPI band (중대 이벤트 / 평균 대응 / 니어미스:사고 / 오탐율,
  each with its one-line reading), bar lists for types and cameras (critical
  presence highlighted), ergo bands as share-of-observed-time, rule tiles.
  Print CSS strips the app chrome - the 인쇄 button produces the meeting
  handout. New 리포트 nav tab.
- Events console: event-type filter beside severity - the INFO-volume types
  (near_fall, ergo_report) can now be folded out of the live stream, or a
  single type isolated for investigation.

Verified: PHPUnit 138 pass (3 new: aggregation math incl. TTA/FP-exclusion/
ergo sums, site scope, auth) + Chrome real-render of the full report (KPIs,
bar lists, rule tiles, footer) and the type filter isolating one type.
2026-08-07 07:17:48 +09:00

197 lines
12 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests\Support;
use App\Repository\{DeviceRepository, NonceRepository, RateLimiterRepository,
EventRepository, SnapshotRepository, UserRepository, ZoneRepository,
ThresholdRepository, AuditRepository};
final class InMemoryDeviceRepository implements DeviceRepository {
public array $heartbeats = [];
// $statusRows: full device rows for listStatus() (the status panel tests populate it). Kept a
// trailing optional arg so the many existing 3-arg call sites are unaffected.
public function __construct(private array $secrets = [], private array $versions = [],
private array $sites = [], public array $statusRows = []) {}
public function secretFor(string $d): ?string { return $this->secrets[$d] ?? null; }
public function exists(string $d): bool {
// A device is "known" if it appears in any provisioned map the test set up.
return isset($this->secrets[$d]) || isset($this->sites[$d]) || isset($this->versions[$d]);
}
public function siteFor(string $d): ?string { return $this->sites[$d] ?? null; }
public function touchHeartbeat(string $d, array $m): void { $this->heartbeats[$d] = $m; }
public function configVersion(string $d): int { return $this->versions[$d] ?? 1; }
public function listStatus(?string $site): array {
$rows = $this->statusRows;
if ($site !== null) $rows = array_filter($rows, fn($d) => ($d['site'] ?? null) === $site);
return array_values($rows);
}
}
final class InMemoryNonceRepository implements NonceRepository {
public array $store = [];
public function seen(string $n): bool { return isset($this->store[$n]); }
public function remember(string $n, int $exp): void { $this->store[$n] = $exp; }
}
final class InMemoryRateLimiter implements RateLimiterRepository {
public array $counts = [];
public function hit(string $k, int $w): int { $key = "$k:$w"; return $this->counts[$key] = ($this->counts[$key] ?? 0) + 1; }
}
final class InMemoryEventRepository implements EventRepository {
public array $rows = []; private int $seq = 0;
public function insert(array $e): int { $id = ++$this->seq; $this->rows[$id] = $e + ['event_id' => $id, 'acknowledged_by' => null]; return $id; }
public function idByUuid(string $uuid): ?int {
foreach ($this->rows as $id => $r) if (($r['event_uuid'] ?? null) === $uuid) return (int)$id;
return null;
}
public function recent(int $limit, ?string $sev): array {
$r = array_reverse($this->rows, true);
if ($sev !== null) $r = array_filter($r, fn($x) => $x['severity'] === $sev);
return array_slice(array_values($r), 0, $limit);
}
public function page(int $limit, ?string $sev, ?string $beforeTs, ?int $beforeId, ?string $site = null): array {
$r = array_values($this->rows);
if ($sev !== null) $r = array_filter($r, fn($x) => $x['severity'] === $sev);
if ($site !== null) $r = array_filter($r, fn($x) => ($x['site'] ?? null) === $site);
// (occurred_at DESC, event_id DESC); events inserted without occurred_at sort as 0.
usort($r, fn($a, $b) => [$b['occurred_at'] ?? 0, $b['event_id']] <=> [$a['occurred_at'] ?? 0, $a['event_id']]);
if ($beforeTs !== null && $beforeId !== null) {
$bt = (float)$beforeTs; // cursor carries occurred_at as a string; compare numerically
$r = array_filter($r, fn($x) => ($x['occurred_at'] ?? 0) < $bt
|| (($x['occurred_at'] ?? 0) == $bt && $x['event_id'] < $beforeId));
}
return array_slice(array_values($r), 0, $limit);
}
public function find(int $id): ?array { return $this->rows[$id] ?? null; }
public function acknowledge(int $id, string $u): bool { if (!isset($this->rows[$id])) return false; $this->rows[$id]['acknowledged_by'] = $u; $this->rows[$id]['acknowledged_at'] = $this->rows[$id]['acknowledged_at'] ?? time(); return true; }
public function markFalsePositive(int $id, string $user): bool {
if (!isset($this->rows[$id])) return false;
$r = $this->rows[$id];
$r['false_positive_by'] = $r['false_positive_by'] ?? $user;
$r['false_positive_at'] = $r['false_positive_at'] ?? time();
$r['acknowledged_by'] = ($r['acknowledged_by'] ?? null) !== null ? $r['acknowledged_by'] : $user;
$this->rows[$id] = $r;
return true;
}
public function fpStats(float $since, ?string $site): array {
$groups = [];
foreach ($this->rows as $r) {
if (($r['occurred_at'] ?? 0) < $since) continue;
if ($site !== null && ($r['site'] ?? null) !== $site) continue;
$key = ($r['camera_id'] ?? '') . '|' . ($r['event_type'] ?? '');
$groups[$key] = $groups[$key] ?? ['camera_id' => $r['camera_id'], 'event_type' => $r['event_type'], 'total' => 0, 'fp' => 0];
$groups[$key]['total']++;
if (($r['false_positive_by'] ?? null) !== null) $groups[$key]['fp']++;
}
$out = array_values(array_filter($groups, fn($g) => $g['fp'] > 0));
usort($out, fn($a, $b) => $b['fp'] <=> $a['fp']);
return $out;
}
public function reportSummary(float $since, ?string $site, int $topCameras): array {
$rows = array_filter($this->rows, fn($r) => ($r['occurred_at'] ?? 0) >= $since
&& ($site === null || ($r['site'] ?? null) === $site));
$byType = []; $byCam = []; $ttaDeltas = []; $ergo = [];
foreach ($rows as $r) {
$tk = ($r['event_type'] ?? '') . '|' . ($r['severity'] ?? '');
$byType[$tk] = $byType[$tk] ?? ['event_type' => $r['event_type'], 'severity' => $r['severity'], 'count' => 0, 'unacked' => 0, 'fp' => 0];
$byType[$tk]['count']++;
if (($r['acknowledged_by'] ?? null) === null) $byType[$tk]['unacked']++;
if (($r['false_positive_by'] ?? null) !== null) $byType[$tk]['fp']++;
$cam = $r['camera_id'] ?? '';
$byCam[$cam] = $byCam[$cam] ?? ['camera_id' => $cam, 'count' => 0, 'critical_high' => 0];
$byCam[$cam]['count']++;
if (in_array($r['severity'] ?? '', ['critical', 'high'], true)) $byCam[$cam]['critical_high']++;
if (in_array($r['severity'] ?? '', ['critical', 'high'], true)
&& ($r['acknowledged_at'] ?? null) !== null && ($r['false_positive_by'] ?? null) === null
&& $r['acknowledged_at'] >= ($r['occurred_at'] ?? 0)) {
$ttaDeltas[] = $r['acknowledged_at'] - $r['occurred_at'];
}
if (($r['event_type'] ?? '') === 'ergo_report') $ergo[] = $r['metrics'] ?? [];
}
$cams = array_values($byCam);
usort($cams, fn($a, $b) => [$b['critical_high'], $b['count']] <=> [$a['critical_high'], $a['count']]);
return [
'by_type' => array_values($byType),
'by_camera' => array_slice($cams, 0, $topCameras),
'tta' => ['acked' => count($ttaDeltas),
'avg_s' => $ttaDeltas ? array_sum($ttaDeltas) / count($ttaDeltas) : null,
'max_s' => $ttaDeltas ? max($ttaDeltas) : null],
'ergo_metrics' => $ergo,
];
}
public function heatmapPoints(string $cameraId, float $since, ?string $site, int $limit): array {
$r = array_filter($this->rows, fn($x) => ($x['camera_id'] ?? '') === $cameraId
&& ($x['occurred_at'] ?? 0) >= $since
&& ($x['spatial_x'] ?? null) !== null && ($x['spatial_y'] ?? null) !== null
&& ($site === null || ($x['site'] ?? null) === $site));
usort($r, fn($a, $b) => ($b['occurred_at'] ?? 0) <=> ($a['occurred_at'] ?? 0));
return array_map(fn($x) => ['x' => (float)$x['spatial_x'], 'y' => (float)$x['spatial_y'],
'severity' => $x['severity'], 'event_type' => $x['event_type'],
'occurred_at' => (float)($x['occurred_at'] ?? 0)], array_slice(array_values($r), 0, $limit));
}
}
final class InMemorySnapshotRepository implements SnapshotRepository {
public array $rows = []; public array $paths = []; public array $created = [];
public function add(int $e, string $uuid, string $hash): void {
// Mirror the DB's UNIQUE (event_id, content_hash): a re-sent event's identical bytes
// collide instead of duplicating, so the dedup recovery path is idempotent.
foreach ($this->rows[$e] ?? [] as $r) { if ($r['content_hash'] === $hash) return; }
$this->rows[$e][] = ['file_uuid' => $uuid, 'content_hash' => $hash]; $this->paths[$uuid] = "/tmp/$uuid.jpg"; $this->created[$uuid] = time();
}
public function forEvent(int $e): array { return $this->rows[$e] ?? []; }
public function thumbUuidsFor(array $eventIds): array {
$out = [];
foreach ($eventIds as $e) {
$list = $this->rows[(int)$e] ?? [];
if ($list !== []) $out[(int)$e] = end($list)['file_uuid']; // newest = last appended
}
return $out;
}
public function pathByUuid(string $u): ?string { return $this->paths[$u] ?? null; }
public function eventIdByUuid(string $u): ?int {
foreach ($this->rows as $e => $list) foreach ($list as $r) if ($r['file_uuid'] === $u) return (int)$e;
return null;
}
/** @var array<string,string> file_uuid => camera_id, recorded by the tests that need it */
public array $cameras = [];
/** @var array<string,string> file_uuid => device_id */
public array $devices = [];
public function latestForCamera(string $cameraId): ?array {
// Insert order, newest first -- mirrors the Pdo impl's ORDER BY snapshot_id DESC.
foreach (array_reverse($this->cameras, true) as $uuid => $cam) {
if ($cam === $cameraId) return ['file_uuid' => $uuid, 'device_id' => $this->devices[$uuid] ?? ''];
}
return null;
}
public function purgeOlderThan(int $cutoff): int {
$n = 0;
foreach ($this->created as $uuid => $ts) {
if ($ts >= $cutoff) continue;
unset($this->created[$uuid], $this->paths[$uuid]);
foreach ($this->rows as $e => $list) {
$this->rows[$e] = array_values(array_filter($list, fn($r) => $r['file_uuid'] !== $uuid));
}
$n++;
}
return $n;
}
}
final class InMemoryUserRepository implements UserRepository {
public function __construct(public array $users = []) {}
public function byUsername(string $u): ?array { return $this->users[$u] ?? null; }
public function recordFailure(int $id, int $lock): void { foreach ($this->users as &$row) if ($row['id'] === $id) { $row['failed_attempts'] = ($row['failed_attempts'] ?? 0) + 1; $row['locked_until'] = $lock; } }
public function clearFailures(int $id): void { foreach ($this->users as &$row) if ($row['id'] === $id) { $row['failed_attempts'] = 0; $row['locked_until'] = 0; } }
}
final class InMemoryZoneRepository implements ZoneRepository {
public array $zones = []; private int $seq = 0;
public function forDevice(string $d): array { return array_values(array_filter($this->zones, fn($z) => ($z['device_id'] ?? '') === $d)); }
public function forCamera(string $c): array { return array_values(array_filter($this->zones, fn($z) => $z['camera_id'] === $c)); }
public function find(string $id): ?array { return $this->zones[$id] ?? null; }
public function save(array $z): string { $id = $z['zone_id'] ?? ('z' . (++$this->seq)); $this->zones[$id] = $z + ['zone_id' => $id]; return $id; }
public function delete(string $id): bool { if (!isset($this->zones[$id])) return false; unset($this->zones[$id]); return true; }
}
final class InMemoryThresholdRepository implements ThresholdRepository {
public function __construct(private array $data = []) {}
public function forDevice(string $d): array { return $this->data[$d] ?? []; }
}
final class InMemoryAuditRepository implements AuditRepository {
public array $log = [];
public function append(string $a, string $act, string $t, array $b, array $af): void { $this->log[] = compact('a', 'act', 't', 'b', 'af'); }
}