product_create.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package handler
  2. import (
  3. "youngee_b_api/consts"
  4. "youngee_b_api/middleware"
  5. "youngee_b_api/model/http_model"
  6. "youngee_b_api/service"
  7. "youngee_b_api/util"
  8. "github.com/gin-gonic/gin"
  9. "github.com/sirupsen/logrus"
  10. log "github.com/sirupsen/logrus"
  11. )
  12. func WrapCreateProductHandler(ctx *gin.Context) {
  13. handler := newCreateProductHandler(ctx)
  14. baseRun(handler)
  15. }
  16. func newCreateProductHandler(ctx *gin.Context) *CreateProductHandler {
  17. return &CreateProductHandler{
  18. req: http_model.NewCreateProductRequest(),
  19. resp: http_model.NewCreateProductResponse(),
  20. ctx: ctx,
  21. }
  22. }
  23. type CreateProductHandler struct {
  24. req *http_model.CreateProductRequest
  25. resp *http_model.CommonResponse
  26. ctx *gin.Context
  27. }
  28. func (h *CreateProductHandler) getRequest() interface{} {
  29. return h.req
  30. }
  31. func (h *CreateProductHandler) getContext() *gin.Context {
  32. return h.ctx
  33. }
  34. func (h *CreateProductHandler) getResponse() interface{} {
  35. return h.resp
  36. }
  37. func (h *CreateProductHandler) run() {
  38. data := http_model.CreateProductRequest{}
  39. data = *h.req
  40. auth := middleware.GetSessionAuth(h.ctx)
  41. enterpriseID := auth.EnterpriseID
  42. //根据品牌名和商品名查询商品是否存在,若存在则更新,否则新增
  43. productID, err := service.Product.FindByName(h.ctx, data.BrandName, data.ProductName)
  44. if err != nil {
  45. logrus.Errorf("[CreateProductHandler] call FindByName err:%+v\n", err)
  46. util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
  47. log.Info("CreateProduct fail,req:%+v", h.req)
  48. return
  49. } else {
  50. if productID != nil {
  51. // 该商品存在,更新
  52. data.ProductId = *productID
  53. res, err := service.Product.Update(h.ctx, data, enterpriseID)
  54. if err != nil {
  55. logrus.Errorf("[CreateProductHandler] call Update err:%+v\n", err)
  56. util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
  57. log.Info("CreateProduct fail,req:%+v", h.req)
  58. return
  59. }
  60. h.resp.Message = "成功更新商品信息"
  61. h.resp.Data = res
  62. } else {
  63. // 商品不存在,新增
  64. res, err := service.Product.Create(h.ctx, data, enterpriseID)
  65. if err != nil {
  66. logrus.Errorf("[CreateProductHandler] call Create err:%+v\n", err)
  67. util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
  68. log.Info("CreateProduct fail,req:%+v", h.req)
  69. return
  70. }
  71. h.resp.Message = "成功新增商品信息"
  72. h.resp.Data = res
  73. }
  74. }
  75. }
  76. func (h *CreateProductHandler) checkParam() error {
  77. return nil
  78. }