TeamQueuePage.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import { TableState } from "../components/TableState";
  2. /**
  3. * 待分派工单队列(册 5 工单域)。
  4. *
  5. * 数据面:`POST /ticket/pending_queue@v1`(行内自带 `candidates[]`,可分派性由服务端
  6. * 按类型/范围/账号状态算好,⛔ 前端再判一遍"谁能接")+ `/ticket/assign@v1` +
  7. * `/ticket/dispatch_auto@v1`(`team_id` 必填、团队须为 auto_avg,否则服务端拒绝,
  8. * 回执原文直出)。队列范围由服务端按身份收口:团队主只见本团队。
  9. *
  10. * 团队主查看本团队的待分派工单,总运营和区域运营按各自的可见范围查看队列。
  11. */
  12. import { useState } from "react";
  13. import { Check, ClipboardList, Clock3, Search, Shuffle, UserRoundCheck, UsersRound, X } from "lucide-react";
  14. import { useSearchParams } from "react-router";
  15. import { Button } from "../components/ui/button";
  16. import { FilterSelect } from "../components/ui/filter-select";
  17. import { FieldHint } from "../components/ui/field-hint";
  18. import { OpsDialog, OpsNotice } from "../components/OperationsKit";
  19. import { SearchInput } from "../components/ui/search-input";
  20. import { TicketState } from "../components/ticketState";
  21. import { WorkOrderLedgerList } from "../components/work-order/WorkOrderLedgerList";
  22. import { classifyTicketError, TICKET_PAGE_SIZE, usePendingQueue } from "../lib/ticket";
  23. import {
  24. TICKET_TYPES, ticketAssign, ticketDispatchAuto, ticketPendingQueue, typeLabel,
  25. type AssignCandidate, type DispatchResult, type PendingQueueItem,
  26. } from "../lib/api/ticket";
  27. import { useSubmit } from "../lib/useLoad";
  28. import { ListPager } from "../components/ListPager";
  29. import "../styles/operations.css";
  30. import "../styles/orders.css";
  31. import "../styles/work-orders.css";
  32. import "../styles/work-order-ledger.css";
  33. type QueueBoardProps = {
  34. /** 团队口径(团队主必传);总运营/区域运营不传=服务端按权限范围内全部团队。 */
  35. teamId?: string;
  36. teamName?: string;
  37. /** 总运营看多团队,需要「团队」列;团队主自己的队列不必重复。 */
  38. showTeamColumn?: boolean;
  39. /** 自动平均分派按团队执行:只有团队主能点,其余身份禁用并说明。 */
  40. canAutoDispatch: boolean;
  41. };
  42. export function QueueBoard({ teamId, teamName, showTeamColumn = false, canAutoDispatch }: QueueBoardProps) {
  43. const [params, setParams] = useSearchParams();
  44. const q = params.get("q") || "";
  45. const type = params.get("type") || "";
  46. const page = Math.max(1, Number(params.get("page")) || 1);
  47. // Wave F:首屏 `include_candidates:false`(~2 UDS);点「指定成员」再按工单现拉候选人。
  48. const queue = usePendingQueue(
  49. { keyword: q.trim() || undefined, ticket_types: type ? [type] : undefined, assign_team_id: teamId },
  50. page,
  51. );
  52. const rows = queue.data?.rows ?? [];
  53. const total = queue.data?.total ?? 0;
  54. const fail = queue.error ? classifyTicketError(queue.error) : null;
  55. const lateCount = rows.filter((item) => item.overdue_7d).length;
  56. const teams = new Set(rows.map((row) => row.assign_team_id).filter(Boolean)).size;
  57. const submit = useSubmit();
  58. const [action, setAction] = useState<PendingQueueItem | "auto" | null>(null);
  59. const [memberId, setMemberId] = useState("");
  60. const [tip, setTip] = useState("");
  61. const [summary, setSummary] = useState<DispatchResult | null>(null);
  62. const [notice, setNotice] = useState("");
  63. const [candidates, setCandidates] = useState<AssignCandidate[]>([]);
  64. const [candLoading, setCandLoading] = useState(false);
  65. async function openAssign(item: PendingQueueItem) {
  66. setAction(item);
  67. setMemberId("");
  68. setTip("");
  69. setSummary(null);
  70. setCandidates([]);
  71. setCandLoading(true);
  72. try {
  73. const r = await ticketPendingQueue({
  74. keyword: item.ticket_id,
  75. assign_team_id: teamId,
  76. page: 1,
  77. page_size: 1,
  78. include_candidates: true,
  79. });
  80. const hit = r.rows.find((row) => row.ticket_id === item.ticket_id) ?? r.rows[0];
  81. setCandidates(hit?.candidates ?? []);
  82. } catch (e) {
  83. setTip(classifyTicketError(e).message);
  84. } finally {
  85. setCandLoading(false);
  86. }
  87. }
  88. function filter(key: string, value: string) {
  89. setParams((current) => {
  90. const next = new URLSearchParams(current);
  91. if (value) next.set(key, value); else next.delete(key);
  92. next.delete("page");
  93. return next;
  94. }, { replace: true });
  95. }
  96. async function confirm() {
  97. if (!action) return;
  98. setTip("");
  99. if (action === "auto" && !teamId) { setTip("自动平均分派按团队执行:请切到团队主账号,或逐张指定成员。"); return; }
  100. if (action !== "auto" && !memberId) { setTip("请选择接单成员。"); return; }
  101. const ok = action === "auto"
  102. ? await submit.run(() => ticketDispatchAuto({ team_id: teamId! }).then((r) => {
  103. setSummary(r);
  104. setNotice(`已自动分派 ${r.dispatched.length} 张${r.skipped.length ? `,${r.skipped.length} 张因无合适成员或已被他人分派留在队列` : ""}(本轮扫描 ${r.scanned} 张)。`);
  105. }))
  106. : await submit.run(() => ticketAssign({ ticket_id: action.ticket_id, assignee_user_id: memberId }));
  107. if (ok) { setAction(null); setMemberId(""); setSummary(null); queue.reload(); }
  108. }
  109. const failure = submit.error ? classifyTicketError(submit.error) : null;
  110. const metrics = [
  111. { title: "待分派工单", value: total, description: q || type ? "符合当前筛选" : teamName || "账号可见范围", icon: ClipboardList },
  112. { title: "超期 / 临期", value: lateCount, description: "当前页 · 7 日内到期或已超期", icon: Clock3, tone: lateCount ? "warning" : undefined },
  113. ...(showTeamColumn ? [{ title: "涉及团队", value: teams, description: "当前页 · 已归属团队", icon: UsersRound }] : []),
  114. ];
  115. const fallback = queue.loading
  116. ? <TableState kind="loading">正在读取待分派队列…</TableState>
  117. : fail
  118. ? <TicketState listTitle="待分派工单" fail={fail} onRetry={queue.reload} />
  119. : !rows.length ? <TableState>{q || type ? "没有匹配的待分派工单" : "暂无待分派工单"}</TableState> : null;
  120. return <>
  121. <div className="work-order-ledger-summary work-order-queue-summary" role="group" aria-label="待分派队列统计" data-count={metrics.length}>
  122. {metrics.map(({ title, value, description, icon: Icon, tone }, index) => (
  123. <div className={`work-order-metric${index === 0 ? " work-order-metric-total" : ""}`} key={title} data-tone={tone}>
  124. <span className="work-order-metric-icon"><Icon size={18} aria-hidden="true" /></span>
  125. <span className="work-order-metric-body"><span>{title}</span><strong>{queue.loading ? "…" : fail ? "—" : value.toLocaleString("zh-CN")}</strong><small>{description}</small></span>
  126. </div>
  127. ))}
  128. </div>
  129. <section className="order-list-shell list-shell-fill" aria-label="待分派队列">
  130. <div className="ops-toolbar order-filters work-order-queue-filters">
  131. <label className="ops-search order-search">
  132. <Search size={17} aria-hidden="true" />
  133. <SearchInput aria-label="搜索待分派工单" placeholder="搜索工单号、工单ID或标题" value={q} onCommit={(value) => filter("q", value)} />
  134. {q && <button type="button" aria-label="清空搜索" onClick={() => filter("q", "")}><X size={15} /></button>}
  135. </label>
  136. <FilterSelect icon="type" aria-label="工单类型" value={type} onChange={(event) => filter("type", event.target.value)}>
  137. <option value="">全部类型</option>
  138. {TICKET_TYPES.map((t) => <option key={t} value={t}>{typeLabel(t)}</option>)}
  139. </FilterSelect>
  140. {(q || type) && <Button variant="ghost" size="sm" onClick={() => setParams({})}>重置筛选</Button>}
  141. <Button className="work-order-queue-auto" size="sm" variant="outline" disabled={queue.loading || !total || !canAutoDispatch} title={canAutoDispatch ? "分派本团队全部待分派工单,不受当前筛选影响" : "仅团队主账号可自动平均分派"} onClick={() => { setAction("auto"); setTip(""); setSummary(null); }}><Shuffle size={15} />自动平均分派</Button>
  142. </div>
  143. <WorkOrderLedgerList
  144. rows={rows}
  145. label="待分派工单"
  146. fallback={fallback}
  147. ownerColumn={showTeamColumn ? "team" : "none"}
  148. showNextStep={false}
  149. showStatus={false}
  150. renderRowAction={(item) => <button type="button" className="ops-table-action" onClick={() => void openAssign(item)}><UserRoundCheck size={15} />指定成员</button>}
  151. />
  152. {!queue.loading && !fail && <ListPager total={total} page={page - 1} pageSize={TICKET_PAGE_SIZE} unit="张" onPageChange={(next) => setParams((current) => {
  153. const updated = new URLSearchParams(current);
  154. if (next) updated.set("page", String(next + 1));
  155. else updated.delete("page");
  156. return updated;
  157. }, { replace: true })} />}
  158. </section>
  159. {action && <OpsDialog title={action === "auto" ? "确认自动平均分派" : "指定接单成员"} subtitle={teamName ?? "权限范围内"} onClose={() => { if (!submit.busy) setAction(null); }}>
  160. <div className="workspace-form">
  161. {action === "auto" ? <>
  162. <div className="work-order-queue-dialog-context">
  163. <Shuffle size={18} aria-hidden="true" />
  164. <div>
  165. <h3>分派本团队的待分派工单</h3>
  166. <p>工单优先分给未完成工单最少的合适成员。没有合适成员的工单会留在队列。团队须启用自动平均分派。</p>
  167. </div>
  168. </div>
  169. {summary && <p className="text-sm leading-7">上轮回执:分派 {summary.dispatched.length} 张 / 扫描 {summary.scanned} 张 / 跳过 {summary.skipped.length} 张。</p>}
  170. </> : <>
  171. <div className="work-order-queue-dialog-context">
  172. <ClipboardList size={18} aria-hidden="true" />
  173. <div>
  174. <h3>{action.ticket_no ?? "未编号"}</h3>
  175. <p>{action.customer_name ?? "—"} · {typeLabel(action.ticket_type)}</p>
  176. </div>
  177. </div>
  178. {candLoading && <p className="text-sm text-muted-foreground">正在按工单类型与负责范围计算候选人…</p>}
  179. <label className="workspace-field"><span>接单成员 <em>*</em><FieldHint label="接单成员说明">{candidates.length ? "名单由服务端按工单类型、成员负责范围与账号状态过滤(运营账号按客户负责范围入池),不支持指派名单之外的成员。" : candLoading ? "正在计算…" : "没有符合条件的成员,请先在成员与负责范围中配置后重试。"}</FieldHint></span>
  180. <select value={memberId} onChange={(event) => setMemberId(event.target.value)} disabled={candLoading}>
  181. <option value="">请选择成员</option>
  182. {candidates.map((c) => <option key={c.user_id} value={c.user_id}>{c.display_name ?? c.username ?? c.user_id}{c.source === "ops_account" ? "(运营账号)" : ""} · 未完成 {c.pending_count} 张</option>)}
  183. </select>
  184. </label>
  185. </>}
  186. {tip && <p role="alert" className="workspace-error">{tip}</p>}
  187. {failure && <p role="alert" className="workspace-error">{failure.message}</p>}
  188. {submit.busy && <p className="text-sm text-muted-foreground">提交中…</p>}
  189. <footer><Button variant="outline" type="button" disabled={submit.busy} onClick={() => setAction(null)}>取消</Button><Button type="button" disabled={submit.busy || candLoading || (action !== "auto" && !memberId)} onClick={confirm}><Check size={16} />确认分派</Button></footer>
  190. </div>
  191. </OpsDialog>}
  192. {notice && <OpsNotice key={notice} message={notice} onClose={() => setNotice("")} />}
  193. </>;
  194. }