refactor: 后端仓库层收口(A1:课程/产品/素材)+ 收进工作区既有对象化重构

本提交含两部分。第一部分是本轮工作;第二部分是此前一直留在工作区、
从未提交的对象化重构,与第一部分在文件上互相咬合(internal/repository
整个包都是未跟踪状态,且 api 层已有文件引用它),无法拆成两个可编译的提交。

一、仓库层收口 A1 批(本轮工作)

把 api 层手写的 store.DB 查询收进具名仓库方法,只给真正获益的对象做方法,
不机械包裹全量。本批迁移 22 处裸查询(courses.go 9 / media.go 12 / products.go 1),
新增方法:

- MediaFileRepo.ListByBind / ListForAudit / MarkExtracted
- KnowledgeChunkRepo.CountByMediaFile
- ProductRepo.GetVisibleByID

两条业务口径改由仓库单点持有,避免各处手写漂移:
「只有 approved 素材出现在课程详情」与「已停用产品不在课程详情露出」。

修掉两个真实缺陷:
- ProductRepo.GetByID 缺 Where 条件。此前 GET /api/products/{id} 对任意 id 都返回
  第一条产品、对不存在的 id 返回 200,且 PUT /api/products/{id} 会覆盖第一条产品
  —— 数据损坏级。全仓扫描确认这是唯一一处同型写法。
- ProductRepo.Delete 写 status="deleted",而 DELETE 处理器文档与回包都声称
  "inactive",接口在说谎;管理员用 status=all 拉列表会看到前端不认识的状态。
  已对齐为 inactive(与 CourseRepo.Delete 一致)。

删除 8 个零调用且列名不存在的死方法(一调即 SQL 报错):
- media_file 上的 file_path / file_type / approval_status 三列并不存在,
  GetByPath / ListByType / UpdateStatus 全废
- knowledge_chunk 上的 space_id 列不存在(模型早已改为 knowledge_space_key),
  List / Total / ListBySpaceIDs / DeleteBySpace / SearchByVector 全废
取舍边界:能对当前 schema 跑通的死方法保留,跑不通的删或修。

CourseRepo.List 补齐 status=all 档(此前传给它会当作 status='all' 过滤出空列表)。
该方法此前零调用,现与产品列表语义对齐。

验证:go build ./... 与 go test ./... 全绿;另用真实 HTTP 请求验证 34 项
(课程 17 / 产品 3 / 素材 14),跑在数据库副本与独立 KB_DATA_DIR 上,
含 multipart 真上传 → 审批 → pdftotext 提取 → 分片入库的完整链路。

二、此前未提交的对象化重构(非本轮工作)

- 新增 internal/repository 仓库层、connectors、skills、specialists、xapps、jsonutil,
  model/task_record|task_run|task_artifact、api/task_runtime|action_definition|chat_message
- 删除 api/app_definition、connectors、my_app_center、notification、office_skill、
  export_docx|pptx|xlsx、official_account_* 等,随 XApp/Skill/Specialist/Connector
  可插拔打包方向(AR10/AR11)调整
- 资产目录归位:backend-go/knowledge_source → assets/knowledge/source、
  training_materials → assets/training/materials;README 内相对路径同步加深两级;
  deploy env 补 ASSET_ROOT_DIR 并改 KNOWLEDGE_SOURCE_DIR / TRAINING_MATERIALS_DIR
- 前端新增 skills/ specialists/ connectors/ xapps/ 目录与对应页面

验证:前端 npm run build 通过(7.26s)。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
eaiadmin
2026-09-19 01:23:51 +08:00
co-authored by Claude Code
parent ddd2d2cbd8
commit 14f303459e
448 changed files with 18792 additions and 17027 deletions
@@ -11,21 +11,32 @@ import (
"eai_agentplatform/backend/internal/auth"
"eai_agentplatform/backend/internal/model"
"eai_agentplatform/backend/internal/store"
"eai_agentplatform/backend/internal/repository"
"eai_agentplatform/backend/internal/web"
)
var (
userRepo repository.UserRepo
examRecordRepo repository.ExamRecordRepo
configRepo repository.SystemConfigRepo
)
func init() {
userRepo = repository.UserRepo{}
examRecordRepo = repository.ExamRecordRepo{}
configRepo = repository.SystemConfigRepo{}
}
// ============ 用户管理(管理员) ============
// ListUsers GET /api/system/users —— 含考试统计(考试次数/通过数/最近成绩)
func ListUsers(c *gin.Context) {
var users []model.User
if err := store.DB.Order("id ASC").Find(&users).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询用户失败"))
return
}
var items []model.User
userRepo.Query().Type(&model.User{}).Order("id ASC").Find(&items)
// 获取考试记录
var recs []model.ExamRecord
store.DB.Order("submitted_at DESC").Find(&recs)
examRecordRepo.Inner().Model(&model.ExamRecord{}).Order("submitted_at DESC").Find(&recs)
type stat struct {
ExamCount int
@@ -55,15 +66,15 @@ func ListUsers(c *gin.Context) {
}
}
out := make([]gin.H, 0, len(users))
for _, u := range users {
out := make([]gin.H, 0, len(items))
for _, u := range items {
h := gin.H{
"id": u.ID, "username": u.Username, "full_name": u.FullName,
"role": u.Role, "status": u.Status, "ai_points": u.AiPoints,
"department": u.Department, "position": u.Position, "hire_batch": u.HireBatch,
"position_id": u.PositionID,
"created_at": u.CreatedAt,
"exam_count": 0, "passed_count": 0,
"created_at": u.CreatedAt,
"exam_count": 0, "passed_count": 0,
"latest_score": nil, "latest_passed": nil, "latest_exam_name": "", "latest_submitted_at": nil,
}
if s := stats[u.ID]; s != nil {
@@ -97,9 +108,8 @@ func CreateUser(c *gin.Context) {
if req.Role != "admin" && req.Role != "employee" {
req.Role = "employee"
}
var count int64
store.DB.Model(&model.User{}).Where("username = ?", req.Username).Count(&count)
if count > 0 {
_, found := userRepo.GetByUsername(req.Username)
if found {
web.Fail(c, web.NewConflictError("用户名已存在"))
return
}
@@ -116,7 +126,7 @@ func CreateUser(c *gin.Context) {
if req.Role == "admin" {
u.AiPoints = 999999
}
if err := store.DB.Create(&u).Error; err != nil {
if !userRepo.Insert(&u) {
web.Fail(c, web.NewBadRequest("创建用户失败"))
return
}
@@ -129,8 +139,8 @@ func UpdateUser(c *gin.Context) {
if !ok {
return
}
var u model.User
if err := store.DB.First(&u, id).Error; err != nil {
u, found := userRepo.GetByID(id)
if !found {
web.Fail(c, web.NewNotFoundError("用户不存在"))
return
}
@@ -181,7 +191,7 @@ func UpdateUser(c *gin.Context) {
}
u.AiPoints = *req.AiPoints
}
if err := store.DB.Save(&u).Error; err != nil {
if !userRepo.Update(&u) {
web.Fail(c, web.NewBadRequest("更新用户失败"))
return
}
@@ -190,11 +200,9 @@ func UpdateUser(c *gin.Context) {
// defaultAiPoints 读取新用户默认 AI 算力点(system_config.ai_points_default,缺省 100)
func defaultAiPoints() int {
var sc model.SystemConfig
if err := store.DB.Where("config_key = ?", "ai_points_default").First(&sc).Error; err == nil {
if v, err := strconv.Atoi(strings.TrimSpace(sc.ConfigValue)); err == nil {
return v
}
val := configRepo.GetByKey("ai_points_default")
if v, err := strconv.Atoi(strings.TrimSpace(val)); err == nil {
return v
}
return 100
}
@@ -203,29 +211,30 @@ func defaultAiPoints() int {
// ListExamRecords GET /api/system/exam-records?user_id=&paper_id=
func ListExamRecords(c *gin.Context) {
q := store.DB.Model(&model.ExamRecord{})
if uid := c.Query("user_id"); uid != "" {
q = q.Where("user_id = ?", uid)
}
if pid := c.Query("paper_id"); pid != "" {
q = q.Where("paper_id = ?", pid)
}
var items []model.ExamRecord
if err := q.Order("submitted_at DESC").Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询成绩失败"))
return
}
items := examRecordRepo.List(c.Query("user_id"), c.Query("paper_id"))
web.OK(c, items)
}
// pointerUint 将字符串解析为 *uint;空串返回 nil。
func pointerUint(s string) *uint {
if s == "" {
return nil
}
if v, err := strconv.ParseUint(s, 10, 32); err == nil {
uv := uint(v)
return &uv
}
return nil
}
// GetExamRecord GET /api/system/exam-records/{id} —— 详情
func GetExamRecord(c *gin.Context) {
id, ok := parseID(c, "id")
if !ok {
return
}
var rec model.ExamRecord
if err := store.DB.First(&rec, id).Error; err != nil {
rec, found := examRecordRepo.GetByID(id)
if !found {
web.Fail(c, web.NewNotFoundError("考试记录不存在"))
return
}
@@ -245,12 +254,7 @@ func DeleteExamRecord(c *gin.Context) {
if !ok {
return
}
var rec model.ExamRecord
if err := store.DB.First(&rec, id).Error; err != nil {
web.Fail(c, web.NewNotFoundError("考试记录不存在"))
return
}
if err := store.DB.Delete(&rec).Error; err != nil {
if !examRecordRepo.Remove(id) {
web.Fail(c, web.NewBadRequest("删除考试记录失败"))
return
}
@@ -259,14 +263,14 @@ func DeleteExamRecord(c *gin.Context) {
// ExportExamRecords GET /api/system/exam-records/export —— 导出 CSV(支持 user_id/paper_id 过滤)
func ExportExamRecords(c *gin.Context) {
q := store.DB.Model(&model.ExamRecord{})
var items []model.ExamRecord
q := repository.DB.Model(&model.ExamRecord{})
if uid := c.Query("user_id"); uid != "" {
q = q.Where("user_id = ?", uid)
}
if pid := c.Query("paper_id"); pid != "" {
q = q.Where("paper_id = ?", pid)
}
var items []model.ExamRecord
if err := q.Order("submitted_at DESC").Find(&items).Error; err != nil {
web.Fail(c, web.NewBadRequest("查询成绩失败"))
return
@@ -274,7 +278,7 @@ func ExportExamRecords(c *gin.Context) {
// 用户名映射
var users []model.User
store.DB.Find(&users)
repository.DB.Find(&users)
nameMap := map[uint]model.User{}
for _, u := range users {
nameMap[u.ID] = u
@@ -312,8 +316,7 @@ func ExportExamRecords(c *gin.Context) {
// GetConfig GET /api/system/config —— 所有系统参数
func GetConfig(c *gin.Context) {
var items []model.SystemConfig
store.DB.Order("id ASC").Find(&items)
items := configRepo.List()
type cfgItem struct {
Key string `json:"config_key"`
Value string `json:"config_value"`
@@ -335,14 +338,14 @@ func UpdateConfig(c *gin.Context) {
web.Fail(c, web.NewBadRequest("configs 必填"))
return
}
for k, v := range req.Configs {
var sc model.SystemConfig
if err := store.DB.Where("config_key = ?", k).First(&sc).Error; err == nil {
sc.ConfigValue = v
store.DB.Save(&sc)
} else {
store.DB.Create(&model.SystemConfig{ConfigKey: k, ConfigValue: v})
}
}
configRepo.BulkUpsert(toSystemConfigs(req.Configs))
web.OK(c, gin.H{"updated": len(req.Configs)})
}
func toSystemConfigs(m map[string]string) []model.SystemConfig {
items := make([]model.SystemConfig, 0, len(m))
for k, v := range m {
items = append(items, model.SystemConfig{ConfigKey: k, ConfigValue: v})
}
return items
}