62 lines
1.6 KiB
Go
62 lines
1.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/wangjia/jiu/backend/internal/middleware"
|
|
"github.com/wangjia/jiu/backend/internal/model"
|
|
)
|
|
|
|
type WarehouseHandler struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewWarehouseHandler(db *gorm.DB) *WarehouseHandler {
|
|
return &WarehouseHandler{db: db}
|
|
}
|
|
|
|
func (h *WarehouseHandler) List(c *gin.Context) {
|
|
shopID := middleware.GetShopID(c)
|
|
warehouses := make([]model.Warehouse, 0)
|
|
h.db.Where("shop_id = ? AND deleted_at IS NULL", shopID).Find(&warehouses)
|
|
c.JSON(http.StatusOK, gin.H{"data": warehouses})
|
|
}
|
|
|
|
func (h *WarehouseHandler) Create(c *gin.Context) {
|
|
shopID := middleware.GetShopID(c)
|
|
var w model.Warehouse
|
|
if err := c.ShouldBindJSON(&w); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
w.ShopID = shopID
|
|
h.db.Create(&w)
|
|
c.JSON(http.StatusCreated, gin.H{"data": w})
|
|
}
|
|
|
|
func (h *WarehouseHandler) Update(c *gin.Context) {
|
|
shopID := middleware.GetShopID(c)
|
|
var w model.Warehouse
|
|
if err := h.db.Where("id = ? AND shop_id = ? AND deleted_at IS NULL", c.Param("id"), shopID).
|
|
First(&w).Error; err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
|
return
|
|
}
|
|
c.ShouldBindJSON(&w)
|
|
w.ShopID = shopID
|
|
h.db.Save(&w)
|
|
c.JSON(http.StatusOK, gin.H{"data": w})
|
|
}
|
|
|
|
func (h *WarehouseHandler) Delete(c *gin.Context) {
|
|
shopID := middleware.GetShopID(c)
|
|
now := timeNow()
|
|
h.db.Model(&model.Warehouse{}).
|
|
Where("id = ? AND shop_id = ? AND deleted_at IS NULL", c.Param("id"), shopID).
|
|
Update("deleted_at", now)
|
|
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
|
}
|