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"]: