File size: 9,849 Bytes
aa1490a
 
 
 
1ad1eea
98c8696
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c8696
aa1490a
 
1ad1eea
 
aa1490a
 
 
 
 
98c8696
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c8696
aa1490a
 
 
 
 
 
 
 
 
 
 
98c8696
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c8696
aa1490a
 
 
 
 
 
 
 
 
 
1ad1eea
 
aa1490a
 
 
1ad1eea
 
aa1490a
 
 
 
98c8696
aa1490a
 
 
 
 
 
 
 
98c8696
aa1490a
 
 
 
 
98c8696
aa1490a
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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<string, unknown> =>
  value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};

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<Result<unknown>, { 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<Person[]>([]);
  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<HTMLButtonElement>(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 <section className="as-ping" aria-label={title || "Wake-up"}>
    <p className="as-ping-label">Wake-up</p>
    {title ? <h3 className="as-ping-title">{title}</h3> : null}
    {!digest.length && ticketId ? <p className="as-ping-assigned" role="status">{assignedState || requestStateLabel(payload)}</p> : null}
    {amount !== null || daysOverdue !== null ? <div className="as-ping-facts">
      {amount !== null ? <span className="as-ping-fact" aria-label="Overdue amount">{currency.format(amount)}</span> : null}
      {daysOverdue !== null ? <span className="as-ping-fact">{daysOverdue} days overdue</span> : null}
    </div> : null}
    {reason ? <p className="as-ping-reason">{reason}</p> : null}
    {action ? <p className="as-ping-action">Suggested action: {action}</p> : null}
    {assignedBy.size ? <p className="as-ping-assigned">Assigned by {assignedBy.size} {assignedBy.size === 1 ? "person" : "people"}</p> : null}
    {digest.length ? <ul className="as-ping-digest">
      {digest.map((ticket, index) => <li className="as-ping-ticket" key={`${ticket.ticketId}-${index}`}>
        <span>{ticket.title}</span>
        {ticket.recordLink ? <a className="as-ping-button" href={ticket.recordLink} aria-label={`Open ${ticket.title}`}
          onClick={(event) => { interceptOpen(inPlace, ticket.recordLink, event); }}>Open</a> : null}
      </li>)}
    </ul> : null}
    <div className="as-ping-actions">
      {recordLink ? <a className="as-ping-button" href={recordLink}
        onClick={(event) => { interceptOpen(inPlace, recordLink, event); }}>Open record</a> : null}
      <button type="button" className="as-ping-button" ref={opener} aria-expanded={open}
        aria-haspopup="dialog" aria-controls={open ? pickerId : undefined} disabled={busy}
        onClick={() => {
          if (open) { closePicker(); return; }
          if (!ticketId) { setProblem(true); setLine("This ping does not name a request."); return; }
          setLine(""); setProblem(false); setPeople([]); setLoading(true); setOpen(true);
        }}>Assign</button>
      <button type="button" className="as-ping-button" disabled={busy} onClick={() => void snooze()}>Snooze</button>
    </div>
    {line ? <p className={`as-ping-result${problem ? " as-ping-problem" : ""}`} role="status">{line}</p> : 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 ? <AnchoredOverlay anchor={opener.current} className="" id={pickerId}
      role="dialog" ariaLabel="Assign request" onDismiss={closePicker} restoreFocus={false}
      initialFocus={loading ? "none" : "first"}>
      <div className="as-ping-picker">
        {loading ? <div className="as-ping-skeleton" role="status" aria-label="Loading people" />
          : people.length ? people.map((person) => <button key={person.username} type="button"
            className="as-ping-button as-ping-person" disabled={busy} onClick={() => void choose(person)}>{person.name}</button>)
          : <p className="as-ping-empty">No one can be assigned to this request.</p>}
      </div>
    </AnchoredOverlay> : null}
  </section>;
}

export default PingCard;