Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff4a2db7cc | |||
| 21aa2523b7 | |||
| f395920a8c | |||
| 3625240839 | |||
| 7969bb41e3 | |||
| a20645671b | |||
| 6570dfc240 | |||
| 078fab30f0 | |||
| 08f9e20010 |
@@ -5,6 +5,25 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [1.0.76] - 2026-06-23
|
||||
|
||||
### 新功能
|
||||
- 商品详情页:双击商品图片即可全屏查看,支持双指缩放、左右翻页
|
||||
- 入库单详情新增「确认进价」:先以 0 价(待定)入库的调货单据,价格确定后可补填真实进价,系统自动回填库存成本、已出库成本与对供应商的应付,售价/应收不受影响;库存与入库明细中未定价的商品显示「待定价」
|
||||
|
||||
## [1.0.75] - 2026-06-22
|
||||
|
||||
### 新功能
|
||||
- 出库单列表新增「商品编码」搜索框:输入完整商品编码回车,即可精确查出包含该商品的所有出库单(与原「单号/往来单位」搜索互不影响)
|
||||
|
||||
### 变更
|
||||
- 移除「系统设置 → 数据管理」里的数据导入入口:数据导入不再对用户开放
|
||||
|
||||
## [1.0.74] - 2026-06-22
|
||||
|
||||
### 改进
|
||||
- 入库单 / 出库单详情页的商品明细表新增「生产日期」「批次号」两列,便于核对货品批次信息
|
||||
|
||||
## [1.0.73] - 2026-06-22
|
||||
|
||||
### 改进
|
||||
|
||||
@@ -5,6 +5,16 @@
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [1.0.77] - 2026-06-22
|
||||
|
||||
### 新功能
|
||||
- 出库单列表支持按「商品编码」精确反查:可查出包含某个商品编码的所有出库单。同时为出库明细新增 (门店, 商品编码) 复合索引,在数万条明细下仍保持毫秒级查询,不影响写入。
|
||||
|
||||
## [1.0.76] - 2026-06-22
|
||||
|
||||
### 修复
|
||||
- 修复「编辑入库单草稿后合计金额变成 0」的问题:此前每次编辑草稿会把单据合计金额错误清零(明细的单价/金额正常,仅单据头合计未重算),现已按明细正确重算。
|
||||
|
||||
## [1.0.75] - 2026-06-22
|
||||
|
||||
### 新功能
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/wangjia/jiu/backend/internal/model"
|
||||
"github.com/wangjia/jiu/backend/testutil"
|
||||
)
|
||||
|
||||
// 调货核心场景:0 价入库 → 审核 → 部分出库 → 确认进价(前向补偿)。
|
||||
func TestConfirmCost_BackfillsCostAndAdjustsPayable(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_MAIN")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "茅台")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
// 0 价入库 10 → 审核
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 10.0, "unit_price": 0.0}},
|
||||
})
|
||||
require.Equal(t, http.StatusCreated, w.Code)
|
||||
inID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/submit", inID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/approve", inID), adminToken, nil)
|
||||
|
||||
var inItem model.StockInItem
|
||||
require.NoError(t, db.Where("order_id = ?", inID).First(&inItem).Error)
|
||||
pid := inItem.ProductID // 序列号模型:入库为该行新建独立 product
|
||||
|
||||
// 库存批次成本待定(UnitPrice 为 NULL)
|
||||
var inv model.Inventory
|
||||
require.NoError(t, db.Where("shop_id = ? AND stock_in_item_id = ?", shop.ID, inItem.ID).First(&inv).Error)
|
||||
assert.Nil(t, inv.UnitPrice, "0 价入库时库存成本应为待定(NULL)")
|
||||
|
||||
// 出库 4(售价 80,成本暂为 0)→ 审核
|
||||
w = makeRequest(r, "POST", "/api/v1/stock-out/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": pid, "quantity": 4.0, "unit_price": 0.0, "sale_price": 80.0}},
|
||||
})
|
||||
outID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-out/orders/%d/submit", outID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-out/orders/%d/approve", outID), adminToken, nil)
|
||||
|
||||
// 确认进价 50
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 50.0}}})
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
// 1. 入库明细成本回填
|
||||
db.First(&inItem, inItem.ID)
|
||||
assert.Equal(t, 50.0, inItem.UnitPrice)
|
||||
assert.Equal(t, 500.0, inItem.TotalPrice)
|
||||
|
||||
// 2. 剩余库存批次成本回填(6 件)
|
||||
db.First(&inv, inv.ID)
|
||||
require.NotNil(t, inv.UnitPrice)
|
||||
assert.Equal(t, 50.0, *inv.UnitPrice)
|
||||
|
||||
// 3. 已出库行成本快照回填,售价/应收不变
|
||||
var outItem model.StockOutItem
|
||||
require.NoError(t, db.Where("order_id = ?", outID).First(&outItem).Error)
|
||||
assert.Equal(t, 50.0, outItem.UnitPrice, "已出库成本应回填")
|
||||
assert.Equal(t, 200.0, outItem.TotalPrice, "成本小计 = 50×4")
|
||||
assert.Equal(t, 80.0, outItem.SalePrice, "售价不应被改动")
|
||||
|
||||
var outOrder model.StockOutOrder
|
||||
db.First(&outOrder, outID)
|
||||
assert.Equal(t, 320.0, outOrder.TotalAmount, "应收按售价 4×80,确认进价不影响")
|
||||
|
||||
// 4. 入库单总额按差额重算:0 → 500
|
||||
var inOrder model.StockInOrder
|
||||
db.First(&inOrder, inID)
|
||||
assert.Equal(t, 500.0, inOrder.TotalAmount)
|
||||
|
||||
// 5. 应付差额调整流水:+500(balance 是应收应付混合滚动总账:0 入 + 320 应收 + 500 = 820)
|
||||
var adj model.FinanceRecord
|
||||
require.NoError(t, db.Where("shop_id = ? AND type = 'payable' AND ref_type = 'stock_in_cost_adjust'", shop.ID).
|
||||
First(&adj).Error)
|
||||
assert.Equal(t, 500.0, adj.Amount)
|
||||
assert.Equal(t, 820.0, adj.Balance)
|
||||
|
||||
// 6. product 参考进价同步(pid 是入库新建的独立 product)
|
||||
var p2 model.Product
|
||||
require.NoError(t, db.First(&p2, pid).Error)
|
||||
assert.Equal(t, 50.0, p2.PurchasePrice)
|
||||
}
|
||||
|
||||
// 非管理员无权确认进价。
|
||||
func TestConfirmCost_Forbidden(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_FORBID")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
op := testutil.CreateTestUser(db, shop.ID, "op", "pass", "operator")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "五粮液")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
opToken := getAuthToken(op.ID, shop.ID, "operator")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 5.0, "unit_price": 0.0}},
|
||||
})
|
||||
inID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/submit", inID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/approve", inID), adminToken, nil)
|
||||
var inItem model.StockInItem
|
||||
db.Where("order_id = ?", inID).First(&inItem)
|
||||
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), opToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 30.0}}})
|
||||
assert.Equal(t, http.StatusForbidden, w.Code)
|
||||
}
|
||||
|
||||
// 仅 approved 单可确认;草稿/待审核拒绝。
|
||||
func TestConfirmCost_RejectsNonApproved(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_DRAFT")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "汾酒")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 5.0, "unit_price": 0.0}},
|
||||
})
|
||||
inID := extractID(w)
|
||||
var inItem model.StockInItem
|
||||
db.Where("order_id = ?", inID).First(&inItem)
|
||||
|
||||
// 仍是 draft → 400
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 30.0}}})
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
// 重复确认:按新旧差额增量补偿,不重复全量。
|
||||
func TestConfirmCost_RepeatableByDiff(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_REPEAT")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "剑南春")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 10.0, "unit_price": 0.0}},
|
||||
})
|
||||
inID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/submit", inID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/approve", inID), adminToken, nil)
|
||||
var inItem model.StockInItem
|
||||
db.Where("order_id = ?", inID).First(&inItem)
|
||||
|
||||
// 第一次确认 50(diff 500)
|
||||
makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 50.0}}})
|
||||
// 第二次修正为 60(diff 100)
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 60.0}}})
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
db.First(&inItem, inItem.ID)
|
||||
assert.Equal(t, 60.0, inItem.UnitPrice)
|
||||
|
||||
var inOrder model.StockInOrder
|
||||
db.First(&inOrder, inID)
|
||||
assert.Equal(t, 600.0, inOrder.TotalAmount, "总额 = 60×10")
|
||||
|
||||
// 两条调整流水:+500 与 +100,余额滚动到 600
|
||||
var adjs []model.FinanceRecord
|
||||
db.Where("shop_id = ? AND ref_type = 'stock_in_cost_adjust'", shop.ID).Order("id ASC").Find(&adjs)
|
||||
require.Len(t, adjs, 2)
|
||||
assert.Equal(t, 500.0, adjs[0].Amount)
|
||||
assert.Equal(t, 100.0, adjs[1].Amount)
|
||||
assert.Equal(t, 600.0, adjs[1].Balance)
|
||||
}
|
||||
@@ -172,6 +172,7 @@ func (h *StockInHandler) Update(c *gin.Context) {
|
||||
it.ProductID = prod.ID
|
||||
it.ProductCode = prod.Code
|
||||
it.TotalPrice = it.Quantity * it.UnitPrice
|
||||
total += it.TotalPrice
|
||||
}
|
||||
updates := map[string]interface{}{
|
||||
"warehouse_id": req.WarehouseID,
|
||||
@@ -314,3 +315,41 @@ func (h *StockInHandler) Return(c *gin.Context) {
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "returned"})
|
||||
}
|
||||
|
||||
// ConfirmCost POST /api/v1/stock-in/orders/:id/confirm-cost
|
||||
// 确认进价:调货等以 0 价(暂估)入库并已审核后,价格确定时补填真实进价。
|
||||
// 前向补偿(更新库存成本、回填已出库成本快照、补应付差额),不反审核。
|
||||
// 仅 approved 单、管理员/超管(service 内判权)。
|
||||
func (h *StockInHandler) ConfirmCost(c *gin.Context) {
|
||||
shopID := middleware.GetShopID(c)
|
||||
userID := middleware.GetUserID(c)
|
||||
role := middleware.GetRole(c)
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
|
||||
var req struct {
|
||||
Items []service.CostConfirmItem `json:"items"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if len(req.Items) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "未提供要确认的明细"})
|
||||
return
|
||||
}
|
||||
for _, it := range req.Items {
|
||||
if it.UnitPrice <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "进价必须大于 0"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := h.stockSvc.ConfirmStockInCost(shopID, id, userID, role, req.Items); err != nil {
|
||||
if errors.Is(err, service.ErrForbidden) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "无权确认进价"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "cost confirmed"})
|
||||
}
|
||||
|
||||
@@ -272,6 +272,44 @@ func TestStockInHandler_TotalAmount(t *testing.T) {
|
||||
assert.Equal(t, float64(110), data["total_amount"])
|
||||
}
|
||||
|
||||
// 回归:编辑草稿入库单后 total_amount 必须按新明细重算(此前 Update 漏了累加,编辑后被清成 0)。
|
||||
func TestStockInHandler_UpdateRecomputesTotal(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "SI_UPD")
|
||||
user := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
warehouse := testutil.CreateTestWarehouse(db, shop.ID, "Warehouse")
|
||||
token := getAuthToken(user.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
// 建草稿:1 行 10×5 = 50
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", token, map[string]interface{}{
|
||||
"warehouse_id": warehouse.ID,
|
||||
"order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{
|
||||
{"product_name": "茅台", "series": "飞天", "spec": "500ml", "quantity": 10.0, "unit_price": 5.0},
|
||||
},
|
||||
})
|
||||
require.Equal(t, http.StatusCreated, w.Code)
|
||||
orderID := extractID(w)
|
||||
|
||||
// 编辑:改成 2 行 12×3100 + 1×4500 = 41700
|
||||
w = makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d", orderID), token, map[string]interface{}{
|
||||
"warehouse_id": warehouse.ID,
|
||||
"order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{
|
||||
{"product_name": "茅台2009", "series": "大件", "spec": "500ml", "quantity": 12.0, "unit_price": 3100.0},
|
||||
{"product_name": "茅台十五年", "series": "大件", "spec": "500ml", "quantity": 1.0, "unit_price": 4500.0},
|
||||
},
|
||||
})
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
// 取详情核对 total_amount 已重算(不是 0)
|
||||
w = makeRequest(r, "GET", fmt.Sprintf("/api/v1/stock-in/orders/%d", orderID), token, nil)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
data := parseResponse(w)["data"].(map[string]interface{})
|
||||
assert.Equal(t, float64(41700), data["total_amount"], "编辑后金额应按新明细重算")
|
||||
}
|
||||
|
||||
func TestStockInHandler_NoAuth(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
@@ -50,6 +50,13 @@ func (h *StockOutHandler) List(c *gin.Context) {
|
||||
like, shopID, like,
|
||||
)
|
||||
}
|
||||
// 按商品编码反查单据:精确匹配,走 idx_so_items_shop_code(shop_id, product_code) 索引
|
||||
if code := strings.TrimSpace(c.Query("product_code")); code != "" {
|
||||
query = query.Where(
|
||||
"id IN (SELECT order_id FROM stock_out_items WHERE shop_id = ? AND product_code = ? AND deleted_at IS NULL)",
|
||||
shopID, code,
|
||||
)
|
||||
}
|
||||
|
||||
var total int64
|
||||
query.Count(&total)
|
||||
|
||||
@@ -133,6 +133,40 @@ func TestStockOutHandler_List(t *testing.T) {
|
||||
assert.Equal(t, float64(2), resp["total"].(float64))
|
||||
}
|
||||
|
||||
// 按商品编码精确反查出库单(明细 product_code = ?)
|
||||
func TestStockOutHandler_List_FilterByProductCode(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "SO_CODE")
|
||||
user := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
warehouse := testutil.CreateTestWarehouse(db, shop.ID, "Warehouse")
|
||||
product := testutil.CreateTestProduct(db, shop.ID, "Beer")
|
||||
token := getAuthToken(user.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
makeRequest(r, "POST", "/api/v1/stock-out/orders", token, map[string]interface{}{
|
||||
"warehouse_id": warehouse.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{
|
||||
{"product_id": product.ID, "product_code": "ZXZ-FIND", "quantity": 1.0},
|
||||
},
|
||||
})
|
||||
makeRequest(r, "POST", "/api/v1/stock-out/orders", token, map[string]interface{}{
|
||||
"warehouse_id": warehouse.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{
|
||||
{"product_id": product.ID, "product_code": "OTHER-CODE", "quantity": 1.0},
|
||||
},
|
||||
})
|
||||
|
||||
// 精确命中 1 单
|
||||
w := makeRequest(r, "GET", "/api/v1/stock-out/orders?product_code=ZXZ-FIND", token, nil)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
|
||||
|
||||
// 不存在的编码 → 0;前缀不算精确(不命中)
|
||||
w = makeRequest(r, "GET", "/api/v1/stock-out/orders?product_code=ZXZ", token, nil)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Equal(t, float64(0), parseResponse(w)["total"].(float64))
|
||||
}
|
||||
|
||||
func TestStockOutHandler_List_FilterByKeyword(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "SO011")
|
||||
|
||||
@@ -60,17 +60,20 @@ func setupProtectedRouter(db *gorm.DB) *gin.Engine {
|
||||
stockIn.GET("/orders", stockInH.List)
|
||||
stockIn.GET("/orders/:id", stockInH.Get)
|
||||
stockIn.POST("/orders", stockInH.Create)
|
||||
stockIn.PUT("/orders/:id", stockInH.Update)
|
||||
stockIn.PUT("/orders/:id/submit", stockInH.Submit)
|
||||
stockIn.PUT("/orders/:id/approve", stockInH.Approve)
|
||||
stockIn.PUT("/orders/:id/reject", stockInH.Reject)
|
||||
stockIn.PUT("/orders/:id/withdraw", stockInH.Withdraw)
|
||||
stockIn.POST("/orders/:id/return", stockInH.Return)
|
||||
stockIn.POST("/orders/:id/confirm-cost", stockInH.ConfirmCost)
|
||||
|
||||
// 出库路由
|
||||
stockOut := api.Group("/stock-out")
|
||||
stockOut.GET("/orders", stockOutH.List)
|
||||
stockOut.GET("/orders/:id", stockOutH.Get)
|
||||
stockOut.POST("/orders", stockOutH.Create)
|
||||
stockOut.PUT("/orders/:id", stockOutH.Update)
|
||||
stockOut.PUT("/orders/:id/submit", stockOutH.Submit)
|
||||
stockOut.PUT("/orders/:id/approve", stockOutH.Approve)
|
||||
stockOut.PUT("/orders/:id/reject", stockOutH.Reject)
|
||||
|
||||
@@ -157,6 +157,8 @@ func Setup(r *gin.Engine, db *gorm.DB) {
|
||||
stockIn.PUT("/orders/:id/withdraw", stockInH.Withdraw)
|
||||
// 退单(已审核单退货,库存删除+冲应付):仅管理员/超管(service 内判权)
|
||||
stockIn.POST("/orders/:id/return", stockInH.Return)
|
||||
// 确认进价(暂估0价→真实价,前向补偿):仅管理员/超管(service 内判权)
|
||||
stockIn.POST("/orders/:id/confirm-cost", stockInH.ConfirmCost)
|
||||
}
|
||||
|
||||
// 出库
|
||||
|
||||
@@ -157,6 +157,111 @@ func (s *StockService) ApproveStockIn(shopID, orderID, reviewerID uint64) error
|
||||
})
|
||||
}
|
||||
|
||||
// CostConfirmItem 是「确认进价」的单行入参:把某入库明细的进价补成真实值。
|
||||
type CostConfirmItem struct {
|
||||
ItemID uint64 `json:"item_id"`
|
||||
UnitPrice float64 `json:"unit_price"`
|
||||
}
|
||||
|
||||
// ConfirmStockInCost 「确认进价」:调货等场景以 0 价(暂估)入库并已审核/已出库后,
|
||||
// 价格确定时补填真实进价。不反审核、不撤销任何已发生的动作,而是在一个事务内
|
||||
// 前向写补偿:
|
||||
// 1. 入库明细 UnitPrice / TotalPrice 改为真实值
|
||||
// 2. 该明细对应的剩余库存批次 Inventory.UnitPrice 由 NULL→真实值
|
||||
// 3. 该 product 已出库行 StockOutItem.UnitPrice/TotalPrice(成本快照)回填真实值
|
||||
// (product↔入库明细 1:1,按 product_id 精确命中;不动 SalePrice/应收)
|
||||
// 4. 入库单 TotalAmount 按差额重算
|
||||
// 5. 对供应商应付按差额补一条调整流水(滚动余额)
|
||||
//
|
||||
// 仅 approved 单可确认(draft 直接编辑即可);权限:管理员/超管。
|
||||
// 以「旧价→新价」差额计算补偿,支持多次修正(再次确认按新旧差额补)。
|
||||
func (s *StockService) ConfirmStockInCost(shopID, orderID, userID uint64, role string, items []CostConfirmItem) error {
|
||||
if role != "admin" && role != "superadmin" {
|
||||
return ErrForbidden
|
||||
}
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var order model.StockInOrder
|
||||
if err := tx.Preload("Items").Where("id = ? AND shop_id = ?", orderID, shopID).
|
||||
First(&order).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if order.Status != "approved" {
|
||||
return errors.New("只有已审核单据可确认进价")
|
||||
}
|
||||
|
||||
want := make(map[uint64]float64, len(items))
|
||||
for _, it := range items {
|
||||
want[it.ItemID] = it.UnitPrice
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var totalDiff float64
|
||||
|
||||
for i := range order.Items {
|
||||
it := &order.Items[i]
|
||||
newPrice, ok := want[it.ID]
|
||||
if !ok || newPrice == it.UnitPrice {
|
||||
continue
|
||||
}
|
||||
oldPrice := it.UnitPrice
|
||||
diff := (newPrice - oldPrice) * it.Quantity
|
||||
totalDiff += diff
|
||||
|
||||
// 1. 入库明细
|
||||
if err := tx.Model(it).Updates(map[string]interface{}{
|
||||
"unit_price": newPrice,
|
||||
"total_price": newPrice * it.Quantity,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. 该明细的剩余库存批次(已全部出库则无行,跳过)
|
||||
if err := tx.Model(&model.Inventory{}).
|
||||
Where("shop_id = ? AND stock_in_item_id = ? AND deleted_at IS NULL", shopID, it.ID).
|
||||
Update("unit_price", newPrice).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. 已出库行成本快照回填(按 product_id 精确命中;product_id=0 的历史导入单不传播)
|
||||
if it.ProductID != 0 {
|
||||
if err := tx.Model(&model.StockOutItem{}).
|
||||
Where("shop_id = ? AND product_id = ?", shopID, it.ProductID).
|
||||
Updates(map[string]interface{}{
|
||||
"unit_price": newPrice,
|
||||
"total_price": gorm.Expr("? * quantity", newPrice),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 同步 product 参考进价
|
||||
if it.ProductID != 0 {
|
||||
tx.Model(&model.Product{}).Where("id = ? AND shop_id = ?", it.ProductID, shopID).
|
||||
Update("purchase_price", newPrice)
|
||||
}
|
||||
}
|
||||
|
||||
if totalDiff == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 4. 入库单总额按差额重算
|
||||
if err := tx.Model(&order).
|
||||
Update("total_amount", gorm.Expr("total_amount + ?", totalDiff)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 5. 应付差额调整流水(滚动余额)
|
||||
bal := partnerLastBalance(tx, shopID, order.PartnerID) + totalDiff
|
||||
oid := order.ID
|
||||
return tx.Create(&model.FinanceRecord{
|
||||
ShopID: shopID, PartnerID: order.PartnerID, Type: "payable",
|
||||
Amount: totalDiff, Balance: bal, Status: "open",
|
||||
RefType: "stock_in_cost_adjust", RefID: &oid, OperatorID: userID, RecordDate: now,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
// ApproveStockOut 审核出库单,FIFO 扣减批次库存
|
||||
func (s *StockService) ApproveStockOut(shopID, orderID, reviewerID uint64) error {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
@@ -144,5 +144,12 @@ func autoMigrate(db *gorm.DB) {
|
||||
log.Fatalf("create unique index uk_shop_code failed: %v", err)
|
||||
}
|
||||
}
|
||||
// stock_out_items(shop_id, product_code) 复合索引:支撑出库列表「按商品编码反查单据」,
|
||||
// 避免在 2.6 万+ 明细行上全表扫。ShopID 在嵌入字段上无法用 struct tag 表达,故显式幂等建。
|
||||
if !db.Migrator().HasIndex(&model.StockOutItem{}, "idx_so_items_shop_code") {
|
||||
if err := db.Exec("CREATE INDEX idx_so_items_shop_code ON stock_out_items (shop_id, product_code)").Error; err != nil {
|
||||
log.Fatalf("create index idx_so_items_shop_code failed: %v", err)
|
||||
}
|
||||
}
|
||||
log.Println("AutoMigrate completed")
|
||||
}
|
||||
|
||||
@@ -369,7 +369,8 @@ CREATE TABLE IF NOT EXISTS `stock_out_items` (
|
||||
`remark` VARCHAR(255) DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_order_id` (`order_id`),
|
||||
KEY `idx_shop_product` (`shop_id`, `product_id`)
|
||||
KEY `idx_shop_product` (`shop_id`, `product_id`),
|
||||
KEY `idx_so_items_shop_code` (`shop_id`, `product_code`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='出库单明细';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
|
||||
@@ -12,6 +12,8 @@ class StockOutItem {
|
||||
final String? productSeries;
|
||||
final String? productSpec;
|
||||
final String? productUnit;
|
||||
final String? batchNo;
|
||||
final String? productionDate;
|
||||
|
||||
bool get isReturned => returnedQuantity >= quantity && quantity > 0;
|
||||
|
||||
@@ -29,6 +31,8 @@ class StockOutItem {
|
||||
this.productSeries,
|
||||
this.productSpec,
|
||||
this.productUnit,
|
||||
this.batchNo,
|
||||
this.productionDate,
|
||||
});
|
||||
|
||||
factory StockOutItem.fromJson(Map<String, dynamic> json) {
|
||||
@@ -57,6 +61,8 @@ class StockOutItem {
|
||||
productSeries: lineOrProduct('series', 'series'),
|
||||
productSpec: lineOrProduct('spec', 'spec'),
|
||||
productUnit: (json['product'] as Map<String, dynamic>?)?['unit'] as String?,
|
||||
batchNo: json['batch_no'] as String?,
|
||||
productionDate: json['production_date'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
|
||||
String? _startDate;
|
||||
String? _endDate;
|
||||
String _keyword = '';
|
||||
String _productCode = '';
|
||||
PageResult<StockOutOrder>? _cache;
|
||||
|
||||
@override
|
||||
@@ -46,6 +47,7 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
|
||||
startDate: _startDate,
|
||||
endDate: _endDate,
|
||||
keyword: _keyword.isEmpty ? null : _keyword,
|
||||
productCode: _productCode.isEmpty ? null : _productCode,
|
||||
page: _page,
|
||||
pageSize: _pageSize,
|
||||
);
|
||||
@@ -84,6 +86,13 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
|
||||
reload();
|
||||
}
|
||||
|
||||
/// 按商品编码精确反查(独立于 keyword)
|
||||
void setProductCode(String code) {
|
||||
_productCode = code;
|
||||
_page = 1;
|
||||
reload();
|
||||
}
|
||||
|
||||
void reload() {
|
||||
state = const AsyncValue.loading();
|
||||
_fetch().then((result) {
|
||||
|
||||
@@ -142,4 +142,17 @@ class StockInRepository {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 确认进价:把指定明细的暂估 0 价补成真实进价(前向补偿成本与应付)。
|
||||
/// items 形如 [{'item_id': 1, 'unit_price': 50.0}]。
|
||||
Future<void> confirmCost(int id, List<Map<String, dynamic>> items) async {
|
||||
try {
|
||||
await _client.post('/stock-in/orders/$id/confirm-cost', data: {'items': items});
|
||||
} on DioException catch (e) {
|
||||
throw AppException(
|
||||
e.response?.data?['error'] as String? ?? '确认进价失败',
|
||||
statusCode: e.response?.statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ class StockOutRepository {
|
||||
String? startDate,
|
||||
String? endDate,
|
||||
String? keyword,
|
||||
String? productCode,
|
||||
int page = 1,
|
||||
int pageSize = 20,
|
||||
}) async {
|
||||
@@ -25,6 +26,8 @@ class StockOutRepository {
|
||||
if (startDate != null) 'start_date': startDate,
|
||||
if (endDate != null) 'end_date': endDate,
|
||||
if (keyword != null && keyword.isNotEmpty) 'keyword': keyword,
|
||||
if (productCode != null && productCode.isNotEmpty)
|
||||
'product_code': productCode,
|
||||
};
|
||||
final resp = await _client.get('/stock-out/orders', params: params);
|
||||
return PageResult.fromJson(
|
||||
|
||||
@@ -312,7 +312,10 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
|
||||
style: const TextStyle(fontFamily: 'monospace', fontSize: 12))),
|
||||
'warehouse' => DataCell(Text(item.warehouseName.isEmpty ? '-' : item.warehouseName)),
|
||||
'price' => DataCell(Text(
|
||||
item.unitPrice != null ? '¥${item.unitPrice!.toStringAsFixed(2)}' : '-')),
|
||||
item.unitPrice != null ? '¥${item.unitPrice!.toStringAsFixed(2)}' : '待定价',
|
||||
style: item.unitPrice == null
|
||||
? const TextStyle(color: AppTheme.warning)
|
||||
: null)),
|
||||
'prodDate' => DataCell(Text(item.productionDate ?? '-')),
|
||||
'inTime' => DataCell(Text(
|
||||
item.createdAt != null && item.createdAt!.length >= 10
|
||||
@@ -358,8 +361,8 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
|
||||
if (item.series.isNotEmpty) MobileCardField('系列', item.series),
|
||||
if (item.batchNo.isNotEmpty) MobileCardField('批次', item.batchNo),
|
||||
MobileCardField('仓库', item.warehouseName.isEmpty ? '-' : item.warehouseName),
|
||||
if (item.unitPrice != null)
|
||||
MobileCardField('单价', '¥${item.unitPrice!.toStringAsFixed(2)}'),
|
||||
MobileCardField('单价',
|
||||
item.unitPrice != null ? '¥${item.unitPrice!.toStringAsFixed(2)}' : '待定价'),
|
||||
if (item.supplierName.isNotEmpty)
|
||||
MobileCardField('供应商', item.supplierName),
|
||||
],
|
||||
|
||||
@@ -9,6 +9,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../core/utils/print_util.dart';
|
||||
import '../../widgets/label_preview_dialog.dart';
|
||||
import '../../widgets/fullscreen_image_viewer.dart';
|
||||
import '../../widgets/write_guard.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../../models/product.dart';
|
||||
@@ -309,9 +310,16 @@ class _ProductDetailScreenState extends ConsumerState<ProductDetailScreen> {
|
||||
height: 120,
|
||||
child: Row(
|
||||
children: [
|
||||
...p.images.map((img) => _ImageThumbnail(
|
||||
url: AppConfig.baseUrl + img.url,
|
||||
onDelete: () => _deleteImage(img),
|
||||
...p.images.asMap().entries.map((e) => _ImageThumbnail(
|
||||
url: AppConfig.baseUrl + e.value.url,
|
||||
onDelete: () => _deleteImage(e.value),
|
||||
onView: () => showFullscreenImages(
|
||||
context,
|
||||
p.images
|
||||
.map((img) => AppConfig.baseUrl + img.url)
|
||||
.toList(),
|
||||
initialIndex: e.key,
|
||||
),
|
||||
)),
|
||||
if (p.images.length < 5)
|
||||
WriteGuard(
|
||||
@@ -567,7 +575,9 @@ class _ProductDetailScreenState extends ConsumerState<ProductDetailScreen> {
|
||||
class _ImageThumbnail extends StatelessWidget {
|
||||
final String url;
|
||||
final VoidCallback onDelete;
|
||||
const _ImageThumbnail({required this.url, required this.onDelete});
|
||||
final VoidCallback onView;
|
||||
const _ImageThumbnail(
|
||||
{required this.url, required this.onDelete, required this.onView});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -575,19 +585,22 @@ class _ImageThumbnail extends StatelessWidget {
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: Image.network(
|
||||
url,
|
||||
width: 110,
|
||||
height: 110,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => Container(
|
||||
GestureDetector(
|
||||
onDoubleTap: onView,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: Image.network(
|
||||
url,
|
||||
width: 110,
|
||||
height: 110,
|
||||
color: AppTheme.border,
|
||||
child: const Icon(Icons.broken_image,
|
||||
color: AppTheme.textSecondary),
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => Container(
|
||||
width: 110,
|
||||
height: 110,
|
||||
color: AppTheme.border,
|
||||
child: const Icon(Icons.broken_image,
|
||||
color: AppTheme.textSecondary),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../widgets/fullscreen_image_viewer.dart';
|
||||
|
||||
// ── Palette & typography constants ────────────────────────────────────
|
||||
const _kPaper = Color(0xFFFAF8F5);
|
||||
@@ -476,12 +477,7 @@ class _HeroGalleryState extends State<_HeroGallery> {
|
||||
}
|
||||
|
||||
void _openFullscreen(int index) {
|
||||
Navigator.of(context).push(PageRouteBuilder(
|
||||
opaque: false,
|
||||
barrierColor: Colors.black87,
|
||||
pageBuilder: (_, __, ___) => _FullscreenViewer(
|
||||
urls: widget.imageUrls, initialIndex: index),
|
||||
));
|
||||
showFullscreenImages(context, widget.imageUrls, initialIndex: index);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,66 +530,6 @@ class _GlassChip extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Full-screen image viewer ──────────────────────────────────────────
|
||||
|
||||
class _FullscreenViewer extends StatefulWidget {
|
||||
final List<String> urls;
|
||||
final int initialIndex;
|
||||
const _FullscreenViewer({required this.urls, required this.initialIndex});
|
||||
|
||||
@override
|
||||
State<_FullscreenViewer> createState() => _FullscreenViewerState();
|
||||
}
|
||||
|
||||
class _FullscreenViewerState extends State<_FullscreenViewer> {
|
||||
late PageController _ctrl;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_ctrl = PageController(initialPage: widget.initialIndex);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() { _ctrl.dispose(); super.dispose(); }
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: () => Navigator.of(context).pop(),
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
body: Stack(
|
||||
children: [
|
||||
PageView.builder(
|
||||
controller: _ctrl,
|
||||
itemCount: widget.urls.length,
|
||||
itemBuilder: (_, i) => Center(
|
||||
child: InteractiveViewer(
|
||||
child: Image.network(widget.urls[i], fit: BoxFit.contain,
|
||||
errorBuilder: (_, __, ___) =>
|
||||
const Icon(Icons.broken_image, size: 64, color: Colors.white54)),
|
||||
)),
|
||||
),
|
||||
Positioned(
|
||||
top: 40, right: 16,
|
||||
child: GestureDetector(
|
||||
onTap: () => Navigator.of(context).pop(),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black54, borderRadius: BorderRadius.circular(20)),
|
||||
child: const Icon(Icons.close, color: Colors.white, size: 20),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Verified Ribbon ───────────────────────────────────────────────────
|
||||
|
||||
class _VerifiedRibbon extends StatelessWidget {
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import 'dart:async';
|
||||
import '../../core/utils/dialog_util.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../core/auth/auth_state.dart';
|
||||
import '../../widgets/write_guard.dart';
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../core/config/app_constants.dart';
|
||||
import '../../core/config/app_info.dart';
|
||||
import '../../core/config/license_copy.dart';
|
||||
import '../../core/responsive/responsive.dart';
|
||||
@@ -46,8 +43,8 @@ class _SettingsScreenState extends ConsumerState<SettingsScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DefaultTabController(
|
||||
length: 6,
|
||||
initialIndex: widget.initialTab,
|
||||
length: 5,
|
||||
initialIndex: widget.initialTab >= 5 ? 0 : widget.initialTab,
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
@@ -66,7 +63,6 @@ class _SettingsScreenState extends ConsumerState<SettingsScreen> {
|
||||
Tab(text: '编号规则'),
|
||||
Tab(text: '系统参数'),
|
||||
Tab(text: '授权'),
|
||||
Tab(text: '数据管理'),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -79,7 +75,6 @@ class _SettingsScreenState extends ConsumerState<SettingsScreen> {
|
||||
_buildNumberRulesTab(),
|
||||
_buildSystemParamsTab(),
|
||||
_buildLicenseTab(),
|
||||
_buildImportTab(),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -823,31 +818,6 @@ class _SettingsScreenState extends ConsumerState<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// ── 数据导入 Tab ──────────────────────────────────────────
|
||||
Widget _buildImportTab() {
|
||||
if (WriteGuard.isReadonly(ref)) {
|
||||
return const Center(
|
||||
child: Text('只读账号无导入权限',
|
||||
style: TextStyle(color: AppTheme.textSecondary)),
|
||||
);
|
||||
}
|
||||
if (WriteGuard.licenseBlocked(ref)) {
|
||||
final lic = ref.watch(licenseProvider).valueOrNull;
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
lic == null ? '授权已过期,暂时无法导入' : LicenseCopy.writeBlockedToast(lic),
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppTheme.textSecondary),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final currentUser = ref.watch(authStateProvider).user;
|
||||
final isSuperAdmin = currentUser?.role == 'superadmin';
|
||||
return _BatchImportWidget(isSuperAdmin: isSuperAdmin);
|
||||
}
|
||||
|
||||
void _showEditParamDialog(
|
||||
String label, String current, ValueChanged<String> onSave) {
|
||||
@@ -1213,685 +1183,6 @@ class _ParamRow extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
// ── 批量数据导入 ───────────────────────────────────────────
|
||||
|
||||
class _ImportSlot {
|
||||
final String title;
|
||||
final String endpoint;
|
||||
final String hint;
|
||||
PlatformFile? file;
|
||||
// null = 未运行;true = 成功;false = 失败
|
||||
bool? success;
|
||||
String? error;
|
||||
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 {
|
||||
final bool isSuperAdmin;
|
||||
const _BatchImportWidget({required this.isSuperAdmin});
|
||||
|
||||
@override
|
||||
ConsumerState<_BatchImportWidget> createState() => _BatchImportWidgetState();
|
||||
}
|
||||
|
||||
class _BatchImportWidgetState extends ConsumerState<_BatchImportWidget> {
|
||||
bool _loading = false;
|
||||
String? _lastDir;
|
||||
OverlayEntry? _importBarrier;
|
||||
|
||||
static const _prefKey = 'import_last_dir';
|
||||
|
||||
late final List<_ImportSlot> _slots = [
|
||||
_ImportSlot('往来单位', '/import/partners',
|
||||
'格式:编号 | 类型 | 状态 | 名称 | 电话 | 卡号 | 初始金额 | 单位 | 地址 | 备注'),
|
||||
_ImportSlot('商品名称', '/import/product-names',
|
||||
'格式:选项编号 | 选项名称 | 备注'),
|
||||
_ImportSlot('商品系列', '/import/product-series',
|
||||
'格式:选项编号 | 选项名称 | 备注'),
|
||||
_ImportSlot('商品规格', '/import/product-specs',
|
||||
'格式:选项编号 | 选项名称 | 单品数量 | 备注'),
|
||||
_ImportSlot('库存', '/import/inventory',
|
||||
'格式:商品编号|商品名称|系列|规格|单位|库存数量|单价|金额|生产日期|批次|分类|所在仓库|入库日期|供应商|上次盘点|备注'),
|
||||
_ImportSlot('入库单', '/import/stock-in',
|
||||
'老系统入库单打印格式:每个文件一张单(含单据号/往来单位/日期/明细)'),
|
||||
_ImportSlot('出库单', '/import/stock-out',
|
||||
'老系统出库单打印格式:每个文件一张单(含单据号/往来单位/日期/明细)'),
|
||||
];
|
||||
|
||||
final Set<String> _selectedTables = {};
|
||||
bool _clearing = false;
|
||||
|
||||
static const _clearOptions = [
|
||||
(key: 'stock_in', label: '入库单'),
|
||||
(key: 'stock_out', label: '出库单'),
|
||||
(key: 'inventory', label: '库存管理'),
|
||||
(key: 'products', label: '商品详情'),
|
||||
(key: 'partners', label: '往来单位'),
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
SharedPreferences.getInstance().then((prefs) {
|
||||
final dir = prefs.getString(_prefKey);
|
||||
if (dir != null && mounted) setState(() => _lastDir = dir);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _pickFile(int index) async {
|
||||
try {
|
||||
final result = await FilePicker.platform.pickFiles(
|
||||
type: FileType.custom,
|
||||
allowedExtensions: ['xls', 'xlsx'],
|
||||
withData: true,
|
||||
initialDirectory: kIsWeb ? null : _lastDir,
|
||||
);
|
||||
if (result == null || result.files.isEmpty) return;
|
||||
|
||||
// 保存目录供下次使用(仅非 web 平台)
|
||||
if (!kIsWeb) {
|
||||
final path = result.files.first.path;
|
||||
if (path != null) {
|
||||
final dir = path.contains('/') ? path.substring(0, path.lastIndexOf('/')) : null;
|
||||
if (dir != null) {
|
||||
_lastDir = dir;
|
||||
SharedPreferences.getInstance().then((p) => p.setString(_prefKey, dir));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_slots[index].file = result.files.first;
|
||||
_slots[index].success = null;
|
||||
_slots[index].error = null;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('选择文件失败:$e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _showBarrier() {
|
||||
_importBarrier = OverlayEntry(
|
||||
builder: (_) => Stack(children: [
|
||||
const ModalBarrier(dismissible: false, color: Colors.transparent),
|
||||
Positioned(
|
||||
bottom: 24, left: 0, right: 0,
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black87,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
SizedBox(width: 14, height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)),
|
||||
SizedBox(width: 10),
|
||||
Text('导入中,请勿切换页面…',
|
||||
style: TextStyle(color: Colors.white, fontSize: 13)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
Overlay.of(context, rootOverlay: true).insert(_importBarrier!);
|
||||
}
|
||||
|
||||
void _removeBarrier() {
|
||||
_importBarrier?.remove();
|
||||
_importBarrier = null;
|
||||
}
|
||||
|
||||
Future<void> _runImport() async {
|
||||
final token = ref.read(authStateProvider).user?.accessToken ?? '';
|
||||
if (!_slots.any((s) => s.file != null)) return;
|
||||
|
||||
_showBarrier();
|
||||
setState(() {
|
||||
_loading = true;
|
||||
for (final s in _slots) {
|
||||
if (s.file != null) s.resetProgress();
|
||||
}
|
||||
});
|
||||
|
||||
final dio = Dio(BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
sendTimeout: AppConstants.importSendTimeout,
|
||||
receiveTimeout: AppConstants.importReceiveTimeout,
|
||||
));
|
||||
dio.options.headers['Authorization'] = 'Bearer $token';
|
||||
|
||||
for (final slot in _slots) {
|
||||
if (slot.file == null) continue;
|
||||
final bytes = slot.file!.bytes;
|
||||
if (bytes == null) {
|
||||
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,
|
||||
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;
|
||||
if (data.containsKey('order_no')) {
|
||||
// 单据类导入(入库单/出库单):每个文件一张单,
|
||||
// 已存在时后端返回 {skipped: true}(布尔),不能按 int 解析。
|
||||
final skippedOne = data['skipped'] == true;
|
||||
slot.imported = skippedOne ? 0 : 1;
|
||||
slot.skipped = skippedOne ? 1 : 0;
|
||||
slot.updated = 0;
|
||||
slot.total = 1;
|
||||
} else {
|
||||
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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
_removeBarrier();
|
||||
setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasAnyFile = _slots.any((s) => s.file != null);
|
||||
final ran = _slots.where((s) => s.file != null && s.hasResult).toList();
|
||||
final allDone = !_loading && ran.length == _slots.where((s) => s.file != null).length && ran.isNotEmpty;
|
||||
final failCount = ran.where((s) => s.success == false).length;
|
||||
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text('数据导入',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 4),
|
||||
const Text(
|
||||
'选择对应的 Excel 文件后点击「全部导入」,系统将依次导入,按名称去重(已存在的数据不重复导入)。',
|
||||
style: TextStyle(fontSize: 13, color: AppTheme.textSecondary),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||
child: Column(
|
||||
children: [
|
||||
for (int i = 0; i < _slots.length; i++) ...[
|
||||
_buildSlotRow(i),
|
||||
if (i < _slots.length - 1)
|
||||
const Divider(height: 1),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: (_loading || !hasAnyFile) ? null : _runImport,
|
||||
icon: _loading
|
||||
? const SizedBox(
|
||||
width: 14, height: 14,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2, color: Colors.white))
|
||||
: const Icon(Icons.upload_rounded, size: 16),
|
||||
label: Text(_loading ? '导入中...' : '全部导入'),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
if (allDone) ...[
|
||||
Icon(
|
||||
failCount == 0
|
||||
? Icons.check_circle_outline
|
||||
: Icons.warning_amber_rounded,
|
||||
size: 16,
|
||||
color: failCount == 0 ? AppTheme.success : Colors.orange,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
failCount == 0 ? '全部导入完成' : '$failCount 项失败,请检查错误信息',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: failCount == 0 ? AppTheme.success : Colors.orange,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
if (widget.isSuperAdmin) ...[
|
||||
const SizedBox(height: 32),
|
||||
const Divider(),
|
||||
const SizedBox(height: 16),
|
||||
_buildClearDataSection(),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildClearDataSection() {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 标题行
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.delete_forever, color: AppTheme.danger, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
const Text('危险操作 — 数据清空',
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppTheme.danger)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
// 红色警告框
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFF3F3),
|
||||
border: Border.all(color: AppTheme.danger.withOpacity(0.5)),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(children: [
|
||||
const Icon(Icons.warning_amber_rounded,
|
||||
color: AppTheme.danger, size: 18),
|
||||
const SizedBox(width: 6),
|
||||
const Text('警告:数据一旦清空,无法恢复!',
|
||||
style: TextStyle(
|
||||
color: AppTheme.danger,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 13)),
|
||||
]),
|
||||
const SizedBox(height: 6),
|
||||
const Text(
|
||||
'• 清空操作仅删除当前门店的数据,不影响其他门店\n'
|
||||
'• 操作不可撤销,请务必提前备份数据\n'
|
||||
'• 仅超级管理员可执行此操作',
|
||||
style: TextStyle(fontSize: 12, color: Color(0xFFB71C1C), height: 1.6),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
// 勾选框
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: _clearOptions.map((opt) {
|
||||
final selected = _selectedTables.contains(opt.key);
|
||||
return FilterChip(
|
||||
label: Text(opt.label),
|
||||
selected: selected,
|
||||
selectedColor: AppTheme.danger.withOpacity(0.15),
|
||||
checkmarkColor: AppTheme.danger,
|
||||
labelStyle: TextStyle(
|
||||
color: selected ? AppTheme.danger : AppTheme.textPrimary,
|
||||
fontWeight: selected ? FontWeight.w600 : FontWeight.normal,
|
||||
),
|
||||
side: BorderSide(
|
||||
color: selected ? AppTheme.danger : Colors.grey.shade300,
|
||||
),
|
||||
onSelected: _clearing
|
||||
? null
|
||||
: (v) => setState(() {
|
||||
if (v) {
|
||||
_selectedTables.add(opt.key);
|
||||
} else {
|
||||
_selectedTables.remove(opt.key);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
// 清空按钮
|
||||
ElevatedButton.icon(
|
||||
onPressed: (_clearing || _selectedTables.isEmpty)
|
||||
? null
|
||||
: () => _confirmClear(),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppTheme.danger,
|
||||
foregroundColor: Colors.white,
|
||||
disabledBackgroundColor: Colors.grey.shade300,
|
||||
),
|
||||
icon: _clearing
|
||||
? const SizedBox(
|
||||
width: 14, height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
|
||||
: const Icon(Icons.delete_sweep_outlined, size: 18),
|
||||
label: Text(_clearing ? '清空中...' : '清空选中数据'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _confirmClear() async {
|
||||
final tables = List<String>.from(_selectedTables);
|
||||
final labels = _clearOptions
|
||||
.where((o) => tables.contains(o.key))
|
||||
.map((o) => o.label)
|
||||
.toList();
|
||||
|
||||
final ctrl = TextEditingController();
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (ctx) => StatefulBuilder(
|
||||
builder: (ctx, setS) => AlertDialog(
|
||||
title: Row(children: [
|
||||
const Icon(Icons.warning_amber_rounded, color: Colors.red, size: 22),
|
||||
const SizedBox(width: 8),
|
||||
const Text('确认清空数据', style: TextStyle(color: Colors.red)),
|
||||
]),
|
||||
content: SizedBox(
|
||||
width: context.dialogWidth(400),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text('即将清空以下数据表:',
|
||||
style: TextStyle(fontWeight: FontWeight.w500)),
|
||||
const SizedBox(height: 8),
|
||||
...labels.map((l) => Padding(
|
||||
padding: const EdgeInsets.only(left: 12, bottom: 4),
|
||||
child: Row(children: [
|
||||
const Icon(Icons.remove_circle,
|
||||
color: Colors.red, size: 14),
|
||||
const SizedBox(width: 6),
|
||||
Text(l,
|
||||
style: const TextStyle(
|
||||
color: Colors.red, fontWeight: FontWeight.w600)),
|
||||
]),
|
||||
)),
|
||||
const SizedBox(height: 16),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFF3F3),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
border: Border.all(color: Colors.red.shade200),
|
||||
),
|
||||
child: const Text(
|
||||
'⚠️ 此操作不可撤销,数据清空后无法恢复!',
|
||||
style: TextStyle(
|
||||
color: Colors.red,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Text('请输入 "确认清空" 以继续:',
|
||||
style: TextStyle(fontSize: 13)),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: ctrl,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '确认清空',
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: (_) => setS(() {}),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: ctrl.text == '确认清空'
|
||||
? () => Navigator.of(ctx).pop(true)
|
||||
: null,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.red,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
child: const Text('确认清空'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
ctrl.dispose();
|
||||
if (confirmed != true || !mounted) return;
|
||||
|
||||
setState(() => _clearing = true);
|
||||
try {
|
||||
final token = ref.read(authStateProvider).user?.accessToken ?? '';
|
||||
final dio = Dio(BaseOptions(baseUrl: AppConfig.apiBaseUrl));
|
||||
dio.options.headers['Authorization'] = 'Bearer $token';
|
||||
await dio.post('/admin/clear-data', data: {'tables': tables});
|
||||
if (!mounted) return;
|
||||
setState(() => _selectedTables.clear());
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('已清空:${labels.join('、')}'),
|
||||
backgroundColor: AppTheme.success,
|
||||
),
|
||||
);
|
||||
} on DioException catch (e) {
|
||||
if (!mounted) return;
|
||||
final msg = (e.response?.data is Map ? e.response!.data['error'] : null) ??
|
||||
e.message ?? '未知错误';
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('清空失败:$msg'), backgroundColor: AppTheme.danger),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('清空失败:$e'), backgroundColor: AppTheme.danger),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _clearing = false);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildSlotRow(int index) {
|
||||
final slot = _slots[index];
|
||||
|
||||
Widget? statusWidget;
|
||||
if (slot.hasResult) {
|
||||
if (slot.success == true) {
|
||||
final duplicate = slot.skipped + slot.updated;
|
||||
final parts = <String>[
|
||||
'共 ${slot.total} 条',
|
||||
'新增 ${slot.imported} 条',
|
||||
if (duplicate > 0) '重复 $duplicate 条',
|
||||
];
|
||||
statusWidget = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.check_circle_outline, size: 15, color: AppTheme.success),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
parts.join(','),
|
||||
style: const TextStyle(fontSize: 13, color: AppTheme.success),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
statusWidget = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.error_outline, size: 15, color: AppTheme.danger),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
slot.error ?? '未知错误',
|
||||
style: const TextStyle(fontSize: 13, color: AppTheme.danger),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
} else if (_loading && slot.file != null) {
|
||||
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(
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 68,
|
||||
child: Text(slot.title,
|
||||
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
OutlinedButton(
|
||||
onPressed: _loading ? null : () => _pickFile(index),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
minimumSize: Size.zero,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
child: const Text('选择文件', style: TextStyle(fontSize: 13)),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
slot.file?.name ?? '未选择',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: slot.file != null ? AppTheme.textPrimary : AppTheme.textSecondary,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
if (statusWidget != null) statusWidget,
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 80),
|
||||
child: Text(
|
||||
slot.hint,
|
||||
style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 门店 Logo 预览 ────────────────────────────────────────
|
||||
class _ShopLogoPreview extends StatelessWidget {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import '../../core/utils/dialog_util.dart';
|
||||
import '../../core/errors/error_reporter.dart';
|
||||
import '../../core/exceptions.dart';
|
||||
import '../../core/utils/print_util.dart' show safePrint, printStockInOrder, LabelData;
|
||||
import '../../widgets/label_preview_dialog.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -897,7 +898,11 @@ class _StockInDetailDialogState extends ConsumerState<_StockInDetailDialog> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = widget.repository.get(widget.orderId).then((order) async {
|
||||
_future = _load();
|
||||
}
|
||||
|
||||
Future<StockInOrder> _load() {
|
||||
return widget.repository.get(widget.orderId).then((order) async {
|
||||
if (mounted) setState(() => _loadedOrder = order);
|
||||
try {
|
||||
final result = await ref
|
||||
@@ -915,6 +920,94 @@ class _StockInDetailDialogState extends ConsumerState<_StockInDetailDialog> {
|
||||
});
|
||||
}
|
||||
|
||||
/// 确认进价:为 0 价(待定)明细补填真实进价,调后端前向补偿后刷新。
|
||||
Future<void> _confirmCost(StockInOrder o) async {
|
||||
final pending =
|
||||
o.items.where((it) => it.unitPrice == 0 && it.id != null).toList();
|
||||
if (pending.isEmpty) return;
|
||||
final controllers = {
|
||||
for (final it in pending) it.id!: TextEditingController()
|
||||
};
|
||||
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('确认进价'),
|
||||
content: SizedBox(
|
||||
width: context.dialogWidth(440),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: pending.map((it) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'${it.productName ?? ''} ${it.productSpec ?? ''} ×${it.quantity.toStringAsFixed(0)}',
|
||||
style: const TextStyle(fontSize: 13),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
width: 120,
|
||||
child: TextField(
|
||||
controller: controllers[it.id],
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true),
|
||||
decoration: const InputDecoration(
|
||||
prefixText: '¥',
|
||||
hintText: '进价',
|
||||
isDense: true),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: const Text('取消')),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: const Text('确认')),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
final items = <Map<String, dynamic>>[];
|
||||
if (ok == true) {
|
||||
for (final it in pending) {
|
||||
final v = double.tryParse(controllers[it.id]!.text.trim());
|
||||
if (v != null && v > 0) {
|
||||
items.add({'item_id': it.id, 'unit_price': v});
|
||||
}
|
||||
}
|
||||
}
|
||||
for (final c in controllers.values) {
|
||||
c.dispose();
|
||||
}
|
||||
if (ok != true || items.isEmpty) return;
|
||||
|
||||
try {
|
||||
await widget.repository.confirmCost(o.id, items);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(const SnackBar(content: Text('进价已确认')));
|
||||
setState(() => _future = _load());
|
||||
ref.invalidate(stockInListProvider);
|
||||
} on AppException catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text('确认失败:${e.message}')));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Dialog(
|
||||
@@ -1034,10 +1127,10 @@ class _StockInDetailDialogState extends ConsumerState<_StockInDetailDialog> {
|
||||
MobileCardField('系列', item.productSeries!),
|
||||
MobileCardField('规格', item.productSpec ?? '-'),
|
||||
MobileCardField('数量', item.quantity.toStringAsFixed(3)),
|
||||
MobileCardField(
|
||||
'单价', '¥${item.unitPrice.toStringAsFixed(2)}'),
|
||||
MobileCardField(
|
||||
'金额', '¥${item.totalPrice.toStringAsFixed(2)}'),
|
||||
MobileCardField('单价',
|
||||
item.unitPrice == 0 ? '待定价' : '¥${item.unitPrice.toStringAsFixed(2)}'),
|
||||
MobileCardField('金额',
|
||||
item.totalPrice == 0 ? '待定' : '¥${item.totalPrice.toStringAsFixed(2)}'),
|
||||
if (item.batchNo?.isNotEmpty ?? false)
|
||||
MobileCardField('批次号', item.batchNo!),
|
||||
if (item.productionDate?.isNotEmpty ?? false)
|
||||
@@ -1064,16 +1157,18 @@ class _StockInDetailDialogState extends ConsumerState<_StockInDetailDialog> {
|
||||
0: FixedColumnWidth(36),
|
||||
1: FlexColumnWidth(1.2),
|
||||
2: FlexColumnWidth(2.2),
|
||||
3: FlexColumnWidth(1.5),
|
||||
4: FlexColumnWidth(1.5),
|
||||
5: FlexColumnWidth(1.2),
|
||||
6: FlexColumnWidth(1.2),
|
||||
7: FlexColumnWidth(1.2),
|
||||
3: FlexColumnWidth(1.3),
|
||||
4: FlexColumnWidth(1.3),
|
||||
5: FlexColumnWidth(1.3),
|
||||
6: FlexColumnWidth(1.3),
|
||||
7: FlexColumnWidth(1.0),
|
||||
8: FlexColumnWidth(1.1),
|
||||
9: FlexColumnWidth(1.1),
|
||||
},
|
||||
children: [
|
||||
TableRow(
|
||||
decoration: const BoxDecoration(color: Color(0xFFF0F4FF)),
|
||||
children: ['序号', '商品编码', '名称', '系列', '规格', '数量', '单价', '金额']
|
||||
children: ['序号', '商品编码', '名称', '系列', '规格', '生产日期', '批次号', '数量', '单价', '金额']
|
||||
.map((h) => Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8, vertical: 10),
|
||||
@@ -1122,14 +1217,38 @@ class _StockInDetailDialogState extends ConsumerState<_StockInDetailDialog> {
|
||||
),
|
||||
_TableCell(item.productSeries ?? '-'),
|
||||
_TableCell(item.productSpec ?? '-'),
|
||||
_TableCell((item.productionDate != null &&
|
||||
item.productionDate!.length >= 10)
|
||||
? item.productionDate!.substring(0, 10)
|
||||
: (item.productionDate ?? '-')),
|
||||
_TableCell(
|
||||
(item.batchNo?.isNotEmpty ?? false) ? item.batchNo! : '-'),
|
||||
_TableCell(item.quantity.toStringAsFixed(3)),
|
||||
_TableCell('¥${item.unitPrice.toStringAsFixed(2)}'),
|
||||
_TableCell('¥${item.totalPrice.toStringAsFixed(2)}'),
|
||||
_TableCell(item.unitPrice == 0 ? '待定价' : '¥${item.unitPrice.toStringAsFixed(2)}'),
|
||||
_TableCell(item.totalPrice == 0 ? '待定' : '¥${item.totalPrice.toStringAsFixed(2)}'),
|
||||
],
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
if (o.status == 'approved' &&
|
||||
ref.watch(isAdminProvider) &&
|
||||
o.items.any((it) => it.unitPrice == 0)) ...[
|
||||
const SizedBox(height: 16),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: () => _confirmCost(o),
|
||||
icon: const Icon(Icons.price_check, size: 18),
|
||||
label: const Text('确认进价'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
const Text(
|
||||
'该单含「待定价」明细:价格确定后补填真实进价,将自动回填库存成本、已出库成本快照与应付差额(不影响售价/应收)。',
|
||||
style: TextStyle(fontSize: 12, color: AppTheme.textSecondary),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -42,6 +42,7 @@ class _StockOutListScreenState extends ConsumerState<StockOutListScreen> {
|
||||
Set<String> _filterCustomer = {};
|
||||
Set<String>? _hiddenCols; // null = 尚未载入本地存档(回退到 minWidth 首次默认)
|
||||
final _searchCtrl = TextEditingController();
|
||||
final _codeSearchCtrl = TextEditingController();
|
||||
|
||||
static const _screenId = 'stock_out_list';
|
||||
|
||||
@@ -77,6 +78,7 @@ class _StockOutListScreenState extends ConsumerState<StockOutListScreen> {
|
||||
@override
|
||||
void dispose() {
|
||||
_searchCtrl.dispose();
|
||||
_codeSearchCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -84,6 +86,10 @@ class _StockOutListScreenState extends ConsumerState<StockOutListScreen> {
|
||||
.read(stockOutListProvider.notifier)
|
||||
.setKeyword(_searchCtrl.text.trim());
|
||||
|
||||
void _triggerCodeSearch() => ref
|
||||
.read(stockOutListProvider.notifier)
|
||||
.setProductCode(_codeSearchCtrl.text.trim());
|
||||
|
||||
String? get _startDate => _dateRange != null
|
||||
? '${_dateRange!.start.year}-${_dateRange!.start.month.toString().padLeft(2, '0')}-${_dateRange!.start.day.toString().padLeft(2, '0')}'
|
||||
: null;
|
||||
@@ -384,6 +390,22 @@ class _StockOutListScreenState extends ConsumerState<StockOutListScreen> {
|
||||
onSubmitted: (_) => _triggerSearch(),
|
||||
);
|
||||
|
||||
// 商品编码精确反查(独立搜索框)
|
||||
final codeSearchField = TextField(
|
||||
controller: _codeSearchCtrl,
|
||||
decoration: InputDecoration(
|
||||
hintText: '商品编码,回车精确查',
|
||||
prefixIcon: const Icon(Icons.qr_code, size: 16),
|
||||
hintStyle: const TextStyle(fontSize: 12),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.search, size: 16),
|
||||
tooltip: '按商品编码查',
|
||||
onPressed: _triggerCodeSearch,
|
||||
),
|
||||
),
|
||||
onSubmitted: (_) => _triggerCodeSearch(),
|
||||
);
|
||||
|
||||
final refreshBtn = IconButton(
|
||||
tooltip: '刷新',
|
||||
icon: const Icon(Icons.refresh, size: 20),
|
||||
@@ -417,6 +439,8 @@ class _StockOutListScreenState extends ConsumerState<StockOutListScreen> {
|
||||
children: [
|
||||
searchField,
|
||||
const SizedBox(height: 8),
|
||||
codeSearchField,
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
@@ -450,6 +474,8 @@ class _StockOutListScreenState extends ConsumerState<StockOutListScreen> {
|
||||
return Row(
|
||||
children: [
|
||||
SizedBox(width: 220, child: searchField),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(width: 180, child: codeSearchField),
|
||||
const SizedBox(width: 12),
|
||||
if (newBtn != null) newBtn,
|
||||
const Spacer(),
|
||||
@@ -1003,16 +1029,18 @@ class _StockOutDetailDialogState extends ConsumerState<_StockOutDetailDialog> {
|
||||
0: FixedColumnWidth(36),
|
||||
1: FlexColumnWidth(1.2),
|
||||
2: FlexColumnWidth(2.2),
|
||||
3: FlexColumnWidth(1.5),
|
||||
4: FlexColumnWidth(1.5),
|
||||
5: FlexColumnWidth(1.2),
|
||||
6: FlexColumnWidth(1.2),
|
||||
7: FlexColumnWidth(1.2),
|
||||
3: FlexColumnWidth(1.3),
|
||||
4: FlexColumnWidth(1.3),
|
||||
5: FlexColumnWidth(1.3),
|
||||
6: FlexColumnWidth(1.3),
|
||||
7: FlexColumnWidth(1.0),
|
||||
8: FlexColumnWidth(1.1),
|
||||
9: FlexColumnWidth(1.1),
|
||||
},
|
||||
children: [
|
||||
TableRow(
|
||||
decoration: const BoxDecoration(color: Color(0xFFF0F4FF)),
|
||||
children: ['序号', '商品编码', '名称', '系列', '规格', '数量', '单价', '金额']
|
||||
children: ['序号', '商品编码', '名称', '系列', '规格', '生产日期', '批次号', '数量', '单价', '金额']
|
||||
.map((h) => Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
|
||||
child: Text(h,
|
||||
@@ -1035,6 +1063,12 @@ class _StockOutDetailDialogState extends ConsumerState<_StockOutDetailDialog> {
|
||||
_TableCell(item.productName ?? '-'),
|
||||
_TableCell(item.productSeries ?? '-'),
|
||||
_TableCell(item.productSpec ?? '-'),
|
||||
_TableCell((item.productionDate != null &&
|
||||
item.productionDate!.length >= 10)
|
||||
? item.productionDate!.substring(0, 10)
|
||||
: (item.productionDate ?? '-')),
|
||||
_TableCell(
|
||||
(item.batchNo?.isNotEmpty ?? false) ? item.batchNo! : '-'),
|
||||
_TableCell(item.quantity.toStringAsFixed(3)),
|
||||
_TableCell('¥${item.unitPrice.toStringAsFixed(2)}'),
|
||||
_TableCell('¥${item.totalPrice.toStringAsFixed(2)}'),
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 全屏图片查看器:黑底 modal + 多图左右翻页(PageView)+ 双指缩放/拖拽(InteractiveViewer)。
|
||||
/// 点击背景或右上角关闭按钮退出。纯 Flutter 内置组件,无需额外依赖。
|
||||
///
|
||||
/// 用法:
|
||||
/// ```dart
|
||||
/// showFullscreenImages(context, urls, initialIndex: 2);
|
||||
/// ```
|
||||
void showFullscreenImages(BuildContext context, List<String> urls,
|
||||
{int initialIndex = 0}) {
|
||||
if (urls.isEmpty) return;
|
||||
Navigator.of(context).push(PageRouteBuilder(
|
||||
opaque: false,
|
||||
barrierColor: Colors.black87,
|
||||
pageBuilder: (_, __, ___) =>
|
||||
FullscreenImageViewer(urls: urls, initialIndex: initialIndex),
|
||||
));
|
||||
}
|
||||
|
||||
class FullscreenImageViewer extends StatefulWidget {
|
||||
final List<String> urls;
|
||||
final int initialIndex;
|
||||
const FullscreenImageViewer(
|
||||
{super.key, required this.urls, this.initialIndex = 0});
|
||||
|
||||
@override
|
||||
State<FullscreenImageViewer> createState() => _FullscreenImageViewerState();
|
||||
}
|
||||
|
||||
class _FullscreenImageViewerState extends State<FullscreenImageViewer> {
|
||||
late PageController _ctrl;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_ctrl = PageController(initialPage: widget.initialIndex);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ctrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: () => Navigator.of(context).pop(),
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
body: Stack(
|
||||
children: [
|
||||
PageView.builder(
|
||||
controller: _ctrl,
|
||||
itemCount: widget.urls.length,
|
||||
itemBuilder: (_, i) => Center(
|
||||
child: InteractiveViewer(
|
||||
child: Image.network(widget.urls[i], fit: BoxFit.contain,
|
||||
errorBuilder: (_, __, ___) => const Icon(
|
||||
Icons.broken_image,
|
||||
size: 64,
|
||||
color: Colors.white54)),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 40,
|
||||
right: 16,
|
||||
child: GestureDetector(
|
||||
onTap: () => Navigator.of(context).pop(),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black54,
|
||||
borderRadius: BorderRadius.circular(20)),
|
||||
child: const Icon(Icons.close, color: Colors.white, size: 20),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>暂估价 → 确认进价 设计 — 酒库管理系统</title>
|
||||
<style>
|
||||
:root{
|
||||
--primary:#2563AC; --primary-dark:#154072; --danger:#D14343; --danger-bg:#FDECEC;
|
||||
--success:#2E8B57; --warn:#B45309; --accent:#8B2331;
|
||||
--ink:#232934; --muted:#6E7888; --border:#DCE2EB; --paper:#F5F7FA; --head:#F0F4FF;
|
||||
}
|
||||
*{box-sizing:border-box;font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;}
|
||||
body{margin:0;background:var(--paper);color:var(--ink);padding:28px;line-height:1.65;}
|
||||
h1{font-size:20px;margin:0 0 4px;}
|
||||
h2{font-size:16px;margin:26px 0 8px;color:var(--primary-dark);border-left:4px solid var(--primary);padding-left:10px;}
|
||||
h3{font-size:14px;margin:18px 0 6px;color:var(--accent);}
|
||||
.sub{color:var(--muted);font-size:13px;margin-bottom:18px;}
|
||||
.card{background:#fff;border:1px solid var(--border);border-radius:10px;padding:16px 20px;max-width:920px;margin-bottom:16px;}
|
||||
p{font-size:14px;margin:6px 0;}
|
||||
code{font-family:ui-monospace,Menlo,monospace;font-size:12.5px;background:#EEF2F8;padding:1px 5px;border-radius:4px;color:var(--primary-dark);}
|
||||
ol,ul{font-size:14px;margin:6px 0;padding-left:22px;}
|
||||
li{margin:4px 0;}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px;max-width:920px;margin:8px 0;}
|
||||
th{background:var(--head);color:var(--primary-dark);font-weight:600;font-size:12px;text-align:left;padding:9px 10px;border:1px solid var(--border);}
|
||||
td{padding:9px 10px;border:1px solid #EEF1F5;vertical-align:top;}
|
||||
.tag{font-size:11px;padding:2px 8px;border-radius:10px;display:inline-block;}
|
||||
.tag.ok{background:#E6F3EC;color:var(--success);}
|
||||
.tag.warn{background:#FFF4E5;color:var(--warn);}
|
||||
.tag.no{background:var(--danger-bg);color:var(--danger);}
|
||||
.lead{font-size:14px;background:#F0F6FF;border-left:3px solid var(--primary);padding:10px 14px;border-radius:4px;max-width:920px;}
|
||||
.flow{font-family:ui-monospace,Menlo,monospace;font-size:13px;background:#1d2430;color:#e6edf6;padding:14px 18px;border-radius:8px;max-width:920px;overflow:auto;}
|
||||
.flow .c{color:#7fd1a0;}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>暂估价(0 价)→ 确认进价 · 设计方案</h1>
|
||||
<div class="sub">调货「先卖后定价」场景 · 分支 feature/jiu_20260623 · 2026-06-23</div>
|
||||
|
||||
<div class="lead">
|
||||
从朋友处调货,价格未定时以 <b>进价 0(暂估)</b> 入库并照常审核、出库售卖;价格确定后,对该入库单执行
|
||||
<b>「确认进价」</b>——系统<b>前向补偿</b>真实成本(不反审核、不撤销任何已发生的动作):回填库存成本、已出库成本快照,
|
||||
并按差额补一条应付流水。售价 / 应收完全不受影响。
|
||||
</div>
|
||||
|
||||
<h2>1. 背景与取舍</h2>
|
||||
<div class="card">
|
||||
<p>老系统做法是「入库价填 0 → 出库 → <b>反审核</b>入库单改价 → 重审」。新系统已审核单据只读、无反审核、流水不可变、库存成本一旦落地无修改接口——强行复刻反审核在「货已出库」时几乎无法回滚干净,且违反现有不可变设计。</p>
|
||||
<p>故改用会计上的「暂估入库 → 实际成本确认」模型:<b>不反审核</b>,以一次前向调整补齐成本与应付。关键前提是新系统的<b>序列号数据模型</b>让这件事变得精确——</p>
|
||||
<ul>
|
||||
<li><b>product ↔ 入库明细 1:1</b>:每行入库新建一个独立 product(序列号),出库明细也带 <code>product_id</code>。因此「某次调货的成本」就是「某个 product 的成本」,可凭 <code>product_id</code> 精确回填到它的所有已出库行,<b>无需额外的批次消耗映射表</b>。</li>
|
||||
<li><b>库存成本天然可空</b>:<code>inventories.unit_price</code> 为 <code>*float64</code>,0 价入库即存 <code>NULL</code>,<b>天然表示「待定价」</b>。</li>
|
||||
</ul>
|
||||
<p>用户确认的口径:①不填预估、直接填 0;②确认后补成本 + 补应付流水;③调货<b>不</b>单独建单据类型,复用普通入库单;④利润统计遇到无进价的行须跳过并单独说明。</p>
|
||||
<p><b>简化决策</b>:不新增 schema 字段(遵循「禁止为每个业务字段改表结构」)。约定 <b>成本待定 = 成本为 0 / <code>unit_price</code> 为 NULL</b>。调货白酒成本不会真为 0,歧义可忽略。</p>
|
||||
</div>
|
||||
|
||||
<h2>2. 核心动作:确认进价</h2>
|
||||
<div class="card">
|
||||
<p>接口:<code>POST /api/v1/stock-in/orders/:id/confirm-cost</code>,body <code>{"items":[{"item_id":N,"unit_price":50.0}]}</code>。
|
||||
仅 <b>approved</b> 单可确认(draft 直接编辑即可);权限 <b>管理员/超管</b>;后端实现 <code>StockService.ConfirmStockInCost</code>。</p>
|
||||
<p>一个事务内,对每个有变化的明细(旧价→新价,差额 <code>diff = (new-old)×qty</code>)前向写补偿:</p>
|
||||
<div class="flow">
|
||||
1. <span class="c">入库明细</span> StockInItem.unit_price / total_price 改为真实值
|
||||
2. <span class="c">剩余库存</span> Inventory.unit_price NULL → 真实值 (按 stock_in_item_id;已全出则无行)
|
||||
3. <span class="c">已出库行</span> StockOutItem.unit_price / total_price 回填 (按 product_id;不动 sale_price)
|
||||
4. <span class="c">入库单总额</span> StockInOrder.total_amount += Σ diff
|
||||
5. <span class="c">应付差额</span> 新增 FinanceRecord{type:payable, amount:Σdiff, ref_type:stock_in_cost_adjust}
|
||||
6. <span class="c">参考进价</span> Product.purchase_price 同步(按 product_id)
|
||||
</div>
|
||||
<p><b>幂等 / 可重复</b>:以「旧价→新价」差额计算,多次修正各补一条差额流水(如 0→50 补 +500,再 50→60 补 +100)。</p>
|
||||
<p><b>应付余额语义</b>:<code>balance</code> 是该往来单位「应收 + 应付」混合的滚动总账(沿用既有 <code>partnerLastBalance</code>),确认流水在此基础上累加差额。</p>
|
||||
</div>
|
||||
|
||||
<h2>3. 影响矩阵</h2>
|
||||
<table>
|
||||
<tr><th>数据</th><th>0 价入库审核后</th><th>确认进价后</th></tr>
|
||||
<tr><td>入库明细 unit_price</td><td>0</td><td><span class="tag ok">→ 真实价</span></td></tr>
|
||||
<tr><td>库存批次 unit_price</td><td>NULL(待定)</td><td><span class="tag ok">→ 真实价</span></td></tr>
|
||||
<tr><td>已出库行 unit_price(成本快照)</td><td>0</td><td><span class="tag ok">→ 真实价(按 product_id)</span></td></tr>
|
||||
<tr><td>出库 sale_price / 应收</td><td>正常</td><td><span class="tag ok">不变</span></td></tr>
|
||||
<tr><td>入库单 total_amount</td><td>0</td><td><span class="tag ok">→ Σ 真实小计</span></td></tr>
|
||||
<tr><td>对供应商应付</td><td>+0</td><td><span class="tag ok">补一条 +差额 流水</span></td></tr>
|
||||
</table>
|
||||
|
||||
<h2>4. 边界</h2>
|
||||
<div class="card">
|
||||
<ul>
|
||||
<li><b>未出库就确认</b>:只走第 1/2/4/5/6 步(无已出库行可回填)。</li>
|
||||
<li><b>部分出库</b>:剩余批次更新 + 已出行回填,各自按 <code>product_id</code> 命中。</li>
|
||||
<li><b>退货</b>(<code>returned_quantity</code>):按现有快照同样回填 <code>unit_price</code>,退货金额逻辑不变;如需特殊冲减再议。</li>
|
||||
<li><b>历史导入单</b>(共享占位 product,<code>product_id=0</code>):不向出库行/参考进价传播(避免误伤),仅改本单明细与库存。</li>
|
||||
<li><b>校验</b>:进价必须 > 0;非管理员 403;非 approved 单 400。</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>5. 前端</h2>
|
||||
<div class="card">
|
||||
<ul>
|
||||
<li><b>待定价标注</b>:库存列表、入库单明细单价/金额为 0/NULL 时显示「待定价」(橙色),而非 <code>-</code> 或 <code>¥0.00</code>。</li>
|
||||
<li><b>确认进价入口</b>:入库单详情弹窗中,单据为 <b>已审核</b> 且含待定行、且当前用户为管理员时,显示「确认进价」按钮 → 弹窗逐行填真实进价 → 调接口 → 刷新详情与列表。</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>6. 利润口径(前瞻约定)</h2>
|
||||
<div class="card">
|
||||
<p>系统当前<b>无</b>利润/毛利报表,本次<b>不</b>新建(YAGNI)。约定:<b>未来任何利润/毛利统计,须排除成本待定(<code>unit_price ≤ 0 / NULL</code>)的出库行,并单独列「N 笔成本待定,未计入利润」。</b> 本设计的「待定价」标识即为该口径提供可识别依据。</p>
|
||||
</div>
|
||||
|
||||
<h2>7. 关键文件</h2>
|
||||
<div class="card">
|
||||
<ul>
|
||||
<li>后端:<code>backend/internal/service/stock.go</code>(<code>ConfirmStockInCost</code> + <code>CostConfirmItem</code>)、<code>internal/handler/stock_in.go</code>(<code>ConfirmCost</code>)、<code>internal/router/router.go</code>、<code>internal/handler/stock_cost_confirm_test.go</code>(4 用例:回填+应付 / 403 / 非 approved / 重复确认)。</li>
|
||||
<li>前端:<code>client/lib/repositories/stock_in_repository.dart</code>(<code>confirmCost</code>)、<code>client/lib/screens/stock_in/stock_in_list_screen.dart</code>(确认进价弹窗 + 待定价)、<code>client/lib/screens/inventory/inventory_list_screen.dart</code>(待定价)。</li>
|
||||
</ul>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user