100 lines
2.8 KiB
Go
100 lines
2.8 KiB
Go
package controllers
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"psi/constant"
|
|
"psi/service"
|
|
"psi/utils"
|
|
)
|
|
|
|
var locationImportService = &service.LocationImportService{}
|
|
|
|
// LocationImportApi 库位导入API
|
|
type LocationImportApi struct{}
|
|
|
|
// ImportFromExcel 从Excel文件批量创建库位
|
|
// POST /api/location/import-from-excel (sign鉴权)
|
|
// multipart/form-data: file (Excel), user_id, warehouse_id
|
|
func (r *LocationImportApi) 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 := locationImportService.ParseLocationImportExcel(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 := locationImportService.ImportLocationsFromExcel(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,
|
|
},
|
|
})
|
|
}
|