deal_statistic_set.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package statistic
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "git.getensh.com/common/gopkgs/database"
  9. "gorm.io/gorm"
  10. "property-company/errors"
  11. dbmodel "property-company/model"
  12. pb_v1 "property-company/pb/v1"
  13. "time"
  14. "git.getensh.com/common/gopkgs/logger"
  15. "go.uber.org/zap"
  16. "google.golang.org/grpc/status"
  17. )
  18. func checkCompanyDealStatisticSetParam(req *pb_v1.CompanyDealStatisticSetRequest) error {
  19. switch {
  20. case req.GardenId == 0:
  21. return status.Error(10003, "小区不能同时为空")
  22. case req.DateTimestamp == 0:
  23. return status.Error(10003, "时间不能为空")
  24. }
  25. return nil
  26. }
  27. func CompanyDealStatisticSetWithDb(req *pb_v1.CompanyDealStatisticSetRequest, db *gorm.DB) error {
  28. now := time.Now()
  29. cid, err := getCidByGarden(req.GardenId)
  30. if err != nil {
  31. return err
  32. }
  33. t := time.Unix(req.DateTimestamp, 0)
  34. t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
  35. timestamp := t.Unix()
  36. where := map[string]interface{}{
  37. "cid": cid,
  38. "date_timestamp": timestamp,
  39. }
  40. values := map[string]interface{}{}
  41. values["deal_amount"] = gorm.Expr("deal_amount + ?", req.Amount)
  42. values["deal_count"] = gorm.Expr("deal_count + ?", 1)
  43. if len(values) == 0 {
  44. return nil
  45. }
  46. p := dbmodel.TStatisticDeal{}
  47. affected, err := p.UpdateAffected(db, where, values)
  48. if err != nil {
  49. return errors.DataBaseError
  50. }
  51. if affected > 0 {
  52. return nil
  53. }
  54. p.DealAmount = req.Amount
  55. p.CreatedAt = now
  56. p.UpdatedAt = now
  57. p.Cid = cid
  58. p.DealCount = 1
  59. p.DateTimestamp = timestamp
  60. err = p.Insert(db)
  61. if err != nil {
  62. return errors.DataBaseError
  63. }
  64. return nil
  65. }
  66. func CompanyDealStatisticSet(ctx context.Context, req *pb_v1.CompanyDealStatisticSetRequest) (reply *pb_v1.CompanyDealStatisticSetReply, err error) {
  67. reply = &pb_v1.CompanyDealStatisticSetReply{}
  68. // 捕获各个task中的异常并返回给调用者
  69. defer func() {
  70. if r := recover(); r != nil {
  71. err = fmt.Errorf("%+v", r)
  72. e := &status.Status{}
  73. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  74. logger.Error("err",
  75. zap.String("system_err", err.Error()),
  76. zap.Stack("stacktrace"))
  77. }
  78. }
  79. }()
  80. // 参数检查
  81. err = checkCompanyDealStatisticSetParam(req)
  82. if err != nil {
  83. return nil, err
  84. }
  85. err = CompanyDealStatisticSetWithDb(req, database.DB())
  86. return reply, err
  87. }