feat: 商品详情页、XLS导入修复、分页选择器、导出功能
后端: - 新增 product_images 表,支持每商品最多5张图(服务端压缩至1200px/JPEG85%) - products 表新增 public_id(UUID)、description 字段 - 新增商品详情接口、二维码接口、公开商品接口(无鉴权) - 修复 XLS 导入:OLE2 magic bytes 检测 + 临时文件解析,兼容 extrame/xls - 修复商品/名称/系列/规格三张表导入数据为0(LastCol()=0 bug) - 所有导入接口返回 total/imported/skipped 统计 - config 新增 StorageConfig,支持 STORAGE_* 环境变量覆盖 - 种子数据修复:products 补 public_id、新增 product_images TRUNCATE、schema.sql 表名修正 前端: - 商品详情页:图片上传/删除、描述内联编辑、二维码弹窗、公开链接复制 - 公开商品页:无鉴权路由 /product/:public_id,Flutter Web SPA - 商品详情列表(批次追踪)商品名超链接跳转详情页 - 导航「商品管理」改名「商品详情」 - 所有列表表格新增每页条数选择(10/20/50/100) - 表格列头内嵌筛选(FilterableColumnHeader) - 导出 Excel 功能(入库/出库/库存/财务/批次/往来单位) - 网络恢复自动刷新 + 离线缓存展示 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,15 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/extrame/xls"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/xuri/excelize/v2"
|
||||
"gorm.io/gorm"
|
||||
@@ -92,60 +98,513 @@ func (h *ImportHandler) ImportProducts(c *gin.Context) {
|
||||
}
|
||||
|
||||
// ImportPartners POST /api/v1/import/partners
|
||||
// 列顺序:名称,类型(supplier/customer),联系人,电话,地址,备注
|
||||
// 列顺序(来往单位.xls):编号,类型,状态,名称,电话,卡号,初始金额,单位,地址,...,备注
|
||||
func (h *ImportHandler) ImportPartners(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
|
||||
file, err := c.FormFile("file")
|
||||
rows, err := parseUploadedExcel(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "file required"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
f, err := file.Open()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
xl, err := excelize.OpenReader(f)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid excel file"})
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := xl.GetRows(xl.GetSheetName(0))
|
||||
if err != nil || len(rows) < 2 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "empty sheet"})
|
||||
return
|
||||
}
|
||||
|
||||
var partners []model.Partner
|
||||
total, imported, skipped := 0, 0, 0
|
||||
for _, row := range rows[1:] {
|
||||
if len(row) < 1 || strings.TrimSpace(row[0]) == "" {
|
||||
name := cell(row, 3)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
t := cell(row, 1)
|
||||
if t == "" {
|
||||
t = "supplier"
|
||||
total++
|
||||
var existing model.Partner
|
||||
if h.db.Where("shop_id = ? AND name = ? AND deleted_at IS NULL", shopID, name).First(&existing).Error == nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
partners = append(partners, model.Partner{
|
||||
balance, _ := strconv.ParseFloat(cell(row, 6), 64)
|
||||
status := "enabled"
|
||||
if cell(row, 2) == "禁用" {
|
||||
status = "disabled"
|
||||
}
|
||||
p := model.Partner{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Code: cell(row, 0),
|
||||
Type: parsePartnerType(cell(row, 1)),
|
||||
Status: status,
|
||||
Name: name,
|
||||
Phone: cell(row, 4),
|
||||
BankAccount: cell(row, 5),
|
||||
Balance: balance,
|
||||
Address: cell(row, 8),
|
||||
Remark: cell(row, 11),
|
||||
}
|
||||
if h.db.Create(&p).Error == nil {
|
||||
imported++
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"total": total, "imported": imported, "skipped": skipped})
|
||||
}
|
||||
|
||||
// ImportProductNames POST /api/v1/import/product-names
|
||||
// 列顺序(商品名称.xls):选项编号,选项名称,备注
|
||||
func (h *ImportHandler) ImportProductNames(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
rows, err := parseUploadedExcel(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
total, imported, skipped := 0, 0, 0
|
||||
for _, row := range rows[1:] {
|
||||
name := cell(row, 1)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
total++
|
||||
var existing model.ProductNameOption
|
||||
if h.db.Where("shop_id = ? AND name = ? AND deleted_at IS NULL", shopID, name).First(&existing).Error == nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
opt := model.ProductNameOption{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Name: cell(row, 0),
|
||||
Type: t,
|
||||
Contact: cell(row, 2),
|
||||
Phone: cell(row, 3),
|
||||
Address: cell(row, 4),
|
||||
Remark: cell(row, 5),
|
||||
Code: cell(row, 0),
|
||||
Name: name,
|
||||
Remark: cell(row, 2),
|
||||
}
|
||||
if h.db.Create(&opt).Error == nil {
|
||||
imported++
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"total": total, "imported": imported, "skipped": skipped})
|
||||
}
|
||||
|
||||
// ImportProductSeries POST /api/v1/import/product-series
|
||||
// 列顺序(商品系列.xls):选项编号,选项名称,备注
|
||||
func (h *ImportHandler) ImportProductSeries(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
rows, err := parseUploadedExcel(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
total, imported, skipped := 0, 0, 0
|
||||
for _, row := range rows[1:] {
|
||||
name := cell(row, 1)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
total++
|
||||
var existing model.ProductSeriesOption
|
||||
if h.db.Where("shop_id = ? AND name = ? AND deleted_at IS NULL", shopID, name).First(&existing).Error == nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
opt := model.ProductSeriesOption{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Code: cell(row, 0),
|
||||
Name: name,
|
||||
Remark: cell(row, 2),
|
||||
}
|
||||
if h.db.Create(&opt).Error == nil {
|
||||
imported++
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"total": total, "imported": imported, "skipped": skipped})
|
||||
}
|
||||
|
||||
// ImportProductSpecs POST /api/v1/import/product-specs
|
||||
// 列顺序(商品规格.xls):选项编号,选项名称,单品数量,备注
|
||||
func (h *ImportHandler) ImportProductSpecs(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
rows, err := parseUploadedExcel(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
total, imported, skipped := 0, 0, 0
|
||||
for _, row := range rows[1:] {
|
||||
name := cell(row, 1)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
total++
|
||||
var existing model.ProductSpecOption
|
||||
if h.db.Where("shop_id = ? AND name = ? AND deleted_at IS NULL", shopID, name).First(&existing).Error == nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
qty, _ := strconv.Atoi(strings.TrimSuffix(cell(row, 2), ".0")) // "12" 或 "12.0"
|
||||
if qty == 0 {
|
||||
qtyF, _ := strconv.ParseFloat(cell(row, 2), 64)
|
||||
qty = int(qtyF)
|
||||
}
|
||||
opt := model.ProductSpecOption{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Code: cell(row, 0),
|
||||
Name: name,
|
||||
Quantity: qty,
|
||||
Remark: cell(row, 3),
|
||||
}
|
||||
if h.db.Create(&opt).Error == nil {
|
||||
imported++
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"total": total, "imported": imported, "skipped": skipped})
|
||||
}
|
||||
|
||||
// ImportStockIn POST /api/v1/import/stock-in
|
||||
// 支持老系统打印格式(每文件一张入库单)
|
||||
func (h *ImportHandler) ImportStockIn(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
userID := middleware.GetUserID(c)
|
||||
rows, err := parseUploadedExcel(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if len(rows) < 7 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "文件行数不足,请检查格式"})
|
||||
return
|
||||
}
|
||||
|
||||
// 解析单据头
|
||||
partnerName := strings.TrimPrefix(cell(rows[3], 0), "来往单位名称:")
|
||||
dateStr := strings.TrimPrefix(cell(rows[3], 7), "单据日期:")
|
||||
orderNo := strings.TrimPrefix(cell(rows[3], 18), "NO.")
|
||||
|
||||
if orderNo == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "未找到单据号,请检查文件格式"})
|
||||
return
|
||||
}
|
||||
|
||||
// 检查重复
|
||||
var existing model.StockInOrder
|
||||
if h.db.Where("shop_id = ? AND order_no = ?", shopID, orderNo).First(&existing).Error == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"order_no": orderNo, "skipped": true, "message": "单据已存在,已跳过"})
|
||||
return
|
||||
}
|
||||
|
||||
// 解析日期
|
||||
orderDate := parseDate(dateStr)
|
||||
|
||||
// 往来单位
|
||||
partnerID := findOrCreatePartner(h.db, shopID, partnerName, "supplier")
|
||||
|
||||
// 默认仓库
|
||||
var wh model.Warehouse
|
||||
if h.db.Where("shop_id = ? AND is_default = 1", shopID).First(&wh).Error != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请先在系统设置中设置默认仓库"})
|
||||
return
|
||||
}
|
||||
|
||||
// 解析明细
|
||||
var items []model.StockInItem
|
||||
var totalAmount float64
|
||||
for _, row := range rows[6:] {
|
||||
if cell(row, 0) == "" || strings.HasPrefix(cell(row, 0), "单据总计") {
|
||||
break
|
||||
}
|
||||
productName := cell(row, 1)
|
||||
if productName == "" {
|
||||
continue
|
||||
}
|
||||
series := cell(row, 5)
|
||||
spec := cell(row, 6)
|
||||
qty, _ := strconv.ParseFloat(cell(row, 9), 64)
|
||||
price, _ := strconv.ParseFloat(cell(row, 11), 64)
|
||||
batchNo := cell(row, 16)
|
||||
|
||||
prod, err := findOrCreateProductFn(h.db, shopID, productName, series, spec)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
total := qty * price
|
||||
totalAmount += total
|
||||
items = append(items, model.StockInItem{
|
||||
ShopID: shopID,
|
||||
ProductID: prod.ID,
|
||||
Quantity: qty,
|
||||
UnitPrice: price,
|
||||
TotalPrice: total,
|
||||
BatchNo: batchNo,
|
||||
})
|
||||
}
|
||||
|
||||
if err := h.db.CreateInBatches(&partners, 100).Error; err != nil {
|
||||
if len(items) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "未解析到有效明细行"})
|
||||
return
|
||||
}
|
||||
|
||||
order := model.StockInOrder{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
OrderNo: orderNo,
|
||||
Type: "purchase",
|
||||
WarehouseID: wh.ID,
|
||||
PartnerID: partnerID,
|
||||
OperatorID: userID,
|
||||
Status: "draft",
|
||||
OrderDate: orderDate,
|
||||
TotalAmount: totalAmount,
|
||||
}
|
||||
|
||||
if err := h.db.Create(&order).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"imported": len(partners)})
|
||||
for i := range items {
|
||||
items[i].OrderID = order.ID
|
||||
}
|
||||
if err := h.db.CreateInBatches(&items, 50).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"order_no": orderNo, "items": len(items)})
|
||||
}
|
||||
|
||||
// ImportStockOut POST /api/v1/import/stock-out
|
||||
// 支持老系统打印格式(每文件一张出库单)
|
||||
func (h *ImportHandler) ImportStockOut(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
userID := middleware.GetUserID(c)
|
||||
rows, err := parseUploadedExcel(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if len(rows) < 7 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "文件行数不足,请检查格式"})
|
||||
return
|
||||
}
|
||||
|
||||
// 出库单日期在 col8(比入库单多一个空列)
|
||||
partnerName := strings.TrimPrefix(cell(rows[3], 0), "来往单位名称:")
|
||||
dateStr := strings.TrimPrefix(cell(rows[3], 8), "单据日期:")
|
||||
orderNo := strings.TrimPrefix(cell(rows[3], 18), "NO.")
|
||||
|
||||
if orderNo == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "未找到单据号,请检查文件格式"})
|
||||
return
|
||||
}
|
||||
|
||||
var existing model.StockOutOrder
|
||||
if h.db.Where("shop_id = ? AND order_no = ?", shopID, orderNo).First(&existing).Error == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"order_no": orderNo, "skipped": true, "message": "单据已存在,已跳过"})
|
||||
return
|
||||
}
|
||||
|
||||
orderDate := parseDate(dateStr)
|
||||
partnerID := findOrCreatePartner(h.db, shopID, partnerName, "customer")
|
||||
|
||||
var wh model.Warehouse
|
||||
if h.db.Where("shop_id = ? AND is_default = 1", shopID).First(&wh).Error != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请先在系统设置中设置默认仓库"})
|
||||
return
|
||||
}
|
||||
|
||||
var items []model.StockOutItem
|
||||
var totalAmount float64
|
||||
for _, row := range rows[6:] {
|
||||
if cell(row, 0) == "" || strings.HasPrefix(cell(row, 0), "单据总计") {
|
||||
break
|
||||
}
|
||||
productName := cell(row, 1)
|
||||
if productName == "" {
|
||||
continue
|
||||
}
|
||||
series := cell(row, 5)
|
||||
spec := cell(row, 6)
|
||||
qty, _ := strconv.ParseFloat(cell(row, 9), 64)
|
||||
price, _ := strconv.ParseFloat(cell(row, 11), 64)
|
||||
|
||||
prod, err := findOrCreateProductFn(h.db, shopID, productName, series, spec)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
total := qty * price
|
||||
totalAmount += total
|
||||
items = append(items, model.StockOutItem{
|
||||
ShopID: shopID,
|
||||
ProductID: prod.ID,
|
||||
Quantity: qty,
|
||||
UnitPrice: price,
|
||||
TotalPrice: total,
|
||||
})
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "未解析到有效明细行"})
|
||||
return
|
||||
}
|
||||
|
||||
order := model.StockOutOrder{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
OrderNo: orderNo,
|
||||
Type: "sale",
|
||||
WarehouseID: wh.ID,
|
||||
PartnerID: partnerID,
|
||||
OperatorID: userID,
|
||||
Status: "draft",
|
||||
OrderDate: orderDate,
|
||||
TotalAmount: totalAmount,
|
||||
}
|
||||
|
||||
if err := h.db.Create(&order).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
for i := range items {
|
||||
items[i].OrderID = order.ID
|
||||
}
|
||||
if err := h.db.CreateInBatches(&items, 50).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"order_no": orderNo, "items": len(items)})
|
||||
}
|
||||
|
||||
// ── 内部辅助函数 ─────────────────────────────────────────────
|
||||
|
||||
func parseUploadedExcel(c *gin.Context) ([][]string, error) {
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("file required")
|
||||
}
|
||||
f, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// 读取前 4 字节检测 OLE2 格式(D0 CF 11 E0 = 老式 .xls BIFF)
|
||||
var magic [4]byte
|
||||
f.Read(magic[:])
|
||||
f.Seek(0, 0)
|
||||
isOLE := magic[0] == 0xD0 && magic[1] == 0xCF && magic[2] == 0x11 && magic[3] == 0xE0
|
||||
|
||||
var rows [][]string
|
||||
|
||||
if isOLE {
|
||||
// 老格式 BIFF — extrame/xls 需要文件路径,写入临时文件
|
||||
tmp, tmpErr := os.CreateTemp("", "import_*.xls")
|
||||
if tmpErr != nil {
|
||||
return nil, fmt.Errorf("cannot create temp file: %s", tmpErr.Error())
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, cpErr := io.Copy(tmp, f); cpErr != nil {
|
||||
tmp.Close()
|
||||
return nil, fmt.Errorf("cannot write temp file: %s", cpErr.Error())
|
||||
}
|
||||
tmp.Close()
|
||||
|
||||
wb, xlErr := xls.Open(tmp.Name(), "utf-8")
|
||||
if xlErr != nil {
|
||||
return nil, fmt.Errorf("invalid xls file: %s", xlErr.Error())
|
||||
}
|
||||
sheet := wb.GetSheet(0)
|
||||
if sheet == nil {
|
||||
return nil, fmt.Errorf("no sheet found")
|
||||
}
|
||||
// LastCol() returns 0 for many data rows in extrame/xls; derive column
|
||||
// count from the header row instead.
|
||||
numCols := 0
|
||||
headerRow := sheet.Row(0)
|
||||
for c := 0; c < headerRow.LastCol(); c++ {
|
||||
if strings.TrimSpace(headerRow.Col(c)) != "" {
|
||||
numCols = c + 1
|
||||
}
|
||||
}
|
||||
if numCols == 0 {
|
||||
numCols = 20
|
||||
}
|
||||
for r := 0; r <= int(sheet.MaxRow); r++ {
|
||||
row := sheet.Row(r)
|
||||
cells := make([]string, numCols)
|
||||
for c := 0; c < numCols; c++ {
|
||||
cells[c] = strings.TrimSpace(row.Col(c))
|
||||
}
|
||||
rows = append(rows, cells)
|
||||
}
|
||||
} else {
|
||||
// xlsx / xlsm(ZIP 格式)
|
||||
xl, xlErr := excelize.OpenReader(f)
|
||||
if xlErr != nil {
|
||||
return nil, fmt.Errorf("invalid xlsx file: %s", xlErr.Error())
|
||||
}
|
||||
rows, err = xl.GetRows(xl.GetSheetName(0))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot read sheet: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if len(rows) < 2 {
|
||||
return nil, fmt.Errorf("empty or invalid sheet")
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func findOrCreateProductFn(db *gorm.DB, shopID uint64, name, series, spec string) (model.Product, error) {
|
||||
var p model.Product
|
||||
if db.Where("shop_id = ? AND name = ? AND series = ? AND spec = ? AND deleted_at IS NULL",
|
||||
shopID, name, series, spec).First(&p).Error == nil {
|
||||
return p, nil
|
||||
}
|
||||
p = model.Product{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Name: name,
|
||||
Series: series,
|
||||
Spec: spec,
|
||||
Unit: "瓶",
|
||||
}
|
||||
return p, db.Create(&p).Error
|
||||
}
|
||||
|
||||
func findOrCreatePartner(db *gorm.DB, shopID uint64, name, ptype string) *uint64 {
|
||||
if name == "" {
|
||||
return nil
|
||||
}
|
||||
var p model.Partner
|
||||
if db.Where("shop_id = ? AND name = ? AND deleted_at IS NULL", shopID, name).First(&p).Error == nil {
|
||||
id := p.ID
|
||||
return &id
|
||||
}
|
||||
p = model.Partner{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Name: name,
|
||||
Type: ptype,
|
||||
Status: "enabled",
|
||||
}
|
||||
if db.Create(&p).Error != nil {
|
||||
return nil
|
||||
}
|
||||
id := p.ID
|
||||
return &id
|
||||
}
|
||||
|
||||
func parseDate(s string) model.Date {
|
||||
t, err := time.ParseInLocation("2006-01-02", s, time.Local)
|
||||
if err != nil {
|
||||
return model.Date{Time: time.Now()}
|
||||
}
|
||||
return model.Date{Time: t}
|
||||
}
|
||||
|
||||
func parsePartnerType(raw string) string {
|
||||
hasCust := strings.Contains(raw, "客户")
|
||||
hasSupp := strings.Contains(raw, "供应商")
|
||||
switch {
|
||||
case hasCust && hasSupp:
|
||||
return "supplier,customer"
|
||||
case hasCust:
|
||||
return "customer"
|
||||
default:
|
||||
return "supplier"
|
||||
}
|
||||
}
|
||||
|
||||
func cell(row []string, idx int) string {
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
qrcode "github.com/skip2/go-qrcode"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/wangjia/jiu/backend/internal/middleware"
|
||||
@@ -65,6 +68,7 @@ func (h *ProductHandler) Create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
product.ShopID = shopID
|
||||
product.PublicID = uuid.New().String()
|
||||
|
||||
// Auto-generate product code if not provided (e.g. P001, P002)
|
||||
// Retry up to 5 times on duplicate key to handle concurrent creates
|
||||
@@ -130,6 +134,7 @@ func (h *ProductHandler) Update(c *gin.Context) {
|
||||
"purchase_price": req.PurchasePrice,
|
||||
"sale_price": req.SalePrice,
|
||||
"min_stock": req.MinStock,
|
||||
"description": req.Description,
|
||||
"remark": req.Remark,
|
||||
"custom_fields": req.CustomFields,
|
||||
}).Error; err != nil {
|
||||
@@ -142,6 +147,97 @@ func (h *ProductHandler) Update(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"data": product})
|
||||
}
|
||||
|
||||
// Detail GET /api/v1/products/:id/detail
|
||||
func (h *ProductHandler) Detail(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var product model.Product
|
||||
if err := h.db.Where("id = ? AND shop_id = ? AND deleted_at IS NULL", id, shopID).
|
||||
Preload("Category").Preload("Images").
|
||||
First(&product).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// 老数据可能没有 public_id,按需补生成
|
||||
if product.PublicID == "" {
|
||||
product.PublicID = uuid.New().String()
|
||||
h.db.Model(&product).Update("public_id", product.PublicID)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"data": product})
|
||||
}
|
||||
|
||||
// QRCode GET /api/v1/products/:id/qrcode
|
||||
func (h *ProductHandler) QRCode(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var product model.Product
|
||||
if err := h.db.Where("id = ? AND shop_id = ? AND deleted_at IS NULL", id, shopID).
|
||||
Select("id, public_id").First(&product).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
url := "https://jiu.51yanmei.com/product/" + product.PublicID
|
||||
png, err := qrcode.Encode(url, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.DataFromReader(http.StatusOK, int64(len(png)), "image/png", bytes.NewReader(png), nil)
|
||||
}
|
||||
|
||||
// FindOrCreate POST /api/v1/products/find-or-create
|
||||
func (h *ProductHandler) FindOrCreate(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var req struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Series string `json:"series"`
|
||||
Spec string `json:"spec"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var product model.Product
|
||||
err := h.db.Where("shop_id = ? AND name = ? AND series = ? AND spec = ? AND deleted_at IS NULL",
|
||||
shopID, req.Name, req.Series, req.Spec).First(&product).Error
|
||||
if err == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"data": product})
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var count int64
|
||||
h.db.Model(&model.Product{}).Where("shop_id = ? AND deleted_at IS NULL", shopID).Count(&count)
|
||||
product = model.Product{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
PublicID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Series: req.Series,
|
||||
Spec: req.Spec,
|
||||
Code: fmt.Sprintf("P%03d", count+1),
|
||||
}
|
||||
if createErr := h.db.Create(&product).Error; createErr != nil {
|
||||
// Race condition: try to find the record created by another request
|
||||
if h.db.Where("shop_id = ? AND name = ? AND series = ? AND spec = ? AND deleted_at IS NULL",
|
||||
shopID, req.Name, req.Series, req.Spec).First(&product).Error == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"data": product})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": createErr.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"data": product})
|
||||
}
|
||||
|
||||
// Delete DELETE /api/v1/products/:id (软删除)
|
||||
func (h *ProductHandler) Delete(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/wangjia/jiu/backend/config"
|
||||
"github.com/wangjia/jiu/backend/internal/middleware"
|
||||
"github.com/wangjia/jiu/backend/internal/model"
|
||||
)
|
||||
|
||||
type ProductImageHandler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewProductImageHandler(db *gorm.DB) *ProductImageHandler {
|
||||
return &ProductImageHandler{db: db}
|
||||
}
|
||||
|
||||
// Upload POST /api/v1/products/:id/images
|
||||
func (h *ProductImageHandler) Upload(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
productID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid product id"})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify product belongs to shop
|
||||
var product model.Product
|
||||
if err := h.db.Where("id = ? AND shop_id = ? AND deleted_at IS NULL", productID, shopID).
|
||||
First(&product).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "product not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Check image count limit
|
||||
var count int64
|
||||
h.db.Model(&model.ProductImage{}).Where("product_id = ? AND shop_id = ?", productID, shopID).Count(&count)
|
||||
if count >= 5 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "最多上传 5 张图片"})
|
||||
return
|
||||
}
|
||||
|
||||
// Parse multipart (1MB limit)
|
||||
if err := c.Request.ParseMultipartForm(1 << 20); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "文件超过 1MB 限制"})
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请上传文件(field: file)"})
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Validate image format via decoding
|
||||
img, _, err := image.Decode(file)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "仅支持 JPEG/PNG 图片"})
|
||||
return
|
||||
}
|
||||
|
||||
// Resize if needed (max 1200px on either dimension, preserve aspect ratio)
|
||||
resized := imaging.Fit(img, 1200, 1200, imaging.Lanczos)
|
||||
|
||||
// Prepare output path
|
||||
filename := uuid.New().String() + ".jpg"
|
||||
subdir := fmt.Sprintf("%s/products/%d", config.C.Storage.UploadDir, productID)
|
||||
if err := os.MkdirAll(subdir, 0755); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "存储目录创建失败"})
|
||||
return
|
||||
}
|
||||
fullPath := filepath.Join(subdir, filename)
|
||||
|
||||
// Save as JPEG with quality 85
|
||||
if err := imaging.Save(resized, fullPath, imaging.JPEGQuality(85)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "图片保存失败"})
|
||||
return
|
||||
}
|
||||
|
||||
// Relative URL served by Nginx / dev static handler
|
||||
relURL := fmt.Sprintf("/images/products/%d/%s", productID, filename)
|
||||
|
||||
pi := model.ProductImage{
|
||||
ProductID: productID,
|
||||
ShopID: shopID,
|
||||
URL: relURL,
|
||||
}
|
||||
if err := h.db.Create(&pi).Error; err != nil {
|
||||
os.Remove(fullPath)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"data": pi})
|
||||
}
|
||||
|
||||
// Delete DELETE /api/v1/products/:id/images/:image_id
|
||||
func (h *ProductImageHandler) Delete(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
productID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid product id"})
|
||||
return
|
||||
}
|
||||
imageID, err := strconv.ParseUint(c.Param("image_id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid image id"})
|
||||
return
|
||||
}
|
||||
|
||||
var pi model.ProductImage
|
||||
if err := h.db.Where("id = ? AND product_id = ? AND shop_id = ?", imageID, productID, shopID).
|
||||
First(&pi).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Delete file from disk
|
||||
filename := filepath.Base(pi.URL)
|
||||
fullPath := filepath.Join(config.C.Storage.UploadDir, fmt.Sprintf("products/%d/%s", productID, filename))
|
||||
os.Remove(fullPath)
|
||||
|
||||
if err := h.db.Delete(&pi).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
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 ProductOptionHandler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewProductOptionHandler(db *gorm.DB) *ProductOptionHandler {
|
||||
return &ProductOptionHandler{db: db}
|
||||
}
|
||||
|
||||
// ── 商品名称 ──────────────────────────────────────────────────
|
||||
|
||||
func (h *ProductOptionHandler) ListNames(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var items []model.ProductNameOption
|
||||
h.db.Where("shop_id = ?", shopID).Order("id ASC").Find(&items)
|
||||
c.JSON(http.StatusOK, gin.H{"data": items})
|
||||
}
|
||||
|
||||
func (h *ProductOptionHandler) CreateName(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var req struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
item := model.ProductNameOption{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Code: req.Code,
|
||||
Name: req.Name,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
if err := h.db.Create(&item).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"data": item})
|
||||
}
|
||||
|
||||
func (h *ProductOptionHandler) DeleteName(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
h.db.Where("id = ? AND shop_id = ?", c.Param("id"), shopID).Delete(&model.ProductNameOption{})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
|
||||
// ── 商品系列 ──────────────────────────────────────────────────
|
||||
|
||||
func (h *ProductOptionHandler) ListSeries(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var items []model.ProductSeriesOption
|
||||
h.db.Where("shop_id = ?", shopID).Order("id ASC").Find(&items)
|
||||
c.JSON(http.StatusOK, gin.H{"data": items})
|
||||
}
|
||||
|
||||
func (h *ProductOptionHandler) CreateSeries(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var req struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
item := model.ProductSeriesOption{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Code: req.Code,
|
||||
Name: req.Name,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
if err := h.db.Create(&item).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"data": item})
|
||||
}
|
||||
|
||||
func (h *ProductOptionHandler) DeleteSeries(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
h.db.Where("id = ? AND shop_id = ?", c.Param("id"), shopID).Delete(&model.ProductSeriesOption{})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
|
||||
// ── 商品规格 ──────────────────────────────────────────────────
|
||||
|
||||
func (h *ProductOptionHandler) ListSpecs(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var items []model.ProductSpecOption
|
||||
h.db.Where("shop_id = ?", shopID).Order("id ASC").Find(&items)
|
||||
c.JSON(http.StatusOK, gin.H{"data": items})
|
||||
}
|
||||
|
||||
func (h *ProductOptionHandler) CreateSpec(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var req struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Quantity int `json:"quantity"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
item := model.ProductSpecOption{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
Code: req.Code,
|
||||
Name: req.Name,
|
||||
Quantity: req.Quantity,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
if err := h.db.Create(&item).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"data": item})
|
||||
}
|
||||
|
||||
func (h *ProductOptionHandler) DeleteSpec(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
h.db.Where("id = ? AND shop_id = ?", c.Param("id"), shopID).Delete(&model.ProductSpecOption{})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/wangjia/jiu/backend/internal/model"
|
||||
)
|
||||
|
||||
type PublicHandler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPublicHandler(db *gorm.DB) *PublicHandler {
|
||||
return &PublicHandler{db: db}
|
||||
}
|
||||
|
||||
// GetProduct GET /api/v1/public/products/:public_id (no auth)
|
||||
func (h *PublicHandler) GetProduct(c *gin.Context) {
|
||||
publicID := c.Param("public_id")
|
||||
|
||||
var product model.Product
|
||||
if err := h.db.Where("public_id = ? AND deleted_at IS NULL", publicID).
|
||||
Preload("Images").
|
||||
First(&product).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Return only public-safe fields (no price/stock info)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"id": product.ID,
|
||||
"name": product.Name,
|
||||
"series": product.Series,
|
||||
"spec": product.Spec,
|
||||
"brand": product.Brand,
|
||||
"unit": product.Unit,
|
||||
"description": product.Description,
|
||||
"images": product.Images,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -51,7 +51,7 @@ func (h *StockInHandler) List(c *gin.Context) {
|
||||
query.Count(&total)
|
||||
|
||||
var orders []model.StockInOrder
|
||||
query.Preload("Warehouse").Preload("Partner").Preload("Operator").
|
||||
query.Preload("Warehouse").Preload("Partner").Preload("Operator").Preload("Reviewer").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Order("id DESC").Find(&orders)
|
||||
|
||||
@@ -62,7 +62,7 @@ func (h *StockInHandler) List(c *gin.Context) {
|
||||
func (h *StockInHandler) Get(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var order model.StockInOrder
|
||||
if err := h.db.Preload("Items.Product").Preload("Warehouse").Preload("Partner").
|
||||
if err := h.db.Preload("Items.Product").Preload("Warehouse").Preload("Partner").Preload("Operator").Preload("Reviewer").
|
||||
Where("id = ? AND shop_id = ? AND deleted_at IS NULL", c.Param("id"), shopID).
|
||||
First(&order).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
|
||||
@@ -45,7 +45,7 @@ func (h *StockOutHandler) List(c *gin.Context) {
|
||||
query.Count(&total)
|
||||
|
||||
var orders []model.StockOutOrder
|
||||
query.Preload("Warehouse").Preload("Partner").Preload("Operator").
|
||||
query.Preload("Warehouse").Preload("Partner").Preload("Operator").Preload("Reviewer").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Order("id DESC").Find(&orders)
|
||||
|
||||
@@ -56,7 +56,7 @@ func (h *StockOutHandler) List(c *gin.Context) {
|
||||
func (h *StockOutHandler) Get(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
var order model.StockOutOrder
|
||||
if err := h.db.Preload("Items.Product").Preload("Warehouse").Preload("Partner").
|
||||
if err := h.db.Preload("Items.Product").Preload("Warehouse").Preload("Partner").Preload("Operator").Preload("Reviewer").
|
||||
Where("id = ? AND shop_id = ? AND deleted_at IS NULL", c.Param("id"), shopID).
|
||||
First(&order).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
|
||||
Reference in New Issue
Block a user