feat(match): 落地搜索匹配口径四件套与次精确名称护栏,同步字集键入库及测试面板改进

This commit is contained in:
lianjianwei2024
2026-10-10 14:58:13 +08:00
parent a3697ba271
commit 6de1370ce5
12 changed files with 940 additions and 286 deletions

View File

@@ -8,6 +8,7 @@ M1 原型:把「后台需要导入的项目」里的 15 个真实文件解析
- 只保留需要的字段,其余丢弃
"""
import io, os, re, sys, time, json, hashlib, zipfile, sqlite3
import match # 比对引擎:字集键 bill_setkey/lme_setkey 唯一实现(决策 27,口径不分叉)
from xml.etree import ElementTree as ET
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
@@ -492,8 +493,10 @@ def save(con, kind, out, fn, sha, mtime, meta=None):
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)
# 决策 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
kb = bkd[i] if i < len(bkd) else None
@@ -505,10 +508,10 @@ def save(con, kind, out, fn, sha, mtime, meta=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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
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, xseq))
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)
@@ -535,10 +538,11 @@ def save(con, kind, out, fn, sha, mtime, meta=None):
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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
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)))
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

View File

@@ -11,9 +11,14 @@
4. 结果按「距基准先近后远」排序,同距按档位(精确>次精确>模糊)
5. 信息价/市场价的结果行带**原文件字段**(可打开附件 PDF)
"""
import sqlite3, re, os, threading
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=""):
@@ -108,6 +113,64 @@ def jaccard(a, b):
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:被审工程的源文件名 —— 同一个文件若也在历史库里,排除掉(避免自己跟自己比)
@@ -184,14 +247,43 @@ def _kw_like(col):
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 _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):
@@ -218,15 +310,18 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
"""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 带回 → 前端展开定额 / 右栏「定额编码·名称」用)
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
out += [dict(x) for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit])]
# L1 次精确:编码+单位
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}
@@ -234,10 +329,27 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
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"]))
# L2 模糊:名称+特征 相似度
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:
@@ -249,10 +361,13 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
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 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"] = "模糊"
out.append(d)
d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim
out.append(d); seen_ids.add(x["id"])
if len(out) >= limit:
break
res = []
@@ -265,17 +380,14 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
"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),
"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)]
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"]]))
res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目)
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]]))
return res[:limit]
@@ -287,27 +399,22 @@ def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=N
· dist=0、排序由本函数做好(期次先近后远),前端不再按 dist 重排。
期次条件=区间重叠语义:批次的 [起,止] 与所选 [起,止] 有交集即命中(检索没有"基准期")。
self_name/self_src:被审工程自己(若它也入库了)**排除**(2026-10-08 主人定),
判定与 match_bill/match_lme 同一套:源文件主干相同(_stem 前 12 字)或项目名相同。
判定与 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 = []
ss = _stem(self_src) if self_src else ""
nm = (self_name or "").strip()
if ss or nm:
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 (ss and _stem(r[2] or "") == ss) or (nm and (r[1] or "").strip() == nm)]
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
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
_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]
@@ -363,22 +470,16 @@ def hist_search_lme(hist, orgs=None, area=None, pfrom=None, pto=None, kw="", pmi
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:
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 (ss and _stem(r[2] or "") == ss) or (nm and (r[1] or "").strip() == nm)]
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
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
_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:
@@ -467,7 +568,7 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
srcs = srcs or ["project", "info", "market"]
c = hist.cursor()
out = []
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)
@@ -479,7 +580,7 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
# 带 l. 前缀,见 lme_list_where 的说明。
# ⚠️ **信息价/市场价分支永远不过滤任何单位/类别**(主人 2026-10-09 明示"永远不能
# 屏蔽信息价/市场价的任何单位")—— 别把 lme_list_where 加到下面价格查询上。
sql = """SELECT '精确' tier, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
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,
@@ -488,11 +589,12 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
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"))
out += [dict(x) for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit])]
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.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
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,
@@ -507,11 +609,30 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
continue
if len(out) >= limit:
break
out.append(d); seen_semi.add((d["Name"], d["Specification"]))
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.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
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,
@@ -523,11 +644,13 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
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 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"] = "模糊"
out.append(d)
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:
@@ -538,9 +661,9 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
"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),
"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 "",
})
@@ -627,8 +750,8 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
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"]))
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)
@@ -654,10 +777,6 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
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"]]))
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

@@ -386,7 +386,9 @@ def open_project(con, files, meta, job, sid=None):
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))
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

View File

@@ -4,6 +4,8 @@ M3-1 后端服务:零依赖(Python 标准库 http.server)
提供后台管理界面需要的接口,并托管前端页面。
"""
import io, os, re, json, sqlite3, urllib.parse, mimetypes, hashlib, time, threading, base64
from itertools import combinations
from collections import Counter
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
# ---- 路径:**一律由本文件位置推导**,不写死绝对路径 ----
@@ -117,6 +119,12 @@ def ensure_attach_schema():
con.execute("ALTER TABLE lmes ADD COLUMN x_hash_semi TEXT")
if "x_hash_semi" not in pcols:
con.execute("ALTER TABLE prices ADD COLUMN x_hash_semi TEXT")
# 2026-10-10 决策 27:字集键列(回填与索引在 migrate_match_keys,连 bills 一起)
bcols = [r[1] for r in con.execute("PRAGMA table_info(bills)")]
if "x_setkey" not in bcols:
con.execute("ALTER TABLE bills ADD COLUMN x_setkey TEXT")
if "x_setkey" not in lcols:
con.execute("ALTER TABLE lmes ADD COLUMN x_setkey TEXT")
# 2026-10-06:价格条数从 x_rows_lme 拆出来,单独一列。
# x_rows_lme 此前被复用(项目=工料机数 / 价格批次=价格数),
# 导致「x_rows_lme>0 ⇒ 有工料机」的写法会把信息价批次误判。
@@ -130,6 +138,65 @@ def ensure_attach_schema():
con.commit(); con.close()
def _hash9_current(con, table):
"""探针:库存清单哈希是否已是「编码前 9 位」口径(决策 27)。整库任取一行重算比对。"""
row = con.execute("""SELECT Number, Name, Unit, x_hash_exact FROM %s
WHERE Number IS NOT NULL AND Length(Number) >= 9 LIMIT 1""" % table).fetchone()
if not row:
return True # 没有长编码行:两种口径结果相同,视为已迁移
num, name, unit, h0 = row
return job.md5(job.norm(num)[:9], name, unit) == h0
def _rehash_bills_9(con, table):
"""整表按「编码前 9 位」重算精确/次精确哈希(决策 27)。返回改动行数。"""
rows = con.execute("SELECT id, Number, Name, Unit, x_hash_exact, x_hash_semi FROM %s" % table).fetchall()
ups = []
for rid, num, name, unit, h0, hs0 in rows:
num9 = job.norm(num)[:9]
h, hs = job.md5(num9, name, unit), job.md5(num9, unit)
if h != h0 or hs != hs0:
ups.append((h, hs, rid))
if ups:
con.executemany("UPDATE %s SET x_hash_exact=?, x_hash_semi=? WHERE id=?" % table, ups)
return len(ups)
def migrate_match_keys():
"""决策 27(2026-10-10)一次性迁移,幂等(探针不匹配才动手,平时启动零成本跳过):
① bills 哈希改「编码前 9 位」口径——history.db.bills 与 session.db.s_bills 全量重算
x_hash_exact / x_hash_semi(编码后 3 位是项目内顺序码,跨项目没有对比意义);
② bills / lmes 回填 x_setkey 字集键 + 建索引(老库补列在 ensure_attach_schema,新库 schema.sql 自带)。"""
con = sqlite3.connect(DB)
try:
if not _hash9_current(con, "bills"):
print("迁移:bills 哈希重算(编码前 9 位,决策 27)……%d 行改动" % _rehash_bills_9(con, "bills"))
nb = con.execute("SELECT COUNT(*) FROM bills WHERE x_setkey IS NULL").fetchone()[0]
if nb:
con.executemany("UPDATE bills SET x_setkey=? WHERE id=?",
[(match.bill_setkey(nm, un), rid) for rid, nm, un in
con.execute("SELECT id, Name, Unit FROM bills WHERE x_setkey IS NULL")])
print("迁移:bills 字集键回填 %d 行" % nb)
nl = con.execute("SELECT COUNT(*) FROM lmes WHERE x_setkey IS NULL").fetchone()[0]
if nl:
con.executemany("UPDATE lmes SET x_setkey=? WHERE id=?",
[(match.lme_setkey(nm, sp, un), rid) for rid, nm, sp, un in
con.execute("SELECT id, Name, Specification, Unit FROM lmes WHERE x_setkey IS NULL")])
print("迁移:lmes 字集键回填 %d 行" % nl)
con.execute("CREATE INDEX IF NOT EXISTS ix_bill_setkey ON bills(x_setkey)")
con.execute("CREATE INDEX IF NOT EXISTS ix_lme_setkey ON lmes(x_setkey)")
con.commit()
finally:
con.close()
scon = sess.connect()
try:
if not _hash9_current(scon, "s_bills"):
print("迁移:s_bills 哈希重算(编码前 9 位,决策 27)……%d 行改动" % _rehash_bills_9(scon, "s_bills"))
scon.commit()
finally:
scon.close()
# ---------------------------------------------------------------------------
# 数据源字典 / 后台设置(2026-10-06)
# ⚠️ 2026-10-06 重构:dict_region / dict_org / settings 三张表的建表 SQL 已全部收口到
@@ -764,13 +831,15 @@ def api_adopt_record(body):
(sha, kind, ref, name, ext, size, now))
sid = int(body.get("session_id") or 0)
lmid = int(body.get("lme_id") or 0)
if not sid or not lmid:
# 决策 28(2026-10-10):目录按会话展示,没有会话的事件永远不可见 → 干脆不收
return {"ok": False, "msg": "未打开项目(无会话),不收集附件"}
proj = (body.get("proj") or "").strip()
if sid and lmid: # 该行的旧事件先撤(换绑:再采纳即替换)
c.execute("DELETE FROM adopt_hits WHERE sid=? AND lme_id=?", (sid, lmid))
if proj:
c.execute("""INSERT INTO adopt_hits(sha256, proj, adopted_at, sid, lme_id)
VALUES(?,?,?,?,?)""", (sha, proj, now,
sid or None, lmid or None))
VALUES(?,?,?,?,?)""", (sha, proj, now, sid, lmid))
c.commit()
n_att = c.execute("SELECT COUNT(*) FROM adopt_files").fetchone()[0]
return {"ok": True, "n_att": n_att}
@@ -807,9 +876,11 @@ def api_adopt_cancel(body):
c.close()
def api_adopt_list():
"""「询价附件」弹框数据:附件目录(按内容去重)+ 每个附件被哪些项目采纳过。
顺带懒清理:磁盘原件已随批次删除的条目,这里从注册表摘掉,不留死链接。"""
def api_adopt_list(sid=0):
"""「询价附件」弹框数据(2026-10-10 主人定:**会话级**)——只看当前会话收进的附件:
过滤 adopt_hits 里 sid 匹配的事件;没打开项目(无 sid)→ 空目录。
会话不删,事件就在,切回来附件还在;删会话连带撤事件(api_session_delete 已有)。
仍顺带懒清理:磁盘原件已随批次删除的条目,从注册表摘掉,不留死链接(对全表做,别留死角)。"""
c = conn()
try:
atts, dead = [], []
@@ -820,13 +891,21 @@ def api_adopt_list():
if not rel or not os.path.exists(os.path.join(DATA_DIR, rel)):
dead.append(sha)
continue
if sid:
n = c.execute("SELECT COUNT(*) FROM adopt_hits WHERE sha256=? AND sid=?",
(sha, sid)).fetchone()[0]
if not n:
continue # 别的会话收的:本会话目录里不显示(行保留)
projs = [h[0] for h in c.execute(
"""SELECT DISTINCT proj FROM adopt_hits WHERE sha256=? AND sid=?
ORDER BY proj""", (sha, sid)).fetchall()]
else:
continue # 没打开项目:不给任何附件(主人 2026-10-10 定)
atts.append({"sha": sha, "kind": kind, "ref": ref2, "name": name, "ext": ext,
"size": size, "adopted_at": at,
"url": ("/api/admin/inq/file/%s" % ref2) if kind == "inq"
else ("/api/admin/file/%s" % sha),
"projs": [h[0] for h in c.execute(
"""SELECT DISTINCT proj FROM adopt_hits WHERE sha256=?
ORDER BY proj""", (sha,)).fetchall()]})
"projs": projs})
if dead:
c.executemany("DELETE FROM adopt_files WHERE sha256=?", [(s,) for s in dead])
c.executemany("DELETE FROM adopt_hits WHERE sha256=?", [(s,) for s in dead])
@@ -2066,68 +2145,11 @@ def api_session_groups(sid, kind):
if kind == "inconsistent":
return _inconsistent(rows, BILLROW)
# ---- similar ----
# 系统内置专业:走固定的「前 4 字 + bigram」自动聚类(与后台同一实现 _group_by_prefix)
if _setting_get("session:%d" % sid, "profession") == SYS_PROF:
gs, rest = _group_by_prefix(rows)
out = []
for g in gs:
d = _grpstat(g["rows"]); d["sim"] = g["sim"]
d["rows"] = [BILLROW(x) for x in g["rows"]]
out.append(d)
out.sort(key=lambda x: -(x.get("spread") or 0))
return {"total": len(out), "groups": out,
"extra": _extra_by_cat(rest, BILLROW), "group_mode": True}
# 优先用「关键字分组」配置;无配置走原「前 6 字」逻辑
cfg = _load_similar_groups(sid)
if cfg:
groups, other = _group_by_keywords(rows, cfg)
out = []
for gname, rs in groups:
d = _grpstat(rs); d["cat"] = gname; d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in rs]
out.append(d)
out.sort(key=lambda x: -(x.get("spread") or 0))
extra = []
if other:
d = _grpstat(other); d["cat"] = "其他"; d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in other]
extra = [d]
return {"total": len(groups), "groups": out, "extra": extra, "group_mode": True}
# 原行为:按名称前 6 字分桶
g = {}
for r in rows:
key = r["x_name_norm"][:6]
if not key:
continue
g.setdefault(key, []).append(r)
out = []
for key, rs in g.items():
names = {x["Name"] for x in rs}
if len(names) < 2:
continue
d = _grpstat(rs)
d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in rs]
out.append(d)
# 2026-09-29 决策 19:similar 组按「差距%」从大到小排
out.sort(key=lambda x: -(x.get("spread") or 0))
# 2026-09-29 决策 18:没进任何组的合规清单按类别归并,保证一条不漏
extra = []
shown = {r[0] for grp in out for r in grp["rows"]}
rest = [r for r in rows if r["id"] not in shown]
buckets = {}
for r in rest:
buckets.setdefault(cat_of(r["Name"]) or "其他", []).append(r)
for lab, rs in sorted(buckets.items(), key=lambda x: (-len(x[1]), x[0])):
d = _grpstat(rs)
d["cat"] = lab
d["rows"] = [BILLROW(x) for x in rs]
extra.append(d)
return {"total": len(out), "groups": out, "extra": extra}
# ---- similar:v2 七点顺序管线(决策 29,2026-10-10 主人定)----
# 关键词层仍读本工程专业的配置(后期专业取消后 kw_cfg 恒 None,管线自动只剩名称层+特征层)
prof = _setting_get("session:%d" % sid, "profession")
kw_cfg = _load_similar_groups(sid) if (prof and prof != SYS_PROF) else None
return _group_v2_output(rows, kw_cfg)
def api_session_bill_norms(bill_id):
@@ -3006,6 +3028,207 @@ def norm_txt(s):
return s.lower()
# ---------- 类似清单分组 v2(2026-10-10 决策 29 主人定:7 点顺序管线) ----------
# 顺序语义(主人定,顺序不可颠倒):逐级实施,**上一级分走的行不再进入下一级**。
# 第3点 关键词层:本工程专业配置的关键词组(首匹配+排除词);**不按单位拆**——取值范围=名称+特征。
# 第4点 名称层:名称字集 交集≥min(4, 短方全长) 并查集聚类(字集等效换序无关:钢混凝土=混凝土钢;
# 短名按全长处理:土=钢混凝土)。
# 第5点 特征层:剩余落单按特征"数字字母签名"(剥换行排序序号后提取字母数字的字符集合)等值成组。
# 第6点 其他:仍没进组的全部按类别归并展示(一条不漏,决策 18)。
# 第7点 池化合并(2026-10-10 主人定修订):1~6 步的组**完全对等**——三层组倒进同一个池,
# 组代表(组内最高频名称的中文主干字集)Jaccard≥grp_merge_thr 即合并;
# **不设条数上限、无跨块限制**(初版"按块+累计上限50"已废,主人拍板池化)。
# 保险丝(防串联巨组,实测 2099/3511 条巨组的解):任何一层产生的组超过 grp_big 条 → 组内按特征签名
# 星形细分(阈值 grp_sig_thr)。
# 规则参数读 global 设置(缺省用默认):grp_big=50 / grp_sig_thr=0.6 / grp_merge_on=1 /
# grp_merge_thr=0.85。专业/组名称配置仍作关键词层来源(后期取消)。
def _grp_rule():
def _i(k, d):
try:
return int(float(_setting_get("global", k) or d))
except Exception:
return d
def _f(k, d):
try:
return float(_setting_get("global", k) or d)
except Exception:
return d
return {"big": _i("grp_big", 50),
"sig_thr": _f("grp_sig_thr", 0.6),
"merge_on": (_setting_get("global", "grp_merge_on") or "1") not in ("0", "false", "off"),
"merge_thr": _f("grp_merge_thr", 0.85)}
def _grp_signature(s):
"""特征「数字字母签名」:norm_attr 剥排序序号后,全部字母数字段的字符集合(排序串)。"""
s = match.norm_attr(s or "")
return "".join(sorted(set("".join(match._TOK.findall(s)))))
def _grp_stem_set(names):
"""组代表(第7点合并判据):组内最高频名称的**中文主干**字集——编号字母不掺进相似度。"""
c = Counter((match.norm_attr(n or "")) for n in names)
if not c:
return set()
best = c.most_common(1)[0][0]
s = match._TOK.sub(" ", best)
s = "".join(re.sub(r"[^一-鿿]+", " ", s).split())
return set(match.set_norm(s)) if s else set()
def _grp_fuse(mem_rows, thr):
"""巨组保险丝:组内按特征签名**星形**细分——锚=先到的签名,行只跟锚比,杜绝串联。
返回子组列表(可能含单行子组,调用方分流到下一层)。"""
reps = []
for r in sorted(mem_rows, key=lambda x: _col(x, "id")):
s = _grp_signature(_col(r, "Attr"))
placed = False
if s:
for rs, m2 in reps:
u = len(set(s) | set(rs))
if u and len(set(s) & set(rs)) / u >= thr:
m2.append(r); placed = True; break
if not placed:
reps.append((s, [r]))
return [m2 for rs, m2 in reps]
def _grp_block_merge(groups, thr):
"""第7点池化合并(2026-10-10 主人定:1~6 步的组看作**完全对等**的待合并组,跨块池化;
**不设条数上限**):组代表(最高频名称的中文主干字集)Jaccard≥thr 即合并。"""
reps = [_grp_stem_set([_col(x, "Name") for x in g]) for g in groups]
par2 = list(range(len(groups)))
def f2(x):
while par2[x] != x: par2[x] = par2[par2[x]]; x = par2[x]
return x
for i in range(len(groups)):
for j in range(len(groups)):
if i == j:
continue
a, b = reps[i], reps[j]
if not a or not b:
continue
ri, rj = f2(i), f2(j)
if ri == rj:
continue
u = len(a | b)
if u and len(a & b) / u >= thr:
par2[ri] = rj
mg = {}
for i in range(len(groups)): mg.setdefault(f2(i), []).extend(groups[i])
return [v for v in mg.values() if len(v) > 1]
def _group_v2(rows, kw_cfg):
"""决策 29 七点顺序管线。kw_cfg=本工程专业关键词配置(无/后期取消=跳过关键词层)。
返回 (blocks, rest):blocks=[(组名或None, 行列表)] 按块顺序(关键词→名称→特征),
rest=未进组的行(调用方交 _extra_by_cat 归并)。"""
rule = _grp_rule()
used = set()
# ---- 第3点 关键词层 ----
kw_blocks = []
if kw_cfg:
for g in kw_cfg:
kws = [match.norm(k) for k in (g.get("keywords") or []) if k]
if not kws:
continue
mem = []
for r in rows:
if _col(r, "id") in used:
continue
nm = match.norm("%s %s" % (_col(r, "Name") or "", _col(r, "Attr") or ""))
if any(k in nm for k in kws) and not any(
match.norm(x) in nm for x in (g.get("exclude") or []) if x):
mem.append(r)
if not mem:
continue
subs = _grp_fuse(mem, rule["sig_thr"]) if len(mem) > rule["big"] else [mem]
for m in subs:
if len(m) > 1: # 单行子组不算"已分组",落回名称层
kw_blocks.append((g.get("name") or "关键词组", m))
used.update(_col(x, "id") for x in m)
# ---- 第4点 名称层:字集 交集≥min(4,短方全长) ----
rest0 = [r for r in rows if _col(r, "id") not in used]
par = list(range(len(rest0)))
def find(x):
while par[x] != x: par[x] = par[par[x]]; x = par[x]
return x
keys = [set(match.set_norm(match.norm_attr(_col(r, "Name") or ""))) for r in rest0]
inv = {}
for i, k in enumerate(keys):
for ch in k:
inv.setdefault(ch, []).append(i)
for ch, lst in inv.items():
for i, j in combinations(lst, 2):
if len(keys[i] & keys[j]) >= min(4, min(len(keys[i]), len(keys[j]))):
ra, rb = find(i), find(j)
if ra != rb:
par[ra] = rb
clus = {}
for i in range(len(rest0)):
clus.setdefault(find(i), []).append(i)
name_blocks = []
rest = []
for root, mem in clus.items():
mrows = sorted((rest0[i] for i in mem), key=lambda x: _col(x, "id"))
if len(mrows) == 1:
rest.append(mrows[0]); continue
subs = _grp_fuse(mrows, rule["sig_thr"]) if len(mrows) > rule["big"] else [mrows]
for m in subs:
if len(m) > 1:
name_blocks.append((None, m))
else:
rest.append(m[0])
# ---- 第5点 特征层:落单按签名等值(签名不足 4 字符的行不参与,留在 rest——条数守恒)----
sigb = {}
for r in rest:
s = _grp_signature(_col(r, "Attr"))
if len(s) >= 4:
sigb.setdefault(s, []).append(r)
attr_blocks = [(None, v) for v in sigb.values() if len(v) >= 2]
taken = set()
for v in sigb.values():
if len(v) >= 2:
taken.update(_col(x, "id") for x in v)
rest = [r for r in rest if _col(r, "id") not in taken]
# ---- 第7点 池化合并(2026-10-10 主人定修订:1~6 步的组**完全对等**,三层组倒进同一个池,
# 组代表主干字集 J≥merge_thr 即并,**不设条数上限、不跨块限制已随池化取消**)----
if rule["merge_on"] and len(kw_blocks) + len(name_blocks) + len(attr_blocks) > 1:
pool = kw_blocks + name_blocks + attr_blocks
merged = _grp_block_merge([b[1] for b in pool], rule["merge_thr"])
lbl_of = {}
for lbl0, g0 in pool:
for x in g0:
lbl_of[id(x)] = lbl0
kw_blocks, name_blocks, attr_blocks = [], [], []
for g in merged:
cnt = Counter(lbl_of.get(id(x)) for x in g if lbl_of.get(id(x)))
lbl = max(cnt, key=lambda l: cnt[l]) if cnt else None # 沿用簇内多数的关键词组名
kw_blocks.append((lbl, g))
return kw_blocks + name_blocks + attr_blocks, rest
def _group_v2_output(rows, kw_cfg):
"""v2 管线 → 前端响应(结构与原 similar 完全同构:total/groups/extra/group_mode)。"""
blocks, rest = _group_v2(rows, kw_cfg)
out = []
for label, rs in blocks:
d = _grpstat(rs)
if label:
d["cat"] = label
d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in rs]
out.append(d)
out.sort(key=lambda x: -(x.get("spread") or 0)) # 决策 19:组按差% 从大到小
return {"total": len(out), "groups": out,
"extra": _extra_by_cat(rest, BILLROW), "group_mode": True}
# 行适配统一用上面的 BILLROW(两侧唯一实现,原 _billrow 已删 —— 2026-10-08 收编)。
@@ -3351,8 +3574,8 @@ class Handler(SimpleHTTPRequestHandler):
return self._json(api_raw_uw(one))
if p == "/api/session/inq": # 工作台:询价附件(只读,来源=后台项目批次)
return self._json(api_session_inq(int(one.get("session_id", 0) or 0)))
if p == "/api/adopt/list": # 工作台「询价附件」:采纳收集的附件目录
return self._json(api_adopt_list())
if p == "/api/adopt/list": # 工作台「询价附件」:当前会话收进的附件目录(会话级,决策 28)
return self._json(api_adopt_list(int((q.get("sid") or ["0"])[0] or 0)))
if p == "/api/session/rows": # 会话数据(工作台三个标签)
return self._json(api_session_rows(one))
if p == "/api/session/inconsistent": # 会话内:组价不一致
@@ -3668,7 +3891,8 @@ def run():
pass
ensure_adopt_schema() # 采纳收集表形状检查(旧去重版 → 事件模型重建)
_ensure_batch_schema() # 唯一建表入口:执行 schema.sql(含 attachments/dict/settings/inquiry 全部表)
ensure_attach_schema() # 老库补列 + 回填(x_attach_sha / x_publisher / x_rows_price / prices.Block)
ensure_attach_schema() # 老库补列 + 回填(x_attach_sha / x_publisher / x_rows_price / prices.Block / x_setkey)
migrate_match_keys() # 决策 27:清单哈希改编码前9位 + 字集键回填(幂等,探针跳过)
ensure_dict_schema() # 数据源字典(首次用库里已有值播种)
backfill_session_batch() # 老会话补 x_batch_id → 工作台才能看到该项目的询价附件
cleanup_sessions() # 启动时清掉超过保留天数的会话(只碰 session.db)

View File

@@ -165,13 +165,15 @@ CREATE TABLE IF NOT EXISTS bills(
x_name_norm TEXT,
x_attr_norm TEXT,
x_unit_norm TEXT,
x_hash_exact TEXT, -- md5(编码 + 名称归一 + 单位归一) —— 不含项目特征 Attr(Attr 写法太杂不参与)
x_hash_semi TEXT, -- md5(Number + Unit)
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)
@@ -206,12 +208,14 @@ CREATE TABLE IF NOT EXISTS lmes(
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,此前每行全表扫)

View File

@@ -19,9 +19,6 @@ body{margin:0;font:13px/1.5 -apple-system,"Segoe UI","Microsoft YaHei",sans-seri
.tabmid #sinfo{color:var(--muted);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.tabmid #msg{font-size:12px;color:#1e8e3e;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.tabright{display:flex;align-items:center;gap:8px;margin-left:auto}
/* 顶栏右侧纵排:「打开项目」在上,「询价附件」紧贴其正下方(2026-10-09 主人定) */
.inqstack{display:inline-flex;flex-direction:column;gap:4px;align-items:stretch;margin:4px 0}
.inqstack .btn{margin:0;white-space:nowrap}
.tabs .btn{padding:4px 10px;font-size:12px;line-height:1.3}
.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}
@@ -236,18 +233,17 @@ body.grptree-dragging{cursor:col-resize !important;user-select:none}
<span id="msg" data-page-node-id="UJXRpAoe46va1XF2HPWQ39"></span>
</div>
<div class="tabright" data-page-node-id="sOfM468xWOKqTjwNbIVMFC">
<!-- 2026-09-30:最近审核**统一走 /sessions.html 唯一窗口**(会话管理页)。
工作台不再挂下拉弹层——打开/重新解析/删除三件事全在那一个页面里做,避免两处入口各改各的。 -->
<a class="btn" href="/sessions.html">最近审核</a>
<a class="btn" href="/admin.html" data-page-node-id="soJGFd2PWIpS6Hbp6B2s0w">后台管理</a>
<!-- 2026-10-10 主人定:右上按钮一字排开,从左到右 =
分组/匹配 → 后台管理 → 询价附件 → 最近审核 → 打开项目。 -->
<button class="btn" onclick="cfgOpen()" title="类似清单分组 / 历史匹配过滤词">⚙ 分组/匹配</button>
<!-- 询价附件(2026-10-09 改版 主人定):**常驻按钮**,叠在「打开项目」正下方。
数据 = 对比框点「采纳」收进来的附件(全局、按内容去重),不再是后台绑定关系的只读展示。 -->
<span class="inqstack">
<button class="btn pri" onclick="openDlg()" data-page-node-id="rlEedAWfYgLJDVpuFxmmxq">打开项目</button>
<button class="btn" id="btnInq" onclick="openInq()"
title="对比框点「采纳」收进来的附件目录;勾选后可批量下载">询价附件</button>
</span>
<a class="btn" href="/admin.html" data-page-node-id="soJGFd2PWIpS6Hbp6B2s0w">后台管理</a>
<!-- 询价附件(2026-10-09 改版;2026-10-10 决策 28 改会话级 主人定):**常驻按钮**。
数据 = 当前会话在对比框点「采纳」收进来的附件(按内容去重;切会话跟着切,删会话才清,
没打开项目=空),不再是后台绑定关系的只读展示。 -->
<button class="btn" id="btnInq" onclick="openInq()"
title="当前会话收进的附件目录(切会话跟着切,删会话才清);勾选后可批量下载">询价附件</button>
<a class="btn" href="/sessions.html">最近审核</a>
<button class="btn pri" onclick="openDlg()" data-page-node-id="rlEedAWfYgLJDVpuFxmmxq">打开项目</button>
</div>
</div>
@@ -311,7 +307,7 @@ body.grptree-dragging{cursor:col-resize !important;user-select:none}
<!-- 4 精确度 -->
<div class="fld" data-page-node-id="L7WHSCZ9g0QKYYx6MjiNLs"><span class="hbl" data-page-node-id="F4AxsY4ncv9GWEqCHbf034">精确度</span>
<select id="htier" data-page-node-id="LbhWXpxnhw5lV82pdsfuOA">
<option value="es" selected data-page-node-id="OaXzgQkGcKDX2AtsnV7P9M">精确 + 次精确</option>
<option value="es" selected data-page-node-id="OaXzgQkGcKDX2AtsnV7P9M">精确 + 次精确 + 字集</option>
<option value="e" data-page-node-id="Kh8bbU4OCl9D4ybwAIM10j">只看精确</option>
<option value="all" data-page-node-id="PZGYWLpejvt9tE5Nq5xTK1">全部(含模糊)</option>
</select>
@@ -587,18 +583,20 @@ async function doOpen(){
if(!r.ok){ $('omsg').textContent=r.msg; return; }
SID=r.session_id;
try{ localStorage.setItem('wb_sid', SID); }catch(e){} // 记住上次审核的会话(切页回来恢复用)
loadAdopt(); // 决策 28:徽章随会话切(新会话=空目录)
// 保存本工程选中的专业(供类似清单按专业分组)
try{ await J('/api/session/setting',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({scope:`session:${SID}`,k:'profession',v:$('oprof').value||''})}); }catch(e){}
$('sinfo').innerHTML=`<b>${esc($('oname').value||f.name)}</b> · 基准 ${esc($('oper').value)} · 清单 ${r.n_bill} · 定额 ${r.n_norm} · 工料机 ${r.n_lme}`;
$('sinfo').innerHTML=`<b>${esc($('oname').value||f.name)}</b>`; // 2026-10-10 主人定:只留名称(基准/条数尾串取消)
$('omask').classList.remove('on');
await loadLme(); tab('p3'); // 2026-09-30:打开后先看「原数据」
$('msg').textContent=r.msg;
}
/* ---------- 询价附件(2026-10-09 改版 主人定)----------
口径:对比框**工料机行**点「采纳」时,该行跟随的附件收进全局目录(按内容 sha 去重,
/* ---------- 询价附件(2026-10-09 改版;2026-10-10 决策 28 改**会话级** 主人定)----------
口径:对比框**工料机行**点「采纳」时,该行跟随的附件记到**当前会话**名下(按内容 sha 去重,
一个附件被采纳多次只显示一个);右侧项目名与采纳备注同源。
切会话=切目录(该会话上次收的还在);删会话连带撤事件;没打开项目=空目录。
2026-10-09 晚:旧「后台绑定」口径的行标/行高亮(询价小标)整套撤掉——
工作台不再展示后台绑定关系,绑定是后台的事;目录里只看采纳。 */
@@ -607,7 +605,7 @@ let ADOPT={atts:[],projs:[],sel:'',checked:new Set()};
async function loadAdopt(){
try{
const d=await J('/api/adopt/list');
const d=await J('/api/adopt/list'+(SID?('?sid='+SID):'')); // 决策 28:只取当前会话的
if(d&&d.ok){
ADOPT.atts=d.atts||[]; ADOPT.projs=d.projs||[];
if(ADOPT.sel && !ADOPT.atts.some(a=>a.sha===ADOPT.sel)) ADOPT.sel='';
@@ -617,7 +615,8 @@ async function loadAdopt(){
}catch(e){}
}
function openInq(){
async function openInq(){
await loadAdopt(); // 打开时现取:会话切换/别处采纳都最新
ADOPT.sel=''; // 打开停在根目录:右侧显示全部项目名称
ADOPT.checked=new Set(ADOPT.atts.map(a=>a.sha)); // 每次打开默认全选(主人定)
renderInqTree(); renderInqRight(); updInqCnt();
@@ -629,7 +628,10 @@ $('inqmask').onclick=e=>{ if(e.target===$('inqmask')) closeInq(); };
function renderInqTree(){
const el=$('inqTree');
if(!ADOPT.atts.length){
el.innerHTML='<div class="empty" style="padding:16px 10px">还没有收进附件。<br>在对比框点工料机行的「采纳」,该行跟随的附件就会收进这里。</div>';
el.innerHTML='<div class="empty" style="padding:16px 10px">'
+(!SID?'还没打开项目。<br>打开项目后,在对比框点工料机行的「采纳」,该行跟随的附件就归到这个会话名下。'
:'这个会话还没有收进附件。<br>在对比框点工料机行的「采纳」,该行跟随的附件就会收进这里。')
+'</div>';
return;
}
const allOn=ADOPT.checked.size===ADOPT.atts.length;
@@ -769,19 +771,30 @@ function curPrice(){
const v = parseFloat(tr.dataset.price); return isNaN(v)?null:v;
}
function renderHist(){
const tiers = $('htier').value==='all' ? ['精确','次精确','模糊']
: ($('htier').value==='e' ? ['精确'] : ['精确','次精确']);
const tiers = $('htier').value==='all' ? ['精确','次精确','字集','模糊']
: ($('htier').value==='e' ? ['精确'] : ['精确','次精确','字集']);
// 检索模式(B):行没有匹配档位,精确度条件不适用;比对模式照旧按档位过滤
let rows = HINDEP ? HROWS.slice() : HROWS.filter(x=>tiers.includes(x.tier));
// 结果关键字搜索:名称/项目特征(规格)/单位,空格分词 AND;直径符号变体折叠(φ/Φ/ϕ/⌀/Ø 一视同仁,
// 与后端 _kw_fold 同款 —— 2026-10-08 主人报「Φ12mm 搜不出来」:库里大写 Φ 与手输小写 φ 互不命中)
// 与后端 _kw_fold 同款 —— 2026-10-08 主人报「Φ12mm 搜不出来」:库里大写 Φ 与手输小写 φ 互不命中)。
// 2026-10-10 决策 27:不按排序——中文词拆单字逐字在场(「混凝土钢筋」命中「钢筋混凝土」),
// 字母数字段(C30、400、P.O)保持原样子串;特征里的排序序号(1、 2. (3) a)①)剥掉不参与(与后端 norm_attr 同款)。
const fold=s=>(s||'').toLowerCase().replace(/[ϕ⌀ø]/g,'φ');
// 序号剥离在 fold 之后(保证 [a-z] 能命中大写字母);与后端 _ORD 同一套规则
const stripOrd=s=>(s||'').replace(/[①-⑳]/g,'').replace(/[((]\d{1,3}[))]/g,'')
.replace(/(?<![a-z0-9.])\d{1,3}[、]/g,'')
.replace(/(?<![a-z0-9.])\d{1,2}[..](?!\d)/g,'')
.replace(/(?<![a-z0-9])[a-z][、))]/g,'');
const kw=fold(FLT.kw||'');
if(kw){
const toks=kw.split(/\s+/).filter(Boolean);
rows=rows.filter(x=>{
const hay=fold(((x.name||'')+'\n'+(x.attr||'')+'\n'+(x.spec||'')+'\n'+(x.unit||'')));
return toks.every(t=>hay.includes(t));
const hay=fold(x.name||'')+'\n'+stripOrd(fold((x.attr||'')+'\n'+(x.spec||'')))+'\n'+fold(x.unit||'');
return toks.every(t=>{
for(const r of (t.match(/[a-z0-9φ][a-z0-9φ./*\-]*/g)||[])) if(!hay.includes(r)) return false;
for(const ch of new Set(t.replace(/[a-z0-9φ./*\-]/g,''))) if(!hay.includes(ch)) return false;
return true;
});
});
}
const s=$('hsort').value;
@@ -812,7 +825,7 @@ function renderHist(){
const tg=(!isLme && x.bill_id)
? `<span class="tog" title="展开/收起该历史清单下的定额" onclick="event.stopPropagation();tgHist(this,${x.bill_id})">+</span>`
: '';
const tdbadge=`<td class="c"><span class="tg tg-${x.tier==='精确'?'e':(x.tier==='次精确'?'s':'f')}">${x.tier}</span></td>`;
const tdbadge=`<td class="c"><span class="tg tg-${x.tier==='精确'?'e':((x.tier==='次精确'||x.tier==='字集')?'s':'f')}">${x.tier}</span></td>`;
const body = isLme
? `<td class="c">${seq0+i+1}</td>`
+ `<td class="c"><span class="srcbadge ${SRC_CLS[x.src]||'src-p'}">${esc(x.src||'—')}</span></td>`
@@ -837,7 +850,7 @@ function renderHist(){
+ `<td>${ell(x.region,'—')}</td>`
+ `<td class="l">${ell(x.period)}</td><td class="r">${num(x.sim,2)}</td>`
+ `<td class="c">${op.join(' · ')}</td>`;
return `<tr data-i="${i}" onclick="pickHistRow(${i},this)">${isLme?'':`<td class="tg">${tg}</td>`}${body}</tr>`;
return `<tr data-i="${i}"${isLme?' data-lme="1"':''} onclick="pickHistRow(${i},this)">${isLme?'':`<td class="tg">${tg}</td>`}${body}</tr>`;
}).join('')||`<tr><td colspan="${cols.length}" class="empty">${HINDEP?(isLme?'没有符合 条件+关键词 的入库工料机/价格':'没有符合 条件+关键词 的入库清单'):'没有命中的历史项'}</td></tr>`;
// 统计(命中数角标已按主人 10-08 要求删除)
const vs=rows.map(x=>x.price).filter(v=>v!=null).sort((a,b)=>a-b);
@@ -911,16 +924,19 @@ async function tgHist(el,bid){
let htipT=0, tipTd=null;
const htip=document.createElement('div'); htip.id='htip'; document.body.appendChild(htip);
function hideHistTip(){ clearTimeout(htipT); tipTd=null; htip.style.display='none'; }
function showHistTip(x, td){
function showHistTip(x, td, lmeOnly){
// lmeOnly(项目工料机结果行,2026-10-10 主人定):只显示完整名称,不弹项目特征/定额
htip.innerHTML = '<div class="htip-hd">'+esc(x.name||'')+'</div>'
+ '<div class="htip-attr">' + (x.attr ? esc(fmtAttr(x.attr)) : '<span class="tip">(无项目特征)</span>') + '</div>'
+ '<div class="htip-hd">定额(编码 / 名称)</div><div class="htip-norms"><div class="tip" style="padding:4px 10px">读取中…</div></div>';
+ (lmeOnly ? '' :
'<div class="htip-attr">' + (x.attr ? esc(fmtAttr(x.attr)) : '<span class="tip">(无项目特征)</span>') + '</div>'
+ '<div class="htip-hd">定额(编码 / 名称)</div><div class="htip-norms"><div class="tip" style="padding:4px 10px">读取中…</div></div>');
const r=td.getBoundingClientRect();
htip.style.visibility='hidden'; htip.style.display='block';
const L=Math.min(window.innerWidth-htip.offsetWidth-10, Math.max(6, r.left));
let T=r.bottom+4;
if(T+htip.offsetHeight>window.innerHeight-8) T=Math.max(8, r.top-htip.offsetHeight-6);
htip.style.left=L+'px'; htip.style.top=T+'px'; htip.style.visibility='visible';
if(lmeOnly) return;
if(!x.bill_id){ htip.querySelector('.htip-norms').innerHTML='<div class="tip" style="padding:4px 10px">(此行无定额)</div>'; return; }
histNorms(x.bill_id).then(ns=>{
const box=htip.querySelector('.htip-norms'); if(!box) return;
@@ -936,7 +952,7 @@ $('htb').addEventListener('mouseover', e=>{
if(!tr || !tr.dataset.i) return;
const x=VISIBLE_ROWS[+tr.dataset.i]; if(!x) return;
clearTimeout(htipT);
htipT=setTimeout(()=>{ tipTd=td; showHistTip(x, td); }, 250);
htipT=setTimeout(()=>{ tipTd=td; showHistTip(x, td, tr.dataset.lme==='1'); }, 250);
});
$('htb').addEventListener('mouseout', e=>{
const td=e.target.closest('td');
@@ -1092,8 +1108,8 @@ async function recOpen(sid,keep){
const m=RECMAP[sid]||{};
SID=sid;
try{ localStorage.setItem('wb_sid', sid); }catch(e){} // 记住上次审核的会话
const p=(m.period_from!=null)?(yms(m.period_from)+(m.period_to&&m.period_to!==m.period_from?'~'+yms(m.period_to):'')):'';
$('sinfo').innerHTML=`<b>${esc(m.name||'')}</b>${p?' · 基准 '+esc(p):''} · 清单 ${m.n_bill??0} · 定额 ${m.n_norm??0} · 工料机 ${m.n_lme??0}`;
loadAdopt(); // 决策 28:切会话=切附件目录(该会话上次收的还在)
$('sinfo').innerHTML=`<b>${esc(m.name||'')}</b>`; // 2026-10-10 主人定:只留名称(基准/条数尾串取消)
if(!keep) closePops();
await loadLme(); tab((document.querySelector('.tab.on')||{dataset:{p:'p0'}}).dataset.p);
$('msg').textContent='已切到该会话';
@@ -1408,7 +1424,7 @@ async function initFilters(){
calcArea(); updAreaBtn(); updPerBtn();
}
initFilters();
loadAdopt(); // 顶栏「询价附件」常驻按钮:进页面就取采纳目录(计数即时可见,不依赖先打开项目)
loadAdopt(); // 顶栏「询价附件」常驻按钮:进页面先取一次(此时无会话=空);打开/切会话由 doOpen/recOpen 再取
/* 从会话管理页 /workbench.html?sid=N 直接打开某个会话(management 页「打开」用)。
2026-10-07 主人报「从后台/最近审核切回工作台,原数据消失」:URL 没有 sid 时,
@@ -1432,17 +1448,16 @@ async function initFromUrl(){
// 2026-10-07 主人定:从「最近审核」点「打开」=**重新解析刷新**(哪怕哈希一致),
// 旧口径数据不留在屏上;原文件已不在的老会话退回直接切过去,不打断。
// (「打开工程」/后台导入本就每次真解析;页面普通刷新恢复 wb_sid 不算“打开”,不重解析。)
let repMsg = '';
if(fromUrl){
try{
const r = await J('/api/session/reparse', {method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({session_id: sid})});
if(r && r.ok){ await recLoad(); repMsg = '已重新解析刷新:清单 ' + r.n_bill + ' 条、定额 '
+ r.n_norm + ' 条、工料机 ' + r.n_lme + ' 条'; }
// 2026-10-10 主人定:完成提示改右下角浮层,只报条数(不再顶栏长句)
if(r && r.ok){ await recLoad();
toast('清单 ' + r.n_bill + ' 条、定额 ' + r.n_norm + ' 条、工料机 ' + r.n_lme + ' 条'); }
}catch(e){}
}
await recOpen(sid, true);
if(repMsg) $('msg').textContent = repMsg;
if(['p0','p1','p2','p3'].includes(savedTab) && savedTab !== 'p3') tab(savedTab);
if(!fromUrl) $('msg').textContent = '已恢复上次审核:《' +
(($('sinfo').querySelector('b')||{}).textContent || '') + '》(「最近审核」页可切换其他工程)';