move_detect/server/tests/HeatmapTest.php
유창욱 9e4225a338 feat(heatmap): near-miss events + spatial ingestion + camera risk-heatmap overlay
Heinrich's-law play: the signals we already compute but used to throw away
become a spatial risk map of the workplace, drawn over the camera's own frame.

Edge:
- near_fall (INFO): a track that reached FALLING (sustained prone) but recovered
  before the FALLEN confirm. Treated as a full event per product decision -
  same ingest, snapshots, dedup, ack flow as incidents. Fix en route: prone_s
  used a truthiness check that turned prone_since=0.0 into "no timer".
- Every per-track event (fall/no_motion/near_fall/immobility/zone hits) now
  carries the foot point in the zones' normalized 0..1 space (reusing the zone
  detector's own coordinate math); ghost's pixel-space loss point is normalized
  at emit. to_payload omits the key when absent, so an old server ignores it.

Server:
- move_events.spatial_x/spatial_y (nullable DOUBLE) + validator: optional
  [x, y] finite-number pair; range deliberately NOT enforced (an off-by-a-hair
  foot must never reject a FALL alert - renderers clamp).
- MIGRATION FIX: chk_events_type would have REJECTED the previous commit's
  lone_worker/overcapacity/overstay inserts on MySQL 8.0.16+ - the constraint
  is rebuilt with all 13 types (incl. near_fall).
- GET /api/heatmap/{camera}?days=N (1..90, default 30, 5000-point cap):
  spatial points with the same fail-closed site scoping as the event list.

UI (zone editor): "위험 히트맵" toggle + day window. Additive radial blots in
an offscreen layer under the zone polygons; severity weighs the alpha so a
cluster of near-misses reads lighter than one confirmed fall at the same spot.
Events console/detail label near_fall in Korean.

Verified: pytest 222 pass / PHPUnit 130 pass + Chrome real-render (blue
near-miss cluster + red incident hotspot inside the restricted zone, amber
cluster in the warning zone, zones drawn on top; no console errors).
2026-08-06 20:19:09 +09:00

85 lines
3.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Http\Request;
use App\Auth\ArraySessionStore;
use App\Dashboard\HeatmapController;
use App\Tests\Support\InMemoryEventRepository;
use PHPUnit\Framework\TestCase;
final class HeatmapTest extends TestCase
{
private function sess(?string $site = null): ArraySessionStore
{
$s = new ArraySessionStore();
$s->set('user_id', 1);
if ($site !== null) $s->set('site_scope', $site);
return $s;
}
private function repo(): InMemoryEventRepository
{
$r = new InMemoryEventRepository();
$base = ['device_id' => 'pi-1', 'event_type' => 'near_fall', 'severity' => 'info',
'metrics' => [], 'occurred_at' => (float)time()];
// array_merge: the per-row override must WIN over $base (the `+` operator keeps the left
// side's keys, which silently discarded the old-row occurred_at override).
$r->insert(array_merge($base, ['camera_id' => 'cam-1', 'site' => 'a', 'spatial_x' => 0.4, 'spatial_y' => 0.6]));
$r->insert(array_merge($base, ['camera_id' => 'cam-1', 'site' => 'b', 'spatial_x' => 0.1, 'spatial_y' => 0.1]));
$r->insert(array_merge($base, ['camera_id' => 'cam-2', 'site' => 'a', 'spatial_x' => 0.9, 'spatial_y' => 0.9]));
$r->insert(array_merge($base, ['camera_id' => 'cam-1', 'site' => 'a'])); // no spatial
$r->insert(array_merge($base, ['camera_id' => 'cam-1', 'site' => 'a', 'spatial_x' => 0.5,
'spatial_y' => 0.5, 'occurred_at' => (float)(time() - 400 * 86400)])); // too old
return $r;
}
private function req(string $days = ''): Request
{
$q = $days === '' ? [] : ['days' => $days];
return new Request('GET', '/api/heatmap/cam-1', [], '', $q, []);
}
public function testRequiresLogin(): void
{
$c = new HeatmapController($this->repo(), new ArraySessionStore());
$this->assertSame(401, $c->json($this->req(), ['camera' => 'cam-1'])->status());
}
public function testReturnsCameraPointsWithinWindow(): void
{
$c = new HeatmapController($this->repo(), $this->sess());
$res = $c->json($this->req(), ['camera' => 'cam-1']);
$this->assertSame(200, $res->status());
$data = json_decode($res->body(), true);
$this->assertSame(30, $data['days']);
// cam-2's point, the spatial-less row, and the 400-day-old row are all excluded.
$this->assertCount(2, $data['points']);
foreach ($data['points'] as $p) {
$this->assertArrayHasKey('x', $p);
$this->assertArrayHasKey('y', $p);
$this->assertSame('near_fall', $p['event_type']);
}
}
public function testSiteScopeFiltersPoints(): void
{
$c = new HeatmapController($this->repo(), $this->sess('a'));
$data = json_decode($c->json($this->req(), ['camera' => 'cam-1'])->body(), true);
$this->assertCount(1, $data['points']); // site-b point excluded
$this->assertSame(0.4, $data['points'][0]['x']);
}
public function testDaysClamped(): void
{
$c = new HeatmapController($this->repo(), $this->sess());
$this->assertSame(90, json_decode($c->json($this->req('9999'), ['camera' => 'cam-1'])->body(), true)['days']);
$this->assertSame(30, json_decode($c->json($this->req('abc'), ['camera' => 'cam-1'])->body(), true)['days']);
}
public function testMissingCameraIs400(): void
{
$c = new HeatmapController($this->repo(), $this->sess());
$this->assertSame(400, $c->json($this->req(), [])->status());
}
}