Files
pricing_review/test/界面体检/清单单价现算_e2e.py

235 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""决策 232 无头浏览器实测(铁律 8):清单单价=∑定额合价÷清单工程量、0 量三格留空。
路径:
① 三溪件(含 2 条工程量=0 的清单):工作台打开 → 切「给水工程」→ 0 量行 量/单价/合价
三格全空白;展开一条普通清单:单价=∑定额子行合价÷清单量、合价=单价×量(DOM 自洽);
② 屏西件:HTTP 走真实采纳接口(9.3 原定额转临删+采纳定额追加)→ 采纳定额计入 ∑、
临删原件不进 ∑,单价保持 4.29、合价=单价×量;
③ 重进路径:reload 后 0 量仍空、数值仍符;全程页面无 JS 错误。
隔离副本服务(server_env 同款),退出整体删除,生产库零接触。
"""
import os
import sqlite3
import sys
import tempfile
import urllib.parse
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
_HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _HERE)
from server_env import Server # noqa: E402
_SRC = Path(_HERE).parents[1] / "CostReview" / "data" / "source_files"
_SANXI = _SRC / ("4926810c6fb1442d70bdf480e5e0de53bb254cbd86901232a9d984dcc08f54c5_"
"三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段GD3181[2023-4-25 17:24].COS")
_PINGXI = _SRC / ("42374399f8a9fcae562515fc834ca8568bc5f9cc511681388f3fcc1e54650907_"
"屏西五路北延工程-有量有价.cos4")
PERIOD = 2026 * 12 + 7
ZERO_CODES = {"040504009004", "041001007001"} # 三溪·给水工程 里工程量=0 的两条清单
def _r2(x):
return float(Decimal(str(x)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
def _num(s):
s = (s or "").replace(",", "").strip()
return float(s) if s else None
def _upload(server, fp):
r = server.client.post("/api/admin/upload", content=fp.read_bytes(),
headers={"Content-Type": "application/octet-stream",
"X-File-Name": urllib.parse.quote(fp.name)})
j = r.json()
assert j.get("ok"), r.text[:300]
return j["path"]
def _audit(server, path, name):
r = server.client.post("/api/audit", json={
"path": path, "name": name, "period_from": PERIOD,
"period_to": PERIOD, "base_period_m": PERIOD})
j = r.json()
assert j.get("ok"), r.text[:300]
return j["session_id"]
def _raw_uw(server, sid, uwid, tab="item"):
r = server.client.get("/api/session/raw/uw",
params={"session_id": sid, "uw_id": uwid, "tab": tab})
return r.json()
def _flatten_bills(d):
out = list(d.get("loose") or [])
def walk(nodes):
for n in nodes or []:
out.extend(n.get("bills") or [])
walk(n.get("children"))
walk(d.get("tree"))
return out
def _find_uw_id(tree, keyword=None):
"""单位工程 id:先查 sections[].uws[],再查顶层 free_uws(无单项工程层时)。"""
for s in tree.get("sections") or []:
for u in s.get("uws") or []:
if keyword is None or keyword in (u.get("Name") or ""):
return u["id"]
for u in tree.get("free_uws") or []:
if keyword is None or keyword in (u.get("Name") or ""):
return u["id"]
return 0
def _pick_browser(pw):
for kwargs in ({"headless": True}, {"headless": True, "channel": "chrome"},
{"headless": True, "channel": "msedge"}):
try:
return pw.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("无可用 Chromium 内核浏览器")
def _rows(page):
return page.evaluate("""() => Array.from(document.querySelectorAll('tr.brow')).map(tr => ({
code: (tr.cells[2] && tr.cells[2].textContent || '').trim(),
qty: (tr.cells[7] && tr.cells[7].textContent || '').trim(),
price:(tr.cells[8] && tr.cells[8].textContent || '').trim(),
total:(tr.cells[9] && tr.cells[9].textContent || '').trim()
}))""")
def main():
assert _SANXI.exists() and _PINGXI.exists(), "样例文件不在本机"
log = os.path.join(tempfile.gettempdir(), "raw_price232_e2e_server.log")
server = Server(log)
server.__enter__()
out = []
try:
# ── ① 三溪:0 量三格留空 + DOM 自洽 ─────────────────────────────
sid1 = _audit(server, _upload(server, _SANXI), "三溪E2E")
from playwright.sync_api import sync_playwright
with sync_playwright() as pw:
browser = _pick_browser(pw)
ctx = browser.new_context()
page = ctx.new_page()
errs = []
page.on("pageerror", lambda e: errs.append(str(e)))
page.goto("%s/workbench.html?sid=%d" % (server.base, sid1))
page.wait_for_function(
"() => typeof RVT !== 'undefined' && RVT && "
"((RVT.free_uws || []).length + (RVT.sections || []).length) > 0",
timeout=30000)
# 0量清单所在单位工程用接口按编码定位(不猜名字)
uw = 0
t1 = server.client.get("/api/session/raw/tree",
params={"session_id": sid1}).json()
uws = [u for s in t1.get("sections") or [] for u in s.get("uws") or []]
uws += list(t1.get("free_uws") or [])
for cand in uws:
bills = _flatten_bills(_raw_uw(server, sid1, cand["id"]))
if any(b.get("Number") in ZERO_CODES for b in bills):
uw = cand["id"]
break
assert uw, "含0量清单的单位工程没找到"
page.evaluate("id => rawPick('uw', id)", uw)
page.wait_for_selector("tr.brow", timeout=30000)
rows = _rows(page)
zeros = [r for r in rows if r["code"] in ZERO_CODES]
assert len(zeros) == 2, "0量清单应有2条,实得%d" % len(zeros)
for z in zeros:
assert z["qty"] == "" and z["price"] == "" and z["total"] == "", \
"0量行未留空:%r" % z
out.append("① 0量清单×2 三格全空白 ✓")
# 自洽:有值行 合价=单价×量
filled = [r for r in rows if r["qty"] and r["price"] and r["total"]]
assert filled, "给水工程没有有值清单?"
for r in filled:
assert abs(_num(r["total"]) - _r2(_num(r["price"]) * _num(r["qty"]))) < 0.011, \
"合价≠单价×量:%r" % r
# 展开第一条有定额清单:单价=∑子行合价÷量(子行取该 brow 紧随的 tr.sub)
first = page.evaluate("""() => {
const tr = Array.from(document.querySelectorAll('tr.brow'))
.find(x => x.querySelector('.tgi'));
if (!tr) return null;
tr.querySelector('.tgi').click();
return tr.cells[2].textContent.trim(); }""")
page.wait_for_timeout(500)
sums = page.evaluate("""() => {
const brows = Array.from(document.querySelectorAll('tr.brow'));
const b0 = brows.find(x => x.querySelector('.tgi'));
const out = []; let n = b0.nextElementSibling;
while (n && n.classList.contains('sub')) {
out.push(n.cells[n.cells.length - 3].textContent.trim());
n = n.nextElementSibling; }
return out; }""")
vals = [_num(s) for s in sums if _num(s) is not None]
assert vals, "第一条清单没有定额子行合价"
brow0 = next(r for r in rows if r["code"] == first)
q0, p0 = _num(brow0["qty"]), _num(brow0["price"])
assert abs(p0 - _r2(sum(vals) / q0)) < 0.011, \
"单价≠∑定额合价÷量:%s vs %s" % (p0, _r2(sum(vals) / q0))
out.append("① DOM 自洽:单价=∑定额合价÷量=%s、合价=单价×量 ✓" % p0)
# ③ 重进路径(决策195:rvst 恢复单位工程上下文)
page.reload()
page.wait_for_function(
"() => typeof RVT !== 'undefined' && RVT && "
"((RVT.free_uws || []).length + (RVT.sections || []).length) > 0",
timeout=30000)
page.wait_for_timeout(800)
if page.evaluate("document.querySelectorAll('tr.brow').length") == 0:
page.evaluate("id => rawPick('uw', id)", uw)
page.wait_for_selector("tr.brow", timeout=30000)
rows2 = _rows(page)
for z in (r for r in rows2 if r["code"] in ZERO_CODES):
assert z["qty"] == "" and z["price"] == "" and z["total"] == "", \
"重进后0量行未留空:%r" % z
assert not errs, "页面 JS 错误:%r" % errs[:3]
out.append("③ reload 后 0 量仍空、无页面 JS 错误 ✓")
browser.close()
# ── ② 屏西:真实采纳接口 → 采纳定额计入 ∑ ────────────────────────
sid2 = _audit(server, _upload(server, _PINGXI), "屏西E2E")
tr1 = server.client.get("/api/session/raw/tree",
params={"session_id": sid2}).json()
uw2 = _find_uw_id(tr1)
assert uw2, "屏西一个单位工程都没有"
before = next(b for b in _flatten_bills(_raw_uw(server, sid2, uw2))
if b["Number"] == "040101001001")
# 批次(采纳源):/api/admin/import 真实入库路径
r = server.client.post("/api/admin/import", json={
"path": _upload(server, _PINGXI)})
assert r.json().get("ok"), r.text[:300]
hdb = sqlite3.connect(os.path.join(server.root, "CostReview",
"data", "history.db"))
src = hdb.execute("SELECT id FROM bills WHERE Number='040101001001' "
"ORDER BY id DESC LIMIT 1").fetchone()
hdb.close()
assert src, "批次库里没有同编码清单"
r = server.client.post("/api/session/bill/adopt", json={
"session_id": sid2, "bill_id": before["id"], "src_bill_id": src[0]})
assert r.json().get("ok"), r.text[:300]
after_b = next(b for b in _flatten_bills(_raw_uw(server, sid2, uw2))
if b["id"] == before["id"])
live = [n for n in after_b["norms"] if not n[7]] # n[7]=x_tdel
assert len(live) == 1 and live[0][8] == 1, \
"采纳后应=原定额临删+采纳定额1条:%r" % after_b["norms"]
assert abs(after_b["Price"] - 4.29) < 1e-9, "采纳后单价应保持4.29:%r" % after_b["Price"]
assert abs(after_b["Total"] - _r2(after_b["Price"] * before["Quantity"])) < 1e-9
out.append("② 采纳后:临删原件不进∑、采纳定额计入∑,单价=%s、合价=%s ✓"
% (after_b["Price"], after_b["Total"]))
print("\n".join(out))
print("决策232 e2e 全过")
finally:
server.stop()
if __name__ == "__main__":
main()