353 lines
13 KiB
Go
353 lines
13 KiB
Go
package run
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"sort"
|
|
"strconv"
|
|
"time"
|
|
|
|
"git.iwork-ai.com/xdc/iqudo-top1/internal/access"
|
|
"git.iwork-ai.com/xdc/iqudo-top1/internal/audit"
|
|
"git.iwork-ai.com/xdc/iqudo-top1/internal/auth"
|
|
"git.iwork-ai.com/xdc/iqudo-top1/internal/model"
|
|
"git.iwork-ai.com/xdc/iqudo-top1/internal/response"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/datatypes"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
type Handler struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewHandler(db *gorm.DB) *Handler {
|
|
return &Handler{db: db}
|
|
}
|
|
|
|
func (h *Handler) PublishedSOPs(c *gin.Context) {
|
|
p, _ := auth.PrincipalFromContext(c)
|
|
type item struct {
|
|
ID uint64 `json:"id"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
ScenarioID uint64 `json:"scenario_id"`
|
|
ScenarioName string `json:"scenario_name"`
|
|
Version int `json:"version"`
|
|
}
|
|
items := make([]item, 0)
|
|
query := h.db.Table("sops s").Select("s.id, s.name, s.description, s.scenario_id, sc.name AS scenario_name, sv.version").Joins("JOIN scenarios sc ON sc.id = s.scenario_id").Joins("JOIN sop_versions sv ON sv.sop_id = s.id AND sv.status = ?", "published")
|
|
query = access.ScopeScenarios(query, p, "sc")
|
|
err := query.Where("s.tenant_id = ? AND s.status = ?", p.TenantID, "published").Order("s.updated_at DESC").Scan(&items).Error
|
|
if err != nil {
|
|
response.Error(c, http.StatusInternalServerError, "QUERY_FAILED", "查询可执行 SOP 失败")
|
|
return
|
|
}
|
|
response.OK(c, gin.H{"items": items, "total": len(items)})
|
|
}
|
|
|
|
func (h *Handler) Start(c *gin.Context) {
|
|
p, _ := auth.PrincipalFromContext(c)
|
|
var input struct {
|
|
SOPID uint64 `json:"sop_id" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
response.Error(c, http.StatusBadRequest, "INVALID_ARGUMENT", "请选择要执行的 SOP")
|
|
return
|
|
}
|
|
if !access.CanViewSOP(h.db, p, input.SOPID) {
|
|
response.Error(c, http.StatusNotFound, "NOT_FOUND", "没有可执行的已发布 SOP")
|
|
return
|
|
}
|
|
var version model.SOPVersion
|
|
if err := h.db.Where("sop_id = ? AND tenant_id = ? AND status = ?", input.SOPID, p.TenantID, "published").Order("version DESC").First(&version).Error; err != nil {
|
|
response.Error(c, http.StatusNotFound, "NOT_FOUND", "没有可执行的已发布版本")
|
|
return
|
|
}
|
|
run := model.SOPRun{TenantID: p.TenantID, SOPID: input.SOPID, SOPVersionID: version.ID, OperatorID: p.UserID, CurrentNodeKey: version.StartNodeKey, Status: "running", Answers: datatypes.JSON([]byte(`{}`)), Result: "", StartedAt: time.Now()}
|
|
err := h.db.Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Create(&run).Error; err != nil {
|
|
return err
|
|
}
|
|
return tx.Create(&model.SOPRunEvent{TenantID: p.TenantID, RunID: run.ID, NodeKey: run.CurrentNodeKey, Action: "start", Payload: datatypes.JSON([]byte(`{}`))}).Error
|
|
})
|
|
if err != nil {
|
|
response.Error(c, http.StatusInternalServerError, "START_FAILED", "启动 SOP 失败")
|
|
return
|
|
}
|
|
_ = audit.Record(h.db, p, "start", "sop_run", run.ID, gin.H{"sop_id": input.SOPID})
|
|
h.respondRun(c, run)
|
|
}
|
|
|
|
func (h *Handler) Get(c *gin.Context) {
|
|
p, _ := auth.PrincipalFromContext(c)
|
|
id, ok := runID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
var item model.SOPRun
|
|
if err := h.db.Where("id = ? AND tenant_id = ?", id, p.TenantID).First(&item).Error; err != nil {
|
|
response.Error(c, http.StatusNotFound, "NOT_FOUND", "执行记录不存在")
|
|
return
|
|
}
|
|
if !canViewRun(p, item) {
|
|
response.Error(c, http.StatusNotFound, "NOT_FOUND", "执行记录不存在")
|
|
return
|
|
}
|
|
h.respondRun(c, item)
|
|
}
|
|
|
|
func (h *Handler) List(c *gin.Context) {
|
|
p, _ := auth.PrincipalFromContext(c)
|
|
type row struct {
|
|
model.SOPRun
|
|
SOPName string `json:"sop_name"`
|
|
}
|
|
page, pageSize := pagination(c)
|
|
query := scopeRuns(h.db.Table("sop_runs r").Joins("JOIN sops s ON s.id = r.sop_id"), p, "r")
|
|
if status := c.Query("status"); status != "" {
|
|
query = query.Where("r.status = ?", status)
|
|
}
|
|
if result := c.Query("result"); result != "" {
|
|
query = query.Where("r.result = ?", result)
|
|
}
|
|
if sopID := c.Query("sop_id"); sopID != "" {
|
|
query = query.Where("r.sop_id = ?", sopID)
|
|
}
|
|
if startedFrom := c.Query("started_from"); startedFrom != "" {
|
|
query = query.Where("r.started_at >= ?", startedFrom)
|
|
}
|
|
if startedTo := c.Query("started_to"); startedTo != "" {
|
|
query = query.Where("r.started_at <= ?", startedTo)
|
|
}
|
|
var total int64
|
|
if err := query.Count(&total).Error; err != nil {
|
|
response.Error(c, http.StatusInternalServerError, "QUERY_FAILED", "查询执行记录失败")
|
|
return
|
|
}
|
|
items := make([]row, 0)
|
|
if err := query.Select("r.*, s.name AS sop_name").Order("r.created_at DESC").Offset((page - 1) * pageSize).Limit(pageSize).Scan(&items).Error; err != nil {
|
|
response.Error(c, http.StatusInternalServerError, "QUERY_FAILED", "查询执行记录失败")
|
|
return
|
|
}
|
|
response.OK(c, gin.H{"items": items, "total": total, "page": page, "page_size": pageSize})
|
|
}
|
|
|
|
func (h *Handler) Answer(c *gin.Context) {
|
|
p, _ := auth.PrincipalFromContext(c)
|
|
id, ok := runID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
var input struct {
|
|
NodeKey string `json:"node_key"`
|
|
Answers map[string]interface{} `json:"answers"`
|
|
}
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
response.Error(c, http.StatusBadRequest, "INVALID_ARGUMENT", "回答格式不正确")
|
|
return
|
|
}
|
|
var updated model.SOPRun
|
|
err := h.db.Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ? AND tenant_id = ?", id, p.TenantID).First(&updated).Error; err != nil {
|
|
return err
|
|
}
|
|
if updated.Status != "running" {
|
|
return errors.New("run is not active")
|
|
}
|
|
if !canOperateRun(p, updated) {
|
|
return gorm.ErrRecordNotFound
|
|
}
|
|
if input.NodeKey != "" && input.NodeKey != updated.CurrentNodeKey {
|
|
return errors.New("当前步骤已经变化,请刷新后重试")
|
|
}
|
|
var currentNode model.SOPNode
|
|
if err := tx.Where("sop_version_id = ? AND node_key = ? AND tenant_id = ?", updated.SOPVersionID, updated.CurrentNodeKey, p.TenantID).First(¤tNode).Error; err != nil {
|
|
return err
|
|
}
|
|
fields := make([]model.ScenarioField, 0)
|
|
if err := tx.Table("scenario_fields sf").Joins("JOIN sops s ON s.scenario_id = sf.scenario_id").Where("s.id = ? AND sf.tenant_id = ?", updated.SOPID, p.TenantID).Order("sf.sort_order, sf.id").Find(&fields).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := validateNodeAnswers(currentNode, fields, input.Answers); err != nil {
|
|
return err
|
|
}
|
|
answers := map[string]interface{}{}
|
|
if len(updated.Answers) > 0 {
|
|
_ = json.Unmarshal(updated.Answers, &answers)
|
|
}
|
|
for key, value := range input.Answers {
|
|
answers[key] = value
|
|
}
|
|
var edges []model.SOPEdge
|
|
if err := tx.Where("sop_version_id = ? AND source_node_key = ?", updated.SOPVersionID, updated.CurrentNodeKey).Order("priority, id").Find(&edges).Error; err != nil {
|
|
return err
|
|
}
|
|
sort.SliceStable(edges, func(i, j int) bool { return edges[i].Priority < edges[j].Priority })
|
|
nextKey := ""
|
|
for _, edge := range edges {
|
|
matched, matchErr := matchCondition(json.RawMessage(edge.Condition), answers)
|
|
if matchErr != nil {
|
|
return matchErr
|
|
}
|
|
if matched {
|
|
nextKey = edge.TargetNodeKey
|
|
break
|
|
}
|
|
}
|
|
if nextKey == "" {
|
|
return errors.New("没有满足条件的下一节点")
|
|
}
|
|
answerBytes, _ := json.Marshal(answers)
|
|
payload, _ := json.Marshal(input)
|
|
if err := tx.Create(&model.SOPRunEvent{TenantID: p.TenantID, RunID: updated.ID, NodeKey: updated.CurrentNodeKey, Action: "answer", Payload: datatypes.JSON(payload)}).Error; err != nil {
|
|
return err
|
|
}
|
|
var next model.SOPNode
|
|
if err := tx.Where("sop_version_id = ? AND node_key = ?", updated.SOPVersionID, nextKey).First(&next).Error; err != nil {
|
|
return err
|
|
}
|
|
updates := map[string]interface{}{"current_node_key": nextKey, "answers": datatypes.JSON(answerBytes)}
|
|
if next.Type == "finish" || next.Type == "escalate" {
|
|
now := time.Now()
|
|
updates["status"] = "completed"
|
|
updates["completed_at"] = &now
|
|
updates["result"] = next.Type
|
|
updated.Status = "completed"
|
|
updated.CompletedAt = &now
|
|
updated.Result = next.Type
|
|
}
|
|
if err := tx.Model(&updated).Updates(updates).Error; err != nil {
|
|
return err
|
|
}
|
|
updated.CurrentNodeKey = nextKey
|
|
updated.Answers = datatypes.JSON(answerBytes)
|
|
return tx.Create(&model.SOPRunEvent{TenantID: p.TenantID, RunID: updated.ID, NodeKey: nextKey, Action: "enter", Payload: datatypes.JSON([]byte(`{}`))}).Error
|
|
})
|
|
if err != nil {
|
|
response.Error(c, http.StatusUnprocessableEntity, "ADVANCE_FAILED", err.Error())
|
|
return
|
|
}
|
|
h.respondRun(c, updated)
|
|
}
|
|
|
|
func (h *Handler) Finish(c *gin.Context) {
|
|
p, _ := auth.PrincipalFromContext(c)
|
|
id, ok := runID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
var input struct {
|
|
Result string `json:"result" binding:"required,max=64"`
|
|
}
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
response.Error(c, http.StatusBadRequest, "INVALID_ARGUMENT", "请选择执行结果")
|
|
return
|
|
}
|
|
var run model.SOPRun
|
|
if err := h.db.Where("id = ? AND tenant_id = ?", id, p.TenantID).First(&run).Error; err != nil || !canOperateRun(p, run) {
|
|
response.Error(c, http.StatusNotFound, "NOT_FOUND", "执行记录不存在")
|
|
return
|
|
}
|
|
if run.Status != "running" {
|
|
response.Error(c, http.StatusConflict, "RUN_COMPLETED", "执行记录已经结束")
|
|
return
|
|
}
|
|
now := time.Now()
|
|
result := h.db.Model(&model.SOPRun{}).Where("id = ? AND tenant_id = ? AND status = ?", id, p.TenantID, "running").Updates(map[string]interface{}{"status": "completed", "result": input.Result, "completed_at": &now})
|
|
if result.Error != nil || result.RowsAffected == 0 {
|
|
response.Error(c, http.StatusNotFound, "NOT_FOUND", "执行记录不存在")
|
|
return
|
|
}
|
|
_ = audit.Record(h.db, p, "finish", "sop_run", id, input)
|
|
h.Get(c)
|
|
}
|
|
|
|
func (h *Handler) Feedback(c *gin.Context) {
|
|
p, _ := auth.PrincipalFromContext(c)
|
|
id, ok := runID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
var input struct {
|
|
Score int `json:"score" binding:"required,min=1,max=5"`
|
|
Comment string `json:"comment" binding:"max=2000"`
|
|
}
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
response.Error(c, http.StatusBadRequest, "INVALID_ARGUMENT", "反馈内容不正确")
|
|
return
|
|
}
|
|
var run model.SOPRun
|
|
if err := h.db.Where("id = ? AND tenant_id = ?", id, p.TenantID).First(&run).Error; err != nil || !canViewRun(p, run) {
|
|
response.Error(c, http.StatusNotFound, "NOT_FOUND", "执行记录不存在")
|
|
return
|
|
}
|
|
if run.Status != "completed" {
|
|
response.Error(c, http.StatusConflict, "RUN_NOT_COMPLETED", "执行完成后才能提交反馈")
|
|
return
|
|
}
|
|
item := model.SOPFeedback{TenantID: p.TenantID, RunID: id, UserID: p.UserID, Score: input.Score, Comment: input.Comment}
|
|
if err := h.db.Create(&item).Error; err != nil {
|
|
response.Error(c, http.StatusConflict, "FEEDBACK_EXISTS", "该执行记录已经提交反馈")
|
|
return
|
|
}
|
|
_ = audit.Record(h.db, p, "feedback", "sop_run", id, gin.H{"score": input.Score})
|
|
response.Created(c, item)
|
|
}
|
|
|
|
func (h *Handler) respondRun(c *gin.Context, item model.SOPRun) {
|
|
var node model.SOPNode
|
|
if err := h.db.Where("sop_version_id = ? AND node_key = ?", item.SOPVersionID, item.CurrentNodeKey).First(&node).Error; err != nil {
|
|
response.Error(c, http.StatusInternalServerError, "NODE_NOT_FOUND", "当前流程节点不存在")
|
|
return
|
|
}
|
|
fields := make([]model.ScenarioField, 0)
|
|
h.db.Table("scenario_fields sf").Joins("JOIN sops s ON s.scenario_id = sf.scenario_id").Where("s.id = ? AND sf.tenant_id = ?", item.SOPID, item.TenantID).Order("sf.sort_order, sf.id").Find(&fields)
|
|
response.OK(c, gin.H{"run": item, "node": node, "fields": fields})
|
|
}
|
|
|
|
func runID(c *gin.Context) (uint64, bool) {
|
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
response.Error(c, http.StatusBadRequest, "INVALID_ID", "执行记录 ID 不正确")
|
|
return 0, false
|
|
}
|
|
return id, true
|
|
}
|
|
|
|
func scopeRuns(query *gorm.DB, principal auth.Principal, alias string) *gorm.DB {
|
|
query = query.Where(alias+".tenant_id = ?", principal.TenantID)
|
|
if auth.HasPermission(principal, "runs.view_all") || auth.HasPermission(principal, "*") {
|
|
return query
|
|
}
|
|
return query.Where(alias+".operator_id = ?", principal.UserID)
|
|
}
|
|
|
|
func canViewRun(principal auth.Principal, run model.SOPRun) bool {
|
|
if run.TenantID != principal.TenantID {
|
|
return false
|
|
}
|
|
return run.OperatorID == principal.UserID || auth.HasPermission(principal, "runs.view_all") || auth.HasPermission(principal, "*")
|
|
}
|
|
|
|
func canOperateRun(principal auth.Principal, run model.SOPRun) bool {
|
|
return run.TenantID == principal.TenantID && (run.OperatorID == principal.UserID || auth.HasPermission(principal, "*"))
|
|
}
|
|
|
|
func pagination(c *gin.Context) (int, int) {
|
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
|
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if pageSize < 1 {
|
|
pageSize = 20
|
|
}
|
|
if pageSize > 100 {
|
|
pageSize = 100
|
|
}
|
|
return page, pageSize
|
|
}
|