重新按英文命名,修改成相对路径

This commit is contained in:
lianjianwei2024
2026-10-11 10:52:01 +08:00
parent eea5d511dc
commit 9bb23ac13b
64 changed files with 913 additions and 1427 deletions

View File

@@ -0,0 +1,65 @@
# -*- 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()

View File

@@ -0,0 +1,693 @@
# -*- coding: utf-8 -*-
"""
M1 原型:把「后台需要导入的项目」里的 15 个真实文件解析入库,并产出导入报告。
规则全部来自《造价审核软件开发方案》§4.5 / §4.6 / §4.7:
- 按文件头 + 根节点分派(不看扩展名)
- 清单:不导入 单位=项
- 工料机:不导入 组合类(有下一级 / Kind=6)
- 只保留需要的字段,其余丢弃
"""
import io, os, re, sys, time, json, hashlib, zipfile, sqlite3
import match # 比对引擎:字集键 bill_setkey/lme_setkey 唯一实现(决策 27,口径不分叉)
from xml.etree import ElementTree as ET
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
_PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核
SRC = os.path.join(os.path.dirname(_PRJ), "后台需要导入的项目") # 在项目目录**之外**;拷走主目录后可能不存在
DB = os.path.join(_PRJ, "data", "history.db")
SCHEMA = os.path.join(_PRJ, "app", "store", "schema.sql")
REPORT = os.path.join(_PRJ, "data", "导入报告.md")
REGION = ("广东省", "珠海市", "香洲区")
# ---------- 解析器版本(2026-10-02 新增)----------
# 干什么用:每次导入把本常量写进 batches.x_parser_ver;服务启动时拿它跟库里的值比,
# 不一致就说明「这批数据是用旧口径解析的」,后台顶部提示需要重导,避免拿旧结构的数据做比对。
#
# ⚠️ 什么时候必须改这个号:只要改了 parse_std / save 的**入库口径**(增删改字段、
# 改过滤规则、改层级记账方式、修了会导致旧数据错/缺的 bug),就把号往上加一位。
# 只改界面 / 只改查询,不动入库结构 —— 不用改号,否则会白白提示全库重导。
# 格式建议 YYYY.MM.DD-N(同一天多次改口径就 +1)。
PARSER_VER = "2026.10.10-2" # 2026.10.10-2:清单序号 x_seq 改**每单位工程从 1 起**(跨工程连号是错口径,老批次需重导)
# 2026.10.10-1:clean_attr 剥号加小数点护栏(x_attr_norm 口径变,老批次需重导)
# 2026.10.08-1:清单节点开始采集源文件备注 Remark(老批次需重导才有)
# ---------- 归一化 ----------
def norm(s):
s = (s or "").strip()
s = s.replace("(", "(").replace(")", ")").replace(",", ",").replace(";", ";")
s = s.replace("×", "*").replace("*", "*").replace("X", "*").replace("x", "*")
s = s.replace("㎡", "m2").replace("m²", "m2").replace("m2", "m2")
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 f(x):
try:
return float(x)
except Exception:
return None
# ---------- 特征清洗(提高"精确"命中率的关键)----------
STOPWORDS = [
"另以上工作内容及未提及部分详见相关规范", "招标文件及图纸", "详见图纸", "详见设计图纸",
"满足设计要求", "满足设计", "按规范要求", "符合规范要求", "综合考虑", "详见相关规范",
"其他", "另行考虑", "投标人自行考虑", "按实结算",
]
FIELD_PREFIX = ["规格型号", "项目名称", "名称", "规格", "型号", "参数", "材质", "品牌",
"备注", "要求", "做法", "部位", "内容", "品种", "类别"]
def clean_attr(s):
"""剥掉项目特征里的"外壳":序号、字段名前缀、标点、无信息套话,只留实质内容。"""
t = norm(s)
for w in STOPWORDS:
t = t.replace(norm(w), "")
# ⚠️ 2026-10-10:后顾加小数点护栏(半角.全角.)—— 否则 "2.5、" 的 "5、" 会被当编号剥掉,
# 键被剁成 "…X2." / "C200…" 碎块(前河东路371 轻钢屋面实测)
t = re.sub(r"(?<![0-9..])\d+[、)).]", "", t) # 1、 2) 3) 1. —— 中文编号分隔
t = re.sub(r"(?<![0-9..])\d+\.(?!\d)", "", t) # 2. —— ASCII 点号编号(排除 M7.5/2.5 这类小数)
t = re.sub(r"[\u2460-\u2473]", "", t) # ①②③
for f in FIELD_PREFIX: # 长词优先
t = re.sub(r"(^|[;\uff1b,\uff0c])" + f + r"[:\uff1a]", "", t)
t = re.sub(r"[:\uff1a\u3001\uff0c,\uff1b;\u3002.()\uff08\uff09\[\]]", "", t)
return t
# ---------- 分派 ----------
def sniff(path):
with io.open(path, "rb") as fh:
head = fh.read(4)
if head[:4] == b"PK\x03\x04":
return "zip"
if head[:2] == b"\x88\x7d":
return "encrypted"
if head[:2] in (b"<?", b"\xef\xbb"):
return "xml"
return "unknown"
# ⚠️ 2026-10-01 删除 root_of_xml_text():全项目无调用的死代码(原为 xml 入口服务)
COST_KEYS = ("Construction", "DivisionalAndElementalWorks", "Preliminaries",
"CostForHSE", "SundryCosts", "Tax")
def _cost_of(attrib):
"""从 SummaryOfCost 的属性里取造价构成(2026-09-30 加,单位工程「汇总分析」用)
六个口径都是造价文件里的标准叫法,缺哪个留 NULL —— 别拿别的数去凑,显示时会写「—」。
"""
return {k: f(attrib.get(k)) for k in COST_KEYS}
def proj_total(root):
"""取「工程总造价」(2026-09-30 加,落地页「项目总造价」列用)
三种写法在不同格式里出现的时机不一样,实测:
· cos4 横琴 —— 根 ConstructionProject **没有** Total 属性,只有 SummaryOfCost.Total
· XML2.0/ESCC2 —— 根 Projects 自带 Total(广州一建 5,972,470.72,与 CostItem ZZJ 一致)
· .COS 三溪 —— Project.xml 根是 ConstructionProject,靠 SummaryOfCost.Total
所以按「根 Total → SummaryOfCost.Total → CostItem[ZZJ]」三级兜底取,
**不要用清单合价求和代替** —— 那样会漏掉税金/其他项目/安全生产费,横琴实测少 610 万(17.6%)。
"""
v = f(root.attrib.get("Total"))
if v:
return v
for e in root.iter("SummaryOfCost"):
v = f(e.attrib.get("Total"))
if v:
return v
for e in root.iter("CostItem"):
if (e.attrib.get("Code") or "").strip().upper() == "ZZJ": # 工程总造价(小写)
v = f(e.attrib.get("Total"))
if v:
return v
return None
# ---------- 解析:2025 标准(ZIP 内 ConstructionProject / UnitWorks)----------
def parse_std(path, out):
out.setdefault("lme_res", {}) # 机械台班 / 配合比的**下一级组成**:编码 → [(子编码, 含量)]
z = zipfile.ZipFile(path)
names = [n for n in z.namelist() if n.lower().endswith(".xml")]
# 项目信息
proj = None
for n in names:
if os.path.basename(n).lower() == "project.xml":
proj = n
break
if proj:
r = ET.fromstring(z.read(proj).decode("utf-8", errors="replace"))
out["proj_name"] = r.attrib.get("Name", "")
out["file_kind"] = f(r.attrib.get("FileKind"))
out["bulid_unit"] = r.attrib.get("BulidUnit", "")
out["total"] = proj_total(r) # 2026-09-30:根节点常无 Total,改三级兜底
out["info"] = {k: v for k, v in r.attrib.items() if (v or "").strip() != ""}
# 2026-10-07 主人定:项目特征信息**只从 Project.xml 收**(根节点下的 AttrInfoItem /
# AddiInfoItem 编制信息条目)。此前从各单位工程 XML 收——那是同一表单的逐工程拷贝,
# 「项目级」卡片理应取项目级文件。名称去重、最多 60 条(口径不变)。
for e in r.iter():
if not e.tag.endswith("InfoItem"):
continue
_nm = (e.attrib.get("Name") or e.attrib.get("Code") or "").strip()
if not _nm:
continue
_f = out.setdefault("feat", [])
if all(x[0] != _nm for x in _f) and len(_f) < 60:
_f.append((_nm, e.attrib.get("Value") or ""))
# 2026-10-07:Project.xml 里还有一份**项目级完整工料机汇总**(横琴 730 条,含
# 人工费等费用科目、-0001 换算编码)—— 这是消耗量编码反查名称的最全兜底,
# 先收进来;各单位工程自己的汇总随后覆盖同编码(单位工程级更贴实际使用)。
# 同时**原样**留一份项目级汇总(含项目级合计消耗量/单价)进 lme_proj ——
# 「原数据 → 工料机汇总」的项目级直接读它(与原版软件同源)。
for sm in r.iter("LabourMaterialsEquipmentsMachinesSummary"):
_c = (sm.attrib.get("Number") or "").strip()
if not _c:
continue
out.setdefault("lme_lib", {}).setdefault(_c, [
(sm.attrib.get("Name") or "").strip(),
(sm.attrib.get("Specification") or "").strip(),
(sm.attrib.get("Unit") or "").strip(),
f(sm.attrib.get("Kind")),
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice"))])
out.setdefault("lme_proj", {}).setdefault(_c, [
(sm.attrib.get("Name") or "").strip(),
(sm.attrib.get("Specification") or "").strip(),
(sm.attrib.get("Unit") or "").strip(),
f(sm.attrib.get("Kind")),
f(sm.attrib.get("Quantity")),
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice"))])
# 单项工程层(2026-09-30):两种新格式节点名不同,都试一遍,谁有取谁。
# 记下每个单项工程下挂哪些单位工程编号 —— 靠它把单位工程归到单项工程下。
for tag in ("DivisionalAndElementalProject", "SectionalWorks"):
for s in r.iter(tag):
nums = [u.attrib.get("Number") for u in s.iter("UnitWorks")]
if not nums:
continue
nm = (s.attrib.get("Name") or "").strip()
# SectionalWorks 常常只有 1 个且名字就是项目名 —— 那不是单项工程,是项目本身,跳过
if tag == "SectionalWorks" and len(list(r.iter(tag))) == 1 \
and nm == out["proj_name"]:
continue
out.setdefault("sections", []).append(
{"number": s.attrib.get("Number"), "name": nm,
"total": f(s.attrib.get("Total")), "ratios": f(s.attrib.get("Ratios")),
"uw_nums": [x for x in nums if x]})
if out.get("sections"):
break
# 清单记账(原先写在 end 事件里 —— 见下方 ★P0 说明)
def _push_bill(a):
out["bill_raw"] += 1
# 2026-10-07 主人定:**导入不过滤**,与工作台同口径收完整集——两侧唯一差异只剩
# 「进哪个库」(会话库 / 批次库)。此前后台导入会跳过 单位=项 / 单价 0或空 的清单,
# 是两侧清单条数不一致的根因。bill_skip / bill_skip_zero 计数器保留只为兼容
# 导入日志与接口响应结构,恒为 0。
out["bills"].append((
a.get("Number", ""), a.get("Name", ""), a.get("Attr", ""),
(a.get("Unit") or "").strip(), f(a.get("Quantity")), f(a.get("Price")),
f(a.get("Total")), (a.get("Remark") or "").strip()))
out["cur_bill"] = len(out["bills"]) - 1
out.setdefault("bill_uw", []).append(out.get("cur_uw", -1))
out.setdefault("bill_kind", []).append("prelim" if out.get("in_prelim") else None)
out.setdefault("bill_div", []).append(out.get("cur_div")) # 归属分部
# 措施项目条目(UnitWorksPreliminaryWorkElement)
# ★ 2026-09-29 决策 17:措施条目**进** bills(Kind='prelim'),它的 Norm 挂在自己名下,
# 这样 s_norms 里再也不会出现 bill_id=NULL 的孤儿定额(A 项的数据结构问题一并解决)。
# 「要不要出现在 C 区」由**视图层**按 单位=项 / 无定额 / 单价=0 三条规则筛选,
# 数据本身保留完整 —— 将来导出全量措施还能取回来。
def _push_prelim(a):
out["prelim_raw"] = out.get("prelim_raw", 0) + 1
out["bills"].append((
a.get("Number", ""), a.get("Name", ""), a.get("Attr", ""),
(a.get("Unit") or "").strip(), f(a.get("Quantity")),
f(a.get("Price")), f(a.get("Total")), (a.get("Remark") or "").strip()))
out["cur_bill"] = len(out["bills"]) - 1
out.setdefault("bill_uw", []).append(out.get("cur_uw", -1))
out.setdefault("bill_kind", []).append("prelim")
out.setdefault("bill_div", []).append(out.get("cur_div")) # 措施清单归措施分部
# ⚠️ 2026-09-30:Project.xml 里也埋着一份 UnitWorks(那是汇总用的**引用节点**,不是真实单位工程)。
# 照单全收会让单位工程数量翻倍 —— 横琴 40 实为 20、三溪 28 实为 14,还连带一半没有造价构成。
# 项目信息上面已单独解析过,这里跳过它;只有包内**只剩** Project.xml 时才退化回去解析。
unit_files = [n for n in names if n != proj] or names
for n in unit_files:
txt = z.read(n).decode("utf-8", errors="replace")
# 每个 xml 文件彼此独立:本文件里没有单位工程的,不许继承上一个文件的归属
out["cur_uw"] = -1
out["cur_bill"] = -1
out["cur_div"] = None
out["div_stack"] = []
out["in_prelim"] = False
# ⚠️ 2026-09-29 修:UnitWorks 是**容器**标签(每个数据 xml 的根元素就是它),
# 它下面所有 WorkElement / Norm 的 end 事件都排在它自己 end 之前。
# 只监听 end 的话,cur_uw 要到整个文件扫完才被赋值 —— 结果是每条清单挂的
# 都是「上一个 xml 的单位工程」(整体错位一个文件),第一个文件的清单则全为 NULL。
# 所以必须连 start 一起监听:一进 UnitWorks 就把 cur_uw 定下来。
#
# ★ P0(2026-09-29 二修):**cur_bill 完全是同一个坑,却漏了没修**。
# WorkElement 也是容器标签,Norm 是它的子元素 —— 子元素的 end **必然先于**父元素。
# 在 WorkElement 的 end 才给 cur_bill 赋值 ⇒ 读到 Norm 时 cur_bill 还停在**上一条**清单上,
# 实测横琴 1077 条清单定额里 **1076 条错位到下一条清单**、1 条丢成 NULL。
# 同理 Preliminaries 排在 DivisionalAndElementalWorks 之后且从不重置 cur_bill,
# 于是 131 条措施项目定额全落到「该单位工程最后一条清单」头上。
# 修法与 cur_uw 一致:容器在 **start** 时就记账。
# 进入措施项目分支时把 cur_bill 置 -1 —— 措施定额**不属于任何清单**,
# 绝不能拿最后一条清单去接(那才是原来最致命的错挂)。
for event, el in ET.iterparse(io.StringIO(txt), events=("start", "end")):
if event == "start":
if el.tag == "UnitWorks" and (el.attrib.get("Name") or "").strip():
out["uw"].append((el.attrib.get("Number", ""), el.attrib.get("Name", ""),
f(el.attrib.get("Total"))))
out["cur_uw"] = len(out["uw"]) - 1
# 2026-10-01 加:专业(UnitWorks 元素的 Specialty 属性)——原数据要显示「专业」列。
# 用独立字典存,不改 out["uw"] 的元组长度(多处按 (num,nm,total) 解包)。
out.setdefault("uw_spec", {})[out["cur_uw"]] = el.attrib.get("Specialty")
# 用栈记 UnitWorks 层级:SummaryOfCost 归栈顶那个,嵌套时不会张冠李戴
out.setdefault("uw_stack", []).append(len(out["uw"]) - 1)
# 分部属于单位工程:换单位工程就把分部上下文清掉
out["div_stack"] = []
out["cur_div"] = None
elif el.tag == "WorkElement":
_push_bill(el.attrib) # ★ 容器在 start 就记账
out["cur_norm"] = -1 # 进清单:清掉定额上下文
elif el.tag == "Norm":
# 定额在 start 就记账:它下面的工料机消耗量要挂到 len(norms)(即它将占的下标)
out["cur_norm"] = len(out["norms"])
elif el.tag in ("DivisionalWorks", "PreliminaryDivisionalWorks"):
# 2026-09-30:分部层 —— 分部分项与措施项目**各有一套**,而且都可能嵌套。
# 「原数据」标签里那张表的「分部」行、以及 ± 目录树全靠它。
_st = out.setdefault("div_stack", [])
_parent = _st[-1] if _st else None
_idx = len(out.setdefault("divides", []))
out["divides"].append({
"uw": out.get("cur_uw", -1), "parent": _parent,
# kind 按**上下文**判断:在 Preliminaries 分支里就是措施分部
# (三溪 .COS 的分部标签也叫 DivisionalWorks,只看标签名会误判成分部分项)
"kind": "prelim" if out.get("in_prelim") else "item",
"number": el.attrib.get("Number"), "name": el.attrib.get("Name"),
"total": f(el.attrib.get("Total")), "code": el.attrib.get("Code"),
"seq": _idx})
_st.append(_idx)
out["cur_div"] = _idx
elif el.tag == "LabourMaterialsEquipmentsMachinesSummary":
# 2026-10-02:进这条工料机汇总 → 它下面的 Element 是**台班的组成**(下一级)。
# 必须在 start 记账:等它自己的 end 再读,子元素属性已被 clear 清掉了。
# ⚠️ 只收**第一份**:同一个台班在每个单位工程的汇总里都重复声明一遍组成,
# 内容一样(后面几份还带 -0001 换算后缀),全收会放大十几倍。
_pc = (el.attrib.get("Number") or "").strip()
out["cur_lme"] = "" if (not _pc or _pc in out.setdefault("lme_res", {})) else _pc
# 顺手记下 **这条工料机自己的名称**(含被排除的费用科目):
# 台班的组成子项在源文件里只有编码,名称要靠这张表反查(见 lme_res.name)。
if _pc and (el.attrib.get("Name") or "").strip():
out.setdefault("lme_name", {})[_pc] = el.attrib.get("Name", "").strip()
# 2026-10-07:整条汇总(名称/规格/单位/类别/单价)原样进 lme_lib ——
# lmes 有同名去重与费用科目过滤,消耗量里引用的编码(人工费、-0001 换算…)
# 在 lmes 里查不到,名称规格从这里兜底。各单位工程的记录覆盖 Project.xml 的。
if _pc:
out.setdefault("lme_lib", {})[_pc] = [
(el.attrib.get("Name") or "").strip(),
(el.attrib.get("Specification") or "").strip(),
(el.attrib.get("Unit") or "").strip(),
f(el.attrib.get("Kind")),
f(el.attrib.get("NoTaxPrice")), f(el.attrib.get("TaxPrice"))]
elif el.tag == "UnitWorksPreliminaryWorkElement":
# 存旧游标,结束时恢复(万一措施条目自身嵌套,子条目的定额不会漏挂到父上)
out.setdefault("prel_stack", []).append(out["cur_bill"])
_push_prelim(el.attrib)
elif el.tag == "Preliminaries":
out["cur_bill"] = -1 # ★ 措施项目分支:不继承任何清单
# 2026-09-30:**用上下文判断措施,不能用标签名** ——
# 横琴 cos4 的措施条目是 UnitWorksPreliminaryWorkElement(直接挂,无分部)
# 三溪 .COS 的措施是 DivisionalWorks → WorkElement(有分部,清单标签与分部分项相同)
# 只认标签名会把三溪的措施整段当成「分部分项」,措施数永远是 0。
out["in_prelim"] = True
continue
tag = el.tag
a = el.attrib
if tag == "Norm":
# 2026-09-29:补 Quantity / Total(源文件里确实有这两个属性,此前只取了 Price)
# 元组顺序:idx, 编码, 名称, 单位, 工程量, 单价, 合价
out["norms"].append((out["cur_bill"], a.get("Number", ""), a.get("Name", ""),
a.get("Unit", ""), f(a.get("Quantity")),
f(a.get("Price")), f(a.get("Total"))))
out["cur_norm"] = -1 # 出这条定额:后面的工料机不再算它的消耗
elif tag == "LabourMaterialsEquipmentsMachinesElement":
# 2026-09-30:定额消耗量。**必须在自己的 end 事件里读属性** ——
# 循环末尾的 el.clear() 会把 attrib 一起清掉,等父元素(Norm)end 再 iter 只能拿到空属性。
# cur_norm 由 Norm 的 start 事件记账;清单直接挂的工料机 cur_norm=-1,跳过。
_n = out.get("cur_norm", -1)
_p = out.get("cur_lme", "")
_code = (a.get("Number") or "").strip()
if _p:
# 2026-10-02:在 Summary 里 → 这是**台班 / 配合比的组成**(下一级)。
# 同样只能在自己的 end 里读属性(见上方 norm_res 的那条坑)。
if _code:
out.setdefault("lme_res", {}).setdefault(_p, []).append((_code, f(a.get("Quantity"))))
elif _n >= 0 and _code:
out.setdefault("norm_res", []).append((_n, _code, f(a.get("Quantity"))))
elif tag == "SummaryOfCost":
# 2026-09-30:单位工程造价构成。同样因为 clear 会清空 attrib,只能在自己的 end 里读。
# 归栈顶那个 UnitWorks(嵌套时内层优先),且每个单位工程只认它的第一个 SummaryOfCost。
_st = out.get("uw_stack") or []
if _st:
_k = _st[-1]
_c = out.setdefault("uw_cost", {})
if _k not in _c:
_c[_k] = _cost_of(a)
elif tag == "UnitWorks":
_st = out.get("uw_stack") or []
if _st:
_st.pop()
elif tag in ("DivisionalWorks", "PreliminaryDivisionalWorks"):
_d = out.get("div_stack") or []
if _d:
_d.pop()
out["cur_div"] = _d[-1] if _d else None
elif tag == "UnitWorksPreliminaryWorkElement":
st = out.get("prel_stack") or []
out["cur_bill"] = st.pop() if st else -1
elif tag == "Preliminaries":
out["cur_bill"] = -1 # 出措施分支:后面的 Sundry 等不许继承措施清单
out["in_prelim"] = False
elif tag == "LabourMaterialsEquipmentsMachinesSummary":
out["lme_raw"] += 1
kids = list(el)
# 组合类判定:① Kind=6 配合比(砂浆、混凝土)② 有"非空"的组成子节点
# 注意:老格式的 ResElements 是空容器(100% 出现但里面没有条目),
# 只判断"存在子节点"会把全部工料机误杀 —— 必须判断子节点里有没有条目
n_sub = sum(1 for k in kids if k.tag == "LabourMaterialsEquipmentsMachinesElement")
kind = str(a.get("Kind"))
# 2026-10-02 变更:**组合类改为入库**(Kind 6 配合比 / Kind 7 机具台班 / 单位=台班),
# 「项目工料机」汇总改为**取数时**按 Kind 排除(见 api_server._lme_rows)——口径不变。
# 为什么要入库:不入库 ⇒ 「子目工料机」面板里台班机械只剩一个编码(名称 join 不到),
# 更无从展开它的组成(人工 / 燃料 / 折旧…)—— 主人 2026-10-02 明确要求能展开。
# 费用科目(折旧费 / 维护费 / 人工费…)2026-10-07 起也**照收入库**:
# 主人定「导入不过滤」,与工作台同口径,原 FEE_ITEMS 过滤随之废除
# (工作台「项目工料机」本就原样显示 s_lmes,含费用科目行——两侧恰好一致)。
out["lmes"].append((
a.get("Number", ""), a.get("Name", ""), a.get("Specification", ""),
a.get("Unit", ""), f(a.get("NoTaxPrice")), f(a.get("TaxRate")),
f(a.get("TaxPrice")), f(a.get("Quantity")), str(a.get("Kind") or "")))
out["cur_lme"] = "" # 出这条汇总:后面的 Element 不再算它的组成
el.clear()
return "2025标准"
# ---------- 解析:老格式(Projects)----------
# ⚠️ 2026-10-01 删除 parse_old()(原 110 行):
# 主人定「不再支持 xml 格式,重点做 cos4 / cos」,而 parse_old 是**唯一的 xml 入口**
# (cos4 / .COS 都是 zip 包,走 parse_std;parse_old 只处理散装 xml / ESCC2.0 / 投标报价 XML2.0)。
# ⚠️ 注意:parse_std 内部仍大量使用 ElementTree —— cos4 是 zip 包,里面装的就是 xml,
# 所以 `from xml.etree import ElementTree as ET` **必须保留**,别一并删掉。
# 已导入的 xml 批次也已从库中清除(tools/purge_batches.py --by-ext .xml)。
# 将来若要恢复:git 历史里有,照 parse_std 的同款容器记账规则重写即可。
def save(con, kind, out, fn, sha, mtime, meta=None):
"""
meta = {name, province, city, district, period_from, period_to, bulid_unit, file_kind}
元数据全部来自导入弹框(你填的);不传时退回旧行为(文件名 + 默认地区 + 文件时间)
"""
ym = int(time.strftime("%Y", time.localtime(mtime))) * 12 + int(time.strftime("%m", time.localtime(mtime)))
if meta:
name = meta.get("name") or out["proj_name"] or os.path.splitext(fn)[0]
prov = meta.get("province") or REGION[0]
city = meta.get("city") or REGION[1]
dist = meta.get("district") or REGION[2]
p_from = meta.get("period_from") or ym
p_to = meta.get("period_to") or p_from
bu = meta.get("bulid_unit") or out["bulid_unit"] or ""
fk = meta.get("file_kind")
if fk in (None, ""):
fk = out["file_kind"]
else:
name, prov, city, dist = out["proj_name"] or os.path.splitext(fn)[0], REGION[0], REGION[1], REGION[2]
p_from = p_to = ym
bu = out["bulid_unit"] or ""
fk = out["file_kind"]
cur = con.cursor()
# 项目级两张卡:与 session_job 同格式落库,保证前后台「原数据」一致
# (x_feat 2026-10-02 补齐;x_info 2026-10-07 补齐——此前解析出了 out["info"] 但没写进 batches,
# 后台「基本信息」卡恒为空,工作台却有数据,就是这个漏)
_info = out.get("info") or {}
info_json = json.dumps(_info, ensure_ascii=False) if _info else None
_feat = out.get("feat") or []
feat_json = json.dumps([{"n": n, "v": v} for n, v in _feat], ensure_ascii=False) if _feat else None
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_parser_ver, x_info, x_feat) VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?)""",
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"], 0, 0,
time.strftime("%Y-%m-%d %H:%M:%S"), sha, "", PARSER_VER, info_json, feat_json))
bid = cur.lastrowid
# ===== 2026-10-01:与工作台会话库对齐,后台批次库同样**存层级 + 工程量** =====
# ⚠️ 此处推翻了原「历史库不存工程量 / 单位工程表已删除、清单不分层」两条旧口径:
# 旧口径下后台清单缺「工程量/合价/单位工程名称」三列、且做不了「原数据」标签,
# 与工作台功能不一致。现按主人 2026-10-01 定的「两库功能一致」改写。
# 写入逻辑照搬 session_job.open_project()(两侧共用 parse_std,out 结构相同)。
# 单项工程(按 (名称, 编号, 单位工程编号组) 去重,防一次导入多文件重复建)
num2sec, sec_built = {}, set()
for s in (out.get("sections") or []):
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 sections(batch_id, Number, Name, Total, Ratios)"
" VALUES(?,?,?,?,?)",
(bid, s.get("number"), s.get("name"), s.get("total"), s.get("ratios")))
for num in (s.get("uw_nums") or []):
num2sec[num] = cur.lastrowid
# 单位工程(清单的 bill_uw 存的是 out["uw"] 下标,靠 uw_ids 换成真实 id)
uw_ids = []
for i, (num, nm, total) in enumerate(out["uw"]):
c = (out.get("uw_cost") or {}).get(i) or {}
cur.execute("""INSERT INTO unit_works(batch_id, section_id, Number, Name, Specialty, Total,
Construction, DivisionalAndElementalWorks, Preliminaries,
CostForHSE, SundryCosts, Tax)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, num2sec.get(num), num, nm, (out.get("uw_spec") or {}).get(i),
total, c.get("Construction"),
c.get("DivisionalAndElementalWorks"), c.get("Preliminaries"),
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax")))
uw_ids.append(cur.lastrowid)
# 分部(必须排在清单之前:清单要挂 div_id)
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 divides(batch_id, uw_id, parent_id, Kind,
Number, Name, Total, Code, x_seq)
VALUES(?,?,?,?,?,?,?,?,?)""",
(bid, _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)
seen_bill = set()
n_bill = 0
bill_ids = []
buw = out.get("bill_uw") or []
bkd = out.get("bill_kind") or []
bdv = out.get("bill_div") or []
# 序号两套(分部分项 / 措施项目),**每个单位工程各自从 1 起**
# (2026-10-10 主人定:原数据序号=单位工程内序号,跨工程连号(如 164)是错口径,与会话库同口径)
seq = {"d": 0, "p": 0}
_seq_uw = None
# bills 元组第 8 位 = 源文件备注(2026-10-08 主人定:只显示在「原数据」备注栏)
for i, (num, name, attr, unit, qty, price, total, srk) in enumerate(out["bills"]):
# 决策 27(2026-10-10):编码只取前 9 位参与哈希(后 3 位是项目内顺序码,无对比意义)
num9 = norm(num)[:9]
h = md5(num9, name, unit) # 精确键:编码9位+名称+单位(特征写法太杂,不参与)
hs = md5(num9, unit)
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
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 bills(batch_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_setkey, x_seq)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, divid, num, name, attr, unit, qty, price, total, kb, srk,
norm(name), clean_attr(attr), norm(unit), h, hs, match.bill_setkey(name, unit), xseq))
n_bill += 1
bill_ids.append(cur.lastrowid)
seen_bill.add(h)
# 定额(补 Quantity / Total,与 s_norms 对齐)
norm_ids = []
for idx, num, name, unit, qty, price, total in out["norms"]:
bid2 = bill_ids[idx] if 0 <= idx < len(bill_ids) else None
cur.execute("""INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total)
VALUES(?,?,?,?,?,?,?)""",
(bid2, num, name, unit, qty, price, total))
norm_ids.append(cur.lastrowid)
# 定额消耗工料机(对应 s_norm_res)
for nidx, code, q in (out.get("norm_res") or []):
nid = norm_ids[nidx] if 0 <= nidx < len(norm_ids) else None
cur.execute("INSERT INTO norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
(nid, code, q))
n_lme = 0
n_lme_errs = 0
for num, name, spec, unit, ntp, tax, tp, qty, _kind in out["lmes"]:
h = md5(name, spec, unit)
try:
cur.execute("""INSERT OR IGNORE INTO lmes(batch_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, x_setkey)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, num, name, spec, unit, qty, ntp, tax, tp, _kind,
norm(name), norm(spec), norm(unit), h, md5(name, unit),
match.lme_setkey(name, spec, unit)))
n_lme += cur.rowcount
except Exception:
n_lme_errs += 1
# 机械台班 / 配合比的下一级组成(lme_res)
n_lres = 0
n_lres_errs = 0
_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
# 子项名称:源文件汇总节点上记的那份;带 -0001 换算后缀的也认(去掉后缀再查一次)
_nm = _lname.get(code) or _lname.get(code.split("-")[0]) or None
try:
cur.execute("""INSERT INTO lme_res(batch_id, p_code, res_code, qty, seq, name)
VALUES(?,?,?,?,?,?)""", (bid, pcode, code, q, i, _nm))
n_lres += cur.rowcount
except Exception:
n_lres_errs += 1
# ⚠️ 2026-10-06:此前静默吞掉入库异常,导入「成功」却缺行,事后极难排查。
# 现在至少打印到日志(launch.log),不再无声无息丢数据。
if n_lme_errs or n_lres_errs:
print("导入警告(batch=%s):工料机 %d 条、台班组成 %d 条入库失败" % (bid, n_lme_errs, n_lres_errs),
flush=True)
# 项目级工料机资源库(2026-10-07):源文件汇总节点全集,名称/规格兜底用
n_lib = 0
n_lib_errs = 0
for _c, (_nm, _sp, _un, _kd, _ntp, _taxp) in (out.get("lme_lib") or {}).items():
try:
cur.execute("""INSERT OR IGNORE INTO lme_lib(batch_id, code, name, spec, unit, kind, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?)""", (bid, _c, _nm, _sp, _un, _kd, _ntp, _taxp))
n_lib += cur.rowcount
except Exception as e:
n_lib_errs += 1
print("资源库入库失败 %s:%s" % (_c, e), flush=True)
if n_lib or n_lib_errs:
cur.execute("SELECT COUNT(*) FROM lme_lib WHERE batch_id=?", (bid,))
print("批次 %s 工料机资源库:%d 条(全库 %s 条,失败 %d)" % (bid, n_lib, cur.fetchone()[0], n_lib_errs), flush=True)
# 项目级工料机汇总(2026-10-07):Project.xml 原样入库,「原数据 → 工料机汇总」项目级读它
n_proj = 0
for _c, (_nm, _sp, _un, _kd, _q, _ntp, _taxp) in (out.get("lme_proj") or {}).items():
try:
cur.execute("""INSERT OR IGNORE INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?,?)""", (bid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp))
n_proj += cur.rowcount
except Exception as e:
print("项目级汇总入库失败 %s:%s" % (_c, e), flush=True)
if n_proj:
print("批次 %s 项目级工料机汇总:%d 条" % (bid, n_proj), flush=True)
cur.execute("UPDATE batches SET x_rows_bill=?, x_rows_lme=? WHERE id=?", (n_bill, n_lme, bid))
return bid, n_bill, n_lme
# ---------- 主流程 ----------
def main():
# ⚠️ 2026-10-06 护栏:本入口连的是**生产库** data/history.db,且会全量清空重导。
# 生产导入应走后台 API(/api/admin/import),这个原型脚本误跑会毁掉底库。
# 必须显式 --yes 才放行,否则只打印警告退出。
if "--yes" not in sys.argv:
print("危险:本脚本会清空 %s 并全量重导。" % DB, flush=True)
print("生产导入请用后台「导入」按钮;确认要跑原型批量导入请加 --yes。", flush=True)
return 1
con = sqlite3.connect(DB)
con.executescript(io.open(SCHEMA, encoding="utf-8").read())
# 每次全量重跑:先清空(避免重复插入)
con.executescript("""DELETE FROM bills; DELETE FROM norms; DELETE FROM lmes;
DELETE FROM batches; DELETE FROM import_log;""")
con.commit()
rows = []
t0 = time.time()
for fn in sorted(os.listdir(SRC)):
p = os.path.join(SRC, fn)
t = time.time()
st = sniff(p)
sha = hashlib.md5(io.open(p, "rb").read(1 << 20)).hexdigest()[:16]
out = {"uw": [], "bills": [], "norms": [], "lmes": [], "lme_res": {}, "cur_bill": -1,
"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}
schema = "?"
msg = ""
try:
if st == "zip":
schema = parse_std(p, out)
elif st == "xml":
schema = "不再支持"
msg = "xml 格式已于 2026-10-01 停止支持(请导出 COS4)"
elif st == "encrypted":
schema = "加密件"
msg = "无法解析:请在计价软件导出为 XML / COS4"
else:
schema = "未知"
msg = "文件头无法识别"
except Exception as e:
msg = "ERROR %s" % e
if schema in ("2025标准", "老格式"):
bid, n_bill, n_lme = save(con, "project", out, fn, sha, os.path.getmtime(p))
else:
bid, n_bill, n_lme = None, 0, 0
secs = time.time() - t
con.execute("""INSERT INTO import_log(batch_id, file, schema, n_bill, n_bill_skip, n_norm,
n_lme, n_lme_skip, secs, msg) VALUES(?,?,?,?,?,?,?,?,?,?)""",
(bid, fn, schema, n_bill, out["bill_skip"] + out["bill_skip_zero"], len(out["norms"]),
n_lme, out["lme_skip"], secs, msg))
con.commit()
rows.append((fn, schema, out["bill_raw"], n_bill, out["bill_skip"] + out["bill_skip_zero"],
len(out["norms"]), out["lme_raw"], n_lme, out["lme_skip"], secs, msg))
con.commit()
con.close()
# 报告
o = []
o.append("# M1 导入报告(原型)")
o.append("")
o.append("生成时间:%s 数据库:%s(%.1f MB)" % (
time.strftime("%Y-%m-%d %H:%M:%S"), DB, os.path.getsize(DB) / 1048576.0))
o.append("")
o.append("| 文件 | 格式 | 清单原始 | 清单入库 | 跳过(单位=项) | 定额入库 | 工料机原始 | 工料机入库 | 跳过(组合) | 秒 |")
o.append("|---|---|---:|---:|---:|---:|---:|---:|---:|---:|")
tot = [0] * 8
for r in rows:
o.append("| %s | %s | %d | %d | %d | %d | %d | %d | %d | %.1f |" % (
r[0][:40], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9]))
for i in range(8):
tot[i] += r[2 + i]
if r[10]:
o.append("| ↳ %s | | | | | | | | | | %s |" % ("", r[10]))
o.append("| **合计** | | **%d** | **%d** | **%d** | **%d** | **%d** | **%d** | **%d** | **%.1f** |" % (
tot[0], tot[1], tot[2], tot[3], tot[4], tot[5], tot[6], sum(r[9] for r in rows)))
o.append("")
o.append("说明:工料机按「名称+规格+单位」在单个工程内去重,故 入库 ≤ 原始。")
io.open(REPORT, "w", encoding="utf-8").write("\n".join(o))
print("DONE total_secs=%.1f" % (time.time() - t0))
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,782 @@
# -*- 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
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):
"""生成批次级筛选 SQL(默认全选=不筛)
self_src:被审工程的源文件名 —— 同一个文件若也在历史库里,排除掉(避免自己跟自己比)
area:地区前缀列表 [(省, 市, 区/县), ...](2026-09-29 树形多选后改成这样)
—— 一个元组就是一个前缀约束(市/区为空=该级不限),**多个元组之间是 OR**;整表空=不限。
例:[("广东省","",""),("湖南省","长沙市","")] = 广东全省 或 湖南长沙。
units:单价类型码(原「文件类型」,2026-09-29 改名)—— 清单比对用;工料机比对不用
orgs:单位(2026-10-08 主人定,工料机比对专用):建设单位 ∪ 发布单位 **跨来源联查**,
一批名字同时匹配 BulidUnit(工程批次)OR x_publisher(价格批次);
工程批次 x_publisher 恒空、价格批次 BulidUnit 恒空,OR 起来天然各走各的。
"""
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 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_conds(fields, kw, where_out, args_out):
"""关键字检索条件(2026-10-10 决策 27「不按排序匹配」):每个词拆成
字母数字段(C30、400、P.O——保持原样要求子串)+ 中文单字(逐字在场即可),
各要求之间 AND、字段之间 OR。「混凝土钢筋」从此能命中「钢筋混凝土」。"""
for t in (kw or "").split():
if not t:
continue
t = _kw_fold(t)
reqs = ["%" + r + "%" for r in _TOK.findall(t)]
reqs += ["%" + c + "%" for c in sorted({c for c in re.sub(r"[a-z0-9φ./*\-]", "", t)})]
per = []
for pat in reqs:
per.append("(" + " OR ".join("%s LIKE ?" % _kw_like(f) for f in fields) + ")")
args_out.extend([pat] * len(fields))
if per:
where_out.append("(" + " AND ".join(per) + ")")
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):
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
"""row: sqlite Row of s_bills"""
c = hist.cursor()
w, args = _filters(kinds, units, [], self_src=self_src, area=area) # classes 只对价格库有意义,清单比对不筛目录
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(导入落列,老库启动迁移回填)。
if len(out) < limit:
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 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):
"""独立检索(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)。"""
c = hist.cursor()
cond, args = _filters(kinds, units, [], prefix="bt") # 批次级条件(拼好的 SQL 串 + 参数)
extra = []
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) # 不按排序(决策 27):φ 等折叠在 _kw_conds 内
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]
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
FROM bills b JOIN batches bt ON bt.id=b.batch_id
WHERE %s
ORDER BY bt.x_period_end_m DESC, bt.id DESC LIMIT ? OFFSET ?""" % " AND ".join([cond] + extra)
args.append(int(limit))
args.append((max(int(page), 1) - 1) * int(limit))
res = []
for x in c.execute(sql, 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"],
"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):
"""独立检索 · 工料机版(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)
condp, cargsp = _filters([], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs)
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)
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 = ''")
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 * FROM (%s) WHERE %s ORDER BY p2 DESC, p1 DESC, batch_id LIMIT ? OFFSET ?"
% (" UNION ALL ".join(branches), " AND ".join(outer) or "1=1"))
rows = c.execute(sql, 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": "检索", "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):
"""工料机:历史工程工料机 + 信息价/市场价(价格库)
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)
wpr, apr = _price_range("l.NoTaxPrice", pmin, pmax)
w = w + " AND " + wpr; args = args + apr
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)
wpp, app = _price_range("p.NoTaxPrice", pmin, pmax)
wp = wp + " AND " + wpp; argp = argp + app
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]

View File

@@ -0,0 +1,154 @@
# -*- 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 同机制,见那里的说明):改了入库口径才升号
PARSER_VER = "2026.10.02-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 "")

View File

@@ -0,0 +1,296 @@
# -*- coding: utf-8 -*-
"""
信息价 / 市场价 Excel 解析器(2026-10-06 新增)
与 price_html 的关系:**只换解析前端,共用后半段**。
price_html.parse(path) ─┐
├─→ 同一种 blocks 结构 ─→ price_html.to_records() ─→ 入库
price_xlsx.parse(path) ─┘
这样保证两种来源进库后 x_name_norm / x_hash_exact 口径完全一致,
HTML 导入的价格和 Excel 导入的价格能互相命中、放在一起比对。
**Excel 模板结构**(由 template_bytes() 生成,9 列):
分类 | 材料编码 | 材料名称 | 规格型号 | 单位 | 不含税单价 | 税率 | 含税单价 | 备注
· 第 1 列「分类」= 目录(对应 HTML 里的 section title),连续的相同分类自动归为一段
· 其余 8 列 = 一行材料,顺序与 price_html 的 8 列一一对应
· 第 2 个 sheet「填写说明」不参与解析
**块名(Block)**:优先用第 1 个 sheet 名;若用了默认的「价格明细」,则回退为文件名。
想指定块名就把 sheet 改名,例如「珠海市建材设备市场综合价」。
口径(沿用 price_html 的两条):
1. 目录(Class)=「分类」列原封不动,含序号,不剥「一、」。
2. 一个 Excel 文件 = 一个批次,不按块拆分;期次统一用导入弹框里填的那个。
"""
import io, os, re
# ⚠️ 版本号**故意与 price_html.PARSER_VER 保持一致**,不要各编各的。
# 原因:两条入口写的是同一张 prices 表、同一套 x_hash_exact 口径;而 stale_batches()
# 对价格类只有「一条」判定线(price_html.PARSER_VER)。如果 Excel 用自己的版本号,
# Excel 导入的批次会被永久误报成「数据过期需重导」。
# 所以:口径一变 → 两个文件一起升号 → 两种来源的数据一起重导。这正是我们要的。
PARSER_VER = "2026.10.02-1" # == price_html.PARSER_VER,改那边时同步改这里
SHEET_DATA = "价格明细" # 数据 sheet 名(模板默认)
SHEET_HELP = "填写说明" # 说明 sheet 名(不解析)
# 列名别名:左边是模板标准名,右边是允许的各种写法(去空格/全角后不区分大小写匹配)
_ALIAS = {
"分类": ("分类", "目录", "类别", "材料类别", "分部", "章节"),
"材料编码": ("材料编码", "编码", "代码", "材料代码", "编号"),
"材料名称": ("材料名称", "名称", "材料名", "品名"),
"规格型号": ("规格型号", "规格", "型号", "规格及型号"),
"单位": ("单位", "计量单位"),
"不含税单价": ("不含税单价", "除税单价", "不含税价", "除税价", "除税编制价", "不含税单价(元)"),
"税率": ("税率", "税率(%)", "税率%"),
"含税单价": ("含税单价", "含税价", "含税编制价", "含税单价(元)"),
"备注": ("备注", "说明", "附注", "Remark"),
}
# 模板固定列序(生成与解析共用,改这里两边一起变)
COLS = ["分类", "材料编码", "材料名称", "规格型号", "单位",
"不含税单价", "税率", "含税单价", "备注"]
_HELP = [
("造价审核 · 信息价/市场价导入模板", ""),
("", ""),
("怎么用", "1) 在【价格明细】页按列填写,从第 2 行开始(第 1 行是表头,不要改列名)"),
("", "2) 存成 .xlsx,回到后台「信息价」或「市场价」标签 → 导入 → 选这个文件"),
("", "3) 名称 / 单位 / 不含税单价 必填;其余选填"),
("", "4) 一个块 = 一个批次。想一次导多个市场,就建多个 sheet,每个 sheet 一个市场"),
("", ""),
("列说明", ""),
("分类", "目录,原样保存(如「一、黑色及有色金属」)。连续相同的行自动归为同一段"),
("材料编码", "选填。没有就留空,不影响比对(精确键只用 名称+规格+单位)"),
("材料名称", "必填。留空的行会被跳过"),
("规格型号", "选填,但建议填——参与相似度计算,填了比对更准"),
("单位", "必填。单位不同视为不同材料,不会互相命中"),
("不含税单价", "必填,数字。不要带 ¥ 或千分位逗号(带了也能读,但不建议)"),
("税率", "数字或百分数,如 0.13 或 13%"),
("含税单价", "选填。留空时界面显示「—」"),
("备注", "选填,如「2956 ~ 3076(均值:3016)」"),
("", ""),
("块名(Block)", "默认取文件名。想改就把【价格明细】这个 sheet 改名,例如「珠海市建材设备市场综合价」"),
("", "改名不只是换标题:**一个块 = 一个批次**,多个 sheet 会拆成多个批次分别入库"),
("期次", "不用在表里填。块名里写了「2026年7月」「2026年4-6月」这种会自动认出来;"),
("", "认不出才用导入弹框里填的那个。所以块名尽量带上年月,比手填更准"),
]
def _clean(s):
"""表头归一化:去空白、全角空格、冒号、星号,便于别名匹配"""
return (str(s or "")).strip().replace(" ", "").replace(" ", "").replace(":", "").replace("*", "")
def _map_header(row):
"""表头行 → {标准列名: 列下标}。认不出的列忽略(返回 None 表示没找到必填列)"""
idx = {}
for i, v in enumerate(row):
k = _clean(v)
if not k:
continue
for std, names in _ALIAS.items():
if std in idx:
continue
if k in names or any(k == _clean(n) for n in names):
idx[std] = i
break
return idx if "材料名称" in idx else None
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 _block_name(path, sheet_title):
"""块名:sheet 名被改过就用 sheet 名,否则用文件名"""
sname = (sheet_title or "").strip()
if sname and sname != SHEET_DATA:
return sname
# 上传的文件在软件里存成「sha256_原名.xlsx」(_save_to 的固定格式),
# 直接 basename 会得到一串 hash 开头的丑名字,这里剥掉 sha_ 前缀取回原名。
fn = os.path.splitext(os.path.basename(path))[0]
return fn[65:] if re.match(r"^[0-9a-f]{64}_", fn) and len(fn) > 65 else fn
def _mk_block(path, block, header, rows):
"""把 (分类, 8列) 序列收成一个块。header 为 None 表示这张表没认出表头 → 返回 None 跳过。"""
if header is None or not rows:
return None
import price_html
ps, pe = price_html.guess_period(block)
return {
"block": block,
"columns": COLS[1:],
"n_sections": len(set(s for s, _ in rows)),
"rows": rows,
"period_start_m": ps,
"period_end_m": pe,
}
def _scan_rows(iter_rows):
"""逐行扫描一张表:先认表头(最多容忍 10 行废话),之后按模板 9 列取值。
返回 (header, rows)。"""
header, rows, skipped = None, [], 0
for r in iter_rows:
if header is None:
header = _map_header(r)
if header is not None:
continue
skipped += 1
if skipped > 10:
break
continue
vals = [r[header.get(c, -1)] if 0 <= header.get(c, -1) < len(r) else "" for c in COLS]
if not any(str(v).strip() for v in vals):
continue # 整行空 → 跳过
rows.append((_cell(vals[0]), [_cell(v) for v in vals[1:]])) # 去掉「分类」,留 8 列
return header, rows
def parse(path):
"""→ [{block, columns, n_sections, rows:[(分类, [8列])], period_start_m, period_end_m}, ...]
结构与 price_html.parse 完全一致。.xlsx 走 openpyxl,.xls(老格式)走 xlrd。
**一个 sheet = 一个块**(2026-10-06):想一次导入多个市场,就建多个 sheet,
每个 sheet 用自己的市场名命名 —— 与 HTML 里「一个块 = 一个市场」对齐,
导入后每个块单独建一个批次、各自带自己的期次。
"""
if not os.path.exists(path):
raise ValueError("文件不存在:%s" % path)
if (path or "").lower().endswith(".xls"):
return _parse_xls(path)
import openpyxl
try:
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
except Exception as e:
raise ValueError("打不开这个 Excel(%s)。请另存为 .xlsx 后再导入" % e)
out = []
for ws in wb.worksheets:
if (ws.title or "").strip() == SHEET_HELP:
continue
header, rows = _scan_rows(ws.iter_rows(values_only=True))
b = _mk_block(path, _block_name(path, ws.title), header, rows)
if b:
out.append(b)
wb.close()
if not out:
raise ValueError("没找到表头行或没有数据行。请下载标准模板,第 1 行保持模板的列名不要改")
return out
def _parse_xls(path):
"""老格式 .xls(Excel 97-2003)。openpyxl 读不了,走 xlrd。
逻辑与 .xlsx 分支完全一致:同样一个 sheet = 一个块、同样复用 _scan_rows / _mk_block。"""
try:
import xlrd
except ImportError:
raise ValueError("读 .xls 需要 xlrd(pip install xlrd)。也可以把文件另存为 .xlsx 后再导入")
try:
bk = xlrd.open_workbook(path)
except Exception as e:
raise ValueError("打不开这个 .xls(%s)。确认不是改名骗人的 csv/html" % e)
out = []
for si in range(bk.nsheets):
sh = bk.sheet_by_index(si)
if (sh.name or "").strip() == SHEET_HELP:
continue
header, rows = _scan_rows([sh.cell_value(i, j) for j in range(sh.ncols)]
for i in range(sh.nrows))
b = _mk_block(path, _block_name(path, sh.name), header, rows)
if b:
out.append(b)
if not out:
raise ValueError("没找到表头行或没有数据行。请下载标准模板,第 1 行保持模板的列名不要改")
return out
def to_records(blocks):
"""直接复用 price_html 的入库转换:两种来源口径必须一致,不容许各写一份"""
import price_html
return price_html.to_records(blocks)
# ---------------------------------------------------------------------------
# 标准模板生成
# ---------------------------------------------------------------------------
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"
# 两行示例(照珠海信息价的实际写法,用户一眼知道填什么)
demo = [
["一、黑色及有色金属", "", "圆钢(HPB300)", "Φ6.5mm", "t", 2956.0, 0.13, 3340.28, "2956 ~ 3076(均值:3016)"],
["一、黑色及有色金属", "", "圆钢(HPB300)", "Φ8-10mm", "t", 2902.0, 0.13, 3279.26, "2902 ~ 3021(均值:2961)"],
]
for d in demo:
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 = 22
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 "")

View File

@@ -0,0 +1,225 @@
# -*- 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()

View File

@@ -0,0 +1,496 @@
# -*- 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 _bill_keys(con, sid):
"""这个会话每条清单的持久键 → {rkey: bill_id}(回填备注用)"""
ks = {}
for r in con.execute("""SELECT b.id, s.src_name, u.Name AS uw, b.Number, b.Name, b.Unit
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.session_id=?""", (sid,)):
ks[rkey(r["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_lmes.x_remark(界面立刻可见)+ s_remarks 持久副本(rkey 前缀 'L:'
# 与清单键隔离),重新解析 wipe 后由 restore_lme_remarks() 按 rkey 回填。
def _lme_keys(con, sid):
"""这个会话每条工料机的持久键 → {rkey: lme_id}(回填备注用)。前缀 'L:' 隔离清单键。"""
ks = {}
for r in con.execute("""SELECT l.id, s.src_name, l.Number, l.Name, l.Unit
FROM s_lmes l JOIN sessions s ON s.id = l.session_id
WHERE l.session_id=?""", (sid,)):
ks["L:" + rkey(r["src_name"], "", r["Number"], r["Name"], r["Unit"])] = r["id"]
return ks
def save_lme_remark(con, lme_id, remark):
"""写工料机备注:双写 s_lmes.x_remark + s_remarks('L:' 前缀 rkey),与 save_remark 同款。"""
con.execute("UPDATE s_lmes SET x_remark=? WHERE id=?", (remark, lme_id))
row = con.execute("""SELECT s.src_name, l.Number, l.Name, l.Unit
FROM s_lmes l JOIN sessions s ON s.id = l.session_id
WHERE l.id=?""", (lme_id,)).fetchone()
if not row:
return 0
k = "L:" + rkey(row["src_name"], "", row["Number"], 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["Number"], 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_lmes.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)<>''"):
lid = ks.get(r["rkey"])
if lid:
con.execute("UPDATE s_lmes SET x_remark=? WHERE id=?", (r["remark"], lid))
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):
"""删掉一个会话的全部数据(会话行本身保留)——「重新解析」先清场再重写
⚠️ s_norms 没有 session_id 列,只能借 s_bills 绕一层;漏了这步会留下孤儿定额。
⚠️ 2026-09-29:bill_id IS NULL 的定额**任何会话都认领不了**(挂不上父表就是死数据),
光靠「按 session 删」永远删不掉它们 —— 实测旧会话留下 39 条,重新解析 N 次还在。
这里顺手清一遍:这些行本来就是不可达数据,删掉没有副作用。
⚠️ 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,))
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, qty, seq) 去重,保最新一行。
2026-10-10 一次性清理(上面 wipe 漏表的存量受害者),幂等——反复跑无副作用。
保留 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, qty, seq)""")
if own:
con.commit()
con.close()
def drop(con, sid):
"""连会话行一起删(台账里「删除」用)"""
wipe(con, sid)
con.execute("DELETE FROM sessions WHERE id=?", (sid,))
def bill_rkeys(con, sid):
"""这个会话全部清单的持久键集合(删会话清备注用,见 drop_remarks)"""
return set(_bill_keys(con, sid))
def lme_rkeys(con, sid):
"""这个会话全部工料机的持久键集合(删会话清备注用,与 bill_rkeys 同款,'L:' 前缀)"""
return set(_lme_keys(con, sid))
def drop_remarks(con, rk, batch_src_hashes=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 可能是「;」连接的多文件串,逐段比对。
⚠️ 重新解析(wipe)不走这里 —— 它的按 rkey 回填机制依赖 s_remarks。
返回删除条数。
"""
if not rk:
return 0
keep = set()
for r in con.execute("SELECT id FROM sessions"):
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
for k in (rk - keep):
n += con.execute("DELETE FROM s_remarks WHERE rkey=?", (k,)).rowcount
return n
def connect():
con = sqlite3.connect(DB)
con.row_factory = sqlite3.Row
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")),
("s_unit_works", ("section_id INTEGER",
"Construction REAL", "DivisionalAndElementalWorks REAL",
"Preliminaries REAL", "CostForHSE REAL",
"SundryCosts REAL", "Tax REAL")),
("s_bills", ("div_id INTEGER",
# 源文件备注(清单节点 Remark 属性,2026-10-08 加;老库补列,老会话重解析才有)
"src_remark TEXT")),
# 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",)),
):
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}
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, 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", ""),
";".join(n for _, n in files),
time.strftime("%Y-%m-%d %H:%M:%S")))
sid = cur.lastrowid
else:
# 重新解析:期次/地区等元信息以这次请求为准,打开时间刷新(7 天清理按它算)
cur.execute("""UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=?,
x_province=?, x_city=?, x_district=?, bulid_unit=?, imported_at=?
WHERE id=?""",
(meta.get("name") or "", pf, pt, pf,
meta.get("province", ""), meta.get("city", ""), meta.get("district", ""),
meta.get("bulid_unit", ""), time.strftime("%Y-%m-%d %H:%M:%S"), sid))
stat = {"bill": 0, "norm": 0, "lme": 0, "uw": 0}
bill_ids = []
ptotal = None # 工程总造价:多文件时取最后一个有值的
pinfo, pfeat = None, None # 项目根节点属性 / 项目特征条目(项目级标签卡用)
num2sec, sec_built = {}, set() # 2026-09-30:单位工程编号 → 单项工程 id
for path, name in files:
st = job.sniff(path)
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。
if st == "xml":
raise ValueError("已不再支持 xml 格式,请导出为 COS4(或 .COS)后打开")
job.parse_std(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"] # 项目特征条目 [(名称, 值)]
# 单项工程先入(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 {}
cur.execute("""INSERT INTO s_unit_works(session_id, section_id, Number, Name,
Specialty, Total, Construction, DivisionalAndElementalWorks,
Preliminaries, CostForHSE, SundryCosts, Tax)
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")))
uw_ids.append(cur.lastrowid)
stat["uw"] += 1
# 第一个 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)
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))
# 决策 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 = []
for idx, num, nm, unit, qty, price, total in out["norms"]:
bid = bill_ids[idx0 + idx] if 0 <= idx < len(out["bills"]) else None
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total)
VALUES(?,?,?,?,?,?,?)""",
(bid, num, nm, unit, qty, price, total))
norm_ids.append(cur.lastrowid)
stat["norm"] += 1
# 2026-09-30:定额消耗量(定额 → 工料机编码 + 消耗量)。
# 有这张表才能回答「某个单位工程用了哪些工料机」——以前工料机只能挂到整个会话。
for nidx, code, q in (out.get("norm_res") or []):
nid = norm_ids[nidx] if 0 <= nidx < len(norm_ids) else None
cur.execute("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
(nid, code, q))
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-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, (_nm, _sp, _un, _kd, _q, _ntp, _taxp) in (out.get("lme_proj") or {}).items():
cur.execute("""INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?,?)""", (sid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp))
# 这几样都要**解析完**才知道(sessions 行在解析之前就插好了),所以这里补一笔
if ptotal is not None or pinfo or pfeat:
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=? 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,
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

View File

@@ -0,0 +1,18 @@
# -*- 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

View File

@@ -0,0 +1,10 @@
# -*- 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

View File

@@ -0,0 +1,472 @@
# -*- 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)
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)
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 {}
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,
"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 {}

View File

@@ -0,0 +1,347 @@
# -*- 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 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
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:门禁自愈触发节流
# ---------------------------------------------------------------- 初始化
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:
_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 path.startswith("/api/license/"):
return _license_api(method, path, body)
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 _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}}
return {"kind": "json", "code": 404,
"obj": {"error": {"code": "NOT_FOUND", "message": "未知授权接口"}}}
# ---------------------------------------------------------------- 授权页
_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}
</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="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 {"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[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="网络错误:无法连接本机服务。";});}
load();
</script></body></html>""")
return _PAGE

View File

@@ -0,0 +1,10 @@
{
"_说明": [
"可信公钥清单(信任根):只随软件/受控部署渠道固定分发,绝不在线发现。",
"上线前由运维(部署环境)交付生产 key_id + 公钥 PEM(SubjectPublicKeyInfo),",
"按 {\"key_id\":..., \"public_key_pem\":\"-----BEGIN PUBLIC KEY-----...\", \"revoked\":false} 追加进 pinned_keys。",
"接入包 test-vectors.json 里的 integration-test-only 测试公钥绝不能加进生产配置。",
"清空 = fail closed:激活/心跳验签一律失败。"
],
"pinned_keys": []
}

View File

@@ -0,0 +1,210 @@
# -*- 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

View File

@@ -0,0 +1,223 @@
# -*- 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。
信任根:只信随软件/受控渠道固定分发的公钥(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"),
}
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}] → {key_id: {"key": pub, "revoked": bool}}。
pinned 文件本身配置错(非 P-256 / 解不开)要立刻暴露,不能静默当不可信。
"""
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)
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)))
return "\n".join(out).encode("utf-8")
# ---------------------------------------------------------------- 结构校验
def _check_payload(payload, version, expected_instance):
if not isinstance(payload, dict):
raise VerifyError("payload 不是对象")
if set(payload.keys()) != set(FIELDSETS[version]):
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)

186
CostReview/app/shell.py Normal file
View File

@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
"""
M5 窗口壳:双击这个脚本 → 直接弹出「造价审核」软件窗口(没有地址栏、没有标签页)。
内部仍然是本地服务 + 网页内容(同一个 Edge WebView2 渲染引擎),但你看到的就是一个普通软件窗口。
排错:每一步都会打印,并同时写进 造价审核\\data\\launch.log
"""
import os, sys, time, threading, urllib.request, 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
URL = "http://127.0.0.1:%d/workbench.html" % PORT
ADMIN_URL = "http://127.0.0.1:%d/admin.html" % PORT
LOG = os.path.join(ROOT, "data", "launch.log")
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 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
def main():
_log("启动中…(端口 %d)" % PORT)
# 1) 后台起本地服务;端口已有服务则直接复用,避免重复占用数据库
if port_in_use():
_log("端口 %d 已有服务在跑,直接复用" % PORT)
else:
threading.Thread(target=api_server.run, daemon=True).start()
if not wait_ready():
_log("服务启动失败:端口 %d 起不来(可能被其他程序占用)" % PORT)
print("服务启动失败,请检查端口 %d 是否被占用" % 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,
)
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())

View File

@@ -0,0 +1,91 @@
# Runtime Storage
The active application and offline comparison tools use `data/history.db`.
Projects and information/market prices share batch metadata, but have separate
detail tables (`bills`, `lmes`, `prices`). Attachments are linked through batches.
`data/session.db` contains audit sessions only.
## Price import sources (2026-10-06)
Two entry points, one pipeline — both land in `prices` with the same
`x_hash_exact` so HTML-imported and Excel-imported rows match each other:
* `core/price_html.py` — the 信息价 HTML (`const DATA = [...]`)
* `core/price_xlsx.py` — the standard Excel template (`/api/admin/price_template`)
⚠️ They share **one** `PARSER_VER` on purpose. `stale_batches()` has a single
price line, so a separate Excel version would make Excel batches report
"expired" forever. Change the 入库口径 → bump both → re-import both.
## Legacy (archived 2026-10-06, do not use)
`price_lib.db` / `price_lib.sql` / `parse/merge_price_lib.py` were moved to
`app/_deprecated/legacy_price_lib/` — the old parser used a different column set
(`x_period_m` single month) and a different hash normalisation, so its rows can
never match current data. Kept only as a read-only reference. Do not run
`merge_price_lib.py`: it writes legacy-shaped rows into the live database.
## 询价附件 (2026-10-06)
`inquiry_files` (one file per upload: pdf/zip/rar) + `lme_attach`
(`lme_id` is the PRIMARY KEY → a 工料机 can only ever point at ONE file;
a file can point at many). Change binding with `INSERT OR REPLACE` — the
primary-key conflict *is* the rebind. Project batches only: price batches
(info/market) have no `lmes` rows, so every entry point asserts `kind='project'`.
## 2026-10-06 changes
**`batches.x_rows_price` (new column).**
`x_rows_lme` used to carry *two* meanings: on `project` batches it was the
工料机 count, on `info` / `market` batches it was the 价格 count. Any code
asking `x_rows_lme > 0` to mean "this batch has 工料机" would wrongly match
price batches. Price counts now live in `x_rows_price`; `x_rows_lme` is
工料机-only. **To ask "does this batch have 工料机", test `kind='project'`,
never a row count.**
**`dict_region` / `dict_org` (new tables) — the 数据源 dictionary.**
Single source for the 地区 / 发布单位 / 建设单位 dropdowns, shared by the
admin UI and the workbench:
* entry dropdowns (import / edit / 打开工程) read **only** `/api/dict`
* filter dropdowns (list filters, area tree) read `/api/admin/filters`,
which is *dictionary ∪ values actually present in `batches`* — filtering
must still be able to reach historical rows, so it only ever widens
On first start the dictionary is seeded from existing `batches` values, so
nothing disappears when it is enabled.
## 2026-10-06 · 价格导入「一个块 = 一个批次」(取代「一个文件 = 一个批次」)
A price file usually carries **several markets** with **different periods**
(珠海市建材设备市场综合价 → 2026-07, 珠海市2026年4-6月园林苗木市场信息 →
2026-04~06, 横琴, 万山). One batch can hold only one period, so cramming all
markets into a single batch forced the period to be left empty — and
`ym2str('')` raises, which took the whole 信息价 list down with a 500
(defect DB-1). Now:
* `price_html.parse()` / `price_xlsx.parse()` return **one entry per block**
(HTML: per top-level object; Excel: **per sheet**), each carrying
`period_start_m` / `period_end_m` detected from the block name
(`guess_period`, e.g. "2026年4-6月" → 24316~24318)
* `api_import_price()` creates **one batch per block**; period precedence is
block name → file name → the value typed in the import dialog
* batch name = block name when there is more than one block
## 2026-10-06 · sessions.x_batch_id(会话 ↔ 后台项目批次)
The workbench opens a file straight into the session DB and never touched
`batches`, so it could not see 询价附件. `sessions.x_batch_id` now links the
two: `api_audit()` matches on the **same source file**
(`batches.x_src_hash` == `sessions.src_name`, both "<sha256>_<original name>").
⚠️ **Source-file match only** (2026-10-06, 主人定): the old "fall back to
project name" branch was removed from both `_link_batch()` and
`backfill_session_batch()`. Same-named projects would bind the wrong batch,
and a *wrong* 询价附件 is worse than none (it looks legitimate). Sessions left
`NULL` simply mean "this project was never imported in the admin UI" (or was
imported by an old build that stored sha1 — re-import once).
`backfill_session_batch()` backfills old sessions at startup. The workbench
reads attachments **read-only** (`GET /api/session/inq`); binding stays in the
admin UI.

View File

@@ -0,0 +1,373 @@
-- 造价审核软件 · 数据库结构(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_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
);
CREATE INDEX IF NOT EXISTS ix_uw_batch ON unit_works(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
);
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 项目级合计)
ntp REAL, -- 除税编制价
taxp 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_period_start_m INTEGER, -- 期次起(从批次继承,_ensure_period 回填)
x_period_end_m INTEGER -- 期次止
);
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 加
);
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 里的一级分组)
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-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-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)。
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_lmes.id;一行只有一条在效采纳)
);
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);

View File

@@ -0,0 +1,162 @@
-- 会话库(工作台:本次打开审核的工程)——完整集,用于"跟原件逐条核对"
-- 与历史库 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, -- 建设单位(文件类型按你的决定:会话库**不存**)
src_name TEXT, -- 源文件名
imported_at TEXT,
x_total REAL, -- 工程总造价(2026-09-30):原文件口径,不是清单合价求和
x_info TEXT, -- 项目根节点属性 JSON → 项目级「基本信息」卡
x_feat TEXT, -- AttrInfo/AddiInfo 条目 JSON → 项目级「项目特征信息」卡
x_batch_id INTEGER -- 后台批次 id(2026-10-06):同一份文件在后台导入过就能对上,
-- 工作台据此**只读**展示该项目的询价附件。对不上 = 0 / NULL,
-- 界面上就不显示「询价附件」入口(不是错误,是没在后台导入过)
);
-- 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 -- 税金
);
-- 分部(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
);
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
);
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 -- 消耗量
);
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 的项目级工料机汇总原样入库,「原数据 → 工料机汇总」项目级读这里。
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
);
CREATE UNIQUE INDEX IF NOT EXISTS ux_slmeproj_code ON s_lme_proj(session_id, code);
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);

View File

@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
"""把 lic_helpers 里的 fixtures 暴露给 pytest(fixtures 必须在 conftest 命名空间)。"""
from lic_helpers import client, keyring, priv_key # noqa: F401

View File

@@ -0,0 +1,171 @@
# -*- coding: utf-8 -*-
"""license_client 测试辅助:本地生成 P-256 测试密钥、签名信封、假传输层。
⚠ 测试只用本地随机生成的密钥 / 包内 test-vectors 的 integration-test-only 公钥,
绝不进入生产 pinned_keys.json。
"""
import base64
import hashlib
import json
import os
import sys
from datetime import datetime, timedelta, timezone
import pytest
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
HERE = os.path.dirname(os.path.abspath(__file__))
SERVER_DIR = os.path.join(os.path.dirname(HERE), "server")
if SERVER_DIR not in sys.path:
sys.path.insert(0, SERVER_DIR)
from license_client.client import LicenseClient # noqa: E402
from license_client.store import JsonFileStore, SecretStore # noqa: E402
from license_client.verify import (FIELDSETS, LICENSE_V2, LEASE_V2, # noqa: E402
build_keyring)
IID = "11111111-2222-3333-4444-555555555555"
IID2 = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
NOW = datetime(2026, 10, 9, 3, 0, 0, tzinfo=timezone.utc)
Z = "%04d-%02d-%02dT%02d:%02d:%02dZ"
def z(dt):
return Z % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
def rfc(dt):
return dt.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
# ---------------------------------------------------------------- 信封构造
def canonical(payload, version):
def val(v):
if isinstance(v, bool):
raise TypeError("bool 不允许")
return str(v) if isinstance(v, int) else v
return "\n".join("%s=%s" % (k, val(payload[k])) for k in FIELDSETS[version]).encode("utf-8")
def sign_b64(key, data):
der = key.sign(data, ec.ECDSA(hashes.SHA256()))
return base64.b64encode(der).decode("ascii").rstrip("=")
def cert_payload(key_id="integration-test-only", iid=IID, **over):
p = {"version": LICENSE_V2, "instance_id": iid, "license_id": 1, "customer_id": 2,
"product_id": 3, "starts_at": z(NOW), "expires_at": z(NOW + timedelta(days=365)),
"key_id": key_id}
p.update(over)
return p
def lease_payload(key_id="integration-test-only", iid=IID,
state="active", server=None, ent=None, le=None, **over):
p = {"version": LEASE_V2, "instance_id": iid, "state": state,
"server_time": z(server or NOW),
"entitlement_expires_at": z(ent or NOW + timedelta(days=365)),
"lease_expires_at": z(le or (server or NOW) + timedelta(days=7)),
"key_id": key_id}
p.update(over)
return p
def envelope(payload, key, kind, next_hb=60, sha=None):
"""kind="cert" → license-v2 信封;"lease" → lease-v2 信封。sha 传 "bad" 可篡改辅助校验。"""
version = LICENSE_V2 if kind == "cert" else LEASE_V2
data = canonical(payload, version)
env = {"payload": payload,
"signature": sign_b64(key, data),
"canonical_sha256": sha or hashlib.sha256(data).hexdigest()}
if kind == "cert":
env = {"version": version, **env}
else:
env = {"algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": next_hb, **env}
return env
# ---------------------------------------------------------------- 假设施
class MemSecret(SecretStore):
def __init__(self):
self.v = None
def get(self):
return self.v
def set(self, s):
self.v = s
def clear(self):
self.v = None
class FakeTransport:
"""脚本化传输层:依次消费 script(异常 / (status, headers, data));记录全部调用。"""
def __init__(self, script):
self.script = list(script)
self.calls = []
def __call__(self, method, url, body, headers):
self.calls.append({"method": method, "url": url, "body": dict(body),
"headers": dict(headers)})
item = self.script.pop(0) if self.script else (500, {}, {"error": {"code": "X", "message": "脚本耗尽"}})
if isinstance(item, Exception):
raise item
status, headers, data = item
return status, dict(headers), data
def keys(self):
return [c["headers"].get("Idempotency-Key") for c in self.calls]
def make_keyring(priv_key, key_id="integration-test-only", revoked=False):
pem = priv_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
return build_keyring([{"key_id": key_id, "public_key_pem": pem.decode("ascii"),
"revoked": revoked}])
@pytest.fixture
def priv_key():
return ec.generate_private_key(ec.SECP256R1())
@pytest.fixture
def keyring(priv_key):
return make_keyring(priv_key)
@pytest.fixture
def client(tmp_path, keyring):
"""已配置凭据的客户端:now 冻结在 NOW,sleep 记录不真等。"""
return make_client(tmp_path, keyring)
def make_client(tmp_path, keyring, transport=None, now_fn=None, max_attempts=4):
sleeps = []
tp = transport or FakeTransport([])
c = LicenseClient(
api_base="https://license.test",
state_store=JsonFileStore(str(tmp_path / "state.json")),
secret_store=MemSecret(),
keyring=keyring,
now_fn=now_fn or (lambda: NOW),
sleep_fn=lambda s: sleeps.append(s),
transport=tp,
max_attempts=max_attempts)
c._sleeps = sleeps
c._tp = tp
c.configure(IID, "LK-TEST-1", "SECRET-DO-NOT-LOG")
return c
def load_vectors():
p = os.path.join(HERE, "testdata", "license_test_vectors.json")
with open(p, encoding="utf-8") as f:
return json.load(f)

View File

@@ -0,0 +1,277 @@
# -*- coding: utf-8 -*-
"""网络/时钟回拨/过期租约负向测试 + 幂等/429/掉线/存储失败(协议交付验收清单)。"""
import json
from datetime import timedelta
import pytest
from lic_helpers import (IID, NOW, FakeTransport, MemSecret, cert_payload,
envelope, lease_payload, make_client, make_keyring, rfc, z)
from license_client.client import LicenseClient
from license_client.store import JsonFileStore, StorageError
from license_client.verify import VerifyError
def ok_lease(priv_key, server=NOW, le=None, state="active", iid=IID, next_hb=60):
return 200, {}, {"data": envelope(
lease_payload(server=server, le=le, state=state, iid=iid),
priv_key, "lease", next_hb=next_hb)}
def ok_cert(priv_key, iid=IID):
return 200, {}, {"data": {"instance_id": iid, "status": "activated",
"certificate": envelope(cert_payload(iid=iid), priv_key, "cert")},
"idempotent_replay": False}
# ------------------------------------------------------------ 激活
def test_activate_happy_path(priv_key, client):
client._tp.script.append(ok_cert(priv_key))
r = client.activate()
assert r["ok"] is True
st = client.state_store.load()
assert st["status"] == "activated"
assert st["certificate"]["version"] == "license-v2"
assert "activation_op" not in st
assert client._tp.calls[0]["url"].endswith("/api/v1/activation/instances/" + IID)
assert client._tp.calls[0]["headers"]["Idempotency-Key"]
def test_activate_retry_reuses_key_and_body(priv_key, tmp_path, keyring):
"""网络失败重试:同一 Idempotency-Key + 同一请求体(含 secret 字段不变)。"""
tp = FakeTransport([ConnectionError("断网"), ok_cert(priv_key)])
c = make_client(tmp_path, keyring, transport=tp)
r = c.activate()
assert r["ok"] is True
assert len(tp.calls) == 2
assert tp.keys()[0] == tp.keys()[1]
assert tp.calls[0]["body"] == tp.calls[1]["body"]
def test_activate_rejects_stop_retrying(priv_key, client):
client._tp.script.append((401, {}, {"error": {"code": "BAD_CREDENTIALS",
"message": "nope"}}))
r = client.activate()
assert r["ok"] is False and r["code"] == "BAD_CREDENTIALS"
assert len(client._tp.calls) == 1 # 401 不重试
st = client.state_store.load()
assert "activation_op" not in st
assert st["last_error"]
def test_activate_verify_failure_fails_closed(priv_key, client, keyring):
"""证书绑定别的实例 → 拒收,状态不得进入 activated。"""
client._tp.script.append(ok_cert(priv_key, iid="bbbbbbbb-cccc-dddd-eeee-ffffffffffff"))
r = client.activate()
assert r["ok"] is False and r["code"] == "VERIFY_FAILED"
assert client.state_store.load().get("status") != "activated"
def test_activate_persisted_key_survives_restart(priv_key, tmp_path, keyring):
"""激活中途进程重启:新客户端从状态文件找回在途幂等键继续用。"""
tp = FakeTransport([ConnectionError("断网")])
c1 = make_client(tmp_path, keyring, transport=tp, max_attempts=1)
c1.activate() # 瞬时失败,键已落盘
saved_key = c1.state_store.load()["activation_op"]["key"]
tp2 = FakeTransport([ok_cert(priv_key)])
c2 = make_client(tmp_path, keyring, transport=tp2)
c2.activate()
assert tp2.calls[0]["headers"]["Idempotency-Key"] == saved_key
# ------------------------------------------------------------ 心跳与租约状态机
def test_heartbeat_accepts_active_lease(priv_key, client):
client._tp.script.append(ok_lease(priv_key))
r = client.heartbeat()
assert r["ok"] and r["state"] == "active"
st = client.state_store.load()
assert st["enabled"] is True
assert st["server_high_water"] == z(NOW)
assert st["next_heartbeat_seconds"] == 60
assert "heartbeat_op" not in st
ok, reason = client.can_run()
assert ok is True and reason is None
@pytest.mark.parametrize("state", ["frozen", "revoked", "expired", "not_started", "not_activated"])
def test_non_active_lease_disables_business(priv_key, client, state):
"""HTTP 200 不代表授权有效:签名租约非 active 必须关闭业务。"""
client._tp.script.append(ok_lease(priv_key, state=state))
r = client.heartbeat()
assert r["ok"] is True
st = client.state_store.load()
assert st["enabled"] is False
ok, reason = client.can_run()
assert ok is False and state in reason
def test_lease_expired(priv_key, client):
client._tp.script.append(ok_lease(priv_key, le=NOW - timedelta(seconds=1)))
client.heartbeat()
ok, reason = client.can_run()
assert ok is False and "租约已过期" in reason
def test_entitlement_expired(priv_key, client):
env = envelope(lease_payload(ent=NOW - timedelta(days=1),
le=NOW - timedelta(days=2)), priv_key, "lease")
client._tp.script.append((200, {}, {"data": env}))
client.heartbeat()
ok, reason = client.can_run()
assert ok is False and "过期" in reason
def test_lease_longer_than_entitlement_rejected(priv_key, client):
env = envelope(lease_payload(ent=NOW + timedelta(days=3),
le=NOW + timedelta(days=10)), priv_key, "lease")
client._tp.script.append((200, {}, {"data": env}))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "LEASE_INVALID"
assert client.state_store.load().get("lease") is None # 不得接受
def test_lease_over_14_days_rejected(priv_key, client):
env = envelope(lease_payload(server=NOW, le=NOW + timedelta(days=14, seconds=1)),
priv_key, "lease")
client._tp.script.append((200, {}, {"data": env}))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "LEASE_INVALID"
def test_server_time_rollback_rejected(priv_key, client):
"""第二份租约 server_time 早于已存高水位 → 拒收且保留新租约。"""
client._tp.script.append(ok_lease(priv_key, server=NOW))
client.heartbeat()
old = client.state_store.load()["lease"]
client._tp.script.append(ok_lease(priv_key, server=NOW - timedelta(hours=1)))
r = client.heartbeat()
assert r["ok"] is False
assert client.state_store.load()["lease"] == old
def test_next_heartbeat_honored_with_min_60(priv_key, client):
client._tp.script.append(ok_lease(priv_key, next_hb=120))
r = client.heartbeat()
assert r["next"] == 120
client._tp.script.append(ok_lease(priv_key, next_hb=30)) # 服务端违反 schema(min 60)→ 拒收
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "VERIFY_FAILED"
assert client.state_store.load()["next_heartbeat_seconds"] == 120 # 旧值保留
# ------------------------------------------------------------ 时钟
def test_local_clock_rollback_locks(priv_key, client):
client.cache_ttl = 0 # 回拨检测专用测试:关掉结果缓存
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
ok, _ = client.can_run()
assert ok
class T:
t = NOW - timedelta(seconds=90) # 把本机时钟往回拨
client.now_fn = lambda: T.t
ok, reason = client.can_run()
assert ok is False and "回拨" in reason
def test_clock_skew_over_5min_rejected(priv_key, client):
client._tp.script.append(ok_lease(priv_key, server=NOW - timedelta(minutes=10)))
client.heartbeat()
ok, reason = client.can_run()
assert ok is False and "5 分钟" in reason
# ------------------------------------------------------------ 掉线与离线宽限
def test_offline_grace_not_extended(priv_key, client):
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
before = client.state_store.load()["lease"]["lease_expires_at"]
client._tp.script.append(ConnectionError("断网"))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "TRANSIENT"
st = client.state_store.load()
assert st["lease"]["lease_expires_at"] == before # 网络失败不得延长租约
assert "heartbeat_op" in st # 在途操作保留(键+client_time 复用)
ok, _ = client.can_run()
assert ok is True # 有效租约内允许继续(离线宽限)
def test_restart_keeps_lease_without_network(priv_key, tmp_path, keyring):
"""重启不得清除高水位/租约:新客户端不联网即可继续运行。"""
tp = FakeTransport([ok_lease(priv_key)])
c1 = make_client(tmp_path, keyring, transport=tp)
c1.heartbeat()
secret = c1.secret_store.get()
tp2 = FakeTransport([]) # 一旦联网即测试失败
c2 = LicenseClient(api_base="https://license.test",
state_store=c1.state_store, secret_store=c1.secret_store,
keyring=keyring, now_fn=lambda: NOW,
sleep_fn=lambda s: None, transport=tp2)
ok, reason = c2.can_run()
assert ok is True and tp2.calls == []
def test_tampered_local_lease_fails_closed(priv_key, client):
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
p = client.state_store.path
st = json.load(open(p, encoding="utf-8"))
st["lease_envelope"]["payload"]["entitlement_expires_at"] = "2099-01-01T00:00:00Z"
json.dump(st, open(p, "w", encoding="utf-8"), ensure_ascii=False)
ok, reason = client.can_run()
assert ok is False and "校验失败" in reason
def test_storage_save_failure_fail_closed(priv_key, client):
"""原子存储失败:can_run 必须 fail closed,不得放行业务。"""
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
class Broken(JsonFileStore):
def update(self, fn):
raise StorageError("磁盘已满")
client.state_store = Broken(client.state_store.path)
ok, reason = client.can_run()
assert ok is False and "fail closed" in reason
# ------------------------------------------------------------ 429 / 5xx
def test_429_respects_retry_after(priv_key, client):
client._tp.script.append((429, {"Retry-After": "7"}, {}))
client._tp.script.append(ok_lease(priv_key))
r = client.heartbeat()
assert r["ok"] is True
assert any(s >= 7 for s in client._sleeps)
assert client._tp.keys()[0] == client._tp.keys()[1] # 同键重试
def test_5xx_bounded_retry_then_transient(priv_key, client):
for _ in range(4):
client._tp.script.append((503, {}, {}))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "TRANSIENT"
assert len(client._tp.calls) == 4 # 有界
assert len(set(client._tp.keys())) == 1 # 同键同体
assert client._tp.calls[0]["body"] == client._tp.calls[-1]["body"]
def test_403_parks_heartbeat_no_auto_retry(priv_key, client):
client._tp.script.append((403, {}, {"error": {"code": "INSTANCE_DISABLED",
"message": "x"}}))
r = client.heartbeat()
assert r["ok"] is False and len(client._tp.calls) == 1
st = client.state_store.load()
assert st["status"] == "needs_attention"
assert "SECRET-DO-NOT-LOG" not in json.dumps(st) # secret 不进状态文件
for c in client._tp.calls:
assert "SECRET-DO-NOT-LOG" not in c["url"] # secret 不进 URL
assert c["body"].get("secret") == "SECRET-DO-NOT-LOG" # 只在请求体里
def test_secret_never_in_error_messages(priv_key, client):
client._tp.script.append(ConnectionError("boom"))
r = client.heartbeat()
assert "SECRET-DO-NOT-LOG" not in r.get("message", "")

View File

@@ -0,0 +1,117 @@
# -*- coding: utf-8 -*-
"""决策 31 加固项:can_run 结果缓存、高水位节流写、product_id 绑定、心跳并发串行、
缓存失效(心跳接受新租约后门禁立即看到)。"""
import json
import threading
import time
from datetime import timedelta
from lic_helpers import (NOW, FakeTransport, envelope, lease_payload,
make_client, cert_payload, z)
def active_env(priv_key, server=NOW):
return (200, {}, {"data": envelope(lease_payload(server=server), priv_key, "lease")})
def test_can_run_cache_within_ttl(priv_key, client):
client.cache_ttl = 600
client.mono_fn = (lambda: 1000.0)
client._tp.script.append(active_env(priv_key))
client.heartbeat()
assert client.can_run()[0] is True
# TTL 内就算本地租约被篡改,也吃到缓存(这正是缓存的意义:不每请求验签)
p = client.state_store.path
st = json.load(open(p, encoding="utf-8"))
st["lease_envelope"]["payload"]["state"] = "frozen"
json.dump(st, open(p, "w", encoding="utf-8"), ensure_ascii=False)
client.mono_fn = (lambda: 1001.0)
assert client.can_run()[0] is True # 缓存命中
client.mono_fn = (lambda: 1000.0 + 601) # TTL 过 → 重新验签发现篡改
ok, reason = client.can_run()
assert ok is False and "校验失败" in reason
def test_cache_invalidated_by_new_lease(priv_key, client):
client.cache_ttl = 600
client.mono_fn = (lambda: 1000.0)
client._tp.script.append((200, {}, {"data": envelope(lease_payload(state="frozen"),
priv_key, "lease")}))
client.heartbeat()
assert client.can_run()[0] is False # 负结果也进缓存
client._tp.script.append(active_env(priv_key))
client.heartbeat() # 新租约必须作废缓存
assert client.can_run()[0] is True
def test_high_water_throttled_write(priv_key, client):
"""55 秒内不重复落盘高水位;跨过阈值才前进;回拨检测不受影响。"""
client.cache_ttl = 0 # 关缓存,专测节流
t = {"now": NOW}
client.now_fn = lambda: t["now"]
client._tp.script.append(active_env(priv_key))
client.heartbeat()
assert client.can_run()[0] is True
assert client.state_store.load()["local_high_water"] == z(NOW)
t["now"] = NOW + timedelta(seconds=30)
assert client.can_run()[0] is True
assert client.state_store.load()["local_high_water"] == z(NOW) # 未落盘
t["now"] = NOW + timedelta(seconds=60)
assert client.can_run()[0] is True
assert client.state_store.load()["local_high_water"] == z(NOW + timedelta(seconds=60))
t["now"] = NOW + timedelta(seconds=20) # 回拨 40 秒:立即锁
ok, reason = client.can_run()
assert ok is False and "回拨" in reason
def test_product_binding(priv_key, tmp_path, keyring):
c = make_client(tmp_path, keyring)
c.expected_product_id = 3
c._tp.script.append((200, {}, {"data": {"instance_id": c.state_store.load()["instance_id"],
"status": "activated",
"certificate": envelope(
cert_payload(product_id=9), priv_key, "cert")}}))
r = c.activate()
assert r["ok"] is False and r["code"] == "PRODUCT_MISMATCH"
assert c.state_store.load().get("status") != "activated"
c._tp.script.append((200, {}, {"data": {"instance_id": c.state_store.load()["instance_id"],
"status": "activated",
"certificate": envelope(
cert_payload(product_id=3), priv_key, "cert")}}))
assert c.activate()["ok"] is True
assert c.status()["product_id"] == 3
def test_concurrent_heartbeats_serialized(priv_key, client):
"""循环/自愈/手动三方并发:必须串行(各自完整操作、键不互踩、状态不撕)。"""
base = client._tp.__call__
def slow(method, url, body, headers):
time.sleep(0.05)
return base(method, url, body, headers)
client._send_fn = slow
client._tp.script.append(active_env(priv_key))
client._tp.script.append(active_env(priv_key))
rs = []
def beat():
rs.append(client.heartbeat())
ts = [threading.Thread(target=beat) for _ in range(2)]
[t.start() for t in ts]
[t.join() for t in ts]
assert all(r["ok"] for r in rs)
keys = [c["headers"].get("Idempotency-Key") for c in client._tp.calls]
assert len(keys) == 2 and len(set(keys)) == 2 # 两个独立操作、两把键
st = client.state_store.load()
assert st["enabled"] is True and "heartbeat_op" not in st
def test_gate_can_run_safe_uses_cache(priv_key, client):
"""门禁入口 can_run_safe 走同一缓存:TTL 内重复调用不再触发落盘。"""
client.cache_ttl = 600
client.mono_fn = (lambda: 1000.0)
client._tp.script.append(active_env(priv_key))
client.heartbeat()
a = client.can_run_safe()
b = client.can_run_safe()
assert a[0] is True and b[0] is True

View File

@@ -0,0 +1,189 @@
# -*- coding: utf-8 -*-
"""验签单元测试:包内向量 + 全套负向(篡改/未知密钥/撤销/实例不匹配/v1/额外字段/
非法类型/CR-LF-NUL/Base64URL/canonical_sha256 不符/非 P-256 公钥)。"""
import hashlib
from datetime import timedelta
import pytest
from cryptography.hazmat.primitives.asymmetric import ec
from lic_helpers import (IID, IID2, NOW, canonical, cert_payload, envelope,
lease_payload, load_vectors, sign_b64)
from license_client.verify import (LICENSE_V2, LEASE_V2, VerifyError,
build_keyring, canonical_bytes,
verify_certificate, verify_lease)
# ------------------------------------------------------------ 包内随机测试向量
def test_package_vectors_canonical_matches():
"""先验规范化串本身:我们拼的字节必须和接入包给的 canonical 逐字节一致。"""
v = load_vectors()
for kind, version in (("license", LICENSE_V2), ("lease", LEASE_V2)):
assert canonical_bytes(v[kind]["payload"], version) == v[kind]["canonical"].encode("utf-8")
assert hashlib.sha256(v[kind]["canonical"].encode("utf-8")).hexdigest() \
== v[kind]["canonical_sha256"]
def test_package_vectors_verify():
"""用包内随机测试公钥过 license-v2 / lease-v2 验签(接入包要求的先行动作)。"""
v = load_vectors()
ring = build_keyring(v["pinned_keys"])
lic = {"version": LICENSE_V2,
"payload": v["license"]["payload"],
"signature": v["license"]["signature"],
"canonical_sha256": v["license"]["canonical_sha256"]}
assert verify_certificate(lic, IID, ring)["version"] == LICENSE_V2
lease = {"payload": v["lease"]["payload"],
"signature": v["lease"]["signature"],
"canonical_sha256": v["lease"]["canonical_sha256"],
"algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": 60}
assert verify_lease(lease, IID, ring)["state"] == "active"
# ------------------------------------------------------------ 正常路径
def test_roundtrip_cert_and_lease(priv_key, keyring):
p = cert_payload()
assert verify_certificate(envelope(p, priv_key, "cert"), IID, keyring) == p
p2 = lease_payload()
assert verify_lease(envelope(p2, priv_key, "lease"), IID, keyring) == p2
# ------------------------------------------------------------ 篡改与伪造
def test_tampered_payload_field(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env["payload"]["state"] = "frozen" # 换状态不换签名
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_tampered_signature(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
sig = env["signature"]
env["signature"] = ("A" if sig[0] != "A" else "B") + sig[1:]
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_signed_by_foreign_key(keyring):
evil = ec.generate_private_key(ec.SECP256R1())
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(), evil, "lease"), IID, keyring)
def test_unknown_key_id(priv_key):
ring = build_keyring([]) # 空信任根
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(), priv_key, "lease"), IID, ring)
def test_revoked_key(priv_key):
from lic_helpers import make_keyring
ring = make_keyring(priv_key, revoked=True)
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(), priv_key, "lease"), IID, ring)
def test_instance_mismatch(priv_key, keyring):
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(iid=IID2), priv_key, "lease"), IID, keyring)
# ------------------------------------------------------------ 结构拒绝
def test_v1_rejected(priv_key, keyring):
p = lease_payload(version="lease-v1")
with pytest.raises(VerifyError):
verify_lease(envelope(p, priv_key, "lease"), IID, keyring)
def test_missing_field(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env["payload"].pop("key_id") # 先签名再抠字段:canonical 与字段集必须双双拒
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_extra_field(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env["payload"]["extra"] = "x"
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_wrong_types(priv_key, keyring):
def bad_cert(mut):
env = envelope(cert_payload(), priv_key, "cert")
mut(env["payload"])
return env
with pytest.raises(VerifyError): # ID 变字符串
verify_certificate(bad_cert(lambda p: p.update(license_id="1")), IID, keyring)
with pytest.raises(VerifyError): # ID 非正数
verify_certificate(bad_cert(lambda p: p.update(license_id=0)), IID, keyring)
with pytest.raises(VerifyError): # bool 冒充整数
verify_certificate(bad_cert(lambda p: p.update(license_id=True)), IID, keyring)
with pytest.raises(VerifyError): # 非法状态枚举
verify_lease(bad_cert(lambda p: p.update(state="睡了的")), IID, keyring)
with pytest.raises(VerifyError): # 时间格式坏
verify_lease(bad_cert(lambda p: p.update(server_time="2026/10/09 03:00:00")),
IID, keyring)
with pytest.raises(VerifyError): # instance_id 非 UUID
verify_certificate(bad_cert(lambda p: p.update(instance_id="not-a-uuid")),
IID, keyring)
def test_cr_lf_nul_in_fields(priv_key, keyring):
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(key_id="k\nid"), priv_key, "lease"), IID, keyring)
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(key_id="k\r"), priv_key, "lease"), IID, keyring)
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(key_id="k\x00"), priv_key, "lease"), IID, keyring)
def test_base64url_signature_rejected(priv_key, keyring):
"""Base64URL 字母表(-/_)不是标准 Base64:出现即拒,不猜填充。"""
env = envelope(lease_payload(), priv_key, "lease")
env["signature"] = "-" + env["signature"][1:]
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
env2 = envelope(lease_payload(), priv_key, "lease")
env2["signature"] = "_" + env2["signature"][1:]
with pytest.raises(VerifyError):
verify_lease(env2, IID, keyring)
def test_canonical_sha_mismatch(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease", sha="0" * 64)
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_non_p256_key_rejected_at_ring_build():
p384 = ec.generate_private_key(ec.SECP384R1())
from cryptography.hazmat.primitives import serialization
pem = p384.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo).decode("ascii")
with pytest.raises(VerifyError):
build_keyring([{"key_id": "k", "public_key_pem": pem}])
def test_lease_envelope_requires_algorithm_and_next(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env.pop("algorithm")
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
env2 = envelope(lease_payload(), priv_key, "lease", next_hb=30) # < 60 拒
with pytest.raises(VerifyError):
verify_lease(env2, IID, keyring)
def test_cert_envelope_missing_version(priv_key, keyring):
env = envelope(cert_payload(), priv_key, "cert")
env.pop("version")
with pytest.raises(VerifyError):
verify_certificate(env, IID, keyring)

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
"""wipe 清场防回归(2026-10-10)。
背景:wipe 手工枚举清表清单两次漏表(2026-09-30 s_sections、2026-10-10 s_lme_res),
每次漏表 = 「重新解析」不断叠加脏数据(台班组成曾叠到 13 份)。
改造后 wipe 按 sqlite_master 动态发现 s_ 表,本测试钉死两条防线:
① 未来新建任何带 session_id 的 s_ 表(即使谁都不记得它),wipe 必然清它;
② WIPE_KEEP 里的表(s_remarks/s_settings)任何情况下不被清。
"""
import sqlite3
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "core"))
import session_job # noqa: E402
def _mk_db():
con = sqlite3.connect(":memory:")
c = con.cursor()
# 业务表形状(简化自 schema,只保留 wipe 相关列)
c.execute("CREATE TABLE s_bills (id INTEGER PRIMARY KEY, session_id INT)")
c.execute("CREATE TABLE s_norms (id INTEGER PRIMARY KEY, bill_id INT)") # 无 session_id
c.execute("CREATE TABLE s_norm_res (id INTEGER PRIMARY KEY, norm_id INT)") # 无 session_id
# ⭐ 模拟「未来新表」:带 session_id 的普通数据表,谁都不用记得登记
c.execute("CREATE TABLE s_future_thing (id INTEGER PRIMARY KEY, session_id INT)")
# 保留清单里的表
c.execute("CREATE TABLE s_remarks (id INTEGER PRIMARY KEY, session_id INT)")
c.execute("CREATE TABLE s_settings (id INTEGER PRIMARY KEY, session_id INT)")
# sessions 表(s_ 前缀误匹配检查:'sessions' 不应以通配方式被清/被当数据表)
c.execute("CREATE TABLE sessions (id INTEGER PRIMARY KEY)")
# 数据
c.execute("INSERT INTO sessions VALUES (58)")
c.execute("INSERT INTO s_bills (session_id) VALUES (58)")
c.execute("INSERT INTO s_norms (bill_id) VALUES (1)")
c.execute("INSERT INTO s_norms (bill_id) VALUES (NULL)") # 孤儿定额
c.execute("INSERT INTO s_norm_res (norm_id) VALUES (1)")
c.execute("INSERT INTO s_norm_res (norm_id) VALUES (NULL)") # 孤儿消耗量
c.execute("INSERT INTO s_future_thing (session_id) VALUES (58)")
c.execute("INSERT INTO s_remarks (session_id) VALUES (58)")
c.execute("INSERT INTO s_settings (session_id) VALUES (58)")
con.commit()
return con
def test_wipe_clears_future_tables():
"""⭐ 核心防线:未来加的新表(带 session_id)即使没人同步 wipe 也必被清。"""
con = _mk_db()
session_job.wipe(con, 58)
assert con.execute("SELECT COUNT(*) FROM s_future_thing").fetchone()[0] == 0
def test_wipe_clears_known_tables():
con = _mk_db()
session_job.wipe(con, 58)
for t in ("s_bills",):
assert con.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] == 0, t
# 定额按 bill_id 绕层清 + 孤儿全清
assert con.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0] == 0
assert con.execute("SELECT COUNT(*) FROM s_norm_res").fetchone()[0] == 0
def test_wipe_keeps_remarks_and_settings():
"""保留清单:备注与设置跨重新解析存活。"""
con = _mk_db()
session_job.wipe(con, 58)
assert con.execute("SELECT COUNT(*) FROM s_remarks").fetchone()[0] == 1
assert con.execute("SELECT COUNT(*) FROM s_settings").fetchone()[0] == 1
def test_wipe_scoped_to_session_and_keeps_sessions_row():
con = _mk_db()
c = con.cursor()
c.execute("INSERT INTO s_bills (session_id) VALUES (99)") # 别的会话
c.execute("INSERT INTO s_remarks (session_id) VALUES (99)")
con.commit()
session_job.wipe(con, 58)
assert c.execute("SELECT COUNT(*) FROM s_bills WHERE session_id=99").fetchone()[0] == 1
assert c.execute("SELECT COUNT(*) FROM sessions WHERE id=58").fetchone()[0] == 1
def test_wipe_keep_list_has_documented_members():
"""保留清单必须精确等于这两张表 —— 多了会漏清数据,少了会丢用户数据。"""
assert session_job.WIPE_KEEP == {"s_remarks", "s_settings"}

View File

@@ -0,0 +1,39 @@
{
"lease": {
"canonical": "version=lease-v2\ninstance_id=11111111-2222-3333-4444-555555555555\nstate=active\nserver_time=2026-10-09T03:00:00Z\nentitlement_expires_at=2027-10-09T03:00:00Z\nlease_expires_at=2026-10-23T03:00:00Z\nkey_id=integration-test-only",
"canonical_sha256": "da433cd2ec57a9ebf1f6a47e30521682e205f397ce5988b05785511a3e428aac",
"payload": {
"entitlement_expires_at": "2027-10-09T03:00:00Z",
"instance_id": "11111111-2222-3333-4444-555555555555",
"key_id": "integration-test-only",
"lease_expires_at": "2026-10-23T03:00:00Z",
"server_time": "2026-10-09T03:00:00Z",
"state": "active",
"version": "lease-v2"
},
"signature": "MEUCIC7K5MBrMw2M+mTnI8V14qUbgsqafewS+iFxnW2t7g68AiEAkBpVMJWsZ8T8szdvZHbR24PSiZbXHIWrNedh/+X/g2I"
},
"license": {
"canonical": "version=license-v2\ninstance_id=11111111-2222-3333-4444-555555555555\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-10-09T03:00:00Z\nexpires_at=2027-10-09T03:00:00Z\nkey_id=integration-test-only",
"canonical_sha256": "81d4930737bf289e752f5f37f43f9a0dfa0c0692075b2dba3d4d643ec1602355",
"payload": {
"customer_id": 2,
"expires_at": "2027-10-09T03:00:00Z",
"instance_id": "11111111-2222-3333-4444-555555555555",
"key_id": "integration-test-only",
"license_id": 1,
"product_id": 3,
"starts_at": "2026-10-09T03:00:00Z",
"version": "license-v2"
},
"signature": "MEUCIQDGb8FCV0JWvdE6UrMoscU9ZaidDajGGecslbI8A5xNkgIgVmI7IHlQQi5qhaulYNM9u27INVmXgPrNwNYLQsJrTJw"
},
"pinned_keys": [
{
"key_id": "integration-test-only",
"public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhrrB+tsg5H7cPScLrwZh/2q6fPx7\nSfzrQwmlKlJV74r0j0r5qPINY59icRBa42fEQTDI6hd9faWGifSW8Fb+jw==\n-----END PUBLIC KEY-----\n",
"revoked": false
}
],
"warning": "TEST ONLY: never trust this key in production; use frozen now=2026-10-09T03:00:00Z for state tests"
}

View File

@@ -0,0 +1,144 @@
#!/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()

View File

@@ -0,0 +1,350 @@
#!/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())

View File

@@ -0,0 +1,169 @@
#!/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())

View File

@@ -0,0 +1,252 @@
# -*- 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()

View File

@@ -0,0 +1,83 @@
# -*- 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)

View File

@@ -0,0 +1,173 @@
# -*- 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())

View File

@@ -0,0 +1,158 @@
#!/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())

View File

@@ -0,0 +1,177 @@
#!/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())

View File

@@ -0,0 +1,133 @@
# -*- 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__)

View File

@@ -0,0 +1,179 @@
#!/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)

View File

@@ -0,0 +1,711 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>造价审核 · 工作台</title>
<style>
:root{--c1:#123a6b;--c2:#1f5fae;--line:#e2e8f0;--head:#f6f9fd;--muted:#7b8794}
*{box-sizing:border-box}
body{margin:0;font:13px/1.5 -apple-system,"Segoe UI","Microsoft YaHei",sans-serif;color:#1f2937;background:#f5f6f8;height:100vh;display:flex;flex-direction:column}
h1{font-size:16px;margin:0}
.top{display:flex;align-items:center;gap:12px;padding:10px 16px;background:#fff;border-bottom:1px solid var(--line)}
.top .info{color:var(--muted);font-size:12px}
.btn{padding:5px 12px;border:1px solid #b8c4d4;border-radius:6px;background:#fff;cursor:pointer;font:inherit;font-size:12.5px;color:#26405e}
.btn:hover{background:#f2f6fb}
.btn.pri{background:var(--c2);border-color:var(--c2);color:#fff;font-weight:600}
.tabs{display:flex;gap:2px;padding:0 16px;background:#fff;border-bottom:2px solid var(--c1)}
.tab{padding:8px 16px;cursor:pointer;color:#456;font-size:13px;border-bottom:2px solid transparent;margin-bottom:-2px}
.tab.on{color:var(--c1);font-weight:700;border-bottom-color:var(--c1)}
.tab .n{background:#eef2f7;border-radius:8px;padding:0 6px;font-size:11px;margin-left:4px;color:#567}
.wrap{flex:1;display:flex;flex-direction:column;min-height:0;overflow:hidden}
.panel{flex:1 1 auto;min-height:0;overflow:auto;display:none;background:#fff}
.panel.on{display:block}
table{width:100%;border-collapse:collapse;font-size:12.5px;table-layout:fixed}
th{position:sticky;top:0;background:var(--head);color:var(--c1);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);border-right:1px solid #eef1f6;white-space:nowrap;z-index:2}
td{padding:5px 8px;border-bottom:1px solid #eef1f6;border-right:1px solid #f4f6f9;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
tbody tr:hover td{background:#f6f9fd}
tr.sel td{background:#e8f0fb;outline:1px solid var(--c2);outline-offset:-1px}
.c{text-align:center}.r{text-align:right}.num{text-align:right;font-variant-numeric:tabular-nums}
.grp td{background:#f4f7fb;font-weight:700;color:#34506f}
.attr{white-space:pre-wrap}
.empty{padding:24px;text-align:center;color:var(--muted)}
/* ---- 底部历史容器 ---- */
#histwrap{flex:0 0 auto;display:flex;flex-direction:column;background:#fff;border-top:1px solid var(--line)}
#histbar{display:flex;align-items:center;gap:8px;padding:5px 12px;background:#fafcff;border-bottom:1px solid var(--line);min-height:32px;flex-wrap:wrap}
#histbar .cur{font-weight:700;color:#1c2430}
#histbar .cur b{color:var(--c2)}
#histbar select{padding:3px 6px;border:1px solid #b8c4d4;border-radius:5px;font:inherit;font-size:12px}
#histbar .hb{border:1px solid #b8c4d4;background:#fff;border-radius:5px;padding:2px 9px;font-size:12px;cursor:pointer;color:var(--c2);font-weight:600}
#histbar .sp{margin-left:auto;color:var(--muted);font-size:11.5px}
#histbody{height:330px;overflow:auto;display:flex;flex-direction:column}
#histwrap.folded #histbody{display:none}
#hfilter{padding:6px 12px;background:#fbfcfe;border-bottom:1px solid var(--line);display:flex;gap:14px;flex-wrap:wrap;align-items:flex-start;font-size:12px}
#hfilter .fg{display:flex;flex-direction:column;gap:3px}
#hfilter .fg b{font-size:11px;color:var(--muted);font-weight:600}
#hfilter .opts{max-height:76px;overflow:auto;border:1px solid var(--line);border-radius:5px;padding:3px 6px;background:#fff;min-width:150px}
#hfilter label{display:block;cursor:pointer;white-space:nowrap}
#histtblwrap{flex:1;overflow:auto}
#hmfoot{display:flex;gap:18px;align-items:center;flex-wrap:wrap;padding:5px 12px;background:#fbfcfe;border-top:1px solid var(--line);font-size:11.5px;color:var(--muted)}
#hmfoot b{color:#1c2430}
.up{color:#c62828;font-weight:700}.down{color:#1e8e3e;font-weight:700}
.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}
.lk{color:var(--c2);cursor:pointer;text-decoration:none;border-bottom:1px dashed #9dbbe0}
.lk:hover{color:var(--c1)}
.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;width:640px;max-width:94vw;display:flex;flex-direction:column;overflow:hidden}
.dlg h4{margin:0;padding:13px 18px;font-size:14.5px;border-bottom:1px solid var(--line);background:var(--head);color:var(--c1)}
.dlg .mbody{padding:14px 18px;display:flex;flex-direction:column;gap:10px}
.dlg .row{display:flex;gap:8px;align-items:center}
.dlg .row span{width:88px;color:#456}
.dlg .row input,.dlg .row select{flex:1;padding:5px 8px;border:1px solid #b8c4d4;border-radius:6px;font:inherit;font-size:13px}
.dlg .mfoot{padding:12px 18px;display:flex;justify-content:flex-end;gap:10px;border-top:1px solid var(--line);background:#fafcff}
.tip{color:var(--muted);font-size:11.5px}
/* 分组/匹配 设置面板(2026-10-01) */
.cfgsec{border:1px solid var(--line);border-radius:8px;padding:10px 12px;background:#fbfcff}
.cfgsec .cfghd{display:flex;align-items:center;gap:8px;font-weight:700;color:var(--c1);margin-bottom:6px}
.cfgsec .cfghd .btn{margin-left:0;padding:3px 9px;font-size:12px}
.cfgsec .cfghd .btn:first-of-type{margin-left:auto}
.cfgrow{display:flex;gap:8px;align-items:flex-start;margin:6px 0;padding:6px;border:1px solid #e3e9f1;border-radius:6px;background:#fff}
.cfgrow .cfgcol{display:flex;flex-direction:column;gap:3px;min-width:0}
.cfgrow .cfgcol-name{width:150px;flex:none}
.cfgrow .cfgcol-kw{flex:2}
.cfgrow .cfgcol-ex{flex:2}
.cfgrow .cfgcol-exu{flex:1}
.cfgrow .cfglbl{font-size:11px;color:#5a6b7e;font-weight:600;white-space:nowrap}
.cfgrow .cfgname,.cfgrow .cfgkw,.cfgrow .cfgex,.cfgrow .cfgexu{width:100%;box-sizing:border-box;padding:5px 8px;border:1px solid #b8c4d4;border-radius:6px;font:inherit;font-size:13px}
.cfgrow .cfgkw,.cfgrow .cfgex,.cfgrow .cfgexu{min-height:40px;resize:vertical;line-height:1.5;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
.cfgrow .cfgex,.cfgrow .cfgexu{background:#fff8f8;border-color:#d8b4b4}
.cfgtabs{display:flex;gap:8px;margin-bottom:8px}
.cfgtab{padding:6px 18px;border:1px solid #c2ccd8;border-radius:6px;background:#eef2f7;font:inherit;font-size:13px;cursor:pointer;color:#456}
.cfgtab.on{background:#fff;border-color:var(--c1);font-weight:700;color:var(--c1)}
.cfgpanel{margin-top:2px}
.cfgrow .cfgop{display:flex;flex-direction:column;gap:3px;flex:none}
.cfgrow .cfgop button{width:30px;padding:2px 0;font-size:13px;border:1px solid #b8c4d4;border-radius:5px;background:#fff;cursor:pointer}
.cfgrow .cfgop button:hover{background:#eef3fa}
#cfgGroups{max-height:340px;overflow-y:auto;overflow-x:hidden;padding:2px 4px 2px 0;border:1px solid #e3e9f0;border-radius:6px;background:#fbfcfe}
#cfgGroups .cfgrow .gpri{font-size:11px;color:#1e8e3e;font-weight:700;width:18px;flex:none;align-self:center}
.chips{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0;min-height:20px}
.chips:empty::before{content:"暂无过滤词";color:#9aa7b5;font-size:12px}
.chip{display:inline-flex;align-items:center;gap:5px;background:#eef3fa;border:1px solid #c4d2e3;border-radius:14px;padding:3px 10px;font-size:13px;color:#2b3a4a}
.chip .x{cursor:pointer;color:#9aa7b5;font-weight:700;line-height:1;font-size:14px}
.chip .x:hover{color:#e5484d}
.chip-add{display:flex;gap:8px;margin-top:6px}
.chip-input{flex:1;padding:6px 8px;border:1px solid #b8c4d4;border-radius:6px;font:inherit;font-size:13px}
#copymask{z-index:120}
.copylist{display:flex;flex-direction:column;gap:6px;margin-top:8px}
.copylist button{text-align:left;padding:9px 12px;border:1px solid #b8c4d4;border-radius:6px;background:#fff;font:inherit;font-size:13px;color:#2b3a4a;cursor:pointer}
.copylist button:hover{background:#eef3fa;border-color:var(--c1)}
.copylist .cnt{color:#5a6b7e;font-size:12px}
</style>
<link rel="stylesheet" href="common.css">
</head>
<body>
<div class="top">
<h1>造价审核 · 工作台</h1>
<span class="info" id="sinfo">尚未打开工程</span>
<button class="btn pri" onclick="openDlg()">打开工程</button>
<button class="btn" onclick="cfgOpen()">⚙ 设置</button>
<a class="btn" href="/admin.html">后台管理</a>
<span class="info" id="msg"></span>
</div>
<!-- 标签由 common.js 的 TABS 派生(顺序/名称与工作台、后台同源;本页暂缺「原数据」面板) -->
<div class="tabs"><span id="tabbar" style="display:contents"></span></div>
<div class="wrap">
<div class="panel on" id="pan0"><table id="t0"><colgroup id="cg0"></colgroup><thead id="th0"></thead><tbody id="tb0"></tbody></table></div>
<div class="panel" id="pan1"><table id="t1"><colgroup id="cg1"></colgroup><thead id="th1"></thead><tbody id="tb1"></tbody></table></div>
<div class="panel" id="pan2"><table id="t2"><colgroup id="cg2"></colgroup><thead id="th2"></thead><tbody id="tb2"></tbody></table></div>
<div id="histwrap">
<div id="histbar">
<span class="cur" id="hcur">点上面任意一行,这里显示它的历史价</span>
<span style="font-size:12px;color:#456">期次</span>
<input id="hper" style="width:150px" placeholder="全部期次(点这里选起~止)">
<button class="hb" onclick="setPeriod($('hper'),'','');search()">清除</button>
<select id="htier">
<option value="es" selected>精确 + 次精确</option>
<option value="e">只看精确</option>
<option value="all">全部(含模糊)</option>
</select>
<select id="hsort">
<option value="time">按时间(先近后远)</option>
<option value="asc">按价格(低→高)</option>
<option value="desc">按价格(高→低)</option>
</select>
<button class="hb" id="fbtn" onclick="toggleF()">筛选 ▾</button>
<button class="hb" onclick="doExport()">导出本结果</button>
<button class="hb" id="foldBtn" onclick="toggleFold()">▾ 收起</button>
<span class="sp" id="hcnt"></span>
</div>
<div id="histbody">
<div id="hfilter" style="display:none">
<div class="fg"><b>文件类型</b><div class="opts" id="fkind"></div></div>
<div class="fg"><b>建设单位</b><div class="opts" id="funit"></div></div>
<div class="fg"><b>信息价目录</b><div class="opts" id="fcls"></div></div>
<div class="fg"><b>来源</b><div class="opts" id="fsrc">
<label><input type="checkbox" class="fchk" data-g="fsrc" value="project" checked onchange="search()"> 历史项目</label>
<label><input type="checkbox" class="fchk" data-g="fsrc" value="info" checked onchange="search()"> 信息价</label>
<label><input type="checkbox" class="fchk" data-g="fsrc" value="market" checked onchange="search()"> 市场价</label>
</div></div>
<div class="fg"><b>&nbsp;</b><button class="btn" onclick="resetF()">重置(全选)</button></div>
</div>
<div id="histtblwrap"><table id="ht"><colgroup id="hcg"></colgroup><thead id="hth"></thead><tbody id="htb"></tbody></table></div>
<div id="hmfoot"></div>
</div>
</div>
</div>
<div class="mask" id="omask">
<div class="dlg">
<h4>打开工程(只审核,不入库)</h4>
<div class="mbody">
<div class="row"><span>工程文件 *</span><input type="file" id="ofile" accept=".cos4,.cos,.xml" onchange="autoName()"></div>
<div class="row"><span>名称 *</span><input id="oname" placeholder="选文件后自动带出文件名,可改"></div>
<div class="row"><span>基准期次 *</span><input id="oper" placeholder="点这里选起~止(同月就选同一个)"></div>
<div class="row"><span>地区</span>
<select id="oprov"><option value="">省</option></select>
<select id="ocity"><option value="">市</option></select>
<select id="odist"><option value="">区/县</option></select>
</div>
<div class="row"><span>建设单位</span><input id="obuid"></div>
<div class="tip">打开后进入「会话库」,数据完整(含工程量/合价/数量),用于跟原件逐条核对;不会进历史底库。</div>
<div class="tip" id="omsg"></div>
</div>
<div class="mfoot">
<button class="btn" onclick="omask.classList.remove('on')">取消</button>
<button class="btn pri" onclick="doOpen()">打开</button>
</div>
</div>
</div>
<script src="common.js"></script>
<script src="period.js"></script>
<script>
let SID=0, CUR=null, CURTYPE='lme', HROWS=[], FOPT={};
const $=id=>document.getElementById(id);
async function J(u,o){const r=await fetch(u,o);return r.json()}
// esc / num / fmtAttr 由 common.js 提供(三页唯一来源)
function ym(s){const m=/^(\d{4})-(\d{1,2})$/.exec((s||'').trim());return m?(+m[1])*12+(+m[2]):null}
// 列定义来自 common.js(三页**唯一来源**)—— 禁止在此另写一份
const C_LME = COLS.lme;
const C_BILL = COLS.bill;
// 与工作台的差异只在数据源,渲染一律走 common.js
var WB_OPTS = { rowClick: 'pick', normApi: '/api/session/bill/' };
const C_H=[['档位',62,'c'],['名称',190,'l'],['规格/特征',170,'l'],['单位',52,'c'],['单价',96,'r'],
['价差%',80,'r'],['来源',110,'l'],['期次',76,'c'],['相似度',64,'r'],['操作',150,'c']];
// head / colg 由 common.js 提供
function head(cols){ return headHTML(cols); }
function colg(el,cols){ $(el).innerHTML = colgHTML(cols); }
document.addEventListener('DOMContentLoaded', function(){
var bar=document.getElementById('tabbar');
if(bar) bar.innerHTML=tabsHTML(['p3']); // 顺序/名称与两侧同源;本页暂缺原数据面板
});
function onWBTab(p){ tab(p); }
function tab(p){
document.querySelectorAll('.tab').forEach(t=>t.classList.toggle('on',t.dataset.p===p));
['p0','p1','p2'].forEach((x,i)=>$('pan'+i).classList.toggle('on',x===p));
if(p==='p1'||p==='p2') loadGroups(p==='p1'?'inconsistent':'similar');
}
/* ---------- 打开工程 ---------- */
function openDlg(){
$('ofile').value=''; $('oname').value=''; $('oname').dataset.auto=''; $('omsg').textContent='';
$('omask').classList.add('on');
}
// 选好文件后,工程名称默认 = 文件名(去掉扩展名),可手动改
function autoName(){
const f=$('ofile').files[0];
if(!f) return;
const stem=f.name.replace(/\.[^.]+$/,'');
if(!$('oname').value.trim() || $('oname').dataset.auto==='1') $('oname').value=stem;
$('oname').dataset.auto='1';
}
async function doOpen(){
const f=$('ofile').files[0];
if(!f){ $('omsg').textContent='请选择文件'; return; }
const pv=PVAL($('oper'));
if(pv.f==null||pv.t==null){ $('omsg').textContent='基准期次必填:点开选起~止(同一个月就选同一个)'; return; }
$('omsg').textContent='正在解析…';
const data=await new Promise(res=>{const r=new FileReader();r.onload=()=>res(r.result);r.readAsDataURL(f)});
const up=await J('/api/admin/upload',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({name:f.name,data})});
if(!up.ok){ $('omsg').textContent=up.msg; return; }
const r=await J('/api/audit',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({path:up.path,name:$('oname').value||f.name,
period_from:pv.f, period_to:pv.t, base_period_m:pv.f,
province:$('oprov').value,city:$('ocity').value,district:$('odist').value,
bulid_unit:$('obuid').value})});
if(!r.ok){ $('omsg').textContent=r.msg; return; }
SID=r.session_id;
$('sinfo').innerHTML=`<b>${esc($('oname').value||f.name)}</b> · 基准 ${esc($('oper').value)} · 清单 ${r.n_bill} · 定额 ${r.n_norm} · 工料机 ${r.n_lme}`;
$('omask').classList.remove('on');
await loadLme(); await loadFilters(); tab('p0');
$('msg').textContent=r.msg;
}
/* ---------- 三个标签 ---------- */
async function loadLme(){
const d=await J(`/api/session/rows?session_id=${SID}&type=lme`);
$('n0').textContent=d.total+' 项';
colg('cg0',C_LME); $('th0').innerHTML=head(C_LME);
$('tb0').innerHTML=renderLme(d.rows, WB_OPTS)
||'<tr><td colspan="11" class="empty">还没有打开工程</td></tr>';
}
async function loadGroups(kind){
const d=await J(`/api/session/${kind}?session_id=${SID}`);
(kind==='inconsistent'?$('n1'):$('n2')).textContent=d.total+' 组';
const el = kind==='inconsistent' ? ['cg1','th1','tb1'] : ['cg2','th2','tb2'];
colg(el[0],C_BILL); $(el[1]).innerHTML=head(C_BILL);
// 组行/清单行/组标题/价差标红 → 与工作台、后台同一份 common.js 实现
$(el[2]).innerHTML=renderGroups(d, kind, WB_OPTS);
}
/* ---------- 选一行 → 历史比对 ---------- */
async function pick(type,id,tr){
document.querySelectorAll('tr.sel').forEach(x=>x.classList.remove('sel'));
tr.classList.add('sel');
CURTYPE=type; CUR={id};
const nm = type==='lme' ? tr.children[2].textContent : tr.children[3].textContent;
const pr = type==='lme' ? tr.children[6].textContent : tr.children[7].textContent;
$('hcur').innerHTML=`当前:<b>${esc(nm)}</b> 报价 <b>${esc(pr)}</b>`;
await search();
}
async function search(){
if(!SID||!CUR) return;
const srcs=selVals('fsrc'); if(!srcs.length) srcs.push('project','info','market');
const r=await J('/api/search',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({session_id:SID,type:CURTYPE,row_id:CUR.id,limit:50,
file_kinds:selVals('fkind'),bulid_units:selVals('funit'),classes:selVals('fcls'),
srcs:srcs, period_from:PVAL($('hper')).f, period_to:PVAL($('hper')).t})});
if(!r.ok){ $('htb').innerHTML=`<tr><td colspan="10" class="empty">${esc(r.msg)}</td></tr>`; return; }
HROWS=r.rows||[];
renderHist();
}
function curPrice(){
const tr=document.querySelector('tr.sel'); if(!tr) return null;
const t = CURTYPE==='lme' ? tr.children[6].textContent : tr.children[7].textContent;
const v = parseFloat((t||'').replace(/,/g,'')); return isNaN(v)?null:v;
}
function renderHist(){
const tiers = $('htier').value==='all' ? ['精确','次精确','模糊']
: ($('htier').value==='e' ? ['精确'] : ['精确','次精确']);
let rows = HROWS.filter(x=>tiers.includes(x.tier));
const s=$('hsort').value;
if(s==='asc') rows=[...rows].sort((a,b)=>(a.price??0)-(b.price??0));
else if(s==='desc') rows=[...rows].sort((a,b)=>(b.price??0)-(a.price??0));
else rows=[...rows].sort((a,b)=>a.dist-b.dist);
const cur=curPrice();
colg('hcg',C_H); $('hth').innerHTML=head(C_H);
$('htb').innerHTML=rows.map((x,i)=>{
let d='—',cls='';
if(cur && x.price!=null){ const p=(x.price-cur)/cur*100;
d=(p>=0?'+':'')+p.toFixed(1)+'%'; cls=p>=0?'up':'down'; }
const op=[];
if(x.file) op.push(`<a class="lk" href="/api/admin/file/${x.file_sha}" target="_blank">原件</a>`);
op.push(`<a class="lk" onclick="adopt(${i})">采纳</a>`);
return `<tr><td class="c"><span class="tg tg-${x.tier==='精确'?'e':(x.tier==='次精确'?'s':'f')}">${x.tier}</span></td>
<td title="${esc(x.name)}">${esc(x.name)}</td><td title="${esc(x.attr)}">${esc(x.attr||'—')}</td>
<td class="c">${esc(x.unit)}</td><td class="r">${num(x.price)}</td>
<td class="r ${cls}">${d}</td><td title="${esc(x.proj)}">${esc(x.proj)}</td>
<td class="c">${esc(x.period)}</td><td class="r">${num(x.sim,2)}</td>
<td class="c">${op.join(' · ')}</td></tr>`;
}).join('')||`<tr><td colspan="${C_H.length}" class="empty">没有命中的历史项</td></tr>`;
const e=HROWS.filter(x=>x.tier==='精确').length,s_=HROWS.filter(x=>x.tier==='次精确').length,f=HROWS.filter(x=>x.tier==='模糊').length;
$('hcnt').textContent=`命中 ${HROWS.length}:精确 ${e} · 次精确 ${s_} · 模糊 ${f}${f?'(模糊默认不显示)':''}`;
// 统计
const vs=rows.map(x=>x.price).filter(v=>v!=null).sort((a,b)=>a-b);
let foot='';
if(vs.length){
const sum=vs.reduce((a,b)=>a+b,0), mid=vs[Math.floor(vs.length/2)];
foot=`最低 <b>${num(vs[0])}</b> · 最高 <b>${num(vs[vs.length-1])}</b> · 均价 <b>${num(sum/vs.length)}</b> · 中位数 <b>${num(mid)}</b>`;
if(cur){ const p=(mid-cur)/cur*100;
foot+=` · 与当前报价 <b class="${p>=0?'up':'down'}">${(p>=0?'+':'')+p.toFixed(1)}%</b>`; }
}
$('hmfoot').innerHTML=foot;
}
/* 采纳:只写进备注(不加新字段),随会话一起删 */
async function adopt(i){
const x=HROWS[i]; if(!x) return;
const tr=document.querySelector('tr.sel'); if(!tr) return;
const txt=`参考:${Number(x.price).toFixed(2)}(${x.period} ${x.proj})`;
await J('/api/session/remark',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({bill_id:CUR.id,remark:txt})});
const cell = tr.children[tr.children.length-1];
if(cell){ cell.textContent=txt; cell.title=txt; }
alert('已写入备注:\n'+txt+'\n\n(只存在会话里,删除该工程时一起清除)');
}
/* 筛选区 */
async function loadFilters(){
FOPT=await J('/api/filter_options');
const box=(el,arr,valKey,nameKey)=>{
$(el).innerHTML=arr.map(v=>{
const val=valKey?v[valKey]:v, nm=nameKey?v[nameKey]:v;
return `<label><input type="checkbox" class="fchk" data-g="${el}" value="${esc(val)}" checked onchange="search()"> ${esc(nm||val)}</label>`;
}).join('')||'<span class="tip">(无)</span>';
};
box('fkind',FOPT.file_kinds,'code','name'); box('funit',FOPT.bulid_units); box('fcls',FOPT.classes);
}
function selVals(g){
const els=document.querySelectorAll(`.fchk[data-g="${g}"]`);
const all=Array.from(els), on=all.filter(x=>x.checked);
return on.length===all.length?[]:on.map(x=>x.value); // 全选=不筛
}
function toggleF(){ const e=$('hfilter'); e.style.display = e.style.display==='none'?'flex':'none'; }
function resetF(){ document.querySelectorAll('.fchk').forEach(x=>x.checked=true); search(); }
function toggleFold(){
const w=$('histwrap'); w.classList.toggle('folded');
$('foldBtn').textContent = w.classList.contains('folded')?'▸ 展开':'▾ 收起';
}
function doExport(){
const cur=curPrice();
const rows=[['档位','名称','规格/特征','单位','单价','价差%','来源','期次','相似度']];
HROWS.forEach(x=>{ let d='';
if(cur&&x.price!=null){const p=(x.price-cur)/cur*100;d=(p>=0?'+':'')+p.toFixed(1)+'%';}
rows.push([x.tier,x.name,x.attr||'',x.unit,x.price,d,x.proj,x.period,x.sim]); });
const csv='\ufeff'+rows.map(r=>r.map(v=>`"${(v??'').toString().replace(/"/g,'""')}"`).join(',')).join('\n');
const a=document.createElement('a');
a.href=URL.createObjectURL(new Blob([csv],{type:'text/csv;charset=utf-8'}));
a.download='历史比对结果.csv'; a.click();
}
$('htier').onchange=renderHist; $('hsort').onchange=renderHist;
mkPeriod($('hper'), ()=>search()); // 期次:一个面板一次选完起~止
mkPeriod($('oper')); // 打开工程:基准期次(起~止,同月填一样)
/* 历史容器:上下拉动调整高度(点控件时不触发) */
let dragY=0, dragH=0, dragging=false;
$('histbar').addEventListener('mousedown', function(e){
if(e.target.closest('select,button,input,label,a,span.lk')) return;
dragging=true; dragY=e.clientY; dragH=$('histbody').offsetHeight;
document.body.style.cursor='ns-resize'; e.preventDefault();
});
document.addEventListener('mousemove', function(e){
if(!dragging) return;
const h=Math.max(90, Math.min(window.innerHeight-170, dragH + (dragY-e.clientY)));
$('histbody').style.height=h+'px';
});
document.addEventListener('mouseup', function(){ if(dragging){dragging=false; document.body.style.cursor='';} });
(async()=>{ const f=await J('/api/admin/filters');
const fill=(el,arr,ph)=>{$(el).innerHTML=`<option value="">${ph}</option>`+arr.map(v=>`<option>${esc(v)}</option>`).join('')};
fill('oprov',f.province,'省'); fill('ocity',f.city,'市'); fill('odist',f.district,'区/县');
})();
/* ================= 分组/匹配 设置(2026-10-01) ================= */
let CFG = {prof:'', groups: []}; // groups: [{name, keywords, exclude}](排除单位列已取消)
let PROFS = []; // 专业列表,与工作台同一数据源(global/professions)
function cfgRowHTML(g, i){
return `<div class="cfgrow" data-i="${i}">
<span class="gpri">${i+1}</span>
<div class="cfgcol cfgcol-name">
<div class="cfglbl">组名称</div>
<input class="cfgname" placeholder="如 道路工程" value="${esc(g.name||'')}">
</div>
<div class="cfgcol cfgcol-kw">
<div class="cfglbl">关键词(名称+项目特征)</div>
<textarea class="cfgkw" placeholder="如 道路,路基,路面">${esc(g.keywords||'')}</textarea>
</div>
<div class="cfgcol cfgcol-ex">
<div class="cfglbl">排除(名称+项目特征)</div>
<textarea class="cfgex" placeholder="如 路面,垫层">${esc(g.exclude||'')}</textarea>
</div>
<div class="cfgop">
<button onclick="cfgUp(${i})" title="上移(提高优先级)">↑</button>
<button onclick="cfgDown(${i})" title="下移(降低优先级)">↓</button>
<button onclick="cfgDel(${i})" title="删除">✕</button>
</div></div>`;
}
function cfgRender(){
const box=$('cfgGroups');
box.innerHTML = CFG.groups.map((g,i)=>cfgRowHTML(g,i)).join('')
|| '<div class="tip">还没有分组。点右上角「+ 添加分组」,或「复制分组」从别的专业拷一套过来。</div>';
}
function cfgAddGroup(){ CFG.groups.push({name:'',keywords:'',exclude:''}); cfgRender(); }
function cfgDel(i){ CFG.groups.splice(i,1); cfgRender(); }
function cfgUp(i){ if(i>0){ const t=CFG.groups[i-1]; CFG.groups[i-1]=CFG.groups[i]; CFG.groups[i]=t; cfgRender(); } }
function cfgDown(i){ if(i<CFG.groups.length-1){ const t=CFG.groups[i+1]; CFG.groups[i+1]=CFG.groups[i]; CFG.groups[i]=t; cfgRender(); } }
function cfgCollect(){
const rows=Array.from(document.querySelectorAll('#cfgGroups .cfgrow'));
const out=[];
for(const row of rows){
const name=row.querySelector('.cfgname').value.trim();
const kw=row.querySelector('.cfgkw').value
.split(/[,,\s]+/).map(s=>s.trim()).filter(Boolean);
const ex=row.querySelector('.cfgex').value
.split(/[,,\s]+/).map(s=>s.trim()).filter(Boolean);
if(!name && !kw.length && !ex.length) continue; // 空行跳过
// 「排除单位」列已取消:同组必须同单位由后端「组内按单位拆平级组」保证(名称相同的除外)
out.push({name: name||('分组'+(out.length+1)), keywords: kw, exclude: ex, exclude_units: []});
}
return out;
}
async function cfgOpen(){
CFG.groups=[];
// 与工作台**同一数据源、同一口径**:分组配置只来自「本工程专业」(global/professions)
const [pf, prof, sw] = await Promise.all([
J('/api/professions'),
J(`/api/session/setting?scope=session:${SID}&k=profession`),
J('/api/session/setting?scope=global&k=match_stopwords')
]);
PROFS = (pf && pf.professions) ? pf.professions : [];
CFG.prof = (prof && prof.v) || (pf && pf.default) || (PROFS[0] && PROFS[0].name) || '';
const p = PROFS.find(x=>x.name===CFG.prof);
CFG.groups = ((p && p.groups) ? p.groups : []).map(g=>({name:g.name||'',keywords:(g.keywords||[]).join(','),exclude:(g.exclude||[]).join(',')}));
STOP = (sw && sw.v) ? (()=>{ try{ const a=JSON.parse(sw.v); return Array.isArray(a)?a:[]; }catch(e){ return []; } })() : [];
renderStop();
cfgRender();
$('cfgmask').classList.add('on');
}
function cfgClose(){ $('cfgmask').classList.remove('on'); }
async function cfgSave(){
const groups=cfgCollect();
const stop = STOP.slice();
// 写回「本工程专业」——与工作台同一数据源 professions(旧的 session 级 similar_groups 已废弃)
const p = PROFS.find(x=>x.name===CFG.prof);
if(p) p.groups = groups; else PROFS.push({name:CFG.prof||'默认', groups:groups});
await J('/api/session/setting',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({scope:'global', k:'professions', v:JSON.stringify(PROFS)})});
await J('/api/session/setting',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({scope:'global', k:'match_stopwords', v:JSON.stringify(stop)})});
cfgClose();
if(document.querySelector('.tab.on') && document.querySelector('.tab.on').dataset.p==='p2') loadGroups('similar');
}
// 「复制分组」:map 页本身没有专业体系,直接从全局专业列表选一个、把它的分组复制过来。
// 取代「载入默认 / 另存为默认」——那套依赖一个看不见的全局默认模板(similar_groups_default),
// 删掉「另存为默认」后就没入口写了;复制分组的来源是显式可见的某个专业。
let COPY_LIST = []; // 本次弹框里可复制的专业
function copyClose(){ $('copymask').classList.remove('on'); }
async function cfgCopyFromProf(){
let list=[];
try{ const pf=await J('/api/professions'); list=(pf && pf.professions)?pf.professions:[]; }catch(e){}
if(!list.length){ alert('还没有任何专业。请到工作台「分组/匹配 → 专业设置」里先建一个并配好分组。'); return; }
COPY_LIST = list;
const n = CFG.groups.length;
$('copyTip').innerHTML = n
? `⚠ 复制会<b>替换</b>当前已有的 <b>${n}</b> 个分组,点下面任一专业即执行。`
: '当前还没有分组,点下面任一专业即把它的分组复制过来。';
$('copyList').innerHTML = list.map((p,i)=>
`<button type="button" onclick="copyDo(${i})">${esc(p.name)}<span class="cnt">(${(p.groups||[]).length} 个分组)</span></button>`
).join('');
$('copymask').classList.add('on');
}
function copyDo(i){
const src = COPY_LIST[i]; if(!src) return;
// 破坏性操作:当前已有分组时才二次确认(原本为空则无损失,直接执行,不烦人)
const n = CFG.groups.length;
if(n && !confirm(`复制会用「${src.name}」的分组替换当前已有的 ${n} 个分组,继续?`)) return;
CFG.groups = (src.groups||[]).map(g=>({
name:g.name||'',
keywords:(g.keywords||[]).join(','),
exclude:(g.exclude||[]).join(',')
}));
cfgRender(); copyClose();
alert(`已复制「${src.name}」的 ${CFG.groups.length} 个分组。确认无误后点「保存」。`);
}
let STOP = []; // 历史匹配过滤词(全局),chip 形式管理
function renderStop(){
const box=$('cfgStopChips'); if(!box) return;
box.innerHTML = STOP.map(w=>`<span class="chip">${esc(w)}<span class="x" onclick="delStop(${JSON.stringify(w)})" title="删除">×</span></span>`).join('');
}
function addStop(){
const inp=$('cfgStopInput'); if(!inp) return;
const parts=inp.value.split(/[,,\s]+/).map(s=>s.trim()).filter(Boolean);
for(const w of parts){ if(w && !STOP.includes(w)) STOP.push(w); }
inp.value=''; renderStop();
}
function delStop(w){ STOP = STOP.filter(x=>x!==w); renderStop(); }
function cfgResetStop(){ STOP=[]; renderStop(); }
function cfgTab(name){
document.querySelectorAll('.cfgtab').forEach(b=>b.classList.toggle('on', b.dataset.tab===name));
$('cfgTabProf').style.display = name==='prof' ? 'block' : 'none';
$('cfgTabStop').style.display = name==='stop' ? 'block' : 'none';
}
</script>
<!-- ===== 区块编号标注层(只做定位用,不改结构/字段/逻辑) ===== -->
<style>
.maptag{position:absolute;top:-7px;left:-7px;z-index:80;background:#ff8c1a;color:#fff;
font:700 10px/1.5 Consolas,"Courier New",monospace;padding:0 4px;border-radius:3px;
box-shadow:0 1px 3px rgba(0,0,0,.3);pointer-events:none;letter-spacing:.3px;white-space:nowrap}
th .maptag{top:-6px;left:0;font-size:9px;padding:0 3px;background:#2f7dd1}
.mapbox{outline:2px dashed #ff8c1a !important;outline-offset:-2px !important}
#mapbtn{position:fixed;right:16px;bottom:16px;z-index:300;background:#ff8c1a;color:#fff;border:0;
border-radius:18px;padding:7px 14px;font:600 12.5px -apple-system,"Segoe UI","Microsoft YaHei",sans-serif;
cursor:pointer;box-shadow:0 3px 10px rgba(0,0,0,.28)}
#mappanel{position:fixed;right:16px;bottom:56px;width:430px;max-height:60vh;overflow:auto;z-index:300;
background:#fff;border:1px solid #d7dee8;border-radius:10px;box-shadow:0 8px 26px rgba(20,30,45,.22);display:none}
#mappanel .ph{padding:9px 12px;border-bottom:1px solid #e6ebf2;font-weight:700;color:#123a6b;font-size:13px;
display:flex;align-items:center;gap:8px;position:sticky;top:0;background:#f6f9fd}
#mappanel .ph .x{margin-left:auto;cursor:pointer;color:#7b8794;font-weight:400}
#mappanel table{width:100%;border-collapse:collapse;font-size:12px;table-layout:auto}
#mappanel td{padding:4px 8px;border-bottom:1px solid #f0f3f7;vertical-align:top;border-right:0}
#mappanel tr{cursor:pointer}
#mappanel tr:hover td{background:#fff6ec}
#mappanel td.k{width:52px;font:700 11px Consolas,monospace;color:#c25b00;white-space:nowrap}
#mapoff .maptag{display:none}
</style>
<script>
(function(){
const F=[
['A','.top','顶栏(整条)'],
['A1','.top h1','标题:造价审核 · 工作台'],
['A2','#sinfo','当前工程信息:名称·基准期次·清单/定额/工料机数'],
['A3','.top button[onclick="openDlg()"]','按钮:打开工程'],
['A4','.top a[href="/admin.html"]','链接:后台管理'],
['A5','#msg','操作结果提示文字'],
['B','.tabs','标签栏(整条)'],
['B1','.tab[data-p="p0"]','标签:项目工料机(右侧计数 n0)'],
['B2','.tab[data-p="p1"]','标签:组价不一致清单(计数 n1)'],
['B3','.tab[data-p="p2"]','标签:类似清单(计数 n2)'],
['C','.wrap','主表区 + 底部历史容器(整块弹性区)'],
['C1','#pan0','表格1:项目工料机(列 C1-1…)'],
['C2','#pan1','表格2:组价不一致清单,含分组标题行(列 C2-1…)'],
['C3','#pan2','表格3:类似清单(列 C3-1…)'],
['D','#histwrap','底部历史容器(整体,可拖动高度 / 收起)'],
['D1','#histbar','历史工具条(整条)'],
['D1a','#hcur','当前选中项:名称 + 报价'],
['D1b','#hper','期次输入(点开一个面板,一次选起~止)'],
['D1c','#histbar button[onclick^="setPeriod"]','按钮:清除期次'],
['D1d','#htier','下拉:档位(精确+次精确 / 只看精确 / 全部含模糊)'],
['D1e','#hsort','下拉:排序(时间 / 价格低→高 / 价格高→低)'],
['D1f','#fbtn','按钮:筛选(展开 D2)'],
['D1g','#histbar button[onclick="doExport()"]','按钮:导出本结果'],
['D1h','#foldBtn','按钮:收起 / 展开历史容器'],
['D1i','#hcnt','命中统计:精确 / 次精确 / 模糊'],
['D2','#hfilter','筛选面板(默认隐藏,点 D1f 展开)'],
['D2a','#fkind','筛选:文件类型'],
['D2b','#funit','筛选:建设单位'],
['D2c','#fcls','筛选:信息价目录'],
['D2d','#fsrc','筛选:来源(历史项目 / 信息价 / 市场价)'],
['D3','#histtblwrap','历史比对表区域(列 D3-1…)'],
['D3h','#hth','历史表表头'],
['D4','#hmfoot','统计脚:最低/最高/均价/中位数/与当前报价'],
['E','#omask .dlg','弹窗:打开工程(整窗)'],
['E1','#ofile','弹窗:工程文件选择'],
['E2','#oname','弹窗:名称(默认=文件名,可改)'],
['E3','#oper','弹窗:基准期次(起~止)'],
['E4','#oprov','弹窗:地区(省 / 市 / 区 三级联动,含 ocity、odist)'],
['E5','#obuid','弹窗:建设单位'],
['E6','#omsg','弹窗:提示 / 报错文字'],
['E7','#omask .mfoot','弹窗:取消 / 打开 按钮行']
];
const COLMAP={th0:'C1',th1:'C2',th2:'C3',hth:'D3'};
function tag(el,id,name){
if(!el) return;
if(el.querySelector(':scope > .maptag')) return;
if(getComputedStyle(el).position==='static') el.style.position='relative';
const s=document.createElement('span');
s.className='maptag'; s.textContent=id; s.title=id+' · '+name;
el.appendChild(s);
}
function markAll(){ F.forEach(f=>tag(document.querySelector(f[1]),f[0],f[2])); markCols(); }
function markCols(){
Object.keys(COLMAP).forEach(k=>{
const th=document.getElementById(k); if(!th) return;
const pre=COLMAP[k];
Array.from(th.querySelectorAll('tr:last-child th')).forEach((c,i)=>{
if(c.querySelector('.maptag')) return;
const s=document.createElement('span');
s.className='maptag'; s.textContent=pre+'-'+(i+1); s.title=pre+'-'+(i+1)+' 列:'+c.textContent.trim();
c.appendChild(s);
});
});
}
document.addEventListener('DOMContentLoaded',function(){
setTimeout(function(){
markAll();
['th0','th1','th2','hth'].forEach(k=>{
const el=document.getElementById(k); if(!el) return;
new MutationObserver(markCols).observe(el,{childList:true,subtree:true});
});
new MutationObserver(markAll).observe(document.body,{childList:true,subtree:true});
},400);
// 右下角:编号开关 + 区块清单
const b=document.createElement('button'); b.id='mapbtn'; b.textContent='区块编号';
const p=document.createElement('div'); p.id='mappanel';
p.innerHTML='<div class="ph">区块编号对照表(点击高亮)<span class="x">✕ 关闭</span></div>'+
'<table>'+F.map(f=>'<tr data-k="'+f[0]+'"><td class="k">'+f[0]+'</td><td>'+f[2]+'</td></tr>').join('')+
'<tr><td class="k">列</td><td>C1-x / C2-x / C3-x = 三张主表列;D3-x = 历史比对表列</td></tr></table>';
document.body.appendChild(b); document.body.appendChild(p);
b.onclick=function(){ p.style.display = p.style.display==='block'?'none':'block'; };
p.querySelector('.x').onclick=function(){ p.style.display='none'; };
p.querySelectorAll('tr[data-k]').forEach(tr=>{
tr.onclick=function(){
document.querySelectorAll('.mapbox').forEach(x=>x.classList.remove('mapbox'));
const f=F.find(x=>x[0]===tr.dataset.k); const el=document.querySelector(f[1]);
if(el){ el.classList.add('mapbox'); el.scrollIntoView({block:'center'}); }
};
});
});
})();
</script>
<!-- 2026-10-01:分组/匹配 设置面板 -->
<div class="mask" id="cfgmask">
<div class="dlg" style="width:860px">
<h4>分组与匹配设置</h4>
<div class="mbody">
<div class="cfgtabs">
<button class="cfgtab on" data-tab="prof" onclick="cfgTab('prof')">分组设置</button>
<button class="cfgtab" data-tab="stop" onclick="cfgTab('stop')">全局过滤词</button>
</div>
<div class="cfgpanel" id="cfgTabProf">
<div class="cfgsec">
<div class="cfghd">类似清单分组(当前工程)
<button class="btn" onclick="cfgCopyFromProf()">复制分组</button>
<button class="btn" onclick="cfgAddGroup()">+ 添加分组</button>
</div>
<div class="tip"><b>分组规则</b>:<b>名称相同的清单强制归为同一组</b>(不管项目特征、单位是否一致);其余清单按关键词归入组,且<b>同组必须单位相同</b>——不同单位会拆成平级组(如「混凝土结构 · m3」「混凝土结构 · 座」),保证组内单价可比。同一清单命中多组时<b>按列表从上到下优先</b>,未命中任何组的归入「其他」。<br><b>排除</b>:命中关键词、但名称/项目特征又含排除词的,跳出本组继续往后匹配其他组。</div>
<div id="cfgGroups"></div>
</div>
</div>
<div class="cfgpanel" id="cfgTabStop" style="display:none">
<div class="cfgsec">
<div class="cfghd">历史匹配过滤词(全局)
<button class="btn" onclick="cfgResetStop()">清空</button>
</div>
<div class="tip">这些词在「与历史项目比对」时会被<b>忽略</b>(不参与相似度计算)。点「添加」加入,每个词一个标签,点标签上的 × 可删除;输入框支持逗号 / 空格批量添加。</div>
<div id="cfgStopChips" class="chips"></div>
<div class="chip-add">
<input id="cfgStopInput" class="chip-input" placeholder="输入过滤词,回车或点添加(可批量:逗号/空格分隔)" onkeydown="if(event.key==='Enter'){event.preventDefault();addStop();}">
<button class="btn" onclick="addStop()">+ 添加</button>
</div>
</div>
</div>
</div>
<div class="mfoot">
<button class="btn" onclick="cfgClose()">取消</button>
<button class="btn pri" onclick="cfgSave()">保存</button>
</div>
</div>
</div>
<!-- 复制分组:点选来源专业(二级弹框,层级高于设置面板) -->
<div class="mask" id="copymask">
<div class="dlg" style="width:380px">
<h4>从哪个专业复制分组?</h4>
<div class="mbody">
<div class="tip" id="copyTip"></div>
<div class="copylist" id="copyList"></div>
</div>
<div class="mfoot">
<button class="btn" onclick="copyClose()">取消</button>
</div>
</div>
</div>
</body>
</html>

1673
CostReview/app/ui/admin.html Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,243 @@
/* ============================================================
前后台共用的样式(唯一来源)
------------------------------------------------------------
4 个标签(原数据 / 类似清单 / 组价不一致清单 / 项目工料机)相关的
展示样式只允许在这里写一份,两侧页面都引用本文件。
目的:两侧不仅「逻辑一致」,连「长相一致」都由同一份 CSS 保证。
依赖变量:--c1 主色 / --c2 次色 / --line 分隔线 / --muted 次要文字 / --head 表头底色
============================================================ */
/* ---- 原数据:左侧目录树 + 右侧标签卡 ---- */
.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}
.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}
/* ---- 树 / 内容 分隔条(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}
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:#fff;font-weight:700;color:var(--c1)}
/* 分部分项 / 措施项目:标签卡右边的「分部 / 清单 / 定额」——控制展开到哪一级 */
.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}
/* 与 .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}
.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}
/* 价差 ≥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}
/* 表格选中态与左树统一:浅底 + 首列 3px 主色竖条 */
tr.sel td:first-child{box-shadow:inset 3px 0 0 var(--c1)}
/* 点定额 → 下方「子目工料机」分区面板(可收起/展开,非行内子行)
与面板上方那条 .rawvsplit 分隔条配套:margin-top 归零,间距由分隔条给。 */
.rawnorm{flex:none;display:flex;flex-direction:column;max-height:40%;min-height:120px;
margin-top:0;border-top:2px solid var(--c1);background:#fcfdfe}
/* ---- 子目工料机 上下分隔条(2026-10-07)----
7px 命中区:按住上下拖 = 调面板高度;正中间 44×15 小把手:点一下收起/展开整块面板。 */
.rawvsplit{height:7px;flex:none;position:relative;cursor:row-resize;margin-top:6px;background:transparent}
.rawvsplit:hover{background:#dbe7f6}
.rawvsplit .vsplitbtn{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
width:44px;height:15px;line-height:13px;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}
.rawvsplit .vsplitbtn:hover{background:#dbe8f7;border-color:var(--c2)}
body.rawrow-dragging{cursor:row-resize !important;user-select:none}
body.rawrow-dragging .rawnorm{pointer-events:none} /* 拖过面板表面时不选中文字 */
.rawnorm .nphd{display:flex;align-items:center;gap:8px;padding:4px 10px;background:#eef3fa;
border-bottom:1px solid var(--line);font-size:12px;color:var(--c1);flex:none}
.rawnorm .nphd b{font-weight:500}
.rawnorm .npname{color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.rawnorm .npclose{margin-left:auto;cursor:pointer;color:var(--c2);font-size:11.5px;white-space:nowrap}
.rawnorm .npclose:hover{text-decoration:underline}
.rawnorm .npbody{flex:1;overflow:auto;min-height:0}
/* ---- 提示条(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}

2005
CostReview/app/ui/common.js Normal file

File diff suppressed because it is too large Load Diff

160
CostReview/app/ui/period.js Normal file
View File

@@ -0,0 +1,160 @@
/* ============================================================
期次区间选择器(工作台 / 后台共用)
—— 一个输入框,点一下弹出「一个」面板,面板里一次选完「起」「止」两个月,不再弹两次。
布局(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);
})();

View File

@@ -0,0 +1,161 @@
<!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}
body{font-family:"Microsoft YaHei",system-ui,sans-serif;margin:0;background:var(--bg);color:var(--txt);font-size:13px}
.wrap{max-width:1760px;margin:0 auto;padding:10px 16px 14px}
h1{font-size:19px;margin:0 0 3px;color:var(--c1)}
.panel{background:#fff;border:1px solid var(--line)}
.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 12px;border-bottom:1px solid var(--line);background:#fafcff}
.bar input,.bar select{padding:6px 10px;border:1px solid #b8c4d4;border-radius:6px;font-size:13px}
.btn{padding:6px 13px;border-radius:6px;border:1px solid #b8c4d4;background:#fff;cursor:pointer;font-size:12.5px;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}
.btn:disabled{opacity:.45;cursor:not-allowed}
.ck{display:flex;align-items:center;gap:5px;font-size:12.5px;color:var(--muted);cursor:pointer}
.tip{color:var(--muted);font-size:12px}
.tw{overflow:auto;max-height:calc(100vh - 230px)}
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)}
a{color:var(--c2);text-decoration:none;cursor:pointer}
a:hover{text-decoration:underline}
</style>
</head>
<body>
<div class="wrap">
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:6px">
<h1 style="margin:0">造价审核 · 最近审核</h1>
<a class="btn pri" style="text-decoration:none;flex:none" href="/workbench.html"
title="打开工作台:导入工程、做历史比对与审核">▶ 工作台</a>
</div>
<div class="panel">
<div class="bar">
<input id="fq" placeholder="项目名 / 文件名关键字" style="width:250px" oninput="render()">
<button class="btn" onclick="load()">刷新</button>
<label class="ck"><input type="checkbox" id="ckall" onchange="selAll(this)"> 全选</label>
<button class="btn danger" id="bdel" disabled onclick="delSel()">删除所选 (0)</button>
<span class="tip" id="cnt"></span>
</div>
<div class="tw">
<table id="tb">
<colgroup id="cg"></colgroup>
<thead id="th"></thead>
<tbody id="tbody"></tbody>
</table>
</div>
</div>
</div>
<script>
/* 会话管理页:照后台「项目界面」的版式,管的是**还没入库**的工作台会话。
会话库不自动清(SESSION_KEEP_DAYS=0),要删只能在这里手动删。 */
const COLS=[['',36,'c'],['项目名',260,'l'],['项目总造价',140,'r'],['源文件',220,'l'],['单位工程',80,'r'],['清单',90,'r'],
['定额',90,'r'],['工料机',90,'r'],['备注',70,'r'],['打开时间',150,'c'],['操作',200,'c']];
let ITEMS=[], RDATA=null;
const esc=s=>String(s==null?'':s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
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); return await r.json(); }
function head(){
$('cg').innerHTML=COLS.map(c=>`<col style="width:${c[1]}px">`).join('');
$('th').innerHTML='<tr>'+COLS.map(c=>`<th>${c[0]}</th>`).join('')+'</tr>';
}
function srcShort(s){ s=s||''; return s.split('_').length>1 ? s.split('_').slice(1).join('_') : s; }
async function load(silent){
if(!silent) $('tbody').innerHTML='<tr><td colspan="'+COLS.length+'" class="empty">正在读取…</td></tr>';
let d;
try{ d=await J('/api/sessions'); }
catch(e){
$('tbody').innerHTML='<tr><td colspan="'+COLS.length+'" class="empty">读取失败:服务没连上(软件可能没启动)</td></tr>';
return;
}
ITEMS=d.items||[];
render();
}
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));
/* 2026-10-07 主人定:同名工程只有一行(后端已按名称去重,代表=最近一次审核)。
不再显示「共 N 次」、不再按时间展开版本;删除=该名称下全部记录一起删。 */
let h='';
rows.forEach(x=>{
h+=`<tr>
<td class="c"><input type="checkbox" class="f-sel" value="${x.id}" onchange="updDel()"></td>
<td class="l name" title="${esc(x.name)}">${esc(x.name||'(无名)')}</td>
<td class="r" title="${x.total==null?'原文件里没取到总造价':'工程总造价(原文件口径,含税金与其他项目)'}">${money(x.total)}</td>
<td class="l name" title="${esc(x.src_name)}">${esc(srcShort(x.src_name))}</td>
<td class="r">${n2(x.n_uw)}</td>
<td class="r">${n2(x.n_bill)}</td>
<td class="r">${n2(x.n_norm)}</td>
<td class="r">${n2(x.n_lme)}</td>
<td class="r">${n2(x.n_remark)}</td>
<td class="c">${esc(x.at||'—')}</td>
<td class="c">
<a onclick="go(${x.id})" title="打开最近一次审核,接着上次的活干">打开</a>
<a onclick="del([${(x.all||[]).map(a=>a.id).join(',')}])" style="margin-left:8px;color:#c0392b">删除</a>
</td></tr>`;
});
$('tbody').innerHTML=h||`<tr><td colspan="${COLS.length}" class="empty">没有匹配的会话</td></tr>`;
$('cnt').textContent=`显示 ${rows.length} / ${ITEMS.length} 个`;
updDel();
}
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; }
/* 2026-09-30 主人定:落地页每行**只留「打开」+「删除」**,去掉「重新解析」按钮。
它只在解析器更新后才需要,不该占日常位置。
⚠️ 去掉之后的替代路径:**删掉这个会话 → 重新打开工程**(走一遍全新解析,数据就是新的),
备注在独立的 s_remarks 里,删会话带不走。后端接口 /api/session/reparse 保留备用。
2026-10-07:同名工程按名称合并成一行,删除传入该名称下全部会话 id(不分时间版本)。 */
async function del(ids){
if(!ids.length) return;
const x=ITEMS.find(v=>(v.all||[]).some(a=>ids.includes(a.id)));
const nm=x?(x.name||'(无名)'):('会话 '+ids.join('、'));
const nb=x?(x.all||[]).reduce((s,a)=>s+(a.n_bill||0),0):0;
const nn=x?(x.all||[]).reduce((s,a)=>s+(a.n_norm||0),0):0;
const nl=x?(x.all||[]).reduce((s,a)=>s+(a.n_lme||0),0):0;
// ⚠️ 2026-09-30:删掉「重新解析」按钮后,刷新数据的唯一路径就是「删了重开」,这句提示必须留着
if(!confirm('确定删除《'+nm+'》?\n\n将同时删除该工程名下的 '+ids.length+' 条审核记录:清单 '+
n2(nb)+' 条、定额 '+n2(nn)+' 条、工料机 '+n2(nl)+' 条(不分时间版本,一次删完)。\n\n'+
'审核备注已独立保存,删会话不会带走它,重新打开工程后自动填回。\n\n'+
'要刷新数据(解析器更新后)=删掉再重新打开工程,会重新解析一遍。\n\n这是真删除,不可恢复。')) return;
const r=await J('/api/session/delete',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({ids})});
alert(r.msg||'(失败)');
await load(true); // 静默刷新:表格原地更新,不再闪"正在读取…"
}
head(); load();
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff