100 lines
2.7 KiB
Go
100 lines
2.7 KiB
Go
package controllers
|
||
|
||
import (
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"strconv"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
|
||
"psi/constant"
|
||
"psi/service"
|
||
"psi/utils"
|
||
)
|
||
|
||
var goodsImportService = &service.GoodsImportService{}
|
||
|
||
// GoodsImportApi 商品导入API(独立模块)
|
||
type GoodsImportApi struct{}
|
||
|
||
// ImportFromExcel 从Excel文件导入商品
|
||
// POST /api/goods/import-from-excel
|
||
// multipart/form-data: file (Excel), user_id, warehouse_id
|
||
func (r *GoodsImportApi) ImportFromExcel(c *gin.Context) {
|
||
// 获取 user_id
|
||
userIDStr := c.PostForm("user_id")
|
||
if userIDStr == "" {
|
||
utils.FailWithRequestLog(constant.LoggerChannelRequest, "商品导入-缺少user_id", fmt.Errorf("user_id不能为空"), c, nil)
|
||
return
|
||
}
|
||
userID, err := strconv.ParseInt(userIDStr, 10, 64)
|
||
if err != nil || userID <= 0 {
|
||
utils.FailWithRequestLog(constant.LoggerChannelRequest, "商品导入-user_id格式错误", err, c, userIDStr)
|
||
return
|
||
}
|
||
|
||
// 获取 warehouse_id
|
||
warehouseIDStr := c.PostForm("warehouse_id")
|
||
if warehouseIDStr == "" {
|
||
utils.FailWithRequestLog(constant.LoggerChannelRequest, "商品导入-缺少warehouse_id", fmt.Errorf("warehouse_id不能为空"), c, nil)
|
||
return
|
||
}
|
||
warehouseID, err := strconv.ParseInt(warehouseIDStr, 10, 64)
|
||
if err != nil || warehouseID <= 0 {
|
||
utils.FailWithRequestLog(constant.LoggerChannelRequest, "商品导入-warehouse_id格式错误", err, c, warehouseIDStr)
|
||
return
|
||
}
|
||
|
||
// 获取上传的 Excel 文件
|
||
file, _, err := c.Request.FormFile("file")
|
||
if err != nil {
|
||
utils.FailWithRequestLog(constant.LoggerChannelRequest, "商品导入-未上传文件", fmt.Errorf("未上传Excel文件: %v", err), c, nil)
|
||
return
|
||
}
|
||
defer file.Close()
|
||
|
||
fileBytes, err := io.ReadAll(file)
|
||
if err != nil {
|
||
utils.FailWithRequestLog(constant.LoggerChannelRequest, "商品导入-读取文件失败", fmt.Errorf("读取文件内容失败: %v", err), c, nil)
|
||
return
|
||
}
|
||
|
||
// 解析Excel
|
||
rows, err := goodsImportService.ParseGoodsImportExcel(fileBytes)
|
||
if err != nil {
|
||
utils.FailWithRequestLog(constant.LoggerChannelWork, "商品导入-解析Excel失败", err, c, nil)
|
||
return
|
||
}
|
||
|
||
if len(rows) == 0 {
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 200,
|
||
"msg": "没有有效数据",
|
||
"data": gin.H{
|
||
"success_count": 0,
|
||
"fail_count": 0,
|
||
"message": "Excel中没有有效数据行",
|
||
},
|
||
})
|
||
return
|
||
}
|
||
|
||
// 导入商品
|
||
result, err := goodsImportService.ImportGoodsFromExcel(userID, warehouseID, rows)
|
||
if err != nil {
|
||
utils.FailWithRequestLog(constant.LoggerChannelWork, "商品导入-导入失败", err, c, nil)
|
||
return
|
||
}
|
||
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 200,
|
||
"msg": "导入完成",
|
||
"data": gin.H{
|
||
"success_count": result.SuccessCount,
|
||
"fail_count": result.FailCount,
|
||
"message": result.Message,
|
||
},
|
||
})
|
||
}
|