chore(AdminCost): 移除 COS4 数据结构迁移的一次性脚本与参考资料
This commit is contained in:
@@ -84,6 +84,61 @@ def _fmt_qty(v, dec):
|
||||
return v
|
||||
|
||||
|
||||
def _apply_div_totals(txt, plans):
|
||||
"""决策 244 补五(2026-11-01 主人定「导出也按现算值,尽量按修改后的数据」):
|
||||
分部 Total / 费用表合计 / UnitWorks@Total 按 api 层现算值回填——
|
||||
plan["div_totals"] = {(Number,Name): [现算值…]} 同键按导入序排队、XML 按文档序消耗;
|
||||
plan["summary_updates"] = {属性: 新值}(Construction/Total 仅原件口径=QDF 时才有值)。
|
||||
分部配不上键的保持原件值(fail-open 不炸导出);SummaryOfCost / UnitWorks@Total
|
||||
仅单 uw 文件回填(归属明确,多 uw 文件不猜)。无 plan 键(旧调用方)→ 原样返回。"""
|
||||
if not plans:
|
||||
return txt
|
||||
starts = [m.start() for m in re.finditer(r'<UnitWorks\b', txt)]
|
||||
if not starts:
|
||||
return txt
|
||||
bounds = starts + [len(txt)]
|
||||
out = []
|
||||
pos = 0
|
||||
for i, s0 in enumerate(starts):
|
||||
e0 = bounds[i + 1]
|
||||
out.append(txt[pos:s0])
|
||||
seg = txt[s0:e0]
|
||||
m0 = re.match(r'<UnitWorks\b[^>]*>', txt[s0:])
|
||||
k = None
|
||||
if m0:
|
||||
k = ((_attr(m0.group(0), "Number") or ""), (_attr(m0.group(0), "Name") or ""))
|
||||
plan = plans.get(k) or (list(plans.values())[0] if len(plans) == 1 else None)
|
||||
if plan:
|
||||
queues = {kk: list(vv) for kk, vv in (plan.get("div_totals") or {}).items()}
|
||||
|
||||
def _sub_div(m):
|
||||
ot = m.group(0)
|
||||
q = queues.get(((_attr(ot, "Number") or ""), (_attr(ot, "Name") or "")))
|
||||
if not q:
|
||||
return ot
|
||||
return _attr_set(ot, "Total", _fmt_qty(q.pop(0), 2))
|
||||
|
||||
seg = re.sub(r'<(?:DivisionalWorks|PreliminaryDivisionalWorks)\b[^>]*>', _sub_div, seg)
|
||||
su = plan.get("summary_updates") or {}
|
||||
if su and len(plans) == 1:
|
||||
ms = re.search(r'<SummaryOfCost\b[^>]*>', seg)
|
||||
if ms:
|
||||
ot = ms.group(0)
|
||||
for _a, _v in su.items():
|
||||
if _a.startswith("_") or _v is None:
|
||||
continue
|
||||
ot = _attr_set(ot, _a, _fmt_qty(_v, 2))
|
||||
seg = seg[:ms.start()] + ot + seg[ms.end():]
|
||||
ut = su.get("_uw_total")
|
||||
if ut is not None and m0:
|
||||
ot = _attr_set(m0.group(0), "Total", _fmt_qty(ut, 2))
|
||||
seg = ot + seg[m0.end():]
|
||||
out.append(seg)
|
||||
pos = e0
|
||||
out.append(txt[pos:])
|
||||
return txt if not out else "".join(out)
|
||||
|
||||
|
||||
def _ws_eq(a, b):
|
||||
"""空白规范化比较:XML 解析器按规范把属性值里的换行/制表符规范化成空格——
|
||||
会话库里的项目特征是空格版、源文件是换行版,内容其实一致。
|
||||
@@ -427,9 +482,10 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None):
|
||||
if opentag:
|
||||
t = _clone_open_tag(opentag)
|
||||
t = _attr_set(t, "Number", b["Number"] or "") # 编码空=空("0"是数值占位,同 127 行口径)
|
||||
# 数据本体精度 6 位(3 位截断丢真值,231 补记二口径)
|
||||
for k, v in (("Name", b["Name"]), ("Quantity", _fmt_qty(b["Quantity"], 6)),
|
||||
("Price", b["Price"]), ("Total", b["Total"])):
|
||||
# 决策 244 补六(2026-11-01 主人定):清单数量 3 位、单价/合价 2 位(存储仍 6 位精度,
|
||||
# 231 补记二口径不变——只改导出格式)
|
||||
for k, v in (("Name", b["Name"]), ("Quantity", _fmt_qty(b["Quantity"], 3)),
|
||||
("Price", _fmt_qty(b["Price"], 2)), ("Total", _fmt_qty(b["Total"], 2))):
|
||||
t = _attr_set(t, k, "0" if v is None else v)
|
||||
if b["Unit"]:
|
||||
t = _attr_set(t, "Unit", b["Unit"])
|
||||
@@ -451,8 +507,8 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None):
|
||||
a += ' Unit="%s"' % _esc(b["Unit"])
|
||||
a += ' Quantity="%s" Price="%s" Total="%s"' % (
|
||||
_fmt_qty(b["Quantity"], 3) if b["Quantity"] is not None else 0,
|
||||
b["Price"] if b["Price"] is not None else 0,
|
||||
b["Total"] if b["Total"] is not None else 0)
|
||||
_fmt_qty(b["Price"], 2) if b["Price"] is not None else 0,
|
||||
_fmt_qty(b["Total"], 2) if b["Total"] is not None else 0)
|
||||
if b["src_remark"]:
|
||||
a += ' Remark="%s"' % _esc(b["src_remark"])
|
||||
t = "<" + tag + a + ">"
|
||||
@@ -625,6 +681,10 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
||||
continue # 会话没值的字段不回写(写 "None" 反而是破坏)
|
||||
if attr == "Quantity":
|
||||
want = _fmt_qty(want, 3) # 清单工程量按源文件规律 3 位小数导出
|
||||
elif attr in ("Price", "Total"):
|
||||
# 决策 244 补六(2026-11-01 主人定):清单单价/合价统一 2 位小数导出
|
||||
# (数值未变的行不重写,原件格式保持)
|
||||
want = _fmt_qty(want, 2)
|
||||
elif attr == "Attr":
|
||||
# 决策 100:特征换行恢复(库里的 \r 已在解析时被归一成空格)
|
||||
want = _restore_attr_breaks(txt, want)
|
||||
@@ -1850,6 +1910,9 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd
|
||||
qu[_c] = qu.get(_c, 0.0) + float(_q or 0)
|
||||
if qu:
|
||||
txt = _apply_qty_updates(txt, qu)
|
||||
# 决策 244 补五:分部 Total/费用表合计按现算回填(api 层算好随 plan 带入;
|
||||
# 旧调用方 plan 无此键 → 原样,fail-open)
|
||||
txt = _apply_div_totals(txt, {k: unit_plans[k] for k in keys})
|
||||
if recode_map: # 2026-10-22:定额消耗量行编码替换(Summary 块外)
|
||||
txt = _recode_norm_lme_rows(txt, recode_map)
|
||||
txt = _drop_zero_qty_summary_rows(txt) # 决策 199:单位级汇总 0 量行不导出
|
||||
|
||||
@@ -189,6 +189,20 @@ def parse_std(path, out):
|
||||
_f = out.setdefault("feat", [])
|
||||
if all(x[0] != _nm for x in _f) and len(_f) < 60:
|
||||
_f.append((_nm, e.attrib.get("Value") or ""))
|
||||
# 决策 244(2026-11-01):项目级「项目汇总分析」卡 = ProjectInstallationWorkCostSummary
|
||||
# 原样入库(r.iter() 即文档序:组先于其中行;层级=Number 前缀,前端归层)。
|
||||
for e in r.iter():
|
||||
if e.tag not in ("ProjectInstallationWorkCostSummaryGroup",
|
||||
"ProjectInstallationWorkCostSummaryItem"):
|
||||
continue
|
||||
out.setdefault("proj_summary", []).append({
|
||||
"kind": "grp" if e.tag.endswith("Group") else "item",
|
||||
"number": (e.attrib.get("Number") or "").strip() or None,
|
||||
"code": (e.attrib.get("Code") or "").strip() or None,
|
||||
"name": e.attrib.get("Name"), "formula": e.attrib.get("QtyFormula"),
|
||||
"rate": f(e.attrib.get("Rate")), "total": f(e.attrib.get("Total")),
|
||||
"ratios": f(e.attrib.get("Ratios")),
|
||||
"remark": (e.attrib.get("Remark") or "").strip()})
|
||||
# 2026-10-07:Project.xml 里还有一份**项目级完整工料机汇总**(横琴 730 条,含
|
||||
# 人工费等费用科目、-0001 换算编码)—— 这是消耗量编码反查名称的最全兜底,
|
||||
# 先收进来;各单位工程自己的汇总随后覆盖同编码(单位工程级更贴实际使用)。
|
||||
@@ -304,11 +318,56 @@ def parse_std(path, out):
|
||||
# 2026-10-01 加:专业(UnitWorks 元素的 Specialty 属性)——原数据要显示「专业」列。
|
||||
# 用独立字典存,不改 out["uw"] 的元组长度(多处按 (num,nm,total) 解包)。
|
||||
out.setdefault("uw_spec", {})[out["cur_uw"]] = el.attrib.get("Specialty")
|
||||
# 决策 244(2026-11-01):代号(Code,如 G130)/ 单位 / 建设规模——
|
||||
# 「汇总分析」三层树与「项目汇总分析」的单位行要用;Scale 逐单位重复存(源文件原样)。
|
||||
out.setdefault("uw_code", {})[out["cur_uw"]] = (el.attrib.get("Code") or "").strip() or None
|
||||
out.setdefault("uw_meta", {})[out["cur_uw"]] = (
|
||||
(el.attrib.get("Unit") or "").strip() or None, f(el.attrib.get("Scale")))
|
||||
# 用栈记 UnitWorks 层级:SummaryOfCost 归栈顶那个,嵌套时不会张冠李戴
|
||||
out.setdefault("uw_stack", []).append(len(out["uw"]) - 1)
|
||||
# 分部属于单位工程:换单位工程就把分部上下文清掉
|
||||
out["div_stack"] = []
|
||||
out["cur_div"] = None
|
||||
elif el.tag in ("UnitWorksSummaryGroup", "UnitWorksSummaryItem"):
|
||||
# 决策 244(2026-11-01):单位工程「汇总分析」卡 = UnitWorksSummary 原样入库。
|
||||
# 在 start 记账:文档序=组先于其中行(前端按 Number 前缀归层);属性在 start 完整。
|
||||
_st = out.get("uw_stack") or []
|
||||
if _st:
|
||||
out.setdefault("uw_summary", {}).setdefault(_st[-1], []).append({
|
||||
"kind": "grp" if el.tag.endswith("Group") else "item",
|
||||
"number": (el.attrib.get("Number") or "").strip() or None,
|
||||
"code": (el.attrib.get("Code") or "").strip() or None,
|
||||
"name": el.attrib.get("Name"), "formula": el.attrib.get("QtyFormula"),
|
||||
"rate": f(el.attrib.get("Rate")), "total": f(el.attrib.get("Total")),
|
||||
"remark": (el.attrib.get("Remark") or "").strip()})
|
||||
if (el.attrib.get("Code") or "").strip().upper() == "ZZJ":
|
||||
out.setdefault("uw_zzj", {})[_st[-1]] = f(el.attrib.get("Total"))
|
||||
elif el.tag == "SundryCosts" or el.tag == "SundryCostsItem":
|
||||
# 决策 244:单位工程「其他项目」卡 = Sundry 容器行(Kind='root')+
|
||||
# SundryCostsItem(Kind='item',Number 落库时按序补 1.1/1.2…)。
|
||||
# ⚠️ Project.xml 不走本循环(unit_files 排除),项目级同名节点不会混入。
|
||||
_st = out.get("uw_stack") or []
|
||||
if _st:
|
||||
_rows = out.setdefault("sundry", {}).setdefault(_st[-1], [])
|
||||
if el.tag == "SundryCosts":
|
||||
_rows.append({"kind": "root", "number": "1",
|
||||
"code": (el.attrib.get("Code") or "").strip() or None,
|
||||
"name": el.attrib.get("Name") or "其他项目", "unit": None,
|
||||
"quantity": None, "formula": None, "price": None,
|
||||
"rate": None, "total": f(el.attrib.get("Total")),
|
||||
"remark": (el.attrib.get("Remark") or "").strip()})
|
||||
else:
|
||||
_rows.append({"kind": "item",
|
||||
"number": (el.attrib.get("Number") or "").strip() or None,
|
||||
"code": (el.attrib.get("Code") or "").strip() or None,
|
||||
"name": el.attrib.get("Name"),
|
||||
"unit": (el.attrib.get("Unit") or "").strip() or None,
|
||||
"quantity": f(el.attrib.get("Quantity")),
|
||||
"formula": el.attrib.get("QtyFormula"),
|
||||
"price": f(el.attrib.get("Price")),
|
||||
"rate": f(el.attrib.get("Rate")),
|
||||
"total": f(el.attrib.get("Total")),
|
||||
"remark": (el.attrib.get("Remark") or "").strip()})
|
||||
elif el.tag == "WorkElement":
|
||||
_push_bill(el.attrib) # ★ 容器在 start 就记账
|
||||
out["cur_norm"] = -1 # 进清单:清掉定额上下文
|
||||
@@ -422,6 +481,8 @@ def parse_std(path, out):
|
||||
_c = out.setdefault("uw_cost", {})
|
||||
if _k not in _c:
|
||||
_c[_k] = _cost_of(a)
|
||||
# 决策 244:SummaryOfCost@Total(总造价)——ztotal 的中间回退值
|
||||
_c[_k]["_sc_total"] = f(a.get("Total"))
|
||||
elif tag == "UnitWorks":
|
||||
_st = out.get("uw_stack") or []
|
||||
if _st:
|
||||
@@ -881,16 +942,48 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
||||
uw_ids = []
|
||||
for i, (num, nm, total) in enumerate(out["uw"]):
|
||||
c = (out.get("uw_cost") or {}).get(i) or {}
|
||||
# 决策 244:总造价 ztotal = UnitWorksSummary 的 ZZJ 行 → SummaryOfCost@Total → UnitWorks@Total
|
||||
_z = (out.get("uw_zzj") or {}).get(i)
|
||||
if _z is None:
|
||||
_z = c.get("_sc_total")
|
||||
_um = (out.get("uw_meta") or {}).get(i) or (None, None)
|
||||
cur.execute("""INSERT INTO unit_works(batch_id, section_id, Number, Name, Specialty, Total,
|
||||
Construction, DivisionalAndElementalWorks, Preliminaries,
|
||||
CostForHSE, SundryCosts, Tax)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
CostForHSE, SundryCosts, Tax, Code, Unit, Scale, ztotal)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(bid, num2sec.get(num), num, nm, (out.get("uw_spec") or {}).get(i),
|
||||
total, c.get("Construction"),
|
||||
c.get("DivisionalAndElementalWorks"), c.get("Preliminaries"),
|
||||
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax")))
|
||||
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax"),
|
||||
(out.get("uw_code") or {}).get(i), _um[0], _um[1],
|
||||
_z if _z is not None else total))
|
||||
uw_ids.append(cur.lastrowid)
|
||||
|
||||
# 决策 244:单位工程「汇总分析」/「其他项目」两卡源数据原样入库(老格式无这些键 → 空转)
|
||||
for _i, _uid in enumerate(uw_ids):
|
||||
for _r in (out.get("uw_summary") or {}).get(_i) or []:
|
||||
cur.execute("""INSERT INTO uw_summary(batch_id, uw_id, Kind, Number, Code, Name,
|
||||
Formula, Rate, Total, Remark) VALUES(?,?,?,?,?,?,?,?,?,?)""",
|
||||
(bid, _uid, _r["kind"], _r["number"], _r["code"], _r["name"],
|
||||
_r["formula"], _r["rate"], _r["total"], _r["remark"]))
|
||||
_sn = 0
|
||||
for _r in (out.get("sundry") or {}).get(_i) or []:
|
||||
if _r["kind"] == "item" and not _r["number"]:
|
||||
_sn += 1
|
||||
_r = dict(_r, number="1.%d" % _sn)
|
||||
cur.execute("""INSERT INTO sundry_items(batch_id, uw_id, Kind, Number, Code, Name, Unit,
|
||||
Quantity, Formula, Price, Rate, Total, Remark)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(bid, _uid, _r["kind"], _r["number"], _r["code"], _r["name"], _r["unit"],
|
||||
_r["quantity"], _r["formula"], _r["price"], _r["rate"], _r["total"],
|
||||
_r["remark"]))
|
||||
# 决策 244:项目级「项目汇总分析」卡源数据原样入库
|
||||
for _r in (out.get("proj_summary") or []):
|
||||
cur.execute("""INSERT INTO proj_summary(batch_id, Kind, Number, Code, Name,
|
||||
Formula, Rate, Total, Ratios, Remark) VALUES(?,?,?,?,?,?,?,?,?,?)""",
|
||||
(bid, _r["kind"], _r["number"], _r["code"], _r["name"], _r["formula"],
|
||||
_r["rate"], _r["total"], _r["ratios"], _r["remark"]))
|
||||
|
||||
# 分部(必须排在清单之前:清单要挂 div_id)
|
||||
div_ids = []
|
||||
for dv_ in (out.get("divides") or []):
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
切出的行编号原样保留(与既有 fmtAttr 显示口径一致,共用层不动)。
|
||||
5. 写库走会话库既有表(s_sections/s_unit_works/s_divides/s_bills),列清单与
|
||||
session_job.open_project 完全同款 —— rawDraw/四页签/汇总分析/取价链零改动。
|
||||
手工工程沿用决策 119 框架:x_manual=1、src_name=''、禁原格式导出/重解析、
|
||||
同名源文件补传恢复(补传后本模块不再接管该会话)。
|
||||
手工工程沿用决策 119 框架:x_manual=1、src_name=''、禁原格式导出/重解析
|
||||
(决策 242:同名一律拒绝导入,原「同名源文件补传恢复」通道随之退役)。
|
||||
"""
|
||||
import hashlib
|
||||
import re
|
||||
@@ -429,7 +429,7 @@ def template_project_bytes():
|
||||
("三、其他", True),
|
||||
(" 1. 只填到清单级:不导定额、不导工料机;合价=工程量×单价由软件现算。", False),
|
||||
(" 2. 必填:目录三列;数据行 类型、名称;清单行 单位、工程量(数字)、单价(数字)。", False),
|
||||
(" 3. 导入即创建整项目(目录树+清单一次到位);同名手工工程再次导入=整项目覆盖。", False),
|
||||
(" 3. 导入即创建整项目(目录树+清单一次到位);与最近审核同名会被拒绝,请改名后再导。", False),
|
||||
(" 4. 单位工程旧模板(只有 分部分项/措施项目 两个 Sheet、无项目目录)仍可在目录树行内导入,不受影响。", False),
|
||||
], 1):
|
||||
c = ws0.cell(row=i, column=1, value=t)
|
||||
@@ -500,7 +500,7 @@ def template_project_bytes():
|
||||
def import_project(con, body):
|
||||
"""决策 238:整项目一把导入——「项目目录」+多对 Sheet → 建手工工程(目录树+清单)。
|
||||
body = {path, name, period_from, period_to, province?/city?/district?/bulid_unit?}
|
||||
同名手工工程再次导入=整项目覆盖(save_tree 同名续用 + 无 id 全删重建);返回 sid + 各单位工程条数。"""
|
||||
同名已存在于最近审核=拒绝(决策 242,取代决策 238「整项目覆盖」);返回 sid + 各单位工程条数。"""
|
||||
p = (body.get("path") or "").strip()
|
||||
if not p:
|
||||
return {"ok": False, "msg": "缺少导入文件路径"}
|
||||
@@ -524,7 +524,8 @@ def import_project(con, body):
|
||||
"name": body.get("name"), "period_from": body.get("period_from"),
|
||||
"period_to": body.get("period_to"), "province": body.get("province"),
|
||||
"city": body.get("city"), "district": body.get("district"),
|
||||
"bulid_unit": body.get("bulid_unit"), "tree": tree,
|
||||
"bulid_unit": body.get("bulid_unit"), "file_kind": body.get("file_kind"),
|
||||
"tree": tree,
|
||||
})
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
@@ -547,7 +548,7 @@ def import_project(con, body):
|
||||
# ---------------------------------------------------------------------------
|
||||
def manual_state(con, sid):
|
||||
"""手工工程回填弹框用:目录树 + 每个单位工程已导入条数 + 共用字段(决策 233)。"""
|
||||
row = con.execute("""SELECT name, period_from, period_to, x_manual,
|
||||
row = con.execute("""SELECT name, period_from, period_to, x_manual, file_kind,
|
||||
x_province, x_city, x_district, bulid_unit
|
||||
FROM sessions WHERE id=?""", (sid,)).fetchone()
|
||||
if not row or not row["x_manual"]:
|
||||
@@ -569,7 +570,7 @@ def manual_state(con, sid):
|
||||
"n_item": c.get("item", 0), "n_prelim": c.get("prelim", 0)}
|
||||
(secmap[u["section_id"]]["units"].append(it) if u["section_id"] in secmap else units.append(it))
|
||||
return {"ok": True, "name": row["name"] or "", "period_from": row["period_from"],
|
||||
"period_to": row["period_to"],
|
||||
"period_to": row["period_to"], "file_kind": row["file_kind"],
|
||||
"province": row["x_province"] or "", "city": row["x_city"] or "",
|
||||
"district": row["x_district"] or "", "bulid_unit": row["bulid_unit"] or "",
|
||||
"sections": secs, "free_uws": units}
|
||||
@@ -662,6 +663,85 @@ def _sum_divides(cur, uwid):
|
||||
cur.execute("UPDATE s_divides SET Total=? WHERE id=?", (round(s, 2), rid))
|
||||
|
||||
|
||||
def build_batch_out(units, name="", file_kind=None, bulid_unit=""):
|
||||
"""决策 245(2026-11-01):Excel(单位工程模板/项目模板)→ import_job.save 的 out 结构。
|
||||
units = [{"section": 单项工程名, "uw": 单位工程名, "data": parse 结果}]。
|
||||
与工作台手工工程同款口径:只到清单级、无定额/工料机;分部合价按子树清单现算;
|
||||
单位工程编号全项目连号(1..n),单项工程 Number 为组序。"""
|
||||
out = {"uw": [], "bills": [], "norms": [], "lmes": [], "divides": [], "sections": [],
|
||||
"bill_uw": [], "bill_kind": [], "bill_div": [],
|
||||
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0, "lme_raw": 0, "lme_skip": 0,
|
||||
"proj_name": name, "file_kind": file_kind, "bulid_unit": bulid_unit, "total": 0.0}
|
||||
sec_idx = {}
|
||||
total_all = 0.0
|
||||
for i, u in enumerate(units):
|
||||
sname = (u.get("section") or "").strip() or "单项工程"
|
||||
if sname not in sec_idx:
|
||||
sec_idx[sname] = len(out["sections"])
|
||||
out["sections"].append({"number": str(len(out["sections"]) + 1), "name": sname,
|
||||
"total": 0.0, "ratios": None, "uw_nums": []})
|
||||
unum = str(i + 1)
|
||||
out["sections"][sec_idx[sname]]["uw_nums"].append(unum)
|
||||
d = u["data"]
|
||||
div_base = len(out["divides"])
|
||||
div_num, counters, div_local = {}, {}, []
|
||||
for j, dv in enumerate(d["divides"]):
|
||||
pkey = dv["pidx"] if dv["pidx"] >= 0 else -1
|
||||
counters[pkey] = counters.get(pkey, 0) + 1
|
||||
num = (div_num[dv["pidx"]] + "." if dv["pidx"] >= 0 else "") + str(counters[pkey])
|
||||
div_num[j] = num
|
||||
out["divides"].append({
|
||||
"uw": i, "parent": (div_base + dv["pidx"]) if dv["pidx"] >= 0 else None,
|
||||
"kind": "item", "number": num, "name": dv["name"],
|
||||
"total": None, "code": None, "seq": len(out["divides"])})
|
||||
div_local.append(div_base + j)
|
||||
tot = {"item": 0.0, "prelim": 0.0}
|
||||
div_sum = {}
|
||||
for b in d["bills"]:
|
||||
out["bills"].append((b["num"] or "", b["name"], b["attr"] or "", b["unit"],
|
||||
b["qty"], b["price"], b["total"], None))
|
||||
out["bill_uw"].append(i)
|
||||
out["bill_kind"].append(None)
|
||||
_dv = div_local[b["didx"]] if b["didx"] is not None else None
|
||||
out["bill_div"].append(_dv)
|
||||
if _dv is not None:
|
||||
div_sum[_dv] = div_sum.get(_dv, 0.0) + (b["total"] or 0)
|
||||
tot["item"] += b["total"] or 0
|
||||
for b in d["prelim"]:
|
||||
out["bills"].append((b["num"] or "", b["name"], b["attr"] or "", b["unit"],
|
||||
b["qty"], b["price"], b["total"], None))
|
||||
out["bill_uw"].append(i)
|
||||
out["bill_kind"].append("prelim")
|
||||
out["bill_div"].append(None)
|
||||
tot["prelim"] += b["total"] or 0
|
||||
# 分部合价=子树清单合价上卷(与工作台手工工程同一算法,纯存储端现算)
|
||||
par = {dv["seq"]: dv["parent"] for dv in out["divides"]}
|
||||
depth = {}
|
||||
|
||||
def _dep(rid):
|
||||
if rid not in depth:
|
||||
p0 = par.get(rid)
|
||||
depth[rid] = 0 if p0 is None else _dep(p0) + 1
|
||||
return depth[rid]
|
||||
|
||||
sums = {rid: div_sum.get(rid, 0.0) for rid in par}
|
||||
for rid in sorted(par, key=lambda x: -_dep(x)):
|
||||
p0 = par.get(rid)
|
||||
if p0 is not None:
|
||||
sums[p0] = sums.get(p0, 0.0) + sums[rid]
|
||||
for rid, s0 in sums.items():
|
||||
out["divides"][rid]["total"] = round(s0, 2)
|
||||
ut = round(tot["item"] + tot["prelim"], 2)
|
||||
out["uw"].append((unum, (u.get("uw") or "").strip(), ut))
|
||||
out["sections"][sec_idx[sname]]["total"] += ut
|
||||
total_all += ut
|
||||
out["bill_raw"] += len(d["bills"]) + len(d["prelim"])
|
||||
out["total"] = round(total_all, 2)
|
||||
for s in out["sections"]:
|
||||
s["total"] = round(s["total"], 2)
|
||||
return out
|
||||
|
||||
|
||||
def save_tree(con, body):
|
||||
"""建/改手工工程目录树并按单位工程导 Excel。
|
||||
body = {sid?, name, period_from, period_to,
|
||||
@@ -678,6 +758,13 @@ def save_tree(con, body):
|
||||
city = (body.get("city") or "").strip()
|
||||
dist = (body.get("district") or "").strip()
|
||||
bu = (body.get("bulid_unit") or "").strip()
|
||||
# 决策 245(2026-11-01):单价类型与打开项目弹框同一口径落库(1..4,空/非法→NULL)
|
||||
fk = body.get("file_kind")
|
||||
try:
|
||||
fk = int(fk) if fk not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
fk = None
|
||||
fk = fk if fk in (1, 2, 3, 4) else None
|
||||
tree = body.get("tree") or []
|
||||
flat = []
|
||||
for s in tree:
|
||||
@@ -700,24 +787,23 @@ def save_tree(con, body):
|
||||
if not row or not row["x_manual"]:
|
||||
return {"ok": False, "msg": "只有手工工程才能用「导入项目」编辑目录树"}
|
||||
else:
|
||||
# 同名:已有手工工程=原地续用;源文件工程=拒绝(不覆盖别人)
|
||||
same = cur.execute("SELECT id, x_manual FROM sessions WHERE TRIM(name)=? ORDER BY id DESC LIMIT 1",
|
||||
same = cur.execute("SELECT id FROM sessions WHERE TRIM(name)=? ORDER BY id DESC LIMIT 1",
|
||||
(name,)).fetchone()
|
||||
# 决策 242(2026-10-30 主人定):同名一律拒绝——整项目导入不再「整项目覆盖」,
|
||||
# 取代决策 238 同名覆盖口径;提示语与工作台导入入口同款。
|
||||
if same:
|
||||
if not same["x_manual"]:
|
||||
return {"ok": False, "msg": "已有同名工程(源文件导入),请换个名称"}
|
||||
sid = same["id"]
|
||||
else:
|
||||
cur.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
||||
x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_manual)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,1)""",
|
||||
(name, pf, pf, pt, prov, city, dist, bu, "",
|
||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
sid = cur.lastrowid
|
||||
return {"ok": False, "msg": "与最近审核的%s名字重复,请修改名称后再导入" % name}
|
||||
cur.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
||||
x_province, x_city, x_district, bulid_unit, file_kind, src_name,
|
||||
imported_at, x_manual)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,1)""",
|
||||
(name, pf, pf, pt, prov, city, dist, bu, fk, "",
|
||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
sid = cur.lastrowid
|
||||
# 决策 233:打开项目弹框共用字段——地区/建设单位随建随改落库(与 /api/audit 同名参数)
|
||||
cur.execute("""UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=?,
|
||||
x_province=?, x_city=?, x_district=?, bulid_unit=? WHERE id=?""",
|
||||
(name, pf, pt, pf, prov, city, dist, bu, sid))
|
||||
x_province=?, x_city=?, x_district=?, bulid_unit=?, file_kind=? WHERE id=?""",
|
||||
(name, pf, pt, pf, prov, city, dist, bu, fk, sid))
|
||||
|
||||
# ---- 结构同步(决策 230 补记:单项/单位均可在组内上下移动)----
|
||||
# 单位工程按 id 对位:改名保留数据 / 删除级联 / 新增先插(归属与编号稍后统一指)。
|
||||
|
||||
88
CostReview/app/core/platform_skeleton.py
Normal file
88
CostReview/app/core/platform_skeleton.py
Normal file
@@ -0,0 +1,88 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""骨架来源(2026-10-31 定稿:随客户端升级包分发,服务端只负责套餐管理)。
|
||||
|
||||
骨架 JSON 由管理台导出脚本(yhy-mager scripts/export_skeleton_for_client.py)
|
||||
生成、随升级包放入 app/skeletons/{suffix}.json。本模块只做:加载 + 结构校验 + 摘要,
|
||||
**没有任何网络逻辑**——离线可用,不依赖凭据与服务端。
|
||||
|
||||
骨架即「数据结构」:租户端导出引擎按点位消费——
|
||||
锚定值以 "/" 开头 = 闭合点;无子目录且非闭合 = 自闭合;其余 = 起点容器;
|
||||
目录的 columns = 该元素属性(is_value/parent_id 标记的为枚举含义列,非属性)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
APP_DIR = os.path.dirname(_HERE) # .../CostReview/app
|
||||
DEFAULT_SKELETON_DIR = os.path.join(APP_DIR, "skeletons")
|
||||
|
||||
|
||||
class SkeletonError(Exception):
|
||||
"""骨架缺失/损坏(信息给足,绝不带病前进)。"""
|
||||
|
||||
|
||||
def skeleton_path(suffix, skeleton_dir=None):
|
||||
safe = "".join(ch for ch in suffix if ch.isalnum() or ch in "-_.") or "x"
|
||||
return os.path.join(skeleton_dir or DEFAULT_SKELETON_DIR, f"{safe}.json")
|
||||
|
||||
|
||||
def load(suffix, skeleton_dir=None):
|
||||
"""加载某后缀的骨架,返回 data dict。文件缺失/损坏一律抛 SkeletonError。"""
|
||||
f = skeleton_path(suffix, skeleton_dir)
|
||||
if not os.path.isfile(f):
|
||||
raise SkeletonError(f"升级包内没有骨架文件:{f}(由管理台导出脚本生成并随包分发)")
|
||||
try:
|
||||
data = json.load(open(f, encoding="utf8"))["data"]
|
||||
except Exception as e:
|
||||
raise SkeletonError(f"骨架文件损坏({f}):{e}") from e
|
||||
validate(data)
|
||||
return data
|
||||
|
||||
|
||||
def validate(data):
|
||||
"""结构校验(坏骨架绝不出引擎)。返回摘要 dict。"""
|
||||
if not isinstance(data, dict) or not isinstance(data.get("dirs"), list) or not data["dirs"]:
|
||||
raise SkeletonError("骨架缺少 dirs 或为空")
|
||||
seen = set()
|
||||
roots = []
|
||||
for d in data["dirs"]:
|
||||
if not isinstance(d, dict) or not d.get("name"):
|
||||
raise SkeletonError("目录项缺 name")
|
||||
did = d.get("id")
|
||||
if did in seen:
|
||||
raise SkeletonError(f"目录 id 重复:{did}")
|
||||
seen.add(did)
|
||||
pid = d.get("parent_id")
|
||||
if pid is None:
|
||||
roots.append(d["name"])
|
||||
elif pid not in {x.get("id") for x in data["dirs"]}:
|
||||
raise SkeletonError(f"目录「{d['name']}」的 parent_id={pid} 不存在")
|
||||
for col in d.get("columns") or []:
|
||||
if not col.get("name"):
|
||||
raise SkeletonError(f"目录「{d['name']}」存在无名属性行")
|
||||
if not roots:
|
||||
raise SkeletonError("骨架没有根目录")
|
||||
if not data.get("version"):
|
||||
raise SkeletonError("骨架缺少 version")
|
||||
return summary(data)
|
||||
|
||||
|
||||
def summary(data):
|
||||
"""骨架摘要(核对/日志用)。"""
|
||||
dirs = data["dirs"]
|
||||
anchored = [d for d in dirs if d.get("anchor")]
|
||||
closes = [d for d in dirs if str(d.get("anchor", "")).startswith("/")]
|
||||
rows = sum(len(d.get("columns") or []) for d in dirs)
|
||||
filled = sum(1 for d in dirs for c in (d.get("columns") or []) if c.get("value"))
|
||||
return {
|
||||
"suffix": (data.get("suffix") or {}).get("name"),
|
||||
"group": (data.get("suffix") or {}).get("group"),
|
||||
"version": data.get("version"),
|
||||
"dirs": len(dirs),
|
||||
"roots": [d["name"] for d in dirs if d.get("parent_id") is None],
|
||||
"anchored": len(anchored),
|
||||
"close_points": len(closes),
|
||||
"rows": rows,
|
||||
"filled_cells": filled,
|
||||
"files": len(data.get("files") or []),
|
||||
}
|
||||
@@ -33,6 +33,15 @@ def rkey(src, uw, no, name, unit):
|
||||
return md5(src, uw, no, name, unit)
|
||||
|
||||
|
||||
def _fk(v):
|
||||
"""单价类型归一(决策 245):1..4 收下,空/非法 → NULL(后台未标注=0 也不收,弹框只给四选)。"""
|
||||
try:
|
||||
n = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return n if n in (1, 2, 3, 4) else None
|
||||
|
||||
|
||||
def _bill_keys(con, sid, src_name=None):
|
||||
"""这个会话每条清单的持久键 → {rkey: bill_id}(回填备注/删备注用)。
|
||||
src_name 可显式传入:两段式删除时会话行已先删,不能再 JOIN sessions 取源文件名。"""
|
||||
@@ -404,7 +413,7 @@ def lme_rkeys(con, sid, src_name=None):
|
||||
return set(_lme_keys(con, sid, src_name))
|
||||
|
||||
|
||||
def drop_remarks(con, rk, batch_src_hashes=None):
|
||||
def drop_remarks(con, rk, batch_src_hashes=None, keep_ids=None):
|
||||
"""删会话时把采纳备注一并删除(2026-10-08 主人定:最近审核删除 = 备注+源文件一起删)。
|
||||
|
||||
rk 为被删会话的 rkey 集合(**删会话前**用 bill_rkeys 收集,删完行就没了)。
|
||||
@@ -416,6 +425,8 @@ def drop_remarks(con, rk, batch_src_hashes=None):
|
||||
删会话不再丢备注;重新打开工程会按 rkey 自动回填)。
|
||||
batch_src_hashes:history.db 现存批次的 x_src_hash 集合(api 层传入——本模块只碰
|
||||
session.db,不越过分层去开历史库)。备注的 src_key 可能是「;」连接的多文件串,逐段比对。
|
||||
keep_ids(决策 242):删除时刻的剩余会话 id 快照——**只认快照里的会话**当引用;
|
||||
删除后立刻重导的新会话不算引用,否则旧备注会被新会话「保住」又回填进新工程。
|
||||
⚠️ 重新解析(wipe)不走这里 —— 它的按 rkey 回填机制依赖 s_remarks。
|
||||
返回删除条数。
|
||||
"""
|
||||
@@ -423,6 +434,8 @@ def drop_remarks(con, rk, batch_src_hashes=None):
|
||||
return 0
|
||||
keep = set()
|
||||
for r in con.execute("SELECT id FROM sessions"):
|
||||
if keep_ids is not None and r["id"] not in keep_ids:
|
||||
continue
|
||||
keep |= bill_rkeys(con, r["id"])
|
||||
keep |= lme_rkeys(con, r["id"])
|
||||
bh = set(batch_src_hashes or ())
|
||||
@@ -450,8 +463,16 @@ def connect_readonly():
|
||||
|
||||
|
||||
def connect():
|
||||
con = sqlite3.connect(DB)
|
||||
# 决策 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())
|
||||
# 老库补列(已存在的列会报错,忽略)
|
||||
# ⚠️ 每个表各补各的 —— 别把 A 表的列塞进 B 表的循环里,那会给 B 表凭空造出无用列
|
||||
@@ -460,11 +481,15 @@ def connect():
|
||||
# 工作台靠它只读展示该项目的询价附件)。老库没有这列,这里补。
|
||||
("sessions", ("period_from INTEGER", "period_to INTEGER", "x_total REAL",
|
||||
"x_info TEXT", "x_feat TEXT", "x_batch_id INTEGER",
|
||||
"x_manual INTEGER DEFAULT 0")),
|
||||
"x_manual INTEGER DEFAULT 0",
|
||||
# 决策 245(2026-11-01):单价类型随「打开项目」落库(老库补列)
|
||||
"file_kind INTEGER")),
|
||||
("s_unit_works", ("section_id INTEGER",
|
||||
"Construction REAL", "DivisionalAndElementalWorks REAL",
|
||||
"Preliminaries REAL", "CostForHSE REAL",
|
||||
"SundryCosts REAL", "Tax REAL")),
|
||||
"SundryCosts REAL", "Tax REAL",
|
||||
# 决策 244(2026-11-01):四张汇总卡——老库补列后重解析才有值
|
||||
"Code TEXT", "Unit TEXT", "Scale REAL", "ztotal REAL")),
|
||||
("s_bills", ("div_id INTEGER",
|
||||
# 源文件备注(清单节点 Remark 属性,2026-10-08 加;老库补列,老会话重解析才有)
|
||||
"src_remark TEXT",
|
||||
@@ -507,7 +532,7 @@ def connect():
|
||||
def open_project(con, files, meta, job, sid=None):
|
||||
"""
|
||||
files: [(path, name)] 一般一次一个
|
||||
meta : {name, period_from, period_to, base_period_m(兼容), province, city, district, bulid_unit}
|
||||
meta : {name, period_from, period_to, base_period_m(兼容), province, city, district, bulid_unit, file_kind}
|
||||
job : import_job 模块(复用它的解析器)
|
||||
sid : 给了就**写进这个已存在的会话**(「重新解析」用:先删旧数据再原地重写,会话 id 不变)
|
||||
返回 session_id
|
||||
@@ -525,21 +550,22 @@ def open_project(con, files, meta, job, sid=None):
|
||||
if sid is None:
|
||||
cur.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
||||
x_province, x_city, x_district,
|
||||
bulid_unit, src_name, imported_at) VALUES(?,?,?,?,?,?,?,?,?,?)""",
|
||||
bulid_unit, file_kind, src_name, imported_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(meta.get("name") or "", pf, pf, pt,
|
||||
meta.get("province", ""), meta.get("city", ""), meta.get("district", ""),
|
||||
meta.get("bulid_unit", ""),
|
||||
meta.get("bulid_unit", ""), _fk(meta.get("file_kind")),
|
||||
";".join(n for _, n in files),
|
||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
sid = cur.lastrowid
|
||||
else:
|
||||
# 重新解析:期次/地区等元信息以这次请求为准,打开时间刷新(7 天清理按它算)
|
||||
cur.execute("""UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=?,
|
||||
x_province=?, x_city=?, x_district=?, bulid_unit=?, imported_at=?
|
||||
x_province=?, x_city=?, x_district=?, bulid_unit=?, file_kind=?, imported_at=?
|
||||
WHERE id=?""",
|
||||
(meta.get("name") or "", pf, pt, pf,
|
||||
meta.get("province", ""), meta.get("city", ""), meta.get("district", ""),
|
||||
meta.get("bulid_unit", ""), time.strftime("%Y-%m-%d %H:%M:%S"), sid))
|
||||
meta.get("bulid_unit", ""), _fk(meta.get("file_kind")),
|
||||
time.strftime("%Y-%m-%d %H:%M:%S"), sid))
|
||||
stat = {"bill": 0, "norm": 0, "lme": 0, "uw": 0}
|
||||
bill_ids = []
|
||||
ptotal = None # 工程总造价:多文件时取最后一个有值的
|
||||
@@ -585,17 +611,51 @@ def open_project(con, files, meta, job, sid=None):
|
||||
uw_ids = []
|
||||
for i, (num, nm, total) in enumerate(out["uw"]):
|
||||
c = (out.get("uw_cost") or {}).get(i) or {}
|
||||
# 决策 244:总造价 ztotal = UnitWorksSummary 的 ZZJ 行 → SummaryOfCost@Total → UnitWorks@Total
|
||||
_z = (out.get("uw_zzj") or {}).get(i)
|
||||
if _z is None:
|
||||
_z = c.get("_sc_total")
|
||||
_um = (out.get("uw_meta") or {}).get(i) or (None, None)
|
||||
cur.execute("""INSERT INTO s_unit_works(session_id, section_id, Number, Name,
|
||||
Specialty, Total, Construction, DivisionalAndElementalWorks,
|
||||
Preliminaries, CostForHSE, SundryCosts, Tax)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
Preliminaries, CostForHSE, SundryCosts, Tax,
|
||||
Code, Unit, Scale, ztotal)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, num2sec.get(num), num, nm, (out.get("uw_spec") or {}).get(i),
|
||||
total, c.get("Construction"),
|
||||
c.get("DivisionalAndElementalWorks"), c.get("Preliminaries"),
|
||||
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax")))
|
||||
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax"),
|
||||
(out.get("uw_code") or {}).get(i), _um[0], _um[1],
|
||||
_z if _z is not None else total))
|
||||
uw_ids.append(cur.lastrowid)
|
||||
stat["uw"] += 1
|
||||
|
||||
# 决策 244(2026-11-01):单位工程「汇总分析」/「其他项目」两卡源数据原样入库
|
||||
#(老格式/手工工程无这些键 → 空转,卡面显示「没有数据」)
|
||||
for _i, _uid in enumerate(uw_ids):
|
||||
for _r in (out.get("uw_summary") or {}).get(_i) or []:
|
||||
cur.execute("""INSERT INTO s_uw_summary(session_id, uw_id, Kind, Number, Code, Name,
|
||||
Formula, Rate, Total, Remark) VALUES(?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, _uid, _r["kind"], _r["number"], _r["code"], _r["name"],
|
||||
_r["formula"], _r["rate"], _r["total"], _r["remark"]))
|
||||
_sn = 0
|
||||
for _r in (out.get("sundry") or {}).get(_i) or []:
|
||||
if _r["kind"] == "item" and not _r["number"]:
|
||||
_sn += 1
|
||||
_r = dict(_r, number="1.%d" % _sn)
|
||||
cur.execute("""INSERT INTO s_sundry(session_id, uw_id, Kind, Number, Code, Name, Unit,
|
||||
Quantity, Formula, Price, Rate, Total, Remark)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, _uid, _r["kind"], _r["number"], _r["code"], _r["name"], _r["unit"],
|
||||
_r["quantity"], _r["formula"], _r["price"], _r["rate"], _r["total"],
|
||||
_r["remark"]))
|
||||
# 决策 244:项目级「项目汇总分析」卡源数据原样入库
|
||||
for _r in (out.get("proj_summary") or []):
|
||||
cur.execute("""INSERT INTO s_proj_summary(session_id, Kind, Number, Code, Name,
|
||||
Formula, Rate, Total, Ratios, Remark) VALUES(?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, _r["kind"], _r["number"], _r["code"], _r["name"], _r["formula"],
|
||||
_r["rate"], _r["total"], _r["ratios"], _r["remark"]))
|
||||
|
||||
# 第一个 xml 的清单在 bill_ids 里的起始位置 —— 定额元组里的 idx 是「本文件内第几条清单」,
|
||||
# 换算成全局下标必须加这个偏移。⚠️ 以前算了 n0 却没用(直接 bill_ids[idx]),
|
||||
# 一次会话导入多个 xml 时,第二个文件起的定额会整套挂到第一个文件的清单上。
|
||||
|
||||
Reference in New Issue
Block a user