| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210 |
- /**
- * 待分派工单队列(团队主视角,册 5 工单域)。
- *
- * 数据面:`POST /ticket/pending_queue@v1`(行内自带 `candidates[]`,可分派性由服务端
- * 按类型/范围/账号状态算好,⛔ 前端再判一遍"谁能接")+ `/ticket/assign@v1` +
- * `/ticket/dispatch_auto@v1`(`team_id` 必填、团队须为 auto_avg,否则服务端拒绝,
- * 回执原文直出)。队列范围由服务端按身份收口:团队主只见本团队。
- *
- * 2026-11-17 界面重构:队列主体抽成 [`QueueBoard`],同时服务
- * - `/workspace/queue`(团队主工作台,团队口径)
- * - `/work-orders/queue`(「工单与任务」菜单,团队主看本团队、总运营/区域运营看权限范围内全部)
- * ⛔ 复制两份队列实现——分派口径与候选人口径必须是一把尺子。
- */
- import { useState } from "react";
- import { ArrowRight, Check, ClipboardList, Clock3, Search, Shuffle, UserRoundCheck, UsersRound, X } from "lucide-react";
- import { Link, useLocation, useSearchParams } from "react-router";
- import { Button } from "../components/ui/button";
- import { FilterSelect } from "../components/ui/filter-select";
- import { FieldHint } from "../components/ui/field-hint";
- import { OpsDrawer, OpsNotice } from "../components/OperationsKit";
- import { WorkspaceEmpty, WorkspaceHeading } from "../components/RoleWorkspaceKit";
- import { SearchInput } from "../components/ui/search-input";
- import { TicketState } from "../components/ticketState";
- import { WorkOrderLedgerList } from "../components/work-order/WorkOrderLedgerList";
- import { useDemoIdentity } from "../lib/demo-session";
- import { classifyTicketError, TICKET_PAGE_SIZE, usePendingQueue } from "../lib/ticket";
- import {
- TICKET_TYPES, ticketAssign, ticketDispatchAuto, ticketPendingQueue, typeLabel,
- type AssignCandidate, type DispatchResult, type PendingQueueItem,
- } from "../lib/api/ticket";
- import { useSubmit } from "../lib/useLoad";
- import { ListPager } from "../components/ListPager";
- import "../styles/operations.css";
- import "../styles/orders.css";
- import "../styles/work-orders.css";
- import "../styles/work-order-ledger.css";
- export function TeamQueuePage() {
- const identity = useDemoIdentity();
- if (identity?.role !== "teamLead" || !identity.maintenanceTeamId) {
- return <WorkspaceEmpty title="请切换到运维团队主账号" description="待分派队列与分派操作由团队主在服务端权限内使用。" />;
- }
- return <section className="role-workspace order-page work-order-ledger page-fill">
- <WorkspaceHeading title="待分派工单" description={`为 ${identity.name} 的待分派工单安排接单人,候选人按工单类型、负责范围和账号状态筛选。`} aside={<Link className="workspace-link" to="/work-orders">查看团队工单 <ArrowRight size={15} /></Link>} />
- <QueueBoard teamId={identity.maintenanceTeamId} teamName={identity.name} canAutoDispatch />
- </section>;
- }
- type QueueBoardProps = {
- /** 团队口径(团队主必传);总运营/区域运营不传=服务端按权限范围内全部团队。 */
- teamId?: string;
- teamName?: string;
- /** 总运营看多团队,需要「团队」列;团队主自己的队列不必重复。 */
- showTeamColumn?: boolean;
- /** 自动平均分派按团队执行:只有团队主能点,其余身份禁用并说明。 */
- canAutoDispatch: boolean;
- };
- export function QueueBoard({ teamId, teamName, showTeamColumn = false, canAutoDispatch }: QueueBoardProps) {
- const [params, setParams] = useSearchParams();
- const location = useLocation();
- const q = params.get("q") || "";
- const type = params.get("type") || "";
- const page = Math.max(1, Number(params.get("page")) || 1);
- // Wave F:首屏 `include_candidates:false`(~2 UDS);点「指定成员」再按工单现拉候选人。
- const queue = usePendingQueue(
- { keyword: q.trim() || undefined, ticket_types: type ? [type] : undefined, assign_team_id: teamId },
- page,
- );
- const rows = queue.data?.rows ?? [];
- const total = queue.data?.total ?? 0;
- const fail = queue.error ? classifyTicketError(queue.error) : null;
- const lateCount = rows.filter((item) => item.overdue_7d).length;
- const teams = new Set(rows.map((row) => row.assign_team_id).filter(Boolean)).size;
- const from = location.pathname + location.search;
- const submit = useSubmit();
- const [action, setAction] = useState<PendingQueueItem | "auto" | null>(null);
- const [memberId, setMemberId] = useState("");
- const [tip, setTip] = useState("");
- const [summary, setSummary] = useState<DispatchResult | null>(null);
- const [notice, setNotice] = useState("");
- const [candidates, setCandidates] = useState<AssignCandidate[]>([]);
- const [candLoading, setCandLoading] = useState(false);
- async function openAssign(item: PendingQueueItem) {
- setAction(item);
- setMemberId("");
- setTip("");
- setSummary(null);
- setCandidates([]);
- setCandLoading(true);
- try {
- const r = await ticketPendingQueue({
- keyword: item.ticket_id,
- assign_team_id: teamId,
- page: 1,
- page_size: 1,
- include_candidates: true,
- });
- const hit = r.rows.find((row) => row.ticket_id === item.ticket_id) ?? r.rows[0];
- setCandidates(hit?.candidates ?? []);
- } catch (e) {
- setTip(classifyTicketError(e).message);
- } finally {
- setCandLoading(false);
- }
- }
- function filter(key: string, value: string) {
- setParams((current) => {
- const next = new URLSearchParams(current);
- if (value) next.set(key, value); else next.delete(key);
- next.delete("page");
- return next;
- }, { replace: true });
- }
- async function confirm() {
- if (!action) return;
- setTip("");
- if (action === "auto" && !teamId) { setTip("自动平均分派按团队执行:请切到团队主账号,或逐张指定成员。"); return; }
- if (action !== "auto" && !memberId) { setTip("请选择接单成员。"); return; }
- const ok = action === "auto"
- ? await submit.run(() => ticketDispatchAuto({ team_id: teamId! }).then((r) => {
- setSummary(r);
- setNotice(`已自动分派 ${r.dispatched.length} 张${r.skipped.length ? `,${r.skipped.length} 张因无合适成员或已被他人分派留在队列` : ""}(本轮扫描 ${r.scanned} 张)。`);
- }))
- : await submit.run(() => ticketAssign({ ticket_id: action.ticket_id, assignee_user_id: memberId }));
- if (ok) { setAction(null); setMemberId(""); setSummary(null); queue.reload(); }
- }
- const failure = submit.error ? classifyTicketError(submit.error) : null;
- const metrics = [
- { title: "待分派工单", value: total, description: q || type ? "符合当前筛选" : teamName || "账号可见范围", icon: ClipboardList },
- { title: "超期 / 临期", value: lateCount, description: "当前页 · 7 日内到期或已超期", icon: Clock3, tone: lateCount ? "warning" : undefined },
- ...(showTeamColumn ? [{ title: "涉及团队", value: teams, description: "当前页 · 已归属团队", icon: UsersRound }] : []),
- ];
- const fallback = queue.loading
- ? <div className="order-empty" role="status">正在读取待分派队列…</div>
- : fail
- ? <TicketState fail={fail} onRetry={queue.reload} />
- : !rows.length ? <div className="order-empty"><h3>{q || type ? "没有匹配的待分派工单" : "暂无待分派工单"}</h3></div> : null;
- return <>
- <div className="work-order-ledger-summary work-order-queue-summary" role="group" aria-label="待分派队列统计" data-count={metrics.length}>
- {metrics.map(({ title, value, description, icon: Icon, tone }, index) => (
- <div className={`work-order-metric${index === 0 ? " work-order-metric-total" : ""}`} key={title} data-tone={tone}>
- <span className="work-order-metric-icon"><Icon size={18} aria-hidden="true" /></span>
- <span className="work-order-metric-body"><span>{title}</span><strong>{queue.loading ? "…" : fail ? "—" : value.toLocaleString("zh-CN")}</strong><small>{description}</small></span>
- </div>
- ))}
- </div>
- <section className="order-list-shell list-shell-fill" aria-label="待分派队列">
- <div className="ops-toolbar order-filters work-order-queue-filters">
- <label className="ops-search order-search">
- <Search size={17} aria-hidden="true" />
- <SearchInput aria-label="搜索待分派工单" placeholder="搜索工单号、工单ID或标题" value={q} onCommit={(value) => filter("q", value)} />
- {q && <button type="button" aria-label="清空搜索" onClick={() => filter("q", "")}><X size={15} /></button>}
- </label>
- <FilterSelect icon="type" aria-label="工单类型" value={type} onChange={(event) => filter("type", event.target.value)}>
- <option value="">全部类型</option>
- {TICKET_TYPES.map((t) => <option key={t} value={t}>{typeLabel(t)}</option>)}
- </FilterSelect>
- {(q || type) && <Button variant="ghost" size="sm" onClick={() => setParams({})}>重置筛选</Button>}
- <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>
- </div>
- <WorkOrderLedgerList
- rows={rows}
- from={from}
- label="待分派工单"
- fallback={fallback}
- ownerColumn={showTeamColumn ? "team" : "none"}
- showNextStep={false}
- renderRowAction={(item) => <button type="button" className="ops-table-action" onClick={() => void openAssign(item)}><UserRoundCheck size={15} />指定成员</button>}
- />
- {!queue.loading && !fail && <ListPager total={total} page={page - 1} pageSize={TICKET_PAGE_SIZE} unit="张" onPageChange={(next) => setParams((current) => {
- const updated = new URLSearchParams(current);
- if (next) updated.set("page", String(next + 1));
- else updated.delete("page");
- return updated;
- }, { replace: true })} />}
- </section>
- {action && <OpsDrawer title={action === "auto" ? "确认自动平均分派" : "指定接单成员"} subtitle={teamName ?? "权限范围内"} onClose={() => setAction(null)}>
- <div className="workspace-form">
- {action === "auto" ? <>
- <Shuffle size={28} className="text-primary" />
- <h3>分派本团队的待分派工单</h3>
- <p className="text-sm leading-7 text-muted-foreground">服务端每张选择符合类型与可派条件的成员,优先分给未完成工单最少者;没有合适成员的工单留在队列。若团队分派方式不是「自动平均分派」,服务端会拒绝并说明原因。</p>
- {summary && <p className="text-sm leading-7">上轮回执:分派 {summary.dispatched.length} 张 / 扫描 {summary.scanned} 张 / 跳过 {summary.skipped.length} 张。</p>}
- </> : <>
- <p className="text-sm leading-7">{action.ticket_no ?? "未编号"}<br />{action.customer_name ?? "-"} · {typeLabel(action.ticket_type)}</p>
- {candLoading && <p className="text-sm text-muted-foreground">正在按工单类型与负责范围计算候选人…</p>}
- <label className="workspace-field"><span>接单成员 <em>*</em><FieldHint label="接单成员说明">{candidates.length ? "名单由服务端按工单类型、成员负责范围与账号状态过滤(运营账号按客户负责范围入池),不支持指派名单之外的成员。" : candLoading ? "正在计算…" : "没有符合条件的成员,请先在成员与负责范围中配置后重试。"}</FieldHint></span>
- <select value={memberId} onChange={(event) => setMemberId(event.target.value)} disabled={candLoading}>
- <option value="">请选择成员</option>
- {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>)}
- </select>
- </label>
- </>}
- {tip && <p role="alert" className="workspace-error">{tip}</p>}
- {failure && <p role="alert" className="workspace-error">{failure.message}</p>}
- {submit.busy && <p className="text-sm text-muted-foreground">提交中…</p>}
- <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>
- </div>
- </OpsDrawer>}
- {notice && <OpsNotice key={notice} message={notice} onClose={() => setNotice("")} />}
- </>;
- }
|