feat: 快捷养护接口

This commit is contained in:
Blizzard
2026-04-27 10:43:42 +08:00
parent 3aae619af5
commit c5aa1c6f2c
4 changed files with 101 additions and 0 deletions
+65
View File
@@ -552,6 +552,71 @@ func (s *MyPlantService) AddGrowthRecord(req plantReq.CreateGrowthRecord, userId
})
}
// QuickCare 快捷养护记录(无需预设任务,直接创建养护记录)
func (s *MyPlantService) QuickCare(req plantReq.QuickCare, userId string) error {
return global.DB.Transaction(func(tx *gorm.DB) error {
// 1.验证植物存在且属于该用户
var myPlant plant.MyPlant
if err := tx.Where("id = ? AND user_id = ?", req.PlantId, userId).First(&myPlant).Error; err != nil {
return errors.New("植物不存在")
}
// 2.直接创建养护记录
record := plant.CareRecord{
UserId: userId,
PlantId: req.PlantId,
Name: req.Name,
Icon: req.Icon,
Remark: req.Remark,
}
if err := tx.Create(&record).Error; err != nil {
return err
}
// 3.更新用户 profile 对应计数(尝试从 icon JSON 解析 targetAction
column := "care_count"
if req.Icon != "" {
// 解析 icon JSON 中的 id 字段来判断动作类型
actionMap := map[string]string{
"water": "water_count", "fertilize": "fertilize_count",
"prune": "prune_count", "repot": "repot_count",
}
// 简单提取: 不引入 encoding/json 解析,用名称匹配
nameMap := map[string]string{
"浇水": "water_count", "施肥": "fertilize_count",
"修剪": "prune_count", "换盆": "repot_count",
}
if col, ok := nameMap[req.Name]; ok {
column = col
} else {
// 尝试从 actionMap (icon.id) 匹配
for key, col := range actionMap {
if len(req.Icon) > 0 && contains(req.Icon, key) {
column = col
break
}
}
}
}
if err := tx.Model(&plant.UserProfile{}).Where("user_id = ?", userId).
Update(column, gorm.Expr(column+" + 1")).Error; err != nil {
return err
}
return nil
})
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsStr(s, substr))
}
func containsStr(s, sub string) bool {
for i := 0; i <= len(s)-len(sub); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}
// 完成任务后异步执行 更新用户等级 sunlight
func (s *MyPlantService) handleCompleteTaskThenUpdateProfile(ctx context.Context, userId string) {
//5.更新用户profile