Files
shangbangbang/internal/handlers/user_warehouse_handler.go
solosw 99b11b04e4 1.0
2026-01-05 14:11:34 +08:00

248 lines
7.0 KiB
Go

package handlers
import (
"awesomeProject/internal/common"
"awesomeProject/internal/models"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
// UserWarehouseHandler 用户仓库处理器
type UserWarehouseHandler struct{}
// GetWarehouseList 获取用户仓库商品列表
func (h *UserWarehouseHandler) GetWarehouseList(c *gin.Context) {
currentUser, _ := c.Get("current_user")
user := currentUser.(models.User)
// 分页参数
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 50 {
pageSize = 10
}
// 筛选参数
productType := c.Query("product_type")
status := c.Query("status")
productName := c.Query("product_name")
db := common.GetDB()
var warehouses []models.UserWarehouse
var total int64
// 构建查询条件
query := db.Model(&models.UserWarehouse{}).Where("user_id = ? and quantity>0", user.ID)
// 添加筛选条件
if productType != "" {
query = query.Where("product_type = ?", productType)
}
if status != "" {
query = query.Where("status = ?", status)
}
if productName != "" {
query = query.Where("product_name LIKE ?", "%"+productName+"%")
}
// 获取总数
query.Count(&total)
// 分页查询
offset := (page - 1) * pageSize
err := query.Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&warehouses).Error
if err != nil {
c.JSON(http.StatusOK, common.Error(500, "查询仓库商品列表失败"))
return
}
// 计算总价值
var totalValue float64
db.Model(&models.UserWarehouse{}).Where("user_id = ? AND status = 1", user.ID).
Select("COALESCE(SUM(warehouse_price * quantity), 0)").Scan(&totalValue)
// 构建返回数据
result := map[string]interface{}{
"list": warehouses,
"total": total,
"page": page,
"page_size": pageSize,
"total_value": totalValue,
}
c.JSON(http.StatusOK, common.Success(result))
}
// GetWarehouseItem 获取单个仓库商品详情
func (h *UserWarehouseHandler) GetWarehouseItem(c *gin.Context) {
currentUser, _ := c.Get("current_user")
user := currentUser.(models.User)
itemID, err := strconv.ParseUint(c.Param("id"), 10, 32)
if err != nil {
c.JSON(http.StatusOK, common.Error(400, "商品ID无效"))
return
}
var warehouse models.UserWarehouse
err = common.GetDB().Where("id = ? AND user_id = ?", itemID, user.ID).First(&warehouse).Error
if err != nil {
c.JSON(http.StatusOK, common.Error(404, "仓库商品不存在"))
return
}
c.JSON(http.StatusOK, common.Success(warehouse))
}
// SellWarehouseItem 出售仓库商品
func (h *UserWarehouseHandler) SellWarehouseItem(c *gin.Context) {
currentUser, _ := c.Get("current_user")
user := currentUser.(models.User)
itemID, err := strconv.ParseUint(c.Param("id"), 10, 32)
if err != nil {
c.JSON(http.StatusOK, common.Error(400, "商品ID无效"))
return
}
var req struct {
Quantity int `json:"quantity" binding:"required,min=1"`
Price float64 `json:"price" binding:"required,gt=0"`
Description string `json:"description" binding:"required"`
Condition string `json:"condition" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, common.Error(400, "请求参数错误"))
return
}
db := common.GetDB()
tx := db.Begin()
// 查询仓库商品
var warehouse models.UserWarehouse
if err := tx.Where("id = ? AND user_id = ? AND status = 1", itemID, user.ID).First(&warehouse).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusOK, common.Error(404, "仓库商品不存在或已出售"))
return
}
// 检查库存数量
if warehouse.Quantity < req.Quantity {
tx.Rollback()
c.JSON(http.StatusOK, common.Error(400, "库存数量不足"))
return
}
// 创建二级商品上架
secondaryProduct := models.SecondaryProduct{
SellerID: user.ID,
OriginalProductID: &warehouse.ProductID,
OriginalProductType: warehouse.ProductType,
ProductName: warehouse.ProductName,
ProductDescription: req.Description,
ProductImages: warehouse.ProductImages,
CostPrice: warehouse.PurchasePrice,
SellingPrice: req.Price,
Quantity: req.Quantity,
Status: 1, // 上架状态
ViewCount: 0,
CategoryID: 1, // 默认分类,可以后续优化
ProductCondition: req.Condition,
UserWarehouseID: uint(itemID),
}
if secondaryProduct.OriginalProductType == 1 {
var primaryProduct models.PrimaryProduct
err = tx.Where("id=?", secondaryProduct.OriginalProductID).First(&primaryProduct).Error
if err == nil {
secondaryProduct.CategoryID = primaryProduct.CategoryID
}
} else {
var sec models.SecondaryProduct
err = tx.Where("id=?", secondaryProduct.OriginalProductID).First(&sec).Error
if err == nil {
secondaryProduct.CategoryID = sec.CategoryID
}
}
if err := tx.Create(&secondaryProduct).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusOK, common.Error(500, "创建出售商品失败"))
return
}
// 更新仓库商品数量
if warehouse.Quantity == req.Quantity {
// 全部出售,更新状态为已出售
if err := tx.Model(&warehouse).Updates(map[string]interface{}{
"quantity": 0,
"status": 0, // 已出售
}).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusOK, common.Error(500, "更新仓库商品状态失败"))
return
}
} else {
// 部分出售,减少数量
if err := tx.Model(&warehouse).Update("quantity", warehouse.Quantity-req.Quantity).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusOK, common.Error(500, "更新仓库商品数量失败"))
return
}
}
tx.Commit()
result := map[string]interface{}{
"message": "商品挂售成功",
"secondary_product": secondaryProduct,
}
c.JSON(http.StatusOK, common.Success(result))
}
// GetWarehouseStats 获取仓库统计信息
func (h *UserWarehouseHandler) GetWarehouseStats(c *gin.Context) {
currentUser, _ := c.Get("current_user")
user := currentUser.(models.User)
db := common.GetDB()
stats := make(map[string]interface{})
// 库存中商品数量
var stockCount int64
db.Model(&models.UserWarehouse{}).Where("user_id = ? AND status = 1", user.ID).Count(&stockCount)
// 已出售商品数量
var soldCount int64
db.Model(&models.UserWarehouse{}).Where("user_id = ? AND status = 0", user.ID).Count(&soldCount)
// 库存总价值
var totalValue float64
db.Model(&models.UserWarehouse{}).Where("user_id = ? AND status = 1", user.ID).
Select("COALESCE(SUM(warehouse_price * quantity), 0)").Scan(&totalValue)
// 一级商品数量
var primaryCount int64
db.Model(&models.UserWarehouse{}).Where("user_id = ? AND product_type = 1 AND status = 1", user.ID).Count(&primaryCount)
// 二级商品数量
var secondaryCount int64
db.Model(&models.UserWarehouse{}).Where("user_id = ? AND product_type = 2 AND status = 1", user.ID).Count(&secondaryCount)
stats["stock_count"] = stockCount
stats["sold_count"] = soldCount
stats["total_value"] = totalValue
stats["primary_count"] = primaryCount
stats["secondary_count"] = secondaryCount
c.JSON(http.StatusOK, common.Success(stats))
}