forked from longtao.wu/droboticflow
441 lines
16 KiB
Go
441 lines
16 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"sort"
|
|
"strings"
|
|
|
|
"droboticflow/internal/domain"
|
|
"droboticflow/internal/store"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
type annotationLabelInput struct {
|
|
Tags []string `json:"tags"`
|
|
RequiresNote *bool `json:"requiresNote"`
|
|
Kind string `json:"kind"`
|
|
Code string `json:"code"`
|
|
Name string `json:"name"`
|
|
Category string `json:"category"`
|
|
Description string `json:"description"`
|
|
Example string `json:"example"`
|
|
Color string `json:"color"`
|
|
Aliases []string `json:"aliases"`
|
|
Status domain.AnnotationLabelStatus `json:"status"`
|
|
}
|
|
|
|
func dictionaryKind(kind string) string {
|
|
if strings.TrimSpace(kind) == "" {
|
|
return "action"
|
|
}
|
|
return strings.TrimSpace(kind)
|
|
}
|
|
func projectDictionaryKind(request *http.Request) string {
|
|
if strings.HasSuffix(request.URL.Path, "/discard-reason-labels") {
|
|
return "discard_reason"
|
|
}
|
|
if strings.HasSuffix(request.URL.Path, "/slice-labels") {
|
|
return "slice"
|
|
}
|
|
return "action"
|
|
}
|
|
|
|
func annotationLabelRevision(item domain.AnnotationLabelRecord) domain.AnnotationLabelRevision {
|
|
return domain.AnnotationLabelRevision{
|
|
RequiresNote: item.RequiresNote, Version: item.Version, Code: item.Code, Name: item.Name, Category: item.Category,
|
|
Description: item.Description, Example: item.Example, Color: item.Color,
|
|
Tags: append([]string(nil), item.Tags...), Aliases: append([]string(nil), item.Aliases...), Status: item.Status,
|
|
UpdatedByUserID: item.UpdatedByUserID, UpdatedAt: item.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
func normalizeAnnotationLabelInput(input annotationLabelInput) annotationLabelInput {
|
|
input.Kind = dictionaryKind(input.Kind)
|
|
input.Code = strings.TrimSpace(input.Code)
|
|
input.Name = strings.TrimSpace(input.Name)
|
|
if input.Kind == "discard_reason" && input.Name == "其他" {
|
|
required := true
|
|
input.RequiresNote = &required
|
|
}
|
|
input.Category = strings.TrimSpace(input.Category)
|
|
input.Description = strings.TrimSpace(input.Description)
|
|
input.Example = strings.TrimSpace(input.Example)
|
|
input.Color = strings.TrimSpace(input.Color)
|
|
if input.Status == "" {
|
|
input.Status = domain.AnnotationLabelActive
|
|
}
|
|
aliases := make([]string, 0, len(input.Aliases))
|
|
seen := map[string]struct{}{}
|
|
for _, value := range input.Aliases {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" {
|
|
continue
|
|
}
|
|
if _, exists := seen[value]; exists {
|
|
continue
|
|
}
|
|
seen[value] = struct{}{}
|
|
aliases = append(aliases, value)
|
|
}
|
|
|
|
if input.Tags != nil {
|
|
tags := []string{}
|
|
seenTags := map[string]bool{}
|
|
for _, tag := range input.Tags {
|
|
tag = strings.TrimSpace(tag)
|
|
if tag != "" && !seenTags[tag] {
|
|
tags = append(tags, tag)
|
|
seenTags[tag] = true
|
|
}
|
|
}
|
|
input.Tags = tags
|
|
}
|
|
input.Aliases = aliases
|
|
return input
|
|
}
|
|
|
|
func validateAnnotationLabelInput(input annotationLabelInput) []validationIssue {
|
|
issues := make([]validationIssue, 0)
|
|
if dictionaryKind(input.Kind) != "action" && dictionaryKind(input.Kind) != "slice" && dictionaryKind(input.Kind) != "discard_reason" {
|
|
issues = append(issues, validationIssue{Field: "kind", Message: "字典用途必须是 action、slice 或 discard_reason"})
|
|
}
|
|
if input.Code == "" {
|
|
issues = append(issues, validationIssue{Field: "code", Message: "标签编码不能为空"})
|
|
}
|
|
if input.Name == "" {
|
|
issues = append(issues, validationIssue{Field: "name", Message: "标签名称不能为空"})
|
|
}
|
|
if input.Status != domain.AnnotationLabelActive && input.Status != domain.AnnotationLabelInactive {
|
|
issues = append(issues, validationIssue{Field: "status", Message: "标签状态必须是 active 或 inactive"})
|
|
}
|
|
if len(input.Tags) > 32 {
|
|
issues = append(issues, validationIssue{Field: "tags", Message: "每个词条最多 32 个标签"})
|
|
}
|
|
for _, tag := range input.Tags {
|
|
if len([]rune(tag)) > 80 {
|
|
issues = append(issues, validationIssue{Field: "tags", Message: "标签最多 80 字"})
|
|
break
|
|
}
|
|
}
|
|
return issues
|
|
}
|
|
|
|
func (server *server) handleAnnotationLabelsList(writer http.ResponseWriter, request *http.Request) {
|
|
kind := dictionaryKind(request.URL.Query().Get("kind"))
|
|
if kind != "action" && kind != "slice" && kind != "discard_reason" {
|
|
renderValidationError(writer, validationIssue{Field: "kind", Message: "未知字典用途"})
|
|
return
|
|
}
|
|
principal, _ := currentPrincipal(request)
|
|
if kind != "action" && !annotationManager(principal) {
|
|
renderJSON(writer, http.StatusForbidden, map[string]string{"error": "请通过项目字典读取可用词条"})
|
|
return
|
|
}
|
|
items, err := server.store.ListAnnotationLabels(request.Context(), server.requestOrganizationID(request))
|
|
if err != nil {
|
|
renderError(writer, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
filtered := make([]domain.AnnotationLabelRecord, 0, len(items))
|
|
for _, item := range items {
|
|
if dictionaryKind(item.Kind) == kind {
|
|
filtered = append(filtered, item)
|
|
}
|
|
}
|
|
items = filtered
|
|
for index := range items {
|
|
if len(items[index].History) == 0 {
|
|
items[index].History = []domain.AnnotationLabelRevision{annotationLabelRevision(items[index])}
|
|
}
|
|
}
|
|
renderJSON(writer, http.StatusOK, map[string]any{"items": items})
|
|
}
|
|
|
|
func (server *server) handleAnnotationLabelCreate(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
|
|
}
|
|
var payload annotationLabelInput
|
|
if !decodeJSON(writer, request, &payload) {
|
|
return
|
|
}
|
|
payload = normalizeAnnotationLabelInput(payload)
|
|
if issues := validateAnnotationLabelInput(payload); len(issues) > 0 {
|
|
renderValidationError(writer, issues...)
|
|
return
|
|
}
|
|
organizationID := server.requestOrganizationID(request)
|
|
items, err := server.store.ListAnnotationLabels(request.Context(), organizationID)
|
|
if err != nil {
|
|
renderError(writer, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
for _, item := range items {
|
|
if strings.EqualFold(item.Code, payload.Code) {
|
|
renderJSON(writer, http.StatusConflict, map[string]string{"error": "标签编码已存在", "code": "annotation_label_code_conflict"})
|
|
return
|
|
}
|
|
}
|
|
actorID := principal.User.ID
|
|
now := nowISO()
|
|
item := domain.AnnotationLabelRecord{
|
|
Kind: payload.Kind, RequiresNote: payload.RequiresNote != nil && *payload.RequiresNote,
|
|
ID: domain.NewID("annotation-label"), OrganizationID: organizationID,
|
|
Code: payload.Code, Name: payload.Name, Category: payload.Category,
|
|
Description: payload.Description, Example: payload.Example, Color: payload.Color,
|
|
Tags: payload.Tags, Aliases: payload.Aliases, Status: payload.Status, Version: 1,
|
|
CreatedByUserID: actorID, UpdatedByUserID: actorID, CreatedAt: now, UpdatedAt: now,
|
|
}
|
|
item.History = []domain.AnnotationLabelRevision{annotationLabelRevision(item)}
|
|
if err := server.store.UpsertAnnotationLabel(request.Context(), item); err != nil {
|
|
if errors.Is(err, store.ErrAnnotationLabelNameConflict) {
|
|
renderJSON(writer, http.StatusConflict, map[string]string{"error": "本字典中已存在同名词条,请使用已有词条或修改名称", "code": "dictionary_name_conflict"})
|
|
return
|
|
}
|
|
renderError(writer, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
renderJSON(writer, http.StatusCreated, item)
|
|
}
|
|
|
|
func (server *server) handleAnnotationLabelPatch(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
|
|
}
|
|
item, err := server.store.GetAnnotationLabel(request.Context(), chi.URLParam(request, "id"))
|
|
if err != nil {
|
|
renderError(writer, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
if item == nil || !server.ensureTenantAccess(writer, request, item.OrganizationID, "Annotation label") {
|
|
if item == nil {
|
|
renderJSON(writer, http.StatusNotFound, map[string]string{"error": "Annotation label not found"})
|
|
}
|
|
return
|
|
}
|
|
var payload annotationLabelInput
|
|
if !decodeJSON(writer, request, &payload) {
|
|
return
|
|
}
|
|
if payload.Kind == "" {
|
|
payload.Kind = dictionaryKind(item.Kind)
|
|
}
|
|
if dictionaryKind(payload.Kind) != dictionaryKind(item.Kind) {
|
|
renderValidationError(writer, validationIssue{Field: "kind", Message: "不能修改字典用途"})
|
|
return
|
|
}
|
|
payload = normalizeAnnotationLabelInput(payload)
|
|
if payload.Code == "" {
|
|
payload.Code = item.Code
|
|
}
|
|
if payload.Name == "" {
|
|
payload.Name = item.Name
|
|
}
|
|
if issues := validateAnnotationLabelInput(payload); len(issues) > 0 {
|
|
renderValidationError(writer, issues...)
|
|
return
|
|
}
|
|
if payload.RequiresNote != nil {
|
|
item.RequiresNote = *payload.RequiresNote
|
|
}
|
|
item.Code, item.Name, item.Category = payload.Code, payload.Name, payload.Category
|
|
item.Description, item.Example, item.Color = payload.Description, payload.Example, payload.Color
|
|
item.Aliases, item.Status = payload.Aliases, payload.Status
|
|
if payload.Tags != nil {
|
|
item.Tags = payload.Tags
|
|
}
|
|
item.Version++
|
|
item.UpdatedByUserID, item.UpdatedAt = principal.User.ID, nowISO()
|
|
item.History = append(item.History, annotationLabelRevision(*item))
|
|
if len(item.History) > 100 {
|
|
item.History = append([]domain.AnnotationLabelRevision(nil), item.History[len(item.History)-100:]...)
|
|
}
|
|
if err := server.store.UpsertAnnotationLabel(request.Context(), *item); err != nil {
|
|
if errors.Is(err, store.ErrAnnotationLabelNameConflict) {
|
|
renderJSON(writer, http.StatusConflict, map[string]string{"error": "本字典中已存在同名词条,请使用已有词条或修改名称", "code": "dictionary_name_conflict"})
|
|
return
|
|
}
|
|
renderError(writer, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
renderJSON(writer, http.StatusOK, item)
|
|
}
|
|
|
|
func (server *server) handleProjectAnnotationLabelsGet(writer http.ResponseWriter, request *http.Request) {
|
|
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 projectDictionaryKind(request) != "action" && !server.projectVisibleToRequest(request, project.OrganizationID, project.ID) {
|
|
renderJSON(writer, http.StatusNotFound, map[string]string{"error": "Project not found"})
|
|
return
|
|
}
|
|
selection, err := server.store.GetProjectAnnotationLabels(request.Context(), 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{}}
|
|
}
|
|
{
|
|
available, e := server.store.ListAnnotationLabels(request.Context(), project.OrganizationID)
|
|
if e != nil {
|
|
renderError(writer, 500, e)
|
|
return
|
|
}
|
|
ids := selection.LabelIDs
|
|
if projectDictionaryKind(request) == "slice" {
|
|
ids = selection.SliceLabelIDs
|
|
}
|
|
if projectDictionaryKind(request) == "discard_reason" {
|
|
ids = selection.DiscardReasonLabelIDs
|
|
}
|
|
if ids == nil {
|
|
ids = []string{}
|
|
}
|
|
enabled := map[string]bool{}
|
|
for _, id := range ids {
|
|
enabled[id] = true
|
|
}
|
|
items := []domain.AnnotationLabelRecord{}
|
|
for _, label := range available {
|
|
if enabled[label.ID] && dictionaryKind(label.Kind) == projectDictionaryKind(request) && label.Status == domain.AnnotationLabelActive {
|
|
items = append(items, label)
|
|
}
|
|
}
|
|
response := struct {
|
|
domain.ProjectAnnotationLabelsRecord
|
|
Items []domain.AnnotationLabelRecord `json:"items"`
|
|
AllowManual *bool `json:"allowManual,omitempty"`
|
|
}{ProjectAnnotationLabelsRecord: *selection, Items: items}
|
|
response.LabelIDs = ids
|
|
if projectDictionaryKind(request) == "discard_reason" {
|
|
manual := selection.OrganizationID == project.OrganizationID && len(ids) == 0
|
|
response.AllowManual = &manual
|
|
}
|
|
|
|
renderJSON(writer, http.StatusOK, response)
|
|
return
|
|
}
|
|
}
|
|
|
|
func (server *server) handleProjectAnnotationLabelsPut(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 || project == nil {
|
|
if err != nil {
|
|
renderError(writer, http.StatusInternalServerError, err)
|
|
} else {
|
|
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 struct {
|
|
LabelIDs []string `json:"labelIds"`
|
|
}
|
|
if !decodeJSON(writer, request, &payload) {
|
|
return
|
|
}
|
|
available, err := server.store.ListAnnotationLabels(request.Context(), project.OrganizationID)
|
|
if err != nil {
|
|
renderError(writer, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
active := map[string]struct{}{}
|
|
nameKeys := map[string]string{}
|
|
for _, label := range available {
|
|
if label.Status == domain.AnnotationLabelActive && dictionaryKind(label.Kind) == projectDictionaryKind(request) {
|
|
active[label.ID] = struct{}{}
|
|
nameKeys[label.ID] = domain.DictionaryNameKey(label.Kind, label.Name)
|
|
}
|
|
}
|
|
ids := make([]string, 0, len(payload.LabelIDs))
|
|
seen := map[string]struct{}{}
|
|
seenNames := map[string]bool{}
|
|
for _, id := range payload.LabelIDs {
|
|
id = strings.TrimSpace(id)
|
|
if _, ok := active[id]; !ok {
|
|
renderValidationError(writer, validationIssue{Field: "labelIds", Message: "项目只能添加当前组织中的有效词条"})
|
|
return
|
|
}
|
|
if _, exists := seen[id]; exists {
|
|
continue
|
|
}
|
|
if seenNames[nameKeys[id]] {
|
|
renderJSON(writer, http.StatusConflict, map[string]string{"error": "本项目不能添加多个同名词条,请保留其中一个", "code": "dictionary_name_conflict"})
|
|
return
|
|
}
|
|
seenNames[nameKeys[id]] = true
|
|
seen[id] = struct{}{}
|
|
ids = append(ids, id)
|
|
}
|
|
sort.Strings(ids)
|
|
item := domain.ProjectAnnotationLabelsRecord{ID: "project-annotation-labels-" + project.ID, OrganizationID: project.OrganizationID, ProjectID: project.ID, LabelIDs: ids, UpdatedByUserID: principal.User.ID, UpdatedAt: nowISO()}
|
|
var saveErr error
|
|
if projectDictionaryKind(request) == "discard_reason" {
|
|
item.DiscardReasonLabelIDs = ids
|
|
saveErr = server.store.UpsertProjectDiscardReasonLabels(request.Context(), item)
|
|
} else if projectDictionaryKind(request) == "slice" {
|
|
item.SliceLabelIDs = ids
|
|
saveErr = server.store.UpsertProjectSliceLabels(request.Context(), item)
|
|
} else {
|
|
saveErr = server.store.UpsertProjectAnnotationLabels(request.Context(), item)
|
|
}
|
|
if saveErr != nil {
|
|
renderError(writer, http.StatusInternalServerError, saveErr)
|
|
return
|
|
}
|
|
renderJSON(writer, http.StatusOK, item)
|
|
}
|
|
|
|
func (server *server) projectAnnotationLabelDefinitions(ctx context.Context, organizationID, projectID string) ([]domain.SemanticLabelDefinition, error) {
|
|
selection, err := server.store.GetProjectAnnotationLabels(ctx, projectID)
|
|
if err != nil || selection == nil || len(selection.LabelIDs) == 0 {
|
|
return nil, err
|
|
}
|
|
items, err := server.store.ListAnnotationLabels(ctx, organizationID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
byID := make(map[string]domain.AnnotationLabelRecord, len(items))
|
|
for _, item := range items {
|
|
byID[item.ID] = item
|
|
}
|
|
labels := make([]domain.SemanticLabelDefinition, 0, len(selection.LabelIDs))
|
|
for _, id := range selection.LabelIDs {
|
|
item, exists := byID[id]
|
|
if !exists || item.Status != domain.AnnotationLabelActive || dictionaryKind(item.Kind) != "action" {
|
|
continue
|
|
}
|
|
labels = append(labels, domain.SemanticLabelDefinition{Dictionary: item.Selection(), ID: item.Code, Name: item.Name, Description: item.Description, Aliases: item.Aliases, Color: item.Color})
|
|
}
|
|
return labels, nil
|
|
}
|