# -*- 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]