初始提交:造价审核系统源码(不含数据库与生成物)

This commit is contained in:
lianjianwei2024
2026-10-09 17:04:37 +08:00
commit 22acb0dfe2
58 changed files with 23493 additions and 0 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,680 @@
# -*- coding: utf-8 -*-
"""
M1 原型:把「后台需要导入的项目」里的 15 个真实文件解析入库,并产出导入报告。
规则全部来自《造价审核软件开发方案》§4.5 / §4.6 / §4.7:
- 按文件头 + 根节点分派(不看扩展名)
- 清单:不导入 单位=项
- 工料机:不导入 组合类(有下一级 / Kind=6)
- 只保留需要的字段,其余丢弃
"""
import io, os, re, sys, time, json, hashlib, zipfile, sqlite3
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.08-1" # 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), "")
t = re.sub(r"(?<!\d)\d+[、)).]", "", t) # 1、 2) 3) 1. —— 中文编号分隔
t = re.sub(r"(?<!\d)\d+\.(?!\d)", "", t) # 2. —— ASCII 点号编号(排除 M7.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 起(分部分项 / 措施项目),与会话库同口径
seq = {"d": 0, "p": 0}
# bills 元组第 8 位 = 源文件备注(2026-10-08 主人定:只显示在「原数据」备注栏)
for i, (num, name, attr, unit, qty, price, total, srk) in enumerate(out["bills"]):
h = md5(num, name, unit) # 精确键:编码+名称+单位(特征写法太杂,不参与)
hs = md5(num, unit)
k = buw[i] if i < len(buw) else -1
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
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_seq)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, divid, num, name, attr, unit, qty, price, total, kb, srk,
norm(name), clean_attr(attr), norm(unit), h, hs, 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)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, num, name, spec, unit, qty, ntp, tax, tp, _kind,
norm(name), norm(spec), norm(unit), h, md5(name, 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,640 @@
# -*- 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, os, threading
SIM_MIN = 0.60
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)
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 _stem(name):
"""文件名去扩展名后的前 12 个字,用于判断"是不是同一工程"""
if not name:
return ""
b = os.path.basename(str(name))
b = re.sub(r"^[0-9a-f]{64}_", "", b) # 去掉上传时加的 sha256 前缀
b = os.path.splitext(b)[0]
return b[:12]
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 = []
# L0 精确:编码+名称+单位(b.id 带回 → 前端展开定额 / 右栏「定额编码·名称」用)
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
out += [dict(x) for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit])]
# L1 次精确:编码+单位
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 len(out) >= limit:
break
out.append(d); seen.add((d["Name"], d["Attr"]))
# L2 模糊:名称+特征 相似度
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
sim = jaccard(norm_match(row["Name"]) + norm_match(row["Attr"]), norm_match(x["Name"]) + norm_match(x["Attr"]))
if sim >= SIM_MIN:
d = dict(x); d["tier"] = "模糊"
out.append(d)
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"] != "模糊" else round(jaccard(
norm_match(row["Name"]) + norm_match(row["Attr"]), norm_match(d["Name"]) + norm(d["Attr"])), 2),
"src": "工程", "file": "", "src_hash": d.get("src") or "",
})
res = [r for r in res if _in_period(r, pfrom, pto)]
ss = _stem(self_src) # 被审工程源文件名主干(前 12 字)
if ss or self_name: # 排除"被审工程自己"
res = [r for r in res
if not (ss and _stem(r.get("src_hash") or r["proj"]) == ss)
and not (self_name and (r["proj"] or "").strip() == self_name.strip())]
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "模糊": 2}[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 同一套:源文件主干相同(_stem 前 12 字)或项目名相同。
page:分页(2026-10-08 主人定,每页=limit 条,第 N 页 OFFSET (N-1)×limit)。"""
c = hist.cursor()
cond, args = _filters(kinds, units, [], prefix="bt") # 批次级条件(拼好的 SQL 串 + 参数)
extra = []
ss = _stem(self_src) if self_src else ""
nm = (self_name or "").strip()
if ss or nm:
self_ids = [r[0] for r in c.execute(
"SELECT id, Name, x_src_hash FROM batches WHERE kind='project'").fetchall()
if (ss and _stem(r[2] or "") == ss) 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
for t in (kw or "").split():
if not t:
continue
pat = "%" + _kw_fold(t) + "%" # 检索词折叠(同 hist_search_lme,符号变体一视同仁)
extra.append("(%s LIKE ? OR %s LIKE ? OR %s LIKE ?)"
% (_kw_like("b.Name"), _kw_like("b.Attr"), _kw_like("b.Unit")))
args = args + [pat] * 3
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 = [], []
ss = _stem(self_src) if self_src else ""
nm = (self_name or "").strip()
if ss or nm:
self_ids = [r[0] for r in c.execute(
"SELECT id, Name, x_src_hash FROM batches").fetchall()
if (ss and _stem(r[2] or "") == ss) 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
for t in (kw or "").split():
if not t:
continue
pat = "%" + _kw_fold(t) + "%" # 检索词折叠(φ/Φ/ϕ/⌀/Ø 一视同仁)
outer.append("(%s LIKE ? OR %s LIKE ? OR %s LIKE ?)"
% (_kw_like("name"), _kw_like("spec"), _kw_like("unit")))
oargs += [pat] * 3
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 一对一)
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""" % cond)
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 = []
# ---- 历史工程工料机 ----
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:
sql = """SELECT '精确' tier, 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 LIMIT ?""" % w
out += [dict(x) for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit])]
if len(out) < limit:
# 次精确:名称+单位一致、规格不同(2026-10-08 主人定)——同名材料不同规格正是常比对象
seen_semi = {(x["Name"], x["Specification"]) for x in out}
sql2 = """SELECT '次精确' tier, 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 LIMIT ?""" % w
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"]))
if len(out) < limit:
q = norm_match(row["Name"])[:6]
if q:
sql3 = """SELECT 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 l.x_name_norm LIKE ? LIMIT 300""" % w
for x in c.execute(sql3, args + ["%" + q + "%"]):
if norm(x["Unit"]) != norm(row["Unit"]):
continue
sim = jaccard(norm_match(row["Name"]) + norm_match(row["Specification"]),
norm_match(x["Name"]) + norm_match(x["Specification"]))
if sim >= SIM_MIN:
d = dict(x); d["tier"] = "模糊"
out.append(d)
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"] != "模糊" else round(jaccard(
norm_match(row["Name"]) + norm_match(row["Specification"]),
norm_match(d["Name"]) + norm_match(d["Specification"])), 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 生效。
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 = jaccard(norm_match(row["Name"]) + norm_match(row["Specification"]),
norm_match(x["Name"]) + norm_match(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")]
ss = _stem(self_src) # 被审工程源文件名主干(前 12 字)
if ss or self_name: # 排除"被审工程自己"
res = [r for r in res
if not (ss and _stem(r.get("src_hash") or r["proj"]) == ss)
and not (self_name and (r["proj"] or "").strip() == self_name.strip())]
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "模糊": 2}[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,457 @@
# -*- 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
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,引用清零才删。)
"""
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")
# ⚠️ 每加一张表都要同步到这里 —— 漏一张,重新解析就会不断叠加脏数据
# (2026-09-30 就漏了 s_sections:横琴解析三遍攒出 11 个单项工程,全是空的)
for t in ("s_bills", "s_lmes", "s_unit_works", "s_sections", "s_divides", "s_lme_lib", "s_lme_proj"):
cur.execute("DELETE FROM %s WHERE session_id=?" % t, (sid,))
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:序号**分两套各自从 1 起** —— 分部分项 1..N、措施项目 1..M。
# 注意这里是**全量占号**(所有入库清单都领号),被 C 区筛掉的行也照占,
# 所以界面上会跳号;主人拍板要的就是「号码对得上原件、任何视图下一致」。
seq = {"d": 0, "p": 0}
# 第 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
# 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(num, nm, unit), md5(num, unit), xseq))
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