// Beta helper: ask WFDASH whether the invoice photo matches what the driver // collected on a PO. Advisory only — nothing here writes to PocketBase or // changes how collecting works. Off unless the driver switches it on in // Settings. import { pb, getSettings } from './pocketbase'; export type Verdict = 'green' | 'amber' | 'red' | 'unchecked'; export interface CheckedLine { id: string; kind: 'customer' | 'stock'; description: string; qty_collected: number; verdict: Verdict; reason: string; } export interface InvoiceCheckResult { po_number: string; lines: CheckedLine[]; all_green: boolean; error: string; } /** The WFDASH address to call, or '' when the helper is off or not set up. */ export function invoiceCheckBase(): string { const s = getSettings(); if (!s.aiCheckEnabled) return ''; const url = (s.aiCheckUrl || process.env.NEXT_PUBLIC_WFDASH_URL || '').trim(); return url.replace(/\/+$/, ''); } export async function checkInvoice(poNumber: string): Promise { const base = invoiceCheckBase(); if (!base) throw new Error('Invoice check is not set up (Settings → Beta).'); const res = await fetch(`${base}/api/v1/driver/collection-check`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${pb.authStore.token}` }, body: JSON.stringify({ po_number: poNumber }), signal: AbortSignal.timeout(120_000), }); const body = await res.json().catch(() => ({})); if (!res.ok) throw new Error(body.error || `Check failed (${res.status})`); return body as InvoiceCheckResult; } // Remembered per PO on this device: the driver looked at the result and // carried on. Purely a note for the driver; it blocks and unlocks nothing. const SEEN_KEY = 'wfdash-driver:invoice-check-seen'; export function readSeen(): Record { try { return JSON.parse(localStorage.getItem(SEEN_KEY) || '{}'); } catch { return {}; } } export function rememberSeen(poNumber: string, how: 'ok' | 'override') { try { localStorage.setItem(SEEN_KEY, JSON.stringify({ ...readSeen(), [poNumber]: how })); } catch { // Storage unavailable: the note is optional. } }