feat(全链): 落实决策322-333——采纳落价Σ合价÷量、编制价三件套归一、块进块出、导出通用化只改导入、母随子动回算、台账分层留存

This commit is contained in:
lianjianwei2024
2026-11-14 23:40:41 +08:00
parent b05b34ffbf
commit b400454f74
12 changed files with 1572 additions and 384 deletions

View File

@@ -533,25 +533,58 @@ def qmap_mtime_of(sc):
return _qpath_mt(sc)[1]
def _propagate(base, kids):
def _propagate(base, kids, remap=None):
"""母子传导唯一实现:子量 = 母量 × 子含量,从直接消耗量快照出发只传一层
(决策 268补三 2026-11-04 主人定口径;子级自己带子级不二次传导)。"""
(决策 268补三 2026-11-04 主人定口径;子级自己带子级不二次传导)。
remap={旧码: 新码}(2026-11-14 决策 304 缺口修复):同码异物拆码迁移后,源件组成边
(uw_id=NULL 全项目一份)仍指向旧码——迁移桶里旧码已无行、行已迁新码,本桶传导目标
按 remap 重定向,消除「原码幽灵量」(显示端项目级=按行所在单位取量会漏它)。
无拆码项目 remap=None,行为与历史完全一致。"""
out = dict(base)
for mcode, mq in base.items():
if mq is None:
continue
for c, q, _nm in kids.get(mcode) or ():
tgt = (remap or {}).get(c, c)
try:
out[c] = out.get(c, 0.0) + float(mq) * float(q or 0)
out[tgt] = out.get(tgt, 0.0) + float(mq) * float(q or 0)
except (TypeError, ValueError):
pass
return out
def _split_remap_by_uw(sc, sid):
"""拆码重定向表 {uw_id: {旧码: 新码}}(2026-11-14 304 缺口修复配套)。
口径:登记簿 recode_ident 的每个 (旧码→新码) 身份包——旧码行所在单位集 U_old、
新码行所在单位集 U_new——U_new − U_old 中的单位 u:本桶传导目标 old→new
(该桶旧码已无行、实际行=新码)。无登记簿/无拆码→返回 {}。"""
try:
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k=?",
("session:%d" % sid, "recode_ident")).fetchone()
rec = __import__("json").loads(row[0] or "{}") if row and row[0] else {}
if not rec:
return {}
units = {}
for r in sc.execute("""SELECT code, uw_id FROM s_lme_uw
WHERE session_id=? AND uw_id IS NOT NULL AND code IS NOT NULL""",
(sid,)):
units.setdefault(r["code"], set()).add(r["uw_id"])
out = {}
for old, idents in rec.items():
u_old = units.get(old) or set()
for new in set(idents.values()):
for u in (units.get(new) or set()) - u_old:
out.setdefault(u, {})[old] = new
return out
except Exception:
return {}
def _qmap_build_all(sc, sid):
consume = _consumption_by_code(sc, sid, None, by_uw=True)
kids = _children_map(sc, sid)
return {u: _propagate(m, kids) for u, m in consume.items()}
remaps = _split_remap_by_uw(sc, sid)
return {u: _propagate(m, kids, remaps.get(u)) for u, m in consume.items()}
def qmap_all_cached(sc, sid):
@@ -587,7 +620,8 @@ def qmap_touch_uw(sc, sid, uw_id, pre_mt=None):
if ent is None:
return
try:
umap = _propagate(_consumption_by_code(sc, sid, uw_id), _children_map(sc, sid))
umap = _propagate(_consumption_by_code(sc, sid, uw_id), _children_map(sc, sid),
_split_remap_by_uw(sc, sid).get(uw_id))
except Exception:
with _QLOCK:
_QCACHE.pop(key, None)

View File

@@ -855,16 +855,32 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None):
return t + pre + region + post + close
def _norm_qty_total(blk, q, t):
"""Norm 开标签 Quantity/Total 回灌(统一函数,2026-11-07:原 _norm_out 与新增清单壳块
def _norm_qty_total(blk, q, t, pp=None, price_attrs=("Price",)):
"""Norm 开标签 Quantity/Total/Price 回灌(统一函数,2026-11-07:原 _norm_out 与新增清单壳块
通道各持一份同款正则,改口径漏一处即分叉——并轨)。q/t 传最终串(空串=清空);
块里没有该属性则不动(不凭空造槽)。"""
块里没有该属性则不动(不凭空造槽)。
决策322(2026-11-14 主人拍板例1「原后缀件定额单价随链写新值」):pp=库值单价串
(None=不碰);price_attrs=标签层适配(cos/ESCC=Price、SWT=Rate)。**值没变不写**
(最小差异,未动定额保持块原文一字不动;单价 2 位口径同 244 补六)。"""
if re.search(r'<Norm\b[^>]*?\sQuantity="', blk):
blk = re.sub(r'(<Norm\b[^>]*?)\sQuantity="[^"]*"',
lambda mo: mo.group(1) + ' Quantity="%s"' % q, blk, count=1)
if re.search(r'<Norm\b[^>]*?\sTotal="', blk):
blk = re.sub(r'(<Norm\b[^>]*?)\sTotal="[^"]*"',
lambda mo: mo.group(1) + ' Total="%s"' % t, blk, count=1)
if pp is not None:
for _a in price_attrs:
_m = re.search(r'<Norm\b[^>]*?\s%s="([^"]*)"' % _a, blk)
if _m is None:
continue
try:
_same = abs(float(_m.group(1) or 0) - float(pp or 0)) < 0.005
except (TypeError, ValueError):
_same = False
if not _same:
blk = re.sub(r'(<Norm\b[^>]*?)\s%s="[^"]*"' % _a,
lambda mo, _a=_a: mo.group(1) + ' %s="%s"' % (_a, pp), blk, count=1)
break
return blk
@@ -951,7 +967,7 @@ def _swt_rid_map(txt, s, end):
def _res_price_edits(txt, price_updates, *, price_attr, total_attr, code_attr="Code",
qty_attr="Quantity", fmt=None):
qty_attr="Quantity", fmt=None, base=0):
"""G-1 修(决策 288 补记十,落实决策 285「改价随链落汇总区、不留第二期」):
ESCC/SWT 的工料机汇总行(ResourceItem)价格回写——Code∈price_updates(改价/合并
已登记 merged_codes,与 cos 的 transform_unit_summaries 同一数据源)的行:
@@ -986,7 +1002,7 @@ def _res_price_edits(txt, price_updates, *, price_attr, total_attr, code_attr="C
except (TypeError, ValueError):
continue
if newtag != tag:
edits.append((m.start(), m.end(), newtag))
edits.append((base + m.start(), base + m.end(), newtag))
return edits
@@ -1014,9 +1030,13 @@ def _shell_out(b, shell, appends, res_by_norm, nn_tmpl=None, form_bank=None, anc
# cos 块是 Element@Number(决策 284:规则一份,标签每格式适配)
_tg, _ca = (("ResElementItem", "ResCode") if "<ResElementItem" in _nb
else ("LabourMaterialsEquipmentsMachinesElement", "Number"))
try:
_pp = _ru(float(nn.get("Price")), 2)
except (TypeError, ValueError):
_pp = ""
_norm_blks.append(_norm_qty_total(
_block_res_sync(_nb, res_by_norm.get(nn["id"]) or [], tag=_tg, code_attr=_ca),
_q, _tt))
_q, _tt, pp=_pp))
else:
_norm_blks.append(_norm_xml(nn, res_by_norm.get(nn["id"], []),
nn_tmpl or _largest_norm_block(shell) or _full_norm_template(shell),
@@ -1344,7 +1364,11 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
_tt = _ru(float(nn.get("Quantity") or 0) * float(nn.get("Price") or 0), 2)
except (TypeError, ValueError):
_tt = ""
return _norm_qty_total(_block_res_sync(_nb, res_by_norm.get(nn["id"]) or []), _q, _tt)
try:
_pp = _ru(float(nn.get("Price")), 2)
except (TypeError, ValueError):
_pp = ""
return _norm_qty_total(_block_res_sync(_nb, res_by_norm.get(nn["id"]) or []), _q, _tt, pp=_pp)
return _norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl, bill_qty=b["Quantity"], form_bank=form_bank)
body = "".join(_norm_out(nn) for nn in napp)
_ai = _line_indent(txt, mk["s"]) # 锚块自身缩进(插入块与它对齐)
@@ -1677,7 +1701,8 @@ def _lme_apply_price(newtag, px):
def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, recode_children=None,
field_updates=None, recode_ident=None, added_children=None, added_org=None,
keep_codes=None, merged_children=None, single_row_codes=None):
keep_codes=None, merged_children=None, single_row_codes=None,
db_price_updates=None):
"""本单位工程的工料机汇总 = 单价被查找的对象(主人口径 5.1/5.3):
①采纳新增的品类行追加到本单位汇总末尾(克隆完整属性集;带子级的整组内嵌,决策 204);
②合并改价按编码写回本单位汇总节点(除税/税率/含税,只动不一致项)——
@@ -1819,6 +1844,60 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
newtag = _attr_set(newtag, attr, v)
if newtag != start_tag:
edits[s0] = (s0, e0, newtag)
# 2026-11-14 主人定「导出和显示要一致」:父/母行价由 323 导入即回算改写库值,但导出只对
# merged_codes 走 price_updates → 未合并的母行仍写源样旧价(实测 99100011 库 20.16、导出 800.5)。
# 本通道按**本单位库值**补写显示端三价(除税/税率/含税):与源值数值相同不写(零漂移);
# 不改原价锚 _org、调价式、别名,也不进同名清扫(只改价,不删行/不重建子级)。
def _same_px(tag, px):
if not _num_eq(_attr(tag, "NoTaxPrice"), px.get("NoTaxPrice")):
return False
if not _num_eq(_attr(tag, "TaxPrice"), px.get("TaxPrice")):
return False
tr = px.get("TaxRate")
if tr is None or tr == "":
return not (_attr(tag, "TaxRate") or "").strip()
return _num_eq(_attr(tag, "TaxRate"), tr)
for code, px in (db_price_updates or {}).items():
if str(code) in {str(c) for c in (price_updates or {})}:
continue # 合并价通道优先(同源库值,保留 force 口径)
if px.get("NoTaxPrice") is None or px.get("TaxPrice") is None:
continue
for s0, e0, _bend, opentag in idx.get(str(code)) or ():
# 决策 324:拆码改印节点(foreign)也要吃库值——它是**另一种身份**,库价就是它的
# 显示价(178「不吃合并价」只限合并 force,不适用于库值回写);以改印后的标签为底。
_f = foreign.get(s0)
_cur = edits.get(s0)
if _f is not None:
start_tag, _s0, _e0 = _f[2], _f[0], _f[1]
elif _cur:
start_tag, _s0, _e0 = _cur[2], _cur[0], _cur[1]
else:
start_tag, _s0, _e0 = opentag, s0, e0
if _same_px(start_tag, px):
continue
newtag = start_tag
for attr in ("NoTaxPrice", "TaxRate", "TaxPrice"):
if attr in px and re.search(r'\b' + attr + r'="', newtag):
newtag = _attr_set(newtag, attr, px[attr])
if newtag != start_tag:
edits[s0] = (_s0, _e0, newtag)
# 拆码改印节点:源文件节点挂**旧码**,库行在**新码** → 上面按库码查 idx 查不到,
# 这里按改印后的 Number 反查库价补写(2026-11-14 T1 实测:99230021 等 5 行漏写)。
for s0, (fs, fe, ntag) in (foreign or {}).items():
_nc = _attr(ntag, "Number")
if not _nc or str(_nc) in {str(c) for c in (price_updates or {})}:
continue
_px = (db_price_updates or {}).get(str(_nc))
if not _px or _px.get("NoTaxPrice") is None or _px.get("TaxPrice") is None:
continue
if _same_px(ntag, _px):
continue
_nt = ntag
for attr in ("NoTaxPrice", "TaxRate", "TaxPrice"):
if attr in _px and re.search(r'\b' + attr + r'="', _nt):
_nt = _attr_set(_nt, attr, _px[attr])
if _nt != ntag:
edits[s0] = (fs, fe, _nt)
blocks = {} # span起点 → (s0, bend, 整块替换)(改码带子级重建)
_claimed = set() # 决策 184:换码占位(每保留码在本单位只占一条)
for old, new in (recode_map or {}).items():
@@ -2802,12 +2881,19 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd
# 决策 241:引用源改印前先记下本单位的「引用地也要跟着换的码」——
# 汇总行一旦改印,定额消耗行用原码就与之对不上(易达关联不到工料机)。
_unit_ident_re = _ident_element_recode(txt, recode_ident)
if upd or added_rows or field_updates or recode_map or recode_ident or merged_children or _single:
# 2026-11-14 主人定「导出和显示要一致」:本单位库值三价表(plan["px_updates"],
# api 层按 s_lme_uw 装入)→ 未合并的母/父行也写库值,不再背源样旧价。
# 同一 xml 多 UnitWorks 且同码异价时后段覆盖(cos4 一单位一文件,实测无此情形)。
_fpx = {}
for k in keys:
for _c2, _p2 in (unit_plans[k].get("px_updates") or {}).items():
_fpx[_c2] = _p2
if upd or added_rows or field_updates or recode_map or recode_ident or merged_children or _single or _fpx:
txt = transform_unit_summaries(txt, upd, added_rows, recode_map, recode_children,
field_updates=field_updates, recode_ident=recode_ident,
added_children=added_children, added_org=added_org,
keep_codes=keep_codes, merged_children=merged_children,
single_row_codes=_single)
single_row_codes=_single, db_price_updates=_fpx)
# 决策 188 数量模型:本单位的现算数量写回导出件(Project 聚合随之正确)——
# 放在 if 外:该单位即使没有其他编辑通道,数量也要按现算写(2026-10-24 实测漏)。
# 一个 xml 可能含多个 uw:各 uw 的数量图合并(同码相加)。
@@ -3078,9 +3164,13 @@ def _transform_esc_unit(txt, u, plan, res_by_norm, tmpls, edits):
_tt = _ru(float(nn.get("Quantity") or 0) * float(nn.get("Price") or 0), 2)
except (TypeError, ValueError):
_tt = ""
try:
_pp = _ru(float(nn.get("Price")), 2)
except (TypeError, ValueError):
_pp = ""
return _norm_qty_total(
_block_res_sync(_nb, res_by_norm.get(nn["id"]) or [],
tag="ResElementItem", code_attr="ResCode"), _q, _tt)
tag="ResElementItem", code_attr="ResCode"), _q, _tt, pp=_pp)
return _norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl,
bill_qty=b.get("Quantity"), form_bank=None)
body = "".join(_norm_out(nn) for nn in napp)
@@ -3196,15 +3286,19 @@ def _esc_ident_print(txt, units, unit_mig, recode_ident):
return edits
def _escc_added_lme_edits(txt, u, plan, added_children):
"""决策 292:ESCC 采纳新增工料机补源——单位 <Resources> 末尾补
def _escc_added_lme_edits(txt, u, plan, added_children, added_org=None):
"""决策 292:ESCC 采纳新增工料机补源——单位 <Resource> 末尾补
<ResourceItem Code ...>(与源同属性集);有子级时补 <ResElements>。
已有同码不重复补;无 <Resources>/模板则返回空,由导出完整性闸门拦截。"""
已有同码不重复补;无 <Resource>/模板则返回空,由导出完整性闸门拦截。
2026-11-14(330/331):容器以真实件为准 `<Resource>`(单数)——旧代码只找
`<Resources>`,真件恒不命中(added 通道空转);两种都认。added_org 补原价锚。"""
adds = [t for t in (plan.get("added_lme") or []) if t and t[0]]
if not adds:
return []
seg = txt[u["s"]:u["end"]]
close = seg.rfind("</Resources>")
if close < 0:
close = seg.rfind("</Resource>")
if close < 0:
return []
tm = re.search(r'<ResourceItem\b[^>]*>', seg)
@@ -3230,11 +3324,17 @@ def _escc_added_lme_edits(txt, u, plan, added_children):
pf = float(ntp or 0)
except (TypeError, ValueError):
pf = 0.0
_og = (added_org or {}).get(code) or ()
try:
_orgp = float(_og[0]) if _og and _og[0] is not None else pf
except (TypeError, ValueError):
_orgp = pf
tag = _attr_set_has(tmpl, "Code", code)
for k, v in (("Name", name), ("Specification", spec), ("Unit", unit),
("OrgPrice", "%.4f" % pf), ("Price", "%.4f" % pf),
("Quantity", "%.4f" % qf),
("OrgTotal", "%.2f" % (qf * pf)), ("Total", "%.2f" % (qf * pf)),
("OrgPrice", "%.4f" % _orgp), ("Price", "%.4f" % pf),
("Quantity", "%.4f" % qf), ("Quantity1", "%.4f" % qf),
("Quantity2", "0.0000"),
("OrgTotal", "%.2f" % (qf * _orgp)), ("Total", "%.2f" % (qf * pf)),
("Kind", "" if kind is None else str(kind))):
tag = _attr_set_has(tag, k, _esc(v))
if tag.rstrip().endswith("/>"):
@@ -3254,7 +3354,9 @@ def _escc_added_lme_edits(txt, u, plan, added_children):
def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
recode_ident=None, unit_mig=None, progress=None, price_updates=None,
added_children=None, merged_children=None):
added_children=None, merged_children=None, db_price_updates=None,
db_price_by_uw=None, added_org=None, field_updates=None,
recode_map=None, recode_children=None):
"""ESCC2.0 散装单文件 xml 导出(决策 283)。
unit_plans 键=(Number,Name)(与 cos 同构);unit_mig={(Number,Name):{旧码:新码}}——
api 侧从 s_lme_uw 现值推导(旧码不在且新码在=该单位整体迁移),归属与导入拆分一致。
@@ -3279,16 +3381,32 @@ def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
plan = unit_plans.get(u["key"])
if plan:
_transform_esc_unit(txt, u, plan, res_by_norm, tmpls, edits)
edits += _escc_added_lme_edits(txt, u, plan, added_children) # 决策 292
edits += _escc_added_lme_edits(txt, u, plan, added_children, added_org) # 决策 292
# 决策 331:三价按**单位级库值**写回本单位段(源件 ResourceItem 就在单位段内);
# 合并 force 优先,其余码用单位库值(值相同不写由 _res_price_edits 数值比较兜住)。
_up = dict(price_updates or {})
for _c, _p in ((db_price_by_uw or {}).get(u["key"]) or {}).items():
_up.setdefault(_c, _p)
if _up:
edits += _res_price_edits(txt[u["s"]:u["end"]], _up, price_attr="Price",
total_attr="Total", fmt=lambda v: "%.2f" % float(v),
base=u["s"])
if progress:
progress(i + 1, len(units))
edits += _esc_ident_print(txt, units, unit_mig or {}, recode_ident or {})
# G-1 修(补记十):工料机汇总行价格回写(决策 285 改价随链落汇总区)。
# ESCC 口径(1182 行导入口径反演):Price=除税现价(NoTaxPrice)、Total=量×价 2 位;
# OrgPrice/OrgTotal=原价锚不动。逐行编辑,不吞同段拆码改印小编辑。
edits += _res_price_edits(txt, price_updates or {}, price_attr="Price", total_attr="Total",
fmt=lambda v: "%.2f" % float(v))
if not edits:
# 2026-11-14 主人定「其余一个逻辑」:项目级 Resource(单位段外)用项目级库值兜底。
# 单位段内已由上面按单位级库值处理——这里必须**跳过单位段**,否则项目中位价会盖掉单位价。
if db_price_updates:
_urgs = [(x["s"], x["end"]) for x in units]
for _a, _b, _r in _res_price_edits(txt, db_price_updates, price_attr="Price",
total_attr="Total", fmt=lambda v: "%.2f" % float(v)):
if any(_s <= _a < _e for _s, _e in _urgs):
continue
edits.append((_a, _b, _r))
if not edits and not field_updates:
integrity.validate_escc(txt, where=out_name) # 决策 292:源样也过闸
return src_bytes, out_name # 无动作:字节级一模一样
# 应用(升序扫;同起点大块优先=整块替换/删除在前,落其内的小改写自然丢弃——同点插入按收集序)
@@ -3305,6 +3423,8 @@ def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
for _c, _kids in (merged_children or {}).items():
if _c and _kids:
_out_text = _escc_replace_children(_out_text, _c, _kids)
_out_text = _apply_res_fields(_out_text, field_updates, "Specification")
_out_text = _apply_res_recode_esc(_out_text, recode_map, recode_children)
integrity.validate_escc(_out_text, where=out_name) # 决策 292:成品引用完整性
return _encode(_out_text, enc), out_name
@@ -3340,8 +3460,8 @@ def _scan_swt_units(txt):
def _scan_swt_bills(txt, s, end):
"""单位内清单块。顺序=parse 推送序:先 BQItem(doc 序)后 MeasureItem 叶(doc 序)——
MeasureItem 父节点(内含子 MeasureItem)是分部,跳过。"""
"""单位内清单块:只有 <BQItem>(分部分项/措施同块、文档序)。
MeasureItem 是**不可编辑区域**(类似分部),不参与配对/整形(2026-11-14 主人定)。"""
marks = []
for m in re.finditer(r'<BQItem\b', txt[s:end]):
gs = s + m.start()
@@ -3355,20 +3475,6 @@ def _scan_swt_bills(txt, s, end):
if ce < 0 or ce + 9 > end:
continue
marks.append({"s": gs, "e": e, "end": ce + 9, "opentag": txt[gs:e], "kind": "item"})
for m in re.finditer(r'<MeasureItem\b', txt[s:end]):
gs = s + m.start()
e = _open_tag_end(txt, gs)
if e < 0 or e > end:
continue
if txt[e - 2:e] == "/>": # 自闭合=叶子清单(解析 start/end 立即配对=has_child False)
marks.append({"s": gs, "e": e, "end": e, "opentag": txt[gs:e], "kind": "prelim"})
continue
ce = txt.find('</MeasureItem>', e)
if ce < 0 or ce + 14 > end:
continue
if '<MeasureItem' in txt[e:ce]: # 真容器且内有子 MeasureItem=分部节点,不是清单
continue
marks.append({"s": gs, "e": e, "end": ce + 14, "opentag": txt[gs:e], "kind": "prelim"})
return marks
@@ -3423,8 +3529,13 @@ def _swt_norm_block_out(nn, res_by_norm, tmpl, rid_map=None):
_tt = _ru(float(nn.get("Quantity") or 0) * float(nn.get("Price") or 0), 2)
except (TypeError, ValueError):
_tt = ""
try:
_pp = _ru(float(nn.get("Price")), 2)
except (TypeError, ValueError):
_pp = ""
return _norm_qty_total(
_swt_usage_sync(_nb, res_by_norm.get(nn["id"]) or [], rid_map or {}), _q, _tt)
_swt_usage_sync(_nb, res_by_norm.get(nn["id"]) or [], rid_map or {}), _q, _tt,
pp=_pp, price_attrs=("Rate",))
if not tmpl:
return ""
ot = tmpl[:_open_tag_end(tmpl, 0)] if _open_tag_end(tmpl, 0) > 0 else tmpl
@@ -3622,32 +3733,56 @@ def _swt_recalc_unit(txt, u, plan, edits):
for sp, b in (plan.get("pairs") or {}).get(kind) or []:
src_pairs.append((kind, b))
src_pairs.sort(key=lambda x: x[1]["id"])
prelim_pairs = [b for kind, b in src_pairs if kind == "prelim"]
pm = [mk for mk in _scan_swt_bills(txt, u["s"], u["end"]) if mk["kind"] == "prelim"]
leaf_pos, leaf_val, leaf_nm = [], [], []
if len(prelim_pairs) == len(pm):
for b, mk in zip(prelim_pairs, pm):
leaf_pos.append(mk["s"])
leaf_val.append(0.0 if b["x_tdel"] else _tv(b["Total"]))
leaf_nm.append(_swt_name_norm(_attr(mk["opentag"], "Name")))
measure_total = sum(leaf_val)
by_name = dict(zip(leaf_nm, leaf_val))
for b in (plan.get("news") or {}).get("prelim") or []:
measure_total += _tv(b.get("Total"))
by_name[_swt_name_norm(b.get("Name"))] = _tv(b.get("Total"))
# 父级容器(真开闭且内含子 MeasureItem):Total=Σ内含叶现值
for m in re.finditer(r'<MeasureItem\b', txt[u["s"]:u["end"]]):
gs = u["s"] + m.start()
e = _open_tag_end(txt, gs)
if e < 0 or txt[e - 2:e] == "/>":
seg = txt[u["s"]:u["end"]]
# 措施:MeasureItem=**不可编辑区域**(类似分部,2026-11-14 主人定)——
# 叶子有 BQItem 子项 → Total=Σ子清单现值;无子项(费率型)→ 保源值;
# 父区域=Σ子区域;B 汇总=顶层区域合计。
newtot = {}
for kind, b in src_pairs:
if not b["x_tdel"]:
newtot[str(b.get("Number") or "")] = _tv(b["Total"])
for kind in ("item", "prelim"):
for b in (plan.get("news") or {}).get(kind) or []:
newtot[str(b.get("Number") or "")] = _tv(b.get("Total"))
nodes, stack = [], []
for m in re.finditer(r'<MeasureItem\b[^>]*>|</MeasureItem>', seg):
if m.group(0).startswith("</"):
if stack:
stack.pop()["end"] = u["s"] + m.start() + len("</MeasureItem>")
continue
ce = txt.find('</MeasureItem>', e)
if ce < 0 or '<MeasureItem' not in txt[e:ce]:
e = _open_tag_end(seg, m.start())
if e < 0:
continue
tot = sum(v for p0, v in zip(leaf_pos, leaf_val) if gs < p0 < ce)
ot = txt[gs:e]
if not _num_eq(_attr(ot, "Total"), tot):
edits.append((gs, e, _attr_set(ot, "Total", _swt_num(tot))))
node = {"s": u["s"] + m.start(), "e": u["s"] + e,
"ot": seg[m.start():e], "parent": stack[-1] if stack else None,
"kids": [], "end": u["s"] + len(seg)}
if node["parent"] is not None:
node["parent"]["kids"].append(node)
nodes.append(node)
stack.append(node)
def _mtot(node):
if node["kids"]:
return round(sum(_mtot(k) for k in node["kids"]), 2)
tot = None
for bm in re.finditer(r'<BQItem\b[^>]*>', txt[node["e"]:node["end"]]):
code = _attr(bm.group(0), "Code")
if code in newtot:
tot = (tot or 0.0) + newtot[code]
if tot is None:
tot = _tv(_attr(node["ot"], "Total"))
return round(tot, 2)
measure_total = 0.0
by_name = {}
for node in nodes:
val = _mtot(node)
if not _num_eq(_attr(node["ot"], "Total"), val):
edits.append((node["s"], node["e"],
_attr_set(node["ot"], "Total", _swt_num(val))))
if node["parent"] is None:
measure_total += val
by_name[_swt_name_norm(_attr(node["ot"], "Name"))] = val
bq_total = sum(_tv(b["Total"]) for kind, b in src_pairs
if kind == "item" and not b["x_tdel"])
for b in (plan.get("news") or {}).get("item") or []:
@@ -3728,8 +3863,178 @@ def _swt_ident_print(txt, units, unit_mig):
return edits
def _del_elem(txt, tag, attr, value):
"""删一个完整元素(自闭合或成对;ResourceItem/ResElement 不嵌套同名)。"""
pat = re.compile(r'<%s\b[^>]*\b%s="%s"[^>]*>' % (tag, attr, re.escape(str(value))))
while True:
m = pat.search(txt)
if not m:
return txt
end = m.end()
if not m.group(0).rstrip().endswith("/>"):
close = txt.find("</%s>" % tag, end)
if close < 0:
return txt
end = close + len("</%s>" % tag)
txt = txt[:m.start()] + txt[end:]
def _apply_res_recode_esc(txt, recode_map, recode_children=None):
"""ESCC 合并收码:消耗引用 ResCode 旧→保留,旧 ResourceItem 整行删除;
保留行子级按 recode_children 重建。"""
for old, keep in (recode_map or {}).items():
if not old or not keep or old == keep:
continue
txt = re.sub(r'(<ResElementItem\b[^>]*?\bResCode=")%s(")' % re.escape(str(old)),
lambda m: m.group(1) + str(keep) + m.group(2), txt)
txt = _del_elem(txt, "ResourceItem", "Code", old)
for old, kids in (recode_children or {}).items():
keep = (recode_map or {}).get(old)
if keep and kids:
txt = _escc_replace_children(txt, keep, kids)
return txt
def _swt_replace_children(txt, code, kids, code2rid):
"""SWT 保留码子级按库值整组重建:<ResourceUsage ResourceID=子码ID Usage=量>。
显示端无子级(kids 空)→ 剥子级,与显示端一致(同 cos/ESCC 口径)。"""
m = re.search(r'<ResourceItem\b[^>]*\bCode="%s"[^>]*>' % re.escape(str(code)), txt)
if not m:
return txt
open_end = m.end()
body = ""
for c, q in (kids or []):
rid = code2rid.get(str(c))
if rid is None:
continue
body += '<ResourceUsage ResourceID="%d" Usage="%s"/>' % (int(rid), _swt_num(q))
if m.group(0).rstrip().endswith("/>"):
new_open = m.group(0).rstrip()[:-2] + ">"
return txt[:m.start()] + new_open + body + "</ResourceItem>" + txt[open_end:]
close = txt.find("</ResourceItem>", open_end)
if close < 0:
return txt
return txt[:open_end] + body + txt[close:]
def _apply_res_recode_swt(txt, recode_map, rid_map=None, recode_children=None):
"""SWT 合并收码:ResourceID 旧→保留(消耗引用与组成引用一起转),旧 ResourceItem 删除。"""
code2rid = {}
for m in re.finditer(r'<ResourceItem\b[^>]*>', txt):
tag = m.group(0)
c, r = _attr(tag, "Code"), _attr(tag, "ResourceID")
if c and r and c not in code2rid:
try:
code2rid[c] = int(r)
except ValueError:
pass
for _c, _r in (rid_map or {}).items():
if _r is not None:
code2rid.setdefault(_c, int(_r))
for old, keep in (recode_map or {}).items():
if not old or not keep or old == keep:
continue
_or, _kr = code2rid.get(old), code2rid.get(keep)
if _or is not None and _kr is not None and _or != _kr:
txt = re.sub(r'(ResourceID=")%d(")' % _or,
lambda m: m.group(1) + str(_kr) + m.group(2), txt)
txt = _del_elem(txt, "ResourceItem", "Code", old)
for code, kids in (recode_children or {}).items():
if code in code2rid:
txt = _swt_replace_children(txt, code, kids, code2rid)
return txt
def _apply_res_fields(txt, field_updates, spec_attr="Specification"):
"""P1-③(2026-11-14):工料机名称/规格/单位行内编辑回写——只改登记过的码,
只在属性已存在时改(骨架无槽不造),不改编码。放在所有编辑拼装完之后做,
避免与同标签的价格/改印编辑抢 span。"""
if not field_updates:
return txt
def _rep(m):
tag = m.group(0)
code = _attr(tag, "Code")
if code not in field_updates:
return tag
nm, sp, un = field_updates[code]
new = tag
for attr, val in (("Name", nm), (spec_attr, sp), ("Unit", un)):
if val is not None and _attr(new, attr) is not None:
new = _attr_set(new, attr, _esc(val))
return new
return re.sub(r'<ResourceItem\b[^>]*>', _rep, txt)
def _swt_added_lme_edits(txt, units, unit_plans, added_children=None):
"""P1-②(2026-11-14 主人拍板 331/332):SWT 采纳新增工料机补源。
ResourceItem 容器可能在单位段内(`</Resource>`)也可能在根上(`</Resources>`);
这里按**全文件**补一次:所有单位 plan 的 added_lme 合并,码→资源ID 由 plan["rid_map"] 给。"""
adds, rid_map = [], {}
for _u in units:
_p = (unit_plans or {}).get(_u["key"]) or {}
rid_map.update(_p.get("rid_map") or {})
for t in (_p.get("added_lme") or []):
if t and t[0]:
adds.append(t)
if not adds:
return []
close = txt.rfind("</Resources>")
if close < 0:
close = txt.rfind("</Resource>")
if close < 0:
return []
tm = re.search(r'<ResourceItem\b[^>]*>', txt)
if not tm:
return []
tmpl = tm.group(0).strip()
have = set(re.findall(r'<ResourceItem\b[^>]*?\bCode="([^"]*)"', txt))
blocks, seen = [], set()
for t in adds:
code = str(t[0])
if code in have or code in seen:
continue
seen.add(code)
rid = rid_map.get(code)
if rid is None:
continue # 无 ID 补不了(应重导/重采纳)
try:
qf = float(t[4] or 0)
except (TypeError, ValueError):
qf = 0.0
rate = t[7] if len(t) > 7 and t[7] is not None else (t[6] if len(t) > 6 else None)
try:
rf = float(rate or 0)
except (TypeError, ValueError):
rf = 0.0
tag = _attr_set_has(tmpl, "ResourceID", str(int(rid)))
for k, v in (("Code", code), ("Name", t[1] if len(t) > 1 else ""),
("Spec", t[2] if len(t) > 2 else ""),
("Unit", t[3] if len(t) > 3 else ""),
("Rate", _swt_num(rf)), ("Quantity", "%.4f" % qf),
("Total", "%.2f" % (qf * rf)),
("CostKind", "" if t[8] is None else str(t[8])),
("StandardCode", code)):
tag = _attr_set_has(tag, k, _esc(v))
if tag.rstrip().endswith("/>"):
tag = tag.rstrip()[:-2] + ">"
kids = (added_children or {}).get(code) or []
body = ""
for c, q in kids:
cr = rid_map.get(str(c))
if not c or cr is None:
continue
body += '<ResourceUsage ResourceID="%d" Usage="%s"/>' % (int(cr), _swt_num(q))
tag = tag + body + "</ResourceItem>"
blocks.append(tag)
if not blocks:
return []
return [(close, close, "".join(blocks))]
def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
recode_ident=None, unit_mig=None, progress=None, price_updates=None):
recode_ident=None, unit_mig=None, progress=None, price_updates=None,
db_price_updates=None, db_price_by_uw=None, added_children=None,
field_updates=None, recode_map=None, recode_children=None):
"""SWT/SWZ 原格式导出(决策 284:并入手术引擎)。.SWZ=zip 包(内装 ConstructProject
xml)——解包手术该成员、其余条目字节原样回包。无动作且无拆码改印 → 原件字节直出。
price_updates=改价/合并码价表(决策 288 补记十 G-1 修:改价随链落 ResourceItem,
@@ -3770,15 +4075,30 @@ def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
_swt_recalc_unit(txt, u, plan, edits) # 汇总区一体(决策 285)
except Exception:
pass # 现算失败不挡导出(fail-open,原件汇总值保底)
# 决策 331:三价按单位级库值写回本单位段(ResourceItem 在 UnitProject 内)
_up = dict(price_updates or {})
for _c, _p in ((db_price_by_uw or {}).get(u["key"]) or {}).items():
_up.setdefault(_c, _p)
if _up:
edits += _res_price_edits(txt[u["s"]:u["end"]], _up, price_attr="Rate",
total_attr="Total", fmt=_swt_num, base=u["s"])
if progress:
progress(i + 1, len(units))
# P1-②:采纳新增工料机补 <ResourceItem>(块内 ResourceID 已在采纳时重分配)
edits += _swt_added_lme_edits(txt, units, unit_plans, added_children)
edits += _swt_ident_print(txt, units, unit_mig or {})
# G-1 修(补记十):工料机汇总行价格回写(决策 285 改价随链落汇总区)。
# SWT 口径A(122):Rate=含税=除税——改价的 taxp(空则 ntp)写回 Rate、Total=量×Rate。
# 逐行编辑,不吞同段拆码改印小编辑。
edits += _res_price_edits(txt, price_updates or {}, price_attr="Rate", total_attr="Total",
fmt=_swt_num)
if not edits:
# 逐行编辑,不吞同段拆码改印小编辑。项目级(单位段外)用项目级库值兜底(决策 331):
# 单位段内已按单位级库值处理,这里跳过单位段,防止项目值盖掉单位价。
if db_price_updates:
_urgs = [(x["s"], x["end"]) for x in units]
for _a, _b, _r in _res_price_edits(txt, db_price_updates, price_attr="Rate",
total_attr="Total", fmt=_swt_num):
if any(_s <= _a < _e for _s, _e in _urgs):
continue
edits.append((_a, _b, _r))
if not edits and not field_updates:
integrity.validate_swt(txt, where=out_name) # 决策 292
return src_bytes, out_name # 无动作:字节级一模一样
edits.sort(key=lambda x: (x[0], -(x[1] - x[0])))
@@ -3791,6 +4111,13 @@ def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
cursor = e0
out.append(txt[cursor:])
_swt_text = "".join(out)
_swt_text = _apply_res_fields(_swt_text, field_updates, "Spec")
_rid_all = {}
for _p in (unit_plans or {}).values():
for _c, _r in (_p.get("rid_map") or {}).items():
if _r is not None:
_rid_all.setdefault(_c, _r)
_swt_text = _apply_res_recode_swt(_swt_text, recode_map, _rid_all, recode_children)
integrity.validate_swt(_swt_text, where=out_name) # 决策 292
new_body = _encode(_swt_text, enc)
if not member:

View File

@@ -27,7 +27,7 @@ REGION = ("广东省", "珠海市", "香洲区")
# 改过滤规则、改层级记账方式、修了会导致旧数据错/缺的 bug),就把号往上加一位。
# 只改界面 / 只改查询,不动入库结构 —— 不用改号,否则会白白提示全库重导。
# 格式建议 YYYY.MM.DD-N(同一天多次改口径就 +1)。
PARSER_VER = "2026.11.12-1" # 2026.11.12-1:清单类别 x_cat 采集(cos=CalcType 原值,esc/swt 无标记=NULL;2026-11-12 主人定「按类别:清单」——直接条目也按清单归类,原值只留数据层;老会话重解析回填);2026.11.07-2:其他项目明细容器子树入库(detgrp/detitem+Content/x_parent/x_lv,其他项目卡把手展开用,2026-11-07 主人定「282 补」);2026.11.07-1:项目级「措施项目/其他项目」卡源数据入库(PIC.Preliminaries / PIC.Sundry 原样,老会话重解析后显示);2026.11.04-1:清单 x_ptag 采集(措施清单原生标签 WorkElement / UnitWorksPreliminaryWorkElement,导出按原形态还原;老批次需重导);-2026.11.03-4:项目级非数据层 x_side;-3:单位工程 x_attr;-2:清单/定额 x_side;-1:x_flags 补采 ProviderBase/Weight;2026.11.02-1:lme_uw 尾部追加 x_flags(决策 259)
PARSER_VER = "2026.11.14-1" # 2026.11.14-1:决策 329 三价归一(norm_price3,全格式)+ 决策 330 块标签 x_ptag 全格式采集(ESCC=Bill、SWT=BQItem/MeasureItem;取块不再回退 COS 标签);2026.11.12-1:清单类别 x_cat 采集(cos=CalcType 原值,esc/swt 无标记=NULL;2026-11-12 主人定「按类别:清单」——直接条目也按清单归类,原值只留数据层;老会话重解析回填);2026.11.07-2:其他项目明细容器子树入库(detgrp/detitem+Content/x_parent/x_lv,其他项目卡把手展开用,2026-11-07 主人定「282 补」);2026.11.07-1:项目级「措施项目/其他项目」卡源数据入库(PIC.Preliminaries / PIC.Sundry 原样,老会话重解析后显示);2026.11.04-1:清单 x_ptag 采集(措施清单原生标签 WorkElement / UnitWorksPreliminaryWorkElement,导出按原形态还原;老批次需重导);-2026.11.03-4:项目级非数据层 x_side;-3:单位工程 x_attr;-2:清单/定额 x_side;-1:x_flags 补采 ProviderBase/Weight;2026.11.02-1:lme_uw 尾部追加 x_flags(决策 259)
# LME_SUM 行的文字/标志属性集(2026-11-02 主人定「原文件有按原文件导,没有则不导出」):
# 数值属性(量/价/合价)另有专列,不在此列;Remark 属数据性质备注,一并按原文件采。
@@ -63,6 +63,34 @@ def f(x):
return None
def norm_price3(ntp, taxp, taxrate):
"""决策 329(2026-11-14 主人定):编制价三件套全后缀归一——任何格式恒有
除税编制价/含税编制价/税率,源件缺则:无税率→0、只有一侧价→另一侧=该价;
两价俱在且不等、税率缺 → 反算税率(保住源值,不硬抹平)。
返回 (ntp, taxp, taxrate);三值全缺 → (None, None, None)。"""
try:
ntp = None if ntp is None else float(ntp)
taxp = None if taxp is None else float(taxp)
tr = None if taxrate is None else float(taxrate)
except (TypeError, ValueError):
return (ntp, taxp, taxrate)
if ntp is None and taxp is None:
return (None, None, tr)
if tr is not None:
if ntp is None:
ntp = round(taxp / (1 + tr / 100.0), 4) if taxp is not None and tr != -100 else taxp
if taxp is None:
taxp = round(ntp * (1 + tr / 100.0), 4)
return (ntp, taxp, tr)
if ntp is None:
return (taxp, taxp, 0.0)
if taxp is None:
return (ntp, ntp, 0.0)
if abs(taxp - ntp) < 1e-9:
return (ntp, taxp, 0.0)
return (ntp, taxp, round((taxp / ntp - 1) * 100.0, 2) if ntp else 0.0)
def unit_prefix(unit):
"""定额单位的**数字前缀**('10m'→10.0、'1000m3天然密实方'→1000.0、't'→1.0)——
GCL(清单量÷前缀)与工程量系数(定额量÷历史GCL)共用的同一把尺
@@ -263,10 +291,24 @@ def _natkey(s):
# 只差标签层声明属性名;cos CalcType:"1"=清单、"3"=直接条目,两类都按清单归类显示)。
BLOCK_FMT = {
"cos": {"bills": ("WorkElement", "UnitWorksPreliminaryWorkElement"), "norm": "Norm",
"pseudo_norm": True, "order": "doc", "cat": "CalcType"},
"esc": {"bills": ("Bill",), "norm": "Norm", "pseudo_norm": False, "order": "doc"},
"pseudo_norm": True, "order": "doc", "cat": "CalcType", "id_attr": "Number"},
"esc": {"bills": ("Bill",), "norm": "Norm", "pseudo_norm": False, "order": "doc",
"id_attr": "Code"},
"swt": {"bills": ("BQItem", "MeasureItem"), "norm": "NormItem",
"pseudo_norm": False, "order": "swt_push"},
"pseudo_norm": False, "order": "swt_push", "id_attr": "Code"},
}
# 330:清单块/定额块标签与后缀族基本一一对应——优先按族**写死查表**,
# 只有老批次无 x_ptag 时才退到"全表逐族试"(不再用无约束的通用正则硬猜)。
_BLOCK_TAG_FMT = {t: k for k, cfg in BLOCK_FMT.items() for t in cfg["bills"]}
_BLOCK_OPEN = { # (tag, attr) 组合全表:Block 开标签 + 身份属性
"cos": [("WorkElement", "Number"), ("UnitWorksPreliminaryWorkElement", "Number")],
"esc": [("Bill", "Code")],
"swt": [("BQItem", "Code"), ("MeasureItem", "Code")],
}
_NORM_OPEN = {
"cos": [("Norm", "Number")],
"esc": [("Norm", "Code")],
"swt": [("NormItem", "Code")],
}
@@ -284,9 +326,8 @@ def extract_blocks(txt, fmt="cos"):
"""决策 279(块进块出)/ 285(一个整体一个逻辑):从 xml 原文切清单壳块/定额块原文——
**全格式同一份逻辑,格式只差 BLOCK_FMT 标签配置**(改这里=全格式生效)。
bills_blocks = [块原文...](壳块含定额段);norms_blocks = [块原文...]
对齐:块序=解析推送序——cos/ESCC=文档序;SWT=BQItem 见即推(键=自身位置)、
措施叶 MeasureItem 在所属 </MeasureTable> 处统一推(键=表尾,与 parse_swt 的
flush_measures 同款),父节点(块内还有子 MeasureItem=分部)不是清单不切。
对齐:块序=解析推送序——cos/ESCC=文档序;SWT=BQItem 文档序(措施区清单也是
BQItem;MeasureItem 是不可编辑区域/分部,不切块)。
cos 专属口径:伪定额(Number 纯数字且 Unit="元")不存,与 skip_res_norm 同口径。"""
cfg = BLOCK_FMT[fmt]
nt = cfg["norm"]
@@ -306,29 +347,17 @@ def extract_blocks(txt, fmt="cos"):
norms_blocks.append(txt[m.start():e + len(nt) + 3])
bills_blocks = []
if cfg["order"] == "swt_push":
keyed = [] # (推序键, 块起位, 标签)
# 2026-11-14 主人定:SWT 清单块只有 <BQItem>(分部分项/措施同块);MeasureItem 是
# 不可编辑区域(类似分部),不切块、不进 s_bills。块序=文档序=解析推送序。
for m in re.finditer(r'<BQItem\b[^>]*>', txt):
keyed.append((m.start(), m.start(), "BQItem"))
for m in re.finditer(r'<MeasureTable\b[^>]*>', txt):
te = txt.find('</MeasureTable>', m.end())
if te < 0:
te = len(txt)
for m2 in re.finditer(r'<MeasureItem\b[^>]*>', txt[m.end():te]):
keyed.append((te, m.end() + m2.start(), "MeasureItem"))
keyed.sort(key=lambda x: (x[0], x[1]))
for _k, gs, tag in keyed:
e = txt.find('>', gs)
if e < 0:
gs, e = m.start(), m.end()
if txt[e - 1] == "/": # 自闭合:块=开标签本身
bills_blocks.append(txt[gs:e])
continue
if txt[e - 1] == "/": # 自闭合:块=开标签本身(解析同样推送)
bills_blocks.append(txt[gs:e + 1])
continue
close = txt.find('</%s>' % tag, e)
close = txt.find('</BQItem>', e)
if close < 0:
continue
if tag == "MeasureItem" and '<MeasureItem' in txt[e:close]:
continue # 分部节点(一标签两用),不是清单
bills_blocks.append(txt[gs:close + len(tag) + 3])
bills_blocks.append(txt[gs:close + len('</BQItem>')])
else:
pat = "|".join(re.escape(t) for t in cfg["bills"])
for m in re.finditer(r'<(%s)\b[^>]*>' % pat, txt):
@@ -506,12 +535,16 @@ def parse_std(path, out):
_c = (sm.attrib.get("Number") or "").strip()
if not _c:
continue
# 决策 329:三价归一(COS 一般三价齐全;缺项按统一规则补,不按格式另写)
_pn, _pt, _pr = norm_price3(f(sm.attrib.get("NoTaxPrice")),
f(sm.attrib.get("TaxPrice")),
f(sm.attrib.get("TaxRate")))
out.setdefault("lme_lib", {}).setdefault(_c, [
(sm.attrib.get("Name") or "").strip(),
(sm.attrib.get("Specification") or "").strip(),
(sm.attrib.get("Unit") or "").strip(),
f(sm.attrib.get("Kind")),
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice"))])
_pn, _pt])
# 决策 69(批次C):lme_proj 增采 TaxRate——合并工料机弹框的「税率」字段要真值
# (此前认为源汇总节点无此属性,实测有:横琴 0、南屏 16.52 等都能采到)
out.setdefault("lme_proj", {}).setdefault(_c, [
@@ -520,8 +553,7 @@ def parse_std(path, out):
(sm.attrib.get("Unit") or "").strip(),
f(sm.attrib.get("Kind")),
f(sm.attrib.get("Quantity")),
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice")),
f(sm.attrib.get("TaxRate")),
_pn, _pt, _pr,
# 决策 183(2026-10-23 主人定):整套按骨架——六价全采,回填按属性一一对应
f(sm.attrib.get("NoTaxOrgPrice")), f(sm.attrib.get("NoTaxPriceExpress")),
f(sm.attrib.get("TaxOrgPrice")), f(sm.attrib.get("TaxPriceExpress"))])
@@ -846,10 +878,12 @@ def parse_std(path, out):
# 费用科目(折旧费 / 维护费 / 人工费…)2026-10-07 起也**照收入库**:
# 主人定「导入不过滤」,与工作台同口径,原 FEE_ITEMS 过滤随之废除
# (工作台「项目工料机」本就原样显示 s_lmes,含费用科目行——两侧恰好一致)。
_pn, _pt, _pr = norm_price3(f(a.get("NoTaxPrice")), f(a.get("TaxPrice")),
f(a.get("TaxRate"))) # 329:三价归一
out["lmes"].append((
a.get("Number", ""), a.get("Name", ""), a.get("Specification", ""),
a.get("Unit", ""), f(a.get("NoTaxPrice")), f(a.get("TaxRate")),
f(a.get("TaxPrice")), f(a.get("Quantity")), str(a.get("Kind") or "")))
a.get("Unit", ""), _pn, _pr, _pt,
f(a.get("Quantity")), str(a.get("Kind") or "")))
# 2026-10-11 决策 41:各单位工程**自己的汇总节点**按单位工程归属另存一份
# (cur_uw=本文件的单位工程,文件级已重置、UnitWorks start 即定——归属可靠),
# 「原数据·单位工程级工料机汇总」直接读它(名称/规格/总数量/单价=源文件原样,
@@ -858,8 +892,8 @@ def parse_std(path, out):
if _st:
out.setdefault("lme_uw", []).append((
_st[-1], a.get("Number", ""), a.get("Name", ""), a.get("Specification", ""),
a.get("Unit", ""), f(a.get("NoTaxPrice")), f(a.get("TaxRate")),
f(a.get("TaxPrice")), f(a.get("Quantity")), str(a.get("Kind") or ""),
a.get("Unit", ""), _pn, _pr, _pt,
f(a.get("Quantity")), str(a.get("Kind") or ""),
# 决策 183:六价全采(属性级对应回填)
f(a.get("NoTaxOrgPrice")), f(a.get("NoTaxPriceExpress")),
f(a.get("TaxOrgPrice")), f(a.get("TaxPriceExpress")),
@@ -945,22 +979,17 @@ def parse_swt(path, out):
return idx
def flush_measures():
# MeasureItem 既可分组也可叶子:有子项=分部(s_divides),无子项=措施清单(Kind='prelim')
# 2026-11-14 主人定:MeasureItem 是**不可编辑区域**(类似分部),不是清单——
# 措施区真正的清单是它里面/措施表里的 <BQItem>。MeasureItem 一律落 s_divides(prelim)。
for node in st["measure_nodes"]:
a = node["attrs"]
parent = node["parent"]["div"] if node["parent"] else node["title"]
if node["has_child"]:
node["div"] = add_divide("prelim", a.get("Code", ""), a.get("Name", ""),
f(a.get("Total")), None, parent)
else:
tot = f(a.get("Total"))
out["bills"].append((a.get("Code", ""), a.get("Name", ""),
a.get("Remark", "") or "", (a.get("Unit") or "").strip(),
1.0, tot, tot, (a.get("Remark") or "").strip()))
out.setdefault("bill_uw", []).append(st["unit"]["idx"] if st["unit"] else -1)
out.setdefault("bill_kind", []).append("prelim")
out.setdefault("bill_cat", []).append(_bill_cat(a, "swt")) # 清单类别(无标记=NULL)
out.setdefault("bill_div", []).append(parent)
node["div"] = add_divide("prelim", a.get("Code", ""), a.get("Name", ""),
f(a.get("Total")), None, parent)
# 措施里嵌的 BQItem 才是措施清单块;其归属分部在 flush 时才拿到,回填 bill_div
for _bi in node.get("bill_idx") or ():
if 0 <= _bi < len(out.get("bill_div") or []):
out["bill_div"][_bi] = node["div"]
st["measure_nodes"] = []
st["measure_stack"] = []
@@ -985,20 +1014,28 @@ def parse_swt(path, out):
qty = f(r.get("Quantity"))
# 主人定 A(2026-10-19,决策 122 恢复;覆盖决策 121 的 B):
# SWT 只有一个 Rate(不含税预算价)→ 除税价=含税价=Rate、税率=0。
out["lmes"].append((code, nm, sp, un, rate, 0.0, rate, qty, kd))
out["lme_uw"].append((u["idx"], code, nm, sp, un, rate, 0.0, rate, qty, kd,
# 决策 329:三价归一收口到 norm_price3(单侧价 → 两侧同值、税率 0)。
_pn, _pt, _pr = norm_price3(rate, None, None)
out["lmes"].append((code, nm, sp, un, _pn, _pr, _pt, qty, kd))
out["lme_uw"].append((u["idx"], code, nm, sp, un, _pn, _pr, _pt, qty, kd,
None, None, None, None)) # SWT 无六价源(决策 122:Rate 同值)
out["lme_lib"][code] = [nm, sp, un, kd, rate, rate]
# P1-②:源件资源内部 ID(NormResUsageItem@ResourceID 的落库槽,采纳/导出重分配用)
try:
_rid = int(str(r.get("ResourceID")).strip())
except (TypeError, ValueError):
_rid = None
out.setdefault("lme_uw_rid", []).append(_rid)
out["lme_lib"][code] = [nm, sp, un, kd, _pn, _pt]
out["lme_name"][code] = nm
p = out["lme_proj"].get(code)
if p is None:
out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, rate, rate, 0.0]
out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, _pn, _pt, _pr]
else:
p[4] = (p[4] or 0.0) + (qty or 0.0)
if rate is not None:
p[5] = rate # 除税价
p[6] = rate # 含税价(A:与除税价同值)
p[7] = 0.0 # 税率(A:0)
p[5] = _pn # 除税价
p[6] = _pt # 含税价(A:与除税价同值)
p[7] = _pr # 税率(A:0)
# 台班/配合比的下一级组成:同编码只收第一份(组成是标准值,各单位工程重复声明)
for r in u["resources"]:
pcode = (r.get("Code") or "").strip()
@@ -1100,15 +1137,22 @@ def parse_swt(path, out):
a.get("BQTitleID"), parent))
elif tag == "BQItem":
idx = len(out["bills"])
_in_meas = bool(st["measure_stack"]) # 措施区里嵌的 BQItem=措施清单(2026-11-14 主人示)
out["bills"].append((a.get("Code", ""), a.get("Name", ""),
a.get("Feature", ""), (a.get("Unit") or "").strip(),
f(a.get("Quantity")), f(a.get("Rate")),
f(a.get("Total")), (a.get("Remark") or "").strip()))
out.setdefault("bill_uw", []).append(st["unit"]["idx"] if st["unit"] else -1)
out.setdefault("bill_kind", []).append(None)
out.setdefault("bill_kind", []).append("prelim" if _in_meas else None)
out.setdefault("bill_cat", []).append(_bill_cat(a, "swt")) # 清单类别(无标记=NULL)
out.setdefault("bill_div", []).append(
st["title_stack"][-1] if st["title_stack"] else None)
out.setdefault("bill_tag", []).append("BQItem") # 330:原生块标签
out.setdefault("bill_div", []).append(None)
if _in_meas:
_node = st["measure_stack"][-1]
_node["has_child"] = True # 外层 MeasureItem 是容器,不是清单
_node.setdefault("bill_idx", []).append(idx)
else:
out["bill_div"][-1] = (st["title_stack"][-1] if st["title_stack"] else None)
st["cur_bill"] = idx
st["cur_norm"] = -1
elif tag == "NormItem":
@@ -1251,6 +1295,7 @@ def parse_esc(path, out):
out.setdefault("bill_uw", []).append(st["unit"]["idx"] if st["unit"] else -1)
out.setdefault("bill_kind", []).append(kind)
out.setdefault("bill_cat", []).append(_bill_cat(a, "esc")) # 清单类别(无标记=NULL)
out.setdefault("bill_tag", []).append("Bill") # 330:原生块标签
out.setdefault("bill_div", []).append(
(st["mdiv_stack"][-1] if st["mdiv_stack"] else None) if kind == "prelim"
else (st["div_stack"][-1] if st["div_stack"] else None))
@@ -1363,24 +1408,26 @@ def parse_esc(path, out):
qty = f(a.get("Quantity"))
nm, sp, un = (a.get("Name") or "").strip(), (a.get("Specification") or "").strip(), (a.get("Unit") or "").strip()
kd = (a.get("Kind") or "").strip() or None
out["lmes"].append((code, nm, sp, un, price, 0.0, price, qty, kd))
out["lme_uw"].append((st["unit"]["idx"], code, nm, sp, un, price, 0.0,
price, qty, kd, None, None, None, None))
_pn, _pt, _pr = norm_price3(price, None, None) # 329:单侧价→两侧同值、税率0
out["lmes"].append((code, nm, sp, un, _pn, _pr, _pt, qty, kd))
out["lme_uw"].append((st["unit"]["idx"], code, nm, sp, un, _pn, _pr,
_pt, qty, kd, None, None, None, None))
elif st["unit"] is None:
# 项目级 Resource 价格表 → lme_lib/lme_proj(决策 122 A:除税=含税=Price)
price, org = f(a.get("Price")), f(a.get("OrgPrice"))
qty = f(a.get("Quantity"))
nm, sp, un = (a.get("Name") or "").strip(), (a.get("Specification") or "").strip(), (a.get("Unit") or "").strip()
kd = (a.get("Kind") or "").strip() or None
_pn, _pt, _pr = norm_price3(price, None, None) # 329
out["lme_lib"].setdefault(code, [nm, sp, un, kd, org, price])
out["lme_name"].setdefault(code, nm)
p = out["lme_proj"].get(code)
if p is None:
out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, price, price, 0.0]
out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, _pn, _pt, _pr]
else:
p[4] = (p[4] or 0.0) + (qty or 0.0)
p[5] = price
p[6] = price
p[5] = _pn
p[6] = _pt
elif tag == "Resource":
st["_uw_res"] = st["unit"] is not None # 区分项目级/单位级 Resource 容器
elif tag == "Summary":
@@ -1548,29 +1595,44 @@ def _block_maps(out):
# 壳块标签与 x_ptag 一致、壳块有足够 Norm 槽(源有定额时)。
# ---------------------------------------------------------------------------
_SHA64_RE = re.compile(r'^([0-9a-f]{64})(?:_|$)')
_BLK_OPEN_RE = re.compile(
r'<(WorkElement|UnitWorksPreliminaryWorkElement)\b[^>]*?\bNumber="([^"]*)"', re.S)
_NORM_OPEN_RE = re.compile(r'<Norm\b[^>]*?\bNumber="([^"]*)"', re.S)
# 决策 330(2026-11-14):块/定额开标签按**块族**参数化,不再写死 COS 标签——
# cos=WorkElement/UnitWorksPreliminaryWorkElement+Number、ESCC=Bill+Code、
# SWT=BQItem/MeasureItem/NormItem+Code;取块只认块自己的标签(x_ptag 同源)。
def _sha_part(s):
m = _SHA64_RE.match((s or "").strip())
return m.group(1) if m else None
def block_open_number(xml):
"""块开标签 → (tag, Number);不是清单块 → (None, None)。"""
m = _BLK_OPEN_RE.search(xml or "")
return (m.group(1), m.group(2)) if m else (None, None)
def _open_id(xml, pairs):
"""按 (标签, 身份属性) 精确表取**块首**开标签与编码。
必须锚定开头(允许前导空白)——块内可能嵌同名子标签(如 MeasureItem 里嵌 BQItem),
全文 search 会把子标签当成块自身(实测 SWT (2.1) 被读成 BQItem)。"""
for tag, attr in pairs:
m = re.match(r'\s*<%s\b[^>]*?\b%s="([^"]*)"' % (re.escape(tag), attr),
xml or "", re.S)
if m:
return tag, m.group(1)
return None, None
def norm_open_number(xml):
m = _NORM_OPEN_RE.search(xml or "")
return m.group(1) if m else None
def block_open_number(xml, fmt=None):
"""块开标签 → (tag, 编码)。有族=按该族写死表;无族(老批次)=逐族试表。"""
pairs = (_BLOCK_OPEN.get(fmt) if fmt
else [p for v in _BLOCK_OPEN.values() for p in v])
return _open_id(xml, pairs or [])
def _block_norm_count(xml):
return len(re.findall(r'<Norm\b', xml or ""))
def norm_open_number(xml, fmt=None):
"""定额块开标签 → 编码。有族=该族 norm 标签+身份属性;无族=逐族试表。"""
pairs = (_NORM_OPEN.get(fmt) if fmt
else [p for v in _NORM_OPEN.values() for p in v])
return _open_id(xml, pairs or [])[1]
def _block_norm_count(xml, fmt=None):
if fmt:
return len(re.findall(r'<%s\b' % re.escape(BLOCK_FMT[fmt]["norm"]), xml or ""))
return len(re.findall(r'<Norm(?:Item)?\b', xml or ""))
def _sha_ok(block_sha, batch_sha):
@@ -1583,10 +1645,8 @@ def _sha_ok(block_sha, batch_sha):
def _bill_want_tag(number, x_ptag, kind):
if x_ptag:
return x_ptag
# 老批次没有 x_ptag:按 Kind 推断;推断只用于取块,不用于入库
return "UnitWorksPreliminaryWorkElement" if kind == "prelim" else "WorkElement"
"""决策 330:只认原生标签;无标签(老批次)返回 None,取块时以块自身标签兜底。"""
return x_ptag
def pick_bill_block(con, bill_id, want_number=None, want_tag=None, n_norms=None):
@@ -1603,13 +1663,18 @@ def pick_bill_block(con, bill_id, want_number=None, want_tag=None, n_norms=None)
ORDER BY bb.id DESC""", (bill_id,)).fetchall()
for r in rows:
num = want_number if want_number is not None else r[4]
# 330:标签只认原生 x_ptag;族由标签查表确定(无标签老批次才逐族试)
tag = want_tag if want_tag is not None else _bill_want_tag(r[4], r[5], r[6])
_fmt = _BLOCK_TAG_FMT.get(tag or "")
nn = n_norms if n_norms is not None else r[8]
xml = r[1] or ""
btag, bnum = block_open_number(xml)
if bnum != num or (tag and btag != tag):
btag, bnum = block_open_number(xml, _fmt)
if not btag:
continue # 不是可认的清单块
tag = tag or btag
if bnum != num or btag != tag:
continue
if nn and _block_norm_count(xml) == 0:
if nn and _block_norm_count(xml, _fmt) == 0:
continue
if not _sha_ok(r[2], r[7]):
continue
@@ -1621,7 +1686,7 @@ def pick_norm_block(con, norm_id, want_number=None):
"""取最新有效定额块(Number 与来源定额一致、同源哈希)。返回 dict 或 None。"""
rows = con.execute(
"""SELECT bb.id, bb.block_xml, bb.src_sha, bb.batch_id,
n.Number, COALESCE(bt.x_src_hash,'')
n.Number, COALESCE(bt.x_src_hash,''), b.x_ptag
FROM block_bank bb
JOIN norms n ON n.id=bb.norm_id
JOIN bills b ON b.id=n.bill_id
@@ -1630,7 +1695,8 @@ def pick_norm_block(con, norm_id, want_number=None):
ORDER BY bb.id DESC""", (norm_id,)).fetchall()
for r in rows:
num = want_number if want_number is not None else r[4]
if norm_open_number(r[1] or "") != num:
_fmt = _BLOCK_TAG_FMT.get(r[6] or "")
if norm_open_number(r[1] or "", _fmt) != num:
continue
if not _sha_ok(r[2], r[5]):
continue
@@ -1666,11 +1732,12 @@ def cleanup_block_bank(con):
continue
nn = con.execute("SELECT COUNT(*) FROM norms WHERE bill_id=?", (bill_id,)).fetchone()[0]
tag = _bill_want_tag(b[0], b[1], b[2])
_fmt = _BLOCK_TAG_FMT.get(tag or "")
keep = None
for rid, xml, sha in rows:
btag, bnum = block_open_number(xml or "")
if (bnum == b[0] and (not tag or btag == tag)
and (not nn or _block_norm_count(xml or "") > 0)
btag, bnum = block_open_number(xml or "", _fmt)
if (btag and bnum == b[0] and (not tag or btag == tag)
and (not nn or _block_norm_count(xml or "", _fmt) > 0)
and _sha_ok(sha, batch_sha.get(b[3], ""))):
keep = rid
break
@@ -1682,11 +1749,12 @@ def cleanup_block_bank(con):
if not n:
dead += [r[0] for r in rows]
continue
b = con.execute("SELECT batch_id FROM bills WHERE id=?", (n[1],)).fetchone()
b = con.execute("SELECT batch_id, x_ptag FROM bills WHERE id=?", (n[1],)).fetchone()
bsha = batch_sha.get(b[0], "") if b else ""
_fmt = _BLOCK_TAG_FMT.get((b[1] if b else "") or "")
keep = None
for rid, xml, sha in rows:
if norm_open_number(xml or "") == n[0] and _sha_ok(sha, bsha):
if norm_open_number(xml or "", _fmt) == n[0] and _sha_ok(sha, bsha):
keep = rid
break
dead += [rid for rid, _x, _s in rows if rid != keep]
@@ -1704,6 +1772,11 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
不传 = 新导入(INSERT 新批次行)。原位路径不动 x_note / x_enabled / x_attach_sha,
也不产生新 id —— sessions.x_batch_id 与 lme_attach 绑定才不至于断链(2026-10-11)
"""
# 2026-11-14 P1-②:老库补练——批库 lme_uw 加源件资源内部 ID 槽(SWT 用;幂等)
try:
con.execute("ALTER TABLE lme_uw ADD COLUMN x_rid INTEGER")
except Exception:
pass
# 决策 279:块序→块原文 映射(save 内 bills/norms 循环按下标取)
out["bill_blocks_map"], out["norm_blocks_map"] = _block_maps(out)
ym = int(time.strftime("%Y", time.localtime(mtime))) * 12 + int(time.strftime("%m", time.localtime(mtime)))
@@ -2034,25 +2107,81 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
# 各单位工程自己的工料机汇总(2026-10-11 决策 41):解析时按单位工程归属原样入库,
# 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。
n_uwlme = 0
for _row in (out.get("lme_uw") or []):
k, num, name, spec, unit, ntp, taxrate, taxp, qty, kind = _row[:10]
for _i, _row in enumerate(out.get("lme_uw") or []):
# 决策322 修(2026-11-14):循环变量原叫 kind——把外层批次参数 kind('project'/'market'/'info')
# 遮蔽成工料机种类整数,函数尾部按 kind 分支的代码(322 合计预存/锚列判定)恒走错。改名 _lkind。
k, num, name, spec, unit, ntp, taxrate, taxp, qty, _lkind = _row[:10]
_x = (list(_row[10:14]) + [None] * 4)[:4] # 决策 183:六价尾部扩展(老结构 len 兼容)
_rid = ((out.get("lme_uw_rid") or [])[_i]
if _i < len(out.get("lme_uw_rid") or []) else None)
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
if not uwid:
continue
try:
cur.execute("""INSERT INTO lme_uw(batch_id, uw_id, code, name, spec, unit, kind,
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, num, name, spec, unit, kind, qty, ntp, taxrate, taxp) + tuple(_x))
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_rid)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, num, name, spec, unit, _lkind, qty, ntp, taxrate, taxp)
+ tuple(_x) + (_rid,))
n_uwlme += 1
except Exception as e:
print("单位工程工料机汇总入库失败 %s:%s" % (num, e), flush=True)
if n_uwlme:
print("批次 %s 单位工程工料机汇总:%d 条" % (bid, n_uwlme), flush=True)
# 决策322(2026-11-14 主人拍板):定额双口径工料机合计预存 + 锚列统一判定(项目批次专属)
if kind == "project":
norm_lme_totals_fill(cur, bid)
price_basis_judge(cur, bid)
cur.execute("UPDATE batches SET x_rows_bill=?, x_rows_lme=? WHERE id=?", (n_bill, n_lme, bid))
return bid, n_bill, n_lme
# ---------- 决策322:定额工料机合计预存 + 锚列判定(2026-11-14 主人拍板②+统一自判) ----------
def norm_lme_totals_fill(cur, bid):
"""每条定额双口径工料机合计:Σ(norm_res.qty × lme_lib.ntp/taxp),一次 UPDATE 预存两列。
后台冻结源锚——导入算一次,此后永不回写;工作台改价/含量编辑只动会话侧 s_norms
(差额法见 api_server._norm_price_cascade),后台合计是「源定额工料机合计值」本体。
qty 取入库含量(不重求 express——与 dyn_lme 汇总数量现算同口径,同码同形);
lme_lib 是全集表(不去重不过滤),缺价行按 0 计(费用科目/影子行天然缺价)。"""
cur.execute("""UPDATE norms SET
x_lme_total_nt=(SELECT ROUND(SUM(COALESCE(nr.qty*lib.ntp,0)),6) FROM norm_res nr
LEFT JOIN lme_lib lib ON lib.batch_id=? AND lib.code=nr.res_code
WHERE nr.norm_id=norms.id),
x_lme_total_tx=(SELECT ROUND(SUM(COALESCE(nr.qty*lib.taxp,0)),6) FROM norm_res nr
LEFT JOIN lme_lib lib ON lib.batch_id=? AND lib.code=nr.res_code
WHERE nr.norm_id=norms.id)
WHERE bill_id IN (SELECT id FROM bills WHERE batch_id=?)""", (bid, bid, bid))
def price_basis_judge(cur, bid):
"""锚列统一判定(全格式一套程序,主人拍板「不按后缀写死、数据自判」):
抽样对账——定额单价=工料机合计+管理费利润,隐含费率必非负;锚列选错时
「合计>单价」大面积出现(实测 cos 负例 8%、cos4 23%,正口径 0~0.7%,信号极强)。
负例少者胜;有效样本不足 30 或两口径无区分度 → NULL(默认除税)。
结果存 batches.x_price_basis,采纳时随行带到 s_norms.x_price_basis。"""
r = cur.execute("""WITH s AS (SELECT Price p, x_lme_total_nt nt, x_lme_total_tx tx
FROM norms WHERE Price>0 AND COALESCE(x_lme_total_nt,0)>0
AND COALESCE(x_lme_total_tx,0)>0 LIMIT 400)
SELECT COUNT(*),
SUM(CASE WHEN p<nt-0.01 THEN 1 ELSE 0 END),
SUM(CASE WHEN p<tx-0.01 THEN 1 ELSE 0 END),
SUM(CASE WHEN ABS(nt-tx)>0.005 THEN 1 ELSE 0 END)
FROM s""").fetchone()
n, nt_neg, tx_neg, diff = (r[0] or 0), (r[1] or 0), (r[2] or 0), (r[3] or 0)
basis = None
if n >= 30 and diff > 0:
if nt_neg < tx_neg:
basis = "ntp"
elif tx_neg < nt_neg:
basis = "taxp"
cur.execute("UPDATE batches SET x_price_basis=? WHERE id=?", (basis, bid))
print("批次 %s 锚列判定:%s(样本 %d,除税负例 %d,含税负例 %d,有区分 %d)"
% (bid, basis or "存疑→默认除税", n, nt_neg, tx_neg, diff), flush=True)
return basis
# ---------- 主流程 ----------
def main():
# ⚠️ 2026-10-06 护栏:本入口连的是**生产库** data/history.db,且会全量清空重导。

View File

@@ -494,19 +494,9 @@ def connect_readonly():
return con
def connect():
# 决策 242(2026-10-30 主人定):写连接显式等锁 30 秒(默认 5 秒即抛
# "database is locked",台账删除实测撞过);会话库转 WAL(读写并行,与
# history.db 同款)。首切若有他连接占用则本次放弃、下次连接再切,不挡业务。
con = sqlite3.connect(DB, timeout=30.0)
con.row_factory = sqlite3.Row
con.execute("PRAGMA busy_timeout=30000")
try:
con.execute("PRAGMA journal_mode=WAL")
except Exception:
pass
con.executescript(io.open(SCHEMA, encoding="utf-8").read())
# 老库补列(已存在的列会报错,忽略)
def upgrade_cols(con):
"""老库补列(已存在的列报 duplicate column 忽略)。connect() 与 open_project
双入口共用——测试手建库/直连 open_project 的路径同样自愈(决策322 收口)。"""
# ⚠️ 每个表各补各的 —— 别把 A 表的列塞进 B 表的循环里,那会给 B 表凭空造出无用列
for tbl, cols in (
# 2026-10-06:x_batch_id = 后台批次 id(同一份源文件导入过就能关联上,
@@ -558,6 +548,11 @@ def connect():
# "1"=清单/"3"=直接条目;esc/swt 无标记=NULL;显示一律「清单」)
("s_bills", ("x_cat TEXT",)),
("s_norms", ("x_side TEXT",)),
# 决策322(2026-11-14 主人拍板):定额单价锚四列(差额法改价联动;老库补列后重开生效)
("s_norms", ("x_price_basis TEXT", "x_price_anchor REAL",
"x_total_anchor REAL", "x_lme_total REAL")),
# 2026-11-14 P1-②:源文件资源内部 ID(SWT 按 ResourceID 引用;cos/esc NULL)
("s_lme_uw", ("x_rid INTEGER",)),
# 2026-11-03:单位工程工程特征树(AttrInfo 原样,导出按数据循环)
("s_unit_works", ("x_attr TEXT",)),
# 2026-11-07 主人定「282 补」:项目级其他项目明细(detgrp/detitem 展开行)
@@ -582,6 +577,22 @@ def connect():
return con
def connect():
# 决策 242(2026-10-30 主人定):写连接显式等锁 30 秒(默认 5 秒即抛
# "database is locked",台账删除实测撞过);会话库转 WAL(读写并行,与
# history.db 同款)。首切若有他连接占用则本次放弃、下次连接再切,不挡业务。
con = sqlite3.connect(DB, timeout=30.0)
con.row_factory = sqlite3.Row
con.execute("PRAGMA busy_timeout=30000")
try:
con.execute("PRAGMA journal_mode=WAL")
except Exception:
pass
con.executescript(io.open(SCHEMA, encoding="utf-8").read())
upgrade_cols(con) # 老库补列(提取共用,open_project 同款)
return con
def open_project(con, files, meta, job, sid=None):
"""
files: [(path, name)] 一般一次一个
@@ -591,6 +602,7 @@ def open_project(con, files, meta, job, sid=None):
返回 session_id
"""
cur = con.cursor()
upgrade_cols(con) # 手建库/老库自愈(与 connect 同一份清单;幂等)
# 基准期次:起~止(单月时两者相同);兼容老参数 base_period_m
pf = meta.get("period_from")
pt = meta.get("period_to")
@@ -815,15 +827,32 @@ def open_project(con, files, meta, job, sid=None):
# 定额入库,同时记下真实 id —— 消耗量要靠它挂(norm_res 里存的是本文件内下标)
norm_ids = []
adj = out.get("norm_adj", {})
# 决策322(2026-11-14 主人拍板):会话自带定额同样落锚四列——锚价=源单价、
# 锚合计=Σ(含量×lme_lib 价)(与后台 norm_lme_totals_fill 同式同口径,缺价行计 0);
# 锚列默认 'ntp'除税(软件主键口径;后台批次判定结果随采纳链带下,原生行无批次链取默认)。
_nr_tot = {}
_lib322 = out.get("lme_lib") or {}
for _ni, _rc, _q, _e in (out.get("norm_res") or []):
_v = _lib322.get(_rc)
if not _v or _q is None:
continue
_t = _nr_tot.setdefault(_ni, [0.0, 0.0])
if _v[4] is not None:
_t[0] += _q * _v[4]
if len(_v) > 5 and _v[5] is not None:
_t[1] += _q * _v[5]
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
vals = adj.get(norm_idx, [])
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust, x_side)
VALUES(?,?,?,?,?,?,?,?,?)""",
_at = round(_nr_tot.get(norm_idx, [0.0, 0.0])[0], 6)
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust, x_side,
x_price_basis, x_price_anchor, x_total_anchor, x_lme_total)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, num, nm, unit, qty, price, total,
json.dumps(vals, ensure_ascii=False) if vals else None,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("norm_side") or {}).get(norm_idx))))
(out.get("norm_side") or {}).get(norm_idx)),
"ntp", price, _at, _at))
norm_ids.append(cur.lastrowid)
stat["norm"] += 1
@@ -861,16 +890,20 @@ def open_project(con, files, meta, job, sid=None):
# 2026-10-11 决策 41:各单位工程**自己的工料机汇总**按 uw 归属原样入库(s_lme_uw),
# 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。
for _row in (out.get("lme_uw") or []):
for _i, _row in enumerate(out.get("lme_uw") or []):
k, num, nm, spec, unit, ntp, tax, tp, qty, kind = _row[:10]
_x = (list(_row[10:14]) + [None] * 4)[:4] # 决策 183:六价尾部扩展(SWT/老结构为 None)
_flags = _row[14] if len(_row) > 14 else None # 决策 259:文字/标志属性 JSON(原文件有才导)
_rid = ((out.get("lme_uw_rid") or [])[_i]
if _i < len(out.get("lme_uw_rid") or []) else None)
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
if not uwid:
continue
cur.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind,
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp) + tuple(_x) + (_flags,))
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags, x_rid)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp) + tuple(_x)
+ (_flags, _rid))
# 2026-10-02:机械台班 / 配合比的下一级组成(s_lme_res)
_lname = out.get("lme_name") or {}