class_update.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package service_phone
  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 checkServicePhoneClassUpdateParam(req *pb_v1.ServicePhoneClassUpdateRequest) error {
  21. switch {
  22. case req.GardenId == 0:
  23. return status.Error(10003, "小区不能为空")
  24. case req.ClassName == "":
  25. return status.Error(10003, "名称不能为空")
  26. case req.Id == 0:
  27. return status.Error(10003, "id 不能为空")
  28. }
  29. return nil
  30. }
  31. func ServicePhoneClassUpdate(ctx context.Context, req *pb_v1.ServicePhoneClassUpdateRequest) (reply *pb_v1.ServicePhoneClassUpdateReply, err error) {
  32. reply = &pb_v1.ServicePhoneClassUpdateReply{}
  33. // 捕获各个task中的异常并返回给调用者
  34. defer func() {
  35. if r := recover(); r != nil {
  36. err = fmt.Errorf("%+v", r)
  37. e := &status.Status{}
  38. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  39. logger.Error("err",
  40. zap.String("system_err", err.Error()),
  41. zap.Stack("stacktrace"))
  42. }
  43. }
  44. }()
  45. // 参数检查
  46. err = checkServicePhoneClassUpdateParam(req)
  47. if err != nil {
  48. return nil, err
  49. }
  50. dbname := utils.GetGardenDbName(req.GardenId)
  51. // 获取旧数据
  52. old := dbmodel.NewServicePhoneClass(dbname)
  53. where := map[string]interface{}{
  54. "id":req.Id,
  55. }
  56. err = old.Find(database.DB(), where)
  57. if err != nil && err != gorm.ErrRecordNotFound {
  58. return nil, errors.DataBaseError
  59. }
  60. if old.ID == 0 {
  61. return nil, errors.ErrRecordNotFound
  62. }
  63. // 更新新数据
  64. now := time.Now()
  65. class := dbmodel.NewServicePhoneClass(dbname)
  66. enable := 1
  67. if !req.Enable {
  68. enable = 2
  69. }
  70. values := map[string]interface{}{
  71. "class_name":req.ClassName,
  72. "enable":enable,
  73. "updated_at":now,
  74. }
  75. where = map[string]interface{}{
  76. "id":req.Id,
  77. }
  78. err = class.Update(database.DB(), where, values)
  79. if err != nil {
  80. if strings.Contains(strings.ToLower(err.Error()), "duplicate") {
  81. return nil, status.Error(10003, "分类名已存在")
  82. }
  83. return nil, errors.DataBaseError
  84. }
  85. return reply, nil
  86. }