// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package statistic import ( "context" "encoding/json" "fmt" "git.getensh.com/common/gopkgs/database" "gorm.io/gorm" "property-garden/errors" dbmodel "property-garden/model" "property-garden/pb" pb_v1 "property-garden/pb/v1" "property-garden/utils" "time" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" "google.golang.org/grpc/status" ) const ( ObjTypeHouse = 1 ObjTypeSpace = 2 ObjTypeVehicle = 3 ObjTypeUser = 4 ) func checkObjStatisticSetParam(req *pb_v1.ObjStatisticSetRequest) error { switch { case req.GardenId == 0: return status.Error(10003, "小区不能为空") case req.ObjType == 0: return status.Error(10003, "类型不能为空") } return nil } func ObjStatisticSetWithDb(req *pb_v1.ObjStatisticSetRequest, db *gorm.DB) error { now := time.Now() dbname := utils.GetGardenDbName(req.GardenId) where := map[string]interface{}{ "obj_type": req.ObjType, } values := map[string]interface{}{} if req.TotalIncrease > 0 { values["total"] = gorm.Expr("total + ?", req.TotalIncrease) } else if req.TotalIncrease < 0 { values["total"] = gorm.Expr("total - ?", 0-req.TotalIncrease) } if len(values) == 0 { return nil } p := dbmodel.NewStatisticObj(dbname) affected, err := p.UpdateAffected(db, where, values) if err != nil { return errors.DataBaseError } if affected > 0 { if req.ObjType != ObjTypeVehicle { mreq := pb_v1.CompanyObjStatisticSetRequest{GardenId: req.GardenId, ObjType: req.ObjType, TotalIncrease: req.TotalIncrease} _, err := pb.Company.CompanyObjStatisticSet(context.Background(), &mreq) if err != nil { return err } } return nil } p.ObjType = req.ObjType p.CreatedAt = now p.UpdatedAt = now p.Total = req.TotalIncrease err = p.Insert(db) if err != nil { return errors.DataBaseError } if req.ObjType != ObjTypeVehicle { mreq := pb_v1.CompanyObjStatisticSetRequest{GardenId: req.GardenId, ObjType: req.ObjType, TotalIncrease: req.TotalIncrease} _, err := pb.Company.CompanyObjStatisticSet(context.Background(), &mreq) if err != nil { return err } } return nil } func ObjStatisticSet(ctx context.Context, req *pb_v1.ObjStatisticSetRequest) (reply *pb_v1.ObjStatisticSetReply, err error) { reply = &pb_v1.ObjStatisticSetReply{} // 捕获各个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 = checkObjStatisticSetParam(req) if err != nil { return nil, err } db := database.DB().Begin() err = ObjStatisticSetWithDb(req, db) if err != nil { db.Rollback() return nil, err } db.Commit() return reply, err }