feat(web): 工单页与升级面板,修掉视图竞态与标签缺失导致的崩溃

- 新增 /w/:wsId/tickets:派给我的 / 我发起的、状态过滤、列表内联快操作
- 详情抽屉按角色显示受理/开工/提交/验收/驳回/改派/取消;任务态底部可升级成工单
- 导航抽成 WorkspaceNav,带未读角标(30 秒对齐,操作后立刻刷新)
- 修竞态:切视图/切 tab 连发请求时,慢的回包会把新结果盖掉(reqId 序号丢弃过期响应)
- 登录支持 ?next= 站内回跳,邀请链接不再'登录完掉回首页'
- e2e/tickets.mjs:双人双上下文的完整闭环,8 项断言全绿
This commit is contained in:
dadao
2026-10-28 13:20:18 +08:00
parent 30caaaf1d9
commit b1dc3cffa6
11 changed files with 750 additions and 45 deletions
+185 -8
View File
@@ -1,7 +1,8 @@
import { useCallback, useEffect, useState } from "react";
import { useAuth } from "../App";
import { ApiError, api } from "../lib/client";
import { PRIORITY_LABEL, STATUS_LABEL } from "../lib/parse";
import type { Activity, Item, ItemDetail } from "../lib/types";
import type { Activity, Item, ItemDetail, Member, Page, Role, TicketInfo } from "../lib/types";
interface Comment {
id: string;
@@ -10,12 +11,16 @@ interface Comment {
created_at: string;
}
type TicketAction = "accept" | "start" | "submit" | "cancel" | "reassign" | "verify";
interface Props {
wsId: string;
itemId: string;
onClose: () => void;
onChanged: (item: Item) => void;
onDeleted: (id: string) => void;
/** 工单状态变化后通知父级刷新角标 */
onTicketChanged?: () => void;
}
function toLocalInput(iso: string | null): string {
@@ -25,7 +30,15 @@ function toLocalInput(iso: string | null): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Props) {
export function TaskDetail({
wsId,
itemId,
onClose,
onChanged,
onDeleted,
onTicketChanged,
}: Props) {
const { user } = useAuth();
const [item, setItem] = useState<ItemDetail | null>(null);
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
@@ -34,9 +47,16 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
const [comments, setComments] = useState<Comment[]>([]);
const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [role, setRole] = useState<Role>("member");
const [members, setMembers] = useState<Member[]>([]);
const [promoteTo, setPromoteTo] = useState("");
const [note, setNote] = useState("");
const base = `/workspaces/${wsId}/items/${itemId}`;
const isAdmin = role === "owner" || role === "admin";
const hydrate = useCallback((next: ItemDetail) => {
setItem(next);
@@ -54,6 +74,13 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
if (alive) hydrate(detail);
const page = await api.get<{ items: Comment[] }>(`${base}/comments`);
if (alive) setComments(page.items);
const ws = await api.get<{ role: Role }>(`/workspaces/${wsId}`);
if (alive) setRole(ws.role);
const roster = await api.get<Page<Member>>(`/workspaces/${wsId}/members`);
if (alive) {
setMembers(roster.items);
setPromoteTo(roster.items.find((m) => m.user_id !== user?.id)?.user_id ?? "");
}
} catch (err) {
if (alive) setError(err instanceof ApiError ? err.message : "加载失败");
}
@@ -61,12 +88,9 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
return () => {
alive = false;
};
}, [base, hydrate]);
}, [base, hydrate, wsId, user?.id]);
async function patch(
values: Record<string, unknown>,
label: string,
): Promise<boolean> {
async function patch(values: Record<string, unknown>, label: string): Promise<boolean> {
if (!item) return false;
setBusy(true);
setError(null);
@@ -154,6 +178,98 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
}
}
/** 任务 -> 工单。成功后原任务变「被阻塞」,这条抽屉继续显示任务本身。 */
async function promote() {
if (!item || !promoteTo) return;
setBusy(true);
setError(null);
try {
const result = await api.post<{ task: Item; ticket: Item }>(`${base}/promote`, {
assignee_id: promoteTo,
version: item.version,
});
onChanged(result.task);
hydrate({ ...(item as ItemDetail), ...result.task, activities: item.activities });
void refreshActivities(result.task);
const who = members.find((m) => m.user_id === promoteTo)?.nickname ?? "同事";
setNotice(`已把工单交给 ${who},这条任务现在处于「被阻塞」;对方验收通过后会自动回来。`);
onTicketChanged?.();
} catch (err) {
setError(err instanceof ApiError ? err.message : "升级失败");
} finally {
setBusy(false);
}
}
async function ticketAction(action: TicketAction, extra: Record<string, unknown> = {}) {
if (!item) return;
setBusy(true);
setError(null);
try {
const updated = await api.post<Item & { ticket: TicketInfo }>(
`${base}/ticket/${action}`,
{ note, version: item.version, ...extra },
);
onChanged(updated);
hydrate({ ...(item as ItemDetail), ...updated, activities: item.activities });
void refreshActivities(updated);
setNote("");
onTicketChanged?.();
} catch (err) {
if (err instanceof ApiError && err.code === 4009) {
setError("这条工单刚被改过,已刷新为最新内容");
hydrate(await api.get<ItemDetail>(base));
} else {
setError(err instanceof ApiError ? err.message : "操作失败");
}
} finally {
setBusy(false);
}
}
const ticket = item?.kind === "ticket" ? item.ticket : undefined;
const isAssignee = !!ticket && !!user && ticket.assignee_id === user.id;
const isRequester = !!ticket && !!user && ticket.requester_id === user.id;
function actionButtons(t: TicketInfo) {
const buttons: { key: TicketAction | "approve" | "reject"; label: string; show: boolean }[] = [
{ key: "accept", label: "接收", show: t && isAssignee && item?.status === "open" },
{ key: "start", label: "开始办理", show: isAssignee && item?.status === "accepted" },
{ key: "submit", label: "提交验收", show: isAssignee && item?.status === "in_progress" },
{ key: "approve", label: "通过验收", show: isRequester || isAdmin },
{ key: "reject", label: "驳回", show: isRequester || isAdmin },
{
key: "cancel",
label: "取消工单",
show:
(isRequester || isAssignee || isAdmin) &&
["open", "accepted", "in_progress", "pending_verify"].includes(item?.status ?? ""),
},
];
const verifyOnly = item?.status !== "pending_verify";
return (
<div className="flex flex-wrap gap-2">
{buttons
.filter((b) => b.show && !(verifyOnly && (b.key === "approve" || b.key === "reject")))
.map((b) => (
<button
key={b.key}
className={b.key === "cancel" || b.key === "reject" ? "btn-ghost" : "btn-primary"}
disabled={busy}
onClick={() => {
if (b.key === "approve") void ticketAction("verify", { approve: true });
else if (b.key === "reject") void ticketAction("verify", { approve: false });
else void ticketAction(b.key);
}}
>
{b.label}
</button>
))}
</div>
);
}
return (
<div className="fixed inset-0 z-20 flex justify-end bg-ink-900/20" onClick={onClose}>
<aside
@@ -166,6 +282,7 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
<>
<div className="mb-4 flex items-center justify-between text-xs text-ink-500">
<span>
{item.kind === "ticket" ? "工单 · " : ""}
{STATUS_LABEL[item.status]} · 版本 {item.version}
</span>
<div className="flex gap-2">
@@ -178,6 +295,33 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
</div>
</div>
{ticket && (
<div className="mb-4 rounded-lg border border-ink-100 bg-ink-50 p-3 text-xs text-ink-700">
<div className="flex flex-wrap gap-x-4 gap-y-1">
<span>
需求人:{members.find((m) => m.user_id === ticket.requester_id)?.nickname ?? "—"}
</span>
<span>
办理人:{members.find((m) => m.user_id === ticket.assignee_id)?.nickname ?? "—"}
</span>
{ticket.reject_count > 0 && <span>退回 {ticket.reject_count} 次</span>}
{ticket.parent_item_id && <span>由任务升级而来</span>}
</div>
{ticket.resolution_md && (
<p className="mt-2 whitespace-pre-wrap text-ink-900">验收结论:{ticket.resolution_md}</p>
)}
<div className="mt-3 space-y-2">
<input
className="input"
placeholder="给对方的说明(提交或验收时一并发过去)"
value={note}
onChange={(e) => setNote(e.target.value)}
/>
{actionButtons(ticket)}
</div>
</div>
)}
<input
className="input text-base font-medium"
value={title}
@@ -236,8 +380,38 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
/>
</label>
{item.kind === "task" && !["done", "canceled"].includes(item.status) && (
<div className="mt-4 rounded-lg border border-ink-100 p-3">
<p className="text-sm font-medium">这件事卡在别人手里?升级成工单</p>
<p className="mt-1 text-xs text-ink-500">
升级后这条任务会变成「被阻塞」,工单办好并验收通过后自动回到待办,不用你自己盯。
</p>
<div className="mt-2 flex gap-2">
<select
className="input flex-1"
value={promoteTo}
onChange={(e) => setPromoteTo(e.target.value)}
>
<option value="">选择找谁办…</option>
{members
.filter((m) => m.status === "active")
.map((m) => (
<option key={m.user_id} value={m.user_id}>
{m.nickname}
{m.role === "guest" ? "(访客)" : ""}
</option>
))}
</select>
<button className="btn-primary" disabled={busy || !promoteTo} onClick={() => void promote()}>
升级成工单
</button>
</div>
</div>
)}
{notice && <p className="mt-3 text-sm text-emerald-700">{notice}</p>}
{error && <p className="mt-3 text-sm text-red-600">{error}</p>}
{busy && <p className="mt-3 text-xs text-ink-500">保存中…</p>}
{busy && <p className="mt-3 text-xs text-ink-500">处理中…</p>}
<h3 className="mt-6 text-sm font-medium">评论({comments.length})</h3>
<ul className="mt-2 space-y-2">
@@ -273,6 +447,9 @@ export function TaskDetail({ wsId, itemId, onClose, onChanged, onDeleted }: Prop
{a.action === "status_changed" && a.payload
? ` ${String(a.payload.from ?? "")} → ${String(a.payload.to ?? "")}`
: ""}
{a.action === "ticket_submit" && a.payload?.note
? ` · ${String(a.payload.note)}`
: ""}
</li>
))}
</ul>
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import { api } from "../lib/client";
const TABS = [
{ path: "", label: "任务" },
{ path: "/board", label: "看板" },
{ path: "/tickets", label: "工单" },
{ path: "/members", label: "成员" },
];
/**
* 工作区内的导航条。
*
* 未读数为什么放在这里:用户在哪个页面都可能被指派工单,
* 角标必须跟着走,所以让它自己拉一次、再每 30 秒对齐一次。
* `refreshKey` 用来在"刚处理完一条工单"后立刻刷新角标。
*/
export function WorkspaceNav({
wsId,
refreshKey = 0,
}: {
wsId: string;
refreshKey?: number;
}) {
const { pathname } = useLocation();
const [unread, setUnread] = useState(0);
const base = `/w/${wsId}`;
useEffect(() => {
let alive = true;
const load = () => {
api
.get<{ unread: number }>(`/workspaces/${wsId}/notifications/unread-count`)
.then((r) => {
if (alive) setUnread(r.unread);
})
.catch(() => {
/* 角标失败不打扰用户 */
});
};
void load();
const timer = window.setInterval(load, 30_000);
return () => {
alive = false;
window.clearInterval(timer);
};
}, [wsId, refreshKey]);
return (
<nav className="flex items-center gap-4 text-sm">
{TABS.map((tab) => {
const active =
tab.path === "" ? pathname === base : pathname.startsWith(base + tab.path);
return (
<Link
key={tab.label}
to={base + tab.path}
className={
active
? "font-medium text-ink-900"
: "text-ink-500 transition hover:text-ink-900"
}
>
{tab.label}
{tab.path === "/tickets" && unread > 0 && (
<span className="ml-1 rounded-full bg-accent-500 px-1.5 text-[10px] leading-4 text-white">
{unread > 99 ? "99+" : unread}
</span>
)}
</Link>
);
})}
<Link to="/" className="text-ink-500 transition hover:text-ink-900">
切换
</Link>
</nav>
);
}