Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b260939563 | |||
| 84f99ef459 | |||
| 102ace42ac | |||
| e8f416ddea | |||
| 08b41a8f63 | |||
| 2eb4275e6f | |||
| 9139192097 | |||
| ff4a2db7cc | |||
| 21aa2523b7 | |||
| f395920a8c | |||
| 3625240839 | |||
| 7969bb41e3 |
@@ -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:
|
||||
|
||||
@@ -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 独立 nginx,jiu 保持 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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -5,6 +5,12 @@ 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
|
||||
|
||||
### 新功能
|
||||
|
||||
@@ -5,6 +5,16 @@
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [1.0.79] - 2026-06-24
|
||||
|
||||
### 改进
|
||||
- 入库单 / 出库单列表的关键词搜索支持按「酒名(商品名)」模糊反查:除单号、往来单位外,输入商品名(含拼音/首字母)即可筛出含该商品的单据。
|
||||
|
||||
## [1.0.78] - 2026-06-23
|
||||
|
||||
### 新功能
|
||||
- 入库单新增「确认进价」接口:以 0 价(暂估)入库并已审核/出库的调货单据,价格确定后可补填真实进价。系统在一个事务内前向补偿——回填库存批次成本与已出库明细的成本快照、按差额补一条对供应商的应付流水、重算入库单合计,售价与应收不受影响;仅管理员可操作,支持多次按差额修正。
|
||||
|
||||
## [1.0.77] - 2026-06-22
|
||||
|
||||
### 新功能
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/wangjia/jiu/backend/internal/model"
|
||||
"github.com/wangjia/jiu/backend/testutil"
|
||||
)
|
||||
|
||||
// 调货核心场景:0 价入库 → 审核 → 部分出库 → 确认进价(前向补偿)。
|
||||
func TestConfirmCost_BackfillsCostAndAdjustsPayable(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_MAIN")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "茅台")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
// 0 价入库 10 → 审核
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 10.0, "unit_price": 0.0}},
|
||||
})
|
||||
require.Equal(t, http.StatusCreated, w.Code)
|
||||
inID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/submit", inID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/approve", inID), adminToken, nil)
|
||||
|
||||
var inItem model.StockInItem
|
||||
require.NoError(t, db.Where("order_id = ?", inID).First(&inItem).Error)
|
||||
pid := inItem.ProductID // 序列号模型:入库为该行新建独立 product
|
||||
|
||||
// 库存批次成本待定(UnitPrice 为 NULL)
|
||||
var inv model.Inventory
|
||||
require.NoError(t, db.Where("shop_id = ? AND stock_in_item_id = ?", shop.ID, inItem.ID).First(&inv).Error)
|
||||
assert.Nil(t, inv.UnitPrice, "0 价入库时库存成本应为待定(NULL)")
|
||||
|
||||
// 出库 4(售价 80,成本暂为 0)→ 审核
|
||||
w = makeRequest(r, "POST", "/api/v1/stock-out/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": pid, "quantity": 4.0, "unit_price": 0.0, "sale_price": 80.0}},
|
||||
})
|
||||
outID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-out/orders/%d/submit", outID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-out/orders/%d/approve", outID), adminToken, nil)
|
||||
|
||||
// 确认进价 50
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 50.0}}})
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
// 1. 入库明细成本回填
|
||||
db.First(&inItem, inItem.ID)
|
||||
assert.Equal(t, 50.0, inItem.UnitPrice)
|
||||
assert.Equal(t, 500.0, inItem.TotalPrice)
|
||||
|
||||
// 2. 剩余库存批次成本回填(6 件)
|
||||
db.First(&inv, inv.ID)
|
||||
require.NotNil(t, inv.UnitPrice)
|
||||
assert.Equal(t, 50.0, *inv.UnitPrice)
|
||||
|
||||
// 3. 已出库行成本快照回填,售价/应收不变
|
||||
var outItem model.StockOutItem
|
||||
require.NoError(t, db.Where("order_id = ?", outID).First(&outItem).Error)
|
||||
assert.Equal(t, 50.0, outItem.UnitPrice, "已出库成本应回填")
|
||||
assert.Equal(t, 200.0, outItem.TotalPrice, "成本小计 = 50×4")
|
||||
assert.Equal(t, 80.0, outItem.SalePrice, "售价不应被改动")
|
||||
|
||||
var outOrder model.StockOutOrder
|
||||
db.First(&outOrder, outID)
|
||||
assert.Equal(t, 320.0, outOrder.TotalAmount, "应收按售价 4×80,确认进价不影响")
|
||||
|
||||
// 4. 入库单总额按差额重算:0 → 500
|
||||
var inOrder model.StockInOrder
|
||||
db.First(&inOrder, inID)
|
||||
assert.Equal(t, 500.0, inOrder.TotalAmount)
|
||||
|
||||
// 5. 应付差额调整流水:+500(balance 是应收应付混合滚动总账:0 入 + 320 应收 + 500 = 820)
|
||||
var adj model.FinanceRecord
|
||||
require.NoError(t, db.Where("shop_id = ? AND type = 'payable' AND ref_type = 'stock_in_cost_adjust'", shop.ID).
|
||||
First(&adj).Error)
|
||||
assert.Equal(t, 500.0, adj.Amount)
|
||||
assert.Equal(t, 820.0, adj.Balance)
|
||||
|
||||
// 6. product 参考进价同步(pid 是入库新建的独立 product)
|
||||
var p2 model.Product
|
||||
require.NoError(t, db.First(&p2, pid).Error)
|
||||
assert.Equal(t, 50.0, p2.PurchasePrice)
|
||||
}
|
||||
|
||||
// 非管理员无权确认进价。
|
||||
func TestConfirmCost_Forbidden(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_FORBID")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
op := testutil.CreateTestUser(db, shop.ID, "op", "pass", "operator")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "五粮液")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
opToken := getAuthToken(op.ID, shop.ID, "operator")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 5.0, "unit_price": 0.0}},
|
||||
})
|
||||
inID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/submit", inID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/approve", inID), adminToken, nil)
|
||||
var inItem model.StockInItem
|
||||
db.Where("order_id = ?", inID).First(&inItem)
|
||||
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), opToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 30.0}}})
|
||||
assert.Equal(t, http.StatusForbidden, w.Code)
|
||||
}
|
||||
|
||||
// 仅 approved 单可确认;草稿/待审核拒绝。
|
||||
func TestConfirmCost_RejectsNonApproved(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_DRAFT")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "汾酒")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 5.0, "unit_price": 0.0}},
|
||||
})
|
||||
inID := extractID(w)
|
||||
var inItem model.StockInItem
|
||||
db.Where("order_id = ?", inID).First(&inItem)
|
||||
|
||||
// 仍是 draft → 400
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 30.0}}})
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
// 重复确认:按新旧差额增量补偿,不重复全量。
|
||||
func TestConfirmCost_RepeatableByDiff(t *testing.T) {
|
||||
db := testutil.SetupTestDB()
|
||||
shop := testutil.CreateTestShop(db, "CC_REPEAT")
|
||||
admin := testutil.CreateTestUser(db, shop.ID, "admin", "pass", "admin")
|
||||
wh := testutil.CreateTestWarehouse(db, shop.ID, "仓")
|
||||
prod := testutil.CreateTestProduct(db, shop.ID, "剑南春")
|
||||
adminToken := getAuthToken(admin.ID, shop.ID, "admin")
|
||||
r := setupProtectedRouter(db)
|
||||
|
||||
w := makeRequest(r, "POST", "/api/v1/stock-in/orders", adminToken, map[string]interface{}{
|
||||
"warehouse_id": wh.ID, "order_date": time.Now().Format(time.RFC3339),
|
||||
"items": []map[string]interface{}{{"product_id": prod.ID, "quantity": 10.0, "unit_price": 0.0}},
|
||||
})
|
||||
inID := extractID(w)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/submit", inID), adminToken, nil)
|
||||
makeRequest(r, "PUT", fmt.Sprintf("/api/v1/stock-in/orders/%d/approve", inID), adminToken, nil)
|
||||
var inItem model.StockInItem
|
||||
db.Where("order_id = ?", inID).First(&inItem)
|
||||
|
||||
// 第一次确认 50(diff 500)
|
||||
makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 50.0}}})
|
||||
// 第二次修正为 60(diff 100)
|
||||
w = makeRequest(r, "POST", fmt.Sprintf("/api/v1/stock-in/orders/%d/confirm-cost", inID), adminToken,
|
||||
map[string]interface{}{"items": []map[string]interface{}{{"item_id": inItem.ID, "unit_price": 60.0}}})
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
db.First(&inItem, inItem.ID)
|
||||
assert.Equal(t, 60.0, inItem.UnitPrice)
|
||||
|
||||
var inOrder model.StockInOrder
|
||||
db.First(&inOrder, inID)
|
||||
assert.Equal(t, 600.0, inOrder.TotalAmount, "总额 = 60×10")
|
||||
|
||||
// 两条调整流水:+500 与 +100,余额滚动到 600
|
||||
var adjs []model.FinanceRecord
|
||||
db.Where("shop_id = ? AND ref_type = 'stock_in_cost_adjust'", shop.ID).Order("id ASC").Find(&adjs)
|
||||
require.Len(t, adjs, 2)
|
||||
assert.Equal(t, 500.0, adjs[0].Amount)
|
||||
assert.Equal(t, 100.0, adjs[1].Amount)
|
||||
assert.Equal(t, 600.0, adjs[1].Balance)
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -315,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"})
|
||||
}
|
||||
|
||||
@@ -451,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")
|
||||
|
||||
@@ -45,9 +45,17 @@ 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) 索引
|
||||
|
||||
@@ -212,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")
|
||||
|
||||
@@ -66,6 +66,7 @@ func setupProtectedRouter(db *gorm.DB) *gin.Engine {
|
||||
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")
|
||||
|
||||
@@ -157,6 +157,8 @@ func Setup(r *gin.Engine, db *gorm.DB) {
|
||||
stockIn.PUT("/orders/:id/withdraw", stockInH.Withdraw)
|
||||
// 退单(已审核单退货,库存删除+冲应付):仅管理员/超管(service 内判权)
|
||||
stockIn.POST("/orders/:id/return", stockInH.Return)
|
||||
// 确认进价(暂估0价→真实价,前向补偿):仅管理员/超管(service 内判权)
|
||||
stockIn.POST("/orders/:id/confirm-cost", stockInH.ConfirmCost)
|
||||
}
|
||||
|
||||
// 出库
|
||||
|
||||
@@ -157,6 +157,111 @@ func (s *StockService) ApproveStockIn(shopID, orderID, reviewerID uint64) error
|
||||
})
|
||||
}
|
||||
|
||||
// CostConfirmItem 是「确认进价」的单行入参:把某入库明细的进价补成真实值。
|
||||
type CostConfirmItem struct {
|
||||
ItemID uint64 `json:"item_id"`
|
||||
UnitPrice float64 `json:"unit_price"`
|
||||
}
|
||||
|
||||
// ConfirmStockInCost 「确认进价」:调货等场景以 0 价(暂估)入库并已审核/已出库后,
|
||||
// 价格确定时补填真实进价。不反审核、不撤销任何已发生的动作,而是在一个事务内
|
||||
// 前向写补偿:
|
||||
// 1. 入库明细 UnitPrice / TotalPrice 改为真实值
|
||||
// 2. 该明细对应的剩余库存批次 Inventory.UnitPrice 由 NULL→真实值
|
||||
// 3. 该 product 已出库行 StockOutItem.UnitPrice/TotalPrice(成本快照)回填真实值
|
||||
// (product↔入库明细 1:1,按 product_id 精确命中;不动 SalePrice/应收)
|
||||
// 4. 入库单 TotalAmount 按差额重算
|
||||
// 5. 对供应商应付按差额补一条调整流水(滚动余额)
|
||||
//
|
||||
// 仅 approved 单可确认(draft 直接编辑即可);权限:管理员/超管。
|
||||
// 以「旧价→新价」差额计算补偿,支持多次修正(再次确认按新旧差额补)。
|
||||
func (s *StockService) ConfirmStockInCost(shopID, orderID, userID uint64, role string, items []CostConfirmItem) error {
|
||||
if role != "admin" && role != "superadmin" {
|
||||
return ErrForbidden
|
||||
}
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var order model.StockInOrder
|
||||
if err := tx.Preload("Items").Where("id = ? AND shop_id = ?", orderID, shopID).
|
||||
First(&order).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if order.Status != "approved" {
|
||||
return errors.New("只有已审核单据可确认进价")
|
||||
}
|
||||
|
||||
want := make(map[uint64]float64, len(items))
|
||||
for _, it := range items {
|
||||
want[it.ItemID] = it.UnitPrice
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var totalDiff float64
|
||||
|
||||
for i := range order.Items {
|
||||
it := &order.Items[i]
|
||||
newPrice, ok := want[it.ID]
|
||||
if !ok || newPrice == it.UnitPrice {
|
||||
continue
|
||||
}
|
||||
oldPrice := it.UnitPrice
|
||||
diff := (newPrice - oldPrice) * it.Quantity
|
||||
totalDiff += diff
|
||||
|
||||
// 1. 入库明细
|
||||
if err := tx.Model(it).Updates(map[string]interface{}{
|
||||
"unit_price": newPrice,
|
||||
"total_price": newPrice * it.Quantity,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. 该明细的剩余库存批次(已全部出库则无行,跳过)
|
||||
if err := tx.Model(&model.Inventory{}).
|
||||
Where("shop_id = ? AND stock_in_item_id = ? AND deleted_at IS NULL", shopID, it.ID).
|
||||
Update("unit_price", newPrice).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. 已出库行成本快照回填(按 product_id 精确命中;product_id=0 的历史导入单不传播)
|
||||
if it.ProductID != 0 {
|
||||
if err := tx.Model(&model.StockOutItem{}).
|
||||
Where("shop_id = ? AND product_id = ?", shopID, it.ProductID).
|
||||
Updates(map[string]interface{}{
|
||||
"unit_price": newPrice,
|
||||
"total_price": gorm.Expr("? * quantity", newPrice),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 同步 product 参考进价
|
||||
if it.ProductID != 0 {
|
||||
tx.Model(&model.Product{}).Where("id = ? AND shop_id = ?", it.ProductID, shopID).
|
||||
Update("purchase_price", newPrice)
|
||||
}
|
||||
}
|
||||
|
||||
if totalDiff == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 4. 入库单总额按差额重算
|
||||
if err := tx.Model(&order).
|
||||
Update("total_amount", gorm.Expr("total_amount + ?", totalDiff)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 5. 应付差额调整流水(滚动余额)
|
||||
bal := partnerLastBalance(tx, shopID, order.PartnerID) + totalDiff
|
||||
oid := order.ID
|
||||
return tx.Create(&model.FinanceRecord{
|
||||
ShopID: shopID, PartnerID: order.PartnerID, Type: "payable",
|
||||
Amount: totalDiff, Balance: bal, Status: "open",
|
||||
RefType: "stock_in_cost_adjust", RefID: &oid, OperatorID: userID, RecordDate: now,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
// ApproveStockOut 审核出库单,FIFO 扣减批次库存
|
||||
func (s *StockService) ApproveStockOut(shopID, orderID, reviewerID uint64) error {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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';
|
||||
@@ -26,9 +28,11 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
|
||||
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 {
|
||||
@@ -80,10 +84,17 @@ class StockOutListNotifier extends AsyncNotifier<PageResult<StockOutOrder>> {
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
/// 按商品编码精确反查(独立于 keyword)
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,7 +312,10 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
|
||||
style: const TextStyle(fontFamily: 'monospace', fontSize: 12))),
|
||||
'warehouse' => DataCell(Text(item.warehouseName.isEmpty ? '-' : item.warehouseName)),
|
||||
'price' => DataCell(Text(
|
||||
item.unitPrice != null ? '¥${item.unitPrice!.toStringAsFixed(2)}' : '-')),
|
||||
item.unitPrice != null ? '¥${item.unitPrice!.toStringAsFixed(2)}' : '待定价',
|
||||
style: item.unitPrice == null
|
||||
? const TextStyle(color: AppTheme.warning)
|
||||
: null)),
|
||||
'prodDate' => DataCell(Text(item.productionDate ?? '-')),
|
||||
'inTime' => DataCell(Text(
|
||||
item.createdAt != null && item.createdAt!.length >= 10
|
||||
@@ -358,8 +361,8 @@ class _InventoryListScreenState extends ConsumerState<InventoryListScreen> {
|
||||
if (item.series.isNotEmpty) MobileCardField('系列', item.series),
|
||||
if (item.batchNo.isNotEmpty) MobileCardField('批次', item.batchNo),
|
||||
MobileCardField('仓库', item.warehouseName.isEmpty ? '-' : item.warehouseName),
|
||||
if (item.unitPrice != null)
|
||||
MobileCardField('单价', '¥${item.unitPrice!.toStringAsFixed(2)}'),
|
||||
MobileCardField('单价',
|
||||
item.unitPrice != null ? '¥${item.unitPrice!.toStringAsFixed(2)}' : '待定价'),
|
||||
if (item.supplierName.isNotEmpty)
|
||||
MobileCardField('供应商', item.supplierName),
|
||||
],
|
||||
|
||||
@@ -9,6 +9,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../core/utils/print_util.dart';
|
||||
import '../../widgets/label_preview_dialog.dart';
|
||||
import '../../widgets/fullscreen_image_viewer.dart';
|
||||
import '../../widgets/write_guard.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../../models/product.dart';
|
||||
@@ -309,9 +310,16 @@ class _ProductDetailScreenState extends ConsumerState<ProductDetailScreen> {
|
||||
height: 120,
|
||||
child: Row(
|
||||
children: [
|
||||
...p.images.map((img) => _ImageThumbnail(
|
||||
url: AppConfig.baseUrl + img.url,
|
||||
onDelete: () => _deleteImage(img),
|
||||
...p.images.asMap().entries.map((e) => _ImageThumbnail(
|
||||
url: AppConfig.baseUrl + e.value.url,
|
||||
onDelete: () => _deleteImage(e.value),
|
||||
onView: () => showFullscreenImages(
|
||||
context,
|
||||
p.images
|
||||
.map((img) => AppConfig.baseUrl + img.url)
|
||||
.toList(),
|
||||
initialIndex: e.key,
|
||||
),
|
||||
)),
|
||||
if (p.images.length < 5)
|
||||
WriteGuard(
|
||||
@@ -567,7 +575,9 @@ class _ProductDetailScreenState extends ConsumerState<ProductDetailScreen> {
|
||||
class _ImageThumbnail extends StatelessWidget {
|
||||
final String url;
|
||||
final VoidCallback onDelete;
|
||||
const _ImageThumbnail({required this.url, required this.onDelete});
|
||||
final VoidCallback onView;
|
||||
const _ImageThumbnail(
|
||||
{required this.url, required this.onDelete, required this.onView});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -575,19 +585,22 @@ class _ImageThumbnail extends StatelessWidget {
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: Image.network(
|
||||
url,
|
||||
width: 110,
|
||||
height: 110,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => Container(
|
||||
GestureDetector(
|
||||
onDoubleTap: onView,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: Image.network(
|
||||
url,
|
||||
width: 110,
|
||||
height: 110,
|
||||
color: AppTheme.border,
|
||||
child: const Icon(Icons.broken_image,
|
||||
color: AppTheme.textSecondary),
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => Container(
|
||||
width: 110,
|
||||
height: 110,
|
||||
color: AppTheme.border,
|
||||
child: const Icon(Icons.broken_image,
|
||||
color: AppTheme.textSecondary),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../widgets/fullscreen_image_viewer.dart';
|
||||
|
||||
// ── Palette & typography constants ────────────────────────────────────
|
||||
const _kPaper = Color(0xFFFAF8F5);
|
||||
@@ -476,12 +477,7 @@ class _HeroGalleryState extends State<_HeroGallery> {
|
||||
}
|
||||
|
||||
void _openFullscreen(int index) {
|
||||
Navigator.of(context).push(PageRouteBuilder(
|
||||
opaque: false,
|
||||
barrierColor: Colors.black87,
|
||||
pageBuilder: (_, __, ___) => _FullscreenViewer(
|
||||
urls: widget.imageUrls, initialIndex: index),
|
||||
));
|
||||
showFullscreenImages(context, widget.imageUrls, initialIndex: index);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,66 +530,6 @@ class _GlassChip extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Full-screen image viewer ──────────────────────────────────────────
|
||||
|
||||
class _FullscreenViewer extends StatefulWidget {
|
||||
final List<String> urls;
|
||||
final int initialIndex;
|
||||
const _FullscreenViewer({required this.urls, required this.initialIndex});
|
||||
|
||||
@override
|
||||
State<_FullscreenViewer> createState() => _FullscreenViewerState();
|
||||
}
|
||||
|
||||
class _FullscreenViewerState extends State<_FullscreenViewer> {
|
||||
late PageController _ctrl;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_ctrl = PageController(initialPage: widget.initialIndex);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() { _ctrl.dispose(); super.dispose(); }
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: () => Navigator.of(context).pop(),
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
body: Stack(
|
||||
children: [
|
||||
PageView.builder(
|
||||
controller: _ctrl,
|
||||
itemCount: widget.urls.length,
|
||||
itemBuilder: (_, i) => Center(
|
||||
child: InteractiveViewer(
|
||||
child: Image.network(widget.urls[i], fit: BoxFit.contain,
|
||||
errorBuilder: (_, __, ___) =>
|
||||
const Icon(Icons.broken_image, size: 64, color: Colors.white54)),
|
||||
)),
|
||||
),
|
||||
Positioned(
|
||||
top: 40, right: 16,
|
||||
child: GestureDetector(
|
||||
onTap: () => Navigator.of(context).pop(),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black54, borderRadius: BorderRadius.circular(20)),
|
||||
child: const Icon(Icons.close, color: Colors.white, size: 20),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Verified Ribbon ───────────────────────────────────────────────────
|
||||
|
||||
class _VerifiedRibbon extends StatelessWidget {
|
||||
|
||||
@@ -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)
|
||||
@@ -1131,13 +1224,31 @@ class _StockInDetailDialogState extends ConsumerState<_StockInDetailDialog> {
|
||||
_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),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -378,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(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
# 阿里云独立 nginx 版(宿主机直接终结 TLS,不经 pangolin)。
|
||||
# 与 nginx-jiu.conf(EC2 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>:进价必须 > 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>
|
||||
@@ -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
@@ -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
@@ -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})"
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user