house_count_change.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package garden
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "gorm.io/gorm"
  9. "property-system/errors"
  10. dbmodel "property-system/model"
  11. pb_v1 "property-system/pb/v1"
  12. "git.getensh.com/common/gopkgs/database"
  13. "git.getensh.com/common/gopkgs/logger"
  14. "go.uber.org/zap"
  15. "google.golang.org/grpc/status"
  16. )
  17. //
  18. func GardenHouseCountChange(ctx context.Context, req *pb_v1.GardenHouseCountChangeRequest) (reply *pb_v1.GardenHouseCountChangeReply, err error) {
  19. reply = &pb_v1.GardenHouseCountChangeReply{}
  20. // 捕获各个task中的异常并返回给调用者
  21. defer func() {
  22. if r := recover(); r != nil {
  23. err = fmt.Errorf("%+v", r)
  24. e := &status.Status{}
  25. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  26. logger.Error("err",
  27. zap.String("system_err", err.Error()),
  28. zap.Stack("stacktrace"))
  29. }
  30. }
  31. }()
  32. if req.GardenId == 0 || req.Count == 0 {
  33. return nil, errors.ParamsError
  34. }
  35. garden := &dbmodel.TGardenApproved{}
  36. where := map[string]interface{}{
  37. "in_use": true,
  38. "id": req.GardenId,
  39. }
  40. err = garden.Find(database.DB(), where)
  41. if err != nil && err != gorm.ErrRecordNotFound {
  42. return nil, errors.DataBaseError
  43. }
  44. if garden.ID == 0 {
  45. return nil, errors.ErrRecordNotFound
  46. }
  47. if garden.HouseCount+req.Count > garden.HouseCountLimit {
  48. return nil, status.Error(10003, "房屋数超过套餐限制")
  49. }
  50. values := map[string]interface{}{
  51. "house_count": gorm.Expr("house_count + ?", req.Count),
  52. }
  53. if req.Count < 0 {
  54. values["house_count"] = gorm.Expr("house_count - ?", -req.Count)
  55. }
  56. err = garden.Update(database.DB(), where, values)
  57. if err != nil {
  58. return nil, errors.DataBaseError
  59. }
  60. return reply, nil
  61. }