feat(costreview): 询价附件支持清单绑定并新增项目筛选、动态明细标签与行结构统一

This commit is contained in:
lianjianwei2024
2026-10-21 20:21:51 +08:00
parent 8235085f26
commit 6f36b2f494
20 changed files with 1521 additions and 332 deletions

View File

@@ -646,7 +646,8 @@ def api_inq_list(con, bid):
if not ok:
return {"ok": False, "msg": msg}
rows = con.execute("""SELECT f.id, f.original_name, f.size, f.ext, f.uploaded_at,
(SELECT COUNT(*) FROM lme_attach a WHERE a.file_id=f.id) AS n
(SELECT COUNT(*) FROM lme_attach a WHERE a.file_id=f.id)
+ (SELECT COUNT(*) FROM bill_attach a WHERE a.file_id=f.id) AS n
FROM inquiry_files f WHERE f.batch_id=? ORDER BY f.id""", (bid,)).fetchall()
total = con.execute("SELECT COUNT(*) FROM lme_attach WHERE batch_id=?", (bid,)).fetchone()[0]
return {"ok": True, "total_bound": total,
@@ -687,64 +688,114 @@ def api_inq_upload(con, bid, body):
def api_inq_bind(con, bid, body):
"""把选中的工料机绑到某个附件。
"""把选中的工料机/清单绑到某个附件(决策 152:清单也能绑,同 lme_attach 口径)。
★ 允许改绑:lme_id 是主键,INSERT OR REPLACE 冲突即覆盖 —— 覆盖即改绑,
★ 允许改绑:lme_id/bill_id 是主键,INSERT OR REPLACE 冲突即覆盖 —— 覆盖即改绑,
不需要先解绑。返回里带着「从哪个附件改过来的、几条」,前端据此做二次确认文案。
body: {file_id, lme_ids?: [...], bill_ids?: [...]} —— 两类至少给一类。
"""
ok, msg = _inq_guard(con, bid)
if not ok:
return {"ok": False, "msg": msg}
fid = int(body.get("file_id") or 0)
ids = [int(x) for x in (body.get("lme_ids") or [])]
lme_ids = [int(x) for x in (body.get("lme_ids") or [])]
bill_ids = [int(x) for x in (body.get("bill_ids") or [])]
if not fid:
return {"ok": False, "msg": "请先在左边选中一个附件"}
if not ids:
return {"ok": False, "msg": "还没有勾选工料机"}
if not lme_ids and not bill_ids:
return {"ok": False, "msg": "还没有勾选工料机/清单"}
row = con.execute("SELECT original_name FROM inquiry_files WHERE id=? AND batch_id=?",
(fid, bid)).fetchone()
if not row:
return {"ok": False, "msg": "附件不存在(可能已被删除)"}
cur = con.cursor()
# 只接受确实属于本项目的工料机(防越权:传别项目的 lme_id 也绑不上)
q = "SELECT id FROM lmes WHERE batch_id=? AND id IN (%s)" % ",".join("?" * len(ids))
valid = [r[0] for r in cur.execute(q, [bid] + ids)]
if not valid:
return {"ok": False, "msg": "勾选的工料机不属于这个项目"}
# 改绑统计:这些行原本绑在哪些附件上
moved = {}
for lme_id, old_name in cur.execute(
"""SELECT a.lme_id, f.original_name FROM lme_attach a
JOIN inquiry_files f ON f.id=a.file_id
WHERE a.lme_id IN (%s)""" % ",".join("?" * len(valid)), valid):
moved[old_name] = moved.get(old_name, 0) + 1
for lme_id in valid:
cur.execute("INSERT OR REPLACE INTO lme_attach(lme_id, batch_id, file_id) VALUES(?,?,?)",
(lme_id, bid, fid))
con.commit()
n = len(valid)
n = 0
hint = ""
if moved:
hint = "(其中 %s)" % "、".join(
"%d 条从《%s》改绑过来" % (c, (k or "").strip()[:24]) for k, c in moved.items())
return {"ok": True, "n": n, "moved": moved,
"msg": "已把 %d 条工料机绑定到《%s》%s" % (n, (row[0] or "")[:40], hint)}
if lme_ids:
# 只接受确实属于本项目的工料机(防越权:传别项目的 lme_id 也绑不上)
q = "SELECT id FROM lmes WHERE batch_id=? AND id IN (%s)" % ",".join("?" * len(lme_ids))
valid = [r[0] for r in cur.execute(q, [bid] + lme_ids)]
if not valid:
return {"ok": False, "msg": "勾选的工料机不属于这个项目"}
# 改绑统计:这些行原本绑在哪些附件上
moved = {}
for lme_id, old_name in cur.execute(
"""SELECT a.lme_id, f.original_name FROM lme_attach a
JOIN inquiry_files f ON f.id=a.file_id
WHERE a.lme_id IN (%s)""" % ",".join("?" * len(valid)), valid):
moved[old_name] = moved.get(old_name, 0) + 1
for lme_id in valid:
cur.execute("INSERT OR REPLACE INTO lme_attach(lme_id, batch_id, file_id) VALUES(?,?,?)",
(lme_id, bid, fid))
n += len(valid)
if moved:
hint = "(其中 %s)" % "、".join(
"%d 条从《%s》改绑过来" % (c, (k or "").strip()[:24]) for k, c in moved.items())
if bill_ids:
q = "SELECT id FROM bills WHERE batch_id=? AND id IN (%s)" % ",".join("?" * len(bill_ids))
valid = [r[0] for r in cur.execute(q, [bid] + bill_ids)]
if not valid and not lme_ids:
return {"ok": False, "msg": "勾选的清单不属于这个项目"}
moved = {}
for bill_id, old_name in cur.execute(
"""SELECT a.bill_id, f.original_name FROM bill_attach a
JOIN inquiry_files f ON f.id=a.file_id
WHERE a.bill_id IN (%s)""" % ",".join("?" * len(valid)), valid):
moved[old_name] = moved.get(old_name, 0) + 1
for bill_id in valid:
cur.execute("INSERT OR REPLACE INTO bill_attach(bill_id, batch_id, file_id) VALUES(?,?,?)",
(bill_id, bid, fid))
n += len(valid)
if moved:
hint += ("%s%s" % (";" if hint else "", "、".join(
"%d 条清单从《%s》改绑过来" % (c, (k or "").strip()[:24]) for k, c in moved.items())))
con.commit()
what = "工料机" if lme_ids else "清单"
return {"ok": True, "n": n, "msg": "已把 %d 条%s绑定到《%s》%s" % (n, what, (row[0] or "")[:40], hint)}
def api_inq_unbind(con, bid, body):
"""解绑:把选中的工料机从附件上摘下来(附件本身保留)"""
"""解绑:把选中的工料机/清单从附件上摘下来(附件本身保留)"""
ok, msg = _inq_guard(con, bid)
if not ok:
return {"ok": False, "msg": msg}
ids = [int(x) for x in (body.get("lme_ids") or [])]
if not ids:
return {"ok": False, "msg": "还没有勾选工料机"}
lme_ids = [int(x) for x in (body.get("lme_ids") or [])]
bill_ids = [int(x) for x in (body.get("bill_ids") or [])]
if not lme_ids and not bill_ids:
return {"ok": False, "msg": "还没有勾选工料机/清单"}
cur = con.cursor()
cur.execute("DELETE FROM lme_attach WHERE batch_id=? AND lme_id IN (%s)"
% ",".join("?" * len(ids)), [bid] + ids)
n = cur.rowcount
n = 0
if lme_ids:
cur.execute("DELETE FROM lme_attach WHERE batch_id=? AND lme_id IN (%s)"
% ",".join("?" * len(lme_ids)), [bid] + lme_ids)
n += cur.rowcount
if bill_ids:
cur.execute("DELETE FROM bill_attach WHERE batch_id=? AND bill_id IN (%s)"
% ",".join("?" * len(bill_ids)), [bid] + bill_ids)
n += cur.rowcount
con.commit()
return {"ok": True, "n": n, "msg": "已解绑 %d 条工料机" % n}
return {"ok": True, "n": n, "msg": "已解绑 %d 条" % n}
def api_inq_bills(con, bid):
"""该项目的全部清单 + 当前绑定状态(决策 152 类似清单页签用)。
字段与后台「类似清单」结果行一致:编码/名称/项目特征/单位/工程量/单价/合价;
不做相似过滤 —— 这里是**本批次自己的全部清单**,勾选绑附件用。"""
ok, msg = _inq_guard(con, bid)
if not ok:
return {"ok": False, "msg": msg}
rows = con.execute("""SELECT b.id, b.Number, b.Name, b.Attr, b.Unit, b.Quantity, b.Price, b.Total,
a.file_id, f.original_name
FROM bills b
LEFT JOIN bill_attach a ON a.bill_id=b.id
LEFT JOIN inquiry_files f ON f.id=a.file_id
WHERE b.batch_id=? ORDER BY b.id""", (bid,)).fetchall()
return {"ok": True, "rows": [
{"id": r[0], "code": r[1] or "", "name": r[2] or "", "attr": r[3] or "",
"unit": r[4] or "", "qty": r[5], "price": r[6], "total": r[7],
"file_id": r[8], "file_name": r[9] or ""}
for r in rows]}
def api_inq_del(con, bid, body):
@@ -759,7 +810,9 @@ def api_inq_del(con, bid, body):
return {"ok": False, "msg": "附件不存在"}
cur = con.cursor()
n = cur.execute("SELECT COUNT(*) FROM lme_attach WHERE file_id=?", (fid,)).fetchone()[0]
n += cur.execute("SELECT COUNT(*) FROM bill_attach WHERE file_id=?", (fid,)).fetchone()[0]
cur.execute("DELETE FROM lme_attach WHERE file_id=?", (fid,))
cur.execute("DELETE FROM bill_attach WHERE file_id=?", (fid,))
cur.execute("DELETE FROM inquiry_files WHERE id=?", (fid,))
con.commit()
# 同 sha 的别处还在用就不删文件(与价格原件同一套规矩)
@@ -1829,18 +1882,22 @@ def _raw_proj(con, T, oid, tab):
# sub = 带子级组成的编码集(台班/配合比),前端据此挂 title 提示。
try:
_hide = " AND COALESCE(x_merged_hide,0)=0" if T.get("lmemerge") else ""
rows = con.execute("""SELECT id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp
# 决策 147(2026-10-21 主人定):项目级卡与「项目工料机」同码同形 —— 返回 _lme_rows 同形
# 11 列(id 在首位、备注位 10),前端 renderLme 唯一渲染;不再 rows/ids 分离。
# 数据集差异保留:此处**不过** LME_LIST_WHERE(全量含台班/配合比),合并隐藏两处同滤。
rows = con.execute("""SELECT id, code, name, spec, unit, qty, ntp, taxrate, taxp,
kind, %(rm)s AS remark
FROM %(lp)s WHERE %(idc)s=?%(hide)s ORDER BY id"""
% {"lp": T["lme_proj"], "idc": T["idcol"], "hide": _hide}, (oid,)).fetchall()
% {"lp": T["lme_proj"], "idc": T["idcol"], "hide": _hide,
"rm": T.get("lme_remark", "NULL")}, (oid,)).fetchall()
except Exception:
rows = [] # 老库还没建表/没回填:退回旧口径
if rows:
return {"ok": True, "rows": [list(x)[1:] for x in rows],
"ids": [x[0] for x in rows], "sub": _lme_sub_codes(con, T, oid)}
return {"ok": True, "rows": [list(x) for x in rows], "sub": _lme_sub_codes(con, T, oid)}
# 老库回退支:lmes 可能没有 TaxRate 列 —— 仿 _norm_res 的 PRAGMA 探测,缺列恒补 None。
# 9 列行形与主路一致:6=除税 7=税率 8=含税(TaxRate 插在 TaxPrice 之前)。
# 决策 147:回退支同样 11 列(id/备注补 NULL),行形与主路一致。
has_tax = any(x[1] == "TaxRate" for x in con.execute("PRAGMA table_info(%s)" % T["lmes"]))
rows = con.execute("""SELECT Number, Name, Specification, Unit, Kind, Quantity, NoTaxPrice, %(txr)s TaxPrice
rows = con.execute("""SELECT NULL, Number, Name, Specification, Unit, Quantity, NoTaxPrice, %(txr)s TaxPrice, Kind, NULL
FROM %(lm)s WHERE %(idc)s=? AND NoTaxPrice IS NOT NULL
ORDER BY Quantity DESC LIMIT 800"""
% {"lm": T["lmes"], "idc": T["idcol"],
@@ -3291,17 +3348,41 @@ def api_bill_adopt(sc, hc, body):
sid = int(body.get("session_id", 0) or 0)
bid = int(body.get("bill_id", 0) or 0)
src_id = int(body.get("src_bill_id", 0) or 0)
src_self = int(body.get("src_self_bill_id", 0) or 0) # 决策 158:来源=本会话清单(范围=是)
sb = sc.execute("SELECT id, session_id, uw_id, x_new, x_tdel FROM s_bills WHERE id=? AND session_id=?",
(bid, sid)).fetchone()
if not sb:
return {"ok": False, "msg": "清单不存在(可能已被删除,请刷新)"}
if sb["x_tdel"]:
return {"ok": False, "msg": "临时删除状态不可以采纳(规格 9.2)——先取消临时删除"}
bb = hc.execute("SELECT id, Number, Name, Attr, Unit, Price, Quantity FROM bills WHERE id=?", (src_id,)).fetchone()
if not bb:
return {"ok": False, "msg": "入库项目清单不存在(批次可能已删除)"}
bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()
if src_self:
if src_self == bid:
return {"ok": False, "msg": "不能采纳清单自己"}
bb = sc.execute("SELECT id, Number, Name, Attr, Unit, Price, Quantity FROM s_bills WHERE id=? AND session_id=?",
(src_self, sid)).fetchone()
if not bb:
return {"ok": False, "msg": "本工程来源清单不存在(可能已被删除,请刷新)"}
bnorms = sc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total,
NULL AS x_qty_coef, x_adjust, qty_expr
FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""",
(src_self,)).fetchall()
else:
bb = hc.execute("SELECT id, Number, Name, Attr, Unit, Price, Quantity FROM bills WHERE id=?", (src_id,)).fetchone()
if not bb:
return {"ok": False, "msg": "入库项目清单不存在(批次可能已删除)"}
bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()
def _norm_expr(nn):
# 批次来源:GCL×系数公式现算(规格 19);会话来源:qty_expr 原样带(公式本就按 GCL 走,
# 换到目标清单后随目标工程量求值,语义同款)
return nn["qty_expr"] if src_self else _gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"])
def _norm_res(nn_id):
if src_self:
return sc.execute("SELECT res_code, qty, express FROM s_norm_res WHERE norm_id=? ORDER BY id", (nn_id,))
return hc.execute("SELECT res_code, qty, express FROM norm_res WHERE norm_id=? ORDER BY id", (nn_id,))
is_new = bool(sb["x_new"])
# 规格 19(2026-10-17 主人定·采纳逻辑变化):采纳定额工程量默认公式 = **GCL×系数**,
# 系数 = 历史定额量 ÷ 历史清单量(例:历史清单量 500、定额量 300 → GCL*0.6000)——
@@ -3320,11 +3401,10 @@ def api_bill_adopt(sc, hc, body):
cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_adopt, x_src_norm_id, qty_expr, x_adjust)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?)""",
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"], nn["id"],
_gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"]),
nn["x_adjust"]))
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"],
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"]))
adopted_norm_ids.append(cur.lastrowid)
for rr in hc.execute("SELECT res_code, qty, express FROM norm_res WHERE norm_id=? ORDER BY id", (nn["id"],)):
for rr in _norm_res(nn["id"]):
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
(cur.lastrowid, rr["res_code"], rr["qty"], rr["express"]))
else:
@@ -3337,18 +3417,21 @@ def api_bill_adopt(sc, hc, body):
cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_adopt, x_src_norm_id, qty_expr, x_adjust)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?)""",
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"], nn["id"],
_gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"]),
nn["x_adjust"]))
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"],
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"]))
adopted_norm_ids.append(cur.lastrowid)
for rr in hc.execute("SELECT res_code, qty, express FROM norm_res WHERE norm_id=? ORDER BY id", (nn["id"],)):
for rr in _norm_res(nn["id"]):
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
(cur.lastrowid, rr["res_code"], rr["qty"], rr["express"]))
bqty = sc.execute("SELECT Quantity FROM s_bills WHERE id=?", (bid,)).fetchone()["Quantity"]
btotal = round((float(bqty) if bqty is not None else 0.0) * (float(new_price) if new_price is not None else 0.0), 2)
sc.execute("UPDATE s_bills SET Price=?, Total=?, x_adopt=1 WHERE id=?", (new_price, btotal, bid))
# 决策 108:消耗量随名称/规格/单位匹配结果改码(逐行读现值再映射,防 A→B→C 链式误改)
n_sum, code_map = _adopt_summary_rows(sc, hc, sid, sb["uw_id"], src_id)
# 会话来源跳过——来源消耗量的编码本就是本地码,无需重配(决策 158)
if src_self:
n_sum, code_map = 0, {}
else:
n_sum, code_map = _adopt_summary_rows(sc, hc, sid, sb["uw_id"], src_id)
n_recode = 0
for nid in adopted_norm_ids:
for rr in sc.execute("SELECT id, res_code FROM s_norm_res WHERE norm_id=?", (nid,)).fetchall():
@@ -3628,10 +3711,14 @@ def api_lme_merge(sc, body):
rid = int(r.get("id", 0) or 0)
except (TypeError, ValueError):
continue
_ntp = _num_or_none(r.get("ntp"))
_rate = _num_or_none(r.get("taxrate"))
_taxp = _num_or_none(r.get("taxp"))
if _ntp is not None and _rate is not None: # 决策 146:等式恒成立(除税方向复核,同 api_lme_price)
_taxp = round(_ntp * (1 + _rate / 100.0) + 1e-9, 2)
sc.execute("""UPDATE s_lme_proj SET code=?, ntp=?, taxrate=?, taxp=?
WHERE session_id=? AND id=? AND COALESCE(x_merged_hide,0)=0""",
(r.get("code"), _num_or_none(r.get("ntp")), _num_or_none(r.get("taxrate")),
_num_or_none(r.get("taxp")), sid, rid))
(r.get("code"), _ntp, _rate, _taxp, sid, rid))
kept += 1
row = sc.execute("SELECT code FROM s_lme_proj WHERE id=?", (rid,)).fetchone()
if row and not keep_code:
@@ -3987,14 +4074,15 @@ def api_search(body):
pmin=_num_or_none(body.get("pmin")),
pmax=_num_or_none(body.get("pmax")),
att=body.get("att") or "all",
kinds=body.get("file_kinds") or [])
kinds=body.get("file_kinds") or [],
projs=body.get("projs") or [])
else:
res = match.match_bill(hist, row, base,
body.get("file_kinds") or [], body.get("bulid_units") or [],
body.get("classes") or [], limit, srcs, pf, pt,
None if scope_self else self_name,
None if scope_self else self_src,
area)
area, projs=body.get("projs") or [])
# 规格 20:本组其他清单的批次记录(bill_id 集合)——组价不一致对比按它过滤
allowed = None
if scope_self and members is not None:
@@ -4021,6 +4109,23 @@ def api_search(body):
# (第 N 组 3 条 → 只显示另外 2 条);别的项目/别的历史记录不展示。
# 工具栏独立检索(/api/hist/search)不受限。被点清单自己的记录亦不在本组集合内。
res = [r for r in res if r.get("bill_id") in allowed]
if typ == "bill" and res:
# 决策 152:清单绑定的询价附件 → 工作台历史对比框可下载(file/file_sha/file_url 同工料机行)
c2 = conn()
try:
m = {}
for bid_, fid_, nm_, sha_ in c2.execute(
"""SELECT a.bill_id, f.id, f.original_name, f.sha256 FROM bill_attach a
JOIN inquiry_files f ON f.id=a.file_id WHERE a.bill_id IN (%s)"""
% ",".join("?" * len(res)), [r.get("bill_id") for r in res]):
m[bid_] = (fid_, nm_, sha_)
finally:
c2.close()
for r in res:
hit = m.get(r.get("bill_id"))
if hit:
r["file"], r["file_sha"] = hit[1] or "", hit[2] or ""
r["file_url"] = "/api/admin/inq/file/%d" % hit[0]
return {"ok": True, "base_period": match.ym(pf) + ("~" + match.ym(pt) if pt != pf else ""),
"rows": res, "total": len(res)}
@@ -4035,6 +4140,154 @@ def _num_or_none(v):
return None
def api_self_search(body):
"""范围=是(决策 158,2026-10-21 主人定):「本项目」下拉是数据第一关——
是=数据流走 session 库(本工程自己的行,本端点);否=走批次库(/api/search、/api/hist/search,
排除自己,现行规则)。关键字「查询」路径同样跟随下拉。
type='bill':本工程其他清单(跨单位工程同名/近似;scope='self_group'=组价不一致:会话内
本组其他清单——规格 20 的组定义直读会话,不再绕批次库);type='lme':本工程自己的工料机
(s_lmes 各单位明细行)。
行结构与 /api/search 一致(renderHist/右栏/±/采纳零改动复用),差异:
· src='本工程'、proj=单位工程名(工料机行无单位归属,恒『本工程』)、period=本工程基准期次;
· 清单行带 norms=6+2 列(同 _bill_norms 形状,右栏/±/悬停直读,不走 histNorms);
· self_bill_id=会话清单 id(采纳走 /api/session/bill/adopt 的 src_self_bill_id 分支)。
档位与库内同一套(精确/次精确/字集/模糊,同 match_bill/match_lme 口径);
kw/stop 同库内口径;期次/地区/单位/价格范围等库条件对本工程无意义,不参与。"""
sid = int(body.get("session_id", 0) or 0)
typ = body.get("type", "lme")
rid = int(body.get("row_id", 0) or 0)
limit = min(int(body.get("limit", 200) or 200), 500)
sc = sess.connect()
try:
s = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
if not s:
return {"ok": False, "msg": "会话不存在"}
_k = s.keys()
pf = (s["period_from"] if "period_from" in _k else None) or s["base_period_m"] or 0
pt = (s["period_to"] if "period_to" in _k else None) or pf
period = match.ym(pf) + ("~" + match.ym(pt) if pt != pf else "")
region = match._region3(s["x_province"] if "x_province" in _k else None,
s["x_city"] if "x_city" in _k else None,
s["x_district"] if "x_district" in _k else None)
bunit = (s["bulid_unit"] if "bulid_unit" in _k else None) or ""
sw = _setting_get("global", "match_stopwords")
try:
match.set_stopwords(json.loads(sw)) if sw else match.set_stopwords([])
except Exception:
match.set_stopwords([])
stops = match.stop_words(body.get("stop"))
kw = match._kw_fold(body.get("kw") or "")
def _pass(txts):
hay = match._kw_fold(" ".join(str(t or "") for t in txts))
if kw and not all(t in hay for t in re.split(r"\s+", kw) if t):
return False
if stops and any(match._kw_fold(w) in hay for w in stops):
return False
return True
rows = []
if typ == "bill":
row = sc.execute("SELECT * FROM s_bills WHERE id=? AND session_id=?", (rid, sid)).fetchone() if rid else None
if rid and not row:
return {"ok": False, "msg": "找不到这一行"}
uw_names = {u["id"]: (u["Name"] or "") for u in
sc.execute("SELECT id, Name FROM s_unit_works WHERE session_id=?", (sid,))}
grp = bool(row) and (body.get("scope") == "self_group") and row["x_name_norm"] is not None
if row is None:
cands = sc.execute("SELECT * FROM s_bills WHERE session_id=? ORDER BY id", (sid,)).fetchall()
elif grp:
cands = sc.execute("""SELECT * FROM s_bills WHERE session_id=? AND id<>?
AND x_name_norm IS ? AND x_attr_norm IS ? ORDER BY id""",
(sid, rid, row["x_name_norm"], row["x_attr_norm"])).fetchall()
else:
cands = sc.execute("SELECT * FROM s_bills WHERE session_id=? AND id<>? ORDER BY id",
(sid, rid)).fetchall()
qn = match.norm_match(row["Name"]) if row is not None else None
qattr = match.norm_match(row["Attr"] or "") if row is not None else None
setkey = match.bill_setkey(row["Name"], row["Unit"]) if row is not None else None
pre = match.norm(row["Name"])[:6] if row is not None else None
for b in cands:
if row is None:
rows.append({
"tier": "检索", "name": b["Name"], "attr": b["Attr"], "unit": b["Unit"],
"price": b["Price"], "period": period, "period_m": pf, "dist": 0,
"sim": None, "src": "本工程", "proj": uw_names.get(b["uw_id"]) or "本工程",
"bunit": bunit, "region": region, "self_bill_id": b["id"],
"norms": [[n["Number"], n["Name"], n["Unit"], n["Quantity"], n["Price"], n["Total"], 0, 0]
for n in sc.execute("""SELECT Number, Name, Unit, Quantity, Price, Total, x_tdel FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""", (b["id"],)).fetchall()],
"file": "", "file_url": ""})
continue
tier, sim = None, None
j = match.jaccard(qn, match.norm_match(b["Name"]))
if b["x_hash_exact"] and b["x_hash_exact"] == row["x_hash_exact"]:
tier, sim = "精确", 1.0
elif b["x_hash_semi"] and b["x_hash_semi"] == row["x_hash_semi"] and j >= match.SEMI_NAME_MIN:
tier, sim = "次精确", 1.0
elif match.bill_setkey(b["Name"], b["Unit"]) == setkey:
tier, sim = "字集", 1.0
elif (not grp and pre and match.norm(b["Name"]).startswith(pre)
and match.norm(b["Unit"]) == match.norm(row["Unit"])):
simv = match.sim_weighted(qn, match.norm_match(b["Name"]), qattr,
match.norm_match(b["Attr"] or ""))
if simv >= match.SIM_MIN:
tier, sim = "模糊", round(simv, 2)
if tier is None:
continue
norms = [[n["Number"], n["Name"], n["Unit"], n["Quantity"], n["Price"], n["Total"], 0, 0]
for n in sc.execute("""SELECT Number, Name, Unit, Quantity, Price, Total, x_tdel
FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0)
ORDER BY id""", (b["id"],)).fetchall()]
rows.append({
"tier": tier, "name": b["Name"], "attr": b["Attr"], "unit": b["Unit"],
"price": b["Price"], "period": period, "period_m": pf, "dist": 0,
"sim": sim, "src": "本工程", "proj": uw_names.get(b["uw_id"]) or "本工程",
"bunit": bunit, "region": region, "self_bill_id": b["id"], "norms": norms,
"file": "", "file_url": ""})
else:
row = sc.execute("SELECT * FROM s_lme_proj WHERE id=? AND session_id=?", (rid, sid)).fetchone() if rid else None
if rid and not row:
return {"ok": False, "msg": "找不到这一行"}
h_e = job.md5(row["name"], row["spec"], row["unit"]) if row is not None else None
h_s = job.md5(row["name"], row["unit"]) if row is not None else None
setk = match.lme_setkey(row["name"], row["spec"], row["unit"]) if row is not None else None
qn = match.norm_match(row["name"]) if row is not None else None
pre = match.norm(row["name"])[:6] if row is not None else None
for l in sc.execute("SELECT * FROM s_lmes WHERE session_id=? ORDER BY id", (sid,)).fetchall():
if row is None:
rows.append({
"tier": "检索", "name": l["Name"], "attr": "", "spec": l["Specification"],
"unit": l["Unit"], "price": l["NoTaxPrice"], "tax": l["TaxRate"],
"price_tax": l["TaxPrice"], "note": "", "period": period, "period_m": pf,
"dist": 0, "sim": None, "src": "本工程", "proj": "本工程", "bunit": bunit,
"region": region, "file": "", "file_url": ""})
continue
tier, sim = None, None
j = match.jaccard(qn, match.norm_match(l["Name"]))
if l["x_hash_exact"] and l["x_hash_exact"] == h_e:
tier, sim = "精确", 1.0
elif l["x_hash_semi"] and l["x_hash_semi"] == h_s:
tier, sim = "次精确", 1.0
elif match.lme_setkey(l["Name"], l["Specification"], l["Unit"]) == setk:
tier, sim = "字集", 1.0
elif pre and match.norm(l["Name"]).startswith(pre) and match.norm(l["Unit"]) == match.norm(row["unit"]):
if j >= match.SIM_MIN:
tier, sim = "模糊", round(j, 2)
if tier is None:
continue
rows.append({
"tier": tier, "name": l["Name"], "attr": "", "spec": l["Specification"],
"unit": l["Unit"], "price": l["NoTaxPrice"], "tax": l["TaxRate"],
"price_tax": l["TaxPrice"], "note": "", "period": period, "period_m": pf,
"dist": 0, "sim": sim, "src": "本工程", "proj": "本工程", "bunit": bunit,
"region": region, "file": "", "file_url": ""})
rows = [r for r in rows
if _pass((r.get("name"), r.get("attr"), r.get("spec"), r.get("unit")))]
return {"ok": True, "base_period": period, "rows": rows[:limit], "total": len(rows)}
finally:
sc.close()
def api_hist_search(body):
"""独立检索(2026-10-08 主人定 B 方案):条件+关键词 跨全部入库项目
target='bill'(默认)查**清单库**;target='lme'(工料机标签专用,2026-10-08 主人定)
@@ -4077,6 +4330,7 @@ def api_hist_search(body):
limit=min(int(body.get("limit", 200)), 500),
self_name=self_name, self_src=self_src,
page=int(body.get("page", 1) or 1),
projs=body.get("projs") or [],
stop=match.stop_words(body.get("stop")))
else:
res = match.hist_search(hist,
@@ -4088,6 +4342,7 @@ def api_hist_search(body):
min(int(body.get("limit", 200)), 500),
self_name=self_name, self_src=self_src,
page=int(body.get("page", 1) or 1),
projs=body.get("projs") or [],
stop=match.stop_words(body.get("stop")))
finally:
hist.close()
@@ -4125,6 +4380,7 @@ def api_delete_batch(con, bid):
con.execute("DELETE FROM lme_proj WHERE batch_id=?", (bid,))
con.execute("DELETE FROM lme_uw WHERE batch_id=?", (bid,))
con.execute("DELETE FROM lme_attach WHERE batch_id=?", (bid,))
con.execute("DELETE FROM bill_attach WHERE batch_id=?", (bid,))
con.execute("DELETE FROM inquiry_files WHERE batch_id=?", (bid,))
con.execute("DELETE FROM unit_works WHERE batch_id=?", (bid,))
con.execute("DELETE FROM sections WHERE batch_id=?", (bid,))
@@ -4213,6 +4469,7 @@ def api_clear_mock(con):
con.execute("DELETE FROM lme_proj WHERE batch_id IN (%s)" % ph, part)
con.execute("DELETE FROM lme_uw WHERE batch_id IN (%s)" % ph, part)
con.execute("DELETE FROM lme_attach WHERE batch_id IN (%s)" % ph, part)
con.execute("DELETE FROM bill_attach WHERE batch_id IN (%s)" % ph, part)
con.execute("DELETE FROM inquiry_files WHERE batch_id IN (%s)" % ph, part)
con.execute("DELETE FROM unit_works WHERE batch_id IN (%s)" % ph, part)
con.execute("DELETE FROM sections WHERE batch_id IN (%s)" % ph, part)
@@ -5736,6 +5993,7 @@ def api_filters():
# 2026-10-07 主人定:列表筛选补 单价类型(已有 file_kind)/建设单位/总价区间/发布单位
"bu_rows": _distinct_rows("BulidUnit", "kind='project'"), # 历史项目里出现过的建设单位
"pub_rows": _distinct_rows("x_publisher", "kind<>'project'"), # 信息价/市场价里出现过的发布单位
"proj_rows": _distinct_rows("Name", "kind='project'"), # 决策 141:项目名称框选项池(历史项目名)
}
@@ -6123,6 +6381,13 @@ class Handler(SimpleHTTPRequestHandler):
return self._json(api_inq_list(c, int(m.group(1))))
finally:
c.close()
m = re.match(r"^/api/admin/batch/(\d+)/inq/bills$", p) # 决策 152:类似清单页签
if m:
c = conn()
try:
return self._json(api_inq_bills(c, int(m.group(1))))
finally:
c.close()
m = re.match(r"^/api/admin/inq/file/(\d+)$", p) # 下载
if m:
return self._inq_file(int(m.group(1)))
@@ -6221,6 +6486,8 @@ class Handler(SimpleHTTPRequestHandler):
return self._json(api_session_delete(body))
if u.path == "/api/search": # 比对:找历史相似项
return self._json(api_search(body))
if u.path == "/api/self/search": # 范围=是(决策 158):本会话内比对/检索
return self._json(api_self_search(body))
if u.path == "/api/hist/search": # 独立检索(2026-10-08 B 方案):条件+关键词 跨全部入库项目查清单
return self._json(api_hist_search(body))
if u.path == "/api/session/setting": # 工作台「分组/匹配」设置写入(会话库)