// 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-company/errors" dbmodel "property-company/model" "property-company/pb" pb_v1 "property-company/pb/v1" "time" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" "google.golang.org/grpc/status" ) const ( ObjTypeHouse = 1 ObjTypeSpace = 2 ObjTypeGarden = 3 ObjTypeUser = 4 ) func checkCompanyObjStatisticSetParam(req *pb_v1.CompanyObjStatisticSetRequest) error { switch { case req.GardenId == 0 && req.Cid == 0: return status.Error(10003, "小区和公司不能同时为空") case req.ObjType == 0: return status.Error(10003, "类型不能为空") } return nil } func getCidByGarden(gardenId int64) (int64, error) { mreq := pb_v1.GardenInfosRequest{Ids: []int64{gardenId}} mreply, err := pb.System.GardenInfos(context.Background(), &mreq) if err != nil { return 0, err } if len(mreply.List) == 0 { return 0, errors.ErrRecordNotFound } return mreply.List[0].Cid, nil } func CompanyObjStatisticSetWithDb(req *pb_v1.CompanyObjStatisticSetRequest, db *gorm.DB) error { now := time.Now() if req.Cid == 0 { cid, err := getCidByGarden(req.GardenId) if err != nil { return err } req.Cid = cid } where := map[string]interface{}{ "cid": req.Cid, "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.TStatisticObj{} affected, err := p.UpdateAffected(db, where, values) if err != nil { return errors.DataBaseError } if affected > 0 { return nil } p.ObjType = req.ObjType p.CreatedAt = now p.UpdatedAt = now p.Cid = req.Cid p.Total = req.TotalIncrease err = p.Insert(db) if err != nil { return errors.DataBaseError } return nil } func CompanyObjStatisticSet(ctx context.Context, req *pb_v1.CompanyObjStatisticSetRequest) (reply *pb_v1.CompanyObjStatisticSetReply, err error) { reply = &pb_v1.CompanyObjStatisticSetReply{} // 捕获各个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 = checkCompanyObjStatisticSetParam(req) if err != nil { return nil, err } err = CompanyObjStatisticSetWithDb(req, database.DB()) return reply, err }