Files
sale/scripts/e2e_ship_settlement.py
hermes 4fe5311a7f
Build and Push Docker Image / build-and-push (push) Successful in 1m37s
Build and Push Docker Image / deploy (push) Successful in 8s
feat(settlement): 供货运费进入结算(应结 = 货款 + 运费)
原来结算只算货款 Σ(供货价×件数),供货商代垫的发货运费无处体现,等于让他
自己承担运费。现在把运费做成独立、可追溯的一等数据:

- inventory.ship_fee:该供货商每件收取的运费(他在后台可见,管理员维护)
- order_items.ship_fee:下单时的运费快照,和 cost_price 同一套口径,
  之后改运费不影响历史结算
- orders.supplier_ship_fee:整单应付供货商运费合计
- supplier_settlements.ship_amount + total_amount:
  应结 = 货款 + 运费;运费允许在开单时手工覆盖(月结按物流对账单修正)

口径统一:
- 毛利 = 销售额 − 货款 − 供货运费(原来只扣货款,毛利虚高)
- 控制台 ranges 增加 goods_cost / ship_cost,cost_amount 改为二者之和
- payable 增加 goods_cost / ship_cost,total_cost 改 应结总额,待结按新口径重算
- 已有结算单没有 total_amount 时回退按 cost_amount 计算(向后兼容)

修一处漏改:attachSettlementState 里又把毛利重算成 sale−cost,把运费吃掉了,
e2e 断言 32 实测 40 才发现,已同步扣运费。

前端:管理员结算页汇总卡与表格拆出货款/供货运费/应结合计,补「在途」列
(原来已结 0、待结 0 会让人以为账对不上);供货价维护加「供货运费/件」可编辑;
供应商端汇总卡、按商品明细(货款/运费/小计)、结算记录都显示运费。

验证 scripts/e2e_ship_settlement.py(全新库、精确金额):
卖100进80运3 / 卖200进180运5 → 商品额 300、货款 260、运费 8、应结 268、
毛利 32;开单 total 268;供应商端应结 268 / 待收 268;无订单周期不给开单
2026-11-22 01:52:11 +08:00

158 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""供货运费进结算的端到端验证(全新库,断言精确金额)。"""
import json
import os
import sqlite3
import urllib.error
import urllib.request
B = os.environ.get("SALE_BASE", "http://127.0.0.1:18097")
DB = os.environ.get("SALE_DB", "/tmp/saletest2/sale.db")
def req(method, path, body=None, token=None):
data = json.dumps(body).encode() if body is not None else None
r = urllib.request.Request(B + path, data=data, method=method)
r.add_header("Content-Type", "application/json")
if token:
r.add_header("Authorization", "Bearer " + token)
try:
with urllib.request.urlopen(r) as resp:
raw = resp.read().decode()
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
return {"_status": e.code, "_body": e.read().decode()}
def q(sql, args=()):
c = sqlite3.connect(DB)
cur = c.execute(sql, args)
rows = cur.fetchall()
c.commit()
c.close()
return rows
def login(email, pwd):
r = req("POST", "/api/auth/login", {"email": email, "password": pwd})
t = r.get("token") or (r.get("data") or {}).get("token")
assert t, f"登录失败 {email}: {r}"
return t
def main():
# ---- 安装 ----
req("POST", "/api/install", {"username": "admin", "email": "admin@test.local",
"password": "Admin12345"}, )
atok = login("admin@test.local", "Admin12345")
# ---- 供货商 + 两个商品:卖 100 进 80 运费 3;卖 200 进 180 运费 5 ----
sup = req("POST", "/api/admin/suppliers",
{"username": "supA", "email": "supA@test.local", "password": "Supplier123"}, atok)
sid = (sup.get("data") or sup).get("id")
assert sid, sup
pcols = [r[1] for r in q("PRAGMA table_info(products)")]
ids = []
c = sqlite3.connect(DB)
for name, price in (("中华(测试)", 100), ("熊猫(测试)", 200)):
f = {"name": name, "price": price, "is_active": 1, "stock": 0, "min_purchase": 1}
f = {k: v for k, v in f.items() if k in pcols}
cur = c.execute(f"INSERT INTO products ({','.join(f)}) VALUES ({','.join(['?'] * len(f))})", list(f.values()))
ids.append(cur.lastrowid)
c.commit()
c.close()
icols = [r[1] for r in q("PRAGMA table_info(inventory)")]
c = sqlite3.connect(DB)
for pid, cost, ship in zip(ids, (80, 180), (3, 5)):
f = {"product_id": pid, "supplier_id": sid, "quantity": 100, "cost_price": cost,
"ship_fee": ship, "warning_threshold": 0, "updated_at": "2026-11-21 00:00:00"}
f = {k: v for k, v in f.items() if k in icols}
c.execute(f"INSERT INTO inventory ({','.join(f)}) VALUES ({','.join(['?'] * len(f))})", list(f.values()))
c.commit()
c.close()
print(f"[seed] 供货商 {sid}:卖100进80运费3 / 卖200进180运费5")
# ---- 买家下单 ----
req("POST", "/api/auth/register", {"username": "buyer1", "email": "buyer1@test.local", "password": "Buyer12345"})
utok = login("buyer1@test.local", "Buyer12345")
a = req("POST", "/api/users/addresses", {"name": "收件", "phone": "13800000000",
"province": "東京都", "city": "東京", "address": "テスト1-2-3"}, utok)
aid = (a.get("data") or a).get("id")
assert aid, a
for pid in ids:
req("POST", "/api/cart", {"product_id": pid, "quantity": 1}, utok)
order = req("POST", "/api/orders", {"shipping_address_id": aid, "payment_method": "manual"}, utok)
oid = (order.get("data") or order).get("id")
assert oid, order
q("UPDATE orders SET status='completed' WHERE id=?", (oid,))
rows = q("SELECT subtotal, supplier_ship_fee FROM orders WHERE id=?", (oid,))
print(f"[order] #{oid} 商品额 {rows[0][0]} / 供货运费 {rows[0][1]}")
assert rows[0][1] == 8, f"供货运费快照错: {rows[0]}"
items = q("SELECT product_id, cost_price, ship_fee, quantity FROM order_items WHERE order_id=?", (oid,))
print("[items] (product_id, 供货价, 运费, 件数):", items)
assert {i[1] for i in items} == {80, 180}, items
assert {i[2] for i in items} == {3, 5}, items
# ---- 管理员汇总:货款 260 + 运费 8 = 应结 268,毛利 300-268=32 ----
sm = req("GET", "/api/admin/settlements/summary?period=this_month", token=atok)["data"]
row = [r for r in sm["rows"] if r["supplier_id"] == sid][0]
print("[admin] 货款 %.2f 运费 %.2f 应结 %.2f 销售 %.2f 毛利 %.2f"
% (row["cost_amount"], row["ship_amount"], row["settle_amount"], row["sale_amount"], row["gross_profit"]))
assert row["cost_amount"] == 260 and row["ship_amount"] == 8, row
assert row["settle_amount"] == 268 and row["gross_profit"] == 32, row
t = sm["totals"]
assert (t["cost_amount"], t["ship_amount"], t["settle_amount"]) == (260, 8, 268), t
print("[check] 管理员汇总:货款 260 + 运费 8 = 应结 268,毛利 32 ✔")
# ---- 生成结算单 ----
made = req("POST", "/api/admin/settlements", {
"supplier_id": sid, "period_type": "this_month",
"period_start": sm["period_start"], "period_end": sm["period_end"],
}, atok)["data"]
print("[settlement] id=%s 货款 %.2f 运费 %.2f 应结 %.2f"
% (made["id"], made["cost_amount"], made["ship_amount"], made["total_amount"]))
assert made["total_amount"] == 268 and made["ship_amount"] == 8, made
# ---- 手工修正运费:按物流对账单抹成 10,应结变 270 ----
ov = req("POST", "/api/admin/settlements", {
"supplier_id": sid, "period_type": "custom",
"period_start": "2020-01-01", "period_end": "2020-01-31", "ship_amount": 10,
}, atok)
# 该周期没有订单,应被拒(只为确认不会凭空开单)
assert ov.get("_status") == 400 or ov.get("error"), ov
print("[check] 无订单周期不给开单 ✔")
# ---- 供应商端:应结 268、待收 268 ----
stok = login("supA@test.local", "Supplier123")
ss = req("GET", "/api/supplier/settlements/summary?period=this_month", token=stok)["data"]
print("[supplier] summary:", ss["summary"])
print("[supplier] items:", [(i["product_name"], i["quantity"], i["cost_amount"], i["ship_amount"]) for i in ss["items"]])
assert ss["summary"]["cost_amount"] == 260 and ss["summary"]["ship_amount"] == 8
assert ss["summary"]["settle_amount"] == 268
sl = req("GET", "/api/supplier/settlements", token=stok)["data"]
print("[supplier] 记录:", [(i["cost_amount"], i["ship_amount"], i["total_amount"]) for i in sl["items"]],
"待收合计", sl["pending_total"])
assert sl["pending_total"] == 268, sl
print("[check] 供应商端应结 268 / 待收 268 ✔")
# ---- 控制台口径 ----
st = req("GET", "/api/admin/stats", token=atok)["data"]
m = st["ranges"]["month"]
pay = st["payable"]
print("[stats] 本月 销售 %.0f 货款 %.0f 运费 %.0f 成本 %.0f 毛利 %.0f"
% (m["sale_amount"], m["goods_cost"], m["ship_cost"], m["cost_amount"], m["gross_profit"]))
print("[stats] 待结 货款 %.0f 运费 %.0f 应结 %.0f 已结 %.0f 未结 %.0f"
% (pay["goods_cost"], pay["ship_cost"], pay["total_cost"], pay["settled"], pay["unsettled"]))
assert m["gross_profit"] == 32 and m["cost_amount"] == 268, m
assert pay["unsettled"] == 0, pay # 已开单,未结为 0
print("\n全部通过 ✔")
if __name__ == "__main__":
main()