fix: 布尔字段的「没传」与「传 false」被库默认值合并

三处同一形状的缺陷:模型的 bool 字段带 `gorm:"default:true"`,而 GORM 在
Create 时会跳过「带 default 标签的零值字段」,于是 Go 里的 false 被当成「没填」,
改由库默认值 true 生效。对象显式设的 false 被持久层改写成 true。

- skill_definition.exposed_to_user
- xapp_definition.exposed_to_user
- position_knowledge.is_mandatory

前两处有两个方向的病症:

1. 创建接口设不出 false —— 管理员建一个「不暴露给用户」的技能/应用,
   接口返回 200、看着成功,库里存的是 true。
2. **更新接口会静默撤下** —— 前端 admin 表单根本不发 exposed_to_user
   (只读不写,见 skillCatalog.js / xappCatalog.js),而 PUT 对每个字段
   无条件覆盖,于是管理员改个标题就把技能/应用从用户目录里摘了。
   这条是线上正在发生的,比第一条更狠。

position_knowledge 同样:前端的必学/选学 el-switch 怎么拨都存成必学。

修法是拿掉那层「持久层替对象拿主意」:

- 模型去掉 `default:true`,对象说了算,仓库原样落库;
- 请求 DTO 改 *bool,把「没传」和「传 false」分开 —— 三态只存在于线上,
  `not null` 的列没有「未设置」态,所以不进模型;
- 默认值归接口契约,放 handler:新建时没传按 true(与种子数据、前端
  `exposed_to_user !== false` 口径一致),更新时没传保持原值
  (前端不发这个字段,不能因为一次无关编辑就改变可见性)。

没选的两个方案:给 Create 加 Select("*") 是把 GORM 的零值规则泄漏进 HTTP
适配层,只盖住症状还得每处创建路径都记得;模型改 *bool 则是给一个
不存在的领域状态造了个位置,还让 JSON 多出 null。

验证(tmp_vfy_fix,临时程序,验完已删):真实路由 + 真实 HTTP,跑在数据库
副本上,39 条断言全绿。同一份断言在修复前跑出 6 条红(S1/X1/P2:显式 false
存成 true;S9/X9:更新不带该字段把 true 静默改成 false),确认断言确实在测
这个修复而不是装饰。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
eaiadmin
2026-09-19 02:17:19 +08:00
co-authored by Claude Code
parent c5af5084b1
commit 9157df40f3
8 changed files with 121 additions and 58 deletions
@@ -5,16 +5,19 @@ import "time"
// PositionKnowledge 岗位知识要求(岗位 ↔ 知识域/课程/产品 映射)
// domain 必填;course_id / product_id 可选(三者共同圈定岗位应学范围)。
type PositionKnowledge struct {
ID uint `gorm:"primaryKey" json:"id"`
PositionID uint `gorm:"not null;index" json:"position_id"`
Domain string `gorm:"size:16;not null;index" json:"domain"` // company / product / sales
CourseID *uint `gorm:"index" json:"course_id"` // 绑定具体课程,可空
ProductID *uint `gorm:"index" json:"product_id"` // 绑定具体产品,可空
RequiredLevel string `gorm:"size:16;not null;default:L1" json:"required_level"` // L1/L2/L3/L4
Weight float64 `gorm:"not null;default:1" json:"weight"`
IsMandatory bool `gorm:"not null;default:true" json:"is_mandatory"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID uint `gorm:"primaryKey" json:"id"`
PositionID uint `gorm:"not null;index" json:"position_id"`
Domain string `gorm:"size:16;not null;index" json:"domain"` // company / product / sales
CourseID *uint `gorm:"index" json:"course_id"` // 绑定具体课程,可空
ProductID *uint `gorm:"index" json:"product_id"` // 绑定具体产品,可空
RequiredLevel string `gorm:"size:16;not null;default:L1" json:"required_level"` // L1/L2/L3/L4
Weight float64 `gorm:"not null;default:1" json:"weight"`
// 有意不写 `default:true`。带上它,GORM 在 Create 时会跳过布尔零值 false,
// 改由库默认值 true 生效 —— 显式传 false(选学)会被静默改写回 true。
// 「没传按必学」是接口契约,归 handler 兜(见 api/position.go 的 mandatoryOrTrue)。
IsMandatory bool `gorm:"not null" json:"is_mandatory"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (PositionKnowledge) TableName() string { return "position_knowledge" }