feat(be): 记录类型挪进数据库,后台可配 + 15 种新类型

## 为什么
9 种记录类型全是低频医疗和记账(疫苗一年一次、驱虫一季一次、体检更少),
用户今天打开 App 大概率没什么可记,时间轴是空的。竞品 35 种里有 26 种是
高频日常(洗澡/剪指甲/换猫砂/喝水/洗食盆),那才是每天打开的理由。

## 一个比预想好得多的发现
本来担心加类型会踩到分析逻辑。把那 9 个常量的引用全捞了一遍,结论是不会:

  weight       record.go:83 回写宠物体重;home/insight/report 的体重趋势与基准
  food + poop  insight.go:130 食便相关性
  symptom      insight.go:160 症状聚类;report 高风险计数
  cost         report.go:99 消费统计
  vaccine      report.go:137 疫苗完成度
  deworm/medicine/photo  没有任何特殊分支

这些分支全都是「按某个具体常量过滤」,没有一处是 switch 全枚举、也没有
default 兜底。CreateRecord 更是完全没有 type 白名单校验。所以新增类型
不可能碰到任何现存逻辑——一行分析代码都不用改。

于是分工是:
  record_types 表  负责「展示什么、能记什么」
  那 9 个常量      负责「哪几种参与分析」
两者各管一段,常量一个都没删。

## 表设计
code / label / icon / group_key / sort / enabled / form / locked。

group_key 而不是 group:group 是 MySQL 保留字,GORM 会加反引号所以能跑,
但手写 SQL 排查时很容易踩。

form 区分 full(弹层里有专用 wx:elif 分支)和 simple(时间+备注+照片)。
15 种新类型全是 simple——下一步在弹层加一个通用分支吃掉它们,不然 28 个
分支再加 15 个会把 bottom-sheet 写到 1800 行。

locked 给那 9 种:有代码分支依赖、且被 care_template_items.sheet_type 引用。

## 两条硬拦在 service 层的规则
1. locked 的删不掉
2. 已经有记录的删不掉(删了历史记录会变孤儿)
想让它从记录页消失应该用 enabled=false,历史记录仍能正常显示。

都在 service 层拦,不是靠前端隐藏按钮。改 code 同样受 2 的约束——
code 是落库值,改了历史记录会对不上任何类型。

## bootstrap 的取舍
文章和养护模板当初按你的要求从代码里挪走了,这次 24 种类型仍然放在 seed 里,
因为它不是内容而是结构:表空着记录页一个可记事项都没有,App 直接不能用。
和管理员账号一样,只在表**完全为空**时铺一次,之后一切以数据库为准。
表非空就完全不碰,否则后台删掉的类型会每次重启自己长回来。

ListRecordTypes 在表为空时返回空数组 + 打 warn,不硬编码兜底一份——
那等于把「可配置」又变回代码常量,下次改配置的人会发现改了没用。

## 图标
新增 15 个(iconfont.wxss 40 → 55),全部取自本地那份 tabler-icons-3.46.0
真源,不是凭记忆画路径。已解码抽检确认路径非空。

## 验证(生产库实跑)
  建表 + 24 条 bootstrap 一次到位,分组 daily6/health7/care6/clean5
  locked 9 个、simple 表单 15 个
  规则 1  删 weight → 「有统计和分析逻辑依赖它,不能删」
  规则 2  新增 nose 成功 → 重复 code 报错 → 删除成功
  规则 3  造 1 条 tmptest 记录 → 删类型被拦;删掉记录后再删 → 成功;残留 0
  规则 4  停用「美容」→ 小程序端洗护组只剩 5 项;恢复后回到 6 项

规则 3 一开始没真验到:库里唯一的记录类型是 weight,locked 先拦住了,
「已有记录」那个分支根本没走到。补了个造真记录的测试才算验过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-07-30 09:24:24 +08:00
parent 09322ecbec
commit 60ee9d4bbc
10 changed files with 733 additions and 4 deletions
+70 -4
View File
@@ -8,11 +8,77 @@ import (
"github.com/sundynix/pets-be/internal/model"
)
// Seed 初始化种子数据:只建管理员账号。
// 文章这类内容数据不放代码里——正文几百字塞进 Go 源文件,既看不清也
// 没法在后台改完再同步回来。上线时直接同步数据库。
// Seed 初始化种子数据:管理员账号 + 记录类型
//
// 文章、养护模板这类**内容**数据不放代码里——正文几百字塞进 Go 源文件,既看不清
// 也没法在后台改完再同步回来。上线时直接同步数据库。
//
// 记录类型是另一码事,它是**结构**:表空着的话记录页一个可记事项都没有,
// App 直接不能用。所以和管理员账号一样,只在表完全为空时铺一次底,
// 之后一切以数据库为准,代码里这份不再参与。
func Seed(db *gorm.DB, cfg *config.Config) error {
return seedAdmin(db, cfg)
if err := seedAdmin(db, cfg); err != nil {
return err
}
return seedRecordTypes(db)
}
// seedRecordTypes 只在表为空时跑。已经有数据(哪怕只有一条)就完全不碰,
// 否则后台删掉的类型会在每次重启后自己长回来
func seedRecordTypes(db *gorm.DB) error {
var count int64
if err := db.Model(&model.RecordType{}).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return nil
}
// locked=true 的这 9 种在 record.go / insight.go / report.go / home.go 里有真实
// 代码分支(体重回写档案、食便相关性、消费统计、疫苗完成度…),并且被
// care_template_items.sheet_type 引用,后台不许删,只能停用。
// form=full 表示 bottom-sheet 里有它专用的 wx:elif 分支。
full := func(code, label, icon, group string, sort int) model.RecordType {
return model.RecordType{Code: code, Label: label, Icon: icon, GroupKey: group,
Sort: sort, Enabled: true, Form: model.RecordFormFull, Locked: true}
}
simple := func(code, label, icon, group string, sort int) model.RecordType {
return model.RecordType{Code: code, Label: label, Icon: icon, GroupKey: group,
Sort: sort, Enabled: true, Form: model.RecordFormSimple, Locked: false}
}
d, h, c, cl := model.RecordGroupDaily, model.RecordGroupHealth, model.RecordGroupCare, model.RecordGroupClean
types := []model.RecordType{
// 日常
full("weight", "体重", "weight", d, 10),
full("poop", "排便", "poop", d, 20),
full("food", "饮食", "food", d, 30),
simple("water", "喝水", "water", d, 40),
full("cost", "记账", "cost", d, 50),
full("photo", "照片", "photo", d, 60),
// 健康
full("symptom", "异常", "symptom", h, 10),
full("vaccine", "疫苗", "vaccine", h, 20),
full("deworm", "驱虫", "deworm", h, 30),
simple("checkup", "体检", "checkup", h, 40),
simple("vet", "看病", "vet", h, 50),
full("medicine", "给药", "medicine", h, 60),
simple("supplement", "保健品", "supplement", h, 70),
// 洗护
simple("bath", "洗澡", "bath", c, 10),
simple("nail", "剪指甲", "nail", c, 20),
simple("ear", "洗耳朵", "ear", c, 30),
simple("tooth", "刷牙", "tooth", c, 40),
simple("brush", "梳毛", "brush", c, 50),
simple("groom", "美容", "groom", c, 60),
// 清洁
simple("litter", "换猫砂", "litter", cl, 10),
simple("litterbox", "洗猫砂盆", "litterbox", cl, 20),
simple("bowl", "洗食盆", "bowl", cl, 30),
simple("waterbowl", "洗水盆", "waterbowl", cl, 40),
simple("clean", "消毒", "clean", cl, 50),
}
return db.Create(&types).Error
}
func seedAdmin(db *gorm.DB, cfg *config.Config) error {
+47
View File
@@ -280,6 +280,53 @@ func (h *Handler) AdminListPro(c *gin.Context) {
// AdminCareTemplateMeta GET /api/admin/care-templates/meta
// 给后台下拉用:物种、阶段、可选关联记录/弹层类型、提醒类型
// ── 记录类型 ──
type recordTypeReq struct {
ID string `json:"id"`
Code string `json:"code"`
Label string `json:"label"`
Icon string `json:"icon"`
Group string `json:"group"`
Sort int `json:"sort"`
Enabled bool `json:"enabled"`
Form string `json:"form"`
}
// AdminListRecordTypes GET /api/admin/record-types 连停用的一起返回
func (h *Handler) AdminListRecordTypes(c *gin.Context) {
response.OK(c, h.svc.AdminListRecordTypes())
}
// AdminSaveRecordType POST /api/admin/record-types 新增或更新
func (h *Handler) AdminSaveRecordType(c *gin.Context) {
var req recordTypeReq
if err := c.ShouldBindJSON(&req); err != nil {
response.FailParams(c, err.Error())
return
}
t := &model.RecordType{
Code: req.Code, Label: req.Label, Icon: req.Icon,
GroupKey: req.Group, Sort: req.Sort, Enabled: req.Enabled, Form: req.Form,
}
t.ID = req.ID
if err := h.svc.SaveRecordType(t); err != nil {
respondErr(c, err)
return
}
response.OK(c, t)
}
// AdminDeleteRecordType DELETE /api/admin/record-types/:id
// locked 的和已有记录的删不了,service 层硬拦
func (h *Handler) AdminDeleteRecordType(c *gin.Context) {
if err := h.svc.DeleteRecordType(idParam(c, "id")); err != nil {
respondErr(c, err)
return
}
response.OK(c, nil)
}
func (h *Handler) AdminCareTemplateMeta(c *gin.Context) {
response.OK(c, gin.H{
"species": []gin.H{
+6
View File
@@ -90,3 +90,9 @@ func (h *Handler) PetInsights(c *gin.Context) {
}
response.OK(c, list)
}
// RecordTypes GET /api/record-types 记录页可记事项,按分组归好。
// 类型从表里来而不是前端写死,后台加一种不用发版
func (h *Handler) RecordTypes(c *gin.Context) {
response.OK(c, h.svc.ListRecordTypes())
}
+1
View File
@@ -29,6 +29,7 @@ func AllModels() []any {
&User{},
&Pet{},
&HealthRecord{},
&RecordType{},
&DailyTask{},
&Plan{},
&PlanTask{},
+47
View File
@@ -0,0 +1,47 @@
package model
// 记录类型。原来这 9 种是写在 health_record.go 里的常量,加一种就得发版;
// 挪到表里之后后台可以直接增删改。
//
// 注意这里**没有**替换掉那 9 个常量:weight / poop / food / symptom / cost /
// vaccine 在 record.go、insight.go、report.go、home.go 里有真实的代码分支
// (体重回写宠物档案、食便相关性分析、消费统计、疫苗完成度……),那些分支
// 按具体常量过滤,不是 switch 全枚举。所以:
// - 表负责「展示什么、能记什么」
// - 常量负责「哪几种参与分析」
// 两者各管一段,新增类型不会碰到任何分析逻辑。
// 记录类型分组
const (
RecordGroupDaily = "daily" // 日常
RecordGroupHealth = "health" // 健康
RecordGroupCare = "care" // 洗护
RecordGroupClean = "clean" // 清洁
)
// 弹层形态
const (
RecordFormFull = "full" // 有专用表单(原来那 9 种,各自一个 wx:elif 分支)
RecordFormSimple = "simple" // 通用简易表单:发生时间 + 备注 + 可选照片
)
// RecordType 一种可记录的事项
type RecordType struct {
Base
// Code 就是小程序 bottom-sheet 的 type,也是 health_records.type 落库的值。
// 建过记录之后改 Code 会让历史数据对不上,后台不允许改(只能删了重建)。
Code string `gorm:"size:32;uniqueIndex" json:"code"`
Label string `gorm:"size:32" json:"label"`
Icon string `gorm:"size:32" json:"icon"` // pt-icon 名,见 styles/iconfont.wxss
// GroupKey 存成 group_key 而不是 groupgroup 是 MySQL 保留字,
// GORM 虽然会加反引号,但手写 SQL 排查时很容易踩
GroupKey string `gorm:"column:group_key;size:16;index" json:"group"`
Sort int `json:"sort"`
Enabled bool `gorm:"default:true" json:"enabled"`
Form string `gorm:"size:16" json:"form"`
// Locked 有代码分支或模板引用依赖它,后台不许删。
// 硬拦在 service 层,不是靠前端隐藏按钮。
Locked bool `json:"locked"`
}
+5
View File
@@ -57,6 +57,7 @@ func registerUserAPI(api *gin.RouterGroup, h *handler.Handler, jm *appjwt.Manage
g.PUT("/pets/:id", h.UpdatePet)
g.DELETE("/pets/:id", h.DeletePet)
g.GET("/record-types", h.RecordTypes)
g.GET("/pets/:id/records", h.ListRecords)
g.POST("/pets/:id/records", h.CreateRecord)
g.GET("/pets/:id/records/weight-trend", h.WeightTrend)
@@ -147,6 +148,10 @@ func registerAdminAPI(api *gin.RouterGroup, h *handler.Handler, jm *appjwt.Manag
g.POST("/articles", h.AdminSaveArticle)
g.DELETE("/articles/:id", h.AdminDeleteArticle)
g.GET("/record-types", h.AdminListRecordTypes)
g.POST("/record-types", h.AdminSaveRecordType)
g.DELETE("/record-types/:id", h.AdminDeleteRecordType)
g.GET("/care-templates/meta", h.AdminCareTemplateMeta)
g.GET("/care-templates", h.AdminGetCareTemplate)
g.PUT("/care-templates", h.AdminSaveCareTemplate)
+127
View File
@@ -0,0 +1,127 @@
package service
import (
"errors"
"log"
"strconv"
"gorm.io/gorm"
"github.com/sundynix/pets-be/internal/model"
)
// 分组展示顺序。前端按这个顺序渲染,不靠 group_key 的字典序
var recordGroupOrder = []struct {
Key string
Label string
}{
{model.RecordGroupDaily, "日常记录"},
{model.RecordGroupHealth, "健康记录"},
{model.RecordGroupCare, "洗护记录"},
{model.RecordGroupClean, "清洁记录"},
}
// RecordTypeGroup 一组类型,给小程序记录页直接渲染
type RecordTypeGroup struct {
Key string `json:"key"`
Label string `json:"label"`
Items []model.RecordType `json:"items"`
}
// ListRecordTypes 小程序用:只返回启用的,按分组归好
func (s *Service) ListRecordTypes() []RecordTypeGroup {
var all []model.RecordType
s.db.Where("enabled = ?", true).Order("sort asc, id asc").Find(&all)
if len(all) == 0 {
// 表被清空了。这里不硬编码兜底一份——那等于把「可配置」又变回代码里的常量,
// 下次改配置的人会发现改了没用。宁可返回空让记录页明显是空的,也别静默用旧值。
log.Println("[warn] record_types 表为空,记录页会没有任何可记事项")
return []RecordTypeGroup{}
}
byGroup := map[string][]model.RecordType{}
for _, t := range all {
byGroup[t.GroupKey] = append(byGroup[t.GroupKey], t)
}
out := make([]RecordTypeGroup, 0, len(recordGroupOrder))
for _, g := range recordGroupOrder {
items := byGroup[g.Key]
if len(items) == 0 {
continue
}
out = append(out, RecordTypeGroup{Key: g.Key, Label: g.Label, Items: items})
}
return out
}
// AdminListRecordTypes 后台用:连禁用的一起返回,按分组顺序再按 sort
func (s *Service) AdminListRecordTypes() []model.RecordType {
var all []model.RecordType
s.db.Order("group_key asc, sort asc, id asc").Find(&all)
if all == nil {
return []model.RecordType{}
}
return all
}
// SaveRecordType 新增或更新。Code 一旦建过记录就不允许改——
// 改了历史记录的 type 会对不上任何类型,列表里直接变成一行没图标没名字的东西
func (s *Service) SaveRecordType(in *model.RecordType) error {
if in.Code == "" || in.Label == "" {
return ErrInvalidParam
}
if in.Form != model.RecordFormFull && in.Form != model.RecordFormSimple {
in.Form = model.RecordFormSimple
}
if in.GroupKey == "" {
in.GroupKey = model.RecordGroupDaily
}
if in.ID == "" {
// 新增:Code 不能和已有的撞
var n int64
s.db.Model(&model.RecordType{}).Where("code = ?", in.Code).Count(&n)
if n > 0 {
return errors.New("这个 code 已经存在了")
}
in.Locked = false // 新加的一律可删;locked 只由 bootstrap 给那 9 种
return s.db.Create(in).Error
}
var old model.RecordType
if err := s.db.First(&old, "id = ?", in.ID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrNotFound
}
return err
}
if old.Code != in.Code {
var used int64
s.db.Model(&model.HealthRecord{}).Where("type = ?", old.Code).Count(&used)
if used > 0 {
return errors.New("已经有 " + strconv.FormatInt(used, 10) + " 条记录用了这个 code,不能改,只能新建一个")
}
}
// locked 和 form 不由后台改:前者是代码依赖,后者对应弹层里真实存在的分支
return s.db.Model(&model.RecordType{}).Where("id = ?", in.ID).Updates(map[string]any{
"code": in.Code, "label": in.Label, "icon": in.Icon,
"group_key": in.GroupKey, "sort": in.Sort, "enabled": in.Enabled,
}).Error
}
// DeleteRecordType locked 的删不了;已经有记录的也删不了(会让历史数据变孤儿)。
// 想让它从记录页消失应该用 enabled=false,历史记录还能正常显示
func (s *Service) DeleteRecordType(id string) error {
var t model.RecordType
if err := s.db.First(&t, "id = ?", id).Error; err != nil {
return ErrNotFound
}
if t.Locked {
return errors.New("「" + t.Label + "」有统计和分析逻辑依赖它,不能删。想隐藏请改成停用")
}
var used int64
s.db.Model(&model.HealthRecord{}).Where("type = ?", t.Code).Count(&used)
if used > 0 {
return errors.New("已经有 " + strconv.FormatInt(used, 10) + " 条「" + t.Label + "」记录,删了这些记录会变成孤儿。想隐藏请改成停用")
}
return s.db.Delete(&model.RecordType{}, "id = ?", id).Error
}