droboticflow/internal/api/acceptance_priority.go
d-robotics b7f4924110
Some checks are pending
web-ci / checks (pull_request) Blocked by required conditions
web-ci / pool-search-mongo (pull_request) Blocked by required conditions
web-ci / work-availability (pull_request) Blocked by required conditions
web-ci / query-serving (pull_request) Blocked by required conditions
📊 Refresh acceptance priority statistics nightly
(cherry picked from commit fb4f6715bb58c1c512284d0651024ac890e6f896)
2026-11-18 20:29:20 +08:00

329 lines
10 KiB
Go

package api
import (
"context"
"droboticflow/internal/domain"
"droboticflow/internal/store"
"errors"
"fmt"
"github.com/go-chi/chi/v5"
"net/http"
"slices"
"strconv"
"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
}
renderJSON(w, 200, map[string]any{"policy": value, "active": priorityActive(value, ""), "remainingCount": nil, "unresolvedCount": nil, "statisticsStatus": "not_requested"})
}
// Statistics are optional display data. Neither reading nor saving a policy
// waits for this work; no partial count is ever serialized as an exact zero.
const acceptancePriorityStatisticsBudget = 2 * time.Second
func (s *server) handleAcceptancePriorityStatistics(w http.ResponseWriter, r *http.Request) {
principal, ok := currentPrincipal(r)
if !ok || !isOrganizationAdmin(principal) {
renderJSON(w, 403, map[string]string{"error": "仅管理员可查看验收优先统计"})
return
}
expected, err := strconv.Atoi(r.URL.Query().Get("version"))
if err != nil || expected < 0 {
renderJSON(w, 400, map[string]string{"error": "统计版本无效"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), acceptancePriorityStatisticsBudget)
defer cancel()
r = r.WithContext(ctx)
incomplete := func() {
renderJSON(w, 200, map[string]any{"status": "incomplete", "policyVersion": expected, "remainingCount": nil, "unresolvedCount": nil})
}
org := s.requestOrganizationID(r)
id := chi.URLParam(r, "supplierId")
supplier, err := s.store.GetSupplier(ctx, id)
if err != nil {
incomplete()
return
}
if supplier == nil || supplier.OrganizationID != org {
renderJSON(w, 404, map[string]string{"error": "供应商不存在"})
return
}
snapshot, err := s.store.ReadAcceptanceSnapshot(ctx, org)
if err != nil {
incomplete()
return
}
rules, err := s.store.ListAcceptancePriorities(ctx, org)
if err != nil {
incomplete()
return
}
var policy domain.AcceptancePriority
for _, rule := range rules {
if rule.SupplierID == id {
policy = rule
break
}
}
if policy.Version != expected {
incomplete()
return
}
if snapshot == nil {
renderJSON(w, 200, map[string]any{"status": "pending", "policyVersion": expected, "remainingCount": nil, "unresolvedCount": nil})
return
}
remaining, unresolved := 0, 0
for _, group := range snapshot.Counts {
if len(policy.ProjectIDs) > 0 && !slices.Contains(policy.ProjectIDs, group.ProjectID) {
continue
}
switch group.SupplierID {
case "":
unresolved += group.Count
case id:
remaining += group.Count
}
}
renderJSON(w, 200, map[string]any{"status": "completed", "policyVersion": expected, "remainingCount": remaining, "unresolvedCount": unresolved, "completedAt": snapshot.CompletedAt})
}
// 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
}