TeamQueuePage.tsx 13 KB

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