// 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" 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 ( HandleTypeRepair = 1 HandleTypeSuggestion = 2 HandleTypeHousehold = 3 ) var StatisticDesc = map[int]string{ HandleTypeRepair:"报事报修", HandleTypeSuggestion:"投诉建议", HandleTypeHousehold:"住户审核", } func checkRepairStatisticSetParam(req *pb_v1.RepairStatisticSetRequest) error { switch { case req.GardenId == 0: return status.Error(10003, "小区不能为空") case req.HandleType == 0: return status.Error(10003, "类型不能为空") } return nil } func RepairStatisticSetWithDb(req *pb_v1.RepairStatisticSetRequest, db *gorm.DB) error { now := time.Now() dbname := utils.GetGardenDbName(req.GardenId) where := map[string]interface{}{ "handle_type":req.HandleType, } 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 req.FinishIncrease > 0 { values["finish"]= gorm.Expr("finish + ?", req.FinishIncrease) } else if req.FinishIncrease < 0{ values["finish"] = gorm.Expr("finish - ?", 0-req.FinishIncrease) } if len(values) == 0 { return nil } p := dbmodel.NewStatisticRepair(dbname) affected, err := p.UpdateAffected(db, where, values) if err != nil { return errors.DataBaseError } if affected > 0 { return nil } p.HandleType = req.HandleType p.CreatedAt = now p.UpdatedAt = now p.Total = req.TotalIncrease p.Finish = req.FinishIncrease err = p.Insert(db) if err != nil { return errors.DataBaseError } return nil } func RepairStatisticSet(ctx context.Context, req *pb_v1.RepairStatisticSetRequest) (reply *pb_v1.RepairStatisticSetReply, err error) { reply = &pb_v1.RepairStatisticSetReply{} // 捕获各个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 = checkRepairStatisticSetParam(req) if err != nil { return nil, err } err = RepairStatisticSetWithDb(req, database.DB()) return reply, err }