feat(costreview): 新增清单库与项目目录管理并修复采纳定额单价回填及换行实体转义
This commit is contained in:
@@ -1,72 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""主人三规律普适性验证:对多份实件逐容器逐标签分类,找覆盖不了的边缘形态。"""
|
||||
import sys
|
||||
sys.path.insert(0, '.')
|
||||
import classic_skeleton as cs
|
||||
import sqlite3
|
||||
import zipfile
|
||||
import io
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections import defaultdict
|
||||
|
||||
con = sqlite3.connect(r'D:/PricingReview/CostReview/data/history.db')
|
||||
con.row_factory = sqlite3.Row
|
||||
|
||||
CASES = [] # (名称, zip字节流)
|
||||
for r in con.execute('SELECT sig,blob,original_name,suffix FROM classic_skel'):
|
||||
CASES.append((r['original_name'][:14], zipfile.ZipFile(io.BytesIO(r['blob']))))
|
||||
import glob
|
||||
for f in (glob.glob(r'D:/PricingReview/CostReview/data/source_files/*华宇路*COS') +
|
||||
glob.glob(r'D:/PricingReview/CostReview/data/source_files/*标准版*cos4') +
|
||||
glob.glob(r'D:/PricingReview/CostReview/data/source_files/*白蕉*.cos4')):
|
||||
CASES.append((f.split('791')[-1][:20] if '791' in f else f[-30:-4], zipfile.ZipFile(f)))
|
||||
|
||||
report = []
|
||||
edge = [] # 规律覆盖不了的边缘形态
|
||||
for name, z in CASES:
|
||||
stat = defaultdict(int)
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith('.xml'):
|
||||
continue
|
||||
try:
|
||||
root = ET.fromstring(z.read(nm))
|
||||
except Exception:
|
||||
continue
|
||||
# 逐父容器逐标签分组(key=父路径+标签)
|
||||
groups = defaultdict(list)
|
||||
parents = {c: p for p in root.iter() for c in p}
|
||||
for el in root.iter():
|
||||
if el.tag is ET.Comment:
|
||||
continue
|
||||
p = parents.get(el)
|
||||
pt = p.tag if p is not None else '#root'
|
||||
groups[(id(p), pt, el.tag)].append(el)
|
||||
for (pid, pt, tag), els in groups.items():
|
||||
n = len(els)
|
||||
container_n = sum(1 for e in els if len(e) > 0)
|
||||
selfclose_n = n - container_n
|
||||
if n == 1 and container_n == 1:
|
||||
stat['区域容器(开闭对,单块→取2行)'] += 1
|
||||
elif n == 1 and selfclose_n == 1:
|
||||
stat['固定单行(自闭合,单条)'] += 1
|
||||
elif container_n == n and n > 1:
|
||||
stat['自增块(开闭对容器,多块重复→取1块)'] += 1
|
||||
elif selfclose_n == n and n > 1:
|
||||
stat['自增行(自闭合,多行重复→取1行)'] += 1
|
||||
else:
|
||||
# 混合形态:自闭合行+容器块混在同父同标签
|
||||
key = (pt, tag, container_n, selfclose_n)
|
||||
edge.append((name, pt, tag, container_n, selfclose_n))
|
||||
stat[f'混合形态(容器{container_n}+自闭合{selfclose_n})'] += 1
|
||||
report.append((name, dict(stat)))
|
||||
|
||||
for name, st in report:
|
||||
print(f'=== {name} ===')
|
||||
for k, v in sorted(st.items(), key=lambda x: -x[1]):
|
||||
print(f' {v:4d} {k}')
|
||||
print()
|
||||
print('=== 混合形态明细(规律未直接覆盖的边缘)===')
|
||||
for e in edge[:10]:
|
||||
print(' ', e[0], '| 父标签:', e[1], '| 标签:', e[2], f'| 容器{e[3]}+自闭合{e[4]}')
|
||||
print('混合形态总处数:', len(edge))
|
||||
@@ -1,38 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""举实际例子:广联达件 LME_SUM 两种列集的原文件原文行(26列版 vs 30列版各贴一条完整原文)。"""
|
||||
import sys
|
||||
sys.path.insert(0, '.')
|
||||
import classic_skeleton as cs
|
||||
import sqlite3
|
||||
import zipfile
|
||||
import io
|
||||
import re
|
||||
|
||||
con = sqlite3.connect(r'D:/PricingReview/CostReview/data/history.db')
|
||||
con.row_factory = sqlite3.Row
|
||||
r = con.execute("SELECT blob FROM classic_skel WHERE original_name LIKE '%广联达导出最新%'").fetchone()
|
||||
z = zipfile.ZipFile(io.BytesIO(r['blob']))
|
||||
seen = {}
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith('.xml'):
|
||||
continue
|
||||
t = z.read(nm).decode('utf-8', errors='replace')
|
||||
for m in re.finditer(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*>', t):
|
||||
cols = tuple(re.findall(r'(\w+)=', m.group(0)))
|
||||
key = '少列版(26列)' if len(cols) == 26 else ('多列版(30列)' if len(cols) == 30 else None)
|
||||
if key and key not in seen:
|
||||
seen[key] = (nm, m.group(0))
|
||||
for key in ('少列版(26列)', '多列版(30列)'):
|
||||
nm, line = seen[key]
|
||||
print(f'=== {key} ===')
|
||||
print('所在成员:', nm[:40])
|
||||
# 属性逐列竖排对比友好显示
|
||||
pairs = re.findall(r'(\w+)="([^"]*)"', line)
|
||||
print('属性列:', ' '.join(p[0] for p in pairs))
|
||||
print()
|
||||
# 差异列
|
||||
c26 = set(re.findall(r'(\w+)=', seen['少列版(26列)'][1]))
|
||||
c30 = set(re.findall(r'(\w+)=', seen['多列版(30列)'][1]))
|
||||
print('=== 两版差异 ===')
|
||||
print('多列版独有:', sorted(c30 - c26))
|
||||
print('少列版独有:', sorted(c26 - c30))
|
||||
@@ -1,676 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""经典整件骨架库(决策 231,2026-10-27 主人定):
|
||||
|
||||
手工工程(无源文件,决策 119/230)没有「本项目原件」可当导出模板——把**经典项目的
|
||||
整件原件**收进骨架库当模板:结构字段相同(同签名)只存一件;每组保留**最全**的代表
|
||||
(不一定最新,平手取最新;绝不跨件拼合,与决策 197 工料机骨架库同一条规则,
|
||||
只是范围从工料机一层扩到整件);**连保留值一起存**——导出件里我们没有的工程级信息
|
||||
(建设单位/编制人/取费程序/费用汇总…)就按代表件原样保留(铁律 5 本通道调整,主人定;
|
||||
⚠️ 决策 259 起按「骨架不能创造数据」原则逐步清零,见决策 260 补记四)。
|
||||
|
||||
收集规则(主人 2026-10-27 逐条定):
|
||||
· 收集口=公共上传口(api_upload):后台导入与工作台「打开工程」两侧自动生效;
|
||||
· 签名=后缀+结构字段指纹:10 字段 / 15 字段是不同组,**都收**(找规律、找框架);
|
||||
· 每组只存最全一件(全文件元素总数为「全」的度量,与 197「形态种类最多」同源;
|
||||
同签名结构相同,元素多=样板更全);平手取最新;
|
||||
· 多后缀:提取器按后缀注册,本次接 cos 族;SWT/SWZ 等后期注册即可。
|
||||
存储:history.db classic_skel 一组一行(连代表件原件字节存库,不随会话清理)。
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import tempfile
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import skeleton_engine as _se # 决策 262:格式无关骨架引擎(族判定/收敛/旁注/匹配)
|
||||
|
||||
# 决策 262(2026-11-03 主人定「引擎写活了,后期还有很多后缀」):
|
||||
# **后缀不再参与拦截**——能不能用由内容判定(zip 内 XML / 裸 XML),见 skeleton_engine。
|
||||
# 这里只保留"从文件名取后缀"的能力;当前已实件验过的四种=cos/cos4/swt/swz。
|
||||
_COS_RE = re.compile(r"\.(cos4?)$", re.I)
|
||||
|
||||
|
||||
def suffix_of(name):
|
||||
"""文件名 → 小写后缀(任意后缀都返回;能不能用由 skeleton_engine.family_of 按内容判)。"""
|
||||
ext = os.path.splitext(os.path.basename(name or ""))[1]
|
||||
return ext[1:].lower() if ext else None
|
||||
|
||||
|
||||
def _now():
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _ensure_table(con):
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS classic_skel(
|
||||
sig TEXT PRIMARY KEY, -- 后缀+结构字段指纹
|
||||
suffix TEXT,
|
||||
rep_sha TEXT, -- 代表件 sha256
|
||||
original_name TEXT,
|
||||
n_shapes INTEGER, -- 结构形态种类数
|
||||
n_nodes INTEGER, -- 全文件元素总数(「最全」度量)
|
||||
blob BLOB, -- 代表件整件原件(保留值来源)
|
||||
extracted_at TEXT
|
||||
)""")
|
||||
_cols = {r[1] for r in con.execute("PRAGMA table_info(classic_skel)")}
|
||||
if "x_blank" not in _cols:
|
||||
# 决策 260 补记三/四:该骨架的**空骨架**(单 XML 空数据模板字节)——由本件
|
||||
# 自动总结(值全空、列集按样板自增行规整),「每件一个小骨架」并存
|
||||
con.execute("ALTER TABLE classic_skel ADD COLUMN x_blank BLOB")
|
||||
if "x_meta" not in _cols:
|
||||
# 决策 262:结构旁注(角色路径 unit/bill/norm/lme + 各路径出现次数)——
|
||||
# 骨架文件只放结构,重复次数与数据源这类"文件里没有的语义"单独存这里
|
||||
con.execute("ALTER TABLE classic_skel ADD COLUMN x_meta TEXT")
|
||||
if "x_layer_cols" not in _cols:
|
||||
# 决策 260 补记八(2026-11-03 主人定「根据第一行的列选骨架」):该骨架的
|
||||
# **分层列集指纹** JSON——{标签: 列集并集},入库时预计算;导出/打开项目时
|
||||
# 与原数据逐层比对算匹配度(第一行权重最高,逐层下探,Jaccard 兜底)
|
||||
con.execute("ALTER TABLE classic_skel ADD COLUMN x_layer_cols TEXT")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 分层列集指纹与骨架匹配度(决策 260 补记八,2026-11-03 主人定:
|
||||
# 「根据第一行的列选骨架;第一行相同找另外不相同的列;主要看原数据的列情况」)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_MATCH_LAYERS = ("ConstructionProject", "UnitWorks", "WorkElement", "Norm",
|
||||
"LabourMaterialsEquipmentsMachinesSummary",
|
||||
"UnitPriceCalculationOfItem", "AttrInfoItem", "AddiInfoItem")
|
||||
|
||||
|
||||
def layer_cols_of(z_or_blob):
|
||||
"""一份实件 → **分层列集指纹**(决策 262:路径键、格式无关、不含次数)。
|
||||
返回 {'v':2,'p':{路径:[列名…]}};认不出格式(加密壳/坏件)→ {}。
|
||||
旧指纹(标签键)由 match_score 兼容读,pick_frame 见非 v2 会重算回写。"""
|
||||
try:
|
||||
blob = z_or_blob if isinstance(z_or_blob, (bytes, bytearray)) \
|
||||
else (z_or_blob.read() if hasattr(z_or_blob, "read") else None)
|
||||
except Exception:
|
||||
return {}
|
||||
if not blob:
|
||||
return {}
|
||||
try:
|
||||
mains, units, fam = _se.split_roots(blob)
|
||||
except Exception:
|
||||
return {}
|
||||
if fam is None:
|
||||
return {}
|
||||
try:
|
||||
return _se.layer_cols(mains + units)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def match_score(src_cols, skel_cols):
|
||||
"""匹配度 0~100(决策 262,主人定「字段越匹配分越高、区域越匹配分越高」):
|
||||
字段=同层列集重合(根层权重最高);区域=骨架结构位在原件里的覆盖率;
|
||||
根标签不同=不同格式族,直接压到 10 分以下。"""
|
||||
try:
|
||||
return _se.match_score(src_cols, skel_cols)
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
|
||||
def _blank_parse(xml_text):
|
||||
"""解析(保留注释节点);返回 (根元素, 声明文本)。"""
|
||||
m = re.match(r"\s*<\?xml[^>]*\?>", xml_text)
|
||||
decl = m.group(0) if m else '<?xml version="1.0" encoding="utf-8"?>'
|
||||
body = xml_text[m.end():] if m else xml_text
|
||||
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
|
||||
root = ET.fromstring(body, parser=parser)
|
||||
return root, decl
|
||||
|
||||
|
||||
_REF_BASE_CACHE = {}
|
||||
|
||||
|
||||
def _blank_ref_base(con, suffix):
|
||||
"""样板基准(活表):{元素路径: 自增行列序}——从 skel_ref_{suffix}.xml(主人样板)
|
||||
提取:**自闭合行=自增行**(主人定),其属性列序=该类行的标准列集(统一列集的基准)。
|
||||
路径=根到该元素的标签链。样板文件在库同目录;缺失→空表(退实件原列集)。"""
|
||||
key = (suffix, id(con))
|
||||
hit = _REF_BASE_CACHE.get(key)
|
||||
if hit is not None:
|
||||
return hit
|
||||
try:
|
||||
db_path = [r[2] for r in con.execute("PRAGMA database_list") if r[1] == "main"][0]
|
||||
ref_p = os.path.join(os.path.dirname(db_path), f"skel_ref_{suffix}.xml")
|
||||
root, _ = _blank_parse(open(ref_p, encoding="utf-8").read())
|
||||
except Exception:
|
||||
base, tag_base = {}, {}
|
||||
_REF_BASE_CACHE[key] = (base, tag_base)
|
||||
return base, tag_base
|
||||
base = {}
|
||||
tag_base = {} # 决策 260:标签名全局基准(同标签列集并集,
|
||||
# 首见列序优先——跨嵌套层同标签统一列集)
|
||||
|
||||
def walk(el, parent_tag):
|
||||
p = parent_tag + "/" + el.tag
|
||||
kids = [k for k in el if k.tag is not ET.Comment]
|
||||
leaf_kids = [k for k in kids if len(k) == 0]
|
||||
for k in leaf_kids: # 自增行样板:无子节点(自闭合)
|
||||
kp = p + "/" + k.tag
|
||||
if kp not in base:
|
||||
base[kp] = list(k.attrib.keys())
|
||||
tb = tag_base.setdefault(k.tag, [])
|
||||
for a in k.attrib.keys(): # 同标签列集并集(样板全集)
|
||||
if a not in tb:
|
||||
tb.append(a)
|
||||
for k in kids:
|
||||
walk(k, el.tag)
|
||||
walk(root, "")
|
||||
_REF_BASE_CACHE[key] = (base, tag_base)
|
||||
return base, tag_base
|
||||
|
||||
|
||||
def _blank_normalize(el, base, tag_base, parent_tag, is_root=False):
|
||||
"""清值+列集规整(递归):
|
||||
· 属性值全清空(骨架不提供任何数值);文本节点清空(换行缩进由序列化重排)。
|
||||
· **自增行规整**(主人定「带自闭合的就是自增行;多个自增行写一行循环就自己会循环」):
|
||||
同路径叶行(自闭合/自增行)的列集统一到样板自增行列序(缺列补空=标准卡槽),
|
||||
实件行特有的列保留追加尾部(原文件有的才保留)。
|
||||
· 容器行的列集对齐其内部自增行基准(样板容器行与自增行列集同)。"""
|
||||
# 重复收敛先行(主人三规律+自增块概念修正 2026-11-02):
|
||||
# 同类判定=**去值后全行同构**(标签+自闭合形态+列集全同)——Name+Value 单行形态
|
||||
# 与 Name+Code 行列集不同=不同类,各自留样板;同父下同类只留首个样板(自增块/
|
||||
# 自增行取一),回灌时按需循环。单条类=自增块单行形态,同样保留样板。
|
||||
# ⚠️ 概念修正(2026-11-02 主人定):**带独立起+独立闭=完整区域,一般不自增**——
|
||||
# 收敛只针对**自闭合行**(只有闭、无起的自增块单行形态/自增行);
|
||||
# 容器块(开闭对)是区域结构,永不作为重复删除(内部按同规律递归处理)。
|
||||
seen = {}
|
||||
for k in list(el):
|
||||
if k.tag is ET.Comment:
|
||||
continue
|
||||
if len(k) > 0:
|
||||
continue # 容器块=区域,不收敛
|
||||
key = (k.tag, tuple(sorted(k.attrib.keys())))
|
||||
if key in seen:
|
||||
el.remove(k)
|
||||
else:
|
||||
seen[key] = k
|
||||
p = parent_tag + "/" + el.tag
|
||||
kids = [k for k in el if k.tag is not ET.Comment]
|
||||
leaf_kids = [k for k in kids if len(k) == 0]
|
||||
# 列集三源合并(决策 260):路径基准列序 → 标签全局基准补缺 → 实件首行列兜底
|
||||
merged = base.get(p)
|
||||
bt = tag_base.get(el.tag)
|
||||
if bt:
|
||||
merged = list(merged) if merged is not None else []
|
||||
for a in bt:
|
||||
if a not in merged:
|
||||
merged.append(a)
|
||||
if merged is None and leaf_kids:
|
||||
merged = list(leaf_kids[0].attrib.keys())
|
||||
base[p] = list(merged)
|
||||
own = list(el.attrib.keys())
|
||||
# 决策 260 补记九(2026-11-03 主人定「导出时只能一个标准,只能用一个我上传的文件
|
||||
# 生成的骨架,不能有交互」):列集**忠实本件实件**——不再按样板基准表(skel_ref=
|
||||
# 2 件合集)补列;本件实件有的列才输出,根治跨件来源。merged 基准仅保留列序参考
|
||||
# (本件实件自己出现过的列序),不引入本件没有的列。
|
||||
new_own = own
|
||||
el.attrib.clear()
|
||||
for a in new_own:
|
||||
el.set(a, "")
|
||||
# text/tail 全清(含空白)——换行缩进由序列化器统一重排(4 空格×深度,样板同款);
|
||||
# 不清会与序列化器的换行叠加成空行(对齐形式偏差,主人 2026-11-02 指出)
|
||||
if el.text:
|
||||
el.text = None
|
||||
if el.tail:
|
||||
el.tail = None
|
||||
for k in el:
|
||||
if k.tag is ET.Comment:
|
||||
continue
|
||||
_blank_normalize(k, base, tag_base, el.tag)
|
||||
|
||||
|
||||
def _blank_ser(el, depth, out, is_root=False, ind_unit=" ", keep_values=False):
|
||||
"""序列化(排版规律从**实件锚定**——主人 2026-11-03 定「注意换行对齐」:
|
||||
缩进单位=实件原生步进(易达 4 空格/层),行首缩进=实件该层缩进 + depth×单位;
|
||||
叶行自闭合、容器开/闭标签同列对齐;注释原样(引擎不造)。
|
||||
keep_values=False(提炼空骨架)=属性值强制输出空串;
|
||||
keep_values=True(引擎 v2 回灌)=输出元素上的真实值(灌好的数据)。"""
|
||||
pad = "\n" + ind_unit * depth
|
||||
if keep_values:
|
||||
attrs = "".join(f' {k}="{v}"' for k, v in el.attrib.items())
|
||||
else:
|
||||
attrs = "".join(f' {k}=""' for k in el.attrib)
|
||||
kids = list(el)
|
||||
comment = None
|
||||
body_kids = []
|
||||
for k in kids:
|
||||
if k.tag is ET.Comment:
|
||||
comment = (k.text or "").strip()
|
||||
else:
|
||||
body_kids.append(k)
|
||||
if not body_kids:
|
||||
out.append(f"{pad}<{el.tag}{attrs} />" +
|
||||
(f" <!-- {comment} -->" if comment else ""))
|
||||
return
|
||||
out.append(f"{pad}<{el.tag}{attrs}>")
|
||||
for k in body_kids:
|
||||
_blank_ser(k, depth + 1, out, ind_unit=ind_unit, keep_values=keep_values)
|
||||
out.append(f"{pad}</{el.tag}>" +
|
||||
(f" <!-- {comment} -->" if comment and not is_root else ""))
|
||||
|
||||
|
||||
def _blank_ind_unit(xml_text):
|
||||
"""实件缩进单位锚定:取 AttrInfo 区「块开标签行」与「块内首条自增行」的缩进差
|
||||
(易达=4 空格;读不出退 4 空格)。主人 2026-11-03 定「注意换行对齐」。"""
|
||||
i = xml_text.find("<AttrInfo")
|
||||
if i < 0:
|
||||
return " "
|
||||
seg = xml_text[i:xml_text.find("</AttrInfo>", i) + 11]
|
||||
lines = [ln for ln in seg.split("\n") if ln.strip()]
|
||||
if len(lines) < 3:
|
||||
return " "
|
||||
lead_of = lambda ln: len(ln) - len(ln.lstrip(" "))
|
||||
base = lead_of(lines[1])
|
||||
for ln in lines[2:]:
|
||||
d = lead_of(ln) - base
|
||||
if d > 0:
|
||||
return " " * d
|
||||
return " "
|
||||
|
||||
|
||||
def refine_blank(con, blob, suffix="cos4"):
|
||||
"""骨架实件(zip 或裸 XML 字节)→ 该件的**空数据模板**(单 XML 字节,值全空)。
|
||||
|
||||
决策 262(2026-11-03 主人定「引擎写活了,后期还有很多后缀」)起改由
|
||||
skeleton_engine 统一提炼——**不看后缀,按内容判族**:
|
||||
· zip 内 XML(cos/cos4 型):主文件骨架 + 首条单位索引行内嵌单位骨架(连接展示);
|
||||
· 裸 XML(swt/swz 型):整件收敛。
|
||||
收敛口径=唯一结构位(父路径+标签+列集)只留一个样板、子节点取并集、值全清空;
|
||||
缩进按实件锚定(主人 2026-11-03 定「注意换行对齐」)。con 保留给旧样板基准表用。"""
|
||||
blank, _meta = refine_blank_ex(blob, suffix)
|
||||
return blank
|
||||
|
||||
|
||||
def refine_blank_ex(blob, suffix="cos4"):
|
||||
"""→ (空骨架字节, 结构旁注 meta)。meta 随骨架入库(x_meta),导出端按它定位层。
|
||||
认不出格式族(加密壳/二进制)→ (None, None)。"""
|
||||
try:
|
||||
ind = " "
|
||||
text0 = None
|
||||
try:
|
||||
members = _se._members(blob)
|
||||
if members:
|
||||
raw0, _e0 = _decode_pair(members[-1][1])
|
||||
text0 = raw0
|
||||
except Exception:
|
||||
text0 = None
|
||||
if text0:
|
||||
ind = _blank_ind_unit(text0)
|
||||
text, meta = _se.build_blank(blob, ind_unit=ind)
|
||||
except Exception:
|
||||
return None, None
|
||||
if not text:
|
||||
return None, None
|
||||
try:
|
||||
return text.encode("utf-8"), meta
|
||||
except Exception:
|
||||
return None, None
|
||||
|
||||
|
||||
def blank_from_frame(blob):
|
||||
"""骨架实件(zip 字节)→ 该件的**空骨架**(卡槽集合 zip 字节)。
|
||||
(决策 260 起主口径=refine_blank 单 XML 空数据模板;本函数留作卡槽集合形态备用。)
|
||||
规律:①Project.xml 保留全结构、引用行只留首条样例、值全清空;
|
||||
②单位工程成员留**最全 1 个**作结构样板、值全清空;③其余成员不进空骨架。"""
|
||||
src = zipfile.ZipFile(io.BytesIO(blob))
|
||||
proj_nm = None
|
||||
unit_best = None # (元素数, 内部名, 文本, 编码)
|
||||
texts = {}
|
||||
for nm in src.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
txt, enc = _decode_pair(src.read(nm))
|
||||
texts[nm] = (txt, enc)
|
||||
body = re.sub(r"^.*?\?>", "", txt, count=1, flags=re.S).lstrip()
|
||||
if "<SectionalWorks" in body or "<ConstructionProject" in body:
|
||||
proj_nm = nm
|
||||
elif body.startswith("<UnitWorks"):
|
||||
n = len(re.findall(r"<[A-Za-z_]", txt))
|
||||
if unit_best is None or n > unit_best[0]:
|
||||
unit_best = (n, nm, txt, enc)
|
||||
if not proj_nm or unit_best is None:
|
||||
return None
|
||||
pt, proj_enc = _blank_strip_values(texts[proj_nm][0]), texts[proj_nm][1]
|
||||
refs = list(re.finditer(r"<UnitWorks\b[^>]*?/>|<UnitWorks\b[^>]*>\s*</UnitWorks>", pt))
|
||||
for m in reversed(refs[_BLANK_KEEP_REFS_DEFAULT:]):
|
||||
pt = pt[:m.start()] + pt[m.end():]
|
||||
ut, unit_enc = _blank_strip_values(unit_best[2]), unit_best[3]
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
zo.writestr(zipfile.ZipInfo("Project.xml", date_time=time.localtime()[:6]),
|
||||
pt.encode(proj_enc or "utf-8"))
|
||||
zo.writestr(zipfile.ZipInfo(unit_best[1], date_time=time.localtime()[:6]),
|
||||
ut.encode(unit_enc or "utf-8"))
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 抽取:整件结构指纹(只看标签+字段集+有无子级,不看值——签名跨值稳定)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _shapes_of_bytes(raw):
|
||||
"""一个 XML 成员 → (形态 key 集合, 元素数);解析失败返回 (set(), 0)。"""
|
||||
try:
|
||||
root = ET.fromstring(raw)
|
||||
except Exception:
|
||||
return set(), 0
|
||||
shapes, n = set(), 0
|
||||
for el in root.iter():
|
||||
n += 1
|
||||
shapes.add((el.tag, tuple(sorted(el.attrib.keys())), len(el) > 0))
|
||||
return shapes, n
|
||||
|
||||
|
||||
def extract(path):
|
||||
"""原件 → dict(sig, suffix, n_shapes, n_nodes);非 zip / 无 XML / 解析全失败 → None。
|
||||
⚠️ 返回 None = 该件不成组(合法,不挡上传),与决策 197 骨架库同约定。"""
|
||||
suf = suffix_of(os.path.basename(path))
|
||||
if not suf or not os.path.exists(path):
|
||||
return None
|
||||
shapes, n_nodes = set(), 0
|
||||
try:
|
||||
blob = open(path, "rb").read()
|
||||
if _se.family_of(blob) is None: # 决策 262:内容判族,后缀不拦截
|
||||
return None
|
||||
members = 0
|
||||
for _nm, raw in _se._members(blob):
|
||||
s, n = _shapes_of_bytes(raw)
|
||||
if n:
|
||||
members += 1
|
||||
shapes |= s
|
||||
n_nodes += n
|
||||
except Exception:
|
||||
return None
|
||||
if not members or not shapes:
|
||||
return None
|
||||
sig = hashlib.md5((suf + "|" + "|".join(sorted(repr(k) for k in shapes))).encode(
|
||||
"utf-8")).hexdigest()
|
||||
return {"sig": sig, "suffix": suf, "n_shapes": len(shapes), "n_nodes": n_nodes}
|
||||
|
||||
|
||||
def _decode_pair(raw):
|
||||
"""同 _decode,但连声明里的编码名一起回(决策 260:XML 声明是唯一按骨架原样
|
||||
保留的部分,空骨架写回按原声明编码落盘,声明与字节始终一致)。"""
|
||||
m = re.match(rb"(?:\xef\xbb\xbf|\s)*<\?xml[^>]*encoding=\"([^\"]*)\"", raw[:200])
|
||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
||||
try:
|
||||
return raw.decode(enc, errors="replace"), enc
|
||||
except Exception:
|
||||
return raw.decode("utf-8", errors="replace"), "utf-8"
|
||||
|
||||
|
||||
def _decode(raw):
|
||||
m = re.match(rb'^\s*<\?xml[^>]*encoding="([^"]*)"', raw[:200])
|
||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
||||
try:
|
||||
return raw.decode(enc, errors="replace")
|
||||
except Exception:
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def collect(con, sha, path, name=""):
|
||||
"""上传口骨架收集=**空操作**(补记十四,2026-10-28 主人定「后期不存骨架了,
|
||||
现有也只有 2 个骨架」):骨架只经升级(seed_frame)入库;上传什么原件都不进
|
||||
classic_skel,库里只保留已升级固定的骨架(COS4骨架G/Y…)。保留函数签名供上传口
|
||||
兼容调用。"""
|
||||
return None
|
||||
|
||||
def rep_for(con, suffix):
|
||||
"""某后缀的当前代表件 → dict;该后缀还没收过 → None(导出侧提示先导入原件)。
|
||||
补记五:专用骨架件(is_frame=1)优先于实项目件。"""
|
||||
_ensure_table(con)
|
||||
try:
|
||||
con.execute("SELECT is_frame FROM classic_skel LIMIT 1")
|
||||
except Exception:
|
||||
return dict(con.execute(
|
||||
"SELECT * FROM classic_skel WHERE suffix=? ORDER BY n_nodes DESC, "
|
||||
"extracted_at DESC LIMIT 1", (suffix,)).fetchone() or ())
|
||||
row = con.execute("""SELECT * FROM classic_skel WHERE suffix=?
|
||||
ORDER BY is_frame DESC, n_nodes DESC, extracted_at DESC
|
||||
LIMIT 1""", (suffix,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def seed_frame(con, path, name):
|
||||
con.row_factory = sqlite3.Row
|
||||
"""升级添加骨架(补记十二,主人定:骨架只经升级进库、上传口不自动收;命名不带
|
||||
软件名——COS4骨架G/Y、COS骨架G/Y…)。同名骨架=升级替换(重写签名/字节);
|
||||
新名=新增固定骨架。返回 sig;解析失败返回 None。"""
|
||||
info = extract(path)
|
||||
if not info:
|
||||
return None
|
||||
_ensure_table(con)
|
||||
_cols = {r[1] for r in con.execute("PRAGMA table_info(classic_skel)")}
|
||||
if "is_frame" not in _cols:
|
||||
con.execute("ALTER TABLE classic_skel ADD COLUMN is_frame INTEGER DEFAULT 0")
|
||||
old = con.execute("SELECT sig FROM classic_skel WHERE original_name=?", (name,)).fetchone()
|
||||
if old and old["sig"] != info["sig"]:
|
||||
con.execute("DELETE FROM classic_skel WHERE original_name=?", (name,))
|
||||
with open(path, "rb") as f:
|
||||
blob = f.read()
|
||||
_blank = None
|
||||
_meta = None
|
||||
try:
|
||||
# 决策 262:入库即提炼空骨架 + 结构旁注(meta 供导出端定位层,不写进骨架文件)
|
||||
_blank, _meta = refine_blank_ex(blob, info["suffix"])
|
||||
except Exception:
|
||||
_blank, _meta = None, None
|
||||
# 决策 260 补记八:入库即预计算**分层列集指纹**(导出/打开项目时算匹配度用)
|
||||
_layer_cols = {}
|
||||
try:
|
||||
_layer_cols = layer_cols_of(blob)
|
||||
except Exception:
|
||||
_layer_cols = {}
|
||||
con.execute("""INSERT INTO classic_skel(sig,suffix,rep_sha,original_name,
|
||||
n_shapes,n_nodes,blob,extracted_at,is_frame,x_blank,x_layer_cols,x_meta)
|
||||
VALUES(?,?,?,?,?,?,?,?,1,?,?,?)
|
||||
ON CONFLICT(sig) DO UPDATE SET rep_sha=excluded.rep_sha,
|
||||
original_name=excluded.original_name, n_shapes=excluded.n_shapes,
|
||||
n_nodes=excluded.n_nodes, blob=excluded.blob,
|
||||
extracted_at=excluded.extracted_at, is_frame=1,
|
||||
x_blank=COALESCE(excluded.x_blank, x_blank),
|
||||
x_layer_cols=COALESCE(excluded.x_layer_cols, x_layer_cols),
|
||||
x_meta=COALESCE(excluded.x_meta, x_meta)""",
|
||||
(info["sig"], info["suffix"],
|
||||
hashlib.sha256(blob).hexdigest(), name,
|
||||
info["n_shapes"], info["n_nodes"], blob, _now(),
|
||||
_blank if isinstance(_blank, (bytes, bytearray)) else None,
|
||||
json.dumps(_layer_cols, ensure_ascii=False) if _layer_cols else None,
|
||||
json.dumps(_meta, ensure_ascii=False) if _meta else None))
|
||||
con.commit()
|
||||
return info["sig"]
|
||||
|
||||
|
||||
def _shapes_of_blob(blob):
|
||||
"""整包字节 → 结构形态集合(与 extract 同口径:标签+字段名集+有无子级)。"""
|
||||
shapes = set()
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
s, _n = _shapes_of_bytes(z.read(nm))
|
||||
shapes |= s
|
||||
except Exception:
|
||||
pass
|
||||
return shapes
|
||||
|
||||
|
||||
def list_frames(con):
|
||||
"""骨架库列表(后台「导出设置」弹框,2026-11-02 主人定):全部骨架平铺,
|
||||
后缀聚簇排序(cos4→cos 字母序)、组内入库时间倒序——前端按后缀分组渲染
|
||||
(组间横线、后缀列组首行标件数)。"""
|
||||
_ensure_table(con)
|
||||
try:
|
||||
rows = con.execute(
|
||||
"SELECT sig, suffix, original_name, n_shapes, n_nodes, extracted_at, is_frame "
|
||||
"FROM classic_skel ORDER BY suffix DESC, extracted_at DESC, n_nodes DESC"
|
||||
).fetchall()
|
||||
except Exception:
|
||||
return []
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def delete_frame(con, sig):
|
||||
"""删除一件骨架(2026-11-02 主人定「要做删除」):硬删一行、不可逆,
|
||||
恢复=同名文件重新上传(seed_frame 同名替换会重建行)。返回删除行数。"""
|
||||
cur = con.execute("DELETE FROM classic_skel WHERE sig=?", (sig,))
|
||||
con.commit()
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
def frame_blob(con, sig):
|
||||
"""取一件骨架的原件字节与原始文件名(下载用)→ (blob, original_name);无 → (None, None)。"""
|
||||
row = con.execute("SELECT blob, original_name FROM classic_skel WHERE sig=?",
|
||||
(sig,)).fetchone()
|
||||
if not row:
|
||||
return None, None
|
||||
return row["blob"], row["original_name"]
|
||||
|
||||
|
||||
def frame_blank(con, sig):
|
||||
"""取一件骨架的**空骨架**(决策 260 补记三「每件一个小骨架」):x_blank 有→直接回;
|
||||
无(存量件)→ 现场总结并回写(惰性补齐,幂等)。→ (空骨架 XML 字节, original_name)。"""
|
||||
row = con.execute("SELECT sig, blob, original_name, x_blank, suffix, x_meta "
|
||||
"FROM classic_skel WHERE sig=?", (sig,)).fetchone()
|
||||
if not row:
|
||||
return None, None
|
||||
blank = row["x_blank"]
|
||||
if not blank:
|
||||
try:
|
||||
blank = refine_blank(con, row["blob"], row["suffix"])
|
||||
except Exception:
|
||||
blank = None
|
||||
if blank:
|
||||
con.execute("UPDATE classic_skel SET x_blank=? WHERE sig=?", (blank, sig))
|
||||
con.commit()
|
||||
try: # 决策 262:顺带补齐结构旁注(幂等)
|
||||
if not row["x_meta"]:
|
||||
_b2, _m2 = refine_blank_ex(row["blob"], row["suffix"])
|
||||
if _m2:
|
||||
con.execute("UPDATE classic_skel SET x_meta=? WHERE sig=?",
|
||||
(json.dumps(_m2, ensure_ascii=False), sig))
|
||||
con.commit()
|
||||
except Exception:
|
||||
pass
|
||||
if not blank:
|
||||
return None, row["original_name"]
|
||||
return bytes(blank), row["original_name"]
|
||||
|
||||
|
||||
def frame_meta(con, sig):
|
||||
"""取一件骨架的**结构旁注**(决策 262):{v,paths,roles};无→None(可惰性补齐)。"""
|
||||
try:
|
||||
row = con.execute("SELECT x_meta FROM classic_skel WHERE sig=?", (sig,)).fetchone()
|
||||
except Exception:
|
||||
return None
|
||||
if not row or not row["x_meta"]:
|
||||
return None
|
||||
try:
|
||||
return json.loads(row["x_meta"])
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def seed_pack(con, path):
|
||||
"""骨架包安装(2026-11-02 主人定两阶段架构:阶段二上市版「后台直接上传骨架包、
|
||||
租户客户端接收」——本函数是包→库的共用解包口,阶段一后台手动传包同走这里)。
|
||||
包 = zip,成员为 .cos/.cos4 原件(可带目录层),逐成员以其文件名(去扩展)为
|
||||
显示名 seed_frame;同名=升级替换。返回 [(显示名, 后缀, sig|None)](None=
|
||||
该成员不成结构,合法跳过不挡包);非 zip → None。"""
|
||||
out = []
|
||||
try:
|
||||
with zipfile.ZipFile(path) as z:
|
||||
for info in z.infolist():
|
||||
nm = info.filename
|
||||
if not _se.family_of(z.read(info)): # 决策 262:按内容认,不按后缀
|
||||
continue
|
||||
try: # zip 成员名常见 GBK 存 KB:cp437 转回
|
||||
nm2 = nm.encode("cp437").decode("gbk")
|
||||
except Exception:
|
||||
nm2 = nm
|
||||
ext = os.path.splitext(nm2)[1]
|
||||
fd, tmp = tempfile.mkstemp(suffix=ext)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
f.write(z.read(info))
|
||||
stem = os.path.splitext(os.path.basename(nm2))[0]
|
||||
sig = seed_frame(con, tmp, stem)
|
||||
out.append({"name": stem, "suffix": suffix_of(nm2), "sig": sig})
|
||||
finally:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
except zipfile.BadZipFile:
|
||||
return None
|
||||
return out
|
||||
|
||||
|
||||
def pick_frame(con, suffix, src_path=None, src_blob=None):
|
||||
"""导出骨架挑选(决策 260 补记八升级,2026-11-03 主人定「根据第一行的列选骨架;
|
||||
第一行相同找另外不相同的列;主要看原数据的列情况」):
|
||||
①原数据分层列集 vs 各骨架 x_layer_cols 指纹 → match_score 最高者
|
||||
(根列集完全一致=满分命中;逐层下探;无指纹的旧骨架退 Jaccard 兜底);
|
||||
②无源文件 → 最近入库的骨架。没有固定骨架 → rep_for(老行为)。"""
|
||||
_ensure_table(con)
|
||||
try:
|
||||
frames = con.execute("SELECT * FROM classic_skel WHERE suffix=? AND is_frame=1",
|
||||
(suffix,)).fetchall()
|
||||
except Exception:
|
||||
frames = []
|
||||
if not frames:
|
||||
return rep_for(con, suffix)
|
||||
if len(frames) == 1:
|
||||
return dict(frames[0])
|
||||
# 原数据分层列集
|
||||
src_cols = {}
|
||||
try:
|
||||
if src_blob:
|
||||
src_cols = layer_cols_of(src_blob)
|
||||
elif src_path and os.path.exists(src_path):
|
||||
src_cols = layer_cols_of(open(src_path, 'rb').read())
|
||||
except Exception:
|
||||
src_cols = {}
|
||||
if src_cols:
|
||||
best, best_s = None, -1.0
|
||||
for f in frames:
|
||||
s = None
|
||||
try:
|
||||
if f["x_layer_cols"]:
|
||||
skel_cols = json.loads(f["x_layer_cols"])
|
||||
# 决策 262:只认新指纹(v2 路径键);旧标签键指纹→按 v2 重算回写
|
||||
if isinstance(skel_cols, dict) and skel_cols.get("v") == 2:
|
||||
s = match_score(src_cols, skel_cols)
|
||||
except Exception:
|
||||
s = None
|
||||
if s is None:
|
||||
# 旧骨架/旧指纹 → 现场算(并回写 v2 指纹)
|
||||
try:
|
||||
skel_cols = layer_cols_of(f["blob"])
|
||||
s = match_score(src_cols, skel_cols)
|
||||
con.execute("UPDATE classic_skel SET x_layer_cols=? WHERE sig=?",
|
||||
(json.dumps(skel_cols, ensure_ascii=False), f["sig"]))
|
||||
con.commit()
|
||||
except Exception:
|
||||
s = -1.0
|
||||
if s > best_s:
|
||||
best, best_s = f, s
|
||||
if best is not None:
|
||||
return dict(best)
|
||||
return dict(max(frames, key=lambda f: (f["extracted_at"] or "", f["n_nodes"] or 0)))
|
||||
|
||||
|
||||
def stats(con):
|
||||
"""库内概况(体检/测试用):每组一行摘要。"""
|
||||
_ensure_table(con)
|
||||
return [dict(r) for r in con.execute(
|
||||
"SELECT suffix,original_name,n_shapes,n_nodes,extracted_at FROM classic_skel "
|
||||
"ORDER BY suffix, n_nodes DESC")]
|
||||
@@ -1,608 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""动态工料机汇总引擎(决策 188,2026-10-24 主人定;数量归零口径=决策 196,2026-10-25 主人定):
|
||||
单位工程汇总/项目级汇总不再读导入快照,而是从真源现算——
|
||||
骨架(决策 196): 空骨架保行——行集合=快照可见码∪现算码(项目级;单位级=本单位快照码∪本单位
|
||||
现算码,本单位快照无此码不出行),骨架只定行与属性槽、不供任何量;
|
||||
合并隐藏且链上无量的纯重复行仍不出。
|
||||
数量: 直接工料机=Σ(定额含量×定额真实工程量);子工料机=Σ(子含量×母定额含量×定额真实工程量)
|
||||
(=母量×子含量,数学全等)——同码双重身份相加,与 qty_map_uw 同式(2026-10-25 主人复确权);
|
||||
项目级=Σ各单位同键;链算不出一律归零(决策 196:快照值兜底取消,188 方案A原
|
||||
「直挂/费用科目行快照原样补位」随之废止,费用行量恒 0)。
|
||||
单价: 决策 219(2026-10-26 主人定)——主取价源=**单位级 s_lme_uw**(每单位每码认导入序第一行,
|
||||
同码不同价随便认一个);项目级行=单位级行按 全字段+三价 一致才归并、不一致各自独立,
|
||||
行量=各成员单位现算量之和;缺码/缺价兜底 s_lme_proj 快照;与源文件自带汇总不保证一致。
|
||||
带子级母行单价=Σ(子级含量×子级单价)(除税/含税各算各的,实测 990304016:Σ=1156.6425
|
||||
→1156.64 ✓),用户显式改过母行价=覆盖值(优先显示)。
|
||||
覆盖标记: s_settings 域键 lme_px_ov = {"码":1,...}(用户显式改过母行价);
|
||||
改子级价/含量 → 清其母的覆盖(母行回到 Σ 现算)。
|
||||
"""
|
||||
import json, os, threading
|
||||
|
||||
_QTY_EXPR_OK = __import__("re").compile(r"^[\d+\-*/().\s]*$")
|
||||
|
||||
|
||||
def gcl_of(bill_qty, unit):
|
||||
"""兼容旧调用的 GCL 原值——决策 216:GCL=清单工程量原值,单位因子只在公式结果上最后除。"""
|
||||
return round(float(bill_qty) if bill_qty is not None else 0.0, 6)
|
||||
|
||||
|
||||
def eval_qty_expr(expr, gcl):
|
||||
"""GCL 公式求值(决策 90;决策 205 从 api_server 收口到核心层供聚合链共用)。
|
||||
全角归一;除零/非法字符/非有限值返回 (None, msg);结果 round 6 位。"""
|
||||
import re
|
||||
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、数字和 + - * / ( )"
|
||||
try:
|
||||
v = eval(s, {"__builtins__": {}}, {"GCL": gcl}) # 字符集白名单已排除一切标识符/函数
|
||||
except ZeroDivisionError:
|
||||
return None, "公式除数为 0"
|
||||
except Exception:
|
||||
return None, "公式无法计算"
|
||||
v = float(v)
|
||||
if v != v or v in (float("inf"), float("-inf")):
|
||||
return None, "公式结果不是有限数"
|
||||
return round(v, 6), None
|
||||
|
||||
|
||||
def unit_factor(unit):
|
||||
"""定额单位数字前缀因子(10m3→10、1000m3→1000;纯字母/无数字=1)。决策 216 用。"""
|
||||
import import_job
|
||||
div = import_job.unit_prefix(unit)
|
||||
return div if div and div > 0 else 1.0
|
||||
|
||||
|
||||
def formula_qty(expr, bill_qty, unit):
|
||||
"""公式定额量——决策 216(2026-10-26 主人定,取代 90/106 的 GCL 先÷单位口径):
|
||||
GCL=**清单工程量原值**(不先除单位);公式不论多少层括号/加减乘除,
|
||||
**最后的结果整体÷单位数字前缀**=定额量。求值失败 → (None, msg)。"""
|
||||
v, msg = eval_qty_expr(expr, bill_qty if bill_qty is not None else 0.0)
|
||||
if v is None:
|
||||
return None, msg
|
||||
return round(v / unit_factor(unit), 6), None
|
||||
|
||||
|
||||
def _norm_qty(nq, expr, unit, bill_qty):
|
||||
"""定额量取数(决策 205;公式口径决策 216 改:GCL=清单原值,结果整体÷单位)。
|
||||
无公式用存储量(纯数字=实际量÷因子口径不变);都无 → None。"""
|
||||
if expr:
|
||||
try:
|
||||
v, _msg = formula_qty(expr, bill_qty, unit)
|
||||
if v is not None:
|
||||
return float(v)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
return float(nq) if nq is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _consumption_by_code(sc, sid, uw_id=None, by_uw=False):
|
||||
"""每码消耗量:{code: qty}。uw_id=None=全会话(项目级)。剔除临删定额/清单。
|
||||
决策 205(2026-10-25 主人定):定额量**按求值取数**——采纳挂 GCL 公式的定额
|
||||
(存储量 NULL,如 10# D3-6-5)此前整条丢掉,自算 0 vs 回导入 1,040 分叉的根因。
|
||||
决策 219 by_uw=True:一次扫描按单位分桶 {uw_id: {code: qty}}(项目级行量=各成员
|
||||
单位现算量之和——组量有真实归属,不再需要按比例分摊)。"""
|
||||
# ⚠️ s_norm_res 无 session_id 列——会话域经 norm→bill 链传达
|
||||
# 防御(与 dyn_rows 同款):老库可能缺 qty_expr/Unit 列 → 可选补位;
|
||||
# 但 **Quantity 必须存在**——缺失说明计算链不完整,抛错让 dyn_rows 退 None 走快照老路
|
||||
# (测试假库契约:src='agg' 回退,test_lme_price 实测)。
|
||||
have = lambda t, c: any(x[1] == c for x in sc.execute("PRAGMA table_info(%s)" % t))
|
||||
if not have("s_norms", "Quantity"):
|
||||
raise RuntimeError("s_norms 缺 Quantity 列:计算链不完整")
|
||||
sel_nq = "n.Quantity AS nq"
|
||||
sel_nex = "n.qty_expr AS nex" if have("s_norms", "qty_expr") else "NULL AS nex"
|
||||
sel_nu = "n.Unit AS nu" if have("s_norms", "Unit") else "NULL AS nu"
|
||||
sel_bq = "b.Quantity AS bq" if have("s_bills", "Quantity") else "NULL AS bq"
|
||||
sel_buw = "b.uw_id AS buw" if have("s_bills", "uw_id") else "NULL AS buw" # 决策 219 分桶
|
||||
sel_td_n = "COALESCE(n.x_tdel,0)=0" if have("s_norms", "x_tdel") else "1=1"
|
||||
sel_td_b = "COALESCE(b.x_tdel,0)=0" if have("s_bills", "x_tdel") else "1=1"
|
||||
sql = """SELECT nr.res_code AS c, nr.qty, n.id AS nid, %s,
|
||||
%s, %s, %s, %s
|
||||
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=? AND nr.res_code IS NOT NULL
|
||||
AND %s AND %s""" % (sel_nq, sel_nex, sel_nu, sel_bq, sel_buw, sel_td_n, sel_td_b)
|
||||
args = [sid]
|
||||
if uw_id is not None:
|
||||
sql += " AND b.uw_id=?"
|
||||
args.append(uw_id)
|
||||
out = {} # by_uw=True 时值= {uw_id: {code: qty}}
|
||||
cache = {} # norm_id → 求值后的定额量(同一定额只算一次)
|
||||
for r in sc.execute(sql, args):
|
||||
if not r["c"]:
|
||||
continue
|
||||
nid = r["nid"]
|
||||
if nid not in cache:
|
||||
cache[nid] = _norm_qty(r["nq"], r["nex"], r["nu"], r["bq"])
|
||||
nq = cache[nid]
|
||||
if nq is None:
|
||||
continue
|
||||
try:
|
||||
q = float(r["qty"] or 0) * nq
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if by_uw:
|
||||
b = out.setdefault(r["buw"], {})
|
||||
b[r["c"]] = b.get(r["c"], 0.0) + q
|
||||
else:
|
||||
out[r["c"]] = out.get(r["c"], 0.0) + q
|
||||
return out
|
||||
|
||||
|
||||
def _children_map(sc, sid):
|
||||
"""{母码: [(res_code, qty含量, name), ...]} 按 seq。"""
|
||||
out = {}
|
||||
for r in sc.execute("""SELECT p_code, res_code, qty, name FROM s_lme_res
|
||||
WHERE session_id=? ORDER BY p_code, seq, id""", (sid,)):
|
||||
out.setdefault(r["p_code"], []).append((r["res_code"], r["qty"], r["name"]))
|
||||
return out
|
||||
|
||||
|
||||
def _price_map(sc, sid):
|
||||
"""{code: {name,spec,unit,kind,ntp,taxrate,taxp,qty,id,hide,x_remark}} 项目级现值快照(价格/名规单/备注真值)。
|
||||
决策 219 起降为**兜底**(缺码/缺价才取)+行id/备注/隐藏标记来源;主取价源=单位级 _uw_price_rows。"""
|
||||
out = {}
|
||||
for r in sc.execute("""SELECT id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp,
|
||||
ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags,
|
||||
x_org_ntp0, x_org_taxp0,
|
||||
COALESCE(x_merged_hide,0) AS hid, x_remark
|
||||
FROM s_lme_proj WHERE session_id=?""", (sid,)):
|
||||
out[r["code"]] = dict(r)
|
||||
return out
|
||||
|
||||
|
||||
def _uw_price_rows(sc, sid):
|
||||
"""决策 219(2026-10-26 主人定):单位级取价——**同单位工程内按成员(码+除数量外全字段)
|
||||
分行**(2026-11-04 主人补:除数量外任一字段不同就是独立成员,不能合并/累计);
|
||||
同字段组合的多行才是同一成员(数量累计,价格取该行)。
|
||||
{code: [行dict(按 uw+成员 去重、id 序)]},行含 uw_id/名规单/类别/三价/六价扩展/flags。
|
||||
项目级汇总(_dyn_rows uw_id=None)以这张表为分组基础——单位级先对,项目级才对。"""
|
||||
out = {}
|
||||
for r in sc.execute("""SELECT id, uw_id, code, name, spec, unit, kind, ntp, taxrate, taxp,
|
||||
ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags
|
||||
FROM s_lme_uw WHERE session_id=? ORDER BY id""", (sid,)):
|
||||
if not r["code"]:
|
||||
continue
|
||||
lst = out.setdefault(r["code"], [])
|
||||
key = (str(r["uw_id"]), r["name"], r["spec"], r["unit"], r["kind"],
|
||||
r["ntp"], r["taxrate"], r["taxp"],
|
||||
r["ntp_org"], r["ntp_expr"], r["taxp_org"], r["taxp_expr"], r["x_flags"])
|
||||
if any(m.get("_mk") == key for m in lst):
|
||||
continue # 同单位同成员(字段全同)→ 合成一行
|
||||
d = dict(r)
|
||||
d["_mk"] = key
|
||||
lst.append(d)
|
||||
return out
|
||||
|
||||
|
||||
def _recode_away(sc, sid):
|
||||
"""已合并换码的旧码集(决策 219 显示端防复活:合并后单位级表可能还留着旧码行,
|
||||
与项目级隐藏口径不一致 → 不再显示,归并到保留码)。"""
|
||||
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='recode_map'",
|
||||
("session:%d" % sid,)).fetchone()
|
||||
try:
|
||||
rm = json.loads(row["v"] or "{}") if row else {}
|
||||
except (TypeError, ValueError):
|
||||
rm = {}
|
||||
return set(k for k, v in rm.items() if k and v and k != v)
|
||||
|
||||
|
||||
def _overrides(sc, sid):
|
||||
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_ov'", ("session:%d" % sid,)).fetchone()
|
||||
try:
|
||||
return json.loads(row["v"] or "{}") if row else {}
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def set_override(sc, sid, code, on):
|
||||
"""改母行价=置覆盖;改子级价/含量=清母覆盖。⚠️ 与调用方同 sc 连接。"""
|
||||
ov = _overrides(sc, sid)
|
||||
changed = False
|
||||
if on:
|
||||
if not ov.get(code):
|
||||
ov[code] = 1
|
||||
changed = True
|
||||
elif code in ov:
|
||||
del ov[code]
|
||||
changed = True
|
||||
if changed:
|
||||
sc.execute("INSERT INTO s_settings(scope,k,v) VALUES(?,?,?) ON CONFLICT(scope,k) DO UPDATE SET v=excluded.v",
|
||||
("session:%d" % sid, "lme_px_ov", json.dumps(ov)))
|
||||
|
||||
|
||||
def mothers_of(sc, sid, child_code):
|
||||
"""引用该子码的全部母码(清覆盖用)。"""
|
||||
return [r[0] for r in sc.execute(
|
||||
"SELECT DISTINCT p_code FROM s_lme_res WHERE session_id=? AND res_code=?", (sid, child_code))]
|
||||
|
||||
|
||||
def mark_manual_price(sc, sid, code):
|
||||
"""决策 191(2026-10-25 主人定):手工改价标记——合并态重放跳过被手工改过价的码。
|
||||
跨清场存活链:标记存 s_settings(无 session_id 列,天然不沾 wipe),价格真值由
|
||||
决策 68 快照 lme_vals 跨重解析带回,重放跑在快照回填之后 → 跳过=手工价存活。"""
|
||||
try:
|
||||
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_manual'",
|
||||
("session:%d" % sid,)).fetchone()
|
||||
m = json.loads(row["v"] or "{}") if row else {}
|
||||
if not m.get(code):
|
||||
m[code] = 1
|
||||
sc.execute("INSERT INTO s_settings(scope,k,v) VALUES(?,?,?) "
|
||||
"ON CONFLICT(scope,k) DO UPDATE SET v=excluded.v",
|
||||
("session:%d" % sid, "lme_px_manual", json.dumps(m)))
|
||||
except Exception:
|
||||
pass # 假库缺表/缺列 → 标记失败不挡编辑
|
||||
|
||||
|
||||
def manual_price_codes(sc, sid):
|
||||
"""决策 191:本会话被手工改过价的码集合(重放跳过用)。假库/缺表 → 空集。"""
|
||||
try:
|
||||
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_manual'",
|
||||
("session:%d" % sid,)).fetchone()
|
||||
return set(json.loads(row["v"] or "{}").keys()) if row else set()
|
||||
except Exception:
|
||||
return set()
|
||||
|
||||
|
||||
def dyn_rows(sc, sid, uw_id=None, keep_zero=False):
|
||||
"""动态汇总行(11 列同 _lme_rows 形状):[id,code,name,spec,unit,qty,ntp,taxrate,taxp,kind,remark]。
|
||||
id=项目级行 id(存在时)——前端行级改价按它定位;骨架行无库行时 id=None。
|
||||
防御:计算链不完整(老库/测试假库缺表缺列)→ 返回 None,调用方退回快照老路。
|
||||
keep_zero=True:2026-11-04 主人定「数量 0 也要参与合并工料机」——合并弹框取全量现算行,
|
||||
汇总页仍走默认过滤(决策 209 显示口径不动)。"""
|
||||
try:
|
||||
return _dyn_rows(sc, sid, uw_id, keep_zero)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dyn_rows(sc, sid, uw_id=None, keep_zero=False):
|
||||
kids = _children_map(sc, sid)
|
||||
pm = _price_map(sc, sid)
|
||||
ov = _overrides(sc, sid)
|
||||
uwp = _uw_price_rows(sc, sid) # 决策 219:主取价源=单位级(每单位每码认第一行)
|
||||
away = _recode_away(sc, sid) # 决策 219:合并换码的旧码不显示
|
||||
uwp = {c: lst for c, lst in uwp.items() if c not in away}
|
||||
# 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入)——手工会话没有源文件,
|
||||
# 单位级/项目级三步链全空,组成子行(折旧费/检修费…)价会落 0(2026-10-28 主人实测
|
||||
# 易达映射源里组成子行编制价全空);库快照垫在链条末尾
|
||||
lbm = {}
|
||||
try:
|
||||
for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp "
|
||||
"FROM s_lme_lib WHERE session_id=?", (sid,)):
|
||||
lbm[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"])
|
||||
except Exception:
|
||||
lbm = {}
|
||||
|
||||
# 决策 219 兜底:单位级行三价缺 → 项目级快照补(主人定「编号或单价实在没有的去项目级取」)
|
||||
for _c, _lst in uwp.items():
|
||||
_p = pm.get(_c)
|
||||
for _r in _lst:
|
||||
if _p:
|
||||
if _r["ntp"] is None:
|
||||
_r["ntp"] = _p["ntp"]
|
||||
if _r["taxrate"] is None:
|
||||
_r["taxrate"] = _p["taxrate"]
|
||||
if _r["taxp"] is None:
|
||||
_r["taxp"] = _p["taxp"]
|
||||
|
||||
def child_px(code, uw=None):
|
||||
"""子级三价(母行Σ用,决策 219):本单位行 → 第一行 → 项目级快照 → s_lme_lib 快照兜底。"""
|
||||
lst = uwp.get(code) or []
|
||||
r = None
|
||||
if uw is not None:
|
||||
r = next((m for m in lst if str(m["uw_id"]) == str(uw)), None)
|
||||
if r is None and lst:
|
||||
r = lst[0]
|
||||
p = pm.get(code) or {}
|
||||
_pk = lambda a, b: (a if a is not None else b)
|
||||
lb = lbm.get(code) or (None, None)
|
||||
return (_pk(_pk(r and r["ntp"], p.get("ntp")), lb[0]),
|
||||
_pk(r and r["taxrate"], p.get("taxrate")),
|
||||
_pk(_pk(r and r["taxp"], p.get("taxp")), lb[1]))
|
||||
|
||||
def _one_price_set(ch):
|
||||
"""同一母码可能按单位工程挂多套组成(ESCC:一处无后缀套、别处 -0003 换算套)——
|
||||
母价 Σ 只取**第一套**(按子码基码去重),避免两套相加把台班单价翻倍;
|
||||
数量传导仍用全量(变体子码各自得量)。"""
|
||||
seen, out = set(), []
|
||||
for c, q, nm in ch:
|
||||
base = (c or "").split("-")[0]
|
||||
if base in seen:
|
||||
continue
|
||||
seen.add(base)
|
||||
out.append((c, q, nm))
|
||||
return out
|
||||
|
||||
def computed_mother(code, uw=None):
|
||||
"""带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退行值)。"""
|
||||
sn = st = 0.0
|
||||
for c, q, _nm in _one_price_set(kids.get(code) or ()):
|
||||
ntp, _rt, taxp = child_px(c, uw)
|
||||
if ntp is None or taxp is None:
|
||||
return None, None
|
||||
try:
|
||||
sn += float(q or 0) * float(ntp)
|
||||
st += float(q or 0) * float(taxp)
|
||||
except (TypeError, ValueError):
|
||||
return None, None
|
||||
return round(sn, 2), round(st, 2)
|
||||
|
||||
_SNAP_KEYS = ("name", "spec", "unit", "kind", "ntp", "taxrate", "taxp")
|
||||
|
||||
def mk_row(code, r, qty):
|
||||
"""16 列行(决策 259 前 11 列)。r=认下的单位级行(或快照 dict);带子级母行 Σ 现算(除非覆盖)。
|
||||
尾部 5 元素=六价扩展四值(ntp_org/ntp_expr/taxp_org/taxp_expr,决策 219 同链:认下行 →
|
||||
项目级快照补缺 → lib 无 org 即 None)+ x_flags(文字/标志属性 JSON,原文件有才导)。"""
|
||||
p = pm.get(code) or {}
|
||||
ntp, rate, taxp = r.get("ntp"), r.get("taxrate"), r.get("taxp")
|
||||
_pk6 = lambda a, b: (a if a is not None else b)
|
||||
org4 = tuple(_pk6(r.get(k), p.get(k)) for k in ("ntp_org", "ntp_expr", "taxp_org", "taxp_expr"))
|
||||
# 定额单价专题(2026-11-03 主人定):原价第③级兜底=第一次外部采纳价(x_org_*0,
|
||||
# 采纳落价时列空才写);①单位级 → ②项目级 → ③此列;Expr(调价式)无采纳源、不兜底。
|
||||
_o = list(org4)
|
||||
if _o[0] is None and p.get("x_org_ntp0") is not None:
|
||||
_o[0] = p["x_org_ntp0"]
|
||||
if _o[2] is None and p.get("x_org_taxp0") is not None:
|
||||
_o[2] = p["x_org_taxp0"]
|
||||
org4 = tuple(_o)
|
||||
# s_lme_lib 快照兜底(手工会话没有源文件:单位级/项目级行都没有,组成子行
|
||||
# 折旧费/检修费等的名称/单位/单价从这里来——2026-10-28 主人实测映射源价全空)
|
||||
lb = lbm.get(code)
|
||||
if lb is not None:
|
||||
_nm2, _sp2, _un2, _kd2, _ln, _lt = lb
|
||||
if not (r.get("name") or "") and _nm2:
|
||||
r = dict(r, name=_nm2, spec=(r.get("spec") or _sp2 or ""),
|
||||
unit=(r.get("unit") or _un2 or ""),
|
||||
kind=(r.get("kind") if r.get("kind") is not None else _kd2))
|
||||
if ntp is None:
|
||||
ntp = _ln
|
||||
if taxp is None:
|
||||
taxp = _lt
|
||||
# 2026-11-04 主人按原件定(990401025 载货汽车 552.75 / 637.29 两价并存、各配一套子级):
|
||||
# **有源价用源价,只有缺价时才用 Σ 子级兜底**——决策 188 的「带子级母行单价=Σ子级」
|
||||
# 据此收窄:若强行 Σ 覆盖,同码多成员(不同价)会被算成同一个价,违反
|
||||
# 「除数量外字段不一致就分多条」的显示规则(原版就是两条)。
|
||||
if kids.get(code) and not ov.get(code) and (ntp is None or taxp is None):
|
||||
cn, ct = computed_mother(code, r.get("uw_id"))
|
||||
if cn is not None:
|
||||
ntp = ntp if ntp is not None else cn
|
||||
taxp = taxp if taxp is not None else ct
|
||||
return [p.get("id"), code, r.get("name") or "", r.get("spec") or "", r.get("unit") or "",
|
||||
qty, ntp, rate, taxp, r.get("kind"), p.get("x_remark"), # 决策 203:备注随行(采纳/手工同字段)
|
||||
*org4, ((r.get("x_flags") if r.get("x_flags") is not None else p.get("x_flags"))
|
||||
if (r.get("x_flags") is not None or p.get("x_flags") is not None) else None)]
|
||||
|
||||
rows, seen = [], set()
|
||||
if uw_id is not None:
|
||||
# —— 单位工程级(决策 219):本单位每码一行(认第一行),量=本单位现算(含子级推导)
|
||||
qmap = qty_map_uw(sc, sid, uw_id)
|
||||
mine = [(code, r) for code, lst in uwp.items() for r in lst
|
||||
if str(r["uw_id"]) == str(uw_id)] # id 序=源文件序(顺序锚,决策 41)
|
||||
for code, r in mine:
|
||||
seen.add(code)
|
||||
rows.append(mk_row(code, r, qmap.get(code) or 0.0))
|
||||
for code in qmap: # 本单位现算有量而表无行的码(名从快照/子级兜底)
|
||||
if code and code not in seen and code not in away:
|
||||
seen.add(code)
|
||||
p = pm.get(code) or {}
|
||||
rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])),
|
||||
qmap.get(code) or 0.0))
|
||||
else:
|
||||
# —— 项目级(决策 219):全字段+三价一致的单位级行才并成一行,不一致各自独立;
|
||||
# 行量=各成员单位现算量之和(真实归属,不按比例分摊)
|
||||
# 2026-11-04 主人定「改哪个单位只算哪个单位」:量图走缓存(qmap_all_cached),
|
||||
# 分桶+子级传导收敛到 _propagate 一处(取代此前活读迭代,与 qty_map_uw 快照迭代
|
||||
# 两处不一致的写法——仅「子级自己带子级」时两法才有差异,现库无此情形)。
|
||||
qmaps = qmap_all_cached(sc, sid)
|
||||
groups, gidx = [], {}
|
||||
for code, lst in uwp.items(): # 顺序锚=单位级行 id 序(源文件序)
|
||||
for r in lst:
|
||||
k = (code, r["name"] or "", r["spec"] or "", r["unit"] or "", r["kind"],
|
||||
r["ntp"], r["taxrate"], r["taxp"],
|
||||
r.get("ntp_org"), r.get("ntp_expr"), r.get("taxp_org"), r.get("taxp_expr"),
|
||||
r.get("x_flags")) # 2026-11-04:成员=除数量外全字段(任一不同各成一行)
|
||||
g = gidx.get(k)
|
||||
if g is None:
|
||||
g = {"code": code, "r": r, "uws": []}
|
||||
gidx[k] = g
|
||||
groups.append(g)
|
||||
g["uws"].append(r["uw_id"])
|
||||
for g in groups:
|
||||
code = g["code"]
|
||||
seen.add(code)
|
||||
qty = 0.0
|
||||
for u in g["uws"]:
|
||||
qty += qmaps.get(u, {}).get(code) or 0.0
|
||||
rows.append(mk_row(code, g["r"], qty))
|
||||
for code, p in pm.items(): # 兜底:单位表全无、仅项目级有的码
|
||||
if not code or code in seen or code in away or p.get("hid"):
|
||||
continue
|
||||
seen.add(code)
|
||||
qty = 0.0
|
||||
for qm in qmaps.values():
|
||||
qty += qm.get(code) or 0.0
|
||||
rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), qty))
|
||||
_extra = {} # 现算有量而两处都无行的码(名从子级/快照兜底)
|
||||
for qm in qmaps.values():
|
||||
for code, q in qm.items():
|
||||
if code:
|
||||
_extra[code] = _extra.get(code, 0.0) + (q or 0.0)
|
||||
for code, q in _extra.items():
|
||||
if code not in seen and code not in away:
|
||||
seen.add(code)
|
||||
p = pm.get(code) or {}
|
||||
rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), q))
|
||||
# 名称空白的子级行:从 lme_res.name 兜底
|
||||
for row in rows:
|
||||
if not row[2]:
|
||||
for mcode, ch in kids.items():
|
||||
for c, q, nm in ch:
|
||||
if c == row[1] and nm:
|
||||
row[2] = nm
|
||||
break
|
||||
# 决策 209(2026-10-26 主人定):显示端与导出端一致(199)——数量为 0 的行整行不显示,
|
||||
# 取代 196「骨架保行」的显示端口径;导出端 199 与 qty_map_uw 供数链不经过此处,不动。
|
||||
# 2026-11-04 主人定(合并工料机):keep_zero=True 时全量返回——0 量品种也要能参与合并。
|
||||
if keep_zero:
|
||||
return rows
|
||||
return [r for r in rows if r[5] is not None and float(r[5]) != 0]
|
||||
|
||||
|
||||
def dyn_uw_rows(sc, sid, uw_id):
|
||||
"""单位工程级 14 列(决策 259):前 9 列同 _raw_uw lme 形状 [码,名,规,单,类别,量,除税,税率,含税],
|
||||
尾部追加六价扩展四值 + x_flags(导出链灌 org/调价式/Total 用;显示端截前 9 列)。链不全→None。"""
|
||||
try:
|
||||
return [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8],
|
||||
r[11], r[12], r[13], r[14], r[15] if len(r) > 15 else None]
|
||||
for r in _dyn_rows(sc, sid, uw_id)]
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dyn_rows_safe9(sc, sid, uw_id):
|
||||
try:
|
||||
return [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8]] for r in _dyn_rows(sc, sid, uw_id)]
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dyn_uw_rows_old(sc, sid, uw_id):
|
||||
return [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8]] for r in dyn_rows(sc, sid, uw_id)]
|
||||
|
||||
# ── 量图缓存(2026-11-04 主人定「改哪个单位只算哪个单位,项目级再汇总」)──────────
|
||||
# 现算结果 {uw_id: {码: 量}} 按 (库文件路径, 会话id) 挂进程内存:
|
||||
# · 读(单位级卡/项目级卡/合并弹框/导出/检索)统一走 qmap_all_cached——首次惰性建
|
||||
# (一次全扫,成本=原项目级卡一次现算),之后其余单位继续用缓存;
|
||||
# · 改定额量/清单量/定额消耗量 → api_server 路由层在 commit 后调 qmap_touch_uw
|
||||
# 只重算该单位;含量编辑/临删恢复/采纳/结构增删/合并/重解析 → qmap_drop 全失效;
|
||||
# · 库文件 mtime 兜底网:任何漏钩写入(含外部进程)都会在下一次读取被发现并整图重建;
|
||||
# · :memory: 库(pytest 假库)不缓存直接现算——与旧全算行为一致,测试无隔离风险。
|
||||
# 母子传导收敛:_propagate 一处实现(从直接消耗量快照出发、只传一层,决策 268补三 口径),
|
||||
# 取代此前 qty_map_uw(快照迭代)与项目级分桶(活读迭代)两处不一致的写法(2026-11-04 主人拍板)。
|
||||
_QLOCK = threading.Lock()
|
||||
_QCACHE = {} # (db_path, sid) -> {"mtime": float, "maps": {uw_id: {码: 量}}}
|
||||
|
||||
|
||||
def _qpath_mt(sc):
|
||||
"""(库文件路径, mtime);:memory: 路径为空 → 调用方旁路缓存。"""
|
||||
path = ""
|
||||
try:
|
||||
for r in sc.execute("PRAGMA database_list").fetchall():
|
||||
if r[1] == "main":
|
||||
path = r[2] or ""
|
||||
break
|
||||
except Exception:
|
||||
path = ""
|
||||
mt = 0.0
|
||||
if path:
|
||||
try:
|
||||
mt = os.path.getmtime(path)
|
||||
except OSError:
|
||||
mt = 0.0
|
||||
return path, mt
|
||||
|
||||
|
||||
def qmap_mtime_of(sc):
|
||||
"""写入口取「写前库 mtime」用(api_server 持 WRITE_LOCK,读与写同线程同库)。"""
|
||||
return _qpath_mt(sc)[1]
|
||||
|
||||
|
||||
def _propagate(base, kids):
|
||||
"""母子传导唯一实现:子量 = 母量 × 子含量,从直接消耗量快照出发只传一层
|
||||
(决策 268补三 2026-11-04 主人定口径;子级自己带子级不二次传导)。"""
|
||||
out = dict(base)
|
||||
for mcode, mq in base.items():
|
||||
if mq is None:
|
||||
continue
|
||||
for c, q, _nm in kids.get(mcode) or ():
|
||||
try:
|
||||
out[c] = out.get(c, 0.0) + float(mq) * float(q or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
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()}
|
||||
|
||||
|
||||
def qmap_all_cached(sc, sid):
|
||||
"""全单位量图缓存读口:{uw_id: {码: 现算量}}。链不全(老库缺列)照旧抛 RuntimeError,
|
||||
由 dyn_rows 退 None 走快照老路——与全算时代同一退路。"""
|
||||
path, mt = _qpath_mt(sc)
|
||||
if not path:
|
||||
return _qmap_build_all(sc, sid)
|
||||
key = (path, int(sid))
|
||||
with _QLOCK:
|
||||
ent = _QCACHE.get(key)
|
||||
if ent is not None and ent["mtime"] == mt:
|
||||
return ent["maps"]
|
||||
maps = _qmap_build_all(sc, sid)
|
||||
with _QLOCK:
|
||||
_QCACHE[key] = {"mtime": mt, "maps": maps}
|
||||
return maps
|
||||
|
||||
|
||||
def qmap_touch_uw(sc, sid, uw_id, pre_mt=None):
|
||||
"""「改哪个单位只算哪个单位」:只重算该单位量图、刷缓存戳(其余单位继续用缓存)。
|
||||
调用约定:api_server 在 commit 之后、WRITE_LOCK 之内调用;pre_mt=写前库 mtime——
|
||||
与缓存戳不一致说明其间有别的写者插队,保守放弃缓存(下次读取整图重建)。"""
|
||||
path, mt_now = _qpath_mt(sc)
|
||||
if not path:
|
||||
return
|
||||
key = (path, int(sid))
|
||||
with _QLOCK:
|
||||
ent = _QCACHE.get(key)
|
||||
if ent is not None and pre_mt is not None and ent["mtime"] != pre_mt:
|
||||
_QCACHE.pop(key, None) # 期间有并发写 → 缓存不可信,整图放弃
|
||||
ent = None
|
||||
if ent is None:
|
||||
return
|
||||
try:
|
||||
umap = _propagate(_consumption_by_code(sc, sid, uw_id), _children_map(sc, sid))
|
||||
except Exception:
|
||||
with _QLOCK:
|
||||
_QCACHE.pop(key, None)
|
||||
return
|
||||
with _QLOCK:
|
||||
ent = _QCACHE.get(key)
|
||||
if ent is not None:
|
||||
ent["maps"][uw_id] = umap
|
||||
ent["mtime"] = mt_now
|
||||
|
||||
|
||||
def qmap_drop(sid=None):
|
||||
"""量图全失效(含量编辑/临删恢复/采纳/结构增删/合并/重解析/删会话);
|
||||
sid=None 清全部(测试收尾用)。下次读取整图重建一次,成本=原项目级卡一次现算。"""
|
||||
with _QLOCK:
|
||||
if sid is None:
|
||||
_QCACHE.clear()
|
||||
else:
|
||||
for k in [k for k in _QCACHE if k[1] == int(sid)]:
|
||||
_QCACHE.pop(k, None)
|
||||
|
||||
|
||||
def qty_map_uw_all(sc, sid):
|
||||
"""全部单位工程的 {uw_id: {码: 现算数量}}——量图缓存读口(2026-11-04 主人定)。
|
||||
首次一次全扫建缓存,之后读缓存;改定额量/清单量由写入口单算刷新(qmap_touch_uw),
|
||||
其余数量链改动整图失效(qmap_drop)。与旧「一次扫描」同形同值。"""
|
||||
return qmap_all_cached(sc, sid)
|
||||
|
||||
|
||||
def qty_map_uw(sc, sid, uw_id):
|
||||
"""决策 188 数量模型(主人定稿)——某单位工程的 {码: 数量} 现算图:
|
||||
母/直挂: Σ(定额含量 × 定额真实工程量)
|
||||
子工料机: Σ(子含量 × 母定额含量 × 定额真实工程量) (=母量×子含量,数学全等已证)
|
||||
只算不写库(原字段不动);导出/显示共同数据源。
|
||||
2026-11-04:走量图缓存(qmap_all_cached)——首次建缓存=一次全扫,之后从缓存取。"""
|
||||
return qmap_all_cached(sc, sid).get(uw_id) or {}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,954 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手工工程导出(决策 231,2026-10-27 主人定):经典整件骨架当模板,我方清单级数据填空。
|
||||
|
||||
口径(主人逐条拍板):
|
||||
· 骨架只在导出时用;内部数据只管采纳。单位工程→清单的计价信息按采纳数值,
|
||||
可计算的(清单合价、分部/容器合计)现算;**其他一切按骨架**(建设单位/编制人/
|
||||
取费程序/费用汇总等工程级信息=代表件保留值,铁律 5 本通道调整);
|
||||
· 我方清单下的定额/工料机=**克隆架子清值**:从骨架件挑最全样板清单整块克隆
|
||||
(费用构成汇总+定额/工料机架子全保留——决策 106:易达按 SummaryOfBasicCost
|
||||
认清单),量价结果与含量式全清、结构属性原样,易达/广联达打开按结构重算;
|
||||
· 分部层级=我方 s_divides 树递归映射原生 DivisionalWorks 嵌套(原生实测:子分部
|
||||
就是 DivisionalWorks 里嵌 DivisionalWorks,南屏 cos 实嵌 3 层;分部 Number 原生
|
||||
即空串,Name/Total 落我方,Quantity/TechnicalAndEconomicIndex 指标清零不背旧值);
|
||||
· 措施项目一起导:原生直接挂 Preliminaries 下,骨架有 PreliminaryDivisionalWorks
|
||||
包装层就克隆一层包装;
|
||||
· 工料机汇总节点:架子在、行不进(我方无工料机数据,别人的行不混入,决策 199 同源);
|
||||
· Project.xml 只改名字:工程名/单项名/单位名落我方;**UnitWorks 引用节点的 Number
|
||||
不动**(它关联成员文件名,动了断链,原生件名 @_001-1_… 实测);其余=保留值;
|
||||
· 多后缀:cos/cos4 各取各的代表件,画像天然正确;SWT/SWZ 等后期注册。
|
||||
实现:整件字节外科手术,复用 export_cos 的样板挑选/属性改写/结果值清零引擎
|
||||
(决策 106/198/204 同款),不碰会话采纳与合并工料机内部逻辑(主人定:内部零改动)。
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
|
||||
import classic_skeleton
|
||||
import export_cos as ec
|
||||
import dyn_lme
|
||||
from formats.skeleton import build_plan, num as _num
|
||||
|
||||
_LME_SUM = "LabourMaterialsEquipmentsMachinesSummary"
|
||||
_ITEM_CONT = "DivisionalAndElementalWorks" # 分部分项容器(cos 族两代同名)
|
||||
_PRE_CONT = "Preliminaries" # 措施项目容器
|
||||
_DW = "DivisionalWorks" # 分部(嵌套=子分部,原生实测)
|
||||
_DW_PRE = "PreliminaryDivisionalWorks" # 措施分部包装层(有则克隆,无则不造)
|
||||
_ITEM_BILL = "WorkElement"
|
||||
_PRE_BILL = "UnitWorksPreliminaryWorkElement"
|
||||
_SEC_TAGS = ("SectionalWorks", "DivisionalAndElementalProject") # 单项工程层(cos/cos4 各叫其一)
|
||||
_ROOT_TAGS = ("ConstructionProject", "ConstructProject")
|
||||
_MAX_DEPTH = 8 # 分部递归保险(我方上限 4 级,决策 230)
|
||||
|
||||
|
||||
def _money(v):
|
||||
if v is None:
|
||||
return "0"
|
||||
try:
|
||||
return "%.2f" % round(float(v), 2)
|
||||
except (TypeError, ValueError):
|
||||
return "0"
|
||||
|
||||
|
||||
def _span(txt, tag, start=0):
|
||||
"""首个 <tag …>…</tag> 的 (s,e)(e 含闭标签);自闭合返回 (s, 开标签止);
|
||||
属性值里的 '>' 用 _open_tag_end 越过;同名嵌套按深度配对。找不到 → None。"""
|
||||
m = re.compile(r"<%s\b" % tag).search(txt, start)
|
||||
if not m:
|
||||
return None
|
||||
s = m.start()
|
||||
oe = ec._open_tag_end(txt, s)
|
||||
if oe < 0:
|
||||
return None
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
return (s, oe)
|
||||
depth, pos = 1, oe
|
||||
while depth:
|
||||
mn = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(txt, pos)
|
||||
if not mn:
|
||||
return None
|
||||
if mn.group(0)[1] == "/":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return (s, mn.end())
|
||||
pos = mn.end()
|
||||
continue
|
||||
o2 = ec._open_tag_end(txt, mn.start())
|
||||
if o2 < 0:
|
||||
return None
|
||||
if txt[o2 - 2:o2] == "/>":
|
||||
pos = o2 # 自闭合同名子行=完整元素,不进深度(2026-10-28 修:
|
||||
continue # 合成件 Summary 子行把深度顶穿→容器配对 None→只删开标签留孤儿闭合)
|
||||
depth += 1
|
||||
pos = o2
|
||||
return None
|
||||
|
||||
|
||||
def _opentag(txt, tag, start=0):
|
||||
m = re.compile(r"<%s\b" % tag).search(txt, start)
|
||||
if not m:
|
||||
return None
|
||||
e = ec._open_tag_end(txt, m.start())
|
||||
return txt[m.start():e] if e > 0 else None
|
||||
|
||||
|
||||
def _block_tag(blk):
|
||||
m = re.match(r"<(\w+)", blk or "")
|
||||
return m.group(1) if m else _ITEM_BILL
|
||||
|
||||
|
||||
def _bill_block(sample_blk, b, norm_tmpl, express_by_norm, txt):
|
||||
"""我方一条清单 → 整块(决策 231①+补记,主人定「和标准采纳一样」):
|
||||
· 有采纳定额 → 走 export_cos 同款引擎挂**真实定额**(_norm_xml:费用构成/单价计算
|
||||
innards 克隆、消耗量行重写、清单级工料机尾表按消耗量现算,决策 98/106);
|
||||
· 没采纳 → **克隆架子清值**(231①,主人 2026-10-28 复确认):cos 清单架子导出、
|
||||
值全清=「还没组价」的形态。
|
||||
工程量按数据本体精度回写(_bill_xml 内部按单件 3 位规律写会截 6 位量,三溪实测)。"""
|
||||
ns = [n for n in (b.get("norms") or []) if not n.get("x_tdel")]
|
||||
# 补记十五(2026-10-28 主人定「分部/清单/定额/工料机全部按自己的值,不能采用骨架值
|
||||
# 兜底」——推翻 231①/补记二的「未采纳=克隆架子清值」):没定额=我方五值+**无定额**
|
||||
# 清单(采纳过源本无定额与未采纳同形态),不套骨架样例定额;骨架只出结构不出值
|
||||
if not ns:
|
||||
return ec._bill_xml(b, _block_tag(sample_blk or _ITEM_BILL), [],
|
||||
template=sample_blk or None, txt=txt)
|
||||
norms_xml = []
|
||||
for n in ns:
|
||||
lres = (express_by_norm or {}).get(n["id"]) or n.get("res") or []
|
||||
norms_xml.append(ec._norm_xml(n, lres, template=norm_tmpl,
|
||||
bill_qty=b.get("Quantity")))
|
||||
t = ec._bill_xml(b, _block_tag(sample_blk or _ITEM_BILL), norms_xml,
|
||||
template=sample_blk or None, txt=txt)
|
||||
oe = ec._open_tag_end(t, 0)
|
||||
if oe > 0:
|
||||
ot = t[:oe]
|
||||
if b.get("Quantity") is not None:
|
||||
ot = ec._attr_set(ot, "Quantity", _num(b.get("Quantity")))
|
||||
if not b.get("Number") and ' Number="' in ot:
|
||||
ot = ec._attr_set(ot, "Number", "") # 编码空=空("0" 是数值占位口径)
|
||||
t = ot + t[oe:]
|
||||
return t
|
||||
|
||||
|
||||
_LME_FILL_ROOTS = ("UnitWorks", "ConstructionProject", "ConstructProject",
|
||||
"ProjectInstallationWorkCost")
|
||||
|
||||
|
||||
def _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=None, lib=None):
|
||||
"""现算行 → 行列 HTML(决策 231 补记五,主人拍板「按现有数据生成」):
|
||||
行模板照骨架本件形态(198 槽不造);台班/配合比码带子级组成(s_lme_res)
|
||||
→ 行转容器+子行;量 0 不导(199)。"""
|
||||
out = []
|
||||
dyn_codes = {str(r[0]) for r in rows9 or []}
|
||||
# 组成子码全单位总额(2026-10-28 主人实测易达映射源组成子行编制价全空后的补行依据;
|
||||
# 原生件铁证:折旧费等组成码在单位表**各有一行自己的价**,量=Σ(母现算量×构成值)——
|
||||
# 构成值就是台班单价的组成(折旧3.44+检修0.80+…=台班价14.10),量×价1.00=总价)
|
||||
comp_tot = {}
|
||||
for r in rows9 or []:
|
||||
for c, q in (children or {}).get(str(r[0])) or []:
|
||||
try:
|
||||
comp_tot[c] = comp_tot.get(c, 0.0) + float(q or 0) * float(r[5] or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
comp_done = set()
|
||||
# 决策 259(2026-11-02 主人定「骨架不能创造数据」):行 16 列(前 11 列同旧)尾部=
|
||||
# 六价扩展四值 + x_flags(文字/标志属性 JSON)。导出三原则:
|
||||
# ①数值属性一律灌项目真值(org=库基准价、四 Total=现算量×对应价);②来源没有的
|
||||
# 属性整个删掉(不灌空、不造值);③文字/标志属性按 flags 有无灌/删。
|
||||
_DATA_ATTRS = ("NoTaxOrgPrice", "NoTaxPriceExpress", "TaxOrgPrice", "TaxPriceExpress",
|
||||
"NoTaxOrgTotal", "NoTaxTotal", "TaxOrgTotal", "TaxTotal",
|
||||
"PriceSource", "Remark")
|
||||
_FLAG_ATTRS = ("LossRate", "Class", "Concrete", "ExtKind", "AddiKind", "MainMaterial",
|
||||
"ProvisionalMaterial", "Provider", "Delivery", "Location",
|
||||
"ProducingArea", "Supplier", "Character")
|
||||
for r in rows9 or []:
|
||||
code, name, spec, unit, kind, qty, ntp, taxrate, taxp = r[:9]
|
||||
try:
|
||||
if float(qty or 0) == 0:
|
||||
continue
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
org4 = (tuple(r[9:13]) + (None,) * 4)[:4] if len(r) >= 14 else (None,) * 4 # 决策 259:导出序 14 列(9+4+flags)
|
||||
flags = r[13] if len(r) > 13 else None
|
||||
t = ec._lme_row(row_tmpl, code, _num(qty))
|
||||
if t.endswith("/>"): # 模板恒自闭合 → 先转开标签再灌/删属性
|
||||
t = t[:-2] + ">" # (_attr_set 对自闭合行新增属性会挤掉 /> 产生残缺标签)
|
||||
t = ec._attr_set_has(t, "Name", name or "")
|
||||
t = ec._attr_set_has(t, "Specification", spec or "")
|
||||
t = ec._attr_set_has(t, "Unit", unit or "")
|
||||
if kind:
|
||||
t = ec._attr_set_has(t, "Kind", str(int(kind)))
|
||||
for k, v in (("Quantity", _num(qty)), ("NoTaxPrice", _money(ntp)),
|
||||
("TaxRate", _money(taxrate)), ("TaxPrice", _money(taxp))):
|
||||
t = ec._attr_set_has(t, k, v)
|
||||
# ①先删全部数据/标志属性(清模板残留),②有来源的再灌真值——「原文件有才导」
|
||||
# (flags=None=存量未采集=视为原文件没有 → 标志属性同样删,重导恢复)
|
||||
for k in _DATA_ATTRS + _FLAG_ATTRS:
|
||||
t = ec._attr_del(t, k)
|
||||
_ntp_org, _ntp_expr, _taxp_org, _taxp_expr = org4
|
||||
_fx = {}
|
||||
if flags:
|
||||
try:
|
||||
_fx = json.loads(flags)
|
||||
except Exception:
|
||||
_fx = {}
|
||||
if _ntp_org is not None:
|
||||
t = ec._attr_set(t, "NoTaxOrgPrice", _money(_ntp_org))
|
||||
t = ec._attr_set(t, "NoTaxOrgTotal", _money(float(qty) * float(_ntp_org)))
|
||||
if _taxp_org is not None:
|
||||
t = ec._attr_set(t, "TaxOrgPrice", _money(_taxp_org))
|
||||
t = ec._attr_set(t, "TaxOrgTotal", _money(float(qty) * float(_taxp_org)))
|
||||
if _ntp_expr is not None:
|
||||
t = ec._attr_set(t, "NoTaxPriceExpress", str(_ntp_expr))
|
||||
if _taxp_expr is not None:
|
||||
t = ec._attr_set(t, "TaxPriceExpress", str(_taxp_expr))
|
||||
t = ec._attr_set(t, "NoTaxTotal", _money(float(qty) * float(ntp or 0))) # 现价链永有→Total 永灌
|
||||
t = ec._attr_set(t, "TaxTotal", _money(float(qty) * float(taxp or 0)))
|
||||
for k, v in _fx.items(): # 文字/标志:原文件有才灌
|
||||
t = ec._attr_set(t, k, v)
|
||||
kids = (children or {}).get(str(code))
|
||||
if kids and child_tmpl:
|
||||
# 原生排版(两骨架实测):母行开标签→换行缩进→子行逐行同缩进→闭合标签前换行缩进
|
||||
ci = (ind or {}).get("ci") or "\n "
|
||||
cc = (ind or {}).get("cc") or "\n "
|
||||
inner = ci + ci.join(ec._child_node(child_tmpl, c, q) for c, q in kids)
|
||||
t = t + inner + cc + "</%s>" % _LME_SUM
|
||||
else:
|
||||
t = t[:-1] + "/>" # 无子级(或无子行模板)=直接走自闭合(2026-11-02 主人定)
|
||||
out.append(t)
|
||||
# 组成子码自有行(价格源行):紧跟首个引用它的母容器行(首现序),每码只补一行;
|
||||
# 已有现算行的码不补(直耗行已带价);名称/规格/单位/类别/单价取 s_lme_lib 快照
|
||||
for c, _q in (kids or ()):
|
||||
if c in dyn_codes or c in comp_done:
|
||||
continue
|
||||
lb = (lib or {}).get(c)
|
||||
if not lb or not comp_tot.get(c):
|
||||
continue
|
||||
nm2, sp2, un2, kd2, ntp2, taxp2 = lb
|
||||
|
||||
t2 = ec._lme_row(row_tmpl, c, _num(comp_tot[c]))
|
||||
t2 = ec._attr_set_has(t2, "Name", nm2 or "")
|
||||
t2 = ec._attr_set_has(t2, "Specification", sp2 or "")
|
||||
t2 = ec._attr_set_has(t2, "Unit", un2 or "")
|
||||
if kd2:
|
||||
try:
|
||||
t2 = ec._attr_set_has(t2, "Kind", str(int(kd2)))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
t2 = ec._attr_set_has(t2, "NoTaxPrice", _money(ntp2))
|
||||
t2 = ec._attr_set_has(t2, "TaxPrice", _money(taxp2))
|
||||
t2 = ec._attr_set_has(t2, "TaxRate", _money(0))
|
||||
out.append(t2)
|
||||
comp_done.add(c)
|
||||
return out
|
||||
|
||||
|
||||
def _lme_fill(txt, rows9=None, children=None, row_tmpl=None, child_tmpl=None, ind=None,
|
||||
lib=None):
|
||||
"""根层工料机汇总行(决策 231 补记五推翻补记三的「清空」定论——易达标准骨架铁证:
|
||||
单位成员根层直挂的 LME_SUM=**单位级汇总表**(每码一行、台班带子级嵌套);项目成员
|
||||
PIWC 内同款=项目级汇总表。骨架行/子行照本件形态克隆,灌**现算行**(主人拍板:
|
||||
定额工程量×消耗量,dyn 引擎)+台班子级组成;无现算行 → 清空(架子在、别人的行不进);
|
||||
行/子行模板缺位时本件全局取(调用方传入)。"""
|
||||
if not row_tmpl:
|
||||
return _lme_clear(txt)
|
||||
sep = ec._native_sep(txt, _LME_SUM, "") or (ind or {}).get("sep") or "\n"
|
||||
keep = _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=ind, lib=lib)
|
||||
spans, stack, pos, n = [], [], 0, len(txt)
|
||||
while pos < n:
|
||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
if m.group(1) == "/":
|
||||
t = m.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t:
|
||||
del stack[i:]
|
||||
break
|
||||
pos = m.end()
|
||||
continue
|
||||
tag = m.group(2)
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
if oe < 0:
|
||||
break
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
spans.append((m.start(), oe))
|
||||
pos = oe
|
||||
continue
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
sp = _span(txt, _LME_SUM, m.start())
|
||||
spans.append((m.start(), sp[1] if sp else oe))
|
||||
pos = sp[1] if sp else oe
|
||||
continue
|
||||
stack.append(tag)
|
||||
pos = oe
|
||||
if not spans:
|
||||
# 空槽成员没有旧行=没有锚(2026-10-28 实测:易达骨架 31 位仅 3 位有汇总行,其余
|
||||
# 单位整表不插)。按原生「表在根尾」位补插(UnitWorksSummary 之后、根闭标签之前,
|
||||
# 两骨架有行成员同款)。首行不补分隔——插入点前已有原生换行。
|
||||
if not keep:
|
||||
return txt
|
||||
m = re.search(r"</([A-Za-z_][\w.]*)>\s*$", txt)
|
||||
anchor = m.start() if m else len(txt)
|
||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
||||
return txt[:anchor] + body + txt[anchor:]
|
||||
anchor = spans[0][0]
|
||||
for s, e in reversed(spans): # 从后往前删,锚点偏移不失效
|
||||
txt = txt[:s] + txt[e:]
|
||||
if not keep:
|
||||
return txt
|
||||
# 首行不补分隔:锚点前保留着原首行的换行+缩进(删行只删 < 起),避免双分隔出空行
|
||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
||||
return txt[:anchor] + body + txt[anchor:]
|
||||
|
||||
|
||||
def _lme_clear(txt):
|
||||
"""无行模板(骨架件无样行)时退回清空——架子在、行不进。"""
|
||||
spans, stack, pos, n = [], [], 0, len(txt)
|
||||
while pos < n:
|
||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
if m.group(1) == "/":
|
||||
t = m.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t:
|
||||
del stack[i:]
|
||||
break
|
||||
pos = m.end()
|
||||
continue
|
||||
tag = m.group(2)
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
if oe < 0:
|
||||
break
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
spans.append((m.start(), oe))
|
||||
pos = oe
|
||||
continue
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
sp = _span(txt, _LME_SUM, m.start())
|
||||
spans.append((m.start(), sp[1] if sp else oe))
|
||||
pos = sp[1] if sp else oe
|
||||
continue
|
||||
stack.append(tag)
|
||||
pos = oe
|
||||
for s, e in reversed(spans):
|
||||
txt = txt[:s] + txt[e:]
|
||||
return txt
|
||||
|
||||
|
||||
def _dw_template(txt):
|
||||
"""骨架件本单位里第一个分部完整块 → {ot 开标签, prefix 前缀(分部自己的费用构成等)}。
|
||||
决策 106:费用构成子块是易达认块的关键——克隆时带上(值清零)。
|
||||
前缀按顶层整元素吸收(_top_scan),费用构成是带子级容器时不会切半。"""
|
||||
sp = _span(txt, _DW)
|
||||
if not sp:
|
||||
return None
|
||||
blk = txt[sp[0]:sp[1]]
|
||||
oe = ec._open_tag_end(blk, 0)
|
||||
close = "</%s>" % _DW
|
||||
inner = blk[oe:-len(close)] if blk.endswith(close) else blk[oe:]
|
||||
prefix, _ = _top_scan(inner, (_DW, _ITEM_BILL))
|
||||
return {"ot": blk[:oe], "prefix": prefix}
|
||||
|
||||
|
||||
def _divtree(plan, uw_id):
|
||||
"""我方 item 分部树:(roots, kids)——按 x_seq 排序(与界面同序),parent 不在集内=根。"""
|
||||
ds = [d for d in plan["divides"].values()
|
||||
if d["uw_id"] == uw_id and d["kind"] == "item"]
|
||||
ds.sort(key=lambda d: (d.get("x_seq") is None,
|
||||
d.get("x_seq") if d.get("x_seq") is not None else 0, d["id"]))
|
||||
ids = {d["id"] for d in ds}
|
||||
kids, roots = {}, []
|
||||
for d in ds:
|
||||
p = d["parent_id"]
|
||||
(kids.setdefault(p, []).append(d)) if p in ids else roots.append(d)
|
||||
return roots, kids
|
||||
|
||||
|
||||
def _sum_bills(bills):
|
||||
n = 0.0
|
||||
for b in bills or []:
|
||||
try:
|
||||
n += float(b.get("Total") or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return n
|
||||
|
||||
|
||||
def _div_block(tmpl, d, kids, bills_by_div, sample, sep, norm_tmpl=None,
|
||||
express_by_norm=None, txt="", depth=0):
|
||||
"""一个分部节点:开标签克隆(Name/Total 落我方,指标清零)+费用构成前缀(清零)
|
||||
+子分部/清单递归。Total=本级+全部子孙清单合计(现算,主人定可计算按采纳)。
|
||||
我方上限 4 级(决策 230),递归保险 8 级。返回 (块文本, 合计)。"""
|
||||
ot = ec._clone_open_tag(tmpl["ot"]) if tmpl else '<%s Name="x">' % _DW
|
||||
ot = ec._attr_set_has(ot, "Name", d.get("name") or "")
|
||||
for k in ("Quantity", "TechnicalAndEconomicIndex"): # 别人的指标不背
|
||||
ot = ec._attr_set_has(ot, k, "0")
|
||||
parts = []
|
||||
total = _sum_bills(bills_by_div.get(d["id"], []))
|
||||
if depth <= _MAX_DEPTH:
|
||||
for sub in kids.get(d["id"], []):
|
||||
blk, sub_total = _div_block(tmpl, sub, kids, bills_by_div, sample, sep,
|
||||
norm_tmpl, express_by_norm, txt, depth + 1)
|
||||
parts.append(blk)
|
||||
total += sub_total
|
||||
ot = ec._attr_set_has(ot, "Total", _money(total))
|
||||
bills = [_bill_block(sample, b, norm_tmpl, express_by_norm, txt)
|
||||
for b in bills_by_div.get(d["id"], [])]
|
||||
prefix = ec._zero_results(tmpl["prefix"]) if tmpl else ""
|
||||
return ot + prefix + sep.join(parts + bills) + "</%s>" % _DW, total
|
||||
|
||||
|
||||
def _replace_span(txt, sp, new):
|
||||
return txt[:sp[0]] + new + txt[sp[1]:]
|
||||
|
||||
|
||||
def _top_scan(inner, stop_tags):
|
||||
"""容器内顶层扫描:返回 (前缀, 命中位)。前缀=首个 stop 顶层元素之前的**完整**
|
||||
顶层元素(费用构成块等,可能带子级——按标签裸切会切在容器中间造成 XML 错配)。"""
|
||||
stop = set(stop_tags)
|
||||
pos, n = 0, len(inner)
|
||||
while pos < n:
|
||||
m = re.compile(r"<([A-Za-z_][\w.]*)").search(inner, pos)
|
||||
if not m:
|
||||
return inner, n
|
||||
tag = m.group(1)
|
||||
if tag in stop:
|
||||
return inner[:m.start()], m.start()
|
||||
oe = ec._open_tag_end(inner, m.start())
|
||||
if oe < 0:
|
||||
return inner, n
|
||||
if inner[oe - 2:oe] == "/>":
|
||||
pos = oe
|
||||
continue
|
||||
depth, p = 1, oe
|
||||
while depth:
|
||||
m2 = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(inner, p)
|
||||
if not m2:
|
||||
return inner, n
|
||||
depth += -1 if m2.group(0)[1] == "/" else 1
|
||||
p = m2.end()
|
||||
if depth == 0:
|
||||
break
|
||||
pos = p
|
||||
return inner, n
|
||||
|
||||
|
||||
def _render_unit(txt, u, plan, sc=None, sid=0, express_by_norm=None,
|
||||
lme_ctx=None):
|
||||
"""一个单位工程成员:分部容器/措施容器清仓重插我方数据;工料机汇总按现算挂真实行
|
||||
(无采纳=空槽);单位名与我方可算合计落位。u=None=骨架多出的单位位:清仓保留值,不改名。"""
|
||||
bills_item = [b for b in (u["bills"] if u else []) if b["kind"] == "item"
|
||||
and not b.get("x_tdel")]
|
||||
bills_pre = [b for b in (u["bills"] if u else []) if b["kind"] == "prelim"
|
||||
and not b.get("x_tdel")]
|
||||
item_sample = ec._largest_bill_block(txt, tag=_ITEM_BILL, prelim=False) \
|
||||
or _fallback_blk(txt, False) or (lme_ctx or {}).get("g_item")
|
||||
pre_sample = ec._largest_bill_block(txt, prelim=True) \
|
||||
or (lme_ctx or {}).get("g_pre") or item_sample
|
||||
norm_tmpl_item = (ec._full_norm_block(item_sample) if item_sample else None) \
|
||||
or (lme_ctx or {}).get("g_norm_item")
|
||||
norm_tmpl_pre = (ec._full_norm_block(pre_sample) if pre_sample else None) \
|
||||
or (lme_ctx or {}).get("g_norm_pre") or norm_tmpl_item
|
||||
sep = ec._native_sep(txt, _ITEM_BILL, "") \
|
||||
or (lme_ctx or {}).get("g_sep") or "\r\n"
|
||||
sep_d = ec._native_sep(txt, _DW, sep) or (lme_ctx or {}).get("g_sep_d") or sep
|
||||
tmpl = _dw_template(txt) or (lme_ctx or {}).get("g_dw")
|
||||
bb = dict(norm_tmpl=norm_tmpl_item, express_by_norm=express_by_norm, txt=txt)
|
||||
|
||||
# ---- 分部分项容器:清仓 → 我方分部树(DivisionalWorks 递归嵌套)+ 容器合计现算 ----
|
||||
sp = _span(txt, _ITEM_CONT)
|
||||
if sp:
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
ot = txt[sp[0]:oe]
|
||||
close = "</%s>" % _ITEM_CONT
|
||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
||||
if u:
|
||||
roots, kids = _divtree(plan, u["id"])
|
||||
bills_by_div = {}
|
||||
for b in bills_item:
|
||||
bills_by_div.setdefault(b.get("div_id"), []).append(b)
|
||||
blocks = [_div_block(tmpl, d, kids, bills_by_div, item_sample, sep_d,
|
||||
norm_tmpl=bb["norm_tmpl"],
|
||||
express_by_norm=express_by_norm, txt=txt)[0]
|
||||
for d in roots]
|
||||
blocks += [_bill_block(item_sample, b, bb["norm_tmpl"],
|
||||
express_by_norm, txt)
|
||||
for b in bills_by_div.get(None, [])]
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_item)))
|
||||
else:
|
||||
blocks = []
|
||||
prefix, _ = _top_scan(inner_old, (_DW, _ITEM_BILL))
|
||||
inner = ec._zero_results(prefix)
|
||||
txt = _replace_span(txt, sp, ot + inner + sep_d.join(blocks) + close)
|
||||
|
||||
# ---- 措施项目容器:清仓 → 我方措施行(有包装层就克隆一层);合计现算 ----
|
||||
sp = _span(txt, _PRE_CONT)
|
||||
if sp:
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
ot = txt[sp[0]:oe]
|
||||
close = "</%s>" % _PRE_CONT
|
||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
||||
if u and bills_pre:
|
||||
ot_wrap = _opentag(inner_old, _DW_PRE)
|
||||
bills = [_bill_block(pre_sample, b, norm_tmpl_pre, express_by_norm, txt)
|
||||
for b in bills_pre]
|
||||
body = (ec._clone_open_tag(ot_wrap) + sep.join(bills) + "</%s>" % _DW_PRE) \
|
||||
if ot_wrap else sep.join(bills)
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_pre)))
|
||||
else:
|
||||
body = ""
|
||||
# 措施分部两种标签都在真实件里出现过:PreliminaryDivisionalWorks(新)与
|
||||
# DivisionalWorks(三溪 .cos 实测)——都要停,包装层连同旧清单整块让位给我方平铺
|
||||
prefix, _ = _top_scan(inner_old, (_DW_PRE, _DW, _PRE_BILL, _ITEM_BILL))
|
||||
inner = ec._zero_results(prefix)
|
||||
txt = _replace_span(txt, sp, ot + inner + body + close)
|
||||
|
||||
# ---- 单位级工料机汇总(补记五:根层 LME_SUM=单位级汇总表,易达标准骨架铁证):
|
||||
# 灌现算行(dyn 引擎,定额工程量×消耗量)+台班子级;没采纳 → 清空(架子在行不进)
|
||||
ctx = lme_ctx or {}
|
||||
rows9 = dyn_lme.dyn_uw_rows(sc, sid, u["id"]) if (sc and u) else None
|
||||
txt = _lme_fill(txt, rows9, ctx.get("children"),
|
||||
ctx.get("row_tmpl"), ctx.get("child_tmpl"),
|
||||
ind={"ci": ctx.get("ci"), "cc": ctx.get("cc"), "sep": ctx.get("sep")},
|
||||
lib=ctx.get("lib"))
|
||||
|
||||
# ---- 单位工程名 + 我方可算合计(分部分项费/措施费;其余保留值)----
|
||||
if u:
|
||||
m = re.compile(r"<UnitWorks\b").search(txt)
|
||||
if m:
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
ot = ec._attr_set(txt[m.start():oe], "Name", u.get("name") or "")
|
||||
ot = ec._attr_set_has(ot, "DivisionalAndElementalWorks",
|
||||
_money(_sum_bills(bills_item)))
|
||||
ot = ec._attr_set_has(ot, "Preliminaries", _money(_sum_bills(bills_pre)))
|
||||
txt = txt[:m.start()] + ot + txt[oe:]
|
||||
sp = _span(txt, "SummaryOfCost")
|
||||
if sp:
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
ot = ec._attr_set_has(txt[sp[0]:oe], "DivisionalAndElementalWorks",
|
||||
_money(_sum_bills(bills_item)))
|
||||
ot = ec._attr_set_has(ot, "Preliminaries", _money(_sum_bills(bills_pre)))
|
||||
txt = txt[:sp[0]] + ot + txt[oe:]
|
||||
return txt
|
||||
|
||||
|
||||
def _fallback_blk(txt, prelim):
|
||||
"""没有合格样板(无费用构成子块)时的兜底:第一条同区清单块原样当模板。"""
|
||||
for mk in ec._scan_bills(txt):
|
||||
is_pre = (mk["tag"] == _PRE_BILL or ec._in_prelim(txt, mk["s"]))
|
||||
if is_pre == prelim:
|
||||
return txt[mk["s"]:mk["end"]]
|
||||
return None
|
||||
|
||||
|
||||
def _rename_opentags(txt, tag, names):
|
||||
"""按出现顺序给 tag 开标签改 Name(第 n 个 → names[n],超出不动)。
|
||||
单位/单项引用节点只改 Name——Number 关联成员文件名,动了断链(原生实测)。"""
|
||||
out, pos, i = [], 0, 0
|
||||
while i < len(names):
|
||||
m = re.compile(r"<%s\b" % tag).search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
e = ec._open_tag_end(txt, m.start())
|
||||
if e < 0:
|
||||
break
|
||||
out.append(txt[pos:m.start()])
|
||||
out.append(ec._attr_set(txt[m.start():e], "Name", names[i] or ""))
|
||||
pos, i = e, i + 1
|
||||
out.append(txt[pos:])
|
||||
return "".join(out)
|
||||
|
||||
|
||||
class _GbkNameZipInfo(ec._RawNameZipInfo):
|
||||
"""克隆补位成员的条目名:骨架原生条目名是 GBK 字节(无旗标)。_RawNameZipInfo 对
|
||||
cp437 编不回的串会退 UTF-8+旗标——那正是乱码教训——新中文名这里改按 GBK 写、同样
|
||||
不打旗标(GBK 也编不了才 UTF-8 兜底)。"""
|
||||
|
||||
def _encodeFilenameFlags(self):
|
||||
try:
|
||||
return self.filename.encode("cp437"), 0
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
try:
|
||||
return self.filename.encode("gbk"), 0
|
||||
except UnicodeEncodeError:
|
||||
return self.filename.encode("utf-8"), 0x800
|
||||
|
||||
|
||||
def _render_project(txt, plan, proj_name, n_ours, n_sections, extra_refs=None):
|
||||
"""项目成员:工程名/单项名/单位引用名落我方;其余全部保留值。
|
||||
extra_refs=骨架位不够时克隆出来的单位引用行 [(我方单位名, 成员文件名, 引用号)]
|
||||
——克隆最后一条现有引用行,号/名/文件名改新,按原生分隔符顺延(2026-10-28 主人定
|
||||
「骨架单位工程位可自由添加」)。"""
|
||||
decl = re.match(r"^.*?\?>", txt, flags=re.S)
|
||||
base = decl.end() if decl else 0
|
||||
lead = base + (len(txt[base:]) - len(txt[base:].lstrip()))
|
||||
root_m = re.match(r"<([\w.]+)", txt[lead:])
|
||||
if root_m and root_m.group(1) in _ROOT_TAGS:
|
||||
oe = ec._open_tag_end(txt, lead)
|
||||
ot = ec._attr_set_has(txt[:oe], "Name", proj_name or "")
|
||||
txt = ot + txt[oe:]
|
||||
txt = _rename_opentags(txt, "UnitWorks",
|
||||
[u.get("name") or "" for u in plan["units"][:n_ours]])
|
||||
sec_names = [s.get("name") or "" for s in plan["sections"]]
|
||||
for t in _SEC_TAGS:
|
||||
txt = _rename_opentags(txt, t, sec_names)
|
||||
if extra_refs:
|
||||
ms = list(re.finditer(r"<UnitWorks\b[^>]*>", txt))
|
||||
if ms:
|
||||
tmpl_o = ms[-1].group(0)
|
||||
# 自闭合引用行先转开标签形态改属性,改完再转回——_attr_set 对缺属性是尾插,
|
||||
# 会把属性插到自闭合的 / 后面(Total="x"/ FileName="y"> 结构破)
|
||||
self_close = tmpl_o.rstrip().endswith("/>")
|
||||
if self_close:
|
||||
tmpl_o = tmpl_o.rstrip()[:-2] + ">"
|
||||
sep = ec._native_sep(txt, "UnitWorks", "\r\n")
|
||||
add = []
|
||||
for name_k, fname_k, num_k in extra_refs:
|
||||
row = ec._attr_set(ec._attr_set(ec._attr_set(
|
||||
tmpl_o, "Number", str(num_k)), "Name", name_k or ""), "FileName", fname_k)
|
||||
if self_close:
|
||||
row = row[:-1] + "/>"
|
||||
add.append(row)
|
||||
txt = txt[:ms[-1].end()] + "".join(sep + r for r in add) + txt[ms[-1].end():]
|
||||
return txt
|
||||
|
||||
|
||||
def export(sc, hcon, sid, suffix, progress=None, src_path=None):
|
||||
"""经典骨架导出 cos/cos4(补记十二,主人定「骨架管导出,数据归软件」:cos4 全量走
|
||||
骨架——手工+普通工程都算;数据全用软件里的现算/采纳,骨架只管格式与字段。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
rep = classic_skeleton.pick_frame(hcon, (suffix or "").lower(), src_path=src_path)
|
||||
if not rep:
|
||||
return None, None, ("该后缀(.%s)还没有经典骨架:请先在后台导入或用工作台"
|
||||
"打开一份 .%s 原件" % (suffix, suffix))
|
||||
plan = build_plan(sc, sid)
|
||||
if plan is None:
|
||||
return None, None, "会话数据读不出来"
|
||||
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
|
||||
# 采纳含量算式(s_norm_res.express,决策 106 补记十二:调整式跟着历史项目走)
|
||||
express_by_norm = {}
|
||||
for r in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty, nr.express
|
||||
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,)):
|
||||
express_by_norm.setdefault(r["norm_id"], []).append(
|
||||
(r["res_code"], r["qty"], r["express"] or None))
|
||||
try:
|
||||
raw = _render(rep["blob"], plan, proj_name, progress, sc, sid,
|
||||
express_by_norm, rep["suffix"])
|
||||
except Exception as e:
|
||||
return None, None, "导出失败:%s" % e
|
||||
return raw, ((proj_name or "工程") + "-审核版." + rep["suffix"]), None
|
||||
|
||||
|
||||
def _render(blob, plan, proj_name, progress=None, sc=None, sid=0,
|
||||
express_by_norm=None, suffix=""):
|
||||
src = zipfile.ZipFile(io.BytesIO(blob))
|
||||
members, texts = [], {}
|
||||
for nm in src.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
txt, enc = ec._decode(src.read(nm))
|
||||
members.append(nm)
|
||||
texts[nm] = [txt, enc]
|
||||
# 单位工程成员=剥掉 xml 声明后根元素是 UnitWorks;项目成员=含单项层标签或项目根
|
||||
unit_nms, proj_nms = [], []
|
||||
for nm in members:
|
||||
body = re.sub(r"^.*?\?>", "", texts[nm][0], count=1, flags=re.S).lstrip()
|
||||
if body.startswith("<UnitWorks"):
|
||||
unit_nms.append(nm)
|
||||
elif any(("<%s" % t) in body for t in _SEC_TAGS) or \
|
||||
any(body[:200].find("<%s" % t) >= 0 for t in _ROOT_TAGS):
|
||||
proj_nms.append(nm)
|
||||
if not unit_nms:
|
||||
raise ValueError("骨架件里没找到单位工程数据,请换一份原件再试")
|
||||
# 单位成员处理序=**项目成员引用行的 FileName 序**(主人 2026-10-28 定:单项/单位排序
|
||||
# 按项目目录先有顺序=引用行序,与压缩包内 xml 次序无关)。骨架自己的引用行序常与
|
||||
# zip 成员序不同——按 zip 序灌名会让「引用行名 ↔ 成员名」错位(实测广联达骨架 20/44
|
||||
# 不一致)。引用行没点到/点丢的成员按原 zip 序垫后,一个不漏。
|
||||
if proj_nms:
|
||||
disp_of = {}
|
||||
for i in src.infolist():
|
||||
if not i.filename.lower().endswith(".xml"):
|
||||
continue
|
||||
try:
|
||||
raw = i.filename.encode("utf-8") if (i.flag_bits & 0x800) \
|
||||
else i.filename.encode("cp437")
|
||||
disp_of[raw.decode("gbk")] = i.filename
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
ref_order = []
|
||||
ref_nums = []
|
||||
for x in re.findall(r"<UnitWorks\b[^>]*>", texts[proj_nms[0]][0]):
|
||||
fn = re.search(r'\bFileName="([^"]*)"', x)
|
||||
nm = re.search(r'\bNumber="([^"]*)"', x)
|
||||
if fn and fn.group(1) in disp_of and disp_of[fn.group(1)] in unit_nms \
|
||||
and disp_of[fn.group(1)] not in ref_order:
|
||||
ref_order.append(disp_of[fn.group(1)])
|
||||
ref_nums.append(nm.group(1) if nm else "")
|
||||
if ref_order:
|
||||
unit_nms = ref_order + [n for n in unit_nms if n not in ref_order]
|
||||
# 决策 260 补记四(2026-11-02 主人定「数据按需自动增加行,按模板序排」):
|
||||
# **我方单位数据(ours)与成员槽(unit_nms)同锚重排**——锚=引用行序(项目目录序)。
|
||||
# 此前 units 序=单项分组+Number 数字自然序(build_plan),与引用行文本序不同的
|
||||
# 源件(华宇路:引用行 3,107,148,146,145,… 非 Number 序)会成员数据错挂引用行。
|
||||
# 关联键=引用行 Number ↔ s_unit_works.Number(解析原样入库)。
|
||||
if ref_order and proj_nms:
|
||||
num_map = {}
|
||||
for _u in plan["units"]:
|
||||
_k = str(_u.get("number") or "")
|
||||
if _k and _k not in num_map:
|
||||
num_map[_k] = _u
|
||||
ours_sorted = [num_map.get(_n) for _n in ref_nums if _n in num_map]
|
||||
ours_sorted += [_u for _u in plan["units"] if _u not in ours_sorted]
|
||||
plan["units"] = ours_sorted
|
||||
ours = plan["units"]
|
||||
# 行/子行模板全局取(专用骨架的空单位位没有样行——借其他成员的形态,补记五):
|
||||
# 行模板=任一自闭合 LME_SUM 行;子行=任一「容器行内嵌的原生 …Element 子行」+原生
|
||||
# 换行缩进(广联达/易达两骨架实测同款:子行一律 Element 形态、只 Number/Express/
|
||||
# Quantity/Remark;2026-10-28 修:旧正则 [^>]*> 会吃掉自闭合的 /,把相邻两条平铺行
|
||||
# 误当「母行+子行」——子行模板成了别人的母行,Name/单价/金额残留全从这来)
|
||||
row_tmpl = child_tmpl = None
|
||||
ci_ind = cc_ind = None
|
||||
g_lme_sep = None
|
||||
pat_row = re.compile(r"<%s\b[^>]*/>" % _LME_SUM)
|
||||
# 子行形态=容器开标签后内嵌的首个 …Element 行(多子行容器里第一条后面跟的是兄弟不是
|
||||
# 闭合,所以闭合缩进单取:最后一条 Element 行与 </…Summary> 之间的空白)
|
||||
pat_child = re.compile(r"<%s\b[^>]*[^/]>(\s*)(<LabourMaterialsEquipmentsMachinesElement"
|
||||
r"\b[^>]*/>)" % _LME_SUM, re.S)
|
||||
pat_close = re.compile(r"<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>"
|
||||
r"(\s*)(</%s>)" % _LME_SUM, re.S)
|
||||
# 清单/定额/分部样板与原生分隔符同样全局兜底(空单位位没有样板 → 借全件的)
|
||||
g_item = g_pre = g_dw = None
|
||||
g_item_nm = None
|
||||
g_sep = g_sep_d = None
|
||||
g_norm_item = g_norm_pre = None
|
||||
for nm in unit_nms:
|
||||
t0 = texts[nm][0]
|
||||
if row_tmpl is None:
|
||||
m1 = pat_row.search(t0)
|
||||
if m1:
|
||||
row_tmpl = m1.group(0)
|
||||
g_lme_sep = ec._native_sep(t0, _LME_SUM, "\n")
|
||||
if child_tmpl is None:
|
||||
m2 = pat_child.search(t0)
|
||||
if m2:
|
||||
child_tmpl, ci_ind = m2.group(2), m2.group(1)
|
||||
if cc_ind is None:
|
||||
m3 = pat_close.search(t0)
|
||||
if m3:
|
||||
cc_ind = m3.group(1)
|
||||
if g_item is None:
|
||||
b1 = ec._largest_bill_block(t0, tag=_ITEM_BILL, prelim=False)
|
||||
if b1:
|
||||
g_item = b1
|
||||
g_item_nm = nm
|
||||
g_sep = ec._native_sep(t0, _ITEM_BILL, "\r\n")
|
||||
g_sep_d = ec._native_sep(t0, _DW, g_sep)
|
||||
g_dw = _dw_template(t0)
|
||||
g_norm_item = ec._full_norm_block(b1)
|
||||
if g_pre is None:
|
||||
b2 = ec._largest_bill_block(t0, prelim=True)
|
||||
if b2:
|
||||
g_pre = b2
|
||||
g_norm_pre = ec._full_norm_block(b2)
|
||||
if row_tmpl and child_tmpl and cc_ind and g_item and g_pre:
|
||||
break
|
||||
# 台班/配合比子级组成(s_lme_res:p_code → [(子码, 含量)])
|
||||
children = {}
|
||||
if sc:
|
||||
for r in sc.execute("SELECT p_code, res_code, qty FROM s_lme_res "
|
||||
"WHERE session_id=? ORDER BY seq, id", (sid,)):
|
||||
children.setdefault(r["p_code"] or "", []).append((r["res_code"], r["qty"]))
|
||||
# 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入;手工会话唯一价格源)
|
||||
lib = {}
|
||||
if sc:
|
||||
for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp FROM s_lme_lib "
|
||||
"WHERE session_id=?", (sid,)):
|
||||
lib[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"])
|
||||
|
||||
lme_ctx = {"children": children, "row_tmpl": row_tmpl, "child_tmpl": child_tmpl,
|
||||
"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep, "lib": lib,
|
||||
"g_item": g_item, "g_pre": g_pre, "g_dw": g_dw,
|
||||
"g_sep": g_sep, "g_sep_d": g_sep_d,
|
||||
"g_norm_item": g_norm_item, "g_norm_pre": g_norm_pre}
|
||||
# 单位工程位自由复制(主人 2026-10-28 定:骨架=数据结构模板,单位工程/单项工程/
|
||||
# 清单/分部/定额想插多少插多少,结构不变——位不够就克隆骨架自己的单位成员补位,
|
||||
# 项目成员的引用行同步顺延;成员名按骨架自己的 @_序号_名.xml 命名顺延)
|
||||
# 决策 260(2026-11-02 主人定「数据按需自动增加行」双向落成员层):位**多**了也删——
|
||||
# 槽数>我方单位数 → 多余成员整槽不导出(卡槽只是结构样板),项目成员里对应引用行
|
||||
# 同步删除(引用行 FileName=成员显示名);zip 写包时跳过(见写包段 _drop)。
|
||||
drop_nms = []
|
||||
if len(ours) < len(unit_nms):
|
||||
drop_nms = unit_nms[len(ours):]
|
||||
_drop_disp = set()
|
||||
for i in src.infolist():
|
||||
if i.filename in drop_nms:
|
||||
try:
|
||||
_drop_disp.add(i.filename.encode("cp437").decode("gbk")
|
||||
if not (i.flag_bits & 0x800)
|
||||
else i.filename)
|
||||
except UnicodeDecodeError:
|
||||
_drop_disp.add(i.filename)
|
||||
for pn in proj_nms:
|
||||
pt = texts[pn][0]
|
||||
for dd in _drop_disp:
|
||||
# 自闭合引用行(主流形态)整行删;容器形态按完整块删
|
||||
m1 = re.search(r'<UnitWorks\b[^>]*\bFileName="' + re.escape(dd) + r'"[^>]*?/>', pt)
|
||||
if m1:
|
||||
pt = pt[:m1.start()] + pt[m1.end():]
|
||||
continue
|
||||
mm = re.search(r'<UnitWorks\b[^>]*\bFileName="' + re.escape(dd) + r'"', pt)
|
||||
if mm:
|
||||
sp = ec._span(pt, "UnitWorks", mm.start())
|
||||
if sp:
|
||||
pt = pt[:sp[0]] + pt[sp[1]:]
|
||||
texts[pn][0] = pt
|
||||
# 决策 260:成员**文件名**=我方单位名(骨架造名不保留)——改名放在 _render_project
|
||||
# **之后**(引用行 Name 已灌我方名,以引用行 Name↔FileName↔成员 三者为准名实一致),
|
||||
# 见写包前的 ren_map 段;zip 写包段对改名成员用 _GbkNameZipInfo(GBK 字节名)。
|
||||
_disp_of = {}
|
||||
for i in src.infolist():
|
||||
if i.filename in texts and i.filename not in _disp_of:
|
||||
try:
|
||||
_disp_of[i.filename] = i.filename if (i.flag_bits & 0x800) \
|
||||
else i.filename.encode("cp437").decode("gbk")
|
||||
except UnicodeDecodeError:
|
||||
_disp_of[i.filename] = i.filename
|
||||
new_units = [] # [(新成员名, 克隆源名, 引用号, 我方单位名)]——写包时补 zip 条目
|
||||
if drop_nms: # 决策 260:多余槽成员整槽出列(循环/写包都不再含)
|
||||
unit_nms = [n for n in unit_nms if n not in drop_nms]
|
||||
members = [n for n in members if n not in drop_nms]
|
||||
for nm in drop_nms:
|
||||
texts.pop(nm, None)
|
||||
if len(ours) > len(unit_nms):
|
||||
src_nm = g_item_nm or unit_nms[0]
|
||||
orig_slots = len(unit_nms)
|
||||
m2 = re.match(r"@_(\d+)_(.+)\.xml$", src_nm)
|
||||
nums = [int(m.group(1)) for m in
|
||||
(re.match(r"@_(\d+)_", n) for n in unit_nms) if m]
|
||||
base_n = (max(nums) + 2) if nums else (len(unit_nms) + 1)
|
||||
disp = m2.group(2) if m2 else "单位工程"
|
||||
t2 = re.search(r"(\d+)$", disp)
|
||||
# 引用号顺延基准:项目成员里现有 UnitWorks 引用行的最大号
|
||||
nxt = 0
|
||||
if proj_nms:
|
||||
nxt = max([int(x.group(1)) for x in
|
||||
re.finditer(r'<UnitWorks\b[^>]*?\bNumber="(\d+)"', texts[proj_nms[0]][0])]
|
||||
or [0])
|
||||
for k in range(len(ours) - orig_slots):
|
||||
# 决策 260:克隆成员名=我方单位名(骨架顺延名也是造名,不保留)
|
||||
_un_k = re.sub(r'[\\/:*?"<>|\r\n]', "_",
|
||||
((ours[orig_slots + k].get("name") or "").strip() or "单位工程"))[:60]
|
||||
nm_k = "@_%d_%s.xml" % (base_n + 2 * k, _un_k)
|
||||
texts[nm_k] = [texts[src_nm][0], texts[src_nm][1]]
|
||||
t0 = texts[nm_k][0]
|
||||
mm = re.search(r"<UnitWorks\b", t0)
|
||||
if mm:
|
||||
oe = ec._open_tag_end(t0, mm.start())
|
||||
t0 = t0[:mm.start()] + ec._attr_set(t0[mm.start():oe], "Number", str(nxt + 1 + k)) + t0[oe:]
|
||||
texts[nm_k][0] = t0
|
||||
members.append(nm_k)
|
||||
unit_nms.append(nm_k)
|
||||
new_units.append((nm_k, src_nm, nxt + 1 + k,
|
||||
(ours[orig_slots + k].get("name") or "")))
|
||||
proj_rows = None
|
||||
if sc:
|
||||
_dp = dyn_lme.dyn_rows(sc, sid, None)
|
||||
if _dp:
|
||||
proj_rows = [(r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8],
|
||||
r[11], r[12], r[13], r[14], r[15] if len(r) > 15 else None)
|
||||
for r in _dp] # 决策 259:导出序 14 列(9 列同形+org/expr 四值+flags)
|
||||
total_steps = len(unit_nms) + len(proj_nms) + 1
|
||||
step = [0]
|
||||
|
||||
def tick():
|
||||
step[0] += 1
|
||||
if progress:
|
||||
progress(step[0], total_steps)
|
||||
|
||||
for i, nm in enumerate(unit_nms):
|
||||
u = ours[i] if i < len(ours) else None
|
||||
texts[nm][0] = _render_unit(texts[nm][0], u, plan, sc, sid, express_by_norm,
|
||||
lme_ctx=lme_ctx)
|
||||
tick()
|
||||
for nm in proj_nms:
|
||||
texts[nm][0] = _render_project(texts[nm][0], plan, proj_name,
|
||||
len(ours), len(plan["sections"]),
|
||||
extra_refs=[(x[3], x[0], x[2]) for x in new_units])
|
||||
texts[nm][0] = _lme_fill(texts[nm][0], proj_rows, children,
|
||||
row_tmpl, child_tmpl,
|
||||
ind={"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep},
|
||||
lib=lib)
|
||||
tick()
|
||||
tick()
|
||||
# 决策 260:成员文件名=我方单位名(引用行 Name 此时已灌我方名,以引用行 Name↔
|
||||
# FileName↔成员 三者为准改名——骨架造名不保留)。zip 写包段按 ren_map 改名。
|
||||
ren_map = {} # zip 内部名 → (旧显示名, 新显示名)
|
||||
_disp_rev = {v: k for k, v in _disp_of.items()}
|
||||
for pn in proj_nms:
|
||||
pt = texts[pn][0]
|
||||
for x in re.finditer(r"<UnitWorks\b[^>]*>", pt):
|
||||
nm_a = re.search(r'\bName="([^"]*)"', x.group(0))
|
||||
fn_a = re.search(r'\bFileName="([^"]*)"', x.group(0))
|
||||
if not nm_a or not fn_a or not nm_a.group(1).strip():
|
||||
continue
|
||||
un = re.sub(r'[\\/:*?"<>|\r\n]', "_", nm_a.group(1).strip())[:60]
|
||||
old_disp = fn_a.group(1)
|
||||
m2 = re.match(r"@_(\d+)_", old_disp)
|
||||
new_disp = "@_%s_%s.xml" % ((m2.group(1) if m2 else "1"), un)
|
||||
in_nm = _disp_rev.get(old_disp)
|
||||
if in_nm and new_disp != old_disp:
|
||||
ren_map[in_nm] = (old_disp, new_disp)
|
||||
pt = pt.replace('FileName="%s"' % old_disp, 'FileName="%s"' % new_disp)
|
||||
texts[pn][0] = pt
|
||||
out = io.BytesIO()
|
||||
item_by_nm = {i.filename: i for i in src.infolist()}
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for item in src.infolist():
|
||||
if item.filename in drop_nms:
|
||||
continue # 决策 260:多余槽成员整槽不导出
|
||||
data = src.read(item.filename)
|
||||
if item.filename in texts:
|
||||
data = ec._encode(texts[item.filename][0], texts[item.filename][1])
|
||||
_rp = ren_map.get(item.filename)
|
||||
if _rp:
|
||||
# 决策 260:成员按我方单位名改名(GBK 字节名,cos4 惯例)
|
||||
zi = _GbkNameZipInfo(_rp[1], 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 = ec._safe_extra(item.extra)
|
||||
except Exception:
|
||||
pass
|
||||
zo.writestr(zi, data)
|
||||
continue
|
||||
zi = ec._RawNameZipInfo(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 = ec._safe_extra(item.extra)
|
||||
except Exception:
|
||||
pass
|
||||
zo.writestr(zi, data)
|
||||
# 克隆补位的单位成员(骨架原生条目名是 GBK 字节无旗标——新名字同样按 GBK 写)
|
||||
for nm_k, src_nm, _num, _n in new_units:
|
||||
data = ec._encode(texts[nm_k][0], texts[nm_k][1])
|
||||
si = item_by_nm.get(src_nm)
|
||||
zi = _GbkNameZipInfo(nm_k, date_time=si.date_time if si else (2026, 1, 1, 0, 0, 0))
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
if si:
|
||||
zi.external_attr = si.external_attr
|
||||
zi.create_system = si.create_system
|
||||
zo.writestr(zi, data)
|
||||
return out.getvalue()
|
||||
@@ -1,966 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出引擎 v2(决策 260/264,2026-11-03 主人定「骨架是水管,不造水」):
|
||||
|
||||
- **结构 100% 取自骨架**(空骨架=卡槽集合):数据层按会话数据循环,固定组整组照出;
|
||||
- **值一律透传**:骨架里有什么写什么、数据里有什么写什么;缺值写 "",引擎不解读、不加工;
|
||||
- 数据层=单位工程/分部/清单/措施/定额/工料机/汇总行;其余层是文件固定结构(单价公式行等)。
|
||||
|
||||
数据链复用:build_plan(清单/定额/采纳/临删)+ dyn_lme(工料机现算)。
|
||||
"""
|
||||
import copy
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import classic_skeleton
|
||||
import dyn_lme
|
||||
import skeleton_engine as se
|
||||
from formats.skeleton import build_plan
|
||||
|
||||
LME = "LabourMaterialsEquipmentsMachinesElement"
|
||||
LME_SUM = "LabourMaterialsEquipmentsMachinesSummary"
|
||||
|
||||
# 决策 263:LME Summary 的恒空链(备注/价格来源/交货地/产地/供应商/特征)——导出不回填
|
||||
_HANG_KONG = {"Remark", "PriceSource", "Delivery", "Location", "ProducingArea",
|
||||
"Supplier", "Character"}
|
||||
|
||||
# 结果值区域:骨架样板里带的是别的项目的数——导出时清空(有数据层再灌)
|
||||
_RESULT_REGIONS = {
|
||||
"SummaryOfCost", "SummaryOfBasicCost", "UnitWorksSummary", "UnitWorksSummaryItem",
|
||||
"UnitWorksSummaryGroup", "Tax", "Sundry", "SundryCostsItem",
|
||||
"ProvisionalMaterialEquipment", "ProjectInstallationWorkCostSummary",
|
||||
}
|
||||
|
||||
|
||||
class _GbkZipInfo(zipfile.ZipInfo):
|
||||
"""条目名按 **GBK 原始字节**写、不带 UTF-8 旗标——与易达/广联达原件完全一致。
|
||||
Python 默认把非 ASCII 名写成「UTF-8 字节 + 0x800 旗标」,而 cos 族软件按 GBK 解名,
|
||||
会找不到成员(主人 2026-11-03 实测:条目名乱码、Project.xml 的 FileName 对不上)。
|
||||
非 GBK 字符(极端情况)才回退 UTF-8+旗标。"""
|
||||
|
||||
def _encodeFilenameFlags(self):
|
||||
try:
|
||||
return self.filename.encode("gbk"), 0
|
||||
except UnicodeEncodeError:
|
||||
return self.filename.encode("utf-8"), self.flag_bits | 0x800
|
||||
|
||||
|
||||
def _money(v):
|
||||
return "" if v is None else "%.2f" % float(v)
|
||||
|
||||
|
||||
def _num(v):
|
||||
if v is None:
|
||||
return ""
|
||||
return "%.6f" % float(v)
|
||||
|
||||
|
||||
def _put(el, mapping):
|
||||
"""只写模板上有的列;值原样透传(不格式化、不清零)。"""
|
||||
for k, v in mapping.items():
|
||||
if k in el.attrib:
|
||||
el.set(k, "" if v is None else str(v))
|
||||
|
||||
|
||||
def _kids(el, tag=None):
|
||||
return [c for c in el if isinstance(c.tag, str) and (tag is None or c.tag == tag)]
|
||||
|
||||
|
||||
def _first(el, tag):
|
||||
for e in el.iter(tag):
|
||||
return e
|
||||
return None
|
||||
|
||||
|
||||
def _strip(el, tags):
|
||||
for c in list(el):
|
||||
if isinstance(c.tag, str) and c.tag in tags:
|
||||
el.remove(c)
|
||||
|
||||
|
||||
def _blank_values(el):
|
||||
for a in el.attrib:
|
||||
el.set(a, "")
|
||||
for c in _kids(el):
|
||||
_blank_values(c)
|
||||
|
||||
|
||||
def _deep(el):
|
||||
return copy.deepcopy(el)
|
||||
|
||||
|
||||
def out_name(proj_name, suffix):
|
||||
"""导出文件名:后缀跟导出格式走(原格式=源文件后缀,由调用方传入)。"""
|
||||
return (proj_name or "工程") + "-审核版." + (suffix or "cos4")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 各层渲染(模板克隆 → 清数据子级 → 按数据回灌)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _emit_lme(rows, tmpl, children):
|
||||
"""工料机汇总行:rows=14 列([码,名,规,单,类别,量,除税,税率,含税,原价×4,flags])。
|
||||
模板行有子级槽 → 台班/配合比子级行一并带出(children={母码: [(子码,量)]})。"""
|
||||
out = []
|
||||
kids = _kids(tmpl)
|
||||
child_t = kids[0] if kids else None
|
||||
for r in rows:
|
||||
code, name, spec, unit, kind, qty, ntp, rate, taxp = (list(r) + [None] * 9)[:9]
|
||||
org4 = (tuple(r[9:13]) + (None,) * 4)[:4] if len(r) >= 13 else (None,) * 4
|
||||
el = _deep(tmpl)
|
||||
_put(el, {
|
||||
"Number": code or "", "Name": name or "", "Specification": spec or "",
|
||||
"Unit": unit or "", "Quantity": _num(qty),
|
||||
"NoTaxPrice": _money(ntp), "TaxRate": _money(rate), "TaxPrice": _money(taxp),
|
||||
"NoTaxOrgPrice": _money(org4[0]), "NoTaxPriceExpress": org4[1],
|
||||
"TaxOrgPrice": _money(org4[2]), "TaxPriceExpress": org4[3],
|
||||
"NoTaxTotal": _money((float(qty or 0) * float(ntp or 0)) or None),
|
||||
"TaxTotal": _money((float(qty or 0) * float(taxp or 0)) or None),
|
||||
"Kind": str(int(kind)) if kind else "", "Remark": "",
|
||||
})
|
||||
if len(r) > 13 and r[13]:
|
||||
try:
|
||||
fl = json.loads(r[13])
|
||||
except (ValueError, TypeError):
|
||||
fl = None
|
||||
if isinstance(fl, dict):
|
||||
_put(el, {k: v for k, v in fl.items() if v is not None})
|
||||
_strip(el, {LME})
|
||||
for ccode, cqty in (children.get(code) or []):
|
||||
if child_t is None:
|
||||
break
|
||||
row = _deep(child_t)
|
||||
_put(row, {"Number": ccode or "", "Quantity": _num(cqty), "Remark": ""})
|
||||
el.append(row)
|
||||
out.append(el)
|
||||
return out
|
||||
|
||||
|
||||
def _apply_side(el, side, tags):
|
||||
"""结构固定子块:按库里采集的 x_side 行数/值回填(列集由骨架闸门决定)。
|
||||
side=None(老批次没采)→ 保留骨架样板 1 行(值空),不造。"""
|
||||
if side in (None, ""):
|
||||
return
|
||||
try:
|
||||
rows = json.loads(side) if isinstance(side, str) else side
|
||||
except (ValueError, TypeError):
|
||||
return
|
||||
if not isinstance(rows, list):
|
||||
return
|
||||
by = {}
|
||||
for r in rows:
|
||||
if isinstance(r, dict):
|
||||
by.setdefault(r.get("tag"), []).append(r.get("attrs") or {})
|
||||
for tag in tags:
|
||||
samples = _kids(el, tag)
|
||||
if not samples:
|
||||
continue
|
||||
pos = list(el).index(samples[0])
|
||||
for s in samples:
|
||||
el.remove(s)
|
||||
for attrs in by.get(tag, []):
|
||||
new = _deep(samples[0])
|
||||
for k in list(new.attrib):
|
||||
v = attrs.get(k)
|
||||
new.set(k, "" if v is None else str(v))
|
||||
el.insert(pos, new)
|
||||
pos += 1
|
||||
|
||||
|
||||
def _emit_norm(n, tmpl, children, norm_db):
|
||||
el = _deep(tmpl)
|
||||
db_total = (norm_db or {}).get(n.get("id"))
|
||||
_put(el, {
|
||||
"Number": n.get("Number") or "", "Name": n.get("Name") or "",
|
||||
"Unit": n.get("Unit") or "", "Quantity": _num(n.get("Quantity")),
|
||||
"Price": _money(n.get("Price")),
|
||||
"Total": _money(db_total if db_total is not None else n.get("Total")),
|
||||
"IsNorm": "true", "Remark": "",
|
||||
})
|
||||
rows = _kids(el, LME)
|
||||
pos = list(el).index(rows[0]) if rows else len(list(el))
|
||||
for r in rows:
|
||||
el.remove(r)
|
||||
if rows:
|
||||
for _res in (n.get("res") or []):
|
||||
code, qty = _res[0], _res[1]
|
||||
exp = _res[2] if len(_res) > 2 else None
|
||||
if not code:
|
||||
continue
|
||||
row = _deep(rows[0])
|
||||
_put(row, {"Number": code, "Quantity": _num(qty), "Express": exp or "",
|
||||
"Remark": ""})
|
||||
el.insert(pos, row)
|
||||
pos += 1
|
||||
adjs = _kids(el, "NormAdjustmentList")
|
||||
apos = list(el).index(adjs[0]) if adjs else None
|
||||
for r in adjs:
|
||||
el.remove(r)
|
||||
adj = n.get("x_adjust") or ""
|
||||
if adj and adjs:
|
||||
row = _deep(adjs[0])
|
||||
_put(row, {"OrderNumber": "1", "Value": adj})
|
||||
el.insert(apos, row)
|
||||
_apply_side(el, n.get("x_side"),
|
||||
("ExpressElement", "ManageFees", "UnitPriceCalculationOfItem"))
|
||||
return el
|
||||
|
||||
|
||||
def _emit_bill(b, tmpl, tmpls, norm_db, children):
|
||||
el = _deep(tmpl)
|
||||
_put(el, {
|
||||
"Number": b.get("Number") or "", "Name": b.get("Name") or "",
|
||||
"Attr": b.get("Attr") or "", "Unit": b.get("Unit") or "",
|
||||
"Quantity": _num(b.get("Quantity")),
|
||||
"QtyFormula": b.get("qty_expr") or "",
|
||||
"Price": _money(b.get("Price")), "Total": _money(b.get("Total")),
|
||||
"Remark": "", "WorkContent": "",
|
||||
})
|
||||
wc = _kids(el, "WorkContent")
|
||||
hosts = []
|
||||
for h in ([wc[0]] if wc else []) + [el]:
|
||||
ns = _kids(h, "Norm")
|
||||
if ns:
|
||||
hosts.append((h, ns))
|
||||
if hosts:
|
||||
host, norms = hosts[0]
|
||||
else:
|
||||
host = wc[0] if wc else el
|
||||
norms = []
|
||||
if wc:
|
||||
_put(host, {"Name": "", "Total": _money(b.get("Total")), "Remark": ""})
|
||||
pos = list(host).index(norms[0]) if norms else len(list(host))
|
||||
for _h, _ns in hosts: # 模板里定额可能挂在 WorkContent 或清单本身(两种形态都清)
|
||||
for c in _ns:
|
||||
_h.remove(c)
|
||||
_strip(el, {LME})
|
||||
for n in (b.get("norms") or []):
|
||||
if n.get("x_tdel"):
|
||||
continue
|
||||
host.insert(pos, _emit_norm(n, tmpls["norm"], children, norm_db))
|
||||
pos += 1
|
||||
_apply_side(el, b.get("x_side"),
|
||||
("SummaryOfBasicCost", "ExpressElement", "UnitPriceCalculationOfItem"))
|
||||
return el
|
||||
|
||||
|
||||
def _emit_div(dv, kids, bills, tmpls, norm_db, children, by_parent):
|
||||
el = _deep(tmpls["div"]) if tmpls.get("div") is not None else ET.Element("DivisionalWorks")
|
||||
_strip(el, {"DivisionalWorks", "WorkElement", "UnitWorksPreliminaryWorkElement"})
|
||||
_put(el, {"Number": dv.get("number") or "", "Name": dv.get("name") or ""})
|
||||
total = sum(float(b.get("Total") or 0) for b in bills)
|
||||
for kid in kids:
|
||||
total += sum(float(b.get("Total") or 0) for b in by_parent["bills"].get(kid["id"], []))
|
||||
if "Total" in el.attrib:
|
||||
el.set("Total", _money(total))
|
||||
for b in bills:
|
||||
el.append(_emit_bill(b, tmpls["bill"], tmpls, norm_db, children))
|
||||
for kid in kids:
|
||||
el.append(_emit_div(kid, by_parent["kids"].get(kid["id"], []),
|
||||
by_parent["bills"].get(kid["id"], []), tmpls, norm_db,
|
||||
children, by_parent))
|
||||
return el
|
||||
|
||||
|
||||
def _emit_works(dea, u, plan, tmpls, norm_db, children):
|
||||
_strip(dea, {"DivisionalWorks", "WorkElement"})
|
||||
divs = [x for x in (plan.get("divides") or {}).values()
|
||||
if x["uw_id"] == u["id"] and x.get("kind") != "prelim"]
|
||||
bills = [b for b in (u.get("bills") or []) if b.get("kind") != "prelim" and not b.get("x_tdel")]
|
||||
by_parent = {"kids": {}, "bills": {}}
|
||||
for x in divs:
|
||||
by_parent["kids"].setdefault(x.get("parent_id"), []).append(x)
|
||||
for b in bills:
|
||||
by_parent["bills"].setdefault(b.get("div_id"), []).append(b)
|
||||
for dv in by_parent["kids"].get(None, []):
|
||||
dea.append(_emit_div(dv, by_parent["kids"].get(dv["id"], []),
|
||||
by_parent["bills"].get(dv["id"], []), tmpls, norm_db,
|
||||
children, by_parent))
|
||||
for b in by_parent["bills"].get(None, []):
|
||||
dea.append(_emit_bill(b, tmpls["bill"], tmpls, norm_db, children))
|
||||
|
||||
|
||||
def _emit_prelim(pre, u, plan, tmpls, norm_db, children):
|
||||
"""措施区:骨架有分部层→按分部嵌套;无→直挂(骨架形态决定)。"""
|
||||
_strip(pre, {"PreliminaryDivisionalWorks", "UnitWorksPreliminaryWorkElement",
|
||||
"PreliminaryWorkElement", "Norm", "WorkElement", "DivisionalWorks"})
|
||||
bills = [b for b in (u.get("bills") or []) if b.get("kind") == "prelim" and not b.get("x_tdel")]
|
||||
divs = [x for x in (plan.get("divides") or {}).values()
|
||||
if x["uw_id"] == u["id"] and x.get("kind") == "prelim"]
|
||||
if tmpls.get("pre_bill") is None and tmpls.get("bill") is None:
|
||||
return
|
||||
by_div = {}
|
||||
for b in bills:
|
||||
by_div.setdefault(b.get("div_id"), []).append(b)
|
||||
by_parent = {}
|
||||
for x in divs:
|
||||
by_parent.setdefault(x.get("parent_id"), []).append(x)
|
||||
|
||||
def emit_bill(b):
|
||||
# 2026-11-04:措施清单有两种原生标签形态(UnitWorksPreliminaryWorkElement / WorkElement),
|
||||
# 导入时存 x_ptag,导出按原形态还原(否则会被统一成一种,结构就变形了)。
|
||||
tag = b.get("x_ptag") or ""
|
||||
_pre = tmpls.get("pre_bill")
|
||||
tmpl = tmpls["bill"] if tag == "WorkElement" else (_pre if _pre is not None else tmpls["bill"])
|
||||
return _emit_bill(b, tmpl, tmpls, norm_db, children)
|
||||
|
||||
def emit_div(dv):
|
||||
el = _deep(tmpls["pre_div"])
|
||||
_strip(el, {"PreliminaryDivisionalWorks", "UnitWorksPreliminaryWorkElement",
|
||||
"WorkElement", "DivisionalWorks"})
|
||||
_put(el, {"Number": dv.get("number") or "", "Name": dv.get("name") or ""})
|
||||
for b in by_div.get(dv["id"], []):
|
||||
el.append(emit_bill(b))
|
||||
for kid in by_parent.get(dv["id"], []):
|
||||
el.append(emit_div(kid))
|
||||
return el
|
||||
|
||||
if tmpls.get("pre_div") is not None and divs:
|
||||
for dv in by_parent.get(None, []):
|
||||
pre.append(emit_div(dv))
|
||||
for b in by_div.get(None, []):
|
||||
pre.append(emit_bill(b))
|
||||
else:
|
||||
for b in bills:
|
||||
pre.append(emit_bill(b))
|
||||
|
||||
|
||||
def _sum_values(r):
|
||||
"""动态汇总行(14 列)→ 骨架列字典 + 母码。"""
|
||||
code, name, spec, unit, kind, qty, ntp, rate, taxp = (list(r) + [None] * 9)[:9]
|
||||
org4 = (tuple(r[9:13]) + (None,) * 4)[:4] if len(r) >= 13 else (None,) * 4
|
||||
vals = {
|
||||
"Number": code or "", "Name": name or "", "Specification": spec or "",
|
||||
"Unit": unit or "", "Quantity": _num(qty),
|
||||
"NoTaxPrice": _money(ntp), "TaxRate": _money(rate), "TaxPrice": _money(taxp),
|
||||
"NoTaxOrgPrice": _money(org4[0]), "NoTaxPriceExpress": org4[1],
|
||||
"TaxOrgPrice": _money(org4[2]), "TaxPriceExpress": org4[3],
|
||||
"NoTaxTotal": _money((float(qty or 0) * float(ntp or 0)) or None),
|
||||
"TaxTotal": _money((float(qty or 0) * float(taxp or 0)) or None),
|
||||
"Kind": str(int(kind)) if kind else "", "Remark": "",
|
||||
}
|
||||
if len(r) > 13 and r[13]:
|
||||
try:
|
||||
fl = json.loads(r[13])
|
||||
except (ValueError, TypeError):
|
||||
fl = None
|
||||
if isinstance(fl, dict):
|
||||
# 决策 263:恒空链(备注/价格来源/交货地…)不随行输出,清残留
|
||||
vals.update({k: v for k, v in fl.items()
|
||||
if v is not None and k not in _HANG_KONG})
|
||||
return code, vals
|
||||
|
||||
|
||||
def _emit_sums(host, rows, children):
|
||||
"""工料机汇总:骨架里的汇总行样板整组替换为库数据(骨架没这层→不造)。
|
||||
行本身就是槽(可能带台班/配合比子级行),行数由库决定。
|
||||
2026-11-03 加固:汇总行可能有**两种形态**(普通行 / 带组成的块行,列集不同)——
|
||||
每行按「列集覆盖 + 有无子级」挑最合适的样板,避免把另一形态的属性丢掉。"""
|
||||
sample = None
|
||||
for e in host.iter(LME_SUM):
|
||||
sample = e
|
||||
break
|
||||
if sample is None:
|
||||
return
|
||||
parent = None
|
||||
for par in host.iter():
|
||||
for c in _kids(par):
|
||||
if c is sample:
|
||||
parent = par
|
||||
break
|
||||
if parent is not None:
|
||||
break
|
||||
if parent is None:
|
||||
return
|
||||
tmpls = [c for c in _kids(parent) if c.tag == LME_SUM]
|
||||
if not tmpls:
|
||||
return
|
||||
|
||||
def _pick(vals, want_child):
|
||||
"""两种导出形态按行硬分派(2026-11-03 主人定):
|
||||
· 带组成的行 → 闭合块形态(<Summary>…</Summary>,内有 Element 子行);
|
||||
· 普通行 → 自闭合行形态(<Summary … />)。
|
||||
形态优先,列覆盖只用于同形态内选最全的样板;该形态没有样板才退回另一形态。"""
|
||||
cands = [t for t in tmpls if bool(_kids(t)) == bool(want_child)]
|
||||
if not cands:
|
||||
cands = tmpls
|
||||
need = set(vals.keys())
|
||||
best, best_s = cands[0], -1
|
||||
for t in cands:
|
||||
have = set(t.attrib.keys())
|
||||
s = 2 * len(need & have)
|
||||
if need <= have:
|
||||
s += 5 # 模板列集能全覆盖该行
|
||||
if s > best_s:
|
||||
best, best_s = t, s
|
||||
return best
|
||||
|
||||
pos = list(parent).index(tmpls[0])
|
||||
for t in tmpls:
|
||||
parent.remove(t)
|
||||
for r in (rows or []):
|
||||
code, vals = _sum_values(r)
|
||||
comp = children.get(code) or []
|
||||
t = _pick(vals, comp)
|
||||
el = _deep(t)
|
||||
_put(el, vals)
|
||||
kids_t = _kids(t)
|
||||
if kids_t:
|
||||
ct = kids_t[0]
|
||||
_strip(el, {ct.tag})
|
||||
for ccode, cqty in comp:
|
||||
row = _deep(ct)
|
||||
_put(row, {"Number": ccode or "", "Quantity": _num(cqty), "Remark": ""})
|
||||
el.append(row)
|
||||
parent.insert(pos, el)
|
||||
pos += 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 主入口
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _blank_and_meta(con, rep, suffix):
|
||||
blank = rep.get("x_blank")
|
||||
if not blank:
|
||||
blank, _fn = classic_skeleton.frame_blank(con, rep["sig"])
|
||||
if not blank:
|
||||
return None, None
|
||||
meta = classic_skeleton.frame_meta(con, rep["sig"])
|
||||
if not meta:
|
||||
try:
|
||||
_b, meta = classic_skeleton.refine_blank_ex(rep["blob"], suffix)
|
||||
except Exception:
|
||||
meta = None
|
||||
return bytes(blank), meta
|
||||
|
||||
|
||||
def _load_children(sc, sid):
|
||||
out = {}
|
||||
try:
|
||||
for r in sc.execute("SELECT p_code, res_code, qty FROM s_lme_res "
|
||||
"WHERE session_id=? ORDER BY seq, id", (sid,)):
|
||||
if r["p_code"]:
|
||||
out.setdefault(r["p_code"], []).append((r["res_code"], r["qty"]))
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def _unit_cols(uw):
|
||||
"""骨架单位层各标签的列集(顺序按首次出现)——side 数据重建的列闸门。"""
|
||||
cols = {}
|
||||
for el in uw.iter():
|
||||
if isinstance(el.tag, str):
|
||||
c = cols.setdefault(el.tag, [])
|
||||
for a in el.attrib:
|
||||
if a not in c:
|
||||
c.append(a)
|
||||
return cols
|
||||
|
||||
|
||||
def _mk_side(node, cols):
|
||||
"""数据树节点 → 元素(只写骨架里有的列;骨架没有的标签/列不造)。"""
|
||||
tag = node.get("tag")
|
||||
if tag not in cols:
|
||||
return None
|
||||
el = ET.Element(tag)
|
||||
attrs = node.get("attrs") or {}
|
||||
for a in cols[tag]:
|
||||
v = attrs.get(a)
|
||||
el.set(a, "" if v is None else str(v))
|
||||
for k in node.get("kids") or []:
|
||||
c = _mk_side(k, cols)
|
||||
if c is not None:
|
||||
el.append(c)
|
||||
return el
|
||||
|
||||
|
||||
def _emit_unit_side(uw, side_json):
|
||||
"""单位工程非数据层(AttrInfo/SummaryOfCost(含 AddiCost)/UnitWorksSummary/Sundry/Tax…):
|
||||
按库里采集的原始结构重建——块数/行数=数据,列由骨架闸门决定;骨架没有的层不造;
|
||||
老批次没采集→保留骨架样板。"""
|
||||
if not side_json:
|
||||
return
|
||||
try:
|
||||
tree = json.loads(side_json)
|
||||
except (ValueError, TypeError):
|
||||
return
|
||||
if not isinstance(tree, list) or not tree:
|
||||
return
|
||||
cols = _unit_cols(uw)
|
||||
by = {}
|
||||
for rec in tree:
|
||||
if isinstance(rec, dict):
|
||||
by.setdefault(rec.get("tag"), []).append(rec)
|
||||
for tag, recs in by.items():
|
||||
tmpls = [c for c in _kids(uw) if c.tag == tag]
|
||||
if not tmpls:
|
||||
continue # 骨架没有该层:不造
|
||||
pos = list(uw).index(tmpls[0])
|
||||
keep = tmpls[0]
|
||||
for t in tmpls:
|
||||
uw.remove(t)
|
||||
made = []
|
||||
for rec in recs:
|
||||
el = _mk_side(rec, cols)
|
||||
if el is not None:
|
||||
made.append(el)
|
||||
if not made and min_count(tag) == 1:
|
||||
made = [_deep(keep)] # 加固:区域至少 1 个空壳,防结构缺失
|
||||
for el in made:
|
||||
uw.insert(pos, el)
|
||||
pos += 1
|
||||
|
||||
|
||||
def _merge_side(el, node, cols):
|
||||
"""把数据树合并进模板元素:写骨架里有的列;同 tag 子块按数据行整组替换
|
||||
(数据里没有的 tag 保留骨架原样——如 ProjectInstallationWorkCost 下的 SectionalWorks)。"""
|
||||
attrs = node.get("attrs") or {}
|
||||
for a in cols.get(el.tag) or []:
|
||||
v = attrs.get(a)
|
||||
el.set(a, "" if v is None else str(v))
|
||||
by = {}
|
||||
for k in node.get("kids") or []:
|
||||
if isinstance(k, dict):
|
||||
by.setdefault(k.get("tag"), []).append(k)
|
||||
for tag, recs in by.items():
|
||||
tmpls = [c for c in _kids(el) if c.tag == tag]
|
||||
if not tmpls:
|
||||
continue # 骨架没有该层:不造
|
||||
pos = list(el).index(tmpls[0])
|
||||
keep = tmpls[0]
|
||||
for t in tmpls:
|
||||
el.remove(t)
|
||||
made = []
|
||||
for rec in recs:
|
||||
c = _mk_side(rec, cols)
|
||||
if c is not None:
|
||||
made.append(c)
|
||||
if not made and min_count(tag) == 1:
|
||||
made = [_deep(keep)] # 加固:区域至少 1 个空壳
|
||||
for c in made:
|
||||
el.insert(pos, c)
|
||||
pos += 1
|
||||
|
||||
|
||||
def _emit_proj_side(proj, side_json):
|
||||
"""项目级非数据层:根属性 / SummaryOfCost(项目级+单项级两处,按路径区分)/ AddiCost /
|
||||
ProjectInstallationWorkCostSummary 等,按库数据合并重建。"""
|
||||
if not side_json:
|
||||
return
|
||||
try:
|
||||
recs = json.loads(side_json)
|
||||
except (ValueError, TypeError):
|
||||
return
|
||||
if not isinstance(recs, list):
|
||||
return
|
||||
cols = _unit_cols(proj)
|
||||
for rec in recs:
|
||||
if not isinstance(rec, dict):
|
||||
continue
|
||||
path = rec.get("path") or []
|
||||
if path and path[0] == proj.tag:
|
||||
path = path[1:] # 路径从根开始;根就是 proj 自身
|
||||
node = rec.get("node") or {}
|
||||
if not path: # 根属性
|
||||
attrs = node.get("attrs") or {}
|
||||
for a in cols.get(proj.tag) or []:
|
||||
if a in attrs:
|
||||
proj.set(a, "" if attrs[a] is None else str(attrs[a]))
|
||||
continue
|
||||
target = proj
|
||||
ok = True
|
||||
for tag in path:
|
||||
nxt = None
|
||||
for c in _kids(target):
|
||||
if c.tag == tag:
|
||||
nxt = c
|
||||
break
|
||||
if nxt is None:
|
||||
ok = False
|
||||
break
|
||||
target = nxt
|
||||
if not ok or target is proj:
|
||||
continue
|
||||
_merge_side(target, node, cols)
|
||||
|
||||
|
||||
def _tag_cols(root):
|
||||
cols = {}
|
||||
for el in root.iter():
|
||||
if isinstance(el.tag, str):
|
||||
cols.setdefault(el.tag, set()).update(el.attrib.keys())
|
||||
return cols
|
||||
|
||||
|
||||
def _own_layers(plan):
|
||||
"""本项目骨架的**数据层**要求(2026-11-04 主人定:列不算全部数据,只要数据层能全部导出)。
|
||||
→ (需要存在的层标签集合, 措施清单原生标签集合, 是否有措施分部)。"""
|
||||
need = set()
|
||||
prelim_tags = set()
|
||||
if plan.get("units"):
|
||||
need.add("UnitWorks")
|
||||
has_item = has_prelim = has_norm = has_res = False
|
||||
need_prelim_div = False
|
||||
for d in (plan.get("divides") or {}).values():
|
||||
if d.get("kind") == "prelim":
|
||||
need_prelim_div = True
|
||||
else:
|
||||
need.add("DivisionalWorks")
|
||||
for u in plan.get("units") or []:
|
||||
for b in u.get("bills") or []:
|
||||
if b.get("x_tdel"):
|
||||
continue
|
||||
if b.get("kind") == "prelim":
|
||||
has_prelim = True
|
||||
if b.get("x_ptag"):
|
||||
prelim_tags.add(b["x_ptag"])
|
||||
else:
|
||||
has_item = True
|
||||
for n in b.get("norms") or []:
|
||||
if n.get("x_tdel"):
|
||||
continue
|
||||
has_norm = True
|
||||
if n.get("x_adjust"):
|
||||
need.add("NormAdjustmentList")
|
||||
if n.get("res"):
|
||||
has_res = True
|
||||
if has_item or (has_prelim and "WorkElement" in prelim_tags):
|
||||
need.add("WorkElement")
|
||||
if has_prelim:
|
||||
need.add("PRELIM")
|
||||
if has_norm:
|
||||
need.add("Norm")
|
||||
if has_res:
|
||||
need.add("LabourMaterialsEquipmentsMachinesElement")
|
||||
if any((u.get("lme") or []) for u in plan.get("units") or []):
|
||||
need.add("LabourMaterialsEquipmentsMachinesSummary")
|
||||
return need, prelim_tags, need_prelim_div
|
||||
|
||||
|
||||
def _missing_layers(need, prelim_tags, need_prelim_div, tags):
|
||||
"""层覆盖判定(**不看列**):缺层才判不覆盖;列少不算。"""
|
||||
miss = [t for t in need if t != "PRELIM" and t not in tags]
|
||||
if "PRELIM" in need:
|
||||
if prelim_tags:
|
||||
for t in prelim_tags:
|
||||
if t not in tags:
|
||||
miss.append(t)
|
||||
elif not any(t in tags for t in ("UnitWorksPreliminaryWorkElement", "WorkElement")):
|
||||
miss.append("PRELIM")
|
||||
if need_prelim_div and "PreliminaryDivisionalWorks" not in tags:
|
||||
miss.append("PreliminaryDivisionalWorks")
|
||||
return miss
|
||||
|
||||
|
||||
def export_v2(con, sc, sid, suffix, progress=None, src_path=None):
|
||||
"""骨架回灌导出(2026-11-04 决策267):**优先本项目自己的骨架**(打开工程时从源件提炼入库);
|
||||
数据层列覆盖不全 → 后台骨架补充缺列;缺整层 → 回落后台骨架;再不行用源件现提炼。"""
|
||||
plan = build_plan(sc, sid)
|
||||
if plan is None:
|
||||
return None, None, "会话数据读不出来"
|
||||
srow = plan["srow"]
|
||||
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
|
||||
try:
|
||||
proj_side = srow["x_side"]
|
||||
except (KeyError, IndexError):
|
||||
proj_side = None
|
||||
children = _load_children(sc, sid)
|
||||
attr_map = {}
|
||||
try:
|
||||
for r in sc.execute("SELECT id, x_attr FROM s_unit_works WHERE session_id=?", (sid,)):
|
||||
attr_map[r["id"]] = r["x_attr"]
|
||||
except Exception:
|
||||
attr_map = {}
|
||||
|
||||
# ===== 骨架选择:本项目骨架优先(只看数据层是否齐全;列少不算不覆盖) =====
|
||||
need, prelim_tags, need_prelim_div = _own_layers(plan)
|
||||
try:
|
||||
own_blank = srow["x_own_blank"]
|
||||
except (KeyError, IndexError):
|
||||
own_blank = None
|
||||
own_meta = None
|
||||
try:
|
||||
if srow["x_own_meta"]:
|
||||
own_meta = json.loads(srow["x_own_meta"])
|
||||
except (KeyError, IndexError, ValueError, TypeError):
|
||||
own_meta = None
|
||||
rep = None
|
||||
blank = meta = None
|
||||
if own_blank:
|
||||
try:
|
||||
oroot, _od = classic_skeleton._blank_parse(bytes(own_blank).decode("utf-8"))
|
||||
tags = {el.tag for el in oroot.iter() if isinstance(el.tag, str)}
|
||||
miss = _missing_layers(need, prelim_tags, need_prelim_div, tags)
|
||||
if not miss:
|
||||
blank, meta = bytes(own_blank), own_meta
|
||||
except Exception:
|
||||
blank, meta = None, None
|
||||
if not blank:
|
||||
if rep is None:
|
||||
rep = classic_skeleton.pick_frame(con, (suffix or "").lower(), src_path=src_path)
|
||||
if rep:
|
||||
blank, meta = _blank_and_meta(con, rep, suffix)
|
||||
if not blank and src_path and os.path.exists(src_path):
|
||||
# 库/本项目骨架都没有:就地按源件提炼一件内存骨架(不落库)
|
||||
try:
|
||||
blank, meta = classic_skeleton.refine_blank_ex(
|
||||
open(src_path, "rb").read(), suffix)
|
||||
except Exception:
|
||||
blank, meta = None, None
|
||||
if not blank:
|
||||
return None, None, "该后缀还没有骨架:请先在后台导入"
|
||||
skel_root, decl = classic_skeleton._blank_parse(blank.decode("utf-8"))
|
||||
norm_db = {}
|
||||
for r in sc.execute("""SELECT n.id, n.Total AS db_total
|
||||
FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=?""", (sid,)):
|
||||
norm_db[r["id"]] = r["db_total"]
|
||||
|
||||
# 单位工程模板=骨架里内嵌的那棵单位子树(项目骨架同一位置换成 N 条索引行)
|
||||
unit_tmpl = None
|
||||
for par in skel_root.iter():
|
||||
for k in _kids(par, "UnitWorks"):
|
||||
if _kids(k):
|
||||
unit_tmpl = k
|
||||
break
|
||||
if unit_tmpl is not None:
|
||||
break
|
||||
if unit_tmpl is None:
|
||||
return None, None, "骨架缺单位工程样板"
|
||||
|
||||
dea_t = _first(unit_tmpl, "DivisionalAndElementalWorks")
|
||||
pre_t = _first(unit_tmpl, "Preliminaries")
|
||||
scope_t = dea_t if dea_t is not None else unit_tmpl
|
||||
_pre_ids = set()
|
||||
for _tag in ("WorkElement", "DivisionalWorks"):
|
||||
if pre_t is not None:
|
||||
for _e in pre_t.iter(_tag):
|
||||
_pre_ids.add(id(_e))
|
||||
bills_t = [w for w in scope_t.iter("WorkElement") if id(w) not in _pre_ids]
|
||||
tmpls = {"bill": bills_t[0] if bills_t else None}
|
||||
if tmpls["bill"] is None:
|
||||
return None, None, "骨架缺清单样板"
|
||||
wc_t = _first(tmpls["bill"], "WorkContent")
|
||||
host_t = wc_t if wc_t is not None else tmpls["bill"]
|
||||
tmpls["norm"] = _first(host_t, "Norm")
|
||||
if tmpls["norm"] is None:
|
||||
return None, None, "骨架缺定额样板"
|
||||
deepest = None
|
||||
for c in scope_t.iter("DivisionalWorks"):
|
||||
if id(c) in _pre_ids:
|
||||
continue
|
||||
if _kids(c, "WorkElement"):
|
||||
deepest = c
|
||||
tmpls["div"] = deepest if deepest is not None else next(
|
||||
(c for c in scope_t.iter("DivisionalWorks") if id(c) not in _pre_ids), None)
|
||||
tmpls["pre_bill"] = _first(pre_t, "UnitWorksPreliminaryWorkElement") if pre_t is not None else None
|
||||
tmpls["pre_div"] = _first(pre_t, "PreliminaryDivisionalWorks") if pre_t is not None else None
|
||||
if pre_t is not None and tmpls["pre_bill"] is None:
|
||||
# 老 cos 族:措施条目就是 WorkElement/DivisionalWorks(标签与分部分项相同)
|
||||
tmpls["pre_bill"] = _first(pre_t, "WorkElement") or tmpls.get("bill")
|
||||
tmpls["pre_div"] = _first(pre_t, "DivisionalWorks")
|
||||
|
||||
unit_xmls = []
|
||||
for i, u in enumerate(plan["units"], 1):
|
||||
uw = _deep(unit_tmpl)
|
||||
_put(uw, {
|
||||
"Number": u.get("number") or "", "Name": u.get("name") or "",
|
||||
"FileName": "@_%s_%s.xml" % (u.get("number") or i, (u.get("name") or "").strip()),
|
||||
"Total": _money(u.get("total")),
|
||||
})
|
||||
dea = _kids(uw, "DivisionalAndElementalWorks")
|
||||
works_host = dea[0] if dea else uw
|
||||
_emit_works(works_host, u, plan, tmpls, norm_db, children)
|
||||
pre = _kids(uw, "Preliminaries")
|
||||
if pre:
|
||||
_emit_prelim(pre[0], u, plan, tmpls, norm_db, children)
|
||||
try:
|
||||
rows = dyn_lme.dyn_uw_rows(sc, sid, u["id"]) or []
|
||||
except Exception:
|
||||
rows = []
|
||||
_emit_sums(uw, rows, children)
|
||||
for region in uw.iter():
|
||||
if isinstance(region.tag, str) and region.tag in _RESULT_REGIONS:
|
||||
_blank_values(region)
|
||||
_emit_unit_side(uw, attr_map.get(u["id"]))
|
||||
# 单位工程 SummaryOfCost 合价回填(决策 264③):全部按现算清单/措施合价
|
||||
qdf = sum(float(b.get("Total") or 0) for b in (u.get("bills") or [])
|
||||
if b.get("kind") != "prelim" and not b.get("x_tdel"))
|
||||
qsf = sum(float(b.get("Total") or 0) for b in (u.get("bills") or [])
|
||||
if b.get("kind") == "prelim" and not b.get("x_tdel"))
|
||||
for sm in _kids(uw, "SummaryOfCost"):
|
||||
_put(sm, {"DivisionalAndElementalWorks": _money(qdf),
|
||||
"Preliminaries": _money(qsf)})
|
||||
name = "@_%s_%s.xml" % (u.get("number") or i, (u.get("name") or "").strip())
|
||||
unit_xmls.append((name, decl + "\n" + se.serialize(uw, 0, " ", keep_values=True)))
|
||||
|
||||
# 项目文件:骨架项目树 + N 条单位索引行 + 项目级工料机汇总
|
||||
proj = _deep(skel_root)
|
||||
hm = None
|
||||
for par in proj.iter():
|
||||
for k in _kids(par, "UnitWorks"):
|
||||
if _kids(k):
|
||||
hm = (par, k)
|
||||
break
|
||||
if hm:
|
||||
break
|
||||
if hm:
|
||||
hm[0].remove(hm[1])
|
||||
holder2 = hm[0]
|
||||
else:
|
||||
holder2 = proj
|
||||
attrs = ((meta or {}).get("index_row") or {}).get("attrs") or []
|
||||
for i, u in enumerate(plan["units"], 1):
|
||||
row = ET.SubElement(holder2, "UnitWorks")
|
||||
for a in attrs:
|
||||
row.set(a, "")
|
||||
fname = "@_%s_%s.xml" % (u.get("number") or i, (u.get("name") or "").strip())
|
||||
row.set("FileName", fname) # 引用成员名:骨架没这列也要写(否则成员对不上)
|
||||
_put(row, {
|
||||
"Number": u.get("number") or "", "Name": u.get("name") or "",
|
||||
"Total": _money(u.get("total")),
|
||||
})
|
||||
try:
|
||||
prows = dyn_lme.dyn_rows(sc, sid, None) or []
|
||||
prows = [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8],
|
||||
r[11], r[12], r[13], r[14], r[15] if len(r) > 15 else None] for r in prows]
|
||||
except Exception:
|
||||
prows = []
|
||||
_emit_sums(proj, prows, children)
|
||||
for region in proj.iter():
|
||||
if isinstance(region.tag, str) and region.tag in _RESULT_REGIONS:
|
||||
_blank_values(region)
|
||||
_emit_proj_side(proj, proj_side)
|
||||
_put(proj, {"Name": proj_name}) # 工程名以当前会话为准(覆盖 side 里的原名)
|
||||
proj_xml = decl + "\n" + se.serialize(proj, 0, " ", keep_values=True)
|
||||
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
zi = zipfile.ZipInfo("Project.xml", date_time=(2026, 1, 1, 0, 0, 0))
|
||||
zo.writestr(zi, proj_xml.encode("utf-8"))
|
||||
for nm, txt in unit_xmls:
|
||||
zi = _GbkZipInfo(nm, date_time=(2026, 1, 1, 0, 0, 0))
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zo.writestr(zi, txt.encode("utf-8"))
|
||||
if progress:
|
||||
progress(len(unit_xmls) + 1, len(unit_xmls) + 1)
|
||||
return out.getvalue(), out_name(proj_name, suffix), None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 骨架库:导出「完全空的骨架 + 导出规则标注」(2026-11-03 主人定,新增功能)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# 自增层:行数=会话数据条数(导出时按数据循环)
|
||||
_LOOP_TAGS = {
|
||||
"UnitWorks", "DivisionalWorks", "WorkElement", "Norm",
|
||||
"LabourMaterialsEquipmentsMachinesElement", "LabourMaterialsEquipmentsMachinesSummary",
|
||||
"UnitWorksPreliminaryWorkElement", "PreliminaryWorkElement", "PreliminaryDivisionalWorks",
|
||||
"NormAdjustmentList",
|
||||
}
|
||||
# 按库行:行数/值来自 x_side(Import 采集的原件固定子块)
|
||||
_SIDE_TAGS = {
|
||||
"UnitPriceCalculationOfItem", "ManageFees", "SummaryOfBasicCost", "ExpressElement",
|
||||
}
|
||||
# 工程特征树(2026-11-03 主人定):AttrInfo 下的组=自增块、叶=自增行,数据来自 s_unit_works.x_attr
|
||||
_ATTR_TAGS = {"AttrInfoItem", "InfoItem"}
|
||||
|
||||
|
||||
# 结构位规则(2026-11-03 主人定「全部按自增区域/自增块/自增行设计」):
|
||||
# · 自增区域 min_count=1 —— 结构壳,数据 0 条也输出 1 个空壳(不然接收软件缺结构);
|
||||
# · 自增块 / 自增行 min_count=0 —— 条数=数据条数,0 条不输出。
|
||||
# 「固定」概念取消,内核只剩「基数下限」。
|
||||
_REGION_TAGS = {
|
||||
"ConstructionProject", "ProjectInstallationWorkCost", "SectionalWorks",
|
||||
"SystemInfo", "ConstructionInfo", "ProjectInfo", "TendereeInfo", "BidderInfo",
|
||||
"AttrInfo", "AddiInfo", "SummaryOfCost", "UnitWorksSummary",
|
||||
"DivisionalAndElementalWorks", "Preliminaries", "WorkContent",
|
||||
}
|
||||
|
||||
|
||||
def min_count(tag):
|
||||
"""结构位基数下限:自增区域=1(至少一个空壳);自增块/自增行及其余=0。"""
|
||||
return 1 if tag in _REGION_TAGS else 0
|
||||
|
||||
|
||||
def row_count(el, data_n):
|
||||
"""导出条数 = max(下限, 数据条数)(加固:区域即使 0 条数据也保留 1 个空壳)。"""
|
||||
tag = el.tag if hasattr(el, "tag") else el
|
||||
return max(min_count(tag), int(data_n or 0))
|
||||
|
||||
|
||||
def rule_note(el):
|
||||
"""导出规则标注(写进空骨架 XML 注释,供主人核对规则对不对)。
|
||||
口径:骨架只给格式;**全部按自增设计**——区域=至少1个空壳、块=按数据块、
|
||||
行=按数据行;不再有「固定」。"""
|
||||
tag = el.tag if isinstance(el.tag, str) else ""
|
||||
if min_count(tag) == 1:
|
||||
return "自增区域:至少 1 个"
|
||||
return "自增块:按数据块循环" if _kids(el) else "自增行:按数据行循环"
|
||||
|
||||
|
||||
def build_blank_package(con, sig):
|
||||
"""骨架库某件 → 完全空的原格式包(Project.xml + 单位成员),每个结构位带规则注释。
|
||||
→ (字节, 文件名, 错误)。zip 族给 .cos4/.cos 包;裸 XML 族给单 XML。"""
|
||||
row = con.execute("SELECT sig, original_name, suffix, x_blank, blob "
|
||||
"FROM classic_skel WHERE sig=?", (sig,)).fetchone()
|
||||
if not row:
|
||||
return None, None, "骨架不存在"
|
||||
name = row["original_name"] or "骨架"
|
||||
suffix = row["suffix"] or "cos4"
|
||||
blank = row["x_blank"]
|
||||
if not blank:
|
||||
blank, _fn = classic_skeleton.frame_blank(con, sig)
|
||||
if not blank:
|
||||
return None, None, "该骨架暂无法总结空骨架"
|
||||
root, decl = classic_skeleton._blank_parse(bytes(blank).decode("utf-8"))
|
||||
meta = classic_skeleton.frame_meta(con, sig) or {}
|
||||
blob = bytes(row["blob"] or b"")
|
||||
|
||||
_LEGEND = ("导出规则:自增区域=至少 1 个空壳;自增块=按数据块循环;"
|
||||
"自增行=按数据行循环。列由骨架决定,值来自数据库")
|
||||
|
||||
def _ser(el):
|
||||
return (decl + "\n<!-- " + _LEGEND + " -->\n"
|
||||
+ se.serialize(el, 0, " ", keep_values=True, note_fn=rule_note) + "\n")
|
||||
|
||||
fam = se.family_of(blob)
|
||||
if fam != se.FAMILY_ZIP:
|
||||
# 裸 XML 族(swt/swz):整件就是骨架,直接单 XML 标注
|
||||
data = _ser(root).encode("utf-8")
|
||||
return data, "%s-空骨架(标注).%s" % (name, suffix), None
|
||||
|
||||
# zip 族:从项目树里取出内嵌单位模板 → 换成 1 条空索引行;单位模板单独成成员
|
||||
unit = None
|
||||
holder = None
|
||||
for par in root.iter():
|
||||
for k in _kids(par, "UnitWorks"):
|
||||
if _kids(k):
|
||||
unit, holder = k, par
|
||||
break
|
||||
if unit is not None:
|
||||
break
|
||||
if unit is None:
|
||||
# 退化骨架(没有单位层):整棵项目树带标注给单 XML,不硬造单位层
|
||||
return _ser(root).encode("utf-8"), "%s-空骨架(标注).%s" % (name, suffix), None
|
||||
member = "@_1_单位工程.xml"
|
||||
holder.remove(unit)
|
||||
idx_attrs = ((meta.get("index_row") or {}).get("attrs") or ["Number", "Name", "FileName"])
|
||||
idx = ET.SubElement(holder, "UnitWorks")
|
||||
for a in idx_attrs:
|
||||
idx.set(a, "")
|
||||
idx.set("FileName", member)
|
||||
proj_xml = _ser(root)
|
||||
unit_xml = _ser(unit)
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
zi = zipfile.ZipInfo("Project.xml", date_time=(2026, 1, 1, 0, 0, 0))
|
||||
zo.writestr(zi, proj_xml.encode("utf-8"))
|
||||
zi = _GbkZipInfo(member, date_time=(2026, 1, 1, 0, 0, 0))
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zo.writestr(zi, unit_xml.encode("utf-8"))
|
||||
return out.getvalue(), "%s-空骨架(标注).%s" % (name, suffix), None
|
||||
@@ -1,65 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把数据库导出成 Excel,方便直接用 WPS / Excel 查看(小白友好)"""
|
||||
import sqlite3, os
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.cell import WriteOnlyCell
|
||||
|
||||
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
|
||||
_PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核
|
||||
DB = os.path.join(_PRJ, "data", "history.db")
|
||||
OUT = os.path.join(_PRJ, "data", "数据库一览.xlsx")
|
||||
|
||||
# 单价类型(2026-09-29 你定:原「文件类型」整体替换为单价类型,取值四选一)
|
||||
FILEKIND = {1: "预算综合单价", 2: "投标综合单价", 3: "预算全费用", 4: "投标全费用", 0: "未标注"}
|
||||
|
||||
SHEETS = [
|
||||
("清单", """SELECT b.id, b.Number 项目编码, b.Name 项目名称, b.Attr 项目特征,
|
||||
b.Unit 单位, b.Price 综合单价 FROM bills b""", None),
|
||||
("定额", "SELECT n.id, n.Number 定额编码, n.Name 定额名称, n.Unit 单位, n.Price 单价 FROM norms n", None),
|
||||
("工料机", """SELECT l.id, l.Name 名称, l.Specification 规格型号, l.Unit 单位,
|
||||
l.NoTaxPrice 除税编制价, l.TaxRate 税率, l.TaxPrice 含税编制价
|
||||
FROM lmes l""", None),
|
||||
("导入日志", """SELECT g.file 文件, g.schema 格式, g.n_bill 清单入库, g.n_bill_skip 跳过项单位,
|
||||
g.n_norm 定额入库, g.n_lme 工料机入库, g.n_lme_skip 跳过组合费用, round(g.secs,2) 耗时秒,
|
||||
g.msg 备注 FROM import_log g""", None),
|
||||
]
|
||||
|
||||
def main():
|
||||
con = sqlite3.connect(DB)
|
||||
wb = Workbook(write_only=True)
|
||||
hdr_font = Font(bold=True, color="FFFFFF")
|
||||
hdr_fill = PatternFill("solid", fgColor="1F5FAE")
|
||||
|
||||
# 批次单独处理(单价类型转中文)
|
||||
ws = wb.create_sheet("批次(项目)")
|
||||
# 2026-10-06:x_rows_price 是后加的列,老库可能还没有 → 容错取 0
|
||||
_cols = [r[1] for r in con.execute("PRAGMA table_info(batches)")]
|
||||
_rp = "x_rows_price" if "x_rows_price" in _cols else "0"
|
||||
rows = con.execute("""SELECT id, Name, FileKind, BulidUnit, x_period_start_m, x_period_end_m,
|
||||
x_total, x_rows_bill, x_rows_lme, x_imported_at, %s FROM batches""" % _rp).fetchall()
|
||||
head = ["ID", "项目名称", "单价类型", "建设单位", "期次起", "期次止",
|
||||
"总价(元)", "清单条目", "工料机条目", "导入时间", "价格条目"]
|
||||
hr = [WriteOnlyCell(ws, value=v) for v in head]
|
||||
for c in hr:
|
||||
c.font = hdr_font; c.fill = hdr_fill
|
||||
ws.append(hr)
|
||||
for r in rows:
|
||||
ws.append([r[0], r[1], FILEKIND.get(r[2], "未标注"), r[3], r[4], r[5], r[6], r[7], r[8], r[9]])
|
||||
|
||||
for name, sql, _ in SHEETS[1:]:
|
||||
ws = wb.create_sheet(name)
|
||||
cur = con.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
hr = [WriteOnlyCell(ws, value=v) for v in cols]
|
||||
for c in hr:
|
||||
c.font = hdr_font; c.fill = hdr_fill
|
||||
ws.append(hr)
|
||||
for r in cur:
|
||||
ws.append(list(r))
|
||||
|
||||
wb.save(OUT)
|
||||
print("OK ->", OUT, os.path.getsize(OUT) // 1024, "KB")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,89 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""".yhy 专有格式导出(2026-11-03 主人定):审核等全部数据打包单文件,不同租户相互交流。
|
||||
|
||||
内容 = 该会话在会话库里的全部数据:
|
||||
· sessions 行(17 列全带,含 x_info/x_feat 等原文)
|
||||
· 全部带 session_id 的 s_* 表(动态枚举 sqlite_master,将来加表自动带上,防漏表)
|
||||
· s_norms / s_norm_res(无 session_id,按 bills→norms 父引用带出)
|
||||
不导:s_settings(软件设置,非会话数据)、s_remarks(按源文件共享的备注源库,备注本体
|
||||
已在 s_bills.x_remark)、s_edit_log(审计日志按内容锚关联,无法按会话切分)。
|
||||
|
||||
格式:zip 包(manifest.json + sessions.json + rows/<表>.json,UTF-8 JSON)。
|
||||
导入(收方建会话)另立项——子表 id 全局自增、跨会话会撞号,方案待主人拍板。"""
|
||||
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
|
||||
YHY_MAGIC = "YHY"
|
||||
YHY_VERSION = 1
|
||||
_SKIP_TABLES = ("s_settings", "s_remarks", "s_edit_log")
|
||||
|
||||
|
||||
def _json_default(o):
|
||||
if isinstance(o, (bytes, bytearray)):
|
||||
return o.decode("utf-8", "replace")
|
||||
return str(o)
|
||||
|
||||
|
||||
def _session_tables(sc):
|
||||
"""带 session_id 的 s_* 表(动态枚举,防漏表)。"""
|
||||
tabs = [r[0] for r in sc.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()]
|
||||
out = []
|
||||
for t in tabs:
|
||||
if not t.startswith("s_") or t in _SKIP_TABLES:
|
||||
continue
|
||||
cols = [c[1] for c in sc.execute("PRAGMA table_info('%s')" % t).fetchall()]
|
||||
if "session_id" in cols:
|
||||
out.append(t)
|
||||
return out
|
||||
|
||||
|
||||
def export(sc, sid):
|
||||
""".yhy 导出入口:返回 (字节, 文件名, 错误)。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
proj = (srow["name"] if "name" in srow.keys() else srow["Name"]) or "工程"
|
||||
payload = {}
|
||||
payload["sessions"] = [dict(r) for r in sc.execute(
|
||||
"SELECT * FROM sessions WHERE id=?", (sid,)).fetchall()]
|
||||
for t in _session_tables(sc):
|
||||
payload[t] = [dict(r) for r in sc.execute(
|
||||
"SELECT * FROM %s WHERE session_id=? ORDER BY id" % t, (sid,)).fetchall()]
|
||||
# 子表按父引用带出(s_norms→bills,s_norm_res→norms;无数据=空表也留键,收方可对结构)
|
||||
bids = [b["id"] for b in payload.get("s_bills", [])]
|
||||
if bids:
|
||||
ph = ",".join("?" * len(bids))
|
||||
payload["s_norms"] = [dict(r) for r in sc.execute(
|
||||
"SELECT * FROM s_norms WHERE bill_id IN (%s) ORDER BY id" % ph, bids).fetchall()]
|
||||
else:
|
||||
payload["s_norms"] = []
|
||||
nids = [n["id"] for n in payload["s_norms"]]
|
||||
if nids:
|
||||
ph = ",".join("?" * len(nids))
|
||||
payload["s_norm_res"] = [dict(r) for r in sc.execute(
|
||||
"SELECT * FROM s_norm_res WHERE norm_id IN (%s) ORDER BY id" % ph, nids).fetchall()]
|
||||
else:
|
||||
payload["s_norm_res"] = []
|
||||
|
||||
manifest = {
|
||||
"magic": YHY_MAGIC,
|
||||
"version": YHY_VERSION,
|
||||
"exported_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"session_name": proj,
|
||||
"tables": {t: len(v) for t, v in sorted(payload.items())},
|
||||
}
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
zo.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=1))
|
||||
zo.writestr("sessions.json", json.dumps(payload["sessions"], ensure_ascii=False,
|
||||
default=_json_default))
|
||||
for t, rows in payload.items():
|
||||
if t == "sessions":
|
||||
continue
|
||||
zo.writestr("rows/%s.json" % t, json.dumps(rows, ensure_ascii=False,
|
||||
default=_json_default))
|
||||
return buf.getvalue(), proj + "-审核版.yhy", None
|
||||
@@ -1,50 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""字段取值策略——全软件唯一写死处(2026-10-28 主人定)。
|
||||
|
||||
原理(主人原话):「a字段=b字段=c字段=n字段,规定a字段是现算的,那么一连串都是现算的」——
|
||||
策略挂在**软件字段(链头)**上,一条链只定义一次;显示层、导出映射层、格式对齐表
|
||||
全部只引用本模块,格式侧不另定义(决策147 同码同形同源)。写死≠改不了:
|
||||
主人改口径=改那一行+跑回归+台账记新决策(铁律7:行只由主人加)。
|
||||
|
||||
六类策略:
|
||||
RAW 捕获原始——照存照显,从不重算(未列字段的默认基线)
|
||||
EDITED 录入/决定——人的操作照存(改价、备注、临删、合并、采纳标记、联动改写)
|
||||
COMPUTED 现算——读时算;库列去留随决策233 挂起的存库方案
|
||||
PRICE3 三价组合(决策235)——原始直填+缺哪算哪+齐全读时复核税率(±0.01pp 容差、
|
||||
只提示不改值);已有的税率从不改写
|
||||
ANCHOR 锚点/快照——第一次落值永不回写
|
||||
SNAPSHOT 存而不用的快照列——不参与显示与取价,物理去留随存库方案(决策234补一)
|
||||
|
||||
逐行出处=决策台账;本模块注释里的行与台账一一对应。
|
||||
"""
|
||||
|
||||
RAW = "raw"
|
||||
EDITED = "edited"
|
||||
COMPUTED = "computed"
|
||||
PRICE3 = "price3"
|
||||
ANCHOR = "anchor"
|
||||
SNAPSHOT = "snapshot"
|
||||
|
||||
DEFAULT = RAW # 未列字段一律按捕获原始(现状基线,非新拍板)
|
||||
|
||||
# 已拍板字段(链头)。键=软件字段;值=策略。
|
||||
STRATEGY = {
|
||||
# ── 清单(决策233,2026-10-28)────────────────────────────
|
||||
"bill.price": COMPUTED, # 清单单价=∑(未临删定额合价)÷清单工程量,半升2位
|
||||
"bill.total": COMPUTED, # 清单合价=清单单价×清单工程量
|
||||
"norm.total": COMPUTED, # 定额合价=显示工程量×单价(公式行用求值量÷单位因子,采纳定额同样算)
|
||||
"qty0.hide": True, # 清单工程量=0 → 量/单价/合价不算不显不报错(前端留空)
|
||||
# ── 工料机(决策234/235/219)──────────────────────────────
|
||||
"lme.qty": COMPUTED, # 汇总数量读时现算(Σ消耗量×定额量)、编辑绝不回写(234补一)
|
||||
"lme.ntp": PRICE3, # 除税编制价
|
||||
"lme.taxrate": PRICE3, # 税率(缺=含税÷除税−1反推;齐全复核对象;已有的永不改写)
|
||||
"lme.taxp": PRICE3, # 含税编制价
|
||||
"uw_card.src": COMPUTED, # 单位工程级卡以我方现算值为准(决策234;dyn→agg 撤 summary,待开干)
|
||||
# ── 锚点/快照(决策217/219/234补一)───────────────────────
|
||||
"bill.x_price0": ANCHOR, # 清单第一次导入单价(备注「+旧价」恒取此)
|
||||
"lme.x_ntp0": ANCHOR, # 三价锚三列(合并生成行=合并后首次三价;永不回写)
|
||||
"lme.x_rate0": ANCHOR,
|
||||
"lme.x_taxp0": ANCHOR,
|
||||
"lme_uw.qty": SNAPSHOT, # 源文件自带汇总数量快照——234 后显示不用(存而不用)
|
||||
"lme_proj.qty": SNAPSHOT, # 导入/合并落值——显示不读(dyn 现算)(234补一)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出格式适配器包:import 本包即完成各格式注册。"""
|
||||
from .registry import get_exporter
|
||||
|
||||
from . import swt # noqa: F401 (导入即注册 SWT/SWZ)
|
||||
|
||||
__all__ = ["get_exporter"]
|
||||
@@ -1,21 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,220 +0,0 @@
|
||||
# -*- 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
|
||||
|
||||
|
||||
def _natkey(s):
|
||||
"""编号自然序键(与界面树/汇总分析同款):数字段按数值、非数字段按文本。"""
|
||||
out, buf, digit = [], "", None
|
||||
for ch in s or "":
|
||||
d = ch.isdigit()
|
||||
if d == digit:
|
||||
buf += ch
|
||||
else:
|
||||
if buf:
|
||||
out.append((1, int(buf), "") if digit else (0, 0, buf))
|
||||
buf, digit = ch, d
|
||||
if buf:
|
||||
out.append((1, int(buf), "") if digit else (0, 0, buf))
|
||||
return out
|
||||
|
||||
_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=? ORDER BY id", (sid,)):
|
||||
sections[r["id"]] = {"id": r["id"], "number": r["Number"] or "",
|
||||
"name": r["Name"] or "", "total": r["Total"]}
|
||||
# 单位顺序=左侧目录树序(2026-10-28 主人定通用口径,与 2026-10-08 汇总分析同款):
|
||||
# 单项按入库序、组内按编号自然序。手工树保存时按组内位置重写编号=目录序持久化在
|
||||
# Number 里;此前 ORDER BY id 在树里上下移动过单位后会与目录顺序脱节。
|
||||
sec_order = {k: i for i, k in enumerate(sections)}
|
||||
rows = sc.execute("SELECT * FROM s_unit_works WHERE session_id=?", (sid,)).fetchall()
|
||||
rows = sorted(rows, key=lambda r: (sec_order.get(r["section_id"], len(sec_order)),
|
||||
_natkey(r["Number"] or ""), r["id"]))
|
||||
units = []
|
||||
for r in rows:
|
||||
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 "",
|
||||
"x_seq": r["x_seq"]}
|
||||
# 定额:先按 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"], r["express"]))
|
||||
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()
|
||||
@@ -1,466 +0,0 @@
|
||||
# -*- 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())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,128 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""".yhy 专有格式导入(2026-11-03 主人定):**id 整体平移法**——
|
||||
每表全部 id 统一加 offset(offset=库内该表当前 max(id)+1−导出件最小 id),
|
||||
父 id/平面 id 引用按被引用表的同款 offset 一并平移,数据行原样保真(含全部 x_* 状态列)。
|
||||
|
||||
引用映射(与 export_yhy 的导出面一致;@SID=换成新会话 id):
|
||||
s_sections.id
|
||||
s_unit_works.section_id → s_sections.id
|
||||
s_divides.uw_id → s_unit_works.id;s_divides.parent_id → s_divides.id(自引用)
|
||||
s_bills.uw_id → s_unit_works.id;s_bills.div_id → s_divides.id
|
||||
s_norms.bill_id → s_bills.id;s_norms.x_src_norm_id → s_norms.id(自引用)
|
||||
s_norm_res.norm_id → s_norms.id
|
||||
s_lme_uw.uw_id / s_sundry.uw_id / s_uw_summary.uw_id → s_unit_works.id
|
||||
其余带 session_id 表只换 session_id。s_settings/s_remarks/s_edit_log 不在导出面(导入天然无关)。
|
||||
|
||||
sessions 行=新会话:name/期次/地区/建设单位/单价类型用弹框传入覆盖(「名称等一切按弹框」,
|
||||
2026-11-03 主人定),其余列(x_info/x_feat/src_name/x_manual 等)原样保真;x_batch_id 跨库
|
||||
引用置空。同名工程拒绝(决策 242)。导入不 commit——事务由调用方提交/回滚(api_server 模式)。"""
|
||||
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
|
||||
# (表名, {引用列: 被引用表});顺序=依赖序(被引用表先插)。
|
||||
_TABLES = [
|
||||
("s_sections", {"session_id": "@SID"}),
|
||||
("s_unit_works", {"session_id": "@SID", "section_id": "s_sections"}),
|
||||
("s_divides", {"session_id": "@SID", "uw_id": "s_unit_works", "parent_id": "s_divides"}),
|
||||
("s_bills", {"session_id": "@SID", "uw_id": "s_unit_works", "div_id": "s_divides"}),
|
||||
("s_norms", {"bill_id": "s_bills", "x_src_norm_id": "s_norms"}),
|
||||
("s_norm_res", {"norm_id": "s_norms"}),
|
||||
("s_lme_lib", {"session_id": "@SID"}),
|
||||
("s_lme_proj", {"session_id": "@SID"}),
|
||||
("s_lme_res", {"session_id": "@SID"}),
|
||||
("s_lme_uw", {"session_id": "@SID", "uw_id": "s_unit_works"}),
|
||||
("s_lmes", {"session_id": "@SID"}),
|
||||
("s_proj_summary", {"session_id": "@SID"}),
|
||||
("s_sundry", {"session_id": "@SID", "uw_id": "s_unit_works"}),
|
||||
("s_uw_summary", {"session_id": "@SID", "uw_id": "s_unit_works"}),
|
||||
]
|
||||
|
||||
|
||||
def _read_zip(zip_path):
|
||||
z = zipfile.ZipFile(zip_path)
|
||||
man = json.loads(z.read("manifest.json").decode("utf-8"))
|
||||
if man.get("magic") != "YHY":
|
||||
raise ValueError("这不是本软件导出的 .yhy 工程包")
|
||||
sessions = json.loads(z.read("sessions.json").decode("utf-8"))
|
||||
rows = {}
|
||||
for name in z.namelist():
|
||||
if name.startswith("rows/") and name.endswith(".json"):
|
||||
rows[name[5:-5]] = json.loads(z.read(name).decode("utf-8"))
|
||||
return man, sessions, rows
|
||||
|
||||
|
||||
def run(con, zip_path, name=None, overrides=None):
|
||||
"""导入 .yhy:成功 {ok,sid,name,manual,tables,msg};失败 {ok:False,msg}。不 commit。"""
|
||||
ov = overrides or {}
|
||||
try:
|
||||
man, sess_rows, rows = _read_zip(zip_path)
|
||||
except (zipfile.BadZipFile, KeyError, ValueError) as e:
|
||||
return {"ok": False, "msg": str(e)}
|
||||
if not sess_rows:
|
||||
return {"ok": False, "msg": "工程包里没有会话数据"}
|
||||
src = sess_rows[0]
|
||||
new_name = (name or "").strip() or src.get("name") or "工程"
|
||||
if con.execute("SELECT 1 FROM sessions WHERE name=?", (new_name,)).fetchone():
|
||||
return {"ok": False, "msg": "同名工程已存在:%s(请换个名称再导入)" % new_name}
|
||||
|
||||
new_sid = con.execute("SELECT COALESCE(MAX(id),0)+1 FROM sessions").fetchone()[0]
|
||||
|
||||
# 每表 offset=库内当前 max(id)+1−导出件最小 id(空库导入时 offset=0,id 原样)
|
||||
offsets = {}
|
||||
for t, _refs in _TABLES:
|
||||
ids = [r.get("id") for r in rows.get(t, []) if isinstance(r.get("id"), int)]
|
||||
if ids:
|
||||
cur = con.execute("SELECT COALESCE(MAX(id),0) FROM %s" % t).fetchone()[0]
|
||||
offsets[t] = cur + 1 - min(ids)
|
||||
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
# ① sessions 新行(弹框字段覆盖)
|
||||
cols = [c[1] for c in con.execute("PRAGMA table_info('sessions')")]
|
||||
srow = dict(src)
|
||||
srow["id"] = new_sid
|
||||
srow["name"] = new_name
|
||||
srow["imported_at"] = now
|
||||
srow["x_batch_id"] = None # 跨库批次引用置空
|
||||
for k in ("period_from", "period_to", "province", "city", "district",
|
||||
"bulid_unit", "file_kind"):
|
||||
if k in cols and ov.get(k) not in (None, ""):
|
||||
srow[k] = ov[k]
|
||||
if "base_period_m" in cols and ov.get("period_from") is not None:
|
||||
srow["base_period_m"] = ov["period_from"]
|
||||
use = [c for c in cols if c in srow]
|
||||
con.execute("INSERT INTO sessions(%s) VALUES(%s)" % (",".join(use), ",".join("?" * len(use))),
|
||||
[_json_safe(srow[c]) for c in use])
|
||||
# ② 各数据表(id 平移+引用平移+换 sid)
|
||||
stat = {}
|
||||
for t, refs in _TABLES:
|
||||
data = rows.get(t) or []
|
||||
if not data:
|
||||
continue
|
||||
off = offsets.get(t, 0)
|
||||
tcols = [c[1] for c in con.execute("PRAGMA table_info('%s')" % t)]
|
||||
use = [c for c in tcols if c in data[0]]
|
||||
sql = "INSERT INTO %s(%s) VALUES(%s)" % (t, ",".join(use), ",".join("?" * len(use)))
|
||||
for r in data:
|
||||
vals = []
|
||||
for c in use:
|
||||
v = r.get(c)
|
||||
if c == "id":
|
||||
v = (v or 0) + off
|
||||
elif c == "session_id":
|
||||
v = new_sid
|
||||
elif c in refs and refs[c] != "@SID" and isinstance(v, int):
|
||||
v = v + offsets.get(refs[c], 0)
|
||||
vals.append(_json_safe(v))
|
||||
con.execute(sql, vals)
|
||||
stat[t] = len(data)
|
||||
return {"ok": True, "sid": new_sid, "session_id": new_sid, "name": new_name,
|
||||
"manual": bool(src.get("x_manual")), "tables": stat,
|
||||
"msg": "导入完成:%s(新会话 #%d)" % (new_name, new_sid)}
|
||||
|
||||
|
||||
def _json_safe(v):
|
||||
if isinstance(v, bool):
|
||||
return int(v)
|
||||
return v
|
||||
@@ -1,208 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""工料机骨架库(决策 197,2026-10-25 主人定):
|
||||
按「后缀+母行字段集」给 cos/cos4 原件建骨架签名组,每组只收**一个代表件**的大骨架
|
||||
(小骨架形态种类最多的单一件;平手取最新)——绝不跨件拼合(主人定:A 的骨架不加到 B)。
|
||||
小骨架 = 节点形态模板:自闭合行 / 带子级块(LabourMaterialsEquipmentsMachinesElement×n);
|
||||
形态 key = (是否自闭合, 母行字段集, 子级字段集),一个项目的骨架大小=形态种类数,与行数无关。
|
||||
命中标准(主人定):只要「后缀+字段」符合,即按此组代表骨架使用——项目级/单位级工料机
|
||||
汇总按代表大骨架备全形态槽位(不管本项目当前是否出现某形态,采纳新进数据可能落在
|
||||
任一形态中);行集合与数值仍按决策 196(本项目快照∪现算,算不出归零)——大骨架管结构,
|
||||
不管行、不供值。
|
||||
存储:永久存 history.db(lme_skel_file 件级 / lme_skel_group 组级);不随会话清理。
|
||||
v1 只报不改:体检提示本件与组代表的缺槽/缺形态差异,不自动改导出件。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
LME_TAG = 'LabourMaterialsEquipmentsMachinesSummary'
|
||||
KID_TAG = 'LabourMaterialsEquipmentsMachinesElement'
|
||||
|
||||
|
||||
def suffix_of(name):
|
||||
"""文件名 → 规范后缀 cos|cos4;其余格式(SWT/SWZ/xlsx…)返回 None——骨架库只收 cos 族。"""
|
||||
m = re.search(r'\.(cos4?)$', os.path.basename(name or ''), re.I)
|
||||
return m.group(1).lower() if m else None
|
||||
|
||||
|
||||
def _time_now():
|
||||
import time
|
||||
return time.strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
|
||||
def extract_shapes(path):
|
||||
"""解包扫 LME 块 → {sig, suffix, shapes:[形态...], n_lme}。
|
||||
形态 = {self_close, m_fields:[...], k_fields:[...], count}。
|
||||
非 zip / 无 LME 块 / 解析失败 → None(合法:空块件不入组,决策 197 实测组3)。"""
|
||||
suf = suffix_of(os.path.basename(path))
|
||||
if not suf or not os.path.exists(path):
|
||||
return None
|
||||
m_all, shapes, n = set(), {}, 0
|
||||
try:
|
||||
with zipfile.ZipFile(path) as z:
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith('.xml'):
|
||||
continue
|
||||
try:
|
||||
raw = z.read(nm)
|
||||
except Exception:
|
||||
continue
|
||||
if LME_TAG.encode() not in raw:
|
||||
continue
|
||||
try:
|
||||
root = ET.fromstring(raw)
|
||||
except Exception:
|
||||
continue
|
||||
for m in root.iter(LME_TAG):
|
||||
n += 1
|
||||
mf = set(m.attrib.keys())
|
||||
m_all |= mf
|
||||
kids = m.findall(KID_TAG)
|
||||
kf = sorted(frozenset().union(*[set(k.attrib) for k in kids])) if kids else []
|
||||
key = json.dumps([not kids, sorted(mf), kf])
|
||||
shapes[key] = shapes.get(key, 0) + 1
|
||||
except Exception:
|
||||
return None
|
||||
if n == 0:
|
||||
return None
|
||||
sig = suf + '|' + ','.join(sorted(m_all))
|
||||
return {'sig': sig, 'suffix': suf, 'n_lme': n,
|
||||
'shapes': [{'self_close': bool(json.loads(k)[0]),
|
||||
'm_fields': json.loads(k)[1],
|
||||
'k_fields': json.loads(k)[2],
|
||||
'count': v} for k, v in shapes.items()]}
|
||||
|
||||
|
||||
def ensure_tables(con):
|
||||
"""建表(IF NOT EXISTS,schema.sql 同款)+轻量补列。history.db 连接。"""
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS lme_skel_file(
|
||||
sha256 TEXT PRIMARY KEY,
|
||||
suffix TEXT,
|
||||
sig TEXT,
|
||||
shapes TEXT,
|
||||
n_lme INTEGER,
|
||||
original_name TEXT,
|
||||
extracted_at TEXT)""")
|
||||
cols = {r[1] for r in con.execute("PRAGMA table_info(lme_skel_file)")}
|
||||
if 'original_name' not in cols:
|
||||
con.execute("ALTER TABLE lme_skel_file ADD COLUMN original_name TEXT")
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS lme_skel_group(
|
||||
sig TEXT PRIMARY KEY,
|
||||
suffix TEXT,
|
||||
m_fields TEXT,
|
||||
rep_sha TEXT,
|
||||
rep_shapes TEXT,
|
||||
rep_nshapes INTEGER,
|
||||
files TEXT,
|
||||
n_files INTEGER,
|
||||
updated_at TEXT)""")
|
||||
con.commit()
|
||||
|
||||
|
||||
def extract_and_record(con, sha, path, name=None):
|
||||
"""抽取单件并写 lme_skel_file;失败/无块返回 None(不挡调用方)。⚠️ con=history.db 连接。"""
|
||||
info = extract_shapes(path)
|
||||
if info is None:
|
||||
return None
|
||||
con.execute("""INSERT INTO lme_skel_file(sha256,suffix,sig,shapes,n_lme,original_name,extracted_at)
|
||||
VALUES(?,?,?,?,?,?,?)
|
||||
ON CONFLICT(sha256) DO UPDATE SET suffix=excluded.suffix, sig=excluded.sig,
|
||||
shapes=excluded.shapes, n_lme=excluded.n_lme,
|
||||
original_name=COALESCE(excluded.original_name, lme_skel_file.original_name),
|
||||
extracted_at=excluded.extracted_at""",
|
||||
(sha, info['suffix'], info['sig'],
|
||||
json.dumps(info['shapes'], ensure_ascii=False), info['n_lme'],
|
||||
name or os.path.basename(path), _time_now()))
|
||||
con.commit()
|
||||
return info
|
||||
|
||||
|
||||
def rebuild_groups(con):
|
||||
"""从 lme_skel_file 全量重建 lme_skel_group。
|
||||
代表 = 形态种类最多的件;平手取 extracted_at 最新(主人可后续指定,当前无改代表入口)。"""
|
||||
rows = con.execute("""SELECT sha256, sig, suffix, shapes, extracted_at FROM lme_skel_file
|
||||
WHERE sig IS NOT NULL""").fetchall()
|
||||
groups = {}
|
||||
for sha, sig, suf, shapes, at in rows:
|
||||
try:
|
||||
sh = json.loads(shapes or '[]')
|
||||
except Exception:
|
||||
sh = []
|
||||
groups.setdefault(sig, []).append((sha, suf, sh, at or ''))
|
||||
for sig, files in groups.items():
|
||||
# 形态种类多者优先;平手时间新者优先
|
||||
files.sort(key=lambda t: (len(t[2]), t[3]), reverse=True)
|
||||
rep = files[0]
|
||||
con.execute("""INSERT INTO lme_skel_group(sig,suffix,m_fields,rep_sha,rep_shapes,rep_nshapes,
|
||||
files,n_files,updated_at) VALUES(?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(sig) DO UPDATE SET suffix=excluded.suffix, m_fields=excluded.m_fields,
|
||||
rep_sha=excluded.rep_sha, rep_shapes=excluded.rep_shapes,
|
||||
rep_nshapes=excluded.rep_nshapes, files=excluded.files,
|
||||
n_files=excluded.n_files, updated_at=excluded.updated_at""",
|
||||
(sig, rep[1], sig.split('|', 1)[1], rep[0],
|
||||
json.dumps(rep[2], ensure_ascii=False), len(rep[2]),
|
||||
json.dumps([f[0] for f in files]), len(files), _time_now()))
|
||||
con.commit()
|
||||
return len(groups)
|
||||
|
||||
|
||||
def backfill_attachments(con, src_dir):
|
||||
"""历史回填:扫 source_files 目录全部 cos 族件(文件名=sha_原名;无 sha 前缀的样本件按
|
||||
内容算 sha)。attachments 表只覆盖走过上传入口的件,目录直扫才收得全。
|
||||
只读原件、只写骨架两表。返回 (n_file, n_group)。"""
|
||||
ensure_tables(con)
|
||||
import hashlib
|
||||
n = 0
|
||||
seen = set()
|
||||
for fn in os.listdir(src_dir):
|
||||
suf = suffix_of(fn)
|
||||
if suf is None:
|
||||
continue
|
||||
m = re.match(r'^([0-9a-fA-F]{64})_', fn)
|
||||
if m:
|
||||
sha = m.group(1).lower()
|
||||
else:
|
||||
with open(os.path.join(src_dir, fn), 'rb') as f:
|
||||
sha = hashlib.sha256(f.read()).hexdigest()
|
||||
if sha in seen:
|
||||
continue # 同哈希同名对只抽一次
|
||||
seen.add(sha)
|
||||
pretty = fn.split('_', 1)[1] if m else fn # 剥 sha 前缀,存原名
|
||||
info = extract_and_record(con, sha, os.path.join(src_dir, fn), name=pretty)
|
||||
if info is not None:
|
||||
n += 1
|
||||
return n, rebuild_groups(con)
|
||||
|
||||
|
||||
def diff_vs_rep(shapes, rep_shapes):
|
||||
"""本件形态清单 vs 组代表差异(v1 体检只报):缺形态/多形态/缺字段/多字段。"""
|
||||
def key(sh):
|
||||
return {(bool(s['self_close']), tuple(s['m_fields']), tuple(s['k_fields'])) for s in sh or []}
|
||||
|
||||
def mfs(sh):
|
||||
out = set()
|
||||
for s in sh or []:
|
||||
out |= set(s.get('m_fields') or [])
|
||||
out |= set(s.get('k_fields') or []) # 子级槽位(如 cos4 的 Express)也算字段差异
|
||||
return out
|
||||
mine, rep = key(shapes), key(rep_shapes)
|
||||
mf, rfm = mfs(shapes), mfs(rep_shapes)
|
||||
return {'missing_shapes': [{'self_close': k[0], 'm_fields': list(k[1]),
|
||||
'k_fields': list(k[2])} for k in sorted(rep - mine)],
|
||||
'extra_shapes': [{'self_close': k[0], 'm_fields': list(k[1]),
|
||||
'k_fields': list(k[2])} for k in sorted(mine - rep)],
|
||||
'missing_fields': sorted(rfm - mf),
|
||||
'extra_fields': sorted(mf - rfm)}
|
||||
|
||||
|
||||
def hit_for_sha(con, sha):
|
||||
"""件 sha → (本件签名记录, 命中组记录) 或 (None, None)。纯 SQL,不解包。"""
|
||||
f = con.execute("SELECT sha256, suffix, sig, shapes, n_lme FROM lme_skel_file WHERE sha256=?",
|
||||
(sha,)).fetchone()
|
||||
if f is None or not f[2]:
|
||||
return None, None
|
||||
g = con.execute("""SELECT sig, suffix, m_fields, rep_sha, rep_shapes, rep_nshapes, files, n_files
|
||||
FROM lme_skel_group WHERE sig=?""", (f[2],)).fetchone()
|
||||
return f, g
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,915 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
比对引擎(M4 核心):拿会话库(本次审核)的一条 清单/工料机,去历史库找相似项。
|
||||
|
||||
规则(2026-09-28 你定的):
|
||||
1. **排除未纳入的批次**(x_enabled=0 的一律不出现)
|
||||
2. 筛选:单价类型(原「文件类型」,2026-09-29 改名,工作台改成**多选**,默认全勾=不筛)/ 建设单位 /
|
||||
地区(**树形多选**:每个节点=一个前缀约束,多节点 OR,「全国」=不筛)——默认全选=不筛。
|
||||
(信息价目录 2026-09-29 起**工作台不再筛**,后台仍保留)
|
||||
3. 期次显示**离基准最近的那个端点**
|
||||
4. 结果按「距基准先近后远」排序,同距按档位(精确>次精确>模糊)
|
||||
5. 信息价/市场价的结果行带**原文件字段**(可打开附件 PDF)
|
||||
"""
|
||||
import sqlite3, re, threading
|
||||
from itertools import permutations
|
||||
|
||||
SIM_MIN = 0.60
|
||||
# 次精确名称护栏(2026-10-10 主人定):清单次精确 = 编码+单位,而国标编码末 3 位是项目内
|
||||
# 顺序号,不同项目把不同设备编到同码同单位很常见(实例:030507008001/台 一边是高空抛物
|
||||
# 摄像枪、一边是 LED 补光灯)。名称(匹配归一后)字符 Jaccard 低于该值的次精确命中不算
|
||||
# 同一清单项,剔除。精确档哈希含名称、工料机/价格次精确 = 名称+单位,都不受影响。
|
||||
SEMI_NAME_MIN = 0.2
|
||||
|
||||
|
||||
def lme_list_where(prefix=""):
|
||||
"""「项目工料机」唯一过滤规则(2026-10-09 起唯一实现挪到本模块:工料机检索同用)。
|
||||
① 排除 Kind 6 配合比 / 7 机具台班 —— 组合类(下挂人工/燃料/折旧…),单独比价无意义;
|
||||
② 排除单位为 元 / 工日 / 台班 —— 费用科目、人工、机械台班,没有跨项目价比对价值。
|
||||
只在**取数时**过滤,导入保持全量(子目工料机面板、名称反查不受影响)。
|
||||
⚠️ Kind 两库都是 **INTEGER** 存储:SQLite 里 `整数 NOT IN ('6','7')` 恒为真(跨类型类
|
||||
不相等),必须 CAST 成文本再比 —— 此前后台 _lme_rows 的旧写法就因此漏放 Kind 6 行。
|
||||
prefix:列限定前缀。裸列名只能在「JOIN 的表里没有 Kind/Unit 同名列」的查询用;
|
||||
检索类查询 JOIN 了 batches(有 kind 列,SQLite 列名不分大小写)必须传 'l.'。"""
|
||||
p = (prefix + ".") if prefix else ""
|
||||
return ("CAST(IFNULL(%sKind,'') AS TEXT) NOT IN ('6','7') "
|
||||
"AND TRIM(IFNULL(%sUnit,'')) NOT IN ('元','工日','台班')" % (p, p))
|
||||
|
||||
|
||||
def norm(s):
|
||||
s = (s or "").strip().replace("(", "(").replace(")", ")").replace("×", "*")
|
||||
return re.sub(r"\s+", "", s).lower()
|
||||
|
||||
|
||||
# ---------- 匹配过滤词(2026-10-01 新增,可配置) ----------
|
||||
# 这些词在「与历史项目比对」时会被剥掉,不参与相似度计算(例如「拆除 / 原有 / 恢复」等噪声词)。
|
||||
# ⚠️ 用线程本地存储:ThreadingHTTPServer 每请求一个线程,避免并发请求互相污染过滤词。
|
||||
_tls = threading.local()
|
||||
|
||||
|
||||
def set_stopwords(words):
|
||||
"""设置匹配过滤词(线程本地)。words: iterable of str(空/None 即清空)。"""
|
||||
_tls.stopwords = set(w for w in (words or []) if w)
|
||||
|
||||
|
||||
def norm_match(s):
|
||||
"""匹配用的归一:在 norm 基础上剥掉过滤词(不参与相似度计算)。单位比较仍用 norm()。"""
|
||||
s2 = norm(s)
|
||||
for w in getattr(_tls, "stopwords", ()):
|
||||
if w:
|
||||
s2 = s2.replace(w, "")
|
||||
return s2
|
||||
|
||||
|
||||
def ym(m):
|
||||
"""月序号 → '2026.07'(空串按 None 处理)"""
|
||||
if m in (None, ""):
|
||||
return "—"
|
||||
m = int(m)
|
||||
return "%04d.%02d" % (m // 12, m % 12 or 12) if m % 12 else "%04d.%02d" % (m // 12 - 1, 12)
|
||||
|
||||
|
||||
def nearest(p1, p2, base):
|
||||
"""起~止里离基准最近的那个端点(空串按 None 处理,避免 int/abs 抛错)"""
|
||||
if p1 in (None, ""):
|
||||
return p2
|
||||
if p2 in (None, ""):
|
||||
return p1
|
||||
return p1 if abs(p1 - base) <= abs(p2 - base) else p2
|
||||
|
||||
|
||||
def span(base):
|
||||
"""基准期次:既可以是单月(int),也可以传 (起, 止) 区间 —— 统一成 (bf, bt)"""
|
||||
if isinstance(base, (tuple, list)):
|
||||
return (base[0], base[1] or base[0])
|
||||
return (base, base)
|
||||
|
||||
|
||||
def dist(p1, p2, bf, bt=None):
|
||||
"""离基准的距离(月):
|
||||
- 历史区间与基准区间**有重叠** → 0(工期覆盖基准,视为同期,排最前)
|
||||
- 整体早于基准 → bf - 最晚端点;整体晚于基准 → 最早端点 - bt
|
||||
"""
|
||||
if bt is None:
|
||||
bt = bf
|
||||
if p1 in (None, ""):
|
||||
p1 = None
|
||||
if p2 in (None, ""):
|
||||
p2 = None
|
||||
lo = p1 if p1 is not None else p2
|
||||
hi = p2 if p2 is not None else p1
|
||||
if lo is None:
|
||||
return 9999
|
||||
if hi < bf:
|
||||
return bf - hi
|
||||
if lo > bt:
|
||||
return lo - bt
|
||||
return 0
|
||||
|
||||
|
||||
def jaccard(a, b):
|
||||
A, B = set(a or ""), set(b or "")
|
||||
if not A or not B:
|
||||
return 0.0
|
||||
return len(A & B) / len(A | B)
|
||||
|
||||
|
||||
# ---------- 字集键 / 加权相似度(2026-10-10 决策 27 主人定) ----------
|
||||
|
||||
def set_norm(s):
|
||||
"""字集归一:归一后按字符排序——顺序无关的等价串,「钢筋混凝土」与「混凝土钢筋」同串。"""
|
||||
return "".join(sorted(norm(s)))
|
||||
|
||||
|
||||
def bill_setkey(name, unit):
|
||||
"""清单字集键(存 bills.x_setkey):名称字集 + 单位——名称不按排序等价、单位一致。"""
|
||||
return set_norm(name) + "|" + norm(unit)
|
||||
|
||||
|
||||
def lme_setkey(name, spec, unit):
|
||||
"""工料机字集键(存 lmes.x_setkey):名称+规格**合并成一个池**再排序(主人 2026-10-10 定
|
||||
「名称+规格型号作为一个整体、不按排序匹配」)+ 单位。"""
|
||||
return set_norm((name or "") + (spec or "")) + "|" + norm(unit)
|
||||
|
||||
|
||||
# 特征里的排序序号——只是排版顺序,剥掉不参与匹配(2026-10-10 主人定)。
|
||||
# ⚠️ 在 norm() 之后套用(小写、全角括号已转半角、空白已去)。「前面的字符不是字母/数字/点」
|
||||
# 负向断言保证 IP67、2.8mm、42.5 这类**正文数字**不被误剥——序号前的邻居是文字或开头。
|
||||
_ORD = re.compile(r"[①-⑳]"
|
||||
r"|([0-9]{1,3})|\([0-9]{1,3}\)"
|
||||
r"|(?<![a-z0-9.])[0-9]{1,3}、"
|
||||
r"|(?<![a-z0-9.])[0-9]{1,2}[..](?![0-9])"
|
||||
r"|(?<![a-z0-9])[a-zA-Z][、))]")
|
||||
|
||||
|
||||
def norm_attr(s):
|
||||
"""项目特征/规格的匹配归一:norm 基础上剥掉**排序序号**(1、 2. (3) a) ①——
|
||||
正文里的数字字母(IP67、2.8mm、C30)原样保留(小数点后跟数字不剥)。再剥过滤词。"""
|
||||
s2 = _ORD.sub("", norm(s))
|
||||
for w in getattr(_tls, "stopwords", ()):
|
||||
if w:
|
||||
s2 = s2.replace(w, "")
|
||||
return s2
|
||||
|
||||
|
||||
# 字母数字身份 token(含小数点/斜杠/连字符/乘号/直径符)
|
||||
_TOK = re.compile(r"[a-z0-9φ][a-z0-9φ./*\-]*")
|
||||
|
||||
|
||||
def sim_weighted(qname, hname, qattr, hattr):
|
||||
"""模糊档加权相似度(2026-10-10 决策 27 主人定):
|
||||
0.7×名称字集Jaccard + 0.3×特征字集Jaccard —— 名称优先于项目特征;
|
||||
字母数字优于文字:查询**名称**里的字母数字 token(400、C30、IP67)在候选
|
||||
(名称+特征)里找不到 → 一票否决返回 0;查询**特征**里的 token 缺失 → 特征得分减半。
|
||||
中文按字符集合(不按排序)。入参都是归一后的串。"""
|
||||
hay = hname + hattr
|
||||
if any(t not in hay for t in _TOK.findall(qname)):
|
||||
return 0.0
|
||||
# 两边都没写特征 → 特征维度按满分(不惩罚);一边有一边没有才正常算
|
||||
a = jaccard(qattr, hattr) if (qattr or hattr) else 1.0
|
||||
if any(t not in hay for t in _TOK.findall(qattr)):
|
||||
a *= 0.5
|
||||
return 0.7 * jaccard(qname, hname) + 0.3 * a
|
||||
|
||||
|
||||
def _filters(kinds, units, classes, prefix="bt", self_src=None, area=None, orgs=None, projs=None):
|
||||
"""生成批次级筛选 SQL(默认全选=不筛)
|
||||
self_src:被审工程的源文件名 —— 同一个文件若也在历史库里,排除掉(避免自己跟自己比)
|
||||
area:地区前缀列表 [(省, 市, 区/县), ...](2026-09-29 树形多选后改成这样)
|
||||
—— 一个元组就是一个前缀约束(市/区为空=该级不限),**多个元组之间是 OR**;整表空=不限。
|
||||
例:[("广东省","",""),("湖南省","长沙市","")] = 广东全省 或 湖南长沙。
|
||||
units:单价类型码(原「文件类型」,2026-09-29 改名)—— 清单比对用;工料机比对不用
|
||||
orgs:单位(2026-10-08 主人定,工料机比对专用):建设单位 ∪ 发布单位 **跨来源联查**,
|
||||
一批名字同时匹配 BulidUnit(工程批次)OR x_publisher(价格批次);
|
||||
工程批次 x_publisher 恒空、价格批次 BulidUnit 恒空,OR 起来天然各走各的。
|
||||
projs:项目名称(决策 141,2026-10-20,主人定):按批次项目名 bt.Name 精确匹配(IN),
|
||||
与 units 同款;比对/检索两条路径、清单/工料机两侧全部透传。
|
||||
"""
|
||||
w, args = ["%s.x_enabled=1" % prefix], []
|
||||
if area:
|
||||
ors, a2 = [], []
|
||||
for prov, city, dist in area:
|
||||
cond = []
|
||||
if prov:
|
||||
cond.append("%s.x_province=?" % prefix); a2.append(prov)
|
||||
if city:
|
||||
cond.append("%s.x_city=?" % prefix); a2.append(city)
|
||||
if dist:
|
||||
cond.append("%s.x_district=?" % prefix); a2.append(dist)
|
||||
if cond:
|
||||
ors.append("(" + " AND ".join(cond) + ")")
|
||||
if ors:
|
||||
w.append("(" + " OR ".join(ors) + ")")
|
||||
args += a2
|
||||
if self_src:
|
||||
w.append("(%s.x_src_hash IS NULL OR %s.x_src_hash<>?)" % (prefix, prefix))
|
||||
args.append(self_src)
|
||||
if kinds:
|
||||
w.append("%s.FileKind IN (%s)" % (prefix, ",".join("?" * len(kinds))))
|
||||
args += list(kinds)
|
||||
if units:
|
||||
w.append("%s.BulidUnit IN (%s)" % (prefix, ",".join("?" * len(units))))
|
||||
args += list(units)
|
||||
if orgs:
|
||||
w.append("(%s.BulidUnit IN (%s) OR %s.x_publisher IN (%s))"
|
||||
% (prefix, ",".join("?" * len(orgs)), prefix, ",".join("?" * len(orgs))))
|
||||
args += list(orgs) + list(orgs)
|
||||
if projs:
|
||||
w.append("%s.Name IN (%s)" % (prefix, ",".join("?" * len(projs))))
|
||||
args += list(projs)
|
||||
if classes:
|
||||
w.append("p.Class IN (%s)" % ",".join("?" * len(classes)))
|
||||
args += list(classes)
|
||||
return (" AND ".join(w), args)
|
||||
|
||||
|
||||
def _price_range(col, pmin, pmax):
|
||||
"""价格范围(2026-10-08 主人定,工料机比对专用):对除税单价的下限/上限。
|
||||
col:价格列名(l.NoTaxPrice / p.NoTaxPrice,调用方按所在 SQL 传入)。"""
|
||||
w, args = [], []
|
||||
if pmin is not None:
|
||||
w.append("%s >= ?" % col); args.append(pmin)
|
||||
if pmax is not None:
|
||||
w.append("%s <= ?" % col); args.append(pmax)
|
||||
return (" AND ".join(w) if w else "1=1", args)
|
||||
|
||||
|
||||
def _kw_fold(s):
|
||||
"""检索词归一(2026-10-08 主人报「Φ12mm 搜不出来」):小写化 + 直径符号变体统一为 φ。
|
||||
SQLite 的 LIKE/LOWER **只对 ASCII 不分大小写** —— 库里 Φ12mm(大写)与手输 φ12mm(小写)
|
||||
互搜不到;ϕ/⌀/Ø 同理。检索词与 SQL 列两边都折叠成同一个字符(见 _kw_like)后再 LIKE。"""
|
||||
s = (s or "").lower() # Python 的 lower 折叠希腊/拉丁大小写(SQLite 的不会)
|
||||
for ch in ("ϕ", "⌀", "ø"):
|
||||
s = s.replace(ch, "φ")
|
||||
return s
|
||||
|
||||
|
||||
def _kw_like(col):
|
||||
"""SQL 列侧的同款折叠表达式(与 _kw_fold 配对):REPLACE 各变体 → φ 再 LOWER。
|
||||
col:列名(可为别名,如 name / spec / b.Name)。"""
|
||||
e = col
|
||||
for a in ("Φ", "ϕ", "⌀", "Ø", "ø"):
|
||||
e = "REPLACE(%s, '%s', 'φ')" % (e, a)
|
||||
return "LOWER(%s)" % e
|
||||
|
||||
|
||||
def _kw_reqs(t):
|
||||
"""一个检索词的「要求组」拆解(2026-10-11 决策 38 分级)。
|
||||
|
||||
返回 (strict, loose):两者都是 req 组列表——组内各图案**任一**命中即算(字段之间 OR ×
|
||||
组内图案 OR),组与组之间 AND。strict 成立必然蕴含 loose 成立。
|
||||
|
||||
strict(严格档,置顶):字母数字段(C30、400、P.O)保持原样子串;
|
||||
中文 2~3 字 → **连写、不分字序**(土方=%土方%或%方土%;3 字 6 种排列);
|
||||
中文 ≥4 字 → 逐字在场(保住「混凝土钢筋」↔「钢筋混凝土」互搜,决策 27 原诉求)。
|
||||
loose(兜底档,垫底):= 决策 27 原口径——字母数字段子串 + 中文全部逐字在场。
|
||||
「混凝土钢筋 土方」输入下,只要行内全部字都在场(土在混凝土、方在方式)也算命中,
|
||||
只排到严格命中的后面(2026-10-11 主人定「用全拆字兜底,排序最后」)。"""
|
||||
segs = _TOK.findall(t)
|
||||
chars = sorted({c for c in re.sub(r"[a-z0-9φ./*\-]", "", t)})
|
||||
strict, loose = [], []
|
||||
for s in segs:
|
||||
strict.append(["%" + s + "%"])
|
||||
loose.append(["%" + s + "%"])
|
||||
if not chars:
|
||||
pass
|
||||
elif len(chars) <= 3:
|
||||
pats = sorted({"".join(p) for p in permutations(chars)}) # 连写不分序:全排列去重
|
||||
strict.append(["%" + p + "%" for p in pats])
|
||||
loose.extend(["%" + c + "%"] for c in chars)
|
||||
else:
|
||||
strict.extend(["%" + c + "%"] for c in chars) # ≥4 字:严格=兜底同款
|
||||
loose.extend(["%" + c + "%"] for c in chars)
|
||||
return strict, loose
|
||||
|
||||
|
||||
def _kw_req_sql(fields, groups, args_out):
|
||||
"""req 组列表 → SQL 布尔串:组内(字段 × 图案)OR,组间 AND。? 按出现序追加 args_out。"""
|
||||
out = []
|
||||
for g in groups:
|
||||
pats = []
|
||||
for pat in g:
|
||||
pats += ["%s LIKE ?" % _kw_like(f) for f in fields]
|
||||
args_out.extend([pat] * len(fields))
|
||||
out.append("(" + " OR ".join(pats) + ")")
|
||||
return " AND ".join(out)
|
||||
|
||||
|
||||
def _kw_conds(fields, kw, where_out, args_out):
|
||||
"""关键字检索 WHERE 条件(结果集口径):**兜底档**——每个词按「字母数字段子串 +
|
||||
中文逐字在场」圈行,与 2026-10-10 决策 27 的结果集**完全一致**(不因分级收紧)。
|
||||
严格档不进 WHERE,只进 ORDER BY 置顶(_kw_rank_expr,决策 38:全拆字兜底排序最后)。"""
|
||||
for t in (kw or "").split():
|
||||
if not t:
|
||||
continue
|
||||
t = _kw_fold(t)
|
||||
_strict, loose = _kw_reqs(t)
|
||||
if loose:
|
||||
where_out.append("(" + _kw_req_sql(fields, loose, args_out) + ")")
|
||||
|
||||
|
||||
def _kw_rank_expr(fields, kw, args_out):
|
||||
"""严格档布尔表达式(决策 38,ORDER BY 置顶用):**所有**词都按严格档命中 → 为真。
|
||||
调用方拼成 CASE WHEN <expr> THEN 0 ELSE 1 END 放排序首键——严格命中在前,
|
||||
全拆字兜底的行不排除、排到同条件行的最后。
|
||||
⚠️ 表达式的 ? 追加在 args_out 尾部:必须在 WHERE 全部参数之后、LIMIT/OFFSET 参数之前调用。
|
||||
无有效检索词 → 返回 None(排序维持原样)。"""
|
||||
groups = []
|
||||
for t in (kw or "").split():
|
||||
if not t:
|
||||
continue
|
||||
strict, _loose = _kw_reqs(_kw_fold(t))
|
||||
groups += strict
|
||||
if not groups:
|
||||
return None
|
||||
return _kw_req_sql(fields, groups, args_out)
|
||||
|
||||
|
||||
def _stop_conds(fields, stop, where_out, args_out):
|
||||
"""屏蔽词排除条件(2026-10-11 主人定):任一字段含任一屏蔽词 → 整行排除。
|
||||
与关键词不同,屏蔽词**不拆字、不做排列**——按输入词的字符顺序整词命中
|
||||
(%拆除% 只挡"拆除"连写,不挡"除…拆"散落、"除拆"倒序——2026-10-11 主人定
|
||||
「按每组出现的词及词的顺序屏蔽」)。与 _kw_conds 同一套折叠(大小写/直径符)。
|
||||
放在 WHERE 里、分页 LIMIT 之前生效——检索模式每页行数不会因屏蔽而缩水。"""
|
||||
for w in (stop or []):
|
||||
w = _kw_fold(str(w).strip())
|
||||
if not w:
|
||||
continue
|
||||
where_out.append("NOT (" + " OR ".join("%s LIKE ?" % _kw_like(f) for f in fields) + ")")
|
||||
args_out.extend(["%" + w + "%"] * len(fields))
|
||||
|
||||
|
||||
def stop_words(s):
|
||||
"""屏蔽词输入解析:空格/半角逗号/全角逗号分隔(与分组设置关键词同款分隔符)。"""
|
||||
return [t for t in re.split(r"[,,\s]+", (s or "")) if t]
|
||||
|
||||
|
||||
def _self_filter(rows, self_name, self_src):
|
||||
"""排除「被审工程自己」(2026-10-10 主人定收紧口径):只认
|
||||
① 同一份文件 —— 批次 x_src_hash 与会话源文件名完全相同(同一文件导入两边);
|
||||
② 项目名与会话名完全相同。
|
||||
原「文件名主干前 12 字」启发式删除:同项目的另一版本(.cos / .cos4、改名副本)是
|
||||
不同文件,正是最要比对的对象,不该整批隐藏(实例:SX-18 前台 cos 副本 vs 后台 cos4,
|
||||
摄像枪真命中被藏,只剩另一项目的 LED 补光灯)。"""
|
||||
nm = (self_name or "").strip()
|
||||
src = (self_src or "").strip()
|
||||
if not nm and not src:
|
||||
return rows
|
||||
out = []
|
||||
for r in rows:
|
||||
if src and (r.get("src_hash") or "").strip() == src:
|
||||
continue
|
||||
if nm and (r.get("proj") or "").strip() == nm:
|
||||
continue
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def _in_period(r, pfrom, pto):
|
||||
"""按"离基准最近的端点"判断是否落在起~止区间内"""
|
||||
if pfrom is None and pto is None:
|
||||
return True
|
||||
v = r.get("period_m")
|
||||
if v is None:
|
||||
return False
|
||||
if pfrom is not None and v < pfrom:
|
||||
return False
|
||||
if pto is not None and v > pto:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _region3(p, c, d3):
|
||||
"""省/市/区 → 「广东省/珠海市/香洲区」(空级跳过;全空=None)"""
|
||||
return "/".join(x for x in (p, c, d3) if x) or None
|
||||
|
||||
|
||||
def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfrom=None, pto=None, self_name=None, self_src=None, area=None, projs=None, pmin=None, pmax=None, att="all", unit_free=False):
|
||||
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
|
||||
"""row: sqlite Row of s_bills
|
||||
unit_free(2026-11-02 主人定,Excel 批量匹配专用):Excel 只有一列清单名称没有单位/编码 ——
|
||||
True=跳过字集档(键含单位对不齐)并放宽模糊档单位护栏,纯按名称相似度匹配;比对框不传(False)行为零变化。"""
|
||||
c = hist.cursor()
|
||||
w, args = _filters(kinds, units, [], self_src=self_src, area=area, projs=projs) # classes 只对价格库有意义,清单比对不筛目录
|
||||
# 决策 208(2026-10-26 主人定):价格范围/附件筛选清单侧同样生效(工具栏恒显最大集)——
|
||||
# 价格=b.Price(NULL 自然不落区间);附件=bill_attach 绑定的询价资料(与 api_search 回填 file 同一来源)。
|
||||
if pmin is not None:
|
||||
w += " AND b.Price>=?"; args = args + [pmin]
|
||||
if pmax is not None:
|
||||
w += " AND b.Price<=?"; args = args + [pmax]
|
||||
if att == "yes":
|
||||
w += " AND EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)"
|
||||
elif att == "no":
|
||||
w += " AND NOT EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)"
|
||||
# 决策 211(2026-10-26 主人定):历史比对默认硬过滤——单位「项」的清单与单价 0 的清单
|
||||
# 无比价意义,不搜出;空价(NULL)不算 0、保守保留(同 199 精神)。各档位共用本串。
|
||||
w += " AND COALESCE(b.Unit,'')<>'项' AND (b.Price IS NULL OR b.Price<>0)"
|
||||
out, seen_ids, qn = [], set(), norm_match(row["Name"])
|
||||
# L0 精确:编码+名称+单位(b.id 带回 → 前端展开定额 / 右栏「定额编码·名称」用)。
|
||||
# 2026-10-10 决策 27:哈希里的编码只取前 9 位(后 3 位是项目内顺序码,没有对比意义),
|
||||
# 口径变更由启动迁移 migrate_match_keys 重算存量,导入侧 import_job 同步。
|
||||
sql = """SELECT '精确' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
|
||||
bt.x_province, bt.x_city, bt.x_district
|
||||
FROM bills b JOIN batches bt ON bt.id=b.batch_id
|
||||
WHERE b.x_hash_exact=? AND bt.kind='project' AND %s LIMIT ?""" % w
|
||||
for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit]):
|
||||
d = dict(x); out.append(d); seen_ids.add(d["id"])
|
||||
# L1 次精确:编码+单位(名称护栏 = SEMI_NAME_MIN,挡同码不同物)
|
||||
if len(out) < limit:
|
||||
sql2 = sql.replace("x_hash_exact", "x_hash_semi").replace("'精确'", "'次精确'")
|
||||
seen = {(x["Name"], x["Attr"]) for x in out}
|
||||
for x in c.execute(sql2, [row["x_hash_semi"]] + args + [limit]):
|
||||
d = dict(x)
|
||||
if (d["Name"], d["Attr"]) in seen:
|
||||
continue
|
||||
if jaccard(qn, norm_match(d["Name"])) < SEMI_NAME_MIN:
|
||||
continue
|
||||
if len(out) >= limit:
|
||||
break
|
||||
out.append(d); seen.add((d["Name"], d["Attr"])); seen_ids.add(d["id"])
|
||||
# L1.5 字集精确(2026-10-10 决策 27):名称字集+单位等价——「钢筋混凝土」=「混凝土钢筋」,
|
||||
# 不按排序的严格命中;键 = bills.x_setkey(导入落列,老库启动迁移回填)。
|
||||
# unit_free(Excel 无单位)时键对不齐 → 整档跳过,交给下方模糊档纯名称相似度。
|
||||
if len(out) < limit and not unit_free:
|
||||
sqlk = """SELECT '字集' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
|
||||
bt.x_province, bt.x_city, bt.x_district
|
||||
FROM bills b JOIN batches bt ON bt.id=b.batch_id
|
||||
WHERE b.x_setkey=? AND bt.kind='project' AND %s LIMIT ?""" % w
|
||||
for x in c.execute(sqlk, [bill_setkey(row["Name"], row["Unit"])] + args + [limit]):
|
||||
d = dict(x)
|
||||
if d["id"] in seen_ids:
|
||||
continue
|
||||
if len(out) >= limit:
|
||||
break
|
||||
out.append(d); seen_ids.add(d["id"])
|
||||
# L2 模糊:加权相似度(0.7×名称 + 0.3×特征,字母数字身份规则见 sim_weighted)
|
||||
if len(out) < limit:
|
||||
q = norm_match(row["Name"])[:6]
|
||||
if q:
|
||||
sql3 = """SELECT b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
|
||||
bt.x_province, bt.x_city, bt.x_district
|
||||
FROM bills b JOIN batches bt ON bt.id=b.batch_id
|
||||
WHERE bt.kind='project' AND %s AND b.x_name_norm LIKE ? LIMIT 300""" % w
|
||||
for x in c.execute(sql3, args + ["%" + q + "%"]):
|
||||
if not unit_free and norm(x["Unit"]) != norm(row["Unit"]):
|
||||
continue
|
||||
if x["id"] in seen_ids:
|
||||
continue
|
||||
sim = sim_weighted(qn, norm_match(x["Name"]),
|
||||
norm_attr(row["Attr"]), norm_attr(x["Attr"]))
|
||||
if sim >= SIM_MIN:
|
||||
d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim
|
||||
out.append(d); seen_ids.add(x["id"])
|
||||
if len(out) >= limit:
|
||||
break
|
||||
res = []
|
||||
for d in out:
|
||||
res.append({
|
||||
"tier": d["tier"], "bill_id": d.get("id"),
|
||||
"name": d["Name"], "attr": d["Attr"], "unit": d["Unit"],
|
||||
"price": d["Price"], "proj": d["proj"], "bunit": d["BulidUnit"],
|
||||
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
|
||||
"period": ym(nearest(d["p1"], d["p2"], bf)),
|
||||
"period_m": nearest(d["p1"], d["p2"], bf),
|
||||
"dist": dist(d["p1"], d["p2"], bf, bt),
|
||||
"sim": (1.0 if d["tier"] in ("精确", "字集") else
|
||||
round(d["_sim"], 2) if "_sim" in d else
|
||||
round(jaccard(qn, norm_match(d["Name"])), 2)), # 次精确=真实名称相似度(决策 27 E)
|
||||
"src": "工程", "file": "", "src_hash": d.get("src") or "",
|
||||
})
|
||||
res = [r for r in res if _in_period(r, pfrom, pto)]
|
||||
res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目)
|
||||
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]]))
|
||||
return res[:limit]
|
||||
|
||||
|
||||
def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=None, self_src=None, page=1, stop=None, projs=None, pmin=None, pmax=None, att="all"):
|
||||
"""独立检索(2026-10-08 主人定第 4 轮 B 方案):跨**全部入库项目**(kind='project')按
|
||||
条件+关键词 直查清单库,与工作台选中的行无关(主人:"搜索条件高于点选清单")。
|
||||
行结构与 match_bill() 完全一致 —— 前端 renderHist / 右栏 / ± 展开零改动复用,差异只有:
|
||||
· tier 固定 "检索"(前端走蓝徽章),sim=None(相似度列显示 —);
|
||||
· dist=0、排序由本函数做好(期次先近后远),前端不再按 dist 重排。
|
||||
期次条件=区间重叠语义:批次的 [起,止] 与所选 [起,止] 有交集即命中(检索没有"基准期")。
|
||||
self_name/self_src:被审工程自己(若它也入库了)**排除**(2026-10-08 主人定),
|
||||
判定与 match_bill/match_lme 同一套(_self_filter 口径):同一份文件(x_src_hash 相同)
|
||||
或项目名相同。
|
||||
page:分页(2026-10-08 主人定,每页=limit 条,第 N 页 OFFSET (N-1)×limit)。
|
||||
pmin/pmax/att:决策 208(2026-10-26 主人定)清单侧同生效——价格=b.Price,附件=bill_attach。"""
|
||||
c = hist.cursor()
|
||||
cond, args = _filters(kinds, units, [], prefix="bt", projs=projs) # 批次级条件(拼好的 SQL 串 + 参数)
|
||||
extra = []
|
||||
if pmin is not None:
|
||||
extra.append("b.Price>=?"); args = args + [pmin]
|
||||
if pmax is not None:
|
||||
extra.append("b.Price<=?"); args = args + [pmax]
|
||||
if att == "yes":
|
||||
extra.append("EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)")
|
||||
elif att == "no":
|
||||
extra.append("NOT EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)")
|
||||
# 决策 211(2026-10-26 主人定):检索模式同款默认硬过滤——单位「项」与单价 0 的清单不搜出
|
||||
extra.append("COALESCE(b.Unit,'')<>'项'")
|
||||
extra.append("(b.Price IS NULL OR b.Price<>0)")
|
||||
nm = (self_name or "").strip()
|
||||
src = (self_src or "").strip()
|
||||
if src or nm:
|
||||
self_ids = [r[0] for r in c.execute(
|
||||
"SELECT id, Name, x_src_hash FROM batches WHERE kind='project'").fetchall()
|
||||
if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)]
|
||||
if self_ids:
|
||||
extra.append("bt.id NOT IN (%s)" % ",".join("?" * len(self_ids)))
|
||||
args = args + self_ids
|
||||
_kw_conds(["b.Name", "b.Attr", "b.Unit"], kw, extra, args) # WHERE=兜底档:结果集与决策 27 一致(决策 38)
|
||||
_stop_conds(["b.Name", "b.Attr", "b.Unit"], stop, extra, args) # 屏蔽词(2026-10-11):命中即整行排除
|
||||
if pfrom is not None:
|
||||
extra.append("bt.x_period_end_m >= ?")
|
||||
args = args + [pfrom]
|
||||
if pto is not None:
|
||||
extra.append("bt.x_period_start_m <= ?")
|
||||
args = args + [pto]
|
||||
# 决策 38:严格档置顶 + 兜底打标——kwrank 同时是排序首键和行的 loose 标记来源。
|
||||
# ⚠️ rank 的 ? 出现在 SELECT 列里(SQL 文本最前),绑定序 = rank_args 在 WHERE 参数之前。
|
||||
rank_args = []
|
||||
rank = _kw_rank_expr(["b.Name", "b.Attr", "b.Unit"], kw, rank_args)
|
||||
rank_col = ("CASE WHEN %s THEN 0 ELSE 1 END kwrank" % rank) if rank else "0 AS kwrank"
|
||||
order = ("kwrank, " if rank else "") + "bt.x_period_end_m DESC, bt.id DESC"
|
||||
sql = """SELECT b.id, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2, %s
|
||||
FROM bills b JOIN batches bt ON bt.id=b.batch_id
|
||||
WHERE %s
|
||||
ORDER BY %s LIMIT ? OFFSET ?""" % (rank_col, " AND ".join([cond] + extra), order)
|
||||
args.append(int(limit))
|
||||
args.append((max(int(page), 1) - 1) * int(limit))
|
||||
res = []
|
||||
for x in c.execute(sql, rank_args + args):
|
||||
p1, p2 = x["p1"], x["p2"]
|
||||
if p1 in (None, "") and p2 in (None, ""):
|
||||
period = "—"
|
||||
elif p2 in (None, "") or p1 == p2:
|
||||
period = ym(p1)
|
||||
elif p1 in (None, ""):
|
||||
period = ym(p2)
|
||||
else:
|
||||
period = ym(p1) + "~" + ym(p2)
|
||||
res.append({
|
||||
"tier": "检索", "bill_id": x["id"],
|
||||
"loose": bool(x["kwrank"]), # 决策 38:1=全拆字兜底命中(前端灰徽标「兜底」)
|
||||
"name": x["Name"], "attr": x["Attr"], "unit": x["Unit"], "price": x["Price"],
|
||||
"proj": x["proj"], "bunit": x["bunit"], "period": period,
|
||||
"fkind": x["FileKind"], "region": _region3(x["x_province"], x["x_city"], x["x_district"]),
|
||||
"period_m": p2 if p2 not in (None, "") else p1,
|
||||
"dist": 0, "sim": None, "src": "工程", "file": "", "src_hash": "",
|
||||
})
|
||||
return res
|
||||
|
||||
|
||||
def hist_search_lme(hist, orgs=None, area=None, pfrom=None, pto=None, kw="", pmin=None, pmax=None,
|
||||
srcs=None, limit=200, self_name=None, self_src=None, page=1, att="all", kinds=None,
|
||||
stop=None, projs=None):
|
||||
"""独立检索 · 工料机版(2026-10-08 主人定):跨全部入库项目的**工料机**(lmes, kind='project')
|
||||
+ 信息价/市场价明细(prices),条件+关键词直查,与工作台选中的行无关。
|
||||
工料机标签的关键字查询走这里(hist_search 查的是清单库,工料机标签不适用)。
|
||||
行结构与 hist_search() 一致(前端 renderHist / 分页 / 右栏零改动复用),差异:
|
||||
· 多 spec 字段(规格型号,前端名称列灰字);
|
||||
· src = 工程/信息价/市场价(前端来源徽章三色);
|
||||
· bunit = 建设单位**或**发布单位(单位筛选 orgs 跨来源联查,见 _filters);
|
||||
· 价格范围 pmin/pmax 对除税单价(子查询统一列名 price 后在外层过滤)。
|
||||
期次=区间重叠语义;排序=期次先近后远(服务端排好,前端不再按 dist 重排);page 分页同 hist_search。
|
||||
被审工程自己(若入库)与它挂的信息价/市场价一并排除(与 match_lme 同一套判定)。"""
|
||||
c = hist.cursor()
|
||||
srcs = srcs or ["project", "info", "market"]
|
||||
# kinds=单价类型,只对工程来源生效(价格批次 FileKind 恒空,一传就整片剔除)
|
||||
# → 工程/价格两个分支各拼各的 cond,cargs 分别跟各自的分支参数走
|
||||
cond, cargs = _filters(kinds or [], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs, projs=projs)
|
||||
condp, cargsp = _filters([], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs, projs=projs)
|
||||
outer, oargs = [], []
|
||||
nm = (self_name or "").strip()
|
||||
src = (self_src or "").strip()
|
||||
if src or nm:
|
||||
self_ids = [r[0] for r in c.execute(
|
||||
"SELECT id, Name, x_src_hash FROM batches").fetchall()
|
||||
if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)]
|
||||
if self_ids:
|
||||
outer.append("batch_id NOT IN (%s)" % ",".join("?" * len(self_ids)))
|
||||
oargs += self_ids
|
||||
_kw_conds(["name", "spec", "unit"], kw, outer, oargs) # 不按排序(决策 27)
|
||||
_stop_conds(["name", "spec", "unit"], stop, outer, oargs) # 屏蔽词(2026-10-11):命中即整行排除
|
||||
# 决策 211(2026-10-26 主人定):检索模式工料机 0 价不搜出(别名 price=NoTaxPrice,
|
||||
# 工程/信息价/市场价三支同滤;NULL 保留)
|
||||
outer.append("(price IS NULL OR price<>0)")
|
||||
if pfrom is not None:
|
||||
outer.append("p2 >= ?"); oargs.append(pfrom)
|
||||
if pto is not None:
|
||||
outer.append("p1 <= ?"); oargs.append(pto)
|
||||
wpr, apr = _price_range("price", pmin, pmax)
|
||||
outer.append(wpr); oargs += apr
|
||||
# 附件筛选(2026-10-08 主人定):有/无 —— 子查询统一列名 file(询价资料名或刊物原件名)
|
||||
if att == "yes":
|
||||
outer.append("file <> ''")
|
||||
elif att == "no":
|
||||
outer.append("file = ''")
|
||||
|
||||
# 决策 38:严格档置顶 + 兜底打标(同 hist_search)——kwrank 进 SELECT 列兼作排序键。
|
||||
# ⚠️ rank 的 ? 出现在 SELECT 列里,绑定序 = rank_args 在 bargs+oargs 之前。
|
||||
rank_args = []
|
||||
rank = _kw_rank_expr(["name", "spec", "unit"], kw, rank_args)
|
||||
rank_col = ("CASE WHEN %s THEN 0 ELSE 1 END kwrank" % rank) if rank else "0 AS kwrank"
|
||||
order = ("kwrank, " if rank else "") + "p2 DESC, p1 DESC, batch_id"
|
||||
branches, bargs = [], []
|
||||
if "project" in srcs:
|
||||
# 工程行附件 = 该工料机绑定的询价资料(lme_attach 一对一)
|
||||
# ⚠️ 同用「项目工料机」过滤(2026-10-09 主人报:搜索能搜出已被屏蔽的单位如台班)——
|
||||
# 列表口径屏蔽的行,检索口径同样不给;JOIN 了 batches(有 kind 列)必须带 l. 前缀。
|
||||
branches.append("""SELECT 'project' src_kind, l.Name name, l.Specification spec, l.Unit unit,
|
||||
l.NoTaxPrice price, l.TaxRate tax, l.TaxPrice price_tax,
|
||||
'' note,
|
||||
bt.Name proj, bt.BulidUnit org, l.batch_id batch_id,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
COALESCE(f.original_name,'') file, CAST(f.id AS TEXT) file_sha
|
||||
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
|
||||
LEFT JOIN lme_attach la ON la.lme_id=l.id
|
||||
LEFT JOIN inquiry_files f ON f.id=la.file_id
|
||||
WHERE bt.kind='project' AND %s AND %s""" % (cond, lme_list_where("l")))
|
||||
bargs += cargs
|
||||
pk = [s for s in ("info", "market") if s in srcs]
|
||||
if pk:
|
||||
branches.append("""SELECT bt.kind src_kind, p.Name name, p.Specification spec, p.Unit unit,
|
||||
p.NoTaxPrice price, p.TaxRate tax, p.TaxPrice price_tax,
|
||||
COALESCE(p.Note,'') note,
|
||||
bt.Name proj, bt.x_publisher org, p.batch_id batch_id,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
a.original_name file, a.sha256 file_sha
|
||||
FROM prices p JOIN batches bt ON bt.id=p.batch_id
|
||||
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
|
||||
WHERE bt.kind IN (%s) AND %s"""
|
||||
% (",".join("'%s'" % k for k in pk), condp))
|
||||
bargs += cargsp
|
||||
if not branches:
|
||||
return []
|
||||
sql = ("SELECT *, %s FROM (%s) WHERE %s ORDER BY %s LIMIT ? OFFSET ?"
|
||||
% (rank_col, " UNION ALL ".join(branches), " AND ".join(outer) or "1=1", order))
|
||||
rows = c.execute(sql, rank_args + bargs + oargs + [int(limit), (max(int(page), 1) - 1) * int(limit)])
|
||||
res = []
|
||||
for x in rows:
|
||||
p1, p2 = x["p1"], x["p2"]
|
||||
if p1 in (None, "") and p2 in (None, ""):
|
||||
period = "—"
|
||||
elif p2 in (None, "") or p1 == p2:
|
||||
period = ym(p1)
|
||||
elif p1 in (None, ""):
|
||||
period = ym(p2)
|
||||
else:
|
||||
period = ym(p1) + "~" + ym(p2)
|
||||
res.append({
|
||||
"tier": "检索",
|
||||
"loose": bool(x["kwrank"]), # 决策 38:1=全拆字兜底命中(前端灰徽标「兜底」)
|
||||
"name": x["name"], "spec": x["spec"], "attr": x["spec"],
|
||||
"unit": x["unit"], "price": x["price"], "tax": x["tax"], "price_tax": x["price_tax"],
|
||||
"proj": x["proj"], "bunit": x["org"], "period": period,
|
||||
"fkind": None, "region": _region3(x["x_province"], x["x_city"], x["x_district"]),
|
||||
"period_m": p2 if p2 not in (None, "") else p1,
|
||||
"dist": 0, "sim": None,
|
||||
"src": {"project": "工程", "info": "信息价", "market": "市场价"}[x["src_kind"]],
|
||||
"note": x["note"],
|
||||
"file": x["file"] or "", "file_sha": x["file_sha"] or "",
|
||||
"file_url": (("/api/admin/inq/file/%s" % x["file_sha"]) if x["src_kind"] == "project"
|
||||
else (("/api/admin/file/%s" % x["file_sha"]) if x["file_sha"] else "")),
|
||||
"src_hash": "",
|
||||
})
|
||||
return res
|
||||
|
||||
|
||||
def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=None, self_name=None, self_src=None, area=None, pmin=None, pmax=None, att="all", kinds=None, projs=None):
|
||||
"""工料机:历史工程工料机 + 信息价/市场价(价格库)
|
||||
2026-10-08 主人定:比对按「名称+规格型号+单位」三件套;筛选 = 来源/单价类型/单位/地区/期次/价格范围/附件。
|
||||
orgs = 单位跨来源联查(建设单位 OR 发布单位,见 _filters);pmin/pmax = 价格范围(除税单价);
|
||||
att = 附件 有/无(全部=不筛);kinds = 单价类型——**只对工程来源生效**(价格批次 FileKind 恒空,
|
||||
一传就整片剔除,故价格查询一律不传)。
|
||||
档位:精确 = md5(名称+规格+单位);次精确 = md5(名称+单位)(规格不同的同名可比价);
|
||||
模糊 = 名称前6字候选 + Jaccard≥SIM_MIN + 单位一致。
|
||||
工程行附件 = 该工料机绑定的询价资料(lme_attach);价格行附件 = 刊物上传原件。"""
|
||||
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
|
||||
srcs = srcs or ["project", "info", "market"]
|
||||
c = hist.cursor()
|
||||
out, seen_ids = [], set()
|
||||
# ---- 历史工程工料机 ----
|
||||
w, args = _filters(kinds or [], [], [], self_src=self_src, area=area, orgs=orgs, projs=projs)
|
||||
wpr, apr = _price_range("l.NoTaxPrice", pmin, pmax)
|
||||
w = w + " AND " + wpr; args = args + apr
|
||||
# 决策 211(2026-10-26 主人定):除税价 0 的历史工料机不搜出(空价 NULL 保留)
|
||||
w = w + " AND (l.NoTaxPrice IS NULL OR l.NoTaxPrice<>0)"
|
||||
res = []
|
||||
if "project" in srcs:
|
||||
# 工程分支三档同用「项目工料机」过滤(2026-10-09 主人拍板:配合比行(Kind 6, m3)曾
|
||||
# 经模糊档漏出 —— 列表/检索/比对三处同一口径)。JOIN 了 batches(有 kind 列)必须
|
||||
# 带 l. 前缀,见 lme_list_where 的说明。
|
||||
# ⚠️ **信息价/市场价分支永远不过滤任何单位/类别**(主人 2026-10-09 明示"永远不能
|
||||
# 屏蔽信息价/市场价的任何单位")—— 别把 lme_list_where 加到下面价格查询上。
|
||||
sql = """SELECT '精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
|
||||
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
f.id fid, f.original_name fname
|
||||
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
|
||||
LEFT JOIN lme_attach la ON la.lme_id=l.id
|
||||
LEFT JOIN inquiry_files f ON f.id=la.file_id
|
||||
WHERE l.x_hash_exact=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
|
||||
for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit]):
|
||||
d = dict(x); out.append(d); seen_ids.add(d["id"])
|
||||
if len(out) < limit:
|
||||
# 次精确:名称+单位一致、规格不同(2026-10-08 主人定)——同名材料不同规格正是常比对象
|
||||
seen_semi = {(x["Name"], x["Specification"]) for x in out}
|
||||
sql2 = """SELECT '次精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
|
||||
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
f.id fid, f.original_name fname
|
||||
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
|
||||
LEFT JOIN lme_attach la ON la.lme_id=l.id
|
||||
LEFT JOIN inquiry_files f ON f.id=la.file_id
|
||||
WHERE l.x_hash_semi=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
|
||||
for x in c.execute(sql2, [row["x_hash_semi"]] + args + [limit]):
|
||||
d = dict(x)
|
||||
if (d["Name"], d["Specification"]) in seen_semi:
|
||||
continue
|
||||
if len(out) >= limit:
|
||||
break
|
||||
out.append(d); seen_semi.add((d["Name"], d["Specification"])); seen_ids.add(d["id"])
|
||||
# 字集精确(2026-10-10 决策 27):名称+规格**合并字集**+单位等价——「P.O 42.5 水泥」
|
||||
# =「水泥 42.5 P.O」这类不按排序的整体命中;键 = lmes.x_setkey(导入落列,老库迁移回填)。
|
||||
if len(out) < limit:
|
||||
sqlk = """SELECT '字集' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
|
||||
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
f.id fid, f.original_name fname
|
||||
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
|
||||
LEFT JOIN lme_attach la ON la.lme_id=l.id
|
||||
LEFT JOIN inquiry_files f ON f.id=la.file_id
|
||||
WHERE l.x_setkey=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
|
||||
for x in c.execute(sqlk, [lme_setkey(row["Name"], row["Specification"], row["Unit"])] + args + [limit]):
|
||||
d = dict(x)
|
||||
if d["id"] in seen_ids:
|
||||
continue
|
||||
if len(out) >= limit:
|
||||
break
|
||||
out.append(d); seen_ids.add(d["id"])
|
||||
if len(out) < limit:
|
||||
q = norm_match(row["Name"])[:6]
|
||||
if q:
|
||||
sql3 = """SELECT l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
|
||||
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
f.id fid, f.original_name fname
|
||||
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
|
||||
LEFT JOIN lme_attach la ON la.lme_id=l.id
|
||||
LEFT JOIN inquiry_files f ON f.id=la.file_id
|
||||
WHERE bt.kind='project' AND %s AND %s AND l.x_name_norm LIKE ? LIMIT 300""" % (w, lme_list_where("l"))
|
||||
for x in c.execute(sql3, args + ["%" + q + "%"]):
|
||||
if norm(x["Unit"]) != norm(row["Unit"]):
|
||||
continue
|
||||
if x["id"] in seen_ids:
|
||||
continue
|
||||
sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]),
|
||||
norm_attr(row["Specification"]), norm_attr(x["Specification"]))
|
||||
if sim >= SIM_MIN:
|
||||
d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim
|
||||
out.append(d); seen_ids.add(x["id"])
|
||||
if len(out) >= limit:
|
||||
break
|
||||
for d in out:
|
||||
res.append({
|
||||
"tier": d["tier"], "name": d["Name"], "attr": d["Specification"], "unit": d["Unit"],
|
||||
"price": d["NoTaxPrice"], "tax": d["TaxRate"], "price_tax": d["TaxPrice"],
|
||||
"proj": d["proj"], "bunit": d["bunit"], "period": ym(nearest(d["p1"], d["p2"], bf)),
|
||||
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
|
||||
"period_m": nearest(d["p1"], d["p2"], bf),
|
||||
"dist": dist(d["p1"], d["p2"], bf, bt),
|
||||
"sim": (1.0 if d["tier"] in ("精确", "字集") else
|
||||
round(d["_sim"], 2) if "_sim" in d else
|
||||
round(jaccard(norm_match(row["Name"]), norm_match(d["Name"])), 2)),
|
||||
"src": "工程", "file": d.get("fname") or "",
|
||||
"file_url": ("/api/admin/inq/file/%d" % d["fid"]) if d.get("fid") else "",
|
||||
})
|
||||
# ---- 信息价 / 市场价 ----
|
||||
pk = [s for s in ("info", "market") if s in srcs]
|
||||
# 价格批次没有「单价类型/建设单位」(FileKind/BulidUnit 恒 NULL),kinds/units 一律不传;
|
||||
# 单位筛选走 orgs(发布单位),价格范围同样对 p.NoTaxPrice 生效。
|
||||
# ⚠️ **这里永远不加 lme_list_where**(主人 2026-10-09 明示"永远不能屏蔽信息价/市场价的
|
||||
# 任何单位")—— 刊物里的台班单价等是正常价格行;搜索对象=项目工料机(过滤后)+价格全量。
|
||||
wp, argp = _filters([], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs, projs=projs)
|
||||
wpp, app = _price_range("p.NoTaxPrice", pmin, pmax)
|
||||
wp = wp + " AND " + wpp; argp = argp + app
|
||||
# 决策 211(2026-10-26 主人定):信息价/市场价 0 价条目同样不搜出(0 价无比价意义)——
|
||||
# 这与 2026-10-09「不能屏蔽价格库任何单位」不冲突:本条滤的是**价格 0**(数据质量),不动单位/类别。
|
||||
wp = wp + " AND (p.NoTaxPrice IS NULL OR p.NoTaxPrice<>0)"
|
||||
if pk:
|
||||
sqlp = """SELECT p.Name, p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Note note,
|
||||
bt.Name proj, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
bt.kind kind, a.original_name att, a.sha256 attsha
|
||||
FROM prices p JOIN batches bt ON bt.id=p.batch_id
|
||||
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
|
||||
WHERE p.x_hash_exact=? AND bt.kind IN (%s) AND %%s LIMIT ?""" % ",".join("'%s'" % k for k in pk) % wp
|
||||
seen_p = set()
|
||||
for x in c.execute(sqlp, [row["x_hash_exact"]] + argp + [limit]):
|
||||
d = dict(x)
|
||||
seen_p.add((d["Name"], d["Specification"], d["Unit"]))
|
||||
res.append({
|
||||
"tier": "精确", "name": d["Name"], "attr": d["Specification"], "unit": d["Unit"],
|
||||
"price": d["NoTaxPrice"], "tax": d["TaxRate"], "price_tax": d["TaxPrice"],
|
||||
"proj": d["proj"], "period": ym(nearest(d["p1"], d["p2"], bf)),
|
||||
"period_m": nearest(d["p1"], d["p2"], bf),
|
||||
"dist": dist(d["p1"], d["p2"], bf, bt),
|
||||
"sim": 1.0,
|
||||
"src": "信息价" if d["kind"] == "info" else "市场价",
|
||||
"note": d["note"],
|
||||
"file": d["att"] or "", "file_sha": d["attsha"] or "",
|
||||
"file_url": ("/api/admin/file/%s" % d["attsha"]) if d["attsha"] else "",
|
||||
"src_hash": d.get("src") or "",
|
||||
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
|
||||
})
|
||||
# 次精确档:名称+单位一致、规格不同(2026-10-08,与工程工料机同口径)
|
||||
if len(res) < limit:
|
||||
sqlps = """SELECT p.Name, p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Note note,
|
||||
bt.Name proj, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
bt.kind kind, a.original_name att, a.sha256 attsha
|
||||
FROM prices p JOIN batches bt ON bt.id=p.batch_id
|
||||
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
|
||||
WHERE p.x_hash_semi=? AND bt.kind IN (%s) AND %%s LIMIT ?""" % ",".join("'%s'" % k for k in pk) % wp
|
||||
for x in c.execute(sqlps, [row["x_hash_semi"]] + argp + [limit]):
|
||||
d = dict(x)
|
||||
key = (d["Name"], d["Specification"], d["Unit"])
|
||||
if key in seen_p:
|
||||
continue
|
||||
seen_p.add(key)
|
||||
res.append({
|
||||
"tier": "次精确", "name": d["Name"], "attr": d["Specification"], "unit": d["Unit"],
|
||||
"price": d["NoTaxPrice"], "tax": d["TaxRate"], "price_tax": d["TaxPrice"],
|
||||
"proj": d["proj"], "period": ym(nearest(d["p1"], d["p2"], bf)),
|
||||
"period_m": nearest(d["p1"], d["p2"], bf),
|
||||
"dist": dist(d["p1"], d["p2"], bf, bt),
|
||||
"sim": 1.0,
|
||||
"src": "信息价" if d["kind"] == "info" else "市场价",
|
||||
"note": d["note"],
|
||||
"file": d["att"] or "", "file_sha": d["attsha"] or "",
|
||||
"file_url": ("/api/admin/file/%s" % d["attsha"]) if d["attsha"] else "",
|
||||
"src_hash": d.get("src") or "",
|
||||
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
|
||||
})
|
||||
# 模糊档:名称前 6 字捞候选 → 相似度 ≥0.60 且单位一致(信息价/市场价此前只走精确,几乎命中不了)
|
||||
q = norm_match(row["Name"])[:6]
|
||||
if q:
|
||||
sqlf = """SELECT p.Name, p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Note note,
|
||||
bt.Name proj, bt.FileKind,
|
||||
bt.x_province, bt.x_city, bt.x_district,
|
||||
bt.x_period_start_m p1, bt.x_period_end_m p2,
|
||||
bt.kind kind, a.original_name att, a.sha256 attsha
|
||||
FROM prices p JOIN batches bt ON bt.id=p.batch_id
|
||||
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
|
||||
WHERE bt.kind IN (%s) AND %%s AND p.x_name_norm LIKE ? LIMIT 300""" % ",".join("'%s'" % k for k in pk) % wp
|
||||
for x in c.execute(sqlf, argp + ["%" + q + "%"]):
|
||||
if norm(x["Unit"]) != norm(row["Unit"]):
|
||||
continue
|
||||
key = (x["Name"], x["Specification"], x["Unit"])
|
||||
if key in seen_p:
|
||||
continue
|
||||
sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]),
|
||||
norm_attr(row["Specification"]), norm_attr(x["Specification"]))
|
||||
if sim < SIM_MIN:
|
||||
continue
|
||||
seen_p.add(key)
|
||||
res.append({
|
||||
"tier": "模糊", "name": x["Name"], "attr": x["Specification"], "unit": x["Unit"],
|
||||
"price": x["NoTaxPrice"], "tax": x["TaxRate"], "price_tax": x["TaxPrice"],
|
||||
"proj": x["proj"], "period": ym(nearest(x["p1"], x["p2"], bf)),
|
||||
"period_m": nearest(x["p1"], x["p2"], bf),
|
||||
"dist": dist(x["p1"], x["p2"], bf, bt),
|
||||
"sim": round(sim, 2),
|
||||
"src": "信息价" if x["kind"] == "info" else "市场价",
|
||||
"note": x["note"],
|
||||
"file": x["att"] or "", "file_sha": x["attsha"] or "",
|
||||
"file_url": ("/api/admin/file/%s" % x["attsha"]) if x["attsha"] else "",
|
||||
"src_hash": x["src"] or "",
|
||||
"fkind": x["FileKind"], "region": _region3(x["x_province"], x["x_city"], x["x_district"]),
|
||||
})
|
||||
if len(res) >= limit:
|
||||
break
|
||||
res = [r for r in res if _in_period(r, pfrom, pto)]
|
||||
# 附件筛选(2026-10-08 主人定):有=只留带附件的;无=只留没附件的;全部=不筛
|
||||
if att == "yes":
|
||||
res = [r for r in res if r.get("file")]
|
||||
elif att == "no":
|
||||
res = [r for r in res if not r.get("file")]
|
||||
res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目)
|
||||
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]]))
|
||||
return res[:limit]
|
||||
@@ -1,88 +0,0 @@
|
||||
# -*- 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 []),
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
信息价 / 市场价 HTML 解析器
|
||||
文件形态:带脚本的 HTML,数据藏在 `const DATA = [...]` 里
|
||||
结构:DATA = [ {name, columns, sections:[{title, subsections, rows:[...]}]}, ... ]
|
||||
每个顶层对象 = 一个「块」(如 建材综合价 / 园林苗木 / 横琴 / 万山)
|
||||
行字段(8 列):材料编码 / 材料名称 / 规格型号 / 单位 / 不含税单价 / 税率 / 含税单价 / 备注
|
||||
|
||||
**两个口径(2026-09-28 你定的)**:
|
||||
1. 目录(Class)= 分类标题,**原封不动**,含序号("一、黑色及有色金属")。不剥"一、"。
|
||||
2. **一个块 = 一个批次**(2026-10-06 改,原来是「一个文件 = 一个批次」)。
|
||||
一个 HTML 常含多个市场(建材 / 苗木 / 横琴 / 万山),期次各不相同;
|
||||
挤进一个批次 → 批次只能有一个期次 → 只能留空 → ym2str('') 抛错 → 信息价列表整页 500。
|
||||
拆块之后每个批次有自己的期次(块名里认得出就用块自己的,认不出才用导入弹框填的)。
|
||||
"""
|
||||
|
||||
import io, os, re, json
|
||||
|
||||
# 解析器版本(与 import_job.PARSER_VER 同机制,见那里的说明):改了入库口径才升号
|
||||
# ⚠️ 2026-10-12 价格重设计:只收标准模板 Excel(HTML 导入退役),与 price_xlsx.PARSER_VER 同步升号
|
||||
PARSER_VER = "2026.10.12-1"
|
||||
|
||||
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
|
||||
_PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核
|
||||
|
||||
|
||||
def _num(v):
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip().replace(",", "")
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return float(s)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def clean_title(t):
|
||||
"""分类标题:**原封不动**(你 2026-09-28 定:'一、黑色及有色金属' 就存 '一、黑色及有色金属')。
|
||||
只做去首尾空白,不剥序号、不改一个字——目录要跟 HTML 原件对得上。"""
|
||||
return (t or "").strip()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 期次识别(2026-10-06)
|
||||
# ---------------------------------------------------------------------------
|
||||
# 一个价格文件里往往装着**好几个市场**,而且期次各不相同:
|
||||
# 珠海市建材设备市场综合价 → 2026年7月 → 24319
|
||||
# 珠海市2026年4-6月园林苗木市场信息 → 2026年4~6月 → 24316~24318
|
||||
# 以前「一个文件 = 一个批次」,批次只能有一个期次,于是只能填空串 —— 这就是
|
||||
# DB-1(ym2str('') 抛 ValueError → 信息价列表整页 500)的根因。
|
||||
# 现在一个块 = 一个批次,块名里能认出期次就用块自己的,认不出才回退到导入弹框填的值。
|
||||
_M_RANGE = re.compile(r"(20\d{2})\s*年\s*(\d{1,2})\s*[~\-—-~至到]\s*(\d{1,2})\s*月")
|
||||
# 跨年:2026年11月~2027年1月(两段各带年份)
|
||||
_M_RANGE_Y = re.compile(r"(20\d{2})\s*年\s*(\d{1,2})\s*月\s*[~\-—-~至到]\s*(20\d{2})\s*年\s*(\d{1,2})\s*月")
|
||||
_M_ONE = re.compile(r"(20\d{2})\s*年\s*(\d{1,2})\s*月")
|
||||
|
||||
|
||||
def guess_period(text):
|
||||
"""从块名 / sheet 名 / 文件名里认期次。
|
||||
|
||||
返回 (start_m, end_m),单位是「月序号」= 年*12+月(与 batches.x_period_*_m 同口径)。
|
||||
认不出返回 (None, None) —— 调用方再依次回退到「文件名里认的」和「导入弹框填的」。
|
||||
"""
|
||||
s = str(text or "")
|
||||
m = _M_RANGE_Y.search(s)
|
||||
if m:
|
||||
y1, m1, y2, m2 = (int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))
|
||||
if 1 <= m1 <= 12 and 1 <= m2 <= 12:
|
||||
a, b = y1 * 12 + m1, y2 * 12 + m2
|
||||
return (min(a, b), max(a, b))
|
||||
m = _M_RANGE.search(s)
|
||||
if m:
|
||||
y, a, b = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
if 1 <= a <= 12 and 1 <= b <= 12:
|
||||
lo, hi = min(a, b), max(a, b)
|
||||
return (y * 12 + lo, y * 12 + hi)
|
||||
m = _M_ONE.search(s)
|
||||
if m:
|
||||
y, a = int(m.group(1)), int(m.group(2))
|
||||
if 1 <= a <= 12:
|
||||
v = y * 12 + a
|
||||
return (v, v)
|
||||
return (None, None)
|
||||
|
||||
|
||||
def parse(path):
|
||||
"""返回 [{block, columns, n_sections, rows:[(sec_title, [8列])]}]"""
|
||||
raw = io.open(path, encoding="utf-8", errors="replace").read()
|
||||
key = "const DATA"
|
||||
if key not in raw:
|
||||
raise ValueError("这个文件里没有 DATA 数据块,不是信息价/市场价 HTML")
|
||||
j = raw[raw.index(key) + len(key):].lstrip()
|
||||
j = j[j.index("=") + 1:]
|
||||
data, _ = json.JSONDecoder().raw_decode(j.lstrip())
|
||||
out = []
|
||||
for blk in data:
|
||||
rows = []
|
||||
for sec in blk.get("sections", []):
|
||||
title = clean_title(sec.get("title", ""))
|
||||
for r in sec.get("rows", []):
|
||||
if len(r) < 8:
|
||||
r = list(r) + [""] * (8 - len(r))
|
||||
rows.append((title, r[:8]))
|
||||
nm = blk.get("name", "") or ""
|
||||
ps, pe = guess_period(nm) # 2026-10-06:块自带期次,供「一个块 = 一个批次」用
|
||||
out.append({
|
||||
"block": nm,
|
||||
"columns": blk.get("columns", []),
|
||||
"n_sections": len(blk.get("sections", [])),
|
||||
"rows": rows,
|
||||
"period_start_m": ps,
|
||||
"period_end_m": pe,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def to_records(blocks):
|
||||
"""把解析结果转成入库记录:材料编码/名称/规格/单位/不含税单价/税率/含税单价/目录/备注"""
|
||||
recs = []
|
||||
for b in blocks:
|
||||
blk = (b.get("block") or "").strip()
|
||||
for sec_title, r in b["rows"]:
|
||||
name = (r[1] or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
recs.append({
|
||||
"Code": (r[0] or "").strip(),
|
||||
"Name": name,
|
||||
"Specification": (r[2] or "").strip(),
|
||||
"Unit": (r[3] or "").strip(),
|
||||
"NoTaxPrice": _num(r[4]),
|
||||
"TaxRate": _num(r[5]),
|
||||
"TaxPrice": _num(r[6]),
|
||||
"Class": sec_title or blk,
|
||||
"Note": (r[7] or "").strip(),
|
||||
"Block": blk, # 块名(三级目录:根=批次 → 块 → 分类)
|
||||
})
|
||||
return recs
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
_sample = os.path.join(os.path.dirname(_PRJ), "珠海信息价_2026年7月.html")
|
||||
p = sys.argv[1] if len(sys.argv) > 1 else (_sample if os.path.exists(_sample) else "")
|
||||
blocks = parse(p)
|
||||
tot = 0
|
||||
for b in blocks:
|
||||
print("块:%s 分类数=%d 行数=%d" % (b["block"], b["n_sections"], len(b["rows"])))
|
||||
tot += len(b["rows"])
|
||||
print("总行数:", tot)
|
||||
recs = to_records(blocks)
|
||||
print("样例:", recs[0])
|
||||
print("样例:", recs[200] if len(recs) > 200 else "")
|
||||
@@ -1,299 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
信息价 / 市场价 Excel 解析器(2026-10-12 重设计版,主人定「只能导入 Excel 标准模板」)
|
||||
|
||||
**只收标准模板 .xlsx**:第 1 行表头必须与模板列名一致(去空格后全等,顺序不限),
|
||||
不是标准模板 → 抛 ValueError,调用方直接把提示给到界面(不做任何宽容解析)。
|
||||
|
||||
**模板结构**(template_bytes() 生成,9 列):
|
||||
目录 | 材料编码 | 材料名称 | 规格型号 | 单位 | 不含税单价 | 税率 | 含税单价 | 备注
|
||||
· 第 1 列「目录」= 多级路径,用「/」分隔(如「建筑材料/黑色及有色金属/钢筋」),
|
||||
层级不限;留空 = 未分类。导入时按路径逐级建目录(price_dirs),行挂在最底层目录。
|
||||
· 其余 8 列 = 一行材料。
|
||||
· 一个文件 = 一个批次(只读第 1 个工作表;「填写说明」页不参与解析)。
|
||||
· 下载给的模板不是空表:数据行来自 tpl/price_template_rows.xlsx(2026-11-01 起为
|
||||
珠海信息价 2026年7月 864 条)。换数据只替换该文件,不改代码。
|
||||
|
||||
与旧版(2026-10-06)的差异:
|
||||
· 旧版接受任意列名别名 + 「分类」单列 —— 全部退役(主人 2026-10-12 定:新软件,
|
||||
不做兼容)。HTML 导入同步退役(api_server._price_parse 只分派 xlsx)。
|
||||
· PARSER_VER 升号必须与 price_html.PARSER_VER 同步(stale_batches 对价格类
|
||||
只有一条判定线,见下方历史注释)。
|
||||
"""
|
||||
|
||||
import io, os, re
|
||||
|
||||
# ⚠️ 版本号与 price_html.PARSER_VER 保持一致(历史约定,见文件头);改这里同步改那边。
|
||||
PARSER_VER = "2026.10.12-1"
|
||||
|
||||
SHEET_DATA = "价格明细" # 数据 sheet 名(模板默认;只读第 1 个工作表,名字不校验)
|
||||
SHEET_HELP = "填写说明" # 说明 sheet 名(不解析)
|
||||
|
||||
# 模板固定列名(生成与解析共用,改这里两边一起变)
|
||||
COLS = ["目录", "材料编码", "材料名称", "规格型号", "单位",
|
||||
"不含税单价", "税率", "含税单价", "备注"]
|
||||
DIR_SEP = "/" # 目录多级路径分隔符
|
||||
|
||||
# 模板数据行来源(2026-11-01 主人定:价格明细不再是 4 行示例,改成珠海信息价 2026年7月 的 864 条真实数据)
|
||||
# 换数据只替换这个文件即可,不碰代码:9 列、首行表头、列名与 COLS 一致,一个 sheet。
|
||||
TPL_ROWS = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"tpl", "price_template_rows.xlsx")
|
||||
|
||||
_HELP = [
|
||||
("造价审核 · 信息价/市场价导入模板", ""),
|
||||
("", ""),
|
||||
("怎么用", "1) 在【价格明细】页按列填写,从第 2 行开始(第 1 行是表头,列名不要改)"),
|
||||
("", "2) 存成 .xlsx,回到后台「信息价」或「市场价」标签 → 导入 → 选这个文件"),
|
||||
("", "3) 名称 / 单位 / 不含税单价 必填;其余选填"),
|
||||
("", "4) 一个文件 = 一个批次(只读第 1 个工作表)"),
|
||||
("", ""),
|
||||
("列说明", ""),
|
||||
("目录", "多级路径用「/」分隔,如「建筑材料/黑色及有色金属/钢筋」,层级不限;"),
|
||||
("", "只填一段 = 一级目录;留空 = 未分类。只有最底层目录挂内容。"),
|
||||
("", "导入后目录仍可在后台明细页继续编辑(改名 / 增删 / 上移下移),不必回来改表重导"),
|
||||
("材料编码", "选填。没有就留空,不影响比对(精确键只用 名称+规格+单位)"),
|
||||
("材料名称", "必填。留空的行会被跳过"),
|
||||
("规格型号", "选填,但建议填——参与相似度计算,填了比对更准"),
|
||||
("单位", "必填。单位不同视为不同材料,不会互相命中"),
|
||||
("不含税单价", "必填,数字。不要带 ¥ 或千分位逗号(带了也能读,但不建议)"),
|
||||
("税率", "数字或百分数,如 0.13 或 13%"),
|
||||
("含税单价", "选填。留空时界面显示「—」"),
|
||||
("备注", "选填,如「2956 ~ 3076(均值:3016)」"),
|
||||
("", ""),
|
||||
("批次 / 期次", "一个文件 = 一个批次。期次从文件名里自动认(如「珠海信息价_2026年7月」),"),
|
||||
("", "认不出才用导入弹框里填的那个。所以文件名尽量带上年月,比手填更准"),
|
||||
]
|
||||
|
||||
|
||||
def _clean(s):
|
||||
"""表头归一化:去空白、全角空格、冒号、星号,便于严格比对"""
|
||||
return (str(s or "")).strip().replace(" ", "").replace(" ", "").replace(":", "").replace("*", "")
|
||||
|
||||
|
||||
def parse(path):
|
||||
"""解析标准模板 .xlsx → blocks 结构(与 api_server 的入库流程对接)。
|
||||
|
||||
返回 [{block, columns, n_sections, rows:[(目录路径, [8列])], period_start_m, period_end_m}, ...]
|
||||
· block = 文件名去扩展名(剥掉「sha256_」存储前缀)——一个文件一个批次
|
||||
· rows[i] = (目录路径原样或 '',[材料编码, 名称, 规格, 单位, 不含税, 税率, 含税, 备注])
|
||||
· 表头严格校验:_clean 后必须与 COLS 全等(顺序不限),否则 ValueError
|
||||
只读第 1 个工作表(模板结构里它就是「价格明细」;「填写说明」等其余 sheet 不看)。
|
||||
"""
|
||||
if not os.path.exists(path):
|
||||
raise ValueError("文件不存在:%s" % path)
|
||||
if not (path or "").lower().endswith(".xlsx"):
|
||||
raise ValueError("只支持标准模板 .xlsx(请用「标准模板」按钮下载后填写)")
|
||||
import openpyxl
|
||||
try:
|
||||
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
|
||||
except Exception as e:
|
||||
raise ValueError("打不开这个 Excel(%s)。请用「标准模板」按钮下载模板后填写" % e)
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
header, rows = _scan_rows(ws.iter_rows(values_only=True))
|
||||
finally:
|
||||
wb.close()
|
||||
if header is None:
|
||||
raise ValueError("这不是标准模板:第 1 行必须是模板的 9 个列名"
|
||||
"(目录 / 材料编码 / 材料名称 / 规格型号 / 单位 / 不含税单价 / 税率 / 含税单价 / 备注)。"
|
||||
"请点「标准模板」按钮下载后填写")
|
||||
fn = os.path.splitext(os.path.basename(path))[0]
|
||||
block = fn[65:] if re.match(r"^[0-9a-f]{64}_", fn) and len(fn) > 65 else fn
|
||||
import price_html
|
||||
ps, pe = price_html.guess_period(block)
|
||||
return [{
|
||||
"block": block,
|
||||
"columns": COLS[1:],
|
||||
"n_sections": len({r[0] for r in rows if r[0]}),
|
||||
"rows": rows,
|
||||
"period_start_m": ps,
|
||||
"period_end_m": pe,
|
||||
}]
|
||||
|
||||
|
||||
def _scan_rows(iter_rows):
|
||||
"""逐行扫描:先严格认表头(最多容忍 10 行废话),之后按模板 9 列取值。
|
||||
返回 (header|None, rows)。header=None = 表头对不上 = 不是标准模板。"""
|
||||
header, rows = None, []
|
||||
for r in iter_rows:
|
||||
if header is None:
|
||||
m = _map_header(r)
|
||||
if m:
|
||||
header = m
|
||||
continue
|
||||
# 表头行前面允许有空行,但出现非空内容仍对不上 → 直接判非模板
|
||||
if any(str(v or "").strip() for v in r):
|
||||
return None, []
|
||||
continue
|
||||
vals = [r[header.get(c, -1)] if 0 <= header.get(c, -1) < len(r) else "" for c in COLS]
|
||||
# ⚠️ openpyxl 只读模式把空单元格读成 None —— str(None)="None" 会被当非空,
|
||||
# 整行空就跳不过去了。None 一律视作空(2026-10-12 修,老口径靠 to_records 兜底)。
|
||||
if not any((str(v).strip() if v is not None else "") for v in vals):
|
||||
continue # 整行空 → 跳过
|
||||
rows.append((_cell(vals[0]), [_cell(v) for v in vals[1:]]))
|
||||
return header, rows
|
||||
|
||||
|
||||
def _map_header(row):
|
||||
"""表头行 → {标准列名: 列下标};**严格模式**:_clean 后必须与标准列名全等,
|
||||
9 列必须一个不缺。对不上返回 None。"""
|
||||
idx = {}
|
||||
for i, v in enumerate(row):
|
||||
k = _clean(v)
|
||||
if k in COLS and k not in idx:
|
||||
idx[k] = i
|
||||
if len(idx) != len(COLS):
|
||||
return None
|
||||
return idx
|
||||
|
||||
|
||||
def _cell(v):
|
||||
if v is None:
|
||||
return ""
|
||||
if isinstance(v, float) and v == int(v):
|
||||
return str(int(v))
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def to_records(blocks):
|
||||
"""入库记录(2026-10-12 新口径,**不再复用 price_html.to_records**):
|
||||
· Class = 目录路径原样(留空就是空 = 未分类;旧实现会回落成块名,与新设计冲突)
|
||||
· 数字列走 _num(去千分位;读不出数字=None,界面显示「—」)
|
||||
"""
|
||||
def _num(v):
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip().replace(",", "")
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return float(s)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
recs = []
|
||||
for b in blocks:
|
||||
blk = (b.get("block") or "").strip()
|
||||
for sec_title, r in b["rows"]:
|
||||
name = (r[1] or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
recs.append({
|
||||
"Code": (r[0] or "").strip(),
|
||||
"Name": name,
|
||||
"Specification": (r[2] or "").strip(),
|
||||
"Unit": (r[3] or "").strip(),
|
||||
"NoTaxPrice": _num(r[4]),
|
||||
"TaxRate": _num(r[5]),
|
||||
"TaxPrice": _num(r[6]),
|
||||
"Class": (sec_title or "").strip(),
|
||||
"Note": (r[7] or "").strip(),
|
||||
"Block": blk,
|
||||
})
|
||||
return recs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 标准模板生成(v2:目录列 = 多级路径)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# 数据文件缺失/读不动时的兜底示例行(保证模板永远能下载,不因文件丢失而 500)
|
||||
_DEMO_ROWS = [
|
||||
["建筑材料/黑色及有色金属/钢筋", "", "圆钢(HPB300)", "Φ6.5mm", "t", 2956.0, 0.13, 3340.28, "2956 ~ 3076(均值:3016)"],
|
||||
["建筑材料/黑色及有色金属/钢筋", "", "螺纹钢(HRB400E)", "Φ12-14mm", "t", 3180.0, 0.13, 3593.40, ""],
|
||||
["建筑材料/水泥、砖、砂石", "", "普通硅酸盐水泥 P.O 42.5", "散装", "t", 385.0, 0.13, 435.05, ""],
|
||||
["", "0101035", "高线(HPB300)", "Φ6mm", "t", 2980.0, 0.13, 3367.40, "留空目录 = 未分类"],
|
||||
]
|
||||
|
||||
|
||||
def _tpl_rows():
|
||||
"""读取模板数据行(内置 xlsx,跳过首行表头)。文件缺失或读失败 → 退回 4 行示例。"""
|
||||
try:
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(TPL_ROWS, read_only=True, data_only=True)
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
out = []
|
||||
for i, r in enumerate(ws.iter_rows(values_only=True)):
|
||||
if i == 0: # 表头由生成方重写,不取文件里的
|
||||
continue
|
||||
if all(v is None or str(v).strip() == "" for v in r):
|
||||
continue # 整行空跳过
|
||||
out.append(list(r[:len(COLS)]))
|
||||
finally:
|
||||
wb.close()
|
||||
if out:
|
||||
return out
|
||||
except Exception:
|
||||
pass # 缺文件/格式坏:走兜底,不让模板下载挂掉
|
||||
return [list(x) for x in _DEMO_ROWS]
|
||||
|
||||
|
||||
def template_bytes():
|
||||
"""生成标准模板 xlsx,返回 bytes(供后端 /api/admin/price_template 直接吐给浏览器)"""
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = SHEET_DATA
|
||||
|
||||
head_fill = PatternFill("solid", fgColor="1F5FAE")
|
||||
head_font = Font(color="FFFFFF", bold=True, size=11)
|
||||
thin = Side(style="thin", color="C9D4E2")
|
||||
bd = Border(left=thin, right=thin, top=thin, bottom=thin)
|
||||
|
||||
ws.append(COLS)
|
||||
for c in ws[1]:
|
||||
c.fill, c.font, c.border = head_fill, head_font, bd
|
||||
c.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
# 数据行:从内置数据文件加载(价格明细 = 珠海信息价 2026年7月 864 条真实数据)
|
||||
for d in _tpl_rows():
|
||||
ws.append(d)
|
||||
for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
|
||||
for c in row:
|
||||
c.border = bd
|
||||
ws.column_dimensions["A"].width = 32
|
||||
ws.column_dimensions["B"].width = 12
|
||||
ws.column_dimensions["C"].width = 30
|
||||
ws.column_dimensions["D"].width = 22
|
||||
ws.column_dimensions["E"].width = 8
|
||||
ws.column_dimensions["F"].width = 14
|
||||
ws.column_dimensions["G"].width = 9
|
||||
ws.column_dimensions["H"].width = 14
|
||||
ws.column_dimensions["I"].width = 28
|
||||
|
||||
hp = wb.create_sheet(SHEET_HELP)
|
||||
for k, v in _HELP:
|
||||
hp.append([k, v])
|
||||
hp.column_dimensions["A"].width = 18
|
||||
hp.column_dimensions["B"].width = 92
|
||||
hp["A1"].font = Font(bold=True, size=13, color="123A6B")
|
||||
key_font = Font(bold=True) # ⚠️ 不能用 cell.font.copy():openpyxl 的 StyleProxy 不可 hash
|
||||
for r in hp.iter_rows(min_row=1, max_row=hp.max_row):
|
||||
if r[0].value:
|
||||
r[0].font = key_font
|
||||
r[1].alignment = Alignment(wrap_text=True, vertical="top")
|
||||
|
||||
bio = io.BytesIO()
|
||||
wb.save(bio)
|
||||
return bio.getvalue()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
p = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
if not p:
|
||||
out = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.abspath(__file__)))), "..", "..", "价格导入模板.xlsx")
|
||||
open(out, "wb").write(template_bytes())
|
||||
print("已生成模板:", out)
|
||||
else:
|
||||
blocks = parse(p)
|
||||
for b in blocks:
|
||||
print("块:%s 目录数=%d 行数=%d" % (b["block"], b["n_sections"], len(b["rows"])))
|
||||
recs = to_records(blocks)
|
||||
print("记录数:", len(recs))
|
||||
print("样例:", recs[0] if recs else "")
|
||||
@@ -1,225 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
M1 最后半步:建索引 + 检索演示 + 测速度
|
||||
方案 §3.3(L0 精确 / L1 次精确 / L2 模糊)+ §5.4(时间邻近 先近后远)
|
||||
"""
|
||||
|
||||
import io, os, re, time, json, random, sqlite3
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.cell import WriteOnlyCell
|
||||
|
||||
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
|
||||
_PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核
|
||||
|
||||
DB = os.path.join(_PRJ, "data", "history.db")
|
||||
OUT = os.path.join(_PRJ, "data", "检索演示.xlsx")
|
||||
REPORT = os.path.join(_PRJ, "data", "检索报告.md")
|
||||
BASE_PERIOD = 2026 * 12 + 6 # 基准期次 2026-06(演示用)
|
||||
SIM_MIN = 0.60
|
||||
|
||||
def norm(s):
|
||||
s = (s or "").strip()
|
||||
s = s.replace("(", "(").replace(")", ")").replace(",", ",").replace(";", ";")
|
||||
s = s.replace("×", "*").replace("*", "*").replace("X", "*").replace("x", "*")
|
||||
s = re.sub(r"\s+", "", s)
|
||||
return s.lower()
|
||||
|
||||
def bigrams(s):
|
||||
s = norm(s)
|
||||
return set(s[i:i + 2] for i in range(len(s) - 1)) or {s}
|
||||
|
||||
def jaccard(a, b):
|
||||
A, B = bigrams(a), bigrams(b)
|
||||
return len(A & B) / max(len(A | B), 1)
|
||||
|
||||
def dist(start, end, base):
|
||||
if start is None:
|
||||
return 9999
|
||||
if start <= base <= end:
|
||||
return 0
|
||||
return start - base if base < start else base - end
|
||||
|
||||
DIST = """(CASE WHEN ?1 BETWEEN {t}.x_period_start_m AND {t}.x_period_end_m THEN 0
|
||||
WHEN ?1 < {t}.x_period_start_m THEN {t}.x_period_start_m - ?1
|
||||
ELSE ?1 - {t}.x_period_end_m END)"""
|
||||
|
||||
def build(con):
|
||||
c = con.cursor()
|
||||
for t in ("bills", "lmes"):
|
||||
cols = [r[1] for r in c.execute("PRAGMA table_info(%s)" % t)]
|
||||
if "x_period_start_m" not in cols:
|
||||
c.execute("ALTER TABLE %s ADD COLUMN x_period_start_m INTEGER" % t)
|
||||
c.execute("ALTER TABLE %s ADD COLUMN x_period_end_m INTEGER" % t)
|
||||
c.execute("""UPDATE {t} SET x_period_start_m=(SELECT x_period_start_m FROM batches WHERE id={t}.batch_id),
|
||||
x_period_end_m=(SELECT x_period_end_m FROM batches WHERE id={t}.batch_id)""".format(t=t))
|
||||
for s in ["CREATE INDEX IF NOT EXISTS ix_bill_exact_pe ON bills(x_hash_exact, x_period_end_m)",
|
||||
"CREATE INDEX IF NOT EXISTS ix_bill_exact_ps ON bills(x_hash_exact, x_period_start_m)",
|
||||
"CREATE INDEX IF NOT EXISTS ix_bill_semi_pe ON bills(x_hash_semi, x_period_end_m)",
|
||||
"CREATE INDEX IF NOT EXISTS ix_bill_semi_ps ON bills(x_hash_semi, x_period_start_m)",
|
||||
"CREATE INDEX IF NOT EXISTS ix_lme_exact_pe ON lmes(x_hash_exact, x_period_end_m)",
|
||||
"CREATE INDEX IF NOT EXISTS ix_lme_exact_ps ON lmes(x_hash_exact, x_period_start_m)"]:
|
||||
c.execute(s)
|
||||
fts = True
|
||||
try:
|
||||
c.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS bills_fts
|
||||
USING fts5(Name, Attr, content='bills', content_rowid='id', tokenize='trigram')""")
|
||||
c.execute("INSERT INTO bills_fts(bills_fts) VALUES('rebuild')")
|
||||
c.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS lmes_fts
|
||||
USING fts5(Name, Specification, content='lmes', content_rowid='id', tokenize='trigram')""")
|
||||
c.execute("INSERT INTO lmes_fts(lmes_fts) VALUES('rebuild')")
|
||||
except Exception as e:
|
||||
print("FTS5 不可用:", e); fts = False
|
||||
con.commit()
|
||||
return fts
|
||||
|
||||
def search_bill(con, r, base, fts, limit=10):
|
||||
c = con.cursor(); out = []
|
||||
sql = """SELECT '精确' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
|
||||
bt.x_period_start_m ps, bt.x_period_end_m pe, %s dist
|
||||
FROM bills b JOIN batches bt ON bt.id=b.batch_id
|
||||
WHERE b.x_hash_exact=? AND b.batch_id<>?
|
||||
ORDER BY dist, b.id LIMIT ?""" % DIST.format(t="b")
|
||||
out += [list(x) for x in c.execute(sql, (base, r["x_hash_exact"], r["batch_id"], limit))]
|
||||
if len(out) < limit:
|
||||
sql2 = """SELECT '次精确', b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name,
|
||||
bt.x_period_start_m, bt.x_period_end_m, %s dist
|
||||
FROM bills b JOIN batches bt ON bt.id=b.batch_id
|
||||
WHERE b.x_hash_semi=? AND b.x_hash_exact<>? AND b.batch_id<>?
|
||||
ORDER BY dist, b.id LIMIT ?""" % DIST.format(t="b")
|
||||
out += [list(x) for x in c.execute(sql2, (base, r["x_hash_semi"], r["x_hash_exact"],
|
||||
r["batch_id"], limit - len(out)))]
|
||||
if fts and len(out) < limit:
|
||||
q = norm(r["Name"])[:24] or norm(r["Attr"])[:24]
|
||||
if q:
|
||||
try:
|
||||
cand = c.execute("""SELECT b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name,
|
||||
bt.x_period_start_m, bt.x_period_end_m
|
||||
FROM bills_fts f JOIN bills b ON b.id=f.rowid
|
||||
JOIN batches bt ON bt.id=b.batch_id
|
||||
WHERE bills_fts MATCH ? AND b.batch_id<>? LIMIT 200""",
|
||||
('"' + q + '"', r["batch_id"])).fetchall()
|
||||
except Exception:
|
||||
cand = []
|
||||
sc = []
|
||||
used = set(x[1] for x in out)
|
||||
for x in cand:
|
||||
if x[0] in used:
|
||||
continue
|
||||
if norm(x[4]) != norm(r["Unit"]):
|
||||
continue
|
||||
sim = jaccard((r["Name"] or "") + (r["Attr"] or ""), (x[2] or "") + (x[3] or ""))
|
||||
if sim >= SIM_MIN:
|
||||
sc.append(["模糊", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8],
|
||||
dist(x[7], x[8], base), round(sim, 3)])
|
||||
sc.sort(key=lambda z: (z[9], -z[10]))
|
||||
out += sc[:limit - len(out)]
|
||||
return out[:limit]
|
||||
|
||||
def search_lme(con, r, base, fts, limit=10):
|
||||
c = con.cursor(); out = []
|
||||
sql = """SELECT '精确', l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
|
||||
bt.Name, bt.x_period_start_m, bt.x_period_end_m, %s dist
|
||||
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
|
||||
WHERE l.x_hash_exact=? AND l.batch_id<>?
|
||||
ORDER BY dist, l.id LIMIT ?""" % DIST.format(t="l")
|
||||
out += [list(x) for x in c.execute(sql, (base, r["x_hash_exact"], r["batch_id"], limit))]
|
||||
if fts and len(out) < limit:
|
||||
q = norm(r["Name"])[:20]
|
||||
if q:
|
||||
try:
|
||||
cand = c.execute("""SELECT l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate,
|
||||
l.TaxPrice, bt.Name, bt.x_period_start_m, bt.x_period_end_m
|
||||
FROM lmes_fts f JOIN lmes l ON l.id=f.rowid
|
||||
JOIN batches bt ON bt.id=l.batch_id
|
||||
WHERE lmes_fts MATCH ? AND l.batch_id<>? LIMIT 200""",
|
||||
('"' + q + '"', r["batch_id"])).fetchall()
|
||||
except Exception:
|
||||
cand = []
|
||||
sc = []
|
||||
used = set(x[1] for x in out)
|
||||
for x in cand:
|
||||
if x[0] in used:
|
||||
continue
|
||||
if norm(x[3]) != norm(r["Unit"]):
|
||||
continue
|
||||
sim = jaccard((r["Name"] or "") + (r["Specification"] or ""), (x[1] or "") + (x[2] or ""))
|
||||
if sim >= SIM_MIN:
|
||||
sc.append(["模糊", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9],
|
||||
dist(x[8], x[9], base), round(sim, 3)])
|
||||
sc.sort(key=lambda z: (z[10], -z[11]))
|
||||
out += sc[:limit - len(out)]
|
||||
return out[:limit]
|
||||
|
||||
def main():
|
||||
con = sqlite3.connect(DB); con.row_factory = sqlite3.Row
|
||||
t0 = time.time(); fts = build(con); t_idx = time.time() - t0
|
||||
|
||||
random.seed(42)
|
||||
bills = con.execute("""SELECT b.*, bt.Name proj FROM bills b JOIN batches bt ON bt.id=b.batch_id""").fetchall()
|
||||
lmes = con.execute("""SELECT l.*, bt.Name proj FROM lmes l JOIN batches bt ON bt.id=l.batch_id""").fetchall()
|
||||
sb = random.sample(bills, min(30, len(bills)))
|
||||
sl = random.sample(lmes, min(30, len(lmes)))
|
||||
|
||||
times, rb, rl = [], [], []
|
||||
first_tier, have_res = [], 0
|
||||
for r in sb:
|
||||
t = time.time(); res = search_bill(con, r, BASE_PERIOD, fts); times.append((time.time() - t) * 1000)
|
||||
if res: have_res += 1; first_tier.append(res[0][0])
|
||||
for x in res[:5]:
|
||||
rb.append([(r["Name"] or "")[:24], r["Price"], x[0], (x[3] or "")[:24], x[6], x[5], (x[7] or "")[:20], x[10]])
|
||||
for r in sl:
|
||||
t = time.time(); res = search_lme(con, r, BASE_PERIOD, fts); times.append((time.time() - t) * 1000)
|
||||
if res: have_res += 1; first_tier.append(res[0][0])
|
||||
for x in res[:5]:
|
||||
rl.append([(r["Name"] or "")[:24], r["NoTaxPrice"], x[0], (x[2] or "")[:24], x[5], (x[8] or "")[:20], x[11]])
|
||||
|
||||
def pct(p):
|
||||
s = sorted(times); return s[min(int(len(s) * p / 100), len(s) - 1)]
|
||||
tier_cnt = {}
|
||||
for x in rb: tier_cnt[x[2]] = tier_cnt.get(x[2], 0) + 1
|
||||
for x in rl: tier_cnt[x[2]] = tier_cnt.get(x[2], 0) + 1
|
||||
ft = {k: first_tier.count(k) for k in ("精确", "次精确", "模糊")}
|
||||
stat = [("数据库", DB), ("基准期次", "2026-06"), ("建索引耗时(秒)", round(t_idx, 1)),
|
||||
("查询有结果的比例", "%d/%d" % (have_res, len(times))),
|
||||
("结果档位分布", " ".join("%s=%d" % kv for kv in sorted(tier_cnt.items()))),
|
||||
("首条命中档位", " ".join("%s=%d" % kv for kv in ft.items())),
|
||||
("清单总量", len(bills)), ("工料机总量", len(lmes)), ("查询次数", len(times)),
|
||||
("平均耗时(毫秒)", round(sum(times) / len(times), 2)),
|
||||
("P50(毫秒)", round(pct(50), 2)), ("P95(毫秒)", round(pct(95), 2)),
|
||||
("P99(毫秒)", round(pct(99), 2)), ("最慢一次(毫秒)", round(max(times), 2))]
|
||||
|
||||
wb = Workbook(write_only=True)
|
||||
hf, hfill = Font(bold=True, color="FFFFFF"), PatternFill("solid", fgColor="1F5FAE")
|
||||
def sheet(name, head, rows):
|
||||
ws = wb.create_sheet(name)
|
||||
hr = [WriteOnlyCell(ws, value=v) for v in head]
|
||||
for cc in hr: cc.font = hf; cc.fill = hfill
|
||||
ws.append(hr)
|
||||
for r in rows: ws.append(list(r))
|
||||
sheet("性能", ["指标", "值"], stat)
|
||||
sheet("清单检索样例", ["被审清单", "本工程单价", "档位", "历史清单", "历史单价", "单位", "来源项目", "距基准(月)"], rb)
|
||||
sheet("工料机检索样例", ["被审工料机", "本工程除税价", "档位", "历史工料机", "历史除税价", "来源项目", "距基准(月)"], rl)
|
||||
out_path = OUT
|
||||
if os.path.exists(OUT):
|
||||
try: open(OUT, "a+b").close()
|
||||
except PermissionError: out_path = OUT.replace(".xlsx", "_v2.xlsx")
|
||||
wb.save(out_path)
|
||||
|
||||
o = ["# 检索演示报告(M1 最后半步)", "", "- 基准期次:2026-06(演示用)", "- 数据库:%s" % DB, "",
|
||||
"## 一、性能", "", "| 指标 | 值 |", "|---|---|"]
|
||||
o += ["| %s | %s |" % kv for kv in stat]
|
||||
o += ["", "## 二、清单检索样例(前 15 行)", "",
|
||||
"| 被审清单 | 本工程单价 | 档位 | 历史清单 | 历史单价 | 单位 | 来源项目 | 距基准(月) |",
|
||||
"|---|---:|---|---|---:|---|---|---:|"]
|
||||
o += ["| %s | %s | %s | %s | %s | %s | %s | %s |" % tuple(r) for r in rb[:15]]
|
||||
o += ["", "## 三、工料机检索样例(前 15 行)", "",
|
||||
"| 被审工料机 | 本工程除税价 | 档位 | 历史工料机 | 历史除税价 | 来源项目 | 距基准(月) |",
|
||||
"|---|---:|---|---|---:|---|---:|"]
|
||||
o += ["| %s | %s | %s | %s | %s | %s | %s |" % tuple(r) for r in rl[:15]]
|
||||
io.open(REPORT, "w", encoding="utf-8").write("\n".join(o))
|
||||
print("OK ->", out_path)
|
||||
print(json.dumps(dict(stat), ensure_ascii=False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,831 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
会话库写入:打开一个工程 → 解析(完整集,不过滤)→ 写进 session.db
|
||||
与历史库的区别:这里要"能核对原件",所以工程量/合价/数量/单位工程/工料机编码与类型全都要。
|
||||
"""
|
||||
|
||||
import io, json, os, re, sqlite3, time, hashlib
|
||||
|
||||
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
|
||||
_PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核
|
||||
|
||||
DB = os.path.join(_PRJ, "data", "session.db")
|
||||
SCHEMA = os.path.join(_PRJ, "app", "store", "session.sql")
|
||||
|
||||
|
||||
def norm(s):
|
||||
s = (s or "").strip().replace("(", "(").replace(")", ")").replace("×", "*")
|
||||
s = re.sub(r"\s+", "", s)
|
||||
return s.lower()
|
||||
|
||||
|
||||
def md5(*parts):
|
||||
return hashlib.md5("|".join(norm(p) for p in parts).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def rkey(src, uw, no, name, unit):
|
||||
"""备注的持久键:源文件 + 单位工程 + 编码 + 名称 + 单位(2026-09-30 拍板)
|
||||
|
||||
为什么不用 x_hash_exact:它只有「编码+名称+单位」,实测同一工程内撞车 **786 组**
|
||||
(会话11 的 BC006001 一个编码撞 15 次:施工围挡-A1 / 施工现场围挡和临时占地围挡),
|
||||
拿它当主键,两条不同清单的备注会互相覆盖。加上「源文件 + 单位工程」后实测冲突 **0**。
|
||||
"""
|
||||
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 取源文件名。"""
|
||||
if src_name is None:
|
||||
row = con.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
src_name = (row[0] if row else "") or ""
|
||||
ks = {}
|
||||
for r in con.execute("""SELECT b.id, u.Name AS uw, b.Number, b.Name, b.Unit
|
||||
FROM s_bills b
|
||||
LEFT JOIN s_unit_works u ON u.id = b.uw_id
|
||||
WHERE b.session_id=?""", (sid,)):
|
||||
ks[rkey(src_name, r["uw"], r["Number"], r["Name"], r["Unit"])] = r["id"]
|
||||
return ks
|
||||
|
||||
|
||||
def save_remark(con, bill_id, remark):
|
||||
"""写备注:**双写** —— s_bills.x_remark(界面立刻可见)+ s_remarks(不随会话消亡)"""
|
||||
con.execute("UPDATE s_bills SET x_remark=? WHERE id=?", (remark, bill_id))
|
||||
row = con.execute("""SELECT s.src_name, u.Name AS uw, b.Number, b.Name, b.Unit, b.session_id
|
||||
FROM s_bills b
|
||||
JOIN sessions s ON s.id = b.session_id
|
||||
LEFT JOIN s_unit_works u ON u.id = b.uw_id
|
||||
WHERE b.id=?""", (bill_id,)).fetchone()
|
||||
if not row:
|
||||
return 0
|
||||
con.execute("""INSERT INTO s_remarks(src_key, uw_name, bill_no, bill_name, bill_unit,
|
||||
rkey, remark, updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(rkey) DO UPDATE SET remark=excluded.remark,
|
||||
updated_at=excluded.updated_at""",
|
||||
(row["src_name"], row["uw"], row["Number"], row["Name"], row["Unit"],
|
||||
rkey(row["src_name"], row["uw"], row["Number"], row["Name"], row["Unit"]),
|
||||
remark, time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
return 1
|
||||
|
||||
|
||||
def restore_remarks(con, sid):
|
||||
"""重新解析 / 打开工程之后,把 s_remarks 里的备注按 rkey 回填到 s_bills.x_remark
|
||||
|
||||
s_bills 每次 wipe 都是全新 id,唯一能对上号的就是这个持久键。
|
||||
备注总量很小(几十条),直接全表取回在内存里比对,不走 IN(?) 以免撞参数上限。
|
||||
返回回填条数。
|
||||
"""
|
||||
ks = _bill_keys(con, sid)
|
||||
if not ks:
|
||||
return 0
|
||||
n = 0
|
||||
for r in con.execute("SELECT rkey, remark FROM s_remarks WHERE remark IS NOT NULL AND TRIM(remark)<>''"):
|
||||
bid = ks.get(r["rkey"])
|
||||
if bid:
|
||||
con.execute("UPDATE s_bills SET x_remark=? WHERE id=?", (r["remark"], bid))
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
# ---------- 工料机审核备注(2026-10-08 主人定:结果表「采纳」写入工料机) ----------
|
||||
# 机制与清单备注完全同款:备注(界面立刻可见)+ s_remarks 持久副本(rkey 前缀 'L:'
|
||||
# 与清单键隔离),重新解析 wipe 后由 restore_lme_remarks() 按 rkey 回填。
|
||||
# ⚠️ 2026-10-11 决策 40:「项目工料机」标签数据源改**项目级汇总 s_lme_proj** ——
|
||||
# 备注随之落在 s_lme_proj.x_remark(老库启动自愈 ALTER 补列);rkey 公式不变
|
||||
# (src_name+编码+名称+单位,内容键),s_remarks 里的存量备注直接平移生效。
|
||||
|
||||
def ensure_lme_proj_remark(con):
|
||||
"""老会话库 s_lme_proj 补 x_remark 列(幂等,决策 40)。"""
|
||||
cols = [r[1] for r in con.execute("PRAGMA table_info(s_lme_proj)")]
|
||||
if "x_remark" not in cols:
|
||||
con.execute("ALTER TABLE s_lme_proj ADD COLUMN x_remark TEXT")
|
||||
con.commit()
|
||||
|
||||
|
||||
def ensure_lme_proj_remark_scoped():
|
||||
"""启动自愈入口:自带连接的老库补列(幂等)。"""
|
||||
con = connect()
|
||||
try:
|
||||
ensure_lme_proj_remark(con)
|
||||
ensure_lme_price_cols(con)
|
||||
ensure_lme_anchor_cols(con)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
_LME_PRICE_COLS = ("ntp_org", "ntp_expr", "taxp_org", "taxp_expr") # 决策 183:六价全采
|
||||
|
||||
|
||||
def ensure_lme_price_cols(con):
|
||||
"""老会话库 s_lme_proj/s_lme_uw 补六价四列(幂等,决策 183:整套按骨架属性对应回填)。"""
|
||||
for t in ("s_lme_proj", "s_lme_uw"):
|
||||
cols = [r[1] for r in con.execute("PRAGMA table_info(%s)" % t)]
|
||||
if not cols:
|
||||
continue # 表还没建(首次初始化走 CREATE)
|
||||
for cn in _LME_PRICE_COLS:
|
||||
if cn not in cols:
|
||||
con.execute("ALTER TABLE %s ADD COLUMN %s REAL" % (t, cn))
|
||||
con.commit()
|
||||
|
||||
|
||||
_LME_ANCHOR_COLS = ("x_ntp0", "x_rate0", "x_taxp0") # 决策 219:第一次计算的三价锚(采纳备注旧价源)
|
||||
|
||||
|
||||
def ensure_lme_anchor_cols(con):
|
||||
"""老会话库 s_lme_proj 补采纳锚三列(幂等,只保列在——防老代码/策略表读崩)。
|
||||
决策 251(2026-11-01 主人定):采纳备注旧价改由采纳端点直读导入原件价(ntp_org/taxp_org),
|
||||
锚列停止灌值、停止回填(列保留不 DROP,数据红线)。"""
|
||||
cols = [r[1] for r in con.execute("PRAGMA table_info(s_lme_proj)")]
|
||||
if not cols:
|
||||
return
|
||||
for cn in _LME_ANCHOR_COLS:
|
||||
if cn not in cols:
|
||||
con.execute("ALTER TABLE s_lme_proj ADD COLUMN %s REAL" % cn)
|
||||
cols.append(cn)
|
||||
con.commit()
|
||||
|
||||
|
||||
def _lme_keys(con, sid, src_name=None):
|
||||
"""这个会话每条工料机的持久键 → {rkey: 行id}(回填备注用)。前缀 'L:' 隔离清单键。
|
||||
2026-10-11 决策 40:行 = 项目级汇总 s_lme_proj(标签数据源所在)。
|
||||
src_name 可显式传入:两段式删除时会话行已先删。"""
|
||||
if src_name is None:
|
||||
row = con.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
src_name = (row[0] if row else "") or ""
|
||||
ks = {}
|
||||
for r in con.execute("""SELECT id, code, name, unit
|
||||
FROM s_lme_proj
|
||||
WHERE session_id=?""", (sid,)):
|
||||
ks["L:" + rkey(src_name, "", r["code"], r["name"], r["unit"])] = r["id"]
|
||||
return ks
|
||||
|
||||
|
||||
def save_lme_remark(con, lme_id, remark):
|
||||
"""写工料机备注:双写 s_lme_proj.x_remark + s_remarks('L:' 前缀 rkey),与 save_remark 同款。
|
||||
lme_id = 项目级汇总行 id(决策 40:标签数据源所在表)。"""
|
||||
con.execute("UPDATE s_lme_proj SET x_remark=? WHERE id=?", (remark, lme_id))
|
||||
row = con.execute("""SELECT s.src_name, p.code, p.name, p.unit
|
||||
FROM s_lme_proj p JOIN sessions s ON s.id = p.session_id
|
||||
WHERE p.id=?""", (lme_id,)).fetchone()
|
||||
if not row:
|
||||
return 0
|
||||
k = "L:" + rkey(row["src_name"], "", row["code"], row["name"], row["unit"])
|
||||
con.execute("""INSERT INTO s_remarks(src_key, uw_name, bill_no, bill_name, bill_unit,
|
||||
rkey, remark, updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(rkey) DO UPDATE SET remark=excluded.remark,
|
||||
updated_at=excluded.updated_at""",
|
||||
(row["src_name"], "", row["code"], row["name"], row["unit"],
|
||||
k, remark, time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
return 1
|
||||
|
||||
|
||||
def restore_lme_remarks(con, sid):
|
||||
"""重新解析 / 打开工程后,把 s_remarks 里 'L:' 前缀的工料机备注回填到 s_lme_proj.x_remark。"""
|
||||
ks = _lme_keys(con, sid)
|
||||
if not ks:
|
||||
return 0
|
||||
n = 0
|
||||
for r in con.execute("SELECT rkey, remark FROM s_remarks WHERE remark IS NOT NULL AND TRIM(remark)<>''"):
|
||||
pid = ks.get(r["rkey"])
|
||||
if pid:
|
||||
con.execute("UPDATE s_lme_proj SET x_remark=? WHERE id=?", (r["remark"], pid))
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def migrate_remark_keys(con, old_src, new_src):
|
||||
"""源文件换了(同名工程换文件重开,闸②同步 src_name 时调用):把 s_remarks 里挂在
|
||||
旧 src_name 下的持久键平移到新键。rkey 是单向散列改不了,但每行存了明文分量
|
||||
(src_key/uw_name/bill_no/bill_name/bill_unit,清单与工料机备注同构)——
|
||||
按「内容分量不变、只换源文件分量」重算即可:内容还对得上的备注跨文件版本存活,
|
||||
内容已变的自然失配(内容键的本意)。返回平移条数。"""
|
||||
n = 0
|
||||
for r in con.execute("SELECT id, uw_name, bill_no, bill_name, bill_unit FROM s_remarks WHERE src_key=?",
|
||||
(old_src,)).fetchall():
|
||||
nk = rkey(new_src, r["uw_name"], r["bill_no"], r["bill_name"], r["bill_unit"])
|
||||
con.execute("""UPDATE s_remarks SET src_key=?, rkey=? WHERE id=?
|
||||
AND NOT EXISTS(SELECT 1 FROM s_remarks WHERE rkey=?)""",
|
||||
(new_src, nk, r["id"], nk))
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
# 「重新解析」时**刻意保留**的表(跨解析存在的人为数据/配置)。
|
||||
# ⚠️ 语义反转的防呆清单:新表**默认被清**,要保留必须显式加进来并写明理由——
|
||||
# 反过来维护"要删的表清单"已经两次漏表(2026-09-30 s_sections、2026-10-10 s_lme_res)。
|
||||
WIPE_KEEP = {
|
||||
"s_remarks", # 采纳/比对备注:人对清单的判断,不属于任何一次导入(restore_remarks 回填)
|
||||
"s_settings", # 工作台「分组/匹配」设置:换数据口径不该带走用户的设置
|
||||
}
|
||||
|
||||
|
||||
def wipe(con, sid, clean_orphans=True):
|
||||
"""删掉一个会话的全部数据(会话行本身保留)——「重新解析」先清场再重写
|
||||
|
||||
⚠️ s_norms 没有 session_id 列,只能借 s_bills 绕一层;漏了这步会留下孤儿定额。
|
||||
⚠️ 2026-09-29:bill_id IS NULL 的定额**任何会话都认领不了**(挂不上父表就是死数据),
|
||||
光靠「按 session 删」永远删不掉它们 —— 实测旧会话留下 39 条,重新解析 N 次还在。
|
||||
这里顺手清一遍:这些行本来就是不可达数据,删掉没有副作用。
|
||||
2026-10-19 两段式删除:后台清理传 clean_orphans=False(孤儿全表扫描移到启动自愈
|
||||
drop_orphan_rows),避免每次删除都全表扫 s_norms/s_norm_res。
|
||||
|
||||
⚠️ 2026-09-30:**绝不碰 s_remarks**。备注是人对清单的判断,不属于任何一次导入,
|
||||
重新解析不许带走它——它靠 restore_remarks() 按 rkey 回填到新的 s_bills。
|
||||
(2026-10-08 起「删会话」改为连带删除:见 drop_remarks,引用清零才删。)
|
||||
|
||||
⚠️ 2026-10-10 防呆改造:其余 s_ 表**按 sqlite_master 动态发现**,不再手工枚举——
|
||||
只要建表带了 session_id 列,「重新解析」就必然清它,加新表忘了同步这里也不会
|
||||
再叠加脏数据。要跨解析保留的表才需要登记进 WIPE_KEEP。
|
||||
"""
|
||||
cur = con.cursor()
|
||||
# 2026-09-30:消耗量挂在定额下,必须在删定额**之前**清,否则会留下指向已删定额的死数据
|
||||
cur.execute("""DELETE FROM s_norm_res WHERE norm_id IN
|
||||
(SELECT n.id FROM s_norms n WHERE n.bill_id IN
|
||||
(SELECT id FROM s_bills WHERE session_id=?))""", (sid,))
|
||||
cur.execute("DELETE FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?)", (sid,))
|
||||
if clean_orphans:
|
||||
cur.execute("DELETE FROM s_norms WHERE bill_id IS NULL")
|
||||
cur.execute("DELETE FROM s_norm_res WHERE norm_id IS NULL")
|
||||
# 动态清场:sqlite_master 里所有 s_ 开头的表,带 session_id 列且不在保留清单 → 删
|
||||
for (t,) in con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall():
|
||||
if not t.startswith("s_") or t in WIPE_KEEP:
|
||||
continue
|
||||
if "session_id" in {x[1] for x in con.execute("PRAGMA table_info(%s)" % t)}:
|
||||
cur.execute("DELETE FROM %s WHERE session_id=?" % t, (sid,))
|
||||
|
||||
|
||||
def dedupe_lme_res(con=None):
|
||||
"""存量自愈:s_lme_res 按 (session_id, p_code, res_code) 去重,保最新一行。
|
||||
|
||||
2026-10-10 一次性清理(上面 wipe 漏表的存量受害者),幂等——反复跑无副作用。
|
||||
2026-11-04 主人定「耗弹框不许重复」:去重键去掉 qty/seq——此前同码不同 qty/seq 的重复套
|
||||
(采纳补子级跨批次灌入的脏数据)能躲过去重、弹框照样重复;组成同码只该有一条。
|
||||
保留 MAX(rowid):越新的行采集口径越全(name 列早期常为空)。"""
|
||||
own = con is None
|
||||
if own:
|
||||
con = connect()
|
||||
con.execute("""DELETE FROM s_lme_res WHERE rowid NOT IN
|
||||
(SELECT MAX(rowid) FROM s_lme_res
|
||||
GROUP BY session_id, p_code, res_code)""")
|
||||
if own:
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def dedupe_lme_uw(con=None):
|
||||
"""存量自愈:s_lme_uw **整行内容完全相同**才去重,保最新一行。幂等。
|
||||
|
||||
2026-10-25 决策 191:合并/重放换码两源撞同保留码会造出同单位同码**同值**双行
|
||||
(实测 uw6830 99450630-0003×2)——只清整行雷同的垃圾。同码多行(含同码不同价)
|
||||
是决策 171/186 定稿口径(镜像源文件多行现实),绝不并。列动态发现防漂移。"""
|
||||
own = con is None
|
||||
if own:
|
||||
con = connect()
|
||||
cols = [r[1] for r in con.execute("PRAGMA table_info(s_lme_uw)")]
|
||||
cols = [c for c in cols if c != "id"] # 2026-10-25 实测修:GROUP BY 含 id=每行自成一组,
|
||||
if cols: # 去重永远空转(决策 191 自愈无效);按内容列去重
|
||||
con.execute("DELETE FROM s_lme_uw WHERE rowid NOT IN "
|
||||
"(SELECT MAX(rowid) FROM s_lme_uw GROUP BY %s)" % ", ".join(cols))
|
||||
if own:
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def drop_orphan_rows():
|
||||
"""启动自愈:s_ 表里 session_id 已不存在(会话早被删)的孤儿行清掉,幂等。
|
||||
|
||||
2026-10-11 起因:s_lme_res 残留幽灵 sid(32/39/60~67,漏表时代老账)——
|
||||
dedupe 只去重不删孤儿,会话没了它们的组成行还躺在库里。口径与 wipe 一致:
|
||||
动态发现带 session_id 列的 s_ 表、跳过 WIPE_KEEP(s_remarks/s_settings 本就没有
|
||||
session_id 列,天然不沾)。
|
||||
2026-10-19 两段式删除兜底:s_norms/s_norm_res 没有 session_id,按父表引用补扫,
|
||||
这样后台清理没跑完就退出软件,下次启动也能把孤儿清干净。返回删除行数。
|
||||
|
||||
2026-10-20(决策 126):本函数已改在**后台线程**跑,先只读探测(SELECT ... LIMIT 1),
|
||||
确认真有孤儿才开写事务。原来不论有没有孤儿都直接 DELETE——即使删 0 行也会拿写锁,
|
||||
后台自愈会和主人正在做的采纳/编辑抢库。"""
|
||||
con = connect()
|
||||
try:
|
||||
tabs = []
|
||||
for (t,) in con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall():
|
||||
if not t.startswith("s_") or t in WIPE_KEEP:
|
||||
continue
|
||||
if "session_id" in {x[1] for x in con.execute("PRAGMA table_info(%s)" % t)}:
|
||||
tabs.append(t)
|
||||
# 只读探测:没有任何孤儿就直接返回,不开写事务(后台自愈不抢用户写入)。
|
||||
# 注意不能“探一个删一个”——父表删完才有子表孤儿,级联顺序必须保持原样。
|
||||
orphan = any(con.execute("SELECT 1 FROM %s WHERE session_id NOT IN "
|
||||
"(SELECT id FROM sessions) LIMIT 1" % t).fetchone()
|
||||
for t in tabs)
|
||||
if not orphan:
|
||||
orphan = bool(con.execute(
|
||||
"SELECT 1 FROM s_norms WHERE bill_id IS NULL "
|
||||
"OR bill_id NOT IN (SELECT id FROM s_bills) LIMIT 1").fetchone()
|
||||
or con.execute(
|
||||
"SELECT 1 FROM s_norm_res WHERE norm_id IS NULL "
|
||||
"OR norm_id NOT IN (SELECT id FROM s_norms) LIMIT 1").fetchone())
|
||||
if not orphan:
|
||||
return 0
|
||||
n = 0
|
||||
for t in tabs:
|
||||
cur = con.execute("DELETE FROM %s WHERE session_id NOT IN (SELECT id FROM sessions)" % t)
|
||||
n += cur.rowcount or 0
|
||||
cur = con.execute("DELETE FROM s_norms WHERE bill_id IS NULL "
|
||||
"OR bill_id NOT IN (SELECT id FROM s_bills)")
|
||||
n += cur.rowcount or 0
|
||||
cur = con.execute("DELETE FROM s_norm_res WHERE norm_id IS NULL "
|
||||
"OR norm_id NOT IN (SELECT id FROM s_norms)")
|
||||
n += cur.rowcount or 0
|
||||
con.commit()
|
||||
return n
|
||||
except Exception:
|
||||
con.rollback()
|
||||
return -1
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def drop_orphan_remarks(batch_src_hashes=None):
|
||||
"""启动自愈:备注的源文件既没有剩余会话、也没有后台批次引用 → 删,幂等。
|
||||
|
||||
2026-10-19 两段式删除的崩溃兜底:后台清理没跑完就退出,孤儿备注下次启动清掉。
|
||||
保守口径:src_key(可能用「;」连多个文件)任一段仍被会话/批次引用 → 整组保留。
|
||||
返回删除条数。"""
|
||||
con = connect()
|
||||
try:
|
||||
refs = set(batch_src_hashes or ())
|
||||
for r in con.execute("SELECT src_name FROM sessions"):
|
||||
for seg in (r[0] or "").split(";"):
|
||||
seg = seg.strip()
|
||||
if seg:
|
||||
refs.add(seg)
|
||||
dead = []
|
||||
for r in con.execute("SELECT DISTINCT src_key FROM s_remarks"):
|
||||
sk = r[0] or ""
|
||||
segs = [x.strip() for x in sk.split(";") if x.strip()]
|
||||
if not segs or not any(s in refs for s in segs):
|
||||
dead.append(sk)
|
||||
n = 0
|
||||
for sk in dead:
|
||||
n += con.execute("DELETE FROM s_remarks WHERE src_key=?", (sk,)).rowcount
|
||||
con.commit()
|
||||
return n
|
||||
except Exception:
|
||||
con.rollback()
|
||||
return -1
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def drop(con, sid):
|
||||
"""连会话行一起删(台账里「删除」用)"""
|
||||
wipe(con, sid)
|
||||
con.execute("DELETE FROM sessions WHERE id=?", (sid,))
|
||||
|
||||
|
||||
def bill_rkeys(con, sid, src_name=None):
|
||||
"""这个会话全部清单的持久键集合(删会话清备注用,见 drop_remarks)"""
|
||||
return set(_bill_keys(con, sid, src_name))
|
||||
|
||||
|
||||
def lme_rkeys(con, sid, src_name=None):
|
||||
"""这个会话全部工料机的持久键集合(删会话清备注用,与 bill_rkeys 同款,'L:' 前缀)"""
|
||||
return set(_lme_keys(con, sid, src_name))
|
||||
|
||||
|
||||
def drop_remarks(con, rk, batch_src_hashes=None, keep_ids=None):
|
||||
"""删会话时把采纳备注一并删除(2026-10-08 主人定:最近审核删除 = 备注+源文件一起删)。
|
||||
|
||||
rk 为被删会话的 rkey 集合(**删会话前**用 bill_rkeys 收集,删完行就没了)。
|
||||
2026-10-08 起 rk 里也含工料机键('L:' 前缀,调用方用 lme_rkeys 一并收)。
|
||||
⚠️ 备注生命周期与**源文件**完全同构(2026-10-08 主人定):只要源文件还被任何
|
||||
「剩余会话」或「批次」引用着,备注就保留;引用清零才删——与 _purge_upload_files 同构。
|
||||
· 会话侧:剩余会话的清单还能拼出同款 rkey → 保留(同一份文件开两个会话互不误伤);
|
||||
· 批次侧:batches.x_src_hash 还引用着同一份 uploads 文件 → 保留(文件已入库时
|
||||
删会话不再丢备注;重新打开工程会按 rkey 自动回填)。
|
||||
batch_src_hashes:history.db 现存批次的 x_src_hash 集合(api 层传入——本模块只碰
|
||||
session.db,不越过分层去开历史库)。备注的 src_key 可能是「;」连接的多文件串,逐段比对。
|
||||
keep_ids(决策 242):删除时刻的剩余会话 id 快照——**只认快照里的会话**当引用;
|
||||
删除后立刻重导的新会话不算引用,否则旧备注会被新会话「保住」又回填进新工程。
|
||||
⚠️ 重新解析(wipe)不走这里 —— 它的按 rkey 回填机制依赖 s_remarks。
|
||||
返回删除条数。
|
||||
"""
|
||||
if not rk:
|
||||
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 ())
|
||||
for k in (rk - keep):
|
||||
row = con.execute("SELECT src_key FROM s_remarks WHERE rkey=?", (k,)).fetchone()
|
||||
if bh and row and row[0] and any(seg in bh for seg in row[0].split(";")):
|
||||
keep.add(k) # 批次还引用着源文件:备注保留
|
||||
n = 0
|
||||
# 2026-10-19:逐条 DELETE 改为每 500 条一批(1.8 万键从 1.8 万次语句降到 ~36 次)
|
||||
keys = list(rk - keep)
|
||||
for i in range(0, len(keys), 500):
|
||||
chunk = keys[i:i + 500]
|
||||
ph = ",".join("?" * len(chunk))
|
||||
n += con.execute("DELETE FROM s_remarks WHERE rkey IN (%s)" % ph, chunk).rowcount
|
||||
return n
|
||||
|
||||
|
||||
def connect_readonly():
|
||||
"""打开会话库的纯只读连接;列表页不应为一次查询重复执行建表/补列。"""
|
||||
con = sqlite3.connect("file:%s?mode=ro" % DB, uri=True, timeout=2.0)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA query_only=ON")
|
||||
con.execute("PRAGMA busy_timeout=2000")
|
||||
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())
|
||||
# 老库补列(已存在的列会报错,忽略)
|
||||
# ⚠️ 每个表各补各的 —— 别把 A 表的列塞进 B 表的循环里,那会给 B 表凭空造出无用列
|
||||
for tbl, cols in (
|
||||
# 2026-10-06:x_batch_id = 后台批次 id(同一份源文件导入过就能关联上,
|
||||
# 工作台靠它只读展示该项目的询价附件)。老库没有这列,这里补。
|
||||
("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",
|
||||
# 决策 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",
|
||||
# 决策 244(2026-11-01):四张汇总卡——老库补列后重解析才有值
|
||||
"Code TEXT", "Unit TEXT", "Scale REAL", "ztotal REAL")),
|
||||
("s_bills", ("div_id INTEGER",
|
||||
# 源文件备注(清单节点 Remark 属性,2026-10-08 加;老库补列,老会话重解析才有)
|
||||
"src_remark TEXT",
|
||||
# 决策 217:第一次导进来的原始单价(采纳备注旧价固定源;老库补列后重开工程生效)
|
||||
"x_price0 REAL")),
|
||||
# 2026-10-08:工料机审核备注(采纳写入,持久副本 s_remarks rkey 前缀 'L:')
|
||||
# + 次精确档(md5 名称+单位,与历史库 lmes 同口径)
|
||||
("s_lmes", ("x_remark TEXT", "x_hash_semi TEXT")),
|
||||
# 2026-10-02:台班组成子项的名称(老库没这列,打开工程时 INSERT 会缺列报错)
|
||||
("s_lme_res", ("name TEXT",)),
|
||||
# 2026-10-18:定额含量算式(换算调整式如 1611.66*1.2,采纳携带;决策 106 补记十二)
|
||||
("s_norm_res", ("express TEXT",)),
|
||||
# 2026-10-18:定额换算调整记录(JSON,采纳携带;决策 106 补记十三)
|
||||
("s_norms", ("x_adjust TEXT",)),
|
||||
# 2026-11-03:结构固定子块原样值(单价行/管理费/费用构成/表达式行,JSON 文档序)
|
||||
("s_bills", ("x_side TEXT", "x_ptag TEXT")),
|
||||
("s_norms", ("x_side TEXT",)),
|
||||
# 2026-11-03:单位工程工程特征树(AttrInfo 原样,导出按数据循环)
|
||||
("s_unit_works", ("x_attr TEXT",)),
|
||||
# 2026-11-03:项目级非数据层结构树
|
||||
("sessions", ("x_side TEXT",)),
|
||||
# 2026-11-04:本项目自己的空骨架(打开工程时提炼,导出优先用)
|
||||
("sessions", ("x_own_blank BLOB", "x_own_meta TEXT")),
|
||||
):
|
||||
for col in cols:
|
||||
try:
|
||||
con.execute("ALTER TABLE %s ADD COLUMN %s" % (tbl, col))
|
||||
except Exception as e:
|
||||
if "duplicate column" not in str(e).lower():
|
||||
# 幂等补列:列已存在是正常路径;其余失败要喊出来(2026-10-07)
|
||||
print("补列失败 %s.%s:%s" % (tbl, col.split()[0], e), flush=True)
|
||||
# 2026-10-01:分组/匹配 设置的持久化(分组关键词、匹配过滤词)
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS s_settings(
|
||||
scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT, PRIMARY KEY(scope,k))""")
|
||||
return con
|
||||
|
||||
|
||||
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, file_kind}
|
||||
job : import_job 模块(复用它的解析器)
|
||||
sid : 给了就**写进这个已存在的会话**(「重新解析」用:先删旧数据再原地重写,会话 id 不变)
|
||||
返回 session_id
|
||||
"""
|
||||
cur = con.cursor()
|
||||
# 基准期次:起~止(单月时两者相同);兼容老参数 base_period_m
|
||||
pf = meta.get("period_from")
|
||||
pt = meta.get("period_to")
|
||||
if pf is None:
|
||||
pf = pt = meta.get("base_period_m")
|
||||
if pt is None:
|
||||
pt = pf
|
||||
if pf is not None and pt is not None and int(pt) < int(pf):
|
||||
pf, pt = pt, pf
|
||||
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, 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", ""), _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=?, 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", ""), _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 # 工程总造价:多文件时取最后一个有值的
|
||||
pinfo, pfeat, pside = None, None, None # 项目根属性 / 项目特征 / 项目级非数据层结构树
|
||||
num2sec, sec_built = {}, set() # 2026-09-30:单位工程编号 → 单项工程 id
|
||||
for path, name in files:
|
||||
out = {"uw": [], "bills": [], "norms": [], "lmes": [],
|
||||
"cur_bill": -1, "cur_uw": -1, "bill_uw": [], # ← 后两个 2026-09-29 加:清单归属哪个单位工程
|
||||
"bill_kind": [], "prelim_raw": 0, # ← 2026-09-29 决策17:措施条目 Kind='prelim'
|
||||
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0,
|
||||
"lme_raw": 0, "lme_skip": 0,
|
||||
"proj_name": "", "file_kind": None, "bulid_unit": "", "total": None}
|
||||
# 2026-10-07 起「导入不过滤」是唯一口径(full 标志废除):工作台与后台导入
|
||||
# 收一样的完整集,两侧唯一差异只剩进哪个库。
|
||||
# 2026-10-01:不再支持 xml(parse_old 已删除)。cos4 / .COS 都是 zip 包 → parse_std。
|
||||
# 2026-10-19:SWT(深圳数据交换标准,散装 XML)走 parse_swt;由 parse_file 按文件头分派。
|
||||
job.parse_file(path, out)
|
||||
if out.get("total") is not None:
|
||||
ptotal = out["total"] # 工程总造价(原文件里的那个,不是清单合价求和)
|
||||
if out.get("info"):
|
||||
pinfo = out["info"] # 项目根节点属性(编号/专业/计价标准/单位…)
|
||||
if out.get("feat"):
|
||||
pfeat = out["feat"] # 项目特征条目 [(名称, 值)]
|
||||
if out.get("proj_side"):
|
||||
pside = out["proj_side"] # 项目级非数据层结构(SummaryOfCost/AddiCost…)
|
||||
|
||||
# 单项工程先入(2026-09-30):记下「单位工程编号 → 单项工程 id」,单位工程靠编号归位。
|
||||
# 没有单项工程层的格式(如三溪 .COS)这里就是空的,树退化成两层,不硬造。
|
||||
for s in (out.get("sections") or []):
|
||||
# ⚠️ 去重键必须带上 uw_nums:cos4 的单项工程 name/number 常常都是空,
|
||||
# 只用 (名称,编号) 会把 5 个不同的单项工程合并成 1 个(横琴实测踩过)。
|
||||
key = (s.get("name") or "", s.get("number") or "",
|
||||
tuple(s.get("uw_nums") or []))
|
||||
if key in sec_built: # 一次导入多文件时防重复建
|
||||
continue
|
||||
sec_built.add(key)
|
||||
cur.execute("INSERT INTO s_sections(session_id, Number, Name, Total, Ratios)"
|
||||
" VALUES(?,?,?,?,?)",
|
||||
(sid, s.get("number"), s.get("name"), s.get("total"), s.get("ratios")))
|
||||
stat["section"] = stat.get("section", 0) + 1
|
||||
for num in (s.get("uw_nums") or []):
|
||||
num2sec[num] = cur.lastrowid
|
||||
|
||||
# 单位工程先入,记下 id 顺序——清单的 bill_uw 存的是 out["uw"] 的下标,靠这个表换成真实 id
|
||||
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,
|
||||
Code, Unit, Scale, ztotal, x_attr)
|
||||
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"),
|
||||
(out.get("uw_code") or {}).get(i), _um[0], _um[1],
|
||||
_z if _z is not None else total,
|
||||
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
|
||||
(out.get("uw_side") or {}).get(i))))
|
||||
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 时,第二个文件起的定额会整套挂到第一个文件的清单上。
|
||||
# 分部(2026-09-30):**必须排在清单之前** —— 清单要挂 div_id。
|
||||
# parent 存的是本文件内的下标,这里换算成真实 id(与 bill_uw 同一套做法)。
|
||||
div_ids = []
|
||||
for dv_ in (out.get("divides") or []):
|
||||
_p = dv_.get("parent")
|
||||
_pid = div_ids[_p] if (_p is not None and 0 <= _p < len(div_ids)) else None
|
||||
_u = dv_.get("uw", -1)
|
||||
_uid = uw_ids[_u] if 0 <= _u < len(uw_ids) else None
|
||||
cur.execute("""INSERT INTO s_divides(session_id, uw_id, parent_id, Kind,
|
||||
Number, Name, Total, Code, x_seq)
|
||||
VALUES(?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, _uid, _pid, dv_.get("kind"), dv_.get("number"), dv_.get("name"),
|
||||
dv_.get("total"), dv_.get("code"), dv_.get("seq")))
|
||||
div_ids.append(cur.lastrowid)
|
||||
stat["div"] = stat.get("div", 0) + 1
|
||||
|
||||
idx0 = len(bill_ids)
|
||||
buw = out.get("bill_uw") or []
|
||||
bkd = out.get("bill_kind") or []
|
||||
bdv = out.get("bill_div") or []
|
||||
# 2026-09-29 决策 19:序号**分两套** —— 分部分项、措施项目。
|
||||
# 2026-10-10 主人定:**每个单位工程各自从 1 起**(原数据序号=单位工程内序号,
|
||||
# 跨工程连号是错口径),与 import_job.bills 同口径。
|
||||
# 注意这里是**全量占号**(所有入库清单都领号),被 C 区筛掉的行也照占,
|
||||
# 所以界面上会跳号;主人拍板要的就是「号码对得上原件、任何视图下一致」。
|
||||
seq = {"d": 0, "p": 0}
|
||||
_seq_uw = None
|
||||
# 第 5 位 qty = 工程量:会话库是"能核对原件"的完整集,必须入库
|
||||
# bills 元组第 8 位 = 源文件备注(2026-10-08 主人定:只显示在「原数据」备注栏)
|
||||
for i, (num, nm, attr, unit, qty, price, total, srk) in enumerate(out["bills"]):
|
||||
# 2026-09-29:uw_id 由"写死 None"改为按 bill_uw 下标取真实单位工程 id
|
||||
k = buw[i] if i < len(buw) else -1
|
||||
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
|
||||
if k != _seq_uw: # 换单位工程 → 两套计数器归零
|
||||
seq = {"d": 0, "p": 0}
|
||||
_seq_uw = k
|
||||
# 2026-09-29 决策17:措施项目条目标 Kind='prelim'(普通清单为 NULL)
|
||||
kb = bkd[i] if i < len(bkd) else None
|
||||
if kb == "prelim":
|
||||
seq["p"] += 1
|
||||
xseq = seq["p"]
|
||||
else:
|
||||
seq["d"] += 1
|
||||
xseq = seq["d"]
|
||||
_dv = bdv[i] if i < len(bdv) else None
|
||||
divid = div_ids[_dv] if (_dv is not None and 0 <= _dv < len(div_ids)) else None
|
||||
cur.execute("""INSERT INTO s_bills(session_id, uw_id, div_id, Number, Name, Attr, Unit,
|
||||
Quantity, Price, Total, Kind, src_remark,
|
||||
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq,
|
||||
x_price0, x_side, x_ptag)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, uwid, divid, num, nm, attr, unit, qty, price, total, kb, srk,
|
||||
norm(nm), norm(attr), norm(unit),
|
||||
md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq,
|
||||
price, # 决策 217:x_price0=第一次导进来的单价,此后改价/采纳不更新
|
||||
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
|
||||
(out.get("bill_side") or {}).get(i)),
|
||||
((out.get("bill_tag") or [])[i] if i < len(out.get("bill_tag") or []) else None)))
|
||||
# 决策 27(2026-10-10):编码只取前 9 位(后 3 位是项目内顺序码,无对比意义);
|
||||
# 与 history.db.bills(import_job)同口径,启动迁移重算老数据
|
||||
bill_ids.append(cur.lastrowid)
|
||||
stat["bill"] += 1
|
||||
|
||||
# 2026-09-29:补 Quantity / Total(源文件有,此前只写 Price,导致工作台定额子行的
|
||||
# 工程量/合价永远是「—」)。元组顺序:idx, 编码, 名称, 单位, 工程量, 单价, 合价
|
||||
# 定额入库,同时记下真实 id —— 消耗量要靠它挂(norm_res 里存的是本文件内下标)
|
||||
norm_ids = []
|
||||
adj = out.get("norm_adj", {})
|
||||
for norm_idx, (idx, num, nm, unit, qty, price, total) in enumerate(out["norms"]):
|
||||
bid = bill_ids[idx0 + idx] if 0 <= idx < len(out["bills"]) else None
|
||||
vals = adj.get(norm_idx, [])
|
||||
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust, x_side)
|
||||
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))))
|
||||
norm_ids.append(cur.lastrowid)
|
||||
stat["norm"] += 1
|
||||
|
||||
# 2026-09-30:定额消耗量(定额 → 工料机编码 + 消耗量 + 含量算式,补记十二)。
|
||||
# 有这张表才能回答「某个单位工程用了哪些工料机」——以前工料机只能挂到整个会话。
|
||||
# 决策 200(2026-10-25 主人定):同一定额下相同工料机只出一条——消耗量相加。
|
||||
# 后台批次库(import_job.save)落地当天起,会话路径(打开工程/重解析)同步同规则;
|
||||
# 此前只修了批次库,金宝实测 4 组重复重解析后原样(2.53+3.55 等),本段补齐。
|
||||
_nr_agg = {}
|
||||
_nr_order = []
|
||||
for nidx, code, q, express in (out.get("norm_res") or []):
|
||||
k = (nidx, code)
|
||||
if k in _nr_agg:
|
||||
q0, e0 = _nr_agg[k]
|
||||
_nr_agg[k] = (((q0 or 0) + (q or 0)) if (q0 is not None or q is not None) else None,
|
||||
e0 or express)
|
||||
else:
|
||||
_nr_agg[k] = (q, express)
|
||||
_nr_order.append(k)
|
||||
for nidx, code in _nr_order:
|
||||
q, express = _nr_agg[(nidx, code)]
|
||||
nid = norm_ids[nidx] if 0 <= nidx < len(norm_ids) else None
|
||||
cur.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
|
||||
(nid, code, q, express or None))
|
||||
stat["nres"] = stat.get("nres", 0) + 1
|
||||
|
||||
for num, nm, spec, unit, ntp, tax, tp, qty, kind in out["lmes"]:
|
||||
cur.execute("""INSERT INTO s_lmes(session_id, Number, Name, Specification, Unit,
|
||||
Quantity, NoTaxPrice, TaxRate, TaxPrice, Kind,
|
||||
x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, num, nm, spec, unit, qty, ntp, tax, tp, kind,
|
||||
norm(nm), norm(spec), norm(unit), md5(nm, spec, unit), md5(nm, unit)))
|
||||
stat["lme"] += 1
|
||||
|
||||
# 2026-10-11 决策 41:各单位工程**自己的工料机汇总**按 uw 归属原样入库(s_lme_uw),
|
||||
# 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。
|
||||
for _row in (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(原文件有才导)
|
||||
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,))
|
||||
|
||||
# 2026-10-02:机械台班 / 配合比的下一级组成(s_lme_res)
|
||||
_lname = out.get("lme_name") or {}
|
||||
for pcode, subs in (out.get("lme_res") or {}).items():
|
||||
for i, (code, q) in enumerate(subs):
|
||||
if not code:
|
||||
continue
|
||||
_nm = _lname.get(code) or _lname.get(code.split("-")[0]) or None
|
||||
cur.execute("""INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)
|
||||
VALUES(?,?,?,?,?,?)""", (sid, pcode, code, q, i, _nm))
|
||||
stat["lres"] = stat.get("lres", 0) + 1
|
||||
|
||||
# 2026-10-07:项目级工料机资源库(s_lme_lib)——与批次库 lme_lib 同口径,
|
||||
# 源文件汇总节点全集,子目工料机名称/规格的兜底来源
|
||||
for _c, (_nm, _sp, _un, _kd, _ntp, _taxp) in (out.get("lme_lib") or {}).items():
|
||||
cur.execute("""INSERT OR IGNORE INTO s_lme_lib(session_id, code, name, spec, unit, kind, ntp, taxp)
|
||||
VALUES(?,?,?,?,?,?,?,?)""", (sid, _c, _nm, _sp, _un, _kd, _ntp, _taxp))
|
||||
|
||||
# 2026-10-07:项目级工料机汇总(s_lme_proj)——Project.xml 原样入库,
|
||||
# 「原数据 → 工料机汇总」项目级读这里(与原版软件同源)
|
||||
for _c, v in (out.get("lme_proj") or {}).items():
|
||||
_nm, _sp, _un, _kd, _q, _ntp, _taxp = v[0], v[1], v[2], v[3], v[4], v[5], v[6]
|
||||
_rate = v[7] if len(v) > 7 else None # 决策 69:TaxRate 采集(合并弹框税率字段)
|
||||
_x = (v[8:12] + [None] * 4)[:4] # 决策 183:六价全采(属性级对应回填)
|
||||
cur.execute("""INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp, taxrate,
|
||||
ntp_org, ntp_expr, taxp_org, taxp_expr)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp, _rate) + tuple(_x))
|
||||
# 决策 251(2026-11-01 主人定,取代 219 锚取值):采纳备注「+旧价」锚=**导入时项目级
|
||||
# 三价快照**(灌库那一刻 s_lme_proj 的 ntp/taxrate/taxp,写入后冻结——合并/重放/映射源
|
||||
# 落位都不再写锚列,227 改价失效链取消,改价/再采纳永不漂)。
|
||||
# 注意:ntp_org/taxp_org(决策 183)会被映射源落位/合并重放改写,不是冻结的导入价,
|
||||
# 故锚用专用列不用 _org。合并生成的行无锚(NULL)→采纳备注退改前现值(前端兜底)。
|
||||
cur.execute("""UPDATE s_lme_proj SET
|
||||
x_ntp0=ntp, x_rate0=taxrate, x_taxp0=taxp
|
||||
WHERE session_id=?""", (sid,))
|
||||
# 这几样都要**解析完**才知道(sessions 行在解析之前就插好了),所以这里补一笔
|
||||
if ptotal is not None or pinfo or pfeat or pside:
|
||||
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=?, x_side=? WHERE id=?",
|
||||
(ptotal,
|
||||
json.dumps(pinfo, ensure_ascii=False) if pinfo else None,
|
||||
json.dumps([{"n": n, "v": v} for n, v in pfeat], ensure_ascii=False) if pfeat else None,
|
||||
json.dumps(pside, ensure_ascii=False) if pside else None,
|
||||
sid))
|
||||
stat["total"] = ptotal
|
||||
stat["feat"] = len(pfeat or [])
|
||||
# 2026-09-30:s_bills 刚被重写(id 全新),把持久备注按 rkey 填回去
|
||||
stat["remark"] = restore_remarks(con, sid)
|
||||
stat["lremark"] = restore_lme_remarks(con, sid) # 工料机采纳备注按 rkey 回填(2026-10-08)
|
||||
con.commit()
|
||||
return sid, stat
|
||||
|
||||
|
||||
@@ -1,436 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""格式无关骨架引擎(决策 262,2026-11-03 主人定「引擎写活了,后期还有很多后缀」)。
|
||||
|
||||
口径(主人逐条定 + 实件勘察结论):
|
||||
· **后缀不参与拦截**:能不能用由**内容**判定——zip 内 XML(cos/cos4 型)/ 裸 XML(swt/swz 型)。
|
||||
后期新后缀(st/uuy…)只要是这两种之一,零代码接入。
|
||||
· **唯一结构位** = (父路径, 标签, 列集):三者相同即同一结构位,只留 1 个样板;值全清空(卡槽)。
|
||||
· **子节点取并集**:同一结构位的子节点按身份合并(递归);自嵌套按实件最大深度保留有限层。
|
||||
· **区域/自增块/自增行**不是三种标签,而是同一套结构位的三种出现形态:
|
||||
区域=全实件恒 1 次;自增块=容器重复;自增行=自闭合行重复。
|
||||
· **次数不进骨架**:骨架只给结构+列序,重复次数由数据条数决定(0 条不输出)。
|
||||
|
||||
实测(2026-11-03):cos4 9507→131、cos 25581→73、swt 463→38、swz 185→37 个唯一结构位。
|
||||
"""
|
||||
import copy
|
||||
import io
|
||||
import zipfile
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 一、格式族判定(按内容,不按后缀)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
FAMILY_ZIP = "zip" # zip 容器 + 若干 XML 成员(主文件 + 单位工程成员)
|
||||
FAMILY_RAW = "raw" # 裸 XML 单文件(单位工程内嵌)
|
||||
|
||||
|
||||
def family_of(blob):
|
||||
"""字节 → FAMILY_ZIP / FAMILY_RAW / None(加密壳、二进制、坏件一律 None)。"""
|
||||
if not blob:
|
||||
return None
|
||||
if blob[:2] == b"PK":
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
||||
for nm in z.namelist():
|
||||
if nm.lower().endswith(".xml"):
|
||||
try:
|
||||
ET.fromstring(z.read(nm))
|
||||
return FAMILY_ZIP
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
head = blob[:6].lstrip()
|
||||
if head[:5].lower().startswith(b"<?xml") or head[:1] == b"<":
|
||||
try:
|
||||
ET.fromstring(blob)
|
||||
return FAMILY_RAW
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _decode_bytes(raw):
|
||||
"""按声明解码,声明缺失/错时退 utf-8、gb18030。返回 (bytes, encoding)。"""
|
||||
import re
|
||||
m = re.match(rb'(?:\xef\xbb\xbf|\s)*<\?xml[^>]*encoding="([^"]+)"', raw[:300])
|
||||
enc = m.group(1).decode("ascii", "ignore") if m else "utf-8"
|
||||
for e in (enc, "utf-8", "gb18030"):
|
||||
try:
|
||||
raw.decode(e)
|
||||
return raw, e
|
||||
except Exception:
|
||||
continue
|
||||
return raw, "utf-8"
|
||||
|
||||
|
||||
def parse_root(raw):
|
||||
"""字节 → (根元素, 声明文本)。保留注释节点(原文件有才保留,引擎不造)。"""
|
||||
import re
|
||||
blob, _enc = _decode_bytes(raw)
|
||||
text = blob.decode(_enc, errors="replace")
|
||||
m = re.match(r"\s*<\?xml[^>]*\?>", text)
|
||||
decl = m.group(0) if m else '<?xml version="1.0" encoding="utf-8"?>'
|
||||
body = text[m.end():] if m else text
|
||||
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
|
||||
return ET.fromstring(body, parser=parser), decl
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 二、唯一结构收敛(本次核心)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _key(el):
|
||||
return (el.tag, tuple(sorted(el.attrib.keys())))
|
||||
|
||||
|
||||
# 骨架只给格式(列集 + 每层是否自增);**所有值来自数据库**,骨架一个值都不带。
|
||||
# 主人 2026-11-03 定:「骨架只管导出格式及是不是自增行」——单价行/管理费/费用构成
|
||||
# 这些值全部随导入进库(s_bills/s_norms 的 x_side),导出时有几行出几行。
|
||||
_DATA_TAGS = set()
|
||||
|
||||
_ZERO_RULES = {}
|
||||
|
||||
|
||||
def _copy_fixed(c):
|
||||
"""(保留占位)固定结构节点深拷贝。"""
|
||||
return copy.deepcopy(c)
|
||||
|
||||
|
||||
def collapse_into(node, el):
|
||||
"""把源元素 el 的子结构并入样板 node:同身份合并、子节点递归取并集、值清空。"""
|
||||
seen = {}
|
||||
for k in node:
|
||||
if isinstance(k.tag, str):
|
||||
seen[_key(k)] = k
|
||||
for c in el:
|
||||
if not isinstance(c.tag, str): # 注释:原样保留一次
|
||||
if not any(isinstance(k.tag, type(c.tag)) and k.text == c.text for k in node):
|
||||
node.append(c)
|
||||
continue
|
||||
key = _key(c)
|
||||
sub = seen.get(key)
|
||||
if sub is None:
|
||||
sub = ET.SubElement(node, c.tag)
|
||||
for a in c.attrib: # 列序=首次出现序,值=空卡槽
|
||||
sub.set(a, "")
|
||||
seen[key] = sub
|
||||
collapse_into(sub, c)
|
||||
return node
|
||||
|
||||
|
||||
def collapse(root):
|
||||
"""整树 → 唯一结构位树(每个结构位只出现一次,值全空)。"""
|
||||
out = ET.Element(root.tag)
|
||||
for a in root.attrib:
|
||||
out.set(a, "")
|
||||
collapse_into(out, root)
|
||||
return out
|
||||
|
||||
|
||||
def paths_of(root):
|
||||
"""→ {路径字符串: 出现次数};路径=根到该元素的标签链('A/B/C')。"""
|
||||
out = {}
|
||||
stack = [(root, root.tag)]
|
||||
while stack:
|
||||
el, p = stack.pop()
|
||||
out[p] = out.get(p, 0) + 1
|
||||
for c in el:
|
||||
if isinstance(c.tag, str):
|
||||
stack.append((c, p + "/" + c.tag))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 三、结构旁注(sidecar):哪些层是清单/定额/工料机/单位工程
|
||||
# 判定只看结构(重复次数+嵌套关系),不看标签名——新后缀零配置。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _attrs_by_path(roots):
|
||||
"""→ {路径: 列集}(只取出现过的属性名,不看值)。"""
|
||||
out = {}
|
||||
for r in roots:
|
||||
stack = [(r, r.tag)]
|
||||
while stack:
|
||||
el, p = stack.pop()
|
||||
s = out.setdefault(p, set())
|
||||
s.update(el.attrib.keys())
|
||||
for c in el:
|
||||
if isinstance(c.tag, str):
|
||||
stack.append((c, p + "/" + c.tag))
|
||||
return out
|
||||
|
||||
|
||||
def derive_meta(roots, unit_tag=None):
|
||||
"""多份实件根 → {'v':1,'paths':{path:count},'roles':{...}}。
|
||||
角色判定只用**结构 + 属性名**(不看标签名、不看后缀),顺序:
|
||||
①工料机行=重复的自闭合叶行里,属性同时有"数量"和"编号/代码"、次数最多者;
|
||||
②定额=工料机行的父节点(父是壳也照取——壳在清单层再跳);
|
||||
③清单=从定额往上最近的非壳容器(壳=只有一个子标签的容器);
|
||||
④分部=清单上方能重复的容器;⑤单位=根标签里出现最多的那个(zip 族=单位成员根)。
|
||||
认结构(清单→定额→工料机三层嵌套)的格式适用;数据模型不同的族(如 SWT 工料机是
|
||||
独立表、不挂在定额下)只认得出部分角色,导出端会回退旧引擎——这是适配器边界。"""
|
||||
counts = {}
|
||||
for r in roots:
|
||||
for p, n in paths_of(r).items():
|
||||
counts[p] = counts.get(p, 0) + n
|
||||
attrs = _attrs_by_path(roots)
|
||||
parent = {p: p.rsplit("/", 1)[0] for p in counts if "/" in p}
|
||||
has_kid = {p: False for p in counts}
|
||||
for p in counts:
|
||||
if p in parent:
|
||||
has_kid[parent[p]] = True
|
||||
|
||||
def kids(p):
|
||||
return [q for q in counts if parent.get(q) == p]
|
||||
|
||||
def is_shell(p):
|
||||
return len({q.rsplit("/", 1)[-1] for q in kids(p)}) == 1
|
||||
|
||||
colset = lambda p: {a.lower() for a in attrs.get(p, ())}
|
||||
|
||||
def is_norm_like(p):
|
||||
"""定额样:有 名称/单位/数量/单价(Price 或 Rate 精确名,不用 NoTaxPrice 这类)。"""
|
||||
c = colset(p)
|
||||
return {"name", "unit", "quantity"} <= c and (("price" in c) or ("rate" in c))
|
||||
|
||||
# ① 工料机行="定额样"节点的子行(数量+编号),次数最大者;避免把汇总表当定额
|
||||
rows = [p for p in counts
|
||||
if counts[p] >= 2 and not has_kid[p]
|
||||
and "quantity" in colset(p) and ({"number", "code"} & colset(p))
|
||||
and is_norm_like(parent.get(p, ""))]
|
||||
lme = max(rows, key=lambda p: counts[p]) if rows else None
|
||||
# ② 定额 = 工料机行父节点
|
||||
norm = parent.get(lme) if lme else None
|
||||
# ③ 清单 = 从定额往上最近的非壳容器
|
||||
bill = None
|
||||
p = parent.get(norm) if norm else None
|
||||
while p:
|
||||
if has_kid[p] and not is_shell(p):
|
||||
bill = p
|
||||
break
|
||||
p = parent.get(p)
|
||||
# ④ 分部 = 清单上方能重复的容器
|
||||
div = None
|
||||
p = parent.get(bill) if bill else None
|
||||
while p:
|
||||
if counts.get(p, 0) >= 2 and not is_shell(p):
|
||||
div = p
|
||||
break
|
||||
p = parent.get(p)
|
||||
# ⑤ 单位 = 调用方指定的单位根(zip 族=单位成员根);否则取出现最多的根标签
|
||||
from collections import Counter
|
||||
roots_cnt = Counter(r.tag for r in roots)
|
||||
unit = unit_tag or (roots_cnt.most_common(1)[0][0] if roots_cnt else None)
|
||||
# 单位级工料机汇总行:单位之下、不在清单/定额链上、重复的自闭合叶行
|
||||
lme_sum = None
|
||||
if unit:
|
||||
sub = [q for q in counts
|
||||
if q.startswith(unit + "/") and counts[q] >= 2 and not has_kid[q]
|
||||
and not (norm and q.startswith(norm))]
|
||||
lme_sum = max(sub, key=lambda q: counts[q]) if sub else None
|
||||
return {"v": 1, "paths": counts,
|
||||
"roles": {"unit": unit, "bill": bill, "div": div,
|
||||
"norm": norm, "lme": lme, "lme_sum": lme_sum}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 四、分层列集指纹与匹配度(字段越像分越高 + 区域越像分越高)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def layer_cols(roots):
|
||||
"""多份实件根 → {'v':2,'p':{路径:[列名…]}}(每层列集并集,首见列序)。"""
|
||||
out = {}
|
||||
for r in roots:
|
||||
stack = [(r, r.tag)]
|
||||
while stack:
|
||||
el, p = stack.pop()
|
||||
cols = out.setdefault(p, [])
|
||||
for a in el.attrib:
|
||||
if a not in cols:
|
||||
cols.append(a)
|
||||
for c in el:
|
||||
if isinstance(c.tag, str):
|
||||
stack.append((c, p + "/" + c.tag))
|
||||
return {"v": 2, "p": out}
|
||||
|
||||
|
||||
def _finger_paths(fp):
|
||||
"""兼容新旧两种指纹 → {path: set(cols)}。旧= {tag:[...]};新= {'v':2,'p':{path:[...]}}。"""
|
||||
if not isinstance(fp, dict):
|
||||
return {}
|
||||
if fp.get("v") == 2 and isinstance(fp.get("p"), dict):
|
||||
return {k: set(v) for k, v in fp["p"].items()}
|
||||
return {k: set(v) for k, v in fp.items() if isinstance(v, (list, tuple, set))}
|
||||
|
||||
|
||||
def _root_path(paths):
|
||||
for p in paths:
|
||||
if "/" not in p:
|
||||
return p, paths[p]
|
||||
return None, set()
|
||||
|
||||
|
||||
def match_score(src_fp, skel_fp):
|
||||
"""0~100:字段匹配(同层列集重合,根层权重最高)+ 区域匹配(骨架的结构区域在原件里有没有)。
|
||||
根标签不同=不同格式族,直接压低到 10 分以下。"""
|
||||
src = _finger_paths(src_fp)
|
||||
skel = _finger_paths(skel_fp)
|
||||
if not src or not skel:
|
||||
return 0.0
|
||||
sroot, scols = _root_path(src)
|
||||
kroot, kcols = _root_path(skel)
|
||||
if sroot != kroot:
|
||||
return 10.0 * (len(scols & kcols) / max(1, len(scols | kcols)))
|
||||
# 字段:逐层 Jaccard,根层×3、二三层×2、其余×1
|
||||
num = den = 0.0
|
||||
for p, cols in skel.items():
|
||||
if p not in src:
|
||||
continue
|
||||
depth = p.count("/")
|
||||
w = 3.0 if depth == 0 else (2.0 if depth <= 2 else 1.0)
|
||||
num += w * len(cols & src[p]) / max(1, len(cols | src[p]))
|
||||
den += w
|
||||
field = (num / den * 100.0) if den else 0.0
|
||||
# 区域:骨架里出现过的结构位,原件里覆盖多少(只看骨架,不看原件多出来的)
|
||||
cover = sum(1 for p in skel if p in src) / max(1, len(skel))
|
||||
return round(field * 0.65 + cover * 100.0 * 0.35, 2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 五、从实件提炼空骨架(主驱动:family 判定,不看后缀)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _members(blob):
|
||||
"""→ [(成员名, 字节)];裸 XML 时 → [('(single)', blob)]。"""
|
||||
if family_of(blob) == FAMILY_ZIP:
|
||||
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
||||
return [(nm, z.read(nm)) for nm in z.namelist() if nm.lower().endswith(".xml")]
|
||||
return [("(single)", blob)]
|
||||
|
||||
|
||||
def split_roots(blob):
|
||||
"""→ (主根列表, 单位根列表, family)。zip:单位根=多数成员根标签;raw:整件即主根。
|
||||
单位工程判定不靠标签名,靠"同一个根标签在多个成员里重复出现"。"""
|
||||
fam = family_of(blob)
|
||||
if fam is None:
|
||||
return [], [], None
|
||||
members = _members(blob)
|
||||
roots = []
|
||||
for nm, raw in members:
|
||||
try:
|
||||
r, _d = parse_root(raw)
|
||||
except Exception:
|
||||
continue
|
||||
roots.append((nm, r))
|
||||
if fam == FAMILY_RAW:
|
||||
return [r for _n, r in roots], [], fam
|
||||
# zip:根标签计数,出现 ≥2 次的当单位成员
|
||||
from collections import Counter
|
||||
cnt = Counter(r.tag for _n, r in roots)
|
||||
unit_tag = None
|
||||
for t, n in cnt.most_common():
|
||||
if n >= 2:
|
||||
unit_tag = t
|
||||
break
|
||||
if unit_tag is None and len(roots) > 1:
|
||||
unit_tag = cnt.most_common()[-1][0]
|
||||
units = [r for _n, r in roots if r.tag == unit_tag]
|
||||
mains = [r for _n, r in roots if r.tag != unit_tag]
|
||||
if not mains:
|
||||
mains = [roots[0][1]]
|
||||
units = [r for _n, r in roots[1:]]
|
||||
return mains, units, fam
|
||||
|
||||
|
||||
def build_blank(blob, ind_unit=" "):
|
||||
"""实件 → (空骨架单 XML 文本, meta)。meta 给导出用(角色路径)。
|
||||
zip 族:主文件骨架 + 首条单位索引行内嵌单位骨架(连接展示);
|
||||
raw 族:整件收敛。两种家族同一个收敛器,零后缀配置。"""
|
||||
mains, units, fam = split_roots(blob)
|
||||
if fam is None or not mains:
|
||||
return None, None
|
||||
main = collapse(mains[0])
|
||||
if not units:
|
||||
roots_for_meta = mains
|
||||
text = _serialize(main, ind_unit)
|
||||
return text, derive_meta(roots_for_meta)
|
||||
unit_best = max(units, key=lambda r: len(list(r.iter())))
|
||||
unit = collapse(unit_best)
|
||||
# 2026-11-04 决策267:单位骨架取**全成员并集**——只取一个成员会丢别的成员才有的
|
||||
# 层/列(实测:本项目分部 13 列、某个成员只有 7 列,导致导出丢列)。值仍为空。
|
||||
for _u in units:
|
||||
if _u is unit_best:
|
||||
continue
|
||||
try:
|
||||
collapse_into(unit, collapse(_u))
|
||||
except Exception:
|
||||
continue
|
||||
# 连接:主骨架里第一条带 FileName 的索引行 → 换成单位骨架
|
||||
placed = False
|
||||
for par in main.iter():
|
||||
for k in list(par):
|
||||
if not isinstance(k.tag, str):
|
||||
continue
|
||||
if "FileName" in k.attrib:
|
||||
idx = list(par).index(k)
|
||||
par.remove(k)
|
||||
par.insert(idx, unit)
|
||||
placed = True
|
||||
break
|
||||
if placed:
|
||||
break
|
||||
if not placed:
|
||||
# 退化样例(Project.xml 没有单位索引行):单位骨架直接挂主根,导出端仍能按它建成员
|
||||
main.append(unit)
|
||||
text = _serialize(main, ind_unit)
|
||||
meta = derive_meta(mains + units, unit_tag=unit_best.tag)
|
||||
# 决策 264:记下被替换掉的**索引行**(导出时按它复制成 N 行),否则项目索引无法还原
|
||||
meta["index_row"] = {"tag": None, "attrs": []}
|
||||
for par in collapse(mains[0]).iter():
|
||||
for k in par:
|
||||
if isinstance(k.tag, str) and "FileName" in k.attrib:
|
||||
meta["index_row"] = {"tag": k.tag, "attrs": list(k.attrib.keys())}
|
||||
break
|
||||
else:
|
||||
continue
|
||||
break
|
||||
return text, meta
|
||||
|
||||
|
||||
def _ind_unit(root):
|
||||
"""缩进单位:优先从实件文本锚定(4 空格常见);此处按层给 4 空格,
|
||||
真实缩进由 refine_blank 传入的件锚定(见 classic_skeleton._blank_ind_unit)。"""
|
||||
return " "
|
||||
|
||||
|
||||
def serialize(el, depth=0, ind=" ", keep_values=False, first=True, note_fn=None):
|
||||
"""唯一结构位树 → 文本行(一行一层、叶自闭合、无空行)。
|
||||
属性值按 XML 规则转义(数据里的 & < > " 会原样出现,不转义整件就坏)。
|
||||
note_fn(el)→字符串:在开标签后追加 XML 注释(骨架库「空骨架+导出规则标注」用)。"""
|
||||
pad = "" if first else "\n" + ind * depth
|
||||
if keep_values:
|
||||
from xml.sax.saxutils import escape
|
||||
attrs = "".join(' %s="%s"' % (k, escape(str(v), {'"': """}))
|
||||
for k, v in el.attrib.items())
|
||||
else:
|
||||
attrs = "".join(' %s=""' % k for k, _ in el.attrib.items())
|
||||
kids = [k for k in el if isinstance(k.tag, str)]
|
||||
note = note_fn(el) if note_fn else ""
|
||||
note = ("<!-- %s -->" % str(note).replace("--", "-")) if note else ""
|
||||
out = [pad + "<" + el.tag + attrs]
|
||||
if not kids:
|
||||
out[0] += " />" + note
|
||||
return "".join(out)
|
||||
out[0] += ">" + note
|
||||
for k in kids:
|
||||
out.append(serialize(k, depth + 1, ind, keep_values, first=False, note_fn=note_fn))
|
||||
out.append("\n" + ind * depth + "</" + el.tag + ">")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _serialize(root, ind=" ", keep_values=False):
|
||||
decl = '<?xml version="1.0" encoding="utf-8"?>'
|
||||
return decl + "\n" + serialize(root, 0, ind, keep_values) + "\n"
|
||||
@@ -1,18 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""无窗口启动后台服务(2026-10-07):双击 启动造价审核.bat 弹软件窗口时用的是 launch.py;
|
||||
这个入口只起 HTTP 服务本身,不弹窗、不开浏览器 —— 给"服务已在运行但要换新代码"的场景用。
|
||||
用法:python run_server_headless.py (Ctrl+C 或结束进程 = 停服务)
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
APP = os.path.dirname(os.path.abspath(__file__))
|
||||
os.chdir(APP)
|
||||
sys.path.insert(0, APP)
|
||||
for sub in ("server", "core"):
|
||||
sys.path.insert(0, os.path.join(APP, sub))
|
||||
|
||||
import api_server
|
||||
|
||||
if __name__ == "__main__":
|
||||
api_server.run()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,10 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""授权平台客户端(license-v2 / lease-v2)。
|
||||
|
||||
api_server 只 import license_client.gate 这一个入口:
|
||||
import license_client.gate as license_gate
|
||||
license_gate.init(DATA_DIR) # run() 启动时
|
||||
license_gate.intercept(method, path, body) # do_GET / do_POST 顶部
|
||||
业务侧判定用 client.can_run_safe()(门禁内部已用,业务代码一般不必再调)。
|
||||
"""
|
||||
from .client import LicenseClient, DEFAULT_API_BASE # noqa: F401
|
||||
@@ -1,475 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""LicenseClient:激活 + 心跳租约 + 本地 can_run 状态机。
|
||||
|
||||
协议硬性口径(protocol.md / prompt.md):
|
||||
- 激活、心跳都必须带 Idempotency-Key;同一次操作的网络重试复用同一键与同一
|
||||
请求体(心跳复用原 client_time,不得改时间续用原键);新业务操作才换新键。
|
||||
→ 在途操作键先落盘再发请求,进程重启也能复用。
|
||||
- 403/409 等确定性拒绝:停止自动重试,转入人工处理(needs_attention)。
|
||||
- 429:至少等 Retry-After;超时/连接错误/5xx:有界退避,键与请求体不变。
|
||||
- 仅 active 且授权到期、租约到期都严格晚于 now 才允许业务;租约结束不得晚于
|
||||
授权结束、不得晚于 server_time + 14 天;本机与服务端时差 ≤ 5 分钟;
|
||||
本地/服务端两个时间高水位只进不退,落盘原子更新,失败即 fail closed。
|
||||
- secret 不进 URL、日志、异常文本。网络失败不得延长已接受的租约(can_run
|
||||
纯本地判定,心跳失败只会让租约自然到期)。
|
||||
|
||||
httpx 为可选依赖:只在真正发请求时导入;无网络库时 can_run/状态读取照常工作。
|
||||
"""
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
import uuid as uuid_mod
|
||||
from datetime import timedelta
|
||||
|
||||
try:
|
||||
from .verify import (VerifyError, verify_certificate, verify_lease,
|
||||
parse_rfc3339, rfc3339, entitlements)
|
||||
from .store import StorageError
|
||||
except ImportError as _e:
|
||||
# 只对"相对导入不可用"退裸导入;包内真实依赖缺失(如 cryptography)必须原样抛出,
|
||||
# 否则真实病因会被掩盖成 "No module named 'verify'" 指错排查方向(2026-10-11 实证踩坑)
|
||||
if "attempted relative import" not in str(_e):
|
||||
raise
|
||||
from verify import (VerifyError, verify_certificate, verify_lease,
|
||||
parse_rfc3339, rfc3339, entitlements)
|
||||
from store import StorageError
|
||||
|
||||
DEFAULT_API_BASE = "https://license.yihuiyong.cn"
|
||||
MIN_HEARTBEAT_SECONDS = 60 # 协议:成功 active 心跳最短间隔 60 秒
|
||||
MAX_LEASE_DAYS = 14 # 协议:租约最长 14 天
|
||||
MAX_CLOCK_SKEW = timedelta(minutes=5)
|
||||
|
||||
NEED_ATTENTION = ("HTTP_400", "HTTP_401", "HTTP_403", "HTTP_409")
|
||||
|
||||
|
||||
class TransientError(Exception):
|
||||
"""暂时性网络失败(重试额度用尽)。在途操作键保留,稍后可继续。"""
|
||||
|
||||
|
||||
class LeaseInvalid(VerifyError):
|
||||
"""租约通过验签但范围非法(租约窗/14 天上限)。"""
|
||||
|
||||
|
||||
class LicenseClient:
|
||||
def __init__(self, api_base, state_store, secret_store, keyring,
|
||||
now_fn=None, sleep_fn=time.sleep, transport=None,
|
||||
max_attempts=4, timeout=15,
|
||||
expected_product_id=None, cache_ttl=10.0, mono_fn=None):
|
||||
self.api_base = (api_base or DEFAULT_API_BASE).rstrip("/")
|
||||
self.state_store = state_store
|
||||
self.secret_store = secret_store
|
||||
self.keyring = keyring or {}
|
||||
self.expected_product_id = expected_product_id # None = 不校验产品线
|
||||
self.now_fn = now_fn or (lambda: __import__("datetime").datetime.now(
|
||||
__import__("datetime").timezone.utc))
|
||||
self.mono_fn = mono_fn or time.monotonic
|
||||
self.cache_ttl = cache_ttl # can_run 结果缓存(0=关)
|
||||
self.sleep_fn = sleep_fn
|
||||
self.max_attempts = max(1, max_attempts)
|
||||
self.timeout = timeout
|
||||
self._send_fn = transport or self._httpx_send
|
||||
self._http = None
|
||||
self._op_lock = threading.RLock() # 状态读改写串行(心跳线程 × 请求线程)
|
||||
self._hb_lock = threading.Lock() # 心跳整体串行(循环/自愈/手动 refresh 并发)
|
||||
self._cr_cache = None # (ok, reason, 过期时刻)——门禁每请求一调,省验签+写盘
|
||||
|
||||
# ------------------------------------------------------------ 凭据
|
||||
|
||||
def has_credentials(self):
|
||||
try:
|
||||
st = self.state_store.load()
|
||||
return bool(st.get("instance_id") and st.get("license_key")
|
||||
and self.secret_store.get())
|
||||
except StorageError:
|
||||
return False
|
||||
|
||||
def configure(self, instance_id, license_key, secret):
|
||||
"""写入交付凭据:secret → 受保护密钥库;其余 → 状态文件。先密钥库后状态。"""
|
||||
instance_id = (instance_id or "").strip()
|
||||
license_key = (license_key or "").strip()
|
||||
secret = (secret or "").strip()
|
||||
if not (instance_id and license_key and secret):
|
||||
raise VerifyError("instance_id / license_key / secret 都必填")
|
||||
self.secret_store.set(secret)
|
||||
def mut(st):
|
||||
st["instance_id"] = instance_id
|
||||
st["license_key"] = license_key
|
||||
st.setdefault("status", "unactivated")
|
||||
st["last_error"] = ""
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
|
||||
def _creds(self):
|
||||
st = self.state_store.load()
|
||||
iid = st.get("instance_id")
|
||||
lk = st.get("license_key")
|
||||
sec = self.secret_store.get() if iid else None
|
||||
if not (iid and lk and sec):
|
||||
raise VerifyError("缺少实例凭据(instance_id / license_key / secret)")
|
||||
return st, iid, lk, sec
|
||||
|
||||
# ------------------------------------------------------------ 激活
|
||||
|
||||
def activate(self):
|
||||
"""首次激活。返回 {"ok": bool, ...};网络暂时失败时幂等键已保留,重试复用。"""
|
||||
st, iid, lk, sec = self._creds()
|
||||
with self._op_lock:
|
||||
st = self.state_store.load()
|
||||
op = st.get("activation_op")
|
||||
if not op:
|
||||
op = {"key": str(uuid_mod.uuid4())}
|
||||
self.state_store.update(lambda s: s.update({"activation_op": op}))
|
||||
body = {"license_key": lk, "secret": sec}
|
||||
try:
|
||||
status, headers, data = self._send_with_retry(
|
||||
"/api/v1/activation/instances/%s" % iid, body, op["key"])
|
||||
except TransientError as e:
|
||||
return {"ok": False, "code": "TRANSIENT",
|
||||
"message": "网络暂时不可用(激活幂等键已保留,重试会复用同一键):%s" % e}
|
||||
if status != 200:
|
||||
self._clear_op("activation_op")
|
||||
code, msg = _err_body(data)
|
||||
human = {400: "激活参数被拒绝(%s)" % (msg or code),
|
||||
401: "license_key 或 secret 不正确,请核对交付凭据",
|
||||
403: "实例不允许激活(%s)" % (msg or code),
|
||||
409: "实例状态冲突,不能重复激活(%s),请核对实例状态或联系管理员"
|
||||
% (msg or code)}.get(status, "激活被拒绝(HTTP %s %s)" % (status, msg or code))
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": code or ("HTTP_%d" % status), "message": human}
|
||||
cert = (data.get("data") or {}).get("certificate")
|
||||
try:
|
||||
payload = verify_certificate(cert, iid, self.keyring)
|
||||
except VerifyError as e:
|
||||
self._clear_op("activation_op")
|
||||
human = "激活证书验签失败:%s(请核对 pinned_keys.json 是否为部署环境交付的生产公钥)" % e
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": "VERIFY_FAILED", "message": human}
|
||||
if self.expected_product_id is not None and \
|
||||
payload.get("product_id") != self.expected_product_id:
|
||||
self._clear_op("activation_op")
|
||||
human = ("证书产品线不符(证书 product_id=%s,本软件要求 %s)——"
|
||||
"多半是凭据发错了产品,请核对交付" % (payload.get("product_id"),
|
||||
self.expected_product_id))
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": "PRODUCT_MISMATCH", "message": human}
|
||||
def mut(s):
|
||||
s["certificate"] = payload
|
||||
s["certificate_envelope"] = cert
|
||||
s["status"] = "activated"
|
||||
s.pop("activation_op", None)
|
||||
s["last_error"] = ""
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
self._cr_cache = None # 新证书 → 门禁缓存作废
|
||||
return {"ok": True}
|
||||
|
||||
# ------------------------------------------------------------ 心跳
|
||||
|
||||
def heartbeat(self):
|
||||
"""刷新运行租约。成功返回 {"ok":True,"state":...,"next":秒}。
|
||||
整体串行:心跳循环 / 门禁自愈 / 手动刷新 三方并发时排队,杜绝两个在途操作
|
||||
互相覆盖 heartbeat_op(幂等键错乱)。"""
|
||||
with self._hb_lock:
|
||||
return self._heartbeat_locked()
|
||||
|
||||
def _heartbeat_locked(self):
|
||||
st, iid, _lk, sec = self._creds()
|
||||
with self._op_lock:
|
||||
st = self.state_store.load()
|
||||
op = st.get("heartbeat_op")
|
||||
if not op:
|
||||
op = {"key": str(uuid_mod.uuid4()), "client_time": rfc3339(self.now_fn())}
|
||||
self.state_store.update(lambda s: s.update({"heartbeat_op": op}))
|
||||
body = {"secret": sec, "client_time": op["client_time"]}
|
||||
try:
|
||||
status, headers, data = self._send_with_retry(
|
||||
"/api/v1/instances/%s/heartbeat" % iid, body, op["key"])
|
||||
except TransientError as e:
|
||||
return {"ok": False, "code": "TRANSIENT",
|
||||
"message": "网络暂时不可用(键与 client_time 已保留,重试复用):%s" % e}
|
||||
if status != 200:
|
||||
self._clear_op("heartbeat_op")
|
||||
code, msg = _err_body(data)
|
||||
human = {400: "心跳参数被拒绝(%s)" % (msg or code),
|
||||
401: "实例凭据已被拒(secret 不正确或已重置),需重新交付凭据",
|
||||
403: "实例被禁止心跳(%s)" % (msg or code),
|
||||
409: "实例状态冲突(%s),需人工处理" % (msg or code)}.get(
|
||||
status, "心跳被拒绝(HTTP %s %s)" % (status, msg or code))
|
||||
if status in (400, 401, 403, 409):
|
||||
self.state_store.update(lambda s: s.update(
|
||||
{"status": "needs_attention", "last_error": human}))
|
||||
return {"ok": False, "code": code or ("HTTP_%d" % status), "message": human}
|
||||
env = data.get("data")
|
||||
try:
|
||||
payload = verify_lease(env, iid, self.keyring)
|
||||
except VerifyError as e:
|
||||
self._clear_op("heartbeat_op")
|
||||
human = "租约验签失败:%s(请核对 pinned_keys.json)" % e
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": "VERIFY_FAILED", "message": human}
|
||||
try:
|
||||
nxt = self._accept_lease(payload, env)
|
||||
except VerifyError as e:
|
||||
self._clear_op("heartbeat_op")
|
||||
self._set_last_error("租约范围非法:%s" % e)
|
||||
return {"ok": False, "code": "LEASE_INVALID",
|
||||
"message": "租约范围非法:%s" % e}
|
||||
return {"ok": True, "state": payload["state"], "next": nxt}
|
||||
|
||||
def _accept_lease(self, payload, envelope):
|
||||
"""验签通过后先做范围检查,再原子落盘(enabled 随租约状态翻转)。"""
|
||||
server = parse_rfc3339(payload["server_time"])
|
||||
ent = parse_rfc3339(payload["entitlement_expires_at"])
|
||||
le = parse_rfc3339(payload["lease_expires_at"])
|
||||
if le > ent:
|
||||
raise LeaseInvalid("租约结束晚于授权结束")
|
||||
if le > server + timedelta(days=MAX_LEASE_DAYS):
|
||||
raise LeaseInvalid("租约超过服务端签发时间 + %d 天" % MAX_LEASE_DAYS)
|
||||
def mut(s):
|
||||
# 服务端时间高水位:只进不退。回退 = 可疑(重放/旧信封),整体拒绝
|
||||
hw = s.get("server_high_water")
|
||||
if hw and server < parse_rfc3339(hw):
|
||||
raise LeaseInvalid("服务端时间早于已记录的高水位")
|
||||
s["server_high_water"] = payload["server_time"] if (
|
||||
not hw or server > parse_rfc3339(hw)) else hw
|
||||
s["lease"] = payload
|
||||
s["lease_envelope"] = envelope
|
||||
s["enabled"] = (payload["state"] == "active")
|
||||
s["status"] = "activated"
|
||||
s.pop("heartbeat_op", None)
|
||||
s["last_heartbeat_at"] = rfc3339(self.now_fn())
|
||||
s["next_heartbeat_seconds"] = max(MIN_HEARTBEAT_SECONDS,
|
||||
envelope.get("next_heartbeat_seconds",
|
||||
MIN_HEARTBEAT_SECONDS))
|
||||
s["last_error"] = ""
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
self._cr_cache = None # 新租约 → 门禁缓存作废
|
||||
return max(MIN_HEARTBEAT_SECONDS, envelope.get("next_heartbeat_seconds",
|
||||
MIN_HEARTBEAT_SECONDS))
|
||||
|
||||
# ------------------------------------------------------------ can_run
|
||||
|
||||
def can_run(self, now=None):
|
||||
"""(True, None) | (False, 原因)。纯本地判定,不发网络请求。
|
||||
结果缓存 cache_ttl 秒:门禁每个请求都调这里,省掉每次的 ECDSA 验签 +
|
||||
高水位落盘(约 10 秒粒度的回拨检测延迟,换来磁盘只在一分钟一次量级写)。"""
|
||||
now = now or self.now_fn()
|
||||
c = self._cr_cache
|
||||
if c and self.mono_fn() < c[2]:
|
||||
return c[0], c[1]
|
||||
ok, reason = self._can_run_uncached(now)
|
||||
if self.cache_ttl > 0:
|
||||
self._cr_cache = (ok, reason, self.mono_fn() + self.cache_ttl)
|
||||
return ok, reason
|
||||
|
||||
def _can_run_uncached(self, now):
|
||||
now = now or self.now_fn()
|
||||
st = self.state_store.load()
|
||||
env = st.get("lease_envelope")
|
||||
if not env:
|
||||
if st.get("certificate_envelope"):
|
||||
return False, "已激活,正在获取运行租约(首次心跳)…"
|
||||
return False, "尚未激活:请在授权页面完成激活"
|
||||
try:
|
||||
payload = verify_lease(env, st.get("instance_id"), self.keyring)
|
||||
except VerifyError as e:
|
||||
return False, "本地租约校验失败:%s" % e
|
||||
try:
|
||||
lhw = st.get("local_high_water")
|
||||
if lhw and now < parse_rfc3339(lhw):
|
||||
return False, ("检测到本机时钟回拨(已记录 %s),为防止绕过授权已锁定,"
|
||||
"请恢复系统时间后重启软件" % lhw)
|
||||
shw = st.get("server_high_water")
|
||||
if shw and parse_rfc3339(payload["server_time"]) < parse_rfc3339(shw):
|
||||
return False, "服务端时间早于已记录的高水位"
|
||||
skew = abs(now - parse_rfc3339(payload["server_time"]))
|
||||
if skew > MAX_CLOCK_SKEW:
|
||||
return False, "本机时间与服务端时间相差超过 5 分钟,请校准系统时间"
|
||||
if payload["state"] != "active":
|
||||
return False, "授权已被服务端置为「%s」,请联系软件提供方" % payload["state"]
|
||||
ent = parse_rfc3339(payload["entitlement_expires_at"])
|
||||
le = parse_rfc3339(payload["lease_expires_at"])
|
||||
if ent <= now:
|
||||
return False, "授权已于 %s 过期" % payload["entitlement_expires_at"]
|
||||
if le <= now:
|
||||
return False, "运行租约已过期(离线过久),请联网后重启软件自动续租"
|
||||
if le > ent or le > parse_rfc3339(payload["server_time"]) + timedelta(days=MAX_LEASE_DAYS):
|
||||
return False, "租约时间窗非法"
|
||||
except VerifyError as e:
|
||||
return False, str(e)
|
||||
try:
|
||||
def mut(s):
|
||||
# 高水位节流写:只在首记或前进超过 55 秒时落盘(配合 can_run 缓存,
|
||||
# 磁盘写入降到分钟级;高水位只进不退的语义不变)
|
||||
w = s.get("local_high_water")
|
||||
if not w or now > parse_rfc3339(w) + timedelta(seconds=55):
|
||||
s["local_high_water"] = rfc3339(now)
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
except StorageError as e:
|
||||
return False, "授权状态保存失败(fail closed):%s" % e
|
||||
return True, None
|
||||
|
||||
def can_run_safe(self):
|
||||
"""门禁专用:任何内部异常都折算成 (False, 原因),绝不让门禁 fail open。"""
|
||||
try:
|
||||
return self.can_run()
|
||||
except Exception as e: # 存储损坏等一切意外
|
||||
return False, "授权子系统异常(fail closed):%s" % e
|
||||
|
||||
# ------------------------------------------------------------ 状态视图
|
||||
|
||||
def status(self, enforce=True, heartbeat_running=False):
|
||||
out = {"enforce": enforce, "api_base": self.api_base,
|
||||
"keyring_ready": bool(self.keyring),
|
||||
"heartbeat_running": heartbeat_running}
|
||||
try:
|
||||
st = self.state_store.load()
|
||||
except StorageError as e:
|
||||
out.update({"configured": False, "activated": False, "enabled": False,
|
||||
"can_run": False, "reason": "授权状态不可读(fail closed):%s" % e,
|
||||
"status": "error"})
|
||||
return out
|
||||
lease = st.get("lease") or {}
|
||||
cert = st.get("certificate") or {}
|
||||
ent = entitlements(cert) if cert else {"edition": None, "max_seats": None}
|
||||
ok, reason = self.can_run_safe()
|
||||
days_left = None
|
||||
try:
|
||||
if cert.get("expires_at"):
|
||||
days_left = (parse_rfc3339(cert["expires_at"]) - self.now_fn()).days
|
||||
except VerifyError:
|
||||
pass
|
||||
out.update({
|
||||
"configured": bool(st.get("instance_id") and st.get("license_key")),
|
||||
"instance_id": st.get("instance_id"),
|
||||
"status": st.get("status") or "unactivated",
|
||||
"activated": bool(st.get("certificate_envelope")),
|
||||
"license_id": cert.get("license_id"),
|
||||
"product_id": cert.get("product_id"),
|
||||
"expected_product_id": self.expected_product_id,
|
||||
"edition": ent["edition"], # 商业版权益(未激活为 None;证书缺省=personal)
|
||||
"max_seats": ent["max_seats"],
|
||||
"days_left": days_left,
|
||||
"starts_at": cert.get("starts_at"),
|
||||
"entitlement_expires_at": cert.get("expires_at") or lease.get("entitlement_expires_at"),
|
||||
"lease_state": lease.get("state"),
|
||||
"lease_expires_at": lease.get("lease_expires_at"),
|
||||
"server_time": lease.get("server_time"),
|
||||
"last_heartbeat_at": st.get("last_heartbeat_at"),
|
||||
"next_heartbeat_seconds": st.get("next_heartbeat_seconds"),
|
||||
"last_error": st.get("last_error") or "",
|
||||
"can_run": ok,
|
||||
"reason": reason or "授权有效,运行中",
|
||||
})
|
||||
return out
|
||||
|
||||
# ------------------------------------------------------------ 心跳循环
|
||||
|
||||
def run_forever(self, stop_event, log_fn=None):
|
||||
"""心跳线程:开机立即跳一次,随后按 next_heartbeat_seconds + 正向抖动调度。
|
||||
403/409/400/401 → 停止自动重试(长休眠直到重启/重新激活);暂时性失败退避。"""
|
||||
log = log_fn or (lambda *a: None)
|
||||
backoff = 0
|
||||
first = True
|
||||
while not stop_event.wait(0 if first else self._next_wait(backoff, True)):
|
||||
first = False
|
||||
try:
|
||||
r = self.heartbeat()
|
||||
except (StorageError, VerifyError) as e:
|
||||
log("license 心跳异常:%s" % e)
|
||||
r = {"ok": False, "code": "TRANSIENT", "message": str(e)}
|
||||
if r.get("ok"):
|
||||
if backoff:
|
||||
log("license 心跳恢复(state=%s)" % r.get("state"))
|
||||
backoff = 0
|
||||
continue
|
||||
if r.get("code") in NEED_ATTENTION or r.get("code") == "VERIFY_FAILED" \
|
||||
or r.get("code") == "LEASE_INVALID":
|
||||
log("license 心跳进入人工处理状态(%s),停止自动重试:%s"
|
||||
% (r.get("code"), r.get("message")))
|
||||
while not stop_event.wait(3600):
|
||||
pass # 停在人工处理状态:不再自动心跳,等重启/重新激活
|
||||
break
|
||||
else:
|
||||
backoff = min(backoff + 1, 6)
|
||||
log("license 心跳暂时失败(第 %d 次):%s" % (backoff, r.get("message")))
|
||||
return
|
||||
|
||||
def _next_wait(self, backoff, is_loop):
|
||||
st = self.state_store.load()
|
||||
base = max(MIN_HEARTBEAT_SECONDS, st.get("next_heartbeat_seconds") or MIN_HEARTBEAT_SECONDS)
|
||||
if backoff:
|
||||
base = min(60 * (2 ** backoff), 300)
|
||||
return base * (1.0 + random.uniform(0, 0.1)) # 少量正向抖动
|
||||
|
||||
# ------------------------------------------------------------ HTTP
|
||||
|
||||
def _httpx_send(self, method, url, body, headers):
|
||||
try:
|
||||
import httpx
|
||||
except ImportError:
|
||||
raise TransientError("缺少 httpx 库(pip install httpx),无法联网刷新授权")
|
||||
if self._http is None:
|
||||
self._http = httpx.Client(base_url=self.api_base, timeout=self.timeout)
|
||||
try:
|
||||
r = self._http.post(url, json=body, headers=headers)
|
||||
except Exception as e: # 超时/连接错误/重置等一律暂时性
|
||||
raise TransientError("%s: %s" % (type(e).__name__, e))
|
||||
return r.status_code, dict(r.headers), _safe_json(r)
|
||||
|
||||
def _send_with_retry(self, path, body, idem_key):
|
||||
"""同一操作:同一请求体 + 同一幂等键,有界重试(429/5xx/网络错误)。
|
||||
⚠ 请求头不能用返回值覆盖(曾因此重试丢 Idempotency-Key——协议红线)。"""
|
||||
url = self.api_base + path
|
||||
req_headers = {"Content-Type": "application/json", "Idempotency-Key": idem_key}
|
||||
delay = 1.0
|
||||
last = None
|
||||
for _ in range(self.max_attempts):
|
||||
try:
|
||||
status, resp_headers, data = self._send_fn("POST", url, body, req_headers)
|
||||
except (TransientError, OSError) as e:
|
||||
# OSError:ConnectionError/TimeoutError 等原生网络异常(测试/极简传输层)
|
||||
last = e
|
||||
self.sleep_fn(delay)
|
||||
delay = min(delay * 2, 30)
|
||||
continue
|
||||
if status < 500 and status != 429:
|
||||
return status, resp_headers, data
|
||||
wait = delay
|
||||
if status == 429:
|
||||
ra = resp_headers.get("Retry-After") or resp_headers.get("retry-after")
|
||||
try:
|
||||
wait = max(float(ra), delay) if ra else delay
|
||||
except (TypeError, ValueError):
|
||||
wait = delay
|
||||
last = TransientError("HTTP %s" % status)
|
||||
self.sleep_fn(min(wait, 120))
|
||||
delay = min(delay * 2, 30)
|
||||
raise TransientError(str(last) if last else "重试额度用尽")
|
||||
|
||||
# ------------------------------------------------------------ 小工具
|
||||
|
||||
def _clear_op(self, name):
|
||||
with self._op_lock:
|
||||
self.state_store.update(lambda s: s.pop(name, None))
|
||||
|
||||
def _set_last_error(self, msg):
|
||||
with self._op_lock:
|
||||
self.state_store.update(lambda s: s.update({"last_error": msg}))
|
||||
|
||||
|
||||
def _err_body(data):
|
||||
"""错误响应 → (code, message)。不回显请求内容。"""
|
||||
err = (data or {}).get("error") if isinstance(data, dict) else None
|
||||
if isinstance(err, dict):
|
||||
return str(err.get("code") or ""), str(err.get("message") or "")
|
||||
return "", ""
|
||||
|
||||
|
||||
def _safe_json(r):
|
||||
try:
|
||||
return r.json()
|
||||
except Exception:
|
||||
return {}
|
||||
@@ -1,547 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""业务门禁:api_server 唯一挂接点。
|
||||
|
||||
run() 时调 init(data_dir):读 data/license/config.json + 随软件分发的
|
||||
pinned_keys.json + 已存授权状态;配置了凭据且信任根就绪则起心跳线程。
|
||||
任何初始化异常都不打断服务启动,但门禁 fail closed:
|
||||
|
||||
- /api/license/* 永远放行(激活入口本身不能被锁死);
|
||||
- 其余请求:enforce 且 can_run()=False → GET 一律回授权页(自包含 HTML,
|
||||
内嵌激活表单),POST/业务 API 回 403 {"error":{"code":"LICENSE_REQUIRED"}}。
|
||||
|
||||
本地开发豁免:data/license/config.json 写 "enforce": false(交付/发布环境
|
||||
不带该文件或 enforce=true,代码默认 true)。
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
from .client import LicenseClient, DEFAULT_API_BASE
|
||||
from .store import JsonFileStore, DpapiSecretStore, StorageError
|
||||
from .verify import VerifyError, load_keyring_file, build_keyring, UUID_RE
|
||||
|
||||
try: # 构建时生成(仅交付版有)
|
||||
from . import license_build_config as BUILD
|
||||
except ImportError:
|
||||
BUILD = None
|
||||
|
||||
_lock = threading.Lock()
|
||||
_client = None
|
||||
_cfg = {"enforce": True, "api_base": DEFAULT_API_BASE, "selfheal_seconds": 300}
|
||||
_hb_thread = None
|
||||
_hb_stop = None
|
||||
_last_selfheal = 0.0 # monotonic:门禁自愈触发节流
|
||||
_INTEGRITY_FAIL = "" # N1 源码保护(2026-10-27):非空 = 交付包文件被改,全线拦截
|
||||
|
||||
|
||||
def _check_build_integrity():
|
||||
"""N1 源码保护:交付包启动时校验 .py 哈希清单(build 期烧入 BUILD.INTEGRITY,
|
||||
覆盖 server/core 全部 .py)。被改 = fail closed 全线拦截(含授权口——防的是
|
||||
「改掉本文件/门禁调用后再激活」的绕过路径)。开发版(BUILD=None)不校验。
|
||||
INTEGRITY 键相对 app 根(server/...、core/...、shell.py)。"""
|
||||
global _INTEGRITY_FAIL
|
||||
if BUILD is None:
|
||||
return
|
||||
manifest = getattr(BUILD, "INTEGRITY", None)
|
||||
if not isinstance(manifest, dict) or not manifest:
|
||||
return
|
||||
app_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
for rel, want in sorted(manifest.items()):
|
||||
p = os.path.join(app_root, rel.replace("/", os.sep))
|
||||
try:
|
||||
with open(p, "rb") as f:
|
||||
got = hashlib.sha256(f.read()).hexdigest()
|
||||
except OSError:
|
||||
_INTEGRITY_FAIL = rel + "(缺失)"
|
||||
print("⚠ 完整性校验失败:%s" % _INTEGRITY_FAIL)
|
||||
return
|
||||
if got != str(want).lower():
|
||||
_INTEGRITY_FAIL = rel
|
||||
print("⚠ 完整性校验失败:%s 哈希不符(文件被改动?)" % rel)
|
||||
return
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 初始化
|
||||
|
||||
def _load_cfg(lic_dir):
|
||||
cfg = {"enforce": True,
|
||||
"api_base": os.environ.get("LICENSE_API_BASE_URL") or DEFAULT_API_BASE}
|
||||
p = os.path.join(lic_dir, "config.json")
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
with open(p, encoding="utf-8") as f:
|
||||
user = json.load(f)
|
||||
if isinstance(user, dict):
|
||||
if "api_base" in user and not os.environ.get("LICENSE_API_BASE_URL"):
|
||||
cfg["api_base"] = str(user["api_base"]).rstrip("/")
|
||||
cfg["enforce"] = bool(user.get("enforce", True))
|
||||
if user.get("pinned_keys"):
|
||||
cfg["pinned_keys"] = user["pinned_keys"]
|
||||
except Exception as e:
|
||||
print("⚠ license 配置读取失败(按默认 enforce 处理):%s" % e)
|
||||
return cfg
|
||||
|
||||
|
||||
def init(data_dir):
|
||||
"""服务启动时调用一次。永不抛异常(授权子系统坏了也不许拖死服务)。
|
||||
|
||||
信任根优先级:交付版(license_build_config.py 存在)→ 只信烧进包里的公钥/
|
||||
平台地址/强制开关,本地 config.json、环境变量、pinned_keys.json 一律不参与
|
||||
(P0-1:客户改文件/环境变量无法自建信任根)。开发版(无该文件)→ 走
|
||||
data/license/config.json + pinned_keys.json 的老路径,便于联调。
|
||||
"""
|
||||
global _client, _cfg, _hb_thread, _hb_stop
|
||||
with _lock:
|
||||
if _client is not None:
|
||||
return _client
|
||||
lic_dir = os.environ.get("LICENSE_DATA_DIR") or os.path.join(data_dir, "license")
|
||||
try:
|
||||
os.makedirs(lic_dir, exist_ok=True)
|
||||
expected_product = None
|
||||
selfheal = 300
|
||||
if BUILD is not None:
|
||||
_check_build_integrity() # N1:烧入清单校验,被改 → 全线拦截
|
||||
_cfg = {"enforce": bool(BUILD.ENFORCE),
|
||||
"api_base": str(BUILD.API_BASE).rstrip("/"),
|
||||
"selfheal_seconds": getattr(BUILD, "SELFHEAL_SECONDS", 300)}
|
||||
keyring = build_keyring(BUILD.PINNED_KEYS)
|
||||
expected_product = getattr(BUILD, "PRODUCT_ID", None)
|
||||
else:
|
||||
_cfg = _load_cfg(lic_dir)
|
||||
_cfg.setdefault("selfheal_seconds", 300)
|
||||
expected_product = _cfg.get("expected_product_id")
|
||||
keys_path = _cfg.get("pinned_keys") or os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), "pinned_keys.json")
|
||||
keyring = load_keyring_file(keys_path)
|
||||
if not keyring:
|
||||
print("⚠ license:可信公钥清单为空(%s)——激活/心跳将无法通过验签" % keys_path)
|
||||
selfheal = max(5, int(_cfg.get("selfheal_seconds") or 300))
|
||||
_cfg["selfheal_seconds"] = selfheal
|
||||
client = LicenseClient(
|
||||
api_base=_cfg["api_base"],
|
||||
state_store=JsonFileStore(os.path.join(lic_dir, "state.json")),
|
||||
secret_store=DpapiSecretStore(os.path.join(lic_dir, "secret.bin")),
|
||||
keyring=keyring,
|
||||
expected_product_id=expected_product)
|
||||
_client = client
|
||||
if client.has_credentials() and keyring:
|
||||
_start_heartbeat()
|
||||
elif client.has_credentials():
|
||||
print("⚠ license:已配置实例凭据但无可信公钥,心跳未启动(补齐 pinned_keys 后重启)")
|
||||
except Exception as e:
|
||||
print("⚠ license 子系统初始化失败(门禁按未授权处理):%s" % e)
|
||||
return _client
|
||||
|
||||
|
||||
def _client_for_request():
|
||||
"""请求期取客户端;未初始化(如直连 Handler 单测)时懒初始化失败 → None。"""
|
||||
return _client
|
||||
|
||||
|
||||
def _start_heartbeat():
|
||||
global _hb_thread, _hb_stop
|
||||
if _hb_thread and _hb_thread.is_alive():
|
||||
return
|
||||
_hb_stop = threading.Event()
|
||||
_hb_thread = threading.Thread(target=_client.run_forever, args=(_hb_stop,),
|
||||
name="license-heartbeat", daemon=True)
|
||||
_hb_thread.start()
|
||||
|
||||
|
||||
def _restart_heartbeat():
|
||||
"""心跳循环在 403/409 后按协议停在人工处理状态;用户侧动作(手动刷新/
|
||||
门禁自愈)成功续上租约时,把循环拉起来恢复自动调度。"""
|
||||
global _hb_thread, _hb_stop
|
||||
with _lock:
|
||||
old = _hb_thread
|
||||
if _hb_stop:
|
||||
_hb_stop.set()
|
||||
if old and old is not threading.current_thread():
|
||||
old.join(timeout=2)
|
||||
_hb_thread = None
|
||||
_start_heartbeat()
|
||||
|
||||
|
||||
def _selfheal_maybe(status):
|
||||
"""授权不可运行时借 /api/license/status 的轮询做后台自愈:
|
||||
节流期内至多试一次心跳;成功(含从 403 停摆状态救回)即重启心跳循环。"""
|
||||
global _last_selfheal
|
||||
if not _cfg.get("enforce", True) or not status.get("configured"):
|
||||
return
|
||||
if status.get("can_run"):
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now - _last_selfheal < _cfg.get("selfheal_seconds", 300):
|
||||
return
|
||||
_last_selfheal = now
|
||||
threading.Thread(target=_selfheal_run, name="license-selfheal",
|
||||
daemon=True).start()
|
||||
|
||||
|
||||
def _selfheal_run():
|
||||
try:
|
||||
r = _client.heartbeat()
|
||||
except Exception:
|
||||
return
|
||||
if r.get("ok"):
|
||||
_restart_heartbeat()
|
||||
|
||||
|
||||
def heartbeat_running():
|
||||
return bool(_hb_thread and _hb_thread.is_alive())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 请求拦截
|
||||
|
||||
def intercept(method, path, body=None):
|
||||
"""None = 放行;否则返回 {"kind":"json"|"html","code":int,...} 由 Handler 发送。"""
|
||||
if _INTEGRITY_FAIL: # N1:文件被改 = 无任何放行(含授权口)
|
||||
if method == "GET" and not path.startswith("/api/"):
|
||||
return {"kind": "html", "code": 200, "text": _integrity_page()}
|
||||
return {"kind": "json", "code": 403,
|
||||
"obj": {"error": {"code": "INTEGRITY_FAILED",
|
||||
"message": "软件文件完整性校验失败,请重新安装或联系软件提供方"}}}
|
||||
if path.startswith("/api/license/"):
|
||||
return _license_api(method, path, body)
|
||||
if path.startswith("/api/version"):
|
||||
# 版本状态口(/api/version、/api/version_info)在锁定态也放行:
|
||||
# 排障要看版本;强制更新页要轮询它(2026-10-27 5.9)。
|
||||
return None
|
||||
if not _cfg.get("enforce", True):
|
||||
return None
|
||||
c = _client_for_request()
|
||||
if c is None:
|
||||
return _blocked("授权子系统未初始化")
|
||||
ok, reason = c.can_run_safe()
|
||||
if ok:
|
||||
return None
|
||||
if method == "GET" and not path.startswith("/api/"):
|
||||
# 页面/静态资源 → 授权页;/api/* 一律 403 JSON(前端 fetch 不能收到 HTML)
|
||||
return {"kind": "html", "code": 200, "text": gate_page(reason)}
|
||||
return _blocked(reason)
|
||||
|
||||
|
||||
def can_run_now():
|
||||
"""给集成层(MCP 等)用:enforce 开启时必须授权有效。返回 (ok, reason)。
|
||||
与 intercept 同一口径,但不关心路由形态(2026-10-15 收费挂钩 MCP)。"""
|
||||
if not _cfg.get("enforce", True):
|
||||
return True, ""
|
||||
c = _client_for_request()
|
||||
if c is None:
|
||||
return False, "授权子系统未初始化"
|
||||
return c.can_run_safe()
|
||||
|
||||
|
||||
def _integrity_page():
|
||||
"""N1 完整性拦截页(自包含):文件被改时的唯一可见页面。"""
|
||||
return """<!DOCTYPE html>
|
||||
<html lang="zh"><head><meta charset="utf-8"><title>软件文件校验失败</title>
|
||||
<style>body{font-family:"Microsoft YaHei",sans-serif;background:#f0f2f5;display:flex;
|
||||
align-items:center;justify-content:center;min-height:100vh;margin:0}
|
||||
.c{background:#fff;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.08);
|
||||
max-width:520px;padding:32px 36px}h1{font-size:19px;color:#b02a2a;margin:0 0 12px}
|
||||
p{color:#33475b;line-height:1.8;font-size:14px;margin:8px 0}
|
||||
.k{color:#8a97a5;font-size:12px;margin-top:16px}</style></head><body><div class="c">
|
||||
<h1>⚠ 软件文件完整性校验失败</h1>
|
||||
<p>检测到程序文件被改动,为保障授权与数据安全,软件已停止服务。</p>
|
||||
<p>请重新安装官方软件包,或联系软件提供方处理。您的数据不受影响。</p>
|
||||
<div class="k">涉及文件见服务日志「完整性校验失败」行。</div>
|
||||
</div></body></html>"""
|
||||
|
||||
|
||||
def _blocked(reason):
|
||||
return {"kind": "json", "code": 403,
|
||||
"obj": {"error": {"code": "LICENSE_REQUIRED", "message": reason}}}
|
||||
|
||||
|
||||
def status_view():
|
||||
c = _client_for_request()
|
||||
if c is None:
|
||||
return {"enforce": _cfg.get("enforce", True), "configured": False,
|
||||
"activated": False, "can_run": False,
|
||||
"reason": "授权子系统未初始化", "api_base": _cfg.get("api_base")}
|
||||
return c.status(enforce=bool(_cfg.get("enforce", True)),
|
||||
heartbeat_running=heartbeat_running())
|
||||
|
||||
|
||||
def _license_api(method, path, body):
|
||||
if method == "GET" and path == "/api/license/status":
|
||||
out = status_view()
|
||||
_selfheal_maybe(out) # 授权不可运行 → 借轮询节流自愈(后台线程)
|
||||
return {"kind": "json", "code": 200, "obj": {"ok": True, "data": out}}
|
||||
if method == "POST" and path == "/api/license/activate":
|
||||
b = body if isinstance(body, dict) else {}
|
||||
iid, lk, sec = (b.get("instance_id") or "").strip(), \
|
||||
(b.get("license_key") or "").strip(), \
|
||||
(b.get("secret") or "").strip()
|
||||
if not (iid and lk and sec):
|
||||
return {"kind": "json", "code": 400,
|
||||
"obj": {"error": {"code": "BAD_REQUEST",
|
||||
"message": "instance_id / license_key / secret 都必填"}}}
|
||||
c = _client_for_request()
|
||||
if c is None:
|
||||
return _blocked("授权子系统未初始化")
|
||||
try:
|
||||
c.configure(iid, lk, sec)
|
||||
r = c.activate()
|
||||
except (StorageError, VerifyError) as e:
|
||||
r = {"ok": False, "code": "CONFIG_FAILED", "message": str(e)}
|
||||
if r.get("ok"):
|
||||
_restart_heartbeat() # 激活成功:新循环(旧循环可能停在人工处理态)
|
||||
out = status_view()
|
||||
out["result"] = r
|
||||
return {"kind": "json", "code": 200, "obj": {"ok": bool(r.get("ok")), "data": out}}
|
||||
if method == "POST" and path == "/api/license/refresh":
|
||||
c = _client_for_request()
|
||||
if c is None:
|
||||
return _blocked("授权子系统未初始化")
|
||||
try:
|
||||
r = c.heartbeat()
|
||||
except (StorageError, VerifyError) as e:
|
||||
r = {"ok": False, "code": "ERROR", "message": str(e)}
|
||||
if r.get("ok"):
|
||||
_restart_heartbeat() # 手动续上 → 恢复自动心跳调度
|
||||
out = status_view()
|
||||
out["result"] = r
|
||||
return {"kind": "json", "code": 200, "obj": {"ok": bool(r.get("ok")), "data": out}}
|
||||
if method == "POST" and path == "/api/license/import":
|
||||
return _license_import(body)
|
||||
return {"kind": "json", "code": 404,
|
||||
"obj": {"error": {"code": "NOT_FOUND", "message": "未知授权接口"}}}
|
||||
|
||||
|
||||
# ------------------------------------------------- 授权文件导入(.license.json)
|
||||
#
|
||||
# 协议口径(接入包「授权文件导入(交付格式 v1)」):文件未签名、不是离线授权,
|
||||
# 只是一份凭据载体——导入=严格校验后写入受保护存储,仍必须走在线激活+验签。
|
||||
# 红线:拒绝未知版本/额外字段;api_base_url 只允许 HTTPS 根地址且必须命中预置
|
||||
# 允许地址;不得覆盖已有不同实例身份(须显式确认);导入错误不得回显文件内容。
|
||||
|
||||
IMPORT_FIELDS = {"format", "version", "api_base_url", "instance_id",
|
||||
"license_key", "secret"}
|
||||
|
||||
|
||||
def _import_invalid(msg):
|
||||
"""固定话术,绝不回显文件内容/secret。"""
|
||||
return {"ok": False, "code": "IMPORT_INVALID", "message": msg}
|
||||
|
||||
|
||||
def _import_check_url(url):
|
||||
"""HTTPS 根地址校验 → (规范化地址, None) | (None, 错误话术)。"""
|
||||
if not isinstance(url, str) or not url or len(url) > 2048:
|
||||
return None, "授权文件 api_base_url 非法"
|
||||
try:
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(url)
|
||||
port = u.port # 非法端口在这里抛 ValueError
|
||||
except ValueError:
|
||||
return None, "授权文件 api_base_url 非法"
|
||||
if u.scheme == "http":
|
||||
# 本机回环 HTTP 仅限开发版(交付版烧根,一律 HTTPS)
|
||||
if BUILD is not None or u.hostname not in ("127.0.0.1", "localhost", "::1"):
|
||||
return None, "授权文件 api_base_url 必须 HTTPS"
|
||||
elif u.scheme != "https":
|
||||
return None, "授权文件 api_base_url 必须 HTTPS"
|
||||
if (u.username or u.password or u.query or u.fragment
|
||||
or not u.hostname or u.path not in ("", "/")):
|
||||
return None, "授权文件 api_base_url 只允许根地址(不得带路径/参数/账号信息)"
|
||||
return url.rstrip("/"), None
|
||||
|
||||
|
||||
def _import_validate(f):
|
||||
if not isinstance(f, dict) or set(f.keys()) != IMPORT_FIELDS:
|
||||
return _import_invalid("授权文件格式不符(应为 yhy-license-activation v1,"
|
||||
"字段缺/多不予接受)")
|
||||
if f.get("format") != "yhy-license-activation":
|
||||
return _import_invalid("授权文件 format 不符(需要 yhy-license-activation)")
|
||||
v = f.get("version")
|
||||
if isinstance(v, bool) or not isinstance(v, int) or v != 1:
|
||||
return _import_invalid("授权文件版本不支持(只接受 version=1)")
|
||||
iid, lk, sec = f.get("instance_id"), f.get("license_key"), f.get("secret")
|
||||
for name, val in (("instance_id", iid), ("license_key", lk), ("secret", sec)):
|
||||
if not isinstance(val, str) or not val or len(val) > 512:
|
||||
return _import_invalid("授权文件 %s 字段非法" % name)
|
||||
if any(ch in val for ch in ("\r", "\n", "\x00")):
|
||||
return _import_invalid("授权文件 %s 字段含非法字符" % name)
|
||||
if not UUID_RE.match(iid):
|
||||
return _import_invalid("授权文件 instance_id 不是 UUID")
|
||||
url, err = _import_check_url(f.get("api_base_url"))
|
||||
if err:
|
||||
return _import_invalid(err)
|
||||
allowed = str(_cfg.get("api_base") or "").rstrip("/")
|
||||
if url.lower() != allowed.lower():
|
||||
return _import_invalid("授权文件指向的授权中心不在本软件预置允许列表"
|
||||
"(固定为 %s)" % allowed)
|
||||
return {"ok": True, "instance_id": iid, "license_key": lk, "secret": sec}
|
||||
|
||||
|
||||
def _license_import(body):
|
||||
b = body if isinstance(body, dict) else {}
|
||||
c = _client_for_request()
|
||||
if c is None:
|
||||
return _blocked("授权子系统未初始化")
|
||||
r = _import_validate(b.get("file"))
|
||||
if not r.get("ok"):
|
||||
return {"kind": "json", "code": 200, "obj": {"ok": False, "data": {"result": r}}}
|
||||
iid = r["instance_id"]
|
||||
cur = status_view().get("instance_id")
|
||||
if cur and cur.lower() != iid.lower() and not b.get("replace_confirmed"):
|
||||
return {"kind": "json", "code": 200, "obj": {"ok": False, "data": {"result": {
|
||||
"ok": False, "code": "INSTANCE_CONFLICT",
|
||||
"message": "本机已配置其他实例(%s…),更换凭据需界面显式确认" % cur[:8]}}}}
|
||||
try:
|
||||
c.configure(iid, r["license_key"], r["secret"])
|
||||
act = c.activate() # 导入≠激活:仍走在线激活+公钥验签
|
||||
except (StorageError, VerifyError) as e:
|
||||
act = {"ok": False, "code": "IMPORT_FAILED", "message": str(e)}
|
||||
if act.get("ok"):
|
||||
_restart_heartbeat()
|
||||
out = status_view()
|
||||
out["result"] = act
|
||||
return {"kind": "json", "code": 200, "obj": {"ok": bool(act.get("ok")), "data": out}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 授权页
|
||||
|
||||
_PAGE = None
|
||||
|
||||
|
||||
def gate_page(reason):
|
||||
"""未授权时替代正常页面的自包含页面:状态 + 激活表单,激活成功自动进系统。"""
|
||||
global _PAGE
|
||||
if _PAGE is None:
|
||||
_PAGE = ("""<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>软件授权</title><style>
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{font-family:"Microsoft YaHei",system-ui,sans-serif;background:#f2f4f8;
|
||||
min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;color:#1c2733}
|
||||
.card{background:#fff;border-radius:10px;box-shadow:0 6px 24px rgba(16,35,61,.10);
|
||||
width:520px;max-width:100%;overflow:hidden}
|
||||
.hd{background:#1f4e79;color:#fff;padding:18px 28px;font-size:19px;font-weight:600}
|
||||
.hd small{display:block;font-weight:400;font-size:12px;opacity:.75;margin-top:4px}
|
||||
.bd{padding:24px 28px 28px}
|
||||
.st{border:1px solid #e3e8ef;border-radius:8px;padding:12px 16px;margin-bottom:20px;
|
||||
background:#fafbfd;font-size:13px;line-height:1.9}
|
||||
.st b{color:#b02a2a}
|
||||
.st .ok{color:#1c7c44}
|
||||
.row{margin-bottom:14px}
|
||||
.row label{display:block;font-size:13px;color:#51606f;margin-bottom:5px}
|
||||
.row input{width:100%;padding:9px 11px;border:1px solid #c8d2dd;border-radius:6px;
|
||||
font-size:13px;font-family:inherit}
|
||||
.row input:focus{outline:none;border-color:#1f4e79;box-shadow:0 0 0 2px rgba(31,78,121,.15)}
|
||||
.btns{display:flex;gap:10px;margin-top:18px}
|
||||
button{flex:1;padding:10px 0;border:0;border-radius:6px;font-size:14px;cursor:pointer;
|
||||
font-family:inherit;background:#1f4e79;color:#fff}
|
||||
button.ghost{background:#fff;color:#1f4e79;border:1px solid #1f4e79}
|
||||
button:disabled{opacity:.5;cursor:default}
|
||||
.msg{margin-top:14px;font-size:13px;line-height:1.7;display:none;
|
||||
padding:10px 12px;border-radius:6px}
|
||||
.msg.err{display:block;background:#fdf0f0;color:#b02a2a;border:1px solid #f3c8c8}
|
||||
.msg.ok{display:block;background:#effaf3;color:#1c7c44;border:1px solid #c4e8d0}
|
||||
.tip{margin-top:16px;font-size:12px;color:#8a97a5;line-height:1.7}
|
||||
.imp{margin-top:14px;font-size:13px}
|
||||
.imp label{color:#1f4e79;text-decoration:underline;cursor:pointer}
|
||||
.imp input{display:none}
|
||||
#impPv button{flex:none;padding:7px 18px;margin-top:8px;font-size:13px}
|
||||
</style></head><body><div class="card">
|
||||
<div class="hd">造价审核 · 软件授权<small id="sub">正在连接授权状态…</small></div>
|
||||
<div class="bd">
|
||||
<div class="st" id="st">加载中…</div>
|
||||
<div class="row"><label>实例 ID(instance_id)</label>
|
||||
<input id="iid" placeholder="形如 11111111-2222-3333-4444-555555555555" spellcheck="false"></div>
|
||||
<div class="row"><label>授权码(license_key)</label>
|
||||
<input id="lk" placeholder="交付单上提供的授权码" spellcheck="false"></div>
|
||||
<div class="row"><label>激活密钥(secret,仅输入一次,本机加密保存)</label>
|
||||
<input id="sec" type="password" placeholder="交付单上提供的一次性 secret"></div>
|
||||
<div class="btns"><button id="go" onclick="doAct()">激活</button>
|
||||
<button class="ghost" onclick="load()">刷新状态</button></div>
|
||||
<div class="imp"><label for="impFile">或导入授权文件(.license.json,由软件提供方交付)— 点击选择</label>
|
||||
<input type="file" id="impFile" accept=".json,application/json" onchange="impPick(this)"></div>
|
||||
<div class="st" id="impPv" style="display:none;margin-top:12px;margin-bottom:0"></div>
|
||||
<div class="msg" id="msg"></div>
|
||||
<div class="tip">本页面由本机服务(127.0.0.1)提供;激活凭据只保存在本机,不会上传到别处。
|
||||
激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。
|
||||
授权到期或被冻结时会停在本页(到期即锁):联系软件提供方续费/解冻并重新激活即可恢复使用,本机数据不受任何影响。</div>
|
||||
</div></div>
|
||||
<script>
|
||||
var TIMER=null;
|
||||
function esc(s){return String(s==null?"":s).replace(/[&<>"]/g,function(c){
|
||||
return {"&":"&","<":"<",">":">",'"':"""}[c];});}
|
||||
function fmtSt(d){
|
||||
var h="";
|
||||
h+="状态:"+(d.can_run?'<span class="ok">已授权,运行中</span>':"<b>"+esc(d.reason||"不可用")+"</b>")+"<br>";
|
||||
if(d.instance_id)h+="实例:"+esc(d.instance_id)+"<br>";
|
||||
if(d.entitlement_expires_at)h+="授权到期:"+esc(d.entitlement_expires_at)+"<br>";
|
||||
if(d.lease_expires_at)h+="租约到期:"+esc(d.lease_expires_at)+"<br>";
|
||||
if(d.last_heartbeat_at)h+="最后心跳:"+esc(d.last_heartbeat_at)+"<br>";
|
||||
if(!d.keyring_ready)h+="<b>⚠ 信任根未配置(pinned_keys.json 为空),激活将无法通过验签——请联系软件提供方。</b><br>";
|
||||
if(d.last_error)h+="最近错误:"+esc(d.last_error);
|
||||
return h;}
|
||||
function load(){
|
||||
fetch("/api/license/status").then(function(r){return r.json()}).then(function(j){
|
||||
var d=j.data||{};
|
||||
document.getElementById("st").innerHTML=fmtSt(d);
|
||||
document.getElementById("sub").textContent="授权服务器:"+(d.api_base||"")+
|
||||
(d.enforce?"":"(当前为开发模式,未强制校验)");
|
||||
if(d.can_run&&d.enforce){location.reload();return;}
|
||||
if(TIMER)clearTimeout(TIMER);
|
||||
TIMER=setTimeout(load,15000);
|
||||
}).catch(function(){
|
||||
document.getElementById("st").innerHTML="<b>无法读取授权状态(本机服务异常?)</b>";
|
||||
});}
|
||||
function doAct(){
|
||||
var b={instance_id:document.getElementById("iid").value.trim(),
|
||||
license_key:document.getElementById("lk").value.trim(),
|
||||
secret:document.getElementById("sec").value};
|
||||
var m=document.getElementById("msg");
|
||||
if(!b.instance_id||!b.license_key||!b.secret){
|
||||
m.className="msg err";m.textContent="三项都要填写(见交付单)。";return;}
|
||||
var btn=document.getElementById("go");btn.disabled=true;
|
||||
m.className="msg";m.style.display="none";
|
||||
fetch("/api/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},
|
||||
body:JSON.stringify(b)}).then(function(r){return r.json()}).then(function(j){
|
||||
btn.disabled=false;
|
||||
var d=j.data||{},res=d.result||{};
|
||||
if(res.ok){document.getElementById("sec").value="";
|
||||
m.className="msg ok";m.textContent="激活成功,正在进入系统…";setTimeout(load,600);return;}
|
||||
m.className="msg err";m.textContent=res.message||"激活失败,请核对凭据。";
|
||||
document.getElementById("st").innerHTML=fmtSt(d);
|
||||
}).catch(function(){btn.disabled=false;
|
||||
m.className="msg err";m.textContent="网络错误:无法连接本机服务。";});}
|
||||
function impErr(m){var p=document.getElementById("impPv");p.style.display="";
|
||||
p.innerHTML="<b>"+esc(m)+"</b>";}
|
||||
function impPick(inp){var f=inp.files&&inp.files[0];if(!f)return;
|
||||
if(f.size>16384)return impErr("文件超过 16KiB,不是有效授权文件。");
|
||||
var r=new FileReader();
|
||||
r.onload=function(){try{impPreview(JSON.parse(r.value))}catch(e){impErr("文件不是有效 JSON。")}};
|
||||
r.readAsText(f,"utf-8");
|
||||
inp.value="";}
|
||||
function impPreview(o){
|
||||
if(!o||typeof o!="object"||Array.isArray(o)||o.format!="yhy-license-activation"||
|
||||
o.version!=1||!o.instance_id||!o.license_key||!o.secret||!o.api_base_url)
|
||||
return impErr("格式不符:需要 yhy-license-activation v1 授权文件。");
|
||||
window._imp=o;
|
||||
fetch("/api/license/status").then(function(r){return r.json()}).then(function(j){
|
||||
var d=j.data||{},p=document.getElementById("impPv");
|
||||
var warn=(d.instance_id&&String(d.instance_id).toLowerCase()!=String(o.instance_id).toLowerCase())
|
||||
?"<b>⚠ 本机已配置其他实例,导入将更换凭据(历史时间记录保留)。</b><br>":"";
|
||||
p.style.display="";
|
||||
p.innerHTML=warn+"实例:"+esc(o.instance_id)+"<br>授权中心:"+esc(o.api_base_url)+
|
||||
"<br><button onclick='impGo()'>确认导入并激活</button>";});}
|
||||
function impGo(){
|
||||
var m=document.getElementById("msg");m.className="msg";m.style.display="none";
|
||||
fetch("/api/license/import",{method:"POST",headers:{"Content-Type":"application/json"},
|
||||
body:JSON.stringify({file:window._imp,replace_confirmed:true})})
|
||||
.then(function(r){return r.json()}).then(function(j){
|
||||
var res=((j.data||{}).result||{});
|
||||
if(j.ok){m.className="msg ok";m.textContent="导入激活成功,正在进入系统…";
|
||||
document.getElementById("impPv").style.display="none";setTimeout(load,600);return;}
|
||||
impErr(res.message||"导入失败,请核对授权文件。");
|
||||
document.getElementById("st").innerHTML=fmtSt(j.data||{});})
|
||||
.catch(function(){impErr("网络错误:无法连接本机服务。")});}
|
||||
load();
|
||||
</script></body></html>""")
|
||||
return _PAGE
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"_说明": [
|
||||
"可信公钥清单(信任根):只随软件/受控部署渠道固定分发,绝不在线发现。",
|
||||
"2026-10-12 经接入包(license-platform-python-service-integration (2).md)交付生产公钥:",
|
||||
"key_id=prod-22056bfacc8fe8a2,SPKI SHA-256 已本地实算比对一致后录入(防拷贝损坏自校验)。",
|
||||
"交付版构建时烧进 license_build_config.py,本文件在交付环境不参与;开发环境直接读本文件。",
|
||||
"轮换时由运维经受控渠道交付新公钥,按 {\"key_id\":..., \"public_key_pem\":..., \"spki_sha256\":..., \"revoked\":false} 追加。",
|
||||
"接入包 test-vectors.json 里的 integration-test-only 测试公钥绝不能加进生产配置。",
|
||||
"清空 = fail closed:激活/心跳验签一律失败。"
|
||||
],
|
||||
"pinned_keys": [
|
||||
{
|
||||
"key_id": "prod-22056bfacc8fe8a2",
|
||||
"public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESr8/VFFwt70o7fwa8HiRNyxWtZEu\nUqzCBfYRG72DazEgeOaSVAdlTv49OujtggXSJzFLOluMENJzaRmp9+iJ0Q==\n-----END PUBLIC KEY-----",
|
||||
"spki_sha256": "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562",
|
||||
"revoked": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""授权状态受保护存储。
|
||||
|
||||
- LicenseStateStore:激活证书 / 运行租约 / enabled / 本地与服务端时间高水位的
|
||||
原子落盘(tmp + fsync + os.replace)。协议要求"先原子保存再启用业务",
|
||||
保存失败必须让调用方走 fail closed。
|
||||
- SecretStore 接口 + Windows DPAPI 实现:实例 secret 只进系统级保护存储
|
||||
(DPAPI CurrentUser),绝不写入源码/日志/普通明文文件;非 Windows 退化为
|
||||
仅当前用户可读的明文文件(开发环境兜底,交付环境只支持 Windows)。
|
||||
|
||||
协议自带声明:一般受控存储不能抵抗完全控制主机的攻击者和磁盘快照回滚,
|
||||
本模块不宣称硬件绑定或防克隆。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
"""状态读写失败(磁盘满/权限等)。调用方必须 fail closed。"""
|
||||
|
||||
|
||||
class LicenseStateStore:
|
||||
"""接口:load() → dict;save(state) 原子写。"""
|
||||
|
||||
def load(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def save(self, state):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class JsonFileStore(LicenseStateStore):
|
||||
"""JSON 文件原子存储。进程内加锁;跨进程不做(本应用本就不支持双实例共库)。"""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
|
||||
def load(self):
|
||||
with self._lock:
|
||||
return self._load_unlocked()
|
||||
|
||||
def _load_unlocked(self):
|
||||
try:
|
||||
with open(self.path, encoding="utf-8") as f:
|
||||
st = json.load(f)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except Exception as e:
|
||||
raise StorageError("授权状态读取失败:%s" % e)
|
||||
return st if isinstance(st, dict) else {}
|
||||
|
||||
def save(self, state):
|
||||
with self._lock:
|
||||
tmp = self.path + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(state, f, ensure_ascii=False, indent=1)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, self.path)
|
||||
except Exception as e:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise StorageError("授权状态保存失败:%s" % e)
|
||||
|
||||
def update(self, fn):
|
||||
"""原子读改写:fn(state) → state'(原地改传入 dict 即可),返回新状态。"""
|
||||
with self._lock:
|
||||
st = self._load_unlocked()
|
||||
fn(st)
|
||||
self._save_unlocked(st)
|
||||
return st
|
||||
|
||||
def _save_unlocked(self, state):
|
||||
tmp = self.path + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(state, f, ensure_ascii=False, indent=1)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, self.path)
|
||||
except Exception as e:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise StorageError("授权状态保存失败:%s" % e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- secret
|
||||
|
||||
class SecretStore:
|
||||
"""接口:get() → str|None;set(secret);clear()。"""
|
||||
|
||||
def get(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def set(self, secret):
|
||||
raise NotImplementedError
|
||||
|
||||
def clear(self):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
class _DATA_BLOB(ctypes.Structure):
|
||||
_fields_ = [("cbData", wintypes.DWORD),
|
||||
("pbData", ctypes.POINTER(ctypes.c_char))]
|
||||
|
||||
_CRYPTPROTECT_UI_FORBIDDEN = 0x1
|
||||
|
||||
def _dpapi(data, protect):
|
||||
crypt32 = ctypes.windll.crypt32
|
||||
k32 = ctypes.windll.kernel32
|
||||
buf = ctypes.create_string_buffer(data, len(data))
|
||||
inb = _DATA_BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
|
||||
out = _DATA_BLOB()
|
||||
if protect:
|
||||
ok = crypt32.CryptProtectData(
|
||||
ctypes.byref(inb), "pricing-review-license", None, None, None,
|
||||
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
|
||||
else:
|
||||
ok = crypt32.CryptUnprotectData(
|
||||
ctypes.byref(inb), None, None, None, None,
|
||||
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
|
||||
if not ok:
|
||||
raise StorageError("DPAPI %s 失败(错误码 %s)"
|
||||
% ("加密" if protect else "解密", ctypes.GetLastError()))
|
||||
try:
|
||||
return ctypes.string_at(out.pbData, out.cbData)
|
||||
finally:
|
||||
k32.LocalFree(out.pbData)
|
||||
|
||||
class DpapiSecretStore(SecretStore):
|
||||
"""Windows DPAPI(CurrentUser)加密落盘:换用户/拷走文件都解不开,
|
||||
源码里没有也不需要任何硬编码密钥。"""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
|
||||
def get(self):
|
||||
try:
|
||||
with open(self.path, "rb") as f:
|
||||
raw = f.read()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except OSError as e:
|
||||
raise StorageError("secret 读取失败:%s" % e)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return _dpapi(base64.b64decode(raw), False).decode("utf-8")
|
||||
except Exception as e:
|
||||
raise StorageError("secret 解密失败(可能换了系统用户):%s" % e)
|
||||
|
||||
def set(self, secret):
|
||||
enc = _dpapi(secret.encode("utf-8"), True)
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(base64.b64encode(enc))
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, self.path)
|
||||
|
||||
def clear(self):
|
||||
try:
|
||||
os.unlink(self.path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
else: # 非 Windows 兜底(开发环境)
|
||||
|
||||
class DpapiSecretStore(SecretStore):
|
||||
"""占位实现:明文落盘(权限收窄到当前用户)。交付环境不支持。"""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
|
||||
def get(self):
|
||||
try:
|
||||
with open(self.path, encoding="utf-8") as f:
|
||||
v = f.read().strip()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
return base64.b64decode(v).decode("utf-8") if v else None
|
||||
|
||||
def set(self, secret):
|
||||
with open(self.path, "w", encoding="utf-8") as f:
|
||||
f.write(base64.b64encode(secret.encode("utf-8")).decode("ascii"))
|
||||
try:
|
||||
os.chmod(self.path, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def clear(self):
|
||||
try:
|
||||
os.unlink(self.path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
@@ -1,267 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""license-v2 / lease-v2 信封验签(ECDSA P-256 + SHA-256)。
|
||||
|
||||
规范要点(license-platform 接入包 protocol.md):
|
||||
- 规范化串不是 JSON:固定顺序 key=value、单个 LF 连接、无末尾 LF、UTF-8 编码;
|
||||
整数字段输出正十进制;时间字段用收到的原始字符串(验签前不得格式化/重序列化)。
|
||||
- signature 是 ASN.1 DER ECDSA 的标准 Base64,不带 = 填充(不是 Base64URL,
|
||||
也不是固定 64 字节 r||s)。
|
||||
- canonical_sha256 是规范化字节的 SHA-256 十六进制,仅辅助校验,不能代替公钥验签。
|
||||
- 拒绝:未知版本、缺字段/多字段、非法类型、含 CR/LF/NUL 的字段、未知或已撤销
|
||||
key_id、非 P-256 公钥、绑定到其他实例的信封、legacy v1。
|
||||
(证书例外:OPTIONAL_CERT_FIELDS 两个可选权益字段可缺省,见下方注释。)
|
||||
|
||||
信任根:只信随软件/受控渠道固定分发的公钥(pinned_keys.json),绝不在线发现。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
LICENSE_V2 = "license-v2"
|
||||
LEASE_V2 = "lease-v2"
|
||||
ALGORITHM = "ECDSA-P256-SHA256"
|
||||
|
||||
# 固定字段顺序 = canonical 顺序;payload 必须恰好等于这些键,缺一个多一个都拒
|
||||
FIELDSETS = {
|
||||
LICENSE_V2: ("version", "instance_id", "license_id", "customer_id",
|
||||
"product_id", "starts_at", "expires_at", "key_id"),
|
||||
LEASE_V2: ("version", "instance_id", "state", "server_time",
|
||||
"entitlement_expires_at", "lease_expires_at", "key_id"),
|
||||
}
|
||||
|
||||
# 商业版权益字段(2026-10-27,《企业和个人版.md》5.1):仅证书载荷**可选**携带;
|
||||
# 出现 → 纳入 canonical(按本元组顺序追加在必填之后)并校验取值;
|
||||
# 缺省 → edition=personal、max_seats=1(fail-closed 不放大权益;平台未升级协议仍能签发)。
|
||||
OPTIONAL_CERT_FIELDS = ("edition", "max_seats")
|
||||
EDITIONS = ("personal", "enterprise", "trial")
|
||||
|
||||
|
||||
def entitlements(cert):
|
||||
"""从证书载荷取商业版权益(规范化缺省)。门禁与状态视图共用唯一口径。"""
|
||||
if not isinstance(cert, dict):
|
||||
return {"edition": "personal", "max_seats": 1}
|
||||
return {"edition": cert.get("edition") or "personal",
|
||||
"max_seats": cert.get("max_seats") or 1}
|
||||
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
||||
re.IGNORECASE)
|
||||
RFC3339_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
|
||||
LEASE_STATES = ("active", "frozen", "revoked", "expired", "not_started", "not_activated")
|
||||
|
||||
# 两种信封的固定键集合(缺一个多一个都拒)
|
||||
CERT_ENVELOPE_KEYS = {"version", "payload", "signature", "canonical_sha256"}
|
||||
LEASE_ENVELOPE_KEYS = {"payload", "signature", "canonical_sha256", "algorithm",
|
||||
"next_heartbeat_seconds"}
|
||||
|
||||
|
||||
class VerifyError(Exception):
|
||||
"""验签/结构校验失败。消息只写原因,不含任何凭据。"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 时间工具
|
||||
|
||||
def parse_rfc3339(s):
|
||||
"""RFC3339 → UTC aware datetime。形状不对抛 VerifyError。"""
|
||||
if not isinstance(s, str) or not RFC3339_RE.match(s):
|
||||
raise VerifyError("时间格式不是 RFC3339:%r" % (s,))
|
||||
from datetime import datetime, timezone
|
||||
v = s.strip()
|
||||
if v.endswith(("Z", "z")):
|
||||
v = v[:-1] + "+00:00"
|
||||
dt = datetime.fromisoformat(v)
|
||||
if dt.tzinfo is None:
|
||||
raise VerifyError("时间缺时区:%r" % (s,))
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def rfc3339(dt):
|
||||
"""aware datetime → RFC3339 UTC(Z 后缀,秒精度)。"""
|
||||
from datetime import timezone
|
||||
dt = dt.astimezone(timezone.utc).replace(microsecond=0)
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
# ------------------------------------------------------------- keyring 管理
|
||||
|
||||
def build_keyring(entries):
|
||||
"""[{key_id, public_key_pem, revoked, spki_sha256?}] → {key_id: {"key": pub, "revoked": bool}}。
|
||||
|
||||
pinned 文件本身配置错(非 P-256 / 解不开 / 指纹不符)要立刻暴露,不能静默当不可信。
|
||||
spki_sha256(受控交付时随公钥附来的 SPKI DER SHA-256 十六进制)选填:
|
||||
给了就实算比对,防 PEM 在拷贝/转存中被损坏(yhy-license-trust v1 口径)。
|
||||
"""
|
||||
ring = {}
|
||||
for e in entries or []:
|
||||
kid, pem = e.get("key_id"), e.get("public_key_pem")
|
||||
if not kid or not pem:
|
||||
raise VerifyError("pinned_keys 条目缺 key_id/public_key_pem")
|
||||
key = serialization.load_pem_public_key(pem.encode("utf-8"))
|
||||
if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1):
|
||||
raise VerifyError("key_id=%s 的公钥不是 EC P-256" % kid)
|
||||
want = e.get("spki_sha256")
|
||||
if want:
|
||||
der = key.public_bytes(serialization.Encoding.DER,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
got = hashlib.sha256(der).hexdigest()
|
||||
if got != str(want).strip().lower():
|
||||
raise VerifyError("key_id=%s 公钥指纹不符(spki_sha256 与 PEM 不匹配,"
|
||||
"疑似拷贝损坏或调包)" % kid)
|
||||
ring[kid] = {"key": key, "revoked": bool(e.get("revoked", False))}
|
||||
return ring
|
||||
|
||||
|
||||
def load_keyring_file(path):
|
||||
"""读取随软件分发的 pinned_keys.json(不存在/为空 = 未配置信任根,fail closed)。"""
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return build_keyring(data.get("pinned_keys"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 规范化
|
||||
|
||||
# 字段类型白名单:ID 三兄弟必须真整数(bool 也拒);时间字段必须合法 RFC3339
|
||||
_INT_FIELDS = {"license_id", "customer_id", "product_id"}
|
||||
_TIME_FIELDS = {"starts_at", "expires_at", "server_time",
|
||||
"entitlement_expires_at", "lease_expires_at"}
|
||||
|
||||
|
||||
def _field_value(payload, name):
|
||||
v = payload[name]
|
||||
if isinstance(v, bool) or v is None or isinstance(v, (list, dict, float)):
|
||||
raise VerifyError("字段 %s 类型非法" % name)
|
||||
if isinstance(v, int) or name in _INT_FIELDS:
|
||||
if not isinstance(v, int) or v <= 0:
|
||||
raise VerifyError("字段 %s 必须是正整数" % name)
|
||||
return str(v) # ID:正十进制整数
|
||||
if not isinstance(v, str):
|
||||
raise VerifyError("字段 %s 类型非法" % name)
|
||||
if any(c in v for c in ("\r", "\n", "\x00")):
|
||||
raise VerifyError("字段 %s 含 CR/LF/NUL" % name)
|
||||
if name in _TIME_FIELDS:
|
||||
parse_rfc3339(v) # 时间字段必须是合法 RFC3339
|
||||
elif not v:
|
||||
raise VerifyError("字段 %s 不能为空" % name)
|
||||
return v
|
||||
|
||||
|
||||
def canonical_bytes(payload, version):
|
||||
"""规范化字节串:固定顺序 key=value、LF 连接、无末尾 LF、UTF-8。"""
|
||||
if version not in FIELDSETS:
|
||||
raise VerifyError("未知信封版本:%r" % (version,))
|
||||
out = []
|
||||
for name in FIELDSETS[version]:
|
||||
if name not in payload:
|
||||
raise VerifyError("payload 缺字段 %s" % name)
|
||||
out.append("%s=%s" % (name, _field_value(payload, name)))
|
||||
if version == LICENSE_V2:
|
||||
# 可选权益字段:签发方带了才进 canonical(顺序固定);取值合法性由 _check_payload 管
|
||||
for name in OPTIONAL_CERT_FIELDS:
|
||||
if name in payload:
|
||||
v = payload[name]
|
||||
out.append("%s=%s" % (name, str(v) if isinstance(v, int) else v))
|
||||
return "\n".join(out).encode("utf-8")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 结构校验
|
||||
|
||||
def _check_payload(payload, version, expected_instance):
|
||||
if not isinstance(payload, dict):
|
||||
raise VerifyError("payload 不是对象")
|
||||
keys = set(payload.keys())
|
||||
required = set(FIELDSETS[version])
|
||||
if version == LICENSE_V2:
|
||||
# 必填全在;多出的键只能是可选权益字段(edition/max_seats),其余多字段仍拒
|
||||
if (keys - required) - set(OPTIONAL_CERT_FIELDS) or required - keys:
|
||||
raise VerifyError("payload 字段集不符(缺/多字段)")
|
||||
ed = payload.get("edition")
|
||||
if ed is not None and (not isinstance(ed, str) or ed not in EDITIONS
|
||||
or any(c in ed for c in ("\r", "\n", "\x00"))):
|
||||
raise VerifyError("edition 取值非法")
|
||||
ms = payload.get("max_seats")
|
||||
if ms is not None and (isinstance(ms, bool) or not isinstance(ms, int) or ms < 1):
|
||||
raise VerifyError("max_seats 必须是正整数")
|
||||
elif keys != required:
|
||||
raise VerifyError("payload 字段集不符(缺/多字段)")
|
||||
if payload["version"] != version:
|
||||
raise VerifyError("payload.version=%r 不是 %s" % (payload["version"], version))
|
||||
for name in FIELDSETS[version]:
|
||||
_field_value(payload, name) # 类型/字符白名单
|
||||
if not UUID_RE.match(str(payload["instance_id"])):
|
||||
raise VerifyError("instance_id 不是 UUID")
|
||||
if expected_instance and str(payload["instance_id"]).lower() != str(expected_instance).lower():
|
||||
raise VerifyError("信封绑定到其他实例")
|
||||
if version == LICENSE_V2:
|
||||
parse_rfc3339(payload["starts_at"])
|
||||
parse_rfc3339(payload["expires_at"])
|
||||
else:
|
||||
if payload["state"] not in LEASE_STATES:
|
||||
raise VerifyError("租约状态非法:%r" % (payload["state"],))
|
||||
parse_rfc3339(payload["server_time"])
|
||||
parse_rfc3339(payload["entitlement_expires_at"])
|
||||
parse_rfc3339(payload["lease_expires_at"])
|
||||
|
||||
|
||||
def _decode_signature(sig):
|
||||
if not isinstance(sig, str) or not sig:
|
||||
raise VerifyError("signature 缺失或非法")
|
||||
if "-" in sig or "_" in sig: # Base64URL 字母表 → 拒
|
||||
raise VerifyError("signature 疑似 Base64URL 编码")
|
||||
pad = "=" * (-len(sig) % 4)
|
||||
try:
|
||||
return base64.b64decode(sig + pad, validate=True)
|
||||
except Exception:
|
||||
raise VerifyError("signature 不是标准 Base64")
|
||||
|
||||
|
||||
def _check_aux_sha(envelope, canonical):
|
||||
want = envelope.get("canonical_sha256")
|
||||
if not isinstance(want, str):
|
||||
raise VerifyError("canonical_sha256 缺失或非法")
|
||||
got = hashlib.sha256(canonical).hexdigest()
|
||||
if want.lower() != got:
|
||||
raise VerifyError("canonical_sha256 不符(载荷与规范化串不一致)")
|
||||
|
||||
|
||||
def _verify_with_keyring(envelope_keys, envelope, version, expected_instance, keyring):
|
||||
if not isinstance(envelope, dict) or set(envelope.keys()) != envelope_keys:
|
||||
raise VerifyError("信封字段集不符(缺/多字段)")
|
||||
payload = envelope.get("payload")
|
||||
_check_payload(payload, version, expected_instance)
|
||||
kid = payload["key_id"]
|
||||
ent = keyring.get(kid) if isinstance(keyring, dict) else None
|
||||
if ent is None:
|
||||
raise VerifyError("未知 key_id:%r(不在可信公钥清单)" % (kid,))
|
||||
if ent["revoked"]:
|
||||
raise VerifyError("key_id=%s 已撤销" % kid)
|
||||
canonical = canonical_bytes(payload, version)
|
||||
_check_aux_sha(envelope, canonical)
|
||||
der = _decode_signature(envelope.get("signature"))
|
||||
try:
|
||||
ent["key"].verify(der, canonical, ec.ECDSA(hashes.SHA256()))
|
||||
except InvalidSignature:
|
||||
raise VerifyError("签名无效")
|
||||
return payload
|
||||
|
||||
|
||||
def verify_certificate(envelope, expected_instance, keyring):
|
||||
"""激活证书(license-v2):信封含 version 字段。"""
|
||||
return _verify_with_keyring(CERT_ENVELOPE_KEYS, envelope, LICENSE_V2,
|
||||
expected_instance, keyring)
|
||||
|
||||
|
||||
def verify_lease(envelope, expected_instance, keyring):
|
||||
"""运行租约(lease-v2):信封含 algorithm / next_heartbeat_seconds。"""
|
||||
if envelope.get("algorithm") != ALGORITHM:
|
||||
raise VerifyError("algorithm=%r 不是 %s" % (envelope.get("algorithm"), ALGORITHM))
|
||||
nhs = envelope.get("next_heartbeat_seconds")
|
||||
if isinstance(nhs, bool) or not isinstance(nhs, int) or nhs < 60:
|
||||
raise VerifyError("next_heartbeat_seconds 必须是 ≥60 的整数")
|
||||
return _verify_with_keyring(LEASE_ENVELOPE_KEYS, envelope, LEASE_V2,
|
||||
expected_instance, keyring)
|
||||
@@ -1,800 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""MCP 接入层(2026-10-15 上线;2026-10-27 主人重定义:**只读**)。
|
||||
|
||||
- 传输:Streamable HTTP(POST /mcp,JSON-RPC 2.0,单响应 JSON;无 SSE/无会话态,stateless)
|
||||
- 开关:全局设置 mcp_enabled(**默认关**——断开就是连不上,403);令牌 mcp_token
|
||||
(首次开启自动生成,调用必须带 Authorization: Bearer <令牌>,/api/mcp/status 可查)
|
||||
- 收费挂钩:license enforce 时未激活/过期(套餐范围外且临时卡失效)→ 整个端点
|
||||
403 LICENSE_REQUIRED(开关开了也断)
|
||||
- 工具(2026-10-29 决策 238/239 起 9 个;①~⑤⑧ 只读,⑥⑦⑨ 写入为**主人拍板新增**,
|
||||
取代 2026-10-27「只读、无任何增删改」旧口径):
|
||||
① bills_query 入库项目清单:编号/名称/项目特征/单价
|
||||
② lme_prices 工料机单价
|
||||
③ market_info_prices 市场价/信息价数据
|
||||
④ recent_review_query 工作台最近审核(口径同 ①②)
|
||||
⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律
|
||||
不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch
|
||||
(价格批次原件);不支持枚举、不支持全量下载
|
||||
⑥ project_import 整项目导入(写入):整项目模板 xlsx(项目目录+多对 Sheet)→ 建手工工程
|
||||
⑦ bill_adopt 清单采纳(写入):走软件采纳同一条 API,整套术语表口径,可取消可追溯;
|
||||
仅在用户明确要求采纳时调用
|
||||
⑧ match_hist 历史价匹配 top-N:对会话一行找最像的历史价(match.py 同一管线),
|
||||
行带 ref 票据供 ⑦⑨ 采纳
|
||||
⑨ lme_adopt 工料机价格采纳(写入):采纳即改价(页面同一条通道),价格数字来自
|
||||
⑧ 的服务端快照,不接受调用方传数字;仅在用户明确要求采纳时调用
|
||||
- 零新增依赖:JSON-RPC 手写,只依赖标准库
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
import uuid
|
||||
|
||||
PROTO_VERSION = "2025-06-18"
|
||||
_API = None # api_server 模块(bind 注入,避免循环导入)
|
||||
ATT_MAX_DL = 20 * 1024 * 1024 # 单附件下载上限:超过请走软件界面下载
|
||||
|
||||
|
||||
def bind(api_module):
|
||||
global _API
|
||||
_API = api_module
|
||||
|
||||
|
||||
def _api():
|
||||
if _API is None:
|
||||
raise RuntimeError("mcp_server 未 bind")
|
||||
return _API
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 开关 / 令牌 / 门禁
|
||||
|
||||
def enabled():
|
||||
a = _api()
|
||||
return (a._setting_get("global", "mcp_enabled") or "") == "1"
|
||||
|
||||
|
||||
def token():
|
||||
a = _api()
|
||||
return a._setting_get("global", "mcp_token") or ""
|
||||
|
||||
|
||||
def set_enabled(on):
|
||||
"""开关(持久化,重启保持)。打开时没有令牌就生成一个。返回 (enabled, token)。"""
|
||||
a = _api()
|
||||
tok = token()
|
||||
if on and not tok:
|
||||
tok = secrets.token_hex(16)
|
||||
a._setting_set("global", "mcp_token", tok)
|
||||
a._setting_set("global", "mcp_enabled", "1" if on else "0")
|
||||
return on, tok
|
||||
|
||||
|
||||
def status():
|
||||
a = _api()
|
||||
return {"enabled": enabled(), "token": token(), "tools": len(TOOLS()),
|
||||
"endpoint": "/mcp", "port": a.PORT, "license_enforced": bool(a.license_gate._cfg.get("enforce", True))}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具实现(只读)
|
||||
|
||||
def _hist(fn):
|
||||
"""历史库只读查询(入库项目 / 市场价信息价 / 附件绑定)。"""
|
||||
a = _api()
|
||||
con = a.conn()
|
||||
try:
|
||||
return fn(con)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _sess(fn):
|
||||
"""会话库只读查询(工作台最近审核)。"""
|
||||
a = _api()
|
||||
sc = a.sess.connect()
|
||||
try:
|
||||
return fn(sc)
|
||||
finally:
|
||||
sc.close()
|
||||
|
||||
|
||||
def _paging(args):
|
||||
"""limit 归一:默认 10,1~100。
|
||||
2026-11-02 主人定:智能体命令没说条数=只给匹配前 10 条;说了最多给到 100。"""
|
||||
try:
|
||||
return min(max(int(args.get("limit") or 10), 1), 100)
|
||||
except (TypeError, ValueError):
|
||||
return 10
|
||||
|
||||
|
||||
def _need_scope(args):
|
||||
"""查询范围守卫:keyword 或 batch_id 至少给一个(防空量拖库)。"""
|
||||
kw = (args.get("keyword") or "").strip()
|
||||
try:
|
||||
bid = int(args.get("batch_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
bid = 0
|
||||
return kw, bid
|
||||
|
||||
|
||||
def _rows(con, sql, params):
|
||||
cur = con.execute(sql, params)
|
||||
cols = [d[0] for d in cur.description]
|
||||
return [dict(zip(cols, r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _t_bills_query(args):
|
||||
"""① 入库项目清单:Number(编号)/Name(名称)/Attr(项目特征)/Price(单价)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(清单编号/名称关键词)或 batch_id 之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT b.id, b.batch_id, t.Name AS batch_name, b.Number, b.Name, b.Attr, b.Price "
|
||||
"FROM bills b JOIN batches t ON t.id = b.batch_id "
|
||||
"WHERE t.kind='project'")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND b.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (b.Number LIKE ? OR b.Name LIKE ?)"
|
||||
params += ["%%%s%%" % kw, "%%%s%%" % kw]
|
||||
sql += " ORDER BY b.batch_id, b.x_seq LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_lme_prices(args):
|
||||
"""② 工料机单价:NoTaxPrice(除税)/TaxRate(税率)/TaxPrice(含税)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(工料机编号/名称/规格关键词)或 batch_id 之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT l.id, l.batch_id, t.Name AS batch_name, l.Number, l.Name, "
|
||||
"l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice "
|
||||
"FROM lmes l JOIN batches t ON t.id = l.batch_id "
|
||||
"WHERE t.kind='project'")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND l.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (l.Number LIKE ? OR l.Name LIKE ? OR l.Specification LIKE ?)"
|
||||
params += ["%%%s%%" % kw] * 3
|
||||
sql += " ORDER BY l.batch_id, l.id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_market_info_prices(args):
|
||||
"""③ 市场价/信息价数据(价格批次明细)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(编号/名称关键词)或 batch_id(价格批次 id)之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT p.id, p.batch_id, t.Name AS batch_name, t.x_publisher, p.Code, p.Name, "
|
||||
"p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Class "
|
||||
"FROM prices p JOIN batches t ON t.id = p.batch_id "
|
||||
"WHERE t.kind IN ('info', 'market')")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND p.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (p.Code LIKE ? OR p.Name LIKE ?)"
|
||||
params += ["%%%s%%" % kw, "%%%s%%" % kw]
|
||||
sql += " ORDER BY p.batch_id, p.id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_recent_review_query(args):
|
||||
"""④ 工作台最近审核:不带 session_id → 最近会话列表;带 session_id+type → 行数据
|
||||
(type=bills 口径同 ①,type=lmes 口径同 ②)。"""
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
sid = 0
|
||||
typ = (args.get("type") or "").strip().lower()
|
||||
kw = (args.get("keyword") or "").strip()
|
||||
lim = _paging(args)
|
||||
if not sid:
|
||||
rows = _sess(lambda sc: _rows(
|
||||
sc, "SELECT id, name, period_from, period_to, imported_at, x_total "
|
||||
"FROM sessions ORDER BY imported_at DESC LIMIT ?", (lim,)))
|
||||
return {"ok": True, "total": len(rows), "rows": rows,
|
||||
"hint": "带 session_id + type(bills/lmes)查行数据"}
|
||||
if typ not in ("bills", "lmes"):
|
||||
return {"ok": False, "msg": "type 必须是 bills 或 lmes(不带 type 时返回会话列表)"}
|
||||
if typ == "bills":
|
||||
sql = ("SELECT id, Number, Name, Attr, Price, Unit, Quantity "
|
||||
"FROM s_bills WHERE session_id=?")
|
||||
else:
|
||||
sql = ("SELECT id, Number, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice "
|
||||
"FROM s_lmes WHERE session_id=?")
|
||||
params = [sid]
|
||||
if kw:
|
||||
if typ == "bills":
|
||||
sql += " AND (Number LIKE ? OR Name LIKE ?)"
|
||||
else:
|
||||
sql += " AND (Number LIKE ? OR Name LIKE ? OR Specification LIKE ?)"
|
||||
params += ["%%%s%%" % kw] * (2 if typ == "bills" else 3)
|
||||
sql += " ORDER BY id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _sess(lambda sc: _rows(sc, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具实现(写入,决策 238)
|
||||
|
||||
def _period_to_m(v):
|
||||
"""'YYYY-MM' 或 'YYYY/MM' 或 月序号 → 月序号(年*12+月);非法返回 None。"""
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip()
|
||||
m = re.match(r"^(\d{4})[-/年](\d{1,2})", s)
|
||||
if m:
|
||||
return int(m.group(1)) * 12 + int(m.group(2))
|
||||
try:
|
||||
n = int(float(s))
|
||||
return n if n > 0 else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _t_project_import(args):
|
||||
"""⑥ 整项目导入(决策 238,写入):整项目模板 xlsx(项目目录+多对 Sheet,每对=1 个单位工程)
|
||||
→ 建手工工程(目录树+清单一次到位)。file_b64=xlsx 内容(base64)。同名手工工程再次导入=整项目覆盖。
|
||||
导入后可用 recent_review_query 查该工程(session_id),再用 bill_adopt 采纳。"""
|
||||
a = _api()
|
||||
name = (args.get("name") or "").strip()
|
||||
if not name:
|
||||
return {"ok": False, "msg": "name(工程名称)必填"}
|
||||
pf = _period_to_m(args.get("period_from"))
|
||||
pt = _period_to_m(args.get("period_to") or args.get("period_from"))
|
||||
if pf is None or pt is None:
|
||||
return {"ok": False, "msg": "period_from(YYYY-MM)必填;period_to 缺省=同 period_from"}
|
||||
b64 = (args.get("file_b64") or "").strip()
|
||||
if not b64:
|
||||
return {"ok": False, "msg": "file_b64(整项目模板 xlsx 的 base64 内容)必填——先向用户要 Excel 或按 template 说明生成"}
|
||||
import base64 as _b64
|
||||
try:
|
||||
raw = _b64.b64decode(b64, validate=True)
|
||||
except Exception:
|
||||
return {"ok": False, "msg": "file_b64 不是合法 base64"}
|
||||
d = os.path.join(a.DATA_DIR, "manual_projects")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
path = os.path.join(d, "mcp_%s.xlsx" % time.strftime("%Y%m%d_%H%M%S"))
|
||||
with open(path, "wb") as f:
|
||||
f.write(raw)
|
||||
body = {"name": name, "period_from": pf, "period_to": pt, "path": path,
|
||||
"province": (args.get("province") or "").strip(),
|
||||
"city": (args.get("city") or "").strip(),
|
||||
"district": (args.get("district") or "").strip(),
|
||||
"bulid_unit": (args.get("bulid_unit") or "").strip()}
|
||||
with a.WRITE_LOCK:
|
||||
con = a.sess.connect()
|
||||
try:
|
||||
r = a.mimp.import_project(con, body)
|
||||
con.commit()
|
||||
except Exception as e:
|
||||
r = {"ok": False, "msg": "导入异常:%s" % e}
|
||||
finally:
|
||||
con.close()
|
||||
if r.get("ok"):
|
||||
r["next"] = "recent_review_query(session_id=%s) 查清单;bill_adopt(session_id, bill_id, src_bill_id) 采纳" % r.get("sid")
|
||||
return r
|
||||
|
||||
|
||||
def _t_bill_adopt(args):
|
||||
"""⑦ 清单采纳(决策 238,写入):把入库项目清单的定额+消耗量落到工作台会话。
|
||||
bill_id=会话清单 id、src_bill_id=入库项目清单 id(都来自查询结果);走软件采纳同一条
|
||||
API(术语表整套口径:新行覆盖/已有行追加、取价锚、可取消可追溯)。仅在用户明确要求
|
||||
采纳时调用;每次一条,采纳后把结果如实告诉用户。"""
|
||||
a = _api()
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
bid = int(args.get("bill_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "session_id / bill_id 都必须是整数 id"}
|
||||
src = 0
|
||||
snap = None
|
||||
if args.get("ref"):
|
||||
snap = _MATCH_CACHE.get((args.get("ref") or "").strip())
|
||||
if not snap or snap.get("type") != "bill":
|
||||
return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist(type=bill)重新匹配"}
|
||||
try:
|
||||
src = int(snap.get("bill_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
src = 0
|
||||
if not src:
|
||||
return {"ok": False, "msg": "该匹配行缺少来源清单 id,无法采纳"}
|
||||
else:
|
||||
try:
|
||||
src = int(args.get("src_bill_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "src_bill_id 必须是整数 id(或改传 ref 票据)"}
|
||||
if not sid or not bid or not src:
|
||||
return {"ok": False, "msg": "参数:session_id(工作台会话)+ bill_id(会话清单)+ src_bill_id(或 ref 票据)"}
|
||||
with a.WRITE_LOCK: # 会话写库统一串行;采纳后分组缓存必撤(与页面路由同口径)
|
||||
sc = a.sess.connect()
|
||||
hc = a.conn()
|
||||
try:
|
||||
r = a.api_bill_adopt(sc, hc, {"session_id": sid, "bill_id": bid, "src_bill_id": src})
|
||||
sc.commit()
|
||||
if r.get("ok"):
|
||||
try:
|
||||
a._grp_cache_drop("session", sid)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
sc.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
r = {"ok": False, "msg": "采纳失败:%s" % e}
|
||||
finally:
|
||||
sc.close()
|
||||
hc.close()
|
||||
return r
|
||||
|
||||
|
||||
# ---- 决策 239(2026-10-29 主人定):历史价匹配 top-N + 工料机价格采纳 ----
|
||||
# match_hist 返回行带 ref 票据:行数据快照(三价/名称/项目名)存本进程缓存,lme_adopt 只传
|
||||
# ref——被采纳的数字全部由服务端快照取,智能体零转录、改不了价。缓存仅进程内,超限整体清空
|
||||
#(语义=ref 失效请重新 match),不落盘、无泄漏面。
|
||||
_MATCH_CACHE = {}
|
||||
_MATCH_CACHE_MAX = 2000
|
||||
|
||||
|
||||
def _match_ref(row):
|
||||
if len(_MATCH_CACHE) >= _MATCH_CACHE_MAX:
|
||||
_MATCH_CACHE.clear()
|
||||
ref = uuid.uuid4().hex[:12]
|
||||
_MATCH_CACHE[ref] = row
|
||||
return ref
|
||||
|
||||
|
||||
def _sess_row_ctx(sc, sid):
|
||||
"""会话元信息 + 匹配停用词(与工作台比对路由同口径)。"""
|
||||
a = _api()
|
||||
s = sc.execute("SELECT name, src_name, base_period_m, period_from, period_to FROM sessions WHERE id=?",
|
||||
(sid,)).fetchone()
|
||||
if not s:
|
||||
return None
|
||||
pf = (s["period_from"] if "period_from" in s.keys() else None) or s["base_period_m"] or 0
|
||||
pt = (s["period_to"] if "period_to" in s.keys() else None) or pf
|
||||
sw = a._setting_get("global", "match_stopwords")
|
||||
try:
|
||||
a.match.set_stopwords(json.loads(sw)) if sw else a.match.set_stopwords([])
|
||||
except Exception:
|
||||
a.match.set_stopwords([])
|
||||
return {"base": (pf, pt),
|
||||
"self_name": (s["name"] or "").strip(),
|
||||
"self_src": (s["src_name"] or "").split(";")[0].strip()}
|
||||
|
||||
|
||||
def _t_match_hist(args):
|
||||
"""⑧ 历史价匹配 top-N(决策 239,只读):对工作台的一行(清单或工料机)在全部入库项目/
|
||||
信息价/市场价里找最像的历史价,按 档位+期次距离 排序返回 top-N。每行带 ref 票据——
|
||||
bill_adopt / lme_adopt 用它采纳,不需要再传价格数字。"""
|
||||
a = _api()
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
rid = int(args.get("row_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "session_id / row_id 必须是整数 id"}
|
||||
typ = (args.get("type") or "bill").strip().lower()
|
||||
if typ not in ("bill", "lme"):
|
||||
return {"ok": False, "msg": "type 必须是 bill(清单)或 lme(工料机)"}
|
||||
if not sid or not rid:
|
||||
return {"ok": False, "msg": "参数:session_id + row_id(来自 recent_review_query 的行 id)"}
|
||||
try:
|
||||
limit = min(max(int(args.get("limit") or 5), 1), 20)
|
||||
except (TypeError, ValueError):
|
||||
limit = 5
|
||||
sc = a.sess.connect()
|
||||
hc = a.conn()
|
||||
try:
|
||||
ctx = _sess_row_ctx(sc, sid)
|
||||
if ctx is None:
|
||||
return {"ok": False, "msg": "会话不存在(%d)" % sid}
|
||||
if typ == "lme":
|
||||
row = sc.execute("SELECT * FROM s_lmes WHERE id=? AND session_id=?", (rid, sid)).fetchone()
|
||||
if not row:
|
||||
return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"}
|
||||
res = a.match.match_lme(hc, row, ctx["base"], limit=limit,
|
||||
self_name=ctx["self_name"], self_src=ctx["self_src"])
|
||||
else:
|
||||
row = sc.execute("SELECT * FROM s_bills WHERE id=? AND session_id=?", (rid, sid)).fetchone()
|
||||
if not row:
|
||||
return {"ok": False, "msg": "清单行不存在(可能已被删除,请刷新)"}
|
||||
res = a.match.match_bill(hc, row, ctx["base"], [], [], [], limit,
|
||||
self_name=ctx["self_name"], self_src=ctx["self_src"])
|
||||
finally:
|
||||
sc.close()
|
||||
hc.close()
|
||||
out = []
|
||||
for r in res:
|
||||
ref = _match_ref({"type": typ, **{k: r.get(k) for k in
|
||||
("name", "attr", "spec", "unit", "price", "tax", "price_tax", "proj", "src", "src_id", "bill_id")}})
|
||||
out.append({"ref": ref, "tier": r.get("tier"), "src": r.get("src"),
|
||||
"name": r.get("name"), "spec": r.get("spec") or r.get("attr"),
|
||||
"unit": r.get("unit"), "price": r.get("price"), "tax": r.get("tax"),
|
||||
"price_tax": r.get("price_tax"), "proj": r.get("proj"),
|
||||
"period": r.get("period"), "sim": r.get("sim")})
|
||||
return {"ok": True, "total": len(out),
|
||||
"hint": "挑最合适的一行,把它的 ref 传给 %s 采纳" % ("lme_adopt" if typ == "lme" else "bill_adopt"),
|
||||
"rows": out}
|
||||
|
||||
|
||||
def _t_lme_adopt(args):
|
||||
"""⑨ 工料机价格采纳(决策 239,写入,仅在用户明确要求采纳时调用)。
|
||||
lme_id=会话工料机行 id(recent_review_query type=lmes 的行)、ref=match_hist 返回的票据。
|
||||
与页面比对框「采纳」同一条通道:三价改价端点(三价联动/编码同步/merged_codes/旧价锚)
|
||||
+「采纳:名称+项目+旧三价」备注。被采纳的价格来自服务端快照,不接受调用方传数字。"""
|
||||
a = _api()
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
lid = int(args.get("lme_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "session_id / lme_id 必须是整数 id"}
|
||||
ref = (args.get("ref") or "").strip()
|
||||
snap = _MATCH_CACHE.get(ref)
|
||||
if not snap or snap.get("type") != "lme":
|
||||
return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist 重新匹配再采纳"}
|
||||
if not sid or not lid:
|
||||
return {"ok": False, "msg": "参数:session_id + lme_id(工作台工料机行 id,来自 recent_review_query)"}
|
||||
sc = a.sess.connect()
|
||||
try:
|
||||
sl = sc.execute("SELECT id, Number, Name FROM s_lmes WHERE id=? AND session_id=?", (lid, sid)).fetchone()
|
||||
if not sl:
|
||||
return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"}
|
||||
proj = sc.execute("""SELECT id, ntp, taxrate, taxp FROM s_lme_proj
|
||||
WHERE session_id=? AND code=? ORDER BY id LIMIT 1""",
|
||||
(sid, sl["Number"] or "")).fetchone() if sl["Number"] else None
|
||||
if not proj:
|
||||
return {"ok": False, "msg": "找不到该项目级工料机行(编码 %s)——项目级汇总未生成或编码为空" % (sl["Number"] or "空")}
|
||||
old = {"price": proj["ntp"], "tax": proj["taxrate"], "taxp": proj["taxp"]}
|
||||
with a.WRITE_LOCK: # 采纳即改价(决策 158)+ 采纳备注(决策 219 旧价锚口径)
|
||||
rp = a.api_lme_price(sc, {"session_id": sid, "id": proj["id"],
|
||||
"ntp": snap.get("price"), "taxrate": snap.get("tax"),
|
||||
"taxp": snap.get("price_tax")})
|
||||
if not rp.get("ok"):
|
||||
sc.rollback()
|
||||
return {"ok": False, "msg": "采纳改价失败:" + (rp.get("msg") or "服务未响应")}
|
||||
# 采纳备注文案与页面 adoptTxtFor 同口径:采纳:名称+项目+旧三价(0/空=「无」)
|
||||
def p(v):
|
||||
try:
|
||||
return "无" if (v is None or v == "" or float(v) == 0) else v
|
||||
except (TypeError, ValueError):
|
||||
return "无"
|
||||
txt = "采纳:%s+%s+%s|%s|%s" % (snap.get("name") or "", snap.get("proj") or "",
|
||||
p(old["price"]), p(old["tax"]), p(old["taxp"]))
|
||||
a.sess.save_lme_remark(sc, proj["id"], txt)
|
||||
sc.commit()
|
||||
finally:
|
||||
sc.close()
|
||||
return {"ok": True, "lme_id": proj["id"], "price": snap.get("price"),
|
||||
"tax": snap.get("tax"), "price_tax": snap.get("price_tax"), "old": old,
|
||||
"msg": "已采纳《%s》%s:除税 %s → %s" % (snap.get("name") or "", snap.get("proj") or "",
|
||||
old["price"], snap.get("price"))}
|
||||
|
||||
|
||||
def _t_attachment_download(args):
|
||||
"""⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。
|
||||
type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach);
|
||||
type=batch → 价格批次原件(batches.x_attach_sha)。"""
|
||||
a = _api()
|
||||
typ = (args.get("type") or "").strip().lower()
|
||||
try:
|
||||
rid = int(args.get("id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
rid = 0
|
||||
if typ not in ("bill", "lme", "batch") or not rid:
|
||||
return {"ok": False, "msg": "参数:type=bill|lme|batch + id(来自查询结果的行/批次 id)"}
|
||||
|
||||
def load(con):
|
||||
if typ == "bill":
|
||||
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
|
||||
"FROM bill_attach a JOIN inquiry_files f ON f.id=a.file_id "
|
||||
"WHERE a.bill_id=?", (rid,)), a.INQ_DIR
|
||||
if typ == "lme":
|
||||
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
|
||||
"FROM lme_attach a JOIN inquiry_files f ON f.id=a.file_id "
|
||||
"WHERE a.lme_id=?", (rid,)), a.INQ_DIR
|
||||
return _rows(con, "SELECT at.original_name, at.stored_path, at.size, at.sha256 "
|
||||
"FROM attachments at WHERE at.sha256="
|
||||
"(SELECT x_attach_sha FROM batches WHERE id=?)", (rid,)), a.ATTACH_DIR
|
||||
|
||||
files, root = _hist(load)
|
||||
if not files:
|
||||
return {"ok": False, "msg": "没有绑定附件(或 id 不存在)"}
|
||||
out = []
|
||||
for f in files:
|
||||
fp = os.path.realpath(os.path.join(a.DATA_DIR, f["stored_path"] or ""))
|
||||
if os.path.commonpath([fp, os.path.realpath(root)]) != os.path.realpath(root):
|
||||
return {"ok": False, "msg": "附件路径不合法,拒绝读取"}
|
||||
try:
|
||||
with open(fp, "rb") as fh:
|
||||
raw = fh.read()
|
||||
except OSError as e:
|
||||
return {"ok": False, "msg": "附件读取失败:%s" % e}
|
||||
if len(raw) > ATT_MAX_DL:
|
||||
return {"ok": False, "msg": "《%s》超过 %d MB 下载上限,请在软件界面下载"
|
||||
% ((f["original_name"] or "")[:40], ATT_MAX_DL // 1024 // 1024)}
|
||||
out.append({"name": f["original_name"], "size": f["size"], "sha256": f["sha256"],
|
||||
"content_base64": base64.b64encode(raw).decode("ascii")})
|
||||
return {"ok": True, "files": out}
|
||||
|
||||
|
||||
def _t_excel_bill_match(args):
|
||||
"""⑩ Excel 批量清单匹配(2026-11-02 主人定,只读):Excel **只放一列清单名称**(A 列,
|
||||
首行若是「清单名称/名称」表头自动跳过),逐行在全部入库项目清单里匹配**每条最优一条**
|
||||
——期次近优先、同批次名称相似度高优先。期次/地区筛选=对比框同款:
|
||||
period_from/period_to(YYYY-MM,可选,同时是期次距离基准)、province/city/district(可选)。
|
||||
行数不限;Excel 无编码无单位 → 走名称相似匹配(match_bill unit_free),无「精确编码」档属预期。"""
|
||||
a = _api()
|
||||
b64 = (args.get("file_b64") or "").strip()
|
||||
if not b64:
|
||||
return {"ok": False, "msg": "file_b64(Excel 的 base64 内容,A 列=清单名称)必填——先向用户要 Excel 或请用户粘贴名称清单"}
|
||||
import base64 as _b64
|
||||
try:
|
||||
raw = _b64.b64decode(b64, validate=True)
|
||||
except Exception:
|
||||
return {"ok": False, "msg": "file_b64 不是合法 base64"}
|
||||
pf = _period_to_m(args.get("period_from"))
|
||||
pt = _period_to_m(args.get("period_to") or args.get("period_from"))
|
||||
prov = (args.get("province") or "").strip()
|
||||
city = (args.get("city") or "").strip()
|
||||
dist = (args.get("district") or "").strip()
|
||||
area = [(prov, city, dist)] if (prov or city or dist) else None
|
||||
try:
|
||||
import io as _io
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(_io.BytesIO(raw), read_only=True, data_only=True)
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": "Excel 读取失败:%s" % e}
|
||||
names = []
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
for i, rx in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True)):
|
||||
v = rx[0] if rx else None
|
||||
v = str(v).strip() if v is not None else ""
|
||||
if not v:
|
||||
continue
|
||||
if i == 0 and v in ("清单名称", "名称", "项目名称", "清单"):
|
||||
continue # 表头行
|
||||
names.append(v)
|
||||
finally:
|
||||
wb.close()
|
||||
if not names:
|
||||
return {"ok": False, "msg": "Excel A 列没有读到任何清单名称"}
|
||||
hc = a.conn()
|
||||
rows_out = []
|
||||
try:
|
||||
base = pf if pf is not None else 0
|
||||
for nm in names:
|
||||
fake = {"Name": nm, "Unit": "", "Attr": "", "x_hash_exact": None, "x_hash_semi": None}
|
||||
try:
|
||||
res = a.match.match_bill(hc, fake, base, [], [], [], limit=8,
|
||||
pfrom=pf, pto=pt, area=area, unit_free=True)
|
||||
except Exception:
|
||||
res = []
|
||||
best = sorted(res, key=lambda r: (r.get("dist") or 0, -(r.get("sim") or 0)))[0] if res else None
|
||||
if best:
|
||||
rows_out.append({"name": nm, "hit": True, "tier": best.get("tier"),
|
||||
"match_name": best.get("name"), "unit": best.get("unit"),
|
||||
"price": best.get("price"), "proj": best.get("proj"),
|
||||
"region": best.get("region"), "period": best.get("period"),
|
||||
"sim": best.get("sim")})
|
||||
else:
|
||||
rows_out.append({"name": nm, "hit": False, "msg": "没有匹配到足够相似的历史清单"})
|
||||
finally:
|
||||
hc.close()
|
||||
return {"ok": True, "total": len(rows_out), "hit": sum(1 for r in rows_out if r["hit"]),
|
||||
"hint": "每行=Excel 一条清单的最优匹配:期次近优先、同批次名称相似度优先;price=该清单历史单价(未匹配行带 hit=false)",
|
||||
"rows": rows_out}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具清单
|
||||
|
||||
def TOOLS():
|
||||
return [
|
||||
{"name": "bills_query",
|
||||
"description": "查入库项目的清单:编号 Number、名称 Name、项目特征 Attr、单价 Price。"
|
||||
"keyword(编号/名称关键词)或 batch_id 至少给一个;limit 默认 10 上限 100(不传 limit=只返回匹配前 10 条)。"
|
||||
"响应不含附件信息。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_bills_query},
|
||||
{"name": "lme_prices",
|
||||
"description": "查入库项目的工料机单价:编号、名称、规格、单位、除税价 NoTaxPrice、"
|
||||
"税率 TaxRate、含税价 TaxPrice。keyword 或 batch_id 至少一个。响应不含附件信息。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_lme_prices},
|
||||
{"name": "market_info_prices",
|
||||
"description": "读市场价/信息价批次明细:Code、Name、Specification、Unit、三价、Class。"
|
||||
"keyword(编号/名称)或 batch_id(价格批次 id)至少一个。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_market_info_prices},
|
||||
{"name": "recent_review_query",
|
||||
"description": "读工作台最近审核:不带参数=最近会话列表;session_id + type(bills=清单"
|
||||
"编号/名称/项目特征/单价,lmes=工料机单价)查该会话行数据,口径与"
|
||||
"bills_query / lme_prices 一致。可选 keyword 过滤。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "type": {"type": "string"},
|
||||
"keyword": {"type": "string"}, "limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_recent_review_query},
|
||||
{"name": "attachment_download",
|
||||
"description": "下载绑定附件。**仅在用户明确要求下载附件时调用**(查询结果不含附件信息,"
|
||||
"不得主动调用)。id 必须来自查询结果:type=bill/lme 用 bills_query/"
|
||||
"lme_prices/recent_review_query 返回的行 id;type=batch 用价格批次 id"
|
||||
"(批次原件)。不支持枚举或全量下载。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"type": {"type": "string"}, "id": {"type": "integer"}},
|
||||
"required": ["type", "id"]},
|
||||
"run": _t_attachment_download},
|
||||
{"name": "project_import",
|
||||
"description": "整项目导入(写入)。把整项目模板 xlsx(「项目目录」Sheet 定目录树+"
|
||||
"多对数据 Sheet,每对 分部分项N/措施项目N=序号 N 的单位工程)导入建为"
|
||||
"手工工程。file_b64=xlsx 文件内容(base64);name/period_from(YYYY-MM) 必填,"
|
||||
"province/city/district/bulid_unit 可选。同名手工工程再次导入=整项目覆盖。"
|
||||
"导入成功后用 recent_review_query 查该工程清单,再按用户要求 bill_adopt。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"name": {"type": "string"}, "period_from": {"type": "string"},
|
||||
"period_to": {"type": "string"}, "file_b64": {"type": "string"},
|
||||
"province": {"type": "string"}, "city": {"type": "string"},
|
||||
"district": {"type": "string"}, "bulid_unit": {"type": "string"}},
|
||||
"required": ["name", "period_from", "file_b64"]},
|
||||
"run": _t_project_import},
|
||||
{"name": "bill_adopt",
|
||||
"description": "清单采纳(写入,仅在用户明确要求采纳时调用)。把入库项目清单的定额+消耗量"
|
||||
"落到工作台会话清单上(软件采纳同一条通道:新行=整组覆盖,已有行=单价覆盖+"
|
||||
"定额追加;可取消可追溯)。session_id=工作台会话、bill_id=会话清单 id、"
|
||||
"src_bill_id=入库项目清单 id(id 必须来自查询结果)。每次采纳一条并把结果如实告诉用户。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "bill_id": {"type": "integer"},
|
||||
"src_bill_id": {"type": "integer"}},
|
||||
"required": ["session_id", "bill_id", "src_bill_id"]},
|
||||
"run": _t_bill_adopt},
|
||||
{"name": "match_hist",
|
||||
"description": "历史价匹配 top-N(只读)。对工作台一行(清单或工料机)在全部入库项目/信息价/"
|
||||
"市场价里找最像的历史价,按档位+期次距离排序返回 top-N;每行带 ref 票据,"
|
||||
"把它传给 bill_adopt / lme_adopt 即可采纳——不需要(也不允许)自己传价格数字。"
|
||||
"session_id + row_id(来自 recent_review_query)+ type(bill/lme)+ limit(默认 5,上限 20)。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "row_id": {"type": "integer"},
|
||||
"type": {"type": "string"}, "limit": {"type": "integer"}},
|
||||
"required": ["session_id", "row_id"]},
|
||||
"run": _t_match_hist},
|
||||
{"name": "lme_adopt",
|
||||
"description": "工料机价格采纳(写入,仅在用户明确要求采纳时调用)。把匹配到的历史价"
|
||||
"(ref 票据)采纳到工作台工料机:与页面比对框「采纳」同一条通道(三价联动/"
|
||||
"编码同步/merged_codes/旧价锚+采纳备注)。lme_id=工作台工料机行 id"
|
||||
"(recent_review_query type=lmes 的行)+ ref(match_hist type=lme 返回的票据)。"
|
||||
"价格数字来自服务端快照,不接受调用方传数字;每次一条,结果如实告知用户。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "lme_id": {"type": "integer"},
|
||||
"ref": {"type": "string"}},
|
||||
"required": ["session_id", "lme_id", "ref"]},
|
||||
"run": _t_lme_adopt},
|
||||
{"name": "excel_bill_match",
|
||||
"description": "Excel 批量清单匹配(只读,数量不限)。Excel 只放一列清单名称(A 列,"
|
||||
"可有「清单名称」表头),file_b64=Excel 的 base64;逐行在全部入库项目清单里"
|
||||
"匹配每条最优一条(期次近优先、同批次名称相似度优先)。期次/地区沿用对比框"
|
||||
"筛选口径:period_from/period_to(YYYY-MM,可选)、province/city/district(可选)。"
|
||||
"适合「按某期查一批清单的历史单价」。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"file_b64": {"type": "string"}, "period_from": {"type": "string"},
|
||||
"period_to": {"type": "string"}, "province": {"type": "string"},
|
||||
"city": {"type": "string"}, "district": {"type": "string"}},
|
||||
"required": ["file_b64"]},
|
||||
"run": _t_excel_bill_match},
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- JSON-RPC 分发
|
||||
|
||||
def _rpc_error(cid, code, message, data=None):
|
||||
e = {"code": code, "message": message}
|
||||
if data is not None:
|
||||
e["data"] = data
|
||||
return {"jsonrpc": "2.0", "id": cid, "error": e}
|
||||
|
||||
|
||||
def _rpc_result(cid, result):
|
||||
return {"jsonrpc": "2.0", "id": cid, "result": result}
|
||||
|
||||
|
||||
def _dispatch(msg):
|
||||
"""单条 JSON-RPC → (is_notification, response_obj)。"""
|
||||
method = msg.get("method", "")
|
||||
cid = msg.get("id")
|
||||
if method == "initialize":
|
||||
return False, _rpc_result(cid, {
|
||||
"protocolVersion": PROTO_VERSION,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "造价审核", "version": "mcp-2.0"}})
|
||||
if method == "ping":
|
||||
return False, _rpc_result(cid, {})
|
||||
if method == "tools/list":
|
||||
tools = [{"name": t["name"], "description": t["description"],
|
||||
"inputSchema": t["inputSchema"]} for t in TOOLS()]
|
||||
return False, _rpc_result(cid, {"tools": tools})
|
||||
if method == "tools/call":
|
||||
params = msg.get("params") or {}
|
||||
name = params.get("name", "")
|
||||
args = params.get("arguments") or {}
|
||||
for t in TOOLS():
|
||||
if t["name"] == name:
|
||||
try:
|
||||
out = t["run"](args)
|
||||
text = json.dumps(out, ensure_ascii=False, default=str)
|
||||
return False, _rpc_result(cid, {"content": [{"type": "text", "text": text}],
|
||||
"isError": bool(out.get("ok") is False)})
|
||||
except Exception as e:
|
||||
return False, _rpc_result(cid, {
|
||||
"content": [{"type": "text", "text": "工具执行异常:%s" % e}], "isError": True})
|
||||
return False, _rpc_error(cid, -32602, "未知工具:%s" % name)
|
||||
if cid is None:
|
||||
return True, None # 未知通知:忽略
|
||||
return False, _rpc_error(cid, -32601, "未知方法:%s" % method)
|
||||
|
||||
|
||||
def handle_post(auth_header, body_text):
|
||||
"""POST /mcp 入口。返回 (HTTP 状态码, 响应对象或 None[202])。
|
||||
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时套餐范围外且临时卡失效整端点断)。"""
|
||||
a = _api()
|
||||
if not enabled():
|
||||
return 403, {"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32001, "message": "MCP 未开启:请在软件「设置 → MCP 接入」打开开关",
|
||||
"data": {"switch_api": "/api/admin/mcp"}}}
|
||||
tok = token()
|
||||
given = (auth_header or "").strip()
|
||||
if given.lower().startswith("bearer "):
|
||||
given = given[7:].strip()
|
||||
if not tok or not given or not secrets.compare_digest(given, tok):
|
||||
return 401, {"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32002, "message": "令牌缺失或不正确(Authorization: Bearer <令牌>;"
|
||||
"令牌见软件「设置 → MCP 接入」或 /api/mcp/status)"}}
|
||||
ok, reason = a.license_gate.can_run_now()
|
||||
if not ok:
|
||||
return 403, {"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32003, "message": "授权不可用:%s" % reason,
|
||||
"data": {"code": "LICENSE_REQUIRED"}}}
|
||||
try:
|
||||
payload = json.loads(body_text or "null")
|
||||
except Exception:
|
||||
return 400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "JSON 解析失败"}}
|
||||
msgs = payload if isinstance(payload, list) else [payload]
|
||||
if not msgs:
|
||||
return 400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "空请求"}}
|
||||
outs, has_call = [], False
|
||||
for m in msgs:
|
||||
if not isinstance(m, dict):
|
||||
outs.append(_rpc_error(None, -32600, "请求必须是对象"))
|
||||
has_call = True
|
||||
continue
|
||||
is_note, resp = _dispatch(m)
|
||||
if not is_note:
|
||||
outs.append(resp)
|
||||
has_call = True
|
||||
if not has_call:
|
||||
return 202, None # 纯通知:202 空体
|
||||
if isinstance(payload, list):
|
||||
return 200, outs
|
||||
return 200, outs[0]
|
||||
@@ -1,226 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""强制更新门禁 version_gate(2026-10-27,《企业和个人版.md》5.9,主人拍板)。
|
||||
|
||||
- 版本信息文件:软件商统一服务器静态 JSON
|
||||
{latest_version, min_required_version, release_notes, package_url, sha256}
|
||||
(URL 出包烧入 BUILD.VERSION_INFO_URL;开发态无 BUILD → 一律旁路,不拉取不拦截)。
|
||||
- 拉取:启动 + 后台低频线程(默认 30 分钟),成功后原子落盘 data/version_cache.json
|
||||
(首装包可预置一份快照,由 build_portable 负责;拉取失败静默沿用旧缓存)。
|
||||
- 判定(纯本地,只读缓存):当前 APP_VERSION < min_required_version → 全员阻断
|
||||
(页面回自包含强制更新页;API 回 403 UPDATE_REQUIRED,绝不回 HTML 给 API——
|
||||
同授权门禁纪律);否则放行,仅版本卡提示有新版。
|
||||
- fail 原则:版本检查不得比授权更硬——从未拉到且无快照 = 不拦;
|
||||
min_required_version 解析失败 = 不拦(视为 0);断网用最近缓存判定
|
||||
(与租约 7 天口径天然对齐:长期断网本来就会被授权先拦住)。
|
||||
- 升级 = 换包(B/S 只更服务器):新版 APP_VERSION ≥ min_required 自动解除拦截。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import license_build_config as BUILD # 出包生成;开发态不存在
|
||||
except Exception:
|
||||
try:
|
||||
import license_build_config as BUILD # 裸跑(server/ 直挂 sys.path)时
|
||||
except Exception:
|
||||
BUILD = None
|
||||
|
||||
CACHE_NAME = "version_cache.json"
|
||||
ALWAYS_PREFIX = ("/api/license/", "/api/version") # 授权三口 + 版本状态口:永不拦
|
||||
DEFAULT_INTERVAL = 30 * 60 # 后台拉取间隔(秒)
|
||||
FETCH_TIMEOUT = 10.0
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cache = None # 最近一次成功拉取的信息(含 fetched_at)
|
||||
_cfg = {"app_version": None, "info_url": None, "interval": DEFAULT_INTERVAL,
|
||||
"data_dir": None}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 版本比较
|
||||
|
||||
def vkey(s):
|
||||
"""'1.2.10' → (1, 2, 10);解析失败 → ()(配合调用方 fail-open,不当硬门禁)。"""
|
||||
try:
|
||||
return tuple(int(x) for x in str(s).strip().lstrip("vV").split("."))
|
||||
except Exception:
|
||||
return ()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 初始化/缓存
|
||||
|
||||
def init(data_dir, build=None, start_thread=True):
|
||||
"""run() 启动时调用。build 不传 = 读出包烧入的 license_build_config。"""
|
||||
b = build if build is not None else BUILD
|
||||
_cfg["data_dir"] = data_dir
|
||||
_cfg["app_version"] = str(getattr(b, "APP_VERSION", "") or "").strip() if b else None
|
||||
_cfg["info_url"] = str(getattr(b, "VERSION_INFO_URL", "") or "").strip() if b else None
|
||||
try:
|
||||
_cfg["interval"] = int(getattr(b, "VERSION_CHECK_INTERVAL", DEFAULT_INTERVAL)
|
||||
or DEFAULT_INTERVAL) if b else DEFAULT_INTERVAL
|
||||
except Exception:
|
||||
_cfg["interval"] = DEFAULT_INTERVAL
|
||||
load_cache()
|
||||
if start_thread and effective() and _cfg["info_url"]:
|
||||
threading.Thread(target=_loop, name="version-gate", daemon=True).start()
|
||||
|
||||
|
||||
def effective():
|
||||
"""开发态(无 BUILD / APP_VERSION 空 / 'dev')旁路:不拦截。"""
|
||||
v = _cfg.get("app_version")
|
||||
return bool(v) and v not in ("dev", "0.0.0")
|
||||
|
||||
|
||||
def _cache_path():
|
||||
dd = _cfg.get("data_dir")
|
||||
return os.path.join(dd, CACHE_NAME) if dd else None
|
||||
|
||||
|
||||
def load_cache():
|
||||
global _cache
|
||||
fp = _cache_path()
|
||||
if not fp:
|
||||
return None
|
||||
try:
|
||||
with open(fp, "r", encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
if isinstance(d, dict):
|
||||
_cache = d
|
||||
return d
|
||||
except Exception:
|
||||
pass # 快照损坏 = 当没有(fail-open)
|
||||
return None
|
||||
|
||||
|
||||
def _save_cache(info):
|
||||
global _cache
|
||||
_cache = info
|
||||
fp = _cache_path()
|
||||
if not fp:
|
||||
return
|
||||
tmp = fp + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, ensure_ascii=False, indent=1)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, fp) # 原子写:中断不留半个文件
|
||||
except Exception:
|
||||
pass # 写盘失败不致命:内存缓存仍在
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 拉取
|
||||
|
||||
def fetch_once(http_get=None):
|
||||
"""拉一次版本信息文件。成功 → 落缓存返回 True;失败静默返回 False(用旧缓存)。"""
|
||||
url = _cfg.get("info_url")
|
||||
if not url:
|
||||
return False
|
||||
try:
|
||||
get = http_get or _http_get
|
||||
d = get(url)
|
||||
if not isinstance(d, dict):
|
||||
return False
|
||||
if not isinstance(d.get("latest_version"), str) or \
|
||||
not isinstance(d.get("min_required_version"), str):
|
||||
return False
|
||||
keep = {k: d.get(k) for k in ("latest_version", "min_required_version",
|
||||
"release_notes", "package_url", "sha256")}
|
||||
keep["fetched_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
with _lock:
|
||||
_save_cache(keep)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _http_get(url):
|
||||
import httpx # 决策 30 已入包依赖
|
||||
r = httpx.get(url, timeout=FETCH_TIMEOUT,
|
||||
headers={"User-Agent": "costreview-versiongate/1"})
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def _loop():
|
||||
fetch_once()
|
||||
while True:
|
||||
time.sleep(max(300, _cfg.get("interval") or DEFAULT_INTERVAL))
|
||||
fetch_once()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 判定/拦截
|
||||
|
||||
def check():
|
||||
"""(ok, info)。ok=False = 低于最低要求版本。"""
|
||||
if not effective():
|
||||
return True, {"bypass": "dev"}
|
||||
c = _cache or load_cache() or {}
|
||||
cur = vkey(_cfg.get("app_version"))
|
||||
req = vkey(c.get("min_required_version"))
|
||||
info = {"current": _cfg.get("app_version"),
|
||||
"latest": c.get("latest_version") or "",
|
||||
"min_required": c.get("min_required_version") or "",
|
||||
"notes": c.get("release_notes") or "",
|
||||
"package_url": c.get("package_url") or "",
|
||||
"last_check": c.get("fetched_at") or ""}
|
||||
if not cur or not req: # 无缓存/解析失败:不拦(fail-open)
|
||||
return True, info
|
||||
return (cur >= req), info
|
||||
|
||||
|
||||
def intercept(method, path):
|
||||
"""仿 license_client.gate.intercept:None=放行;dict=拦截(html 强制页 / json 403)。"""
|
||||
if not effective():
|
||||
return None
|
||||
ok, info = check()
|
||||
if ok:
|
||||
return None
|
||||
p = (path or "").split("?")[0]
|
||||
if p.startswith(ALWAYS_PREFIX):
|
||||
return None
|
||||
if method == "GET":
|
||||
return {"kind": "html", "code": 200, "text": forced_page(info)}
|
||||
return {"kind": "json", "code": 403,
|
||||
"obj": {"error": {"code": "UPDATE_REQUIRED",
|
||||
"message": "当前版本已停止服务,请升级到 %s 或更高版本"
|
||||
% (info.get("min_required") or "最新版")}}}
|
||||
|
||||
|
||||
def status():
|
||||
"""/api/version_info:当前/最新/最低要求/是否被强制/是否有新版。"""
|
||||
ok, info = check()
|
||||
out = dict(info)
|
||||
out["forced"] = not ok
|
||||
cur, lat = vkey(info.get("current")), vkey(info.get("latest"))
|
||||
out["update_available"] = bool(ok and cur and lat and cur < lat)
|
||||
return out
|
||||
|
||||
|
||||
def forced_page(info):
|
||||
cur = info.get("current") or "?"
|
||||
req = info.get("min_required") or "?"
|
||||
notes = str(info.get("notes") or "")
|
||||
pkg = str(info.get("package_url") or "")
|
||||
return """<!DOCTYPE html>
|
||||
<html lang="zh"><head><meta charset="utf-8">
|
||||
<title>软件需要升级</title><style>
|
||||
body{font-family:"Microsoft YaHei",sans-serif;background:#f0f2f5;display:flex;
|
||||
align-items:center;justify-content:center;min-height:100vh;margin:0}
|
||||
.c{background:#fff;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.08);
|
||||
max-width:560px;padding:34px 38px}
|
||||
h1{font-size:20px;color:#b02a2a;margin:0 0 14px}
|
||||
p{color:#33475b;line-height:1.8;margin:8px 0;font-size:14px}
|
||||
.k{color:#8a97a5;font-size:12px;margin-top:18px;line-height:1.7}
|
||||
b{color:#1f2d3d}
|
||||
</style></head><body><div class="c">
|
||||
<h1>⚠ 当前版本已停止服务,需要升级</h1>
|
||||
<p>当前版本:<b>__CUR__</b> | 本软件要求的最低版本:<b>__REQ__</b></p>
|
||||
<p>升级方法:请联系软件提供方获取升级包(或在服务器上运行升级流程),完成后重新打开本页即可自动恢复。</p>
|
||||
__PKG____NOTES__
|
||||
<div class="k">本页面由本机服务提供。升级不会影响任何数据;如对升级有疑问,请联系软件提供方。
|
||||
版本状态口:/api/version_info(供排查用)。</div>
|
||||
</div></body></html>""".replace("__CUR__", cur).replace("__REQ__", req) \
|
||||
.replace("__PKG__", '<p>升级包地址:<a href="%s">%s</a></p>' % (pkg, pkg) if pkg else "") \
|
||||
.replace("__NOTES__", "<p>更新说明:%s</p>" % notes if notes else "")
|
||||
@@ -1,499 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
M5 窗口壳:双击这个脚本 → 直接弹出「造价审核」软件窗口(没有地址栏、没有标签页)。
|
||||
|
||||
内部仍然是本地服务 + 网页内容(同一个 Edge WebView2 渲染引擎),但你看到的就是一个普通软件窗口。
|
||||
|
||||
排错:每一步都会打印,并同时写进 造价审核\\data\\launch.log
|
||||
"""
|
||||
import os, re, sys, json, time, threading, urllib.request, urllib.error, urllib.parse, socket, traceback
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE) # 造价审核/
|
||||
sys.path.insert(0, os.path.join(HERE, "server"))
|
||||
sys.path.insert(0, os.path.join(HERE, "core"))
|
||||
|
||||
import api_server
|
||||
|
||||
PORT = api_server.PORT
|
||||
|
||||
|
||||
def _page_ver(name):
|
||||
"""页面文件 mtime 作版本参数(2026-10-12):文件一更新 URL 就变,任何内核的
|
||||
磁盘缓存都必然失配。起因:主人的 WebView2 对静态响应的 no-store 不完全遵守,
|
||||
价格库重设计后壳里一直显示旧界面(IAB/新浏览器带 ?v= 才是新的)。"""
|
||||
try:
|
||||
return str(int(os.path.getmtime(os.path.join(api_server.ROOT, name))))
|
||||
except Exception:
|
||||
return "0"
|
||||
|
||||
|
||||
URL = "http://127.0.0.1:%d/workbench.html?v=%s" % (PORT, _page_ver("workbench.html"))
|
||||
ADMIN_URL = "http://127.0.0.1:%d/admin.html?v=%s" % (PORT, _page_ver("admin.html"))
|
||||
LOG = os.path.join(ROOT, "data", "launch.log")
|
||||
|
||||
|
||||
# ---------- 原生「另存为」桥(决策 91,2026-10-17 主人定「全部是另存为」)----------
|
||||
# 壳里的 WebView2 对 JS 的 showSaveFilePicker 支持不稳(实测直接抛错掉进静默下载,
|
||||
# 文件落到下载目录深处主人找不到)——由 Python 侧接管:页面调
|
||||
# window.pywebview.api.download_save_as(相对url, 建议名),这里弹**原生另存为对话框**
|
||||
# (文件名预填 工程名-审核版.原后缀),把本地服务的下载内容写到所选位置。
|
||||
# 普通浏览器没有这个桥,页面自动落回原有 showSaveFilePicker 分支,互不影响。
|
||||
_LAST_SAVE_DIR = {"d": ""} # 本次运行记住的上一另存位置(下次同目录打开)
|
||||
|
||||
|
||||
class _BridgeApi:
|
||||
def set_title(self, text=""):
|
||||
"""全局语言切换时同步软件窗口标题(2026-10-19 主人定:语言控制整个软件)。"""
|
||||
try:
|
||||
import webview
|
||||
win = webview.windows[0] if webview.windows else None
|
||||
if win is None:
|
||||
return {"ok": False, "msg": "窗口未就绪"}
|
||||
win.set_title(str(text or "造价审核")[:80])
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": str(e)}
|
||||
|
||||
def export_save_as(self, session_id, suggested_name="", fmt=""):
|
||||
"""决策 92(主人定流程):点导出=①先弹原生另存为选路径(此刻还不生成,大工程不再干等)
|
||||
→②后台线程生成+分块写盘(逐条目进度经 evaluate_js 推给页面进度条)
|
||||
→③完成/失败也推给页面(模态收尾或后台 toast)。
|
||||
决策 231:fmt=cos4/cos/xlsx——手工工程导出三选,meta 与生成 URL 都带上。"""
|
||||
try:
|
||||
sid = int(session_id)
|
||||
except Exception:
|
||||
return {"ok": False, "msg": "会话参数不合法"}
|
||||
name = (suggested_name or "").strip()
|
||||
if not name:
|
||||
try:
|
||||
req = urllib.request.urlopen(
|
||||
"http://127.0.0.1:%d/api/session/export/meta?session_id=%d&fmt=%s"
|
||||
% (PORT, sid, urllib.parse.quote(fmt or "")), timeout=15)
|
||||
j = json.loads(req.read().decode("utf-8", "replace"))
|
||||
if j.get("ok"):
|
||||
name = j.get("name") or name
|
||||
elif not fmt:
|
||||
return {"ok": False, "msg": j.get("msg") or "导出失败"}
|
||||
except Exception:
|
||||
pass
|
||||
if not name:
|
||||
name = "工程导出.cos4"
|
||||
import webview
|
||||
win = webview.windows[0] if webview.windows else None
|
||||
if win is None:
|
||||
return {"ok": False, "msg": "窗口未就绪"}
|
||||
ext = os.path.splitext(name)[1]
|
||||
ftypes = ("文件 (*%s)" % ext, "所有文件 (*.*)") if ext else ("所有文件 (*.*)",)
|
||||
fd = getattr(webview, "FileDialog", None)
|
||||
dtype = fd.SAVE if fd is not None else webview.SAVE_DIALOG
|
||||
picked = win.create_file_dialog(dtype, directory=_LAST_SAVE_DIR["d"],
|
||||
save_filename=name, file_types=ftypes)
|
||||
if not picked:
|
||||
return {"ok": False, "cancel": True}
|
||||
p = picked if isinstance(picked, str) else picked[0]
|
||||
_LAST_SAVE_DIR["d"] = os.path.dirname(p)
|
||||
threading.Thread(target=self._export_worker, args=(win, sid, p, name, fmt),
|
||||
daemon=True).start()
|
||||
return {"ok": True, "started": True, "path": p, "name": name}
|
||||
|
||||
def _push(self, win, payload):
|
||||
"""进度推给页面(window.__exportProgress 由 workbench 定义;后台与否页面自己决定展示)。"""
|
||||
try:
|
||||
win.evaluate_js("window.__exportProgress && window.__exportProgress(%s)"
|
||||
% json.dumps(payload, ensure_ascii=False))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _export_worker(self, win, sid, path, name, fmt=""):
|
||||
token = "x%d" % int(time.time() * 1000000)
|
||||
base = "http://127.0.0.1:%d" % PORT
|
||||
stop = threading.Event()
|
||||
|
||||
def poller(): # 生成阶段(响应头没回来)轮询逐条目进度
|
||||
while not stop.is_set():
|
||||
try:
|
||||
r = urllib.request.urlopen(
|
||||
base + "/api/session/export/progress?token=" + token, timeout=5)
|
||||
j = json.loads(r.read().decode("utf-8", "replace"))
|
||||
if j.get("total"):
|
||||
self._push(win, {"phase": "gen", "done": j.get("done", 0),
|
||||
"total": j.get("total", 0)})
|
||||
except Exception:
|
||||
pass
|
||||
stop.wait(1.0)
|
||||
|
||||
pt = threading.Thread(target=poller, daemon=True)
|
||||
pt.start()
|
||||
tmp = path + ".part"
|
||||
try:
|
||||
self._push(win, {"phase": "gen"})
|
||||
req = urllib.request.urlopen(base + "/api/session/export?session_id=%d&token=%s&fmt=%s"
|
||||
% (sid, token, urllib.parse.quote(fmt or "")),
|
||||
timeout=3600)
|
||||
stop.set() # 响应头到了=生成完毕,轮询停;接下来按字节真实进度
|
||||
if "json" in (req.headers.get("Content-Type") or "").lower():
|
||||
j = json.loads(req.read().decode("utf-8", "replace"))
|
||||
self._push(win, {"done": False, "msg": j.get("msg") or "服务端返回错误"})
|
||||
return
|
||||
total = int(req.headers.get("Content-Length") or 0)
|
||||
done, last = 0, -1
|
||||
with open(tmp, "wb") as f:
|
||||
while True:
|
||||
chunk = req.read(262144)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
done += len(chunk)
|
||||
if total:
|
||||
pct = int(done * 100 / total)
|
||||
if pct != last:
|
||||
last = pct
|
||||
self._push(win, {"phase": "put", "pct": pct})
|
||||
if total and done != total:
|
||||
raise IOError("下载不完整 %d/%d 字节" % (done, total))
|
||||
os.replace(tmp, path)
|
||||
_log("已另存为:%s(%d 字节)" % (path, done))
|
||||
self._push(win, {"done": True, "path": path, "name": os.path.basename(path)})
|
||||
except Exception as e:
|
||||
stop.set()
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
_log("导出失败:%s\n%s" % (e, traceback.format_exc()))
|
||||
self._push(win, {"done": False, "msg": str(e)})
|
||||
finally:
|
||||
stop.set()
|
||||
|
||||
def download_save_as(self, url, suggested_name=""):
|
||||
try:
|
||||
if not url or not url.startswith("/") or url.startswith("//"):
|
||||
return {"ok": False, "msg": "非法下载地址"}
|
||||
req = urllib.request.urlopen("http://127.0.0.1:%d%s" % (PORT, url), timeout=600)
|
||||
data = req.read()
|
||||
if "json" in (req.headers.get("Content-Type") or "").lower():
|
||||
j = json.loads(data.decode("utf-8", "replace"))
|
||||
return {"ok": False, "msg": j.get("msg") or "服务端返回错误"}
|
||||
cd = req.headers.get("Content-Disposition") or ""
|
||||
name = (suggested_name or "").strip()
|
||||
m = re.search(r"filename\*=UTF-8''([^;]+)", cd)
|
||||
if not m:
|
||||
m = re.search(r'filename="([^"]+)"', cd)
|
||||
if m:
|
||||
try:
|
||||
name = urllib.parse.unquote(m.group(1), errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
if not name:
|
||||
name = "下载文件"
|
||||
import webview
|
||||
win = webview.windows[0] if webview.windows else None
|
||||
if win is None:
|
||||
return {"ok": False, "msg": "窗口未就绪"}
|
||||
ext = os.path.splitext(name)[1]
|
||||
ftypes = ("文件 (*%s)" % ext, "所有文件 (*.*)") if ext else ("所有文件 (*.*)",)
|
||||
fd = getattr(webview, "FileDialog", None)
|
||||
dtype = fd.SAVE if fd is not None else webview.SAVE_DIALOG
|
||||
picked = win.create_file_dialog(dtype, directory=_LAST_SAVE_DIR["d"],
|
||||
save_filename=name, file_types=ftypes)
|
||||
if not picked:
|
||||
return {"ok": False, "cancel": True}
|
||||
p = picked if isinstance(picked, str) else picked[0]
|
||||
_LAST_SAVE_DIR["d"] = os.path.dirname(p)
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
_log("已另存为:%s(%d 字节)" % (p, len(data)))
|
||||
return {"ok": True, "path": p, "name": os.path.basename(p)}
|
||||
except Exception as e:
|
||||
_log("另存为失败:%s\n%s" % (e, traceback.format_exc()))
|
||||
return {"ok": False, "msg": str(e)}
|
||||
|
||||
|
||||
def _log(msg):
|
||||
line = "[%s] %s" % (time.strftime("%H:%M:%S"), msg)
|
||||
print(line, flush=True)
|
||||
try:
|
||||
os.makedirs(os.path.dirname(LOG), exist_ok=True)
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def port_in_use():
|
||||
s = socket.socket()
|
||||
s.settimeout(0.5)
|
||||
ok = s.connect_ex(("127.0.0.1", PORT)) == 0
|
||||
s.close()
|
||||
return ok
|
||||
|
||||
|
||||
def server_healthy():
|
||||
"""端口有监听 ≠ 服务能用:垂死进程的套接字还能完成 TCP 握手,但 HTTP 已不应答。
|
||||
用一次带超时的 HTTP 探活区分健康/垂死(2026-10-11 启动竞态加固)。
|
||||
有任何 HTTP 应答(含 404/403)都算活;只有连接被拒/超时才算垂死。"""
|
||||
try:
|
||||
urllib.request.urlopen("http://127.0.0.1:%d/admin.html" % PORT, timeout=1)
|
||||
return True
|
||||
except urllib.error.HTTPError:
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _code_mtime():
|
||||
"""程序代码更新时间——与 api_server._code_mtime 同口径(api_server.py + core/*.py +
|
||||
server/*.py 的最新 mtime)。启动器拿它和端口上实例自报的版本比,判断是不是旧代码。"""
|
||||
import glob
|
||||
files = [os.path.abspath(__file__)]
|
||||
for sub in ("core", "server"):
|
||||
files += glob.glob(os.path.join(api_server.ROOT, sub, "*.py"))
|
||||
mt = 0.0
|
||||
for f in files:
|
||||
try:
|
||||
mt = max(mt, os.path.getmtime(f))
|
||||
except OSError:
|
||||
pass
|
||||
return mt
|
||||
|
||||
|
||||
def remote_code_mtime():
|
||||
"""端口上健康实例自报的代码时间;报不出来(更老的实例没有 /api/version)→ None=视为过期。"""
|
||||
import json
|
||||
try:
|
||||
r = urllib.request.urlopen("http://127.0.0.1:%d/api/version" % PORT, timeout=2)
|
||||
j = json.loads(r.read().decode("utf-8"))
|
||||
return float(j["code_mtime_f"]) if j.get("ok") else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def kill_port_owner():
|
||||
"""结束占用本端口的进程——只可能是我们自己的旧实例(单实例互斥保证)。"""
|
||||
import subprocess
|
||||
try:
|
||||
out = subprocess.check_output(["netstat", "-ano", "-p", "TCP"], text=True, errors="replace")
|
||||
except Exception:
|
||||
return False
|
||||
pids = set()
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 5 and parts[1] == "127.0.0.1:%d" % PORT and parts[3] == "LISTENING":
|
||||
pids.add(parts[4])
|
||||
hit = False
|
||||
for pid in pids:
|
||||
try:
|
||||
subprocess.run(["taskkill", "/PID", pid, "/F"], capture_output=True)
|
||||
hit = True
|
||||
except Exception:
|
||||
pass
|
||||
return hit
|
||||
|
||||
|
||||
def wait_ready(timeout=15):
|
||||
for _ in range(int(timeout / 0.25)):
|
||||
try:
|
||||
urllib.request.urlopen("http://127.0.0.1:%d/admin.html" % PORT, timeout=1)
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.25)
|
||||
return False
|
||||
|
||||
|
||||
def serve_admin_mode():
|
||||
"""后台管理模式:起服务 + 用默认浏览器打开后台管理,本窗口保持运行即服务在跑。"""
|
||||
import webbrowser
|
||||
_log("后台管理模式:用默认浏览器打开 %s" % ADMIN_URL)
|
||||
webbrowser.open(ADMIN_URL)
|
||||
print("已打开后台管理。要停止服务,直接关掉这个黑窗口。", flush=True)
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def fallback_to_browser(reason):
|
||||
"""独立窗口起不来时的兜底:用默认浏览器打开,至少保证能用。"""
|
||||
import webbrowser
|
||||
_log("兜底:改用默认浏览器打开(%s)" % reason)
|
||||
webbrowser.open(URL)
|
||||
print("已改用默认浏览器打开。若浏览器也没反应,请手动访问:%s" % URL, flush=True)
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
WEBVIEW2_KEY = r"Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
|
||||
WEBVIEW2_DL = "https://developer.microsoft.com/microsoft-edge/webview2/"
|
||||
|
||||
|
||||
def webview2_available():
|
||||
"""WebView2 运行库装没装:查 EdgeUpdate 的 pv 版本号(HKLM/HKCU、两种注册表视图都查)。
|
||||
|
||||
返回 True/False/None —— None = 检测不了(非 Windows / 注册表读不到),当作"可能行",
|
||||
让后面的 webview.start 异常兜底去处理,不在这里误杀。
|
||||
"""
|
||||
if os.name != "nt":
|
||||
return None
|
||||
try:
|
||||
import winreg
|
||||
except Exception:
|
||||
return None
|
||||
for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
|
||||
for view in (winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY):
|
||||
try:
|
||||
with winreg.OpenKey(root, WEBVIEW2_KEY, 0, view | winreg.KEY_READ) as k:
|
||||
pv = (winreg.QueryValueEx(k, "pv")[0] or "").strip()
|
||||
if pv and pv != "0.0.0.0":
|
||||
return True
|
||||
except OSError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def warn_webview2_missing():
|
||||
"""运行库缺失:弹窗说明 + 提供"打开官方下载页",用户关掉弹窗后走浏览器兜底。"""
|
||||
try:
|
||||
import ctypes
|
||||
MB_OKCANCEL, MB_ICONWARN = 0x0, 0x30
|
||||
r = ctypes.windll.user32.MessageBoxW(
|
||||
0,
|
||||
"独立窗口需要 Microsoft Edge WebView2 运行库,这台电脑上没有检测到。\n\n"
|
||||
"点「确定」打开官方下载页(免费,装一次即可);\n"
|
||||
"点「取消」直接用默认浏览器打开软件(功能相同)。",
|
||||
"造价审核 · 需要一次性安装组件",
|
||||
MB_OKCANCEL | MB_ICONWARN)
|
||||
if r == 1:
|
||||
import webbrowser
|
||||
webbrowser.open(WEBVIEW2_DL)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
_SRV_ERR = {}
|
||||
|
||||
|
||||
def _run_srv():
|
||||
"""后台服务线程:异常写进 launch.log,避免只剩一句“端口起不来”。"""
|
||||
try:
|
||||
api_server.run()
|
||||
except Exception:
|
||||
import traceback
|
||||
tb = traceback.format_exc()
|
||||
_SRV_ERR["tb"] = tb
|
||||
_log("本地服务异常退出:\n" + tb)
|
||||
print("本地服务异常退出:\n" + tb, flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
_log("启动中…(端口 %d)" % PORT)
|
||||
|
||||
# 1) 后台起本地服务;端口已有服务则直接复用,避免重复占用数据库
|
||||
# 2026-10-11 加固(主人拍板):端口被占 ≠ 服务健康——关窗后旧进程收尾期间套接字
|
||||
# 还没释放,新实例会误「复用」一个垂死服务跟着一起死(表现为「关了马上开就打不开」)。
|
||||
# 现在被占时先 HTTP 探活:健康才复用;不健康等 2 秒重试最多 5 次(约 10 秒),
|
||||
# 让旧进程把端口让出来后正常自起;等完仍占用且无响应 → 明确报错指引清残留。
|
||||
reused = False
|
||||
if port_in_use():
|
||||
healthy = False
|
||||
for attempt in range(5):
|
||||
if server_healthy():
|
||||
healthy = True
|
||||
break
|
||||
if not port_in_use():
|
||||
break # 收尾进程让位了 → 落到下面正常自起
|
||||
if attempt < 4:
|
||||
_log("端口 %d 被占但服务无响应(疑似旧进程收尾中),2 秒后重试 %d/5" % (PORT, attempt + 1))
|
||||
time.sleep(2)
|
||||
if healthy:
|
||||
# 2026-10-17 主人需求「重启后永远是最新程序」:端口上的健康实例,代码比磁盘旧
|
||||
# (或老到不认识版本接口)→ 自动结束它、加载新代码再开窗;同版本才复用。
|
||||
remote = remote_code_mtime()
|
||||
local = _code_mtime()
|
||||
if remote is not None and remote >= local - 1: # 1 秒容差(mtime 秒级)
|
||||
_log("端口 %d 服务已是最新版本,直接复用" % PORT)
|
||||
reused = True
|
||||
else:
|
||||
_log("端口 %d 上是旧版本程序(代码时间 %s,磁盘已是 %s),自动升级重启…" % (
|
||||
PORT,
|
||||
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(remote)) if remote else "未知(更老的实例)",
|
||||
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(local))))
|
||||
kill_port_owner()
|
||||
for _ in range(40): # 最多 10 秒等端口让出
|
||||
if not port_in_use():
|
||||
break
|
||||
time.sleep(0.25)
|
||||
if port_in_use():
|
||||
_log("旧实例未能结束(端口仍被占),请到任务管理器结束 python.exe 后重试")
|
||||
print("旧版本实例结束失败,请到任务管理器结束 python.exe 后再双击本文件", flush=True)
|
||||
return 1
|
||||
_log("旧实例已结束,加载新代码…")
|
||||
elif port_in_use():
|
||||
_log("服务启动失败:端口 %d 被占且多次探活无响应(残留进程),请到任务管理器结束 python.exe 后重试" % PORT)
|
||||
print("端口 %d 被残留进程占用且无响应,请到任务管理器结束 python.exe 后再双击本文件" % PORT, flush=True)
|
||||
return 1
|
||||
if not reused:
|
||||
threading.Thread(target=_run_srv, daemon=True).start()
|
||||
if not wait_ready():
|
||||
_log("服务启动失败:端口 %d 起不来(可能被其他程序占用)" % PORT)
|
||||
if _SRV_ERR.get("tb"):
|
||||
_log("服务异常:\n" + _SRV_ERR["tb"])
|
||||
print("服务异常(详见 launch.log):%s" % _SRV_ERR["tb"].splitlines()[-1], flush=True)
|
||||
else:
|
||||
print("服务启动失败,请检查端口 %d 是否被占用;若刚关过软件,请等 5 秒、只开一个窗口再试" % PORT,
|
||||
flush=True)
|
||||
return 1
|
||||
_log("本地服务就绪")
|
||||
|
||||
# 后台管理入口(launch.py admin):不弹软件窗口,用浏览器打开
|
||||
if "--admin" in sys.argv:
|
||||
return serve_admin_mode()
|
||||
|
||||
# 2) 弹出独立窗口
|
||||
try:
|
||||
import webview
|
||||
except Exception as e:
|
||||
_log("缺少 pywebview:%s" % e)
|
||||
print("缺少 pywebview,请先执行:%s -m pip install pywebview" % sys.executable, flush=True)
|
||||
return 1
|
||||
|
||||
# 2.5) WebView2 运行库预检(2026-10-07 单机分发):没装就先说清楚,给出官方下载页;
|
||||
# 用户不想装 → 浏览器兜底,软件照常能用(窗口只是更好的壳)。
|
||||
_w2 = webview2_available()
|
||||
_log("WebView2 运行库检测结果:%s" % _w2)
|
||||
if _w2 is False:
|
||||
warn_webview2_missing()
|
||||
fallback_to_browser("WebView2 运行库缺失")
|
||||
return 0
|
||||
|
||||
try:
|
||||
win = webview.create_window(
|
||||
"造价审核",
|
||||
URL,
|
||||
width=1440, height=900, min_size=(1100, 700),
|
||||
text_select=True, # 允许选中复制表格里的文字
|
||||
confirm_close=True,
|
||||
js_api=_BridgeApi(), # 原生另存为桥(决策 91):页面导出/附件一律弹系统保存框
|
||||
)
|
||||
except Exception as e:
|
||||
_log("窗口创建失败:%s" % e)
|
||||
traceback.print_exc()
|
||||
fallback_to_browser("窗口创建失败")
|
||||
return 1
|
||||
|
||||
_log("窗口已创建,正在进入界面…")
|
||||
try:
|
||||
webview.start(debug=False)
|
||||
except Exception as e:
|
||||
_log("窗口运行异常:%s" % e)
|
||||
traceback.print_exc()
|
||||
fallback_to_browser("窗口运行异常")
|
||||
return 1
|
||||
|
||||
_log("窗口已关闭,退出")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,504 +0,0 @@
|
||||
-- 造价审核软件 · 数据库结构(M1 原型)
|
||||
-- 字段口径:2025 造价数据标准属性名;x_ 前缀为自建字段
|
||||
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA synchronous = NORMAL;
|
||||
|
||||
-- 批次:项目 / 市场价 / 信息价 共用
|
||||
CREATE TABLE IF NOT EXISTS batches(
|
||||
id INTEGER PRIMARY KEY,
|
||||
kind TEXT, -- project | market | info
|
||||
Name TEXT, -- 名称 / 项目名称
|
||||
FileKind INTEGER, -- 单价类型 1预算综合单价 2投标综合单价 3预算全费用 4投标全费用 0未标注
|
||||
BulidUnit TEXT, -- 建设单位
|
||||
x_province TEXT,
|
||||
x_city TEXT,
|
||||
x_district TEXT,
|
||||
x_period_start_m INTEGER, -- 期次起(月序号 year*12+month)
|
||||
x_period_end_m INTEGER, -- 期次止
|
||||
x_enabled INTEGER DEFAULT 1,
|
||||
x_total REAL,
|
||||
x_rows_bill INTEGER,
|
||||
x_rows_lme INTEGER, -- ★ 只表示「工料机条数」。project 批次专用;价格批次恒 0
|
||||
x_rows_price INTEGER, -- ★ 只表示「价格条数」。market / info 批次专用;project 批次恒 0
|
||||
-- ⚠️ 2026-10-06 拆列:此前价格批次的条数被塞进 x_rows_lme,
|
||||
-- 导致 x_rows_lme>0 判断「有没有工料机」会误判信息价批次。
|
||||
-- 判断有无工料机一律走 kind='project',不要用行数。
|
||||
x_imported_at TEXT,
|
||||
x_src_hash TEXT,
|
||||
x_note TEXT,
|
||||
x_attach_sha TEXT, -- 关联 attachments.sha256(原始文件留档)
|
||||
x_publisher TEXT, -- 发布单位(信息价用)
|
||||
x_info TEXT, -- 项目级「基本信息」卡(原文件项目节点属性 JSON)
|
||||
x_feat TEXT, -- 项目级「项目特征信息」卡(AttrInfo/AddiInfo JSON)
|
||||
x_side TEXT, -- 2026-11-03:项目级非数据层整棵(SummaryOfCost/AddiCost/项目汇总…,JSON 路径树)
|
||||
x_parser_ver TEXT, -- 导入时的解析器版本(import_job.PARSER_VER / price_html.PARSER_VER)
|
||||
-- 与当前代码版本不一致 = 数据口径过期,后台顶部提示重导
|
||||
is_mock INTEGER NOT NULL DEFAULT 0 -- 1=自动模拟生成(测试数据);后台「清空模拟数据」按此整批删除
|
||||
-- ⚠️ 2026-10-01 删除 profession 列:后台不再按专业分组(固定走系统默认),该列无人读写
|
||||
);
|
||||
|
||||
-- 原始文件留档:按内容指纹去重(同名同内容只存一份)
|
||||
-- ⚠️ 2026-10-01 补:这张表此前一直只存在于演进出来的旧库里,schema.sql 没写 →
|
||||
-- 一旦按 schema.sql 新建库就会缺表,导入即报 "no such table: attachments"。
|
||||
CREATE TABLE IF NOT EXISTS attachments(
|
||||
sha256 TEXT PRIMARY KEY, -- 内容指纹:天然去重
|
||||
stored_path TEXT, -- 软件内相对路径
|
||||
original_name TEXT, -- 原名(可能带中文)
|
||||
size INTEGER,
|
||||
uploaded_at TEXT
|
||||
);
|
||||
|
||||
-- ===== 2026-10-01:与工作台会话库(session.sql)结构对齐 =====
|
||||
-- 后台库 = 长期资产库(持久化、完整可追溯、不自动删);工作台库 = 临时工作区(可清理)。
|
||||
-- 两者**表结构一一对应、功能一致**,区别只在数据生命周期。
|
||||
-- 下面各表由会话库同名表去掉 s_ 前缀得到,session_id → batch_id。
|
||||
|
||||
-- 单项工程(对应 s_sections;三种格式节点名不同,可以为空)
|
||||
CREATE TABLE IF NOT EXISTS sections(
|
||||
id INTEGER PRIMARY KEY, batch_id INTEGER,
|
||||
Number TEXT, Name TEXT, Total REAL, Ratios REAL
|
||||
);
|
||||
|
||||
-- 单位工程(对应 s_unit_works)
|
||||
CREATE TABLE IF NOT EXISTS unit_works(
|
||||
id INTEGER PRIMARY KEY, batch_id INTEGER,
|
||||
Number TEXT, Name TEXT, Specialty INTEGER, Total REAL,
|
||||
section_id INTEGER,
|
||||
Construction REAL, DivisionalAndElementalWorks REAL, Preliminaries REAL,
|
||||
CostForHSE REAL, SundryCosts REAL, Tax REAL,
|
||||
-- 决策 244(2026-11-01):四张汇总卡——Code=单位工程代号(UnitWorks@Code,如 G130)、
|
||||
-- Unit=单位(UnitWorks@Unit)、Scale=建设规模(UnitWorks@Scale,逐单位重复存)、
|
||||
-- ztotal=总造价(UnitWorksSummary 的 ZZJ 行;缺则回退 SummaryOfCost@Total / UnitWorks@Total)
|
||||
Code TEXT, Unit TEXT, Scale REAL, ztotal REAL,
|
||||
x_attr TEXT -- 2026-11-03:单位工程「工程特征」树(AttrInfo 结构原样,JSON;导出按数据循环)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_uw_batch ON unit_works(batch_id);
|
||||
|
||||
-- 决策 244(2026-11-01):单位工程「汇总分析」卡 = 源文件 UnitWorksSummary 原样入库
|
||||
--(1 QDF / 2 CSF→其中行 / 3 QTF→其中行 / 4 税前造价 / 5 增值税 / 6 ZZJ……随文件而变)。
|
||||
-- 嵌套不用父指针:Group/Item 都带 Number(2 与 2.1),前端按编号前缀归层。
|
||||
CREATE TABLE IF NOT EXISTS uw_summary(
|
||||
id INTEGER PRIMARY KEY, batch_id INTEGER, uw_id INTEGER,
|
||||
Kind TEXT, Number TEXT, Code TEXT, Name TEXT,
|
||||
Formula TEXT, Rate REAL, Total REAL, Remark TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_uws_uw ON uw_summary(uw_id);
|
||||
|
||||
-- 决策 244:单位工程「其他项目」卡 = 源文件 Sundry > SundryCosts(容器行 Kind='root')+
|
||||
-- SundryCostsItem(Kind='item',Number=落库时按序补 1.1/1.2…)
|
||||
CREATE TABLE IF NOT EXISTS sundry_items(
|
||||
id INTEGER PRIMARY KEY, batch_id INTEGER, uw_id INTEGER,
|
||||
Kind TEXT, Number TEXT, Code TEXT, Name TEXT, Unit TEXT,
|
||||
Quantity REAL, Formula TEXT, Price REAL, Rate REAL, Total REAL, Remark TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_snd_uw ON sundry_items(uw_id);
|
||||
|
||||
-- 决策 244:项目级「项目汇总分析」卡 = Project.xml 的 ProjectInstallationWorkCostSummary
|
||||
-- 原样入库(1 QDF→1.1 单项→1.1.1…单位行 / 2 CSF→2.1 / 3 QTF→3.1~3.6 / 4 SJ / 5 ZZJ);
|
||||
-- 嵌套同 uw_summary:按 Number 前缀归层。
|
||||
CREATE TABLE IF NOT EXISTS proj_summary(
|
||||
id INTEGER PRIMARY KEY, batch_id INTEGER,
|
||||
Kind TEXT, Number TEXT, Code TEXT, Name TEXT,
|
||||
Formula TEXT, Rate REAL, Total REAL, Ratios REAL, Remark TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_pjs_batch ON proj_summary(batch_id);
|
||||
|
||||
-- 分部(对应 s_divides):分部分项与措施项目各一套,可嵌套
|
||||
CREATE TABLE IF NOT EXISTS divides(
|
||||
id INTEGER PRIMARY KEY, batch_id INTEGER, uw_id INTEGER, parent_id INTEGER,
|
||||
Kind TEXT, Number TEXT, Name TEXT, Total REAL, Code TEXT, x_seq INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_div_uw ON divides(uw_id);
|
||||
|
||||
-- 定额消耗工料机(对应 s_norm_res)
|
||||
CREATE TABLE IF NOT EXISTS norm_res(
|
||||
id INTEGER PRIMARY KEY,
|
||||
norm_id INTEGER, res_code TEXT, qty REAL,
|
||||
express TEXT -- 含量算式(换算调整式,如 1611.66*1.2;决策 106 补记十二)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_nr_norm ON norm_res(norm_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_nr_code ON norm_res(res_code);
|
||||
|
||||
-- 机械台班 / 配合比的**下一级组成**(对应 s_lme_res),2026-10-02 新增
|
||||
-- 例:990106030 履带式单斗液压挖掘机(台班)→ 00010003 人工 2.0、99450680 柴油 63.0 …
|
||||
-- ⚠️ 父用**编码**而不是 lmes.id:同一个台班在工程里可能出现多行,按编码取才不会漏
|
||||
CREATE TABLE IF NOT EXISTS lme_res(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER, p_code TEXT, res_code TEXT, qty REAL, seq INTEGER,
|
||||
-- 子项名称:源文件的组成节点只有编码,**费用科目(折旧费 / 维护费 …)按 09-28 口径不进
|
||||
-- lmes**,join 不到名称。名称其实就在同一份源文件的汇总节点上,解析时顺手记下来存这儿,
|
||||
-- 展开台班时才不会只剩一串数字。口径不变:这些科目**仍不出现在工料机汇总里**。
|
||||
name TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_lr_p ON lme_res(batch_id, p_code);
|
||||
|
||||
-- 项目级工料机资源库(2026-10-07 新增,对应会话库 s_lme_lib)
|
||||
-- 背景:子目工料机的名称/规格此前**只**靠 res_code 去 join lmes 反查,而 lmes 有两道
|
||||
-- 有意的口径把行砍掉了 —— ① UNIQUE(batch_id, x_hash_exact) 把同名同规格的换算编码
|
||||
-- (34110010-0001 与 34110010 都是"水")只留第一条;② 费用科目(人工费 00010010、
|
||||
-- 其他材料费 99450760 …)按 09-28 口径根本不入库。于是消耗量里引用的编码有 70+ 个
|
||||
-- 查不到名称(原版软件有内置定额库所以都能认出)。
|
||||
-- 解法:导入时把源文件里**所有** LabourMaterialsEquipmentsMachinesSummary 节点
|
||||
-- (Project.xml 的项目级汇总 + 各单位工程的汇总,全集)按编码原样收进这张表,
|
||||
-- 不去重、不过滤 —— 名称/规格/单位/类别/单价都在源文件上。
|
||||
-- 用途:_norm_res / _lme_res 的名称兜底(第一优先仍是 lmes join,单位工程自己的价更贴)。
|
||||
CREATE TABLE IF NOT EXISTS lme_lib(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER,
|
||||
code TEXT, -- 工料机编码(原样,含 -0001 换算后缀 / BC-xxxx 补充编码)
|
||||
name TEXT, spec TEXT, unit TEXT, kind INTEGER,
|
||||
ntp REAL, -- 除税编制价(源文件汇总节点单价,仅供 lmes 查不到时兜底显示)
|
||||
taxp REAL -- 含税编制价
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_lmelib_code ON lme_lib(batch_id, code);
|
||||
|
||||
-- 项目级工料机汇总(2026-10-07 新增,对应会话库 s_lme_proj)
|
||||
-- 来源 = 源文件 **Project.xml** 里的项目级工料机汇总节点(原样一行一条,含费用科目)。
|
||||
-- 为什么单开一张表:lme_lib 存的是"各单位工程汇总覆盖后的值"(名称规格兜底用),
|
||||
-- 而「原数据 → 工料机汇总」的**项目级**要展示的是 Project.xml 的项目级合计
|
||||
-- (消耗量=全项目合计、单价=项目级单价)—— 两份口径不同,不能混用一张表。
|
||||
-- 单位工程级的工料机汇总维持原口径(按本单位工程的清单→定额→消耗量归集)。
|
||||
CREATE TABLE IF NOT EXISTS lme_proj(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER,
|
||||
code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INTEGER,
|
||||
qty REAL, -- 总数量(Project.xml 项目级合计;2026-10-11 更正列语义)
|
||||
ntp REAL, -- 除税编制价
|
||||
taxp REAL, -- 含税编制价
|
||||
ntp_org REAL, -- 除税原始价(决策 183:六价全采,回填按属性一一对应)
|
||||
ntp_expr REAL, -- 除税表达式价
|
||||
taxp_org REAL, -- 含税原始价
|
||||
taxp_expr REAL -- 含税表达式价
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_lmeproj_code ON lme_proj(batch_id, code);
|
||||
|
||||
-- 各单位工程自己的工料机汇总(2026-10-11 决策 41,对应会话库 s_lme_uw):
|
||||
-- 解析时从每个单位工程 xml 的工料机汇总节点按 uw 归属原样入库,
|
||||
-- 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。
|
||||
CREATE TABLE IF NOT EXISTS lme_uw(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER,
|
||||
uw_id INTEGER,
|
||||
code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INTEGER,
|
||||
qty REAL, -- 总数量(本单位工程汇总节点原样)
|
||||
ntp REAL, -- 除税编制价
|
||||
taxrate REAL, -- 源文件比率属性原样存(界面不显示)
|
||||
taxp REAL, -- 含税编制价
|
||||
ntp_org REAL, -- 除税原始价(决策 183:六价全采)
|
||||
ntp_expr REAL, -- 除税表达式价
|
||||
taxp_org REAL, -- 含税原始价
|
||||
taxp_expr REAL -- 含税表达式价
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_lmeproj_code ON lme_proj(batch_id, code);
|
||||
|
||||
-- 审核备注(对应 s_remarks):长期留痕,不随任何清理删除
|
||||
CREATE TABLE IF NOT EXISTS remarks(
|
||||
id INTEGER PRIMARY KEY,
|
||||
src_key TEXT, uw_name TEXT, bill_no TEXT, bill_name TEXT, bill_unit TEXT,
|
||||
rkey TEXT, remark TEXT, updated_at TEXT
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_rem_rkey ON remarks(rkey);
|
||||
CREATE INDEX IF NOT EXISTS ix_rem_src ON remarks(src_key);
|
||||
|
||||
-- ⚠️ 2026-10-01 删除:批次库的 settings 配置表(原本计划「两库各存一套 professions」)。
|
||||
-- 主人定「后台类似清单固定走系统默认分组」后,后台再无配置项 → 该表没有写入方,故移除。
|
||||
-- (老库里已存在的 settings 空表无害;将来后台若需要配置,照 s_settings 同款重建即可。)
|
||||
|
||||
-- 清单项目(核心比对对象)
|
||||
CREATE TABLE IF NOT EXISTS bills(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER,
|
||||
uw_id INTEGER, -- 所属单位工程(2026-10-01 加,与 s_bills 对齐)
|
||||
div_id INTEGER, -- 所属分部(2026-10-01 加)
|
||||
Number TEXT, -- 项目编码
|
||||
Name TEXT, -- 项目名称
|
||||
Attr TEXT, -- 项目特征
|
||||
Unit TEXT, -- 计量单位
|
||||
Quantity REAL, -- 工程量(2026-10-01 加)
|
||||
Price REAL, -- 综合单价
|
||||
Total REAL, -- 合价(2026-10-01 加)
|
||||
Kind TEXT, -- ⚠️ 实存 'prelim'/NULL(措施项目标签),历史误声明为 INTEGER
|
||||
src_remark TEXT, -- 源文件备注(清单节点 Remark 属性,2026-10-08 加;只显示在「原数据」备注栏。两库同名列,别一处驼峰一处下划线)
|
||||
x_name_norm TEXT,
|
||||
x_attr_norm TEXT,
|
||||
x_unit_norm TEXT,
|
||||
x_hash_exact TEXT, -- md5(编码前9位 + 名称归一 + 单位归一) —— 决策27(2026-10-10):编码只比前9位(后3位是顺序码);不含项目特征 Attr
|
||||
x_hash_semi TEXT, -- md5(编码前9位 + 单位归一)(决策 27 前=全编码+单位;名称护栏在 match.py)
|
||||
x_setkey TEXT, -- 字集键(决策27):sort(名称归一)+'|'+单位归一 ——「钢筋混凝土」=「混凝土钢筋」的不按排序等价命中
|
||||
x_seq INTEGER,
|
||||
x_new INTEGER DEFAULT 0, -- 编辑状态列(决策 67/68 两库同构;批次库只加列不写入,恒 0)
|
||||
x_tdel INTEGER DEFAULT 0, -- 同上
|
||||
x_adopt INTEGER DEFAULT 0, -- 同上
|
||||
x_price0 REAL, -- 决策 217:第一次导进来的原始单价(采纳备注旧价取此;改价/采纳覆盖都不动;新增清单恒空→备注显「无」)
|
||||
x_period_start_m INTEGER, -- 期次起(从批次继承,_ensure_period 回填)
|
||||
x_period_end_m INTEGER, -- 期次止
|
||||
x_side TEXT, -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/费用构成/表达式行)
|
||||
x_ptag TEXT -- 2026-11-04:措施清单原生标签(UnitWorksPreliminaryWorkElement / WorkElement)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_bill_exact_pe ON bills(x_hash_exact);
|
||||
CREATE INDEX IF NOT EXISTS ix_bill_setkey ON bills(x_setkey); -- 字集精确档(决策 27)
|
||||
CREATE INDEX IF NOT EXISTS ix_bill_batch ON bills(batch_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_bill_uw ON bills(uw_id); -- 原数据/单位工程归集按 uw 取清单(2026-10-07)
|
||||
|
||||
-- 定额子目(导入但不显示)
|
||||
CREATE TABLE IF NOT EXISTS norms(
|
||||
id INTEGER PRIMARY KEY,
|
||||
bill_id INTEGER,
|
||||
Number TEXT,
|
||||
Name TEXT,
|
||||
Unit TEXT,
|
||||
Quantity REAL, -- 2026-10-01 加(与 s_norms 对齐)
|
||||
Price REAL,
|
||||
Total REAL, -- 2026-10-01 加
|
||||
x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/表达式行)
|
||||
, x_adjust TEXT -- 换算调整记录(JSON 数组,Value 串;补记十三)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_norm_bill ON norms(bill_id);
|
||||
|
||||
-- 工料机(核心比对对象)
|
||||
CREATE TABLE IF NOT EXISTS lmes(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER,
|
||||
Number TEXT,
|
||||
Name TEXT,
|
||||
Specification TEXT,
|
||||
Unit TEXT,
|
||||
Quantity REAL, -- 数量(2026-10-01 加,与 s_lmes 对齐)
|
||||
NoTaxPrice REAL, -- 除税编制价
|
||||
TaxRate REAL, -- 除税率
|
||||
TaxPrice REAL, -- 含税编制价
|
||||
Kind INTEGER, -- 人工/材料/机械(2026-10-01 加)
|
||||
x_name_norm TEXT,
|
||||
x_spec_norm TEXT,
|
||||
x_unit_norm TEXT,
|
||||
x_hash_exact TEXT, -- md5(Name归一 + Spec归一 + Unit归一)
|
||||
x_hash_semi TEXT, -- md5(Name归一 + Unit归一) 次精确档(2026-10-08 主人定:同名同单位、规格不同的可比价)
|
||||
x_setkey TEXT, -- 字集键(决策27):sort(名称+规格归一)+'|'+单位归一 —— 不按排序的整体等价命中
|
||||
x_period_start_m INTEGER, -- 期次起(从批次继承)
|
||||
x_period_end_m INTEGER, -- 期次止
|
||||
UNIQUE(batch_id, x_hash_exact)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_lme_exact ON lmes(x_hash_exact);
|
||||
CREATE INDEX IF NOT EXISTS ix_lme_semi ON lmes(x_hash_semi); -- 次精确档(2026-10-08)
|
||||
CREATE INDEX IF NOT EXISTS ix_lme_setkey ON lmes(x_setkey); -- 字集精确档(决策 27)
|
||||
CREATE INDEX IF NOT EXISTS ix_lme_batch ON lmes(batch_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_lme_num ON lmes(batch_id, Number); -- 消耗量 join 按编码取工料机(2026-10-07,此前每行全表扫)
|
||||
|
||||
-- 价格库(信息价 / 市场价)明细就存本库的 prices 表(见下方)。
|
||||
-- 历史上有过独立 price_lib.db(store/price_lib.sql),现已废弃(legacy),不再写入。
|
||||
|
||||
-- 导入日志
|
||||
CREATE TABLE IF NOT EXISTS import_log(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER,
|
||||
file TEXT,
|
||||
schema TEXT, -- 2025标准 | 老格式 | 加密件
|
||||
n_bill INTEGER, n_bill_skip INTEGER,
|
||||
n_norm INTEGER,
|
||||
n_lme INTEGER, n_lme_skip INTEGER,
|
||||
secs REAL,
|
||||
msg TEXT
|
||||
);
|
||||
|
||||
-- 价格库:信息价 / 市场价明细(2026-09-28 建;字段按 §4.6 F + 台账 23~25)
|
||||
CREATE TABLE IF NOT EXISTS prices(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER,
|
||||
Code TEXT, -- 材料编码(实测多为空白,保留字段允许空)
|
||||
Name TEXT, -- 材料名称
|
||||
Specification TEXT, -- 规格型号
|
||||
Unit TEXT, -- 单位
|
||||
NoTaxPrice REAL, -- 不含税单价
|
||||
TaxRate REAL, -- 税率(实测多为空)
|
||||
TaxPrice REAL, -- 含税单价(实测多为空)
|
||||
Class TEXT, -- 目录 = 分类标题(台账 23)
|
||||
Note TEXT, -- 行备注(价格区间等)
|
||||
x_name_norm TEXT,
|
||||
x_spec_norm TEXT,
|
||||
x_unit_norm TEXT,
|
||||
x_hash_exact TEXT, -- md5(名称归一 + 规格归一 + 单位归一)
|
||||
x_hash_semi TEXT, -- md5(名称归一 + 单位归一) 次精确档(2026-10-08,与 lmes 同口径)
|
||||
Block TEXT, -- 区块/大类(信息价 HTML 里的一级分组;2026-10-12 起新导入不再写,留供旧数据)
|
||||
dir_id INTEGER, -- 挂在哪个目录(price_dirs.id;0/NULL=未分类;2026-10-12 新增)
|
||||
x_period_start_m INTEGER,
|
||||
x_period_end_m INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_batch ON prices(batch_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_exact ON prices(x_hash_exact);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_semi ON prices(x_hash_semi); -- 次精确档(2026-10-08)
|
||||
CREATE INDEX IF NOT EXISTS ix_price_key ON prices(x_name_norm, x_spec_norm, x_unit_norm);
|
||||
|
||||
-- ===========================================================================
|
||||
-- 价格目录树(2026-10-12 重设计,主人定)
|
||||
--
|
||||
-- 每个价格批次(kind='info'/'market')一棵自己的树:单根=批次名(根不落库,
|
||||
-- parent_id=0 即一级目录),层级不限。只有**最底层目录(叶子)**可以挂价格行
|
||||
-- (prices.dir_id 指到叶子;中间层目录只是路径节点,新增行由应用层拒绝)。
|
||||
-- prices.Class 同步冗余完整路径文本(「建筑材料/黑色及有色金属/钢筋」),
|
||||
-- 供导出 Excel 与检索展示直接取用,不用回溯 join。
|
||||
-- 「(未分类)」不落库:dir_id=0 即未分类,由界面渲染固定节点。
|
||||
-- ===========================================================================
|
||||
CREATE TABLE IF NOT EXISTS price_dirs(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER NOT NULL,
|
||||
parent_id INTEGER NOT NULL DEFAULT 0, -- 0=挂在批次根下的 一级目录;否则=父目录 id
|
||||
name TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL DEFAULT 0, -- 同级排序(小在前)
|
||||
UNIQUE(batch_id, parent_id, name)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_pdir_batch ON price_dirs(batch_id, parent_id);
|
||||
|
||||
-- ===========================================================================
|
||||
-- 询价附件(2026-10-06 新增)
|
||||
--
|
||||
-- ⚠️ 只服务「项目」:给某个项目的**工料机**挂询价资料(报价单、询价函、厂商回复…)。
|
||||
-- 与信息价 / 市场价**完全无关**——价格批次(kind='info'/'market')的明细在 prices 表,
|
||||
-- 不在 lmes 表,没有"工料机"这个概念,因此后台只在「项目界面」标签下出现。
|
||||
--
|
||||
-- 文件形态:pdf / zip / rar,只存不解析(下载可取回原文件)。一个项目可传多个。
|
||||
-- 存储:与价格原件同一套规矩 —— 内容 sha256 去重,文件存 data/ 下,库里只存相对路径。
|
||||
-- ===========================================================================
|
||||
CREATE TABLE IF NOT EXISTS inquiry_files(
|
||||
id INTEGER PRIMARY KEY,
|
||||
batch_id INTEGER NOT NULL, -- 所属项目批次(必须是 kind='project')
|
||||
sha256 TEXT NOT NULL, -- 内容指纹:同一项目内重复上传直接拒绝
|
||||
original_name TEXT, -- 原名(可能带中文)
|
||||
stored_path TEXT, -- 软件内相对路径(相对 data/)
|
||||
size INTEGER, -- 字节
|
||||
ext TEXT, -- pdf | zip | rar
|
||||
uploaded_at TEXT,
|
||||
UNIQUE(batch_id, sha256)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_inq_batch ON inquiry_files(batch_id);
|
||||
|
||||
-- 工料机 ↔ 询价附件 的关联
|
||||
-- · 一个附件 → 多条工料机 (file_id 可重复)
|
||||
-- · 一条工料机 → 只一个附件 (★ lme_id 作主键,由数据库强制,不靠代码判断)
|
||||
-- 想换绑直接 INSERT OR REPLACE:主键冲突即覆盖,天然实现"允许改绑"。
|
||||
CREATE TABLE IF NOT EXISTS lme_attach(
|
||||
lme_id INTEGER PRIMARY KEY, -- lmes.id
|
||||
batch_id INTEGER NOT NULL, -- 冗余,便于按项目整体清理
|
||||
file_id INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_lmeatt_file ON lme_attach(file_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_lmeatt_batch ON lme_attach(batch_id);
|
||||
|
||||
-- 清单 ↔ 询价附件 的关联(2026-10-21 决策 152:类似清单页签也能绑附件,同 lme_attach 口径)
|
||||
-- · 一条清单 → 只一个附件(★ bill_id 作主键,数据库强制);换绑 INSERT OR REPLACE 覆盖。
|
||||
CREATE TABLE IF NOT EXISTS bill_attach(
|
||||
bill_id INTEGER PRIMARY KEY, -- bills.id
|
||||
batch_id INTEGER NOT NULL, -- 冗余,便于按项目整体清理
|
||||
file_id INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_bilatt_file ON bill_attach(file_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_bilatt_batch ON bill_attach(batch_id);
|
||||
|
||||
-- ===========================================================================
|
||||
-- 数据源字典(2026-10-06 新增)
|
||||
--
|
||||
-- 唯一来源:后台「数据源」面板维护,**后台 / 工作台共用同一份**。
|
||||
-- · 录入类下拉(导入 / 编辑 / 打开工程)→ 只从这里取,杜绝手工输入漂移
|
||||
-- · 过滤类下拉(列表筛选 / 地区树) → 这里 ∪ 库里实际出现过的值
|
||||
-- (过滤必须能筛到历史数据,所以取并集;录入才严格收口)
|
||||
--
|
||||
-- 首次启用会自动用库里已有的地区 / 发布单位 / 建设单位播种,不会丢现有选项。
|
||||
-- ===========================================================================
|
||||
CREATE TABLE IF NOT EXISTS dict_region(
|
||||
id INTEGER PRIMARY KEY,
|
||||
province TEXT NOT NULL, -- 省
|
||||
city TEXT NOT NULL DEFAULT '',-- 市(空 = 只到省级)
|
||||
district TEXT NOT NULL DEFAULT '',-- 区/县(空 = 只到市级)
|
||||
sort INTEGER DEFAULT 0,
|
||||
UNIQUE(province, city, district)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS dict_org(
|
||||
id INTEGER PRIMARY KEY,
|
||||
cat TEXT NOT NULL, -- publisher 发布单位 | builder 建设单位
|
||||
name TEXT NOT NULL,
|
||||
sort INTEGER DEFAULT 0,
|
||||
UNIQUE(cat, name)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_dictorg_cat ON dict_org(cat);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 后台设置(2026-10-06):k/v 一张表,新增设置项不用改表结构。
|
||||
-- 现有项:
|
||||
-- upload_max_mb 单个附件大小上限(MB),默认 10,范围 1~500;
|
||||
-- 适用 询价附件 / 市场价原件 / 信息价原件。格式不限(可执行文件除外)。
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS settings(
|
||||
k TEXT PRIMARY KEY,
|
||||
v TEXT,
|
||||
updated_at TEXT
|
||||
);
|
||||
|
||||
-- ===========================================================================
|
||||
-- 采纳收集(2026-10-09 主人定):工作台「询价附件」常驻按钮的数据源
|
||||
--
|
||||
-- 口径:对比框点「采纳」→ 该行挂的附件(询价资料 / 刊物原件)连同其「项目/刊物」名
|
||||
-- 收进这里。全局注册(跨会话常驻),附件按 sha256 内容去重——同一份文件被采纳多少次、
|
||||
-- 被多少个项目采纳,adopt_files 都只有一行;「哪个项目收了它」记 adopt_hits,
|
||||
-- 同 (附件, 项目) 反复采纳靠 UNIQUE 天然去重,只算一条。
|
||||
-- 不复制文件本体:仍指向 inquiry_files / attachments 的磁盘原件;原件随批次删除后,
|
||||
-- /api/adopt/list 按磁盘存在性懒清理注册表,不留死链接。
|
||||
-- ===========================================================================
|
||||
CREATE TABLE IF NOT EXISTS adopt_files(
|
||||
sha256 TEXT PRIMARY KEY, -- 内容指纹:同一份文件(哪个项目传的都一样)只显示一个
|
||||
kind TEXT NOT NULL, -- inq=询价附件(项目)| att=价格原件(信息价/市场价)
|
||||
ref TEXT, -- 下载定位:inq→inquiry_files.id(列表时按 sha 现解析最新一行);att→sha256
|
||||
name TEXT, -- 原名(可能带中文)
|
||||
ext TEXT, -- 小写含点,如 .pdf
|
||||
size INTEGER, -- 字节
|
||||
adopted_at TEXT -- 首次采纳时间
|
||||
);
|
||||
|
||||
-- 采纳事件(2026-10-09 晚改版):每次「某会话的某工料机行」点采纳记一行,**不去重**——
|
||||
-- 目录展示时按 (sha256, proj) 去重即可;取消采纳/换绑按 (sid, lme_id) 整行撤,
|
||||
-- 一个事件只归一个工料机行,撤 A 行不会误伤 B 行对同一附件的同名采纳。
|
||||
-- 附件从目录消失 = 它的**最后一条**事件被撤(api_adopt_cancel / 删会话里顺带清孤儿 adopt_files)。
|
||||
-- 决策 243(2026-10-30 主人定):清单采纳也收附件——来源入库清单挂的询价附件记
|
||||
-- (sid, bill_id) 事件,取消采纳按整行撤;目录分「清单附件/工料机附件」两标签展示。
|
||||
CREATE TABLE IF NOT EXISTS adopt_hits(
|
||||
id INTEGER PRIMARY KEY,
|
||||
sha256 TEXT NOT NULL, -- adopt_files.sha256
|
||||
proj TEXT NOT NULL, -- 采纳时所在行的「项目/刊物」名(与写入备注同源)
|
||||
adopted_at TEXT,
|
||||
sid INTEGER, -- 采纳来源会话(sessions.id,取消/删会话按此清)
|
||||
lme_id INTEGER, -- 采纳来源工料机行(s_lme_proj.id;一行只有一条在效采纳)
|
||||
lme_rkey TEXT, -- 决策 159:该行的内容键 'L:'+rkey(源文件,编码,名称,单位)——
|
||||
-- 重解析/重开工程行 id 重生,靠它把事件改绑到新行(与备注同一套机制)
|
||||
bill_id INTEGER, -- 决策 243:采纳来源清单行(s_bills.id;与 lme_id 互斥成对出现)
|
||||
bill_rkey TEXT -- 决策 243:清单内容键 'b:'+rkey(与编辑历史 ekbase 同一把键)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_adopth_sha ON adopt_hits(sha256);
|
||||
CREATE INDEX IF NOT EXISTS ix_adopth_row ON adopt_hits(sid, lme_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_adopth_billrow ON adopt_hits(sid, bill_id);
|
||||
|
||||
-- ===== 工料机骨架库(决策 197,2026-10-25 主人定)=====
|
||||
-- 按「后缀+母行字段集」建签名组,每组只收一个代表件的大骨架(形态种类最多的单一件),
|
||||
-- 绝不跨件拼合;命中标准=后缀+字段;永久存储,不随会话清理。v1 只报不改(体检提示差异)。
|
||||
CREATE TABLE IF NOT EXISTS lme_skel_file(
|
||||
sha256 TEXT PRIMARY KEY, -- 对应 attachments.sha256
|
||||
suffix TEXT, -- cos | cos4(小写规范)
|
||||
sig TEXT, -- 签名 = 后缀 + '|' + 母行字段集(排序逗号串);无 LME 块不写入
|
||||
shapes TEXT, -- 本件小骨架形态清单 JSON [{self_close,m_fields,k_fields,count}]
|
||||
n_lme INTEGER, -- 母行总数(行数与骨架大小无关,仅参考)
|
||||
extracted_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS lme_skel_group(
|
||||
sig TEXT PRIMARY KEY, -- 签名(后缀+字段集)
|
||||
suffix TEXT,
|
||||
m_fields TEXT, -- 母行字段集(逗号串)
|
||||
rep_sha TEXT, -- 组代表件 sha(形态种类最多;平手取最新)
|
||||
rep_shapes TEXT, -- 代表件全形态模板 JSON(大骨架)
|
||||
rep_nshapes INTEGER, -- 代表形态种类数
|
||||
files TEXT, -- 组内 sha 清单 JSON
|
||||
n_files INTEGER,
|
||||
updated_at TEXT
|
||||
);
|
||||
-- (决策 197 补) lme_skel_file 含 original_name 列(原名,剥 sha 前缀)——上面建表语句已含;
|
||||
-- 旧库由 ensure_tables 的 ALTER 补列。
|
||||
@@ -1,235 +0,0 @@
|
||||
-- 会话库(工作台:本次打开审核的工程)——完整集,用于"跟原件逐条核对"
|
||||
-- 与历史库 history.db 的区别见方案 §4.8
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions(
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT,
|
||||
base_period_m INTEGER, -- 基准期次(单月)—— 旧字段,保留兼容
|
||||
period_from INTEGER, -- 基准期次 起(月序号,必填)★ 现行
|
||||
period_to INTEGER, -- 基准期次 止(月序号,必填)★ 现行(单月时与起相同)
|
||||
x_province TEXT, x_city TEXT, x_district TEXT,
|
||||
bulid_unit TEXT, -- 建设单位(文件类型按你的决定:会话库**不存**)
|
||||
file_kind INTEGER, -- 单价类型(2026-11-01 决策 245:打开项目弹框新增,取代上述「会话库不存」口径;
|
||||
-- 取值与历史库 batches.FileKind 同枚举 1/2/3/4/0)
|
||||
src_name TEXT, -- 源文件名
|
||||
imported_at TEXT,
|
||||
x_total REAL, -- 工程总造价(2026-09-30):原文件口径,不是清单合价求和
|
||||
x_info TEXT, -- 项目根节点属性 JSON → 项目级「基本信息」卡
|
||||
x_feat TEXT, -- AttrInfo/AddiInfo 条目 JSON → 项目级「项目特征信息」卡
|
||||
x_side TEXT, -- 2026-11-03:项目级非数据层整棵(SummaryOfCost/AddiCost/项目汇总…,JSON 路径树;导出按数据重建)
|
||||
x_batch_id INTEGER, -- 后台批次 id(2026-10-06):同一份文件在后台导入过就能对上,
|
||||
-- 工作台据此**只读**展示该项目的询价附件。对不上 = 0 / NULL,
|
||||
-- 界面上就不显示「询价附件」入口(不是错误,是没在后台导入过)
|
||||
x_manual INTEGER DEFAULT 0, -- 2026-10-19:手工工程(无源文件)。1=创建工程建的空工程,
|
||||
-- 不能按原格式导出/重新解析;用同名源文件打开即变回 0。
|
||||
x_own_blank BLOB, -- 2026-11-04:本项目自己的空骨架(打开工程时从源件提炼;导出优先用)
|
||||
x_own_meta TEXT -- 本项目骨架的结构旁注(index_row 等,JSON)
|
||||
);
|
||||
-- 2026-09-30 再加两张项目级标签卡的数据,都以 JSON 存(字段随格式而变,不值得各开一列):
|
||||
-- x_info = 项目根节点属性(编号/名称/专业/计价标准/单位/规模…)→ 「基本信息」卡
|
||||
-- x_feat = AttrInfo / AddiInfo 条目 [{n:名称, v:值}] → 「项目特征信息」卡
|
||||
-- CREATE TABLE 里已含这两列(见下方 sessions 定义)。
|
||||
|
||||
-- 单项工程(2026-09-30 加)
|
||||
-- ⚠️ 三种格式节点名不同,且"有没有这一层"也不一样:
|
||||
-- cos4 → DivisionalAndElementalProject(有层级,但 Name/Total 常为空)
|
||||
-- .COS → SectionalWorks(常常只有 1 个、名字就等于项目名 ⇒ 实际上没有单项工程层)
|
||||
-- ESCC2.0 → ProjectGroup(真正有名字、造价、费率)
|
||||
-- 所以这一层**可以是空的**:没有就不建行,目录树退化成两层,别硬造。
|
||||
CREATE TABLE IF NOT EXISTS s_sections(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER,
|
||||
Number TEXT, Name TEXT, Total REAL, Ratios REAL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS s_unit_works(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER,
|
||||
Number TEXT, Name TEXT, Specialty INTEGER, Total REAL,
|
||||
section_id INTEGER, -- 属于哪个单项工程(2026-09-30 加,没有则 NULL)
|
||||
-- 2026-09-30 加:单位工程的造价构成(来自 UnitWorks/SummaryOfCost)
|
||||
-- 没有这些列,单位工程级的「汇总分析」标签就无从显示
|
||||
Construction REAL, -- 建筑安装工程费
|
||||
DivisionalAndElementalWorks REAL, -- 分部分项工程费
|
||||
Preliminaries REAL, -- 措施项目费
|
||||
CostForHSE REAL, -- 绿色施工安全防护费(安全生产)
|
||||
SundryCosts REAL, -- 其他项目费
|
||||
Tax REAL, -- 税金
|
||||
-- 决策 244(2026-11-01):四张汇总卡——Code=单位工程代号(UnitWorks@Code,如 G130)、
|
||||
-- Unit=单位、Scale=建设规模、ztotal=总造价(UnitWorksSummary 的 ZZJ 行,缺则回退)
|
||||
Code TEXT, Unit TEXT, Scale REAL, ztotal REAL,
|
||||
x_attr TEXT -- 2026-11-03:单位工程「工程特征」树(AttrInfo 结构原样,JSON;导出按数据循环)
|
||||
);
|
||||
|
||||
-- 决策 244(2026-11-01):单位工程「汇总分析」卡 = 源文件 UnitWorksSummary 原样入库
|
||||
--(嵌套按 Number 前缀归层:2 与 2.1,前端拼树)。
|
||||
CREATE TABLE IF NOT EXISTS s_uw_summary(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER, uw_id INTEGER,
|
||||
Kind TEXT, Number TEXT, Code TEXT, Name TEXT,
|
||||
Formula TEXT, Rate REAL, Total REAL, Remark TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_suws_uw ON s_uw_summary(uw_id);
|
||||
|
||||
-- 决策 244:单位工程「其他项目」卡 = Sundry > SundryCosts(容器行 Kind='root')+ SundryCostsItem
|
||||
CREATE TABLE IF NOT EXISTS s_sundry(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER, uw_id INTEGER,
|
||||
Kind TEXT, Number TEXT, Code TEXT, Name TEXT, Unit TEXT,
|
||||
Quantity REAL, Formula TEXT, Price REAL, Rate REAL, Total REAL, Remark TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_ssnd_uw ON s_sundry(uw_id);
|
||||
|
||||
-- 决策 244:项目级「项目汇总分析」卡 = Project.xml 的 ProjectInstallationWorkCostSummary 原样入库
|
||||
CREATE TABLE IF NOT EXISTS s_proj_summary(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER,
|
||||
Kind TEXT, Number TEXT, Code TEXT, Name TEXT,
|
||||
Formula TEXT, Rate REAL, Total REAL, Ratios REAL, Remark TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_spjs_sess ON s_proj_summary(session_id);
|
||||
|
||||
-- 分部(2026-09-30 加):分部分项与措施项目**各有一套**,且可能嵌套
|
||||
-- 分部分项:UnitWorks → DivisionalAndElementalWorks → DivisionalWorks → WorkElement
|
||||
-- 措施项目:Preliminaries → PreliminaryDivisionalWorks → UnitWorksPreliminaryWorkElement
|
||||
-- 「原数据」标签里那张表格的「分部」行、以及 ± 目录树都靠它。
|
||||
CREATE TABLE IF NOT EXISTS s_divides(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER, uw_id INTEGER, parent_id INTEGER,
|
||||
Kind TEXT, -- 'item' 分部分项 / 'prelim' 措施项目
|
||||
Number TEXT, Name TEXT, Total REAL, Code TEXT, x_seq INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_sdiv_uw ON s_divides(uw_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS s_bills(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER, uw_id INTEGER,
|
||||
div_id INTEGER, -- 属于哪个分部(2026-09-30 加,没有则 NULL)
|
||||
Number TEXT, Name TEXT, Attr TEXT, Unit TEXT,
|
||||
Quantity REAL, Price REAL, Total REAL, -- 工程量 / 单价 / 合价(历史库没有)
|
||||
Kind TEXT, -- ⚠️ 实存 'prelim'/NULL
|
||||
x_remark TEXT, -- 审核备注(点击填写,存库)
|
||||
src_remark TEXT, -- 源文件备注(清单节点 Remark 属性,2026-10-08 加;只显示在「原数据」备注栏,与审核备注分开两列)
|
||||
x_name_norm TEXT, x_attr_norm TEXT, x_unit_norm TEXT,
|
||||
x_hash_exact TEXT, x_hash_semi TEXT, x_seq INTEGER,
|
||||
x_new INTEGER DEFAULT 0, -- 本软件新增的清单(唯一可真删;淡绿底)——决策 67
|
||||
x_tdel INTEGER DEFAULT 0, -- 临时删除(假删,浅灰+横线,可恢复)——决策 67
|
||||
x_adopt INTEGER DEFAULT 0, -- 数据采纳标记(取消采纳列;决策 68 批次B)
|
||||
x_side TEXT, -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/费用构成/表达式行)
|
||||
x_ptag TEXT -- 2026-11-04:措施清单的原生标签(UnitWorksPreliminaryWorkElement / WorkElement),导出按形态还原
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_sb_sess ON s_bills(session_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_sb_uw ON s_bills(uw_id); -- 原数据按 uw 取清单(2026-10-07)
|
||||
CREATE INDEX IF NOT EXISTS ix_sb_ex ON s_bills(x_hash_exact);
|
||||
CREATE INDEX IF NOT EXISTS ix_sb_se ON s_bills(x_hash_semi);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS s_norms(
|
||||
id INTEGER PRIMARY KEY, bill_id INTEGER,
|
||||
Number TEXT, Name TEXT, Unit TEXT, Quantity REAL, Price REAL, Total REAL,
|
||||
x_tdel INTEGER DEFAULT 0, -- 定额临删(批次B 采纳语义用)——决策 67 预埋
|
||||
x_adopt INTEGER DEFAULT 0, -- 采纳标记(批次B)——决策 67 预埋
|
||||
x_src_norm_id INTEGER -- 来源定额 id(取消采纳撤行用,批次B)——决策 67 预埋
|
||||
,
|
||||
x_adjust TEXT, -- 换算调整记录(JSON;采纳携带,补记十三)
|
||||
x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/表达式行)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_sn_bill ON s_norms(bill_id);
|
||||
|
||||
-- 定额消耗工料机的关系(2026-09-30 加)
|
||||
-- 没有这张表,「单位工程级工料机」根本算不出来 —— 工料机只能挂到整个会话,
|
||||
-- 不知道它属于哪条定额、哪个单位工程(s_lmes 只有 session_id,这是老问题)。
|
||||
-- 定额 → 工料机编码 + 消耗量;工料机本体(名称/规格/单价)在 s_lmes 里按编码对。
|
||||
CREATE TABLE IF NOT EXISTS s_norm_res(
|
||||
id INTEGER PRIMARY KEY,
|
||||
norm_id INTEGER, -- 对应 s_norms.id
|
||||
res_code TEXT, -- 工料机编码(对 s_lmes.Number)
|
||||
qty REAL, -- 消耗量
|
||||
express TEXT -- 含量算式(换算调整式,采纳携带;决策 106 补记十二)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_snr_norm ON s_norm_res(norm_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_snr_code ON s_norm_res(res_code);
|
||||
|
||||
-- 机械台班 / 配合比的下一级组成(对应批次库 lme_res),2026-10-02 新增
|
||||
CREATE TABLE IF NOT EXISTS s_lme_res(
|
||||
id INTEGER PRIMARY KEY,
|
||||
session_id INTEGER, p_code TEXT, res_code TEXT, qty REAL, seq INTEGER,
|
||||
name TEXT -- 同批次库 lme_res.name:源文件汇总节点上的子项名称(费用科目用)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_slr_p ON s_lme_res(session_id, p_code);
|
||||
|
||||
-- 项目级工料机资源库(2026-10-07 新增,对应批次库 lme_lib):
|
||||
-- 源文件全部工料机汇总节点(Project.xml + 各单位工程)按编码原样收一条,
|
||||
-- 供子目工料机/台班组成的名称规格兜底(lmes 有去重与费用科目过滤,会缺编码)。
|
||||
CREATE TABLE IF NOT EXISTS s_lme_lib(
|
||||
id INTEGER PRIMARY KEY,
|
||||
session_id INTEGER,
|
||||
code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INTEGER,
|
||||
ntp REAL, taxp REAL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_slmelib_code ON s_lme_lib(session_id, code);
|
||||
|
||||
-- 项目级工料机汇总(2026-10-07 新增,对应批次库 lme_proj):
|
||||
-- Project.xml 的项目级工料机汇总原样入库,「原数据 → 工料机汇总」项目级读这里。
|
||||
-- 2026-10-11 决策 40:「项目工料机」标签两侧统一改读本表 → 工料机采纳备注落在本表
|
||||
-- (x_remark,老库由启动自愈 ALTER 补列 + restore_lme_remarks 按 rkey 回填)。
|
||||
CREATE TABLE IF NOT EXISTS s_lme_proj(
|
||||
id INTEGER PRIMARY KEY,
|
||||
session_id INTEGER,
|
||||
code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INTEGER,
|
||||
qty REAL, ntp REAL, taxp REAL,
|
||||
taxrate REAL, -- 税率(决策 69 批次C:源节点 TaxRate 采集/弹框可编辑)
|
||||
ntp_org REAL, ntp_expr REAL, -- 决策 183:六价全采(属性级对应回填)
|
||||
taxp_org REAL, taxp_expr REAL,
|
||||
x_remark TEXT,
|
||||
x_adopt_added INTEGER DEFAULT 0, -- 采纳追加的品类行(决策 68 批次B,取消采纳时撤下)
|
||||
x_merged_hide INTEGER DEFAULT 0, -- 合并工料机隐藏标记(决策 69 批次C:未勾选行隐藏不删除)
|
||||
x_ntp0 REAL, x_rate0 REAL, x_taxp0 REAL -- 决策 219:第一次计算的三价锚(采纳备注旧价恒取此;合并生成行=合并后首次三价;老库补列不回填,重导生效)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_slmeproj_code ON s_lme_proj(session_id, code);
|
||||
|
||||
-- 各单位工程自己的工料机汇总(2026-10-11 决策 41,对应批次库 lme_uw):
|
||||
-- 解析时按单位工程归属原样入库,「原数据 · 单位工程级工料机汇总」直接读它
|
||||
-- (总数量=源文件原样,不走消耗量归集;老会话无数据时前端回退归集口径)。
|
||||
CREATE TABLE IF NOT EXISTS s_lme_uw(
|
||||
id INTEGER PRIMARY KEY,
|
||||
session_id INTEGER,
|
||||
uw_id INTEGER,
|
||||
code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INTEGER,
|
||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
|
||||
ntp_org REAL, ntp_expr REAL, -- 决策 183:六价全采(属性级对应回填)
|
||||
taxp_org REAL, taxp_expr REAL,
|
||||
x_adopt_added INTEGER DEFAULT 0 -- 采纳追加的品类行(决策 68 批次B,取消采纳时撤下)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_slmu_code ON s_lme_uw(session_id, code); -- 合并/改价按编码同步(决策 161:无索引时大库合并全表扫,慢)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS s_lmes(
|
||||
id INTEGER PRIMARY KEY, session_id INTEGER,
|
||||
Number TEXT, -- 工料机编码(历史库取消,会话库要)
|
||||
Name TEXT, Specification TEXT, Unit TEXT,
|
||||
Quantity REAL, -- 数量(历史库取消,会话库要)
|
||||
NoTaxPrice REAL, TaxRate REAL, TaxPrice REAL,
|
||||
Kind INTEGER, -- 类型:人工/材料/机械(历史库取消,会话库要)
|
||||
x_name_norm TEXT, x_spec_norm TEXT, x_unit_norm TEXT, x_hash_exact TEXT,
|
||||
x_hash_semi TEXT, -- md5(名称归一+单位归一) 次精确档(2026-10-08,与历史库同口径)
|
||||
x_remark TEXT -- 审核备注(采纳写入;持久副本在 s_remarks,rkey 前缀 'L:')
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_sl_sess ON s_lmes(session_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_sl_num ON s_lmes(session_id, Number); -- 消耗量 join 按编码取工料机(2026-10-07)
|
||||
CREATE INDEX IF NOT EXISTS ix_sl_ex ON s_lmes(x_hash_exact);
|
||||
|
||||
-- 审核备注的**持久落点**(2026-09-30 建)
|
||||
-- 为什么要单开一张表:备注是「人 × 某个工程的某条清单」的判断,不是某一次导入的产物。
|
||||
-- s_bills.x_remark 会随 删除会话 / 重新解析(wipe)一起没,而这张表**两个都不参与**:
|
||||
-- wipe()(重新解析)只删 s_bills / s_norms / s_lmes / s_unit_works,绝不碰 s_remarks;
|
||||
-- drop()(最近审核删除)2026-10-08 起配套 drop_remarks 把备注一并带走(引用清零才删)。
|
||||
-- 主见 rkey = md5(源文件 + 单位工程 + 编码 + 名称 + 单位),实测工程内冲突 0 组
|
||||
-- (对照:只用「编码+名称+单位」的 x_hash_exact 撞 786 组,会串号覆盖)。
|
||||
CREATE TABLE IF NOT EXISTS s_remarks(
|
||||
id INTEGER PRIMARY KEY,
|
||||
src_key TEXT, -- 会话源文件标识(sessions.src_name,同名文件复用同一份上传)
|
||||
uw_name TEXT, -- 单位工程名称
|
||||
bill_no TEXT, -- 清单编码
|
||||
bill_name TEXT, -- 清单名称
|
||||
bill_unit TEXT, -- 单位
|
||||
rkey TEXT, -- 上面五个字段 norm 后的 md5 —— 唯一键
|
||||
remark TEXT, -- 备注内容(清空时写空串,不删行,留痕)
|
||||
updated_at TEXT
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_srem_rkey ON s_remarks(rkey);
|
||||
CREATE INDEX IF NOT EXISTS ix_srem_src ON s_remarks(src_key);
|
||||
@@ -1,144 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""给**已导入**的历史批次补建 lme_lib(项目级工料机资源库)—— 2026-10-07。
|
||||
|
||||
背景:子目工料机的名称/规格此前只靠编码去 join lmes 反查,而 lmes 有两道有意的口径:
|
||||
① UNIQUE(batch_id, x_hash_exact) 把同名同规格的换算编码只留第一条;
|
||||
② 费用科目(人工费 / 其他材料费 / 折旧费 …)按 09-28 口径不入库。
|
||||
结果消耗量里引用的编码大量查不到名称(实测批次16 缺 78 个,00010010 就是其中之一)。
|
||||
新导入的批次由解析器自动写 lme_lib;**已经导入的批次**用本工具回填,不用重导。
|
||||
|
||||
做法:按 batches.x_src_hash 找到 data/uploads 里的源 .cos4 / .COS,重新只跑"解析"
|
||||
拿到 lme_lib 全集(源文件所有工料机汇总节点),INSERT OR IGNORE 进库。
|
||||
只新增 lme_lib 行,不碰 bills / lmes / norms —— 不改变任何既有口径,也不触发
|
||||
「解析器版本过期需重导」提示(PARSER_VER 不动)。
|
||||
|
||||
会话库(session.db):会话只存源文件名不存路径,无法重解析;改用 x_batch_id 关联——
|
||||
同一份文件在后台导入过就把批次的 lme_lib 复制给会话(s_lme_lib)。没关联的会话等
|
||||
用户在工作台点「重新解析」时由新解析器自动补。
|
||||
|
||||
用法:
|
||||
python tools/backfill_lme_lib.py # 实际执行
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, APP_DIR)
|
||||
sys.path.insert(0, os.path.join(APP_DIR, "core"))
|
||||
|
||||
import import_job # noqa: E402 (只用它的 parse_std;不碰它的 main)
|
||||
|
||||
ROOT_DATA = os.path.abspath(os.path.join(APP_DIR, "..", "data"))
|
||||
HIST_DB = os.path.join(ROOT_DATA, "history.db")
|
||||
SESS_DB = os.path.join(ROOT_DATA, "session.db")
|
||||
UPLOADS = os.path.join(ROOT_DATA, "uploads")
|
||||
|
||||
|
||||
def _seed_out():
|
||||
"""parse_std 需要的计数器 / 容器(真实调用方 api_server/session_job 也是这么撒的)。"""
|
||||
return {"uw": [], "bills": [], "norms": [], "lmes": [], "cur_bill": -1,
|
||||
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0,
|
||||
"lme_raw": 0, "lme_skip": 0}
|
||||
|
||||
|
||||
def _src_path(src_hash):
|
||||
"""uploads/<sha前2位>/<sha_原文件名>;找不到返回 None"""
|
||||
if not src_hash:
|
||||
return None
|
||||
p = os.path.join(UPLOADS, src_hash[:2], src_hash)
|
||||
return p if os.path.isfile(p) else None
|
||||
|
||||
|
||||
def _apply_schema(db, schema_file):
|
||||
con = sqlite3.connect(db)
|
||||
con.executescript(io.open(os.path.join(APP_DIR, "store", schema_file),
|
||||
encoding="utf-8").read())
|
||||
con.commit()
|
||||
return con
|
||||
|
||||
|
||||
def backfill_batches():
|
||||
con = _apply_schema(HIST_DB, "schema.sql")
|
||||
rows = con.execute("SELECT id, Name, x_src_hash FROM batches WHERE kind='project'").fetchall()
|
||||
ok = miss_file = miss_hash = 0
|
||||
for bid, name, src in rows:
|
||||
if not src:
|
||||
print(" 批次 %-3s %-24s 无源文件记录,跳过" % (bid, (name or "")[:24]))
|
||||
miss_hash += 1
|
||||
continue
|
||||
p = _src_path(src)
|
||||
if not p:
|
||||
print(" 批次 %-3s %-24s 源文件不在 uploads(%s…),跳过" % (bid, (name or "")[:24], src[:12]))
|
||||
miss_file += 1
|
||||
continue
|
||||
try:
|
||||
out = _seed_out()
|
||||
import_job.parse_std(p, out)
|
||||
except Exception as e:
|
||||
print(" 批次 %-3s %-24s 解析失败:%s" % (bid, (name or "")[:24], e))
|
||||
miss_file += 1
|
||||
continue
|
||||
lib = out.get("lme_lib") or {}
|
||||
n = 0
|
||||
for code, (nm, sp, un, kd, ntp, taxp) in lib.items():
|
||||
cur = con.execute(
|
||||
"""INSERT OR IGNORE INTO lme_lib(batch_id, code, name, spec, unit, kind, ntp, taxp)
|
||||
VALUES(?,?,?,?,?,?,?,?)""", (bid, code, nm, sp, un, kd, ntp, taxp))
|
||||
n += cur.rowcount
|
||||
# 项目级工料机汇总(2026-10-07):Project.xml 原样(含项目级合计消耗量/单价)
|
||||
proj = out.get("lme_proj") or {}
|
||||
np_ = 0
|
||||
for code, (nm, sp, un, kd, q, ntp, taxp) in proj.items():
|
||||
cur = con.execute(
|
||||
"""INSERT OR IGNORE INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp)
|
||||
VALUES(?,?,?,?,?,?,?,?,?)""", (bid, code, nm, sp, un, kd, q, ntp, taxp))
|
||||
np_ += cur.rowcount
|
||||
have = con.execute("SELECT COUNT(*) FROM lme_lib WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
havep = con.execute("SELECT COUNT(*) FROM lme_proj WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
ok += 1
|
||||
print(" 批次 %-3s %-24s 资源库补 %s(现 %s)· 项目级汇总补 %s(现 %s,源文件 %s 条)"
|
||||
% (bid, (name or "")[:24], n, have, np_, havep, len(proj)))
|
||||
con.commit()
|
||||
print("批次库回填完成:%s 个批次成功,%s 个缺源文件/失败,%s 个无源记录" % (ok, miss_file, miss_hash))
|
||||
|
||||
|
||||
def backfill_sessions():
|
||||
"""会话库:按 x_batch_id 复制批次的 lme_lib / lme_proj(同一份文件才可靠)。"""
|
||||
con = _apply_schema(SESS_DB, "session.sql")
|
||||
con.execute("ATTACH DATABASE ? AS hist", (HIST_DB,)) # 批次库的表跨库引用(显式 hist. 前缀)
|
||||
rows = con.execute("SELECT id, name, x_batch_id FROM sessions").fetchall()
|
||||
n_all = 0
|
||||
for sid, name, bid in rows:
|
||||
if not bid:
|
||||
print(" 会话 %-3s %-24s 未关联后台批次(重新解析时自动补),跳过" % (sid, (name or "")[:24]))
|
||||
continue
|
||||
src = con.execute("SELECT COUNT(*) FROM hist.lme_lib WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
srcp = con.execute("SELECT COUNT(*) FROM hist.lme_proj WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
if not src and not srcp:
|
||||
print(" 会话 %-3s %-24s 关联的批次 %s 还没有资源库,跳过" % (sid, (name or "")[:24], bid))
|
||||
continue
|
||||
cur = con.execute("""INSERT OR IGNORE INTO s_lme_lib(session_id, code, name, spec, unit, kind, ntp, taxp)
|
||||
SELECT ?, code, name, spec, unit, kind, ntp, taxp
|
||||
FROM hist.lme_lib WHERE batch_id=?""", (sid, bid))
|
||||
n = cur.rowcount
|
||||
cur = con.execute("""INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp)
|
||||
SELECT ?, code, name, spec, unit, kind, qty, ntp, taxp
|
||||
FROM hist.lme_proj WHERE batch_id=?""", (sid, bid))
|
||||
np_ = cur.rowcount
|
||||
have = con.execute("SELECT COUNT(*) FROM s_lme_lib WHERE session_id=?", (sid,)).fetchone()[0]
|
||||
havep = con.execute("SELECT COUNT(*) FROM s_lme_proj WHERE session_id=?", (sid,)).fetchone()[0]
|
||||
n_all += 1
|
||||
print(" 会话 %-3s %-24s 资源库补 %s(现 %s)· 项目级汇总补 %s(现 %s,来自批次 %s)"
|
||||
% (sid, (name or "")[:24], n, have, np_, havep, bid))
|
||||
con.commit()
|
||||
print("会话库回填完成:%s 个会话补上" % n_all)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("== 批次库 history.db ==")
|
||||
backfill_batches()
|
||||
print("== 会话库 session.db ==")
|
||||
backfill_sessions()
|
||||
@@ -1,350 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""前后台一致性校验(防分叉)—— 把「功能一致」变成可断言的契约。
|
||||
|
||||
为什么需要:工作台(workbench.html) 与后台(admin.html) 要求「4 个标签功能完全一致」,
|
||||
但两侧是两份 HTML。若各自维护一份列定义,改动一侧就会**静默分叉**:两边都能正常出结果,
|
||||
只是结论不同,极难发现。这正是 2026-10-01 重构前两侧列数不一致(12 vs 7)的根因。
|
||||
|
||||
硬规则:入口功能一致(4 个标签),数据流与数据库独立(session.db / history.db)。
|
||||
→ 因此「渲染逻辑、列定义、标签顺序、样式」必须只有一份(common.js / common.css);
|
||||
「API 地址、库名」允许不同,且**只允许**不同在 WB_OPTS 与 RawView 配置里。
|
||||
|
||||
守护方式(七道闸):
|
||||
闸1:两侧都必须引入 common.js / common.css
|
||||
闸2:两侧都**不得**再自带列定义(不许出现第二份实现)
|
||||
闸3:common.js 的列与后端 BILLROW() 的字段互为映射
|
||||
闸4:两侧都不得自带基础工具(esc / num / fmtAttr / headHTML / colgHTML)
|
||||
闸5:两侧都不得自带渲染实现(billTR / grpTR / grpTitle / tgGrp / tgNorm / renderLme
|
||||
/ 原数据的 rawTbl/rawProj/rawSec/rawUw/drawRawTree 等)—— 一律由 common.js 提供
|
||||
闸6:标签不得硬编码 data-p(顺序/名称由 common.js 的 TABS 唯一决定)
|
||||
闸7:后端两套接口的**行结构必须一致**(lme 10 列、定额 6 列),否则共用渲染会错位
|
||||
|
||||
用法:
|
||||
python check_parity.py # 有问题时退出码 1
|
||||
"""
|
||||
import io, os, re, sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
UI = os.path.join(ROOT, "ui")
|
||||
SERVER = os.path.join(ROOT, "server")
|
||||
|
||||
# 清单表里必须能映射到后端 BILLROW() 字段的列名(缺一个就说明列被删了 / 后端字段没跟上)
|
||||
BILL_REQUIRED = ["序号", "编码", "名称", "项目特征", "单位",
|
||||
"工程量", "单价", "合价", "单位工程名称"]
|
||||
LME_REQUIRED = ["序号", "编码", "名称", "规格型号", "单位",
|
||||
"数量", "除税编制价", "税率", "含税编制价", "备注"]
|
||||
# ↑「类型」2026-10-08 起不显示(后端仍返回在 r[9],显示 10 列含备注)——要求列表随显示列走
|
||||
|
||||
|
||||
def _read(p):
|
||||
with io.open(p, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def _block(src, name):
|
||||
"""取出 `const NAME = [ ... ];` 的内容块。"""
|
||||
m = re.search(r"const\s+%s\s*=\s*\{(.*?)\n\};" % name, src, re.S)
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def _col_names(block, key):
|
||||
"""从 COLS 定义里取某个键(bill/lme)的列名:['序号',52,'c'] → 序号。
|
||||
|
||||
用**括号平衡**截到该数组真正的结尾 —— 不能用非贪婪正则,列定义跨多行时
|
||||
(`['类别',52,'c'],\\n ['单位工程名称'…`)会在第一行末尾就误截断,报出假缺列。
|
||||
"""
|
||||
m = re.search(r"%s\s*:\s*\[" % key, block)
|
||||
if not m:
|
||||
return None
|
||||
depth, i = 1, m.end()
|
||||
while i < len(block) and depth > 0:
|
||||
if block[i] == "[":
|
||||
depth += 1
|
||||
elif block[i] == "]":
|
||||
depth -= 1
|
||||
i += 1
|
||||
return re.findall(r"\[\s*'([^']*)'", block[m.end():i - 1])
|
||||
|
||||
|
||||
def main():
|
||||
wb = _read(os.path.join(UI, "workbench.html"))
|
||||
ad = _read(os.path.join(UI, "admin.html"))
|
||||
cm = _read(os.path.join(UI, "common.js"))
|
||||
api = _read(os.path.join(SERVER, "api_server.py"))
|
||||
problems = []
|
||||
|
||||
# 注:workbench_map.html 已于 2026-10-01 废弃(它是 gen_workbench_map.py 从 workbench.html
|
||||
# 自动生成的「区块编号标注版」,非独立入口,且长期过期),移入 ui/_deprecated/。
|
||||
# 校验范围收敛为**两个真实入口**:工作台 + 后台。
|
||||
|
||||
# 闸1:两侧都引入 common.js / common.css
|
||||
for tag, src in (("工作台", wb), ("后台", ad)):
|
||||
if "common.js" not in src:
|
||||
problems.append("%s未引入 common.js" % tag)
|
||||
if "common.css" not in src:
|
||||
problems.append("%s未引入 common.css" % tag)
|
||||
|
||||
# 闸2:两侧不得自带第二份列定义
|
||||
if re.search(r"const\s+C_BILL\s*=\s*\[", wb):
|
||||
problems.append("工作台仍自带 C_BILL 定义(应改为 C_BILL = COLS.bill)")
|
||||
if re.search(r"const\s+COL_BILL\s*=\s*\[", ad):
|
||||
problems.append("后台仍自带 COL_BILL 定义(应改为 colsObjs(COLS.bill))")
|
||||
if re.search(r"const\s+C_LME\s*=\s*\[", wb):
|
||||
problems.append("工作台仍自带 C_LME 定义(应改为 C_LME = COLS.lme)")
|
||||
if re.search(r"const\s+COL_LME\s*=\s*\[", ad):
|
||||
problems.append("后台仍自带 COL_LME 定义(应改为 colsObjs(COLS.lme))")
|
||||
|
||||
# 闸4/闸5:两侧不得自带基础工具与渲染实现(这些必须只有 common.js 一份)
|
||||
FORBIDDEN = [
|
||||
(r"function\s+esc\s*\(", "esc"),
|
||||
(r"function\s+num\s*\(", "num"),
|
||||
(r"function\s+fmtAttr\s*\(", "fmtAttr"),
|
||||
(r"function\s+headHTML\s*\(", "headHTML"),
|
||||
(r"function\s+colgHTML\s*\(", "colgHTML"),
|
||||
(r"function\s+billTR\s*\(", "billTR"),
|
||||
(r"function\s+grpTR\s*\(", "grpTR"),
|
||||
(r"function\s+grpTitle\s*\(", "grpTitle"),
|
||||
(r"function\s+tgGrp\s*\(", "tgGrp"),
|
||||
(r"async function\s+tgNorm\s*\(|function\s+tgNorm\s*\(", "tgNorm"),
|
||||
(r"function\s+renderLme\s*\(", "renderLme"),
|
||||
(r"function\s+renderGroups\s*\(", "renderGroups"),
|
||||
(r"function\s+rawTbl\s*\(", "rawTbl"),
|
||||
(r"function\s+rawKV\s*\(", "rawKV"),
|
||||
(r"function\s+rawProj\s*\(", "rawProj"),
|
||||
(r"function\s+rawSec\s*\(", "rawSec"),
|
||||
(r"function\s+rawUw\s*\(", "rawUw"),
|
||||
(r"function\s+rawTreeHTML\s*\(", "rawTreeHTML"),
|
||||
(r"function\s+rawTog\s*\(", "rawTog"),
|
||||
(r"function\s+drawRawTree\s*\(", "drawRawTree"),
|
||||
(r"async function\s+rawDraw\s*\(|function\s+rawDraw\s*\(", "rawDraw"),
|
||||
]
|
||||
for tag, src in (("工作台", wb), ("后台", ad)):
|
||||
for pat, name in FORBIDDEN:
|
||||
if re.search(pat, src):
|
||||
problems.append("%s仍自带 %s()(应改为调用 common.js 的那一份)" % (tag, name))
|
||||
|
||||
# 闸6:标签不得硬编码(顺序/名称由 common.js 的 TABS 唯一决定)
|
||||
for tag, src in (("工作台", wb), ("后台", ad)):
|
||||
if re.search(r'<div class="tab[^"]*" data-p="p\d"', src):
|
||||
problems.append("%s仍硬编码标签 <div class=\"tab\" data-p=...>(应改用 tabsHTML())" % tag)
|
||||
# 公共层的标签顺序必须齐全
|
||||
if not re.search(r"p:\s*'p3'.*p:\s*'p2'.*p:\s*'p1'.*p:\s*'p0'", cm, re.S):
|
||||
problems.append("common.js 的 TABS 顺序不是 原数据→类似清单→组价不一致清单→项目工料机")
|
||||
|
||||
# 闸3:common.js 的列 与 后端字段映射
|
||||
blk = _block(cm, "COLS")
|
||||
if not blk:
|
||||
problems.append("common.js 里找不到 COLS 定义")
|
||||
else:
|
||||
cb, cl = _col_names(blk, "bill"), _col_names(blk, "lme")
|
||||
if not cb or not cl:
|
||||
problems.append("common.js 的 COLS.bill / COLS.lme 解析失败")
|
||||
else:
|
||||
miss_b = [c for c in BILL_REQUIRED if c not in cb]
|
||||
miss_l = [c for c in LME_REQUIRED if c not in cl]
|
||||
if miss_b:
|
||||
problems.append("COLS.bill 缺列:%s" % "、".join(miss_b))
|
||||
if miss_l:
|
||||
problems.append("COLS.lme 缺列:%s" % "、".join(miss_l))
|
||||
|
||||
# 后端:分组算法必须唯一;_billrow 与 BILLROW 列数必须相同
|
||||
if api.count("def _group_by_keywords") != 1:
|
||||
problems.append("_group_by_keywords 不是唯一实现(分组算法只能有一份)")
|
||||
m1 = re.search(r"def _billrow\(x\):(.*?)\n\n", api, re.S)
|
||||
m2 = re.search(r"def BILLROW\(x\):(.*?)\n\n", api, re.S)
|
||||
if m1 and m2:
|
||||
n1 = len(re.findall(r'x\["', m1.group(1)))
|
||||
n2 = len(re.findall(r'x\["', m2.group(1)))
|
||||
if n1 != n2:
|
||||
problems.append("后端行数组列数不一致:_billrow=%d,BILLROW=%d(必须同步改)"
|
||||
% (n1, n2))
|
||||
|
||||
# 闸7:后端两套接口的**行结构必须一致**(共用 common.js 渲染,错位就是静默错误)
|
||||
def _sql_cols(fn):
|
||||
"""取函数里 SELECT ... FROM 之间的列名个数(粗略但足够抓出 7 列 vs 10 列这类分叉)"""
|
||||
m = re.search(r"def\s+%s\((.*?)\n\n\n" % fn, api, re.S)
|
||||
if not m:
|
||||
return None
|
||||
s = re.search(r"SELECT\s+(.*?)\s+FROM", m.group(1), re.S)
|
||||
if not s:
|
||||
return None
|
||||
cols = [c.strip() for c in s.group(1).replace("\n", " ").split(",") if c.strip()]
|
||||
return [c.split()[-1] for c in cols] # 去掉 AS 别名前的东西,保留最终名
|
||||
|
||||
# 行结构由**公共实现**保证(两侧入口已是薄封装),所以直接查公共函数的列数
|
||||
lm = _sql_cols("_lme_rows")
|
||||
if lm and len(lm) != 10:
|
||||
problems.append("_lme_rows 返回 %d 列(应为 10)→ renderLme() 会错位" % len(lm))
|
||||
bn = _sql_cols("_bill_norms")
|
||||
if bn and len(bn) != 6:
|
||||
problems.append("_bill_norms 返回 %d 列(应为 6)→ tgNorm() 会错位" % len(bn))
|
||||
|
||||
# 闸8:后端的同功能接口必须走**同一个公共实现**(TBL 表映射 + _xxx 函数),不得各写一份 SQL
|
||||
COMMON = ["_raw_tree", "_raw_proj", "_raw_sec", "_raw_uw", "_lme_rows", "_bill_norms"]
|
||||
for fn in COMMON:
|
||||
if api.count("def %s(" % fn) != 1:
|
||||
problems.append("公共实现 %s() 定义数=%d(必须恰好 1 份)" % (fn, api.count("def %s(" % fn)))
|
||||
if "TBL = {" not in api:
|
||||
problems.append("后端缺少 TBL 表映射(数据流独立的唯一表达方式)")
|
||||
# 两侧入口必须是「薄封装」:函数体里不该再有 FROM <具体表名>
|
||||
for fn in ("api_raw_tree", "api_admin_raw_tree", "api_raw_proj", "api_admin_raw_proj",
|
||||
"api_raw_sec", "api_admin_raw_sec", "api_raw_uw", "api_admin_raw_uw",
|
||||
"api_lme_rows", "api_bill_norms", "api_session_bill_norms"):
|
||||
m = re.search(r"\ndef %s\(.*?\n(?=\ndef |\Z)" % fn, api, re.S)
|
||||
if m:
|
||||
body = m.group(0)
|
||||
if re.search(r"FROM\s+(s_bills|s_norms|s_lmes|s_divides|s_sections|s_unit_works|sessions)", body):
|
||||
problems.append("%s() 仍在函数体里直接查会话表(应改为调用公共实现)" % fn)
|
||||
if re.search(r"FROM\s+(bills|norms|lmes|divides|sections|unit_works|batches)", body):
|
||||
problems.append("%s() 仍在函数体里直接查批次表(应改为调用公共实现)" % fn)
|
||||
|
||||
# 闸9:两套 schema 必须能**各自独立建库**,且结构对齐
|
||||
# (2026-10-01 教训:schema.sql 长期不完整,缺表缺列,一旦重建库就全线报错)
|
||||
problems.extend(_check_schema())
|
||||
|
||||
# 闸10:xml 格式已于 2026-10-01 停止支持 —— 解析器不得复活,入口必须显式拦截
|
||||
if re.search(r"^\s*def parse_old\(", api, re.M):
|
||||
problems.append("parse_old() 又出现了:xml 已停止支持,该解析器不应复活")
|
||||
if 'if st == "xml"' not in api:
|
||||
problems.append("api_import 缺少 xml 拦截(删除 parse_old 后,传 xml 会直接 500)")
|
||||
job = _read(os.path.join(ROOT, "core", "import_job.py"))
|
||||
if 'from xml.etree import ElementTree as ET' not in job:
|
||||
problems.append("import_job.py 丢了 ElementTree 导入 —— cos4 是 zip 包、内部就是 xml,"
|
||||
"parse_std 依赖它,删了会导致 cos4 也导不进来")
|
||||
|
||||
if problems:
|
||||
print("[FAIL] 前后台存在分叉:")
|
||||
for p in problems:
|
||||
print(" - " + p)
|
||||
return 1
|
||||
print("[OK] 前后台结构一致(列定义唯一来源 common.js,分组算法唯一,两套 schema 可独立建库)")
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 闸9:两套库的 schema 结构
|
||||
# ---------------------------------------------------------------------------
|
||||
# 两库「核心业务列」必须一致(ID 列不同是数据流独立的正常差异,不比)
|
||||
# 注意:主表 batches/sessions 本就不同(跨期次检索 vs 当期会话),不做全等比对
|
||||
MUST_COLS = {
|
||||
("bills", "s_bills"): ["Number", "Name", "Attr", "Unit", "Quantity", "Price",
|
||||
"Total", "Kind", "x_name_norm", "x_attr_norm", "x_unit_norm",
|
||||
"x_hash_exact", "x_seq"],
|
||||
("norms", "s_norms"): ["Number", "Name", "Unit", "Quantity", "Price", "Total"],
|
||||
("lmes", "s_lmes"): ["Number", "Name", "Specification", "Unit", "Quantity",
|
||||
"NoTaxPrice", "TaxRate", "TaxPrice", "Kind",
|
||||
"x_name_norm", "x_spec_norm", "x_unit_norm", "x_hash_exact"],
|
||||
("unit_works", "s_unit_works"): ["Number", "Name", "Total",
|
||||
"DivisionalAndElementalWorks", "Preliminaries",
|
||||
"CostForHSE", "SundryCosts", "Tax"],
|
||||
("sections", "s_sections"): ["Number", "Name", "Total"],
|
||||
("divides", "s_divides"): ["Number", "Name", "Kind", "parent_id", "Total", "x_seq"],
|
||||
("norm_res", "s_norm_res"): ["res_code", "qty"],
|
||||
("remarks", "s_remarks"): ["rkey", "src_key"],
|
||||
}
|
||||
|
||||
|
||||
def _build_mem(sql_path):
|
||||
"""用 schema 文件建一个临时库,返回 (连接, 错误)"""
|
||||
import tempfile
|
||||
try:
|
||||
sql = _read(sql_path)
|
||||
except Exception as e:
|
||||
return None, "读不到 %s:%s" % (os.path.basename(sql_path), e)
|
||||
p = os.path.join(tempfile.gettempdir(), "_parity_%s.db" % os.path.basename(sql_path))
|
||||
if os.path.exists(p):
|
||||
try:
|
||||
os.remove(p)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
import sqlite3
|
||||
c = sqlite3.connect(p)
|
||||
c.executescript(sql)
|
||||
return c, None
|
||||
except Exception as e:
|
||||
return None, "%s 建库失败:%s" % (os.path.basename(sql_path), e)
|
||||
|
||||
|
||||
def _tables(c):
|
||||
return [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table'")]
|
||||
|
||||
|
||||
def _cols(c, t):
|
||||
try:
|
||||
return [r[1] for r in c.execute("PRAGMA table_info(%s)" % t)]
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _tbl_map(api_src):
|
||||
"""从 api_server.py 的 TBL 里抽出两侧的表名(供「表必须存在」检查用)"""
|
||||
m = re.search(r"TBL = \{(.*?)\n\}", api_src, re.S)
|
||||
if not m:
|
||||
return None
|
||||
body = m.group(1)
|
||||
out = {}
|
||||
for scope in ("session", "batch"):
|
||||
seg = re.search(r'"%s":\s*\{(.*?)\}' % scope, body, re.S)
|
||||
if not seg:
|
||||
continue
|
||||
out[scope] = [v for k, v in re.findall(r'"(\w+)":\s*"([^"]+)"', seg.group(1))
|
||||
if k not in ("idcol", "pname")]
|
||||
return out or None
|
||||
|
||||
|
||||
def _check_schema():
|
||||
"""闸9:两套 schema 可独立建库 + 核心列对齐 + TBL 引用的表都存在"""
|
||||
bad = []
|
||||
API = os.path.join(SERVER, "api_server.py")
|
||||
SCH_B = os.path.join(ROOT, "store", "schema.sql") # 批次库(后台/长期)
|
||||
SCH_S = os.path.join(ROOT, "store", "session.sql") # 会话库(工作台/临时)
|
||||
|
||||
cb, e1 = _build_mem(SCH_B)
|
||||
cs, e2 = _build_mem(SCH_S)
|
||||
if e1:
|
||||
bad.append(e1)
|
||||
if e2:
|
||||
bad.append(e2)
|
||||
if not cb or not cs:
|
||||
return bad
|
||||
|
||||
try:
|
||||
tb, ts = _tables(cb), _tables(cs)
|
||||
|
||||
# 9a:TBL 里引用的每一张表,必须在对应 schema 建出的库里存在
|
||||
tm = _tbl_map(_read(API))
|
||||
if not tm:
|
||||
bad.append("api_server.py 里解析不到 TBL 表映射")
|
||||
else:
|
||||
for t in tm.get("batch", []):
|
||||
if t not in tb:
|
||||
bad.append("批次库 schema.sql 缺表 %s(TBL['batch'] 会查它)" % t)
|
||||
for t in tm.get("session", []):
|
||||
if t not in ts:
|
||||
bad.append("会话库 session.sql 缺表 %s(TBL['session'] 会查它)" % t)
|
||||
|
||||
# 9b:核心业务列必须两边都有
|
||||
for (a, b), cols in MUST_COLS.items():
|
||||
ca, cbb = _cols(cb, a), _cols(cs, b)
|
||||
if ca is None:
|
||||
bad.append("批次库缺表 %s" % a)
|
||||
continue
|
||||
if cbb is None:
|
||||
bad.append("会话库缺表 %s" % b)
|
||||
continue
|
||||
miss_a = [c for c in cols if c not in ca]
|
||||
miss_b = [c for c in cols if c not in cbb]
|
||||
if miss_a:
|
||||
bad.append("%s(批次库)缺列:%s" % (a, "、".join(miss_a)))
|
||||
if miss_b:
|
||||
bad.append("%s(会话库)缺列:%s" % (b, "、".join(miss_b)))
|
||||
finally:
|
||||
cb.close()
|
||||
cs.close()
|
||||
return bad
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""死代码体检:列出「定义了但零调用」的函数 / 类 / 常量。
|
||||
|
||||
为什么需要:2026-10-01 连续发现两处同类问题——
|
||||
① import_job.root_of_xml_text() 定义了却全项目零调用(改解析流程时被遗弃)
|
||||
② schema.sql 长期不完整(只改调用方、没回写被调用方)
|
||||
这类残留越积越多,最后没人敢删东西。所以做成可重复跑的体检。
|
||||
|
||||
判定口径(**保守优先**:宁可漏报,不可误报成「可删」)
|
||||
- 引用数 = 全项目(.py / .js / .html)里出现的次数,**排除**整行注释
|
||||
- HTML 里的 onclick / onchange / oninput 等事件属性算引用(前端函数常只在这里被调用)
|
||||
- 定义处自身不计入
|
||||
- 出现在字符串 / 路由表 / 动态分发里的,会被计为引用 → 判「被引用」,不敢误判
|
||||
|
||||
用法:
|
||||
python app/tools/deadcode_scan.py # 全项目
|
||||
python app/tools/deadcode_scan.py --py # 只看 Python
|
||||
python app/tools/deadcode_scan.py --js # 只看 JS
|
||||
python app/tools/deadcode_scan.py --md 报告.md # 顺便写 Markdown 报告
|
||||
"""
|
||||
import io, os, re, sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
assert os.path.basename(ROOT) == "造价审核", "项目根算错了:%s" % ROOT
|
||||
|
||||
SKIP_DIR = {"__pycache__", "_deprecated", ".git", "node_modules", "uploads", "data", "dist", "build"}
|
||||
# 约定上不该判死的东西
|
||||
PY_KEEP = {"main", "__init__", "do_GET", "do_POST", "do_PUT", "do_DELETE",
|
||||
"log_message", "end_headers", "translate_path", "guess_type", "run"}
|
||||
JS_KEEP = {"onWBTab", "WB_TAB", "WB_RAW", "onclick"}
|
||||
|
||||
|
||||
def walk(exts):
|
||||
out = []
|
||||
for dirpath, dirnames, filenames in os.walk(ROOT):
|
||||
dirnames[:] = [d for d in dirnames if d not in SKIP_DIR]
|
||||
for fn in filenames:
|
||||
if any(fn.endswith(e) for e in exts):
|
||||
out.append(os.path.join(dirpath, fn))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def strip_comments(text, lang):
|
||||
"""去掉整行注释(保守:行内注释保留,避免把真引用误判成死代码)"""
|
||||
lines = []
|
||||
for ln in text.split("\n"):
|
||||
s = ln.strip()
|
||||
if lang == "py" and s.startswith("#"):
|
||||
lines.append("")
|
||||
elif lang == "js" and (s.startswith("//") or s.startswith("*") or s.startswith("/*")):
|
||||
lines.append("")
|
||||
else:
|
||||
lines.append(ln)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def collect_files():
|
||||
py = [p for p in walk((".py",))]
|
||||
js = [p for p in walk((".js",))]
|
||||
html = [p for p in walk((".html",))]
|
||||
return py, js, html
|
||||
|
||||
|
||||
def read(p):
|
||||
try:
|
||||
return io.open(p, encoding="utf-8").read()
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def py_defs(src):
|
||||
"""返回 [(名称, 行号, 类型)]"""
|
||||
out = []
|
||||
for m in re.finditer(r"^(\s*)(def|class)\s+(\w+)", src, re.M):
|
||||
kind = "函数" if m.group(2) == "def" else "类"
|
||||
out.append((m.group(3), src[:m.start()].count("\n") + 1, kind))
|
||||
# 模块级常量:全大写(含下划线),至少 3 字符,排除常见内置
|
||||
for m in re.finditer(r"^([A-Z][A-Z0-9_]{2,})\s*=", src, re.M):
|
||||
out.append((m.group(1), src[:m.start()].count("\n") + 1, "常量"))
|
||||
return out
|
||||
|
||||
|
||||
def js_defs(src):
|
||||
out = []
|
||||
for m in re.finditer(r"^\s*(?:async\s+)?function\s+(\w+)\s*\(", src, re.M):
|
||||
out.append((m.group(1), src[:m.start()].count("\n") + 1, "JS函数"))
|
||||
for m in re.finditer(r"^\s*(?:var|let|const)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:function|async\s+function|\()", src, re.M):
|
||||
out.append((m.group(1), src[:m.start()].count("\n") + 1, "JS函数"))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
only = "--py" if "--py" in sys.argv else ("--js" if "--js" in sys.argv else None)
|
||||
md_path = None
|
||||
if "--md" in sys.argv:
|
||||
i = sys.argv.index("--md")
|
||||
if i + 1 < len(sys.argv):
|
||||
md_path = sys.argv[i + 1]
|
||||
|
||||
py_files, js_files, html_files = collect_files()
|
||||
# 语料:去掉整行注释后的全部文本
|
||||
corpus = []
|
||||
for p in py_files:
|
||||
corpus.append(strip_comments(read(p), "py"))
|
||||
for p in js_files:
|
||||
corpus.append(strip_comments(read(p), "js"))
|
||||
for p in html_files:
|
||||
corpus.append(read(p)) # HTML 里的 onclick 必须算引用,不去注释
|
||||
all_text = "\n".join(corpus)
|
||||
|
||||
findings = []
|
||||
if only in (None, "--py"):
|
||||
for p in py_files:
|
||||
src = read(p)
|
||||
clean = strip_comments(src, "py")
|
||||
for name, ln, kind in py_defs(src):
|
||||
if name in PY_KEEP or name.startswith("__") and name != "__init__":
|
||||
continue
|
||||
if name.endswith("__"):
|
||||
continue
|
||||
# 定义处自身 1 次;若只出现这 1 次 → 零调用
|
||||
total = len(re.findall(r"\b" + re.escape(name) + r"\b", all_text))
|
||||
mine = len(re.findall(r"\b" + re.escape(name) + r"\b", clean))
|
||||
if total <= 1 and mine <= 1:
|
||||
findings.append((os.path.relpath(p, ROOT), ln, kind, name, total))
|
||||
if only in (None, "--js"):
|
||||
for p in js_files + html_files:
|
||||
src = read(p)
|
||||
clean = strip_comments(src, "js")
|
||||
for name, ln, kind in js_defs(src):
|
||||
if name in JS_KEEP:
|
||||
continue
|
||||
total = len(re.findall(r"\b" + re.escape(name) + r"\b", all_text))
|
||||
mine = len(re.findall(r"\b" + re.escape(name) + r"\b", clean))
|
||||
if total <= 1 and mine <= 1:
|
||||
findings.append((os.path.relpath(p, ROOT), ln, kind, name, total))
|
||||
|
||||
findings.sort(key=lambda x: (x[0], x[1]))
|
||||
print("=" * 74)
|
||||
print("死代码体检(定义了但全项目零调用)")
|
||||
print("=" * 74)
|
||||
print("扫描范围:%d 个 .py / %d 个 .js / %d 个 .html" % (len(py_files), len(js_files), len(html_files)))
|
||||
print("(已排除 __pycache__ / _deprecated / data / uploads)\n")
|
||||
if not findings:
|
||||
print(" 没有发现零调用的定义。")
|
||||
return 0
|
||||
print("%-38s %-6s %-8s %s" % ("文件", "行", "类型", "名称"))
|
||||
print("-" * 74)
|
||||
for f, ln, kind, name, n in findings:
|
||||
print("%-38s %-6s %-8s %s" % (f[:38], ln, kind, name))
|
||||
print("\n合计 %d 项" % len(findings))
|
||||
print("\n⚠️ 判定说明:引用数按「全项目出现次数」统计,已排除整行注释。")
|
||||
print(" 出现在字符串/动态分发里的会算作引用(保守,不误判为可删)。")
|
||||
print(" 删除前请人工确认一次,尤其是可能被外部脚本或将来功能用到的。")
|
||||
|
||||
if md_path:
|
||||
with io.open(md_path, "w", encoding="utf-8") as fh:
|
||||
fh.write("# 死代码体检报告\n\n")
|
||||
fh.write("扫描范围:%d 个 .py / %d 个 .js / %d 个 .html\n\n" % (len(py_files), len(js_files), len(html_files)))
|
||||
fh.write("| 文件 | 行 | 类型 | 名称 | 引用数 |\n|---|---|---|---|---|\n")
|
||||
for f, ln, kind, name, n in findings:
|
||||
fh.write("| %s | %s | %s | `%s` | %d |\n" % (f, ln, kind, name, n))
|
||||
print("\n报告已写入:%s" % md_path)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,252 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
模拟生成 100 份市场价/信息价批次(每份 >=500 条价格明细),每份挂一个随机附件。
|
||||
|
||||
口径说明(务必与软件一致):
|
||||
- 价格明细的 材料编码/名称/规格/单位 取自现有项目 lmes 去重池("根据现有项目工料机");
|
||||
价格随机生成(按材料关键词给合理区间),其余字段按 api_server 入库口径填。
|
||||
- 归一化与 x_hash_exact 完全复刻 api_server._norm / _md5,保证进库后能被软件比对命中。
|
||||
- 附件走 batches.x_attach_sha -> attachments 表(= 市场价原件/信息价原件)。
|
||||
与 inquiry_files/lme_attach(项目专属询价附件)无关,不破坏"询价附件=项目专属"规则。
|
||||
每份批次生成一个真实小文件存入 data/attachments/<sha[:2]>/。
|
||||
- 幂等:运行前先清掉 Name 以"模拟"开头的旧批次(含其价格、附件文件、attachments 行)。
|
||||
|
||||
运行:python gen_price_mock.py (默认 100 份,每份 500~900 条)
|
||||
python gen_price_mock.py 30 400 600 (30 份,每份 400~600 条)
|
||||
"""
|
||||
import sqlite3, os, re, hashlib, random, sys, time
|
||||
|
||||
def _resolve_db():
|
||||
cands = []
|
||||
try:
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
cands.append(os.path.normpath(os.path.join(here, "..", "..", "data", "history.db")))
|
||||
except Exception:
|
||||
pass
|
||||
cands.append(os.path.normpath(os.path.join(os.getcwd(), "造价审核", "data", "history.db")))
|
||||
cands.append(os.path.normpath(os.path.join(os.getcwd(), "data", "history.db")))
|
||||
cands.append("造价审核/data/history.db")
|
||||
seen = set()
|
||||
for c in cands:
|
||||
if c in seen:
|
||||
continue
|
||||
seen.add(c)
|
||||
if os.path.exists(c):
|
||||
return c
|
||||
return cands[0]
|
||||
|
||||
DB = _resolve_db()
|
||||
DATA_DIR = os.path.dirname(DB) # .../造价审核/data
|
||||
ATTACH_DIR = os.path.join(DATA_DIR, "attachments")
|
||||
PARSER_VER = "2026.10.02-1"
|
||||
|
||||
# ---- 复刻 api_server 归一化(必须与软件一致,否则比对命中不了)----
|
||||
def _norm(s):
|
||||
s = (s or "").strip().replace("(", "(").replace(")", ")").replace("×", "*")
|
||||
s = re.sub(r"\s+", "", s)
|
||||
return s.lower()
|
||||
|
||||
def _md5(*parts):
|
||||
return hashlib.md5("|".join(_norm(p) for p in parts).encode("utf-8")).hexdigest()
|
||||
|
||||
# 价格区间:按材料名称关键词粗略归类,给个像样的单价
|
||||
def guess_price(name, unit):
|
||||
n = name or ""
|
||||
if "人工" in n or "工日" in (unit or ""):
|
||||
return round(random.uniform(80, 260), 2)
|
||||
if any(k in n for k in ("水泥", "砂", "石", "砖", "混凝土", "砂浆", "砌块", "墙材")):
|
||||
return round(random.uniform(20, 600), 2)
|
||||
if any(k in n for k in ("钢筋", "型钢", "钢管", "钢板", "钢带", "镀锌", "钢材")):
|
||||
return round(random.uniform(3000, 6500), 2)
|
||||
if any(k in n for k in ("电缆", "电线", "母线", "导线")):
|
||||
return round(random.uniform(5, 400), 2)
|
||||
if any(k in n for k in ("柴油", "汽油", "电", "水", "燃气")):
|
||||
return round(random.uniform(0.5, 12), 2)
|
||||
if any(k in n for k in ("机械", "台班", "挖掘机", "起重机", "泵车", "装载机", "打桩")):
|
||||
return round(random.uniform(150, 3000), 2)
|
||||
if any(k in n for k in ("门", "窗", "玻璃", "涂料", "防水", "卷材", "管材")):
|
||||
return round(random.uniform(15, 800), 2)
|
||||
if any(k in n for k in ("乔木", "灌木", "苗木", "地被", "草坪", "棕榈", "竹")):
|
||||
return round(random.uniform(5, 1500), 2)
|
||||
return round(random.uniform(2, 2000), 2)
|
||||
|
||||
CLASSES = [
|
||||
"一、黑色及有色金属", "二、安全网、施工围挡",
|
||||
"三、水泥、砖、石、混凝土制品、墙材、瓷砖", "四、PC装配式构件",
|
||||
"五、木材料及其制品、装饰板材", "六、玻璃及玻璃制品", "七、防火门",
|
||||
"八、涂料及防腐、防水材料", "十二、开关、插座", "十三、电线、电缆",
|
||||
"十四、电线电缆敷设管材", "十五、电线电缆桥架(国标厚度)",
|
||||
"十六、密集型铜导体母线槽(外壳防护等级IP65)",
|
||||
"一、假植乔木", "二、假植棕榈科植物", "三、观赏竹类", "四、藤本植物",
|
||||
"五、袋装灌木", "六、袋装地被", "七、水生植物", "八、时花", "九、红树林植物",
|
||||
"横琴粤澳深度合作区材料市场综合价", "万山各岛建设工程人工、机械、材料市场参考价",
|
||||
]
|
||||
BLOCKS = [
|
||||
"珠海市建材设备市场综合价", "珠海市2026年4-6月园林苗木市场信息",
|
||||
"横琴粤澳深度合作区材料市场综合价", "万山各岛建设工程人工、机械、材料市场参考价",
|
||||
]
|
||||
# 各区块对应的真实分类集合(让模拟数据看起来像真实导入,而不是乱配)
|
||||
BLOCK_CLASSES = {
|
||||
"珠海市建材设备市场综合价": [
|
||||
"一、黑色及有色金属", "二、安全网、施工围挡",
|
||||
"三、水泥、砖、石、混凝土制品、墙材、瓷砖", "四、PC装配式构件",
|
||||
"五、木材料及其制品、装饰板材", "六、玻璃及玻璃制品", "七、防火门",
|
||||
"八、涂料及防腐、防水材料", "十二、开关、插座", "十三、电线、电缆",
|
||||
"十四、电线电缆敷设管材", "十五、电线电缆桥架(国标厚度)",
|
||||
"十六、密集型铜导体母线槽(外壳防护等级IP65)",
|
||||
],
|
||||
"珠海市2026年4-6月园林苗木市场信息": [
|
||||
"一、假植乔木", "二、假植棕榈科植物", "三、观赏竹类", "四、藤本植物",
|
||||
"五、袋装灌木", "六、袋装地被", "七、水生植物", "八、时花", "九、红树林植物",
|
||||
],
|
||||
"横琴粤澳深度合作区材料市场综合价": ["横琴粤澳深度合作区材料市场综合价"],
|
||||
"万山各岛建设工程人工、机械、材料市场参考价": ["万山各岛建设工程人工、机械、材料市场参考价"],
|
||||
}
|
||||
REGIONS = [
|
||||
("广东省", "珠海市", "香洲区"), ("广东省", "珠海市", "横琴"),
|
||||
("广东省", "珠海市", "万山镇"), ("福建省", "福州市", "漳州区"),
|
||||
("广西", "桂林市", "桂林区"),
|
||||
]
|
||||
PUBS = ["珠海市住房和城乡建设局", "珠海市建设工程造价管理站", "广东省建设工程标准定额站"]
|
||||
EXTS = ["pdf", "zip", "rar", "txt", "xlsx", "docx"]
|
||||
ATTACH_NAMES = ["询价单", "报价函", "市场调研记录", "厂商回复", "价格确认表", "采购公告", "成交公示"]
|
||||
|
||||
|
||||
def make_attachment(cur, bid, kind, bname):
|
||||
"""生成真实小文件 + 写 attachments 行 + 关联 batches.x_attach_sha。返回 sha。
|
||||
|
||||
文件名按 bname 确定性生成(sha 取 bname 的散列、ext 由 sha 推导),
|
||||
因此重跑会原地覆盖同一文件,不会累积孤儿文件,也不必批量删文件(避免触发安全删除护栏)。
|
||||
"""
|
||||
sha = hashlib.sha256(("mock-price|%s" % bname).encode("utf-8")).hexdigest()
|
||||
ext = EXTS[int(sha, 16) % len(EXTS)]
|
||||
ori = "%s.%s" % (bname, ext)
|
||||
if ext == "pdf":
|
||||
content = b"%PDF-1.4\n" + ("%% mock attachment for %s\n" % bname).encode("utf-8") \
|
||||
+ os.urandom(random.randint(1024, 4096))
|
||||
elif ext in ("zip", "rar"):
|
||||
hdr = b"PK\x03\x04" if ext == "zip" else b"Rar!\x1a\x07"
|
||||
content = hdr + os.urandom(random.randint(2048, 8192))
|
||||
else:
|
||||
content = ("模拟附件(%s)\n本文件为造价审核自动生成的测试样本,无实际业务内容。\n"
|
||||
% bname).encode("utf-8") + os.urandom(random.randint(512, 2048))
|
||||
prefix = sha[:2]
|
||||
stored_name = "%s_%s" % (sha, ori)
|
||||
d = os.path.join(ATTACH_DIR, prefix)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
with open(os.path.join(d, stored_name), "wb") as f:
|
||||
f.write(content)
|
||||
stored_path = os.path.join("attachments", prefix, stored_name)
|
||||
cur.execute("INSERT OR IGNORE INTO attachments(sha256, stored_path, original_name, size, uploaded_at)"
|
||||
" VALUES(?,?,?,?,?)",
|
||||
(sha, stored_path, ori, len(content), time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
cur.execute("UPDATE batches SET x_attach_sha=? WHERE id=?", (sha, bid))
|
||||
return sha
|
||||
|
||||
|
||||
def cleanup_old(con, cur):
|
||||
"""清掉上一轮生成的模拟批次,保证幂等。"""
|
||||
# 2026-10-07:只清价格类模拟(模拟市场价/模拟信息价)——别把项目模拟(模拟项目××)误删
|
||||
old = [r[0] for r in cur.execute(
|
||||
"SELECT id FROM batches WHERE Name LIKE '模拟市场价%' OR Name LIKE '模拟信息价%'").fetchall()]
|
||||
if not old:
|
||||
return 0
|
||||
ph = ",".join("?" * len(old))
|
||||
shas = [r[0] for r in cur.execute(
|
||||
"SELECT DISTINCT x_attach_sha FROM batches WHERE id IN (%s)" % ph, old) if r[0]]
|
||||
# 仅删库内行;附件物理文件交由 make_attachment 按确定性文件名覆盖,
|
||||
# 不在脚本里批量删文件(会触发安全删除护栏)。
|
||||
if shas:
|
||||
cur.execute("DELETE FROM attachments WHERE sha256 IN (%s)" % ",".join("?" * len(shas)), shas)
|
||||
cur.execute("DELETE FROM prices WHERE batch_id IN (%s)" % ph, old)
|
||||
cur.execute("DELETE FROM batches WHERE id IN (%s)" % ph, old)
|
||||
return len(old)
|
||||
|
||||
|
||||
def main():
|
||||
n_batches = int(sys.argv[1]) if len(sys.argv) > 1 else 100
|
||||
lo = int(sys.argv[2]) if len(sys.argv) > 2 else 500
|
||||
hi = int(sys.argv[3]) if len(sys.argv) > 3 else 900
|
||||
|
||||
con = sqlite3.connect(DB)
|
||||
con.execute("PRAGMA foreign_keys = OFF")
|
||||
cur = con.cursor()
|
||||
|
||||
# 去重工料机池
|
||||
cur.execute("SELECT DISTINCT Number, Name, Specification, Unit FROM lmes "
|
||||
"WHERE Name IS NOT NULL AND Name <> ''")
|
||||
pool = [(r[0], r[1], r[2], r[3]) for r in cur.fetchall()]
|
||||
if len(pool) < lo:
|
||||
print("工料机池只有 %d 条,不足以支撑每份 %d 条,退出。" % (len(pool), lo))
|
||||
return
|
||||
print("工料机去重池:%d 条;准备生成 %d 份,每份 %d~%d 条。" % (len(pool), n_batches, lo, hi))
|
||||
|
||||
removed = cleanup_old(con, cur)
|
||||
if removed:
|
||||
print("已清理上一轮模拟批次:%d 份。" % removed)
|
||||
|
||||
random.seed(20261007)
|
||||
kinds = []
|
||||
for i in range(n_batches):
|
||||
kinds.append("market" if i % 2 == 0 else "info")
|
||||
random.shuffle(kinds)
|
||||
|
||||
total_prices = 0
|
||||
t0 = time.time()
|
||||
for i in range(n_batches):
|
||||
kind = kinds[i]
|
||||
n = random.randint(lo, hi)
|
||||
sample = random.sample(pool, n)
|
||||
y = random.choice([2025, 2026])
|
||||
mo = random.randint(1, 12)
|
||||
m_idx = y * 12 + mo
|
||||
prov, city, dist = random.choice(REGIONS)
|
||||
pub = random.choice(PUBS) if kind == "info" else ""
|
||||
block = random.choice(BLOCKS)
|
||||
bname = "模拟%s-%03d" % ("市场价" if kind == "market" else "信息价", i + 1)
|
||||
now = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
cur.execute(
|
||||
"""INSERT INTO batches(kind, Name, FileKind, BulidUnit, x_province, x_city, x_district,
|
||||
x_period_start_m, x_period_end_m, x_enabled, x_total, x_rows_bill, x_rows_lme,
|
||||
x_imported_at, x_src_hash, x_note, x_publisher, x_parser_ver, is_mock)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,1)""",
|
||||
(kind, bname[:200], None, "", prov, city, dist, m_idx, m_idx, None, 0, 0,
|
||||
now, "mock://%s/%03d" % (kind, i + 1), "自动模拟生成", pub, PARSER_VER))
|
||||
bid = cur.lastrowid
|
||||
|
||||
rows = []
|
||||
for (code, name, spec, unit) in sample:
|
||||
nt = guess_price(name, unit)
|
||||
rate = random.choice([0.13, 0.09, 0.03, None])
|
||||
tp = round(nt * (1 + rate), 2) if rate else None
|
||||
cls = random.choice(BLOCK_CLASSES[block])
|
||||
h = _md5(name, spec, unit)
|
||||
rows.append((bid, code, name, spec, unit, nt, rate, tp, cls,
|
||||
"模拟区间价", block, _norm(name), _norm(spec), _norm(unit), h, m_idx, m_idx))
|
||||
cur.executemany(
|
||||
"""INSERT INTO prices(batch_id, Code, Name, Specification, Unit, NoTaxPrice, TaxRate,
|
||||
TaxPrice, Class, Note, Block, x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact,
|
||||
x_period_start_m, x_period_end_m) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", rows)
|
||||
cur.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (n, bid))
|
||||
make_attachment(cur, bid, kind, bname)
|
||||
total_prices += n
|
||||
if (i + 1) % 10 == 0:
|
||||
print(" ...已生成 %d/%d 份(累计 %d 条价格)" % (i + 1, n_batches, total_prices))
|
||||
|
||||
con.commit()
|
||||
dt = time.time() - t0
|
||||
print("完成:%d 份批次,%d 条价格,%.1fs。" % (n_batches, total_prices, dt))
|
||||
# 校验
|
||||
cur.execute("SELECT COUNT(*) FROM batches WHERE Name LIKE '模拟%'")
|
||||
print("校验 batches(模拟):", cur.fetchone()[0])
|
||||
cur.execute("SELECT COUNT(*) FROM prices p JOIN batches b ON b.id=p.batch_id WHERE b.Name LIKE '模拟%'")
|
||||
print("校验 prices(模拟):", cur.fetchone()[0])
|
||||
cur.execute("SELECT MIN(x_rows_price), MAX(x_rows_price) FROM batches WHERE Name LIKE '模拟%'")
|
||||
print("校验 每份条数范围:", cur.fetchone())
|
||||
cur.execute("SELECT COUNT(*) FROM attachments a JOIN batches b ON b.x_attach_sha=a.sha256 WHERE b.Name LIKE '模拟%'")
|
||||
print("校验 已挂附件的模拟批次:", cur.fetchone()[0])
|
||||
con.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,83 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""模拟生成项目批次(列表测试用,2026-10-07)。
|
||||
|
||||
与 gen_price_mock.py 同族:Name 以「模拟」开头保证幂等清理,is_mock=1 供
|
||||
后台「清空模拟数据」整批删除。**只生成 batches 行**(清单/定额/工料机明细不生成
|
||||
——用途是列表 UI 的排序/分页/滚动压测,点开模拟批次的明细是空表属预期)。
|
||||
|
||||
运行:python tools/gen_project_mock.py 3000
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
DB_CANDS = [
|
||||
os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "data", "history.db")),
|
||||
os.path.normpath(os.path.join(os.getcwd(), "data", "history.db")),
|
||||
]
|
||||
DB = next((c for c in DB_CANDS if os.path.exists(c)), DB_CANDS[0])
|
||||
|
||||
STEMS = [
|
||||
"市政道路改造工程", "供水管网升级工程", "老旧小区环境整治提升工程", "产业园基础设施工程",
|
||||
"学校改扩建工程", "医院配套设施工程", "公园绿地建设工程", "桥涵结构工程", "隧道结构工程",
|
||||
"海绵城市建设工程", "污水处理厂扩建工程", "保障房建设项目", "智慧城市基础设施工程",
|
||||
"河道整治与生态修复工程", "地下综合管廊工程", "LED 路灯节能改造工程",
|
||||
]
|
||||
UNITS = ["珠海市供水有限公司", "珠海城建市政建设有限公司", "珠海市政府投资工程项目管理中心",
|
||||
"北京师范大学珠海校区", "珠海市香洲区三溪科创小镇发展中心", "广东省建筑工程集团"]
|
||||
REGIONS = [("广东省", "珠海市", "香洲区"), ("广东省", "珠海市", "横琴"),
|
||||
("广东省", "珠海市", "万山镇"), ("福建省", "福州市", "漳州区"),
|
||||
("广西", "桂林市", "桂林区")]
|
||||
KINDS = [1, 2, 3, 4] # 单价类型:预算综合/投标综合/预算全费用/投标全费用
|
||||
|
||||
|
||||
def main(n=3000):
|
||||
n = int(n)
|
||||
con = sqlite3.connect(DB)
|
||||
con.execute("PRAGMA foreign_keys = OFF")
|
||||
cur = con.cursor()
|
||||
|
||||
# 幂等:清掉上一轮项目模拟(Name 以「模拟项目」开头;is_mock=1)
|
||||
old = [r[0] for r in cur.execute(
|
||||
"SELECT id FROM batches WHERE kind='project' AND Name LIKE '模拟项目%'").fetchall()]
|
||||
if old:
|
||||
ph = ",".join("?" * len(old))
|
||||
cur.execute("DELETE FROM bills WHERE batch_id IN (%s)" % ph, old)
|
||||
cur.execute("DELETE FROM batches WHERE id IN (%s)" % ph, old)
|
||||
print("已清理上一轮项目模拟:%d 份。" % len(old))
|
||||
|
||||
# 基于现有真实项目名取词根("基于现有数据")
|
||||
stems = [r[0] for r in con.execute(
|
||||
"SELECT DISTINCT Name FROM batches WHERE kind='project' AND Name NOT LIKE '模拟%' LIMIT 30")]
|
||||
stems = [s for s in stems if s] or STEMS
|
||||
|
||||
random.seed(20261007)
|
||||
now = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
t0 = time.time()
|
||||
for i in range(n):
|
||||
base = random.choice(stems).strip()
|
||||
name = "模拟项目%04d-%s" % (i + 1, base[:18])
|
||||
y, mo = random.choice([2025, 2026]), random.randint(1, 12)
|
||||
m = y * 12 + mo
|
||||
prov, city, dist = random.choice(REGIONS)
|
||||
cur.execute(
|
||||
"""INSERT INTO batches(kind, Name, FileKind, BulidUnit, x_province, x_city, x_district,
|
||||
x_period_start_m, x_period_end_m, x_enabled, x_total, x_rows_bill, x_rows_lme,
|
||||
x_imported_at, x_src_hash, x_parser_ver, is_mock)
|
||||
VALUES('project',?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,1)""",
|
||||
(name[:200], random.choice(KINDS), random.choice(UNITS),
|
||||
prov, city, dist, m, m,
|
||||
round(random.uniform(3_000_000, 420_000_000), 2),
|
||||
random.randint(200, 5200), random.randint(300, 6800),
|
||||
now, "mock://project/%04d" % (i + 1), "2026.10.02-1"))
|
||||
con.commit()
|
||||
print("完成:%d 份项目模拟批次,%.1fs。" % (n, time.time() - t0))
|
||||
print("校验:", cur.execute(
|
||||
"SELECT COUNT(*) FROM batches WHERE kind='project' AND Name LIKE '模拟项目%'").fetchone()[0])
|
||||
con.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1] if len(sys.argv) > 1 else 3000)
|
||||
@@ -1,173 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""提交前体检门禁(2026-10-06)。
|
||||
|
||||
为什么要有这道闸:
|
||||
10-06 那天 app/ui/common.js 被整段写成随机二进制,工具却报告"写入成功"。
|
||||
它当时**根本没进 git**,于是唯一的副本就是那份坏文件,最后只能靠重建。
|
||||
更危险的是:如果当时已经配了"每天自动 git commit",坏文件会被**自动提交**,
|
||||
把服务器上一份好版本也顶掉 —— 备份就变成了销毁。
|
||||
|
||||
所以体检必须跑在 `git add` **之前**,且只要有一个文件坏,就中止提交。
|
||||
|
||||
查三件事(语法没错 ≠ 没坏):
|
||||
① 编码:必须能按 UTF-8 解开(随机二进制在这一步就露馅)
|
||||
② 语法:.js 走 node --check,.py 走 py_compile
|
||||
③ 锚点:唯一来源文件必须含关键符号 —— 防"语法合法但内容被截短/换成别的"
|
||||
另加④ 体积骤降:比上次体检小一半以上且掉超 2KB,多半是被截断,同样拦下
|
||||
|
||||
用法:
|
||||
python health_check.py # 体检,坏了 exit 1(备份脚本据此中止)
|
||||
python health_check.py --init # 只建基线不判体积(首次/大改后跑一次)
|
||||
"""
|
||||
import os, sys, json, subprocess, shutil
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.abspath(os.path.join(HERE, '..', '..', '..')) # 项目根(D:/Pricing review)
|
||||
APP = os.path.join(ROOT, '造价审核', 'app')
|
||||
BASE = os.path.join(ROOT, '.workbuddy', 'health_baseline.json') # .workbuddy 已被 gitignore
|
||||
|
||||
EXT = ('.py', '.js', '.html', '.css', '.sql')
|
||||
SKIP_DIR = {'__pycache__', 'node_modules', '.git', 'release', '_build', 'data', 'uploads'}
|
||||
# 顶层也要查的(根目录脚本/文档不查,只查 app 下的代码)
|
||||
|
||||
# 唯一来源文件 → 必须出现的关键串(缺一个就是内容不对)
|
||||
ANCHORS = {
|
||||
os.path.join('ui', 'common.js'): [
|
||||
'function esc(', 'function ell(', 'const COLS', 'function RawView',
|
||||
'function regFill', 'function saveAs', 'function tgNorm', 'function renderLme'],
|
||||
os.path.join('ui', 'common.css'): ['.ell{', '.kind', '.brow'],
|
||||
os.path.join('store', 'schema.sql'): ['CREATE TABLE'],
|
||||
os.path.join('store', 'session.sql'): ['CREATE TABLE'],
|
||||
}
|
||||
|
||||
|
||||
def find_node():
|
||||
base = os.path.join(os.path.expanduser('~'), '.workbuddy', 'binaries', 'node', 'versions')
|
||||
if os.path.isdir(base):
|
||||
for d in sorted(os.listdir(base), reverse=True):
|
||||
for cand in (os.path.join(base, d, 'node.exe'), os.path.join(base, d, 'bin', 'node.exe')):
|
||||
if os.path.exists(cand):
|
||||
return cand
|
||||
return None
|
||||
|
||||
|
||||
NODE = find_node()
|
||||
PY = sys.executable
|
||||
|
||||
|
||||
def check_utf8(p):
|
||||
try:
|
||||
with open(p, 'rb') as f:
|
||||
f.read().decode('utf-8')
|
||||
return None
|
||||
except Exception as e:
|
||||
return 'UTF-8 解不开(多半被写成二进制):%s' % e
|
||||
|
||||
|
||||
def _as_ext(p, ext):
|
||||
"""校验用的路径:node / py_compile 都是**按后缀**认文件类型的,
|
||||
给它们一个 .tmp 会直接报 Unknown file extension,所以先复制成正确后缀的副本。"""
|
||||
if p.endswith(ext):
|
||||
return p, None
|
||||
t = p + ext
|
||||
shutil.copyfile(p, t)
|
||||
return t, t
|
||||
|
||||
|
||||
def check_syntax(p, ext=None):
|
||||
# ext 可显式传入:校验 .tmp 临时文件时,后缀是 .tmp,必须按**目标文件**的类型判
|
||||
ext = ext or os.path.splitext(p)[1].lower()
|
||||
if ext == '.js':
|
||||
if not NODE:
|
||||
return None, '(未找到 node,跳过语法检查)'
|
||||
tgt, tmp = _as_ext(p, ext)
|
||||
try:
|
||||
r = subprocess.run([NODE, '--check', tgt], capture_output=True)
|
||||
finally:
|
||||
if tmp and os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
return (None if r.returncode == 0 else r.stderr.decode('utf-8', 'ignore').strip()[:160]), None
|
||||
if ext == '.py':
|
||||
tgt, tmp = _as_ext(p, ext)
|
||||
try:
|
||||
r = subprocess.run([PY, '-m', 'py_compile', tgt], capture_output=True)
|
||||
finally:
|
||||
if tmp and os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
return (None if r.returncode == 0 else r.stderr.decode('utf-8', 'ignore').strip()[:160]), None
|
||||
return None, None
|
||||
|
||||
|
||||
def check_anchor(rel):
|
||||
keys = ANCHORS.get(rel)
|
||||
if not keys:
|
||||
return None
|
||||
try:
|
||||
s = open(os.path.join(APP, rel), encoding='utf-8').read()
|
||||
except Exception as e:
|
||||
return '读不出来:%s' % e
|
||||
miss = [k for k in keys if k not in s]
|
||||
return ('关键符号缺失:%s —— 文件可能被截短或换成了别的版本' % ', '.join(miss)) if miss else None
|
||||
|
||||
|
||||
def main():
|
||||
init_only = '--init' in sys.argv
|
||||
files = []
|
||||
for dirpath, dirnames, filenames in os.walk(APP):
|
||||
dirnames[:] = [d for d in dirnames if d not in SKIP_DIR]
|
||||
for fn in filenames:
|
||||
if fn.endswith(EXT):
|
||||
files.append(os.path.join(dirpath, fn))
|
||||
|
||||
old = {}
|
||||
if os.path.exists(BASE):
|
||||
try:
|
||||
old = json.load(open(BASE, encoding='utf-8'))
|
||||
except Exception:
|
||||
old = {}
|
||||
new = {}
|
||||
bad, warn = [], []
|
||||
|
||||
for p in sorted(files):
|
||||
rel = os.path.relpath(p, APP).replace('\\', '/')
|
||||
sz = os.path.getsize(p)
|
||||
new[rel] = sz
|
||||
e = check_utf8(p)
|
||||
if e:
|
||||
bad.append((rel, e)); continue
|
||||
e, note = check_syntax(p)
|
||||
if e:
|
||||
bad.append((rel, '语法错误:' + e)); continue
|
||||
if note:
|
||||
warn.append((rel, note))
|
||||
e = check_anchor(rel)
|
||||
if e:
|
||||
bad.append((rel, e)); continue
|
||||
if (not init_only) and rel in old:
|
||||
o = old[rel]
|
||||
if sz < o * 0.5 and (o - sz) > 2000:
|
||||
bad.append((rel, '体积骤降 %d → %d 字节,疑似被截断' % (o, sz)))
|
||||
|
||||
os.makedirs(os.path.dirname(BASE), exist_ok=True)
|
||||
json.dump(new, open(BASE, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
||||
|
||||
print('=' * 62)
|
||||
print(' 提交前体检:共 %d 个文件' % len(files))
|
||||
print('=' * 62)
|
||||
for r, m in bad:
|
||||
print(' [坏] %s' % r)
|
||||
print(' %s' % m)
|
||||
for r, m in warn:
|
||||
print(' [提醒] %s %s' % (r, m))
|
||||
if not bad and not warn:
|
||||
print(' 全部通过:编码 OK / 语法 OK / 关键符号全在 / 体积无异常')
|
||||
print('=' * 62)
|
||||
if bad:
|
||||
print(' 体检不通过 —— 已中止,本次不会提交任何东西。')
|
||||
print(' 请先把上面标[坏]的文件修好,再重新备份。')
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,158 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""按「源文件格式」清理批次库里已导入的批次。
|
||||
|
||||
用途:某种格式不再支持导入后,把历史上由该格式导入的批次一并清掉,避免库里留着
|
||||
「现在再也导不进来」的数据(会造成困惑:看得见、但没法重建)。
|
||||
|
||||
识别方式:**按源文件 SHA1 指纹匹配** batches.x_src_hash —— 不看文件名。
|
||||
(实测 #13「…施工6.29xml.cos4」名字里带 xml 但其实是 cos4,按名字判断会误删。)
|
||||
|
||||
安全:删除前**先备份**整库;只删显式命中的批次,其余原样保留。
|
||||
|
||||
用法:
|
||||
python app/tools/purge_batches.py --by-ext .xml # 清理 xml 导入的批次
|
||||
python app/tools/purge_batches.py --by-ext .xml --dry # 只列不删
|
||||
python app/tools/purge_batches.py --ids 3,5,7 # 按批次 id 删
|
||||
"""
|
||||
import io, os, sys, shutil, sqlite3, time, hashlib
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
DB = os.path.join(ROOT, "data", "history.db")
|
||||
SRC = os.path.join(os.path.dirname(ROOT), "后台需要导入的项目")
|
||||
|
||||
assert os.path.basename(ROOT) == "造价审核", "项目根算错了:%s" % ROOT
|
||||
assert os.path.isdir(SRC), "导入目录找不到:%s" % SRC
|
||||
|
||||
|
||||
def log(s):
|
||||
print(s, flush=True)
|
||||
|
||||
|
||||
def sha1_of(p):
|
||||
h = hashlib.sha1()
|
||||
with open(p, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def ids_by_ext(ext):
|
||||
"""扫描导入目录里该扩展名的文件,用指纹反查批次 id"""
|
||||
ext = ext.lower()
|
||||
hashes = {}
|
||||
for fn in sorted(os.listdir(SRC)):
|
||||
if not fn.lower().endswith(ext):
|
||||
continue
|
||||
hashes[sha1_of(os.path.join(SRC, fn))] = fn
|
||||
c = sqlite3.connect(DB)
|
||||
c.row_factory = sqlite3.Row
|
||||
out = []
|
||||
for r in c.execute("SELECT id,Name,x_src_hash FROM batches"):
|
||||
if r["x_src_hash"] in hashes:
|
||||
out.append((r["id"], str(r["Name"]), hashes[r["x_src_hash"]]))
|
||||
c.close()
|
||||
return out
|
||||
|
||||
|
||||
def purge(ids):
|
||||
"""级联删除批次及其全部子数据"""
|
||||
c = sqlite3.connect(DB)
|
||||
before = {}
|
||||
for t in ("batches", "bills", "norms", "lmes", "unit_works", "sections",
|
||||
"divides", "norm_res", "prices", "import_log"):
|
||||
try:
|
||||
before[t] = c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0]
|
||||
except Exception:
|
||||
before[t] = None
|
||||
for bid in ids:
|
||||
c.execute("DELETE FROM norm_res WHERE norm_id IN "
|
||||
"(SELECT id FROM norms WHERE bill_id IN (SELECT id FROM bills WHERE batch_id=?))", (bid,))
|
||||
c.execute("DELETE FROM norms WHERE bill_id IN (SELECT id FROM bills WHERE batch_id=?)", (bid,))
|
||||
for t in ("bills", "lmes", "unit_works", "sections", "divides", "prices", "import_log"):
|
||||
try:
|
||||
c.execute("DELETE FROM %s WHERE batch_id=?" % t, (bid,))
|
||||
except Exception:
|
||||
pass
|
||||
c.execute("DELETE FROM batches WHERE id=?", (bid,))
|
||||
# 兜底:清掉任何漏网的孤儿(父行已删但子行还在)
|
||||
c.execute("DELETE FROM norm_res WHERE norm_id NOT IN (SELECT id FROM norms)")
|
||||
c.execute("DELETE FROM norms WHERE bill_id NOT IN (SELECT id FROM bills)")
|
||||
# divides 有两层归属(batch_id + uw_id + parent_id 层级),循环清到稳定为止
|
||||
for _ in range(5):
|
||||
n1 = c.execute("DELETE FROM divides WHERE uw_id IS NOT NULL "
|
||||
"AND uw_id NOT IN (SELECT id FROM unit_works)").rowcount
|
||||
n2 = c.execute("DELETE FROM divides WHERE parent_id IS NOT NULL "
|
||||
"AND parent_id NOT IN (SELECT id FROM divides)").rowcount
|
||||
if n1 + n2 == 0:
|
||||
break
|
||||
c.commit()
|
||||
c.execute("VACUUM")
|
||||
c.commit()
|
||||
after = {}
|
||||
for t in before:
|
||||
try:
|
||||
after[t] = c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0]
|
||||
except Exception:
|
||||
after[t] = None
|
||||
c.close()
|
||||
return before, after
|
||||
|
||||
|
||||
def main():
|
||||
dry = "--dry" in sys.argv
|
||||
ext = None
|
||||
ids = None
|
||||
for i, a in enumerate(sys.argv):
|
||||
if a == "--by-ext" and i + 1 < len(sys.argv):
|
||||
ext = sys.argv[i + 1]
|
||||
if a == "--ids" and i + 1 < len(sys.argv):
|
||||
ids = [int(x) for x in sys.argv[i + 1].split(",") if x.strip().isdigit()]
|
||||
|
||||
if not os.path.exists(DB):
|
||||
log("库不存在:%s" % DB)
|
||||
return 1
|
||||
if not ids and not ext:
|
||||
log("请指定 --by-ext <扩展名> 或 --ids <id列表>")
|
||||
return 1
|
||||
|
||||
if ext:
|
||||
found = ids_by_ext(ext)
|
||||
if not found:
|
||||
log("没有由 %s 导入的批次" % ext)
|
||||
return 0
|
||||
log("匹配到 %d 个批次(按源文件指纹):" % len(found))
|
||||
for bid, nm, fn in found:
|
||||
log(" #%-3d %-40s ← %s" % (bid, nm[:40], fn[:46]))
|
||||
ids = [x[0] for x in found]
|
||||
else:
|
||||
c = sqlite3.connect(DB)
|
||||
log("指定删除批次:")
|
||||
for bid in ids:
|
||||
r = c.execute("SELECT Name FROM batches WHERE id=?", (bid,)).fetchone()
|
||||
log(" #%-3d %s" % (bid, (r[0] if r else "(不存在)")))
|
||||
c.close()
|
||||
|
||||
if dry:
|
||||
log("\n--dry:只列出,未删除")
|
||||
return 0
|
||||
|
||||
stamp = time.strftime("%Y%m%d_%H%M%S")
|
||||
bak = DB + ".bak_" + stamp
|
||||
shutil.copy2(DB, bak)
|
||||
log("\n已备份 → %s (%.1f MB)" % (os.path.basename(bak), os.path.getsize(bak) / 1048576.0))
|
||||
|
||||
log("\n删除 %d 个批次及级联数据…" % len(ids))
|
||||
before, after = purge(ids)
|
||||
log("\n%12s %12s %12s" % ("表", "删前", "删后"))
|
||||
for t in before:
|
||||
if before[t] is None:
|
||||
continue
|
||||
log("%12s %12s %12s" % (t, before[t], after[t]))
|
||||
log("\n库大小:%.1f MB" % (os.path.getsize(DB) / 1048576.0))
|
||||
log("备份在:%s" % bak)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,177 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""全量重建后台批次库(history.db)并重新导入「后台需要导入的项目」目录里的文件。
|
||||
|
||||
为什么需要:2026-10-01 给批次库补了层级表(sections/unit_works/divides/norm_res/remarks)
|
||||
与工程量列(bills.Quantity/Total/uw_id),**已导入的老批次没有这些字段的数据**(导入时才写)。
|
||||
开发阶段数据可全量重导,故直接重建,不做兼容迁移。
|
||||
|
||||
安全:执行前**先备份**原库到 history.db.bak_<时间戳>;失败也不会丢数据。
|
||||
|
||||
用法:
|
||||
python app/tools/rebuild_batch_db.py # 备份 + 重建 + 导入 + 验证
|
||||
python app/tools/rebuild_batch_db.py --no-import # 只备份 + 重建(不导入)
|
||||
"""
|
||||
import io, os, sys, shutil, sqlite3, time, hashlib, traceback
|
||||
|
||||
# __file__ = <根>/造价审核/app/tools/rebuild_batch_db.py
|
||||
# dirname×1 = 造价审核/app/tools dirname×2 = 造价审核/app dirname×3 = 造价审核(项目根)
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
DB = os.path.join(ROOT, "data", "history.db")
|
||||
SCHEMA = os.path.join(ROOT, "app", "store", "schema.sql")
|
||||
SRC = os.path.join(os.path.dirname(ROOT), "后台需要导入的项目")
|
||||
|
||||
# 起手先自检:路径不对就直接停,绝不能把库删错地方
|
||||
assert os.path.isfile(SCHEMA), "schema.sql 找不到:%s" % SCHEMA
|
||||
assert os.path.basename(ROOT) == "造价审核", "项目根算错了:%s" % ROOT
|
||||
assert os.path.isdir(SRC), "导入目录找不到:%s" % SRC
|
||||
|
||||
# 价格类(信息价/市场价)走另一条导入路径,与工程文件区分
|
||||
PRICE_SUFFIX = ("price_html",)
|
||||
|
||||
|
||||
def log(s):
|
||||
print(s, flush=True)
|
||||
|
||||
|
||||
def backup():
|
||||
if not os.path.exists(DB):
|
||||
log(" 原库不存在,无需备份")
|
||||
return None
|
||||
stamp = time.strftime("%Y%m%d_%H%M%S")
|
||||
dst = DB + ".bak_" + stamp
|
||||
shutil.copy2(DB, dst)
|
||||
for ext in ("-wal", "-shm"):
|
||||
p = DB + ext
|
||||
if os.path.exists(p):
|
||||
shutil.copy2(p, dst + ext)
|
||||
log(" 已备份 → %s (%.1f MB)" % (os.path.basename(dst), os.path.getsize(dst) / 1048576.0))
|
||||
return dst
|
||||
|
||||
|
||||
def drop():
|
||||
for p in (DB, DB + "-wal", DB + "-shm"):
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
log(" 已删除 %s" % os.path.basename(p))
|
||||
|
||||
|
||||
def create():
|
||||
sql = io.open(SCHEMA, encoding="utf-8").read()
|
||||
c = sqlite3.connect(DB)
|
||||
c.executescript(sql)
|
||||
c.commit()
|
||||
tabs = [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")]
|
||||
c.close()
|
||||
log(" 已按 schema.sql 建库:%d 张表" % len(tabs))
|
||||
return tabs
|
||||
|
||||
|
||||
def sha1_of(p):
|
||||
h = hashlib.sha1()
|
||||
with open(p, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
do_import = "--no-import" not in sys.argv
|
||||
log("=" * 62)
|
||||
log("全量重建批次库 history.db")
|
||||
log("=" * 62)
|
||||
|
||||
log("\n[1/4] 备份原库")
|
||||
bak = backup()
|
||||
|
||||
log("\n[2/4] 删除旧库")
|
||||
drop()
|
||||
|
||||
log("\n[3/4] 按新 schema 建库")
|
||||
create()
|
||||
|
||||
if not do_import:
|
||||
log("\n(--no-import:跳过导入)")
|
||||
return 0
|
||||
|
||||
# 导入依赖生产环境模块,这里 stub 掉测试机上没有的包
|
||||
import types
|
||||
sys.modules.setdefault("openpyxl", types.SimpleNamespace(
|
||||
Workbook=object, load_workbook=lambda *a, **k: None))
|
||||
sys.modules.setdefault("search_demo", types.SimpleNamespace(build=lambda *a, **k: None))
|
||||
sys.path.insert(0, os.path.join(ROOT, "app", "server"))
|
||||
import api_server as A
|
||||
|
||||
log("\n[4/4] 导入 %s" % SRC)
|
||||
files = A.api_scan().get("files", [])
|
||||
if not files:
|
||||
log(" 目录里没有可导入文件")
|
||||
return 1
|
||||
ok, fail = 0, []
|
||||
for f in files:
|
||||
fn, st = f["name"], f.get("state")
|
||||
price = st in PRICE_SUFFIX
|
||||
body = {
|
||||
"kind": "info" if price else "project",
|
||||
"path": f["path"],
|
||||
"name": os.path.splitext(fn)[0],
|
||||
"province": "", "city": "", "district": "",
|
||||
"period_from": None, "period_to": None,
|
||||
"bulid_unit": "", "sha": sha1_of(f["path"]), "force": True,
|
||||
}
|
||||
t0 = time.time()
|
||||
try:
|
||||
con = A.conn()
|
||||
try:
|
||||
r = A.api_import(con, body)
|
||||
if r.get("ok"):
|
||||
con.commit()
|
||||
else:
|
||||
con.rollback()
|
||||
finally:
|
||||
con.close()
|
||||
except Exception as e:
|
||||
r = {"ok": False, "msg": "异常:" + str(e)}
|
||||
traceback.print_exc()
|
||||
dt = time.time() - t0
|
||||
if r.get("ok"):
|
||||
ok += 1
|
||||
extra = ""
|
||||
if not price:
|
||||
extra = " 清单%s 定额%s 工料机%s" % (r.get("n_bill", "-"), r.get("n_norm", "-"), r.get("n_lme", "-"))
|
||||
log(" [OK] %-52s %6.1fs%s" % (fn[:52], dt, extra))
|
||||
else:
|
||||
fail.append((fn, str(r.get("msg", ""))[:70]))
|
||||
log(" [FAIL] %-50s %s" % (fn[:50], str(r.get("msg", ""))[:70]))
|
||||
|
||||
log("\n导入结果:成功 %d / 失败 %d" % (ok, len(fail)))
|
||||
for fn, msg in fail:
|
||||
log(" × %s → %s" % (fn, msg))
|
||||
|
||||
log("\n" + "=" * 62)
|
||||
log("验证")
|
||||
log("=" * 62)
|
||||
c = sqlite3.connect(DB)
|
||||
for t in ("batches", "bills", "norms", "lmes", "unit_works", "sections", "divides", "norm_res", "prices"):
|
||||
try:
|
||||
log(" %-12s %s" % (t, c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0]))
|
||||
except Exception as e:
|
||||
log(" %-12s 查询失败 %s" % (t, e))
|
||||
log("\n各批次层级 / 工程量:")
|
||||
for r in c.execute("SELECT id, Name FROM batches ORDER BY id"):
|
||||
uw = c.execute("SELECT COUNT(*) FROM unit_works WHERE batch_id=?", (r[0],)).fetchone()[0]
|
||||
sc = c.execute("SELECT COUNT(*) FROM sections WHERE batch_id=?", (r[0],)).fetchone()[0]
|
||||
bl = c.execute("SELECT COUNT(*) FROM bills WHERE batch_id=?", (r[0],)).fetchone()[0]
|
||||
q = c.execute("SELECT COUNT(*) FROM bills WHERE batch_id=? AND Quantity IS NOT NULL AND Quantity<>0",
|
||||
(r[0],)).fetchone()[0]
|
||||
flag = "OK" if (bl == 0 or uw > 0) else "无层级!"
|
||||
log(" #%-3d %-44s 单项%s 单位工程%-4s 清单%-6s 有工程量%-6s %s"
|
||||
% (r[0], str(r[1])[:44], sc, uw, bl, q, flag))
|
||||
c.close()
|
||||
if bak:
|
||||
log("\n原库备份在:%s" % bak)
|
||||
return 0 if not fail else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,133 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""安全写文件 + 自动快照(2026-10-06)。
|
||||
|
||||
事故背景:common.js 被整段写成随机二进制,而工具报告"写入成功"。
|
||||
直接从源头堵:以后写核心文件都走这里 —— 先留快照,再写临时文件,
|
||||
**校验通过才原子替换**;校验不过就删掉临时文件,原文件一动不动。
|
||||
|
||||
三道保险:
|
||||
① 写前快照:旧版存进 .workbuddy/snapshots/(保留最近 10 份)
|
||||
② 原子替换:先写 .tmp → 校验 → os.replace() 一步换掉(不会存在"写了一半"的中间态)
|
||||
③ 写完校验:UTF-8 + 语法 + 关键符号,任一项不过就回滚
|
||||
|
||||
命令行:
|
||||
python safe_write.py snap 造价审核/app/ui/common.js # 只留快照
|
||||
python safe_write.py list 造价审核/app/ui/common.js # 列出快照
|
||||
python safe_write.py restore 造价审核/app/ui/common.js # 回滚到上一份
|
||||
作为模块用(推荐,我以后改文件走这条):
|
||||
import safe_write
|
||||
safe_write.write('造价审核/app/ui/common.js', text)
|
||||
"""
|
||||
import os, sys, shutil, subprocess, time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.abspath(os.path.join(HERE, '..', '..', '..'))
|
||||
SNAP = os.path.join(ROOT, '.workbuddy', 'snapshots') # .workbuddy 已被 gitignore
|
||||
KEEP = 10
|
||||
|
||||
sys.path.insert(0, HERE)
|
||||
import health_check as HC # 复用同一套校验口径
|
||||
|
||||
|
||||
def _abs(rel):
|
||||
return rel if os.path.isabs(rel) else os.path.join(ROOT, rel)
|
||||
|
||||
|
||||
def snapshot(rel):
|
||||
"""写前留一份旧版。返回快照路径(原文件不存在时返回 None)。"""
|
||||
p = _abs(rel)
|
||||
if not os.path.exists(p):
|
||||
return None
|
||||
d = os.path.join(SNAP, os.path.dirname(os.path.relpath(p, ROOT)).replace('\\', '/'))
|
||||
os.makedirs(d, exist_ok=True)
|
||||
name = '%s_%s' % (time.strftime('%m%d-%H%M%S'), os.path.basename(p))
|
||||
dst = os.path.join(d, name)
|
||||
shutil.copy2(p, dst)
|
||||
# 只留最近 KEEP 份
|
||||
olds = sorted([x for x in os.listdir(d) if x.endswith('_' + os.path.basename(p))])
|
||||
for x in olds[:-KEEP]:
|
||||
try:
|
||||
os.remove(os.path.join(d, x))
|
||||
except Exception:
|
||||
pass
|
||||
return dst
|
||||
|
||||
|
||||
def list_snaps(rel):
|
||||
p = _abs(rel)
|
||||
d = os.path.join(SNAP, os.path.dirname(os.path.relpath(p, ROOT)).replace('\\', '/'))
|
||||
if not os.path.isdir(d):
|
||||
return []
|
||||
return sorted([x for x in os.listdir(d) if x.endswith('_' + os.path.basename(p))])
|
||||
|
||||
|
||||
def restore(rel, n=1):
|
||||
"""回滚到第 n 新的快照(n=1 即上一份)。"""
|
||||
snaps = list_snaps(rel)
|
||||
if not snaps:
|
||||
raise SystemExit('没有快照可回滚:%s' % rel)
|
||||
src = os.path.join(SNAP, os.path.dirname(os.path.relpath(_abs(rel), ROOT)).replace('\\', '/'), snaps[-n])
|
||||
shutil.copy2(src, _abs(rel))
|
||||
print('已回滚:%s ← %s' % (rel, snaps[-n]))
|
||||
return src
|
||||
|
||||
|
||||
def verify(path, target=None):
|
||||
"""校验一份文件:UTF-8 + 语法 + 锚点。返回 None 表示通过。
|
||||
|
||||
⚠️ target 是**最终要落盘的文件名**。校验的是 path(可能是 .tmp),
|
||||
但语法类型和锚点必须按 target 判 —— 否则 .tmp 后缀会让语法检查被跳过,
|
||||
坏内容直接放行(2026-10-06 实测踩到)。
|
||||
"""
|
||||
t = target or path
|
||||
ext = os.path.splitext(t)[1].lower()
|
||||
e = HC.check_utf8(path)
|
||||
if e:
|
||||
return e
|
||||
e, _ = HC.check_syntax(path, ext)
|
||||
if e:
|
||||
return '语法错误:' + e
|
||||
try:
|
||||
rel = os.path.relpath(t, HC.APP)
|
||||
except Exception:
|
||||
rel = ''
|
||||
if rel and not rel.startswith('..'):
|
||||
e = HC.check_anchor(rel.replace('\\', '/'))
|
||||
if e:
|
||||
return e
|
||||
return None
|
||||
|
||||
|
||||
def write(rel, text):
|
||||
"""安全写:快照 → 写 .tmp → 校验 → 原子替换。校验失败则原文件不动。"""
|
||||
p = _abs(rel)
|
||||
snap = snapshot(rel)
|
||||
tmp = p + '.tmp'
|
||||
try:
|
||||
with open(tmp, 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write(text)
|
||||
err = verify(tmp, p) # 按目标文件名判类型,别被 .tmp 后缀骗过去
|
||||
except Exception as ex: # 写都写不进去(含非法字符)也算失败
|
||||
err = '无法写入:%s' % ex
|
||||
if err:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp) # 不留半成品
|
||||
raise SystemExit('写入被拒绝(原文件未改动):%s\n %s' % (rel, err))
|
||||
os.replace(tmp, p) # 原子替换:要么全是新的,要么全是旧的
|
||||
return snap
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 3:
|
||||
print(__doc__)
|
||||
raise SystemExit(2)
|
||||
cmd, rel = sys.argv[1], sys.argv[2]
|
||||
if cmd == 'snap':
|
||||
print('快照:', snapshot(rel) or '(原文件不存在)')
|
||||
elif cmd == 'list':
|
||||
for s in list_snaps(rel):
|
||||
print(' ', s)
|
||||
elif cmd == 'restore':
|
||||
restore(rel, int(sys.argv[3]) if len(sys.argv) > 3 else 1)
|
||||
else:
|
||||
print(__doc__)
|
||||
@@ -1,179 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""解析器 parse_std 的自动化测试(2026-10-07,零依赖:只用标准库 unittest)。
|
||||
|
||||
背景:解析器是全软件的数据源头,此前每次改动的"复核"全靠人工对数——
|
||||
overMaxMsg 那类"页面看着没坏"的事故风险它同样存在。这份测试把复核变成一条命令:
|
||||
|
||||
python tools/test_parse_std.py
|
||||
|
||||
两层断言:
|
||||
① 结构不变量(对**所有**能找到的源文件跑):元组字段数/类型、norm_res 下标
|
||||
不越界、lme_lib/lme_proj 收录、费用科目在库——解析器再怎么改,这些不能破;
|
||||
② golden 精确对数(对横琴/三溪两个固定样本):清单/定额/工料机条数、
|
||||
项目名、单位工程数——改解析器导致数字变化时,测试会红,
|
||||
**红灯 = 你要有意识地更新 golden**(口径变更)而不是无脑改数字。
|
||||
|
||||
样本来源:data/uploads 里已导入的源文件(按 batches.x_src_hash 定位);
|
||||
文件不在时对应用例 skip,不失败。
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DATA = os.path.abspath(os.path.join(APP_DIR, "..", "data"))
|
||||
UPLOADS = os.path.join(DATA, "uploads")
|
||||
HIST = os.path.join(DATA, "history.db")
|
||||
sys.path.insert(0, APP_DIR)
|
||||
sys.path.insert(0, os.path.join(APP_DIR, "core"))
|
||||
|
||||
import import_job # noqa: E402
|
||||
|
||||
|
||||
def seed_out():
|
||||
"""parse_std 需要的计数器/容器(与 api_server / session_job 的真实调用一致)。
|
||||
|
||||
2026-10-07 起「导入不过滤」是唯一口径(full 标志废除),golden 数字即完整集口径。
|
||||
"""
|
||||
return {"uw": [], "bills": [], "norms": [], "lmes": [], "cur_bill": -1,
|
||||
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0,
|
||||
"lme_raw": 0, "lme_skip": 0}
|
||||
|
||||
|
||||
def src_path(src_hash):
|
||||
p = os.path.join(UPLOADS, (src_hash or "")[:2], src_hash or "")
|
||||
return p if os.path.isfile(p) else None
|
||||
|
||||
|
||||
def load_samples():
|
||||
"""从 history.db 找已导入的工程源文件 → [(标签, 路径)],找不到就空列表。"""
|
||||
out = []
|
||||
if not os.path.isfile(HIST):
|
||||
return out
|
||||
con = sqlite3.connect(HIST)
|
||||
try:
|
||||
rows = con.execute("""SELECT Name, x_src_hash FROM batches
|
||||
WHERE kind='project' AND x_src_hash IS NOT NULL
|
||||
ORDER BY id DESC""").fetchall()
|
||||
finally:
|
||||
con.close()
|
||||
seen = set()
|
||||
for name, h in rows:
|
||||
p = src_path(h)
|
||||
if p and h not in seen:
|
||||
seen.add(h)
|
||||
out.append(((name or "")[:20], p))
|
||||
return out
|
||||
|
||||
|
||||
def parse(path):
|
||||
out = seed_out()
|
||||
kind = import_job.parse_std(path, out)
|
||||
return kind, out
|
||||
|
||||
|
||||
class Invariants(unittest.TestCase):
|
||||
"""结构不变量:对每个样本跑,任何一条破 = 解析器坏了。"""
|
||||
|
||||
def _check(self, path):
|
||||
kind, out = parse(path)
|
||||
self.assertEqual(kind, "2025标准")
|
||||
# 元组字段数(列定义/入库 INSERT 按位置对位,多一字段少一字段都是错位事故)
|
||||
for b in out["bills"]:
|
||||
self.assertEqual(len(b), 8, "bills 元组必须 8 字段(第 8 位=源文件备注,2026-10-08 加)")
|
||||
for n in out["norms"]:
|
||||
self.assertEqual(len(n), 7, "norms 元组必须 7 字段")
|
||||
for l in out["lmes"]:
|
||||
self.assertEqual(len(l), 9, "lmes 元组必须 9 字段")
|
||||
# norm_res 的定额下标必须落在 norms 范围内(挂错=孤儿消耗量)
|
||||
for idx, code, q in out.get("norm_res", []):
|
||||
self.assertTrue(0 <= idx < len(out["norms"]), "norm_res 下标越界: %s" % idx)
|
||||
self.assertTrue(code, "norm_res 编码不能为空")
|
||||
self.assertTrue(q is None or isinstance(q, (int, float)),
|
||||
"消耗量必须是数字或空: %r" % (q,))
|
||||
# 台班组成的下一级
|
||||
for pcode, subs in (out.get("lme_res") or {}).items():
|
||||
self.assertTrue(pcode)
|
||||
for code, q in subs:
|
||||
self.assertTrue(code)
|
||||
# 资源库 / 项目级汇总:编码非空、字段齐
|
||||
for code, row in (out.get("lme_lib") or {}).items():
|
||||
self.assertTrue(code)
|
||||
self.assertEqual(len(row), 6)
|
||||
for code, row in (out.get("lme_proj") or {}).items():
|
||||
self.assertTrue(code)
|
||||
self.assertEqual(len(row), 7)
|
||||
# 清单/定额/工料机都有量(空文件在这里红)
|
||||
self.assertGreater(len(out["bills"]), 0)
|
||||
self.assertGreater(len(out["norms"]), 0)
|
||||
self.assertGreater(len(out["lmes"]), 0)
|
||||
self.assertGreater(len(out["uw"]), 0)
|
||||
return out
|
||||
|
||||
def test_all_samples(self):
|
||||
samples = load_samples()
|
||||
if not samples:
|
||||
self.skipTest("data/uploads 里没有可用源文件")
|
||||
for name, p in samples:
|
||||
with self.subTest(sample=name):
|
||||
self._check(p)
|
||||
|
||||
|
||||
class GoldenHengqin(unittest.TestCase):
|
||||
"""横琴 .cos4 的精确对数(口径变了 = 有意识更新这些数字)。"""
|
||||
|
||||
def setUp(self):
|
||||
p = None
|
||||
for name, path in load_samples():
|
||||
if "横琴" in os.path.basename(path):
|
||||
p = path
|
||||
break
|
||||
if not p:
|
||||
self.skipTest("横琴源文件不在 data/uploads")
|
||||
self.kind, self.out = parse(p)
|
||||
|
||||
def test_counts(self):
|
||||
self.assertEqual(len(self.out["bills"]), 1212, "清单条数")
|
||||
self.assertEqual(len(self.out["norms"]), 1208, "定额条数")
|
||||
self.assertEqual(len(self.out["lmes"]), 2073, "工料机条数")
|
||||
self.assertEqual(len(self.out["uw"]), 20, "单位工程数")
|
||||
|
||||
def test_project(self):
|
||||
self.assertEqual(self.out["proj_name"], "横琴高位水池及加压泵房工程")
|
||||
|
||||
def test_lme_lib_and_proj(self):
|
||||
lib = self.out.get("lme_lib") or {}
|
||||
proj = self.out.get("lme_proj") or {}
|
||||
self.assertEqual(len(lib), 659, "资源库编码数")
|
||||
self.assertEqual(len(proj), 659, "项目级汇总编码数")
|
||||
self.assertEqual(lib["00010010"][0], "人工费", "费用科目必须在资源库里")
|
||||
self.assertEqual(proj["00010010"][0], "人工费")
|
||||
# 项目级消耗量 = Project.xml 合计(人工费 5,344,049.5925,2026-10-07 对数)
|
||||
self.assertAlmostEqual(proj["00010010"][4], 5344049.5925, places=3)
|
||||
|
||||
|
||||
class GoldenSanxi(unittest.TestCase):
|
||||
"""三溪 .COS(无 Project.xml 层级差异的另一种包格式)——防"只测一种格式"。"""
|
||||
|
||||
def setUp(self):
|
||||
p = None
|
||||
for name, path in load_samples():
|
||||
if "三溪" in os.path.basename(path):
|
||||
p = path
|
||||
break
|
||||
if not p:
|
||||
self.skipTest("三溪源文件不在 data/uploads")
|
||||
self.kind, self.out = parse(p)
|
||||
|
||||
def test_counts(self):
|
||||
self.assertEqual(len(self.out["bills"]), 489, "清单条数")
|
||||
self.assertEqual(len(self.out["norms"]), 870, "定额条数")
|
||||
self.assertEqual(len(self.out["lmes"]), 1757, "工料机条数")
|
||||
self.assertTrue(self.out.get("lme_lib"), "资源库不应为空")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,319 +0,0 @@
|
||||
/* ============================================================
|
||||
前后台共用的样式(唯一来源)
|
||||
------------------------------------------------------------
|
||||
4 个标签(原数据 / 类似清单 / 组价不一致清单 / 项目工料机)相关的
|
||||
展示样式只允许在这里写一份,两侧页面都引用本文件。
|
||||
目的:两侧不仅「逻辑一致」,连「长相一致」都由同一份 CSS 保证。
|
||||
依赖变量:--c1 主色 / --c2 次色 / --line 分隔线 / --muted 次要文字 / --head 表头底色
|
||||
============================================================ */
|
||||
|
||||
#tabbar .tab, #dtabs .tab{height:24px;min-height:24px;max-height:24px;flex-shrink:0;align-self:flex-end}
|
||||
|
||||
/* ---- 原数据:左侧目录树 + 右侧标签卡 ---- */
|
||||
.rawbox{display:flex;height:100%;min-height:0}
|
||||
.rawtree{width:300px;flex:none;border-right:1px solid var(--line);overflow:auto;padding:6px 4px;background:#fcfdfe}
|
||||
.rawmain{flex:1;display:flex;flex-direction:column;min-width:0}
|
||||
.rawbody{flex:1;overflow:auto;min-height:0;position:relative}
|
||||
/* 2026-10-08 主人定(第 2 次):**前后台所有表头**统一居中(td 内容保持各自对齐不变)。
|
||||
两页各自的 th.l/th.r 覆盖规则已同步删除 —— 居中只允许这一条规则,别处再写会局部改回去。
|
||||
带 data-sumw 的定宽表有内联 width,本规则不覆盖宽度,仍按各自尺寸。 */
|
||||
thead th{text-align:center}
|
||||
/* 规格 16(主人定):全部字段名称居中(全局)——数字列头原本被 .r 右对齐盖住,
|
||||
这里用更高优先级压回居中;**只影响表头**,表体内容对齐(.r 右/.l 左)原样保留 */
|
||||
th,th.r,th.l{text-align:center}
|
||||
.rawmain > table, .rawmain .rawbody > table{width:100%}
|
||||
/* ---- 原数据加载无感(2026-10-07)----
|
||||
切标签不清空旧内容(那一下跳动最扎眼):旧内容压暗 + 右上角小角标,
|
||||
数据到了原位替换;命中内存缓存时原位直出,全程无感。 */
|
||||
.rawbody.rawloading{opacity:.55;pointer-events:none}
|
||||
.rawbody.rawloading::after{content:'读取中…';position:absolute;top:8px;right:16px;
|
||||
font-size:11px;color:var(--c2);background:#fff;border:1px solid var(--line);
|
||||
border-radius:10px;padding:1px 9px;z-index:5}
|
||||
/* 决策 221(2026-10-27 主人定):编辑保存静默档——只锁点击防重绘中途误点,无任何视觉变化 */
|
||||
.rawbody.rawbusy{pointer-events:none}
|
||||
/* ---- 树 / 内容 分隔条(2026-10-07)----
|
||||
6px 命中区(视觉线仍是 .rawtree 的 border-right,margin-left:-1px 盖上去连成一条),
|
||||
正中间挂一个小把手:点它 = 收起/展开整棵树;按住分隔条其余部分拖 = 改树宽。
|
||||
收起后 .rawtree display:none,把手留在原地,随时点回来。 */
|
||||
.rawsplit{width:6px;flex:none;position:relative;cursor:col-resize;margin-left:-1px;background:transparent}
|
||||
.rawsplit:hover{background:#dbe7f6}
|
||||
.rawsplit .splitbtn{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);
|
||||
width:15px;height:44px;line-height:42px;text-align:center;font-size:9px;color:var(--c2);
|
||||
background:#eef3fa;border:1px solid var(--line);border-radius:4px;cursor:pointer;user-select:none;z-index:2}
|
||||
.rawsplit .splitbtn:hover{background:#dbe8f7;border-color:var(--c2)}
|
||||
.rawbox.treeclosed .rawtree{display:none}
|
||||
/* 收起后树没了,分隔条成了 rawbox 第一个子节点:加宽命中区、去掉负边距,
|
||||
把手才能完整露出来(弹框 .db.fx 是 overflow:hidden,贴边会被裁) */
|
||||
.rawbox.treeclosed .rawsplit{width:14px;margin-left:0}
|
||||
/* 决策 221(2026-10-27 主人定):左树容器框收起/展开六处一套——组树容器(.grpbox)与
|
||||
独立树(后台明细 #simtree / 附件页 #qsimtree,无外层容器框)同款收起态与把手加宽 */
|
||||
.grptree{width:230px;flex:none;border-right:1px solid var(--line);overflow:auto;padding:6px 4px;background:#fcfdfe}
|
||||
.grpbox.treeclosed .grptree{display:none}
|
||||
.grpbox.treeclosed .rawsplit{width:14px;margin-left:0}
|
||||
.grptree.treeclosed{display:none}
|
||||
.rawsplit.treeclosed{width:14px;margin-left:0}
|
||||
body.grptree-dragging{cursor:col-resize !important;user-select:none}
|
||||
body.rawcol-dragging{cursor:col-resize !important;user-select:none}
|
||||
body.rawcol-dragging .rawtree{pointer-events:none} /* 拖过树表面时不选中文字、不闪烁 */
|
||||
.rn{display:flex;align-items:center;gap:5px;padding:3px 6px;border-radius:4px;cursor:pointer;white-space:nowrap;font-size:12.5px}
|
||||
.rn:hover{background:#eef3fa}
|
||||
/* 全软件**只有一套选中态**:浅底 + 左侧 3px 主色竖条 + 深蓝字(2026-10-01 统一)。
|
||||
此前左树用「实心蓝底白字」、表格用「浅底+蓝框」、级别按钮用「蓝底白字」——三套并存,
|
||||
尤其按钮那套语义和标签卡相反(看着像被禁用),必须统一。 */
|
||||
.rn.on{background:#e8f0fb;color:var(--c1);font-weight:600;box-shadow:inset 3px 0 0 var(--c1)}
|
||||
.rn .arw{width:12px;flex:none;text-align:center;color:var(--muted);font-size:11px}
|
||||
.rn.on .arw{color:var(--c1)}
|
||||
.rn .nm{overflow:hidden;text-overflow:ellipsis}
|
||||
.rn.lv0{font-weight:700;color:var(--c1);margin-bottom:3px}
|
||||
.rn.lv0.on{background:#e8f0fb;color:var(--c1);box-shadow:inset 3px 0 0 var(--c1)}
|
||||
.rn.lv1{font-weight:600;color:#2a4a70}
|
||||
.rn.lv2{color:#456}
|
||||
.rkids{margin-left:15px;border-left:1px dashed var(--line);padding-left:3px}
|
||||
.hint{font-size:11.5px;color:var(--muted);padding:4px 10px;background:#fafcff;border-bottom:1px solid var(--line)}
|
||||
.stabs{display:flex;gap:2px;padding:4px 8px 0;background:#fafcff;border-bottom:1px solid var(--line);flex-wrap:wrap;flex:none}
|
||||
.stab{padding:4px 13px;border:1px solid var(--line);border-bottom:none;background:#eef3fa;border-radius:5px 5px 0 0;font-size:12px;cursor:pointer;color:var(--muted)}
|
||||
.stab.on{background:var(--c2);border-color:var(--c2);color:#fff;font-weight:600} /* 规格 2026-10-17 工具栏5:工作态蓝底(原白底凸出款废止) */
|
||||
/* 分部分项 / 措施项目:标签卡右边的「分部 / 清单 / 定额」——控制展开到哪一级 */
|
||||
.lvgrp{margin-left:auto;display:flex;align-items:center;gap:2px;padding:0 2px 4px}
|
||||
.lvbtn{padding:3px 10px;border:1px solid var(--line);border-radius:4px;background:#fff;
|
||||
font-size:12px;color:var(--muted);cursor:pointer;user-select:none}
|
||||
.lvbtn:hover{background:#eef3fb}
|
||||
/* 「默认列宽」是动作按钮,不是状态按钮 → 不做选中态,用中性色跟分部/清单/定额区分开;
|
||||
再给 8px 右间距,把「动作」和「状态」两组在视觉上劈开(只差一个色阶容易被看成同一组) */
|
||||
.lvbtn.rst{color:#5a6b7e;background:#f6f8fb;margin-right:8px}
|
||||
/* 规格 2026-10-17 工具栏5:工作态=蓝底白字 */
|
||||
.lvbtn.on{background:var(--c2);border-color:var(--c2);color:#fff;font-weight:600}
|
||||
.lvbtn.on:hover{background:var(--c2);color:#fff}
|
||||
/* 与 .stab.on 同一语义:选中 = 白底凸出 + 主色粗字(不能做成蓝底白字,那看着像禁用) */
|
||||
.lvbtn.on{background:#fff;border-color:var(--c1);color:var(--c1);font-weight:700}
|
||||
.kvtb td:first-child{background:#f7f9fc;color:var(--c1);font-weight:600;width:220px}
|
||||
|
||||
/* 拖宽某列后表格右侧会露出留白(表宽=列宽和,多出的空间不摊给别的列),
|
||||
没有收口线看着像"表格断了" → 给这类表(data-sumw)的右缘补一条线。 */
|
||||
#rawbody table, #drawbody table, table[data-sumw]{border-right:1px solid var(--line)}
|
||||
|
||||
/* ---- 2026-10-07 全项目「拖列只动被拖列」----
|
||||
带列定义的表一律 data-sumw(表宽=列宽之和,见 common.js 的 sumw()):
|
||||
拖某列只动该列,其余列不再被 100% 均摊挤动。 */
|
||||
table[data-sumw]{width:max-content}
|
||||
|
||||
/* ---- 单位列(td.u):表宽锁死后,长单位(如「100m3天然密实方」)不再挤动邻列
|
||||
而是本列内换行 —— 白空间放开 + 逐字符断行,绝不外溢到旁边格子。 */
|
||||
td.u{white-space:normal;word-break:break-all}
|
||||
|
||||
/* ---- 列宽拖动:表头右侧 7px 手柄(4 个标签通用,见 common.js 的委托实现)----
|
||||
.rs 是绝对定位,需要 th 自己是定位元素;两页的表头都必须是 sticky(滚动时列宽手柄跟着走)。 */
|
||||
/* 下边框 2px:1px 太轻,滚动时表头压不住数据行 */
|
||||
thead th{position:sticky;top:0;border-bottom:2px solid #c4d2e3}
|
||||
.rs{position:absolute;top:0;bottom:0;right:0;width:7px;cursor:col-resize;user-select:none}
|
||||
.rs:hover{background:#9fb3cb}
|
||||
|
||||
/* ---- 原数据 ± 目录树:分部行 + 折叠图标 ---- */
|
||||
/* ---- 分部/清单/定额的行底色:从上往下**明度单调递增**(深 → 浅) ----
|
||||
2026-10-06 重做。此前有个层级错误:一级分部 #dce7f6 比单位工程根行 #e8eef7 还深,
|
||||
读起来像"分部比单位工程还大";而清单(真正的主内容)**完全没有底色**,被上面的色块压住。
|
||||
现在:容器行(根/分部)越靠上越深,清单白底 + 首列主色竖条,定额最淡。 */
|
||||
tr.uwrow td{background:#dbe4f2} /* 单位工程(固定根)最重 */
|
||||
tr.divrow td{background:#eff4fa;font-weight:600;color:#1c3f6e}
|
||||
tr.divrow.d0 td{background:#e6edf8} /* 一级分部 */
|
||||
tr.divrow.d1 td{background:#eff4fa} /* 二级分部 */
|
||||
tr.divrow.d2 td{background:#f6f9fc} /* 三级分部最轻 */
|
||||
/* 把手独立成第一列,列内按层级错开(见 common.js 的 TX)。
|
||||
与「类似清单」的把手列(td.tg)同款;2026-10-01 去掉了竖虚线(主人不要)。 */
|
||||
td.tgc{padding-left:4px;padding-right:4px;white-space:nowrap}
|
||||
/* 把手列里把手右侧没有文字,去掉 5px 的 margin-right */
|
||||
td.tgc .tgi{margin-right:0}
|
||||
/* 18×18:14×14 的点击热区太小,鼠标容易点空 */
|
||||
.tgi{display:inline-block;width:18px;height:18px;line-height:16px;text-align:center;
|
||||
border:1px solid #9fb3cb;border-radius:3px;background:#fff;color:var(--c2);
|
||||
font-weight:700;font-size:12px;cursor:pointer;margin-right:5px;user-select:none}
|
||||
.tgi:hover{background:#e7eefb}
|
||||
|
||||
/* ---- 分组标题行 / 分隔行 / 类别徽章 / 展开把手 ---- */
|
||||
.grp td{background:#f4f7fb;font-weight:700;color:#34506f}
|
||||
.grp2 td{background:#fbf6ef;font-weight:700;color:#6f5334}
|
||||
.grp td,.grp2 td{cursor:pointer;user-select:none}
|
||||
/* 原数据·汇总分析的单项工程分组行(2026-10-08,与左侧目录树同构):只读,不给手型 */
|
||||
tr.gsec td{background:#f4f7fb;font-weight:700;color:#34506f;cursor:default;user-select:none}
|
||||
td.gtitle{text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.sep td{background:#eef0f2;color:#456;font-style:italic;font-size:12px;padding:3px 8px}
|
||||
.tg{border-radius:3px;padding:1px 6px;font-size:11px;font-weight:700}
|
||||
.tg-e{background:#e8f5ec;color:#1e8e3e}.tg-s{background:#fff4e5;color:#a86300}.tg-f{background:#e7f0fb;color:#1e4e8c}
|
||||
td.tg{text-align:center;padding-left:4px;padding-right:4px}
|
||||
/* 组/清单两级把手层级(2026-10-11 主人定):组把手贴左,清单把手再缩进一层 */
|
||||
tr[data-grp]>td.tg{text-align:left;padding-left:5px}
|
||||
tr[data-bid]>td.tg{text-align:left;padding-left:21px}
|
||||
.tog{display:inline-block;width:17px;height:17px;line-height:15px;text-align:center;border:1px solid #8ba3c2;
|
||||
border-radius:3px;background:#fff;color:#1f5fae;cursor:pointer;font-weight:700;font-size:12px;user-select:none}
|
||||
.tog:hover{background:#e7eefb}
|
||||
.tog.g{border-color:#123a6b;background:#123a6b;color:#fff}
|
||||
/* 清单是**主内容**:不整行染色(整页蓝会糊成一片),改用首列 3px 主色竖条标记。
|
||||
这一竖条与左侧树/表格的选中态(inset 3px var(--c1))是同一套手法,只是清单用更亮的 --c2。 */
|
||||
tr.brow > td:first-child{box-shadow:inset 3px 0 0 var(--c2)}
|
||||
tr.sub td{background:#f8fafc;color:#44546a;font-size:12px}
|
||||
/* 类别徽章:按层级排"实心 → 描边"(2026-10-06 重做,清单为主色)。
|
||||
① 以前 4 个全是同一套淡蓝底,层级分不出,挤在 56px 列里整列发亮;
|
||||
② 更严重的是第 117 行曾有一段重复定义 `.kind.uw{background:#123a6b}` ——
|
||||
它覆盖了下面第 94 行的浅底,却没重设 color,结果根目录变成**深蓝底 + 深蓝字**
|
||||
(字完全看不见),这就是主人说的"根目录被颜色覆盖"。重复定义已删。
|
||||
③ 「定额」早年用绿色,跟造价行业「跌=绿」撞语义 —— 彩色只留给涨/跌/价差。 */
|
||||
.kind{display:inline-block;padding:0 7px;border-radius:3px;font-size:11.5px;font-weight:600;
|
||||
white-space:nowrap;background:var(--c2);color:#fff;border:1px solid var(--c2)}
|
||||
.kind.d{background:#f4f6f9;color:#6b7a8c;border-color:#e3e8ef;font-weight:500} /* 定额:附属行 */
|
||||
.kind.dv{background:#e2ebf7;color:#274a72;border-color:#c6d6ea} /* 分部:分组容器 */
|
||||
.kind.uw{background:#123a6b;color:#fff;border-color:#123a6b;font-weight:700} /* 单位工程:根 */
|
||||
.ind{display:inline-block;color:#aab}
|
||||
.empty{padding:24px;text-align:center;color:var(--muted)}
|
||||
|
||||
/* ---- 项目特征:pre-wrap 只对「已存在的 \n」生效,编号拆行由 fmtAttr() 负责 ---- */
|
||||
.attr{white-space:pre-wrap;word-break:break-word;overflow-wrap:anywhere;vertical-align:top;line-height:1.45}
|
||||
td.attr.nv{color:#9aa8b8;font-style:italic}
|
||||
/* 决策 204(2026-10-26 主人定):备注格自动换行——与项目特征格同款换行规则,
|
||||
多行备注撑开行高,不再单行截断;换行来源:textarea 编辑框 Enter=换行 */
|
||||
.rmk{white-space:pre-wrap;word-break:break-word;overflow-wrap:anywhere;vertical-align:top;line-height:1.45}
|
||||
|
||||
/* 价差 ≥20% 的组标红(两侧同一口径,由 renderGroups 统一判定后加 class) */
|
||||
.grp.bad td,.grp2.bad td{background:#fbe0dc}
|
||||
|
||||
/* 左目录树点组 → 定位到组头行:闪一圈轮廓(1.5s 后由 JS 摘掉,common.js 的 grpLocateRow) */
|
||||
tr.loc>td{outline:2px solid var(--c2);outline-offset:-2px}
|
||||
|
||||
/* ---- P0:项目特征拆成多行时,同行的其它列也要顶部对齐 ----
|
||||
此前只有 .attr 设了 top,名称/单价/合价默认垂直居中 → 特征一多(10 行以上)
|
||||
数字就「浮」在行的中间,看起来整行错位。清单行与定额行统一 top。 */
|
||||
tr.brow > td, tr.sub > td { vertical-align: top; }
|
||||
tr.brow > td.c, tr.sub > td.c { vertical-align: top; }
|
||||
|
||||
/* ---- 单位工程根行 / 定额把手 / 工料机面板 ----
|
||||
⚠️ 底色已统一提到上面「分部/清单/定额的行底色」一段写(那里才有完整层级梯度),
|
||||
这里只留文字样式 —— 底色在两处各写一份,改的时候必然漏一处。 */
|
||||
tr.uwrow td{font-weight:700;color:#123a6b}
|
||||
.spec{display:inline-block;padding:0 6px;border-radius:3px;background:#eef3fa;color:#5a6b7f;
|
||||
font-size:11px;font-style:normal;font-weight:400}
|
||||
.rn .nm .spec{padding:0 4px;font-size:10px}
|
||||
/* ⚠️ 这里原本有一段 `.kind.uw{background:#123a6b}`(重复定义,且没重设 color)
|
||||
→ 根目录徽章变成深蓝底 + 深蓝字,字彻底看不见(主人反馈"根目录被颜色覆盖")。已删除。 */
|
||||
/* 定额子行(组表 / 原数据共用):手型与选中高亮样式保留;行上动作现走序号格的「耗」按钮 */
|
||||
tr.sub{cursor:pointer}
|
||||
tr.sub.on td{background:#e8f0fb;outline:1px solid var(--c2);outline-offset:-1px}
|
||||
/* 工料机浮层里,台班 / 配合比展开的**组成明细**(下一级):淡底小字,别跟主行抢视觉 */
|
||||
tr.resk td{background:#f7f9fc;color:#5a6b7e;font-size:12px}
|
||||
|
||||
/* 数字列必须等宽数字:金额/工程量小数点对齐后才扫得动(审计表格最容易翻车的地方)。
|
||||
.r 只做了右对齐还不够——比例数字下「1」比「8」窄,位数不同就串行。 */
|
||||
td.r, td.num, .r, .num{font-variant-numeric:tabular-nums}
|
||||
/* 表格选中态(2026-10-11 主人定:淡蓝底、无边框、无竖条——全页面含弹框统一;
|
||||
规格 2026-10-16 组价不一致③改版:整行淡蓝 + 鼠标点选格 #a8e3d2 + 整行绿色外框,
|
||||
定额子行点选 .subsel 同配色,整套软件一套) */
|
||||
tr.sel td, tr.subsel td{background:#d8e9fc}
|
||||
tr.sel td.cellhit, tr.subsel td.cellhit{background:#a8e3d2 !important}
|
||||
tr.sel, tr.subsel{outline:1px solid #35a06b; outline-offset:-1px}
|
||||
|
||||
/* ---- 定额「耗」按钮 + 工料机浮层(2026-10-15 公共功能4,取代旧「子目工料机」底板)----
|
||||
圆按钮嵌在定额子行序号格里;浮层挂 body + fixed 定位(z-600 高于明细弹框遮罩),
|
||||
不受表格滚动容器裁剪;表头 sticky,内容超 60vh 在浮层内滚。 */
|
||||
.haobtn{display:inline-block;width:17px;height:17px;line-height:15px;text-align:center;
|
||||
border:1px solid var(--c2);border-radius:50%;background:#fff;color:var(--c2);
|
||||
font-size:11px;font-weight:700;cursor:pointer;user-select:none}
|
||||
.haobtn:hover{background:var(--c2);color:#fff}
|
||||
.haopop{position:fixed;z-index:600;background:#fff;border:1px solid var(--line);border-radius:6px;
|
||||
box-shadow:0 6px 18px rgba(15,40,80,.18);overflow:auto;max-height:60vh;max-width:1100px}
|
||||
/* 规格 公共功能4:浮层字段支持左右拉伸(colgroup px + th.rs,拖动只动被拖列、浮层总宽跟着变)。
|
||||
.rs 需要定位父级——.haopop th 已是 sticky(定位元素),无需再加 relative。
|
||||
📌 钉住条:默认鼠标离开即灭(规格原文),钉住后离开不关、点空白关闭 */
|
||||
.haobar{display:flex;align-items:center;justify-content:space-between;padding:2px 8px 4px;
|
||||
border-bottom:1px solid var(--line);position:sticky;top:0;background:#eef3fa;z-index:1}
|
||||
.haobar .ht{font-size:11px;color:var(--c1);font-weight:700}
|
||||
.haobar .pin{cursor:pointer;font-size:12px;line-height:1;opacity:.5;user-select:none;border-radius:4px;padding:0 3px}
|
||||
.haobar .pin:hover{opacity:1;background:#dde8f6}
|
||||
.haobar .pin.on{opacity:1;background:#dde8f6;box-shadow:0 0 0 1px var(--c2) inset}
|
||||
.haopop table{border-collapse:collapse;font-size:12px}
|
||||
.haopop th{position:sticky;top:0;background:#eef3fa;color:var(--c1);padding:3px 8px;
|
||||
border-bottom:1px solid var(--line);white-space:nowrap;text-align:center}
|
||||
.haopop td{padding:2px 8px;border-bottom:1px solid #f1f5f9;vertical-align:top}
|
||||
.haopop tbody tr:hover td{background:#f4f8fc}
|
||||
.haopop td.c{text-align:center}
|
||||
.haopop td.r{text-align:right;font-variant-numeric:tabular-nums}
|
||||
/* 浮层序号格里的 ± 把手:台班 / 配合比展开下一级组成 */
|
||||
.haosub{display:inline-block;width:14px;height:14px;line-height:12px;text-align:center;margin-right:4px;
|
||||
border:1px solid #9fb3cb;border-radius:3px;background:#fff;color:var(--c2);
|
||||
font-weight:700;font-size:11px;cursor:pointer;user-select:none}
|
||||
.haosub:hover{background:#e7eefb}
|
||||
|
||||
/* ---- 提示条(2026-10-06,替代 alert:页面内、不打断操作、3 秒淡出)----
|
||||
两处形态共用一套配色:内联 #dlmsg 写在查询栏里;没有它时右下角浮 .toast。
|
||||
颜色只用三档语义色,不新增主题变量:成功 #1a7f37 / 提醒 #a15c00 / 失败 #c0392b。 */
|
||||
.dlmsg{margin-left:8px;font-size:12px;color:#1a7f37;opacity:0;
|
||||
transition:opacity .35s ease;white-space:nowrap;max-width:520px;overflow:hidden;text-overflow:ellipsis}
|
||||
.dlmsg.warn{color:#a15c00}
|
||||
.dlmsg.err{color:#c0392b}
|
||||
#toastBox{position:fixed;right:18px;bottom:18px;z-index:9999;display:flex;
|
||||
flex-direction:column;gap:8px;align-items:flex-end;pointer-events:none}
|
||||
.toast{max-width:460px;padding:9px 13px;border-radius:6px;background:#fff;border:1px solid #bfe0c9;
|
||||
box-shadow:0 2px 10px rgba(0,0,0,.08);font-size:12.5px;line-height:1.5;color:#1a7f37;
|
||||
opacity:0;transform:translateY(6px);transition:opacity .25s ease,transform .25s ease}
|
||||
.toast.on{opacity:1;transform:none}
|
||||
.toast.warn{border-color:#e8d3a8;color:#a15c00}
|
||||
.toast.err{border-color:#e8bfb8;color:#c0392b}
|
||||
|
||||
/* ---- 可搜索下拉(combobox,2026-10-07,配套 common.js 的 comboAttach)----
|
||||
输入框沿用所在查询栏的 input 皮肤;面板绝对定位于输入框下方。 */
|
||||
.combo{position:relative;display:inline-flex;align-items:center}
|
||||
.combo input{flex:1;min-width:0;padding-right:24px;cursor:text}
|
||||
.combo-x{position:absolute;right:7px;cursor:pointer;color:#8899aa;font-size:14px;line-height:1;user-select:none}
|
||||
.combo-x:hover{color:var(--c2)}
|
||||
.combo-panel{position:fixed;z-index:500;background:#fff; /* 高于弹框遮罩 z-99/120(2026-10-08 修:面板曾被压在弹框下) */
|
||||
border:1px solid #b8c4d4;border-radius:6px;max-height:242px;overflow:auto;display:none;
|
||||
box-shadow:0 4px 12px rgba(0,0,0,.14)}
|
||||
.combo-it{padding:6px 10px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:13px}
|
||||
.combo-it:hover,.combo-it.on{background:#e8f0fb}
|
||||
.combo-it.all{color:var(--muted)}
|
||||
.combo-none{padding:6px 10px;color:var(--muted);font-size:12.5px}
|
||||
|
||||
/* ---- 单元格截断(2026-10-06,前后台共用;配套 common.js 的 ell())----
|
||||
fixed 布局下没空格的长串不换行、只会溢出格子;cursor:help 提示"能悬停看全名"。 */
|
||||
.ell{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
|
||||
max-width:100%;cursor:help}
|
||||
/* 项目特征列需要 pre-wrap 多行显示,不能被 .ell 的 nowrap 压平(否则 fmtAttr 按编号拆的行白拆)。
|
||||
仅覆盖 .attr 单元格内的 ell,恢复换行、关闭省略号。 */
|
||||
.attr .ell{white-space:pre-wrap;text-overflow:clip;cursor:auto}
|
||||
|
||||
|
||||
/* 组表右键菜单(2026-10-13 主人定:暂时只做弹框,无功能) */
|
||||
.grpctx{position:fixed;z-index:9999;background:#fff;border:1px solid #c9d4e2;border-radius:6px;
|
||||
box-shadow:0 4px 14px rgba(18,58,107,.15);padding:4px 0;min-width:150px}
|
||||
.grpctx .gi{padding:7px 14px;font-size:12.5px;cursor:pointer;white-space:nowrap;color:#1c2733}
|
||||
.grpctx .gi:hover{background:#eef3fa;color:#123a6b}
|
||||
|
||||
/* ================= 共享层批次A(决策 67,2026-10-14 主人定「开工」)=================
|
||||
清单编辑状态视觉:x_new=本软件新增(淡绿底);x_tdel=临时删除(浅灰底+整行横线)。
|
||||
取消临删=移除类名即恢复原底色(规格:恢复成临删前的状态及底色)。
|
||||
原数据树表(.brow)与组表明细行(billTR)同款一套类名,四视图一致。 */
|
||||
tr.xnew > td { background: #e9f7ee !important; }
|
||||
tr.xtdel > td { background: #eef1f4 !important; color: #8a97a8; }
|
||||
tr.xtdel > td:not(.tgc), tr.xtdel > td:not(.tgc) span { text-decoration: line-through; }
|
||||
/* 单元格编辑的通用设计(2026-10-22 主人定,全软件统一):行内编辑框**动态填满所在单元格**、
|
||||
四边与单元格边线重合——td.editing(JS 锁行高)内 .cellin 绝对定位铺满 padding 盒,
|
||||
列宽怎么变编辑框就怎么宽(input/textarea 同规则)。 */
|
||||
td.editing{position:relative}
|
||||
/* 决策 204(2026-10-26 主人定):编辑框内文字与原格子**同位**——内边距 7px = 格子 8px − 框 1px;
|
||||
对齐方式跟格子走(右对齐数量格/居中单位格进编辑不漂移) */
|
||||
td.editing .cellin, td.editing textarea.cellin { position: absolute; inset: 0; width: 100%; height: 100%;
|
||||
box-sizing: border-box; border: 1px solid #7aa7d9; border-radius: 0; font: inherit; padding: 0 7px; outline: none; margin: 0; }
|
||||
td.r.editing .cellin{text-align:right}
|
||||
td.c.editing .cellin{text-align:center}
|
||||
/* 决策 189 通用要求(2026-10-24 主人定):任何单元格编辑框——含耗浮层/弹框内——
|
||||
一律动态填满所在单元格、四边与单元格边线重合(±2px 内):同一铺满规则覆盖所有容器。
|
||||
宿主 td 由 JS 加 td.editing(cellEditFill 锁行高);非 td 宿主由 resk/hao 编辑函数处理。 */
|
||||
.haopop td.editing .cellin, .haopop td.editing textarea.cellin,
|
||||
.kvtb td.editing .cellin { position: absolute; inset: 0; width: 100%; height: 100%;
|
||||
box-sizing: border-box; border: 1px solid #7aa7d9; border-radius: 0; font: inherit; padding: 0 7px; outline: none; margin: 0; }
|
||||
|
||||
/* ==================== 本页搜索(决策 172/209;2026-10-27 决策 229 上移共享)====================
|
||||
前后台共用一套:工作台四页 + 后台(入库项目列表/明细页/附件页双页签)。样式随代码上移。 */
|
||||
mark.pghl{background:#ffe58a;color:inherit;padding:0}
|
||||
mark.pghlcur{background:#ff9c40;color:#fff;padding:0} /* 决策 209:当前命中橙底 */
|
||||
.pgsrch{width:200px;height:24px;box-sizing:border-box}
|
||||
.pgsnav{height:24px;padding:0 8px;font:inherit;font-size:12px;border:1px solid #b8c4d4;border-radius:5px;background:#fff;color:#24425f;cursor:pointer;box-sizing:border-box} /* 决策 209:跳转按钮 */
|
||||
.pgsnav:disabled{background:#f0f2f5;color:#a8b4c4;border-color:#d5dde8;cursor:default}
|
||||
.tfhide{display:none} /* 决策 237 补记二:组树点选就地过滤(grpTreeBind),与附件页 .qfhide 绑定筛选正交叠加 */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,160 +0,0 @@
|
||||
/* ============================================================
|
||||
期次区间选择器(工作台 / 后台共用)
|
||||
—— 一个输入框,点一下弹出「一个」面板,面板里一次选完「起」「止」两个月,不再弹两次。
|
||||
|
||||
布局(2026-09-29 你定的两排式):
|
||||
第 1 排 起始 [年下拉][月下拉]
|
||||
第 2 排 结束 [年下拉][月下拉]
|
||||
第 3 排 清空 止=起
|
||||
第 4 排 确定(主操作,占整行)
|
||||
|
||||
用法:
|
||||
mkPeriod(el, onChange) 把 el 变成期次区间输入框
|
||||
PVAL(el) 取值 {f,t,fs,ts} 月序号 + "2026-01" 字符串
|
||||
setPeriod(el, from, to) 赋值("2026-01" / "2026-12"),传空串清空
|
||||
============================================================ */
|
||||
(function () {
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
const m2s = m => (m == null || m === '' ? '' : Math.floor(m / 12) + '-' + pad(m % 12 || 12));
|
||||
const s2m = s => { const m = /^(\d{4})-(\d{1,2})$/.exec((s || '').trim()); return m ? (+m[1]) * 12 + (+m[2]) : null; };
|
||||
|
||||
let box = null, curEl = null, st = { fy: 0, fm: 0, ty: 0, tm: 0 };
|
||||
const Y0 = 2015, Y1 = 2035;
|
||||
|
||||
function ensureBox() {
|
||||
if (box) return box;
|
||||
box = document.createElement('div');
|
||||
box.className = 'pcal';
|
||||
box.innerHTML =
|
||||
'<div class="pcal-hd">期次区间</div>' +
|
||||
'<div class="pcal-row"><b>起始</b><select class="py" data-k="f"></select><select class="pmo" data-k="f"></select></div>' +
|
||||
'<div class="pcal-row"><b>结束</b><select class="py" data-k="t"></select><select class="pmo" data-k="t"></select></div>' +
|
||||
'<div class="pcal-prev"></div>' +
|
||||
'<div class="pcal-ft">' +
|
||||
'<div class="pcal-ft1"><button type="button" class="pq" data-a="clear">清空</button>' +
|
||||
'<button type="button" class="pq" data-a="same">止=起</button></div>' +
|
||||
'<div class="pcal-ft2"><button type="button" class="pq pri" data-a="ok">确定</button></div>' +
|
||||
'</div>';
|
||||
document.body.appendChild(box);
|
||||
|
||||
// 年 / 月 下拉(起始、结束各一组)
|
||||
box.querySelectorAll('select.py').forEach(sel => {
|
||||
for (let y = Y0; y <= Y1; y++) {
|
||||
const o = document.createElement('option');
|
||||
o.value = y; o.textContent = y + ' 年';
|
||||
sel.appendChild(o);
|
||||
}
|
||||
sel.onchange = () => {
|
||||
const k = sel.dataset.k;
|
||||
if (k === 'f') st.fy = +sel.value; else st.ty = +sel.value;
|
||||
fixOrder(); paint();
|
||||
};
|
||||
});
|
||||
box.querySelectorAll('select.pmo').forEach(sel => {
|
||||
for (let m = 1; m <= 12; m++) {
|
||||
const o = document.createElement('option');
|
||||
o.value = m; o.textContent = m + ' 月';
|
||||
sel.appendChild(o);
|
||||
}
|
||||
sel.onchange = () => {
|
||||
const k = sel.dataset.k;
|
||||
if (k === 'f') st.fm = +sel.value; else st.tm = +sel.value;
|
||||
fixOrder(); paint();
|
||||
};
|
||||
});
|
||||
box.querySelector('[data-a="clear"]').onclick = () => { setPeriod(curEl, '', ''); close(); };
|
||||
box.querySelector('[data-a="same"]').onclick = () => { st.ty = st.fy; st.tm = st.fm; paint(); };
|
||||
box.querySelector('[data-a="ok"]').onclick = () => { apply(); close(); };
|
||||
document.addEventListener('mousedown', e => {
|
||||
if (!box.contains(e.target) && e.target !== curEl) close();
|
||||
});
|
||||
return box;
|
||||
}
|
||||
|
||||
// 止早于起 → 自动把止拉到起(跟以前一样,不改规则)
|
||||
function fixOrder() {
|
||||
if (st.ty * 12 + st.tm < st.fy * 12 + st.fm) { st.ty = st.fy; st.tm = st.fm; }
|
||||
}
|
||||
|
||||
function paint() {
|
||||
const F = st.fy * 12 + st.fm, T = st.ty * 12 + st.tm;
|
||||
box.querySelector('select.py[data-k="f"]').value = st.fy;
|
||||
box.querySelector('select.pmo[data-k="f"]').value = st.fm;
|
||||
box.querySelector('select.py[data-k="t"]').value = st.ty;
|
||||
box.querySelector('select.pmo[data-k="t"]').value = st.tm;
|
||||
box.querySelector('.pcal-prev').textContent = m2s(F) + ' ~ ' + m2s(T);
|
||||
}
|
||||
|
||||
function apply() {
|
||||
if (!curEl) return;
|
||||
setPeriod(curEl, st.fy + '-' + pad(st.fm), st.ty + '-' + pad(st.tm));
|
||||
}
|
||||
|
||||
function open(el) {
|
||||
curEl = el;
|
||||
ensureBox();
|
||||
const v = PVAL(el), now = new Date();
|
||||
const fy = v.fs ? +v.fs.slice(0, 4) : now.getFullYear();
|
||||
const fm = v.fs ? +v.fs.slice(5, 7) : now.getMonth() + 1;
|
||||
const ty = v.ts ? +v.ts.slice(0, 4) : fy;
|
||||
const tm = v.ts ? +v.ts.slice(5, 7) : fm;
|
||||
st = { fy, fm, ty, tm };
|
||||
fixOrder(); paint();
|
||||
const r = el.getBoundingClientRect();
|
||||
box.style.display = 'block';
|
||||
const W = 252, H = 210;
|
||||
let left = r.left, top = r.bottom + 4;
|
||||
if (left + W > window.innerWidth) left = Math.max(8, window.innerWidth - W - 10);
|
||||
if (top + H > window.innerHeight) top = Math.max(8, r.top - H - 4);
|
||||
box.style.left = left + 'px';
|
||||
box.style.top = top + 'px';
|
||||
}
|
||||
|
||||
function close() { if (box) box.style.display = 'none'; }
|
||||
|
||||
window.mkPeriod = function (el, onChange) {
|
||||
if (!el) return;
|
||||
el.classList.add('perinp');
|
||||
el.readOnly = true;
|
||||
el.onclick = () => open(el);
|
||||
if (onChange) el._onChange = onChange;
|
||||
};
|
||||
|
||||
window.setPeriod = function (el, from, to) {
|
||||
if (!el) return;
|
||||
el.dataset.pf = from || '';
|
||||
el.dataset.pt = to || '';
|
||||
el.value = (from && to) ? (from === to ? from : from + ' ~ ' + to) : (from || '');
|
||||
if (el._onChange) el._onChange();
|
||||
};
|
||||
|
||||
window.PVAL = function (el) {
|
||||
const fs = (el && el.dataset.pf) || '', ts = (el && el.dataset.pt) || '';
|
||||
return { fs, ts, f: s2m(fs), t: s2m(ts) };
|
||||
};
|
||||
|
||||
// 样式(两个页面共用,不写进各自的 <style>)
|
||||
const css = document.createElement('style');
|
||||
css.textContent = `
|
||||
.perinp{cursor:pointer;background:#fff url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='7'><path d='M0 0l5 6 5-6z' fill='%23788'/></svg>") no-repeat right 7px center}
|
||||
.pcal{display:none;position:fixed;z-index:9999;width:252px;background:#fff;border:1px solid #c9d4e3;
|
||||
border-radius:9px;box-shadow:0 8px 26px rgba(20,40,80,.20);padding:9px 10px;font-size:12.5px}
|
||||
.pcal-hd{font-weight:600;color:#1f3a5f;padding:0 2px 7px;border-bottom:1px solid #e6ecf4;margin-bottom:7px}
|
||||
.pcal-row{display:flex;align-items:center;gap:6px;margin-bottom:6px}
|
||||
.pcal-row b{width:30px;color:#456;font-weight:500}
|
||||
.pcal-row select{padding:3px 4px;border:1px solid #b8c4d4;border-radius:5px;font:inherit;font-size:12.5px}
|
||||
.pcal-row select.py{flex:1.1}
|
||||
.pcal-row select.pmo{flex:1}
|
||||
.pcal-prev{margin:2px 0 7px;padding:4px 6px;background:#f4f8fd;border:1px solid #e3ebf5;border-radius:5px;
|
||||
text-align:center;color:#1f5fae;font-weight:600;font-variant-numeric:tabular-nums}
|
||||
.pcal-ft{display:flex;flex-direction:column;gap:6px;margin-top:2px;padding-top:7px;border-top:1px solid #e6ecf4}
|
||||
.pcal-ft1{display:flex;gap:6px}
|
||||
.pcal-ft1 .pq{flex:1}
|
||||
.pcal-ft2{display:flex}
|
||||
.pcal-ft2 .pq{flex:1}
|
||||
.pq{padding:4px 10px;border:1px solid #b8c4d4;border-radius:6px;background:#fff;cursor:pointer;font:inherit;font-size:12.5px;color:#334}
|
||||
.pq:hover{background:#f0f5fb}
|
||||
.pq.pri{background:#2f6fd0;border-color:#2f6fd0;color:#fff;font-weight:600}
|
||||
.pq.pri:hover{background:#2660bb}`;
|
||||
document.head.appendChild(css);
|
||||
})();
|
||||
@@ -1,323 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>最近审核</title>
|
||||
<style>
|
||||
:root{--c1:#123a6b;--c2:#1f5fae;--line:#c9d4e2;--head:#eef3fa;--bg:#f5f7fa;--txt:#1c2733;--muted:#5a6b7f}
|
||||
*{box-sizing:border-box}
|
||||
html,body{height:100%}
|
||||
body{font-family:"Microsoft YaHei",system-ui,sans-serif;margin:0;background:var(--bg);color:var(--txt);font-size:13px}
|
||||
/* 2026-10-22 主人定:显示区按最大行撑满(去掉原 max-height:100vh-230px 的底部留白);
|
||||
行数超过可视范围走前端分页(只改显示,接口/数据逻辑不动)。 */
|
||||
.wrap{margin:0 auto;padding:10px 16px 14px;height:100%;display:flex;flex-direction:column}
|
||||
h1{font-size:19px;margin:0 0 3px;color:var(--c1)}
|
||||
.panel{background:#fff;border:1px solid var(--line);flex:1;display:flex;flex-direction:column;min-height:0}
|
||||
.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:6px 0 8px}
|
||||
/* 2026-10-22 主人定:搜索框与「工作台」按钮同款(28px 高/12.5px 字号/同边框圆角) */
|
||||
.bar input{width:250px;height:28px;padding:0 10px;border:1px solid #b8c4d4;border-radius:6px;font:inherit;font-size:12.5px;background:#fff;box-sizing:border-box}
|
||||
.btn{padding:4px 10px;border-radius:6px;border:1px solid #b8c4d4;background:#fff;cursor:pointer;font-size:12px;line-height:1.3;text-decoration:none;display:inline-block}
|
||||
.btn:hover{background:#eef3fa}
|
||||
.btn.pri{background:var(--c2);color:#fff;border-color:var(--c2)}
|
||||
.btn.danger{color:#c0392b;border-color:#e0b4b4}
|
||||
/* 「工作台 / 删除所选」尺寸样式对齐工作台顶栏按钮=「打开项目」(2026-10-19 主人定:
|
||||
大小风格与工作台一致=28px 高 / 左右 12px / 12.5px 字号白底;删除所选保留红色) */
|
||||
.btn.wb{display:inline-flex;align-items:center;justify-content:center;height:28px;padding:0 12px;border:1px solid #b8c4d4;border-radius:6px;background:#fff;cursor:pointer;font:inherit;font-size:12.5px;color:#26405e;text-decoration:none;line-height:1;white-space:nowrap;vertical-align:middle;user-select:none;flex:none}
|
||||
.btn.wb:hover{background:#eef3fa}
|
||||
.btn.wb:active{background:#e0effc}
|
||||
.btn.wb.danger{color:#c0392b;border-color:#e0b4b4}
|
||||
.btn:disabled{opacity:.45;cursor:not-allowed}
|
||||
.ck{display:flex;align-items:center;gap:5px;font-size:12.5px;color:var(--muted);cursor:pointer}
|
||||
/* 2026-10-22 主人定:全选复选框做小做精致(13px、圆角、主题色勾) */
|
||||
.ck input{width:13px;height:13px;margin:0;accent-color:var(--c2);cursor:pointer}
|
||||
.tip{color:var(--muted);font-size:12px}
|
||||
.tw{overflow:auto;flex:1;min-height:0}
|
||||
table{width:100%;border-collapse:collapse;table-layout:fixed}
|
||||
th,td{border:1px solid var(--line);padding:5px 8px;vertical-align:top}
|
||||
th{background:var(--head);position:sticky;top:0;z-index:3;box-shadow:inset 0 -1px 0 var(--line);
|
||||
text-align:center;font-weight:600;white-space:nowrap;font-size:12.5px}
|
||||
td.r{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
td.c{text-align:center;white-space:nowrap}
|
||||
td.l{text-align:left}
|
||||
td.name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
tr.duprow td{background:#fbfcfe;color:#456;font-size:11.5px}
|
||||
tr:hover td{background:#f6f9fd}
|
||||
.empty{padding:26px;text-align:center;color:var(--muted)}
|
||||
.pager{flex:none;display:none;align-items:center;justify-content:flex-end;gap:8px;margin-left:auto}
|
||||
.manualtag{color:#1f5fae;font-weight:600;white-space:nowrap}
|
||||
a{color:var(--c2);text-decoration:none;cursor:pointer}
|
||||
a:hover{text-decoration:underline}
|
||||
/* 统一弹框体系(2026-10-19 主人定:删除确认按「风格预览」里打开项目的弹框样式) */
|
||||
.mask{position:fixed;inset:0;background:rgba(20,30,45,.45);display:none;align-items:center;justify-content:center;z-index:99}
|
||||
.mask.on{display:flex}
|
||||
.dlg{background:#fff;border-radius:10px;box-shadow:0 18px 48px rgba(15,30,50,.25);width:420px;max-width:94vw;max-height:92vh;display:flex;flex-direction:column;overflow:hidden}
|
||||
.dlg .dh{flex:none;display:flex;justify-content:space-between;align-items:center;padding:11px 16px;border-bottom:1px solid var(--line);background:var(--head);border-radius:10px 10px 0 0}
|
||||
.dlg .dh b{color:var(--c1);font-size:14px}
|
||||
.close{cursor:pointer;color:#8899aa;font-size:20px;line-height:1;user-select:none;padding:0 2px}
|
||||
.close:hover{color:#e5484d}
|
||||
.dbody{padding:18px 16px;overflow:auto;display:flex;flex-direction:column;gap:10px}
|
||||
.dfoot{flex:none;display:flex;justify-content:flex-end;gap:8px;padding:11px 16px;border-top:1px solid var(--line);background:#fafcff}
|
||||
</style>
|
||||
<!-- 2026-10-19 补引共用层样式:本页此前漏引 common.css,.rs 列宽把手因此 0 宽度、
|
||||
列宽拖不动(核对时发现);表头底线 1px→2px 与工作台/后台一致。 -->
|
||||
<link rel="stylesheet" href="common.css?v=20261017c">
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<!-- 决策 226(2026-10-27 主人定):标题行加工作台顶栏同款 2px 蓝色底线(--c1 同一变量),与下一行筛选区分割 -->
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px;padding-bottom:6px;border-bottom:2px solid var(--c1)">
|
||||
<h1 style="margin:0;font-size:12.5px">最近审核</h1>
|
||||
<!-- 时间戳参数:老 WebView2 对 no-store 不完全遵守,跨页跳转带新 URL 强制绕缓存(2026-10-12) -->
|
||||
<!-- 2026-10-19 主人定:去掉 ▶ 图标,尺寸样式对齐工作台顶栏「打开项目」按钮 -->
|
||||
<button class="btn wb" onclick="location.href='/workbench.html?v='+Date.now()"
|
||||
title="打开工作台:导入工程、做历史比对与审核">工作台</button>
|
||||
</div>
|
||||
<!-- 2026-10-22 主人定:筛选行移到「工作台」按钮下一行;分页条放同一行右端(右上角)。
|
||||
搜索框/删除所选与「工作台」按钮同款(28px 高、同边框圆角字号)。 -->
|
||||
<div class="bar">
|
||||
<input id="fq" placeholder="项目名称 / 文件名关键字" oninput="render()">
|
||||
<label class="ck"><input type="checkbox" id="ckall" onchange="selAll(this)"> 全选</label>
|
||||
<button class="btn wb danger" id="bdel" disabled onclick="delSel()">删除所选 (0)</button>
|
||||
<div class="pager" id="pager"></div>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<div class="tw" id="tw">
|
||||
<table id="tb">
|
||||
<colgroup id="cg"></colgroup>
|
||||
<thead id="th"></thead>
|
||||
<tbody id="tbody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 统一确认/提示弹框(2026-10-19 主人定:删除确认只用一句「删除后不可恢复,是否删除?」) -->
|
||||
<div class="mask" id="dlgmask">
|
||||
<div class="dlg">
|
||||
<div class="dh"><b id="dlgtitle">确认</b><span class="close" title="关闭" onclick="dlgCancel()">×</span></div>
|
||||
<div class="dbody"><div id="dlgtext" style="color:var(--txt);font-size:13px;line-height:1.7">删除后不可恢复,是否删除?</div></div>
|
||||
<div class="dfoot">
|
||||
<button class="btn wb" id="dlgcancel" onclick="dlgCancel()">取消</button>
|
||||
<button class="btn wb danger" id="dlgok" onclick="dlgOk()">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="common.js?v=20261102a"></script>
|
||||
<script>
|
||||
/* 会话管理页:照后台「项目界面」的版式,管的是**还没入库**的工作台会话。
|
||||
会话库不自动清(SESSION_KEEP_DAYS=0),要删只能在这里手动删。
|
||||
2026-10-11 主人五点:①列宽左右拖拉(公共层 .rs 手柄+localStorage 记忆)
|
||||
②当页排序(sortHeadHTML/sortRows 共用层)③操作列收窄、余量给「项目名称」(原「项目名」改名)
|
||||
④表格撑满屏幕(项目名称列=伸缩列 attrFillBind,.wrap 去掉 max-width 上限)。
|
||||
排序状态 ST={k,dir}:k=SCOLS 下标,刷新/过滤后保持,换数据不重置。 */
|
||||
/* 决策 213 补记七(2026-10-26 主人定):单位工程/清单/定额/工料机/备注 五个统计列取消
|
||||
(后端不再逐会话 COUNT,确实取消提速)——列表只留 身份/总造价/源文件/打开时间/操作。 */
|
||||
const SCOLS=[['',36,'c','','ns'],['序号',50,'c','','ns'],['项目名称',260,'l'],['项目总造价',140,'r'],['源文件',220,'l'],['打开时间',150,'c'],['操作',96,'c','','ns']];
|
||||
let ITEMS=[], ST={k:-1,dir:1};
|
||||
const SES_NUM=new Set([3]); // 项目总造价 按数值比
|
||||
const NAME_IDX=2; // 伸缩列:项目名称(余宽都给它)
|
||||
|
||||
const n2 =n=>(n==null?'—':(+n).toLocaleString('zh-CN'));
|
||||
// 金额:带两位小数。⚠️ 项目总造价取自原文件(含税金/其他项目),**不是**清单合价求和
|
||||
const money=n=>(n==null?'—':(+n).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2}));
|
||||
const $=id=>document.getElementById(id);
|
||||
async function J(u,o){ const r=await fetch(u,o); const d=await r.json(); if(!r.ok) throw new Error((d&&d.error)||('HTTP '+r.status)); return d; }
|
||||
|
||||
function head(){
|
||||
$('cg').innerHTML=colgHTML(SCOLS);
|
||||
$('th').innerHTML=sortHeadHTML(SCOLS,ST,'sesSort');
|
||||
}
|
||||
function sesSort(i){
|
||||
if(ST.k===i) ST.dir=-ST.dir; else { ST.k=i; ST.dir=(i===5?-1:1); } /* 打开时间首点=最新在前(2026-10-13 主人问询后定);213 补记七:列缩后 10→5 */
|
||||
$('th').innerHTML=sortHeadHTML(SCOLS,ST,'sesSort');
|
||||
render();
|
||||
}
|
||||
function srcShort(s){ s=s||''; return s.split('_').length>1 ? s.split('_').slice(1).join('_') : s; }
|
||||
|
||||
/* 上次列表缓存:进页面先画上次的名单,再后台刷新。
|
||||
2026-10-20 主人反馈「进最近审核还要正在加载、太久」——启动自愈/冷盘时 /api/sessions
|
||||
可能被挡十几秒;有缓存就不让页面等接口,接口回来再静默替换。 */
|
||||
const SESS_CACHE_KEY='sess_list_cache_v1';
|
||||
const SESSION_FETCH_TIMEOUT_MS=8000;
|
||||
const SESSION_FETCH_ATTEMPTS=2;
|
||||
let LOAD_SEQ=0;
|
||||
function cacheLoad(){
|
||||
try{
|
||||
const s=localStorage.getItem(SESS_CACHE_KEY);
|
||||
if(!s) return null;
|
||||
const c=JSON.parse(s);
|
||||
return (c && Array.isArray(c.items) && c.items.every(x=>x && typeof x==='object')) ? c.items : null;
|
||||
}catch(e){ return null; }
|
||||
}
|
||||
function cacheSave(){
|
||||
try{ localStorage.setItem(SESS_CACHE_KEY, JSON.stringify({t:Date.now(),items:ITEMS})); }catch(e){}
|
||||
}
|
||||
|
||||
async function load(silent){
|
||||
const seq=++LOAD_SEQ;
|
||||
if(!silent && !ITEMS.length) $('tbody').innerHTML='<tr><td colspan="'+SCOLS.length+'" class="empty">正在读取…</td></tr>';
|
||||
let d, lastErr;
|
||||
for(let attempt=0; attempt<SESSION_FETCH_ATTEMPTS; attempt++){
|
||||
const ctl=typeof AbortController==='function' ? new AbortController() : null;
|
||||
const timer=ctl ? setTimeout(()=>ctl.abort(),SESSION_FETCH_TIMEOUT_MS) : null;
|
||||
try{
|
||||
d=await J('/api/sessions',ctl?{signal:ctl.signal}:undefined);
|
||||
if(!d || d.ok!==true || !Array.isArray(d.items)) throw new Error('会话列表响应格式错误');
|
||||
break;
|
||||
}catch(e){
|
||||
lastErr=e;
|
||||
if(attempt+1<SESSION_FETCH_ATTEMPTS) await new Promise(r=>setTimeout(r,250));
|
||||
}finally{ if(timer) clearTimeout(timer); }
|
||||
}
|
||||
if(!d){
|
||||
if(seq!==LOAD_SEQ) return;
|
||||
if(ITEMS.length){ if(typeof toast==='function') toast('刷新失败:显示上次列表'); return; }
|
||||
$('tbody').innerHTML='<tr><td colspan="'+SCOLS.length+'" class="empty">读取失败:服务没连上(软件可能没启动)</td></tr>';
|
||||
return;
|
||||
}
|
||||
if(seq!==LOAD_SEQ) return;
|
||||
ITEMS=d.items;
|
||||
render();
|
||||
cacheSave();
|
||||
}
|
||||
|
||||
function render(){
|
||||
const q=($('fq').value||'').trim().toLowerCase();
|
||||
const rows=ITEMS.filter(x=>!q || (x.name||'').toLowerCase().includes(q) || (x.src_name||'').toLowerCase().includes(q))
|
||||
.map(x=>[x.id, 0, x.name||'', x.total, srcShort(x.src_name), x.at||'', (x.all||[]).map(a=>a.id), x.src_name,
|
||||
x.can_reparse === false, x.manual === true]); /* [8] 源文件缺失(决策 94) [9] 手工工程;[5]打开时间 [6]删除ids [7]源文件名;[1]=序号占位 */
|
||||
const view=sortRows(rows, ST.k, ST.dir, SES_NUM);
|
||||
view.forEach((r,i)=>{ r[1]=view.length-i; }); /* 序号倒序编号(与后台入库项目一致:第一行=总数,往下递减);默认序=打开时间越新越靠前(服务端 id 倒序=打开时间倒序,同名工程后端只留最近一次,2026-10-07 主人定) */
|
||||
/* 2026-10-22 主人定:显示区按最大行撑满(.tw flex 撑满窗口余量),行数超可视范围=前端分页
|
||||
(只改显示,接口/数据不动)。每页行数按表格区实际高度÷行高动态算,窗口缩放自动跟随。 */
|
||||
const tw=$('tw');
|
||||
const thH=$('th').getBoundingClientRect().height||30;
|
||||
const rowH=PAG.rowH||29;
|
||||
const size=Math.max(1,Math.floor(((tw?tw.clientHeight:0)-thH-4)/rowH)||1); /* 容器未就绪时兜底 1 行,绝不让 render 抛错 */
|
||||
PAG.size=size;
|
||||
let rowsToShow=view;
|
||||
if(view.length>size){
|
||||
const tp=Math.max(1,Math.ceil(view.length/size));
|
||||
if(PAG.p>tp) PAG.p=tp; if(PAG.p<1) PAG.p=1;
|
||||
const st=(PAG.p-1)*size;
|
||||
rowsToShow=view.slice(st,st+size);
|
||||
}else PAG.p=1;
|
||||
let h='';
|
||||
rowsToShow.forEach(r=>{
|
||||
const srcCell = r[9]
|
||||
? `<span class="manualtag" title="手工工程:没有源文件,不能按原格式导出/重新解析;要上源文件数据请先删除本工程,再按源文件重新导入(同名导入会被拒,决策 242)">手工创建</span>`
|
||||
: (r[8]
|
||||
? esc(r[4]) + ' <span class="srcmiss" style="color:#c0392b;font-weight:600;white-space:nowrap" title="原文件已不在软件里:该工程无法导出、无法重新解析(已解析的数据仍可查看)。删除会话不受影响">源文件缺失</span>'
|
||||
: esc(r[4]));
|
||||
h+=`<tr>
|
||||
<td class="c"><input type="checkbox" class="f-sel" value="${r[0]}" onchange="updDel()"></td>
|
||||
<td class="c" title="${r[1]}">${r[1]}</td>
|
||||
<td class="l name" title="${esc(r[2])}">${esc(r[2]||'(无名)')}</td>
|
||||
<td class="r" title="${r[3]==null?'原文件里没取到总造价':'工程总造价(原文件口径,含税金与其他项目)'}">${money(r[3])}</td>
|
||||
<td class="l name" title="${esc(r[7])}">${srcCell}</td>
|
||||
<td class="c" title="${esc(r[5]||'')}">${esc(r[5]||'—')}</td>
|
||||
<td class="c">
|
||||
<a onclick="go(${r[0]})" title="打开最近一次审核,接着上次的活干">打开</a>
|
||||
<a onclick="del([${(r[6]||[]).join(',')}])" style="margin-left:8px;color:#c0392b">删除</a>
|
||||
</td></tr>`;
|
||||
});
|
||||
$('tbody').innerHTML=h||`<tr><td colspan="${SCOLS.length}" class="empty">没有匹配的会话</td></tr>`;
|
||||
/* 行高实测回填(行高变了且正在分页 → 重算一次;rowH 稳定后不再二次渲染) */
|
||||
const fr=$('tbody').firstElementChild;
|
||||
if(fr && !fr.classList.contains('empty')){
|
||||
const rh=fr.getBoundingClientRect().height;
|
||||
if(rh && Math.abs(rh-(PAG.rowH||0))>0.5){ PAG.rowH=rh; if(view.length>PAG.size){ render(); return; } }
|
||||
}
|
||||
/* 分页条:只有超页时显示 */
|
||||
const pg=$('pager');
|
||||
if(view.length>PAG.size){
|
||||
const tp=Math.ceil(view.length/PAG.size);
|
||||
pg.style.display='flex';
|
||||
pg.innerHTML='<span class="tip">共 '+view.length+' 行 · 第 '+PAG.p+' / '+tp+' 页 · 每页 '+PAG.size+' 行</span>'
|
||||
+'<button class="btn wb" onclick="pgGo(-1)"'+(PAG.p<=1?' disabled':'')+'>上一页</button>'
|
||||
+'<button class="btn wb" onclick="pgGo(1)"'+(PAG.p>=tp?' disabled':'')+'>下一页</button>';
|
||||
}else pg.style.display='none';
|
||||
updDel();
|
||||
}
|
||||
/* 分页翻页(前端切片,不动数据) */
|
||||
const PAG={p:1,size:0,rowH:0};
|
||||
function pgGo(d){ PAG.p+=d; render(); }
|
||||
function selAll(el){ document.querySelectorAll('.f-sel').forEach(x=>x.checked=el.checked); updDel(); }
|
||||
function updDel(){
|
||||
const n=document.querySelectorAll('.f-sel:checked').length;
|
||||
$('bdel').textContent='删除所选 ('+n+')'; $('bdel').disabled=n===0;
|
||||
}
|
||||
/* 删除所选 = 把每个勾中名称下的**全部**审核记录一起删(代表 id → 该组所有会话 id) */
|
||||
function delSel(){
|
||||
const rep=Array.from(document.querySelectorAll('.f-sel:checked')).map(x=>+x.value);
|
||||
del(ITEMS.filter(x=>rep.includes(x.id)).flatMap(x=>(x.all||[]).map(a=>a.id)));
|
||||
}
|
||||
|
||||
function go(id){ location.href='/workbench.html?sid='+id+'&t='+Date.now(); }
|
||||
/* 2026-09-30 主人定:落地页每行**只留「打开」+「删除」**,去掉「重新解析」按钮。
|
||||
它只在解析器更新后才需要,不该占日常位置。
|
||||
2026-10-07:同名工程按名称合并成一行,删除传入该名称下全部会话 id(不分时间版本)。
|
||||
2026-10-19 主人定:删除=连带清干净(备注/源文件/采纳事件一起走;后台同源还引用时保留),
|
||||
确认弹框统一为一句「删除后不可恢复,是否删除?」。 */
|
||||
/* ---- 统一确认/提示弹框(2026-10-19 主人定)----
|
||||
删除确认只用一句「删除后不可恢复,是否删除?」,取消/关闭=不删;
|
||||
原先那句「要刷新数据=删了重开」的旧提示随 2026-09-30 决定一并废除(主人 2026-10-19 拍板)。*/
|
||||
let DLG_CB=null;
|
||||
function dlgShow(text, okText, cb, title, danger){
|
||||
$('dlgtitle').textContent=title||'确认';
|
||||
$('dlgtext').textContent=text;
|
||||
$('dlgok').textContent=okText||'确定';
|
||||
$('dlgok').className='btn wb'+(danger?' danger':'');
|
||||
$('dlgcancel').style.display=cb?'':'none';
|
||||
DLG_CB=cb||null;
|
||||
$('dlgmask').classList.add('on');
|
||||
}
|
||||
function dlgCancel(){ $('dlgmask').classList.remove('on'); DLG_CB=null; }
|
||||
function dlgOk(){ const cb=DLG_CB; dlgCancel(); if(cb) cb(); }
|
||||
function dlgNotice(text){ dlgShow(text,'确定',null,'提示',false); }
|
||||
$('dlgmask').addEventListener('click',function(e){ if(e.target===this) dlgCancel(); });
|
||||
document.addEventListener('keydown',function(e){
|
||||
if(e.key==='Escape' && $('dlgmask').classList.contains('on')) dlgCancel();
|
||||
});
|
||||
|
||||
async function del(ids){
|
||||
if(!ids.length) return;
|
||||
dlgShow('删除后不可恢复,是否删除?','删除',async ()=>{
|
||||
/* 2026-10-19 主人定:乐观删除——确认后行立即消失,子表/备注/文件由服务端后台清;
|
||||
接口失败则整表还原并提示。 */
|
||||
const before=ITEMS.slice();
|
||||
++LOAD_SEQ; // 删除期间的旧读响应不得把已消失的行补回来
|
||||
ITEMS=ITEMS.filter(x=>!(x.all||[]).some(a=>ids.includes(a.id)));
|
||||
$('ckall').checked=false;
|
||||
render();
|
||||
cacheSave();
|
||||
let r;
|
||||
try{
|
||||
r=await J('/api/session/delete',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({ids})});
|
||||
}catch(e){ ITEMS=before; render(); cacheSave(); dlgNotice('删除失败:服务没连上'); return; }
|
||||
if(r&&r.ok){
|
||||
toast('已删除'); // 2026-10-19 主人定:删除成功只弹右下角消息,不再弹确认框
|
||||
load(true); // 静默对账(行已消失,不闪"正在读取…")
|
||||
}else{
|
||||
ITEMS=before; render(); cacheSave();
|
||||
dlgNotice((r&&r.msg)||'删除失败');
|
||||
}
|
||||
},'确认',true);
|
||||
}
|
||||
|
||||
|
||||
head();
|
||||
sumw($('tb')); // 表宽=列宽和(先按基础宽出表)
|
||||
colwApply($('tb')); // 套用上次拖动记忆(伸缩列只记基础宽)
|
||||
attrFillBind($('tb'), NAME_IDX, 260); // 项目名称列吃掉全部余宽 → 表格撑满屏幕(RO 盯缩放)
|
||||
const _sessCached=cacheLoad();
|
||||
if(_sessCached!==null){
|
||||
ITEMS=_sessCached; render(); load(true); // 先出上次名单,后台静默刷新(不等接口)
|
||||
}else{
|
||||
ldWrap('','正在加载会话…',()=>load()); // 首次无缓存:保留进度条
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
||||
{"enforce": false}
|
||||
@@ -1,2 +0,0 @@
|
||||
!! 会话工程量公式口径修复失败:no such column: qty_expr
|
||||
serving on http://127.0.0.1:60223 (db=D:\PricingReview\_analysis\定额单价专题\iab_env3\CostReview\data\history.db) (PID=13136)
|
||||
104
_analysis/定额单价专题/patch_273_api.py
Normal file
104
_analysis/定额单价专题/patch_273_api.py
Normal file
@@ -0,0 +1,104 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 273 实施:采纳外部定额的单价行组——行与列按本项目同区模板复制,
|
||||
Total 按 Name 匹配外部(一致=外部该行 Total,不一致留空)。
|
||||
改动:①api_server 采纳段 bnorms SELECT+INSERT 带 x_side(采纳时构造最终行组)
|
||||
②export_cos._norm_xml 按 x_side 回填单价行 Total(无 x_side 维持清零现状)。"""
|
||||
import io
|
||||
p = r"D:\PricingReview\CostReview\app\server\api_server.py"
|
||||
s = io.open(p, encoding="utf-8").read()
|
||||
|
||||
# ---- ① 两处 bnorms SELECT 加 x_side ----
|
||||
old = ''' bnorms = sc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total,
|
||||
NULL AS x_qty_coef, x_adjust, qty_expr
|
||||
FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""",
|
||||
(src_self,)).fetchall()'''
|
||||
new = ''' bnorms = sc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total,
|
||||
NULL AS x_qty_coef, x_adjust, qty_expr, x_side
|
||||
FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""",
|
||||
(src_self,)).fetchall()'''
|
||||
assert old in s, "bnorms sc NOT FOUND"
|
||||
s = s.replace(old, new)
|
||||
|
||||
old2 = ''' bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust
|
||||
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()'''
|
||||
new2 = ''' bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side
|
||||
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()'''
|
||||
assert old2 in s, "bnorms hc NOT FOUND"
|
||||
s = s.replace(old2, new2)
|
||||
|
||||
# ---- ② bnorms 取完后构造:外部 Name→Total 映射 + 本项目同区模板行组 ----
|
||||
old3 = ''' def _norm_expr(nn):
|
||||
# 决策 217(2026-10-26 主人定):采纳定额公式**四入口统一为分部分项同款 GCL×系数**——'''
|
||||
new3 = ''' # 决策 273(2026-11-04 主人定):采纳定额的单价行组——行与列按本项目同区模板复制,
|
||||
# Total 按 Name 匹配外部(一致=外部该行 Total,不一致留空)。外部单价行=norms.x_side
|
||||
# (norm_side 通道 2026-11-03 已入库);本项目同区模板=同 x_ptag(措施/分部)任一条
|
||||
# 非采纳定额的 x_side;本项目无同区模板→x_side 置空(骨架态,等原软件组价)。
|
||||
_ext_by_norm = {}
|
||||
if not src_self:
|
||||
for _n2 in bnorms:
|
||||
if not _n2["x_side"]:
|
||||
continue
|
||||
try:
|
||||
_m = {}
|
||||
for _rec in json.loads(_n2["x_side"]):
|
||||
if _rec.get("tag") == "UnitPriceCalculationOfItem":
|
||||
_a = _rec.get("attrs") or {}
|
||||
_m[(_a.get("Name") or "").strip()] = _a.get("Total")
|
||||
_ext_by_norm[_n2["id"]] = _m
|
||||
except Exception:
|
||||
pass
|
||||
_tmpl_side = None
|
||||
try:
|
||||
_pt = sc.execute("SELECT x_ptag FROM s_bills WHERE id=?", (bid,)).fetchone()
|
||||
_ptag = ((_pt["x_ptag"] if _pt else None) or "")
|
||||
_t = sc.execute("""SELECT n.x_side FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=? AND COALESCE(n.x_adopt,0)=0 AND n.x_side IS NOT NULL
|
||||
AND b.id<>? AND COALESCE(b.x_ptag,'')=?
|
||||
ORDER BY n.id LIMIT 1""", (sid, bid, _ptag)).fetchone()
|
||||
if _t and _t["x_side"]:
|
||||
_tmpl_side = _t["x_side"]
|
||||
except Exception:
|
||||
_tmpl_side = None
|
||||
|
||||
def _adopt_side(nn):
|
||||
"""本条采纳定额的 x_side:本项目来源=源行组原样复制;外部来源=同区模板行组
|
||||
+ Total 按 Name 匹配外部(一致=外部值,不一致留空);无模板=None。"""
|
||||
if src_self:
|
||||
return nn["x_side"]
|
||||
_m = _ext_by_norm.get(nn["id"])
|
||||
if not _tmpl_side or _m is None:
|
||||
return None
|
||||
try:
|
||||
_side = json.loads(_tmpl_side)
|
||||
for _rec in _side:
|
||||
if _rec.get("tag") == "UnitPriceCalculationOfItem":
|
||||
_a = _rec.get("attrs") or {}
|
||||
_nm = (_a.get("Name") or "").strip()
|
||||
_a["Total"] = _m.get(_nm, "")
|
||||
_rec["attrs"] = _a
|
||||
return json.dumps(_side, ensure_ascii=False)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _norm_expr(nn):
|
||||
# 决策 217(2026-10-26 主人定):采纳定额公式**四入口统一为分部分项同款 GCL×系数**——'''
|
||||
assert old3 in s, "norm_expr anchor NOT FOUND"
|
||||
s = s.replace(old3, new3)
|
||||
|
||||
# ---- ③ 两处采纳 INSERT 加 x_side ----
|
||||
old4 = ''' cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
|
||||
x_adopt, x_src_norm_id, qty_expr, x_adjust)
|
||||
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?)""",
|
||||
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"],
|
||||
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"]))'''
|
||||
new4 = ''' cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
|
||||
x_adopt, x_src_norm_id, qty_expr, x_adjust, x_side)
|
||||
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?,?)""",
|
||||
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"],
|
||||
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"], _adopt_side(nn)))'''
|
||||
c = s.count(old4)
|
||||
assert c == 2, "INSERT count=%d" % c
|
||||
s = s.replace(old4, new4)
|
||||
|
||||
io.open(p, "w", encoding="utf-8").write(s)
|
||||
print("api_server adopt side done")
|
||||
51
_analysis/定额单价专题/patch_273_exp.py
Normal file
51
_analysis/定额单价专题/patch_273_exp.py
Normal file
@@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 273 导出端:采纳定额(x_side 有值)的单价行 Total 按 x_side 回填——
|
||||
一致=外部值/不一致=空串;无 x_side 维持清零现状(106 口径不动)。"""
|
||||
import io
|
||||
p = r"D:\PricingReview\CostReview\app\core\export_cos.py"
|
||||
s = io.open(p, encoding="utf-8").read()
|
||||
|
||||
# ---- ① _norm_xml 里 pre/post 清零后按 x_side 回填单价行 Total ----
|
||||
old = ''' pre, post = _zero_results(pre), _zero_results(post)
|
||||
pre = re.sub(r'<ExpressElement\\b[^>]*/>', '', pre)
|
||||
post = re.sub(r'<ExpressElement\\b[^>]*/>', '', post)'''
|
||||
new = ''' pre, post = _zero_results(pre), _zero_results(post)
|
||||
pre = re.sub(r'<ExpressElement\\b[^>]*/>', '', pre)
|
||||
post = re.sub(r'<ExpressElement\\b[^>]*/>', '', post)
|
||||
# 决策 273(2026-11-04 主人定):采纳定额的单价行 Total 按 Name 匹配外部——
|
||||
# x_side(采纳时构造:同区模板行组+Total 按 Name 匹配外部,一致=外部值/不一致留空)
|
||||
# 有值时回填 Total 覆盖清零;无 x_side 维持清零现状(106 口径不动)。
|
||||
_sm = {}
|
||||
if n.get("x_side"):
|
||||
try:
|
||||
for _rec in json.loads(n["x_side"]):
|
||||
if _rec.get("tag") == "UnitPriceCalculationOfItem":
|
||||
_a = _rec.get("attrs") or {}
|
||||
_sm[(_a.get("Name") or "").strip()] = _a.get("Total")
|
||||
except Exception:
|
||||
_sm = {}
|
||||
if _sm:
|
||||
pre = _adopt_totals(pre, _sm)
|
||||
post = _adopt_totals(post, _sm)'''
|
||||
assert old in s, "zero block NOT FOUND"
|
||||
s = s.replace(old, new)
|
||||
|
||||
# ---- ② _adopt_totals 函数(挂在 _zero_results 后面) ----
|
||||
old2 = '''def _zero_results(frag):'''
|
||||
new2 = '''def _adopt_totals(frag, sm):
|
||||
"""决策 273:单价行 Total 按 Name 匹配回填——一致=外部该行 Total;不一致=空串(留空)。
|
||||
只动骨架已有的 UnitPriceCalculationOfItem 自闭合行(卡槽在才写)。"""
|
||||
def _f(m):
|
||||
a = dict(re.findall(r'(\\w+)="([^"]*)"', m.group(1)))
|
||||
nm = (a.get("Name") or "").strip()
|
||||
v = sm.get(nm)
|
||||
return _attr_set(m.group(0), "Total", "" if v is None else v)
|
||||
return re.sub(r'<UnitPriceCalculationOfItem\\b([^>]*?)/>', _f, frag)
|
||||
|
||||
|
||||
def _zero_results(frag):'''
|
||||
assert old2 in s, "_zero_results anchor NOT FOUND"
|
||||
s = s.replace(old2, new2)
|
||||
|
||||
io.open(p, "w", encoding="utf-8").write(s)
|
||||
print("export side done")
|
||||
@@ -1,254 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""设置弹框 v2 手术:①标签卡行共用「添加」按钮(导出卡=选文件入库/工料机卡=列设置)
|
||||
②工料机卡撤列设置按钮 ③列设置无确定/取消(即时保存)④插=往后面一行插入
|
||||
⑤# /后缀/起点 固定最前、不进列设置——列设置只管自定义列;新建时固定送一行空列;
|
||||
自定义列有值不可删、无值可删。"""
|
||||
import io
|
||||
p = r"D:\PricingReview\CostReview\app\ui\admin.html"
|
||||
s = io.open(p, encoding="utf-8").read()
|
||||
|
||||
# ---- ① 标签卡行加共用「添加」按钮 ----
|
||||
old = ''' <div style="padding:10px 16px 0">
|
||||
<div class="tabs">
|
||||
<div class="dtab on" id="ftabExp" onclick="ftabSet('exp')">导出</div>
|
||||
<div class="dtab" id="ftabLme" onclick="ftabSet('lme')">工料机</div>
|
||||
</div>
|
||||
</div>'''
|
||||
new = ''' <div style="padding:10px 16px 0">
|
||||
<div class="tabs">
|
||||
<div class="dtab on" id="ftabExp" onclick="ftabSet('exp')">导出</div>
|
||||
<div class="dtab" id="ftabLme" onclick="ftabSet('lme')">工料机</div>
|
||||
<button class="btn pri" style="margin-left:auto;height:24px;padding:0 16px" onclick="fsetAdd()"
|
||||
title="导出卡:选 .cos / .cos4 原件或骨架包入库;工料机卡:列设置(自定义列增删改/排序)">添加</button>
|
||||
</div>
|
||||
</div>'''
|
||||
assert old in s, "tabs NOT FOUND"
|
||||
s = s.replace(old, new)
|
||||
|
||||
# ---- ② 工料机面板撤「列设置」按钮行 ----
|
||||
old2 = ''' <div id="fpaneLme" style="display:none">
|
||||
<div style="display:flex;justify-content:flex-end">
|
||||
<button class="btn" onclick="openColSet()" title="配置工料机表的列:显隐/顺序/增删">列设置</button>
|
||||
</div>
|
||||
<div class="tw" style="max-height:52vh">'''
|
||||
new2 = ''' <div id="fpaneLme" style="display:none">
|
||||
<div class="tw" style="max-height:52vh">'''
|
||||
assert old2 in s, "lme pane NOT FOUND"
|
||||
s = s.replace(old2, new2)
|
||||
|
||||
# ---- ③ 列设置弹框撤确定/取消按钮行 ----
|
||||
old3 = ''' <div style="display:flex;justify-content:flex-end;gap:8px">
|
||||
<button class="btn pri" onclick="colSetApply()">确定</button>
|
||||
<button class="btn" onclick="closeColSet()">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>'''
|
||||
new3 = ''' </div>
|
||||
</div>
|
||||
</div>'''
|
||||
assert old3 in s, "colset btns NOT FOUND"
|
||||
s = s.replace(old3, new3)
|
||||
|
||||
# ---- ④ JS:fsetAdd + 即时保存 + 插=后插 + 自定义列有值不可删 ----
|
||||
old4 = '''function ftabSet(which){
|
||||
const exp = which === 'exp';
|
||||
$('ftabExp').classList.toggle('on', exp);
|
||||
$('ftabLme').classList.toggle('on', !exp);
|
||||
$('fpaneExp').style.display = exp ? '' : 'none';
|
||||
$('fpaneLme').style.display = exp ? 'none' : '';
|
||||
if(!exp) lmeSetRender();
|
||||
}'''
|
||||
new4 = '''function ftabSet(which){
|
||||
const exp = which === 'exp';
|
||||
$('ftabExp').classList.toggle('on', exp);
|
||||
$('ftabLme').classList.toggle('on', !exp);
|
||||
$('fpaneExp').style.display = exp ? '' : 'none';
|
||||
$('fpaneLme').style.display = exp ? 'none' : '';
|
||||
if(!exp) lmeSetRender();
|
||||
}
|
||||
function fsetAdd(){ // 共用「添加」:导出卡=选文件入库;工料机卡=列设置
|
||||
const exp = $('fpaneExp').style.display !== 'none';
|
||||
if(exp) framesAdd(); else openColSet();
|
||||
}'''
|
||||
assert old4 in s, "ftabSet NOT FOUND"
|
||||
s = s.replace(old4, new4)
|
||||
|
||||
old5 = '''/* ---- 列设置弹框 ---- */
|
||||
let WORKCOLS = null; // 列设置弹框的工作副本(确定才写回)
|
||||
function openColSet(){
|
||||
WORKCOLS = JSON.parse(JSON.stringify(colSetLoad()));
|
||||
colRender();
|
||||
$('colmask').classList.add('on');
|
||||
}
|
||||
function closeColSet(){ $('colmask').classList.remove('on'); }
|
||||
colmask.onclick = e => { if(e.target===colmask) closeColSet() };
|
||||
function colRender(){
|
||||
$('colBody').innerHTML = WORKCOLS.map((c, i) =>
|
||||
'<tr><td class="c">' + (i+1) + '</td>'
|
||||
+ '<td><input type="text" value="' + escLme(c.name) + '" style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="WORKCOLS[' + i + '].name=this.value"></td>'
|
||||
+ '<td class="c"><input type="checkbox" ' + (c.on?'checked':'') + ' onchange="WORKCOLS[' + i + '].on=this.checked"></td>'
|
||||
+ '<td class="c">'
|
||||
+ '<a href="javascript:colMove(' + i + ',-1)" style="color:#26405e">↑</a> '
|
||||
+ '<a href="javascript:colMove(' + i + ',1)" style="color:#26405e">↓</a> '
|
||||
+ '<a href="javascript:colInsert(' + i + ')" style="color:#26405e" title="在该行位置插入新列">插</a> '
|
||||
+ '<a href="javascript:colDel(' + i + ')" style="color:#c0392b">×</a>'
|
||||
+ '</td></tr>').join('') || '<tr><td colspan="4" class="c" style="color:#888">空</td></tr>';
|
||||
}
|
||||
function colMove(i, d){
|
||||
const j = i + d;
|
||||
if(j < 0 || j >= WORKCOLS.length) return;
|
||||
const t = WORKCOLS[i]; WORKCOLS[i] = WORKCOLS[j]; WORKCOLS[j] = t;
|
||||
colRender();
|
||||
}
|
||||
function colInsert(i){
|
||||
WORKCOLS.splice(i, 0, { key: 'c' + Date.now(), name: '', on: true });
|
||||
colRender();
|
||||
}
|
||||
function colDel(i){
|
||||
if(WORKCOLS.length <= 1) return; // 至少留一列
|
||||
WORKCOLS.splice(i, 1);
|
||||
colRender();
|
||||
}
|
||||
function colSetApply(){
|
||||
const on = WORKCOLS.filter(c => c.on).map((c, i) => ({ key: c.key,
|
||||
name: c.name || ('列' + (i+1)), on: true }));
|
||||
const off = WORKCOLS.filter(c => !c.on).map(c => ({ key: c.key, name: c.name, on: false }));
|
||||
colSetSave(on.concat(off)); // 未勾选列保留定义(不丢配置)
|
||||
closeColSet();
|
||||
lmeSetRender();
|
||||
$('fmsg').textContent = '列设置已应用';
|
||||
}'''
|
||||
new5 = '''/* ---- 列设置弹框(2026-11-04 主人定 v2:无确定/取消=即时保存;插=往后面一行插入;
|
||||
# /后缀/起点 固定最前、不进列设置——这里只管自定义列;新建时固定送一行空列;
|
||||
自定义列有值不可删、无值才可删。---- */
|
||||
function openColSet(){
|
||||
const cs = colSetLoad();
|
||||
if(cs.length === 0){ // 新建时固定有一行(空列占位)
|
||||
cs.push({ key: 'c' + Date.now(), name: '', on: true });
|
||||
colSetSave(cs);
|
||||
}
|
||||
colRender();
|
||||
$('colmask').classList.add('on');
|
||||
}
|
||||
function closeColSet(){ $('colmask').classList.remove('on'); }
|
||||
colmask.onclick = e => { if(e.target===colmask) closeColSet() };
|
||||
function colSaveRender(){ // 每次改动即时落存+两处同步刷新
|
||||
colRender();
|
||||
lmeSetRender();
|
||||
}
|
||||
function colRender(){
|
||||
const cs = colSetLoad();
|
||||
$('colBody').innerHTML = cs.map((c, i) =>
|
||||
'<tr><td class="c">' + (i+1) + '</td>'
|
||||
+ '<td><input type="text" value="' + escLme(c.name) + '" placeholder="列名"'
|
||||
+ ' style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="colRename(' + i + ',this.value)"></td>'
|
||||
+ '<td class="c"><input type="checkbox" ' + (c.on?'checked':'') + ' onchange="colToggle(' + i + ',this.checked)"></td>'
|
||||
+ '<td class="c">'
|
||||
+ '<a href="javascript:colMove(' + i + ',-1)" style="color:#26405e">↑</a> '
|
||||
+ '<a href="javascript:colMove(' + i + ',1)" style="color:#26405e">↓</a> '
|
||||
+ '<a href="javascript:colInsert(' + i + ')" style="color:#26405e" title="往后面一行插入新列">插</a> '
|
||||
+ '<a href="javascript:colDel(' + i + ')" style="color:#c0392b">×</a>'
|
||||
+ '</td></tr>').join('');
|
||||
}
|
||||
function colRename(i, v){
|
||||
const cs = colSetLoad(); cs[i].name = v; colSetSave(cs);
|
||||
colSaveRender();
|
||||
}
|
||||
function colToggle(i, on){
|
||||
const cs = colSetLoad(); cs[i].on = on; colSetSave(cs);
|
||||
colSaveRender();
|
||||
}
|
||||
function colMove(i, d){
|
||||
const cs = colSetLoad();
|
||||
const j = i + d;
|
||||
if(j < 0 || j >= cs.length) return;
|
||||
const t = cs[i]; cs[i] = cs[j]; cs[j] = t;
|
||||
colSetSave(cs);
|
||||
colSaveRender();
|
||||
}
|
||||
function colInsert(i){
|
||||
const cs = colSetLoad();
|
||||
cs.splice(i + 1, 0, { key: 'c' + Date.now(), name: '', on: true }); // 往后面一行插入
|
||||
colSetSave(cs);
|
||||
colSaveRender();
|
||||
}
|
||||
function colHasValue(i){ // 该列在所有后缀行上是否有值
|
||||
const cs = colSetLoad();
|
||||
const key = cs[i] ? cs[i].key : null;
|
||||
const suffixes = [];
|
||||
(FRAMES||[]).forEach(r => { if(!suffixes.includes(r.suffix)) suffixes.push(r.suffix); });
|
||||
return suffixes.some(sfx => lmeStartGet(key, sfx) !== '');
|
||||
}
|
||||
function colDel(i){
|
||||
if(colHasValue(i)) { $('fmsg').textContent = '该列已有值,不能删除'; return; }
|
||||
const cs = colSetLoad();
|
||||
cs.splice(i, 1);
|
||||
colSetSave(cs);
|
||||
colSaveRender();
|
||||
}'''
|
||||
assert old5 in s, "colset js NOT FOUND"
|
||||
s = s.replace(old5, new5)
|
||||
|
||||
# ---- ⑤ colSetLoad 只存自定义列 + 工料机表固定 # /后缀 /起点 ----
|
||||
old6 = '''function colSetLoad(){ // 列设置(localStorage 持久;损坏回默认)
|
||||
try{ const v = JSON.parse(localStorage.getItem('lme_colset')||'null');
|
||||
if(Array.isArray(v) && v.length && v.every(c => c && c.key && 'name' in c))
|
||||
return v; }catch(e){}
|
||||
return [{key:'suffix', name:'后缀', on:true},{key:'start', name:'起点', on:true}];
|
||||
}'''
|
||||
new6 = '''function colSetLoad(){ // 自定义列清单(localStorage 持久;损坏回空)
|
||||
try{ const v = JSON.parse(localStorage.getItem('lme_colset')||'null');
|
||||
if(Array.isArray(v) && v.every(c => c && c.key && 'name' in c))
|
||||
return v; }catch(e){}
|
||||
return [];
|
||||
}'''
|
||||
assert old6 in s, "colSetLoad NOT FOUND"
|
||||
s = s.replace(old6, new6)
|
||||
|
||||
old7 = '''function lmeSetRender(){ // 工料机卡:行=导出卡后缀去重;列=colSet 勾选列按序
|
||||
const suffixes = [];
|
||||
(FRAMES||[]).forEach(r => { if(!suffixes.includes(r.suffix)) suffixes.push(r.suffix); });
|
||||
const cols = colSetLoad().filter(c => c.on);
|
||||
$('lmeSetHead').innerHTML = '<th class="c">#</th>' + cols.map(c => '<th>' + escLme(c.name) + '</th>').join('');
|
||||
let html = '';
|
||||
suffixes.forEach((sfx, i) => {
|
||||
html += '<tr><td class="c">' + (i+1) + '</td>' + cols.map(c => {
|
||||
if(c.key === 'suffix') return '<td>' + escLme(sfx) + '</td>';
|
||||
const val = escLme(lmeStartGet(c.key, sfx));
|
||||
return '<td><input type="text" value="' + val + '" style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="lmeStartSet(\\'' + c.key + '\\',\\'' + escLme(sfx) + '\\',this.value)"></td>';
|
||||
}).join('') + '</tr>';
|
||||
});
|
||||
$('lmeSetBody').innerHTML = html
|
||||
|| '<tr><td colspan="9" class="c" style="color:#888">还没有骨架:先在「导出」卡添加,后缀会带到这里</td></tr>';
|
||||
}'''
|
||||
new7 = '''function lmeSetRender(){ // 工料机卡:# /后缀 /起点 固定最前 + 自定义勾选列按序
|
||||
const suffixes = [];
|
||||
(FRAMES||[]).forEach(r => { if(!suffixes.includes(r.suffix)) suffixes.push(r.suffix); });
|
||||
const cols = colSetLoad().filter(c => c.on);
|
||||
$('lmeSetHead').innerHTML = '<th class="c" style="width:56px">#</th><th>后缀</th><th>起点</th>'
|
||||
+ cols.map(c => '<th>' + escLme(c.name) + '</th>').join('');
|
||||
let html = '';
|
||||
suffixes.forEach((sfx, i) => {
|
||||
html += '<tr><td class="c">' + (i+1) + '</td><td>' + escLme(sfx) + '</td>';
|
||||
const sv = escLme(lmeStartGet('start', sfx));
|
||||
html += '<td><input type="text" value="' + sv + '" style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="lmeStartSet(\\'start\\',\\'' + escLme(sfx) + '\\',this.value)"></td>';
|
||||
html += cols.map(c => {
|
||||
const val = escLme(lmeStartGet(c.key, sfx));
|
||||
return '<td><input type="text" value="' + val + '" style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="lmeStartSet(\\'' + c.key + '\\',\\'' + escLme(sfx) + '\\',this.value)"></td>';
|
||||
}).join('');
|
||||
html += '</tr>';
|
||||
});
|
||||
$('lmeSetBody').innerHTML = html
|
||||
|| '<tr><td colspan="9" class="c" style="color:#888">还没有骨架:先在「导出」卡添加,后缀会带到这里</td></tr>';
|
||||
}'''
|
||||
assert old7 in s, "lmeSetRender NOT FOUND"
|
||||
s = s.replace(old7, new7)
|
||||
|
||||
io.open(p, "w", encoding="utf-8").write(s)
|
||||
print("surgery v2 done")
|
||||
@@ -1,211 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""设置弹框 v3:①工料机表单元格=双击编辑(决策174:编辑框布满单元格偏差≤2px),起点+自定义列;
|
||||
②自定义列单元格带圆形「代」按钮(haobtn 同款)→ 浮层=该列代号清单(序号|代号,可插行/删行/代入);
|
||||
③列设置弹框名称列=双击编辑布满单元格。"""
|
||||
import io
|
||||
p = r"D:\PricingReview\CostReview\app\ui\admin.html"
|
||||
s = io.open(p, encoding="utf-8").read()
|
||||
|
||||
# ---- ① lmeSetRender 单元格改:常显值+(自定义列)代按钮;双击编辑 ----
|
||||
old = '''function lmeSetRender(){ // 工料机卡:# /后缀 /起点 固定最前 + 自定义勾选列按序
|
||||
const suffixes = [];
|
||||
(FRAMES||[]).forEach(r => { if(!suffixes.includes(r.suffix)) suffixes.push(r.suffix); });
|
||||
const cols = colSetLoad().filter(c => c.on);
|
||||
$('lmeSetHead').innerHTML = '<th class="c" style="width:56px">#</th><th>后缀</th><th>起点</th>'
|
||||
+ cols.map(c => '<th>' + escLme(c.name) + '</th>').join('');
|
||||
let html = '';
|
||||
suffixes.forEach((sfx, i) => {
|
||||
html += '<tr><td class="c">' + (i+1) + '</td><td>' + escLme(sfx) + '</td>';
|
||||
const sv = escLme(lmeStartGet('start', sfx));
|
||||
html += '<td><input type="text" value="' + sv + '" style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="lmeStartSet(\\'start\\',\\'' + escLme(sfx) + '\\',this.value)"></td>';
|
||||
html += cols.map(c => {
|
||||
const val = escLme(lmeStartGet(c.key, sfx));
|
||||
return '<td><input type="text" value="' + val + '" style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="lmeStartSet(\\'' + c.key + '\\',\\'' + escLme(sfx) + '\\',this.value)"></td>';
|
||||
}).join('');
|
||||
html += '</tr>';
|
||||
});
|
||||
$('lmeSetBody').innerHTML = html
|
||||
|| '<tr><td colspan="9" class="c" style="color:#888">还没有骨架:先在「导出」卡添加,后缀会带到这里</td></tr>';
|
||||
}'''
|
||||
new = '''function lmeSetRender(){ // 工料机卡:# /后缀 /起点 固定最前 + 自定义勾选列按序
|
||||
const suffixes = [];
|
||||
(FRAMES||[]).forEach(r => { if(!suffixes.includes(r.suffix)) suffixes.push(r.suffix); });
|
||||
const cols = colSetLoad().filter(c => c.on);
|
||||
$('lmeSetHead').innerHTML = '<th class="c" style="width:56px">#</th><th>后缀</th><th>起点</th>'
|
||||
+ cols.map(c => '<th>' + escLme(c.name) + '</th>').join('');
|
||||
let html = '';
|
||||
suffixes.forEach((sfx, i) => {
|
||||
html += '<tr><td class="c">' + (i+1) + '</td><td>' + escLme(sfx) + '</td>'
|
||||
+ lmeCell('start', sfx)
|
||||
+ cols.map(c => lmeCell(c.key, sfx, true)).join('')
|
||||
+ '</tr>';
|
||||
});
|
||||
$('lmeSetBody').innerHTML = html
|
||||
|| '<tr><td colspan="9" class="c" style="color:#888">还没有骨架:先在「导出」卡添加,后缀会带到这里</td></tr>';
|
||||
}
|
||||
/* 单元格(2026-11-04 主人定):常显值文本(自定义列带圆形「代」按钮=haobtn 同款);
|
||||
双击进入行内编辑——编辑框布满单元格、与单元格边线偏差≤2px(决策 174 通用设计);
|
||||
代按钮占位不算编辑区(点击它不开编辑)。 */
|
||||
function lmeCell(key, sfx, dai){
|
||||
const val = escLme(lmeStartGet(key, sfx));
|
||||
return '<td class="lmetd" data-key="' + escLme(key) + '" data-sfx="' + escLme(sfx) + '"'
|
||||
+ ' ondblclick="lmeCellEdit(this)" title="双击编辑">'
|
||||
+ '<span class="lmeval">' + val + '</span>'
|
||||
+ (dai ? '<span class="haobtn" title="代号清单:插行/删行,点行代入"'
|
||||
+ ' onclick="event.stopPropagation();daiPop(this,\\'' + escLme(key) + '\\',\\'' + escLme(sfx) + '\\')">代</span>' : '')
|
||||
+ '</td>';
|
||||
}
|
||||
function lmeCellEdit(td){
|
||||
if(td.querySelector('input')) return;
|
||||
const key = td.dataset.key, sfx = td.dataset.sfx;
|
||||
const old = lmeStartGet(key, sfx);
|
||||
td.style.position = 'relative';
|
||||
const inp = document.createElement('input');
|
||||
inp.type = 'text'; inp.value = old;
|
||||
inp.style.cssText = 'position:absolute;left:1px;top:1px;right:1px;bottom:1px;width:calc(100% - 2px);'
|
||||
+ 'height:calc(100% - 2px);border:1px solid var(--c2);padding:0 3px;box-sizing:border-box;font-size:12px;z-index:5';
|
||||
td.appendChild(inp);
|
||||
inp.focus(); inp.select();
|
||||
let done = false;
|
||||
const finish = save => {
|
||||
if(done) return; done = true;
|
||||
if(save && inp.value !== old) lmeStartSet(key, sfx, inp.value);
|
||||
lmeSetRender();
|
||||
};
|
||||
inp.onkeydown = e => { if(e.key === 'Enter') finish(true); if(e.key === 'Escape') finish(false); };
|
||||
inp.onblur = () => finish(true);
|
||||
}
|
||||
/* ---- 「代」按钮浮层:该列的代号清单(字段=序号|代号;可插行/删行;点行代入本格)---- */
|
||||
function daiGet(key, sfx){
|
||||
try{ const v = JSON.parse(localStorage.getItem('lme_dai_' + key + '_' + sfx) || 'null');
|
||||
return Array.isArray(v) ? v : []; }catch(e){ return []; }
|
||||
}
|
||||
function daiSet(key, sfx, arr){ try{ localStorage.setItem('lme_dai_' + key + '_' + sfx, JSON.stringify(arr)); }catch(e){} }
|
||||
let DAI_POP = null;
|
||||
function daiClose(){ if(DAI_POP){ DAI_POP.remove(); DAI_POP = null; } }
|
||||
function daiPop(btn, key, sfx){
|
||||
daiClose();
|
||||
const list = daiGet(key, sfx);
|
||||
const p = document.createElement('div');
|
||||
p.className = 'haopop';
|
||||
p.style.cssText = 'width:230px;padding:8px';
|
||||
p.innerHTML = '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">'
|
||||
+ '<b style="color:#123a6b;font-size:12px">代号清单</b>'
|
||||
+ '<a href="javascript:daiAdd(\\'' + escLme(key) + '\\',\\'' + escLme(sfx) + '\\')" style="color:#26405e">+插行</a></div>'
|
||||
+ '<table style="width:100%"><thead><tr>'
|
||||
+ '<th class="c" style="width:44px">序号</th><th>代号</th><th style="width:44px"></th></tr></thead><tbody>'
|
||||
+ (list.length ? list.map((d, i) =>
|
||||
'<tr><td class="c">' + (i+1) + '</td>'
|
||||
+ '<td><input type="text" value="' + escLme(d) + '" style="width:100%;border:1px solid #c9d4e2;padding:1px 4px"'
|
||||
+ ' onchange="daiRename(\\'' + escLme(key) + '\\',\\'' + escLme(sfx) + '\\',' + i + ',this.value)"></td>'
|
||||
+ '<td class="c"><a href="javascript:daiPick(\\'' + escLme(key) + '\\',\\'' + escLme(sfx) + '\\',' + i + ')"'
|
||||
+ ' style="color:#26405e" title="代入本格">代</a> '
|
||||
+ '<a href="javascript:daiDel(\\'' + escLme(key) + '\\',\\'' + escLme(sfx) + '\\',' + i + ')" style="color:#c0392b">×</a></td></tr>').join('')
|
||||
: '<tr><td colspan="3" class="c" style="color:#888">空——点右上「+插行」加代号</td></tr>')
|
||||
+ '</tbody></table>';
|
||||
document.body.appendChild(p);
|
||||
const rc = btn.getBoundingClientRect();
|
||||
p.style.left = Math.max(4, Math.min(rc.left, window.innerWidth - 244)) + 'px';
|
||||
p.style.top = Math.min(rc.bottom + 4, window.innerHeight - 160) + 'px';
|
||||
DAI_POP = p;
|
||||
setTimeout(() => document.addEventListener('mousedown', daiOutside, true), 0);
|
||||
}
|
||||
function daiOutside(e){
|
||||
if(DAI_POP && !DAI_POP.contains(e.target)) { daiClose();
|
||||
document.removeEventListener('mousedown', daiOutside, true); }
|
||||
}
|
||||
function daiAdd(key, sfx){
|
||||
const a = daiGet(key, sfx); a.push(''); daiSet(key, sfx, a);
|
||||
const btn = document.querySelector('.haobtn[title*="代号清单"]');
|
||||
daiClose();
|
||||
if(btn) daiPop(btn, key, sfx);
|
||||
}
|
||||
function daiRename(key, sfx, i, v){
|
||||
const a = daiGet(key, sfx); a[i] = v; daiSet(key, sfx, a);
|
||||
}
|
||||
function daiPick(key, sfx, i){
|
||||
const a = daiGet(key, sfx);
|
||||
if(a[i] === '' ) { $('fmsg').textContent = '代号是空的,先填内容'; return; }
|
||||
lmeStartSet(key, sfx, a[i]);
|
||||
daiClose();
|
||||
lmeSetRender();
|
||||
$('fmsg').textContent = '已代入:' + a[i];
|
||||
}
|
||||
function daiDel(key, sfx, i){
|
||||
const a = daiGet(key, sfx); a.splice(i, 1); daiSet(key, sfx, a);
|
||||
const btn = document.querySelector('.haobtn[title*="代号清单"]');
|
||||
daiClose();
|
||||
if(btn) daiPop(btn, key, sfx);
|
||||
}'''
|
||||
assert old in s, "lmeSetRender NOT FOUND"
|
||||
s = s.replace(old, new)
|
||||
|
||||
# ---- ② 列设置名称列改双击编辑(布满单元格) ----
|
||||
old2 = '''function colRender(){
|
||||
const cs = colSetLoad();
|
||||
$('colBody').innerHTML = cs.map((c, i) =>
|
||||
'<tr><td class="c">' + (i+1) + '</td>'
|
||||
+ '<td><input type="text" value="' + escLme(c.name) + '" placeholder="列名"'
|
||||
+ ' style="width:100%;border:1px solid #c9d4e2;padding:2px 6px"'
|
||||
+ ' onchange="colRename(' + i + ',this.value)"></td>'
|
||||
+ '<td class="c"><input type="checkbox" ' + (c.on?'checked':'') + ' onchange="colToggle(' + i + ',this.checked)"></td>'
|
||||
+ '<td class="c">'
|
||||
+ '<a href="javascript:colMove(' + i + ',-1)" style="color:#26405e">↑</a> '
|
||||
+ '<a href="javascript:colMove(' + i + ',1)" style="color:#26405e">↓</a> '
|
||||
+ '<a href="javascript:colInsert(' + i + ')" style="color:#26405e" title="往后面一行插入新列">插</a> '
|
||||
+ '<a href="javascript:colDel(' + i + ')" style="color:#c0392b">×</a>'
|
||||
+ '</td></tr>').join('');
|
||||
}'''
|
||||
new2 = '''function colRender(){
|
||||
const cs = colSetLoad();
|
||||
$('colBody').innerHTML = cs.map((c, i) =>
|
||||
'<tr><td class="c">' + (i+1) + '</td>'
|
||||
+ '<td class="colnm" data-i="' + i + '" ondblclick="colNameEdit(this)" title="双击编辑列名">'
|
||||
+ '<span class="lmeval">' + escLme(c.name) + '</span></td>'
|
||||
+ '<td class="c"><input type="checkbox" ' + (c.on?'checked':'') + ' onchange="colToggle(' + i + ',this.checked)"></td>'
|
||||
+ '<td class="c">'
|
||||
+ '<a href="javascript:colMove(' + i + ',-1)" style="color:#26405e">↑</a> '
|
||||
+ '<a href="javascript:colMove(' + i + ',1)" style="color:#26405e">↓</a> '
|
||||
+ '<a href="javascript:colInsert(' + i + ')" style="color:#26405e" title="往后面一行插入新列">插</a> '
|
||||
+ '<a href="javascript:colDel(' + i + ')" style="color:#c0392b">×</a>'
|
||||
+ '</td></tr>').join('');
|
||||
}
|
||||
function colNameEdit(td){ // 列名:双击编辑(决策174 布满单元格)
|
||||
if(td.querySelector('input')) return;
|
||||
const i = +td.dataset.i;
|
||||
const cs = colSetLoad();
|
||||
const old = cs[i].name;
|
||||
td.style.position = 'relative';
|
||||
const inp = document.createElement('input');
|
||||
inp.type = 'text'; inp.value = old;
|
||||
inp.style.cssText = 'position:absolute;left:1px;top:1px;right:1px;bottom:1px;width:calc(100% - 2px);'
|
||||
+ 'height:calc(100% - 2px);border:1px solid var(--c2);padding:0 3px;box-sizing:border-box;font-size:12px;z-index:5';
|
||||
td.appendChild(inp);
|
||||
inp.focus(); inp.select();
|
||||
let done = false;
|
||||
const finish = save => {
|
||||
if(done) return; done = true;
|
||||
if(save && inp.value !== old){ cs[i].name = inp.value; colSetSave(cs); }
|
||||
colSaveRender();
|
||||
};
|
||||
inp.onkeydown = e => { if(e.key === 'Enter') finish(true); if(e.key === 'Escape') finish(false); };
|
||||
inp.onblur = () => finish(true);
|
||||
}'''
|
||||
assert old2 in s, "colRender NOT FOUND"
|
||||
s = s.replace(old2, new2)
|
||||
|
||||
# ---- ③ .lmetd/.lmeval/.colnm 样式(一次性注入 style 块尾部) ----
|
||||
old3 = '''/* 统一另存为(2026-11-03 主人定「导出一律另存为方式」):'''
|
||||
new3 = '''/* 工料机卡单元格(2026-11-04):值+圆形代按钮;双击编辑(决策174 布满) */
|
||||
.lmetd{position:relative;cursor:default;min-width:90px}
|
||||
.lmetd .lmeval{white-space:pre-wrap}
|
||||
.lmetd .haobtn{float:right;margin-left:6px}
|
||||
.colnm{position:relative;cursor:default;min-width:110px}
|
||||
/* 统一另存为(2026-11-03 主人定「导出一律另存为方式」):'''
|
||||
assert old3 in s, "css anchor NOT FOUND"
|
||||
s = s.replace(old3, new3)
|
||||
|
||||
io.open(p, "w", encoding="utf-8").write(s)
|
||||
print("surgery v3 done")
|
||||
Reference in New Issue
Block a user