Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fbb4f90ebd | |||
| a05f9bd4ec | |||
| 831dbc5959 | |||
| d5dc499c6b | |||
| 5725e84971 | |||
| 86baaf3a1c | |||
| fcf92675b1 | |||
| d81b2d1fac |
@@ -33,6 +33,21 @@ jobs:
|
||||
SHOPS: ${{ github.event.inputs.shops }}
|
||||
CLEAR: ${{ github.event.inputs.clear }}
|
||||
run: |
|
||||
# 第一步:若需要清空,先把所有门店都清掉再写入
|
||||
# 避免 S001(id=1 硬编码) 因 S002 占用 id=1 而被 INSERT IGNORE 跳过
|
||||
if [ "$CLEAR" = "true" ]; then
|
||||
echo "=== 清空阶段 ==="
|
||||
for SHOP in $(echo "$SHOPS" | tr ',' ' '); do
|
||||
echo " 清空 ${SHOP}..."
|
||||
printf "SET @shop_code='%s';\n" "$SHOP" | cat - backend/seeds/clear_shop.sql | \
|
||||
ssh -i ~/.ssh/ec2_deploy.pem ${EC2_USER}@${EC2_HOST} \
|
||||
"docker exec -i jiu_mysql mysql -uroot -p${DB_PASSWORD} --default-character-set=utf8mb4 jiu_db"
|
||||
done
|
||||
echo "✓ 清空完成"
|
||||
fi
|
||||
|
||||
# 第二步:依次写入所有门店
|
||||
echo "=== 写入阶段 ==="
|
||||
for SHOP in $(echo "$SHOPS" | tr ',' ' '); do
|
||||
FILE="backend/seeds/${SHOP}.sql"
|
||||
if [ ! -f "$FILE" ]; then
|
||||
@@ -40,12 +55,6 @@ jobs:
|
||||
continue
|
||||
fi
|
||||
echo "→ Seeding $SHOP ..."
|
||||
if [ "$CLEAR" = "true" ]; then
|
||||
echo " 清空 ${SHOP} 数据..."
|
||||
printf "SET @shop_code='%s';\n" "$SHOP" | cat - backend/seeds/clear_shop.sql | \
|
||||
ssh -i ~/.ssh/ec2_deploy.pem ${EC2_USER}@${EC2_HOST} \
|
||||
"docker exec -i jiu_mysql mysql -uroot -p${DB_PASSWORD} --default-character-set=utf8mb4 jiu_db"
|
||||
fi
|
||||
ssh -i ~/.ssh/ec2_deploy.pem ${EC2_USER}@${EC2_HOST} \
|
||||
"docker exec -i jiu_mysql mysql -uroot -p${DB_PASSWORD} --default-character-set=utf8mb4 jiu_db" \
|
||||
< "$FILE"
|
||||
|
||||
@@ -132,21 +132,21 @@ func main() {
|
||||
hash := mustHash("password123")
|
||||
admin := upsert(db, &model.User{}, "shop_id = ? AND username = ?", shop.ID, "admin", func() any {
|
||||
return &model.User{
|
||||
TenantBase: model.TenantBase{ShopID: shop.ID},
|
||||
ShopID: shop.ID,
|
||||
Username: "admin", PasswordHash: hash, RealName: "张三(管理员)",
|
||||
Phone: "13800000001", Role: "admin", IsActive: true,
|
||||
}
|
||||
}).(model.User)
|
||||
operator := upsert(db, &model.User{}, "shop_id = ? AND username = ?", shop.ID, "operator", func() any {
|
||||
return &model.User{
|
||||
TenantBase: model.TenantBase{ShopID: shop.ID},
|
||||
ShopID: shop.ID,
|
||||
Username: "operator", PasswordHash: hash, RealName: "李四(操作员)",
|
||||
Phone: "13800000002", Role: "operator", IsActive: true,
|
||||
}
|
||||
}).(model.User)
|
||||
upsert(db, &model.User{}, "shop_id = ? AND username = ?", shop.ID, "test", func() any {
|
||||
return &model.User{
|
||||
TenantBase: model.TenantBase{ShopID: shop.ID},
|
||||
ShopID: shop.ID,
|
||||
Username: "test", PasswordHash: hash, RealName: "王五(只读)",
|
||||
Phone: "13800000003", Role: "readonly", IsActive: true,
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
@@ -512,66 +513,126 @@ func (h *ImportHandler) ImportInventory(c *gin.Context) {
|
||||
}
|
||||
|
||||
type importResult struct {
|
||||
total int
|
||||
imported int
|
||||
updated int
|
||||
skipped int
|
||||
errors []string
|
||||
}
|
||||
var res importResult
|
||||
|
||||
// 仓库缓存,只查找不创建
|
||||
warehouseCache := map[string]*uint64{}
|
||||
// 预加载仓库(1 次查询)
|
||||
var warehouses []model.Warehouse
|
||||
h.db.Where("shop_id = ? AND deleted_at IS NULL", shopID).Find(&warehouses)
|
||||
warehouseByName := make(map[string]uint64, len(warehouses))
|
||||
for _, wh := range warehouses {
|
||||
warehouseByName[wh.Name] = wh.ID
|
||||
}
|
||||
findWarehouse := func(name string) *uint64 {
|
||||
if name == "" {
|
||||
return nil
|
||||
}
|
||||
if idPtr, ok := warehouseCache[name]; ok {
|
||||
return idPtr
|
||||
if id, ok := warehouseByName[name]; ok {
|
||||
return &id
|
||||
}
|
||||
var wh model.Warehouse
|
||||
if h.db.Where("shop_id = ? AND name = ? AND deleted_at IS NULL", shopID, name).First(&wh).Error != nil {
|
||||
warehouseCache[name] = nil
|
||||
return nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// 预加载商品(1 次查询)
|
||||
var allProducts []model.Product
|
||||
h.db.Where("shop_id = ? AND deleted_at IS NULL", shopID).Find(&allProducts)
|
||||
productByCode := make(map[string]*model.Product, len(allProducts))
|
||||
productByNSS := make(map[string]*model.Product, len(allProducts))
|
||||
for i := range allProducts {
|
||||
p := &allProducts[i]
|
||||
if p.Code != "" {
|
||||
productByCode[p.Code] = p
|
||||
}
|
||||
id := wh.ID
|
||||
warehouseCache[name] = &id
|
||||
return &id
|
||||
productByNSS[p.Name+"|"+p.Series+"|"+p.Spec] = p
|
||||
}
|
||||
|
||||
// 预加载已有导入库存(1 次查询)
|
||||
// 同时建两套索引:编号索引 + 名称|系列|规格索引,供后续双路查找
|
||||
var allInvs []model.Inventory
|
||||
h.db.Where("shop_id = ? AND stock_in_item_id IS NULL AND deleted_at IS NULL", shopID).Find(&allInvs)
|
||||
invByCode := make(map[string]*model.Inventory, len(allInvs)) // key: productCode|warehouseID
|
||||
invByNSS := make(map[string]*model.Inventory, len(allInvs)) // key: name|series|spec|warehouseID
|
||||
for i := range allInvs {
|
||||
inv := &allInvs[i]
|
||||
whID := uint64(0)
|
||||
if inv.WarehouseID != nil {
|
||||
whID = *inv.WarehouseID
|
||||
}
|
||||
if inv.ProductCode != "" {
|
||||
invByCode[fmt.Sprintf("%s|%d", inv.ProductCode, whID)] = inv
|
||||
}
|
||||
nssKey := fmt.Sprintf("%s|%s|%s|%d", inv.ProductName, inv.Series, inv.Spec, whID)
|
||||
invByNSS[nssKey] = inv
|
||||
}
|
||||
lookupInv := func(productCode, name, series, spec string, whID uint64) *model.Inventory {
|
||||
if productCode != "" {
|
||||
if inv, ok := invByCode[fmt.Sprintf("%s|%d", productCode, whID)]; ok {
|
||||
return inv
|
||||
}
|
||||
}
|
||||
return invByNSS[fmt.Sprintf("%s|%s|%s|%d", name, series, spec, whID)]
|
||||
}
|
||||
|
||||
// Dynamic column detection from header row
|
||||
colProductCode, colProductName, colSeries, colSpec, colUnit := 0, 1, 2, 3, 4
|
||||
colQty, colPrice, colProductionDate, colBatchNo, colWarehouse, colSupplier, colRemark := 5, 6, 8, 9, 11, 13, 15
|
||||
if len(rows) > 0 {
|
||||
log.Printf("[import-inv] header row (%d cols): %v", len(rows[0]), rows[0])
|
||||
for j, h := range rows[0] {
|
||||
switch strings.TrimSpace(h) {
|
||||
case "库存数量", "数量":
|
||||
case "商品编号", "商品编码", "编号", "编码", "商品条码":
|
||||
colProductCode = j
|
||||
case "商品名称", "品名", "名称", "货品名称":
|
||||
colProductName = j
|
||||
case "系列", "品牌系列":
|
||||
colSeries = j
|
||||
case "规格", "规格型号":
|
||||
colSpec = j
|
||||
case "单位":
|
||||
colUnit = j
|
||||
case "库存数量", "数量", "库存":
|
||||
colQty = j
|
||||
case "单价":
|
||||
case "单价", "进价", "采购单价":
|
||||
colPrice = j
|
||||
case "生产日期":
|
||||
case "生产日期", "生产年月":
|
||||
colProductionDate = j
|
||||
case "批次", "批次号":
|
||||
colBatchNo = j
|
||||
case "所在仓库", "仓库":
|
||||
case "所在仓库", "仓库", "库位":
|
||||
colWarehouse = j
|
||||
case "供应商":
|
||||
case "供应商", "供应商名称":
|
||||
colSupplier = j
|
||||
case "备注":
|
||||
colRemark = j
|
||||
}
|
||||
}
|
||||
}
|
||||
log.Printf("[import-inv] total rows=%d, colProductName=%d, colProductCode=%d, colQty=%d",
|
||||
len(rows), colProductName, colProductCode, colQty)
|
||||
|
||||
// 如果没有匹配到任何列头,返回诊断信息
|
||||
detectedHeader := strings.Join(rows[0], " | ")
|
||||
|
||||
var logsToCreate []model.InventoryLog
|
||||
|
||||
for i, row := range rows[1:] {
|
||||
productName := cell(row, 1)
|
||||
productName := cell(row, colProductName)
|
||||
if i < 5 {
|
||||
log.Printf("[import-inv] row[%d] len=%d | productName=%q productCode=%q qty=%q",
|
||||
i+2, len(row), productName, cell(row, colProductCode), cell(row, colQty))
|
||||
}
|
||||
if productName == "" {
|
||||
res.skipped++
|
||||
continue
|
||||
continue // 空行(文件末尾填充行),不计入 total
|
||||
}
|
||||
|
||||
productCode := cell(row, 0)
|
||||
series := cell(row, 2)
|
||||
spec := cell(row, 3)
|
||||
unit := cell(row, 4)
|
||||
productCode := cell(row, colProductCode)
|
||||
series := cell(row, colSeries)
|
||||
spec := cell(row, colSpec)
|
||||
unit := cell(row, colUnit)
|
||||
qtyStr := cell(row, colQty)
|
||||
priceStr := cell(row, colPrice)
|
||||
productionDateStr := cell(row, colProductionDate)
|
||||
@@ -586,20 +647,32 @@ func (h *ImportHandler) ImportInventory(c *gin.Context) {
|
||||
}
|
||||
price, _ := strconv.ParseFloat(priceStr, 64)
|
||||
|
||||
// 只查找商品,不强制创建
|
||||
var prod model.Product
|
||||
if h.db.Where("shop_id = ? AND deleted_at IS NULL AND (code = ? OR (name = ? AND series = ? AND spec = ?))",
|
||||
shopID, productCode, productName, series, spec).First(&prod).Error != nil {
|
||||
// 若找不到则创建
|
||||
res.total++ // 有商品名称的行才计入总数
|
||||
|
||||
// 从缓存查商品,找不到才创建
|
||||
var prod *model.Product
|
||||
if productCode != "" {
|
||||
prod = productByCode[productCode]
|
||||
}
|
||||
if prod == nil {
|
||||
prod = productByNSS[productName+"|"+series+"|"+spec]
|
||||
}
|
||||
if prod == nil {
|
||||
newProd, createErr := findOrCreateProductFn(h.db, shopID, productCode, productName, series, spec)
|
||||
if createErr != nil {
|
||||
res.errors = append(res.errors, fmt.Sprintf("行%d: 商品创建失败: %s", i+2, createErr.Error()))
|
||||
continue
|
||||
}
|
||||
prod = newProd
|
||||
allProducts = append(allProducts, newProd)
|
||||
prod = &allProducts[len(allProducts)-1]
|
||||
if prod.Code != "" {
|
||||
productByCode[prod.Code] = prod
|
||||
}
|
||||
productByNSS[prod.Name+"|"+prod.Series+"|"+prod.Spec] = prod
|
||||
}
|
||||
if unit != "" && prod.Unit == "" {
|
||||
h.db.Model(&prod).Update("unit", unit)
|
||||
h.db.Model(prod).Update("unit", unit)
|
||||
prod.Unit = unit
|
||||
}
|
||||
|
||||
// 解析生产日期
|
||||
@@ -609,7 +682,6 @@ func (h *ImportHandler) ImportInventory(c *gin.Context) {
|
||||
productionDate = &d
|
||||
}
|
||||
|
||||
// 查找仓库(只查,不创建)
|
||||
whIDPtr := findWarehouse(warehouseName)
|
||||
|
||||
var unitPricePtr *float64
|
||||
@@ -617,30 +689,24 @@ func (h *ImportHandler) ImportInventory(c *gin.Context) {
|
||||
unitPricePtr = &price
|
||||
}
|
||||
|
||||
productIDCopy := prod.ID
|
||||
|
||||
// Upsert:按商品编号 + 仓库查找已有导入记录,存在则更新,不存在则新建
|
||||
var existing model.Inventory
|
||||
q := h.db.Where("shop_id = ? AND product_code = ? AND stock_in_item_id IS NULL AND deleted_at IS NULL",
|
||||
shopID, prod.Code)
|
||||
whIDVal := uint64(0)
|
||||
if whIDPtr != nil {
|
||||
q = q.Where("warehouse_id = ?", *whIDPtr)
|
||||
} else {
|
||||
q = q.Where("warehouse_id IS NULL")
|
||||
whIDVal = *whIDPtr
|
||||
}
|
||||
found := q.First(&existing).Error == nil
|
||||
|
||||
if found {
|
||||
existing := lookupInv(productCode, prod.Name, prod.Series, prod.Spec, whIDVal)
|
||||
|
||||
if existing != nil {
|
||||
updates := map[string]interface{}{
|
||||
"quantity": qty,
|
||||
"product_name": prod.Name,
|
||||
"series": prod.Series,
|
||||
"spec": prod.Spec,
|
||||
"unit": prod.Unit,
|
||||
"warehouse_name": warehouseName,
|
||||
"supplier_name": supplierName,
|
||||
"remark": remark,
|
||||
"deleted_at": nil,
|
||||
"quantity": qty,
|
||||
"product_name": prod.Name,
|
||||
"series": prod.Series,
|
||||
"spec": prod.Spec,
|
||||
"unit": prod.Unit,
|
||||
"warehouse_name": warehouseName,
|
||||
"supplier_name": supplierName,
|
||||
"remark": remark,
|
||||
"deleted_at": nil,
|
||||
}
|
||||
if unitPricePtr != nil {
|
||||
updates["unit_price"] = *unitPricePtr
|
||||
@@ -651,11 +717,18 @@ func (h *ImportHandler) ImportInventory(c *gin.Context) {
|
||||
if batchNo != "" {
|
||||
updates["batch_no"] = batchNo
|
||||
}
|
||||
if err := h.db.Model(&existing).Updates(updates).Error; err != nil {
|
||||
if err := h.db.Model(existing).Updates(updates).Error; err != nil {
|
||||
res.errors = append(res.errors, fmt.Sprintf("行%d: 库存更新失败: %s", i+2, err.Error()))
|
||||
continue
|
||||
}
|
||||
logsToCreate = append(logsToCreate, model.InventoryLog{
|
||||
ShopID: shopID, WarehouseID: whIDVal, ProductID: prod.ID,
|
||||
Direction: "in", Quantity: qty, QtyBefore: existing.Quantity, QtyAfter: qty,
|
||||
RefType: "import", RefID: 0,
|
||||
})
|
||||
res.updated++
|
||||
} else {
|
||||
productIDCopy := prod.ID
|
||||
inv := model.Inventory{
|
||||
ShopID: shopID,
|
||||
WarehouseID: whIDPtr,
|
||||
@@ -678,38 +751,38 @@ func (h *ImportHandler) ImportInventory(c *gin.Context) {
|
||||
res.errors = append(res.errors, fmt.Sprintf("行%d: 库存写入失败: %s", i+2, err.Error()))
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 写流水
|
||||
warehouseID := uint64(0)
|
||||
if whIDPtr != nil {
|
||||
warehouseID = *whIDPtr
|
||||
}
|
||||
qtyBefore := 0.0
|
||||
if found {
|
||||
qtyBefore = existing.Quantity
|
||||
res.updated++
|
||||
} else {
|
||||
// 写入两套缓存,防止同文件后续行重复插入
|
||||
if inv.ProductCode != "" {
|
||||
invByCode[fmt.Sprintf("%s|%d", inv.ProductCode, whIDVal)] = &inv
|
||||
}
|
||||
invByNSS[fmt.Sprintf("%s|%s|%s|%d", inv.ProductName, inv.Series, inv.Spec, whIDVal)] = &inv
|
||||
logsToCreate = append(logsToCreate, model.InventoryLog{
|
||||
ShopID: shopID, WarehouseID: whIDVal, ProductID: prod.ID,
|
||||
Direction: "in", Quantity: qty, QtyBefore: 0, QtyAfter: qty,
|
||||
RefType: "import", RefID: 0,
|
||||
})
|
||||
res.imported++
|
||||
}
|
||||
log := model.InventoryLog{
|
||||
ShopID: shopID,
|
||||
WarehouseID: warehouseID,
|
||||
ProductID: prod.ID,
|
||||
Direction: "in",
|
||||
Quantity: qty,
|
||||
QtyBefore: qtyBefore,
|
||||
QtyAfter: qty,
|
||||
RefType: "import",
|
||||
RefID: 0,
|
||||
}
|
||||
h.db.Create(&log)
|
||||
}
|
||||
|
||||
// 批量写流水
|
||||
if len(logsToCreate) > 0 {
|
||||
h.db.CreateInBatches(&logsToCreate, 100)
|
||||
}
|
||||
|
||||
// total=0 说明列格式不匹配,没有解析到任何有效行
|
||||
if res.total == 0 {
|
||||
res.errors = append(res.errors,
|
||||
fmt.Sprintf("未解析到任何有效行,可能列格式不匹配。识别到的表头:%s", detectedHeader))
|
||||
}
|
||||
|
||||
log.Printf("[import-inv] RESULT: total=%d imported=%d updated=%d errors=%d",
|
||||
res.total, res.imported, res.updated, len(res.errors))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"total": res.total,
|
||||
"imported": res.imported,
|
||||
"updated": res.updated,
|
||||
"skipped": res.skipped,
|
||||
"errors": res.errors,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/wangjia/jiu/backend/config"
|
||||
"github.com/wangjia/jiu/backend/internal/middleware"
|
||||
"github.com/wangjia/jiu/backend/internal/model"
|
||||
)
|
||||
@@ -38,6 +46,7 @@ func (h *ShopHandler) UpdateInfo(c *gin.Context) {
|
||||
Address string `json:"address"`
|
||||
Phone string `json:"phone"`
|
||||
ManagerName string `json:"manager_name"`
|
||||
LogoURL string `json:"logo_url"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -50,6 +59,9 @@ func (h *ShopHandler) UpdateInfo(c *gin.Context) {
|
||||
"phone": req.Phone,
|
||||
"manager_name": req.ManagerName,
|
||||
}
|
||||
if req.LogoURL != "" {
|
||||
updates["logo_url"] = req.LogoURL
|
||||
}
|
||||
if err := h.db.Model(&model.Shop{}).Where("id = ?", shopID).Updates(updates).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -59,3 +71,48 @@ func (h *ShopHandler) UpdateInfo(c *gin.Context) {
|
||||
h.db.First(&shop, shopID)
|
||||
c.JSON(http.StatusOK, shop)
|
||||
}
|
||||
|
||||
// UploadLogo POST /api/v1/shop/logo (admin only)
|
||||
func (h *ShopHandler) UploadLogo(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
|
||||
if err := c.Request.ParseMultipartForm(2 << 20); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "文件超过 2MB 限制"})
|
||||
return
|
||||
}
|
||||
file, _, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请上传文件(field: file)"})
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
img, _, err := image.Decode(file)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "仅支持 JPEG/PNG 图片"})
|
||||
return
|
||||
}
|
||||
|
||||
// 裁剪为正方形后缩放到 256×256
|
||||
resized := imaging.Fill(img, 256, 256, imaging.Center, imaging.Lanczos)
|
||||
|
||||
subdir := filepath.Join(config.C.Storage.UploadDir, "shops", fmt.Sprintf("%d", shopID))
|
||||
if err := os.MkdirAll(subdir, 0755); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "存储目录创建失败"})
|
||||
return
|
||||
}
|
||||
fullPath := filepath.Join(subdir, "logo.jpg")
|
||||
|
||||
if err := imaging.Save(resized, fullPath, imaging.JPEGQuality(90)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "图片保存失败"})
|
||||
return
|
||||
}
|
||||
|
||||
logoURL := fmt.Sprintf("/images/shops/%d/logo.jpg", shopID)
|
||||
if err := h.db.Model(&model.Shop{}).Where("id = ?", shopID).Update("logo_url", logoURL).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"logo_url": logoURL})
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func (h *UserHandler) Create(c *gin.Context) {
|
||||
role = "operator"
|
||||
}
|
||||
u := model.User{
|
||||
TenantBase: model.TenantBase{ShopID: shopID},
|
||||
ShopID: shopID,
|
||||
Username: req.Username,
|
||||
PasswordHash: string(hash),
|
||||
RealName: req.RealName,
|
||||
|
||||
@@ -8,6 +8,7 @@ type Shop struct {
|
||||
Phone string `gorm:"size:30" json:"phone"`
|
||||
BusinessHours string `gorm:"size:100" json:"business_hours"`
|
||||
ManagerName string `gorm:"size:50" json:"manager_name"`
|
||||
LogoURL string `gorm:"column:logo_url;size:500" json:"logo_url"`
|
||||
BusinessLicense string `gorm:"size:500" json:"business_license"`
|
||||
ShopPhotos JSON `gorm:"type:json" json:"shop_photos,omitempty"`
|
||||
CustomFields JSON `gorm:"type:json" json:"custom_fields,omitempty"`
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package model
|
||||
|
||||
type User struct {
|
||||
TenantBase
|
||||
Base
|
||||
ShopID uint64 `gorm:"not null;index;uniqueIndex:uk_shop_username" json:"shop_id"`
|
||||
Username string `gorm:"size:50;uniqueIndex:uk_shop_username" json:"username"`
|
||||
PasswordHash string `gorm:"size:255" json:"-"`
|
||||
RealName string `gorm:"size:50" json:"real_name"`
|
||||
|
||||
@@ -165,6 +165,7 @@ func Setup(r *gin.Engine, db *gorm.DB) {
|
||||
{
|
||||
shop.GET("/info", shopH.GetInfo)
|
||||
shop.PUT("/info", middleware.AdminOnly(), shopH.UpdateInfo)
|
||||
shop.POST("/logo", middleware.AdminOnly(), shopH.UploadLogo)
|
||||
}
|
||||
|
||||
// 编号规则
|
||||
|
||||
@@ -17,6 +17,7 @@ CREATE TABLE IF NOT EXISTS `shops` (
|
||||
`address` VARCHAR(255) DEFAULT NULL,
|
||||
`phone` VARCHAR(30) DEFAULT NULL,
|
||||
`manager_name` VARCHAR(50) DEFAULT NULL COMMENT '负责人',
|
||||
`logo_url` VARCHAR(500) DEFAULT '' COMMENT '门店 logo URL',
|
||||
`business_license` VARCHAR(500) DEFAULT NULL COMMENT '营业执照照片URL',
|
||||
`shop_photos` JSON DEFAULT NULL COMMENT '门店照片URL数组',
|
||||
`custom_fields` JSON DEFAULT NULL COMMENT '扩展字段',
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
-- 或由脚本拼接:
|
||||
-- echo "SET @shop_code='S001';" | cat - clear_shop.sql | mysql ...
|
||||
|
||||
SET @sid = (SELECT id FROM shops WHERE code = @shop_code LIMIT 1);
|
||||
SET @sid = (SELECT id FROM shops WHERE BINARY code = BINARY @shop_code LIMIT 1);
|
||||
|
||||
SET FOREIGN_KEY_CHECKS = 0;
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ func SetupTestDB() *gorm.DB {
|
||||
address TEXT,
|
||||
phone TEXT,
|
||||
manager_name TEXT,
|
||||
logo_url TEXT DEFAULT '',
|
||||
business_license TEXT,
|
||||
business_hours TEXT,
|
||||
shop_photos TEXT,
|
||||
@@ -349,10 +350,7 @@ func hashPassword(plain string) string {
|
||||
func CreateTestUser(db *gorm.DB, shopID uint64, username, password, role string) *model.User {
|
||||
hash := hashPassword(password)
|
||||
user := &model.User{
|
||||
TenantBase: model.TenantBase{
|
||||
Base: model.Base{},
|
||||
ShopID: shopID,
|
||||
},
|
||||
ShopID: shopID,
|
||||
Username: username,
|
||||
PasswordHash: hash,
|
||||
RealName: "Test User " + username,
|
||||
|
||||
@@ -5,6 +5,7 @@ class ShopInfo {
|
||||
final String address;
|
||||
final String phone;
|
||||
final String managerName;
|
||||
final String logoUrl;
|
||||
|
||||
const ShopInfo({
|
||||
required this.id,
|
||||
@@ -13,6 +14,7 @@ class ShopInfo {
|
||||
required this.address,
|
||||
required this.phone,
|
||||
required this.managerName,
|
||||
this.logoUrl = '',
|
||||
});
|
||||
|
||||
factory ShopInfo.fromJson(Map<String, dynamic> json) => ShopInfo(
|
||||
@@ -22,5 +24,6 @@ class ShopInfo {
|
||||
address: json['address'] as String? ?? '',
|
||||
phone: json['phone'] as String? ?? '',
|
||||
managerName: json['manager_name'] as String? ?? '',
|
||||
logoUrl: json['logo_url'] as String? ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../core/api/api_client.dart';
|
||||
import '../core/exceptions.dart';
|
||||
import '../models/shop.dart';
|
||||
@@ -30,4 +31,19 @@ class ShopRepository {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> uploadLogo(Uint8List bytes, String filename) async {
|
||||
try {
|
||||
final formData = FormData.fromMap({
|
||||
'file': MultipartFile.fromBytes(bytes, filename: filename),
|
||||
});
|
||||
final resp = await _client.post('/shop/logo', data: formData);
|
||||
return (resp.data as Map<String, dynamic>)['logo_url'] as String? ?? '';
|
||||
} on DioException catch (e) {
|
||||
throw AppException(
|
||||
e.response?.data?['error'] as String? ?? 'Logo 上传失败',
|
||||
statusCode: e.response?.statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,42 +99,97 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
|
||||
final file = result.files.first;
|
||||
final bytes = file.bytes;
|
||||
if (bytes == null) return;
|
||||
if (!context.mounted) return;
|
||||
|
||||
final token = ref.read(authStateProvider).user?.accessToken ?? '';
|
||||
final dio = Dio(BaseOptions(baseUrl: AppConfig.apiBaseUrl));
|
||||
final dio = Dio(BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
sendTimeout: const Duration(seconds: 120),
|
||||
receiveTimeout: const Duration(seconds: 300),
|
||||
));
|
||||
dio.options.headers['Authorization'] = 'Bearer $token';
|
||||
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('导入中,请稍候...'), duration: Duration(seconds: 60)),
|
||||
final stateNotifier = ValueNotifier<_ImportState>(
|
||||
const _ImportState(stage: _ImportStage.uploading, uploadPercent: 0),
|
||||
);
|
||||
|
||||
BuildContext? dialogCtx;
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (ctx) {
|
||||
dialogCtx = ctx;
|
||||
return PopScope(
|
||||
canPop: false,
|
||||
child: _ImportProgressDialog(stateNotifier: stateNotifier),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Timer? processingTimer;
|
||||
bool uploadDone = false;
|
||||
int elapsed = 0;
|
||||
|
||||
void closeDialog() {
|
||||
processingTimer?.cancel();
|
||||
if (dialogCtx != null && dialogCtx!.mounted) {
|
||||
Navigator.of(dialogCtx!).pop();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
final formData = FormData.fromMap({
|
||||
'file': MultipartFile.fromBytes(bytes, filename: file.name),
|
||||
});
|
||||
final resp = await dio.post('/import/inventory', data: formData);
|
||||
final data = resp.data as Map<String, dynamic>;
|
||||
final imported = data['imported'] ?? 0;
|
||||
final skipped = data['skipped'] ?? 0;
|
||||
final errors = (data['errors'] as List?)?.cast<String>() ?? [];
|
||||
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('导入完成:$imported 条成功,$skipped 条跳过${errors.isNotEmpty ? ',${errors.length} 条失败' : ''}'),
|
||||
backgroundColor: errors.isEmpty ? Colors.green : AppTheme.accent,
|
||||
duration: const Duration(seconds: 4),
|
||||
));
|
||||
ref.read(inventoryListProvider.notifier).reload();
|
||||
final resp = await dio.post(
|
||||
'/import/inventory',
|
||||
data: formData,
|
||||
onSendProgress: (sent, total) {
|
||||
if (total <= 0) return;
|
||||
if (sent >= total && !uploadDone) {
|
||||
uploadDone = true;
|
||||
elapsed = 0;
|
||||
stateNotifier.value = const _ImportState(
|
||||
stage: _ImportStage.processing, uploadPercent: 100, processingSeconds: 0,
|
||||
);
|
||||
processingTimer = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
elapsed++;
|
||||
stateNotifier.value = _ImportState(
|
||||
stage: _ImportStage.processing, uploadPercent: 100, processingSeconds: elapsed,
|
||||
);
|
||||
});
|
||||
} else if (!uploadDone) {
|
||||
final pct = (sent / total * 100).round().clamp(0, 99);
|
||||
stateNotifier.value = _ImportState(stage: _ImportStage.uploading, uploadPercent: pct);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
processingTimer?.cancel();
|
||||
final data = resp.data as Map<String, dynamic>;
|
||||
stateNotifier.value = _ImportState(
|
||||
stage: _ImportStage.done,
|
||||
uploadPercent: 100,
|
||||
total: data['total'] ?? 0,
|
||||
imported: data['imported'] ?? 0,
|
||||
updated: data['updated'] ?? 0,
|
||||
errors: (data['errors'] as List?)?.cast<String>() ?? [],
|
||||
);
|
||||
|
||||
final hasErrors = (data['errors'] as List?)?.isNotEmpty ?? false;
|
||||
if (!hasErrors) {
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
closeDialog();
|
||||
}
|
||||
if (context.mounted) ref.read(inventoryListProvider.notifier).reload();
|
||||
} on DioException catch (e) {
|
||||
final msg = (e.response?.data is Map ? e.response!.data['error'] : null) ?? e.message ?? '未知错误';
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('导入失败:$msg'),
|
||||
backgroundColor: AppTheme.danger,
|
||||
));
|
||||
processingTimer?.cancel();
|
||||
final msg = (e.response?.data is Map ? e.response!.data['error'] : null)
|
||||
?? e.message ?? '未知错误';
|
||||
stateNotifier.value = _ImportState(
|
||||
stage: _ImportStage.error, uploadPercent: 0, errorMsg: msg,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -865,3 +920,163 @@ class _DirectionBadge extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 导入进度对话框 ──────────────────────────────────────────
|
||||
|
||||
enum _ImportStage { uploading, processing, done, error }
|
||||
|
||||
class _ImportState {
|
||||
final _ImportStage stage;
|
||||
final int uploadPercent;
|
||||
final int processingSeconds;
|
||||
final int total;
|
||||
final int imported;
|
||||
final int updated;
|
||||
final List<String> errors;
|
||||
final String? errorMsg;
|
||||
|
||||
const _ImportState({
|
||||
required this.stage,
|
||||
required this.uploadPercent,
|
||||
this.processingSeconds = 0,
|
||||
this.total = 0,
|
||||
this.imported = 0,
|
||||
this.updated = 0,
|
||||
this.errors = const [],
|
||||
this.errorMsg,
|
||||
});
|
||||
}
|
||||
|
||||
class _ImportProgressDialog extends StatelessWidget {
|
||||
final ValueNotifier<_ImportState> stateNotifier;
|
||||
const _ImportProgressDialog({required this.stateNotifier});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('导入库存'),
|
||||
content: ValueListenableBuilder<_ImportState>(
|
||||
valueListenable: stateNotifier,
|
||||
builder: (_, state, __) => SizedBox(
|
||||
width: 320,
|
||||
child: _buildContent(context, state),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
ValueListenableBuilder<_ImportState>(
|
||||
valueListenable: stateNotifier,
|
||||
builder: (ctx, state, __) {
|
||||
if (state.stage == _ImportStage.done || state.stage == _ImportStage.error) {
|
||||
return TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(),
|
||||
child: const Text('关闭'),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(BuildContext context, _ImportState state) {
|
||||
switch (state.stage) {
|
||||
case _ImportStage.uploading:
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text('上传文件...', style: TextStyle(fontSize: 14)),
|
||||
const SizedBox(height: 12),
|
||||
LinearProgressIndicator(
|
||||
value: state.uploadPercent / 100,
|
||||
backgroundColor: Colors.grey[200],
|
||||
valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primary),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text('${state.uploadPercent}%',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[600])),
|
||||
],
|
||||
);
|
||||
|
||||
case _ImportStage.processing:
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(children: [
|
||||
SizedBox(
|
||||
width: 16, height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primary),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
'导入数据中...${state.processingSeconds > 0 ? "(${state.processingSeconds}秒)" : ""}',
|
||||
style: const TextStyle(fontSize: 14),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 8),
|
||||
LinearProgressIndicator(
|
||||
backgroundColor: Colors.grey[200],
|
||||
valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primary),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
case _ImportStage.done:
|
||||
final allFailed = state.total == 0 && state.errors.isNotEmpty;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(children: [
|
||||
Icon(
|
||||
allFailed ? Icons.warning_amber_rounded : Icons.check_circle,
|
||||
color: allFailed ? AppTheme.danger : AppTheme.success,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
allFailed ? '导入失败' : '导入完成',
|
||||
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 10),
|
||||
Text('共 ${state.total} 行', style: const TextStyle(fontSize: 13)),
|
||||
Text('成功插入:${state.imported} 行', style: const TextStyle(fontSize: 13)),
|
||||
Text('重复更新:${state.updated} 行',
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey[600])),
|
||||
if (state.errors.isNotEmpty)
|
||||
Text('失败:${state.errors.length} 行',
|
||||
style: TextStyle(fontSize: 13, color: AppTheme.danger)),
|
||||
if (state.errors.isNotEmpty) ...[
|
||||
const SizedBox(height: 6),
|
||||
...state.errors.map((e) => Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(e,
|
||||
style: TextStyle(fontSize: 12, color: AppTheme.danger)),
|
||||
)),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
case _ImportStage.error:
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: AppTheme.danger, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'导入失败:${state.errorMsg}',
|
||||
style: TextStyle(fontSize: 13, color: AppTheme.danger),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import '../../core/utils/dialog_util.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
@@ -126,14 +127,24 @@ class _SettingsScreenState extends ConsumerState<SettingsScreen> {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_ShopInfoRow(
|
||||
label: '门店编号',
|
||||
value: shop.code.isNotEmpty ? shop.code : '—'),
|
||||
const Divider(height: 16),
|
||||
_ShopInfoRow(
|
||||
label: '门店名称',
|
||||
value: shop.name.isNotEmpty ? shop.name : '—'),
|
||||
const Divider(height: 16),
|
||||
// Logo 预览行
|
||||
Row(
|
||||
children: [
|
||||
_ShopLogoPreview(logoUrl: shop.logoUrl, shopName: shop.name, size: 64),
|
||||
const SizedBox(width: 16),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(shop.name.isNotEmpty ? shop.name : '—',
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 4),
|
||||
Text(shop.code.isNotEmpty ? shop.code : '—',
|
||||
style: const TextStyle(fontSize: 13, color: AppTheme.textSecondary)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(height: 24),
|
||||
_ShopInfoRow(
|
||||
label: '门店地址',
|
||||
value: shop.address.isNotEmpty ? shop.address : '—'),
|
||||
@@ -1524,10 +1535,23 @@ class _ImportSlot {
|
||||
int total = 0;
|
||||
int imported = 0;
|
||||
int skipped = 0;
|
||||
int updated = 0;
|
||||
// 进度
|
||||
int uploadPercent = 0;
|
||||
bool isProcessing = false;
|
||||
int processingSeconds = 0;
|
||||
|
||||
_ImportSlot(this.title, this.endpoint, this.hint);
|
||||
|
||||
bool get hasResult => success != null;
|
||||
|
||||
void resetProgress() {
|
||||
uploadPercent = 0;
|
||||
isProcessing = false;
|
||||
processingSeconds = 0;
|
||||
success = null;
|
||||
error = null;
|
||||
}
|
||||
}
|
||||
|
||||
class _BatchImportWidget extends ConsumerStatefulWidget {
|
||||
@@ -1657,14 +1681,15 @@ class _BatchImportWidgetState extends ConsumerState<_BatchImportWidget> {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
for (final s in _slots) {
|
||||
if (s.file != null) {
|
||||
s.success = null;
|
||||
s.error = null;
|
||||
}
|
||||
if (s.file != null) s.resetProgress();
|
||||
}
|
||||
});
|
||||
|
||||
final dio = Dio(BaseOptions(baseUrl: AppConfig.apiBaseUrl));
|
||||
final dio = Dio(BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
sendTimeout: const Duration(seconds: 120),
|
||||
receiveTimeout: const Duration(seconds: 300),
|
||||
));
|
||||
dio.options.headers['Authorization'] = 'Bearer $token';
|
||||
|
||||
for (final slot in _slots) {
|
||||
@@ -1674,29 +1699,57 @@ class _BatchImportWidgetState extends ConsumerState<_BatchImportWidget> {
|
||||
if (mounted) setState(() { slot.success = false; slot.error = '无法读取文件'; });
|
||||
continue;
|
||||
}
|
||||
|
||||
Timer? processingTimer;
|
||||
bool uploadDone = false;
|
||||
|
||||
try {
|
||||
final formData = FormData.fromMap({
|
||||
'file': MultipartFile.fromBytes(bytes, filename: slot.file!.name),
|
||||
});
|
||||
final resp = await dio.post(slot.endpoint, data: formData);
|
||||
final resp = await dio.post(
|
||||
slot.endpoint,
|
||||
data: formData,
|
||||
onSendProgress: (sent, total) {
|
||||
if (total <= 0 || !mounted) return;
|
||||
if (sent >= total && !uploadDone) {
|
||||
uploadDone = true;
|
||||
setState(() { slot.isProcessing = true; slot.processingSeconds = 0; });
|
||||
processingTimer = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (!mounted) return;
|
||||
setState(() => slot.processingSeconds++);
|
||||
});
|
||||
} else if (!uploadDone) {
|
||||
final pct = (sent / total * 100).round().clamp(0, 99);
|
||||
if (mounted) setState(() => slot.uploadPercent = pct);
|
||||
}
|
||||
},
|
||||
);
|
||||
processingTimer?.cancel();
|
||||
final data = (resp.data is Map) ? resp.data as Map<String, dynamic> : <String, dynamic>{};
|
||||
if (mounted) setState(() {
|
||||
slot.success = true;
|
||||
slot.total = (data['total'] ?? data['imported'] ?? 0) as int;
|
||||
slot.imported = (data['imported'] ?? 0) as int;
|
||||
slot.skipped = (data['skipped'] ?? 0) as int;
|
||||
slot.updated = (data['updated'] ?? 0) as int;
|
||||
slot.total = (data['total'] ?? slot.imported + slot.skipped + slot.updated) as int;
|
||||
slot.isProcessing = false;
|
||||
});
|
||||
} on DioException catch (e) {
|
||||
processingTimer?.cancel();
|
||||
final raw = e.response?.data;
|
||||
final msg = (raw is Map ? raw['error'] : null) ?? e.message ?? '未知错误';
|
||||
if (mounted) setState(() {
|
||||
slot.success = false;
|
||||
slot.error = msg.toString();
|
||||
slot.isProcessing = false;
|
||||
});
|
||||
} catch (e) {
|
||||
processingTimer?.cancel();
|
||||
if (mounted) setState(() {
|
||||
slot.success = false;
|
||||
slot.error = e.toString();
|
||||
slot.isProcessing = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2017,10 +2070,11 @@ class _BatchImportWidgetState extends ConsumerState<_BatchImportWidget> {
|
||||
Widget? statusWidget;
|
||||
if (slot.hasResult) {
|
||||
if (slot.success == true) {
|
||||
final duplicate = slot.skipped + slot.updated;
|
||||
final parts = <String>[
|
||||
'共 ${slot.total} 条',
|
||||
'新增 ${slot.imported} 条',
|
||||
if (slot.skipped > 0) '重复跳过 ${slot.skipped} 条',
|
||||
if (duplicate > 0) '重复 $duplicate 条',
|
||||
];
|
||||
statusWidget = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -2047,10 +2101,42 @@ class _BatchImportWidgetState extends ConsumerState<_BatchImportWidget> {
|
||||
);
|
||||
}
|
||||
} else if (_loading && slot.file != null) {
|
||||
statusWidget = const SizedBox(
|
||||
width: 14, height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
);
|
||||
if (slot.isProcessing) {
|
||||
statusWidget = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 12, height: 12,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: AppTheme.primary),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'导入数据${slot.processingSeconds > 0 ? "(${slot.processingSeconds}秒)" : ""}',
|
||||
style: const TextStyle(fontSize: 13, color: AppTheme.textSecondary),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
statusWidget = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 80,
|
||||
child: LinearProgressIndicator(
|
||||
value: slot.uploadPercent / 100,
|
||||
backgroundColor: Colors.grey[200],
|
||||
valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primary),
|
||||
minHeight: 6,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'上传 ${slot.uploadPercent}%',
|
||||
style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Padding(
|
||||
@@ -2104,6 +2190,54 @@ class _BatchImportWidgetState extends ConsumerState<_BatchImportWidget> {
|
||||
}
|
||||
}
|
||||
|
||||
// ── 门店 Logo 预览 ────────────────────────────────────────
|
||||
class _ShopLogoPreview extends StatelessWidget {
|
||||
final String logoUrl;
|
||||
final String shopName;
|
||||
final double size;
|
||||
const _ShopLogoPreview({required this.logoUrl, required this.shopName, this.size = 64});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final radius = BorderRadius.circular(size * 0.19);
|
||||
if (logoUrl.isNotEmpty) {
|
||||
final fullUrl = logoUrl.startsWith('http') ? logoUrl : '${AppConfig.apiBaseUrl.replaceAll('/api/v1', '')}$logoUrl';
|
||||
return ClipRRect(
|
||||
borderRadius: radius,
|
||||
child: Image.network(
|
||||
fullUrl,
|
||||
width: size,
|
||||
height: size,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => _initial(radius),
|
||||
),
|
||||
);
|
||||
}
|
||||
return _initial(radius);
|
||||
}
|
||||
|
||||
Widget _initial(BorderRadius radius) {
|
||||
final initial = shopName.isNotEmpty ? shopName.characters.first : '店';
|
||||
return Container(
|
||||
width: size,
|
||||
height: size,
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF0F3057),
|
||||
borderRadius: radius,
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
initial,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: size * 0.5,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 酒行信息行 ────────────────────────────────────────────
|
||||
class _ShopInfoRow extends StatelessWidget {
|
||||
final String label;
|
||||
@@ -2149,6 +2283,7 @@ class _ShopEditDialogState extends ConsumerState<_ShopEditDialog> {
|
||||
late final TextEditingController _phoneCtrl;
|
||||
late final TextEditingController _managerCtrl;
|
||||
bool _saving = false;
|
||||
bool _uploadingLogo = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -2168,6 +2303,37 @@ class _ShopEditDialogState extends ConsumerState<_ShopEditDialog> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _uploadLogo() async {
|
||||
final result = await FilePicker.platform.pickFiles(
|
||||
type: FileType.custom,
|
||||
allowedExtensions: ['jpg', 'jpeg', 'png'],
|
||||
withData: true,
|
||||
);
|
||||
if (result == null || result.files.isEmpty) return;
|
||||
final file = result.files.first;
|
||||
if (file.bytes == null) return;
|
||||
setState(() => _uploadingLogo = true);
|
||||
try {
|
||||
await ref.read(shopRepositoryProvider).uploadLogo(file.bytes!, file.name);
|
||||
ref.invalidate(shopInfoProvider);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
|
||||
content: Text('Logo 已更新'),
|
||||
backgroundColor: AppTheme.success,
|
||||
));
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('上传失败:$e'),
|
||||
backgroundColor: AppTheme.danger,
|
||||
));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _uploadingLogo = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
setState(() => _saving = true);
|
||||
try {
|
||||
@@ -2206,6 +2372,25 @@ class _ShopEditDialogState extends ConsumerState<_ShopEditDialog> {
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Logo 上传行
|
||||
Row(
|
||||
children: [
|
||||
_ShopLogoPreview(
|
||||
logoUrl: ref.watch(shopInfoProvider).valueOrNull?.logoUrl ?? widget.shop.logoUrl,
|
||||
shopName: _nameCtrl.text,
|
||||
size: 56,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _uploadingLogo ? null : _uploadLogo,
|
||||
icon: _uploadingLogo
|
||||
? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.upload_outlined, size: 16),
|
||||
label: const Text('更换 Logo'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _nameCtrl,
|
||||
decoration: const InputDecoration(labelText: '门店名称'),
|
||||
|
||||
@@ -5,8 +5,10 @@ import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'dart:async';
|
||||
import '../../core/auth/auth_state.dart';
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../../providers/connectivity_provider.dart';
|
||||
import '../../providers/shop_provider.dart';
|
||||
import '../../providers/update_provider.dart';
|
||||
|
||||
class AppShell extends ConsumerStatefulWidget {
|
||||
@@ -575,27 +577,31 @@ void _showShopPanel(BuildContext context, AuthUser u, {String version = 'v1.0.0'
|
||||
);
|
||||
}
|
||||
|
||||
class _ShopButton extends StatelessWidget {
|
||||
class _ShopButton extends ConsumerWidget {
|
||||
final AuthUser? user;
|
||||
final String version;
|
||||
const _ShopButton({this.user, this.version = 'v1.0.0'});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final shopAsync = ref.watch(shopInfoProvider);
|
||||
final shopName = shopAsync.valueOrNull?.name ?? user?.shopNo ?? '';
|
||||
final logoUrl = shopAsync.valueOrNull?.logoUrl ?? '';
|
||||
|
||||
return MouseRegion(
|
||||
cursor: SystemMouseCursors.click,
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
if (user != null) _showShopPanel(context, user!, version: version);
|
||||
},
|
||||
child: const Row(
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_YanmeiMark(size: 28),
|
||||
SizedBox(width: 10),
|
||||
_ShopLogo(logoUrl: logoUrl, shopName: shopName, size: 28),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
'岩美',
|
||||
style: TextStyle(
|
||||
shopName.isEmpty ? '—' : shopName,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w600,
|
||||
@@ -608,70 +614,54 @@ class _ShopButton extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// Brand mark widget — approximates the 岩美 logo SVG without flutter_svg.
|
||||
/// Dark blue rounded rect, white mountain/wave strokes, bordeaux dot.
|
||||
class _YanmeiMark extends StatelessWidget {
|
||||
/// 门店 Logo:有图片显示网络图片,无图片显示店名首字文字头像。
|
||||
class _ShopLogo extends StatelessWidget {
|
||||
final String logoUrl;
|
||||
final String shopName;
|
||||
final double size;
|
||||
const _YanmeiMark({this.size = 32});
|
||||
const _ShopLogo({required this.logoUrl, required this.shopName, this.size = 32});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final radius = BorderRadius.circular(size * 0.19);
|
||||
if (logoUrl.isNotEmpty) {
|
||||
final fullUrl = logoUrl.startsWith('http') ? logoUrl : '${AppConfig.apiBaseUrl.replaceAll('/api/v1', '')}$logoUrl';
|
||||
return ClipRRect(
|
||||
borderRadius: radius,
|
||||
child: Image.network(
|
||||
fullUrl,
|
||||
width: size,
|
||||
height: size,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => _initial(radius),
|
||||
),
|
||||
);
|
||||
}
|
||||
return _initial(radius);
|
||||
}
|
||||
|
||||
Widget _initial(BorderRadius radius) {
|
||||
final initial = shopName.isNotEmpty ? shopName.characters.first : '店';
|
||||
return Container(
|
||||
width: size,
|
||||
height: size,
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF0F3057),
|
||||
borderRadius: BorderRadius.circular(size * 0.19),
|
||||
borderRadius: radius,
|
||||
),
|
||||
child: CustomPaint(
|
||||
painter: _YanmeiMarkPainter(),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
initial,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: size * 0.5,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _YanmeiMarkPainter extends CustomPainter {
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final w = size.width;
|
||||
final h = size.height;
|
||||
final paint = Paint()
|
||||
..color = Colors.white
|
||||
..strokeWidth = w * 0.055
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeCap = StrokeCap.round
|
||||
..strokeJoin = StrokeJoin.round;
|
||||
|
||||
// Mountain/wave path: M14 38 L22 22 L32 32 L42 22 L50 38 (on 64px grid)
|
||||
final path = Path();
|
||||
path.moveTo(w * 0.219, h * 0.594);
|
||||
path.lineTo(w * 0.344, h * 0.344);
|
||||
path.lineTo(w * 0.500, h * 0.500);
|
||||
path.lineTo(w * 0.656, h * 0.344);
|
||||
path.lineTo(w * 0.781, h * 0.594);
|
||||
canvas.drawPath(path, paint);
|
||||
|
||||
// Horizontal baseline: M12 46 L52 46 (on 64px grid)
|
||||
canvas.drawLine(
|
||||
Offset(w * 0.1875, h * 0.719),
|
||||
Offset(w * 0.8125, h * 0.719),
|
||||
paint,
|
||||
);
|
||||
|
||||
// Bordeaux dot: circle cx=32 cy=52 r=2.4 (on 64px grid)
|
||||
canvas.drawCircle(
|
||||
Offset(w * 0.500, h * 0.859),
|
||||
w * 0.042,
|
||||
Paint()
|
||||
..color = const Color(0xFFC97B86)
|
||||
..style = PaintingStyle.fill,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
|
||||
}
|
||||
|
||||
class _InfoRow extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
|
||||
@@ -7,6 +7,8 @@ server {
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 20m;
|
||||
|
||||
# 商品图片静态文件
|
||||
location ^~ /images/ {
|
||||
alias /opt/jiu/images/;
|
||||
@@ -14,6 +16,14 @@ server {
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# 文件导入接口(超时更长)
|
||||
location ~ ^/api/v1/import/ {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
# API 反向代理
|
||||
location ~ ^/(api|health|version) {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
|
||||
Reference in New Issue
Block a user