// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package event import ( "context" "encoding/json" "fmt" "gorm.io/gorm" "property-garden/errors" dbmodel "property-garden/model" pb_v1 "property-garden/pb/v1" "property-garden/utils" "strings" "time" "git.getensh.com/common/gopkgs/database" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" "google.golang.org/grpc/status" ) func checkEventSignAddParam(req *pb_v1.EventSignAddRequest) error { switch { case req.GardenId < 1: return status.Error(10003, "小区不能为空") case req.Name == "": return status.Error(10003, "姓名不能为空") case req.Phone == "": return status.Error(10003, "电话不能为空") case req.Count < 1: return status.Error(10003, "报名人数不能为空") case req.HouseholdUid < 1: return status.Error(10003, "住户id不能为空") case req.EventId < 1: return status.Error(10003, "活动不能为空") } return nil } // func EventSignAdd(ctx context.Context, req *pb_v1.EventSignAddRequest) (reply *pb_v1.EventSignAddReply, err error) { reply = &pb_v1.EventSignAddReply{} // 捕获各个task中的异常并返回给调用者 defer func() { if r := recover(); r != nil { err = fmt.Errorf("%+v", r) e := &status.Status{} if er := json.Unmarshal([]byte(err.Error()), e); er != nil { logger.Error("err", zap.String("system_err", err.Error()), zap.Stack("stacktrace")) } } }() // 参数检查 err = checkEventSignAddParam(req) if err != nil { return nil, err } dbname := utils.GetGardenDbName(req.GardenId) now := time.Now() // 乐观锁方案,先直接更新和插入,最后查询是否超过人数限制 p := dbmodel.NewEvent(dbname) where := map[string]interface{}{ "id":req.EventId, } values := map[string]interface{}{ "people_count":gorm.Expr("people_count + ?", req.Count), } db := database.DB().Begin() defer func() { if err != nil { db.Rollback() } }() err = p.FindForUpdate(db, where) if err != nil { if err != gorm.ErrRecordNotFound { return nil, errors.DataBaseError } } if p.ID == 0 { return nil, errors.ErrRecordNotFound } if p.PeopleCount + req.Count > p.PeopleLimit { return nil, status.Error(10003, "人数已达上限") } // 更新活动报名总人数 err = p.Update(db, where, values) if err != nil { return nil, errors.DataBaseError } // 插入报名记录 sign := dbmodel.TEventSign{ EventId:req.EventId, HouseholdUid:req.HouseholdUid, SignCount:req.Count, Name:req.Name, Phone:req.Phone, Comment:req.Comment, CreatedAt:now, UpdatedAt:now, } sign.SetTable(dbname) err = sign.Insert(db) if err != nil { if strings.Contains(strings.ToLower(err.Error()), "duplicate") { return nil, status.Error(10003, "不能重复报名") } return nil, errors.DataBaseError } db.Commit() return reply, nil }