droboticflow/src/components/WorkforceStatisticsPanel.tsx

456 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { userErrorMessage } from "../lib/user-error-message.js";
import React, { useEffect, useMemo, useState } from "react";
import type { DashboardWorkforceMetric, WorkforceReturnDetail, WorkforceReturnMetrics } from "../types";
import { workforceApi, type WorkforceDetailQuery, type WorkforceReportQuery } from "../services/api/workforce";
import { useTimeZone } from "../context/TimeZoneContext";
import { formatCompactDateTime } from "../lib/datetime";
import { stripTaskOpinionLines } from "../lib/task-scope-visibility.js";
import { useUser } from "../context/UserContext";
export type WorkforceFilters = {
projectId?: string;
supplierId?: string;
from?: string;
to?: string;
};
type Member = DashboardWorkforceMetric;
const count = (value?: number) => value ?? "暂无数据";
const duration = (value?: number) =>
value === undefined ? "暂无数据" : value < 60 ? `${Number(value.toFixed(1))} 秒` : `${(value / 60).toFixed(1)} 分钟`;
const rate = (value?: number | null) => (value == null ? "暂无数据" : `${value.toFixed(1)}%`);
const roleLabel = (role?: string) =>
role === "annotator"
? "标注员"
: role === "quality_reviewer"
? "质检审核员"
: role === "acceptance_reviewer"
? "最终验收员"
: "未标明";
const isReviewerRole = (role?: string) => role === "quality_reviewer" || role === "acceptance_reviewer";
const apiDate = (value?: string, end = false) => {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
return `${value}T${end ? "23:59:59.999" : "00:00:00"}+08:00`;
};
function ReturnSummary({ label, value }: { label: string; value?: WorkforceReturnMetrics }) {
if (!value) return <p>{label}:暂无数据</p>;
return (
<div className="space-y-1">
<p className="font-medium">
{label}:{value.decisionCount} 次 · {value.taskCount} 个任务
</p>
<p>
{value.problemCount} 个问题对象 · {value.sliceCount} 个切片 · 覆盖 {duration(value.videoSeconds)}
</p>
{(value.unlocatedCount > 0 || value.unknownDetailCount > 0) && (
<p className="text-amber-700 dark:text-amber-300">
{value.unlocatedCount > 0 && `${value.unlocatedCount} 个意见无可定位范围。`}
{value.unknownDetailCount > 0 && `${value.unknownDetailCount} 次历史打回缺少详细范围。`}
以上未计入覆盖时长。
</p>
)}
</div>
);
}
function ReturnDetails({ query }: { query: WorkforceDetailQuery }) {
const { timeZone } = useTimeZone();
const [offset, setOffset] = useState(0);
const [data, setData] = useState<{ items: WorkforceReturnDetail[]; total: number } | null>(null);
const [error, setError] = useState("");
const [attempt, setAttempt] = useState(0);
const identity = JSON.stringify(query);
useEffect(() => {
let active = true;
setData(null);
setError("");
workforceApi
.returns(JSON.parse(identity), offset)
.then((result) => {
if (active) setData(result);
})
.catch(() => {
if (active) setError("打回明细暂时未能加载,请重试。");
});
return () => {
active = false;
};
}, [identity, offset, attempt]);
if (error) {
return (
<p role="alert">
{userErrorMessage(error)}{" "}
<button className="underline" onClick={() => setAttempt((value) => value + 1)}>
重试
</button>
</p>
);
}
if (!data) return <p role="status">正在加载打回明细…</p>;
return (
<div className="mt-3 space-y-3">
{data.items.map((item) => (
<article
key={`${item.id}/${item.userId}/${item.supplierId}`}
className="rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] p-3"
>
<p className="font-medium">
{item.stage === "quality" ? "质检打回" : "终审打回"} · 第 {item.round} 轮 ·{" "}
{formatCompactDateTime(item.createdAt, timeZone)}
</p>
<p className="mt-1 break-all text-xs text-gray-500">任务:{item.taskIds.join("、") || item.taskId}</p>
{item.problems?.length ? (
<ol className="mt-2 space-y-2">
{item.problems.map((problem, index) => (
<li key={`${problem.id}-${index}`} className="border-l-2 border-orange-300 pl-3">
<div className="break-all text-xs text-gray-500">
{`${problem.scope === "slice" ? "切片" : problem.scope === "action" ? "动作" : "时间点"} ${problem.actionId || problem.sliceId || ""}`}
{problem.sourceItemId ? ` · 来源 ${problem.sourceItemId}` : ""}
{problem.end !== undefined && problem.start !== undefined && problem.end > problem.start
? ` · ${problem.start.toFixed(3)}–${problem.end.toFixed(3)} 秒(${problem.timeBasis === "slice-seconds" ? "片内" : "原视频"})`
: " · 无可定位范围"}
</div>
<p className="whitespace-pre-wrap break-words">{problem.text}</p>
</li>
))}
</ol>
) : (
<p className="mt-2 whitespace-pre-wrap break-words">
{stripTaskOpinionLines(item.comment) || "历史记录未保存意见明细,范围待核对。"}
</p>
)}
</article>
))}
{!data.items.length && <p>当前区间没有正式打回记录。</p>}
<div className="flex items-center gap-4">
<button
disabled={offset === 0}
onClick={() => setOffset(Math.max(0, offset - 20))}
className="disabled:opacity-40"
>
上一页
</button>
<span>
{data.total} 条记录 · 第 {Math.floor(offset / 20) + 1} 页
</span>
<button
disabled={offset + 20 >= data.total}
onClick={() => setOffset(offset + 20)}
className="disabled:opacity-40"
>
下一页
</button>
</div>
</div>
);
}
function DailyDetails({ query }: { query: WorkforceReportQuery }) {
const [items, setItems] = useState<Member[] | null>(null);
const [error, setError] = useState("");
const identity = JSON.stringify({ ...query, groupBy: "day" });
useEffect(() => {
let active = true;
setItems(null);
workforceApi
.report(JSON.parse(identity))
.then((result) => {
if (active) setItems(result.items);
})
.catch(() => {
if (active) setError("按天工作记录暂时未能加载,请重试。");
});
return () => {
active = false;
};
}, [identity]);
if (error) return <p role="alert">{userErrorMessage(error)}</p>;
if (!items) return <p role="status">正在加载按天明细…</p>;
return (
<div className="mt-3 overflow-x-auto rounded-lg border border-[color:var(--app-border)]">
<table className="w-full min-w-[760px] text-left text-xs">
<thead className="border-b border-[color:var(--app-border)] text-gray-500">
<tr>
{["日期", "产出", "质检通过率", "终审通过率", "返工", "视频时长", "审查产出", "审查视频时长"].map(
(label) => (
<th key={label} className="px-3 py-2 font-normal">
{label}
</th>
),
)}
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={`${item.userId}/${item.date}`} className="border-b border-[color:var(--app-border)] last:border-0">
<td className="px-3 py-2">{item.date || "未标明日期"}</td>
<td className="px-3 py-2">{count(item.outputCount ?? item.firstSubmittedTasks)}</td>
<td className="px-3 py-2">{rate(item.qualityPassRate)}</td>
<td className="px-3 py-2">{rate(item.acceptancePassRate)}</td>
<td className="px-3 py-2">{count(item.reworkSubmissionCount)}</td>
<td className="px-3 py-2">{duration(item.firstVideoSeconds)}</td>
<td className="px-3 py-2">{count(item.reviewDecisionCount)}</td>
<td className="px-3 py-2">{duration(item.reviewVideoSeconds)}</td>
</tr>
))}
</tbody>
</table>
{!items.length && <p className="p-4 text-center text-gray-500">当前区间暂无按天记录</p>}
</div>
);
}
export function WorkforceStatisticsPanel({
items,
totals,
from,
to,
projectId,
supplierId,
filters,
surface = "dashboard",
self = false,
vendor = false,
collapsedByDefault = true,
deferLoad = false,
}: {
items: Member[];
totals?: Member;
from?: string;
to?: string;
projectId?: string;
supplierId?: string;
filters?: WorkforceFilters;
surface?: "dashboard" | "workload";
self?: boolean;
vendor?: boolean;
collapsedByDefault?: boolean;
deferLoad?: boolean;
}) {
const { timeZone } = useTimeZone();
const { currentUser } = useUser();
// Reviewers submit nothing, so their own record shows review video seconds
// where annotators see first-submission video seconds.
const reviewerSelf = self && isReviewerRole(currentUser?.role);
const [collapsed, setCollapsed] = useState(collapsedByDefault);
const [search, setSearch] = useState("");
const [role, setRole] = useState("");
const [expanded, setExpanded] = useState<string | null>(null);
const [remoteItems, setRemoteItems] = useState<Member[] | null>(null);
const [remoteTotals, setRemoteTotals] = useState<Member | undefined>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const effectiveFilters = filters || { projectId, supplierId, from, to };
const filterKey = JSON.stringify(effectiveFilters);
const apiFilters: WorkforceFilters = {
...effectiveFilters,
from: apiDate(effectiveFilters.from),
to: apiDate(effectiveFilters.to, true),
};
useEffect(() => {
if (collapsed || !deferLoad) return;
let active = true;
setLoading(true);
setError("");
workforceApi
.report({ ...apiFilters, role, groupBy: "member" })
.then((result) => {
if (!active) return;
setRemoteItems(result.items);
setRemoteTotals(result.totals);
})
.catch(() => {
if (active) setError("工作记录暂时未能加载,请重试。");
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [collapsed, deferLoad, role, filterKey]);
const visibleItems = remoteItems || items;
const visibleTotals = remoteTotals || totals;
const filtered = visibleItems.filter((member) => {
if (role && member.role !== role) return false;
return `${member.userName || ""} ${member.userId || ""} ${member.supplierName || ""} ${member.supplierId || ""}`
.toLowerCase()
.includes(search.trim().toLowerCase());
});
// Until the first report arrives, "暂无数据" would read as an empty record.
const pending = loading && !visibleTotals;
const cards = [
reviewerSelf
? ["审查产出", count(visibleTotals?.reviewDecisionCount)]
: ["产出", count(visibleTotals?.outputCount ?? visibleTotals?.firstSubmittedTasks)],
["质量通过率", rate(visibleTotals?.qualityPassRate)],
["返工次数", count(visibleTotals?.reworkSubmissionCount)],
reviewerSelf
? ["审查视频时长", duration(visibleTotals?.reviewVideoSeconds)]
: ["视频时长", duration(visibleTotals?.firstVideoSeconds)],
].map(([label, value]) => [label, pending ? "加载中…" : value]);
const title = self ? "我的工作记录" : vendor ? "供应商团队工作记录" : "工作记录";
return (
<section className="dashboard-workforce space-y-4 text-[color:var(--app-text)]">
<header className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-xl font-bold">{title}</h2>
{!collapsed && (
<p className="mt-1 text-xs text-gray-500">
{formatCompactDateTime(from || effectiveFilters.from, timeZone)} 至{" "}
{formatCompactDateTime(to || effectiveFilters.to, timeZone)}
</p>
)}
</div>
<button
type="button"
className="rounded-lg border border-[color:var(--app-border)] px-3 py-2 text-sm"
onClick={() => setCollapsed((value) => !value)}
>
{collapsed ? "展开工作记录" : "收起工作记录"}
</button>
</header>
{!collapsed && (
<>
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
{cards.map(([label, value]) => (
<div
key={label}
aria-label={
label === "视频时长" ? "首交视频时长" : label === "审查视频时长" ? "审查视频时长" : undefined
}
className="rounded-xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)] p-4"
>
<div className="text-xs text-gray-500">{label}</div>
<div className="mt-2 text-2xl font-semibold">{value}</div>
</div>
))}
</div>
{reviewerSelf && !pending && (visibleTotals?.unknownReviewVideoCount ?? 0) > 0 && (
<p className="text-xs text-amber-700 dark:text-amber-300">
另有 {visibleTotals?.unknownReviewVideoCount} 次审查决定缺少可靠的切片版本,待核对,未计入审查视频时长。
</p>
)}
{loading && (
<p role="status" className="text-sm text-gray-500">
正在加载工作记录…
</p>
)}
{error && (
<p role="alert" className="text-sm text-red-600">
{userErrorMessage(error)}
</p>
)}
{!self && (
<div className="flex flex-wrap gap-2">
<input
aria-label="筛选供应商成员指标"
placeholder="按成员或供应商筛选"
value={search}
onChange={(event) => setSearch(event.target.value)}
className="min-w-[220px] flex-1 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-3 py-2 text-sm"
/>
<select
aria-label="筛选工作记录角色"
value={role}
onChange={(event) => setRole(event.target.value)}
className="rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-3 py-2 text-sm"
>
<option value="">全部角色</option>
<option value="annotator">标注员</option>
<option value="quality_reviewer">质检审核员</option>
<option value="acceptance_reviewer">最终验收员</option>
</select>
</div>
)}
<div className="overflow-x-auto rounded-xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)]">
<table className="w-full min-w-[1080px] text-left text-sm">
<thead className="border-b border-[color:var(--app-border)] text-xs text-gray-500">
<tr>
{[
"成员",
"供应商",
"角色",
"产出",
"质量通过率",
"返工",
"视频时长",
"审查产出",
"审查视频时长",
"查看详情",
].map((label) => (
<th key={label} className="whitespace-nowrap px-3 py-3 font-normal">
{label}
</th>
))}
</tr>
</thead>
<tbody>
{filtered.map((member) => {
const key = `${member.userId}/${member.supplierId}/${member.templateVersion ?? ""}`;
const isOpen = expanded === key;
const query: WorkforceDetailQuery = {
userId: member.userId || "",
supplierId: member.supplierId,
projectId: apiFilters.projectId,
from: apiFilters.from,
to: apiFilters.to,
surface,
...(surface === "workload" ? { templateVersion: member.templateVersion } : {}),
};
const reportQuery: WorkforceReportQuery = { ...apiFilters, userId: member.userId, role: member.role };
return (
<React.Fragment key={key}>
<tr className="border-b border-[color:var(--app-border)] align-top [&>td]:px-3 [&>td]:py-3">
<td>{member.userName || member.userId || "归属待核对"}</td>
<td>
{member.supplierName || (member.supplierId ? "历史供应商(名称待核对)" : "未分配供应商")}
</td>
<td>{roleLabel(member.role)}</td>
<td>{count(member.outputCount ?? member.firstSubmittedTasks)}</td>
<td>{rate(member.qualityPassRate)}</td>
<td>{count(member.reworkSubmissionCount)}</td>
<td>{duration(member.firstVideoSeconds)}</td>
<td>{count(member.reviewDecisionCount)}</td>
<td>{duration(member.reviewVideoSeconds)}</td>
<td>
<button
aria-expanded={isOpen}
onClick={() => setExpanded(isOpen ? null : key)}
className="whitespace-nowrap text-blue-600 underline"
>
{isOpen ? "收起" : "查看详情"}
</button>
</td>
</tr>
{isOpen && (
<tr>
<td colSpan={10} className="p-4">
<div className="grid gap-3 text-sm md:grid-cols-2">
<ReturnSummary label="标注收到质检打回" value={member.qualityReturns} />
<ReturnSummary label="质检收到终审打回" value={member.acceptanceReturns} />
</div>
<DailyDetails query={reportQuery} />
<ReturnDetails query={query} />
</td>
</tr>
)}
</React.Fragment>
);
})}
</tbody>
</table>
{!filtered.length && (
<p className="p-8 text-center text-gray-500">
{visibleItems.length ? "没有匹配的成员记录" : "当前区间暂无工作记录"}
</p>
)}
</div>
</>
)}
</section>
);
}