| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293 |
- /**
- * 门户提交工单(册 5 §6.2;enterprise 主账号/sub 下属分账号)。
- *
- * 真调 `POST /ticket/create@v1`:
- * - 只收 `fault`/`after_sale`(create.rs `CREATE_TYPES`),开户/停机/服务开通联系运营办理;
- * - `customer_id` ⛔ 由前端传——服务端按登录会话派生(`resolve_customer`,跨客户 `KLT-C007`);
- * - `title` 是服务端必填(≤128 字),⛔ 服务端替提交方编标题;
- * - 「挂接团队自动分派」是服务端行为(分派引擎),⛔ 在本地演示数据里复刻;
- * ⚠️ 建单层**不做**同类未完成并入(2026-11-18 撤除),一次提交=一张单;
- * - 附件:`material_grant` 要 `ticket_id`,建单前拿不到上传凭证,
- * ⛔ 把未上传的文件名随单提交,材料在建单后到工单详情直传(§5.8)。
- */
- import { useCallback, useEffect, useRef, useState, type FormEvent } from "react";
- import { ArrowRight, Check, CircleAlert, ClipboardList, Clock3, FileText, Info, RefreshCw, Search, Send, X } from "lucide-react";
- import { Link, useLocation, useSearchParams } from "react-router";
- import { Button } from "../components/ui/button";
- import { SearchInput } from "../components/ui/search-input";
- import { FilterSelect } from "../components/ui/filter-select";
- import { FieldHint } from "../components/ui/field-hint";
- import { ServerListPager } from "../components/ListPager";
- import { TicketState } from "../components/ticketState";
- import { WorkspaceEmpty, WorkspaceHeading, WorkspacePanel } from "../components/RoleWorkspaceKit";
- import { OpsNotice } from "../components/OperationsKit";
- import { useDemoIdentity } from "../lib/demo-session";
- import { readCustomers } from "../lib/customer-records";
- import { detailLinkState } from "../lib/detail-navigation";
- import { classifyTicketError, fmtTime, TICKET_PAGE_SIZE, useTicketDetail, useTicketList } from "../lib/ticket";
- import { ticketCreate, TICKET_STATUSES, statusLabel, nonMainlineStatusLabel, typeLabel, ticketConfirmClose, ticketWithdraw } from "../lib/api/ticket";
- import type { TicketListItem } from "../lib/api/ticket";
- import { useSubmit } from "../lib/useLoad";
- import { customerLiveTicketActions } from "../lib/customer-workspace";
- import "../styles/operations.css";
- import "../styles/work-orders.css";
- export function CustomerSubmitPage() {
- const location = useLocation();
- const identity = useDemoIdentity();
- const customer = readCustomers().find((item) => item.no === identity?.customerNo);
- const [type, setType] = useState<"fault" | "after_sale">("fault");
- const [title, setTitle] = useState("");
- const [description, setDescription] = useState("");
- const [errors, setErrors] = useState({ title: "", desc: "" });
- const [done, setDone] = useState<{ id: string; no: string } | null>(location.state?.submittedTicket ?? null);
- const detailState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, submittedTicket: done });
- const submit = useSubmit();
- if (!identity || !["enterprise", "sub"].includes(identity.role)) return <WorkspaceEmpty title="请切换到客户账号" description="故障与售后提交入口面向客户侧账号;运维请在工单管理代办。" />;
- async function onSubmit(event: FormEvent) {
- event.preventDefault();
- setDone(null);
- // D-17:⛔ HTML5 required 静默拦截——浏览器先拦则提示永不出现;校验一律走这里。
- // 一次提交收集**全部**缺失项一并回显,⛔ 只报第一条(修完一条又冒下一条=挤牙膏)。
- const next = {
- title: title.trim().length < 2 || title.trim().length > 128 ? "请填写事项标题(2–128 字,服务端必填)。" : "",
- desc: description.trim().length < 2 ? "请至少填写 2 个字,描述具体事项。" : "",
- };
- setErrors(next);
- if (next.title || next.desc) return;
- const ok = await submit.run(() => ticketCreate({
- ticket_type: type,
- title: title.trim(),
- detail: description.trim(),
- }).then((r) => {
- setDone({ id: r.ticket_id, no: r.ticket_no });
- setTitle(""); setDescription("");
- }));
- if (!ok) return;
- }
- const failure = submit.error ? classifyTicketError(submit.error) : null;
- const titleInvalid = Boolean(errors.title);
- const descInvalid = Boolean(errors.desc);
- return <section className="role-workspace">
- <WorkspaceHeading title="提交故障或售后" description={`为 ${customer?.name ?? identity.customerNo ?? "本企业"} 提交服务请求,运维团队受理后可在工单中跟进。`} aside={<Link className="workspace-link" to="/workspace/progress">查看工单进度 <ArrowRight size={15} /></Link>} />
- <div className="workspace-split">
- <WorkspacePanel title="描述需要协助的事项" description="尽量说明发生时间、影响范围和具体表现,便于团队定位。">
- {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>}
- <form className="workspace-form !pt-0" noValidate onSubmit={onSubmit}>
- <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>
- <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>
- <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>
- <p className="text-[13px] leading-6 text-muted-foreground">现场照片、录音等材料请在工单创建后到工单详情上传。</p>
- {(errors.title || errors.desc) && <p className="workspace-error" role="alert">请补全以下内容后重新提交:{[errors.title, errors.desc].filter(Boolean).join(";")}</p>}
- {failure && <p className="workspace-error" role="alert">{failure.message}</p>}
- {submit.busy && <p className="text-sm text-muted-foreground">提交中…</p>}
- <footer><Button type="submit" disabled={submit.busy}><Send size={16} />提交工单</Button></footer>
- </form>
- </WorkspacePanel>
- <aside className="workspace-panel workspace-aside">
- <h3>提交之后会发生什么</h3>
- <ol>
- <li><strong>团队受理与分派</strong><br />工单先进入挂接的运维团队,由团队主账号安排责任人。</li>
- <li><strong>处理与进度记录</strong><br />在「工单进度」中查看处理记录和结果;本人提交的单在完成前可填写原因撤回。</li>
- <li><strong>确认关闭</strong><br />运维标记完成后,由提交人确认关闭,形成服务闭环。</li>
- </ol>
- <p className="mt-5 border-t border-border pt-4 text-[13px]">每次提交都会生成一张独立工单,请在「工单进度」中分别跟踪。此入口只受理故障与售后;开户、停机与套餐变更请联系运营办理。</p>
- </aside>
- </div>
- </section>;
- }
- /* ═════════════════ 工单进度=客户侧「我的工单」(缺陷 P-21)════════════════ */
- /**
- * 客户侧「我的工单」列表(手册 P7 第 172-185 行:建单 → 团队分派 → 运维处理并标记完成
- * → **客户点「确认完成,关闭工单」** → 7 天未确认由系统自动关闭;在办期间可填原因撤回)。
- *
- * 存在理由(缺陷 P-21,2026-11-14 实测):`/workspace/progress` 此前直接挂运营侧
- * `WorkOrderLedgerPage`,那是运营口径的列集与取数,客户账号打开既看不到自己的单,
- * 也没有「确认完成,关闭工单」和「撤回」的任何入口⇒ 手册要求的客户侧闭环断在这一步。
- * 这里⛔ 复用运营台账页(那会把客户/团队/责任人这些客户不该关心的口径一起摊开,
- * 也⛔ 复制一份 900 行台账),只走真实接口:
- * - 行集=`POST /ticket/list@v1`(`read.rs` 对该口⛔ 角色闸门,只按数据范围把行收到
- * 本客户名下),单次服务端分页查询,⛔ 前端拼接多次请求补齐(契约 14.3);
- * - 操作=`POST /ticket/confirm_close@v1`/`POST /ticket/withdraw@v1`(`finalize.rs`)。
- * ⛔ 调 `/ticket/confirm_done@v1`:后端没有这条路由,网关按「未声明即拒绝」拦(C-5)。
- * ⛔ 把本件的按钮判定当权限边界:闸门在 `finalize.rs`,这里只是⛔ 给客户无效点击。
- */
- export function CustomerTicketProgressPage() {
- const identity = useDemoIdentity();
- /**
- * 筛选与页码落在 URL 上(`?q=&status=&page=`),⛔ 只放组件内 state。
- *
- * 2026-11-18 实测:客户在这里点「详情」进 `/work-orders/:no`,再点「返回工单列表」回到的
- * 是另一张列表(运营台账口径)——既不是本页,进来时的关键词/状态/页码也全丢。修好返回
- * 目标后,本页必须能按 URL 原样复原,否则「回到同一张列表」仍做不到。
- */
- const [searchParams, setSearchParams] = useSearchParams();
- const location = useLocation();
- const keyword = searchParams.get("q") ?? "";
- const status = searchParams.get("status") ?? "";
- const page = Math.max(1, Number(searchParams.get("page")) || 1);
- const [notice, setNotice] = useState("");
- const [active, setActive] = useState<TicketListItem | null>(null);
- /**
- * 「提交方」回填补:`read.rs` 的 `LIST_COLS` ⛔ 下发 `submitter_type`,客户点过一次「办理」
- * 后把详情拿到的值记在这里,用于回填本行的提交方列与按钮文案。
- * ⛔ 换成"进页面就给每行拉一次详情"把整页拼出来(契约 14.3 明令禁止的拼接取数)。
- */
- const [submitterById, setSubmitterById] = useState<Record<string, string>>({});
- const rememberSubmitter = useCallback((ticketId: string, submitterType: string | null) => {
- if (!submitterType) return;
- setSubmitterById((prev) => (prev[ticketId] === submitterType ? prev : { ...prev, [ticketId]: submitterType }));
- }, []);
- const list = useTicketList({ keyword: keyword.trim() || undefined, statuses: status ? [status] : undefined }, page);
- /** 写 URL:空值删键;换筛选(未显式给 `page`)一律回第 1 页。 */
- function patchParams(patch: Record<string, string>) {
- const next = new URLSearchParams(searchParams);
- Object.entries(patch).forEach(([key, value]) => (value ? next.set(key, value) : next.delete(key)));
- if (!("page" in patch)) next.delete("page");
- setSearchParams(next);
- }
- if (!identity || !["enterprise", "sub"].includes(identity.role)) return <WorkspaceEmpty title="请切换到客户账号" description="工单进度面向企业客户与子账号;运维请到「工单管理」。" />;
- const rows = list.data?.rows ?? [];
- const total = list.data?.total ?? 0;
- const pages = Math.max(1, Math.ceil(total / TICKET_PAGE_SIZE));
- const currentPage = Math.min(page, pages);
- const fail = list.error ? classifyTicketError(list.error) : null;
- /** 进详情的「来路」=本页当前 URL(含筛选与页码),返回时逐字复原。 */
- const detailState = detailLinkState(location.pathname + location.search + location.hash, location.state);
- return <section className="work-order-page work-order-ledger-page page-fill">
- <header className="work-order-heading"><div><p className="work-order-eyebrow"><span /> CUSTOMER SUPPORT / 我的工单</p><h1>工单进度</h1></div><Link to="/workspace/submit"><Button><FileText size={17} />提交故障或售后</Button></Link></header>
- <div className="work-order-list-shell list-shell-fill">
- <div className="work-order-ledger-filters">
- <label className="work-order-ledger-search"><Search size={17} /><SearchInput aria-label="搜索我的工单" placeholder="搜索工单号或事项标题" value={keyword} onCommit={(value) => patchParams({ q: value })} />{keyword && <button type="button" aria-label="清空搜索" onClick={() => patchParams({ q: "" })}><X size={15} /></button>}</label>
- <FilterSelect icon="status" aria-label="工单状态筛选" value={status} onChange={(event) => patchParams({ status: event.target.value })}><option value="">全部状态</option>{TICKET_STATUSES.map((item) => <option key={item} value={item}>{customerStatusLabel(item)}</option>)}</FilterSelect>
- <Button variant="ghost" size="sm" onClick={() => list.reload()}><RefreshCw size={15} />刷新</Button>
- {(keyword || status) ? <Button variant="ghost" size="sm" onClick={() => setSearchParams(new URLSearchParams())}>重置筛选</Button> : null}
- </div>
- <div className="measured-table-scroll work-order-table-wrap" role="region" aria-label="我的工单列表,可横向滚动查看字段" tabIndex={0}><table className="work-order-ledger-table"><thead><tr><th>工单号</th><th>类型</th><th>事项标题</th><th>状态</th><th>提交方</th><th>要求完成</th><th>竣工时间</th><th>提交时间</th><th>操作</th></tr></thead>
- <tbody>{rows.map((item) => {
- const submitterType = item.submitter_type ?? submitterById[item.ticket_id] ?? null;
- const gate = customerLiveTicketActions({ status: item.status, ticket_type: item.ticket_type, submitter_type: submitterType });
- const label = gate.confirmClose ? "确认完成,关闭工单" : gate.withdraw ? "撤回" : "办理";
- return <tr key={item.ticket_id}>
- <td><strong className="work-order-ticket-number" title={item.ticket_no ?? ""}>{item.ticket_no ?? "-"}</strong></td>
- <td>{typeLabel(item.ticket_type)}</td>
- <td><span title={item.title ?? undefined}>{item.title}</span></td>
- <td><CustomerStatusTag status={item.status} type={item.ticket_type} /></td>
- <td>{submitterType ? SUBMITTER_NAMES[submitterType] ?? submitterType : <span className="table-placeholder" title="列表未回提交方,需要确认时点「办理」查看该单详情">未回传</span>}</td>
- <td>{item.expected_done_date ? item.expected_done_date.slice(0, 10) : <span className="table-placeholder">—</span>}</td>
- <td>{fmtTime(item.completed_at)}</td>
- <td>{fmtTime(item.created_at)}</td>
- <td className="work-order-row-actions">
- {(gate.confirmClose || gate.withdraw || gate.needsDetail) && <Button variant="outline" size="sm" onClick={() => setActive(item)}>{label}</Button>}
- {/* 客户侧 URL 只走业务工单号(`ticket_no`):内部主键⛔ 出现在客户地址里。 */}
- <Link className="ops-table-action" to={`/work-orders/${encodeURIComponent(item.ticket_no ?? item.ticket_id)}`} state={detailState}>详情</Link>
- </td>
- </tr>;
- })}</tbody></table>
- {list.loading && <div className="work-order-empty"><RefreshCw size={27} /><h3>正在读取工单…</h3></div>}
- {fail && <TicketState fail={fail} onRetry={list.reload} />}
- {!list.loading && !fail && !rows.length && <div className="work-order-empty"><ClipboardList size={27} /><h3>还没有工单</h3><p>需要报修或咨询,请到「提交故障或售后」建单。</p><Link to="/workspace/submit"><Button variant="ghost" size="sm">去提交</Button></Link></div>}
- </div>
- <ServerListPager total={total} page={currentPage} pageSize={TICKET_PAGE_SIZE} unit="张" className="list-pager work-order-ledger-pager" onPageChange={(next) => patchParams({ page: next > 1 ? String(next) : "" })} />
- </div>
- {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
- {active && <CustomerTicketActionSheet row={active} onClose={() => setActive(null)} onResolved={rememberSubmitter} onDone={(message) => { setActive(null); setNotice(message); list.reload(); }} />}
- </section>;
- }
- /** 提交方显示名(`tickets.submitter_type` 口径见 `docs/需求文档/14-API接口契约.md`)。 */
- const SUBMITTER_NAMES: Record<string, string> = { customer: "本人提交", ops: "运维代建", system: "系统生成", unicom: "运营商报文" };
- /** 状态徽标沿用台账类名(`work-orders.css`),⛔ 另起一套配色体系。 */
- function CustomerStatusTag({ status, type }: { status: string; type: string }) {
- const tone: Record<string, string> = { unassigned: "pending", pending: "pending", processing: "doing", completed: "done", rejected: "doing", settled: "done", terminated: "closed" };
- return <span className={`work-order-status status-${tone[status] ?? "pending"}`}><i />{statusLabel(status, type)}</span>;
- }
- /**
- * 客户侧的状态筛选器文案:门户只受理故障/售后(EP-03),没有主线单,
- * ⇒ `completed` 一律按非主线叫法「已处理待确认」(该态等本人确认或超时自动闭环,不是终态)。
- * ⚠️ 与行内徽标 `statusLabel(status, ticket_type)` 同源,⛔ 在这里另抄一份中文名。
- */
- const customerStatusLabel = (status: string) => nonMainlineStatusLabel(status);
- /**
- * 「办理」弹框:先就该单取**一次**详情定闸门,再给「确认完成,关闭工单」/「撤回」。
- *
- * `read_event=false`:客户只是来看进度并确认结果,⛔ 一次查看就把待处理单推进成处理中
- * (那是运维接手的语义,服务端按 `read_event` 决定是否记接手事件)。
- * 撤回原因必填=`finalize.rs` 的 `WithdrawReq`(`reason` 为空回参数校验失败)。
- * `expected_version`=详情头的 `row_version`(乐观锁):并发下版本不符由服务端拒,
- * 回执经 `classifyTicketError` 原样显示,⛔ 静默重试覆盖对方。
- */
- function CustomerTicketActionSheet({ row, onClose, onResolved, onDone }: {
- row: TicketListItem;
- onClose: () => void;
- onResolved: (ticketId: string, submitterType: string | null) => void;
- onDone: (message: string) => void;
- }) {
- const detail = useTicketDetail(row.ticket_id, false);
- const submit = useSubmit();
- const location = useLocation();
- const [reason, setReason] = useState("");
- const ref = useRef<HTMLDialogElement>(null);
- const head = detail.data?.ticket ?? null;
- /** 「查看完整记录」=从本弹框(仍在本列表页)进详情,返回目标就是这张列表。 */
- const detailState = detailLinkState(location.pathname + location.search + location.hash, location.state);
- useEffect(() => {
- const el = ref.current;
- if (!el) return;
- // ⚠️ 属性 `open` 与 showModal() ⛔ 同时置:React 先把 open 写进 DOM,effect 再调 showModal()
- // 会抛 InvalidStateError(2026-11-13 实测抽屉打不开)。已开就跳过。
- if (el.open) return;
- if (typeof el.showModal === "function") el.showModal();
- else el.open = true;
- }, []);
- const submitterType = head?.submitter_type ?? null;
- useEffect(() => { if (submitterType) onResolved(row.ticket_id, submitterType); }, [onResolved, row.ticket_id, submitterType]);
- const gate = head ? customerLiveTicketActions({ status: head.status, ticket_type: head.ticket_type, submitter_type: head.submitter_type }) : null;
- const detailFail = detail.error ? classifyTicketError(detail.error) : null;
- const tip = submit.error ? classifyTicketError(submit.error).message : "";
- async function act(kind: "confirm" | "withdraw") {
- if (!head) return;
- const version = Number(head.row_version);
- const ok = await submit.run(() => kind === "confirm"
- ? ticketConfirmClose({ ticket_id: head.ticket_id, expected_version: Number.isFinite(version) ? version : undefined })
- : ticketWithdraw({ ticket_id: head.ticket_id, reason: reason.trim() }));
- if (ok) onDone(kind === "confirm" ? `工单 ${head.ticket_no} 已确认完成并关闭。` : `工单 ${head.ticket_no} 已撤回并关闭。`);
- }
- return <dialog ref={ref} className="work-order-drawer" aria-label="工单办理" onCancel={onClose} onClick={(event) => { if (event.target === ref.current) onClose(); }}>
- <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>
- <div className="work-order-editor">
- {detail.loading && !head && <div className="work-order-empty"><RefreshCw size={27} /><h3>正在核对可执行的操作…</h3></div>}
- {detailFail && <TicketState fail={detailFail} onRetry={detail.reload} />}
- {head && gate && <>
- <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>
- {gate.confirmClose && <div className="work-order-editor-note"><Check size={17} /><span>运维已标记完成,等您确认:确认后工单立即关闭;按手册 P7,7 天内未确认由系统自动关闭。</span></div>}
- {gate.withdraw && <div className="work-order-editor-note"><Clock3 size={17} /><span>该单仍在处理中,可以撤回:撤回即关闭工单,请填写原因(工单§5.1.9:原因必填)。</span></div>}
- {gate.blockedReason && <div className="work-order-editor-note"><CircleAlert size={17} /><span>{gate.blockedReason}</span></div>}
- {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>}
- {tip && <p className="work-order-form-error" role="alert">{tip}</p>}
- <div className="work-order-detail-actions">
- <Button variant="ghost" size="sm" onClick={onClose}>返回</Button>
- <Link to={`/work-orders/${encodeURIComponent(row.ticket_no ?? row.ticket_id)}`} state={detailState}><Button variant="ghost" size="sm"><FileText size={15} />查看完整记录</Button></Link>
- {gate.confirmClose && <Button size="sm" disabled={submit.busy} onClick={() => void act("confirm")}><Check size={15} />确认完成,关闭工单</Button>}
- {gate.withdraw && <Button size="sm" disabled={submit.busy || !reason.trim()} onClick={() => void act("withdraw")}><X size={15} />撤回并关闭</Button>}
- </div>
- </>}
- </div>
- </dialog>;
- }
|