77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
package myPlant
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"sundynix-micro-go/app/plant/api/internal/svc"
|
|
"sundynix-micro-go/app/plant/api/internal/types"
|
|
plantModel "sundynix-micro-go/app/plant/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type QuickCareLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewQuickCareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuickCareLogic {
|
|
return &QuickCareLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
|
|
}
|
|
|
|
func (l *QuickCareLogic) QuickCare(req *types.QuickCareReq) error {
|
|
userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
|
|
|
|
return l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
|
// 1. Validate plant exists and belongs to user
|
|
var myPlant plantModel.MyPlant
|
|
if err := tx.Where("id = ? AND user_id = ?", req.PlantId, userId).First(&myPlant).Error; err != nil {
|
|
return errors.New("植物不存在")
|
|
}
|
|
|
|
// 2. Create care record
|
|
record := plantModel.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. Update user profile counter
|
|
column := "care_count"
|
|
if req.Icon != "" || req.Name != "" {
|
|
nameMap := map[string]string{
|
|
"浇水": "water_count",
|
|
"施肥": "fertilize_count",
|
|
"修剪": "prune_count",
|
|
"换盆": "repot_count",
|
|
}
|
|
if col, ok := nameMap[req.Name]; ok {
|
|
column = col
|
|
} else if req.Icon != "" {
|
|
actionMap := map[string]string{
|
|
"water": "water_count", "fertilize": "fertilize_count",
|
|
"prune": "prune_count", "repot": "repot_count",
|
|
}
|
|
for key, col := range actionMap {
|
|
if strings.Contains(req.Icon, key) {
|
|
column = col
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return tx.Model(&plantModel.UserProfile{}).Where("user_id = ?", userId).
|
|
Update(column, gorm.Expr(column+" + 1")).Error
|
|
})
|
|
}
|