CustomerTicketPages.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /**
  2. * 门户提交工单(册 5 §6.2;enterprise 主账号/sub 下属分账号)。
  3. *
  4. * 真调 `POST /ticket/create@v1`:
  5. * - 只收 `fault`/`after_sale`(create.rs `CREATE_TYPES`),开户/停机/服务开通联系运营办理;
  6. * - `customer_id` ⛔ 由前端传——服务端按登录会话派生(`resolve_customer`,跨客户 `KLT-C007`);
  7. * - `title` 是服务端必填(≤128 字),⛔ 服务端替提交方编标题;
  8. * - 「挂接团队自动分派」是服务端行为(分派引擎),⛔ 在本地演示数据里复刻;
  9. * ⚠️ 建单层**不做**同类未完成并入(2026-11-18 撤除),一次提交=一张单;
  10. * - 附件:`material_grant` 要 `ticket_id`,建单前拿不到上传凭证,
  11. * ⛔ 把未上传的文件名随单提交,材料在建单后到工单详情直传(§5.8)。
  12. */
  13. import { useCallback, useEffect, useRef, useState, type FormEvent } from "react";
  14. import { ArrowRight, Check, CircleAlert, ClipboardCheck, ClipboardList, Clock3, FileText, Info, RefreshCw, Search, Send, X } from "lucide-react";
  15. import { Link, useLocation, useSearchParams } from "react-router";
  16. import { Button } from "../components/ui/button";
  17. import { SearchInput } from "../components/ui/search-input";
  18. import { FilterSelect } from "../components/ui/filter-select";
  19. import { DateRangeFilter } from "../components/ui/date-range-filter";
  20. import { FieldHint } from "../components/ui/field-hint";
  21. import { ServerListPager } from "../components/ListPager";
  22. import { TicketState } from "../components/ticketState";
  23. import { TicketStatusTag, TicketTypeTag } from "../components/work-order/TicketBadges";
  24. import { PageIntro } from "../components/PageIntro";
  25. import { WorkspaceEmpty, WorkspaceHeading, WorkspacePanel } from "../components/RoleWorkspaceKit";
  26. import { OpsNotice, OpsTableColumns } from "../components/OperationsKit";
  27. import { useDemoIdentity } from "../lib/demo-session";
  28. import { readCustomers } from "../lib/customer-records";
  29. import { detailLinkState } from "../lib/detail-navigation";
  30. import { classifyTicketError, fmtTime, TICKET_PAGE_SIZE, useTicketDetail, useTicketList } from "../lib/ticket";
  31. import { ticketCreate, TICKET_STATUSES, TICKET_TYPES, statusLabel, nonMainlineStatusLabel, typeLabel, ticketConfirmClose, ticketWithdraw } from "../lib/api/ticket";
  32. import type { TicketListItem } from "../lib/api/ticket";
  33. import { useSubmit } from "../lib/useLoad";
  34. import { customerLiveTicketActions } from "../lib/customer-workspace";
  35. import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
  36. import { useTicketStatusCounts } from "../lib/work-order-counts";
  37. import "../styles/operations.css";
  38. import "../styles/orders.css";
  39. import "../styles/work-orders.css";
  40. import "../styles/work-order-ledger.css";
  41. export function CustomerSubmitPage() {
  42. const location = useLocation();
  43. const identity = useDemoIdentity();
  44. const customer = readCustomers().find((item) => item.no === identity?.customerNo);
  45. const [type, setType] = useState<"fault" | "after_sale">("fault");
  46. const [title, setTitle] = useState("");
  47. const [description, setDescription] = useState("");
  48. const [errors, setErrors] = useState({ title: "", desc: "" });
  49. const [done, setDone] = useState<{ id: string; no: string } | null>(location.state?.submittedTicket ?? null);
  50. const detailState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, submittedTicket: done });
  51. const submit = useSubmit();
  52. if (!identity || !["enterprise", "sub"].includes(identity.role)) return <WorkspaceEmpty title="请切换到客户账号" description="故障与售后提交入口面向客户侧账号;运维请在工单管理代办。" />;
  53. async function onSubmit(event: FormEvent) {
  54. event.preventDefault();
  55. setDone(null);
  56. // D-17:⛔ HTML5 required 静默拦截——浏览器先拦则提示永不出现;校验一律走这里。
  57. // 一次提交收集**全部**缺失项一并回显,⛔ 只报第一条(修完一条又冒下一条=挤牙膏)。
  58. const next = {
  59. title: title.trim().length < 2 || title.trim().length > 128 ? "请填写事项标题(2–128 字,服务端必填)。" : "",
  60. desc: description.trim().length < 2 ? "请至少填写 2 个字,描述具体事项。" : "",
  61. };
  62. setErrors(next);
  63. if (next.title || next.desc) return;
  64. const ok = await submit.run(() => ticketCreate({
  65. ticket_type: type,
  66. title: title.trim(),
  67. detail: description.trim(),
  68. }).then((r) => {
  69. setDone({ id: r.ticket_id, no: r.ticket_no });
  70. setTitle(""); setDescription("");
  71. }));
  72. if (!ok) return;
  73. }
  74. const failure = submit.error ? classifyTicketError(submit.error) : null;
  75. const titleInvalid = Boolean(errors.title);
  76. const descInvalid = Boolean(errors.desc);
  77. return <section className="role-workspace">
  78. <WorkspaceHeading title="提交故障或售后" description={`为 ${customer?.name ?? identity.customerNo ?? "本企业"} 提交服务请求,运维团队受理后可在工单中跟进。`} aside={<Link className="workspace-link" to="/workspace/progress">查看工单进度 <ArrowRight size={15} /></Link>} />
  79. <div className="workspace-split">
  80. <WorkspacePanel title="描述需要协助的事项" description="尽量说明发生时间、影响范围和具体表现,便于团队定位。">
  81. {done && <div className="workspace-success" role="status"><Check size={18} /><span>{`工单 ${done.no} 已提交,运维团队将尽快与您联系。`} <Link className="workspace-link" to={`/work-orders/${encodeURIComponent(done.no ?? done.id)}`} state={detailState}>查看工单 <ArrowRight size={14} /></Link></span></div>}
  82. <form className="workspace-form !pt-0" noValidate onSubmit={onSubmit}>
  83. <label className="workspace-field"><span>事项类型 <em>*</em></span><select value={type} onChange={(event) => setType(event.target.value as "fault" | "after_sale")}><option value="fault">故障报修</option><option value="after_sale">售后服务</option></select></label>
  84. <label className="workspace-field"><span>事项标题 <em>*</em><FieldHint label="事项标题说明">受理方按标题快速识别事项,最长 128 字。</FieldHint></span><input maxLength={128} placeholder="一句话说明诉求" value={title} aria-invalid={titleInvalid || undefined} aria-describedby={titleInvalid ? "submit-title-error" : undefined} onChange={(event) => { setTitle(event.target.value); setErrors((prev) => (prev.title ? { ...prev, title: "" } : prev)); }} />{titleInvalid && <small id="submit-title-error" className="workspace-error" role="alert">{errors.title}</small>}</label>
  85. <label className="workspace-field"><span>问题描述 <em>*</em></span><textarea maxLength={1000} rows={7} placeholder="例如:今天上午办公应用无法访问,已重启客户端,仍提示连接超时……" value={description} aria-invalid={descInvalid || undefined} aria-describedby={descInvalid ? "submit-desc-error" : undefined} onChange={(event) => { setDescription(event.target.value); setErrors((prev) => (prev.desc ? { ...prev, desc: "" } : prev)); }} /><small>{description.length} / 1000 字</small>{descInvalid && <small id="submit-desc-error" className="workspace-error" role="alert">{errors.desc}</small>}</label>
  86. <p className="text-[13px] leading-6 text-muted-foreground">现场照片、录音等材料请在工单创建后到工单详情上传。</p>
  87. {(errors.title || errors.desc) && <p className="workspace-error" role="alert">请补全以下内容后重新提交:{[errors.title, errors.desc].filter(Boolean).join(";")}</p>}
  88. {failure && <p className="workspace-error" role="alert">{failure.message}</p>}
  89. {submit.busy && <p className="text-sm text-muted-foreground">提交中…</p>}
  90. <footer><Button type="submit" disabled={submit.busy}><Send size={16} />提交工单</Button></footer>
  91. </form>
  92. </WorkspacePanel>
  93. <aside className="workspace-panel workspace-aside">
  94. <h3>提交之后会发生什么</h3>
  95. <ol>
  96. <li><strong>团队受理与分派</strong><br />工单先进入挂接的运维团队,由团队主账号安排责任人。</li>
  97. <li><strong>处理与进度记录</strong><br />在「工单进度」中查看处理记录和结果;本人提交的单在完成前可填写原因撤回。</li>
  98. <li><strong>确认关闭</strong><br />运维标记完成后,由提交人确认关闭,形成服务闭环。</li>
  99. </ol>
  100. <p className="mt-5 border-t border-border pt-4 text-[13px]">每次提交都会生成一张独立工单,请在「工单进度」中分别跟踪。此入口只受理故障与售后;开户、停机与套餐变更请联系运营办理。</p>
  101. </aside>
  102. </div>
  103. </section>;
  104. }
  105. /* ═════════════════ 工单进度=客户侧「我的工单」(缺陷 P-21)════════════════ */
  106. /**
  107. * 客户侧「我的工单」列表(手册 P7 第 172-185 行:建单 → 团队分派 → 运维处理并标记完成
  108. * → **客户点「确认完成,关闭工单」** → 7 天未确认由系统自动关闭;在办期间可填原因撤回)。
  109. *
  110. * 存在理由(缺陷 P-21,2026-11-14 实测):`/workspace/progress` 此前直接挂运营侧
  111. * `WorkOrderLedgerPage`,那是运营口径的列集与取数,客户账号打开既看不到自己的单,
  112. * 也没有「确认完成,关闭工单」和「撤回」的任何入口⇒ 手册要求的客户侧闭环断在这一步。
  113. * 这里⛔ 复用运营台账页(那会把客户/团队/责任人这些客户不该关心的口径一起摊开,
  114. * 也⛔ 复制一份 900 行台账),只走真实接口:
  115. * - 行集与状态统计=`POST /ticket/list@v1`,服务端按会话控制可见范围。
  116. * - 操作=`POST /ticket/confirm_close@v1`/`POST /ticket/withdraw@v1`(`finalize.rs`)。
  117. * ⛔ 调 `/ticket/confirm_done@v1`:后端没有这条路由,网关按「未声明即拒绝」拦(C-5)。
  118. * ⛔ 把本件的按钮判定当权限边界:闸门在 `finalize.rs`,这里只是⛔ 给客户无效点击。
  119. */
  120. export function CustomerTicketProgressPage() {
  121. const identity = useDemoIdentity();
  122. if (identity?.role !== "enterprise" && identity?.role !== "sub") return <WorkspaceEmpty title="请切换到客户账号" description="工单进度面向企业客户与子账号;运维请到「工单管理」。" />;
  123. return <CustomerTicketProgressLedger key={identity.customerNo} />;
  124. }
  125. function CustomerTicketProgressLedger() {
  126. /**
  127. * 筛选与页码落在 URL 上(`?q=&status=&page=`),⛔ 只放组件内 state。
  128. *
  129. * 2026-11-18 实测:客户在这里点「详情」进 `/work-orders/:no`,再点「返回工单列表」回到的
  130. * 是另一张列表(运营台账口径)——既不是本页,进来时的关键词/状态/页码也全丢。修好返回
  131. * 目标后,本页必须能按 URL 原样复原,否则「回到同一张列表」仍做不到。
  132. */
  133. const [searchParams, setSearchParams] = useSearchParams();
  134. const location = useLocation();
  135. const keyword = searchParams.get("q") ?? "";
  136. const status = searchParams.get("status") ?? "";
  137. const type = searchParams.get("type") ?? "";
  138. const from = searchParams.get("from") ?? "";
  139. const to = searchParams.get("to") ?? "";
  140. const page = Math.max(1, Number(searchParams.get("page")) || 1);
  141. const [notice, setNotice] = useState("");
  142. const [active, setActive] = useState<TicketListItem | null>(null);
  143. /**
  144. * 「提交方」回填补:`read.rs` 的 `LIST_COLS` ⛔ 下发 `submitter_type`,客户点过一次「办理」
  145. * 后把详情拿到的值记在这里,用于回填本行的提交方列与按钮文案。
  146. * ⛔ 换成"进页面就给每行拉一次详情"把整页拼出来(契约 14.3 明令禁止的拼接取数)。
  147. */
  148. const [submitterById, setSubmitterById] = useState<Record<string, string>>({});
  149. const rememberSubmitter = useCallback((ticketId: string, submitterType: string | null) => {
  150. if (!submitterType) return;
  151. setSubmitterById((prev) => (prev[ticketId] === submitterType ? prev : { ...prev, [ticketId]: submitterType }));
  152. }, []);
  153. const list = useTicketList({
  154. keyword: keyword.trim() || undefined,
  155. statuses: status ? [status] : undefined,
  156. ticket_types: type ? [type] : undefined,
  157. date_from: from || undefined,
  158. date_to: to || undefined,
  159. }, page);
  160. const counts = useTicketStatusCounts(TICKET_STATUSES);
  161. const tableOverflow = useHorizontalOverflow();
  162. /** 写 URL:空值删键;换筛选(未显式给 `page`)一律回第 1 页。 */
  163. function patchParams(patch: Record<string, string>) {
  164. const next = new URLSearchParams(searchParams);
  165. Object.entries(patch).forEach(([key, value]) => (value ? next.set(key, value) : next.delete(key)));
  166. if (!("page" in patch)) next.delete("page");
  167. setSearchParams(next);
  168. }
  169. const rows = list.data?.rows ?? [];
  170. const total = list.data?.total ?? 0;
  171. const pages = Math.max(1, Math.ceil(total / TICKET_PAGE_SIZE));
  172. const currentPage = Math.min(page, pages);
  173. const fail = list.error ? classifyTicketError(list.error) : null;
  174. /** 进详情的「来路」=本页当前 URL(含筛选与页码),返回时逐字复原。 */
  175. const detailState = detailLinkState(location.pathname + location.search + location.hash, location.state);
  176. const filtered = Boolean(keyword || status || type || from || to);
  177. const visibleCounts = counts.error ? null : counts.data;
  178. const displayCount = (key: string) => visibleCounts?.[key]?.toLocaleString("zh-CN") ?? (counts.loading ? "…" : "—");
  179. const metrics = [
  180. { title: "工单总量", key: "total", icon: ClipboardList },
  181. { title: "处理中", key: "processing", icon: Clock3 },
  182. { title: "待确认", key: "completed", icon: ClipboardCheck },
  183. { title: "已办结", key: "settled", icon: Check },
  184. ];
  185. function reloadProgress() {
  186. list.reload();
  187. counts.reload();
  188. }
  189. return <section className="order-page work-order-ledger customer-ticket-progress page-fill page-fill-window">
  190. <header className="order-heading">
  191. <div>
  192. <h1>工单进度</h1>
  193. <PageIntro>跟进工单处理进度,查看处理结果并确认办结。</PageIntro>
  194. </div>
  195. <Link className="customer-progress-submit" to="/workspace/submit"><FileText size={17} aria-hidden="true" />提交故障或售后</Link>
  196. </header>
  197. <div className="work-order-ledger-summary" role="group" aria-label="工单统计">
  198. {metrics.map(({ title, key, icon: Icon }) => (
  199. <div className={key === "total" ? "work-order-metric work-order-metric-total" : "work-order-metric"} key={key}>
  200. <span className="work-order-metric-icon"><Icon size={18} aria-hidden="true" /></span>
  201. <span className="work-order-metric-body"><span>{title}</span><strong>{displayCount(key)}</strong></span>
  202. </div>
  203. ))}
  204. </div>
  205. <section className="order-list-shell list-shell-fill" aria-label="工单列表">
  206. <div className="order-tabs" role="group" aria-label="按工单状态筛选" aria-describedby="customer-progress-count-scope">
  207. <span className="sr-only" id="customer-progress-count-scope">角标为当前账号可见的工单数量。</span>
  208. <button type="button" className={!status ? "active" : ""} aria-pressed={!status} onClick={() => patchParams({ status: "" })}>
  209. 全部状态<span>{displayCount("total")}</span>
  210. </button>
  211. {TICKET_STATUSES.map((code) => (
  212. <button key={code} type="button" className={status === code ? "active" : ""} aria-pressed={status === code} onClick={() => patchParams({ status: code })}>
  213. {code === "completed" ? "待确认" : nonMainlineStatusLabel(code)}<span>{displayCount(code)}</span>
  214. </button>
  215. ))}
  216. </div>
  217. <div className="ops-toolbar order-filters">
  218. <label className="ops-search order-search">
  219. <Search size={17} aria-hidden="true" />
  220. <SearchInput aria-label="搜索我的工单" placeholder="搜索工单号或事项标题" value={keyword} onCommit={(value) => patchParams({ q: value })} />
  221. {keyword && <button type="button" aria-label="清空搜索" onClick={() => patchParams({ q: "" })}><X size={15} /></button>}
  222. </label>
  223. <FilterSelect icon="type" aria-label="工单类型筛选" value={type} onChange={(event) => patchParams({ type: event.target.value })}>
  224. <option value="">全部类型</option>
  225. {TICKET_TYPES.map((code) => <option key={code} value={code}>{typeLabel(code)}</option>)}
  226. </FilterSelect>
  227. <DateRangeFilter label="提交时间" from={from} to={to} constrainRange onChange={(key, value) => patchParams({ [key]: value })} />
  228. {filtered && <Button variant="ghost" size="sm" onClick={() => setSearchParams(new URLSearchParams())}>重置筛选</Button>}
  229. <Button className="customer-progress-refresh" variant="ghost" size="sm" onClick={reloadProgress}><RefreshCw size={15} />刷新</Button>
  230. </div>
  231. <div
  232. ref={tableOverflow.ref}
  233. className={`measured-table-scroll order-ledger-scroll${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}
  234. role="region"
  235. aria-label="我的工单列表,可横向滚动查看字段"
  236. tabIndex={0}
  237. >
  238. {list.loading ? <div className="order-empty" role="status">正在读取工单…</div>
  239. : fail ? <TicketState fail={fail} onRetry={reloadProgress} />
  240. : !rows.length ? <div className="order-empty">
  241. {filtered ? <Search size={26} aria-hidden="true" /> : <ClipboardList size={26} aria-hidden="true" />}
  242. <h3>{filtered ? "没有匹配的工单" : "暂无工单"}</h3>
  243. {filtered
  244. ? <Button variant="ghost" size="sm" onClick={() => setSearchParams(new URLSearchParams())}>重置筛选</Button>
  245. : <Link className="ops-table-action" to="/workspace/submit">提交故障或售后<ArrowRight size={14} aria-hidden="true" /></Link>}
  246. </div> : <table className="order-table order-ledger customer-progress-table">
  247. <OpsTableColumns widths={[250, 112, 122, 100, 115, 132, 132, 155]} />
  248. <thead><tr>{["事项 / 工单号", "类型", "状态", "提交方", "要求完成", "竣工时间", "提交时间", "操作"].map((column) => <th key={column} scope="col">{column}</th>)}</tr></thead>
  249. <tbody>{rows.map((item) => {
  250. const submitterType = item.submitter_type ?? submitterById[item.ticket_id] ?? null;
  251. const gate = customerLiveTicketActions({ status: item.status, ticket_type: item.ticket_type, submitter_type: submitterType });
  252. const actionLabel = gate.confirmClose ? "确认关闭" : gate.withdraw ? "撤回" : "办理";
  253. const number = item.ticket_no ?? item.ticket_id;
  254. return <tr key={item.ticket_id}>
  255. <td>
  256. <strong className="table-cell-title" title={item.title ?? undefined}>{item.title || <span className="table-placeholder">未填写标题</span>}</strong>
  257. <small title={item.ticket_no ?? undefined}>{item.ticket_no || "—"}</small>
  258. </td>
  259. <td><TicketTypeTag type={item.ticket_type} /></td>
  260. <td><TicketStatusTag status={item.status} type={item.ticket_type} /></td>
  261. <td>{submitterType ? SUBMITTER_NAMES[submitterType] ?? submitterType : <span className="table-placeholder">未回传</span>}</td>
  262. <td className="order-date">{item.expected_done_date?.slice(0, 10) || <span className="table-placeholder">—</span>}</td>
  263. <td className="order-date">{item.completed_at ? fmtTime(item.completed_at) : <span className="table-placeholder">—</span>}</td>
  264. <td className="order-date">{item.created_at ? fmtTime(item.created_at) : <span className="table-placeholder">—</span>}</td>
  265. <td><div className="ops-inline-actions">
  266. {(gate.confirmClose || gate.withdraw || gate.needsDetail) && <button className="ops-table-action" type="button" onClick={() => setActive(item)}>{actionLabel}</button>}
  267. <Link className="ops-table-action" to={`/work-orders/${encodeURIComponent(number)}`} state={detailState} aria-label={`查看工单 ${number} 详情`}>详情<ArrowRight size={14} aria-hidden="true" /></Link>
  268. </div></td>
  269. </tr>;
  270. })}</tbody>
  271. </table>}
  272. </div>
  273. {!list.loading && !fail && <ServerListPager total={total} page={currentPage} pageSize={TICKET_PAGE_SIZE} unit="张" onPageChange={(next) => patchParams({ page: next > 1 ? String(next) : "" })} />}
  274. </section>
  275. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  276. {active && <CustomerTicketActionSheet row={active} onClose={() => setActive(null)} onResolved={rememberSubmitter} onDone={(message) => { setActive(null); setNotice(message); reloadProgress(); }} />}
  277. </section>;
  278. }
  279. /** 提交方显示名(`tickets.submitter_type` 口径见 `docs/需求文档/14-API接口契约.md`)。 */
  280. const SUBMITTER_NAMES: Record<string, string> = { customer: "本人提交", ops: "运维代建", system: "系统生成", unicom: "运营商报文" };
  281. /**
  282. * 「办理」弹框:先就该单取**一次**详情定闸门,再给「确认完成,关闭工单」/「撤回」。
  283. *
  284. * `read_event=false`:客户只是来看进度并确认结果,⛔ 一次查看就把待处理单推进成处理中
  285. * (那是运维接手的语义,服务端按 `read_event` 决定是否记接手事件)。
  286. * 撤回原因必填=`finalize.rs` 的 `WithdrawReq`(`reason` 为空回参数校验失败)。
  287. * `expected_version`=详情头的 `row_version`(乐观锁):并发下版本不符由服务端拒,
  288. * 回执经 `classifyTicketError` 原样显示,⛔ 静默重试覆盖对方。
  289. */
  290. function CustomerTicketActionSheet({ row, onClose, onResolved, onDone }: {
  291. row: TicketListItem;
  292. onClose: () => void;
  293. onResolved: (ticketId: string, submitterType: string | null) => void;
  294. onDone: (message: string) => void;
  295. }) {
  296. const detail = useTicketDetail(row.ticket_id, false);
  297. const submit = useSubmit();
  298. const location = useLocation();
  299. const [reason, setReason] = useState("");
  300. const ref = useRef<HTMLDialogElement>(null);
  301. const head = detail.data?.ticket ?? null;
  302. /** 「查看完整记录」=从本弹框(仍在本列表页)进详情,返回目标就是这张列表。 */
  303. const detailState = detailLinkState(location.pathname + location.search + location.hash, location.state);
  304. useEffect(() => {
  305. const el = ref.current;
  306. if (!el) return;
  307. // ⚠️ 属性 `open` 与 showModal() ⛔ 同时置:React 先把 open 写进 DOM,effect 再调 showModal()
  308. // 会抛 InvalidStateError(2026-11-13 实测抽屉打不开)。已开就跳过。
  309. if (el.open) return;
  310. if (typeof el.showModal === "function") el.showModal();
  311. else el.open = true;
  312. }, []);
  313. const submitterType = head?.submitter_type ?? null;
  314. useEffect(() => { if (submitterType) onResolved(row.ticket_id, submitterType); }, [onResolved, row.ticket_id, submitterType]);
  315. const gate = head ? customerLiveTicketActions({ status: head.status, ticket_type: head.ticket_type, submitter_type: head.submitter_type }) : null;
  316. const detailFail = detail.error ? classifyTicketError(detail.error) : null;
  317. const tip = submit.error ? classifyTicketError(submit.error).message : "";
  318. async function act(kind: "confirm" | "withdraw") {
  319. if (!head) return;
  320. const version = Number(head.row_version);
  321. const ok = await submit.run(() => kind === "confirm"
  322. ? ticketConfirmClose({ ticket_id: head.ticket_id, expected_version: Number.isFinite(version) ? version : undefined })
  323. : ticketWithdraw({ ticket_id: head.ticket_id, reason: reason.trim() }));
  324. if (ok) onDone(kind === "confirm" ? `工单 ${head.ticket_no} 已确认完成并关闭。` : `工单 ${head.ticket_no} 已撤回并关闭。`);
  325. }
  326. return <dialog ref={ref} className="work-order-drawer" aria-label="工单办理" onCancel={onClose} onClick={(event) => { if (event.target === ref.current) onClose(); }}>
  327. <header><div><p className="work-order-eyebrow"><span /> CUSTOMER SUPPORT / 工单办理</p><h2>{row.ticket_no ?? "工单办理"}</h2><p>{typeLabel(row.ticket_type)} · {row.title}</p></div><button type="button" aria-label="关闭" onClick={onClose}><X size={17} /></button></header>
  328. <div className="work-order-editor">
  329. {detail.loading && !head && <div className="work-order-empty"><RefreshCw size={27} /><h3>正在核对可执行的操作…</h3></div>}
  330. {detailFail && <TicketState fail={detailFail} onRetry={detail.reload} />}
  331. {head && gate && <>
  332. <div className="work-order-editor-note"><Info size={17} /><span>当前状态:{statusLabel(head.status, head.ticket_type)} · 提交方:{SUBMITTER_NAMES[head.submitter_type ?? ""] ?? head.submitter_type ?? "未回传"} · 要求完成 {head.expected_done_date ? head.expected_done_date.slice(0, 10) : "—"} · 竣工 {fmtTime(head.completed_at)}{head.confirm_deadline ? ` · 自动关闭期限 ${fmtTime(head.confirm_deadline)}` : ""}</span></div>
  333. {gate.confirmClose && <div className="work-order-editor-note"><Check size={17} /><span>运维已标记完成,等您确认:确认后工单立即关闭;按手册 P7,7 天内未确认由系统自动关闭。</span></div>}
  334. {gate.withdraw && <div className="work-order-editor-note"><Clock3 size={17} /><span>该单仍在处理中,可以撤回:撤回即关闭工单,请填写原因(工单§5.1.9:原因必填)。</span></div>}
  335. {gate.blockedReason && <div className="work-order-editor-note"><CircleAlert size={17} /><span>{gate.blockedReason}</span></div>}
  336. {gate.withdraw && <form className="work-order-form-grid" onSubmit={(event: FormEvent) => { event.preventDefault(); void act("withdraw"); }}><label className="wide">撤回原因 <em>*</em><textarea rows={3} maxLength={500} value={reason} placeholder="例如:故障已自行恢复,无需处理" onChange={(event) => setReason(event.target.value)} /></label></form>}
  337. {tip && <p className="work-order-form-error" role="alert">{tip}</p>}
  338. <div className="work-order-detail-actions">
  339. <Button variant="ghost" size="sm" onClick={onClose}>返回</Button>
  340. <Link to={`/work-orders/${encodeURIComponent(row.ticket_no ?? row.ticket_id)}`} state={detailState}><Button variant="ghost" size="sm"><FileText size={15} />查看完整记录</Button></Link>
  341. {gate.confirmClose && <Button size="sm" disabled={submit.busy} onClick={() => void act("confirm")}><Check size={15} />确认完成,关闭工单</Button>}
  342. {gate.withdraw && <Button size="sm" disabled={submit.busy || !reason.trim()} onClick={() => void act("withdraw")}><X size={15} />撤回并关闭</Button>}
  343. </div>
  344. </>}
  345. </div>
  346. </dialog>;
  347. }