import { useCallback, useEffect, useId, useRef, useState } from "react"; import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; import { call, errorMessage, type Result } from "../query/queryApi"; import type { AssistantLogTurn } from "./AssistantPage"; import { interceptOpen, useOpenInPlace } from "./OpenInPlace"; import { requestStateLabel } from "./NoticeCard"; type Person = { username: string; name: string }; type DigestTicket = { ticketId: string; title: string; recordLink: string }; const currency = new Intl.NumberFormat(undefined, { style: "currency", currency: "USD" }); const text = (value: unknown): string => typeof value === "string" ? value : ""; const record = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; function assignable(body: unknown): Person[] { const users = Array.isArray(body) ? body : record(body).users; if (!Array.isArray(users)) return []; const people = users.map((user) => { const row = record(user); const username = text(user) || text(row.username); return { username, name: text(row.name) || username }; }).filter((user) => Boolean(user.username)); return people.filter((user, index) => people.findIndex((other) => other.username === user.username) === index); } const UNMOUNTED_MESSAGES = new Set(["Not Found", "Method Not Allowed"]); function ticketFailure(result: Extract, { ok: false }>, action: "assign" | "snooze"): string { // A mounted C21 route answers with its own sentence ("There is no ticket with that ID."). // An unmounted router (CA4) reaches `main.py::_error_shape`, which normalises Starlette's // generic "Not Found" / "Method Not Allowed" into error.message, or no message at all. const bare = (result.status === 404 || result.status === 405) && (result.message === errorMessage(result.status) || UNMOUNTED_MESSAGES.has(result.message)); if (bare) return action === "assign" ? "Assigning is not available in this workspace yet." : "Snoozing is not available in this workspace yet."; return result.message && result.message !== errorMessage(result.status) ? result.message : "That did not work. Try again."; } /** C22 supplies all displayed facts. C21 supplies the audience and action results. */ export function PingCard({ turn }: { turn: AssistantLogTurn }) { const payload = record(turn.payload); const ticketId = text(payload.ticketId); const title = text(payload.title); const reason = text(payload.reason); const action = text(payload.action); const recordLink = text(payload.recordLink); const amount = typeof payload.amount === "number" && Number.isFinite(payload.amount) ? payload.amount : null; const daysOverdue = typeof payload.daysOverdue === "number" && Number.isFinite(payload.daysOverdue) ? payload.daysOverdue : null; const assignedBy = new Set(Array.isArray(payload.assignedBy) ? payload.assignedBy.filter( (username): username is string => typeof username === "string" && Boolean(username)) : []); const digest: DigestTicket[] = Array.isArray(payload.digest) ? payload.digest.map((entry) => { const row = record(entry); const id = text(entry) || text(row.ticketId) || text(row.id); return { ticketId: id, title: text(row.title) || `Request ${id}`, recordLink: text(row.recordLink) }; }) : []; // S72-T14: with a host mounted, Open record shows the record in the pop-up and the hash stays. const inPlace = useOpenInPlace(); const [open, setOpen] = useState(false); const [loading, setLoading] = useState(false); const [people, setPeople] = useState([]); const [busy, setBusy] = useState(false); const [line, setLine] = useState(""); const [assignedState, setAssignedState] = useState(""); const [problem, setProblem] = useState(false); const inFlight = useRef(false); const opener = useRef(null); const restoreFocus = useRef(false); const pickerId = useId(); const closePicker = useCallback(() => { restoreFocus.current = true; setOpen(false); }, []); // Restore after disabled attributes have updated, including an Escape during a write. useEffect(() => { if (!open && !busy && restoreFocus.current) { restoreFocus.current = false; opener.current?.focus({ preventScroll: true }); } }, [open, busy]); useEffect(() => { if (!open) return; let active = true; const load = async () => { try { const result = await call(`/tickets/${encodeURIComponent(ticketId)}/assignable`, {}, assignable); if (!active) return; if (result.ok) setPeople(result.value); else { setProblem(true); setLine(ticketFailure(result, "assign")); closePicker(); } } catch { if (active) { setProblem(true); setLine("That did not work. Try again."); closePicker(); } } finally { if (active) setLoading(false); } }; void load(); return () => { active = false; }; }, [open, ticketId, closePicker]); const choose = async (person: Person) => { if (inFlight.current) return; inFlight.current = true; setBusy(true); setLine(""); setProblem(false); try { const result = await call(`/tickets/${encodeURIComponent(ticketId)}/assign`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ to: person.username }), }, () => true); setProblem(!result.ok); if (result.ok) setAssignedState(`With ${person.name}`); setLine(result.ok ? `Assigned to ${person.name}.` : ticketFailure(result, "assign")); closePicker(); } catch { setProblem(true); setLine("That did not work. Try again."); closePicker(); } finally { inFlight.current = false; setBusy(false); } }; const snooze = async () => { if (inFlight.current) return; if (!ticketId) { setProblem(true); setLine("This ping does not name a request."); return; } inFlight.current = true; setBusy(true); setLine(""); setProblem(false); if (open) closePicker(); try { const result = await call(`/tickets/${encodeURIComponent(ticketId)}/snooze`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}), }, () => true); setProblem(!result.ok); setLine(result.ok ? "Snoozed until tomorrow." : ticketFailure(result, "snooze")); } catch { setProblem(true); setLine("That did not work. Try again."); } finally { inFlight.current = false; setBusy(false); } }; return

Wake-up

{title ?

{title}

: null} {!digest.length && ticketId ?

{assignedState || requestStateLabel(payload)}

: null} {amount !== null || daysOverdue !== null ?
{amount !== null ? {currency.format(amount)} : null} {daysOverdue !== null ? {daysOverdue} days overdue : null}
: null} {reason ?

{reason}

: null} {action ?

Suggested action: {action}

: null} {assignedBy.size ?

Assigned by {assignedBy.size} {assignedBy.size === 1 ? "person" : "people"}

: null} {digest.length ? : null}
{recordLink ? { interceptOpen(inPlace, recordLink, event); }}>Open record : null}
{line ?

{line}

: null} {/* No className on the overlay: its bare `cg-overlay` class is the one index.css already scrolls (W62-T33, `.cg-overlay[class="cg-overlay"]`); the picker's look is the inner box. */} {open ?
{loading ?
: people.length ? people.map((person) => ) :

No one can be assigned to this request.

}
: null}
; } export default PingCard;