class_add.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "strings"
  9. "property-garden/errors"
  10. dbmodel "property-garden/model"
  11. pb_v1 "property-garden/pb/v1"
  12. "property-garden/utils"
  13. "time"
  14. "git.getensh.com/common/gopkgs/database"
  15. "git.getensh.com/common/gopkgs/logger"
  16. "go.uber.org/zap"
  17. "google.golang.org/grpc/status"
  18. )
  19. func checkServicePhoneClassAddParam(req *pb_v1.ServicePhoneClassAddRequest) error {
  20. switch {
  21. case req.GardenId == 0:
  22. return status.Error(10003, "小区不能为空")
  23. case req.ClassName == "":
  24. return status.Error(10003, "名称不能为空")
  25. }
  26. return nil
  27. }
  28. func ServicePhoneClassAdd(ctx context.Context, req *pb_v1.ServicePhoneClassAddRequest) (reply *pb_v1.ServicePhoneClassAddReply, err error) {
  29. reply = &pb_v1.ServicePhoneClassAddReply{}
  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. // 参数检查
  43. err = checkServicePhoneClassAddParam(req)
  44. if err != nil {
  45. return nil, err
  46. }
  47. now := time.Now()
  48. dbname := utils.GetGardenDbName(req.GardenId)
  49. enable := int32(1)
  50. if !req.Enable {
  51. enable = 2
  52. }
  53. p := dbmodel.TServicePhoneClass{
  54. ClassName:req.ClassName,
  55. Enable:enable,
  56. UpdatedAt:now,
  57. CreatedAt:now,
  58. }
  59. p.SetTable(dbname)
  60. err = p.Insert(database.DB())
  61. if err != nil {
  62. if strings.Contains(strings.ToLower(err.Error()), "duplicate") {
  63. return nil, status.Error(10003, "分类名已存在")
  64. }
  65. return nil, errors.DataBaseError
  66. }
  67. reply.Id = p.ID
  68. return reply, nil
  69. }