// 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" pb_v1 "property-company/pb/v1" "time" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" "google.golang.org/grpc/status" ) func checkCompanyDealStatisticSetParam(req *pb_v1.CompanyDealStatisticSetRequest) error { switch { case req.GardenId == 0: return status.Error(10003, "小区不能同时为空") case req.DateTimestamp == 0: return status.Error(10003, "时间不能为空") } return nil } func CompanyDealStatisticSetWithDb(req *pb_v1.CompanyDealStatisticSetRequest, db *gorm.DB) error { now := time.Now() cid, err := getCidByGarden(req.GardenId) if err != nil { return err } t := time.Unix(req.DateTimestamp, 0) t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) timestamp := t.Unix() where := map[string]interface{}{ "cid": cid, "date_timestamp": timestamp, } values := map[string]interface{}{} values["deal_amount"] = gorm.Expr("deal_amount + ?", req.Amount) values["deal_count"] = gorm.Expr("deal_count + ?", 1) if len(values) == 0 { return nil } p := dbmodel.TStatisticDeal{} affected, err := p.UpdateAffected(db, where, values) if err != nil { return errors.DataBaseError } if affected > 0 { return nil } p.DealAmount = req.Amount p.CreatedAt = now p.UpdatedAt = now p.Cid = cid p.DealCount = 1 p.DateTimestamp = timestamp err = p.Insert(db) if err != nil { return errors.DataBaseError } return nil } func CompanyDealStatisticSet(ctx context.Context, req *pb_v1.CompanyDealStatisticSetRequest) (reply *pb_v1.CompanyDealStatisticSetReply, err error) { reply = &pb_v1.CompanyDealStatisticSetReply{} // 捕获各个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 = checkCompanyDealStatisticSetParam(req) if err != nil { return nil, err } err = CompanyDealStatisticSetWithDb(req, database.DB()) return reply, err }