feat: 看板全局时间筛选 + 协同留言抽屉

任务1 — 后端时间快照逻辑:
  get_dashboard_stats 新增 since/until 参数
  PENDING/WIP/总数 → 永远实时快照(忽略时间筛选)
  COMPLETED/REJECTED → 严格按时段过滤
  完成率基于过滤后的COMPLETED计算

任务2 — 前端时间筛选器:
  Radio.Button: 今天 | 近7天 | 近30天 | 自定义
  DatePicker.RangePicker 自定义区间
  切换时重新拉取 /dashboard/stats

任务3 — 协同留言抽屉:
  后端: GET /dashboard/messages(上帝视角全厂数据)
    JOIN Product → serial_number + material_name
    支持 keyword 搜: SN/物料名/留言人/内容
    按 created_at 倒序
  前端: Drawer + Input.Search + List
    点击"留言"数字打开抽屉
    分页展示: 留言人/内容/SN标签/物料名/时间
This commit is contained in:
2026-08-12 13:50:56 +08:00
parent 39377ae5e4
commit 3b53db03c1
4 changed files with 392 additions and 106 deletions

View File

@ -1,14 +1,35 @@
import { useEffect, useState } from "react";
import { useEffect, useState, useCallback } from "react";
import {
Package, ClipboardList, Bell, TrendingUp, AlertTriangle,
RefreshCw, Loader2, AlertCircle, Plus, ArrowRight, Clock, MessageCircle,
RefreshCw, Loader2, AlertCircle, ArrowRight, Clock, MessageCircle, Search,
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import { Radio, DatePicker, Drawer, Input, List, Tag } from "antd";
import dayjs, { type Dayjs } from "dayjs";
import {
fetchDashboardStats, fetchWipTasks,
type DashboardStats, type WipTask,
fetchDashboardStats, fetchWipTasks, fetchDashboardMessages,
type DashboardStats, type WipTask, type ProductMessageItem,
} from "../../services/dashboardApi";
const { RangePicker } = DatePicker;
// ─── 时间筛选选项 ─────────────────────────────────────────
type DateRangeKey = "today" | "7d" | "30d" | "custom";
function rangeToParams(key: DateRangeKey, customRange: [Dayjs, Dayjs] | null) {
if (key === "custom" && customRange) {
return {
since: customRange[0].startOf("day").toISOString(),
until: customRange[1].endOf("day").toISOString(),
};
}
const since = dayjs().startOf("day");
if (key === "7d") return { since: since.subtract(7, "day").toISOString() };
if (key === "30d") return { since: since.subtract(30, "day").toISOString() };
// today
return { since: since.toISOString() };
}
// ─── 进度条 ───────────────────────────────────────────────
function ProgressBar({ a, b, c, total, labels }: {
a: number; b: number; c: number; total: number;
@ -41,32 +62,28 @@ function ProgressBar({ a, b, c, total, labels }: {
);
}
// ─── 滞留时间颜色 ─────────────────────────────────────────
function durationColor(h: number): string {
// ─── 滞留时间 ─────────────────────────────────────────────
function durationColor(h: number) {
if (h >= 48) return "text-red-600 bg-red-50";
if (h >= 24) return "text-orange-600 bg-orange-50";
if (h >= 8) return "text-amber-600 bg-amber-50";
return "text-gray-500 bg-gray-50";
}
function durationLabel(h: number): string {
function durationLabel(h: number) {
if (h >= 48) return `${Math.round(h / 24)}`;
if (h >= 24) return `${Math.round(h / 24)}`;
if (h >= 1) return `${h}小时`;
return `${Math.round(h * 60)}分钟`;
}
// ─── 在制品条目 ───────────────────────────────────────────
function WipRow({ t }: { t: WipTask }) {
return (
<div className="flex items-center gap-3 border-b border-gray-50 py-2.5 last:border-0">
{/* 状态标识 */}
<span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold ${
t.status === "WIP" ? "bg-blue-100 text-blue-700" : "bg-amber-100 text-amber-700"
}`}>
{t.status === "WIP" ? "进行中" : "待接收"}
</span>
{/* 任务信息 */}
<div className="min-w-0 flex-1">
<div className="flex items-baseline gap-2">
<span className="text-sm font-medium text-gray-700 truncate">{t.task_name}</span>
@ -77,7 +94,6 @@ function WipRow({ t }: { t: WipTask }) {
{t.received_at && <span>: {t.received_at}</span>}
</div>
</div>
{/* 滞留时长 */}
<span className={`shrink-0 rounded-md px-2 py-1 text-xs font-bold ${durationColor(t.duration_hours)}`}>
<Clock className="mr-0.5 inline h-3 w-3" />
{durationLabel(t.duration_hours)}
@ -86,29 +102,85 @@ function WipRow({ t }: { t: WipTask }) {
);
}
// ─── 留言列表项 ───────────────────────────────────────────
function MsgRow({ m }: { m: ProductMessageItem }) {
const t = m.created_at ? dayjs(m.created_at).format("MM-DD HH:mm") : "";
return (
<List.Item>
<div className="flex w-full flex-col gap-1">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-700">{m.operator_name}</span>
<span className="text-[11px] text-gray-400">{t}</span>
</div>
<div className="text-sm text-gray-600">{m.content}</div>
<div className="flex items-center gap-2 text-[11px] text-gray-400">
<Tag color="blue" className="text-[10px] leading-tight">{m.product_sn}</Tag>
<span className="truncate">{m.material_name}</span>
</div>
</div>
</List.Item>
);
}
// ─── 主组件 ───────────────────────────────────────────────
export default function AdminDashboard() {
const [stats, setStats] = useState<DashboardStats | null>(null);
const [wipTasks, setWipTasks] = useState<WipTask[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 时间筛选
const [dateKey, setDateKey] = useState<DateRangeKey>("today");
const [customRange, setCustomRange] = useState<[Dayjs, Dayjs] | null>(null);
// 留言抽屉
const [msgDrawerOpen, setMsgDrawerOpen] = useState(false);
const [msgKeyword, setMsgKeyword] = useState("");
const [msgData, setMsgData] = useState<ProductMessageItem[]>([]);
const [msgTotal, setMsgTotal] = useState(0);
const [msgLoading, setMsgLoading] = useState(false);
const navigate = useNavigate();
const loadData = () => {
// ── 加载主数据 ──
const loadData = useCallback((key: DateRangeKey, range: [Dayjs, Dayjs] | null) => {
setLoading(true);
const { since, until } = rangeToParams(key, range);
Promise.all([
fetchDashboardStats(),
fetchDashboardStats(since, until),
fetchWipTasks(20),
])
.then(([s, w]) => { setStats(s); setWipTasks(w); setError(null); })
.catch(() => setError("加载失败,请确认后端已启动"))
.finally(() => setLoading(false));
}, []);
useEffect(() => { loadData(dateKey, customRange); }, [dateKey, customRange]);
// ── 加载留言 ──
const loadMessages = useCallback(async (kw: string) => {
setMsgLoading(true);
try {
const res = await fetchDashboardMessages(kw, 0, 50);
setMsgData(res.items);
setMsgTotal(res.total);
} catch { /* ignore */ }
finally { setMsgLoading(false); }
}, []);
const openMsgDrawer = () => {
setMsgDrawerOpen(true);
setMsgKeyword("");
loadMessages("");
};
useEffect(() => { loadData(); }, []);
const onMsgSearch = (value: string) => {
setMsgKeyword(value);
loadMessages(value);
};
// ── 加载态 ──
if (loading) {
if (loading && !stats) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
@ -116,33 +188,63 @@ export default function AdminDashboard() {
);
}
// ── 错误态 ──
if (error || !stats) {
return (
<div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
<AlertCircle className="h-4 w-4" />{error || "数据为空"}
<button onClick={loadData} className="ml-auto text-blue-600 underline"></button>
<button onClick={() => loadData(dateKey, customRange)} className="ml-auto text-blue-600 underline"></button>
</div>
);
}
return (
<div className="space-y-6">
{/* ═══ 页头 ═══ */}
<div className="flex items-center justify-between">
{/* ═══ 页头 + 时间筛选器 ═══ */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-xl font-bold text-gray-800">📊 </h2>
<p className="mt-0.5 text-sm text-gray-400">
= =
= =
</p>
</div>
<button onClick={loadData}
className="flex items-center gap-1 rounded-lg px-3 py-1.5 text-xs text-gray-500 hover:bg-gray-100">
<RefreshCw className="h-3.5 w-3.5" />
</button>
<div className="flex items-center gap-3">
{/* 时间筛选 */}
<Radio.Group
value={dateKey}
onChange={e => { setDateKey(e.target.value); setCustomRange(null); }}
size="small"
optionType="button"
buttonStyle="solid"
>
<Radio.Button value="today"></Radio.Button>
<Radio.Button value="7d">7</Radio.Button>
<Radio.Button value="30d">30</Radio.Button>
<Radio.Button value="custom"></Radio.Button>
</Radio.Group>
{dateKey === "custom" && (
<RangePicker
size="small"
value={customRange as any}
onChange={dates => setCustomRange(dates as [Dayjs, Dayjs] | null)}
style={{ width: 240 }}
placeholder={["开始", "结束"]}
/>
)}
<button onClick={() => loadData(dateKey, customRange)}
className="flex items-center gap-1 rounded-lg px-2 py-1 text-xs text-gray-500 hover:bg-gray-100">
<RefreshCw className="h-3.5 w-3.5" />
</button>
</div>
</div>
{/* ═══ 第1行4 张概览卡片 ═══ */}
{/* 提示:已完结受时间筛选 */}
{dateKey !== "today" && (
<div className="rounded-lg bg-blue-50 px-3 py-1.5 text-[11px] text-blue-600">
📐 <strong>/</strong>
</div>
)}
{/* ═══ 4 卡片 ═══ */}
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
{/* 产品流转 */}
<div className="rounded-xl bg-white p-5 shadow-sm">
@ -151,7 +253,7 @@ export default function AdminDashboard() {
<h3 className="text-sm font-semibold text-gray-700">📦 </h3>
</div>
<p className="text-3xl font-bold text-gray-800">{stats.products_total}<span className="text-sm font-normal text-gray-400"> </span></p>
<p className="mb-3 text-[11px] text-gray-400"> · /</p>
<p className="mb-3 text-[11px] text-gray-400"></p>
<ProgressBar a={stats.products_pending} b={stats.products_in_progress} c={stats.products_completed}
total={stats.products_total} labels={["待流转", "流转中", "已完成"]} />
</div>
@ -163,34 +265,39 @@ export default function AdminDashboard() {
<h3 className="text-sm font-semibold text-gray-700">📋 </h3>
</div>
<p className="text-3xl font-bold text-gray-800">{stats.tasks_total}<span className="text-sm font-normal text-gray-400"> </span></p>
<p className="mb-3 text-[11px] text-gray-400"> · 1=N任务</p>
<p className="mb-3 text-[11px] text-gray-400">PENDING/WIP | COMPLETED </p>
<ProgressBar a={stats.tasks_pending} b={stats.tasks_in_progress} c={stats.tasks_completed}
total={stats.tasks_total} labels={["待接收", "进行中", "已完成"]} />
</div>
{/* 品质 & 留言板未读 */}
{/* 品质 & 留言 */}
<div className="rounded-xl bg-white p-5 shadow-sm">
<div className="mb-4 flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-orange-600" />
<h3 className="text-sm font-semibold text-gray-700"> </h3>
<h3 className="text-sm font-semibold text-gray-700"> </h3>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="rounded-lg bg-red-50 p-3 text-center">
<p className="text-xl font-bold text-red-600">{stats.tasks_rejected + stats.tasks_rework}</p>
<p className="text-[11px] text-red-500">/</p>
</div>
<button onClick={() => navigate("/notifications")}
className="rounded-lg bg-blue-50 p-3 text-center hover:bg-blue-100 transition-colors border-0 cursor-pointer">
<p className="text-xl font-bold text-blue-600">{stats.unread_notifications}</p>
<p className="text-[11px] text-blue-500"> </p>
{/* 留言 — 可点击打开抽屉 */}
<button
onClick={openMsgDrawer}
className="rounded-lg bg-purple-50 p-3 text-center hover:bg-purple-100 transition-colors border-0 cursor-pointer"
>
<p className="text-xl font-bold text-purple-600">{stats.unread_messages}</p>
<p className="flex items-center justify-center gap-1 text-[11px] text-purple-500">
<MessageCircle className="h-3 w-3" />
</p>
</button>
</div>
<div className="mt-3 flex items-center justify-between border-t border-gray-100 pt-3">
<div className="flex items-center gap-1 text-xs text-gray-500">
<MessageCircle className="h-3.5 w-3.5" />
</div>
<span className="text-lg font-bold text-purple-600">{stats.unread_messages}</span>
<button onClick={() => navigate("/notifications")}
className="flex items-center gap-1 text-xs text-gray-500 hover:text-blue-600">
<Bell className="h-3.5 w-3.5" />
{stats.unread_notifications > 0 ? `(${stats.unread_notifications})` : ""}
</button>
</div>
</div>
@ -204,7 +311,7 @@ export default function AdminDashboard() {
<p className="text-3xl font-bold text-emerald-600">
{stats.tasks_total > 0 ? Math.round((stats.tasks_completed / stats.tasks_total) * 100) : 0}%
</p>
<p className="text-sm text-gray-400">{stats.tasks_completed}/{stats.tasks_total} </p>
<p className="text-sm text-gray-400">{stats.tasks_completed}/{stats.tasks_total}</p>
</div>
<svg viewBox="0 0 100 100" className="mx-auto mt-4 h-20 w-20 -rotate-90">
<circle cx="50" cy="50" r="40" fill="none" stroke="#f3f4f6" strokeWidth="10" />
@ -212,26 +319,23 @@ export default function AdminDashboard() {
strokeDasharray={`${stats.tasks_total > 0 ? (stats.tasks_completed / stats.tasks_total) * 251 : 0} 251`}
strokeLinecap="round" />
</svg>
<p className="mt-1 text-center text-[10px] text-gray-400"></p>
</div>
</div>
{/* ═══ 第2行在制品看板 + 快捷入口 ═══ */}
{/* ═══ 在制品 + 快捷入口 ═══ */}
<div className="grid gap-4 lg:grid-cols-3">
{/* 在制品看板 — 替换原来的"最近动态" */}
<div className="rounded-xl bg-white p-5 shadow-sm lg:col-span-2">
<div className="mb-3 flex items-center justify-between">
<h3 className="flex items-center gap-2 text-sm font-semibold text-gray-700">
<Clock className="h-4 w-4 text-orange-500" />
<Clock className="h-4 w-4 text-orange-500" />
</h3>
<span className="text-[11px] text-gray-400">
· {wipTasks.length}
</span>
<span className="text-[11px] text-gray-400"> {wipTasks.length} </span>
</div>
{wipTasks.length === 0 ? (
<div className="py-10 text-center text-sm text-gray-400">🎉 </div>
<div className="py-10 text-center text-sm text-gray-400">🎉 </div>
) : (
<div>
{/* 表头 */}
<div className="mb-1 flex items-center gap-3 text-[11px] font-medium text-gray-400">
<span className="w-14 shrink-0"></span>
<span className="flex-1"> · </span>
@ -248,38 +352,64 @@ export default function AdminDashboard() {
<div className="space-y-2">
<button onClick={() => navigate("/admin/products")}
className="flex w-full items-center justify-between rounded-lg bg-blue-50 px-4 py-3 text-left text-sm font-medium text-blue-700 hover:bg-blue-100 transition-colors">
<span className="flex items-center gap-2"><Plus className="h-4 w-4" /></span>
<ArrowRight className="h-4 w-4" />
<span>📦 </span><ArrowRight className="h-4 w-4" />
</button>
<button onClick={() => navigate("/admin/tasks")}
className="flex w-full items-center justify-between rounded-lg bg-purple-50 px-4 py-3 text-left text-sm font-medium text-purple-700 hover:bg-purple-100 transition-colors">
<span className="flex items-center gap-2"><ClipboardList className="h-4 w-4" /></span>
<ArrowRight className="h-4 w-4" />
<span>📋 </span><ArrowRight className="h-4 w-4" />
</button>
<button onClick={() => navigate("/notifications")}
className="flex w-full items-center justify-between rounded-lg bg-red-50 px-4 py-3 text-left text-sm font-medium text-red-700 hover:bg-red-100 transition-colors">
<span className="flex items-center gap-2"><Bell className="h-4 w-4" />
{stats.unread_notifications > 0 ? `通知 (${stats.unread_notifications})` : "通知中心"}
</span>
<ArrowRight className="h-4 w-4" />
className="flex w-full items-center justify-between rounded-lg bg-blue-50 px-4 py-3 text-left text-sm font-medium text-blue-700 hover:bg-blue-100 transition-colors">
<span>🔔 </span><ArrowRight className="h-4 w-4" />
</button>
<button onClick={() => navigate("/admin/print-config")}
className="flex w-full items-center justify-between rounded-lg bg-amber-50 px-4 py-3 text-left text-sm font-medium text-amber-700 hover:bg-amber-100 transition-colors">
<span className="flex items-center gap-2">🖨 </span>
<ArrowRight className="h-4 w-4" />
<button onClick={openMsgDrawer}
className="flex w-full items-center justify-between rounded-lg bg-purple-50 px-4 py-3 text-left text-sm font-medium text-purple-700 hover:bg-purple-100 transition-colors">
<span>💬 </span><ArrowRight className="h-4 w-4" />
</button>
</div>
<div className="mt-5 rounded-lg bg-gray-50 p-3">
<p className="text-[11px] leading-relaxed text-gray-500">
<strong>💡 = </strong><br />
=
<span className="text-red-600 font-bold">48</span>
<span className="text-orange-600 font-bold">24</span>
</p>
</div>
</div>
</div>
{/* ═══ 留言抽屉 ═══ */}
<Drawer
title={`💬 协同留言板(全厂 · ${msgTotal} 条)`}
open={msgDrawerOpen}
onClose={() => setMsgDrawerOpen(false)}
width={520}
styles={{ body: { padding: 0 } }}
>
<div className="px-4 pt-4">
<Input
prefix={<Search className="h-4 w-4 text-gray-400" />}
placeholder="搜索 SN码 / 物料名称 / 留言人 / 内容"
value={msgKeyword}
onChange={e => setMsgKeyword(e.target.value)}
onPressEnter={() => onMsgSearch(msgKeyword)}
allowClear
onClear={() => onMsgSearch("")}
/>
</div>
<List
className="mt-3 px-4"
loading={msgLoading}
dataSource={msgData}
locale={{ emptyText: "暂无留言记录" }}
renderItem={(item: ProductMessageItem) => <MsgRow m={item} />}
pagination={{
total: msgTotal,
pageSize: 30,
size: "small",
onChange: (page, size) => {
loadMessages(msgKeyword);
// simplified: re-fetch with skip
fetchDashboardMessages(msgKeyword, (page - 1) * size, size)
.then(res => { setMsgData(res.items); setMsgTotal(res.total); })
.catch(() => {});
},
showTotal: (t) => `${t}`,
}}
/>
</Drawer>
</div>
);
}

View File

@ -25,8 +25,25 @@ export interface WipTask {
duration_hours: number;
}
export async function fetchDashboardStats(): Promise<DashboardStats> {
const { data } = await api.get<DashboardStats>("/dashboard/stats");
export interface ProductMessageItem {
id: string;
content: string;
operator_name: string;
product_sn: string;
material_name: string;
created_at: string;
}
export interface ProductMessageList {
items: ProductMessageItem[];
total: number;
}
export async function fetchDashboardStats(since?: string, until?: string): Promise<DashboardStats> {
const params: Record<string, string> = {};
if (since) params.since = since;
if (until) params.until = until;
const { data } = await api.get<DashboardStats>("/dashboard/stats", { params });
return data;
}
@ -34,3 +51,12 @@ export async function fetchWipTasks(limit = 20): Promise<WipTask[]> {
const { data } = await api.get<WipTask[]>("/dashboard/wip-tasks", { params: { limit } });
return data;
}
export async function fetchDashboardMessages(
keyword = "", skip = 0, limit = 30,
): Promise<ProductMessageList> {
const { data } = await api.get<ProductMessageList>("/dashboard/messages", {
params: { keyword, skip, limit },
});
return data;
}