product.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "box-cost/log"
  6. "errors"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "go.mongodb.org/mongo-driver/bson"
  10. "go.mongodb.org/mongo-driver/bson/primitive"
  11. )
  12. func Product(r *GinRouter) {
  13. // 获取生产计划详情
  14. r.GETJWT("/product/detail/:id", ProductDetail)
  15. CreateCRUD(r, "/product", &CRUDOption{
  16. Collection: "product",
  17. NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  18. entity := &model.Product{}
  19. c.ShouldBindJSON(entity)
  20. entity.CreateTime = time.Now()
  21. entity.UpdateTime = time.Now()
  22. return entity, nil
  23. },
  24. EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
  25. return &model.Product{}
  26. },
  27. SearchFilter: func(c *gin.Context, apictx *ApiSession, query map[string]interface{}) map[string]interface{} {
  28. if _name, ok := query["name"]; ok {
  29. delete(query, "name")
  30. query["name"] = bson.M{"$regex": _name.(string)}
  31. }
  32. if _norm, ok := query["norm"]; ok {
  33. delete(query, "norm")
  34. query["norm"] = bson.M{"$regex": _norm.(string)}
  35. }
  36. return query
  37. },
  38. JWT: true,
  39. OnUpdate: func(c *gin.Context, apictx *ApiSession, entity interface{}) {
  40. product := entity.(*model.Product)
  41. product.UpdateTime = time.Now()
  42. },
  43. SearchProject: []string{"name", "unit", "norm", "price", "category", "remark"},
  44. })
  45. }
  46. func ProductDetail(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  47. productId := c.Param("id")
  48. id, err := primitive.ObjectIDFromHex(productId)
  49. if err != nil {
  50. return nil, errors.New("非法id")
  51. }
  52. var product model.Product
  53. option := &repo.DocSearchOptions{
  54. CollectName: repo.CollectionProduct,
  55. Query: repo.Map{"_id": id},
  56. }
  57. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &product)
  58. if !found || err != nil {
  59. log.Info(err)
  60. return nil, errors.New("数据未找到")
  61. }
  62. return product, nil
  63. }