feat(notify): 站内通知与手工开单,指派/改状态/评论/验收都有人收到
CI / backend (push) Canceled after 0s

M2 最后一块:让"该我办了"能出现在系统里,并且允许不经过任务直接开单。

通知(backend/app/services/notify.py 统一出口)
- 七类触发:task_assigned、task_status_changed、item_commented、
  ticket_assigned、ticket_submitted、ticket_approved/rejected、task_unblocked
- 不通知自己:notify() 按 actor_id 跳过,调用方不用各自判断
- 已读:GET /notifications、/unread-count、POST /read、/read-all

手工开单
- POST /tickets:直接指定人、初始 open,与任务升级单共用同一条 kind='ticket' item,
  ticket_ext.parent_item_id 为空,验收通过不回流任务
- 指派前 _ensure_member 校验在册成员,越界指派返回 1001(避免"挂在看不到的名字上")

前端
- Web:通知页 /w/:wsId/notifications(未读/全部,点开标已读并跳目标);
  工单页"新建"面板;AppShell 每 30 秒对未读数,标已读后 dispatch notifications:changed 立刻刷新;
  任务与工单支持 ?open= 深链落地即展开
- 安卓:五个 tab 加"通知",未读数 30 秒刷新;工单动作按需求人/办理人/管理员显隐;手工开单对话框

验证
- pytest 85 passed(新增 backend/tests/test_notifications.py 6 个用例)
- ruff check / format --check 全 0
- tsc --noEmit 通过;vite build 成功
- web/e2e/notifications.mjs 12 项断言全绿(手工开单 → B 收到 → 点开跳转 → 未读归零)
- 安卓:本机 JDK 25 与 Gradle 8.7 / AGP 8.7.3 不兼容,本次未做编译验证,
  装回 JDK 17 后第一件事是 assembleDebug
This commit is contained in:
Steven
2026-10-30 02:19:42 +08:00
parent d079564d6c
commit 91b3dde670
23 changed files with 1674 additions and 60 deletions
+2
View File
@@ -10,6 +10,7 @@ import { TasksPage } from "./pages/Tasks";
import { BoardPage } from "./pages/Board";
import { TicketsPage } from "./pages/Tickets";
import { KnowledgePage } from "./pages/Knowledge";
import { NotificationsPage } from "./pages/Notifications";
import { JoinPage } from "./pages/Join";
interface AuthState {
@@ -90,6 +91,7 @@ export function App() {
<Route path="/w/:wsId/board" element={<BoardPage />} />
<Route path="/w/:wsId/tickets" element={<TicketsPage />} />
<Route path="/w/:wsId/knowledge" element={<KnowledgePage />} />
<Route path="/w/:wsId/notifications" element={<NotificationsPage />} />
<Route path="/w/:wsId/members" element={<WorkspacePage />} />
<Route path="/join/:wsId/:code" element={<JoinPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
+23 -4
View File
@@ -6,6 +6,7 @@ import type { Workspace } from "../lib/types";
import {
Book,
ChevronDown,
Bell,
Columns,
Inbox,
Logo,
@@ -15,13 +16,25 @@ import {
X,
} from "./icons";
export type Section = "tasks" | "board" | "tickets" | "knowledge" | "members";
export type Section =
| "tasks"
| "board"
| "tickets"
| "knowledge"
| "notifications"
| "members";
const NAV: { key: Section; label: string; to: (id: string) => string; icon: ReactNode }[] = [
{ key: "tasks", label: "任务", to: (id) => `/w/${id}`, icon: <Inbox size={16} /> },
{ key: "board", label: "看板", to: (id) => `/w/${id}/board`, icon: <Columns size={16} /> },
{ key: "tickets", label: "工单", to: (id) => `/w/${id}/tickets`, icon: <TicketIcon size={16} /> },
{ key: "knowledge", label: "知识", to: (id) => `/w/${id}/knowledge`, icon: <Book size={16} /> },
{
key: "notifications",
label: "通知",
to: (id) => `/w/${id}/notifications`,
icon: <Bell size={16} />,
},
{ key: "members", label: "成员", to: (id) => `/w/${id}/members`, icon: <Users size={16} /> },
];
@@ -73,16 +86,22 @@ export function AppShell({
let alive = true;
const load = async () => {
try {
const r = await api.get<{ count: number }>(`/workspaces/${wsId}/notifications/unread-count`);
if (alive) setUnread(r.count);
const r = await api.get<{ unread: number }>(
`/workspaces/${wsId}/notifications/unread-count`,
);
if (alive) setUnread(r.unread ?? 0);
} catch {
/* 未读数失败不该影响主流程 */
}
};
// 通知页标了已读之后立刻刷新角标,不必等下一个轮询周期
const onChange = () => void load();
void load();
window.addEventListener("notifications:changed", onChange);
const timer = window.setInterval(load, 30_000);
return () => {
alive = false;
window.removeEventListener("notifications:changed", onChange);
window.clearInterval(timer);
};
}, [wsId]);
@@ -174,7 +193,7 @@ export function AppShell({
<Link key={n.key} to={n.to(ws.id)} className={`nav-item ${isActive ? "nav-item-active" : ""}`}>
<span className={isActive ? "text-primary-200" : "text-ink-400"}>{n.icon}</span>
{n.label}
{n.key === "tickets" && unread > 0 ? (
{n.key === "notifications" && unread > 0 ? (
<span
className={`ml-auto rounded-full px-1.5 py-px text-2xs font-semibold tabular-nums ${
isActive ? "bg-clay-500 text-white" : "bg-clay-500/12 text-clay-600"
+7
View File
@@ -178,6 +178,13 @@ export const Inbox = (p: IconProps) => (
</svg>
);
export const Bell = (p: IconProps) => (
<svg {...base(p)}>
<path d="M6 9a6 6 0 1 1 12 0c0 3.2.8 4.9 1.6 5.9.4.5 0 1.1-.6 1.1H5c-.6 0-1-.6-.6-1.1C5.2 13.9 6 12.2 6 9Z" />
<path d="M10 19a2 2 0 0 0 4 0" />
</svg>
);
export const Sparkle = (p: IconProps) => (
<svg {...base(p)}>
<path d="M12 3.5 13.6 9l5.4 1.6-5.4 1.6L12 17.5l-1.6-5.3L5 10.6 10.4 9Z" />
+12
View File
@@ -170,3 +170,15 @@ export interface SearchHit {
vector_score: number;
lexical_score: number;
}
/** 站内通知:只有"谁做了什么"和"指向哪条事项",详情永远回源取。 */
export interface AppNotification {
id: string;
kind: string;
item_id: string | null;
item_title: string | null;
title: string;
body: string;
read_at: string | null;
created_at: string;
}
+228
View File
@@ -0,0 +1,228 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { AppShell } from "../components/AppShell";
import { Bell, Check, TicketIcon, Inbox, Clock } from "../components/icons";
import { Button, EmptyState, PageHeader, SkeletonRows } from "../components/ui";
import { api, ApiError } from "../lib/client";
import type { AppNotification } from "../lib/types";
const PAGE = 30;
/** 工单类通知点开跳到工单页,其余回任务页——都带 `?open=`,落地即展开那一条。 */
function targetOf(wsId: string, n: AppNotification): string {
if (!n.item_id) return `/w/${wsId}/notifications`;
const isTicket = n.kind.startsWith("ticket_");
return isTicket ? `/w/${wsId}/tickets?open=${n.item_id}` : `/w/${wsId}?open=${n.item_id}`;
}
function iconOf(kind: string) {
if (kind.startsWith("ticket_")) return <TicketIcon size={15} />;
if (kind === "item_commented") return <Inbox size={15} />;
return <Bell size={15} />;
}
function ago(iso: string): string {
const then = new Date(iso).getTime();
const diff = Math.max(0, Date.now() - then);
const min = Math.floor(diff / 60_000);
if (min < 1) return "刚刚";
if (min < 60) return `${min} 分钟前`;
const hour = Math.floor(min / 60);
if (hour < 24) return `${hour} 小时前`;
const day = Math.floor(hour / 24);
if (day < 30) return `${day} 天前`;
return new Date(iso).toLocaleDateString("zh-CN");
}
/** 通知页:默认只看未读——"全部"是查历史用的,不是日常入口。 */
export function NotificationsPage() {
const { wsId = "" } = useParams();
const navigate = useNavigate();
const [tab, setTab] = useState<"unread" | "all">("unread");
const [rows, setRows] = useState<AppNotification[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(
async (reset: boolean) => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
unread_only: tab === "unread" ? "true" : "false",
limit: String(PAGE),
});
if (!reset && cursor) params.set("cursor", cursor);
const page = await api.get<{
notifications: AppNotification[];
next_cursor: string | null;
has_more: boolean;
}>(`/workspaces/${wsId}/notifications?${params.toString()}`);
setRows((prev) => (reset ? page.notifications : [...prev, ...page.notifications]));
setCursor(page.next_cursor);
setHasMore(page.has_more);
} catch (err) {
setError(err instanceof ApiError ? err.message : "通知加载失败");
} finally {
setLoading(false);
}
},
[wsId, tab, cursor],
);
useEffect(() => {
setRows([]);
setCursor(null);
void load(true);
// 只在切 tab / 换工作区时重拉,翻页由按钮触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [wsId, tab]);
const unreadCount = useMemo(() => rows.filter((r) => !r.read_at).length, [rows]);
async function markRead(n: AppNotification) {
if (!n.read_at) {
try {
await api.post(`/workspaces/${wsId}/notifications/${n.id}/read`);
} catch {
/* 标已读失败不拦着用户点进去看 */
}
setRows((prev) =>
prev.map((r) => (r.id === n.id ? { ...r, read_at: new Date().toISOString() } : r)),
);
window.dispatchEvent(new Event("notifications:changed"));
}
navigate(targetOf(wsId, n));
}
async function markAll() {
try {
await api.post(`/workspaces/${wsId}/notifications/read-all`);
setRows((prev) => prev.map((r) => ({ ...r, read_at: r.read_at ?? new Date().toISOString() })));
window.dispatchEvent(new Event("notifications:changed"));
} catch (err) {
setError(err instanceof ApiError ? err.message : "操作失败");
}
}
return (
<AppShell wsId={wsId} active="notifications">
<PageHeader
eyebrow="事情有动静时,这里会告诉你"
title="通知"
desc="工单被接受、提交、验收,任务被指派、改状态,有人在你关注的事情下说话,都会落在这里。"
actions={
<>
<Button variant="ghost" size="sm" onClick={() => void load(true)} disabled={loading}>
刷新
</Button>
<Button variant="subtle" size="sm" onClick={() => void markAll()} disabled={!unreadCount}>
全部已读
</Button>
</>
}
/>
<div className="mb-3 flex items-center gap-1">
{(
[
["unread", "未读"],
["all", "全部"],
] as const
).map(([key, label]) => (
<button
key={key}
onClick={() => setTab(key)}
className={`rounded-lg px-3 py-1.5 text-xs transition ${
tab === key
? "bg-ink-900 font-medium text-white"
: "text-ink-500 hover:bg-ink-100 hover:text-ink-800"
}`}
>
{label}
</button>
))}
{tab === "unread" && unreadCount > 0 ? (
<span className="ml-auto text-2xs text-ink-400">还有 {unreadCount} 条没看</span>
) : null}
</div>
{error ? (
<div className="mb-3 rounded-xl border border-rust-100 bg-rust-50 px-4 py-3 text-sm text-rust-700">
{error}
</div>
) : null}
{loading && rows.length === 0 ? (
<SkeletonRows rows={4} />
) : rows.length === 0 ? (
<div className="card">
<EmptyState
icon={<Bell size={20} />}
title={tab === "unread" ? "没有未读通知" : "还没有通知"}
hint={
tab === "unread"
? "有人给你派活、或你关注的事情有进展时,会出现在这里。"
: "这里会留下所有历史通知,方便回头找。"
}
/>
</div>
) : (
<ul className="space-y-2">
{rows.map((n) => (
<li key={n.id} className={`card ${n.read_at ? "" : "border-primary-100 bg-primary-50/40"}`}>
<button
onClick={() => void markRead(n)}
className="flex w-full items-start gap-3 px-4 py-3 text-left"
>
<span
className={`mt-0.5 grid h-7 w-7 shrink-0 place-items-center rounded-full ${
n.read_at ? "bg-ink-100 text-ink-500" : "bg-primary-500 text-white"
}`}
>
{iconOf(n.kind)}
</span>
<span className="min-w-0 flex-1">
<span className="flex items-baseline gap-2">
<span className="truncate text-sm font-medium text-ink-900">{n.title}</span>
{!n.read_at ? (
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-clay-500" />
) : null}
<span className="ml-auto shrink-0 text-2xs text-ink-400">
{ago(n.created_at)}
</span>
</span>
{n.body ? (
<span className="mt-1 block truncate text-xs text-ink-500">{n.body}</span>
) : null}
{n.item_title ? (
<span className="mt-1.5 inline-flex items-center gap-1 text-2xs text-ink-400">
<Clock size={11} />
{n.item_title}
</span>
) : null}
</span>
</button>
</li>
))}
</ul>
)}
{hasMore ? (
<div className="mt-4 flex justify-center">
<Button variant="ghost" size="sm" onClick={() => void load(false)} disabled={loading}>
加载更早
</Button>
</div>
) : rows.length > 0 && !hasMore ? (
<p className="mt-4 text-center text-2xs text-ink-300">
<Check size={11} className="mr-1 inline" />
没有更多了
</p>
) : null}
</AppShell>
);
}
+8 -3
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { useParams, useSearchParams } from "react-router-dom";
import { AppShell } from "../components/AppShell";
import { TaskDetail } from "../components/TaskDetail";
import { Check, Inbox, Plus, Search } from "../components/icons";
@@ -41,7 +41,9 @@ export function TasksPage() {
const [draft, setDraft] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [openId, setOpenId] = useState<string | null>(null);
// 从通知点进来时带 ?open=<id>,落地即展开那一条
const [searchParams, setSearchParams] = useSearchParams();
const [openId, setOpenId] = useState<string | null>(searchParams.get("open"));
const [activeIdx, setActiveIdx] = useState(0);
const reqId = useRef(0);
@@ -333,7 +335,10 @@ export function TasksPage() {
<TaskDetail
wsId={wsId}
itemId={openId}
onClose={() => setOpenId(null)}
onClose={() => {
setOpenId(null);
if (searchParams.get("open")) setSearchParams({}, { replace: true });
}}
onChanged={(updated) =>
setItems((prev) => prev.map((it) => (it.id === updated.id ? updated : it)))
}
+205 -19
View File
@@ -1,12 +1,21 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { useParams, useSearchParams } from "react-router-dom";
import { AppShell } from "../components/AppShell";
import { TaskDetail } from "../components/TaskDetail";
import { ChevronRight, TicketIcon } from "../components/icons";
import { Button, EmptyState, InlineAlert, PageHeader, SkeletonRows, StatusPill } from "../components/ui";
import { ChevronRight, Plus, TicketIcon } from "../components/icons";
import {
Button,
EmptyState,
InlineAlert,
PageHeader,
Sheet,
SkeletonRows,
StatusPill,
useToast,
} from "../components/ui";
import { ApiError, api } from "../lib/client";
import { STATUS_LABEL } from "../lib/parse";
import type { Item, Ticket } from "../lib/types";
import type { Item, Member, Ticket } from "../lib/types";
const ROLES = [
{ key: "assigned", label: "派给我的", desc: "别人等你的" },
@@ -25,14 +34,43 @@ const STATUS_FILTERS = [
export function TicketsPage() {
const { wsId = "" } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const [role, setRole] = useState<(typeof ROLES)[number]["key"]>("assigned");
const [status, setStatus] = useState<string>("");
const [tickets, setTickets] = useState<Ticket[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [openId, setOpenId] = useState<string | null>(null);
// 从通知点进来时带 ?open=<id>,落地即展开那一条
const [openId, setOpenId] = useState<string | null>(searchParams.get("open"));
const reqId = useRef(0);
const { push: toast } = useToast();
// 手工开单:这条路径不经过任何任务,所以人得自己选
const [members, setMembers] = useState<Member[]>([]);
const [creating, setCreating] = useState(false);
const [formTitle, setFormTitle] = useState("");
const [formBody, setFormBody] = useState("");
const [formAssignee, setFormAssignee] = useState("");
const [formPriority, setFormPriority] = useState(1);
const [formDue, setFormDue] = useState("");
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!wsId) return;
let alive = true;
void api
.get<{ items: Member[] }>(`/workspaces/${wsId}/members?limit=100`)
.then((page) => {
if (alive) setMembers(page.items);
})
.catch(() => {
/* 成员拉不到时,表单里就没人可选,但不该拦住列表 */
});
return () => {
alive = false;
};
}, [wsId]);
const load = useCallback(
async (nextCursor: string | null) => {
@@ -75,7 +113,8 @@ export function TicketsPage() {
void load(null);
} catch (err) {
if (err instanceof ApiError && err.code === 4009) {
setError("这条刚被别人改过,已为你刷新列表"); void load(null);
setError("这条刚被别人改过,已为你刷新列表");
void load(null);
return;
}
setError(err instanceof ApiError ? err.message : "操作失败");
@@ -84,6 +123,41 @@ export function TicketsPage() {
const currentRole = ROLES.find((r) => r.key === role);
async function createTicket() {
if (!formTitle.trim()) {
setError("工单得有个标题,别人才能知道要办什么");
return;
}
if (!formAssignee) {
setError("先选一个人——工单不指派就等于没人接");
return;
}
setSaving(true);
setError(null);
try {
const created = await api.post<Ticket>(`/workspaces/${wsId}/tickets`, {
title: formTitle.trim(),
body_md: formBody.trim() || null,
assignee_id: formAssignee,
priority: formPriority,
due_at: formDue ? new Date(formDue).toISOString() : null,
});
setCreating(false);
setFormTitle("");
setFormBody("");
setFormAssignee("");
setFormDue("");
setFormPriority(1);
setRole("requested");
toast("工单已开出,对方会收到通知", "success");
setOpenId(created.id);
} catch (err) {
setError(err instanceof ApiError ? err.message : "开单失败");
} finally {
setSaving(false);
}
}
return (
<AppShell wsId={wsId} active="tickets">
<PageHeader
@@ -91,18 +165,24 @@ export function TicketsPage() {
desc="待接 → 办理中 → 待验收 → 完成。验收通过后,当初卡住的那条任务会自动回到待办。"
eyebrow={<>需要别人搭把手的事,都在这里</>}
actions={
<select
className="input h-9 w-36 text-sm"
value={status}
onChange={(e) => setStatus(e.target.value)}
aria-label="按状态筛选"
>
{STATUS_FILTERS.map((s) => (
<option key={s.key} value={s.key}>
{s.label}
</option>
))}
</select>
<>
<select
className="input h-9 w-36 text-sm"
value={status}
onChange={(e) => setStatus(e.target.value)}
aria-label="按状态筛选"
>
{STATUS_FILTERS.map((s) => (
<option key={s.key} value={s.key}>
{s.label}
</option>
))}
</select>
<Button variant="primary" size="sm" onClick={() => setCreating(true)}>
<Plus size={14} />
新建工单
</Button>
</>
}
/>
@@ -218,11 +298,117 @@ export function TicketsPage() {
</div>
)}
{/* 手工开单:不经过任务,直接把一件要别人帮忙的事开成工单 */}
<Sheet
open={creating}
onClose={() => setCreating(false)}
title="新建工单"
subtitle="不是从任务升级来的也可以——写清楚要办什么,指定一个人。"
footer={
<>
<Button variant="ghost" onClick={() => setCreating(false)} disabled={saving}>
取消
</Button>
<Button variant="primary" onClick={() => void createTicket()} disabled={saving}>
{saving ? "正在开单…" : "开单并通知对方"}
</Button>
</>
}
>
<div className="space-y-5">
<div>
<label className="label" htmlFor="ticket-title">
要办什么
</label>
<input
id="ticket-title"
className="input"
value={formTitle}
onChange={(e) => setFormTitle(e.target.value)}
placeholder="一句能直接看懂的话,例如:核对 9 月发票与报销单"
maxLength={200}
autoFocus
/>
</div>
<div>
<label className="label" htmlFor="ticket-body">
详细说明(可选)
</label>
<textarea
id="ticket-body"
className="input min-h-[96px] resize-y text-sm leading-6"
value={formBody}
onChange={(e) => setFormBody(e.target.value)}
placeholder="背景、已有的线索、验收标准…对方看到的就是这些"
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<label className="label" htmlFor="ticket-assignee">
交给谁
</label>
<select
id="ticket-assignee"
className="input"
value={formAssignee}
onChange={(e) => setFormAssignee(e.target.value)}
>
<option value="">选择一个人…</option>
{members.map((m) => (
<option key={m.user_id} value={m.user_id}>
{m.nickname || m.user_id.slice(0, 8)}
</option>
))}
</select>
</div>
<div>
<label className="label" htmlFor="ticket-priority">
优先级
</label>
<select
id="ticket-priority"
className="input"
value={formPriority}
onChange={(e) => setFormPriority(Number(e.target.value))}
>
<option value={0}>无</option>
<option value={1}>低</option>
<option value={2}>中</option>
<option value={3}>高</option>
</select>
</div>
</div>
<div>
<label className="label" htmlFor="ticket-due">
希望什么时候办好(可选)
</label>
<input
id="ticket-due"
type="datetime-local"
className="input"
value={formDue}
onChange={(e) => setFormDue(e.target.value)}
/>
</div>
<p className="rounded-xl border border-line-200 bg-paper-200/60 px-3.5 py-2.5 text-2xs leading-5 text-ink-500">
开出后对方会收到通知,并按「待接 → 办理中 → 待验收 → 完成」推进。
手工开的单没有来源任务,验收通过后不会回流任何任务,但同样会沉淀一份知识草稿。
</p>
</div>
</Sheet>
{openId && (
<TaskDetail
wsId={wsId}
itemId={openId}
onClose={() => setOpenId(null)}
onClose={() => {
setOpenId(null);
if (searchParams.get("open")) setSearchParams({}, { replace: true });
}}
onChanged={(updated: Item) =>
setTickets((prev) => prev.map((t) => (t.id === updated.id ? { ...t, ...updated } : t)))
}