add.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package department
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "property-system/errors"
  9. dbmodel "property-system/model"
  10. pb_v1 "property-system/pb/v1"
  11. "strings"
  12. "time"
  13. "git.getensh.com/common/gopkgs/database"
  14. "git.getensh.com/common/gopkgs/logger"
  15. "go.uber.org/zap"
  16. "google.golang.org/grpc/status"
  17. )
  18. func checkDepartmentAddParam(req *pb_v1.DepartmentAddRequest) error {
  19. switch {
  20. case req.DepartmentName == "":
  21. return status.Error(10003, "部门名不能为空")
  22. case req.GardenId < 1:
  23. return status.Error(10003, "小区不能为空")
  24. case req.Cid < 1:
  25. return status.Error(10003, "物业公司不能为空")
  26. }
  27. return nil
  28. }
  29. //
  30. func DepartmentAdd(ctx context.Context, req *pb_v1.DepartmentAddRequest) (reply *pb_v1.DepartmentAddReply, err error) {
  31. reply = &pb_v1.DepartmentAddReply{}
  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. err = checkDepartmentAddParam(req)
  45. if err != nil {
  46. return nil, err
  47. }
  48. now := time.Now()
  49. p := dbmodel.TDepartment{
  50. GardenId:req.GardenId,
  51. Cid: req.Cid,
  52. DepartmentName:req.DepartmentName,
  53. Desc:req.Desc,
  54. UpdatedAt: now,
  55. CreatedAt: now,
  56. }
  57. err = p.Insert(database.DB())
  58. if err != nil {
  59. if strings.Contains(strings.ToLower(err.Error()), "duplicate") {
  60. return nil, status.Error(10003, "该部门已存在")
  61. }
  62. return nil, errors.DataBaseError
  63. }
  64. reply.Id = p.ID
  65. return reply, nil
  66. }