check.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package visitor
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "git.getensh.com/common/gopkgs/database"
  7. "git.getensh.com/common/gopkgs/logger"
  8. "go.uber.org/zap"
  9. "google.golang.org/grpc/status"
  10. "gorm.io/gorm"
  11. "property-device/errors"
  12. dbmodel "property-device/model"
  13. pb_v1 "property-device/pb/v1"
  14. "time"
  15. )
  16. func checkGateVisitorCheckParam(req *pb_v1.GateVisitorCheckRequest) error {
  17. switch {
  18. case req.Id == 0:
  19. return status.Error(10003, "设备id不能为空")
  20. case req.DeviceId == 0:
  21. return status.Error(10003, "设备id不能为空")
  22. }
  23. if req.OpenTime == 0 {
  24. req.OpenTime = time.Now().Unix()
  25. }
  26. return nil
  27. }
  28. func GateVisitorCheck(ctx context.Context, req *pb_v1.GateVisitorCheckRequest) (reply *pb_v1.GateVisitorCheckReply, err error) {
  29. reply = &pb_v1.GateVisitorCheckReply{}
  30. // 捕获各个task中的异常并返回给调用者
  31. defer func() {
  32. if r := recover(); r != nil {
  33. err = fmt.Errorf("%+v", r)
  34. e := &status.Status{}
  35. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  36. logger.Error("err",
  37. zap.String("system_err", err.Error()),
  38. zap.Stack("stacktrace"))
  39. }
  40. }
  41. }()
  42. err = checkGateVisitorCheckParam(req)
  43. if err != nil {
  44. return nil, err
  45. }
  46. now := time.Now()
  47. g := dbmodel.TGateVisitor{}
  48. where := [][2]interface{}{}
  49. where = dbmodel.WhereAdd(where, "id", req.Id)
  50. where = dbmodel.WhereAdd(where, "device_id", req.DeviceId)
  51. err = g.Find(database.DB(), where)
  52. if err != nil && err != gorm.ErrRecordNotFound {
  53. return nil, errors.DataBaseError
  54. }
  55. if g.ID == 0 {
  56. return nil, errors.ErrRecordNotFound
  57. }
  58. if g.End < req.OpenTime {
  59. return nil, status.Error(10003, "已过期")
  60. }
  61. if g.OpenTime > 0 {
  62. if now.Unix()-g.OpenTime > 120 {
  63. return nil, status.Error(10003, "不能重复通行")
  64. } else {
  65. req.OpenTime = g.OpenTime
  66. }
  67. }
  68. values := map[string]interface{}{
  69. "updated_at": now,
  70. "open_time": req.OpenTime,
  71. }
  72. err = g.Update(database.DB(), where, values)
  73. if err != nil {
  74. return nil, errors.DataBaseError
  75. }
  76. return reply, nil
  77. }