droboticflow/internal/api/annotation_labels_import.go

222 lines
7.6 KiB
Go

package api
import (
"errors"
"fmt"
"net/http"
"sort"
"strings"
"time"
"droboticflow/internal/domain"
"droboticflow/internal/store"
"github.com/go-chi/chi/v5"
)
// dictionaryImportMaxNames bounds one bulk import request; dictionaries are
// maintained in review-sized batches, not migrated wholesale.
const dictionaryImportMaxNames = 1000
type dictionaryImportPayload struct {
Kind string `json:"kind"`
Names []string `json:"names"`
}
type dictionaryImportSkip struct {
Name string `json:"name"`
Reason string `json:"reason"`
}
// handleProjectDictionaryLabelsImport accepts one name per entry, reuses the
// organization's active term when the name already exists (shared terms are
// never renamed or revived from inactive), creates the missing ones, and links
// everything onto this project's selection. Existing selection entries are
// preserved; removals stay on the per-project PUT.
func (server *server) handleProjectDictionaryLabelsImport(writer http.ResponseWriter, request *http.Request) {
principal, _ := currentPrincipal(request)
if !annotationManager(principal) {
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "organization administrator role is required"})
return
}
project, err := server.store.GetProject(request.Context(), chi.URLParam(request, "id"))
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
}
if project == nil {
renderJSON(writer, http.StatusNotFound, map[string]string{"error": "Project not found"})
return
}
if !server.ensureTenantAccess(writer, request, project.OrganizationID, "Project") {
return
}
if project.DeletionTaskID != "" {
renderJSON(writer, http.StatusConflict, map[string]string{"error": "项目正在删除,不能修改字典", "code": "project_deleting"})
return
}
var payload dictionaryImportPayload
if !decodeJSON(writer, request, &payload) {
return
}
kind := dictionaryKind(payload.Kind)
if kind != "action" && kind != "slice" && kind != "discard_reason" {
renderValidationError(writer, validationIssue{Field: "kind", Message: "字典用途必须是 action、slice 或 discard_reason"})
return
}
names := make([]string, 0, len(payload.Names))
seenInput := map[string]bool{}
for _, raw := range payload.Names {
name := strings.Join(strings.Fields(raw), " ")
if name == "" {
continue
}
key := domain.DictionaryNameKey(kind, name)
if seenInput[key] {
continue
}
seenInput[key] = true
names = append(names, name)
}
if len(names) == 0 {
renderValidationError(writer, validationIssue{Field: "names", Message: "导入列表为空,请每行填写一个名称"})
return
}
if len(names) > dictionaryImportMaxNames {
renderValidationError(writer, validationIssue{Field: "names", Message: fmt.Sprintf("单次最多导入 %d 个名称", dictionaryImportMaxNames)})
return
}
ctx := request.Context()
available, err := server.store.ListAnnotationLabels(ctx, project.OrganizationID)
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
}
activeByKey := map[string]domain.AnnotationLabelRecord{}
codeTaken := map[string]bool{}
byID := map[string]domain.AnnotationLabelRecord{}
for _, item := range available {
byID[item.ID] = item
codeTaken[strings.ToLower(item.Code)] = true
if dictionaryKind(item.Kind) == kind && item.Status == domain.AnnotationLabelActive {
activeByKey[domain.DictionaryNameKey(item.Kind, item.Name)] = item
}
}
selection, err := server.store.GetProjectAnnotationLabels(ctx, project.ID)
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
}
if selection == nil {
selection = &domain.ProjectAnnotationLabelsRecord{ID: "project-annotation-labels-" + project.ID, OrganizationID: project.OrganizationID, ProjectID: project.ID, LabelIDs: []string{}}
}
base := selection.LabelIDs
if kind == "slice" {
base = selection.SliceLabelIDs
} else if kind == "discard_reason" {
base = selection.DiscardReasonLabelIDs
}
selectedKeys := map[string]bool{}
nextIDs := make([]string, 0, len(base)+len(names))
for _, id := range base {
if id == "" {
continue
}
nextIDs = append(nextIDs, id)
if item, ok := byID[id]; ok && dictionaryKind(item.Kind) == kind && item.Status == domain.AnnotationLabelActive {
selectedKeys[domain.DictionaryNameKey(item.Kind, item.Name)] = true
}
}
actorID := principal.User.ID
stamp := time.Now().UnixNano()
created, reused := 0, 0
skipped := []dictionaryImportSkip{}
for index, name := range names {
key := domain.DictionaryNameKey(kind, name)
if selectedKeys[key] {
skipped = append(skipped, dictionaryImportSkip{Name: name, Reason: "已在本项目字典中"})
continue
}
if existing, ok := activeByKey[key]; ok {
nextIDs = append(nextIDs, existing.ID)
selectedKeys[key] = true
activeByKey[key] = existing
reused++
continue
}
code := fmt.Sprintf("imp_%s_%d_%03d", kind, stamp, index)
for suffix := 0; codeTaken[code]; suffix++ {
code = fmt.Sprintf("imp_%s_%d_%03d_%d", kind, stamp, index, suffix)
}
input := normalizeAnnotationLabelInput(annotationLabelInput{Kind: kind, Code: code, Name: name, Status: domain.AnnotationLabelActive})
now := nowISO()
item := domain.AnnotationLabelRecord{
Kind: input.Kind, RequiresNote: input.RequiresNote != nil && *input.RequiresNote,
ID: domain.NewID("annotation-label"), OrganizationID: project.OrganizationID,
Code: input.Code, Name: input.Name, Description: input.Description, Status: input.Status, Version: 1,
CreatedByUserID: actorID, UpdatedByUserID: actorID, CreatedAt: now, UpdatedAt: now,
}
item.History = []domain.AnnotationLabelRevision{annotationLabelRevision(item)}
if err := server.store.UpsertAnnotationLabel(ctx, item); err != nil {
if errors.Is(err, store.ErrAnnotationLabelNameConflict) {
// A concurrent import may have created the term; reuse the winner
// instead of failing the whole batch.
latest, listErr := server.store.ListAnnotationLabels(ctx, project.OrganizationID)
if listErr == nil {
for _, candidate := range latest {
if dictionaryKind(candidate.Kind) == kind && candidate.Status == domain.AnnotationLabelActive && domain.DictionaryNameKey(candidate.Kind, candidate.Name) == key {
activeByKey[key] = candidate
break
}
}
}
if existing, ok := activeByKey[key]; ok && existing.ID != item.ID {
nextIDs = append(nextIDs, existing.ID)
selectedKeys[key] = true
reused++
continue
}
}
renderError(writer, http.StatusInternalServerError, err)
return
}
codeTaken[strings.ToLower(item.Code)] = true
activeByKey[key] = item
nextIDs = append(nextIDs, item.ID)
selectedKeys[key] = true
created++
}
sort.Strings(nextIDs)
deduped := nextIDs[:0]
seenID := map[string]bool{}
for _, id := range nextIDs {
if seenID[id] {
continue
}
seenID[id] = true
deduped = append(deduped, id)
}
saved := domain.ProjectAnnotationLabelsRecord{ID: selection.ID, OrganizationID: project.OrganizationID, ProjectID: project.ID, LabelIDs: deduped, UpdatedByUserID: actorID, UpdatedAt: nowISO()}
var saveErr error
if kind == "discard_reason" {
saved.DiscardReasonLabelIDs = deduped
saveErr = server.store.UpsertProjectDiscardReasonLabels(ctx, saved)
} else if kind == "slice" {
saved.SliceLabelIDs = deduped
saveErr = server.store.UpsertProjectSliceLabels(ctx, saved)
} else {
saveErr = server.store.UpsertProjectAnnotationLabels(ctx, saved)
}
if saveErr != nil {
renderError(writer, http.StatusInternalServerError, saveErr)
return
}
renderJSON(writer, http.StatusOK, map[string]any{
"projectId": project.ID, "kind": kind, "labelIds": deduped,
"created": created, "reused": reused, "skipped": skipped,
})
}