refactor: 后端仓库层收口(A4:任务/项目/笔记/专员/动作定义)

把 B 档(此前尚无仓库的对象)的 api 裸查询收进仓库,api 层裸 store.DB
从 162 降到 96(口径:internal/ 下非测试 .go,不含 internal/repository/ 自身)。
新增 7 个仓库:TaskRecordRepo / TaskArtifactRepo / TaskRunRepo / ProjectRepo /
StudyNoteRepo / SpecialistRepo / ActionDefinitionRepo。

按对象补齐的方法:
- TaskRecordRepo:GetByID / GetByIDForOwners / ListBySpecialistKey / ListByOwners /
  ListByProject / CountBySpecialistKey / ClearProject / DeleteCascade
- ProjectRepo:GetByIDForOwners / ListByOwners
- StudyNoteRepo:ListByUser / GetByID
- SpecialistRepo:GetByKey / GetByID / Query / List / CountByKey
- TaskArtifactRepo / TaskRunRepo:GetByID / ListByTask
- ActionDefinitionRepo:List / GetByID / GetByKey

几条口径改由仓库单点持有,避免各处手写漂移:
- 归属过滤抽成 ownerScope:owners 为空时套恒假条件(空集),绝不退化成全表。
  specialists/runtime 的 MyTaskQuery / ProjectQuery 随之删除,调用方改用
  MyTaskOwners + 仓库方法 —— 任务与项目共用同一套归属口径。
- 「任务 + 交付物 + 运行记录三张表同事务级联删除」从 handler 收进 DeleteCascade,
  不留没有任务的孤儿交付物;删项目只解除其下任务的 project_id 归属(置 NULL,
  不是 0),不删任务本身 —— 任务是「做过的事」,删一个分组不该把它一起抹掉。
- 专员目录的 state 档位(默认 active / all 仅管理员 / system / 其它精确匹配,
  且除显式要 system 外一律排除 system 记录)收进 SpecialistRepo.List。
- GetByKey 有意不过滤 state:调用方口径不同(建任务时要能查到,对话取 prompt
  时要拒绝 inactive),口径留在调用方,仓库只负责取数。顺带把「按 key 找专员」
  从 4 个文件里各写一遍收敛成一处。
- ActionDefinitionRepo.List 不替调用方定 state 默认值 ——「不传 state 就只看
  active」是列表接口的契约,由 handler 解析 query 后传入。
- StudyNoteRepo.GetByID 不判归属,越权检查留在 handler(那里能把「不存在」与
  「不是你的」分别回成 404 / 403)。

保留未动:skills/api/office_handlers.go 里两处 store.DB.Transaction —— 运行记录
与交付物要在同一个事务里落库,QueryBuilder 不带事务,维持原样并就地注明。

验证:go build ./... 与 go vet ./... 干净,go test ./... 6 个包全绿。
另用独立验证程序走真实路由 + 真实 HTTP,对数据库副本跑 148 项断言全绿
(覆盖跨用户越权 404、空 owners 退化成空集、级联删除、解除归属置 NULL、
笔记按用户隔离、专员 key 唯一性排除自身、管理员 state=all 仍排除 system 等)。

另对其中 10 条关键语义做了变异测试:逐条注入反向实现,确认断言确实会失败,
捕获 10 / 漏掉 0。变异测试同时暴露并修掉了验证体系自身的两个漏洞:
- 「state=all 排除 system」这条规则此前没有任何断言能观察到 —— 默认档被
  state=active 挡着、system 档被 state=system 挡着,删掉实现也不会红;
- 变异驱动只跑 HTTP 断言、不跑 go test,导致针对单元测试注入的变异
  (拒绝已下线专员的 prompt)永远逮不到。

验证程序为一次性脚手架,验证完成后已删除(tmp_vfy_b/)。
原始 data/eai_agentplatform.db 全程未触碰(mtime 仍为 2026-09-17 15:14)。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
eaiadmin
2026-09-19 01:55:26 +08:00
co-authored by Claude Code
parent 19cf6fb5f2
commit 4f31e0c438
18 changed files with 669 additions and 268 deletions
@@ -7,10 +7,17 @@ import (
"eai_agentplatform/backend/internal/jsonutil" "eai_agentplatform/backend/internal/jsonutil"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
"eai_agentplatform/backend/internal/store" "eai_agentplatform/backend/internal/repository"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
// actionDefinitionRepo 动作定义仓库(便于测试时覆写),包内共享。
var actionDefinitionRepo repository.ActionDefinitionRepo
func init() {
actionDefinitionRepo = repository.ActionDefinitionRepo{}
}
type actionDefinitionReq struct { type actionDefinitionReq struct {
Key string `json:"key"` Key string `json:"key"`
Label string `json:"label"` Label string `json:"label"`
@@ -79,18 +86,12 @@ func validateActionDefinitionReq(req *actionDefinitionReq) *web.AppError {
} }
func ListActionDefinitions(c *gin.Context) { func ListActionDefinitions(c *gin.Context) {
q := store.DB.Model(&model.ActionDefinition{}) // 不传 state 默认只看 active —— 这是列表接口的契约,放在这里解析。
if c.Query("state") == "" { state := c.Query("state")
q = q.Where("state = ?", "active") if state == "" {
} else { state = "active"
q = q.Where("state = ?", c.Query("state"))
} }
var items []model.ActionDefinition web.OK(c, actionDefinitionRepo.List(state))
if err := q.Order("sort_order ASC, id ASC").Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询 Action 定义失败"))
return
}
web.OK(c, items)
} }
func GetActionDefinitionByKey(c *gin.Context) { func GetActionDefinitionByKey(c *gin.Context) {
@@ -99,8 +100,8 @@ func GetActionDefinitionByKey(c *gin.Context) {
web.Fail(c, web.NewBadRequest("action key 不能为空")) web.Fail(c, web.NewBadRequest("action key 不能为空"))
return return
} }
var item model.ActionDefinition item, found := actionDefinitionRepo.GetByKey(key)
if err := store.DB.Where("key = ?", key).First(&item).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("Action 定义不存在")) web.Fail(c, web.NewNotFoundError("Action 定义不存在"))
return return
} }
@@ -133,7 +134,7 @@ func CreateActionDefinition(c *gin.Context) {
State: req.State, State: req.State,
SortOrder: req.SortOrder, SortOrder: req.SortOrder,
} }
if err := store.DB.Create(&item).Error; err != nil { if !actionDefinitionRepo.Insert(&item) {
web.Fail(c, web.NewBadRequest("创建 Action 定义失败")) web.Fail(c, web.NewBadRequest("创建 Action 定义失败"))
return return
} }
@@ -145,8 +146,8 @@ func UpdateActionDefinition(c *gin.Context) {
if !ok { if !ok {
return return
} }
var item model.ActionDefinition item, found := actionDefinitionRepo.GetByID(id)
if err := store.DB.First(&item, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("Action 定义不存在")) web.Fail(c, web.NewNotFoundError("Action 定义不存在"))
return return
} }
@@ -173,7 +174,7 @@ func UpdateActionDefinition(c *gin.Context) {
item.OntologyBindingJSON = req.OntologyBindingJSON item.OntologyBindingJSON = req.OntologyBindingJSON
item.State = req.State item.State = req.State
item.SortOrder = req.SortOrder item.SortOrder = req.SortOrder
if err := store.DB.Save(&item).Error; err != nil { if !actionDefinitionRepo.Update(&item) {
web.Fail(c, web.NewBadRequest("更新 Action 定义失败")) web.Fail(c, web.NewBadRequest("更新 Action 定义失败"))
return return
} }
@@ -185,12 +186,12 @@ func DeleteActionDefinition(c *gin.Context) {
if !ok { if !ok {
return return
} }
var item model.ActionDefinition item, found := actionDefinitionRepo.GetByID(id)
if err := store.DB.First(&item, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("Action 定义不存在")) web.Fail(c, web.NewNotFoundError("Action 定义不存在"))
return return
} }
if err := store.DB.Delete(&item).Error; err != nil { if !actionDefinitionRepo.Delete(&item) {
web.Fail(c, web.NewBadRequest("删除 Action 定义失败")) web.Fail(c, web.NewBadRequest("删除 Action 定义失败"))
return return
} }
@@ -9,9 +9,7 @@ import (
"eai_agentplatform/backend/internal/middleware" "eai_agentplatform/backend/internal/middleware"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
specialistmodel "eai_agentplatform/backend/internal/specialists/model"
specialistruntime "eai_agentplatform/backend/internal/specialists/runtime" specialistruntime "eai_agentplatform/backend/internal/specialists/runtime"
"eai_agentplatform/backend/internal/store"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
@@ -39,16 +37,8 @@ func ListMyTasks(c *gin.Context) {
return return
} }
var items []model.TaskRecord // 置顶的排在前面,其余按最近动过的排 —— 置顶只是一个排序偏好。
if err := specialistruntime.MyTaskQuery(user). web.OK(c, taskRecordRepo.ListByOwners(specialistruntime.MyTaskOwners(user), 50))
// 置顶的排在前面,其余按最近动过的排 —— 置顶只是一个排序偏好。
Order("pinned DESC, updated_at DESC, id DESC").
Limit(50).
Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询我的任务失败"))
return
}
web.OK(c, items)
} }
// DeleteMyTask 彻底删掉一条任务。task_record 没有软删字段,删了就是删了 —— // DeleteMyTask 彻底删掉一条任务。task_record 没有软删字段,删了就是删了 ——
@@ -64,12 +54,12 @@ func DeleteMyTask(c *gin.Context) {
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByIDForOwners(id, specialistruntime.MyTaskOwners(user))
if err := specialistruntime.MyTaskQuery(user).Where("id = ?", id).First(&task).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("任务不存在")) web.Fail(c, web.NewNotFoundError("任务不存在"))
return return
} }
if err := store.DB.Delete(&task).Error; err != nil { if !taskRecordRepo.Delete(&task) {
web.Fail(c, web.NewBadRequest("删除任务失败")) web.Fail(c, web.NewBadRequest("删除任务失败"))
return return
} }
@@ -95,8 +85,8 @@ func CreateMyTask(c *gin.Context) {
if specialistKey == "" { if specialistKey == "" {
specialistKey = generalAssistantKey specialistKey = generalAssistantKey
} }
var specialist specialistmodel.Specialist specialist, found := specialistRepo.GetByKey(specialistKey)
if err := store.DB.Where("key = ?", specialistKey).First(&specialist).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("专员不存在")) web.Fail(c, web.NewNotFoundError("专员不存在"))
return return
} }
@@ -123,7 +113,7 @@ func CreateMyTask(c *gin.Context) {
task.Status = "待处理" task.Status = "待处理"
} }
if err := store.DB.Create(&task).Error; err != nil { if !taskRecordRepo.Insert(&task) {
web.Fail(c, web.NewBadRequest("创建任务失败")) web.Fail(c, web.NewBadRequest("创建任务失败"))
return return
} }
@@ -142,8 +132,9 @@ func UpdateMyTask(c *gin.Context) {
return return
} }
var task model.TaskRecord owners := specialistruntime.MyTaskOwners(user)
if err := specialistruntime.MyTaskQuery(user).Where("id = ?", id).First(&task).Error; err != nil { task, found := taskRecordRepo.GetByIDForOwners(id, owners)
if !found {
web.Fail(c, web.NewNotFoundError("任务不存在")) web.Fail(c, web.NewNotFoundError("任务不存在"))
return return
} }
@@ -158,8 +149,8 @@ func UpdateMyTask(c *gin.Context) {
task.Title = title task.Title = title
} }
if key := strings.TrimSpace(req.SpecialistKey); key != "" && key != task.SpecialistKey { if key := strings.TrimSpace(req.SpecialistKey); key != "" && key != task.SpecialistKey {
var specialist specialistmodel.Specialist specialist, ok := specialistRepo.GetByKey(key)
if err := store.DB.Where("key = ?", key).First(&specialist).Error; err != nil { if !ok {
web.Fail(c, web.NewNotFoundError("目标专员不存在")) web.Fail(c, web.NewNotFoundError("目标专员不存在"))
return return
} }
@@ -173,8 +164,8 @@ func UpdateMyTask(c *gin.Context) {
if *req.ProjectID == 0 { if *req.ProjectID == 0 {
task.ProjectID = nil task.ProjectID = nil
} else { } else {
var project model.Project project, ok := projectRepo.GetByIDForOwners(*req.ProjectID, owners)
if err := specialistruntime.ProjectQuery(user).Where("id = ?", *req.ProjectID).First(&project).Error; err != nil { if !ok {
web.Fail(c, web.NewNotFoundError("项目不存在")) web.Fail(c, web.NewNotFoundError("项目不存在"))
return return
} }
@@ -185,7 +176,7 @@ func UpdateMyTask(c *gin.Context) {
task.Pinned = *req.Pinned task.Pinned = *req.Pinned
} }
if err := store.DB.Save(&task).Error; err != nil { if !taskRecordRepo.Update(&task) {
web.Fail(c, web.NewBadRequest("更新任务失败")) web.Fail(c, web.NewBadRequest("更新任务失败"))
return return
} }
@@ -8,10 +8,17 @@ import (
"eai_agentplatform/backend/internal/middleware" "eai_agentplatform/backend/internal/middleware"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
"eai_agentplatform/backend/internal/store" "eai_agentplatform/backend/internal/repository"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
// noteRepo 学习笔记仓库(便于测试时覆写),包内共享。
var noteRepo repository.StudyNoteRepo
func init() {
noteRepo = repository.StudyNoteRepo{}
}
var validNoteItemTypes = map[string]bool{"company": true, "product": true, "course": true} var validNoteItemTypes = map[string]bool{"company": true, "product": true, "course": true}
// ListNotes GET /api/notes?item_type=&item_id= —— 我的学习笔记 // ListNotes GET /api/notes?item_type=&item_id= —— 我的学习笔记
@@ -21,21 +28,16 @@ func ListNotes(c *gin.Context) {
web.Fail(c, web.NewAuthError("未登录")) web.Fail(c, web.NewAuthError("未登录"))
return return
} }
q := store.DB.Where("user_id = ?", u.ID) // item_id 解析失败(不是数字)就当没传 —— 不给一个错参数回 400,
if t := c.Query("item_type"); t != "" { // 笔记列表本来就是按内容可筛可不筛。
q = q.Where("item_type = ?", t) var itemID *uint
}
if s := c.Query("item_id"); s != "" { if s := c.Query("item_id"); s != "" {
if n, err := strconv.ParseUint(s, 10, 64); err == nil { if n, err := strconv.ParseUint(s, 10, 64); err == nil {
q = q.Where("item_id = ?", n) id := uint(n)
itemID = &id
} }
} }
var items []model.StudyNote web.OK(c, noteRepo.ListByUser(u.ID, c.Query("item_type"), itemID))
if err := q.Order("updated_at DESC").Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询笔记失败"))
return
}
web.OK(c, items)
} }
// CreateNote POST /api/notes —— 新增学习笔记 // CreateNote POST /api/notes —— 新增学习笔记
@@ -63,7 +65,7 @@ func CreateNote(c *gin.Context) {
return return
} }
n := model.StudyNote{UserID: u.ID, ItemType: req.ItemType, ItemID: req.ItemID, Content: strings.TrimSpace(req.Content)} n := model.StudyNote{UserID: u.ID, ItemType: req.ItemType, ItemID: req.ItemID, Content: strings.TrimSpace(req.Content)}
if err := store.DB.Create(&n).Error; err != nil { if !noteRepo.Insert(&n) {
web.Fail(c, web.NewBadRequest("保存笔记失败")) web.Fail(c, web.NewBadRequest("保存笔记失败"))
return return
} }
@@ -81,8 +83,8 @@ func UpdateNote(c *gin.Context) {
if !ok { if !ok {
return return
} }
var n model.StudyNote n, found := noteRepo.GetByID(id)
if err := store.DB.First(&n, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("笔记不存在")) web.Fail(c, web.NewNotFoundError("笔记不存在"))
return return
} }
@@ -102,7 +104,7 @@ func UpdateNote(c *gin.Context) {
return return
} }
n.Content = strings.TrimSpace(req.Content) n.Content = strings.TrimSpace(req.Content)
if err := store.DB.Save(&n).Error; err != nil { if !noteRepo.Update(&n) {
web.Fail(c, web.NewBadRequest("更新笔记失败")) web.Fail(c, web.NewBadRequest("更新笔记失败"))
return return
} }
@@ -120,8 +122,8 @@ func DeleteNote(c *gin.Context) {
if !ok { if !ok {
return return
} }
var n model.StudyNote n, found := noteRepo.GetByID(id)
if err := store.DB.First(&n, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("笔记不存在")) web.Fail(c, web.NewNotFoundError("笔记不存在"))
return return
} }
@@ -129,7 +131,7 @@ func DeleteNote(c *gin.Context) {
web.Fail(c, web.NewForbiddenError("无权操作他人笔记")) web.Fail(c, web.NewForbiddenError("无权操作他人笔记"))
return return
} }
if err := store.DB.Delete(&n).Error; err != nil { if !noteRepo.Delete(&n) {
web.Fail(c, web.NewBadRequest("删除笔记失败")) web.Fail(c, web.NewBadRequest("删除笔记失败"))
return return
} }
@@ -10,9 +10,7 @@ import (
"eai_agentplatform/backend/internal/middleware" "eai_agentplatform/backend/internal/middleware"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
specialistmodel "eai_agentplatform/backend/internal/specialists/model"
specialistruntime "eai_agentplatform/backend/internal/specialists/runtime" specialistruntime "eai_agentplatform/backend/internal/specialists/runtime"
"eai_agentplatform/backend/internal/store"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
@@ -33,8 +31,6 @@ type projectReq struct {
Pinned *bool `json:"pinned"` Pinned *bool `json:"pinned"`
} }
// encodeKeys 把 key 列表存成 JSON 字符串。空列表存空串而不是 "[]", // encodeKeys 把 key 列表存成 JSON 字符串。空列表存空串而不是 "[]",
// 读的时候一眼能看出「没配」和「配了但为空」的区别不大,但空串更省。 // 读的时候一眼能看出「没配」和「配了但为空」的区别不大,但空串更省。
func encodeKeys(keys []string) string { func encodeKeys(keys []string) string {
@@ -62,15 +58,7 @@ func ListProjects(c *gin.Context) {
return return
} }
var items []model.Project web.OK(c, projectRepo.ListByOwners(specialistruntime.MyTaskOwners(user), 50))
if err := specialistruntime.ProjectQuery(user).
Order("pinned DESC, updated_at DESC, id DESC").
Limit(50).
Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询项目失败"))
return
}
web.OK(c, items)
} }
// CreateProject 建一个项目。空 body 也收(跟「新建任务」一样,全走默认值), // CreateProject 建一个项目。空 body 也收(跟「新建任务」一样,全走默认值),
@@ -117,7 +105,7 @@ func CreateProject(c *gin.Context) {
SkillKeys: encodeKeys(req.SkillKeys), SkillKeys: encodeKeys(req.SkillKeys),
ConnectorKeys: encodeKeys(req.ConnectorKeys), ConnectorKeys: encodeKeys(req.ConnectorKeys),
} }
if err := store.DB.Create(&project).Error; err != nil { if !projectRepo.Insert(&project) {
web.Fail(c, web.NewBadRequest("创建项目失败")) web.Fail(c, web.NewBadRequest("创建项目失败"))
return return
} }
@@ -137,8 +125,8 @@ func UpdateProject(c *gin.Context) {
return return
} }
var project model.Project project, found := projectRepo.GetByIDForOwners(id, specialistruntime.MyTaskOwners(user))
if err := specialistruntime.ProjectQuery(user).Where("id = ?", id).First(&project).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("项目不存在")) web.Fail(c, web.NewNotFoundError("项目不存在"))
return return
} }
@@ -181,7 +169,7 @@ func UpdateProject(c *gin.Context) {
project.ConnectorKeys = encodeKeys(req.ConnectorKeys) project.ConnectorKeys = encodeKeys(req.ConnectorKeys)
} }
if err := store.DB.Save(&project).Error; err != nil { if !projectRepo.Update(&project) {
web.Fail(c, web.NewBadRequest("更新项目失败")) web.Fail(c, web.NewBadRequest("更新项目失败"))
return return
} }
@@ -204,18 +192,16 @@ func DeleteProject(c *gin.Context) {
return return
} }
var project model.Project project, found := projectRepo.GetByIDForOwners(id, specialistruntime.MyTaskOwners(user))
if err := specialistruntime.ProjectQuery(user).Where("id = ?", id).First(&project).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("项目不存在")) web.Fail(c, web.NewNotFoundError("项目不存在"))
return return
} }
if err := store.DB.Model(&model.TaskRecord{}). if !taskRecordRepo.ClearProject(project.ID) {
Where("project_id = ?", project.ID).
Update("project_id", nil).Error; err != nil {
web.Fail(c, web.NewBadRequest("解除任务归属失败")) web.Fail(c, web.NewBadRequest("解除任务归属失败"))
return return
} }
if err := store.DB.Delete(&project).Error; err != nil { if !projectRepo.Delete(&project) {
web.Fail(c, web.NewBadRequest("删除项目失败")) web.Fail(c, web.NewBadRequest("删除项目失败"))
return return
} }
@@ -235,21 +221,13 @@ func ListProjectTasks(c *gin.Context) {
return return
} }
var project model.Project project, found := projectRepo.GetByIDForOwners(id, specialistruntime.MyTaskOwners(user))
if err := specialistruntime.ProjectQuery(user).Where("id = ?", id).First(&project).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("项目不存在")) web.Fail(c, web.NewNotFoundError("项目不存在"))
return return
} }
var items []model.TaskRecord web.OK(c, taskRecordRepo.ListByProject(project.ID, 100))
if err := store.DB.Where("project_id = ?", project.ID).
Order("updated_at DESC, id DESC").
Limit(100).
Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询项目任务失败"))
return
}
web.OK(c, items)
} }
// validateSpecialistKeys 专员 key 得真实存在才让存 —— 项目卡片上要显示专员名, // validateSpecialistKeys 专员 key 得真实存在才让存 —— 项目卡片上要显示专员名,
@@ -262,8 +240,7 @@ func validateSpecialistKeys(keys []string) error {
if trimmed == "" { if trimmed == "" {
continue continue
} }
var specialist specialistmodel.Specialist if _, found := specialistRepo.GetByKey(trimmed); !found {
if err := store.DB.Where("key = ?", trimmed).First(&specialist).Error; err != nil {
return errors.New("专员不存在:" + trimmed) return errors.New("专员不存在:" + trimmed)
} }
} }
@@ -4,10 +4,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"eai_agentplatform/backend/internal/model"
skillcore "eai_agentplatform/backend/internal/skills/core" skillcore "eai_agentplatform/backend/internal/skills/core"
specialistmodel "eai_agentplatform/backend/internal/specialists/model" specialistmodel "eai_agentplatform/backend/internal/specialists/model"
"eai_agentplatform/backend/internal/store"
) )
// 本文件回答一个问题:一次对话/一次动作,到底该以哪个专员的身份说话。 // 本文件回答一个问题:一次对话/一次动作,到底该以哪个专员的身份说话。
@@ -25,12 +23,10 @@ func loadSpecialistByKey(key string) *specialistmodel.Specialist {
if key == "" { if key == "" {
return nil return nil
} }
var s specialistmodel.Specialist // state = inactive 的专员不再接新会话,但 system(通用助手)要能查到 ——
if err := store.DB.Where("key = ?", key).First(&s).Error; err != nil { // 「要不要拒绝 inactive」这个口径只在这里,不去污染仓库的取数口径。
return nil s, found := specialistRepo.GetByKey(key)
} if !found || s.State == "inactive" {
// state = inactive 的专员不再接新会话,但 system(通用助手)要能查到。
if s.State == "inactive" {
return nil return nil
} }
return &s return &s
@@ -48,8 +44,7 @@ func resolveSpecialist(req ChatMessageRequest) *specialistmodel.Specialist {
if req.TaskID > 0 { if req.TaskID > 0 {
// 与 task_runtime.go 其余读路径一致,不按 created_by 收窄: // 与 task_runtime.go 其余读路径一致,不按 created_by 收窄:
// 专员目录本身就是所有登录用户可读的,这里不构成新的信息暴露。 // 专员目录本身就是所有登录用户可读的,这里不构成新的信息暴露。
var task model.TaskRecord if task, found := taskRecordRepo.GetByID(req.TaskID); found {
if err := store.DB.First(&task, req.TaskID).Error; err == nil {
if s := loadSpecialistByKey(task.SpecialistKey); s != nil { if s := loadSpecialistByKey(task.SpecialistKey); s != nil {
return s return s
} }
@@ -10,6 +10,7 @@ import (
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
"eai_agentplatform/backend/internal/repository"
specialistmodel "eai_agentplatform/backend/internal/specialists/model" specialistmodel "eai_agentplatform/backend/internal/specialists/model"
"eai_agentplatform/backend/internal/store" "eai_agentplatform/backend/internal/store"
) )
@@ -124,6 +125,12 @@ func setupAPITestDB(t *testing.T) {
store.DB = db store.DB = db
t.Cleanup(func() { store.DB = prev }) t.Cleanup(func() { store.DB = prev })
// 取数现在走仓库层,零值仓库(repository.XxxRepo{})的 base() 会回落到
// 包级 repository.DB —— 这根线不接,第一个查询就是 nil 解引用。
prevRepo := repository.DB
repository.SetDB(db)
t.Cleanup(func() { repository.SetDB(prevRepo) })
for _, s := range []specialistmodel.Specialist{ for _, s := range []specialistmodel.Specialist{
{Key: "contract-review", Label: "合同审查专员", State: "active", Tier: "industry", ObjectEntryRoute: "/apps/contract-review"}, {Key: "contract-review", Label: "合同审查专员", State: "active", Tier: "industry", ObjectEntryRoute: "/apps/contract-review"},
{Key: "report-generation", Label: "报告生成专员", State: "active", Tier: "generic", ObjectEntryRoute: "/apps/report-generation"}, {Key: "report-generation", Label: "报告生成专员", State: "active", Tier: "generic", ObjectEntryRoute: "/apps/report-generation"},
@@ -7,30 +7,43 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gorm.io/gorm"
"eai_agentplatform/backend/internal/middleware" "eai_agentplatform/backend/internal/middleware"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
specialistmodel "eai_agentplatform/backend/internal/specialists/model" "eai_agentplatform/backend/internal/repository"
wechatofficialaccountapi "eai_agentplatform/backend/internal/specialists/packages/wechat_official_account/api" wechatofficialaccountapi "eai_agentplatform/backend/internal/specialists/packages/wechat_official_account/api"
specialistruntime "eai_agentplatform/backend/internal/specialists/runtime" specialistruntime "eai_agentplatform/backend/internal/specialists/runtime"
"eai_agentplatform/backend/internal/store"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
// 任务域仓库,包内共享。
//
// specialistRepo 还被 my_task.go、project.go、specialist_prompt.go 共用,
// projectRepo 还被 my_task.go 共用 —— 同一个仓库只声明一处:
// 两份变量持有同一个仓库时,测试里覆写一份、另一份照旧,行为会静默分叉。
var (
specialistRepo repository.SpecialistRepo
taskRecordRepo repository.TaskRecordRepo
taskRunRepo repository.TaskRunRepo
taskArtifactRepo repository.TaskArtifactRepo
projectRepo repository.ProjectRepo
)
func init() {
specialistRepo = repository.SpecialistRepo{}
taskRecordRepo = repository.TaskRecordRepo{}
taskRunRepo = repository.TaskRunRepo{}
taskArtifactRepo = repository.TaskArtifactRepo{}
projectRepo = repository.ProjectRepo{}
}
func ListTasks(c *gin.Context) { func ListTasks(c *gin.Context) {
specialistKey := strings.TrimSpace(c.Query("specialist_key")) specialistKey := strings.TrimSpace(c.Query("specialist_key"))
if specialistKey == "" { if specialistKey == "" {
web.Fail(c, web.NewBadRequest("specialist_key 不能为空")) web.Fail(c, web.NewBadRequest("specialist_key 不能为空"))
return return
} }
web.OK(c, taskRecordRepo.ListBySpecialistKey(specialistKey))
var items []model.TaskRecord
if err := store.DB.Where("specialist_key = ?", specialistKey).Order("updated_at DESC, id DESC").Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询事项失败"))
return
}
web.OK(c, items)
} }
func GetTaskDetail(c *gin.Context) { func GetTaskDetail(c *gin.Context) {
@@ -39,23 +52,14 @@ func GetTaskDetail(c *gin.Context) {
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByID(id)
if err := store.DB.First(&task, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("事项不存在")) web.Fail(c, web.NewNotFoundError("事项不存在"))
return return
} }
var artifacts []model.TaskArtifact artifacts := taskArtifactRepo.ListByTask(id)
if err := store.DB.Where("task_id = ?", id).Order("created_at DESC, id DESC").Find(&artifacts).Error; err != nil { runs := taskRunRepo.ListByTask(id)
web.Fail(c, web.NewBadRequest("查询交付物失败"))
return
}
var runs []model.TaskRun
if err := store.DB.Where("task_id = ?", id).Order("started_at DESC, id DESC").Find(&runs).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询运行记录失败"))
return
}
if task.SpecialistKey == wechatofficialaccountapi.OfficialAccountSpecialistKey { if task.SpecialistKey == wechatofficialaccountapi.OfficialAccountSpecialistKey {
artifacts = wechatofficialaccountapi.CompactOfficialAccountArtifactsForResponse(artifacts) artifacts = wechatofficialaccountapi.CompactOfficialAccountArtifactsForResponse(artifacts)
runs = wechatofficialaccountapi.CompactOfficialAccountRunsForResponse(runs) runs = wechatofficialaccountapi.CompactOfficialAccountRunsForResponse(runs)
@@ -75,22 +79,21 @@ func GetArtifactDetail(c *gin.Context) {
return return
} }
var artifact model.TaskArtifact artifact, found := taskArtifactRepo.GetByID(id)
if err := store.DB.First(&artifact, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("交付物不存在")) web.Fail(c, web.NewNotFoundError("交付物不存在"))
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByID(artifact.TaskID)
if err := store.DB.First(&task, artifact.TaskID).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("事项不存在")) web.Fail(c, web.NewNotFoundError("事项不存在"))
return return
} }
var run model.TaskRun
var runData any var runData any
if artifact.CreatedByRunID != nil { if artifact.CreatedByRunID != nil {
if err := store.DB.First(&run, *artifact.CreatedByRunID).Error; err == nil { if run, ok := taskRunRepo.GetByID(*artifact.CreatedByRunID); ok {
runData = run runData = run
} }
} }
@@ -113,8 +116,8 @@ func CreateTask(c *gin.Context) {
return return
} }
var specialist specialistmodel.Specialist specialist, found := specialistRepo.GetByKey(strings.TrimSpace(req.SpecialistKey))
if err := store.DB.Where("key = ?", strings.TrimSpace(req.SpecialistKey)).First(&specialist).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("专员不存在")) web.Fail(c, web.NewNotFoundError("专员不存在"))
return return
} }
@@ -132,7 +135,7 @@ func CreateTask(c *gin.Context) {
task.Status = "待处理" task.Status = "待处理"
} }
if err := store.DB.Create(&task).Error; err != nil { if !taskRecordRepo.Insert(&task) {
web.Fail(c, web.NewBadRequest("创建事项失败")) web.Fail(c, web.NewBadRequest("创建事项失败"))
return return
} }
@@ -145,8 +148,8 @@ func UpdateTask(c *gin.Context) {
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByID(id)
if err := store.DB.First(&task, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("事项不存在")) web.Fail(c, web.NewNotFoundError("事项不存在"))
return return
} }
@@ -163,9 +166,9 @@ func UpdateTask(c *gin.Context) {
return return
} }
if strings.TrimSpace(req.SpecialistKey) != "" && strings.TrimSpace(req.SpecialistKey) != task.SpecialistKey { if key := strings.TrimSpace(req.SpecialistKey); key != "" && key != task.SpecialistKey {
var specialist specialistmodel.Specialist specialist, ok := specialistRepo.GetByKey(key)
if err := store.DB.Where("key = ?", strings.TrimSpace(req.SpecialistKey)).First(&specialist).Error; err != nil { if !ok {
web.Fail(c, web.NewNotFoundError("目标专员不存在")) web.Fail(c, web.NewNotFoundError("目标专员不存在"))
return return
} }
@@ -178,7 +181,7 @@ func UpdateTask(c *gin.Context) {
task.Status = specialistruntime.NormalizeTaskStatus(updated.Status) task.Status = specialistruntime.NormalizeTaskStatus(updated.Status)
task.ContextJSON = updated.ContextJSON task.ContextJSON = updated.ContextJSON
task.DueAt = updated.DueAt task.DueAt = updated.DueAt
if err := store.DB.Save(&task).Error; err != nil { if !taskRecordRepo.Update(&task) {
web.Fail(c, web.NewBadRequest("更新事项失败")) web.Fail(c, web.NewBadRequest("更新事项失败"))
return return
} }
@@ -191,8 +194,8 @@ func UpdateTaskStatus(c *gin.Context) {
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByID(id)
if err := store.DB.First(&task, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("事项不存在")) web.Fail(c, web.NewNotFoundError("事项不存在"))
return return
} }
@@ -208,7 +211,7 @@ func UpdateTaskStatus(c *gin.Context) {
return return
} }
task.Status = status task.Status = status
if err := store.DB.Save(&task).Error; err != nil { if !taskRecordRepo.Update(&task) {
web.Fail(c, web.NewBadRequest("更新事项状态失败")) web.Fail(c, web.NewBadRequest("更新事项状态失败"))
return return
} }
@@ -221,24 +224,14 @@ func DeleteTask(c *gin.Context) {
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByID(id)
if err := store.DB.First(&task, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("事项不存在")) web.Fail(c, web.NewNotFoundError("事项不存在"))
return return
} }
if err := store.DB.Transaction(func(tx *gorm.DB) error { // 交付物与运行记录跟着任务一起走,三张表在同一个事务里。
if err := tx.Where("task_id = ?", task.ID).Delete(&model.TaskArtifact{}).Error; err != nil { if !taskRecordRepo.DeleteCascade(task.ID) {
return err
}
if err := tx.Where("task_id = ?", task.ID).Delete(&model.TaskRun{}).Error; err != nil {
return err
}
if err := tx.Delete(&task).Error; err != nil {
return err
}
return nil
}); err != nil {
web.Fail(c, web.NewBadRequest("删除事项失败")) web.Fail(c, web.NewBadRequest("删除事项失败"))
return return
} }
@@ -252,13 +245,13 @@ func UpdateArtifactStatus(c *gin.Context) {
return return
} }
var artifact model.TaskArtifact artifact, found := taskArtifactRepo.GetByID(id)
if err := store.DB.First(&artifact, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("交付物不存在")) web.Fail(c, web.NewNotFoundError("交付物不存在"))
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByID(artifact.TaskID)
if err := store.DB.First(&task, artifact.TaskID).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("事项不存在")) web.Fail(c, web.NewNotFoundError("事项不存在"))
return return
} }
@@ -274,14 +267,14 @@ func UpdateArtifactStatus(c *gin.Context) {
return return
} }
artifact.Status = nextStatus artifact.Status = nextStatus
if err := store.DB.Save(&artifact).Error; err != nil { if !taskArtifactRepo.Update(&artifact) {
web.Fail(c, web.NewBadRequest("更新交付物状态失败")) web.Fail(c, web.NewBadRequest("更新交付物状态失败"))
return return
} }
task.Status = specialistruntime.TaskStatusFromArtifactStatus(nextStatus) task.Status = specialistruntime.TaskStatusFromArtifactStatus(nextStatus)
task.CurrentResult = specialistruntime.BuildArtifactStatusSummary(artifact, strings.TrimSpace(req.Remark)) task.CurrentResult = specialistruntime.BuildArtifactStatusSummary(artifact, strings.TrimSpace(req.Remark))
if err := store.DB.Save(&task).Error; err != nil { if !taskRecordRepo.Update(&task) {
web.Fail(c, web.NewBadRequest("更新事项状态失败")) web.Fail(c, web.NewBadRequest("更新事项状态失败"))
return return
} }
@@ -298,13 +291,13 @@ func ExecuteTaskAction(c *gin.Context) {
return return
} }
var task model.TaskRecord task, found := taskRecordRepo.GetByID(id)
if err := store.DB.First(&task, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("事项不存在")) web.Fail(c, web.NewNotFoundError("事项不存在"))
return return
} }
var specialist specialistmodel.Specialist specialist, found := specialistRepo.GetByKey(task.SpecialistKey)
if err := store.DB.Where("key = ?", task.SpecialistKey).First(&specialist).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("专员不存在")) web.Fail(c, web.NewNotFoundError("专员不存在"))
return return
} }
@@ -350,7 +343,7 @@ func ExecuteTaskAction(c *gin.Context) {
StartedAt: now, StartedAt: now,
FinishedAt: &now, FinishedAt: &now,
} }
if err := store.DB.Create(&run).Error; err != nil { if !taskRunRepo.Insert(&run) {
web.Fail(c, web.NewBadRequest("执行动作失败")) web.Fail(c, web.NewBadRequest("执行动作失败"))
return return
} }
@@ -369,7 +362,7 @@ func ExecuteTaskAction(c *gin.Context) {
SourceRefsJSON: string(sourceRefsJSON), SourceRefsJSON: string(sourceRefsJSON),
CreatedByRunID: &run.ID, CreatedByRunID: &run.ID,
} }
if err := store.DB.Create(artifact).Error; err != nil { if !taskArtifactRepo.Insert(artifact) {
web.Fail(c, web.NewBadRequest("保存交付物失败")) web.Fail(c, web.NewBadRequest("保存交付物失败"))
return return
} }
@@ -379,7 +372,7 @@ func ExecuteTaskAction(c *gin.Context) {
task.CurrentRunID = &run.ID task.CurrentRunID = &run.ID
task.CurrentResult = runOutput.Summary task.CurrentResult = runOutput.Summary
task.LastTriggeredAt = &now task.LastTriggeredAt = &now
if err := store.DB.Save(&task).Error; err != nil { if !taskRecordRepo.Update(&task) {
web.Fail(c, web.NewBadRequest("更新事项状态失败")) web.Fail(c, web.NewBadRequest("更新事项状态失败"))
return return
} }
@@ -391,18 +384,17 @@ func ExecuteTaskAction(c *gin.Context) {
}) })
} }
// ensureBootstrapTask 某专员名下一条任务都没有时,铺一条默认任务。
//
// 注意:目前全仓没有调用方(保留原样迁到仓库层,未删)。
func ensureBootstrapTask(specialistKey string, user *model.User) error { func ensureBootstrapTask(specialistKey string, user *model.User) error {
var count int64 if taskRecordRepo.CountBySpecialistKey(specialistKey) > 0 {
if err := store.DB.Model(&model.TaskRecord{}).Where("specialist_key = ?", specialistKey).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return nil return nil
} }
var specialist specialistmodel.Specialist specialist, found := specialistRepo.GetByKey(specialistKey)
if err := store.DB.Where("key = ?", specialistKey).First(&specialist).Error; err != nil { if !found {
return err return fmt.Errorf("专员不存在:%s", specialistKey)
} }
now := time.Now() now := time.Now()
@@ -427,7 +419,10 @@ func ensureBootstrapTask(specialistKey string, user *model.User) error {
if user != nil { if user != nil {
task.CreatedBy = &user.ID task.CreatedBy = &user.ID
} }
return store.DB.Create(&task).Error if !taskRecordRepo.Insert(&task) {
return fmt.Errorf("创建铺底任务失败")
}
return nil
} }
func buildBottomPanel(runs []model.TaskRun) gin.H { func buildBottomPanel(runs []model.TaskRun) gin.H {
@@ -0,0 +1,57 @@
package repository
import (
"eai_agentplatform/backend/internal/model"
)
// ActionDefinition 原子执行动作定义仓库。
type ActionDefinitionRepo struct{ *QueryBuilder }
// List 全部动作定义(sort_order ASC, id ASC)。
//
// 这里不替调用方定 state 默认值:列表接口「不传 state 就只看 active」是接口契约,
// 由 handler 解析 query 参数后把结果传进来。
func (r ActionDefinitionRepo) List(state string) []model.ActionDefinition {
q := r.Type(&model.ActionDefinition{})
if state != "" {
q = q.Where("state = ?", state)
}
var items []model.ActionDefinition
if q.Order("sort_order ASC, id ASC").Find(&items) {
return items
}
return nil
}
// GetByID 按 ID 取。
func (r ActionDefinitionRepo) GetByID(id uint) (model.ActionDefinition, bool) {
var a model.ActionDefinition
if r.Type(&a).Where("id = ?", id).First(&a) {
return a, true
}
return model.ActionDefinition{}, false
}
// GetByKey 按 key 取(key 上有唯一索引)。
func (r ActionDefinitionRepo) GetByKey(key string) (model.ActionDefinition, bool) {
var a model.ActionDefinition
if r.Type(&a).Where("key = ?", key).First(&a) {
return a, true
}
return model.ActionDefinition{}, false
}
// Insert 新建。
func (r ActionDefinitionRepo) Insert(a *model.ActionDefinition) bool {
return r.QueryBuilder.Insert(a)
}
// Update 更新。
func (r ActionDefinitionRepo) Update(a *model.ActionDefinition) bool {
return r.Save(a)
}
// Delete 硬删除。
func (r ActionDefinitionRepo) Delete(a *model.ActionDefinition) bool {
return r.QueryBuilder.Delete(a)
}
@@ -0,0 +1,52 @@
package repository
import (
"eai_agentplatform/backend/internal/model"
)
// Project 项目仓库(任务的容器)。
type ProjectRepo struct{ *QueryBuilder }
// GetByIDForOwners 按 ID 取项目,且必须归属于 owners 里的一员。
//
// owners 为空时查不到任何东西(而不是查到全部)——跟任务同一套归属口径,
// 别人的项目和不存在的项目在这里不做区分,调用方一律回 404。
func (r ProjectRepo) GetByIDForOwners(id uint, owners []string) (model.Project, bool) {
var p model.Project
if ownerScope(r.Type(&p), owners).Where("id = ?", id).First(&p) {
return p, true
}
return model.Project{}, false
}
// ListByOwners 「我的项目」:置顶的排前面,其余按最近动过的排。
// limit <= 0 表示不设上限。
func (r ProjectRepo) ListByOwners(owners []string, limit int) []model.Project {
q := ownerScope(r.Type(&model.Project{}), owners)
if limit > 0 {
q = q.Limit(limit)
}
var items []model.Project
if q.Order("pinned DESC, updated_at DESC, id DESC").Find(&items) {
return items
}
return nil
}
// Insert 新建项目。
func (r ProjectRepo) Insert(p *model.Project) bool {
return r.QueryBuilder.Insert(p)
}
// Update 更新项目。
func (r ProjectRepo) Update(p *model.Project) bool {
return r.Save(p)
}
// Delete 删除项目。
//
// 项目里的任务**不删**——先由调用方把它们的 project_id 置空(见
// TaskRecordRepo.ClearProject),再删项目本身。
func (r ProjectRepo) Delete(p *model.Project) bool {
return r.QueryBuilder.Delete(p)
}
@@ -0,0 +1,110 @@
package repository
import (
specialistmodel "eai_agentplatform/backend/internal/specialists/model"
)
// Specialist 数字员工专员目录仓库。
//
// 模型定义在 specialists 领域包内(internal/specialists/model),取数统一走这里——
// 「按 key 找专员」原先在 4 个文件里各写了一遍,散着改迟早分叉。
type SpecialistRepo struct{ *QueryBuilder }
// GetByKey 按 key 取专员,**不限 state**。
//
// 不过滤 state 是有意的:调用方对「停用的专员算不算数」口径不同——
// 建任务时要能查到(任务挂在已下线的专员上仍要能解释),
// 而对话取 prompt 时要拒绝 inactive。把口径留在调用方,这里只负责取数。
func (r SpecialistRepo) GetByKey(key string) (specialistmodel.Specialist, bool) {
var s specialistmodel.Specialist
if r.Type(&s).Where("key = ?", key).First(&s) {
return s, true
}
return specialistmodel.Specialist{}, false
}
// GetByID 按 ID 取专员。
func (r SpecialistRepo) GetByID(id uint) (specialistmodel.Specialist, bool) {
var s specialistmodel.Specialist
if r.Type(&s).Where("id = ?", id).First(&s) {
return s, true
}
return specialistmodel.Specialist{}, false
}
// Query 返回专员表的查询构建器(已 Type 好)。
//
// 给「带自己那套 state 策略」的调用方用——比如按 key 取且非管理员只认 active、
// 或者按 state 分档计数。这类策略是各接口自己的口径,不在这里替它们定。
func (r SpecialistRepo) Query() *QueryBuilder {
return r.QueryBuilder.Query().Type(&specialistmodel.Specialist{})
}
// List 专员目录列表(sort_order ASC, id ASC)。
//
// state 的档位是接口契约,调用方直接透传 query 参数:
// - ""(默认):仅 active —— 员工浏览视角
// - "all":管理员看全部状态,非管理员仍只看 active
// - "system":仅 system(通用助手那条内置记录)
// - 其它:按该状态精确匹配
//
// 除显式要 system 外,一律排除 system 记录——它是内置的通用助手,
// 不该混进专员目录里让人当成一个可选的专员。
func (r SpecialistRepo) List(tier, marketTag, state string, isAdmin bool) []specialistmodel.Specialist {
q := r.Type(&specialistmodel.Specialist{})
if tier != "" {
q = q.Where("tier = ?", tier)
}
if marketTag != "" {
q = q.Where("market_tag = ?", marketTag)
}
switch state {
case "":
q = q.Where("state = ?", "active")
case "all":
if !isAdmin {
q = q.Where("state = ?", "active")
}
case "system":
q = q.Where("state = ?", "system")
default:
q = q.Where("state = ?", state)
}
if state != "system" {
q = q.Where("state <> ?", "system")
}
var items []specialistmodel.Specialist
if q.Order("sort_order ASC, id ASC").Find(&items) {
return items
}
return nil
}
// CountByKey 按 key 统计(唯一性检查)。excludeID 用于更新时排除自身,nil 表示不排除。
func (r SpecialistRepo) CountByKey(key string, excludeID *uint) int64 {
q := r.Inner().Model(&specialistmodel.Specialist{}).Where("key = ?", key)
if excludeID != nil {
q = q.Where("id <> ?", *excludeID)
}
var c int64
q.Count(&c)
return c
}
// Insert 新建专员。
func (r SpecialistRepo) Insert(s *specialistmodel.Specialist) bool {
return r.QueryBuilder.Insert(s)
}
// Update 更新专员。
func (r SpecialistRepo) Update(s *specialistmodel.Specialist) bool {
return r.Save(s)
}
// Delete 硬删除专员。
//
// 表上没有软删字段,删了就是删了——跟「停用」(state=inactive)是两回事:
// 停用还留着记录、还能查到,删除会让挂在它名下的历史任务失去解释依据。
func (r SpecialistRepo) Delete(id uint) bool {
return r.Type(&specialistmodel.Specialist{}).Where("id = ?", id).Delete(&specialistmodel.Specialist{})
}
@@ -0,0 +1,52 @@
package repository
import (
"eai_agentplatform/backend/internal/model"
)
// StudyNote 学习笔记仓库(员工私人笔记,按 user_id 隔离)。
type StudyNoteRepo struct{ *QueryBuilder }
// ListByUser 某用户的笔记,最近改过的在前。
//
// itemType 为空表示不按内容类型过滤;itemID 为 nil 表示不按内容 ID 过滤
// (指针而非 0 值,是因为 company 类笔记的 item_id 本来就固定是 0)。
func (r StudyNoteRepo) ListByUser(userID uint, itemType string, itemID *uint) []model.StudyNote {
q := r.Type(&model.StudyNote{}).Where("user_id = ?", userID)
if itemType != "" {
q = q.Where("item_type = ?", itemType)
}
if itemID != nil {
q = q.Where("item_id = ?", *itemID)
}
var items []model.StudyNote
if q.Order("updated_at DESC").Find(&items) {
return items
}
return nil
}
// GetByID 按 ID 取笔记。**不在这里判归属**——越权检查留在 handler,
// 那里能把「不存在」和「不是你的」分别回成 404 / 403。
func (r StudyNoteRepo) GetByID(id uint) (model.StudyNote, bool) {
var n model.StudyNote
if r.Type(&n).Where("id = ?", id).First(&n) {
return n, true
}
return model.StudyNote{}, false
}
// Insert 新建笔记。
func (r StudyNoteRepo) Insert(n *model.StudyNote) bool {
return r.QueryBuilder.Insert(n)
}
// Update 更新笔记。
func (r StudyNoteRepo) Update(n *model.StudyNote) bool {
return r.Save(n)
}
// Delete 删除笔记(硬删,表上没有软删字段)。
func (r StudyNoteRepo) Delete(n *model.StudyNote) bool {
return r.QueryBuilder.Delete(n)
}
@@ -0,0 +1,37 @@
package repository
import (
"eai_agentplatform/backend/internal/model"
)
// TaskArtifact 专员交付物仓库。
type TaskArtifactRepo struct{ *QueryBuilder }
// GetByID 按 ID 取交付物。
func (r TaskArtifactRepo) GetByID(id uint) (model.TaskArtifact, bool) {
var a model.TaskArtifact
if r.Type(&a).Where("id = ?", id).First(&a) {
return a, true
}
return model.TaskArtifact{}, false
}
// ListByTask 某任务的全部交付物(最近产出的在前)。
func (r TaskArtifactRepo) ListByTask(taskID uint) []model.TaskArtifact {
var items []model.TaskArtifact
if r.Type(&items).Where("task_id = ?", taskID).
Order("created_at DESC, id DESC").Find(&items) {
return items
}
return nil
}
// Insert 新建交付物。
func (r TaskArtifactRepo) Insert(a *model.TaskArtifact) bool {
return r.QueryBuilder.Insert(a)
}
// Update 更新交付物(状态流转走这里)。
func (r TaskArtifactRepo) Update(a *model.TaskArtifact) bool {
return r.Save(a)
}
@@ -0,0 +1,125 @@
package repository
import (
"gorm.io/gorm"
"eai_agentplatform/backend/internal/model"
)
// TaskRecord 专员事项/任务仓库。
//
// 任务是这个聚合的根:交付物(task_artifact)与运行记录(task_run)都挂在它下面,
// 所以级联删除也放在这里,而不是让 handler 去协调三个仓库。
type TaskRecordRepo struct{ *QueryBuilder }
// GetByID 按 ID 取任务。
func (r TaskRecordRepo) GetByID(id uint) (model.TaskRecord, bool) {
var t model.TaskRecord
if r.Type(&t).Where("id = ?", id).First(&t) {
return t, true
}
return model.TaskRecord{}, false
}
// GetByIDForOwners 按 ID 取任务,且必须归属于 owners 里的一员。
//
// owners 为空时查不到任何东西(而不是查到全部):归属标识缺失时必须退化成
// 「什么都看不到」,绝不能反过来退化成「看所有人的」。
func (r TaskRecordRepo) GetByIDForOwners(id uint, owners []string) (model.TaskRecord, bool) {
var t model.TaskRecord
if ownerScope(r.Type(&t), owners).Where("id = ?", id).First(&t) {
return t, true
}
return model.TaskRecord{}, false
}
// ListBySpecialistKey 某专员名下的全部任务(最近更新的在前)。
func (r TaskRecordRepo) ListBySpecialistKey(specialistKey string) []model.TaskRecord {
var items []model.TaskRecord
if r.Type(&items).Where("specialist_key = ?", specialistKey).
Order("updated_at DESC, id DESC").Find(&items) {
return items
}
return nil
}
// ListByOwners 「我的任务」:置顶的排前面,其余按最近动过的排。
// limit <= 0 表示不设上限。
func (r TaskRecordRepo) ListByOwners(owners []string, limit int) []model.TaskRecord {
q := ownerScope(r.Type(&model.TaskRecord{}), owners)
if limit > 0 {
q = q.Limit(limit)
}
var items []model.TaskRecord
if q.Order("pinned DESC, updated_at DESC, id DESC").Find(&items) {
return items
}
return nil
}
// ListByProject 项目下的任务(最近更新的在前)。limit <= 0 表示不设上限。
func (r TaskRecordRepo) ListByProject(projectID uint, limit int) []model.TaskRecord {
q := r.Type(&model.TaskRecord{}).Where("project_id = ?", projectID)
if limit > 0 {
q = q.Limit(limit)
}
var items []model.TaskRecord
if q.Order("updated_at DESC, id DESC").Find(&items) {
return items
}
return nil
}
// CountBySpecialistKey 统计某专员名下的任务数(首次进入时判断要不要铺底任务)。
func (r TaskRecordRepo) CountBySpecialistKey(specialistKey string) int64 {
var c int64
r.Inner().Model(&model.TaskRecord{}).Where("specialist_key = ?", specialistKey).Count(&c)
return c
}
// Insert 新建任务。
func (r TaskRecordRepo) Insert(t *model.TaskRecord) bool {
return r.QueryBuilder.Insert(t)
}
// Update 更新任务。
func (r TaskRecordRepo) Update(t *model.TaskRecord) bool {
return r.Save(t)
}
// Delete 删除单条任务(不动它的交付物与运行记录,级联请用 DeleteCascade)。
func (r TaskRecordRepo) Delete(t *model.TaskRecord) bool {
return r.QueryBuilder.Delete(t)
}
// ClearProject 把项目下的任务全部解除归属(project_id 置空)。
//
// 任务是「做过的事」,删一个分组不该把它一起抹掉,所以只解除归属、不删记录。
func (r TaskRecordRepo) ClearProject(projectID uint) bool {
return r.Type(&model.TaskRecord{}).Where("project_id = ?", projectID).
UpdateColumn("project_id", nil)
}
// DeleteCascade 删任务,连同它的交付物与运行记录。
//
// 三张表必须一起成功或一起失败——留下没有任务的交付物,详情页就再也点不进去了。
func (r TaskRecordRepo) DeleteCascade(id uint) bool {
err := r.Inner().Transaction(func(tx *gorm.DB) error {
if err := tx.Where("task_id = ?", id).Delete(&model.TaskArtifact{}).Error; err != nil {
return err
}
if err := tx.Where("task_id = ?", id).Delete(&model.TaskRun{}).Error; err != nil {
return err
}
return tx.Delete(&model.TaskRecord{}, id).Error
})
return err == nil
}
// ownerScope 给查询套上归属范围。owners 为空时套一个恒假条件(空集,不是全表)。
func ownerScope(q *QueryBuilder, owners []string) *QueryBuilder {
if len(owners) == 0 {
return q.Where("1 = 0")
}
return q.Where("owner IN ?", owners)
}
@@ -0,0 +1,34 @@
package repository
import (
"eai_agentplatform/backend/internal/model"
)
// TaskRun 专员动作运行记录仓库。
//
// 运行记录只增不改:一次动作一条,是任务详情的「时间线/回放」底稿。
type TaskRunRepo struct{ *QueryBuilder }
// GetByID 按 ID 取运行记录。
func (r TaskRunRepo) GetByID(id uint) (model.TaskRun, bool) {
var run model.TaskRun
if r.Type(&run).Where("id = ?", id).First(&run) {
return run, true
}
return model.TaskRun{}, false
}
// ListByTask 某任务的全部运行记录(最近开始的在前)。
func (r TaskRunRepo) ListByTask(taskID uint) []model.TaskRun {
var items []model.TaskRun
if r.Type(&items).Where("task_id = ?", taskID).
Order("started_at DESC, id DESC").Find(&items) {
return items
}
return nil
}
// Insert 追加一条运行记录。
func (r TaskRunRepo) Insert(run *model.TaskRun) bool {
return r.QueryBuilder.Insert(run)
}
@@ -20,10 +20,20 @@ import (
"eai_agentplatform/backend/internal/middleware" "eai_agentplatform/backend/internal/middleware"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
"eai_agentplatform/backend/internal/repository"
"eai_agentplatform/backend/internal/store" "eai_agentplatform/backend/internal/store"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
// taskRecordRepo 任务仓库(便于测试时覆写)。本文件里还有两处
// store.DB.Transaction —— 运行记录和交付物要在同一个事务里落库,
// QueryBuilder 不带事务,那两处维持原样。
var taskRecordRepo repository.TaskRecordRepo
func init() {
taskRecordRepo = repository.TaskRecordRepo{}
}
type officeSkillExecuteReq struct { type officeSkillExecuteReq struct {
TaskID uint `json:"task_id"` TaskID uint `json:"task_id"`
SkillKey string `json:"skill_key"` SkillKey string `json:"skill_key"`
@@ -304,18 +314,20 @@ func persistOfficeExecution(task model.TaskRecord, definition officecontracts.Ru
} }
func loadMyOwnedTask(c *gin.Context, user *model.User, taskID uint) (model.TaskRecord, bool) { func loadMyOwnedTask(c *gin.Context, user *model.User, taskID uint) (model.TaskRecord, bool) {
var task model.TaskRecord task, found := taskRecordRepo.GetByIDForOwners(taskID, specialistruntime.MyTaskOwners(user))
if err := specialistruntime.MyTaskQuery(user).Where("id = ?", taskID).First(&task).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("任务不存在")) web.Fail(c, web.NewNotFoundError("任务不存在"))
return task, false return model.TaskRecord{}, false
} }
return task, true return task, true
} }
func reloadTask(taskID uint) (model.TaskRecord, error) { func reloadTask(taskID uint) (model.TaskRecord, error) {
var task model.TaskRecord task, found := taskRecordRepo.GetByID(taskID)
err := store.DB.First(&task, taskID).Error if !found {
return task, err return model.TaskRecord{}, gorm.ErrRecordNotFound
}
return task, nil
} }
func anyToStrings(value any) []string { func anyToStrings(value any) []string {
@@ -5,12 +5,20 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"eai_agentplatform/backend/internal/repository"
specialistmodel "eai_agentplatform/backend/internal/specialists/model" specialistmodel "eai_agentplatform/backend/internal/specialists/model"
specialistruntime "eai_agentplatform/backend/internal/specialists/runtime" specialistruntime "eai_agentplatform/backend/internal/specialists/runtime"
"eai_agentplatform/backend/internal/store"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
// specialistRepo 专员目录仓库(便于测试时覆写)。query_handlers.go 里的读接口共用,
// 声明只此一处。
var specialistRepo repository.SpecialistRepo
func init() {
specialistRepo = repository.SpecialistRepo{}
}
// CreateSpecialist POST /api/specialists (admin) // CreateSpecialist POST /api/specialists (admin)
func CreateSpecialist(c *gin.Context) { func CreateSpecialist(c *gin.Context) {
var req specialistReq var req specialistReq
@@ -23,9 +31,7 @@ func CreateSpecialist(c *gin.Context) {
return return
} }
var count int64 if specialistRepo.CountByKey(req.Key, nil) > 0 {
store.DB.Model(&specialistmodel.Specialist{}).Where("key = ?", req.Key).Count(&count)
if count > 0 {
web.Fail(c, web.NewConflictError("专员 key 已存在")) web.Fail(c, web.NewConflictError("专员 key 已存在"))
return return
} }
@@ -64,7 +70,7 @@ func CreateSpecialist(c *gin.Context) {
SortOrder: req.SortOrder, SortOrder: req.SortOrder,
} }
specialistruntime.EnsureStructuredRecords(&item) specialistruntime.EnsureStructuredRecords(&item)
if err := store.DB.Create(&item).Error; err != nil { if !specialistRepo.Insert(&item) {
web.Fail(c, web.NewBadRequest("创建专员失败")) web.Fail(c, web.NewBadRequest("创建专员失败"))
return return
} }
@@ -77,8 +83,8 @@ func UpdateSpecialist(c *gin.Context) {
if !ok { if !ok {
return return
} }
var item specialistmodel.Specialist item, found := specialistRepo.GetByID(id)
if err := store.DB.First(&item, id).Error; err != nil { if !found {
web.Fail(c, web.NewNotFoundError("专员不存在")) web.Fail(c, web.NewNotFoundError("专员不存在"))
return return
} }
@@ -93,9 +99,7 @@ func UpdateSpecialist(c *gin.Context) {
return return
} }
var count int64 if specialistRepo.CountByKey(req.Key, &id) > 0 {
store.DB.Model(&specialistmodel.Specialist{}).Where("key = ? AND id <> ?", req.Key, id).Count(&count)
if count > 0 {
web.Fail(c, web.NewConflictError("专员 key 已存在")) web.Fail(c, web.NewConflictError("专员 key 已存在"))
return return
} }
@@ -133,7 +137,7 @@ func UpdateSpecialist(c *gin.Context) {
item.SortOrder = req.SortOrder item.SortOrder = req.SortOrder
specialistruntime.EnsureStructuredRecords(&item) specialistruntime.EnsureStructuredRecords(&item)
if err := store.DB.Save(&item).Error; err != nil { if !specialistRepo.Update(&item) {
web.Fail(c, web.NewBadRequest("更新专员失败")) web.Fail(c, web.NewBadRequest("更新专员失败"))
return return
} }
@@ -146,12 +150,11 @@ func DeleteSpecialist(c *gin.Context) {
if !ok { if !ok {
return return
} }
var item specialistmodel.Specialist if _, found := specialistRepo.GetByID(id); !found {
if err := store.DB.First(&item, id).Error; err != nil {
web.Fail(c, web.NewNotFoundError("专员不存在")) web.Fail(c, web.NewNotFoundError("专员不存在"))
return return
} }
if err := store.DB.Delete(&item).Error; err != nil { if !specialistRepo.Delete(id) {
web.Fail(c, web.NewBadRequest("删除专员失败")) web.Fail(c, web.NewBadRequest("删除专员失败"))
return return
} }
@@ -8,42 +8,15 @@ import (
"eai_agentplatform/backend/internal/middleware" "eai_agentplatform/backend/internal/middleware"
specialistmodel "eai_agentplatform/backend/internal/specialists/model" specialistmodel "eai_agentplatform/backend/internal/specialists/model"
specialistruntime "eai_agentplatform/backend/internal/specialists/runtime" specialistruntime "eai_agentplatform/backend/internal/specialists/runtime"
"eai_agentplatform/backend/internal/store"
"eai_agentplatform/backend/internal/web" "eai_agentplatform/backend/internal/web"
) )
// ListSpecialists GET /api/specialists?tier=&state=&market_tag= // ListSpecialists GET /api/specialists?tier=&state=&market_tag=
func ListSpecialists(c *gin.Context) { func ListSpecialists(c *gin.Context) {
q := store.DB.Model(&specialistmodel.Specialist{})
if tier := c.Query("tier"); tier != "" {
q = q.Where("tier = ?", tier)
}
if marketTag := c.Query("market_tag"); marketTag != "" {
q = q.Where("market_tag = ?", marketTag)
}
user := middleware.CurrentUser(c) user := middleware.CurrentUser(c)
isAdmin := user != nil && user.Role == "admin" isAdmin := user != nil && user.Role == "admin"
switch state := c.Query("state"); state {
case "":
q = q.Where("state = ?", "active")
case "all":
if !isAdmin {
q = q.Where("state = ?", "active")
}
case "system":
q = q.Where("state = ?", "system")
default:
q = q.Where("state = ?", state)
}
if c.Query("state") != "system" {
q = q.Where("state <> ?", "system")
}
var items []specialistmodel.Specialist items := specialistRepo.List(c.Query("tier"), c.Query("market_tag"), c.Query("state"), isAdmin)
if err := q.Order("sort_order ASC, id ASC").Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询专员目录失败"))
return
}
for i := range items { for i := range items {
specialistruntime.EnsureStructuredRecords(&items[i]) specialistruntime.EnsureStructuredRecords(&items[i])
} }
@@ -58,7 +31,7 @@ func GetSpecialistByKey(c *gin.Context) {
return return
} }
q := store.DB.Model(&specialistmodel.Specialist{}).Where("key = ?", key) q := specialistRepo.Query().Where("key = ?", key)
user := middleware.CurrentUser(c) user := middleware.CurrentUser(c)
isAdmin := user != nil && user.Role == "admin" isAdmin := user != nil && user.Role == "admin"
if !isAdmin { if !isAdmin {
@@ -66,7 +39,7 @@ func GetSpecialistByKey(c *gin.Context) {
} }
var item specialistmodel.Specialist var item specialistmodel.Specialist
if err := q.First(&item).Error; err != nil { if !q.First(&item) {
web.Fail(c, web.NewNotFoundError("专员不存在")) web.Fail(c, web.NewNotFoundError("专员不存在"))
return return
} }
@@ -87,14 +60,14 @@ func SpecialistSummary(c *gin.Context) {
} }
var resp summary var resp summary
// column 全是代码里写死的常量(tier / specialist_mode / market_tag),
// 没有一处来自请求参数。
count := func(column string, value string) int64 { count := func(column string, value string) int64 {
var total int64 q := specialistRepo.Query().Where("state = ?", "active")
q := store.DB.Model(&specialistmodel.Specialist{}).Where("state = ?", "active")
if column != "" { if column != "" {
q = q.Where(column+" = ?", value) q = q.Where(column+" = ?", value)
} }
q.Count(&total) return q.Count()
return total
} }
resp.Total = count("", "") resp.Total = count("", "")
@@ -7,15 +7,13 @@ import (
"strings" "strings"
"time" "time"
"gorm.io/gorm"
"eai_agentplatform/backend/internal/ai" "eai_agentplatform/backend/internal/ai"
"eai_agentplatform/backend/internal/config" "eai_agentplatform/backend/internal/config"
connectorcontracts "eai_agentplatform/backend/internal/connectors/core/contracts" connectorcontracts "eai_agentplatform/backend/internal/connectors/core/contracts"
connectorregistry "eai_agentplatform/backend/internal/connectors/registry" connectorregistry "eai_agentplatform/backend/internal/connectors/registry"
"eai_agentplatform/backend/internal/model" "eai_agentplatform/backend/internal/model"
"eai_agentplatform/backend/internal/repository"
specialistmodel "eai_agentplatform/backend/internal/specialists/model" specialistmodel "eai_agentplatform/backend/internal/specialists/model"
"eai_agentplatform/backend/internal/store"
) )
// Cfg 全局配置,由 internal/api.RegisterRoutes 注入。 // Cfg 全局配置,由 internal/api.RegisterRoutes 注入。
@@ -109,27 +107,6 @@ func MyTaskOwners(user *model.User) []string {
return owners return owners
} }
// MyTaskQuery 「我的任务」永远是"我自己的",管理员也只看自己的。
func MyTaskQuery(user *model.User) *gorm.DB {
owners := MyTaskOwners(user)
query := store.DB.Model(&model.TaskRecord{})
if len(owners) == 0 {
// 没有可用的归属标识,返回空集而不是全表
return query.Where("1 = 0")
}
return query.Where("owner IN ?", owners)
}
// ProjectQuery 「我的项目」永远只列自己的,归属判定复用 MyTaskOwners。
func ProjectQuery(user *model.User) *gorm.DB {
owners := MyTaskOwners(user)
query := store.DB.Model(&model.Project{})
if len(owners) == 0 {
return query.Where("1 = 0")
}
return query.Where("owner IN ?", owners)
}
// BuildTaskFromReq 由请求体构建任务记录。 // BuildTaskFromReq 由请求体构建任务记录。
func BuildTaskFromReq(req TaskReq, user *model.User) (model.TaskRecord, error) { func BuildTaskFromReq(req TaskReq, user *model.User) (model.TaskRecord, error) {
task := model.TaskRecord{ task := model.TaskRecord{
@@ -164,9 +141,10 @@ func BuildTaskFromReq(req TaskReq, user *model.User) (model.TaskRecord, error) {
task.DueAt = &parsed task.DueAt = &parsed
} }
// 挂项目:得确认这个项目是自己的,否则等于给别人的项目里塞任务。 // 挂项目:得确认这个项目是自己的,否则等于给别人的项目里塞任务。
// 「自己的」判定复用 MyTaskOwners —— 任务和项目的归属是同一套口径。
if req.ProjectID != nil && *req.ProjectID != 0 { if req.ProjectID != nil && *req.ProjectID != 0 {
var project model.Project project, found := repository.ProjectRepo{}.GetByIDForOwners(*req.ProjectID, MyTaskOwners(user))
if err := ProjectQuery(user).Where("id = ?", *req.ProjectID).First(&project).Error; err != nil { if !found {
return task, fmt.Errorf("项目不存在") return task, fmt.Errorf("项目不存在")
} }
task.ProjectID = &project.ID task.ProjectID = &project.ID