Files
pricing_review/CostReview/app/core/match.py
lianjianwei2024 79ab8d1ffd feat(history): 历史对比框工具栏恒显最大集并统一筛选逻辑(决策 208)
工具栏来源/价格范围/附件不再按页签隐藏,改一处=改两处;新增 histCtxUI 处理上下文置灰,histFlt 共享比对与检索两路径;match_bill/hist_search 及对应 API 透传 pmin/pmax/att,价格与附件筛选在清单侧同生效;补 p1/p3 精确度默认,修复 163 死控件缺口。
2026-10-26 09:39:01 +08:00

899 lines
50 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
比对引擎(M4 核心):拿会话库(本次审核)的一条 清单/工料机,去历史库找相似项。
规则(2026-09-28 你定的):
1. **排除未纳入的批次**(x_enabled=0 的一律不出现)
2. 筛选:单价类型(原「文件类型」,2026-09-29 改名,工作台改成**多选**,默认全勾=不筛)/ 建设单位 /
地区(**树形多选**:每个节点=一个前缀约束,多节点 OR,「全国」=不筛)——默认全选=不筛。
(信息价目录 2026-09-29 起**工作台不再筛**,后台仍保留)
3. 期次显示**离基准最近的那个端点**
4. 结果按「距基准先近后远」排序,同距按档位(精确>次精确>模糊)
5. 信息价/市场价的结果行带**原文件字段**(可打开附件 PDF)
"""
import sqlite3, re, threading
from itertools import permutations
SIM_MIN = 0.60
# 次精确名称护栏(2026-10-10 主人定):清单次精确 = 编码+单位,而国标编码末 3 位是项目内
# 顺序号,不同项目把不同设备编到同码同单位很常见(实例:030507008001/台 一边是高空抛物
# 摄像枪、一边是 LED 补光灯)。名称(匹配归一后)字符 Jaccard 低于该值的次精确命中不算
# 同一清单项,剔除。精确档哈希含名称、工料机/价格次精确 = 名称+单位,都不受影响。
SEMI_NAME_MIN = 0.2
def lme_list_where(prefix=""):
"""「项目工料机」唯一过滤规则(2026-10-09 起唯一实现挪到本模块:工料机检索同用)。
① 排除 Kind 6 配合比 / 7 机具台班 —— 组合类(下挂人工/燃料/折旧…),单独比价无意义;
② 排除单位为 元 / 工日 / 台班 —— 费用科目、人工、机械台班,没有跨项目价比对价值。
只在**取数时**过滤,导入保持全量(子目工料机面板、名称反查不受影响)。
⚠️ Kind 两库都是 **INTEGER** 存储:SQLite 里 `整数 NOT IN ('6','7')` 恒为真(跨类型类
不相等),必须 CAST 成文本再比 —— 此前后台 _lme_rows 的旧写法就因此漏放 Kind 6 行。
prefix:列限定前缀。裸列名只能在「JOIN 的表里没有 Kind/Unit 同名列」的查询用;
检索类查询 JOIN 了 batches(有 kind 列,SQLite 列名不分大小写)必须传 'l.'。"""
p = (prefix + ".") if prefix else ""
return ("CAST(IFNULL(%sKind,'') AS TEXT) NOT IN ('6','7') "
"AND TRIM(IFNULL(%sUnit,'')) NOT IN ('元','工日','台班')" % (p, p))
def norm(s):
s = (s or "").strip().replace("(", "(").replace(")", ")").replace("×", "*")
return re.sub(r"\s+", "", s).lower()
# ---------- 匹配过滤词(2026-10-01 新增,可配置) ----------
# 这些词在「与历史项目比对」时会被剥掉,不参与相似度计算(例如「拆除 / 原有 / 恢复」等噪声词)。
# ⚠️ 用线程本地存储:ThreadingHTTPServer 每请求一个线程,避免并发请求互相污染过滤词。
_tls = threading.local()
def set_stopwords(words):
"""设置匹配过滤词(线程本地)。words: iterable of str(空/None 即清空)。"""
_tls.stopwords = set(w for w in (words or []) if w)
def norm_match(s):
"""匹配用的归一:在 norm 基础上剥掉过滤词(不参与相似度计算)。单位比较仍用 norm()。"""
s2 = norm(s)
for w in getattr(_tls, "stopwords", ()):
if w:
s2 = s2.replace(w, "")
return s2
def ym(m):
"""月序号 → '2026.07'(空串按 None 处理)"""
if m in (None, ""):
return "—"
m = int(m)
return "%04d.%02d" % (m // 12, m % 12 or 12) if m % 12 else "%04d.%02d" % (m // 12 - 1, 12)
def nearest(p1, p2, base):
"""起~止里离基准最近的那个端点(空串按 None 处理,避免 int/abs 抛错)"""
if p1 in (None, ""):
return p2
if p2 in (None, ""):
return p1
return p1 if abs(p1 - base) <= abs(p2 - base) else p2
def span(base):
"""基准期次:既可以是单月(int),也可以传 (起, 止) 区间 —— 统一成 (bf, bt)"""
if isinstance(base, (tuple, list)):
return (base[0], base[1] or base[0])
return (base, base)
def dist(p1, p2, bf, bt=None):
"""离基准的距离(月):
- 历史区间与基准区间**有重叠** → 0(工期覆盖基准,视为同期,排最前)
- 整体早于基准 → bf - 最晚端点;整体晚于基准 → 最早端点 - bt
"""
if bt is None:
bt = bf
if p1 in (None, ""):
p1 = None
if p2 in (None, ""):
p2 = None
lo = p1 if p1 is not None else p2
hi = p2 if p2 is not None else p1
if lo is None:
return 9999
if hi < bf:
return bf - hi
if lo > bt:
return lo - bt
return 0
def jaccard(a, b):
A, B = set(a or ""), set(b or "")
if not A or not B:
return 0.0
return len(A & B) / len(A | B)
# ---------- 字集键 / 加权相似度(2026-10-10 决策 27 主人定) ----------
def set_norm(s):
"""字集归一:归一后按字符排序——顺序无关的等价串,「钢筋混凝土」与「混凝土钢筋」同串。"""
return "".join(sorted(norm(s)))
def bill_setkey(name, unit):
"""清单字集键(存 bills.x_setkey):名称字集 + 单位——名称不按排序等价、单位一致。"""
return set_norm(name) + "|" + norm(unit)
def lme_setkey(name, spec, unit):
"""工料机字集键(存 lmes.x_setkey):名称+规格**合并成一个池**再排序(主人 2026-10-10 定
「名称+规格型号作为一个整体、不按排序匹配」)+ 单位。"""
return set_norm((name or "") + (spec or "")) + "|" + norm(unit)
# 特征里的排序序号——只是排版顺序,剥掉不参与匹配(2026-10-10 主人定)。
# ⚠️ 在 norm() 之后套用(小写、全角括号已转半角、空白已去)。「前面的字符不是字母/数字/点」
# 负向断言保证 IP67、2.8mm、42.5 这类**正文数字**不被误剥——序号前的邻居是文字或开头。
_ORD = re.compile(r"[①-⑳]"
r"|([0-9]{1,3})|\([0-9]{1,3}\)"
r"|(?<![a-z0-9.])[0-9]{1,3}、"
r"|(?<![a-z0-9.])[0-9]{1,2}[..](?![0-9])"
r"|(?<![a-z0-9])[a-zA-Z][、))]")
def norm_attr(s):
"""项目特征/规格的匹配归一:norm 基础上剥掉**排序序号**(1、 2. (3) a) ①——
正文里的数字字母(IP67、2.8mm、C30)原样保留(小数点后跟数字不剥)。再剥过滤词。"""
s2 = _ORD.sub("", norm(s))
for w in getattr(_tls, "stopwords", ()):
if w:
s2 = s2.replace(w, "")
return s2
# 字母数字身份 token(含小数点/斜杠/连字符/乘号/直径符)
_TOK = re.compile(r"[a-z0-9φ][a-z0-9φ./*\-]*")
def sim_weighted(qname, hname, qattr, hattr):
"""模糊档加权相似度(2026-10-10 决策 27 主人定):
0.7×名称字集Jaccard + 0.3×特征字集Jaccard —— 名称优先于项目特征;
字母数字优于文字:查询**名称**里的字母数字 token(400、C30、IP67)在候选
(名称+特征)里找不到 → 一票否决返回 0;查询**特征**里的 token 缺失 → 特征得分减半。
中文按字符集合(不按排序)。入参都是归一后的串。"""
hay = hname + hattr
if any(t not in hay for t in _TOK.findall(qname)):
return 0.0
# 两边都没写特征 → 特征维度按满分(不惩罚);一边有一边没有才正常算
a = jaccard(qattr, hattr) if (qattr or hattr) else 1.0
if any(t not in hay for t in _TOK.findall(qattr)):
a *= 0.5
return 0.7 * jaccard(qname, hname) + 0.3 * a
def _filters(kinds, units, classes, prefix="bt", self_src=None, area=None, orgs=None, projs=None):
"""生成批次级筛选 SQL(默认全选=不筛)
self_src:被审工程的源文件名 —— 同一个文件若也在历史库里,排除掉(避免自己跟自己比)
area:地区前缀列表 [(省, 市, 区/县), ...](2026-09-29 树形多选后改成这样)
—— 一个元组就是一个前缀约束(市/区为空=该级不限),**多个元组之间是 OR**;整表空=不限。
例:[("广东省","",""),("湖南省","长沙市","")] = 广东全省 或 湖南长沙。
units:单价类型码(原「文件类型」,2026-09-29 改名)—— 清单比对用;工料机比对不用
orgs:单位(2026-10-08 主人定,工料机比对专用):建设单位 ∪ 发布单位 **跨来源联查**,
一批名字同时匹配 BulidUnit(工程批次)OR x_publisher(价格批次);
工程批次 x_publisher 恒空、价格批次 BulidUnit 恒空,OR 起来天然各走各的。
projs:项目名称(决策 141,2026-10-20,主人定):按批次项目名 bt.Name 精确匹配(IN),
与 units 同款;比对/检索两条路径、清单/工料机两侧全部透传。
"""
w, args = ["%s.x_enabled=1" % prefix], []
if area:
ors, a2 = [], []
for prov, city, dist in area:
cond = []
if prov:
cond.append("%s.x_province=?" % prefix); a2.append(prov)
if city:
cond.append("%s.x_city=?" % prefix); a2.append(city)
if dist:
cond.append("%s.x_district=?" % prefix); a2.append(dist)
if cond:
ors.append("(" + " AND ".join(cond) + ")")
if ors:
w.append("(" + " OR ".join(ors) + ")")
args += a2
if self_src:
w.append("(%s.x_src_hash IS NULL OR %s.x_src_hash<>?)" % (prefix, prefix))
args.append(self_src)
if kinds:
w.append("%s.FileKind IN (%s)" % (prefix, ",".join("?" * len(kinds))))
args += list(kinds)
if units:
w.append("%s.BulidUnit IN (%s)" % (prefix, ",".join("?" * len(units))))
args += list(units)
if orgs:
w.append("(%s.BulidUnit IN (%s) OR %s.x_publisher IN (%s))"
% (prefix, ",".join("?" * len(orgs)), prefix, ",".join("?" * len(orgs))))
args += list(orgs) + list(orgs)
if projs:
w.append("%s.Name IN (%s)" % (prefix, ",".join("?" * len(projs))))
args += list(projs)
if classes:
w.append("p.Class IN (%s)" % ",".join("?" * len(classes)))
args += list(classes)
return (" AND ".join(w), args)
def _price_range(col, pmin, pmax):
"""价格范围(2026-10-08 主人定,工料机比对专用):对除税单价的下限/上限。
col:价格列名(l.NoTaxPrice / p.NoTaxPrice,调用方按所在 SQL 传入)。"""
w, args = [], []
if pmin is not None:
w.append("%s >= ?" % col); args.append(pmin)
if pmax is not None:
w.append("%s <= ?" % col); args.append(pmax)
return (" AND ".join(w) if w else "1=1", args)
def _kw_fold(s):
"""检索词归一(2026-10-08 主人报「Φ12mm 搜不出来」):小写化 + 直径符号变体统一为 φ。
SQLite 的 LIKE/LOWER **只对 ASCII 不分大小写** —— 库里 Φ12mm(大写)与手输 φ12mm(小写)
互搜不到;ϕ/⌀/Ø 同理。检索词与 SQL 列两边都折叠成同一个字符(见 _kw_like)后再 LIKE。"""
s = (s or "").lower() # Python 的 lower 折叠希腊/拉丁大小写(SQLite 的不会)
for ch in ("ϕ", "⌀", "ø"):
s = s.replace(ch, "φ")
return s
def _kw_like(col):
"""SQL 列侧的同款折叠表达式(与 _kw_fold 配对):REPLACE 各变体 → φ 再 LOWER。
col:列名(可为别名,如 name / spec / b.Name)。"""
e = col
for a in ("Φ", "ϕ", "⌀", "Ø", "ø"):
e = "REPLACE(%s, '%s', 'φ')" % (e, a)
return "LOWER(%s)" % e
def _kw_reqs(t):
"""一个检索词的「要求组」拆解(2026-10-11 决策 38 分级)。
返回 (strict, loose):两者都是 req 组列表——组内各图案**任一**命中即算(字段之间 OR ×
组内图案 OR),组与组之间 AND。strict 成立必然蕴含 loose 成立。
strict(严格档,置顶):字母数字段(C30、400、P.O)保持原样子串;
中文 2~3 字 → **连写、不分字序**(土方=%土方%或%方土%;3 字 6 种排列);
中文 ≥4 字 → 逐字在场(保住「混凝土钢筋」↔「钢筋混凝土」互搜,决策 27 原诉求)。
loose(兜底档,垫底):= 决策 27 原口径——字母数字段子串 + 中文全部逐字在场。
「混凝土钢筋 土方」输入下,只要行内全部字都在场(土在混凝土、方在方式)也算命中,
只排到严格命中的后面(2026-10-11 主人定「用全拆字兜底,排序最后」)。"""
segs = _TOK.findall(t)
chars = sorted({c for c in re.sub(r"[a-z0-9φ./*\-]", "", t)})
strict, loose = [], []
for s in segs:
strict.append(["%" + s + "%"])
loose.append(["%" + s + "%"])
if not chars:
pass
elif len(chars) <= 3:
pats = sorted({"".join(p) for p in permutations(chars)}) # 连写不分序:全排列去重
strict.append(["%" + p + "%" for p in pats])
loose.extend(["%" + c + "%"] for c in chars)
else:
strict.extend(["%" + c + "%"] for c in chars) # ≥4 字:严格=兜底同款
loose.extend(["%" + c + "%"] for c in chars)
return strict, loose
def _kw_req_sql(fields, groups, args_out):
"""req 组列表 → SQL 布尔串:组内(字段 × 图案)OR,组间 AND。? 按出现序追加 args_out。"""
out = []
for g in groups:
pats = []
for pat in g:
pats += ["%s LIKE ?" % _kw_like(f) for f in fields]
args_out.extend([pat] * len(fields))
out.append("(" + " OR ".join(pats) + ")")
return " AND ".join(out)
def _kw_conds(fields, kw, where_out, args_out):
"""关键字检索 WHERE 条件(结果集口径):**兜底档**——每个词按「字母数字段子串 +
中文逐字在场」圈行,与 2026-10-10 决策 27 的结果集**完全一致**(不因分级收紧)。
严格档不进 WHERE,只进 ORDER BY 置顶(_kw_rank_expr,决策 38:全拆字兜底排序最后)。"""
for t in (kw or "").split():
if not t:
continue
t = _kw_fold(t)
_strict, loose = _kw_reqs(t)
if loose:
where_out.append("(" + _kw_req_sql(fields, loose, args_out) + ")")
def _kw_rank_expr(fields, kw, args_out):
"""严格档布尔表达式(决策 38,ORDER BY 置顶用):**所有**词都按严格档命中 → 为真。
调用方拼成 CASE WHEN <expr> THEN 0 ELSE 1 END 放排序首键——严格命中在前,
全拆字兜底的行不排除、排到同条件行的最后。
⚠️ 表达式的 ? 追加在 args_out 尾部:必须在 WHERE 全部参数之后、LIMIT/OFFSET 参数之前调用。
无有效检索词 → 返回 None(排序维持原样)。"""
groups = []
for t in (kw or "").split():
if not t:
continue
strict, _loose = _kw_reqs(_kw_fold(t))
groups += strict
if not groups:
return None
return _kw_req_sql(fields, groups, args_out)
def _stop_conds(fields, stop, where_out, args_out):
"""屏蔽词排除条件(2026-10-11 主人定):任一字段含任一屏蔽词 → 整行排除。
与关键词不同,屏蔽词**不拆字、不做排列**——按输入词的字符顺序整词命中
(%拆除% 只挡"拆除"连写,不挡"除…拆"散落、"除拆"倒序——2026-10-11 主人定
「按每组出现的词及词的顺序屏蔽」)。与 _kw_conds 同一套折叠(大小写/直径符)。
放在 WHERE 里、分页 LIMIT 之前生效——检索模式每页行数不会因屏蔽而缩水。"""
for w in (stop or []):
w = _kw_fold(str(w).strip())
if not w:
continue
where_out.append("NOT (" + " OR ".join("%s LIKE ?" % _kw_like(f) for f in fields) + ")")
args_out.extend(["%" + w + "%"] * len(fields))
def stop_words(s):
"""屏蔽词输入解析:空格/半角逗号/全角逗号分隔(与分组设置关键词同款分隔符)。"""
return [t for t in re.split(r"[,,\s]+", (s or "")) if t]
def _self_filter(rows, self_name, self_src):
"""排除「被审工程自己」(2026-10-10 主人定收紧口径):只认
① 同一份文件 —— 批次 x_src_hash 与会话源文件名完全相同(同一文件导入两边);
② 项目名与会话名完全相同。
原「文件名主干前 12 字」启发式删除:同项目的另一版本(.cos / .cos4、改名副本)是
不同文件,正是最要比对的对象,不该整批隐藏(实例:SX-18 前台 cos 副本 vs 后台 cos4,
摄像枪真命中被藏,只剩另一项目的 LED 补光灯)。"""
nm = (self_name or "").strip()
src = (self_src or "").strip()
if not nm and not src:
return rows
out = []
for r in rows:
if src and (r.get("src_hash") or "").strip() == src:
continue
if nm and (r.get("proj") or "").strip() == nm:
continue
out.append(r)
return out
def _in_period(r, pfrom, pto):
"""按"离基准最近的端点"判断是否落在起~止区间内"""
if pfrom is None and pto is None:
return True
v = r.get("period_m")
if v is None:
return False
if pfrom is not None and v < pfrom:
return False
if pto is not None and v > pto:
return False
return True
def _region3(p, c, d3):
"""省/市/区 → 「广东省/珠海市/香洲区」(空级跳过;全空=None)"""
return "/".join(x for x in (p, c, d3) if x) or None
def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfrom=None, pto=None, self_name=None, self_src=None, area=None, projs=None, pmin=None, pmax=None, att="all"):
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, projs=projs) # classes 只对价格库有意义,清单比对不筛目录
# 决策 208(2026-10-26 主人定):价格范围/附件筛选清单侧同样生效(工具栏恒显最大集)——
# 价格=b.Price(NULL 自然不落区间);附件=bill_attach 绑定的询价资料(与 api_search 回填 file 同一来源)。
if pmin is not None:
w += " AND b.Price>=?"; args = args + [pmin]
if pmax is not None:
w += " AND b.Price<=?"; args = args + [pmax]
if att == "yes":
w += " AND EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)"
elif att == "no":
w += " AND NOT EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)"
out, seen_ids, qn = [], set(), norm_match(row["Name"])
# L0 精确:编码+名称+单位(b.id 带回 → 前端展开定额 / 右栏「定额编码·名称」用)。
# 2026-10-10 决策 27:哈希里的编码只取前 9 位(后 3 位是项目内顺序码,没有对比意义),
# 口径变更由启动迁移 migrate_match_keys 重算存量,导入侧 import_job 同步。
sql = """SELECT '精确' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
bt.x_province, bt.x_city, bt.x_district
FROM bills b JOIN batches bt ON bt.id=b.batch_id
WHERE b.x_hash_exact=? AND bt.kind='project' AND %s LIMIT ?""" % w
for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit]):
d = dict(x); out.append(d); seen_ids.add(d["id"])
# L1 次精确:编码+单位(名称护栏 = SEMI_NAME_MIN,挡同码不同物)
if len(out) < limit:
sql2 = sql.replace("x_hash_exact", "x_hash_semi").replace("'精确'", "'次精确'")
seen = {(x["Name"], x["Attr"]) for x in out}
for x in c.execute(sql2, [row["x_hash_semi"]] + args + [limit]):
d = dict(x)
if (d["Name"], d["Attr"]) in seen:
continue
if jaccard(qn, norm_match(d["Name"])) < SEMI_NAME_MIN:
continue
if len(out) >= limit:
break
out.append(d); seen.add((d["Name"], d["Attr"])); seen_ids.add(d["id"])
# L1.5 字集精确(2026-10-10 决策 27):名称字集+单位等价——「钢筋混凝土」=「混凝土钢筋」,
# 不按排序的严格命中;键 = bills.x_setkey(导入落列,老库启动迁移回填)。
if len(out) < limit:
sqlk = """SELECT '字集' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
bt.x_province, bt.x_city, bt.x_district
FROM bills b JOIN batches bt ON bt.id=b.batch_id
WHERE b.x_setkey=? AND bt.kind='project' AND %s LIMIT ?""" % w
for x in c.execute(sqlk, [bill_setkey(row["Name"], row["Unit"])] + args + [limit]):
d = dict(x)
if d["id"] in seen_ids:
continue
if len(out) >= limit:
break
out.append(d); seen_ids.add(d["id"])
# L2 模糊:加权相似度(0.7×名称 + 0.3×特征,字母数字身份规则见 sim_weighted)
if len(out) < limit:
q = norm_match(row["Name"])[:6]
if q:
sql3 = """SELECT b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
bt.x_province, bt.x_city, bt.x_district
FROM bills b JOIN batches bt ON bt.id=b.batch_id
WHERE bt.kind='project' AND %s AND b.x_name_norm LIKE ? LIMIT 300""" % w
for x in c.execute(sql3, args + ["%" + q + "%"]):
if norm(x["Unit"]) != norm(row["Unit"]):
continue
if x["id"] in seen_ids:
continue
sim = sim_weighted(qn, norm_match(x["Name"]),
norm_attr(row["Attr"]), norm_attr(x["Attr"]))
if sim >= SIM_MIN:
d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim
out.append(d); seen_ids.add(x["id"])
if len(out) >= limit:
break
res = []
for d in out:
res.append({
"tier": d["tier"], "bill_id": d.get("id"),
"name": d["Name"], "attr": d["Attr"], "unit": d["Unit"],
"price": d["Price"], "proj": d["proj"], "bunit": d["BulidUnit"],
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
"period": ym(nearest(d["p1"], d["p2"], bf)),
"period_m": nearest(d["p1"], d["p2"], bf),
"dist": dist(d["p1"], d["p2"], bf, bt),
"sim": (1.0 if d["tier"] in ("精确", "字集") else
round(d["_sim"], 2) if "_sim" in d else
round(jaccard(qn, norm_match(d["Name"])), 2)), # 次精确=真实名称相似度(决策 27 E)
"src": "工程", "file": "", "src_hash": d.get("src") or "",
})
res = [r for r in res if _in_period(r, pfrom, pto)]
res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目)
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]]))
return res[:limit]
def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=None, self_src=None, page=1, stop=None, projs=None, pmin=None, pmax=None, att="all"):
"""独立检索(2026-10-08 主人定第 4 轮 B 方案):跨**全部入库项目**(kind='project')按
条件+关键词 直查清单库,与工作台选中的行无关(主人:"搜索条件高于点选清单")。
行结构与 match_bill() 完全一致 —— 前端 renderHist / 右栏 / ± 展开零改动复用,差异只有:
· tier 固定 "检索"(前端走蓝徽章),sim=None(相似度列显示 —);
· dist=0、排序由本函数做好(期次先近后远),前端不再按 dist 重排。
期次条件=区间重叠语义:批次的 [起,止] 与所选 [起,止] 有交集即命中(检索没有"基准期")。
self_name/self_src:被审工程自己(若它也入库了)**排除**(2026-10-08 主人定),
判定与 match_bill/match_lme 同一套(_self_filter 口径):同一份文件(x_src_hash 相同)
或项目名相同。
page:分页(2026-10-08 主人定,每页=limit 条,第 N 页 OFFSET (N-1)×limit)。
pmin/pmax/att:决策 208(2026-10-26 主人定)清单侧同生效——价格=b.Price,附件=bill_attach。"""
c = hist.cursor()
cond, args = _filters(kinds, units, [], prefix="bt", projs=projs) # 批次级条件(拼好的 SQL 串 + 参数)
extra = []
if pmin is not None:
extra.append("b.Price>=?"); args = args + [pmin]
if pmax is not None:
extra.append("b.Price<=?"); args = args + [pmax]
if att == "yes":
extra.append("EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)")
elif att == "no":
extra.append("NOT EXISTS(SELECT 1 FROM bill_attach ba WHERE ba.bill_id=b.id)")
nm = (self_name or "").strip()
src = (self_src or "").strip()
if src or nm:
self_ids = [r[0] for r in c.execute(
"SELECT id, Name, x_src_hash FROM batches WHERE kind='project'").fetchall()
if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)]
if self_ids:
extra.append("bt.id NOT IN (%s)" % ",".join("?" * len(self_ids)))
args = args + self_ids
_kw_conds(["b.Name", "b.Attr", "b.Unit"], kw, extra, args) # WHERE=兜底档:结果集与决策 27 一致(决策 38)
_stop_conds(["b.Name", "b.Attr", "b.Unit"], stop, extra, args) # 屏蔽词(2026-10-11):命中即整行排除
if pfrom is not None:
extra.append("bt.x_period_end_m >= ?")
args = args + [pfrom]
if pto is not None:
extra.append("bt.x_period_start_m <= ?")
args = args + [pto]
# 决策 38:严格档置顶 + 兜底打标——kwrank 同时是排序首键和行的 loose 标记来源。
# ⚠️ rank 的 ? 出现在 SELECT 列里(SQL 文本最前),绑定序 = rank_args 在 WHERE 参数之前。
rank_args = []
rank = _kw_rank_expr(["b.Name", "b.Attr", "b.Unit"], kw, rank_args)
rank_col = ("CASE WHEN %s THEN 0 ELSE 1 END kwrank" % rank) if rank else "0 AS kwrank"
order = ("kwrank, " if rank else "") + "bt.x_period_end_m DESC, bt.id DESC"
sql = """SELECT b.id, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2, %s
FROM bills b JOIN batches bt ON bt.id=b.batch_id
WHERE %s
ORDER BY %s LIMIT ? OFFSET ?""" % (rank_col, " AND ".join([cond] + extra), order)
args.append(int(limit))
args.append((max(int(page), 1) - 1) * int(limit))
res = []
for x in c.execute(sql, rank_args + args):
p1, p2 = x["p1"], x["p2"]
if p1 in (None, "") and p2 in (None, ""):
period = "—"
elif p2 in (None, "") or p1 == p2:
period = ym(p1)
elif p1 in (None, ""):
period = ym(p2)
else:
period = ym(p1) + "~" + ym(p2)
res.append({
"tier": "检索", "bill_id": x["id"],
"loose": bool(x["kwrank"]), # 决策 38:1=全拆字兜底命中(前端灰徽标「兜底」)
"name": x["Name"], "attr": x["Attr"], "unit": x["Unit"], "price": x["Price"],
"proj": x["proj"], "bunit": x["bunit"], "period": period,
"fkind": x["FileKind"], "region": _region3(x["x_province"], x["x_city"], x["x_district"]),
"period_m": p2 if p2 not in (None, "") else p1,
"dist": 0, "sim": None, "src": "工程", "file": "", "src_hash": "",
})
return res
def hist_search_lme(hist, orgs=None, area=None, pfrom=None, pto=None, kw="", pmin=None, pmax=None,
srcs=None, limit=200, self_name=None, self_src=None, page=1, att="all", kinds=None,
stop=None, projs=None):
"""独立检索 · 工料机版(2026-10-08 主人定):跨全部入库项目的**工料机**(lmes, kind='project')
+ 信息价/市场价明细(prices),条件+关键词直查,与工作台选中的行无关。
工料机标签的关键字查询走这里(hist_search 查的是清单库,工料机标签不适用)。
行结构与 hist_search() 一致(前端 renderHist / 分页 / 右栏零改动复用),差异:
· 多 spec 字段(规格型号,前端名称列灰字);
· src = 工程/信息价/市场价(前端来源徽章三色);
· bunit = 建设单位**或**发布单位(单位筛选 orgs 跨来源联查,见 _filters);
· 价格范围 pmin/pmax 对除税单价(子查询统一列名 price 后在外层过滤)。
期次=区间重叠语义;排序=期次先近后远(服务端排好,前端不再按 dist 重排);page 分页同 hist_search。
被审工程自己(若入库)与它挂的信息价/市场价一并排除(与 match_lme 同一套判定)。"""
c = hist.cursor()
srcs = srcs or ["project", "info", "market"]
# kinds=单价类型,只对工程来源生效(价格批次 FileKind 恒空,一传就整片剔除)
# → 工程/价格两个分支各拼各的 cond,cargs 分别跟各自的分支参数走
cond, cargs = _filters(kinds or [], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs, projs=projs)
condp, cargsp = _filters([], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs, projs=projs)
outer, oargs = [], []
nm = (self_name or "").strip()
src = (self_src or "").strip()
if src or nm:
self_ids = [r[0] for r in c.execute(
"SELECT id, Name, x_src_hash FROM batches").fetchall()
if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)]
if self_ids:
outer.append("batch_id NOT IN (%s)" % ",".join("?" * len(self_ids)))
oargs += self_ids
_kw_conds(["name", "spec", "unit"], kw, outer, oargs) # 不按排序(决策 27)
_stop_conds(["name", "spec", "unit"], stop, outer, oargs) # 屏蔽词(2026-10-11):命中即整行排除
if pfrom is not None:
outer.append("p2 >= ?"); oargs.append(pfrom)
if pto is not None:
outer.append("p1 <= ?"); oargs.append(pto)
wpr, apr = _price_range("price", pmin, pmax)
outer.append(wpr); oargs += apr
# 附件筛选(2026-10-08 主人定):有/无 —— 子查询统一列名 file(询价资料名或刊物原件名)
if att == "yes":
outer.append("file <> ''")
elif att == "no":
outer.append("file = ''")
# 决策 38:严格档置顶 + 兜底打标(同 hist_search)——kwrank 进 SELECT 列兼作排序键。
# ⚠️ rank 的 ? 出现在 SELECT 列里,绑定序 = rank_args 在 bargs+oargs 之前。
rank_args = []
rank = _kw_rank_expr(["name", "spec", "unit"], kw, rank_args)
rank_col = ("CASE WHEN %s THEN 0 ELSE 1 END kwrank" % rank) if rank else "0 AS kwrank"
order = ("kwrank, " if rank else "") + "p2 DESC, p1 DESC, batch_id"
branches, bargs = [], []
if "project" in srcs:
# 工程行附件 = 该工料机绑定的询价资料(lme_attach 一对一)
# ⚠️ 同用「项目工料机」过滤(2026-10-09 主人报:搜索能搜出已被屏蔽的单位如台班)——
# 列表口径屏蔽的行,检索口径同样不给;JOIN 了 batches(有 kind 列)必须带 l. 前缀。
branches.append("""SELECT 'project' src_kind, l.Name name, l.Specification spec, l.Unit unit,
l.NoTaxPrice price, l.TaxRate tax, l.TaxPrice price_tax,
'' note,
bt.Name proj, bt.BulidUnit org, l.batch_id batch_id,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
COALESCE(f.original_name,'') file, CAST(f.id AS TEXT) file_sha
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
LEFT JOIN lme_attach la ON la.lme_id=l.id
LEFT JOIN inquiry_files f ON f.id=la.file_id
WHERE bt.kind='project' AND %s AND %s""" % (cond, lme_list_where("l")))
bargs += cargs
pk = [s for s in ("info", "market") if s in srcs]
if pk:
branches.append("""SELECT bt.kind src_kind, p.Name name, p.Specification spec, p.Unit unit,
p.NoTaxPrice price, p.TaxRate tax, p.TaxPrice price_tax,
COALESCE(p.Note,'') note,
bt.Name proj, bt.x_publisher org, p.batch_id batch_id,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
a.original_name file, a.sha256 file_sha
FROM prices p JOIN batches bt ON bt.id=p.batch_id
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
WHERE bt.kind IN (%s) AND %s"""
% (",".join("'%s'" % k for k in pk), condp))
bargs += cargsp
if not branches:
return []
sql = ("SELECT *, %s FROM (%s) WHERE %s ORDER BY %s LIMIT ? OFFSET ?"
% (rank_col, " UNION ALL ".join(branches), " AND ".join(outer) or "1=1", order))
rows = c.execute(sql, rank_args + bargs + oargs + [int(limit), (max(int(page), 1) - 1) * int(limit)])
res = []
for x in rows:
p1, p2 = x["p1"], x["p2"]
if p1 in (None, "") and p2 in (None, ""):
period = "—"
elif p2 in (None, "") or p1 == p2:
period = ym(p1)
elif p1 in (None, ""):
period = ym(p2)
else:
period = ym(p1) + "~" + ym(p2)
res.append({
"tier": "检索",
"loose": bool(x["kwrank"]), # 决策 38:1=全拆字兜底命中(前端灰徽标「兜底」)
"name": x["name"], "spec": x["spec"], "attr": x["spec"],
"unit": x["unit"], "price": x["price"], "tax": x["tax"], "price_tax": x["price_tax"],
"proj": x["proj"], "bunit": x["org"], "period": period,
"fkind": None, "region": _region3(x["x_province"], x["x_city"], x["x_district"]),
"period_m": p2 if p2 not in (None, "") else p1,
"dist": 0, "sim": None,
"src": {"project": "工程", "info": "信息价", "market": "市场价"}[x["src_kind"]],
"note": x["note"],
"file": x["file"] or "", "file_sha": x["file_sha"] or "",
"file_url": (("/api/admin/inq/file/%s" % x["file_sha"]) if x["src_kind"] == "project"
else (("/api/admin/file/%s" % x["file_sha"]) if x["file_sha"] else "")),
"src_hash": "",
})
return res
def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=None, self_name=None, self_src=None, area=None, pmin=None, pmax=None, att="all", kinds=None, projs=None):
"""工料机:历史工程工料机 + 信息价/市场价(价格库)
2026-10-08 主人定:比对按「名称+规格型号+单位」三件套;筛选 = 来源/单价类型/单位/地区/期次/价格范围/附件。
orgs = 单位跨来源联查(建设单位 OR 发布单位,见 _filters);pmin/pmax = 价格范围(除税单价);
att = 附件 有/无(全部=不筛);kinds = 单价类型——**只对工程来源生效**(价格批次 FileKind 恒空,
一传就整片剔除,故价格查询一律不传)。
档位:精确 = md5(名称+规格+单位);次精确 = md5(名称+单位)(规格不同的同名可比价);
模糊 = 名称前6字候选 + Jaccard≥SIM_MIN + 单位一致。
工程行附件 = 该工料机绑定的询价资料(lme_attach);价格行附件 = 刊物上传原件。"""
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
srcs = srcs or ["project", "info", "market"]
c = hist.cursor()
out, seen_ids = [], set()
# ---- 历史工程工料机 ----
w, args = _filters(kinds or [], [], [], self_src=self_src, area=area, orgs=orgs, projs=projs)
wpr, apr = _price_range("l.NoTaxPrice", pmin, pmax)
w = w + " AND " + wpr; args = args + apr
res = []
if "project" in srcs:
# 工程分支三档同用「项目工料机」过滤(2026-10-09 主人拍板:配合比行(Kind 6, m3)曾
# 经模糊档漏出 —— 列表/检索/比对三处同一口径)。JOIN 了 batches(有 kind 列)必须
# 带 l. 前缀,见 lme_list_where 的说明。
# ⚠️ **信息价/市场价分支永远不过滤任何单位/类别**(主人 2026-10-09 明示"永远不能
# 屏蔽信息价/市场价的任何单位")—— 别把 lme_list_where 加到下面价格查询上。
sql = """SELECT '精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
f.id fid, f.original_name fname
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
LEFT JOIN lme_attach la ON la.lme_id=l.id
LEFT JOIN inquiry_files f ON f.id=la.file_id
WHERE l.x_hash_exact=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit]):
d = dict(x); out.append(d); seen_ids.add(d["id"])
if len(out) < limit:
# 次精确:名称+单位一致、规格不同(2026-10-08 主人定)——同名材料不同规格正是常比对象
seen_semi = {(x["Name"], x["Specification"]) for x in out}
sql2 = """SELECT '次精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
f.id fid, f.original_name fname
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
LEFT JOIN lme_attach la ON la.lme_id=l.id
LEFT JOIN inquiry_files f ON f.id=la.file_id
WHERE l.x_hash_semi=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
for x in c.execute(sql2, [row["x_hash_semi"]] + args + [limit]):
d = dict(x)
if (d["Name"], d["Specification"]) in seen_semi:
continue
if len(out) >= limit:
break
out.append(d); seen_semi.add((d["Name"], d["Specification"])); seen_ids.add(d["id"])
# 字集精确(2026-10-10 决策 27):名称+规格**合并字集**+单位等价——「P.O 42.5 水泥」
# =「水泥 42.5 P.O」这类不按排序的整体命中;键 = lmes.x_setkey(导入落列,老库迁移回填)。
if len(out) < limit:
sqlk = """SELECT '字集' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
f.id fid, f.original_name fname
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
LEFT JOIN lme_attach la ON la.lme_id=l.id
LEFT JOIN inquiry_files f ON f.id=la.file_id
WHERE l.x_setkey=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
for x in c.execute(sqlk, [lme_setkey(row["Name"], row["Specification"], row["Unit"])] + args + [limit]):
d = dict(x)
if d["id"] in seen_ids:
continue
if len(out) >= limit:
break
out.append(d); seen_ids.add(d["id"])
if len(out) < limit:
q = norm_match(row["Name"])[:6]
if q:
sql3 = """SELECT l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
f.id fid, f.original_name fname
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
LEFT JOIN lme_attach la ON la.lme_id=l.id
LEFT JOIN inquiry_files f ON f.id=la.file_id
WHERE bt.kind='project' AND %s AND %s AND l.x_name_norm LIKE ? LIMIT 300""" % (w, lme_list_where("l"))
for x in c.execute(sql3, args + ["%" + q + "%"]):
if norm(x["Unit"]) != norm(row["Unit"]):
continue
if x["id"] in seen_ids:
continue
sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]),
norm_attr(row["Specification"]), norm_attr(x["Specification"]))
if sim >= SIM_MIN:
d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim
out.append(d); seen_ids.add(x["id"])
if len(out) >= limit:
break
for d in out:
res.append({
"tier": d["tier"], "name": d["Name"], "attr": d["Specification"], "unit": d["Unit"],
"price": d["NoTaxPrice"], "tax": d["TaxRate"], "price_tax": d["TaxPrice"],
"proj": d["proj"], "bunit": d["bunit"], "period": ym(nearest(d["p1"], d["p2"], bf)),
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
"period_m": nearest(d["p1"], d["p2"], bf),
"dist": dist(d["p1"], d["p2"], bf, bt),
"sim": (1.0 if d["tier"] in ("精确", "字集") else
round(d["_sim"], 2) if "_sim" in d else
round(jaccard(norm_match(row["Name"]), norm_match(d["Name"])), 2)),
"src": "工程", "file": d.get("fname") or "",
"file_url": ("/api/admin/inq/file/%d" % d["fid"]) if d.get("fid") else "",
})
# ---- 信息价 / 市场价 ----
pk = [s for s in ("info", "market") if s in srcs]
# 价格批次没有「单价类型/建设单位」(FileKind/BulidUnit 恒 NULL),kinds/units 一律不传;
# 单位筛选走 orgs(发布单位),价格范围同样对 p.NoTaxPrice 生效。
# ⚠️ **这里永远不加 lme_list_where**(主人 2026-10-09 明示"永远不能屏蔽信息价/市场价的
# 任何单位")—— 刊物里的台班单价等是正常价格行;搜索对象=项目工料机(过滤后)+价格全量。
wp, argp = _filters([], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs, projs=projs)
wpp, app = _price_range("p.NoTaxPrice", pmin, pmax)
wp = wp + " AND " + wpp; argp = argp + app
if pk:
sqlp = """SELECT p.Name, p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Note note,
bt.Name proj, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
bt.kind kind, a.original_name att, a.sha256 attsha
FROM prices p JOIN batches bt ON bt.id=p.batch_id
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
WHERE p.x_hash_exact=? AND bt.kind IN (%s) AND %%s LIMIT ?""" % ",".join("'%s'" % k for k in pk) % wp
seen_p = set()
for x in c.execute(sqlp, [row["x_hash_exact"]] + argp + [limit]):
d = dict(x)
seen_p.add((d["Name"], d["Specification"], d["Unit"]))
res.append({
"tier": "精确", "name": d["Name"], "attr": d["Specification"], "unit": d["Unit"],
"price": d["NoTaxPrice"], "tax": d["TaxRate"], "price_tax": d["TaxPrice"],
"proj": d["proj"], "period": ym(nearest(d["p1"], d["p2"], bf)),
"period_m": nearest(d["p1"], d["p2"], bf),
"dist": dist(d["p1"], d["p2"], bf, bt),
"sim": 1.0,
"src": "信息价" if d["kind"] == "info" else "市场价",
"note": d["note"],
"file": d["att"] or "", "file_sha": d["attsha"] or "",
"file_url": ("/api/admin/file/%s" % d["attsha"]) if d["attsha"] else "",
"src_hash": d.get("src") or "",
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
})
# 次精确档:名称+单位一致、规格不同(2026-10-08,与工程工料机同口径)
if len(res) < limit:
sqlps = """SELECT p.Name, p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Note note,
bt.Name proj, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
bt.kind kind, a.original_name att, a.sha256 attsha
FROM prices p JOIN batches bt ON bt.id=p.batch_id
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
WHERE p.x_hash_semi=? AND bt.kind IN (%s) AND %%s LIMIT ?""" % ",".join("'%s'" % k for k in pk) % wp
for x in c.execute(sqlps, [row["x_hash_semi"]] + argp + [limit]):
d = dict(x)
key = (d["Name"], d["Specification"], d["Unit"])
if key in seen_p:
continue
seen_p.add(key)
res.append({
"tier": "次精确", "name": d["Name"], "attr": d["Specification"], "unit": d["Unit"],
"price": d["NoTaxPrice"], "tax": d["TaxRate"], "price_tax": d["TaxPrice"],
"proj": d["proj"], "period": ym(nearest(d["p1"], d["p2"], bf)),
"period_m": nearest(d["p1"], d["p2"], bf),
"dist": dist(d["p1"], d["p2"], bf, bt),
"sim": 1.0,
"src": "信息价" if d["kind"] == "info" else "市场价",
"note": d["note"],
"file": d["att"] or "", "file_sha": d["attsha"] or "",
"file_url": ("/api/admin/file/%s" % d["attsha"]) if d["attsha"] else "",
"src_hash": d.get("src") or "",
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
})
# 模糊档:名称前 6 字捞候选 → 相似度 ≥0.60 且单位一致(信息价/市场价此前只走精确,几乎命中不了)
q = norm_match(row["Name"])[:6]
if q:
sqlf = """SELECT p.Name, p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Note note,
bt.Name proj, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
bt.kind kind, a.original_name att, a.sha256 attsha
FROM prices p JOIN batches bt ON bt.id=p.batch_id
LEFT JOIN attachments a ON a.sha256=bt.x_attach_sha
WHERE bt.kind IN (%s) AND %%s AND p.x_name_norm LIKE ? LIMIT 300""" % ",".join("'%s'" % k for k in pk) % wp
for x in c.execute(sqlf, argp + ["%" + q + "%"]):
if norm(x["Unit"]) != norm(row["Unit"]):
continue
key = (x["Name"], x["Specification"], x["Unit"])
if key in seen_p:
continue
sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]),
norm_attr(row["Specification"]), norm_attr(x["Specification"]))
if sim < SIM_MIN:
continue
seen_p.add(key)
res.append({
"tier": "模糊", "name": x["Name"], "attr": x["Specification"], "unit": x["Unit"],
"price": x["NoTaxPrice"], "tax": x["TaxRate"], "price_tax": x["TaxPrice"],
"proj": x["proj"], "period": ym(nearest(x["p1"], x["p2"], bf)),
"period_m": nearest(x["p1"], x["p2"], bf),
"dist": dist(x["p1"], x["p2"], bf, bt),
"sim": round(sim, 2),
"src": "信息价" if x["kind"] == "info" else "市场价",
"note": x["note"],
"file": x["att"] or "", "file_sha": x["attsha"] or "",
"file_url": ("/api/admin/file/%s" % x["attsha"]) if x["attsha"] else "",
"src_hash": x["src"] or "",
"fkind": x["FileKind"], "region": _region3(x["x_province"], x["x_city"], x["x_district"]),
})
if len(res) >= limit:
break
res = [r for r in res if _in_period(r, pfrom, pto)]
# 附件筛选(2026-10-08 主人定):有=只留带附件的;无=只留没附件的;全部=不筛
if att == "yes":
res = [r for r in res if r.get("file")]
elif att == "no":
res = [r for r in res if not r.get("file")]
res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目)
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]]))
return res[:limit]