chore: tk 全量提交(新增 formats 模块与界面体检测试包,更新核心/UI/测试/文档)
This commit is contained in:
7
CostReview/app/core/formats/__init__.py
Normal file
7
CostReview/app/core/formats/__init__.py
Normal file
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出格式适配器包:import 本包即完成各格式注册。"""
|
||||
from .registry import get_exporter
|
||||
|
||||
from . import swt # noqa: F401 (导入即注册 SWT/SWZ)
|
||||
|
||||
__all__ = ["get_exporter"]
|
||||
21
CostReview/app/core/formats/registry.py
Normal file
21
CostReview/app/core/formats/registry.py
Normal file
@@ -0,0 +1,21 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出格式注册表:按源文件后缀选「骨架/填空」适配器。
|
||||
|
||||
新格式接入 = 写一个 Exporter(提供 exts + export())并 register,
|
||||
api_server 不用改;COS4/.COS 仍走现有专用引擎(不在本表)。
|
||||
"""
|
||||
_EXPORTERS = []
|
||||
|
||||
|
||||
def register(exporter):
|
||||
_EXPORTERS.append(exporter)
|
||||
return exporter
|
||||
|
||||
|
||||
def get_exporter(src_name):
|
||||
"""按源文件名后缀找适配器(不分大小写);没有则返回 None(回落 COS 引擎)。"""
|
||||
low = (src_name or "").lower()
|
||||
for e in _EXPORTERS:
|
||||
if any(low.endswith(ext) for ext in e.exts):
|
||||
return e
|
||||
return None
|
||||
195
CostReview/app/core/formats/skeleton.py
Normal file
195
CostReview/app/core/formats/skeleton.py
Normal file
@@ -0,0 +1,195 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""骨架/填空导出的公共层:与格式无关的导出模型 + XML/zip 工具。
|
||||
|
||||
思路(2026-10-19 主人定):
|
||||
· **骨架** = 源文件里固定的开头/结尾/固定段(每个格式各准备一份/profile);
|
||||
· **填空** = 中间重复块(清单/定额/工料机/汇总)由本模块的导出模型统一供给;
|
||||
· 新格式只写一个 Exporter(标签名/容器定位/汇总公式),不复制取数逻辑。
|
||||
|
||||
导出模型直接读会话库:清单(含新增/临删/编辑)、定额(含采纳/临删)、
|
||||
定额消耗、单位工料机;格式适配器负责把这些值填回自己的骨架。
|
||||
"""
|
||||
import io
|
||||
import re
|
||||
import zipfile
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
import import_job as job
|
||||
|
||||
_QTY_EXPR_OK = re.compile(r"^[0-9+\-*/().\s]*$")
|
||||
|
||||
|
||||
def f(x):
|
||||
try:
|
||||
return float(x)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def num(v):
|
||||
"""SWT/XML 数字写法:整数不带小数点,其余最多 6 位(源文件规律)。"""
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
x = float(v)
|
||||
except Exception:
|
||||
return str(v)
|
||||
if abs(x - round(x)) < 1e-9:
|
||||
return str(int(round(x)))
|
||||
return ("%.6f" % x).rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def set_attr(el, name, val):
|
||||
if val is None:
|
||||
el.attrib.pop(name, None)
|
||||
else:
|
||||
el.attrib[name] = str(val)
|
||||
|
||||
|
||||
def max_id(elements, attr, start=0):
|
||||
n = start
|
||||
for e in elements:
|
||||
try:
|
||||
n = max(n, int((e.attrib.get(attr) or "0").strip() or 0))
|
||||
except Exception:
|
||||
pass
|
||||
return n
|
||||
|
||||
|
||||
def eval_qty(expr, bill_qty, norm_unit):
|
||||
"""GCL 公式求值(GCL=清单量÷定额单位数字前缀;纯数字四则也合法)。"""
|
||||
s = (expr or "").strip()
|
||||
for a, b in (("(", "("), (")", ")"), ("+", "+"), ("-", "-"), ("*", "*"),
|
||||
("×", "*"), ("÷", "/"), (",", ",")):
|
||||
s = s.replace(a, b)
|
||||
s = s.upper()
|
||||
if not _QTY_EXPR_OK.match(s.replace("GCL", "")):
|
||||
return None
|
||||
gcl = round((float(bill_qty) if bill_qty is not None else 0.0)
|
||||
/ job.unit_prefix(norm_unit), 6)
|
||||
try:
|
||||
v = float(eval(s, {"__builtins__": {}}, {"GCL": gcl}))
|
||||
except Exception:
|
||||
return None
|
||||
if v != v or v in (float("inf"), float("-inf")):
|
||||
return None
|
||||
return round(v, 6)
|
||||
|
||||
|
||||
def source_ext(src_name):
|
||||
m = re.search(r"(\.[A-Za-z0-9]+)$", (src_name or "").strip())
|
||||
return m.group(1) if m else ".swt"
|
||||
|
||||
|
||||
def build_plan(sc, sid):
|
||||
"""从会话库建一份格式无关的导出模型;返回 None=会话不存在。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return None
|
||||
sections = {}
|
||||
for r in sc.execute("SELECT * FROM s_sections WHERE session_id=?", (sid,)):
|
||||
sections[r["id"]] = {"id": r["id"], "number": r["Number"] or "",
|
||||
"name": r["Name"] or "", "total": r["Total"]}
|
||||
units = []
|
||||
for r in sc.execute("SELECT * FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,)):
|
||||
sec = sections.get(r["section_id"]) if r["section_id"] is not None else None
|
||||
units.append({"id": r["id"], "number": r["Number"] or "", "name": r["Name"] or "",
|
||||
"total": r["Total"], "section_number": (sec or {}).get("number", ""),
|
||||
"bills": [], "lme": []})
|
||||
uw_by_id = {u["id"]: u for u in units}
|
||||
divides = {}
|
||||
for r in sc.execute("SELECT * FROM s_divides WHERE session_id=?", (sid,)):
|
||||
divides[r["id"]] = {"id": r["id"], "uw_id": r["uw_id"], "parent_id": r["parent_id"],
|
||||
"kind": r["Kind"], "number": r["Number"] or "",
|
||||
"name": r["Name"] or "", "code": r["Code"] or ""}
|
||||
# 定额:先按 bill 归组,再挂到清单(含采纳/临删/公式求值)
|
||||
norms_by_bill, res_by_norm = {}, {}
|
||||
for r in sc.execute("""SELECT n.* FROM s_norms n
|
||||
JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=? ORDER BY n.id""", (sid,)):
|
||||
norms_by_bill.setdefault(r["bill_id"], []).append(dict(r))
|
||||
for r in sc.execute("""SELECT nr.* FROM s_norm_res nr
|
||||
JOIN s_norms n ON n.id=nr.norm_id
|
||||
JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=?""", (sid,)):
|
||||
res_by_norm.setdefault(r["norm_id"], []).append((r["res_code"], r["qty"]))
|
||||
for bill_id, ns in norms_by_bill.items():
|
||||
for n in ns:
|
||||
n["res"] = res_by_norm.get(n["id"], [])
|
||||
n["x_adopt"] = int(n.get("x_adopt") or 0)
|
||||
n["x_tdel"] = int(n.get("x_tdel") or 0)
|
||||
# 清单:x_seq 是单位工程内源序(导入时按原件顺序编号)
|
||||
for r in sc.execute("""SELECT * FROM s_bills WHERE session_id=?
|
||||
ORDER BY uw_id,
|
||||
CASE WHEN Kind='prelim' THEN 1 ELSE 0 END,
|
||||
CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (sid,)):
|
||||
b = dict(r)
|
||||
b["kind"] = "prelim" if r["Kind"] == "prelim" else "item"
|
||||
b["x_new"] = int(r["x_new"] or 0)
|
||||
b["x_tdel"] = int(r["x_tdel"] or 0)
|
||||
b["norms"] = norms_by_bill.get(r["id"], [])
|
||||
# 公式定额:按导出时的清单量求值(与 COS 导出同口径)
|
||||
for n in b["norms"]:
|
||||
if n.get("qty_expr"):
|
||||
q = eval_qty(n["qty_expr"], b["Quantity"], n["Unit"])
|
||||
if q is not None:
|
||||
n["Quantity"] = q
|
||||
if n["Quantity"] is not None and n["Price"] is not None:
|
||||
n["Total"] = round(float(n["Quantity"]) * float(n["Price"]), 2)
|
||||
if b["Quantity"] is not None and b["Price"] is not None:
|
||||
b["Total"] = round(float(b["Quantity"]) * float(b["Price"]), 2)
|
||||
u = uw_by_id.get(r["uw_id"])
|
||||
if u:
|
||||
u["bills"].append(b)
|
||||
for r in sc.execute("SELECT * FROM s_lme_uw WHERE session_id=? ORDER BY id", (sid,)):
|
||||
u = uw_by_id.get(r["uw_id"])
|
||||
if u:
|
||||
u["lme"].append(dict(r))
|
||||
lme_proj = {}
|
||||
for r in sc.execute("SELECT * FROM s_lme_proj WHERE session_id=?", (sid,)):
|
||||
lme_proj[r["code"]] = dict(r)
|
||||
return {"srow": srow, "sections": list(sections.values()), "units": units,
|
||||
"divides": divides, "lme_proj": lme_proj}
|
||||
|
||||
|
||||
def load_xml(src_bytes, root_tag="ConstructProject"):
|
||||
"""返回 (root, zip_member, 是否zip)。SWZ/SWT 都可能是裸 XML 或压缩包。"""
|
||||
if src_bytes[:2] == b"PK":
|
||||
z = zipfile.ZipFile(io.BytesIO(src_bytes))
|
||||
member = None
|
||||
for n in z.namelist():
|
||||
if not n.lower().endswith((".xml", ".swt", ".swz")):
|
||||
continue
|
||||
try:
|
||||
if ("<%s" % root_tag).encode() in z.read(n)[:16384]:
|
||||
member = n
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if not member:
|
||||
raise ValueError("压缩包里没有 %s XML" % root_tag)
|
||||
return ET.fromstring(z.read(member)), member, True
|
||||
return ET.fromstring(src_bytes), None, False
|
||||
|
||||
|
||||
def save_xml(root, src_bytes, member, is_zip):
|
||||
data = ET.tostring(root, encoding="utf-8", xml_declaration=True)
|
||||
if not is_zip:
|
||||
return data
|
||||
zin = zipfile.ZipFile(io.BytesIO(src_bytes))
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for item in zin.infolist():
|
||||
raw = zin.read(item.filename)
|
||||
if item.filename == member:
|
||||
raw = data
|
||||
zi = zipfile.ZipInfo(item.filename, date_time=item.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = item.external_attr
|
||||
zi.create_system = item.create_system
|
||||
try:
|
||||
zi.extra = item.extra
|
||||
except Exception:
|
||||
pass
|
||||
zo.writestr(zi, raw)
|
||||
return out.getvalue()
|
||||
466
CostReview/app/core/formats/swt.py
Normal file
466
CostReview/app/core/formats/swt.py
Normal file
@@ -0,0 +1,466 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SWT/SWZ(深圳市工程造价数据交换标准)的「骨架+填空」导出适配器。
|
||||
|
||||
骨架:源文件本身(ConstructProject/SingleProject/UnitProject/固定表);
|
||||
填空:BQItem/MeasureItem/NormItem/ResourceItem/SummaryItem 这些重复块按下表映射。
|
||||
|
||||
mapping(SWT → 会话库):
|
||||
BQItem.Code/Name/Feature/Unit/Quantity/Rate/Total/Remark
|
||||
NormItem.Code/Name/Unit/Quantity/Rate/Total
|
||||
ResourceItem.Code/Name/Spec/Unit/Rate/Quantity/CostKind
|
||||
SummaryItem CostCode A/B/C/D/E、B1(安全文明施工费)
|
||||
2026-10-19 主人定:税率 A —— ResourceItem 只有一个 Rate(不含税预算价),
|
||||
不写含税/税率字段(SWT 本来就没有这两列)。
|
||||
"""
|
||||
import copy
|
||||
import re
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
from .registry import register
|
||||
from .skeleton import (build_plan, f, load_xml, max_id, num, save_xml,
|
||||
set_attr, source_ext)
|
||||
|
||||
|
||||
def _name_norm(s):
|
||||
s = (s or "").strip()
|
||||
for a, b in (("(", "("), (")", ")"), (",", ","), (";", ";"), (" ", "")):
|
||||
s = s.replace(a, b)
|
||||
return s
|
||||
|
||||
|
||||
def _pick_largest(els, score):
|
||||
"""从源文件同类行里挑**最完整**的当模板(属性多、子结构全)。
|
||||
主人 2026-10-20:自动截取最大清单/定额/工料机骨架,按需要的值回填。"""
|
||||
return max(els, key=score) if els else None
|
||||
|
||||
|
||||
def _bill_score(el):
|
||||
norms = el.find("Norms")
|
||||
return (1 if norms is not None else 0,
|
||||
len(el.findall("BQPriceAnalysisItem")),
|
||||
len(norms.findall("NormItem")) if norms is not None else 0,
|
||||
len(list(el.iter("NormResUsageItem"))),
|
||||
len(el.attrib), sum(1 for _ in el))
|
||||
|
||||
|
||||
def _simple_score(el):
|
||||
return (len(el.attrib), sum(1 for _ in el), sum(1 for _ in el.iter()))
|
||||
|
||||
|
||||
class SWTExporter:
|
||||
exts = (".swt", ".swz")
|
||||
|
||||
# ---------------- 对外入口 ----------------
|
||||
def export(self, sc, sid, src_bytes, srow, progress=None):
|
||||
plan = build_plan(sc, sid)
|
||||
if plan is None:
|
||||
raise ValueError("会话不存在")
|
||||
root, member, is_zip = load_xml(src_bytes, "ConstructProject")
|
||||
self._apply(root, plan)
|
||||
data = save_xml(root, src_bytes, member, is_zip)
|
||||
ext = source_ext(srow["src_name"])
|
||||
name = ((srow["Name"] if "Name" in srow.keys() else srow["name"]) or "工程") + "-审核版" + ext
|
||||
if progress:
|
||||
progress(1, 1)
|
||||
return data, name
|
||||
|
||||
# ---------------- 主流程 ----------------
|
||||
def _apply(self, root, plan):
|
||||
src_units = root.findall(".//UnitProject")
|
||||
by_num, by_name = {}, {}
|
||||
for el in src_units:
|
||||
by_num.setdefault((el.get("ProjectID") or "").strip(), []).append(el)
|
||||
by_name.setdefault((el.get("Name") or "").strip(), []).append(el)
|
||||
# 2026-10-20 主人定:模板取**本项目范围内**最大最全的同类块(不是只看本单位)。
|
||||
all_bq = list(root.iter("BQItem"))
|
||||
all_ml = [e for e in root.iter("MeasureItem")
|
||||
if not any(c.tag == "MeasureItem" for c in e)]
|
||||
all_norm = list(root.iter("NormItem"))
|
||||
all_res = list(root.iter("ResourceItem"))
|
||||
res_by_kind = {}
|
||||
for x in all_res:
|
||||
k = (x.get("CostKind") or "").strip()
|
||||
if k not in res_by_kind or _simple_score(x) > _simple_score(res_by_kind[k]):
|
||||
res_by_kind[k] = x
|
||||
proj_tpl = {"item": _pick_largest(all_bq, _bill_score),
|
||||
"measure": _pick_largest(all_ml, _simple_score),
|
||||
"norm": _pick_largest(all_norm, _simple_score),
|
||||
"res": _pick_largest(all_res, _simple_score),
|
||||
"res_by_kind": res_by_kind}
|
||||
used = set()
|
||||
for u in plan["units"]:
|
||||
el = None
|
||||
for cand in by_num.get(u["number"], []):
|
||||
if id(cand) not in used:
|
||||
el = cand
|
||||
break
|
||||
if el is None:
|
||||
for cand in by_name.get(u["name"], []):
|
||||
if id(cand) not in used:
|
||||
el = cand
|
||||
break
|
||||
if el is None:
|
||||
continue # 新单位没有骨架:暂不生成(不在本轮范围)
|
||||
used.add(id(el))
|
||||
self._apply_unit(el, u, plan, proj_tpl)
|
||||
|
||||
# 单项工程 = 其下单位工程合计;TenderInfo = 各单项合计
|
||||
for sp in root.findall(".//SingleProject"):
|
||||
us = [u for u in sp.findall("UnitProject")]
|
||||
if us:
|
||||
set_attr(sp, "Total", num(sum(f(u.get("Total")) or 0 for u in us)))
|
||||
ti = root.find("TenderInfo")
|
||||
if ti is not None:
|
||||
sps = root.findall("SingleProject")
|
||||
if sps:
|
||||
set_attr(ti, "Total", num(sum(f(sp.get("Total")) or 0 for sp in sps)))
|
||||
|
||||
def _apply_unit(self, unit, u, plan, proj_tpl=None):
|
||||
proj_tpl = proj_tpl or {}
|
||||
parents = {c: p for p in unit.iter() for c in p}
|
||||
res_ctx = self._apply_resources(unit, u, plan, proj_tpl)
|
||||
item_els = list(unit.iter("BQItem"))
|
||||
measure_els = [e for e in unit.iter("MeasureItem")
|
||||
if not any(c.tag == "MeasureItem" for c in e)]
|
||||
state = {"item_pos": 0, "prelim_pos": 0,
|
||||
"item_tpl": proj_tpl.get("item") or _pick_largest(item_els, _bill_score),
|
||||
"measure_tpl": proj_tpl.get("measure") or _pick_largest(measure_els, _simple_score),
|
||||
"norm_tpl": proj_tpl.get("norm") or _pick_largest(list(unit.iter("NormItem")),
|
||||
_simple_score),
|
||||
"bq_id": max_id(unit.iter("BQItem"), "BQItemID"),
|
||||
"mi_id": max_id(unit.iter("MeasureItem"), "MeasureItemID"),
|
||||
"norm_id": max_id(unit.iter("NormItem"), "NormItemID")}
|
||||
for b in u["bills"]:
|
||||
if b["kind"] == "item":
|
||||
el = self._bill_slot(b, item_els, "item_pos", state)
|
||||
else:
|
||||
el = self._bill_slot(b, measure_els, "prelim_pos", state)
|
||||
if b["x_new"]:
|
||||
el = self._new_bill(unit, b, plan, state)
|
||||
elif el is None:
|
||||
continue
|
||||
elif b["x_tdel"]:
|
||||
if el in parents:
|
||||
parents[el].remove(el)
|
||||
el = None
|
||||
if el is None:
|
||||
continue
|
||||
self._fill_bill(el, b)
|
||||
self._apply_norms(el, b, unit, state, res_ctx, plan["lme_proj"])
|
||||
self._recalc_totals(unit)
|
||||
|
||||
def _bill_slot(self, b, els, key, state):
|
||||
if b["x_new"]:
|
||||
return None
|
||||
i = state[key]
|
||||
state[key] = i + 1
|
||||
return els[i] if i < len(els) else None
|
||||
|
||||
# ---------------- 工料机骨架 ----------------
|
||||
def _apply_resources(self, unit, u, plan, proj_tpl=None):
|
||||
res = unit.find("Resource")
|
||||
if res is None:
|
||||
res = ET.SubElement(unit, "Resource")
|
||||
items = list(res.findall("ResourceItem"))
|
||||
by_code = {(x.get("Code") or "").strip(): x for x in items}
|
||||
by_id = {(x.get("ResourceID") or "").strip(): x for x in items}
|
||||
# 项目范围内同类资源模板优先;本单位更大的同类行可以覆盖
|
||||
tpl_by_kind = dict((proj_tpl or {}).get("res_by_kind") or {})
|
||||
for x in items:
|
||||
k = (x.get("CostKind") or "").strip()
|
||||
if k not in tpl_by_kind or _simple_score(x) > _simple_score(tpl_by_kind[k]):
|
||||
tpl_by_kind[k] = x
|
||||
ctx = {"res": res, "items": items, "by_code": by_code, "by_id": by_id,
|
||||
"tpl": (proj_tpl or {}).get("res") or _pick_largest(items, _simple_score),
|
||||
"tpl_by_kind": tpl_by_kind,
|
||||
"next_id": max_id(items, "ResourceID") + 1}
|
||||
for row in u.get("lme") or []:
|
||||
code = (row.get("code") or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
el = by_code.get(code)
|
||||
if el is None:
|
||||
if not int(row.get("x_adopt_added") or 0):
|
||||
continue # 源里没有、也不是采纳新增:不硬造
|
||||
el = self._new_resource(ctx, code, row.get("kind"))
|
||||
by_code[code] = el
|
||||
for attr, key in (("Name", "name"), ("Spec", "spec"), ("Unit", "unit")):
|
||||
v = row.get(key)
|
||||
if v is not None and str(v).strip() != "":
|
||||
set_attr(el, attr, v)
|
||||
if row.get("ntp") is not None:
|
||||
set_attr(el, "Rate", num(row.get("ntp")))
|
||||
if row.get("qty") is not None:
|
||||
set_attr(el, "Quantity", num(row.get("qty")))
|
||||
if row.get("kind") is not None:
|
||||
set_attr(el, "CostKind", num(row.get("kind")))
|
||||
if row.get("ntp") is not None and row.get("qty") is not None:
|
||||
set_attr(el, "Total", num(round(float(row["qty"]) * float(row["ntp"]), 2)))
|
||||
by_id[(el.get("ResourceID") or "").strip()] = el
|
||||
return ctx
|
||||
|
||||
def _new_resource(self, ctx, code, kind=None):
|
||||
tpl = ctx["tpl_by_kind"].get(str(kind or "").strip()) or ctx["tpl"]
|
||||
el = copy.deepcopy(tpl) if tpl is not None else ET.Element("ResourceItem")
|
||||
for c in list(el):
|
||||
el.remove(c)
|
||||
rid = str(ctx["next_id"])
|
||||
ctx["next_id"] += 1
|
||||
set_attr(el, "ResourceID", rid)
|
||||
set_attr(el, "Code", code)
|
||||
set_attr(el, "StandardCode", code)
|
||||
set_attr(el, "Name", code)
|
||||
set_attr(el, "Spec", "")
|
||||
set_attr(el, "Unit", "")
|
||||
set_attr(el, "Rate", "")
|
||||
set_attr(el, "Quantity", "")
|
||||
ctx["res"].append(el)
|
||||
ctx["by_id"][rid] = el
|
||||
return el
|
||||
|
||||
def _ensure_resource(self, code, unit, res_ctx, lme_proj):
|
||||
code = (code or "").strip()
|
||||
if not code:
|
||||
return None
|
||||
el = res_ctx["by_code"].get(code)
|
||||
if el is not None:
|
||||
return (el.get("ResourceID") or "").strip()
|
||||
# 采纳消耗里引用了源 Resource 表没有的编码:按项目级/单位级数据补一条
|
||||
row = lme_proj.get(code) or {}
|
||||
el = self._new_resource(res_ctx, code, row.get("kind"))
|
||||
for attr, key in (("Name", "name"), ("Spec", "spec"), ("Unit", "unit")):
|
||||
v = row.get(key)
|
||||
if v is not None and str(v).strip() != "":
|
||||
set_attr(el, attr, v)
|
||||
if row.get("ntp") is not None:
|
||||
set_attr(el, "Rate", num(row.get("ntp")))
|
||||
if row.get("qty") is not None:
|
||||
set_attr(el, "Quantity", num(row.get("qty")))
|
||||
if row.get("kind") is not None:
|
||||
set_attr(el, "CostKind", num(row.get("kind")))
|
||||
if row.get("ntp") is not None and row.get("qty") is not None:
|
||||
set_attr(el, "Total", num(round(float(row["qty"]) * float(row["ntp"]), 2)))
|
||||
res_ctx["by_code"][code] = el
|
||||
rid = (el.get("ResourceID") or "").strip()
|
||||
res_ctx["by_id"][rid] = el
|
||||
return rid
|
||||
|
||||
# ---------------- 清单骨架 ----------------
|
||||
def _new_bill(self, unit, b, plan, state):
|
||||
if b["kind"] == "item":
|
||||
el = self._clone(state["item_tpl"], "BQItem")
|
||||
state["bq_id"] += 1
|
||||
set_attr(el, "BQItemID", state["bq_id"])
|
||||
container = self._item_container(unit, b, plan)
|
||||
else:
|
||||
el = self._clone(state["measure_tpl"], "MeasureItem")
|
||||
state["mi_id"] += 1
|
||||
set_attr(el, "MeasureItemID", state["mi_id"])
|
||||
container = self._measure_container(unit, b, plan)
|
||||
self._prepare_new_bill(el, b["kind"])
|
||||
if container is None:
|
||||
return None
|
||||
seq = sum(1 for c in container
|
||||
if c.tag == ("BQItem" if b["kind"] == "item" else "MeasureItem")) + 1
|
||||
set_attr(el, "Sequence", seq)
|
||||
container.append(el)
|
||||
return el
|
||||
|
||||
def _prepare_new_bill(self, el, kind):
|
||||
"""新增行只保留骨架结构:清单保留 Norms(空)和单价构成行(结果清零),
|
||||
其余模板数据删掉;措施叶子无子结构。"""
|
||||
if kind == "item":
|
||||
for c in list(el):
|
||||
if c.tag == "Norms":
|
||||
for n in list(c):
|
||||
c.remove(n)
|
||||
elif c.tag == "BQPriceAnalysisItem":
|
||||
set_attr(c, "Total", "0")
|
||||
else:
|
||||
el.remove(c)
|
||||
else:
|
||||
for c in list(el):
|
||||
el.remove(c)
|
||||
|
||||
def _clone(self, tpl, tag):
|
||||
if tpl is not None:
|
||||
return copy.deepcopy(tpl)
|
||||
return ET.Element(tag)
|
||||
|
||||
def _item_container(self, unit, b, plan):
|
||||
titles = list(unit.iter("BQTitle"))
|
||||
div = plan["divides"].get(b["div_id"]) if b["div_id"] is not None else None
|
||||
if div and div["kind"] == "item" and div["code"]:
|
||||
for t in titles:
|
||||
if (t.get("BQTitleID") or "").strip() == str(div["code"]).strip():
|
||||
return t
|
||||
return titles[0] if titles else unit.find("BQTable")
|
||||
|
||||
def _measure_container(self, unit, b, plan):
|
||||
div = plan["divides"].get(b["div_id"]) if b["div_id"] is not None else None
|
||||
titles = list(unit.iter("MeasureTitle"))
|
||||
if div and div["kind"] == "prelim":
|
||||
if div["code"]:
|
||||
for t in titles:
|
||||
if (t.get("MeasureTitleID") or "").strip() == str(div["code"]).strip():
|
||||
return t
|
||||
if div["number"]:
|
||||
for g in unit.iter("MeasureItem"):
|
||||
if (g.get("Code") or "").strip() == str(div["number"]).strip() \
|
||||
and any(c.tag == "MeasureItem" for c in g):
|
||||
return g
|
||||
return titles[0] if titles else unit.find("MeasureTable")
|
||||
|
||||
def _fill_bill(self, el, b):
|
||||
if b["x_new"]:
|
||||
# 新增行是从模板克隆的:模板里的旧编码/名称/单位/费用分析都不是这行的值,
|
||||
# 按骨架有的字段逐个写;骨架没有的(如单价为空)就保持为空,不拿旧值顶。
|
||||
set_attr(el, "Code", b.get("Number") or "")
|
||||
set_attr(el, "Name", b.get("Name") or "")
|
||||
set_attr(el, "Unit", b.get("Unit") or None)
|
||||
if b.get("src_remark") is not None:
|
||||
set_attr(el, "Remark", b.get("src_remark"))
|
||||
if b["kind"] == "item":
|
||||
set_attr(el, "Feature", b.get("Attr") or "")
|
||||
set_attr(el, "Quantity",
|
||||
num(b.get("Quantity")) if b.get("Quantity") is not None else "0")
|
||||
if b.get("Price") is not None:
|
||||
set_attr(el, "Rate", num(b.get("Price")))
|
||||
set_attr(el, "Total", num(b.get("Total")))
|
||||
else:
|
||||
set_attr(el, "Rate", None)
|
||||
set_attr(el, "Total", None)
|
||||
for attr in ("LaborRate", "MaterialRate", "MachineRate",
|
||||
"OverheadRate", "ProfitRate"):
|
||||
set_attr(el, attr, "0")
|
||||
else:
|
||||
set_attr(el, "Total",
|
||||
num(b.get("Total")) if b.get("Total") is not None else "0")
|
||||
return
|
||||
if b.get("Number") is not None:
|
||||
set_attr(el, "Code", b.get("Number"))
|
||||
for attr, key in (("Name", "Name"), ("Feature", "Attr"), ("Unit", "Unit")):
|
||||
v = b.get(key)
|
||||
if v is not None:
|
||||
set_attr(el, attr, v)
|
||||
if b.get("src_remark") is not None:
|
||||
set_attr(el, "Remark", b.get("src_remark"))
|
||||
if b["kind"] == "item":
|
||||
if b.get("Quantity") is not None:
|
||||
set_attr(el, "Quantity", num(b["Quantity"]))
|
||||
if b.get("Price") is not None:
|
||||
set_attr(el, "Rate", num(b["Price"]))
|
||||
set_attr(el, "Total", num(b.get("Total")))
|
||||
else:
|
||||
if b.get("Total") is not None:
|
||||
set_attr(el, "Total", num(b.get("Total")))
|
||||
|
||||
def _apply_norms(self, bill_el, b, unit, state, res_ctx, lme_proj=None):
|
||||
norms = b.get("norms") or []
|
||||
src = [n for n in norms if not n["x_adopt"]]
|
||||
add = [n for n in norms if n["x_adopt"] and not n["x_tdel"]]
|
||||
if not src and not add:
|
||||
return
|
||||
np = bill_el.find("Norms")
|
||||
if np is None:
|
||||
np = ET.SubElement(bill_el, "Norms")
|
||||
src_els = list(np.findall("NormItem"))
|
||||
for i, n in enumerate(src):
|
||||
if i >= len(src_els):
|
||||
continue
|
||||
el = src_els[i]
|
||||
if n["x_tdel"]:
|
||||
np.remove(el)
|
||||
continue
|
||||
for attr, key in (("Code", "Number"), ("Name", "Name"),
|
||||
("Unit", "Unit"), ("Quantity", "Quantity"),
|
||||
("Rate", "Price"), ("Total", "Total")):
|
||||
v = n.get(key)
|
||||
if v is not None:
|
||||
set_attr(el, attr, num(v) if key in ("Quantity", "Price", "Total") else v)
|
||||
for n in add:
|
||||
el = self._clone(state["norm_tpl"], "NormItem")
|
||||
for c in list(el):
|
||||
el.remove(c)
|
||||
state["norm_id"] += 1
|
||||
set_attr(el, "NormItemID", state["norm_id"])
|
||||
set_attr(el, "Code", n.get("Number") or "")
|
||||
set_attr(el, "StandardCode", n.get("Number") or "")
|
||||
for attr in ("LaborRate", "MaterialRate", "MachineRate",
|
||||
"OverheadRate", "ProfitRate"):
|
||||
set_attr(el, attr, "0")
|
||||
for attr, key in (("Code", "Number"), ("Name", "Name"),
|
||||
("Unit", "Unit"), ("Quantity", "Quantity"),
|
||||
("Rate", "Price"), ("Total", "Total")):
|
||||
v = n.get(key)
|
||||
if v is not None:
|
||||
set_attr(el, attr, num(v) if key in ("Quantity", "Price", "Total") else v)
|
||||
for code, q in n.get("res") or []:
|
||||
rid = self._ensure_resource(code, unit, res_ctx, lme_proj or {})
|
||||
if rid:
|
||||
ue = ET.SubElement(el, "NormResUsageItem")
|
||||
set_attr(ue, "ResourceID", rid)
|
||||
set_attr(ue, "Usage", num(q))
|
||||
np.append(el)
|
||||
|
||||
# ---------------- 汇总骨架 ----------------
|
||||
def _recalc_totals(self, unit):
|
||||
def recalc_measure(el):
|
||||
kids = [c for c in el if c.tag == "MeasureItem"]
|
||||
if kids:
|
||||
total = sum(recalc_measure(c) for c in kids)
|
||||
set_attr(el, "Total", num(total))
|
||||
return total
|
||||
return f(el.get("Total")) or 0.0
|
||||
|
||||
measure_total = 0.0
|
||||
measure_by_name = {}
|
||||
for title in unit.iter("MeasureTitle"):
|
||||
for m in title.findall("MeasureItem"):
|
||||
total = recalc_measure(m)
|
||||
measure_total += total
|
||||
measure_by_name[_name_norm(m.get("Name"))] = total
|
||||
for leaf in m.iter("MeasureItem"):
|
||||
measure_by_name[_name_norm(leaf.get("Name"))] = f(leaf.get("Total")) or 0.0
|
||||
bq_total = sum(f(x.get("Total")) or 0.0 for x in unit.iter("BQItem"))
|
||||
other = unit.find("OtherTable")
|
||||
other_total = sum(f(x.get("Total")) or 0.0 for x in other.findall("OtherItem")) \
|
||||
if other is not None else 0.0
|
||||
sm = unit.find("Summary")
|
||||
items = {}
|
||||
if sm is not None:
|
||||
for x in sm.iter("SummaryItem"):
|
||||
code = (x.get("CostCode") or "").strip()
|
||||
if code and code not in items:
|
||||
items[code] = x
|
||||
c2 = f(items["C2"].get("Total")) if "C2" in items else 0.0
|
||||
base = bq_total + measure_total + other_total - (c2 or 0.0)
|
||||
d0 = f(items["D"].get("Total")) if "D" in items else 0.0
|
||||
rate = f(items["D"].get("CostRate")) if "D" in items else None
|
||||
# 源文件没写税率时,用源 D/计费基数反推有效税率(不把已有税金抹成 0)
|
||||
if (rate is None or rate == 0) and base and d0:
|
||||
rate = d0 / base * 100.0
|
||||
rate = 0.0 if rate is None else rate
|
||||
d_total = round(base * rate / 100.0, 2)
|
||||
e_total = round(bq_total + measure_total + other_total + d_total, 2)
|
||||
for code, val in (("A", bq_total), ("B", measure_total), ("C", other_total),
|
||||
("D", d_total), ("E", e_total)):
|
||||
if code in items:
|
||||
set_attr(items[code], "Total", num(val))
|
||||
# 措施明细(B1/B11/B12/B13):按名称对到措施行,避免只改 B 不改明细
|
||||
if "B1" in items:
|
||||
for nm, val in measure_by_name.items():
|
||||
if "安全文明施工费" in nm:
|
||||
set_attr(items["B1"], "Total", num(val))
|
||||
break
|
||||
for code, needle in (("B11", "按费率计算"), ("B12", "按清单列项"),
|
||||
("B13", "产业工人职业训练")):
|
||||
if code in items:
|
||||
for nm, val in measure_by_name.items():
|
||||
if needle in nm:
|
||||
set_attr(items[code], "Total", num(val))
|
||||
break
|
||||
set_attr(unit, "Total", num(e_total))
|
||||
|
||||
|
||||
register(SWTExporter())
|
||||
Reference in New Issue
Block a user