Compare commits

...

18 Commits

Author SHA1 Message Date
wangjia b260939563 chore: release server-v1.0.79
Deploy Server / release-deploy-server (push) Successful in 1m46s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-24 00:32:24 +08:00
wangjia 84f99ef459 test: 补酒名搜索拼音/多租户与前端搜索限流用例
- backend: 入库酒名全拼(feitian)+首字母(ftmt)命中、不相关拼音不命中
- backend: 入库酒名反查的多租户隔离(店A搜茅台不串到店B)
- client: setKeyword 防抖(350ms内连发取最后一次)+去重(同词不重查)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 00:19:34 +08:00
wangjia 102ace42ac feat(client): 入库/出库搜索框支持酒名,并对搜索限流
- 搜索框 hint 改为「单号/往来单位/酒名」
- setKeyword 加去重+350ms 防抖:同词不重查、连发回车/狂点合并取最后一次,
  避免酒名模糊查询(单次约 55ms 明细扫描)被刷
- Timer 在 provider dispose 时取消

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 00:19:34 +08:00
wangjia e8f416ddea feat(backend): 入库/出库列表 keyword 支持酒名模糊反查
- keyword 在单号/往来单位基础上,新增按酒名反查含该酒明细的单据
- 酒名匹配复用拼音基建:name(优先 product 回退快照) + name_pinyin + name_initials
- 子查询带 shop_id,多租户隔离不破
- 补 stock_in/stock_out List 按酒名+拼音命中的测试用例

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 00:19:34 +08:00
wangjia 08b41a8f63 feat(client): 入库单价允许留空/0(待定价),移除 >0 校验
- 删除新建入库商品明细单价的「不能为空 + >0」校验,留空或填 0 视为「待定价」
- 待定价明细经审核后在入库单详情「确认进价」补填真实进价
- 清理未使用的 productCode 局部变量与 _productCodeOf 辅助方法

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 00:19:34 +08:00
wangjia 2eb4275e6f chore(deploy): CI 双轨——发版同时部署 EC2 + 阿里(EC2→Ali 迁移期)
deploy-{server,site,client}.sh 目标主机参数化(DEPLOY_HOST/USER/SSH_KEY),
不传时行为与现状完全一致(只发 EC2)。workflow 的 Deploy 拆成 EC2(前)+
Ali(后,if:always + continue-on-error,影子目标失败不挡线上)。deploy-server
的 ali 分支只换二进制 + reload 独立 nginx(listen 443),不启动 jiu(阿里 DB
为只读从库,切流提升为主后才起)。新增 deploy/nginx-jiu-ali.conf 并打进
configs.tar.gz。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-23 22:57:41 +08:00
wangjia 9139192097 chore: release server-v1.0.78
Deploy Server / release-deploy-server (push) Successful in 6m36s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:12:34 +08:00
wangjia ff4a2db7cc chore: release client-v1.0.76
Deploy Client / build-client-web (push) Successful in 42s
Deploy Client / build-macos (push) Successful in 2m33s
Deploy Client / build-android (push) Successful in 1m37s
Deploy Client / build-ios (push) Successful in 2m51s
Deploy Client / build-windows (push) Successful in 2m22s
Deploy Client / release-deploy-client (push) Successful in 2m58s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:12:12 +08:00
wangjia 21aa2523b7 docs: 暂估价→确认进价 设计方案(HTML)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:07:50 +08:00
wangjia f395920a8c feat(client): 入库确认进价入口与「待定价」标注
入库单详情弹窗为已审核+含 0 价明细+管理员时显示「确认进价」,
逐行补填真实进价调后端;库存列表与入库明细 0 价/NULL 显示
「待定价」而非 ¥0.00。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:07:50 +08:00
wangjia 3625240839 feat(backend): 入库「确认进价」前向补偿(暂估价→真实价)
调货 0 价入库并已审核/出库后,价格确定时补填真实进价:一事务内
回填入库明细/库存批次/已出库成本快照,重算入库单总额,按差额补
应付流水,同步参考进价。按 product_id 精确命中(序列号 1:1),
不动售价/应收。仅 approved 单、管理员/超管,差额幂等可重复确认。

新增 POST /stock-in/orders/:id/confirm-cost 及 4 个测试用例。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:07:49 +08:00
wangjia 7969bb41e3 feat(client): 商品详情页图片支持双击全屏查看
抽出共享全屏查看器 fullscreen_image_viewer.dart(复用扫码页的
InteractiveViewer+PageView+黑底 modal),详情页缩略图双击打开,
扫码公开页改为复用同一组件去重。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:07:49 +08:00
wangjia a20645671b chore: release client-v1.0.75
Deploy Client / build-client-web (push) Successful in 41s
Deploy Client / build-macos (push) Successful in 5m37s
Deploy Client / build-android (push) Successful in 1m15s
Deploy Client / build-ios (push) Successful in 4m3s
Deploy Client / build-windows (push) Has been cancelled
Deploy Client / release-deploy-client (push) Has been cancelled
出库列表加商品编码精确搜索框 + 移除数据导入入口

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-22 22:25:22 +08:00
wangjia 6570dfc240 chore: release server-v1.0.77
Deploy Server / release-deploy-server (push) Successful in 1m32s
出库列表按商品编码精确反查 + stock_out_items(shop_id,product_code) 索引

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-22 22:24:43 +08:00
wangjia 078fab30f0 chore: release client-v1.0.74
Deploy Client / build-client-web (push) Successful in 39s
Deploy Client / build-macos (push) Successful in 2m23s
Deploy Client / build-android (push) Successful in 1m37s
Deploy Client / build-ios (push) Successful in 2m51s
Deploy Client / build-windows (push) Has been cancelled
Deploy Client / release-deploy-client (push) Has been cancelled
入库/出库详情页明细新增生产日期、批次号两列

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-22 20:16:19 +08:00
wangjia 08f9e20010 chore: release server-v1.0.76
Deploy Server / release-deploy-server (push) Successful in 1m30s
修复编辑入库单草稿后合计金额被清零(Update 漏累加 total)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-22 20:15:38 +08:00
wangjia 2fac1aff66 chore: release client-v1.0.73
Deploy Client / build-client-web (push) Successful in 40s
Deploy Client / build-windows (push) Successful in 2m7s
Deploy Client / build-macos (push) Successful in 2m11s
Deploy Client / build-android (push) Successful in 1m8s
Deploy Client / build-ios (push) Successful in 2m48s
Deploy Client / release-deploy-client (push) Successful in 1m26s
出库选货弹窗改为分页加载(默认20条+库存总数+翻页)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-22 14:26:23 +08:00
wangjia 6b0b2645ce chore: release client-v1.0.72
Deploy Client / build-client-web (push) Successful in 41s
Deploy Client / build-windows (push) Successful in 2m34s
Deploy Client / build-macos (push) Successful in 2m17s
Deploy Client / build-android (push) Successful in 1m26s
Deploy Client / build-ios (push) Successful in 2m42s
Deploy Client / release-deploy-client (push) Successful in 1m35s
出库售价可编辑列(应收按售价) + 退单按钮红色实心 + 库存列表隐藏数量列

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZ4DskSRKsSiheQonFtQvx
2026-06-22 13:02:29 +08:00
37 changed files with 1559 additions and 916 deletions
+14 -1
View File
@@ -180,7 +180,7 @@ jobs:
GITEA_REPOSITORY: ${{ gitea.repository }}
run: sh scripts/ci/release-client.sh "${{ gitea.ref_name }}"
- name: Deploy
- name: Deploy → EC2
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_URL: ${{ secrets.FORGEJO_URL }}
@@ -190,6 +190,19 @@ jobs:
EC2_USER: ${{ secrets.EC2_USER }}
run: sh scripts/ci/deploy-client.sh "${{ gitea.ref_name }}"
# 迁移期影子目标:同步 Flutter web + version.yaml + 安装包到阿里机。失败不挡 EC2。
- name: Deploy → Ali (migration shadow)
if: always()
continue-on-error: true
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_URL: ${{ secrets.FORGEJO_URL }}
GITEA_REPOSITORY: ${{ gitea.repository }}
DEPLOY_SSH_KEY: ${{ secrets.ALI_SSH_KEY }}
DEPLOY_HOST: ${{ secrets.ALI_HOST }}
DEPLOY_USER: ${{ secrets.ALI_USER }}
run: sh scripts/ci/deploy-client.sh "${{ gitea.ref_name }}"
- name: Notify
if: always()
env:
+17 -1
View File
@@ -36,16 +36,32 @@ jobs:
GITEA_REPOSITORY: ${{ gitea.repository }}
run: sh scripts/ci/release-server.sh "${{ gitea.ref_name }}"
- name: Deploy
- name: Deploy → EC2
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_URL: ${{ secrets.FORGEJO_URL }}
GITEA_REPOSITORY: ${{ gitea.repository }}
DEPLOY_TARGET: ec2
EC2_SSH_KEY: ${{ secrets.EC2_SSH_KEY }}
EC2_HOST: ${{ secrets.EC2_HOST }}
EC2_USER: ${{ secrets.EC2_USER }}
run: sh scripts/ci/deploy-server.sh "${{ gitea.ref_name }}"
# 迁移期影子目标:部署到阿里机(只换二进制 + reload 独立 nginxjiu 保持 stopped)。
# if: always() → EC2 失败也照样尝试;continue-on-error → 阿里失败不让流水线变红。
- name: Deploy → Ali (migration shadow)
if: always()
continue-on-error: true
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_URL: ${{ secrets.FORGEJO_URL }}
GITEA_REPOSITORY: ${{ gitea.repository }}
DEPLOY_TARGET: ali
DEPLOY_SSH_KEY: ${{ secrets.ALI_SSH_KEY }}
DEPLOY_HOST: ${{ secrets.ALI_HOST }}
DEPLOY_USER: ${{ secrets.ALI_USER }}
run: sh scripts/ci/deploy-server.sh "${{ gitea.ref_name }}"
- name: Notify
if: always()
env:
+14 -1
View File
@@ -32,7 +32,7 @@ jobs:
GITEA_REPOSITORY: ${{ gitea.repository }}
run: sh scripts/ci/release-site.sh "${{ gitea.ref_name }}"
- name: Deploy
- name: Deploy → EC2
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_URL: ${{ secrets.FORGEJO_URL }}
@@ -42,6 +42,19 @@ jobs:
EC2_USER: ${{ secrets.EC2_USER }}
run: sh scripts/ci/deploy-site.sh "${{ gitea.ref_name }}"
# 迁移期影子目标:同步官网到阿里机。失败不挡 EC2。
- name: Deploy → Ali (migration shadow)
if: always()
continue-on-error: true
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
FORGEJO_URL: ${{ secrets.FORGEJO_URL }}
GITEA_REPOSITORY: ${{ gitea.repository }}
DEPLOY_SSH_KEY: ${{ secrets.ALI_SSH_KEY }}
DEPLOY_HOST: ${{ secrets.ALI_HOST }}
DEPLOY_USER: ${{ secrets.ALI_USER }}
run: sh scripts/ci/deploy-site.sh "${{ gitea.ref_name }}"
- name: Notify
if: always()
env:
+34
View File
@@ -5,6 +5,40 @@ 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
### 改进
- 出库「添加商品」选货弹窗改为分页加载:默认显示前 20 条,底部显示库存总数并支持上一页/下一页翻页;弹窗打开即加载、按编码/名称/系列搜索时即时分页,避免一次拉取过多导致加载缓慢或看不到商品
## [1.0.72] - 2026-06-22
### 新功能
- 出库单录入新增「售价」可编辑列:可按实际销售价录入,金额与单据应收按「售价 × 数量」实时计算,同时保留成本价一栏便于对比
### 改进
- 「退单」按钮改为红色实心样式,更醒目地突出该危险操作(与原型一致)
- 库存列表隐藏「库存量」列:序列号模型下每件商品独立,原数量列易受历史数据误导,故不再展示(缺货/预警逻辑不受影响)
- 出库「添加商品」可一次看到整仓商品(需配合后端 v1.0.75)
## [1.0.71] - 2026-06-21
### 新功能
+20
View File
@@ -5,6 +5,26 @@
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.79] - 2026-06-24
### 改进
- 入库单 / 出库单列表的关键词搜索支持按「酒名(商品名)」模糊反查:除单号、往来单位外,输入商品名(含拼音/首字母)即可筛出含该商品的单据。
## [1.0.78] - 2026-06-23
### 新功能
- 入库单新增「确认进价」接口:以 0 价(暂估)入库并已审核/出库的调货单据,价格确定后可补填真实进价。系统在一个事务内前向补偿——回填库存批次成本与已出库明细的成本快照、按差额补一条对供应商的应付流水、重算入库单合计,售价与应收不受影响;仅管理员可操作,支持多次按差额修正。
## [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)
// 第一次确认 50diff 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}}})
// 第二次修正为 60diff 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)
}
+49 -2
View File
@@ -52,9 +52,17 @@ func (h *StockInHandler) List(c *gin.Context) {
}
if kw := strings.TrimSpace(c.Query("keyword")); kw != "" {
like := "%" + kw + "%"
// keyword 同时命中:单号 / 往来单位 / 酒名(含全拼+首字母,反查含该酒明细的单据)。
// 酒名优先取 product 主数据、回退快照列;拼音只在 products 上(快照无拼音列)。
query = query.Where(
"order_no LIKE ? OR partner_id IN (SELECT id FROM partners WHERE shop_id = ? AND name LIKE ?)",
like, shopID, like,
"order_no LIKE ?"+
" OR partner_id IN (SELECT id FROM partners WHERE shop_id = ? AND name LIKE ?)"+
" OR id IN (SELECT it.order_id FROM stock_in_items it"+
" LEFT JOIN products p ON p.id = it.product_id AND p.shop_id = it.shop_id"+
" WHERE it.shop_id = ? AND it.deleted_at IS NULL"+
" AND (COALESCE(NULLIF(p.name,''), it.product_name) LIKE ?"+
" OR p.name_pinyin LIKE ? OR p.name_initials LIKE ?))",
like, shopID, like, shopID, like, like, like,
)
}
@@ -172,6 +180,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 +323,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"})
}
+138
View File
@@ -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)
@@ -413,6 +451,106 @@ func TestStockInHandler_List_FilterByKeyword(t *testing.T) {
assert.Equal(t, float64(2), parseResponse(w)["total"].(float64))
}
func TestStockInHandler_List_FilterByProductName(t *testing.T) {
db := testutil.SetupTestDB()
shop := testutil.CreateTestShop(db, "SI012")
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:明细酒名「飞天茅台」(入库按 product_name 新建独立 product
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": "飞天茅台", "quantity": 5.0}},
})
require.Equal(t, http.StatusCreated, w.Code)
// 单据2:明细酒名「拉菲红酒」
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": "拉菲红酒", "quantity": 3.0}},
})
require.Equal(t, http.StatusCreated, w.Code)
// 按酒名模糊反查 → 各命中 1 单
w = makeRequest(r, "GET", "/api/v1/stock-in/orders?keyword=茅台", token, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
w = makeRequest(r, "GET", "/api/v1/stock-in/orders?keyword=红酒", token, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
// 无关键词 → 两单都在
w = makeRequest(r, "GET", "/api/v1/stock-in/orders", token, nil)
assert.Equal(t, float64(2), parseResponse(w)["total"].(float64))
}
func TestStockInHandler_List_FilterByProductPinyin(t *testing.T) {
db := testutil.SetupTestDB()
shop := testutil.CreateTestShop(db, "SI013")
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)
// 入库按 product_name 新建独立 product,会自动写入拼音列(name_pinyin/name_initials
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": "飞天茅台", "quantity": 5.0}},
})
require.Equal(t, http.StatusCreated, w.Code)
// 全拼命中(feitianmaotai
w = makeRequest(r, "GET", "/api/v1/stock-in/orders?keyword=feitian", token, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
// 首字母命中(ftmt
w = makeRequest(r, "GET", "/api/v1/stock-in/orders?keyword=ftmt", token, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
// 不相关拼音不命中
w = makeRequest(r, "GET", "/api/v1/stock-in/orders?keyword=wuliangye", token, nil)
assert.Equal(t, float64(0), parseResponse(w)["total"].(float64))
}
func TestStockInHandler_List_FilterByProductName_TenantIsolation(t *testing.T) {
db := testutil.SetupTestDB()
r := setupProtectedRouter(db)
// 店A、店B 各建一张含「茅台」明细的入库单
shopA := testutil.CreateTestShop(db, "SI014A")
userA := testutil.CreateTestUser(db, shopA.ID, "adminA", "pass", "admin")
whA := testutil.CreateTestWarehouse(db, shopA.ID, "WA")
tokenA := getAuthToken(userA.ID, shopA.ID, "admin")
shopB := testutil.CreateTestShop(db, "SI014B")
userB := testutil.CreateTestUser(db, shopB.ID, "adminB", "pass", "admin")
whB := testutil.CreateTestWarehouse(db, shopB.ID, "WB")
tokenB := getAuthToken(userB.ID, shopB.ID, "admin")
for _, tc := range []struct {
token string
wh uint64
}{{tokenA, whA.ID}, {tokenB, whB.ID}} {
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", tc.token, map[string]interface{}{
"warehouse_id": tc.wh,
"order_date": time.Now().Format(time.RFC3339),
"items": []map[string]interface{}{{"product_name": "飞天茅台", "quantity": 1.0}},
})
require.Equal(t, http.StatusCreated, w.Code)
}
// 店A 搜茅台只看到自己的 1 单,绝不串到店B
w := makeRequest(r, "GET", "/api/v1/stock-in/orders?keyword=茅台", tokenA, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
w = makeRequest(r, "GET", "/api/v1/stock-in/orders?keyword=茅台", tokenB, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
}
func TestStockInHandler_List_FilterByStatus(t *testing.T) {
db := testutil.SetupTestDB()
shop := testutil.CreateTestShop(db, "SI010")
+17 -2
View File
@@ -45,9 +45,24 @@ func (h *StockOutHandler) List(c *gin.Context) {
}
if kw := strings.TrimSpace(c.Query("keyword")); kw != "" {
like := "%" + kw + "%"
// keyword 同时命中:单号 / 往来单位 / 酒名(含全拼+首字母,反查含该酒明细的单据)。
// 酒名优先取 product 主数据、回退快照列;拼音只在 products 上(快照无拼音列)。
query = query.Where(
"order_no LIKE ? OR partner_id IN (SELECT id FROM partners WHERE shop_id = ? AND name LIKE ?)",
like, shopID, like,
"order_no LIKE ?"+
" OR partner_id IN (SELECT id FROM partners WHERE shop_id = ? AND name LIKE ?)"+
" OR id IN (SELECT it.order_id FROM stock_out_items it"+
" LEFT JOIN products p ON p.id = it.product_id AND p.shop_id = it.shop_id"+
" WHERE it.shop_id = ? AND it.deleted_at IS NULL"+
" AND (COALESCE(NULLIF(p.name,''), it.product_name) LIKE ?"+
" OR p.name_pinyin LIKE ? OR p.name_initials LIKE ?))",
like, shopID, like, shopID, like, like, 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,
)
}
@@ -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")
@@ -178,6 +212,42 @@ func TestStockOutHandler_List_FilterByKeyword(t *testing.T) {
assert.Equal(t, float64(2), parseResponse(w)["total"].(float64))
}
func TestStockOutHandler_List_FilterByProductName(t *testing.T) {
db := testutil.SetupTestDB()
shop := testutil.CreateTestShop(db, "SO012")
user := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
warehouse := testutil.CreateTestWarehouse(db, shop.ID, "Warehouse")
maotai := testutil.CreateTestProduct(db, shop.ID, "飞天茅台")
lafei := testutil.CreateTestProduct(db, shop.ID, "拉菲红酒")
token := getAuthToken(user.ID, shop.ID, "admin")
r := setupProtectedRouter(db)
w := 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": maotai.ID, "quantity": 1.0}},
})
require.Equal(t, http.StatusCreated, w.Code)
w = 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": lafei.ID, "quantity": 1.0}},
})
require.Equal(t, http.StatusCreated, w.Code)
// 按酒名模糊反查 → 各命中 1 单
w = makeRequest(r, "GET", "/api/v1/stock-out/orders?keyword=茅台", token, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
w = makeRequest(r, "GET", "/api/v1/stock-out/orders?keyword=红酒", token, nil)
assert.Equal(t, float64(1), parseResponse(w)["total"].(float64))
// 无关键词 → 两单都在
w = makeRequest(r, "GET", "/api/v1/stock-out/orders", token, nil)
assert.Equal(t, float64(2), parseResponse(w)["total"].(float64))
}
func TestStockOutHandler_Reject(t *testing.T) {
db := testutil.SetupTestDB()
shop := testutil.CreateTestShop(db, "SO004")
@@ -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)
+2
View File
@@ -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)
}
// 出库
+105
View File
@@ -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 {
+7
View File
@@ -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")
}
+2 -1
View File
@@ -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='出库单明细';
-- ------------------------------------------------------------
+9
View File
@@ -4,6 +4,7 @@ class StockOutItem {
final int productId;
final double quantity;
final double unitPrice;
final double salePrice;
final double totalPrice;
final double returnedQuantity;
final String? productName;
@@ -11,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;
@@ -20,6 +23,7 @@ class StockOutItem {
required this.productId,
required this.quantity,
required this.unitPrice,
this.salePrice = 0,
required this.totalPrice,
this.returnedQuantity = 0,
this.productName,
@@ -27,6 +31,8 @@ class StockOutItem {
this.productSeries,
this.productSpec,
this.productUnit,
this.batchNo,
this.productionDate,
});
factory StockOutItem.fromJson(Map<String, dynamic> json) {
@@ -47,6 +53,7 @@ class StockOutItem {
productId: (json['product_id'] as num).toInt(),
quantity: (json['quantity'] as num).toDouble(),
unitPrice: (json['unit_price'] as num).toDouble(),
salePrice: (json['sale_price'] as num?)?.toDouble() ?? 0,
totalPrice: (json['total_price'] as num).toDouble(),
returnedQuantity: (json['returned_quantity'] as num?)?.toDouble() ?? 0,
productName: lineOrProduct('product_name', 'name'),
@@ -54,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?,
);
}
}
+14 -3
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/api/api_client.dart';
import '../core/auth/auth_state.dart';
@@ -25,9 +27,11 @@ class StockInListNotifier extends AsyncNotifier<PageResult<StockInOrder>> {
String? _endDate;
String _keyword = '';
PageResult<StockInOrder>? _cache;
Timer? _searchDebounce;
@override
Future<PageResult<StockInOrder>> build() async {
ref.onDispose(() => _searchDebounce?.cancel());
ref.watch(authStateProvider.select((s) => s.user?.shopId));
ref.watch(networkRecoveryCountProvider);
try {
@@ -78,10 +82,17 @@ class StockInListNotifier extends AsyncNotifier<PageResult<StockInOrder>> {
reload();
}
/// 关键词搜索(含酒名模糊反查,单次约 55ms 的明细扫描)。
/// 去重 + 防抖限流:同词不重查;连发回车/狂点合并取最后一次,避免昂贵查询被刷。
void setKeyword(String keyword) {
_keyword = keyword;
_page = 1;
reload();
final kw = keyword.trim();
if (kw == _keyword) return;
_searchDebounce?.cancel();
_searchDebounce = Timer(const Duration(milliseconds: 350), () {
_keyword = kw;
_page = 1;
reload();
});
}
void reload() {
+21 -1
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/api/api_client.dart';
import '../core/auth/auth_state.dart';
@@ -24,10 +26,13 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
String? _startDate;
String? _endDate;
String _keyword = '';
String _productCode = '';
PageResult<StockOutOrder>? _cache;
Timer? _searchDebounce;
@override
Future<PageResult<StockOutOrder>> build() async {
ref.onDispose(() => _searchDebounce?.cancel());
ref.watch(authStateProvider.select((s) => s.user?.shopId));
ref.watch(networkRecoveryCountProvider);
try {
@@ -46,6 +51,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,
);
@@ -78,8 +84,22 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
reload();
}
/// 关键词搜索(含酒名模糊反查,单次约 55ms 的明细扫描)。
/// 去重 + 防抖限流:同词不重查;连发回车/狂点合并取最后一次,避免昂贵查询被刷。
void setKeyword(String keyword) {
_keyword = keyword;
final kw = keyword.trim();
if (kw == _keyword) return;
_searchDebounce?.cancel();
_searchDebounce = Timer(const Duration(milliseconds: 350), () {
_keyword = kw;
_page = 1;
reload();
});
}
/// 按商品编码精确反查(独立于 keyword)
void setProductCode(String code) {
_productCode = code;
_page = 1;
reload();
}
@@ -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(
@@ -51,7 +51,7 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
ColDef('series', '系列'),
ColDef('batch', '批次号'),
ColDef('warehouse', '仓库'),
ColDef('qty', '库存量'),
// 库存量列已移除:序列号模型下每件独立,原数量列含历史装箱数脏数据易误导
ColDef('price', '单价'),
ColDef('prodDate', '生产日期'),
ColDef('inTime', '入库时间'),
@@ -311,17 +311,11 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
'batch' => DataCell(Text(item.batchNo.isEmpty ? '-' : item.batchNo,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12))),
'warehouse' => DataCell(Text(item.warehouseName.isEmpty ? '-' : item.warehouseName)),
'qty' => DataCell(Text(
'${item.quantity.toStringAsFixed(0)} ${item.unit}'.trim(),
style: TextStyle(
fontWeight: FontWeight.w600,
color: item.quantity == 0
? AppTheme.danger
: (item.minStock != null && item.quantity < item.minStock!)
? AppTheme.accent
: AppTheme.textPrimary))),
'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
@@ -367,21 +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),
MobileCardField('库存', null,
valueWidget: Text(
'${item.quantity.toStringAsFixed(0)} ${item.unit}'.trim(),
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: item.quantity == 0
? AppTheme.danger
: (item.minStock != null && item.quantity < item.minStock!)
? AppTheme.accent
: AppTheme.textPrimary,
),
)),
if (item.unitPrice != null)
MobileCardField('单价', '¥${item.unitPrice!.toStringAsFixed(2)}'),
MobileCardField('单价',
item.unitPrice != null ? '¥${item.unitPrice!.toStringAsFixed(2)}' : '待定价'),
if (item.supplierName.isNotEmpty)
MobileCardField('供应商', item.supplierName),
],
@@ -763,7 +744,7 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
};
return DataColumn(
label: label,
numeric: c.key == 'qty' || c.key == 'price',
numeric: c.key == 'price',
);
}).toList(),
rows: items.isEmpty
@@ -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 {
@@ -868,11 +868,8 @@ class _StockInFormScreenState extends ConsumerState<StockInFormScreen> {
FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}'))
],
onChanged: (_) => setState(() {}),
validator: (v) {
if (v == null || v.isEmpty) return '不能为空';
if ((double.tryParse(v) ?? 0) <= 0) return '>0';
return null;
},
// 0
validator: (_) => null,
);
}
@@ -976,15 +973,6 @@ class _StockInFormScreenState extends ConsumerState<StockInFormScreen> {
);
}
String _productCodeOf(_ItemRow item) =>
ref
.read(productNameListProvider)
.valueOrNull
?.where((o) => o.id == item.selectedNameId)
.firstOrNull
?.code ??
'';
//
Widget _buildItemTableHeader() {
Widget th(String s) => Padding(
@@ -1019,7 +1007,6 @@ class _StockInFormScreenState extends ConsumerState<StockInFormScreen> {
final qty = double.tryParse(item.qtyCtrl.text) ?? 0;
final price = double.tryParse(item.priceCtrl.text) ?? 0;
final amount = qty * price;
final productCode = _productCodeOf(item);
Widget tc(String s, {Color? color, FontWeight? weight}) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
@@ -1166,7 +1153,6 @@ class _StockInFormScreenState extends ConsumerState<StockInFormScreen> {
final qty = double.tryParse(item.qtyCtrl.text) ?? 0;
final price = double.tryParse(item.priceCtrl.text) ?? 0;
final amount = qty * price;
final productCode = _productCodeOf(item);
return MobileListCard(
title: Text('商品 ${index + 1}'),
@@ -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';
@@ -365,7 +366,7 @@ class _StockInListScreenState extends ConsumerState<StockInListScreen> {
final searchField = TextField(
controller: _searchCtrl,
decoration: InputDecoration(
hintText: '单号/往来单位,回车搜索',
hintText: '单号/往来单位/酒名,回车搜索',
prefixIcon: const Icon(Icons.search, size: 16),
hintStyle: const TextStyle(fontSize: 12),
suffixIcon: IconButton(
@@ -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),
),
],
],
),
);
@@ -83,6 +83,7 @@ class _ItemRow {
final String spec;
final double? unitPrice;
final TextEditingController qtyCtrl;
final TextEditingController salePriceCtrl;
_ItemRow({
this.productId,
@@ -91,9 +92,19 @@ class _ItemRow {
this.series = '',
this.spec = '',
this.unitPrice,
}) : qtyCtrl = TextEditingController(text: '1');
double? salePrice,
}) : qtyCtrl = TextEditingController(text: '1'),
//
salePriceCtrl = TextEditingController(
text: ((salePrice != null && salePrice > 0)
? salePrice
: (unitPrice ?? 0))
.toStringAsFixed(2));
void dispose() => qtyCtrl.dispose();
void dispose() {
qtyCtrl.dispose();
salePriceCtrl.dispose();
}
}
class StockOutFormScreen extends ConsumerStatefulWidget {
@@ -152,6 +163,7 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
series: item.productSeries ?? '',
spec: item.productSpec ?? '',
unitPrice: item.unitPrice,
salePrice: item.salePrice,
);
row.qtyCtrl.text = item.quantity.toStringAsFixed(0);
_items.add(row);
@@ -178,11 +190,13 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
super.dispose();
}
// = = Σ(×)
double get _totalAmount {
double total = 0;
for (final item in _items) {
final qty = double.tryParse(item.qtyCtrl.text) ?? 0;
total += qty * (item.unitPrice ?? 0);
final sale = double.tryParse(item.salePriceCtrl.text) ?? 0;
total += qty * sale;
}
return total;
}
@@ -280,10 +294,12 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
final itemsData = _items.map((item) {
final qty = double.tryParse(item.qtyCtrl.text) ?? 0;
final price = item.unitPrice ?? 0;
final sale = double.tryParse(item.salePriceCtrl.text) ?? 0;
return {
'product_id': item.productId ?? 0,
'quantity': qty,
'unit_price': price,
'sale_price': sale,
'total_price': qty * price,
};
}).toList();
@@ -647,10 +663,11 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
2: FlexColumnWidth(2.0), //
3: FlexColumnWidth(1.2), //
4: FlexColumnWidth(1.2), //
5: FlexColumnWidth(1.0), //
6: FlexColumnWidth(0.8), //
7: FlexColumnWidth(1.0), //
8: FixedColumnWidth(48), //
5: FlexColumnWidth(1.0), //
6: FlexColumnWidth(1.0), //
7: FlexColumnWidth(0.8), //
8: FlexColumnWidth(1.0), //
9: FixedColumnWidth(48), //
},
children: [
TableRow(
@@ -662,7 +679,8 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
'商品名称',
'系列',
'规格',
'',
'成本',
'售价',
'数量',
'金额',
'操作',
@@ -734,7 +752,8 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
final item = _items[index];
final qty = double.tryParse(item.qtyCtrl.text) ?? 0;
final price = item.unitPrice ?? 0;
final amount = qty * price;
final sale = double.tryParse(item.salePriceCtrl.text) ?? 0;
final amount = qty * sale;
return TableRow(
decoration: BoxDecoration(
@@ -761,12 +780,16 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
_cell(Text(item.spec,
style:
const TextStyle(fontSize: 12, color: AppTheme.textSecondary))),
//
//
_cell(Text(price > 0 ? '¥${price.toStringAsFixed(2)}' : '-',
style: const TextStyle(fontSize: 13))),
style: const TextStyle(
fontSize: 13, color: AppTheme.textSecondary))),
//
Padding(
padding: const EdgeInsets.all(4), child: _salePriceField(item)),
//
Padding(padding: const EdgeInsets.all(4), child: _qtyField(item)),
//
// =×
_cell(Text('¥${amount.toStringAsFixed(2)}',
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500))),
//
@@ -803,12 +826,27 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
);
}
// () ×
Widget _salePriceField(_ItemRow item) {
return TextFormField(
controller: item.salePriceCtrl,
decoration: const InputDecoration(hintText: '0.00', isDense: true),
style: const TextStyle(fontSize: 13),
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}'))
],
onChanged: (_) => setState(() {}),
);
}
///
Widget _buildItemCard(int index) {
final item = _items[index];
final qty = double.tryParse(item.qtyCtrl.text) ?? 0;
final price = item.unitPrice ?? 0;
final amount = qty * price;
final sale = double.tryParse(item.salePriceCtrl.text) ?? 0;
final amount = qty * sale;
return MobileListCard(
title: Text(item.productName),
@@ -824,7 +862,9 @@ class _StockOutFormScreenState extends ConsumerState<StockOutFormScreen> {
fields: [
if (item.series.isNotEmpty) MobileCardField('系列', item.series),
if (item.spec.isNotEmpty) MobileCardField('规格', item.spec),
MobileCardField('单价', price > 0 ? '¥${price.toStringAsFixed(2)}' : '-'),
MobileCardField(
'成本价', price > 0 ? '¥${price.toStringAsFixed(2)}' : '-'),
MobileCardField('售价', null, valueWidget: _salePriceField(item)),
MobileCardField('数量', null, valueWidget: _qtyField(item)),
MobileCardField('金额', '¥${amount.toStringAsFixed(2)}'),
],
@@ -921,6 +961,27 @@ class _InventoryPickerDialogState
};
bool _loading = false;
Timer? _debounce;
// 1 20 _total
static const int _pageSize = 20;
int _page = 1;
int _total = 0;
int get _totalPages => _total <= 0 ? 1 : ((_total + _pageSize - 1) ~/ _pageSize);
@override
void initState() {
super.initState();
// 1 20
// initState setState
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _fetch();
});
}
void _goPage(int p) {
if (p < 1 || p > _totalPages || _loading) return;
setState(() => _page = p);
_fetch();
}
@override
void dispose() {
@@ -930,7 +991,11 @@ class _InventoryPickerDialogState
}
void _onSearchChanged(String v) {
setState(() => _search = v);
// 1
setState(() {
_search = v;
_page = 1;
});
_debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 300), _fetch);
}
@@ -942,13 +1007,19 @@ class _InventoryPickerDialogState
final result = await ref.read(inventoryRepositoryProvider).listInventory(
warehouseId: widget.warehouseId,
keyword: kw.isEmpty ? null : kw,
pageSize: AppConstants.stockOutPickerPageSize,
page: _page,
pageSize: _pageSize,
);
final items = _aggregatePickerItems(result.data);
for (final it in items) {
_known[it.productId] = it;
}
if (mounted) setState(() => _results = items);
if (mounted) {
setState(() {
_results = items;
_total = result.total;
});
}
} catch (_) {
//
} finally {
@@ -1121,6 +1192,39 @@ class _InventoryPickerDialogState
}),
child: Text(allSelected ? '取消全选' : '全选当前'),
),
const SizedBox(width: 8),
// ==
Text(
_loading ? '加载中…' : '$_total 项库存商品',
style: const TextStyle(
fontSize: 13, color: AppTheme.textSecondary),
),
const SizedBox(width: 12),
//
IconButton(
icon: const Icon(Icons.chevron_left, size: 20),
onPressed: (_page > 1 && !_loading)
? () => _goPage(_page - 1)
: null,
tooltip: '上一页',
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 32, minHeight: 32),
),
Text('$_page / $_totalPages',
style: const TextStyle(fontSize: 13)),
IconButton(
icon: const Icon(Icons.chevron_right, size: 20),
onPressed: (_page < _totalPages && !_loading)
? () => _goPage(_page + 1)
: null,
tooltip: '下一页',
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 32, minHeight: 32),
),
const Spacer(),
OutlinedButton(
onPressed: () => Navigator.pop(context),
@@ -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;
@@ -372,7 +378,7 @@ class _StockOutListScreenState extends ConsumerState<StockOutListScreen> {
final searchField = TextField(
controller: _searchCtrl,
decoration: InputDecoration(
hintText: '单号/往来单位,回车搜索',
hintText: '单号/往来单位/酒名,回车搜索',
prefixIcon: const Icon(Icons.search, size: 16),
hintStyle: const TextStyle(fontSize: 12),
suffixIcon: IconButton(
@@ -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,82 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:jiu_client/core/api/api_client.dart';
import 'package:jiu_client/core/models/page_result.dart';
import 'package:jiu_client/models/stock_in.dart';
import 'package:jiu_client/providers/stock_in_provider.dart';
import 'package:jiu_client/repositories/stock_in_repository.dart';
/// list()
class _CountingStockInRepo extends StockInRepository {
int listCalls = 0;
String? lastKeyword;
_CountingStockInRepo() : super(ApiClient(token: 't'));
@override
Future<PageResult<StockInOrder>> list({
String? status,
String? startDate,
String? endDate,
String? keyword,
int page = 1,
int pageSize = 20,
}) async {
listCalls++;
lastKeyword = keyword;
return const PageResult<StockInOrder>(
data: [], total: 0, page: 1, pageSize: 20);
}
}
void main() {
test('setKeyword 防抖:350ms 内连发只触发最后一次', () async {
final repo = _CountingStockInRepo();
final container = ProviderContainer(
overrides: [stockInRepositoryProvider.overrideWithValue(repo)],
);
addTearDown(container.dispose);
// build
await container.read(stockInListProvider.future);
expect(repo.listCalls, 1);
final notifier = container.read(stockInListProvider.notifier);
// 350ms
notifier.setKeyword('');
notifier.setKeyword('茅台');
notifier.setKeyword('飞天茅台');
//
await Future<void>.delayed(const Duration(milliseconds: 120));
expect(repo.listCalls, 1);
// 1
await Future<void>.delayed(const Duration(milliseconds: 350));
expect(repo.listCalls, 2);
expect(repo.lastKeyword, '飞天茅台');
});
test('setKeyword 去重:相同关键词不重复查询', () async {
final repo = _CountingStockInRepo();
final container = ProviderContainer(
overrides: [stockInRepositoryProvider.overrideWithValue(repo)],
);
addTearDown(container.dispose);
await container.read(stockInListProvider.future);
final notifier = container.read(stockInListProvider.notifier);
//
notifier.setKeyword('茅台');
await Future<void>.delayed(const Duration(milliseconds: 400));
expect(repo.listCalls, 2);
expect(repo.lastKeyword, '茅台');
// return
notifier.setKeyword('茅台');
await Future<void>.delayed(const Duration(milliseconds: 400));
expect(repo.listCalls, 2);
});
}
+103
View File
@@ -0,0 +1,103 @@
# 阿里云独立 nginx 版(宿主机直接终结 TLS,不经 pangolin)。
# 与 nginx-jiu.confEC2 pangolin 容器版,listen 127.0.0.1:8445)等价,
# 仅入口监听改为对公网 443 直连。CI deploy-server.sh 的 ali 分支落到
# /etc/nginx/conf.d/jiu.conf。
limit_req_zone $binary_remote_addr zone=jiu_pub:10m rate=10r/s;
limit_req_status 429;
server {
listen 443 ssl http2;
server_name jiu.51yanmei.com;
ssl_certificate /etc/letsencrypt/live/jiu.51yanmei.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/jiu.51yanmei.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
client_max_body_size 20m;
# 商品图片静态文件
location ^~ /images/ {
alias /opt/jiu/images/;
expires 30d;
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;
}
# 未鉴权公开/登录接口:加最外层 per-IP 限流
location ~ ^/api/v1/(public|auth)/ {
limit_req zone=jiu_pub burst=20 nodelay;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 30s;
}
# API 反向代理
location ~ ^/(api|health|version) {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 30s;
}
# Flutter 管理端(仅 /app/ 前缀)
location /app/ {
alias /opt/jiu/web/;
index index.html;
try_files $uri $uri/ /app/index.html;
}
location = /app/index.html {
alias /opt/jiu/web/index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
expires 0;
}
# 公开商品详情页(扫码跳转)→ 后端注入 OG 标签
location ~ ^/product/ {
limit_req zone=jiu_pub burst=20 nodelay;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 30s;
}
# Flutter base-href=/app/ 会把 /product/:id 重写为 /app/product/:id
location ~ ^/app/product/ {
limit_req zone=jiu_pub burst=20 nodelay;
rewrite ^/app(/product/.+)$ $1 break;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 30s;
}
# 桌面客户端安装包下载
location /downloads/ {
alias /opt/jiu/downloads/;
add_header Content-Disposition "attachment";
add_header Cache-Control "no-cache";
autoindex off;
}
# 营销站点兜底
location / {
root /opt/jiu/marketing;
try_files $uri $uri.html $uri/index.html /index.html;
}
}
server {
listen 80;
server_name jiu.51yanmei.com;
return 301 https://$host$request_uri;
}
@@ -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>:进价必须 &gt; 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>
+1
View File
@@ -26,6 +26,7 @@ mv backend/jiu-gencode dist/jiu-gencode
# it belongs to the client pipeline.
tar -czf dist/configs.tar.gz \
deploy/nginx-jiu.conf \
deploy/nginx-jiu-ali.conf \
deploy/jiu.service \
deploy/production.env.template \
deploy/setup-ec2.sh \
+13 -10
View File
@@ -1,14 +1,17 @@
#!/usr/bin/env bash
# deploy-client.sh <tag> — deploy the Flutter web app, desktop/mobile installers,
# and version.yaml to EC2. Does NOT restart the backend (version.yaml is read
# per-request) nor touch nginx / the marketing site.
# and version.yaml. Does NOT restart the backend (version.yaml is read
# per-request) nor touch nginx / the marketing site. Target is EC2 by default;
# set DEPLOY_HOST/DEPLOY_USER/DEPLOY_SSH_KEY to retarget the Ali box (migration).
set -euo pipefail
# shellcheck source=scripts/ci/lib-forgejo.sh
. "$(dirname "$0")/lib-forgejo.sh"
TAG="$1"
echo "==> deploy-client: tag=${TAG}"
TARGET_HOST="${DEPLOY_HOST:-$EC2_HOST}"
TARGET_USER="${DEPLOY_USER:-$EC2_USER}"
echo "==> deploy-client: tag=${TAG} host=${TARGET_HOST}"
if [ ! -f dist/web.tar.gz ] || [ ! -f dist/version.yaml ]; then
download_release_assets "$TAG"
@@ -27,18 +30,18 @@ mkdir -p /tmp/jiu-web-new
tar -xzf dist/web.tar.gz -C /tmp/jiu-web-new --strip-components=1
setup_ssh
echo "==> deploy-client: uploading files to EC2"
${SCP} "$VERSION_YAML" "${EC2_USER}@${EC2_HOST}:/tmp/version.yaml"
echo "==> deploy-client: uploading files to ${TARGET_HOST}"
${SCP} "$VERSION_YAML" "${TARGET_USER}@${TARGET_HOST}:/tmp/version.yaml"
rsync -avz --delete -e "ssh -i ~/.ssh/ec2_deploy.pem -o StrictHostKeyChecking=no" \
/tmp/jiu-web-new/ "${EC2_USER}@${EC2_HOST}:/tmp/jiu-web-new/"
/tmp/jiu-web-new/ "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-web-new/"
# Desktop / mobile installers (served from /downloads/ by nginx). Guarded —
# may be absent in a partial manual deploy.
[ -f dist/jiu-windows-x64-setup.exe ] && ${SCP} dist/jiu-windows-x64-setup.exe "${EC2_USER}@${EC2_HOST}:/tmp/jiu-windows-x64-setup.exe" || true
[ -f dist/jiu-macos-x64.zip ] && ${SCP} dist/jiu-macos-x64.zip "${EC2_USER}@${EC2_HOST}:/tmp/jiu-macos-x64.zip" || true
[ -f dist/jiu-android.apk ] && ${SCP} dist/jiu-android.apk "${EC2_USER}@${EC2_HOST}:/tmp/jiu-android.apk" || true
[ -f dist/jiu-windows-x64-setup.exe ] && ${SCP} dist/jiu-windows-x64-setup.exe "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-windows-x64-setup.exe" || true
[ -f dist/jiu-macos-x64.zip ] && ${SCP} dist/jiu-macos-x64.zip "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-macos-x64.zip" || true
[ -f dist/jiu-android.apk ] && ${SCP} dist/jiu-android.apk "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-android.apk" || true
${SSH} "${EC2_USER}@${EC2_HOST}" << 'ENDSSH'
${SSH} "${TARGET_USER}@${TARGET_HOST}" << 'ENDSSH'
set -e
# Update version config (WorkingDirectory=/opt/jiu reads config/version.yaml).
+59 -12
View File
@@ -1,15 +1,26 @@
#!/usr/bin/env bash
# deploy-server.sh <tag> — deploy the backend binary + nginx config to EC2.
# Two modes: uses dist/ built in the same job, or downloads the release assets
# by tag (manual rollback). Does NOT touch the web app, marketing site, or
# version.yaml.
# deploy-server.sh <tag> — deploy the backend binary + nginx config.
# Two source modes: uses dist/ built in the same job, or downloads the release
# assets by tag (manual rollback). Does NOT touch the web app, marketing site,
# or version.yaml.
#
# Target is EC2 by default. During the EC2→Ali migration, set DEPLOY_TARGET=ali
# plus DEPLOY_HOST/DEPLOY_USER/DEPLOY_SSH_KEY to deploy to the Alibaba Cloud box.
# - ec2 (default): stop jiu → swap binary → start jiu → health check →
# reload nginx inside the pangolin-edge container.
# - ali: swap binary only (jiu.service stays stopped — the Ali DB is a
# read-only replica until cutover; backend is started at cutover) →
# reload the host nginx with the standalone (listen 443) config.
set -euo pipefail
# shellcheck source=scripts/ci/lib-forgejo.sh
. "$(dirname "$0")/lib-forgejo.sh"
TAG="$1"
echo "==> deploy-server: tag=${TAG}"
DEPLOY_TARGET="${DEPLOY_TARGET:-ec2}"
TARGET_HOST="${DEPLOY_HOST:-$EC2_HOST}"
TARGET_USER="${DEPLOY_USER:-$EC2_USER}"
echo "==> deploy-server: tag=${TAG} target=${DEPLOY_TARGET} host=${TARGET_HOST}"
if [ ! -f dist/jiu-server ] || [ ! -f dist/configs.tar.gz ]; then
download_release_assets "$TAG"
@@ -22,19 +33,54 @@ rm -rf /tmp/jiu-configs
mkdir -p /tmp/jiu-configs
tar -xzf dist/configs.tar.gz -C /tmp/jiu-configs
# Pick the nginx config matching the target's reverse-proxy topology.
if [ "$DEPLOY_TARGET" = "ali" ]; then
NGINX_SRC=/tmp/jiu-configs/deploy/nginx-jiu-ali.conf
else
NGINX_SRC=/tmp/jiu-configs/deploy/nginx-jiu.conf
fi
setup_ssh
echo "==> deploy-server: uploading files to EC2"
${SCP} dist/jiu-server "${EC2_USER}@${EC2_HOST}:/tmp/jiu-server"
${SCP} /tmp/jiu-configs/deploy/nginx-jiu.conf "${EC2_USER}@${EC2_HOST}:/tmp/nginx-jiu.conf"
echo "==> deploy-server: uploading files to ${TARGET_HOST}"
${SCP} dist/jiu-server "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-server"
${SCP} "${NGINX_SRC}" "${TARGET_USER}@${TARGET_HOST}:/tmp/nginx-jiu.conf"
# Platform code-minting CLI + wrapper (absent when rolling back to a pre-gencode
# release — upload only when present).
if [ -f dist/jiu-gencode ]; then
${SCP} dist/jiu-gencode "${EC2_USER}@${EC2_HOST}:/tmp/jiu-gencode"
${SCP} /tmp/jiu-configs/deploy/jiu-gencode.sh "${EC2_USER}@${EC2_HOST}:/tmp/jiu-gencode.sh"
${SCP} dist/jiu-gencode "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-gencode"
${SCP} /tmp/jiu-configs/deploy/jiu-gencode.sh "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-gencode.sh"
fi
${SSH} "${EC2_USER}@${EC2_HOST}" << 'ENDSSH'
if [ "$DEPLOY_TARGET" = "ali" ]; then
# --- Alibaba Cloud (shadow target, pre-cutover) ---
# Swap the binary but DO NOT start jiu: the Ali DB is a read-only replica, so
# the backend's startup AutoMigrate/backfill would fail. jiu.service is started
# only at cutover (after the replica is promoted to primary). Reload the host
# nginx with the standalone listen-443 config.
${SSH} "${TARGET_USER}@${TARGET_HOST}" << 'ENDSSH'
set -e
cp /tmp/jiu-server /opt/jiu/backend/jiu-server
chmod +x /opt/jiu/backend/jiu-server
if [ -f /tmp/jiu-gencode ]; then
cp /tmp/jiu-gencode /opt/jiu/backend/jiu-gencode
chmod +x /opt/jiu/backend/jiu-gencode
if [ -f /tmp/jiu-gencode.sh ]; then
cp /tmp/jiu-gencode.sh /opt/jiu/backend/jiu-gencode.sh
chmod +x /opt/jiu/backend/jiu-gencode.sh
fi
fi
cp /tmp/nginx-jiu.conf /etc/nginx/conf.d/jiu.conf
nginx -t && systemctl reload nginx
echo "Ali server staged (binary swapped, jiu.service left stopped, nginx reloaded)"
ENDSSH
else
# --- EC2 (live primary) ---
${SSH} "${TARGET_USER}@${TARGET_HOST}" << 'ENDSSH'
set -e
# Replace backend binary
@@ -72,7 +118,8 @@ docker exec pangolin-edge nginx -t && docker exec pangolin-edge nginx -s reload
echo "Server deploy complete!"
ENDSSH
fi
teardown_ssh
rm -rf /tmp/jiu-configs
echo "==> deploy-server: done"
echo "==> deploy-server: done (target=${DEPLOY_TARGET})"
+9 -6
View File
@@ -1,13 +1,16 @@
#!/usr/bin/env bash
# deploy-site.sh <tag> — deploy the Eleventy marketing site to EC2
# (/opt/jiu/marketing). Does NOT restart the backend or touch nginx.
# deploy-site.sh <tag> — deploy the Eleventy marketing site to /opt/jiu/marketing.
# Does NOT restart the backend or touch nginx. Target is EC2 by default; set
# DEPLOY_HOST/DEPLOY_USER/DEPLOY_SSH_KEY to retarget the Ali box (migration).
set -euo pipefail
# shellcheck source=scripts/ci/lib-forgejo.sh
. "$(dirname "$0")/lib-forgejo.sh"
TAG="$1"
echo "==> deploy-site: tag=${TAG}"
TARGET_HOST="${DEPLOY_HOST:-$EC2_HOST}"
TARGET_USER="${DEPLOY_USER:-$EC2_USER}"
echo "==> deploy-site: tag=${TAG} host=${TARGET_HOST}"
if [ ! -f dist/marketing.tar.gz ]; then
download_release_assets "$TAG"
@@ -21,11 +24,11 @@ mkdir -p /tmp/jiu-marketing-new
tar -xzf dist/marketing.tar.gz -C /tmp/jiu-marketing-new
setup_ssh
echo "==> deploy-site: uploading marketing site to EC2"
echo "==> deploy-site: uploading marketing site to ${TARGET_HOST}"
rsync -avz --delete -e "ssh -i ~/.ssh/ec2_deploy.pem -o StrictHostKeyChecking=no" \
/tmp/jiu-marketing-new/ "${EC2_USER}@${EC2_HOST}:/tmp/jiu-marketing-new/"
/tmp/jiu-marketing-new/ "${TARGET_USER}@${TARGET_HOST}:/tmp/jiu-marketing-new/"
${SSH} "${EC2_USER}@${EC2_HOST}" << 'ENDSSH'
${SSH} "${TARGET_USER}@${TARGET_HOST}" << 'ENDSSH'
set -e
mkdir -p /opt/jiu/marketing
rsync -a --delete /tmp/jiu-marketing-new/ /opt/jiu/marketing/
+8 -3
View File
@@ -106,12 +106,17 @@ for a in rel.get('assets', []):
PYEOF
}
# setup_ssh — write the EC2 deploy key and export SSH / SCP commands.
# setup_ssh — write the deploy key and export SSH / SCP commands.
# Target is the EC2 host by default; set DEPLOY_HOST / DEPLOY_USER / DEPLOY_SSH_KEY
# to retarget another host (e.g. the Alibaba Cloud box during the EC2→Ali migration).
# Backward-compatible: with no DEPLOY_* set, behaves exactly as before (EC2).
setup_ssh() {
local host="${DEPLOY_HOST:-$EC2_HOST}"
local key="${DEPLOY_SSH_KEY:-$EC2_SSH_KEY}"
mkdir -p ~/.ssh
printf '%s' "${EC2_SSH_KEY}" > ~/.ssh/ec2_deploy.pem
printf '%s' "${key}" > ~/.ssh/ec2_deploy.pem
chmod 600 ~/.ssh/ec2_deploy.pem
ssh-keyscan -H "${EC2_HOST}" >> ~/.ssh/known_hosts 2>/dev/null
ssh-keyscan -H "${host}" >> ~/.ssh/known_hosts 2>/dev/null
SSH="ssh -i ~/.ssh/ec2_deploy.pem -o StrictHostKeyChecking=no"
SCP="scp -O -i ~/.ssh/ec2_deploy.pem"
}