material.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. // 材料管理
  13. // 不提供修改
  14. func Material(r *GinRouter) {
  15. // 新增材料
  16. r.POST("/material", CreateMaterial)
  17. // 获取材料信息
  18. r.GET("/material/:id", GetMaterial)
  19. // 获取材料列表
  20. r.GET("/materials", GetMaterials)
  21. r.POST("/material/delete/:id", DelMaterial)
  22. }
  23. func CreateMaterial(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  24. var material model.Material
  25. err := c.ShouldBindJSON(&material)
  26. if err != nil {
  27. return nil, errors.New("参数错误!")
  28. }
  29. ctx := apictx.CreateRepoCtx()
  30. if material.Name == "" {
  31. return nil, errors.New("材料名为空")
  32. }
  33. if material.Type == "" {
  34. return nil, errors.New("材料类型为空")
  35. }
  36. material.CreateTime = time.Now()
  37. material.UpdateTime = time.Now()
  38. result, err := repo.RepoAddDoc(ctx, repo.CollectionMaterial, &material)
  39. return result, err
  40. }
  41. // 获取材料信息
  42. func GetMaterial(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  43. materialId := c.Param("id")
  44. id, err := primitive.ObjectIDFromHex(materialId)
  45. if err != nil {
  46. return nil, errors.New("非法id")
  47. }
  48. var material model.Material
  49. option := &repo.DocSearchOptions{
  50. CollectName: repo.CollectionMaterial,
  51. Query: repo.Map{"_id": id},
  52. }
  53. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &material)
  54. if !found || err != nil {
  55. log.Info(err)
  56. return nil, errors.New("数据未找到")
  57. }
  58. return material, nil
  59. }
  60. // 获取材料列表
  61. func GetMaterials(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  62. page, size, query := UtilQueryPageSize(c)
  63. option := &repo.PageSearchOptions{
  64. CollectName: repo.CollectionMaterial,
  65. Query: query,
  66. Page: page,
  67. Size: size,
  68. Sort: bson.M{"createTime": -1},
  69. }
  70. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  71. }
  72. // 删除材料
  73. func DelMaterial(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  74. materialId := c.Param("id")
  75. if materialId == "" {
  76. return nil, errors.New("id为空")
  77. }
  78. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionMaterial, materialId)
  79. }