unit_add.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package house
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "gorm.io/gorm"
  9. "property-garden/errors"
  10. dbmodel "property-garden/model"
  11. pb_v1 "property-garden/pb/v1"
  12. "property-garden/utils"
  13. "strings"
  14. "time"
  15. "git.getensh.com/common/gopkgs/database"
  16. "git.getensh.com/common/gopkgs/logger"
  17. "go.uber.org/zap"
  18. "google.golang.org/grpc/status"
  19. )
  20. func checkUnitAddParam(req *pb_v1.UnitAddRequest) error {
  21. switch {
  22. case req.UnitNumber < 0:
  23. return status.Error(10003, "单元编号不能为空")
  24. case req.UnitName == "":
  25. return status.Error(10003, "单元名称名称不能为空")
  26. case req.UnitLayers < 1:
  27. return status.Error(10003, "层数不能为空")
  28. case req.GardenId < 1:
  29. return status.Error(10003, "小区不能为空")
  30. case req.BuildingId < 1:
  31. return status.Error(10003, "楼栋id不能为空")
  32. }
  33. return nil
  34. }
  35. //
  36. func UnitAdd(ctx context.Context, req *pb_v1.UnitAddRequest) (reply *pb_v1.UnitAddReply, err error) {
  37. reply = &pb_v1.UnitAddReply{}
  38. // 捕获各个task中的异常并返回给调用者
  39. defer func() {
  40. if r := recover(); r != nil {
  41. err = fmt.Errorf("%+v", r)
  42. e := &status.Status{}
  43. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  44. logger.Error("err",
  45. zap.String("system_err", err.Error()),
  46. zap.Stack("stacktrace"))
  47. }
  48. }
  49. }()
  50. err = checkUnitAddParam(req)
  51. if err != nil {
  52. return nil, err
  53. }
  54. dbname := utils.GetGardenDbName(req.GardenId)
  55. building := dbmodel.NewBuilding(dbname)
  56. where := map[string]interface{}{
  57. "id":req.BuildingId,
  58. }
  59. err = building.Find(database.DB(), where)
  60. if err != nil && err != gorm.ErrRecordNotFound {
  61. return nil, errors.DataBaseError
  62. }
  63. if building.ID == 0 {
  64. return nil, errors.ErrRecordNotFound
  65. }
  66. now := time.Now()
  67. hasLift := int64(2)
  68. if req.HasLift {
  69. hasLift = 1
  70. }
  71. unit := &dbmodel.TUnit{
  72. //GardenId:req.GardenId,
  73. UnitName:req.UnitName,
  74. UnitNumber:req.UnitNumber,
  75. UnitLayers:req.UnitLayers,
  76. BuildingId:req.BuildingId,
  77. HasLift:hasLift,
  78. UpdatedAt: now,
  79. CreatedAt: now,
  80. }
  81. db := database.DB()
  82. unit.SetTable(dbname)
  83. err = unit.Insert(db)
  84. if err != nil {
  85. if strings.Contains(strings.ToLower(err.Error()), "duplicate") {
  86. return nil, errors.ErrRecordExist
  87. }
  88. return nil, errors.DataBaseError
  89. }
  90. reply.Id = unit.ID
  91. return reply, nil
  92. }