Files
pj0235-eai_agentplatform/eai_agentplatform/backend-go/internal/api/department.go
T
eaiadminandClaude Code e8aedd50d2 refactor: 后端仓库层更名为数据访问层(internal/repository → internal/dal)
「仓库层」是 repository 的直译,中文里与「代码仓库 / git 仓库」同词,
而这一层做的事就是数据访问。名字改成它实际在做的事。

改名口径(纯机械替换,无逻辑改动):
- 包:internal/repository → internal/dal(package repository → package dal)
- 类型:XxxRepo → XxxDAO(TaskRecordDAO / SpecialistDAO / PositionDAO …)
- 变量:xxxRepo → xxxDAO
- import 路径、包限定符、日志前缀 [repository] → [dal] 同步
- 注释里的「仓库层」→「数据访问层」;core.go 包注释补上 DAL/DAO 全称

命名规范补登(AR09 是命名问题的最高依据,改了名就得回去登记):
- AR09 §3.1 术语表新增「数据访问层 dal / DAO」一行
- AR09 §5.6 缩写表新增 DAO / dal —— 原文是「只有下表内的缩写允许使用」,
  不登记就是自己破自己的规矩
- PROJECT_STATE.md 新增 D27 记录本次更名决策

验证:全部在 db 副本上做,生产库 data/eai_agentplatform.db 未触碰。
- 等价性对照:拿 HEAD 源码 + 仅改名 造出第二棵树,两棵树各自起
  httptest 服务跑同一份探针(60 个 GET + 13 个写/回读,覆盖专员/技能/应用/
  任务/交付物/项目/岗位/考试/知识/积分/管理端只读等),逐端点比对响应体:
  73 项里 52 项字节完全一致、21 项仅运行期时间戳不同、内容差异 0。
- 探针非空:往改名后的树注入「SpecialistDAO.List 限 3 条」变异,
  /api/specialists 立刻被抓出 —— 证明上面那个 0 不是没测到。
- 暂存区自洽:把索引整个导出成源码树,go build / go vet / go test ./... 全绿。
- gofmt:因 import 排序变化而错位的 19 个文件已修;另 2 个文件(skill_definition.go、
  seed.go)的格式问题是工作区里别人的在制品带来的,未替其改动。

未纳入本次提交:工作区里正在进行中的「文生语音技能 + 技能展示色/交互卡」
(tts_handlers.go、text_to_speech/manifest.go、skillCatalog.js 等),
以及 router.go / skill_definition.go / seed.go 三个文件里属于该在制品的改动 ——
这三个文件只把「改名那一版」放进索引,工作区原样保留。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-19 09:19:21 +08:00

261 lines
6.5 KiB
Go

package api
import (
"fmt"
"sort"
"strings"
"github.com/gin-gonic/gin"
"eai_agentplatform/backend/internal/dal"
"eai_agentplatform/backend/internal/model"
"eai_agentplatform/backend/internal/web"
)
// deptDAO 部门仓库(便于测试时覆写),包内共享。
var deptDAO dal.DepartmentDAO
func init() {
deptDAO = dal.DepartmentDAO{}
}
// ListDepartments GET /api/departments?status= —— 部门字典列表(含成员数)
func ListDepartments(c *gin.Context) {
items := deptDAO.ListByStatus(c.Query("status"))
// 成员数按 user.department 字符串匹配(部门为字典、用户以字符串归属)
users := userDAO.ListEmployees("active")
nameCount := map[string]int{}
for _, u := range users {
if strings.TrimSpace(u.Department) != "" {
nameCount[u.Department]++
}
}
out := make([]gin.H, 0, len(items))
for _, d := range items {
out = append(out, gin.H{
"id": d.ID,
"name": d.Name,
"description": d.Description,
"status": d.Status,
"member_count": nameCount[d.Name],
"created_at": d.CreatedAt,
})
}
web.OK(c, out)
}
// CreateDepartment POST /api/departments (admin)
func CreateDepartment(c *gin.Context) {
var req struct {
Name string `json:"name"`
Description string `json:"description"`
}
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Name) == "" {
web.Fail(c, web.NewBadRequest("部门名称为必填"))
return
}
req.Name = strings.TrimSpace(req.Name)
if deptDAO.CountByName(req.Name, nil) > 0 {
web.Fail(c, web.NewConflictError("部门名称已存在"))
return
}
d := model.Department{Name: req.Name, Description: req.Description, Status: "active"}
if !deptDAO.Insert(&d) {
web.Fail(c, web.NewBadRequest("创建部门失败"))
return
}
web.OK(c, d)
}
// UpdateDepartment PUT /api/departments/{id} (admin) —— 改名时同步 user.department 字符串
func UpdateDepartment(c *gin.Context) {
id, ok := parseID(c, "id")
if !ok {
return
}
d, found := deptDAO.GetByID(id)
if !found {
web.Fail(c, web.NewNotFoundError("部门不存在"))
return
}
var req struct {
Name string `json:"name"`
Description string `json:"description"`
Status string `json:"status"`
}
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Name) == "" {
web.Fail(c, web.NewBadRequest("部门名称为必填"))
return
}
req.Name = strings.TrimSpace(req.Name)
oldName := d.Name
if req.Name != oldName {
if deptDAO.CountByName(req.Name, &id) > 0 {
web.Fail(c, web.NewConflictError("部门名称已存在"))
return
}
}
d.Name = req.Name
d.Description = req.Description
if req.Status == "active" || req.Status == "inactive" {
d.Status = req.Status
}
if !deptDAO.Update(&d) {
web.Fail(c, web.NewBadRequest("更新部门失败"))
return
}
// 改名后同步员工归属,保证按部门统计与展示一致
if req.Name != oldName {
userDAO.RenameDepartment(oldName, req.Name)
}
web.OK(c, d)
}
// DeleteDepartment DELETE /api/departments/{id} (admin) —— 有员工归属时拒绝删除
func DeleteDepartment(c *gin.Context) {
id, ok := parseID(c, "id")
if !ok {
return
}
d, found := deptDAO.GetByID(id)
if !found {
web.Fail(c, web.NewNotFoundError("部门不存在"))
return
}
if n := userDAO.CountActiveByDepartment(d.Name); n > 0 {
web.Fail(c, web.NewConflictError(fmt.Sprintf("该部门下仍有 %d 名员工,请先调整其部门", n)))
return
}
if !deptDAO.Delete(id) {
web.Fail(c, web.NewBadRequest("删除部门失败"))
return
}
web.OK(c, gin.H{"id": id, "deleted": true})
}
// DepartmentStats GET /api/system/department-stats —— 按部门学情聚合
func DepartmentStats(c *gin.Context) {
employees := userDAO.ListEmployees("active")
// 每用户聚合:积分 / 考试 / 学习进度
type userAgg struct {
Points int
FormalCount int
FormalPassed int
ScoreSum int
CompanyViewed bool
ProductCount int
CourseCount int
}
perUser := map[uint]*userAgg{}
get := func(id uint) *userAgg {
a := perUser[id]
if a == nil {
a = &userAgg{}
perUser[id] = a
}
return a
}
for _, e := range employees {
get(e.ID).Points = e.LearningPoints
}
recs := examRecordDAO.ListAll()
for _, r := range recs {
a := get(r.UserID)
a.FormalCount++
if r.Passed {
a.FormalPassed++
}
a.ScoreSum += r.Score
}
lps := learningDAO.ListAll()
for _, lp := range lps {
a := get(lp.UserID)
switch lp.ItemType {
case "company":
a.CompanyViewed = true
case "product":
a.ProductCount++
case "course":
a.CourseCount++
}
}
// 按部门字符串聚合
type deptAgg struct {
EmployeeCount int
PointsTotal int
FormalCount int
FormalPassed int
ScoreSum int
CompanyViewed int
ProductSum int
CourseSum int
}
perDept := map[string]*deptAgg{}
order := []string{}
for _, e := range employees {
name := strings.TrimSpace(e.Department)
if name == "" {
name = "未分组"
}
a := perDept[name]
if a == nil {
a = &deptAgg{}
perDept[name] = a
order = append(order, name)
}
a.EmployeeCount++
if u := perUser[e.ID]; u != nil {
a.PointsTotal += u.Points
a.FormalCount += u.FormalCount
a.FormalPassed += u.FormalPassed
a.ScoreSum += u.ScoreSum
if u.CompanyViewed {
a.CompanyViewed++
}
a.ProductSum += u.ProductCount
a.CourseSum += u.CourseCount
}
}
// 排序:未分组沉底,其余按名称
sort.Slice(order, func(i, j int) bool {
if order[i] == "未分组" {
return false
}
if order[j] == "未分组" {
return true
}
return order[i] < order[j]
})
out := make([]gin.H, 0, len(order))
for _, name := range order {
a := perDept[name]
passRate, avgScore, companyRate, productAvg, courseAvg := 0.0, 0.0, 0.0, 0.0, 0.0
if a.FormalCount > 0 {
passRate = round1(float64(a.FormalPassed) * 100 / float64(a.FormalCount))
avgScore = round1(float64(a.ScoreSum) / float64(a.FormalCount))
}
if a.EmployeeCount > 0 {
companyRate = round1(float64(a.CompanyViewed) * 100 / float64(a.EmployeeCount))
productAvg = round1(float64(a.ProductSum) / float64(a.EmployeeCount))
courseAvg = round1(float64(a.CourseSum) / float64(a.EmployeeCount))
}
out = append(out, gin.H{
"department": name,
"employee_count": a.EmployeeCount,
"points_total": a.PointsTotal,
"formal_count": a.FormalCount,
"formal_passed": a.FormalPassed,
"pass_rate": passRate,
"avg_score": avgScore,
"company_rate": companyRate,
"product_avg": productAvg,
"course_avg": courseAvg,
})
}
web.OK(c, gin.H{"items": out})
}