forked from longtao.wu/droboticflow
🐛 Fix dashboard date ranges, stale results and production reads
This commit is contained in:
parent
d93fb5f0dd
commit
6eee426e3c
10
.scratch/dashboard-date-refresh/work.md
Normal file
10
.scratch/dashboard-date-refresh/work.md
Normal file
@ -0,0 +1,10 @@
|
||||
# Dashboard dates, freshness and production reads
|
||||
|
||||
Goal: Fix shared dashboard single-day selection, stale results and slow production reads.
|
||||
Agent: Codex
|
||||
Base: codex/release-review-source-20261103 @ d93fb5f0 (verified live baseline; contains origin/dev; follow-up to user review).
|
||||
Scope: Shared dashboard UI, production report read path and focused regression tests.
|
||||
Out of scope: Production writes, indexes, deployment and changing ADR 0012 cohort semantics.
|
||||
Risk: Preserve exclusive API bounds and existing authorization; UI uses inclusive dates. Report read optimizations require result equivalence.
|
||||
|
||||
Verification: Five-role browser flows cover inclusive dates, invalid input, recovery, snapshot refresh, CSV, daily work and legacy zero counters. Mongo synthetic evidence preserves exact report results and tenant/database isolation; cache hits avoid repeated finds. Production cold-query latency remains unverified after deployment; no new indexes or production writes are authorized or performed. Evidence is under local-data/test-results/dashboard-date-refresh-evidence/.
|
||||
@ -10,6 +10,14 @@
|
||||
|
||||
误判率按原正式意见点计数,`不改了(误报)` 为确认误报,撤销即取消。保留原意见及原判定人,不将误报改成标注返工。延续 ADR 0009,整体任务意见不计。标注员处理原审核意见;领取返工的审核员可处理本来源的验收意见,不能修改其他来源或其他人的当前任务。写入保留任务版本检查和处理记录 CAS。
|
||||
|
||||
## 日期交互与每日作业入口
|
||||
|
||||
界面日期控件包含起止两个自然日,允许选择同一天;前端将结束日期换成次日再调用原有 `[from, to)` 接口。接口及默认批次范围不变,导出采用相同转换。
|
||||
|
||||
“批次质量”按首次送检日期归组;“每日作业”复用原工作记录接口,按所选期间实际发生的首交、返工重提及正式审查决定统计。两种视图分开呈现,不相加、不改变任务的批次归属。缺少可靠视频时长的记录保留未知状态,不显示为已知零值。
|
||||
|
||||
查询失败不保留可被误认为新筛选结果的旧数字;批次结果展示快照更新时间,过期或正在更新时自动复查。生产总览复用已有 45 秒事实缓存并保留事实读取时间,权限每次实时判定。
|
||||
|
||||
## 展示和数据
|
||||
|
||||
新增 `/api/dashboard/production-quality`;原统计 API 默认语义不变。新接口使用已有共享快照,权限每次从当前身份限制,参数不能扩大组织、供应商或本人范围。默认两类列表各 5 条;CSV 使用相同筛选和快照,导出完整人员结果。昨日及近六天同样按各日首次提交批次计算最新质量结果。
|
||||
|
||||
@ -138,7 +138,14 @@ func (s *server) handleProductionDashboard(w http.ResponseWriter, r *http.Reques
|
||||
return
|
||||
}
|
||||
}
|
||||
snapshot, err := s.store.LoadProductionStats(ctx, org, ids)
|
||||
var snapshot productionstats.Snapshot
|
||||
if cached, ok := s.store.(interface {
|
||||
LoadProductionStatsCached(context.Context, string, []string) (productionstats.Snapshot, error)
|
||||
}); ok {
|
||||
snapshot, err = cached.LoadProductionStatsCached(ctx, org, ids)
|
||||
} else {
|
||||
snapshot, err = s.store.LoadProductionStats(ctx, org, ids)
|
||||
}
|
||||
if err != nil {
|
||||
renderError(w, 500, err)
|
||||
return
|
||||
@ -189,7 +196,11 @@ func (s *server) handleProductionDashboard(w http.ResponseWriter, r *http.Reques
|
||||
}
|
||||
}
|
||||
}
|
||||
response := map[string]any{"configured": scope.Revision > 0, "asOf": started.Format(time.RFC3339Nano), "summary": summary, "projects": projectOptions, "suppliers": supplierOptions, "from": q.From.Format(time.RFC3339), "to": q.To.Format(time.RFC3339)}
|
||||
asOf := snapshot.AsOf
|
||||
if asOf == "" {
|
||||
asOf = started.Format(time.RFC3339Nano)
|
||||
}
|
||||
response := map[string]any{"configured": scope.Revision > 0, "asOf": asOf, "summary": summary, "projects": projectOptions, "suppliers": supplierOptions, "from": q.From.Format(time.RFC3339), "to": q.To.Format(time.RFC3339)}
|
||||
if params.Get("details") == "true" {
|
||||
items := productionstats.Details(report, q, params.Get("metric"), strings.TrimSpace(params.Get("search")))
|
||||
page, pageErr := strconv.Atoi(params.Get("page"))
|
||||
|
||||
@ -11,6 +11,8 @@ type Scope struct {
|
||||
UpdatedBy string `json:"updatedBy,omitempty" bson:"updatedBy,omitempty"`
|
||||
}
|
||||
type Snapshot struct {
|
||||
// AsOf is retained with cached facts, rather than replaced by response time.
|
||||
AsOf string `json:"asOf,omitempty"`
|
||||
Captures []domain.CaptureRecord
|
||||
Runs []domain.RunRecord
|
||||
Items []domain.HumanItemRecord
|
||||
|
||||
113
internal/store/production_event_projection_test.go
Normal file
113
internal/store/production_event_projection_test.go
Normal file
@ -0,0 +1,113 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
"droboticflow/internal/productionstats"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/event"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
func TestProductionMongoReadSkipsEditingEventsWithoutChangingMilestones(t *testing.T) {
|
||||
if os.Getenv("SOURCE_ADMISSION_LOCAL_MONGO") != "1" {
|
||||
t.Skip("isolated local Mongo opt-in")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
var finds atomic.Int64
|
||||
monitor := &event.CommandMonitor{Started: func(_ context.Context, e *event.CommandStartedEvent) {
|
||||
if e.CommandName == "find" {
|
||||
finds.Add(1)
|
||||
}
|
||||
}}
|
||||
client, err := mongo.Connect(ctx, options.Client().SetMonitor(monitor).ApplyURI("mongodb://127.0.0.1:27018/?directConnection=true").SetServerSelectionTimeout(3*time.Second))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Disconnect(context.Background())
|
||||
db := client.Database(fmt.Sprintf("production_event_projection_%d", time.Now().UnixNano()))
|
||||
defer db.Drop(context.Background())
|
||||
full := productionstats.Snapshot{
|
||||
Captures: []domain.CaptureRecord{{ID: "c", OrganizationID: "o", ProjectID: "p", Prefix: "source", RunID: "r"}},
|
||||
Runs: []domain.RunRecord{{ID: "r", OrganizationID: "o", ProjectID: "p", TaskID: "c"}},
|
||||
Items: []domain.HumanItemRecord{{ID: "i", OrganizationID: "o", ProjectID: "p", RunID: "r", LegacyTaskID: "t", CurrentStageID: "acceptance", Status: domain.HumanItemReady}},
|
||||
Tasks: []domain.AnnotationTaskRecord{{ID: "t", OrganizationID: "o", ProjectID: "p", RunID: "r"}},
|
||||
}
|
||||
full.Events = []domain.HumanEventRecord{
|
||||
{ID: "approve", OrganizationID: "o", ItemID: "i", StageID: "acceptance", EventType: "approved", CreatedAt: "2026-11-03T01:00:00Z"},
|
||||
{ID: "reject", OrganizationID: "o", ItemID: "i", StageID: "acceptance", EventType: "rejected", CreatedAt: "2026-11-03T02:00:00Z"},
|
||||
// Legacy package linkage can live on a non-decision event; retain it.
|
||||
{ID: "link", OrganizationID: "o", ItemID: "i", EventType: "created", Payload: map[string]any{"deliveryPackageId": "pkg"}},
|
||||
}
|
||||
for i := 0; i < 2000; i++ {
|
||||
full.Events = append(full.Events, domain.HumanEventRecord{ID: fmt.Sprint("edit-", i), OrganizationID: "o", ItemID: "i", EventType: "annotation_description_confirmed"})
|
||||
}
|
||||
for col, rows := range map[string][]any{"captureRecords": {full.Captures[0]}, "runs": {full.Runs[0]}, "humanItems": {full.Items[0]}, "annotationTasks": {full.Tasks[0]}} {
|
||||
if _, err = db.Collection(col).InsertMany(ctx, rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rows := make([]any, len(full.Events))
|
||||
for i, e := range full.Events {
|
||||
rows[i] = e
|
||||
}
|
||||
if _, err = db.Collection("humanEvents").InsertMany(ctx, rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Another tenant's matching ID must never enter the report.
|
||||
if _, err = db.Collection("humanEvents").InsertOne(ctx, bson.M{"id": "foreign", "organizationId": "other", "itemId": "i", "eventType": "approved"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := NewMongoStore(db).LoadProductionStats(ctx, "o", []string{"p"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Events) != 3 {
|
||||
t.Fatalf("irrelevant editing history loaded: got %d events, want 3", len(got.Events))
|
||||
}
|
||||
cachedStore := NewMongoStore(db)
|
||||
first, err := cachedStore.LoadProductionStatsCached(ctx, "o", []string{"p"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first.Events[0].ID = "caller-mutated"
|
||||
beforeHit := finds.Load()
|
||||
second, err := cachedStore.LoadProductionStatsCached(ctx, "o", []string{"p"})
|
||||
if err != nil || len(second.Events) != 3 {
|
||||
t.Fatalf("cached snapshot: count=%d err=%v", len(second.Events), err)
|
||||
}
|
||||
if first.AsOf == "" || second.AsOf != first.AsOf {
|
||||
t.Fatal("cached facts lost their observation time")
|
||||
}
|
||||
if finds.Load() != beforeHit {
|
||||
t.Fatal("warm production snapshot repeated Mongo reads")
|
||||
}
|
||||
t.Logf("same fixture: editing history reads 2003 -> %d; warm snapshot additional finds=%d", len(got.Events), finds.Load()-beforeHit)
|
||||
for _, e := range second.Events {
|
||||
if e.ID == "caller-mutated" {
|
||||
t.Fatal("caller mutated shared cached facts")
|
||||
}
|
||||
}
|
||||
otherDB := client.Database(db.Name() + "_other")
|
||||
defer otherDB.Drop(context.Background())
|
||||
isolated, err := NewMongoStore(otherDB).LoadProductionStatsCached(ctx, "o", []string{"p"})
|
||||
if err != nil || len(isolated.Captures) != 0 || len(isolated.Events) != 0 {
|
||||
t.Fatalf("cache crossed database boundary: %+v err=%v", isolated, err)
|
||||
}
|
||||
wantReport, gotReport := productionstats.Build(full), productionstats.Build(got)
|
||||
sort.Slice(wantReport.Events, func(i, j int) bool { return wantReport.Events[i].ID < wantReport.Events[j].ID })
|
||||
sort.Slice(gotReport.Events, func(i, j int) bool { return gotReport.Events[i].ID < gotReport.Events[j].ID })
|
||||
if !reflect.DeepEqual(wantReport, gotReport) {
|
||||
t.Fatalf("projected read changed milestones\nwant=%+v\ngot=%+v", wantReport, gotReport)
|
||||
}
|
||||
}
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@ -64,7 +65,7 @@ func (s *MongoStore) SaveProductionStatsScope(ctx context.Context, org string, n
|
||||
func (s *MemoryStore) LoadProductionStats(ctx context.Context, org string, projects []string) (productionstats.Snapshot, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
d := productionstats.Snapshot{}
|
||||
d := productionstats.Snapshot{AsOf: time.Now().UTC().Format(time.RFC3339Nano)}
|
||||
allowed := map[string]bool{}
|
||||
for _, id := range projects {
|
||||
allowed[id] = true
|
||||
@ -122,15 +123,15 @@ func (s *MemoryStore) LoadProductionStats(ctx context.Context, org string, proje
|
||||
func (s *MongoStore) LoadProductionStatsCached(ctx context.Context, org string, projects []string) (productionstats.Snapshot, error) {
|
||||
keyProjects := append([]string(nil), projects...)
|
||||
sort.Strings(keyProjects)
|
||||
key := org + "|" + strings.Join(keyProjects, ",")
|
||||
key := fmt.Sprintf("%p|%s|%s|%s", s.db.Client(), s.db.Name(), org, strings.Join(keyProjects, ","))
|
||||
if snapshot, ok := productionStatsCache.get(key, dashboardStatsCacheTTL); ok {
|
||||
return snapshot, nil
|
||||
return clone(snapshot), nil
|
||||
}
|
||||
snapshot, err := s.LoadProductionStats(ctx, org, projects)
|
||||
if err != nil {
|
||||
return snapshot, err
|
||||
}
|
||||
productionStatsCache.set(key, snapshot, dashboardStatsCacheTTL)
|
||||
productionStatsCache.set(key, clone(snapshot), dashboardStatsCacheTTL)
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
@ -157,7 +158,7 @@ func (s *MongoStore) LoadProductionStats(ctx context.Context, org string, projec
|
||||
}
|
||||
|
||||
func (s *MongoStore) loadProductionStats(ctx context.Context, org string, projects []string) (productionstats.Snapshot, error) {
|
||||
d := productionstats.Snapshot{}
|
||||
d := productionstats.Snapshot{AsOf: time.Now().UTC().Format(time.RFC3339Nano)}
|
||||
if len(projects) == 0 {
|
||||
return d, nil
|
||||
}
|
||||
@ -192,10 +193,13 @@ func (s *MongoStore) loadProductionStats(ctx context.Context, org string, projec
|
||||
}
|
||||
cursor, err := c.Find(ctx, f, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("production stats %s: %w", c.Name(), err)
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
return cursor.All(ctx, target)
|
||||
if err := cursor.All(ctx, target); err != nil {
|
||||
return fmt.Errorf("production stats %s: %w", c.Name(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
fields := func(names ...string) bson.M {
|
||||
m := bson.M{"_id": 0}
|
||||
@ -241,7 +245,12 @@ func (s *MongoStore) loadProductionStats(ctx context.Context, org string, projec
|
||||
ids = append(ids, item.ID)
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
if err := read(s.humanEvents, organizationScopedFilter(org, bson.M{"itemId": bson.M{"$in": ids}}), fields("id", "itemId", "stageId", "eventType", "createdAt", "payload.sourceItemIds", "payload.deliveryPackageId"), &d.Events); err != nil {
|
||||
if err := read(s.humanEvents, organizationScopedFilter(org, bson.M{
|
||||
"itemId": bson.M{"$in": ids},
|
||||
// Decisions drive milestones. Historical package linkage may also
|
||||
// be recorded on created/reopened events, so keep those links.
|
||||
"$or": bson.A{bson.M{"eventType": bson.M{"$in": bson.A{"approved", "rejected"}}}, bson.M{"payload.deliveryPackageId": bson.M{"$exists": true}}},
|
||||
}), fields("id", "itemId", "stageId", "eventType", "createdAt", "payload.sourceItemIds", "payload.deliveryPackageId"), &d.Events); err != nil {
|
||||
return d, err
|
||||
}
|
||||
}
|
||||
|
||||
@ -214,7 +214,12 @@
|
||||
"^src/.*([Dd]ashboard|WorkforceStatistics|annotation-output)",
|
||||
"^internal/(api|store)/(production_(dashboard|stats)|annotation_output|workforce)",
|
||||
"^internal/(outputsnapshot|workforcestats)/",
|
||||
"^tests/browser/.*dashboard"
|
||||
"^tests/browser/.*dashboard",
|
||||
"^src/components/ProductionStatistics\\.tsx$",
|
||||
"^src/lib/production-quality-dates\\.js$",
|
||||
"^src/services/api/production-quality\\.ts$",
|
||||
"^tests/browser/production-quality-replica\\.mjs$",
|
||||
"^internal/store/production_event_projection_test\\.go$"
|
||||
],
|
||||
"frontend": [
|
||||
"tests/frontend/dashboard-presentation.test.mjs",
|
||||
@ -239,11 +244,47 @@
|
||||
"python3",
|
||||
"scripts/test_dashboard_stability.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"argv": [
|
||||
"go",
|
||||
"test",
|
||||
"./internal/store",
|
||||
"-run",
|
||||
"^TestProductionMongoReadSkipsEditingEventsWithoutChangingMilestones$|^TestProductionCaptureCoveringRead$",
|
||||
"-count=1",
|
||||
"-timeout=90s"
|
||||
],
|
||||
"env": {
|
||||
"SOURCE_ADMISSION_LOCAL_MONGO": "1"
|
||||
},
|
||||
"tests": true
|
||||
}
|
||||
],
|
||||
"warnings": [
|
||||
"统计/查询改动须额外记录同数据规模的性能对照;完整 120 人容量另行验收。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "production-statistics-model",
|
||||
"paths": [
|
||||
"^internal/productionstats/model\\.go$"
|
||||
],
|
||||
"frontend": [],
|
||||
"go": {},
|
||||
"task": [
|
||||
{
|
||||
"argv": [
|
||||
"npm",
|
||||
"run",
|
||||
"test:go:gate"
|
||||
],
|
||||
"tests": false
|
||||
}
|
||||
],
|
||||
"warnings": [
|
||||
"共享生产统计事实结构改动:使用既有 Go 基线门禁比较历史失败,不扩大失败基线。"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@ -10,7 +10,14 @@ import {
|
||||
type Quality,
|
||||
} from "../services/api/production-quality";
|
||||
import type { OutputMetric, OutputOption } from "../services/api/annotation-output";
|
||||
import { productionQualityDates } from "../lib/production-quality-dates.js";
|
||||
import {
|
||||
productionQualityDates,
|
||||
productionQualityDisplayDates,
|
||||
productionQualityRequestDates,
|
||||
productionSnapshotRefreshDelay,
|
||||
} from "../lib/production-quality-dates.js";
|
||||
import { formatCompactDateTime } from "../lib/datetime";
|
||||
import { WorkforceStatisticsPanel } from "./WorkforceStatisticsPanel";
|
||||
import { useUser } from "../context/UserContext";
|
||||
import "../styles/production-quality.css";
|
||||
const roles: Record<ProductionRole, string> = { annotation: "标注员", quality: "审核员", acceptance: "验收员" };
|
||||
@ -145,13 +152,14 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
? "acceptance"
|
||||
: "annotation";
|
||||
const defaults = (): ProductionQuery => ({
|
||||
...productionQualityDates(new Date(), timeZone),
|
||||
...productionQualityDisplayDates(productionQualityDates(new Date(), timeZone)),
|
||||
timeZone,
|
||||
projectId: "",
|
||||
supplierId: "",
|
||||
userId: "",
|
||||
role: defaultRole,
|
||||
});
|
||||
const [view, setView] = useState<"cohort" | "daily">("cohort");
|
||||
const [draft, setDraft] = useState(defaults),
|
||||
[query, setQuery] = useState(defaults);
|
||||
const [data, setData] = useState<ProductionReport | null>(null),
|
||||
@ -160,6 +168,7 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
const [refresh, setRefresh] = useState(0),
|
||||
[exporting, setExporting] = useState(false);
|
||||
const seq = useRef(0);
|
||||
const loadedQuery = useRef("");
|
||||
const personSection = useRef<HTMLElement>(null);
|
||||
useEffect(() => {
|
||||
setDraft(defaults());
|
||||
@ -167,14 +176,21 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
setData(null);
|
||||
}, [timeZone, currentUser?.id, currentUser?.role]);
|
||||
useEffect(() => {
|
||||
if (view !== "cohort") {
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController(),
|
||||
id = ++seq.current;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setData(null);
|
||||
getProductionQuality(query, controller.signal)
|
||||
if (loadedQuery.current !== JSON.stringify(query)) setData(null);
|
||||
getProductionQuality({ ...query, ...productionQualityRequestDates(query) }, controller.signal)
|
||||
.then((result) => {
|
||||
if (id === seq.current) setData(result);
|
||||
if (id === seq.current) {
|
||||
loadedQuery.current = JSON.stringify(query);
|
||||
setData(result);
|
||||
}
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (controller.signal.aborted || id !== seq.current) return;
|
||||
@ -182,6 +198,7 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
setQuery((q) => ({ ...q, snapshotId: undefined, peoplePage: 1, suppliersPage: 1 }));
|
||||
return;
|
||||
}
|
||||
setData(null);
|
||||
setError(cause instanceof Error ? cause.message : "加载失败,请重试");
|
||||
})
|
||||
.finally(() => {
|
||||
@ -191,9 +208,21 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
seq.current++;
|
||||
controller.abort();
|
||||
};
|
||||
}, [JSON.stringify(query), refresh]);
|
||||
}, [JSON.stringify(query), refresh, view]);
|
||||
useEffect(() => {
|
||||
if (view !== "cohort" || busy || !data) return;
|
||||
const delay = productionSnapshotRefreshDelay(data.snapshot);
|
||||
if (delay == null) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
// Pagination/export pin one generation; a refresh starts a new one.
|
||||
setQuery((q) => ({ ...q, snapshotId: undefined, peoplePage: 1, suppliersPage: 1 }));
|
||||
setRefresh((n) => n + 1);
|
||||
}, delay);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [busy, data, view]);
|
||||
const apply = () => {
|
||||
if (!draft.from || !draft.to || draft.from >= draft.to) {
|
||||
if (!draft.from || !draft.to || draft.from > draft.to) {
|
||||
setData(null);
|
||||
setError("请选择有效日期范围");
|
||||
return;
|
||||
}
|
||||
@ -216,7 +245,11 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
if (exporting || !data) return;
|
||||
setExporting(true);
|
||||
try {
|
||||
const blob = await exportProductionQuality({ ...query, snapshotId: data.snapshot.id });
|
||||
const blob = await exportProductionQuality({
|
||||
...query,
|
||||
...productionQualityRequestDates(query),
|
||||
snapshotId: data.snapshot.id,
|
||||
});
|
||||
const url = URL.createObjectURL(blob),
|
||||
a = document.createElement("a");
|
||||
a.href = url;
|
||||
@ -244,7 +277,7 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
return (
|
||||
<section className="pq-dashboard" aria-label="生产与质量看板">
|
||||
<header>
|
||||
<h1>{personal ? "我的工作记录" : "生产与质量总览"}</h1>
|
||||
<h1>{view === "daily" ? "每日作业记录" : personal ? "我的批次质量" : "生产与批次质量总览"}</h1>
|
||||
<button
|
||||
aria-label="刷新"
|
||||
disabled={busy}
|
||||
@ -256,6 +289,38 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
<RefreshCw size={16} />
|
||||
</button>
|
||||
</header>
|
||||
<div className="pq-tabs" role="group" aria-label="统计口径">
|
||||
<button
|
||||
aria-pressed={view === "cohort"}
|
||||
onClick={() => {
|
||||
setView("cohort");
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
批次质量
|
||||
</button>
|
||||
<button
|
||||
aria-pressed={view === "daily"}
|
||||
onClick={() => {
|
||||
const today = productionQualityDates(new Date(), timeZone).to;
|
||||
const next = {
|
||||
...query,
|
||||
from: today,
|
||||
to: today,
|
||||
projectId: "",
|
||||
supplierId: "",
|
||||
userId: "",
|
||||
snapshotId: undefined,
|
||||
};
|
||||
setDraft(next);
|
||||
setQuery(next);
|
||||
setView("daily");
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
每日作业
|
||||
</button>
|
||||
</div>
|
||||
<form
|
||||
className="pq-filter"
|
||||
onSubmit={(e) => {
|
||||
@ -264,7 +329,7 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
日期范围
|
||||
{view === "cohort" ? "首次送检日期" : "作业日期"}
|
||||
<div className="pq-date">
|
||||
<input
|
||||
aria-label="开始日期"
|
||||
@ -281,13 +346,15 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
<Select
|
||||
label="项目"
|
||||
value={draft.projectId}
|
||||
items={data?.projects || []}
|
||||
onChange={(projectId) => setDraft({ ...draft, projectId, supplierId: "", userId: "" })}
|
||||
/>
|
||||
{!personal && (
|
||||
{view === "cohort" && (
|
||||
<Select
|
||||
label="项目"
|
||||
value={draft.projectId}
|
||||
items={data?.projects || []}
|
||||
onChange={(projectId) => setDraft({ ...draft, projectId, supplierId: "", userId: "" })}
|
||||
/>
|
||||
)}
|
||||
{!personal && view === "cohort" && (
|
||||
<>
|
||||
<Select
|
||||
label="供应商"
|
||||
@ -306,187 +373,217 @@ export function ProductionQualityDashboard({ timeZone }: { timeZone: string; key
|
||||
<button className="pq-primary" disabled={busy}>
|
||||
查询
|
||||
</button>
|
||||
<button type="button" disabled={busy || exporting || !data} onClick={() => void download()}>
|
||||
<Download size={15} />
|
||||
导出
|
||||
</button>
|
||||
{view === "cohort" && (
|
||||
<button type="button" disabled={busy || exporting || !data} onClick={() => void download()}>
|
||||
<Download size={15} />
|
||||
导出
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
{error && (
|
||||
<p role="alert" className="pq-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{busy && (
|
||||
<div role="status" className="pq-loading">
|
||||
加载中…
|
||||
{view === "daily" && !error && (
|
||||
<div key={`${JSON.stringify(query)}:${refresh}`}>
|
||||
<WorkforceStatisticsPanel
|
||||
items={[]}
|
||||
filters={{
|
||||
from: query.from,
|
||||
to: query.to,
|
||||
projectId: query.projectId,
|
||||
supplierId: query.supplierId,
|
||||
userId: query.userId,
|
||||
}}
|
||||
self={personal}
|
||||
vendor={currentUser?.role === "supplier_manager"}
|
||||
collapsedByDefault={false}
|
||||
deferLoad
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className={`pq-cards${personal && defaultRole !== "annotation" ? " pq-cards-review" : ""}`}>
|
||||
{[
|
||||
[personal && defaultRole !== "annotation" ? "审查视频时长" : "提交视频时长", totals?.submitted],
|
||||
["质检通过时长", totals?.quality],
|
||||
["最终验收通过时长", totals?.acceptance],
|
||||
["可交付时长", data?.deliverable],
|
||||
["返工中时长", totals?.rework],
|
||||
]
|
||||
.filter(
|
||||
([label]) =>
|
||||
!personal || defaultRole === "annotation" || !["质检通过时长", "可交付时长"].includes(String(label)),
|
||||
)
|
||||
.map(([label, value]) => (
|
||||
<div key={String(label)}>
|
||||
<span>{String(label)}</span>
|
||||
<strong>
|
||||
{hour(value as OutputMetric | undefined)}
|
||||
<small> 小时</small>
|
||||
</strong>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{!personal && (
|
||||
{view === "cohort" && (
|
||||
<>
|
||||
<section className="pq-panel">
|
||||
<h2>供应商总体产出</h2>
|
||||
{data && (
|
||||
<p className="text-xs text-slate-500">
|
||||
更新于 {formatCompactDateTime(data.snapshot.asOf, timeZone)}
|
||||
{(data.snapshot.stale || data.snapshot.refreshing) && " · 正在更新"}
|
||||
</p>
|
||||
)}
|
||||
{busy && (
|
||||
<div role="status" className="pq-loading">
|
||||
加载中…
|
||||
</div>
|
||||
)}
|
||||
<div className={`pq-cards${personal && defaultRole !== "annotation" ? " pq-cards-review" : ""}`}>
|
||||
{[
|
||||
[personal && defaultRole !== "annotation" ? "审查视频时长" : "提交视频时长", totals?.submitted],
|
||||
["质检通过时长", totals?.quality],
|
||||
["最终验收通过时长", totals?.acceptance],
|
||||
["可交付时长", data?.deliverable],
|
||||
["返工中时长", totals?.rework],
|
||||
]
|
||||
.filter(
|
||||
([label]) =>
|
||||
!personal || defaultRole === "annotation" || !["质检通过时长", "可交付时长"].includes(String(label)),
|
||||
)
|
||||
.map(([label, value]) => (
|
||||
<div key={String(label)}>
|
||||
<span>{String(label)}</span>
|
||||
<strong>
|
||||
{hour(value as OutputMetric | undefined)}
|
||||
<small> 小时</small>
|
||||
</strong>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{!personal && (
|
||||
<>
|
||||
<section className="pq-panel">
|
||||
<h2>供应商总体产出</h2>
|
||||
<div className="pq-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>供应商</th>
|
||||
<th>标注人数</th>
|
||||
<th>审核人数</th>
|
||||
<th>验收人数</th>
|
||||
<th>提交时长</th>
|
||||
<th>质检通过时长</th>
|
||||
<th>最终验收通过时长</th>
|
||||
<th>返工中时长</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.suppliers.items.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.name || "—"}</td>
|
||||
<td>{s.members.annotation || 0}</td>
|
||||
<td>{s.members.quality || 0}</td>
|
||||
<td>{s.members.acceptance || 0}</td>
|
||||
<td>{hours(s.totals.submitted)}</td>
|
||||
<td>{hours(s.totals.quality)}</td>
|
||||
<td>{hours(s.totals.acceptance)}</td>
|
||||
<td>{hours(s.totals.rework)}</td>
|
||||
<td>
|
||||
<button className="pq-link" onClick={() => viewPeople(s.id)}>
|
||||
查看人员
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{data && (
|
||||
<Paging
|
||||
page={data.suppliers.page}
|
||||
total={data.suppliers.total}
|
||||
size={data.suppliers.pageSize}
|
||||
onChange={(n) => page("suppliersPage", n)}
|
||||
busy={busy}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<section className="pq-panel">
|
||||
<h2>供应商质量统计</h2>
|
||||
<div className="pq-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>供应商</th>
|
||||
<th>角色</th>
|
||||
<QualityHead />
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.suppliers.items.flatMap((s) =>
|
||||
(Object.keys(roles) as ProductionRole[]).map((role) => (
|
||||
<tr key={`${s.id}:${role}`}>
|
||||
<td>{s.name || "—"}</td>
|
||||
<td>{roles[role]}</td>
|
||||
<QualityCells row={s.quality?.find((q) => q.role === role)} />
|
||||
<td>
|
||||
<button className="pq-link" onClick={() => viewPeople(s.id)}>
|
||||
查看人员
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)),
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
<section className="pq-panel" ref={personSection}>
|
||||
<div className="pq-section-heading">
|
||||
<h2>{personal ? "产出统计" : "人员产出统计"}</h2>
|
||||
{roleTabs}
|
||||
</div>
|
||||
<div className="pq-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>供应商</th>
|
||||
<th>标注人数</th>
|
||||
<th>审核人数</th>
|
||||
<th>验收人数</th>
|
||||
<th>提交时长</th>
|
||||
<th>质检通过时长</th>
|
||||
<th>人员</th>
|
||||
<th>{query.role === "annotation" ? "提交时长" : "审查时长"}</th>
|
||||
<th>最终验收通过时长</th>
|
||||
<th>返工中时长</th>
|
||||
<th></th>
|
||||
{query.role === "annotation" && <th>可交付时长</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.suppliers.items.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.name || "—"}</td>
|
||||
<td>{s.members.annotation || 0}</td>
|
||||
<td>{s.members.quality || 0}</td>
|
||||
<td>{s.members.acceptance || 0}</td>
|
||||
<td>{hours(s.totals.submitted)}</td>
|
||||
<td>{hours(s.totals.quality)}</td>
|
||||
<td>{hours(s.totals.acceptance)}</td>
|
||||
<td>{hours(s.totals.rework)}</td>
|
||||
<td>
|
||||
<button className="pq-link" onClick={() => viewPeople(s.id)}>
|
||||
查看人员
|
||||
</button>
|
||||
</td>
|
||||
{data?.people.items.map((p) => (
|
||||
<tr key={`${p.supplierId}:${p.id}`}>
|
||||
<td>{p.name || "—"}</td>
|
||||
<td>{hours(p.totals.submitted)}</td>
|
||||
<td>{hours(p.totals.acceptance)}</td>
|
||||
<td>{hours(p.totals.rework)}</td>
|
||||
{query.role === "annotation" && <td>{hours(p.deliverable)}</td>}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{data && data.people.total === 0 && <div className="pq-empty">暂无数据</div>}
|
||||
{data && (
|
||||
<Paging
|
||||
page={data.suppliers.page}
|
||||
total={data.suppliers.total}
|
||||
size={data.suppliers.pageSize}
|
||||
onChange={(n) => page("suppliersPage", n)}
|
||||
page={data.people.page}
|
||||
total={data.people.total}
|
||||
size={data.people.pageSize}
|
||||
onChange={(n) => page("peoplePage", n)}
|
||||
busy={busy}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<section className="pq-panel">
|
||||
<h2>供应商质量统计</h2>
|
||||
<h2>{personal ? "质量统计" : "人员质量统计"}</h2>
|
||||
<div className="pq-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>供应商</th>
|
||||
<th>角色</th>
|
||||
<th>人员</th>
|
||||
<QualityHead />
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.suppliers.items.flatMap((s) =>
|
||||
(Object.keys(roles) as ProductionRole[]).map((role) => (
|
||||
<tr key={`${s.id}:${role}`}>
|
||||
<td>{s.name || "—"}</td>
|
||||
<td>{roles[role]}</td>
|
||||
<QualityCells row={s.quality?.find((q) => q.role === role)} />
|
||||
<td>
|
||||
<button className="pq-link" onClick={() => viewPeople(s.id)}>
|
||||
查看人员
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)),
|
||||
)}
|
||||
{data?.people.items.map((p) => (
|
||||
<tr key={`${p.supplierId}:${p.id}`}>
|
||||
<td>{p.name || "—"}</td>
|
||||
<QualityCells row={p.quality} />
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
<section className="pq-panel" ref={personSection}>
|
||||
<div className="pq-section-heading">
|
||||
<h2>{personal ? "产出统计" : "人员产出统计"}</h2>
|
||||
{roleTabs}
|
||||
</div>
|
||||
<div className="pq-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>人员</th>
|
||||
<th>{query.role === "annotation" ? "提交时长" : "审查时长"}</th>
|
||||
<th>最终验收通过时长</th>
|
||||
<th>返工中时长</th>
|
||||
{query.role === "annotation" && <th>可交付时长</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.people.items.map((p) => (
|
||||
<tr key={`${p.supplierId}:${p.id}`}>
|
||||
<td>{p.name || "—"}</td>
|
||||
<td>{hours(p.totals.submitted)}</td>
|
||||
<td>{hours(p.totals.acceptance)}</td>
|
||||
<td>{hours(p.totals.rework)}</td>
|
||||
{query.role === "annotation" && <td>{hours(p.deliverable)}</td>}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{data && data.people.total === 0 && <div className="pq-empty">暂无数据</div>}
|
||||
{data && (
|
||||
<Paging
|
||||
page={data.people.page}
|
||||
total={data.people.total}
|
||||
size={data.people.pageSize}
|
||||
onChange={(n) => page("peoplePage", n)}
|
||||
busy={busy}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<section className="pq-panel">
|
||||
<h2>{personal ? "质量统计" : "人员质量统计"}</h2>
|
||||
<div className="pq-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>人员</th>
|
||||
<QualityHead />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.people.items.map((p) => (
|
||||
<tr key={`${p.supplierId}:${p.id}`}>
|
||||
<td>{p.name || "—"}</td>
|
||||
<QualityCells row={p.quality} />
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,6 +2,8 @@ import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { productionDashboardApi, type ProductionResult } from "../services/api/production-dashboard";
|
||||
import { getActionErrorMessage } from "../lib/action-errors.js";
|
||||
import { useTimeZone } from "../context/TimeZoneContext";
|
||||
import { formatCompactDateTime } from "../lib/datetime";
|
||||
import { defaultProductionFilters, type ProductionFilters } from "../lib/production-filters";
|
||||
|
||||
const control = "rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-3 py-2 text-sm";
|
||||
@ -31,6 +33,7 @@ export function ProductionStatistics({
|
||||
filters: ProductionFilters;
|
||||
onFiltersChange: (next: ProductionFilters) => void;
|
||||
}) {
|
||||
const { timeZone } = useTimeZone();
|
||||
const [view, setView] = useState<"current" | "period">("current");
|
||||
const [group, setGroup] = useState<"project" | "supplier">("project");
|
||||
const [result, setResult] = useState<ProductionResult | null>(null);
|
||||
@ -57,6 +60,8 @@ export function ProductionStatistics({
|
||||
useEffect(() => {
|
||||
const seq = ++sequence.current;
|
||||
setLoading(true);
|
||||
setResult(null);
|
||||
setError("");
|
||||
productionDashboardApi
|
||||
.get(params)
|
||||
.then((loaded) => {
|
||||
@ -210,11 +215,13 @@ export function ProductionStatistics({
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{result && <p className="text-xs text-gray-500">更新于 {formatCompactDateTime(result.asOf, timeZone)}</p>}
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
{pipelineMetrics.map((metric) => (
|
||||
<button
|
||||
key={metric}
|
||||
type="button"
|
||||
disabled={!result || loading}
|
||||
onClick={() => {
|
||||
setDrawer({ metric });
|
||||
setPage(1);
|
||||
@ -222,7 +229,7 @@ export function ProductionStatistics({
|
||||
className="rounded-xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)] p-4 text-left hover:border-orange-400"
|
||||
>
|
||||
<div className="text-sm text-gray-500">{stageLabels[metric]}</div>
|
||||
<div className="mt-2 text-3xl font-semibold">{pipeline[metric] || 0}</div>
|
||||
<div className="mt-2 text-3xl font-semibold">{result ? pipeline[metric] || 0 : "—"}</div>
|
||||
<div className="mt-1 text-xs text-gray-500">{view === "current" ? "当前处于此阶段" : "期间完成"}</div>
|
||||
</button>
|
||||
))}
|
||||
|
||||
@ -8,6 +8,7 @@ import { stripTaskOpinionLines } from "../lib/task-scope-visibility.js";
|
||||
import { useUser } from "../context/UserContext";
|
||||
|
||||
export type WorkforceFilters = {
|
||||
userId?: string;
|
||||
projectId?: string;
|
||||
supplierId?: string;
|
||||
from?: string;
|
||||
@ -19,6 +20,10 @@ 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 firstVideoDuration = (member?: Member) =>
|
||||
duration(member?.unknownVideoCount && !member.firstVideoSeconds ? undefined : member?.firstVideoSeconds);
|
||||
const reviewVideoDuration = (member?: Member) =>
|
||||
duration(member?.unknownReviewVideoCount && !member.reviewVideoSeconds ? undefined : member?.reviewVideoSeconds);
|
||||
const rate = (value?: number | null) => (value == null ? "暂无数据" : `${value.toFixed(1)}%`);
|
||||
const roleLabel = (role?: string) =>
|
||||
role === "annotator"
|
||||
@ -154,6 +159,7 @@ function DailyDetails({ query }: { query: WorkforceReportQuery }) {
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setItems(null);
|
||||
setError("");
|
||||
workforceApi
|
||||
.report(JSON.parse(identity))
|
||||
.then((result) => {
|
||||
@ -173,7 +179,7 @@ function DailyDetails({ query }: { query: WorkforceReportQuery }) {
|
||||
<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(
|
||||
{["日期", "首交任务数", "质检通过率", "终审通过率", "返工", "视频时长", "审查产出", "审查视频时长"].map(
|
||||
(label) => (
|
||||
<th key={label} className="px-3 py-2 font-normal">
|
||||
{label}
|
||||
@ -186,13 +192,13 @@ function DailyDetails({ query }: { query: WorkforceReportQuery }) {
|
||||
{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">{count(item.firstSubmittedTasks ?? item.outputCount)}</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">{firstVideoDuration(item)}</td>
|
||||
<td className="px-3 py-2">{count(item.reviewDecisionCount)}</td>
|
||||
<td className="px-3 py-2">{duration(item.reviewVideoSeconds)}</td>
|
||||
<td className="px-3 py-2">{reviewVideoDuration(item)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@ -253,6 +259,8 @@ export function WorkforceStatisticsPanel({
|
||||
if (collapsed || !deferLoad) return;
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
setRemoteItems(null);
|
||||
setRemoteTotals(undefined);
|
||||
setError("");
|
||||
workforceApi
|
||||
.report({ ...apiFilters, role, groupBy: "member" })
|
||||
@ -271,8 +279,8 @@ export function WorkforceStatisticsPanel({
|
||||
active = false;
|
||||
};
|
||||
}, [collapsed, deferLoad, role, filterKey]);
|
||||
const visibleItems = remoteItems || items;
|
||||
const visibleTotals = remoteTotals || totals;
|
||||
const visibleItems = deferLoad ? remoteItems || [] : items;
|
||||
const visibleTotals = deferLoad ? remoteTotals : totals;
|
||||
const filtered = visibleItems.filter((member) => {
|
||||
if (role && member.role !== role) return false;
|
||||
return `${member.userName || ""} ${member.userId || ""} ${member.supplierName || ""} ${member.supplierId || ""}`
|
||||
@ -284,12 +292,12 @@ export function WorkforceStatisticsPanel({
|
||||
const cards = [
|
||||
reviewerSelf
|
||||
? ["审查产出", count(visibleTotals?.reviewDecisionCount)]
|
||||
: ["产出", count(visibleTotals?.outputCount ?? visibleTotals?.firstSubmittedTasks)],
|
||||
: ["首交任务数", count(visibleTotals?.firstSubmittedTasks ?? visibleTotals?.outputCount)],
|
||||
["质量通过率", rate(visibleTotals?.qualityPassRate)],
|
||||
["返工次数", count(visibleTotals?.reworkSubmissionCount)],
|
||||
reviewerSelf
|
||||
? ["审查视频时长", duration(visibleTotals?.reviewVideoSeconds)]
|
||||
: ["视频时长", duration(visibleTotals?.firstVideoSeconds)],
|
||||
? ["审查视频时长", reviewVideoDuration(visibleTotals)]
|
||||
: ["视频时长", firstVideoDuration(visibleTotals)],
|
||||
].map(([label, value]) => [label, pending ? "加载中…" : value]);
|
||||
const title = self ? "我的工作记录" : vendor ? "供应商团队工作记录" : "工作记录";
|
||||
return (
|
||||
@ -299,8 +307,8 @@ export function WorkforceStatisticsPanel({
|
||||
<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)}
|
||||
{formatCompactDateTime(from || apiFilters.from, timeZone)} 至{" "}
|
||||
{formatCompactDateTime(to || apiFilters.to, timeZone)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@ -319,7 +327,13 @@ export function WorkforceStatisticsPanel({
|
||||
<div
|
||||
key={label}
|
||||
aria-label={
|
||||
label === "视频时长" ? "首交视频时长" : label === "审查视频时长" ? "审查视频时长" : undefined
|
||||
label === "视频时长"
|
||||
? "首交视频时长"
|
||||
: label === "审查视频时长"
|
||||
? "审查视频时长"
|
||||
: label === "首交任务数"
|
||||
? "首交任务数"
|
||||
: undefined
|
||||
}
|
||||
className="rounded-xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)] p-4"
|
||||
>
|
||||
@ -328,7 +342,12 @@ export function WorkforceStatisticsPanel({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{reviewerSelf && !pending && (visibleTotals?.unknownReviewVideoCount ?? 0) > 0 && (
|
||||
{!reviewerSelf && !pending && (visibleTotals?.unknownVideoCount ?? 0) > 0 && (
|
||||
<p className="text-xs text-amber-700 dark:text-amber-300">
|
||||
另有 {visibleTotals?.unknownVideoCount} 条提交缺少可靠视频时长,未计入时长。
|
||||
</p>
|
||||
)}
|
||||
{!pending && (visibleTotals?.unknownReviewVideoCount ?? 0) > 0 && (
|
||||
<p className="text-xs text-amber-700 dark:text-amber-300">
|
||||
另有 {visibleTotals?.unknownReviewVideoCount} 次审查决定缺少可靠的切片版本,待核对,未计入审查视频时长。
|
||||
</p>
|
||||
@ -373,7 +392,7 @@ export function WorkforceStatisticsPanel({
|
||||
"成员",
|
||||
"供应商",
|
||||
"角色",
|
||||
"产出",
|
||||
"首交任务数",
|
||||
"质量通过率",
|
||||
"返工",
|
||||
"视频时长",
|
||||
@ -409,12 +428,12 @@ export function WorkforceStatisticsPanel({
|
||||
{member.supplierName || (member.supplierId ? "历史供应商(名称待核对)" : "未分配供应商")}
|
||||
</td>
|
||||
<td>{roleLabel(member.role)}</td>
|
||||
<td>{count(member.outputCount ?? member.firstSubmittedTasks)}</td>
|
||||
<td>{count(member.firstSubmittedTasks ?? member.outputCount)}</td>
|
||||
<td>{rate(member.qualityPassRate)}</td>
|
||||
<td>{count(member.reworkSubmissionCount)}</td>
|
||||
<td>{duration(member.firstVideoSeconds)}</td>
|
||||
<td>{firstVideoDuration(member)}</td>
|
||||
<td>{count(member.reviewDecisionCount)}</td>
|
||||
<td>{duration(member.reviewVideoSeconds)}</td>
|
||||
<td>{reviewVideoDuration(member)}</td>
|
||||
<td>
|
||||
<button
|
||||
aria-expanded={isOpen}
|
||||
|
||||
@ -94,6 +94,7 @@ export function useAnnotationOutputData(audience: "self" | "vendor" | "platform"
|
||||
}));
|
||||
const apply = (next: OutputFilters) => {
|
||||
if (!next.from || !next.to || next.from > next.to) {
|
||||
setResult(null);
|
||||
setError("请选择有效日期范围");
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -17,3 +17,24 @@ export function productionQualityDates(now, timeZone) {
|
||||
to: format(year, month, day),
|
||||
};
|
||||
}
|
||||
|
||||
// Calendar inputs include both dates; the existing API retains [from, to).
|
||||
export function productionQualityRequestDates({ from, to }) {
|
||||
return { from, to: shiftCalendarDate(to, 1) };
|
||||
}
|
||||
export function productionQualityDisplayDates({ from, to }) {
|
||||
return { from, to: shiftCalendarDate(to, -1) };
|
||||
}
|
||||
function shiftCalendarDate(value, days) {
|
||||
const date = new Date(`${value}T00:00:00Z`);
|
||||
if (!Number.isFinite(date.getTime())) throw new Error("请选择有效日期范围");
|
||||
date.setUTCDate(date.getUTCDate() + days);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function productionSnapshotRefreshDelay(snapshot, now = Date.now()) {
|
||||
if (!snapshot) return null;
|
||||
if (snapshot.stale || snapshot.refreshing) return 5000;
|
||||
const at = Date.parse(snapshot.asOf);
|
||||
return Number.isFinite(at) ? Math.max(1000, at + 120000 - now) : 120000;
|
||||
}
|
||||
|
||||
@ -49,7 +49,7 @@ export type ProductionQuery = {
|
||||
snapshotId?: string;
|
||||
};
|
||||
export type ProductionReport = {
|
||||
snapshot: { id: string; stale: boolean; asOf: string };
|
||||
snapshot: { id: string; stale: boolean; asOf: string; refreshing?: boolean };
|
||||
audienceScope: "platform" | "vendor" | "self";
|
||||
from: string;
|
||||
to: string;
|
||||
|
||||
@ -84,7 +84,126 @@ try {
|
||||
const download = page.waitForEvent("download");
|
||||
await panel.getByRole("button", { name: "导出", exact: true }).click();
|
||||
await (await download).saveAs(path.join(out, id + ".csv"));
|
||||
// Calendar controls include the selected end day; API remains exclusive.
|
||||
const day = data.from;
|
||||
const nextDay = new Date(`${day}T00:00:00Z`);
|
||||
nextDay.setUTCDate(nextDay.getUTCDate() + 1);
|
||||
const end = nextDay.toISOString().slice(0, 10);
|
||||
await panel.getByLabel("开始日期", { exact: true }).fill(day);
|
||||
await panel.getByLabel("结束日期", { exact: true }).fill(day);
|
||||
const single = page.waitForResponse((r) => {
|
||||
const u = new URL(r.url());
|
||||
return (
|
||||
u.pathname === "/api/dashboard/production-quality" &&
|
||||
u.searchParams.get("from") === day &&
|
||||
u.searchParams.get("to") === end &&
|
||||
r.status() === 200
|
||||
);
|
||||
});
|
||||
await panel.getByRole("button", { name: "查询", exact: true }).click();
|
||||
await single;
|
||||
await page.waitForFunction(() => !document.querySelector('.pq-dashboard [role="status"]'));
|
||||
assert.equal(await panel.getByLabel("结束日期", { exact: true }).inputValue(), day);
|
||||
await panel.getByLabel("开始日期", { exact: true }).fill(end);
|
||||
await panel.getByRole("button", { name: "查询", exact: true }).click();
|
||||
await panel.getByRole("alert").filter({ hasText: "请选择有效日期范围" }).waitFor();
|
||||
assert.ok(
|
||||
(await panel.locator(".pq-cards strong").allTextContents()).every((t) => t.includes("—")),
|
||||
"invalid filter retained old numbers",
|
||||
);
|
||||
assert.equal(await panel.getByRole("button", { name: "导出", exact: true }).isDisabled(), true);
|
||||
await page.screenshot({ path: path.join(out, id + "-invalid-date.png"), fullPage: true });
|
||||
await panel.getByLabel("开始日期", { exact: true }).fill(day);
|
||||
const restored = page.waitForResponse(
|
||||
(r) => r.url().includes("/api/dashboard/production-quality?") && r.status() === 200,
|
||||
);
|
||||
await panel.getByRole("button", { name: "查询", exact: true }).click();
|
||||
await restored;
|
||||
await page.waitForFunction(() => !document.querySelector('.pq-dashboard [role="status"]'));
|
||||
if (id === "admin") {
|
||||
let reads = 0;
|
||||
await page.route("**/api/dashboard/production-quality?*", async (route) => {
|
||||
const response = await route.fetch();
|
||||
const body = await response.json();
|
||||
if (response.status() === 200) {
|
||||
reads++;
|
||||
body.snapshot = {
|
||||
...body.snapshot,
|
||||
asOf: reads === 1 ? "2020-01-01T00:00:00Z" : new Date().toISOString(),
|
||||
stale: reads === 1,
|
||||
refreshing: reads === 1,
|
||||
};
|
||||
}
|
||||
await route.fulfill({ response, json: body });
|
||||
});
|
||||
await panel.getByRole("button", { name: "刷新", exact: true }).click();
|
||||
await panel.getByText(/更新于.*正在更新/).waitFor();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector(".pq-dashboard")?.textContent.includes("正在更新") === false,
|
||||
{},
|
||||
{ timeout: 15000 },
|
||||
);
|
||||
assert.ok(reads >= 2, "stale snapshot was never rechecked");
|
||||
await page.unroute("**/api/dashboard/production-quality?*");
|
||||
}
|
||||
await page.screenshot({ path: path.join(out, id + ".png"), fullPage: true });
|
||||
const daily = page.waitForResponse((r) => r.url().includes("/api/dashboard/workforce?") && r.status() === 200);
|
||||
await panel.getByRole("button", { name: "每日作业", exact: true }).click();
|
||||
await daily;
|
||||
await panel.getByRole("heading", { name: "每日作业记录", exact: true }).waitFor();
|
||||
assert.equal(await panel.locator(".pq-cards").count(), 0, "cohort results leaked into daily view");
|
||||
await page.screenshot({ path: path.join(out, id + "-daily-empty.png"), fullPage: true });
|
||||
await panel.getByLabel("开始日期", { exact: true }).fill(data.from);
|
||||
await panel.getByLabel("结束日期", { exact: true }).fill(data.to);
|
||||
const dailyRange = page.waitForResponse(
|
||||
(r) => r.url().includes("/api/dashboard/workforce?") && r.status() === 200,
|
||||
);
|
||||
await panel.getByRole("button", { name: "查询", exact: true }).click();
|
||||
const dailyData = await (await dailyRange).json();
|
||||
if (["admin", "manager", "u1"].includes(id))
|
||||
assert.ok(
|
||||
(dailyData.totals.outputCount || dailyData.totals.firstSubmittedTasks) > 0,
|
||||
"daily work lost real submissions",
|
||||
);
|
||||
if (["admin", "manager", "u1"].includes(id)) {
|
||||
const expected = String(dailyData.totals.firstSubmittedTasks ?? dailyData.totals.outputCount);
|
||||
await page.waitForFunction(
|
||||
({ expected }) =>
|
||||
document.querySelector('[aria-label="首交任务数"]')?.textContent?.trim() === `首交任务数${expected}`,
|
||||
{ expected },
|
||||
);
|
||||
}
|
||||
await page.screenshot({ path: path.join(out, id + "-daily.png"), fullPage: true });
|
||||
|
||||
if (id === "admin") {
|
||||
await page.getByText("生产进度与运行概览", { exact: true }).click();
|
||||
const overview = page.getByRole("region", { name: "生产总览", exact: true });
|
||||
await overview.getByRole("button", { name: "刷新", exact: true }).waitFor();
|
||||
await page.waitForFunction(() =>
|
||||
document.querySelector('[aria-label="生产总览"]')?.textContent?.includes("更新于"),
|
||||
);
|
||||
await page.screenshot({ path: path.join(out, "production-overview.png"), fullPage: true });
|
||||
await page.route("**/api/dashboard/production?*", (route) =>
|
||||
route.fulfill({
|
||||
status: 503,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ error: "生产总览暂时无法加载" }),
|
||||
}),
|
||||
);
|
||||
await overview.getByRole("button", { name: "刷新", exact: true }).click();
|
||||
await overview.getByRole("alert").waitFor();
|
||||
assert.ok(
|
||||
(await overview.locator(".grid>button .text-3xl").allTextContents()).every((t) => t === "—"),
|
||||
"failed production request retained old numbers or false zeros",
|
||||
);
|
||||
await page.screenshot({ path: path.join(out, "production-overview-error.png"), fullPage: true });
|
||||
await page.unroute("**/api/dashboard/production?*");
|
||||
await overview.getByRole("button", { name: "刷新", exact: true }).click();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('[aria-label="生产总览"]')?.querySelector('[role="alert"]') == null,
|
||||
);
|
||||
await page.getByText("生产进度与运行概览", { exact: true }).click();
|
||||
}
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
assert.ok(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 2),
|
||||
|
||||
@ -19,3 +19,25 @@ test("calendar month defaults clamp month end and use application timezone", ()
|
||||
to: "2026-10-30",
|
||||
});
|
||||
});
|
||||
|
||||
test("inclusive calendar range maps to the unchanged exclusive API, including DST and year end", async () => {
|
||||
const { productionQualityRequestDates, productionQualityDisplayDates } =
|
||||
await import("../../src/lib/production-quality-dates.js");
|
||||
for (const [day, next] of [
|
||||
["2026-11-04", "2026-11-05"],
|
||||
["2026-12-31", "2027-01-01"],
|
||||
["2024-02-29", "2024-03-01"],
|
||||
["2026-03-08", "2026-03-09"],
|
||||
]) {
|
||||
assert.deepEqual(productionQualityRequestDates({ from: day, to: day }), { from: day, to: next });
|
||||
assert.deepEqual(productionQualityDisplayDates({ from: day, to: next }), { from: day, to: day });
|
||||
}
|
||||
});
|
||||
test("stale snapshots recheck soon; fresh snapshots retain the 120-second cadence", async () => {
|
||||
const { productionSnapshotRefreshDelay: delay } = await import("../../src/lib/production-quality-dates.js");
|
||||
const now = Date.parse("2026-11-04T10:00:00Z");
|
||||
assert.equal(delay({ asOf: "2026-11-04T09:59:00Z" }, now), 60000);
|
||||
assert.equal(delay({ asOf: "2026-11-04T09:59:00Z", stale: true }, now), 5000);
|
||||
assert.equal(delay({ asOf: "2026-11-04T09:59:00Z", refreshing: true }, now), 5000);
|
||||
assert.equal(delay(null, now), null);
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user