charge_time_set.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package charge
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "git.getensh.com/common/gopkgs/database"
  9. "git.getensh.com/common/gopkgs/logger"
  10. "go.uber.org/zap"
  11. "google.golang.org/grpc/status"
  12. "gorm.io/gorm"
  13. "property-garden/errors"
  14. "property-garden/impl/v1/charge_utils"
  15. dbmodel "property-garden/model"
  16. pb_v1 "property-garden/pb/v1"
  17. "property-garden/utils"
  18. )
  19. func checkChargeTimeSetParam(req *pb_v1.ChargeTimeSetRequest) error {
  20. switch {
  21. case req.GardenId == 0:
  22. return status.Error(10003, "小区不能为空")
  23. case req.Start == 0:
  24. return status.Error(10003, "开始时间不能为空")
  25. case req.BindId == 0:
  26. return status.Error(10003, "关系id不能为空")
  27. }
  28. return nil
  29. }
  30. func ChargeTimeSet(ctx context.Context, req *pb_v1.ChargeTimeSetRequest) (reply *pb_v1.ChargeTimeSetReply, err error) {
  31. reply = &pb_v1.ChargeTimeSetReply{}
  32. // 捕获各个task中的异常并返回给调用者
  33. defer func() {
  34. if r := recover(); r != nil {
  35. err = fmt.Errorf("%+v", r)
  36. e := &status.Status{}
  37. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  38. logger.Error("err",
  39. zap.String("system_err", err.Error()),
  40. zap.Stack("stacktrace"))
  41. }
  42. }
  43. }()
  44. // 参数检查
  45. err = checkChargeTimeSetParam(req)
  46. if err != nil {
  47. return nil, err
  48. }
  49. dbname := utils.GetGardenDbName(req.GardenId)
  50. bind := dbmodel.NewChargeBind(dbname)
  51. where := map[string]interface{}{
  52. "id":req.BindId,
  53. }
  54. err = bind.Find(database.DB(), where)
  55. if err != nil && err != gorm.ErrRecordNotFound{
  56. return nil, errors.DataBaseError
  57. }
  58. if bind.ID == 0 {
  59. return nil, errors.ErrRecordNotFound
  60. }
  61. if bind.Start > req.Start {
  62. return nil, status.Error(10003, "开始时间只能后延")
  63. }
  64. if bind.ChargeType == charge_utils.ChargeTypeVehicle && bind.End <= bind.Start {
  65. return nil, status.Error(10003, "结束时间不能大于开始时间")
  66. }
  67. if bind.ChargeType != charge_utils.ChargeTypeVehicle {
  68. req.End = 0
  69. }
  70. values := map[string]interface{}{
  71. "start":req.Start,
  72. "end":req.End,
  73. }
  74. err = bind.Update(database.DB(), where, values)
  75. if err != nil {
  76. return nil, errors.DataBaseError
  77. }
  78. return reply, nil
  79. }