WFDASH-WEBAPP/src/app/api/v1/visits/route.ts
Dave c8b7e1f51b feat(rep): visit check-in PWA — phone GPS, offline outbox
The rep app: open it on site, it finds who's around you, tick who you
saw, done. Third instance of the per-route-group PWA pattern already
running here (/m boss phone, /counter), so it reuses MobileAuthGate and
gets its own manifest + service worker.

Phone GPS is the primary position source, not the vehicle tracker. The
tracker knows where the bakkie is; the phone knows where the rep is,
and those diverge by a few hundred metres once the rep walks into the
plant. GPS also needs no network, which matters because mine shafts
have poor signal. The tracker is the secondary path
(GET /api/v1/visits/position) for when location is denied or
unavailable. The independently-collected vehicle trail corroborates
check-ins afterwards, so honesty doesn't depend on the phone.

Matching runs on the phone, not the server. The app caches a compact
customer snapshot and runs rankNearbyCustomers locally, so there's one
code path that behaves identically online and off — rather than a
server path plus an offline fallback that only gets exercised in the
places it's hardest to debug.

- (rep)/rep/            layout, page, check-in view, outbox
- visits-service.ts     getCustomerSnapshot, recordVisits
- POST /api/v1/visits           record a check-in
- GET  /api/v1/visits/customers snapshot for the offline cache
- GET  /api/v1/visits/position  tracker fallback
- public/manifest-rep.json, public/sw-rep.js, pickSwPath() branch

These routes authenticate with the browser session, not AGENT_API_KEY —
the caller is a logged-in rep. The rep id comes from the validated
session rather than the request body, so a client can't log a visit as
someone else.

The outbox uses localStorage rather than IndexedDB deliberately: the
payloads are tiny and localStorage is synchronous, which matters when
the rep hits Save and immediately pockets the phone. Entries are only
removed once the server acknowledges them, so a failed flush retries
instead of dropping a visit — duplicates are preferred over loss, and
surfaced rather than merged. Permanently-rejected entries (4xx other
than 401/408/429) are dropped so one bad row can't wedge the queue.

recordVisits writes each visit independently: a stale customer id
shouldn't cost the other four visits in a queued batch.

BLOCKED until one PB admin change: rep_visits.position_source does not
yet allow "phone" — verified against the live instance, PB returns
400 "Invalid value phone". Add it to the select. Separately,
accuracy_m is silently accepted and discarded (PB ignores unknown
fields), so GPS accuracy is thrown away until that number field is
added; not blocking.

47 new tests. Verified on :4001: /rep serves 200 with the right
metadata, manifest-rep.json and sw-rep.js are served.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 21:09:27 +02:00

115 lines
3.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getBrowserSessionUser } from "@/lib/server/browser-session";
import {
recordVisits,
type PositionSource,
type RecordVisitInput,
} from "@/lib/server/visits-service";
const SOURCES: PositionSource[] = ["phone", "tracker", "manual"];
/**
* POST /api/v1/visits — record a rep check-in.
*
* Authenticated with the **browser session**, not `AGENT_API_KEY`: the
* caller is a logged-in rep on their phone. The rep id comes from the
* validated session rather than the request body, so a client can't
* log a visit as someone else.
*
* A plain route rather than a Server Action because the rep PWA
* replays queued check-ins from an offline outbox — a `fetch` is
* trivial to retry from stored JSON, whereas a Server Action is bound
* to the React runtime that queued it.
*
* Body:
* {
* lat, lon required, decimal degrees
* positionSource "phone" | "tracker" | "manual"
* accuracyM? GPS accuracy in metres
* fixAgeSeconds? how old the fix was
* visitedAt? ISO; set by the phone when the check-in was
* *made*, which for a queued submission is
* hours before it reaches us
* visits: [{ customerId, notes?, pinCustomer? }]
* }
*
* Idempotency is deliberately not attempted here — see the outbox in
* the rep PWA, which only removes an entry once the server has
* acknowledged it, and surfaces duplicates to the rep rather than
* silently merging them.
*/
export async function POST(req: NextRequest) {
try {
const user = await getBrowserSessionUser(req);
const body = (await req.json().catch(() => null)) as {
lat?: unknown;
lon?: unknown;
positionSource?: unknown;
accuracyM?: unknown;
fixAgeSeconds?: unknown;
visitedAt?: unknown;
visits?: unknown;
} | null;
if (!body || typeof body !== "object") {
return NextResponse.json({ error: "JSON object body required" }, { status: 400 });
}
const { lat, lon } = body;
if (typeof lat !== "number" || typeof lon !== "number") {
return NextResponse.json(
{ error: "lat and lon are required as numbers" },
{ status: 400 }
);
}
const positionSource = SOURCES.includes(body.positionSource as PositionSource)
? (body.positionSource as PositionSource)
: "phone";
if (!Array.isArray(body.visits) || body.visits.length === 0) {
return NextResponse.json(
{ error: "visits must be a non-empty array" },
{ status: 400 }
);
}
const visits: RecordVisitInput[] = [];
for (const entry of body.visits) {
if (!entry || typeof entry !== "object") continue;
const { customerId, notes, pinCustomer } = entry as Record<string, unknown>;
if (typeof customerId !== "string" || !customerId) continue;
visits.push({
customerId,
notes: typeof notes === "string" ? notes : undefined,
pinCustomer: pinCustomer === true,
});
}
if (visits.length === 0) {
return NextResponse.json(
{ error: "no valid customer ids in visits" },
{ status: 400 }
);
}
const result = await recordVisits({
repId: user.id,
lat,
lon,
positionSource,
accuracyM: typeof body.accuracyM === "number" ? body.accuracyM : null,
fixAgeSeconds:
typeof body.fixAgeSeconds === "number" ? body.fixAgeSeconds : null,
visitedAt: typeof body.visitedAt === "string" ? body.visitedAt : undefined,
visits,
});
return NextResponse.json(result);
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to record visits";
const status = (error as Error & { status?: number }).status || 500;
return NextResponse.json({ error: message }, { status });
}
}