feat(export): 采纳定额携带含量算式与换算调整,屏蔽金额汇总行改价同步

This commit is contained in:
lianjianwei2024
2026-10-18 20:25:27 +08:00
parent 9ddd9bb240
commit b0dc236245
30 changed files with 2727 additions and 274 deletions

View File

@@ -21,6 +21,7 @@
"""
import io
import json
import re
import struct
import zipfile
@@ -227,7 +228,7 @@ def _norm_parts(tmpl):
return opentag, inner[:spans[0].start()], spans[0].group(0), inner[spans[-1].end():]
def _norm_xml(n, lres, template=None):
def _norm_xml(n, lres, template=None, bill_qty=None):
"""定额行:优先克隆源文件同类 Norm 的完整属性集(值除会话字段外原样保留,
与易达的已知可行解一致);没有模板时退回最小形态。会话没算出的数值写 0
(易达同款处理)——占位属性可以在位为 0,但不能缺席。
@@ -257,16 +258,47 @@ def _norm_xml(n, lres, template=None):
if n["Total"] is not None:
a += ' Total="%s"' % n["Total"]
tag = "<Norm" + a + ">"
def _lres():
for it in lres:
if not it[0]:
continue
c, q = it[0], it[1]
ex = it[2] if len(it) > 2 else None
yield c, q, ex
if row_tmpl is None:
kids = "".join('<%s Number="%s" Quantity="%s" NOCost="false" Remark=""/>' % (_LME, _esc(c), _esc(q))
for c, q in lres if c)
for c, q, _ex in _lres())
else:
kids = "".join(_lme_row(row_tmpl, c, q, express=_esc(q)) for c, q in lres if c)
# 决策 106 补记十二:含量行 Express 优先填**历史项目自己的调整式**(如 1611.66*1.2),
# 没有算式的退裸含量——采纳定额的换算调整跟着历史项目走。
kids = "".join(_lme_row(row_tmpl, c, q, express=_esc(ex) if ex else _esc(q))
for c, q, ex in _lres())
if pre or row_tmpl is not None or post:
# 数量算式行(ExpressElement):**采纳/新增的定额一律不带**——主人实测:易达对带
# 算式行的定额按计算式显示(QGCL 代号 / [24.7157] 方括号值),都不是要的纯数字;
# 去掉算式行后易达直接显示 Quantity 属性。原生未动定额的算式行原样保留(原样原则)。
pre, post = _zero_results(pre), _zero_results(post)
# 换算记录是模板定额自己的操作历史(换机/改价…,决策 101 同类)——新定额没有历史,整行不落
pre = re.sub(r'<ExpressElement\b[^>]*/>', '', pre)
post = re.sub(r'<ExpressElement\b[^>]*/>', '', post)
# 换算调整记录(补记十三):先剥掉模板的记录(那是模板定额的历史),再按本定额
# 会话携带的 x_adjust 重写——采纳定额的调整工艺(GConvInfo 标准换算/R*2,J*2/送桩
# 材料含量…)跟历史项目走,主人定「有信息就要搬」。行形态照模板首行克隆。
# 换算调整记录(补记十三):先剥掉模板的记录(那是模板定额的历史),再按本定额
# 会话携带的 x_adjust 重写——采纳定额的调整工艺(GConvInfo 标准换算/R*2,J*2/送桩
# 材料含量…)跟历史项目走,主人定「有信息就要搬」。行形态照模板首行克隆。
m_adj = re.search(r'<NormAdjustmentList\b[^>]*/>', post)
adj_tmpl = m_adj.group(0) if m_adj else '<NormAdjustmentList OrderNumber="1" Value=""/>'
post = re.sub(r'<NormAdjustmentList\b[^>]*/>', '', post)
post = re.sub(r'<NormAdjustmentList\b[^>]*>.*?</NormAdjustmentList>', '', post)
try:
adj_vals = json.loads(n.get("x_adjust") or "[]")
except (TypeError, ValueError):
adj_vals = []
if isinstance(adj_vals, list) and adj_vals:
rows = "".join(_attr_set(_attr_set(adj_tmpl, "OrderNumber", str(i + 1)), "Value", str(v))
for i, v in enumerate(adj_vals))
post += rows
return tag + pre + kids + post + "</Norm>"
return tag + kids + "</Norm>"
@@ -547,7 +579,15 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
nrm_changed = True
continue
newn = nsp["opentag"]
for attr in ("Name", "Quantity"):
for attr in ("Name", "Quantity", "Total"):
if attr == "Total":
# 补记十六:改过工程量的定额 合价=工程量×单价(数值相同不重写)
if nn["Quantity"] is None or nn["Price"] is None:
continue
w = "%.2f" % round(float(nn["Quantity"]) * float(nn["Price"]), 2)
if not _num_eq(_attr(newn, "Total"), w):
newn = _attr_set(newn, "Total", w)
continue
if nn[attr] is None or (attr == "Quantity" and _num_eq(_attr(newn, attr), nn[attr])):
continue
w = _fmt_qty(nn[attr], 6) if attr == "Quantity" else nn[attr] # 定额工程量按源文件 6 位小数
@@ -567,7 +607,8 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
# WorkContent 之后(工料机汇总平铺表之前)。此前裸 Norm 插在块尾
# (汇总表和单价计算节点之后),广联达按 schema 解析错位 →
# 采纳定额的工料机外溢到定额层(屏西五路 040301004001 实测)。
body = "".join(_norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl) for nn in napp)
body = "".join(_norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl, bill_qty=b["Quantity"])
for nn in napp)
if has_wc and wc_close != -1:
ins = wc_close + len("</WorkContent>")
# 决策 99:原生 WorkContent 恒带 Name/Total/Remark 三属性(清单名/清单合价 2 位/空)
@@ -594,7 +635,7 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
inner = txt[nsp["e"] + mk["s"]: nsp["end"] + mk["s"]]
keep |= set(re.findall(r'<LabourMaterialsEquipmentsMachinesElement\b[^>]*?Number="([^"]*)"', inner))
for nn in napp:
keep |= {c for c, _q in res_by_norm.get(nn["id"], []) if c}
keep |= {it[0] for it in res_by_norm.get(nn["id"], []) if it[0]}
have = {c for _s, _e, c in dspans}
for _s, _e, c in dspans:
if c not in keep:
@@ -602,8 +643,33 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
add = [c for c in sorted(keep) if c not in have]
if add:
ins_at = dspans[-1][1] if dspans else tail_start
kid = "".join('<LabourMaterialsEquipmentsMachinesElement Number="%s" Express="0" Quantity="0" Remark=""/>'
% _esc(c) for c in add)
# 决策 106 补记十一:补码行与新增清单同口径——数量按 Σ(含量×定额量)÷清单量
# 填真值(此前恒 0)。仅新增码计算(原生码的行保持原值不动)。
agg = {}
try:
bq = float(b["Quantity"]) if b.get("Quantity") is not None else 0.0
except (TypeError, ValueError):
bq = 0.0
for nn in napp:
try:
nq = float(nn["Quantity"]) if nn["Quantity"] is not None else 0.0
except (TypeError, ValueError):
nq = 0.0
for it in res_by_norm.get(nn["id"], []):
cc, qq = it[0], it[1]
if cc not in add:
continue
try:
agg[cc] = agg.get(cc, 0.0) + float(qq) * nq
except (TypeError, ValueError):
pass
row_tmpl = txt[dspans[0][0]:dspans[0][1]] if dspans else None
kid = ""
for c in add:
vs = "%.4f" % round((agg.get(c, 0.0) / bq if bq else 0.0), 4)
kid += (_lme_row(row_tmpl, c, vs, express=vs) if row_tmpl else
'<%s Number="%s" Express="%s" Quantity="%s" Remark=""/>'
% (_LME, _esc(c), _esc(vs), _esc(vs)))
edits.append((ins_at, ins_at, kid))
# 新增清单落位:锚点 = 「第 N 条源清单之后」;**锚点 0 = 插在第一条源清单之前**
# (主人在工作台把新增行插到最上面时 x_seq 排最前——此前 0 被当成「无锚点」甩到组尾,
@@ -639,7 +705,8 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
if ' NormIdentity="' in nsp["opentag"]:
nn_tmpl = nsp["opentag"]
break
norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), nn_tmpl or norm_tmpl)
norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), nn_tmpl or norm_tmpl,
bill_qty=b["Quantity"])
for nn in norms_by_bill.get(b["id"], {}).get("append") or []]
parts.append(_bill_xml(b, tgt["tag"], norms_xml, tmpl_blk or tgt["opentag"], txt=txt))
edits.append((pos, pos, "".join(parts)))
@@ -683,6 +750,22 @@ def _summary_node(fields, template=None):
"" if np_ is None else np_, "" if tp is None else tp, "" if kd is None else kd))
def _is_amount_aggregate(opentag):
"""金额汇总行判定(决策 106 补记九):广联达文件里「人工费/管理费」这类汇总行的
惯例是 数量=金额合计、单价恒为 1(元/元恒等)。这类行回写会话里的资源单价
(如人工 500 元/工日)会被按 数量×单价 重算 → 人工费爆炸外溢(样例工程实测)。
判据:单位=元 且 原除税价数值=1。"""
if (_attr(opentag, "Unit") or "").strip() != "元":
return False
try:
return abs(float(_attr(opentag, "NoTaxPrice") or 0) - 1.0) < 1e-9
except (TypeError, ValueError):
return False
_PRICE_ATTRS = ("NoTaxPrice", "TaxRate", "TaxPrice")
def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, recode_children=None):
"""本单位工程的工料机汇总 = 单价被查找的对象(主人口径 5.1/5.3):
①采纳新增的品类行追加到本单位汇总末尾(克隆完整属性集);
@@ -709,6 +792,8 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
if not span:
continue
s0, e0, _bend, opentag = span
if _is_amount_aggregate(opentag):
continue # 金额汇总行不回写价格(补记九:人工费外溢实测)
newtag = opentag
for attr, v in (("NoTaxPrice", ntp), ("TaxRate", rate), ("TaxPrice", taxp)):
if v is None:
@@ -845,13 +930,16 @@ def transform_project(txt, added_summaries, hidden_codes, sync_rows=None):
if not span:
continue
s0, e0, _bend, opentag = span
aggregate = _is_amount_aggregate(opentag)
newtag = opentag
for attr, want in (("Name", name), ("Specification", spec), ("Unit", unit),
("NoTaxPrice", ntp), ("TaxRate", rate), ("TaxPrice", taxp)):
cur = _attr(newtag, attr)
if cur is None or want is None:
continue
if attr in ("NoTaxPrice", "TaxRate", "TaxPrice") and _num_eq(cur, want):
if aggregate and attr in _PRICE_ATTRS:
continue # 金额汇总行价格不回写(补记九)
if attr in _PRICE_ATTRS and _num_eq(cur, want):
continue
if attr in ("Name", "Specification", "Unit") and (cur or "").strip() == (want or "").strip():
continue

View File

@@ -306,8 +306,17 @@ def parse_std(path, out):
_push_bill(el.attrib) # ★ 容器在 start 就记账
out["cur_norm"] = -1 # 进清单:清掉定额上下文
elif el.tag == "Norm":
# 定额在 start 就记账:它下面的工料机消耗量要挂到 len(norms)(即它将占的下标)
out["cur_norm"] = len(out["norms"])
# 决策 106 补记十四:广联达把清单级的资源构成行(人工费等,编码=纯数字
# 工料机码、单位=元)也写成 <Norm> 元素——那是派生的金额行,不是定额
# (样例工程实测:采纳把它当定额带进工作台=人工费外溢)。不占定额下标,
# 子元素(含量/调整记录)一并跳过。
if (el.attrib.get("Number", "").isdigit()
and (el.attrib.get("Unit") or "").strip() == "元"):
out["skip_res_norm"] = True
out["cur_norm"] = -1
else:
# 定额在 start 就记账:它下面的工料机消耗量要挂到 len(norms)(即它将占的下标)
out["cur_norm"] = len(out["norms"])
elif el.tag in ("DivisionalWorks", "PreliminaryDivisionalWorks"):
# 2026-09-30:分部层 —— 分部分项与措施项目**各有一套**,而且都可能嵌套。
# 「原数据」标签里那张表的「分部」行、以及 ± 目录树全靠它。
@@ -360,12 +369,15 @@ def parse_std(path, out):
tag = el.tag
a = el.attrib
if tag == "Norm":
# 2026-09-29:补 Quantity / Total(源文件里确实有这两个属性,此前只取了 Price)
# 元组顺序:idx, 编码, 名称, 单位, 工程量, 单价, 合价
out["norms"].append((out["cur_bill"], a.get("Number", ""), a.get("Name", ""),
a.get("Unit", ""), f(a.get("Quantity")),
f(a.get("Price")), f(a.get("Total"))))
out["cur_norm"] = -1 # 出这条定额:后面的工料机不再算它的消耗
if out.pop("skip_res_norm", False):
out["cur_norm"] = -1 # 伪定额(资源构成行)不落库,见 start 侧
else:
# 2026-09-29:补 Quantity / Total(源文件里确实有这两个属性,此前只取了 Price)
# 元组顺序:idx, 编码, 名称, 单位, 工程量, 单价, 合价
out["norms"].append((out["cur_bill"], a.get("Number", ""), a.get("Name", ""),
a.get("Unit", ""), f(a.get("Quantity")),
f(a.get("Price")), f(a.get("Total"))))
out["cur_norm"] = -1 # 出这条定额:后面的工料机不再算它的消耗
elif tag == "LabourMaterialsEquipmentsMachinesElement":
# 2026-09-30:定额消耗量。**必须在自己的 end 事件里读属性** ——
# 循环末尾的 el.clear() 会把 attrib 一起清掉,等父元素(Norm)end 再 iter 只能拿到空属性。
@@ -379,7 +391,21 @@ def parse_std(path, out):
if _code:
out.setdefault("lme_res", {}).setdefault(_p, []).append((_code, f(a.get("Quantity"))))
elif _n >= 0 and _code:
out.setdefault("norm_res", []).append((_n, _code, f(a.get("Quantity"))))
# 决策 106 补记十二:含量算式(Express,如 "1611.66*1.2" 换算调整式)
# 随含量一起入库——采纳导出时按历史项目的调整式原样填写(此前只存数值,
# 调整信息丢失,只能填裸含量)。
out.setdefault("norm_res", []).append((_n, _code, f(a.get("Quantity")),
a.get("Express") or None))
elif tag == "NormAdjustmentList":
# 补记十三:换算调整记录(GConvInfo 标准换算/R*2, J*2/送桩材料含量…)
# 整条搬运——采纳定额的调整工艺跟历史项目走(此前整段丢弃)。
# cur_norm 由 Norm 的 start 事件记账,取属性同样要在自己的 end 事件里。
_n = out.get("cur_norm", -1)
v = a.get("Value") or "" # 原样保真(原生值可带首尾空格,strip 会改字面量)
if _n >= 0 and v.strip():
# 主人定(补记十五改):导入什么就是什么,原样整串入库,导出原样回填
out.setdefault("norm_adj", {}).setdefault(_n, []).append(v)
elif tag == "SummaryOfCost":
# 2026-09-30:单位工程造价构成。同样因为 clear 会清空 attrib,只能在自己的 end 里读。
# 归栈顶那个 UnitWorks(嵌套时内层优先),且每个单位工程只认它的第一个 SummaryOfCost。
@@ -586,21 +612,23 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
# 2026-10-17 修正:系数必须先除掉定额单位的数字前缀(10m/100m…),否则 GCL 求值时
# 单位换算双算两遍(前山河 040501004001:10m 定额导出量少 10 倍实测)。
norm_ids = []
for idx, num, name, unit, qty, price, total in out["norms"]:
for norm_idx, (idx, num, name, unit, qty, price, total) in enumerate(out["norms"]):
bid2 = bill_ids[idx] if 0 <= idx < len(bill_ids) else None
bqty = out["bills"][idx][4] if 0 <= idx < len(out["bills"]) else None
coef = (round(qty * unit_prefix(unit) / bqty, 6)
if (qty is not None and bqty not in (None, 0)) else None)
cur.execute("""INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef)
VALUES(?,?,?,?,?,?,?,?)""",
(bid2, num, name, unit, qty, price, total, coef))
cur.execute("""INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust)
VALUES(?,?,?,?,?,?,?,?,?)""",
(bid2, num, name, unit, qty, price, total, coef,
(lambda vals: json.dumps(vals, ensure_ascii=False) if vals else None)(
out.get("norm_adj", {}).get(norm_idx, []))))
norm_ids.append(cur.lastrowid)
# 定额消耗工料机(对应 s_norm_res)
for nidx, code, q in (out.get("norm_res") or []):
for nidx, code, q, express in (out.get("norm_res") or []):
nid = norm_ids[nidx] if 0 <= nidx < len(norm_ids) else None
cur.execute("INSERT INTO norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
(nid, code, q))
cur.execute("INSERT INTO norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
(nid, code, q, express or None))
n_lme = 0
n_lme_errs = 0

View File

@@ -324,6 +324,10 @@ def connect():
("s_lmes", ("x_remark TEXT", "x_hash_semi TEXT")),
# 2026-10-02:台班组成子项的名称(老库没这列,打开工程时 INSERT 会缺列报错)
("s_lme_res", ("name TEXT",)),
# 2026-10-18:定额含量算式(换算调整式如 1611.66*1.2,采纳携带;决策 106 补记十二)
("s_norm_res", ("express TEXT",)),
# 2026-10-18:定额换算调整记录(JSON,采纳携带;决策 106 补记十三)
("s_norms", ("x_adjust TEXT",)),
):
for col in cols:
try:
@@ -508,20 +512,23 @@ def open_project(con, files, meta, job, sid=None):
# 工程量/合价永远是「—」)。元组顺序:idx, 编码, 名称, 单位, 工程量, 单价, 合价
# 定额入库,同时记下真实 id —— 消耗量要靠它挂(norm_res 里存的是本文件内下标)
norm_ids = []
for idx, num, nm, unit, qty, price, total in out["norms"]:
adj = out.get("norm_adj", {})
for norm_idx, (idx, num, nm, unit, qty, price, total) in enumerate(out["norms"]):
bid = bill_ids[idx0 + idx] if 0 <= idx < len(out["bills"]) else None
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total)
VALUES(?,?,?,?,?,?,?)""",
(bid, num, nm, unit, qty, price, total))
vals = adj.get(norm_idx, [])
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust)
VALUES(?,?,?,?,?,?,?,?)""",
(bid, num, nm, unit, qty, price, total,
json.dumps(vals, ensure_ascii=False) if vals else None))
norm_ids.append(cur.lastrowid)
stat["norm"] += 1
# 2026-09-30:定额消耗量(定额 → 工料机编码 + 消耗量)。
# 2026-09-30:定额消耗量(定额 → 工料机编码 + 消耗量 + 含量算式,补记十二)。
# 有这张表才能回答「某个单位工程用了哪些工料机」——以前工料机只能挂到整个会话。
for nidx, code, q in (out.get("norm_res") or []):
for nidx, code, q, express in (out.get("norm_res") or []):
nid = norm_ids[nidx] if 0 <= nidx < len(norm_ids) else None
cur.execute("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
(nid, code, q))
cur.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
(nid, code, q, express or None))
stat["nres"] = stat.get("nres", 0) + 1
for num, nm, spec, unit, ntp, tax, tp, qty, kind in out["lmes"]:

View File

@@ -2186,16 +2186,17 @@ def _snap_norms(con, bill_id):
"""一条清单的定额+消耗量快照(仅当定额带状态列才值得回填;无状态返回 [])"""
out = []
for n in con.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total,
x_tdel, x_adopt, x_src_norm_id, qty_expr
x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust
FROM s_norms WHERE bill_id=? ORDER BY id""", (bill_id,)):
if not (n["x_tdel"] or n["x_adopt"] or n["x_src_norm_id"] or n["qty_expr"]):
continue # 干净定额:重导自然重建,不 snapshot
res = [list(x) for x in con.execute(
"SELECT res_code, qty FROM s_norm_res WHERE norm_id=? ORDER BY id", (n["id"],))]
"SELECT res_code, qty, express FROM s_norm_res WHERE norm_id=? ORDER BY id", (n["id"],))]
out.append({"Number": n["Number"], "Name": n["Name"], "Unit": n["Unit"],
"Quantity": n["Quantity"], "Price": n["Price"], "Total": n["Total"],
"x_tdel": n["x_tdel"], "x_adopt": n["x_adopt"],
"x_src_norm_id": n["x_src_norm_id"], "qty_expr": n["qty_expr"], "res": res})
"x_src_norm_id": n["x_src_norm_id"], "qty_expr": n["qty_expr"],
"x_adjust": n["x_adjust"], "res": res})
return out
@@ -2258,12 +2259,13 @@ def _restore_norms(con, bill_id, norms):
con.execute("DELETE FROM s_norms WHERE bill_id=?", (bill_id,))
for n in norms:
cur = con.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_tdel, x_adopt, x_src_norm_id, qty_expr) VALUES(?,?,?,?,?,?,?,?,?,?,?)""",
x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
(bill_id, n["Number"], n["Name"], n["Unit"], n["Quantity"], n["Price"],
n["Total"], n["x_tdel"], n["x_adopt"], n["x_src_norm_id"], n.get("qty_expr")))
for i, (code, qty) in enumerate(n["res"]):
con.execute("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
(cur.lastrowid, code, qty))
n["Total"], n["x_tdel"], n["x_adopt"], n["x_src_norm_id"], n.get("qty_expr"),
n.get("x_adjust")))
for i, (code, qty, express) in enumerate(n["res"]):
con.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
(cur.lastrowid, code, qty, express))
def _bill_state_restore(con, sid, snap):
@@ -2786,6 +2788,10 @@ def api_bill_op(sc, body):
_edit_log(sc, _bill_ekbase(sc, cur_row), ef, _BILL_EDIT_FIELDS, cur_row)
if "Name" in fields or "Attr" in fields:
_bill_rehash(sc, bid)
# 补记十六(主人定):改工程量 → 合价 = 工程量×单价(工作台即时同步,导出同口径)
if "Quantity" in fields:
sc.execute("""UPDATE s_bills SET Total=ROUND(COALESCE(Quantity,0)*COALESCE(Price,0),2)
WHERE id=?""", (bid,))
return {"ok": True, "sid": sid}
return {"ok": False, "msg": "未知操作:%s" % op}
@@ -3017,6 +3023,10 @@ def api_norm_edit(sc, body):
_edit_log(sc, _norm_ekbase(sc, cur_row),
{k: fields[k] for k in ("Name", "Quantity") if k in fields},
{"Name": "Name", "Quantity": "Quantity"}, cur_row)
# 补记十六(主人定):改工程量(数字) → 合价 = 工程量×单价(工作台即时同步)
if "Quantity" in fields:
sc.execute("""UPDATE s_norms SET Total=ROUND(COALESCE(Quantity,0)*COALESCE(Price,0),2)
WHERE id=?""", (nid,))
out = {"ok": True}
if qty_out is not None:
out["quantity"] = qty_out
@@ -3132,7 +3142,7 @@ def api_bill_adopt(sc, hc, body):
bb = hc.execute("SELECT id, Number, Name, Attr, Unit, Price, Quantity FROM bills WHERE id=?", (src_id,)).fetchone()
if not bb:
return {"ok": False, "msg": "入库项目清单不存在(批次可能已删除)"}
bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef
bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()
is_new = bool(sb["x_new"])
# 规格 19(2026-10-17 主人定·采纳逻辑变化):采纳定额工程量默认公式 = **GCL×系数**,
@@ -3149,12 +3159,14 @@ def api_bill_adopt(sc, hc, body):
sc.execute("DELETE FROM s_norms WHERE bill_id=?", (bid,))
for nn in bnorms:
cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_adopt, x_src_norm_id, qty_expr) VALUES(?,?,?,?,NULL,?,NULL,1,?,?)""",
x_adopt, x_src_norm_id, qty_expr, x_adjust)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?)""",
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"], nn["id"],
_gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"])))
for rr in hc.execute("SELECT res_code, qty FROM norm_res WHERE norm_id=? ORDER BY id", (nn["id"],)):
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
(cur.lastrowid, rr["res_code"], rr["qty"]))
_gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"]),
nn["x_adjust"]))
for rr in hc.execute("SELECT res_code, qty, express FROM norm_res WHERE norm_id=? ORDER BY id", (nn["id"],)):
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
(cur.lastrowid, rr["res_code"], rr["qty"], rr["express"]))
else:
# 9.3 定额追加 + 原定额转临删 + 清单单价按采纳价覆盖
sc.execute("DELETE FROM s_norm_res WHERE norm_id IN (SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=1)", (bid,))
@@ -3162,12 +3174,14 @@ def api_bill_adopt(sc, hc, body):
sc.execute("UPDATE s_norms SET x_tdel=1 WHERE bill_id=?", (bid,)) # 原有定额 → 临删
for nn in bnorms:
cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_adopt, x_src_norm_id, qty_expr) VALUES(?,?,?,?,NULL,?,NULL,1,?,?)""",
x_adopt, x_src_norm_id, qty_expr, x_adjust)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?)""",
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"], nn["id"],
_gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"])))
for rr in hc.execute("SELECT res_code, qty FROM norm_res WHERE norm_id=? ORDER BY id", (nn["id"],)):
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
(cur.lastrowid, rr["res_code"], rr["qty"]))
_gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"]),
nn["x_adjust"]))
for rr in hc.execute("SELECT res_code, qty, express FROM norm_res WHERE norm_id=? ORDER BY id", (nn["id"],)):
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
(cur.lastrowid, rr["res_code"], rr["qty"], rr["express"]))
bqty = sc.execute("SELECT Quantity FROM s_bills WHERE id=?", (bid,)).fetchone()["Quantity"]
btotal = round((float(bqty) if bqty is not None else 0.0) * (float(new_price) if new_price is not None else 0.0), 2)
sc.execute("UPDATE s_bills SET Price=?, Total=?, x_adopt=1 WHERE id=?", (new_price, btotal, bid))
@@ -3227,14 +3241,22 @@ def _export_session(sc, sid, progress=None):
kind = "prelim" if b["Kind"] == "prelim" else "item"
g = groups.setdefault((b["uw_id"], kind), {"pos": 0, "pairs": [], "news": []})
bd = dict(b)
# 补记十六:合价口径——**新增清单** 导出时按 工程量×单价 现算;
# 已有清单在编辑保存时已同步(上面的 API 入口),导出按会话现值原样写穿(决策 90)
if b["x_new"]:
_q, _p2 = f_(b["Quantity"]), f_(b["Price"])
bd["Total"] = round((_q or 0) * (_p2 or 0), 2)
if b["x_new"]:
bd["_anchor"] = g["pos"]
# 补记十六(主人定):新增清单 合价 = 工程量×单价——工作台不预存合价,导出时现算
_q, _p2 = f_(b["Quantity"]), f_(b["Price"])
bd["Total"] = round((_q or 0) * (_p2 or 0), 2)
g["news"].append(bd)
else:
g["pos"] += 1
g["pairs"].append((g["pos"], bd))
norms_by_bill = {}
for nb in sc.execute("""SELECT id, bill_id, Number, Name, Unit, Quantity, Price, Total, x_tdel, x_adopt, x_src_norm_id, qty_expr
for nb in sc.execute("""SELECT id, bill_id, Number, Name, Unit, Quantity, Price, Total, x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust
FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?)
ORDER BY id""", (sid,)):
entry = norms_by_bill.setdefault(nb["bill_id"], {"source": [], "append": []})
@@ -3269,11 +3291,16 @@ def _export_session(sc, sid, progress=None):
nb["Quantity"], nb["Total"] = row["Quantity"], row["Total"]
finally:
hc.close()
# 补记十六:定额 合价 = 工程量×单价(统一口径;单价缺失的行保持原值)
for entry in norms_by_bill.values():
for nb in entry["append"] + entry["source"]:
if nb.get("Quantity") is not None and nb.get("Price") is not None:
nb["Total"] = round(float(nb["Quantity"]) * float(nb["Price"]), 2)
res_by_norm = {}
for rr in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty FROM s_norm_res nr
for rr in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty, nr.express FROM s_norm_res nr
WHERE nr.norm_id IN (SELECT id FROM s_norms
WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?))""", (sid,)):
res_by_norm.setdefault(rr["norm_id"], []).append((rr["res_code"], rr["qty"]))
res_by_norm.setdefault(rr["norm_id"], []).append((rr["res_code"], rr["qty"], rr["express"]))
# (uw_id, kind) → uw 键;同 uw 的两种 kind 合成一份 plan
uwmap = {r["id"]: ((r["Number"] or ""), (r["Name"] or ""))
for r in sc.execute("SELECT id, Number, Name FROM s_unit_works WHERE session_id=?", (sid,))}
@@ -4745,6 +4772,8 @@ def _ensure_batch_schema():
AND norms.Quantity IS NOT NULL
AND EXISTS (SELECT 1 FROM bills b WHERE b.id = norms.bill_id
AND b.Quantity IS NOT NULL AND b.Quantity != 0)""")
_ensure_cols(c, "norm_res", [("express", "TEXT")]) # 含量算式(换算调整式,补记十二)
_ensure_cols(c, "norms", [("x_adjust", "TEXT")]) # 换算调整记录(JSON,补记十三)
_ensure_cols(c, "lmes", [("Quantity", "REAL"), ("Kind", "INTEGER")])
# x_info / x_feat:项目级「基本信息」「项目特征信息」两张卡的数据(与 sessions 对齐)
# x_parser_ver:导入时的解析器版本,用于启动比对「数据是否过期需重导」

View File

@@ -79,7 +79,8 @@ CREATE INDEX IF NOT EXISTS ix_div_uw ON divides(uw_id);
-- 定额消耗工料机(对应 s_norm_res)
CREATE TABLE IF NOT EXISTS norm_res(
id INTEGER PRIMARY KEY,
norm_id INTEGER, res_code TEXT, qty REAL
norm_id INTEGER, res_code TEXT, qty REAL,
express TEXT -- 含量算式(换算调整式,如 1611.66*1.2;决策 106 补记十二)
);
CREATE INDEX IF NOT EXISTS ix_nr_norm ON norm_res(norm_id);
CREATE INDEX IF NOT EXISTS ix_nr_code ON norm_res(res_code);
@@ -206,6 +207,7 @@ CREATE TABLE IF NOT EXISTS norms(
Quantity REAL, -- 2026-10-01 加(与 s_norms 对齐)
Price REAL,
Total REAL -- 2026-10-01 加
, x_adjust TEXT -- 换算调整记录(JSON 数组,Value 串;补记十三)
);
CREATE INDEX IF NOT EXISTS ix_norm_bill ON norms(bill_id);

View File

@@ -84,6 +84,8 @@ CREATE TABLE IF NOT EXISTS s_norms(
x_tdel INTEGER DEFAULT 0, -- 定额临删(批次B 采纳语义用)——决策 67 预埋
x_adopt INTEGER DEFAULT 0, -- 采纳标记(批次B)——决策 67 预埋
x_src_norm_id INTEGER -- 来源定额 id(取消采纳撤行用,批次B)——决策 67 预埋
,
x_adjust TEXT -- 换算调整记录(JSON;采纳携带,补记十三)
);
CREATE INDEX IF NOT EXISTS ix_sn_bill ON s_norms(bill_id);
@@ -95,7 +97,8 @@ CREATE TABLE IF NOT EXISTS s_norm_res(
id INTEGER PRIMARY KEY,
norm_id INTEGER, -- 对应 s_norms.id
res_code TEXT, -- 工料机编码(对 s_lmes.Number)
qty REAL -- 消耗量
qty REAL, -- 消耗量
express TEXT -- 含量算式(换算调整式,采纳携带;决策 106 补记十二)
);
CREATE INDEX IF NOT EXISTS ix_snr_norm ON s_norm_res(norm_id);
CREATE INDEX IF NOT EXISTS ix_snr_code ON s_norm_res(res_code);

View File

@@ -85,11 +85,12 @@ def test_appended_norm_keeps_innards():
"""采纳定额追加进原有清单:innards 一并克隆(此前裸 Norm 同样过不了结构关)。"""
out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], xcos._full_norm_block(RICH_BILL))
norm = _parse(out)
assert [c.tag for c in norm] == ["ExpressElement", "ManageFees",
# 补记二十一:采纳定额不带数量算式行(Express 大于 Quantity,易达会按算式显示代号/方括号)
assert [c.tag for c in norm] == ["ManageFees",
"LabourMaterialsEquipmentsMachinesElement",
"UnitPriceCalculationOfItem", "UnitPriceCalculationOfItem"]
assert all(c.get("Total") == "0" for c in norm.findall("UnitPriceCalculationOfItem"))
assert norm.find("ExpressElement").get("Express") == "" # 表达式文本清空(别人的公式带 QGCL 但量是别人的)
assert norm.findall("ExpressElement") == [] # 补记二十一:采纳定额不带数量算式行(易达才显示纯数字,不带方括号)
assert norm.get("Remark") == "" # 决策 101 口径不变
@@ -248,6 +249,177 @@ def test_new_bill_top_anchor_position(server):
assert txt.index('Name="顶部新增清单"') < txt.index('Number="B001"'), "新增清单应在第一条源清单之前"
def test_amount_aggregate_row_price_never_synced():
"""决策 106 补记九:广联达文件的「人工费」类汇总行是金额汇总行(数量=金额合计、
单价恒 1、单位=元)。会话里合并改价把它的单价改成资源口径(如人工 500 元/工日)
后,导出同步不得回写——原文件 数量×500 会让 Glodon 人工费爆炸外溢(样例工程实测)。"""
txt = ('<ConstructionProject>'
'<LabourMaterialsEquipmentsMachinesSummary Number="00010010" Name="人工费" Unit="元"'
' Quantity="4142082.6" NoTaxPrice="1" TaxRate="0" TaxPrice="1"/>'
'<LabourMaterialsEquipmentsMachinesSummary Number="990101015" Name="履带式推土机" Unit="台班"'
' Quantity="6.1" NoTaxPrice="1039.8" TaxRate="9.48" TaxPrice="1138.37"/>'
'</ConstructionProject>')
sync = [("00010010", "人工费", "", "元", 500.0, 0.0, 500.0),
("990101015", "履带式推土机", "", "台班", 1232.54, 0.0, 1232.54)]
out = xcos.transform_project(txt, [], [], sync_rows=sync)
agg = re.search(r'<LabourMaterialsEquipmentsMachinesSummary Number="00010010"[^>]*', out).group(0)
assert 'NoTaxPrice="1"' in agg and 'TaxPrice="1"' in agg # 金额汇总行价格不动
mac = re.search(r'<LabourMaterialsEquipmentsMachinesSummary Number="990101015"[^>]*', out).group(0)
assert 'NoTaxPrice="1232.54"' in mac # 正常资源行照常回写
assert xcos._is_amount_aggregate(
'<LabourMaterialsEquipmentsMachinesSummary Number="X" Unit="元" NoTaxPrice="1"/>')
assert not xcos._is_amount_aggregate(
'<LabourMaterialsEquipmentsMachinesSummary Number="X" Unit="台班" NoTaxPrice="1039.8"/>')
def test_adoption_carries_express_adjustment(server):
"""决策 106 补记十二:定额换算调整式(含量 Express,如人工费 *1.2)跟历史项目走——
导入捕获入库 → 采纳携带 → 导出按算式原样填写(此前只存数值,调整信息丢失)。"""
import hashlib
import sqlite3
import uuid
proj = "调整式工程-" + uuid.uuid4().hex[:6]
bills = [("010101001001", "挖单独土方", "1、x", "m3", 10000, 126.17)]
p = H.make_cos4(str(server["src_dir"] / ("expr_%s_raw.cos4" % proj[-6:])), proj, bills)
# 给夹具的定额工料机行补上换算算式(模拟广联达原生 Express)
z = _zipfile.ZipFile(p) if False else zipfile.ZipFile(p)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for nm in z.namelist():
d = z.read(nm)
if nm.lower() != "project.xml":
d = d.replace(b'Quantity="1.5"/>', b'Quantity="1.5" Express="1.5*1.2"/>')
d = d.replace(b'<Norm ', b'<Norm NormIdentity="TEST 1 2018" ')
zo.writestr(nm, d)
raw = buf.getvalue()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_expr.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
hc = sqlite3.connect(server["db"])
got = hc.execute("SELECT express FROM norm_res WHERE express IS NOT NULL").fetchall()
hc.close()
assert got and got[0][0] == "1.5*1.2", got[:3] # 导入捕获算式
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
"district": H.META["district"], "period_from": H.PERIOD_202607,
"period_to": H.PERIOD_202607, "file_kind": 1}
resp = post(server, "/api/audit", dict(audit, path=hp))
assert resp.get("session_id"), resp
sid = resp["session_id"]
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
bill_id = [r[0] for r in rows if r[1] == bills[0][0]][0]
src_id = sqlite3.connect(server["db"]).execute(
"SELECT id FROM bills WHERE Number=?", (bills[0][0],)).fetchone()[0]
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
"src_bill_id": src_id})
assert r["ok"] is True, r
se = sqlite3.connect(server["sessdb"])
got = se.execute("SELECT express FROM s_norm_res WHERE norm_id IN "
"(SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=1)", (bill_id,)).fetchall()
se.close()
assert got and got[0][0] == "1.5*1.2", got[:3] # 采纳携带
zf = _export_zip(server, sid)
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
if n.lower() != "project.xml")
import re as _re
mm = _re.search(r'<Norm Number="N-1".{0,600}?</Norm>', txt, _re.S)
print('ADOPTED NORM BLOCK:', mm.group(0)[:600] if mm else '(N-1 不在导出中)')
print('txt has N-1:', 'N-1' in txt, '| txt len:', len(txt))
assert 'Express="1.5*1.2"' in txt # 导出按历史调整式填写
def test_resource_pseudo_norm_skipped_on_import(server):
"""决策 106 补记十四:广联达把清单级资源构成行(人工费等,编码=纯数字工料机码、
单位=元)也写成 <Norm> 元素——不是定额,导入即滤掉(此前被采纳当定额带进
工作台=人工费外溢实测);真定额与调整记录不受影响。"""
import hashlib
import sqlite3
import uuid
proj = "伪定额过滤工程-" + uuid.uuid4().hex[:6]
bills = [("010101001001", "挖单独土方", "1、x", "m3", 10000, 126.17)]
p = H.make_cos4(str(server["src_dir"] / ("pseudo_%s_raw.cos4" % proj[-6:])), proj, bills)
z = zipfile.ZipFile(p)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for nm in z.namelist():
d = z.read(nm)
if nm.lower() != "project.xml":
pseudo = ('<Norm Number="00010010" Name="人工费" Unit="元" Quantity="89.1513"'
' Price="1.2" Total="106.98" IsNorm="true" Type="1" CalculationKind="1"'
' CostKind="1" EfficiencyKind="2" IncFeeKind="2" Specialty="1"'
' NormIdentity="TEST 1 2018" Remark=""/>').encode("utf-8")
d = d.replace(b'</Norm></WorkElement>', b'</Norm>' + pseudo + b'</WorkElement>')
zo.writestr(nm, d)
raw = buf.getvalue()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_pseudo.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
hc = sqlite3.connect(server["db"])
n = hc.execute("SELECT COUNT(*) FROM norms WHERE Number='00010010'").fetchone()[0]
hc.close()
assert n == 0, n # 伪定额不落批次库
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
"district": H.META["district"], "period_from": H.PERIOD_202607,
"period_to": H.PERIOD_202607, "file_kind": 1}
sid = post(server, "/api/audit", dict(audit, path=hp))["session_id"]
sc = sqlite3.connect(server["sessdb"])
n2 = sc.execute("SELECT COUNT(*) FROM s_norms WHERE Number='00010010'").fetchone()[0]
n3 = sc.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0]
sc.close()
assert n2 == 0 and n3 >= 1, (n2, n3) # 工作台也不出现(外溢源头掐断)
def test_edited_totals_follow_qty_times_price(server):
"""决策 106 补记十六(主人定):清单/定额 合价 = 工程量×单价——
改工程量后(工作台保存时 + 导出兜底)合价跟着走;数值相同不产生字节改动。"""
import hashlib
import sqlite3
import uuid
proj = "合价口径工程-" + uuid.uuid4().hex[:6]
bills = [("B001", "挖单独土方", "1、x", "m3", 10, 500)]
p = H.make_cos4(str(server["src_dir"] / ("total_%s_raw.cos4" % proj[-6:])), proj, bills)
raw = open(p, "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_total.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
"district": H.META["district"], "period_from": H.PERIOD_202607,
"period_to": H.PERIOD_202607, "file_kind": 1}
sid = post(server, "/api/audit", dict(audit, path=hp))["session_id"]
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
bill_id = [r[0] for r in rows if r[1] == "B001"][0]
norm_id = sqlite3.connect(server["sessdb"]).execute(
"SELECT id FROM s_norms WHERE bill_id=?", (bill_id,)).fetchone()[0]
# 改清单工程量 10→20:合价 = 20×500
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit",
"bill_id": bill_id, "fields": {"Quantity": "20"}})
assert r["ok"] is True, r
tb = sqlite3.connect(server["sessdb"]).execute(
"SELECT Total FROM s_bills WHERE id=?", (bill_id,)).fetchone()[0]
assert abs(tb - 10000) < 0.01, tb # 工作台保存即同步
# 改定额工程量 10→15(数字):合价 = 15×80
r = post(server, "/api/session/norm/op", {"session_id": sid, "norm_id": norm_id,
"fields": {"Quantity": "15"}})
assert r["ok"] is True, r
tn = sqlite3.connect(server["sessdb"]).execute(
"SELECT Total FROM s_norms WHERE id=?", (norm_id,)).fetchone()[0]
assert abs(tn - 1200) < 0.01, tn # 15×80
zf = _export_zip(server, sid)
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
if n.lower() != "project.xml")
assert 'Total="10000.0"' in txt, "清单合价应=20×500"
assert 'Total="1200.00"' in txt, "定额合价应=15×80"
def _export_zip(server, sid):
resp = server["client"].get("/api/session/export", params={"session_id": sid})
if not resp.headers["content-type"].startswith("application/zip"):

View File

@@ -951,8 +951,17 @@ document.addEventListener('dblclick', function(e){
editCell(td, api, id, field, (cur0==='—'?'':cur0));
});
function editCell(td, api, id, field, cur){
const inp = document.createElement('input');
// 项目特征是多行文本(fmtAttr 显示自带换行):input 会把换行整段剥掉,保存即黏团、
// 导出也无法按编号恢复(2026-10-18 主人实测「点了再导出排序就不行」)——Attr 用 textarea,
// 换行原样保存、导出原样回填;Enter=换行,Ctrl+Enter 或点开别处=保存。
const multi = (field === 'Attr');
const inp = document.createElement(multi ? 'textarea' : 'input');
inp.className = 'cellin'; inp.value = cur; inp.spellcheck = false;
if(multi){
inp.rows = Math.min(8, Math.max(3, cur.split('\n').length + 1));
inp.style.width = '100%'; inp.style.boxSizing = 'border-box';
inp.title = 'Enter 换行;Ctrl+Enter 或点其他位置保存';
}
td.textContent = ''; td.appendChild(inp);
inp.focus(); inp.select();
let done = false;
@@ -971,6 +980,7 @@ function editCell(td, api, id, field, cur){
await refreshRaw();
};
inp.addEventListener('keydown', ev=>{
if(multi && ev.key==='Enter' && !ev.ctrlKey){ return; } // 换行用,不保存
if(ev.key==='Enter'){ ev.preventDefault(); fin(true); }
else if(ev.key==='Escape'){ fin(false); }
});
@@ -1043,7 +1053,7 @@ function grpNormQtyEdit(td, tr, cur0){
if(!r.ok){ $('msg').textContent = r.msg || '保存失败'; td.textContent = cur0; return; }
// 决策 96:界面永远显示求值数字;公式原文收进 data-expr/悬停提示(双击再改还能取到)
td.textContent = r.quantity != null ? numG(r.quantity) : '—';
if(r.expr){ td.dataset.expr = r.expr; td.title = '公式:' + r.expr + '(按清单工程量求值,双击可改公式)'; }
if(r.expr){ td.dataset.expr = r.expr; td.title = '公式:' + r.expr + '(按清单工程量求值,双击再改还能取到)'; }
else { delete td.dataset.expr; td.removeAttribute('title'); }
$('msg').textContent = '已保存' + (r.quantity != null ? ':= ' + numG(r.quantity) : '');
loadEditLog().then(()=>{ markGroupEH('tb1'); markGroupEH('tb2'); }); // ⑮ 红三角即时点亮