diff --git a/.scratch/acceptance-supplier-priority/work.md b/.scratch/acceptance-supplier-priority/work.md new file mode 100644 index 00000000..f247680d --- /dev/null +++ b/.scratch/acceptance-supplier-priority/work.md @@ -0,0 +1,22 @@ +# #21 Temporary supplier acceptance priority + +Baseline: 5699e7cf585d4823ef8e37cd484baf655cb56f23 (dev). Decision gate 1 approved option B; local implementation/checks/commit only. No push, deployment, company-cluster/BOS/customer-data writes. + +Goal: finish an exiting supplier's existing acceptance work for settlement; supplier and accounts remain. Admin-only per-supplier policy with project scope, expiry, cancellation and version history. Keep reviewer supplier anonymity, aggregate membership/frozen sampling, permissions, decision receipts and count totals unchanged. Owned tasks precede new admission; priority groups precede normal candidates in random and continuous admission. + +Owned files: new acceptance_priority domain/store/API files and tests; Store interface/MemoryStore field; human loop routes/review continuation; review-claim-candidates helper/human-loop service; Users admin insertion and new SupplierAcceptancePriorityPanel. Existing AGENTS/docs/admin pool test edits are unrelated, preserved and excluded from staging/check selection. + +Status: local implementation and scoped verification complete; awaiting local commit/handoff. Source supplier resolution is request-local through SourceBatchID and source human items/task ownership; missing/conflicting evidence stays unknown, visible only as admin “归属待核对” count. No customer record backfill. New collection acceptancePriorities is created only when an administrator first saves locally/after approved deployment. No startup migration/index build. + +Implemented: immutable versioned per-supplier configuration in acceptancePriorities; admin-only read/write routes and supplier account-management panel; request-local batch source ownership resolution through identity-only bulk queries; priority-before-normal admission in random/continuous paths; existing own-task precedence, permission checks, final store CAS and totals preserved. Unknown/conflicting source ownership is shown only in the admin unresolved count. No startup migrations or task backfill. Candidate-only metadata read mode avoids annotation hydration and serializes an explicit anonymous whitelist. Source lookup failure does not silently fall back to ordinary admission. + +Verification: +- Final task report: local-data/test-results/verify-1794885636928492000/report.json, selected-checks-passed, all 14 commands passed, no unmapped checks or input changes during execution. Task baseline remains 5699e7cf. Standard verification planner/runner used with the task's declared file set and acceptance-supplier-priority scope; protected unrelated changes and their checks excluded. Reproducible local wrapper/terminal log: local-data/test-results/issue21/run-scoped-verification.py and task-final.log. npm verify:plan was inspected before editing and again after mapping. +- TypeScript lint/typecheck, changed-file formatting, Go formatting, verification tooling tests, frontend business regressions, API and MemoryStore regressions passed. Includes priority beyond 200 newer ordinary candidates, per-project scope, unknown/conflicting historical ownership and task fallback, expired/canceled policy fallback, returned acceptance rounds, admin access/version conflicts, unchanged count totals, owned-task-first continuation, grant revocation and a single winner among eight competing claim requests from two reviewers. +- Real localhost Mongo 27018: isolated acceptance_priority_test_* databases, configuration CAS/history, ownership resolution and new-store-instance persistence passed; temporary databases cleaned. No shared snapshot customer records changed. +- Race detector: go test -race ./internal/api ./internal/store -run '^TestAcceptancePriorityConcurrentClaimCAS$|^TestAcceptancePriorityStoreMemory$' -count=1 -timeout=2m passed (issue21/race.log). +- Actual Users page + isolated MemoryStore API browser: admin save/project selection/reload/cancel/load error/retry and supplier-manager exclusion passed. Desktop light/dark inspected: issue21/browser/active-light.png and active-dark.png. Loading/error and mobile screenshots retained. Existing global navigation compresses the Users page at 390px; the narrow screenshot is observation, not a mobile usability acceptance claim. No global layout changes were included. +- #18/#19 regressions passed: original-video-time browser for annotation/QC; acceptance timeline normal/focused/read-only; acceptance-playback-rate engines native/movi/movi-fractional, 15 slice changes each, retained rates and zero page errors. Player report: local-data/test-results/acceptance-playback-rate/report.json. These fixtures are local synthetic media. +- Earlier development failures are retained in temporary diagnostic logs; corrected MemoryStore private-field cloning and browser fixture routing/auth/reload assumptions. UI startup imports an existing synthetic legacy task once, so browser count assertions compare with the live fixture API rather than assume a fixed backlog size. The separate API before/after count equality and exact source ownership/count assertions remain in place. + +Compatibility/activation: see docs/acceptance-supplier-priority.md. Production activation and business acceptance remain gate 2/explicit deployment authorization. Production supplier/project/expiry selection is not yet made; no production policy was created. No pushes, PRs, cluster/BOS writes, or customer-data writes. Production-size latency/capacity and full release gates have not been claimed. diff --git a/docs/acceptance-supplier-priority.md b/docs/acceptance-supplier-priority.md new file mode 100644 index 00000000..3419893c --- /dev/null +++ b/docs/acceptance-supplier-priority.md @@ -0,0 +1,33 @@ +# 临时供应商验收优先 + +#21,决策门 1 已批准方案 B。用途是先处理指定生产供应商的存量验收以便结算,不删除供应商或账号。当前阶段仅本地实现;推送、部署、生产策略保存仍按各自授权执行。 + +## 管理入口与作用范围 + +平台管理员在账号管理中选择生产供应商,设置“验收优先”的适用项目与到期时间;不选具体项目表示组织内全部项目。可更新或取消。多个有效供应商策略属于同一优先组,不再互相排序。供应商管理员及验收员不能读取或修改这些配置。 + +配置存入独立 `acceptancePriorities` 集合,组织与供应商确定唯一 `_id`,版本 CAS 防止管理员互相覆盖,保留操作人、时间与每次范围/有效期。读取权威存储,不通过检索副本或跨请求权限缓存。到期由请求时判断,不依赖定时作业或写入。 + +管理员看到所选范围内该供应商未领取的待验收任务数;“归属待核对”是该范围内无法可靠归属的任务数,不表示它们已经归属此供应商。数量不是每位验收员的个人可领取数量,也不是源采集或视频文件数量。已领取任务不计入该数量。 + +## 领取顺序与权限 + +- 随机领取沿用项目、工作流及来源范围:跨页寻找合法优先候选,在首个含合法优先候选的页面内随机选择;确认优先组耗尽后,回到普通组的首个合法候选页。不是全池均匀随机。 +- 连续审查先继续本人已领任务;领取新任务先遍历优先组,再遍历普通组;每组沿用创建时间顺序。原项目/全部项目范围、页面代次、未确认领取的恢复与决定回执不变。 +- 随机候选接口为 `GET /api/acceptance-claim-candidates`,仅返回领取所需身份、版本、阶段、轮次与服务端 `canClaim`。不读取标注/视频证据正文或做展示补全,不返回生产供应商、来源归属或优先原因。质检与标注领取不切换到该接口。 +- 优先策略不授予任何访问或领取权限。列表的服务端权限过滤及正式领取的账号、供应商共享授权、任务版本 CAS 检查仍生效。撤权阻止新领取,原轮次已领任务继续遵守原处理资格;取消或到期不撤回已领取任务及在途合法领取。 +- 任务列表及计数接口不应用优先过滤,总数口径不变。源查询失败或候选扫描未完成返回错误,不能伪装成优先组耗尽并派普通任务。 + +## 来源归属与业务保护 + +经验收批次 `SourceBatchID` 读取来源批次和来源 HumanItem 的生产供应商;旧记录缺失时可用关联标注任务的稳定归属补足。按页批量只读取身份字段,不经当前员工或手机号推算。跨组织/项目、来源缺失、成员归属不一致或 HumanItem 与标注任务冲突时均视为“归属待核对”,不进入优先组,仍按既有权限留在普通组。不把生产供应商回填到匿名验收任务。 + +不改变聚合成员、冻结抽样、质检前置、审核决定/意见、生产归属、正式记录或交付结果。返工后重新进入验收仍按稳定来源匹配当时有效策略。只影响已进入验收池的任务,不能据此承诺未抽中或未质检通过的视频也全部经过人工最终验收。 + +## 启用与回退 + +无需回填客户任务或启动迁移;配置集合在管理员首次保存时创建,使用已有 `_id` 唯一性,不在启动时建新业务索引。生产尚未创建或保存任何本功能配置。 + +回退代码后新旧任务、意见和决定仍兼容,配置记录保留,但旧版忽略优先策略并恢复普通选择。回退不撤销已领任务。上线后由管理员选择实际供应商、项目和有效期另行启用;不能把部署成功等同策略已经生效。 + +本地验证及剩余发布事项见 [.scratch 任务记录](../.scratch/acceptance-supplier-priority/work.md)。 diff --git a/internal/api/acceptance_priority.go b/internal/api/acceptance_priority.go new file mode 100644 index 00000000..40ac9847 --- /dev/null +++ b/internal/api/acceptance_priority.go @@ -0,0 +1,302 @@ +package api + +import ( + "context" + "droboticflow/internal/domain" + "droboticflow/internal/store" + "errors" + "fmt" + "github.com/go-chi/chi/v5" + "net/http" + "slices" + "time" +) + +func priorityActive(v domain.AcceptancePriority, project string) bool { + expires, err := time.Parse(time.RFC3339, v.ExpiresAt) + return v.Enabled && err == nil && time.Now().Before(expires) && (project == "" || len(v.ProjectIDs) == 0 || slices.Contains(v.ProjectIDs, project)) +} + +// Request-local source resolution. Missing/conflicting historical evidence stays unknown; +// never join through current employees or write production ownership onto acceptance. +type acceptancePriorityResolver struct { + server *server + ctx context.Context + rules []domain.AcceptancePriority + suppliers map[string]string +} + +func (s *server) newAcceptancePriorityResolver(ctx context.Context, org string) (*acceptancePriorityResolver, error) { + rules, err := s.store.ListAcceptancePriorities(ctx, org) + if err != nil { + return nil, err + } + return &acceptancePriorityResolver{server: s, ctx: ctx, rules: rules, suppliers: map[string]string{}}, nil +} +func (p *acceptancePriorityResolver) active(project string) bool { + for _, v := range p.rules { + if priorityActive(v, project) { + return true + } + } + return false +} +func (p *acceptancePriorityResolver) prime(items []domain.HumanItemRecord) error { + ids := []string{} + seen := map[string]bool{} + org := "" + for _, item := range items { + org = item.OrganizationID + if _, ok := p.suppliers[item.BatchID]; !ok && !seen[item.BatchID] { + ids = append(ids, item.BatchID) + seen[item.BatchID] = true + } + } + if len(ids) == 0 { + return nil + } + values, err := p.server.store.ResolveAcceptanceSourceSuppliers(p.ctx, org, ids) + if err != nil { + return err + } + for _, id := range ids { + p.suppliers[id] = values[id] + } + return nil +} +func (p *acceptancePriorityResolver) supplier(item domain.HumanItemRecord) (string, error) { + if err := p.prime([]domain.HumanItemRecord{item}); err != nil { + return "", err + } + return p.suppliers[item.BatchID], nil +} +func (p *acceptancePriorityResolver) matches(item domain.HumanItemRecord) (bool, error) { + if !p.active(item.ProjectID) { + return false, nil + } + supplier, err := p.supplier(item) + if err != nil { + return false, err + } + if supplier == "" { + return false, nil + } + for _, v := range p.rules { + if v.SupplierID == supplier && priorityActive(v, item.ProjectID) { + return true, nil + } + } + return false, nil +} +func (s *server) handleAcceptancePriority(w http.ResponseWriter, r *http.Request) { + principal, ok := currentPrincipal(r) + if !ok || !isOrganizationAdmin(principal) { + renderJSON(w, 403, map[string]string{"error": "仅管理员可设置验收优先级"}) + return + } + org := s.requestOrganizationID(r) + id := chi.URLParam(r, "supplierId") + supplier, err := s.store.GetSupplier(r.Context(), id) + if err != nil { + renderError(w, 500, err) + return + } + if supplier == nil || supplier.OrganizationID != org { + renderJSON(w, 404, map[string]string{"error": "供应商不存在"}) + return + } + resolver, err := s.newAcceptancePriorityResolver(r.Context(), org) + if err != nil { + renderError(w, 500, err) + return + } + value := domain.AcceptancePriority{OrganizationID: org, SupplierID: id, ProjectIDs: []string{}} + for _, v := range resolver.rules { + if v.SupplierID == id { + value = v + } + } + if r.Method == http.MethodPut { + var input struct { + Enabled bool `json:"enabled"` + ProjectIDs []string `json:"projectIds"` + ExpiresAt string `json:"expiresAt"` + Version int `json:"version"` + } + if !decodeJSON(w, r, &input) { + return + } + if input.Version < 0 || len(input.ProjectIDs) > 100 { + renderValidationError(w, validationIssue{Field: "priority", Message: "验收优先设置无效"}) + return + } + if input.Enabled { + expiry, e := time.Parse(time.RFC3339, input.ExpiresAt) + if e != nil || !time.Now().Before(expiry) || supplier.Status != "active" { + renderValidationError(w, validationIssue{Field: "expiresAt", Message: "请选择未来的到期时间及有效供应商"}) + return + } + input.ExpiresAt = expiry.UTC().Format(time.RFC3339) + for _, pid := range input.ProjectIDs { + project, e := s.store.GetProject(r.Context(), pid) + if e != nil { + renderError(w, 500, e) + return + } + if project == nil || project.OrganizationID != org || project.DeletionTaskID != "" || project.Status == domain.ProjectStatusArchived { + renderValidationError(w, validationIssue{Field: "projectIds", Message: "项目不可用"}) + return + } + } + } + value.Enabled = input.Enabled + value.ProjectIDs = slices.Clone(input.ProjectIDs) + value.ExpiresAt = input.ExpiresAt + value.UpdatedBy = principal.User.ID + saved, e := s.store.SaveAcceptancePriority(r.Context(), value, input.Version) + if errors.Is(e, store.ErrAcceptancePriorityConflict) { + renderError(w, 409, e) + return + } + if e != nil { + renderError(w, 500, e) + return + } + value = *saved + } + remaining, unresolved := 0, 0 + for offset := 0; ; offset += 100 { + rows, e := s.store.ListReviewCandidates(r.Context(), org, "", "", false, offset, 100, fanyuV5PrePackageAcceptanceStageID) + if e != nil { + renderError(w, 500, e) + return + } + batchIDs := []string{} + for _, item := range rows { + batchIDs = append(batchIDs, item.BatchID) + } + batchRows, e := s.store.ListHumanBatchAccessRecords(r.Context(), org, batchIDs) + if e != nil { + renderError(w, 500, e) + return + } + batches := map[string]*domain.HumanBatchRecord{} + for i := range batchRows { + batches[batchRows[i].ID] = &batchRows[i] + } + if e := resolver.prime(rows); e != nil { + renderError(w, 500, e) + return + } + for _, item := range rows { + if len(value.ProjectIDs) > 0 && !slices.Contains(value.ProjectIDs, item.ProjectID) { + continue + } + b := batches[item.BatchID] + if !domain.SharedAcceptanceItem(item, b) { + continue + } + sid, e := resolver.supplier(item) + if e != nil { + renderError(w, 500, e) + return + } + if sid == "" { + unresolved++ + } else if sid == id { + remaining++ + } + } + if len(rows) < 100 { + break + } + } + renderJSON(w, 200, map[string]any{"policy": value, "active": priorityActive(value, ""), "remainingCount": remaining, "unresolvedCount": unresolved}) +} + +// Preserve the existing first-eligible-page random semantics inside each group. +// Search all pages for a legal priority group before returning the ordinary page. +func (s *server) handleAcceptanceClaimCandidates(w http.ResponseWriter, r *http.Request) { + principal, ok := currentPrincipal(r) + if !ok || principal.User.Role != domain.UserRoleAcceptanceReviewer { + renderJSON(w, 403, map[string]string{"error": "仅验收员可领取验收任务"}) + return + } + resolver, err := s.newAcceptancePriorityResolver(r.Context(), s.requestOrganizationID(r)) + if err != nil { + renderError(w, 500, err) + return + } + next := r.Clone(context.WithValue(r.Context(), humanPoolReadModeKey{}, humanPoolReadClaimCandidates)) + url := *r.URL + next.URL = &url + q := url.Query() + q.Set("pluginId", "annotation-qa") + q.Set("pool", "available") + q.Set("stageIds", fanyuV5PrePackageAcceptanceStageID) + q.Del("stageId") + q.Set("limit", "200") + q.Del("cursor") + var fallback []domain.HumanItemRecord + seen := map[string]bool{} + for round := 0; round < 200; round++ { + next.URL.RawQuery = q.Encode() + page, _ := s.readHumanItemsList(w, next) + if page == nil { + return + } + if resolver.active(q.Get("projectId")) { + if e := resolver.prime(page.Items); e != nil { + renderError(w, 500, e) + return + } + } + ordinary, priority := []domain.HumanItemRecord{}, []domain.HumanItemRecord{} + for _, item := range page.Items { + if item.CanClaim == nil || !*item.CanClaim { + continue + } + ordinary = append(ordinary, item) + if resolver.active(item.ProjectID) { + matches, e := resolver.matches(item) + if e != nil { + renderError(w, 500, e) + return + } + if matches { + priority = append(priority, item) + } + } + } + if len(priority) > 0 { + renderJSON(w, 200, map[string]any{"items": anonymousAcceptanceCandidates(priority)}) + return + } + if fallback == nil && len(ordinary) > 0 { + fallback = ordinary + } + if !resolver.active(q.Get("projectId")) && len(fallback) > 0 || !page.HasMore { + if fallback == nil { + fallback = []domain.HumanItemRecord{} + } + renderJSON(w, 200, map[string]any{"items": anonymousAcceptanceCandidates(fallback)}) + return + } + if page.NextCursor == "" || seen[page.NextCursor] { + break + } + seen[page.NextCursor] = true + q.Set("cursor", page.NextCursor) + } + renderError(w, 503, fmt.Errorf("可领取任务加载未完成,请缩小项目范围后重试")) +} + +// Never serialize raw candidate records: legacy records may carry production +// identities even though current three-role acceptance creation omits them. +func anonymousAcceptanceCandidates(items []domain.HumanItemRecord) []map[string]any { + out := make([]map[string]any, 0, len(items)) + for _, item := range items { + out = append(out, map[string]any{"id": item.ID, "projectId": item.ProjectID, "version": item.Version, "reviewRound": item.ReviewRound, "currentStageId": item.CurrentStageID, "status": item.Status, "canClaim": item.CanClaim != nil && *item.CanClaim}) + } + return out +} diff --git a/internal/api/acceptance_priority_browser_test.go b/internal/api/acceptance_priority_browser_test.go new file mode 100644 index 00000000..fe8ba392 --- /dev/null +++ b/internal/api/acceptance_priority_browser_test.go @@ -0,0 +1,49 @@ +package api + +import ( + "context" + "droboticflow/internal/domain" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "testing" + "time" +) + +// Actual app and API, isolated MemoryStore; no customer records or credentials. +func TestAcceptancePriorityBrowser(t *testing.T) { + if os.Getenv("ACCEPTANCE_PRIORITY_BROWSER") != "1" { + t.Skip("local browser opt-in") + } + f := priorityFixture(t) + _ = f.store.UpsertSupplier(f.ctx, domain.SupplierRecord{ID: "priority-production", Name: "优先供应商", OrganizationID: f.item.OrganizationID, Status: "active"}) + item := f.item + item.ID = "priority-browser" + addPrioritySource(t, f, item, "priority-production") + h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Test-only authentication at the loopback fixture boundary. + user := f.admin + if r.Header.Get("X-Fixture-Role") == "supplier_manager" { + user = domain.UserRecord{ID: "fixture-manager", Role: domain.UserRoleSupplierManager, SupplierID: "priority-production", OrganizationID: f.item.OrganizationID, Status: domain.UserStatusActive} + } + if r.URL.Path == "/api/auth/me" { + http.SetCookie(w, &http.Cookie{Name: csrfCookieName, Value: "priority-fixture-csrf", Path: "/"}) + renderJSON(w, 200, map[string]any{"user": sanitizeUser(&user), "organization": domain.OrganizationRecord{ID: f.item.OrganizationID, Status: domain.OrganizationStatusActive}}) + return + } + r = r.WithContext(context.WithValue(r.Context(), authContextKey{}, &authenticatedPrincipal{User: user, Organization: domain.OrganizationRecord{ID: f.item.OrganizationID, Status: domain.OrganizationStatusActive}})) + f.handler.ServeHTTP(w, r) + })) + defer h.Close() + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, "node", "tests/browser/acceptance-priority.mjs") + cmd.Dir = "../.." + cmd.Env = append(os.Environ(), "ACCEPTANCE_PRIORITY_API="+h.URL) + output, e := cmd.CombinedOutput() + t.Log(string(output)) + if e != nil { + t.Fatal(e) + } +} diff --git a/internal/api/acceptance_priority_test.go b/internal/api/acceptance_priority_test.go new file mode 100644 index 00000000..783f64c7 --- /dev/null +++ b/internal/api/acceptance_priority_test.go @@ -0,0 +1,329 @@ +package api + +import ( + "context" + "droboticflow/internal/domain" + "droboticflow/internal/store" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "sync" + "testing" + "time" +) + +func priorityFixture(t *testing.T) combinedDraftFixture { + f := sharedAcceptanceFixture(t) + // Existing acceptance is ordinary; source identities are separate from reviewer identity. + addPrioritySource(t, f, f.item, "ordinary-production") + _ = f.store.UpsertSupplier(f.ctx, domain.SupplierRecord{ID: "priority-production", OrganizationID: f.item.OrganizationID, Name: "Priority producer", Status: "active"}) + return f +} +func addPrioritySource(t *testing.T, f combinedDraftFixture, item domain.HumanItemRecord, supplier string) { + t.Helper() + batch, _ := f.store.GetHumanBatch(f.ctx, f.item.BatchID) + b := *batch + b.RequirePrePackageAcceptance = false + b.ID = "acceptance-batch-" + item.ID + b.SourceBatchID = "production-batch-" + item.ID + source := b + source.ID = b.SourceBatchID + source.SourceBatchID = "" + source.Stages = domain.DefaultFanyuV58HumanStages() + for _, v := range []domain.HumanBatchRecord{source, b} { + if e := f.store.UpsertHumanBatch(f.ctx, v); e != nil { + t.Fatal(e) + } + } + row := domain.HumanItemRecord{ID: "production-" + item.ID, OrganizationID: item.OrganizationID, ProjectID: item.ProjectID, BatchID: source.ID, PluginID: "annotation-qa", SupplierID: supplier, Status: domain.HumanItemAccepted, CurrentStageID: domain.FanyuV58StageQualityReview, Version: 1, CreatedAt: item.CreatedAt} + if e := f.store.UpsertHumanItem(f.ctx, row); e != nil { + t.Fatal(e) + } + item.BatchID = b.ID + item.SupplierID = "" + item.LegacyTaskID = "" + if e := f.store.UpsertHumanItem(f.ctx, item); e != nil { + t.Fatal(e) + } +} +func priorityPolicy(t *testing.T, f combinedDraftFixture, enabled bool, version int, expiry string, projects []string) { + t.Helper() + r := f.request("PUT", "/api/suppliers/priority-production/acceptance-priority", f.admin, map[string]any{"enabled": enabled, "projectIds": projects, "expiresAt": expiry, "version": version}) + if r.Code != 200 { + t.Fatalf("policy %d %s", r.Code, r.Body.String()) + } +} +func priorityCandidates(t *testing.T, f combinedDraftFixture) []domain.HumanItemRecord { + t.Helper() + r := f.request("GET", "/api/acceptance-claim-candidates?projectId="+f.item.ProjectID, f.reviewer, nil) + if r.Code != 200 { + t.Fatalf("candidates %d %s", r.Code, r.Body.String()) + } + var page humanItemListPage + if e := json.Unmarshal(r.Body.Bytes(), &page); e != nil { + t.Fatal(e) + } + for _, item := range page.Items { + if item.SupplierID != "" || item.CanClaim == nil || !*item.CanClaim { + t.Fatal("identity leaked or unauthorized candidate") + } + } + if strings.Contains(r.Body.String(), "priority-production") || strings.Contains(r.Body.String(), "ordinary-production") { + t.Fatal("supplier leaked") + } + return page.Items +} +func TestAcceptancePriorityRandomAcrossPagesCountsAndCancellation(t *testing.T) { + f := priorityFixture(t) + for i := 0; i < 205; i++ { + item := f.item + item.ID = fmt.Sprintf("ordinary-%03d", i) + item.CreatedAt = "2026-01-02T00:00:00Z" + addPrioritySource(t, f, item, "ordinary-production") + } + target := f.item + target.ID = "priority-oldest" + target.CreatedAt = "2001-01-01T00:00:00Z" + addPrioritySource(t, f, target, "priority-production") + before := f.request("GET", "/api/human-item-counts?pluginId=annotation-qa&stageIds=prepackage_acceptance", f.reviewer, nil) + expiry := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + priorityPolicy(t, f, true, 0, expiry, []string{f.item.ProjectID}) + after := f.request("GET", "/api/human-item-counts?pluginId=annotation-qa&stageIds=prepackage_acceptance", f.reviewer, nil) + if before.Code != 200 || after.Code != 200 || before.Body.String() != after.Body.String() { + t.Fatalf("counts changed: %s / %s", before.Body, after.Body) + } + candidates := priorityCandidates(t, f) + if len(candidates) != 1 || candidates[0].ID != target.ID { + t.Fatalf("old priority lost beyond page: %d", len(candidates)) + } + // Reopened acceptance rounds keep production ownership and policy matching. + fresh, _ := f.store.GetHumanItem(f.ctx, target.ID) + fresh.ReviewRound++ + fresh.Version++ + fresh.Status = domain.HumanItemReady + _ = f.store.UpsertHumanItem(f.ctx, *fresh) + if got := priorityCandidates(t, f); len(got) != 1 || got[0].ReviewRound != fresh.ReviewRound { + t.Fatal("rework lost priority") + } + // Conflicting admin save never overwrites a newer policy. + stale := f.request("PUT", "/api/suppliers/priority-production/acceptance-priority", f.admin, map[string]any{"enabled": false, "version": 0}) + if stale.Code != 409 { + t.Fatalf("stale admin %d", stale.Code) + } + priorityPolicy(t, f, false, 1, expiry, nil) + if got := priorityCandidates(t, f); len(got) < 2 { + t.Fatal("cancellation did not restore ordinary group") + } +} +func TestAcceptancePriorityContinuationOwnedFirstAndPermissionRefresh(t *testing.T) { + for _, owned := range []bool{false, true} { + t.Run(fmt.Sprint(owned), func(t *testing.T) { + f := priorityFixture(t) + item := f.item + item.ID = "priority-newer" + item.CreatedAt = "2090-01-01T00:00:00Z" + addPrioritySource(t, f, item, "priority-production") + priorityPolicy(t, f, true, 0, time.Now().Add(time.Hour).UTC().Format(time.RFC3339), nil) + if owned { + old, _ := f.store.GetHumanItem(f.ctx, f.item.ID) + old.AssignedUserID = f.reviewer.ID + old.Status = domain.HumanItemClaimed + _ = f.store.UpsertHumanItem(f.ctx, *old) + } + r := continuationCall(f, "start", "priority-page", 0, map[string]any{"stage": "acceptance"}, nil) + result := continuationResult(t, r) + want := item.ID + if owned { + want = f.item.ID + } + if result.Item == nil || result.Item.ID != want { + t.Fatalf("continuation selected %+v want %s", result.Item, want) + } + // Revocation stops fresh admission immediately; existing current-round access remains. + _, err := f.store.SetSupplierAcceptanceAuthorization(f.ctx, f.item.OrganizationID, f.reviewer.SupplierID, false, 1, f.admin.ID) + if err != nil { + t.Fatal(err) + } + if got := priorityCandidates(t, f); len(got) != 0 { + t.Fatal("revoked reviewer sees new admission") + } + }) + } +} +func TestAcceptancePriorityUnknownScopeExpiryAndAdminOnly(t *testing.T) { + f := priorityFixture(t) + expiry := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + for _, u := range []domain.UserRecord{f.annotator, f.reviewer, {ID: "manager", Role: domain.UserRoleSupplierManager, OrganizationID: f.item.OrganizationID, SupplierID: "priority-production"}} { + for _, method := range []string{"GET", "PUT"} { + r := f.request(method, "/api/suppliers/priority-production/acceptance-priority", u, nil) + if r.Code != 403 { + t.Fatalf("admin-only %s %d", method, r.Code) + } + } + } + // Missing source supplier: leave ordinary, report unknown only to admin. + target := f.item + target.ID = "unknown" + addPrioritySource(t, f, target, "") + priorityPolicy(t, f, true, 0, expiry, nil) + got := priorityCandidates(t, f) + if len(got) != 2 { + t.Fatalf("unknown dropped from ordinary group: %d", len(got)) + } + admin := f.request("GET", "/api/suppliers/priority-production/acceptance-priority", f.admin, nil) + if admin.Code != 200 || !strings.Contains(admin.Body.String(), `"unresolvedCount":1`) { + t.Fatalf("unknown not reported %s", admin.Body) + } + // Expired policies are ignored without a cron/job/database mutation. + _, e := f.store.SaveAcceptancePriority(f.ctx, domain.AcceptancePriority{OrganizationID: f.item.OrganizationID, SupplierID: "priority-production", Enabled: true, ExpiresAt: time.Now().Add(-time.Second).UTC().Format(time.RFC3339)}, 1) + if e != nil { + t.Fatal(e) + } + if got := priorityCandidates(t, f); len(got) != 2 { + t.Fatal("expiry blocked fallback") + } + // Invalid expiry and cross-organization project never persist. + bad := f.request("PUT", "/api/suppliers/priority-production/acceptance-priority", f.admin, map[string]any{"enabled": true, "expiresAt": "bad", "version": 2}) + if bad.Code != 422 && bad.Code != 400 { + t.Fatalf("expiry validation %d", bad.Code) + } +} +func TestAcceptancePriorityConcurrentClaimCAS(t *testing.T) { + f := priorityFixture(t) + target := f.item + target.ID = "priority-race" + addPrioritySource(t, f, target, "priority-production") + priorityPolicy(t, f, true, 0, time.Now().Add(time.Hour).UTC().Format(time.RFC3339), nil) + adminCount := f.request("GET", "/api/suppliers/priority-production/acceptance-priority", f.admin, nil) + if !strings.Contains(adminCount.Body.String(), `"remainingCount":1`) { + t.Fatalf("admin count %s", adminCount.Body) + } + candidate := priorityCandidates(t, f)[0] + competitor := f.reviewer + competitor.ID = "priority-competitor" + _ = f.store.UpsertUser(f.ctx, competitor) + codes := make(chan int, 8) + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + actor := f.reviewer + if i%2 == 1 { + actor = competitor + } + go func() { + defer wg.Done() + r := f.request(http.MethodPost, "/api/human-items/"+candidate.ID+"/claim", actor, map[string]any{"version": candidate.Version}) + codes <- r.Code + }() + } + wg.Wait() + close(codes) + success := 0 + for code := range codes { + if code == 200 { + success++ + } else if code != 409 { + t.Fatalf("unexpected claim %d", code) + } + } + if success != 1 { + t.Fatalf("successful claims %d", success) + } + // Once exhausted, ordinary candidates remain available. + if got := priorityCandidates(t, f); len(got) != 1 || got[0].ID != f.item.ID { + t.Fatal("exhausted group did not fall back") + } +} + +func TestAcceptancePriorityProjectScopeExpiryAndSourceConflict(t *testing.T) { + f := priorityFixture(t) + item := f.item + item.ID = "target-scoped" + addPrioritySource(t, f, item, "priority-production") + _ = f.store.UpsertProject(f.ctx, domain.ProjectRecord{ID: "other-project", OrganizationID: f.item.OrganizationID, Status: domain.ProjectStatusActive}) + expiry := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + priorityPolicy(t, f, true, 0, expiry, []string{"other-project"}) + if got := priorityCandidates(t, f); len(got) != 2 { + t.Fatal("project scope leaked priority into another project") + } + priorityPolicy(t, f, true, 1, expiry, []string{f.item.ProjectID}) + if got := priorityCandidates(t, f); len(got) != 1 || got[0].ID != item.ID { + t.Fatal("project priority not applied") + } + // Expiry really changes the chosen group, while preserving all ordinary candidates. + _, err := f.store.SaveAcceptancePriority(f.ctx, domain.AcceptancePriority{OrganizationID: f.item.OrganizationID, SupplierID: "priority-production", Enabled: true, ExpiresAt: time.Now().Add(-time.Second).UTC().Format(time.RFC3339)}, 2) + if err != nil { + t.Fatal(err) + } + if got := priorityCandidates(t, f); len(got) != 2 { + t.Fatal("expired target remained preferred") + } + // Resolve legacy blank human ownership from the stable task, never current user membership. + source, _ := f.store.GetHumanItem(f.ctx, "production-"+item.ID) + source.SupplierID = "" + source.LegacyTaskID = "source-task-owned" + source.LatestAuthorUserID = "deleted-annotator" + _ = f.store.UpsertHumanItem(f.ctx, *source) + task := f.task + task.ID = source.LegacyTaskID + task.SupplierID = "priority-production" + _ = f.store.UpsertAnnotationTask(f.ctx, task) + target, _ := f.store.GetHumanItem(f.ctx, item.ID) + resolver, _ := (&server{store: f.store}).newAcceptancePriorityResolver(f.ctx, f.item.OrganizationID) + sid, err := resolver.supplier(*target) + if err != nil || sid != "priority-production" { + t.Fatalf("task ownership fallback %s %v", sid, err) + } + // Disagreeing historical identities are unknown rather than guessed from either side. + source.SupplierID = "ordinary-production" + _ = f.store.UpsertHumanItem(f.ctx, *source) + resolver, _ = (&server{store: f.store}).newAcceptancePriorityResolver(f.ctx, f.item.OrganizationID) + sid, err = resolver.supplier(*target) + if err != nil || sid != "" { + t.Fatal("conflicting source ownership was guessed") + } + // Source ownership is never copied onto the anonymous acceptance record. + stored, _ := f.store.GetHumanItem(f.ctx, target.ID) + if stored.SupplierID != "" { + t.Fatal("acceptance ownership changed") + } +} + +// Admission must not fetch annotation bodies, and source-query failures must +// never be converted into an empty priority pool and ordinary admission. +type priorityReadGuardStore struct { + store.Store + failSources bool +} + +func (s priorityReadGuardStore) ListHumanItems(ctx context.Context, org string, q domain.HumanItemQuery) ([]domain.HumanItemRecord, error) { + if q.ListProjection && !q.PoolCandidateProjection && len(q.IDs) > 0 { + return nil, errors.New("unexpected evidence hydration in candidate scan") + } + return s.Store.ListHumanItems(ctx, org, q) +} +func (s priorityReadGuardStore) ResolveAcceptanceSourceSuppliers(ctx context.Context, org string, ids []string) (map[string]string, error) { + if s.failSources { + return nil, errors.New("source identity query unavailable") + } + return s.Store.ResolveAcceptanceSourceSuppliers(ctx, org, ids) +} +func TestAcceptancePriorityCandidateReadsAreLightAndFailClosed(t *testing.T) { + f := priorityFixture(t) + item := f.item + item.ID = "guarded-priority" + addPrioritySource(t, f, item, "priority-production") + priorityPolicy(t, f, true, 0, time.Now().Add(time.Hour).UTC().Format(time.RFC3339), nil) + f.handler = NewHandler(priorityReadGuardStore{Store: f.store}, nil) + got := priorityCandidates(t, f) + if len(got) != 1 || got[0].ID != item.ID { + t.Fatal("metadata admission changed candidate") + } + f.handler = NewHandler(priorityReadGuardStore{Store: f.store, failSources: true}, nil) + r := f.request("GET", "/api/acceptance-claim-candidates", f.reviewer, nil) + if r.Code != 500 || strings.Contains(r.Body.String(), `"items"`) { + t.Fatalf("source failure became ordinary admission %d %s", r.Code, r.Body) + } +} diff --git a/internal/api/human_loop.go b/internal/api/human_loop.go index 6c402569..fd0a5e89 100644 --- a/internal/api/human_loop.go +++ b/internal/api/human_loop.go @@ -535,7 +535,7 @@ func (server *server) readHumanItemsList(writer http.ResponseWriter, request *ht } } } - if poolReadMode(request) == humanPoolReadCount { + if humanPoolMetadataOnly(request) { page := &humanItemListPage{Items: filtered, HasMore: hasMore} if hasMore { page.NextCursor = encodeHumanItemCursor(nextCursor) @@ -652,7 +652,7 @@ func (server *server) filterHumanPoolItem(request *http.Request, item domain.Hum // changes between reads sends this page through the original single-read path; // stale metadata must not govern a newer assignment, stage or permission scope. func (server *server) hydrateHumanPoolPage(request *http.Request, items []domain.HumanItemRecord, pool string, query domain.HumanItemQuery, remaining int, batches map[string]*domain.HumanBatchRecord) ([]domain.HumanItemRecord, error) { - if poolReadMode(request) == humanPoolReadCount { + if humanPoolMetadataOnly(request) { return items, nil } ids := []string{} diff --git a/internal/api/human_pool_reads.go b/internal/api/human_pool_reads.go index 693cf3ae..c19eefa1 100644 --- a/internal/api/human_pool_reads.go +++ b/internal/api/human_pool_reads.go @@ -13,8 +13,15 @@ const ( humanPoolReadFull humanPoolReadMode = iota humanPoolReadSummary humanPoolReadCount + humanPoolReadClaimCandidates ) +// Candidate admission needs authoritative eligibility, but no annotation/evidence +// hydration or display joins. Only the dedicated anonymous candidate endpoint uses it. +func humanPoolMetadataOnly(r *http.Request) bool { + return poolReadMode(r) == humanPoolReadCount || poolReadMode(r) == humanPoolReadClaimCandidates +} + type humanPoolReadModeKey struct{} func poolReadMode(r *http.Request) humanPoolReadMode { diff --git a/internal/api/review_continuation.go b/internal/api/review_continuation.go index ce0da71a..bf08f151 100644 --- a/internal/api/review_continuation.go +++ b/internal/api/review_continuation.go @@ -334,12 +334,30 @@ func (server *server) continuationChoose(r *http.Request, v *domain.ReviewContin if v.Stage == "acceptance" { stageID = fanyuV5PrePackageAcceptanceStageID } - for _, owned := range []bool{true, false} { + var priority *acceptancePriorityResolver + if v.Stage == "acceptance" { + var err error + priority, err = server.newAcceptancePriorityResolver(ctx, v.OrganizationID) + if err != nil { + return err + } + } + phases := []int{0, 2} + if priority != nil && priority.active(v.ProjectID) { + phases = []int{0, 1, 2} + } + for _, phase := range phases { + owned := phase == 0 for offset := 0; ; offset += 100 { items, e := server.store.ListReviewCandidates(ctx, v.OrganizationID, v.ProjectID, v.UserID, owned, offset, 100, stageID) if e != nil { return e } + if phase == 1 { + if err := priority.prime(items); err != nil { + return err + } + } candidates := make([]domain.HumanItemRecord, 0, len(items)) listCtx, e := server.withHumanListReads(ctx, v.OrganizationID, v.ProjectID, items) if e != nil { @@ -365,6 +383,15 @@ func (server *server) continuationChoose(r *http.Request, v *domain.ReviewContin if !found || !continuationStage(stage, v.Stage) || server.reviewDecisionProtocol(listCtx, item) != "receipt" || !(mine && server.canAccessHumanItem(listCtx, pageRequest, item, annotationRoleForHumanStage(stage)) || !mine && server.canClaimHumanItem(listCtx, pageRequest, item, annotationRoleForHumanStage(stage))) { continue } + if phase == 1 { + matches, err := priority.matches(item) + if err != nil { + return err + } + if !matches { + continue + } + } candidates = append(candidates, item) } sort.Slice(candidates, func(i, j int) bool { diff --git a/internal/api/routes_human_loop.go b/internal/api/routes_human_loop.go index 1ff1410c..c467ce9c 100644 --- a/internal/api/routes_human_loop.go +++ b/internal/api/routes_human_loop.go @@ -6,6 +6,7 @@ import "github.com/go-chi/chi/v5" // review sessions and drafts, submissions and decisions, rejects, sampling // and audit tasks. func (server *server) mountHumanLoopRoutes(router chi.Router) { + router.Get("/api/acceptance-claim-candidates", server.handleAcceptanceClaimCandidates) router.Get("/api/human-batches", server.handleHumanBatchesList) router.Get("/api/human-items", server.handleHumanItemsList) router.Get("/api/human-item-summaries", server.handleHumanPoolSummaries) @@ -50,6 +51,8 @@ func (server *server) mountHumanLoopRoutes(router chi.Router) { reviewers.Post("/api/human-items/{id}/escalation", server.handleHumanEscalationDecision) admin := server.withRoles(router, rolesAdmin...) + admin.Get("/api/suppliers/{supplierId}/acceptance-priority", server.handleAcceptancePriority) + admin.Put("/api/suppliers/{supplierId}/acceptance-priority", server.handleAcceptancePriority) admin.Patch("/api/human-items/{id}/assignment", server.handleHumanItemAssignment) admin.Post("/api/human-rejects/{id}/reopen", server.handleHumanRejectReopen) diff --git a/internal/api/testdata/routes.golden b/internal/api/testdata/routes.golden index 62be43f4..d982cae8 100644 --- a/internal/api/testdata/routes.golden +++ b/internal/api/testdata/routes.golden @@ -1,7 +1,7 @@ # Generated by TestRouteSnapshot; see routes_snapshot_test.go. # access: reach = endpoint reached; otherwise the status the middleware chain returned. global=[diagnosticTrace,middleware.(*Compressor).Handler-fm,(*server).invalidateDashboardCachesOnWrite-fm,(*server).apiTokenAuth-fm,(*server).sessionAuth-fm,(*server).csrfProtection-fm,(*server).projectDeletionWriteGuard-fm,(*server).supplierDeletionWriteGuard-fm,(*server).acceptanceAccessCache-fm,annotationReadCache] -routes=382 +routes=385 DELETE /api/admin/organizations/{id} | mw=[(*server).requireSuperAdmin-fm] | (*server).handleAdminOrganizationsDelete-fm | anon=401 token=401 super=reach admin=403 supplier=403 annotator=403 quality=403 acceptance=403 DELETE /api/admin/users/{id} | mw=[(*server).requireSuperAdmin-fm] | (*server).handleAdminUserDelete-fm | anon=401 token=401 super=reach admin=403 supplier=403 annotator=403 quality=403 acceptance=403 DELETE /api/database/collections/{name} | mw=[(*server).requireBusinessRole.1] | (*server).handleDatabaseCollectionDelete-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 @@ -23,6 +23,7 @@ DELETE /api/templates/{id} | mw=[(*server).requireBusinessRole.1] | (*server).ha DELETE /api/users/{id} | mw=[(*server).requireBusinessRole.1] | (*server).handleUsersDelete-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=403 quality=403 acceptance=403 DELETE /api/workflows/{id} | mw=[(*server).requireBusinessRole.1] | (*server).handleWorkflowsDelete-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 DELETE /api/workflows/{id}/nodes/{nodeId}/source-state | mw=[(*server).requireBusinessRole.1] | (*server).handleWorkflowNodeSourceStateDelete-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 +GET /api/acceptance-claim-candidates | mw=[] | (*server).handleAcceptanceClaimCandidates-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach GET /api/acceptance/poc-readiness | mw=[(*server).requireAdminMonitoringAccess-fm] | (*server).handlePocAcceptanceReadiness-fm | anon=401 token=reach super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 GET /api/admin/organizations | mw=[(*server).requireSuperAdmin-fm] | (*server).handleAdminOrganizationsList-fm | anon=401 token=401 super=reach admin=403 supplier=403 annotator=403 quality=403 acceptance=403 GET /api/admin/organizations/{id}/users | mw=[(*server).requireSuperAdmin-fm] | (*server).handleAdminOrganizationUsersList-fm | anon=401 token=401 super=reach admin=403 supplier=403 annotator=403 quality=403 acceptance=403 @@ -170,6 +171,7 @@ GET /api/supplier-deletions | mw=[] | (*server).handleSupplierDeletionsList-fm | GET /api/supplier-deletions/{deletionId} | mw=[] | (*server).handleSupplierDeletionGet-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach GET /api/suppliers | mw=[] | (*server).handleSuppliersList-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach GET /api/suppliers/{supplierId}/acceptance-authorization | mw=[] | (*server).handleSupplierAcceptanceAuthorization-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach +GET /api/suppliers/{supplierId}/acceptance-priority | mw=[(*server).requireBusinessRole.1] | (*server).handleAcceptancePriority-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 GET /api/suppliers/{supplierId}/deletion-preview | mw=[] | (*server).handleSupplierDeletionPreview-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach GET /api/suppliers/{supplierId}/project-authorizations | mw=[] | (*server).handleSupplierProjectAuthorizations-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach GET /api/templates | mw=[] | (*server).handleTemplatesList-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach @@ -378,6 +380,7 @@ PUT /api/settings | mw=[(*server).requireBusinessRole.1] | (*server).handleSetti PUT /api/storage/connections/{id} | mw=[(*server).requireBusinessRole.1] | (*server).handleStorageConnectionsUpdate-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 PUT /api/suppliers/{supplierId} | mw=[(*server).requireBusinessRole.1] | (*server).handleSupplierUpdate-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=403 quality=403 acceptance=403 PUT /api/suppliers/{supplierId}/acceptance-authorization | mw=[] | (*server).handleSupplierAcceptanceAuthorization-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach +PUT /api/suppliers/{supplierId}/acceptance-priority | mw=[(*server).requireBusinessRole.1] | (*server).handleAcceptancePriority-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 PUT /api/templates/{id} | mw=[(*server).requireBusinessRole.1] | (*server).handleTemplatesUpdate-fm | anon=401 token=401 super=403 admin=reach supplier=403 annotator=403 quality=403 acceptance=403 PUT /api/users/me | mw=[] | (*server).handleCurrentUserProfileUpdate-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=reach quality=reach acceptance=reach PUT /api/users/{id} | mw=[(*server).requireBusinessRole.1] | (*server).handleUsersUpdate-fm | anon=401 token=401 super=403 admin=reach supplier=reach annotator=403 quality=403 acceptance=403 diff --git a/internal/domain/acceptance_priority.go b/internal/domain/acceptance_priority.go new file mode 100644 index 00000000..83c1b1e3 --- /dev/null +++ b/internal/domain/acceptance_priority.go @@ -0,0 +1,23 @@ +package domain + +// AcceptancePriority changes admission order only, never production ownership or access. +// Empty ProjectIDs means all production projects in this organization. +type AcceptancePriority struct { + ID string `json:"-" bson:"_id"` + OrganizationID string `json:"-" bson:"organizationId"` + SupplierID string `json:"supplierId" bson:"supplierId"` + Enabled bool `json:"enabled" bson:"enabled"` + ProjectIDs []string `json:"projectIds" bson:"projectIds"` + ExpiresAt string `json:"expiresAt" bson:"expiresAt"` + Version int `json:"version" bson:"version"` + UpdatedAt string `json:"updatedAt,omitempty" bson:"updatedAt"` + UpdatedBy string `json:"updatedBy,omitempty" bson:"updatedBy"` + History []AcceptancePriorityChange `json:"-" bson:"history"` +} +type AcceptancePriorityChange struct { + Enabled bool `bson:"enabled"` + ProjectIDs []string `bson:"projectIds"` + ExpiresAt string `bson:"expiresAt"` + ActorID string `bson:"actorId"` + At string `bson:"at"` +} diff --git a/internal/store/acceptance_priority.go b/internal/store/acceptance_priority.go new file mode 100644 index 00000000..dd964c6c --- /dev/null +++ b/internal/store/acceptance_priority.go @@ -0,0 +1,226 @@ +package store + +import ( + "context" + "droboticflow/internal/domain" + "errors" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "sort" +) + +var ErrAcceptancePriorityConflict = errors.New("验收优先设置已更新,请刷新后重试") + +func cloneAcceptancePriority(v domain.AcceptancePriority) domain.AcceptancePriority { + v.ProjectIDs = append([]string(nil), v.ProjectIDs...) + v.History = append([]domain.AcceptancePriorityChange(nil), v.History...) + for i := range v.History { + v.History[i].ProjectIDs = append([]string(nil), v.History[i].ProjectIDs...) + } + return v +} +func nextAcceptancePriority(v, old domain.AcceptancePriority) domain.AcceptancePriority { + v.ID = normalizedOrganizationID(v.OrganizationID) + ":" + v.SupplierID + v.OrganizationID = normalizedOrganizationID(v.OrganizationID) + v.Version = old.Version + 1 + v.UpdatedAt = nowISO() + v.History = append(old.History, domain.AcceptancePriorityChange{Enabled: v.Enabled, ProjectIDs: append([]string(nil), v.ProjectIDs...), ExpiresAt: v.ExpiresAt, ActorID: v.UpdatedBy, At: v.UpdatedAt}) + return v +} +func (s *MemoryStore) ListAcceptancePriorities(_ context.Context, org string) ([]domain.AcceptancePriority, error) { + s.mu.Lock() + defer s.mu.Unlock() + out := []domain.AcceptancePriority{} + for _, v := range s.acceptancePriorities { + if v.OrganizationID == normalizedOrganizationID(org) { + out = append(out, cloneAcceptancePriority(v)) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].SupplierID < out[j].SupplierID }) + return out, nil +} +func (s *MemoryStore) SaveAcceptancePriority(_ context.Context, v domain.AcceptancePriority, version int) (*domain.AcceptancePriority, error) { + s.mu.Lock() + defer s.mu.Unlock() + id := normalizedOrganizationID(v.OrganizationID) + ":" + v.SupplierID + old := s.acceptancePriorities[id] + if old.Version != version { + return nil, ErrAcceptancePriorityConflict + } + v = nextAcceptancePriority(v, old) + if s.acceptancePriorities == nil { + s.acceptancePriorities = map[string]domain.AcceptancePriority{} + } + s.acceptancePriorities[id] = cloneAcceptancePriority(v) + return &v, nil +} +func (s *MongoStore) ListAcceptancePriorities(ctx context.Context, org string) ([]domain.AcceptancePriority, error) { + // Authoritative config reads: never query-replica cached. + cur, err := s.queryCollection("acceptancePriorities").Find(ctx, bson.M{"organizationId": normalizedOrganizationID(org)}) + if err != nil { + return nil, err + } + return decodeMany[domain.AcceptancePriority](ctx, cur) +} +func (s *MongoStore) SaveAcceptancePriority(ctx context.Context, v domain.AcceptancePriority, version int) (*domain.AcceptancePriority, error) { + c := s.queryCollection("acceptancePriorities") + var old domain.AcceptancePriority + err := c.FindOne(ctx, bson.M{"_id": normalizedOrganizationID(v.OrganizationID) + ":" + v.SupplierID}).Decode(&old) + if err != nil && !errors.Is(err, mongo.ErrNoDocuments) { + return nil, err + } + if old.Version != version { + return nil, ErrAcceptancePriorityConflict + } + v = nextAcceptancePriority(v, old) + if version == 0 { + _, err = c.InsertOne(ctx, v) + } else { + r, e := c.ReplaceOne(ctx, bson.M{"_id": v.ID, "version": version}, v) + err = e + if err == nil && r.MatchedCount == 0 { + err = ErrAcceptancePriorityConflict + } + } + if mongo.IsDuplicateKeyError(err) { + err = ErrAcceptancePriorityConflict + } + if err != nil { + return nil, err + } + return &v, nil +} + +// Resolve ownership using bounded input batch IDs and identity-only bulk reads. +// No employee lookups, private evidence payloads, ownership writes or replica cache. +func resolveAcceptanceSuppliers(org string, ids []string, batches map[string]domain.HumanBatchRecord, rows []domain.HumanItemRecord, tasks map[string]domain.AnnotationTaskRecord) map[string]string { + out := map[string]string{} + bySource := map[string][]domain.HumanItemRecord{} + for _, row := range rows { + bySource[row.BatchID] = append(bySource[row.BatchID], row) + } + for _, id := range ids { + out[id] = "" + b, ok := batches[id] + if !ok || b.OrganizationID != normalizedOrganizationID(org) || b.SourceBatchID == "" { + continue + } + source, ok := batches[b.SourceBatchID] + if !ok || source.OrganizationID != b.OrganizationID || source.ProjectID != b.ProjectID { + continue + } + supplier := "" + valid := len(bySource[source.ID]) > 0 + for _, row := range bySource[source.ID] { + sid := row.SupplierID + if row.OrganizationID != b.OrganizationID || row.ProjectID != b.ProjectID { + valid = false + break + } + if task, ok := tasks[row.LegacyTaskID]; ok { + if task.OrganizationID != b.OrganizationID || task.ProjectID != b.ProjectID || (sid != "" && task.SupplierID != "" && sid != task.SupplierID) { + valid = false + break + } + if sid == "" { + sid = task.SupplierID + } + } + if sid == "" || (supplier != "" && supplier != sid) { + valid = false + break + } + supplier = sid + } + if valid { + out[id] = supplier + } + } + return out +} +func (s *MemoryStore) ResolveAcceptanceSourceSuppliers(ctx context.Context, org string, ids []string) (map[string]string, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + batches := map[string]domain.HumanBatchRecord{} + sources := map[string]bool{} + for _, id := range ids { + if b, ok := s.humanBatches[id]; ok { + batches[id] = b + if source, ok := s.humanBatches[b.SourceBatchID]; ok { + batches[source.ID] = source + sources[source.ID] = true + } + } + } + rows := []domain.HumanItemRecord{} + tasks := map[string]domain.AnnotationTaskRecord{} + for _, row := range s.humanItems { + if sources[row.BatchID] { + rows = append(rows, row) + if task, ok := s.annotationTasks[row.LegacyTaskID]; ok { + tasks[task.ID] = task + } + } + } + return resolveAcceptanceSuppliers(org, ids, batches, rows, tasks), nil +} +func (s *MongoStore) ResolveAcceptanceSourceSuppliers(ctx context.Context, org string, ids []string) (map[string]string, error) { + if len(ids) == 0 { + return map[string]string{}, nil + } + batches := map[string]domain.HumanBatchRecord{} + first, err := s.readBatchAccess(ctx, org, ids) + if err != nil { + return nil, err + } + sourceIDs := []string{} + for _, b := range first { + batches[b.ID] = b + if b.SourceBatchID != "" { + sourceIDs = append(sourceIDs, b.SourceBatchID) + } + } + if len(sourceIDs) == 0 { + return resolveAcceptanceSuppliers(org, ids, batches, nil, nil), nil + } + sources, err := s.readBatchAccess(ctx, org, sourceIDs) + if err != nil { + return nil, err + } + for _, b := range sources { + batches[b.ID] = b + } + cur, err := s.humanItems.Find(ctx, organizationScopedFilter(org, bson.M{"batchId": bson.M{"$in": sourceIDs}}), options.Find().SetProjection(bson.M{"_id": 0, "id": 1, "batchId": 1, "organizationId": 1, "projectId": 1, "supplierId": 1, "legacyTaskId": 1})) + if err != nil { + return nil, err + } + rows, err := decodeMany[domain.HumanItemRecord](ctx, cur) + if err != nil { + return nil, err + } + taskIDs := []string{} + for _, row := range rows { + if row.LegacyTaskID != "" { + taskIDs = append(taskIDs, row.LegacyTaskID) + } + } + tasks := map[string]domain.AnnotationTaskRecord{} + if len(taskIDs) > 0 { + cur, err := s.annotationTasks.Find(ctx, organizationScopedFilter(org, bson.M{"id": bson.M{"$in": taskIDs}}), options.Find().SetProjection(bson.M{"_id": 0, "id": 1, "organizationId": 1, "projectId": 1, "supplierId": 1})) + if err != nil { + return nil, err + } + values, err := decodeMany[domain.AnnotationTaskRecord](ctx, cur) + if err != nil { + return nil, err + } + for _, task := range values { + tasks[task.ID] = task + } + } + return resolveAcceptanceSuppliers(org, ids, batches, rows, tasks), nil +} diff --git a/internal/store/acceptance_priority_test.go b/internal/store/acceptance_priority_test.go new file mode 100644 index 00000000..d266f643 --- /dev/null +++ b/internal/store/acceptance_priority_test.go @@ -0,0 +1,113 @@ +package store + +import ( + "context" + "droboticflow/internal/domain" + "fmt" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "os" + "sync" + "sync/atomic" + "testing" + "time" +) + +func acceptancePriorityStoreContract(t *testing.T, s Store) { + t.Helper() + ctx := t.Context() + v := domain.AcceptancePriority{OrganizationID: domain.DefaultOrganizationID, SupplierID: "producer", Enabled: true, ProjectIDs: []string{"p"}, ExpiresAt: time.Now().Add(time.Hour).UTC().Format(time.RFC3339), UpdatedBy: "admin"} + rows, e := s.ListAcceptancePriorities(ctx, v.OrganizationID) + if e != nil || len(rows) != 0 { + t.Fatalf("default %v %v", rows, e) + } + saved, e := s.SaveAcceptancePriority(ctx, v, 0) + if e != nil || saved.Version != 1 || len(saved.History) != 1 { + t.Fatalf("save %+v %v", saved, e) + } + var wins atomic.Int32 + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + copy := v + copy.Enabled = false + if _, err := s.SaveAcceptancePriority(ctx, copy, 1); err == nil { + wins.Add(1) + } else if err != ErrAcceptancePriorityConflict { + t.Errorf("CAS %v", err) + } + }() + } + wg.Wait() + if wins.Load() != 1 { + t.Fatalf("CAS wins %d", wins.Load()) + } + rows, e = s.ListAcceptancePriorities(ctx, v.OrganizationID) + if e != nil || len(rows) != 1 || rows[0].Enabled || rows[0].Version != 2 || len(rows[0].History) != 2 { + t.Fatalf("recovery %+v %v", rows, e) + } + rows[0].History[0].ProjectIDs[0] = "tampered" + rows, e = s.ListAcceptancePriorities(ctx, v.OrganizationID) + if e != nil || rows[0].History[0].ProjectIDs[0] != "p" { + t.Fatal("history mutated") + } + // Ownership remains resolvable after employee deletion; no employee record is consulted. + org := v.OrganizationID + source := domain.HumanBatchRecord{ID: "source", OrganizationID: org, ProjectID: "p"} + acceptance := domain.HumanBatchRecord{ID: "acceptance", OrganizationID: org, ProjectID: "p", SourceBatchID: source.ID} + for _, b := range []domain.HumanBatchRecord{source, acceptance} { + if err := s.UpsertHumanBatch(ctx, b); err != nil { + t.Fatal(err) + } + } + task := domain.AnnotationTaskRecord{ID: "task", OrganizationID: org, ProjectID: "p", SupplierID: "producer"} + if err := s.UpsertAnnotationTask(ctx, task); err != nil { + t.Fatal(err) + } + sourceItem := domain.HumanItemRecord{ID: "source-item", OrganizationID: org, ProjectID: "p", BatchID: source.ID, LegacyTaskID: task.ID, LatestAuthorUserID: "deleted-author", Version: 1} + if err := s.UpsertHumanItem(ctx, sourceItem); err != nil { + t.Fatal(err) + } + owners, err := s.ResolveAcceptanceSourceSuppliers(ctx, org, []string{acceptance.ID, "missing"}) + if err != nil || owners[acceptance.ID] != "producer" || owners["missing"] != "" { + t.Fatalf("ownership %+v %v", owners, err) + } + sourceItem.SupplierID = "conflicting-producer" + sourceItem.Version++ + if err := s.UpsertHumanItem(ctx, sourceItem); err != nil { + t.Fatal(err) + } + owners, err = s.ResolveAcceptanceSourceSuppliers(ctx, org, []string{acceptance.ID}) + if err != nil || owners[acceptance.ID] != "" { + t.Fatalf("conflicting source %+v %v", owners, err) + } + rows, e = s.ListAcceptancePriorities(ctx, "foreign-org") + if e != nil || len(rows) != 0 { + t.Fatal("cross organization policy leak") + } +} +func TestAcceptancePriorityStoreMemory(t *testing.T) { + acceptancePriorityStoreContract(t, NewMemoryStore()) +} +func TestAcceptancePriorityStoreMongo(t *testing.T) { + if os.Getenv("ACCEPTANCE_PRIORITY_LOCAL_MONGO") != "1" { + t.Skip("isolated local Mongo opt-in") + } + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + client, e := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27018")) + if e != nil { + t.Fatal(e) + } + defer client.Disconnect(context.Background()) + db := client.Database(fmt.Sprintf("acceptance_priority_test_%d", time.Now().UnixNano())) + defer db.Drop(context.Background()) + acceptancePriorityStoreContract(t, NewMongoStore(db)) + // New store instance uses persisted cancellation/history, without initialization writes. + rows, e := NewMongoStore(db).ListAcceptancePriorities(ctx, domain.DefaultOrganizationID) + if e != nil || len(rows) != 1 || rows[0].Enabled || rows[0].Version != 2 { + t.Fatal("restart lost policy") + } +} diff --git a/internal/store/memory.go b/internal/store/memory.go index d15a7fdf..2f312401 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -14,6 +14,7 @@ import ( ) type MemoryStore struct { + acceptancePriorities map[string]domain.AcceptancePriority outputSnapshots outputsnapshot.MemoryBackend acceptanceAuthorizations map[string]domain.SupplierAcceptanceAuthorization productionStatsScopes map[string]productionstats.Scope diff --git a/internal/store/store.go b/internal/store/store.go index ab600ea2..58e9c75f 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -247,6 +247,9 @@ type Store interface { SupplierIndexingActive(context.Context, domain.SupplierDeletionPlan) (bool, error) ListSuppliers(context.Context, string) ([]domain.SupplierRecord, error) GetSupplier(context.Context, string) (*domain.SupplierRecord, error) + ResolveAcceptanceSourceSuppliers(context.Context, string, []string) (map[string]string, error) + ListAcceptancePriorities(context.Context, string) ([]domain.AcceptancePriority, error) + SaveAcceptancePriority(context.Context, domain.AcceptancePriority, int) (*domain.AcceptancePriority, error) GetSupplierAcceptanceAuthorization(context.Context, string, string) (*domain.SupplierAcceptanceAuthorization, error) SetSupplierAcceptanceAuthorization(context.Context, string, string, bool, int, string) (*domain.SupplierAcceptanceAuthorization, error) ListReviewCandidates(context.Context, string, string, string, bool, int, int, ...string) ([]domain.HumanItemRecord, error) diff --git a/scripts/verification-scopes.json b/scripts/verification-scopes.json index cbb1ae18..99631aaa 100644 --- a/scripts/verification-scopes.json +++ b/scripts/verification-scopes.json @@ -1,6 +1,89 @@ { "version": 1, "scopes": [ + { + "name": "acceptance-supplier-priority", + "paths": [ + "^internal/(api|domain|store)/acceptance_priority.*\\.go$", + "^src/components/SupplierAcceptancePriorityPanel\\.tsx$", + "^src/pages/Users\\.tsx$", + "^src/lib/review-claim-candidates\\.js$", + "^internal/api/review_continuation\\.go$", + "^internal/store/memory\\.go$", + "^tests/(frontend/acceptance-priority\\.test|browser/acceptance-priority)\\.mjs$", + "^src/services/api/human-loop\\.ts$", + "^internal/api/(routes_human_loop\\.go|testdata/routes\\.golden)$", + "^internal/store/store\\.go$", + "^internal/api/(human_loop|human_pool_reads)\\.go$" + ], + "frontend": [ + "tests/frontend/acceptance-priority.test.mjs", + "tests/frontend/review-random-claim.test.mjs", + "tests/frontend/original-video-time.test.mjs", + "tests/frontend/acceptance-interactions.test.mjs", + "tests/frontend/acceptance-workspace.test.mjs", + "tests/frontend/timeline-viewport.test.mjs" + ], + "go": { + "./internal/api": [ + "^TestAcceptancePriority", + "^TestSharedAcceptance", + "^TestAcceptanceRevocation", + "^TestReviewContinuation", + "^TestRouteSnapshot$", + "^TestHumanPoolCountScan", + "^TestHumanPoolCountsTraversesPages", + "^TestHumanDisplay" + ], + "./internal/store": ["^TestAcceptancePriorityStoreMemory$"] + }, + "task": [ + { + "argv": [ + "go", + "test", + "./internal/store", + "-run", + "^TestAcceptancePriorityStoreMongo$", + "-count=1", + "-timeout=2m", + "-v" + ], + "env": { + "ACCEPTANCE_PRIORITY_LOCAL_MONGO": "1" + }, + "tests": true + }, + { + "argv": [ + "go", + "test", + "./internal/api", + "-run", + "^TestAcceptancePriorityBrowser$", + "-count=1", + "-timeout=3m", + "-v" + ], + "env": { + "ACCEPTANCE_PRIORITY_BROWSER": "1" + }, + "tests": true + }, + { + "argv": ["node", "tests/browser/original-video-time.mjs"], + "tests": true + }, + { + "argv": ["node", "tests/browser/acceptance-timeline-pan.mjs"], + "tests": true + }, + { + "argv": ["node", "tests/browser/acceptance-playback-rate.mjs"], + "tests": true + } + ] + }, { "name": "query-cutover-safety", "paths": [ @@ -965,7 +1048,12 @@ }, { "name": "release-config-guards", - "paths": ["^scripts/release\\.py$", "^tests/release/test_release\\.py$", "^scripts/release-build-api-image\\.sh$", "^tests/release/test_release_build_image\\.py$"], + "paths": [ + "^scripts/release\\.py$", + "^tests/release/test_release\\.py$", + "^scripts/release-build-api-image\\.sh$", + "^tests/release/test_release_build_image\\.py$" + ], "frontend": [], "go": {}, "task": [ diff --git a/src/components/SupplierAcceptancePriorityPanel.tsx b/src/components/SupplierAcceptancePriorityPanel.tsx new file mode 100644 index 00000000..35758ae8 --- /dev/null +++ b/src/components/SupplierAcceptancePriorityPanel.tsx @@ -0,0 +1,153 @@ +import { useEffect, useState } from "react"; +import { projectsApi } from "../services/api/projects"; +import { apiRequest } from "../services/api/client"; +import type { Project } from "../types"; +import { getActionErrorMessage } from "../lib/action-errors.js"; +import { userErrorMessage } from "../lib/user-error-message.js"; + +type Policy = { supplierId: string; enabled: boolean; projectIds: string[] | null; expiresAt: string; version: number }; +type PriorityState = { policy: Policy; active: boolean; remainingCount: number; unresolvedCount: number }; +export function SupplierAcceptancePriorityPanel({ supplierId }: { supplierId: string }) { + const [value, setValue] = useState(null); + const [projects, setProjects] = useState([]); + const [projectIds, setProjectIds] = useState([]); + const [expiresAt, setExpiresAt] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [attempt, setAttempt] = useState(0); + const path = `/api/suppliers/${encodeURIComponent(supplierId)}/acceptance-priority`; + const apply = (next: PriorityState) => { + setValue(next); + setProjectIds(next.policy.projectIds || []); + const date = new Date(next.policy.expiresAt); + setExpiresAt( + Number.isNaN(date.getTime()) + ? "" + : new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16), + ); + }; + useEffect(() => { + let active = true; + setValue(null); + setError(""); + Promise.all([apiRequest(path), projectsApi.list()]) + .then(([next, options]) => { + if (!active) return; + apply(next); + setProjects(options); + }) + .catch((cause) => { + if (active) setError(getActionErrorMessage(cause, "验收优先设置加载失败")); + }); + return () => { + active = false; + }; + }, [path, attempt]); + const save = async (enabled: boolean) => { + if (!value || busy) return; + setBusy(true); + setError(""); + try { + const next = await apiRequest(path, { + method: "PUT", + body: JSON.stringify({ + enabled, + projectIds: enabled ? projectIds : value.policy.projectIds, + expiresAt: enabled ? new Date(expiresAt).toISOString() : value.policy.expiresAt, + version: value.policy.version, + }), + }); + apply(next); + } catch (cause) { + setError(getActionErrorMessage(cause, "验收优先设置保存失败")); + } finally { + setBusy(false); + } + }; + return ( +
+
+

验收优先

+ + {value + ? value.active + ? "生效中" + : value.policy.enabled + ? "已过期" + : "未启用" + : error + ? "加载失败" + : "加载中…"} + +
+ {value && ( + <> +
+ 待领取 {value.remainingCount} + {value.unresolvedCount > 0 && 归属待核对 {value.unresolvedCount}} +
+
+ 适用项目 +
+ + {projects.map((project) => ( + + ))} +
+
+ +
+ + {value.policy.enabled && ( + + )} +
+ + )} + {error && ( +

+ {userErrorMessage(error)}{" "} + +

+ )} +
+ ); +} diff --git a/src/lib/review-claim-candidates.js b/src/lib/review-claim-candidates.js index ca77ba34..f11cf3af 100644 --- a/src/lib/review-claim-candidates.js +++ b/src/lib/review-claim-candidates.js @@ -5,7 +5,13 @@ export async function loadReviewClaimCandidates({ human, filters, isCurrent = () const seen = new Set(); for (let pageIndex = 0; pageIndex < 200; pageIndex++) { if (!isCurrent()) return null; - const page = await human.listItemsPage({ + const readPage = + filters.stageIds?.length === 1 && + filters.stageIds[0] === "prepackage_acceptance" && + human.listAcceptanceClaimCandidates + ? human.listAcceptanceClaimCandidates + : human.listItemsPage; + const page = await readPage({ ...filters, pluginId: "annotation-qa", pool: "available", diff --git a/src/pages/Users.tsx b/src/pages/Users.tsx index f95ce8f1..c885eca1 100644 --- a/src/pages/Users.tsx +++ b/src/pages/Users.tsx @@ -28,6 +28,7 @@ import { getUserRoleLabel, } from "../lib/user-roles"; import { CHINA_MOBILE_PHONE_PATTERN } from "../lib/phone"; +import { SupplierAcceptancePriorityPanel } from "../components/SupplierAcceptancePriorityPanel"; import { SupplierAcceptancePanel } from "../components/SupplierAcceptancePanel"; import type { SupplierAcceptanceAuthorization } from "../services/api/suppliers"; import { SupplierAuthorizationsPanel } from "../components/SupplierAuthorizationsPanel"; @@ -426,6 +427,7 @@ export default function Users() { canManage={currentUser?.role === "admin"} onChange={setAcceptanceAuthorization} /> + {currentUser?.role === "admin" && } )} diff --git a/src/services/api/human-loop.ts b/src/services/api/human-loop.ts index c5fd5300..d5249fba 100644 --- a/src/services/api/human-loop.ts +++ b/src/services/api/human-loop.ts @@ -95,6 +95,8 @@ async function listAcceptancePool(filters: HumanItemFilters, options: { signal?: export const humanLoopApi = { listItems, listItemsPage, + listAcceptanceClaimCandidates: (filters: HumanItemFilters = {}) => + apiRequest(`/api/acceptance-claim-candidates${queryString(filters)}`), listSummariesPage: (filters: HumanItemFilters = {}, options: { signal?: AbortSignal } = {}) => apiRequest<{ summaries: HumanPoolSummary[]; filtersApplied: boolean; hasMore: boolean; nextCursor?: string }>( `/api/human-item-summaries${queryString(filters)}`, diff --git a/tests/browser/acceptance-priority.mjs b/tests/browser/acceptance-priority.mjs new file mode 100644 index 00000000..094b7347 --- /dev/null +++ b/tests/browser/acceptance-priority.mjs @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import { createServer } from "vite"; +import { chromium } from "playwright"; +import { browserExecutableOptions } from "../../scripts/lib/browser-executable.mjs"; +import { closeBrowserFixture } from "../../scripts/lib/browser-test-lifecycle.mjs"; +const out = "local-data/test-results/issue21/browser"; +await fs.mkdir(out, { recursive: true }); +let browser, vite; +try { + vite = await createServer({ + configFile: "tests/browser/vite.platform-feedback.config.ts", + server: { host: "127.0.0.1", port: 0 }, + }); + await vite.listen(); + const base = `http://127.0.0.1:${vite.httpServer.address().port}`; + browser = await chromium.launch({ ...browserExecutableOptions(), headless: true, args: ["--no-proxy-server"] }); + for (const role of ["admin", "supplier_manager"]) { + const page = await browser.newPage({ viewport: { width: 1400, height: 1000 } }); + page.setDefaultTimeout(15000); + let fail = false; + const errors = []; + page.on("pageerror", (e) => { + errors.push(e.message); + console.log("pageerror", e.message); + }); + + await page.route("**/worker-api/**", (route) => route.fulfill({ json: { ready: true, status: "ok" } })); + await page.route("**/api/**", async (route) => { + const request = route.request(), + u = new URL(request.url()); + if (!u.pathname.startsWith("/api/")) return route.continue(); + if (fail && u.pathname.endsWith("/acceptance-priority") && request.method() === "GET") + return route.fulfill({ status: 503, json: { error: "设置暂不可用" } }); + const response = await route.fetch({ + url: process.env.ACCEPTANCE_PRIORITY_API + u.pathname + u.search, + headers: { ...request.headers(), "X-Fixture-Role": role }, + }); + if (u.pathname.endsWith("/acceptance-priority")) console.log("priority-response", await response.text()); + await route.fulfill({ response }); + }); + await page.goto(base + "/users"); + if (role === "supplier_manager") { + await page.getByRole("heading", { name: "账号管理", exact: false }).first().waitFor(); + assert.equal(await page.locator('section[aria-label="验收优先"]').count(), 0); + await page.screenshot({ path: out + "/supplier-manager.png", fullPage: true }); + } else { + await page + .getByRole("button", { name: /^优先供应商/ }) + .first() + .click(); + const panel = page.getByRole("region", { name: "验收优先", exact: true }); + await panel.getByText("未启用", { exact: true }).waitFor(); + const state = await page.evaluate(async () => + (await fetch("/api/suppliers/priority-production/acceptance-priority")).json(), + ); + assert(state.remainingCount > 0); + assert.match(await panel.innerText(), new RegExp(`待领取 ${state.remainingCount}`)); + await panel.getByRole("checkbox", { name: "泛宇草稿项目", exact: true }).check(); + await panel.getByLabel("到期时间").fill("2090-01-01T12:00"); + await panel.getByRole("button", { name: "保存优先设置" }).click(); + await panel.getByText("生效中", { exact: true }).waitFor(); + await page.reload(); + await page + .getByRole("button", { name: /^优先供应商/ }) + .first() + .click(); + await panel.getByText("生效中", { exact: true }).waitFor(); + assert(await panel.getByRole("checkbox", { name: "泛宇草稿项目", exact: true }).isChecked()); + await page.screenshot({ path: out + "/active-light.png", fullPage: true }); + await page.evaluate(() => { + document.documentElement.classList.add("dark"); + }); + await page.screenshot({ path: out + "/active-dark.png", fullPage: true }); + await panel.getByRole("button", { name: "取消优先" }).click(); + await panel.getByText("未启用", { exact: true }).waitFor(); + await page.setViewportSize({ width: 390, height: 844 }); + await page.screenshot({ path: out + "/mobile.png", fullPage: true }); + fail = true; + await page.reload(); + await page + .getByRole("button", { name: /^优先供应商/ }) + .first() + .click(); + await panel.getByRole("alert").waitFor(); + await page.screenshot({ path: out + "/load-error.png", fullPage: true }); + fail = false; + await panel.getByRole("button", { name: "刷新", exact: true }).click(); + await panel.getByText("未启用", { exact: true }).waitFor(); + } + assert.deepEqual(errors, []); + await page.close(); + } + console.log("Admin save/reload/cancel/error-recovery, supplier-manager isolation, light/dark/mobile passed"); +} finally { + await closeBrowserFixture({ browser, vite }); +} diff --git a/tests/frontend/acceptance-priority.test.mjs b/tests/frontend/acceptance-priority.test.mjs new file mode 100644 index 00000000..3c429a00 --- /dev/null +++ b/tests/frontend/acceptance-priority.test.mjs @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { loadReviewClaimCandidates } from "../../src/lib/review-claim-candidates.js"; + +test("acceptance random claim uses server priority candidates, QC keeps its existing endpoint", async () => { + const calls = []; + const human = { + listAcceptanceClaimCandidates: async (q) => { + calls.push(["acceptance", q]); + return { items: [{ id: "priority", canClaim: true }] }; + }, + listItemsPage: async (q) => { + calls.push(["quality", q]); + return { items: [{ id: "quality", canClaim: true }] }; + }, + }; + const acceptance = await loadReviewClaimCandidates({ + human, + filters: { projectId: "p", stageIds: ["prepackage_acceptance"] }, + }); + assert.equal(acceptance[0].id, "priority"); + const quality = await loadReviewClaimCandidates({ human, filters: { stageIds: ["quality_review"] } }); + assert.equal(quality[0].id, "quality"); + assert.deepEqual( + calls.map(([kind]) => kind), + ["acceptance", "quality"], + ); + assert.equal(calls[0][1].projectId, "p"); +}); +test("priority candidates still require server claim eligibility and current selection", async () => { + await assert.rejects( + loadReviewClaimCandidates({ + human: { listAcceptanceClaimCandidates: async () => ({ items: [{ id: "unknown" }] }) }, + filters: { stageIds: ["prepackage_acceptance"] }, + }), + /领取状态/, + ); + let current = true; + const value = await loadReviewClaimCandidates({ + human: { + listAcceptanceClaimCandidates: async () => { + current = false; + return { items: [{ id: "stale", canClaim: true }] }; + }, + }, + filters: { stageIds: ["prepackage_acceptance"] }, + isCurrent: () => current, + }); + assert.equal(value, null); +});