feat: 决策 237/238/239——附件页绑定/上传/筛选防闪跳就地更新+定额子行对齐+目录默认300px;组树点选就地化铺四处+取数等待占位;整项目导入模板与一把导入建手工工程;MCP 九工具(project_import/bill_adopt/match_hist/lme_adopt,ref 票据防转录)

This commit is contained in:
lianjianwei2024
2026-10-29 15:34:57 +08:00
parent 25f73f856a
commit a2a1d81440
7 changed files with 934 additions and 131 deletions

View File

@@ -6,7 +6,8 @@
(首次开启自动生成,调用必须带 Authorization: Bearer <令牌>,/api/mcp/status 可查)
- 收费挂钩:license enforce 时未激活/过期(套餐范围外且临时卡失效)→ 整个端点
403 LICENSE_REQUIRED(开关开了也断)
- 工具(2026-10-27 主人定,共 5 个,**全部只读,无任何增删改/导出**):
- 工具(2026-10-29 决策 238/239 起 9 个;①~⑤⑧ 只读,⑥⑦⑨ 写入为**主人拍板新增**,
取代 2026-10-27「只读、无任何增删改」旧口径):
① bills_query 入库项目清单:编号/名称/项目特征/单价
② lme_prices 工料机单价
③ market_info_prices 市场价/信息价数据
@@ -14,12 +15,22 @@
⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律
不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch
(价格批次原件);不支持枚举、不支持全量下载
⑥ project_import 整项目导入(写入):整项目模板 xlsx(项目目录+多对 Sheet)→ 建手工工程
⑦ bill_adopt 清单采纳(写入):走软件采纳同一条 API,整套术语表口径,可取消可追溯;
仅在用户明确要求采纳时调用
⑧ match_hist 历史价匹配 top-N:对会话一行找最像的历史价(match.py 同一管线),
行带 ref 票据供 ⑦⑨ 采纳
⑨ lme_adopt 工料机价格采纳(写入):采纳即改价(页面同一条通道),价格数字来自
⑧ 的服务端快照,不接受调用方传数字;仅在用户明确要求采纳时调用
- 零新增依赖:JSON-RPC 手写,只依赖标准库
"""
import base64
import json
import os
import re
import secrets
import time
import uuid
PROTO_VERSION = "2025-06-18"
_API = None # api_server 模块(bind 注入,避免循环导入)
@@ -217,6 +228,262 @@ def _t_recent_review_query(args):
return {"ok": True, "total": len(rows), "rows": rows}
# ---------------------------------------------------------------- 工具实现(写入,决策 238)
def _period_to_m(v):
"""'YYYY-MM' 或 'YYYY/MM' 或 月序号 → 月序号(年*12+月);非法返回 None。"""
if v is None:
return None
s = str(v).strip()
m = re.match(r"^(\d{4})[-/年](\d{1,2})", s)
if m:
return int(m.group(1)) * 12 + int(m.group(2))
try:
n = int(float(s))
return n if n > 0 else None
except ValueError:
return None
def _t_project_import(args):
"""⑥ 整项目导入(决策 238,写入):整项目模板 xlsx(项目目录+多对 Sheet,每对=1 个单位工程)
→ 建手工工程(目录树+清单一次到位)。file_b64=xlsx 内容(base64)。同名手工工程再次导入=整项目覆盖。
导入后可用 recent_review_query 查该工程(session_id),再用 bill_adopt 采纳。"""
a = _api()
name = (args.get("name") or "").strip()
if not name:
return {"ok": False, "msg": "name(工程名称)必填"}
pf = _period_to_m(args.get("period_from"))
pt = _period_to_m(args.get("period_to") or args.get("period_from"))
if pf is None or pt is None:
return {"ok": False, "msg": "period_from(YYYY-MM)必填;period_to 缺省=同 period_from"}
b64 = (args.get("file_b64") or "").strip()
if not b64:
return {"ok": False, "msg": "file_b64(整项目模板 xlsx 的 base64 内容)必填——先向用户要 Excel 或按 template 说明生成"}
import base64 as _b64
try:
raw = _b64.b64decode(b64, validate=True)
except Exception:
return {"ok": False, "msg": "file_b64 不是合法 base64"}
d = os.path.join(a.DATA_DIR, "manual_projects")
os.makedirs(d, exist_ok=True)
path = os.path.join(d, "mcp_%s.xlsx" % time.strftime("%Y%m%d_%H%M%S"))
with open(path, "wb") as f:
f.write(raw)
body = {"name": name, "period_from": pf, "period_to": pt, "path": path,
"province": (args.get("province") or "").strip(),
"city": (args.get("city") or "").strip(),
"district": (args.get("district") or "").strip(),
"bulid_unit": (args.get("bulid_unit") or "").strip()}
with a.WRITE_LOCK:
con = a.sess.connect()
try:
r = a.mimp.import_project(con, body)
con.commit()
except Exception as e:
r = {"ok": False, "msg": "导入异常:%s" % e}
finally:
con.close()
if r.get("ok"):
r["next"] = "recent_review_query(session_id=%s) 查清单;bill_adopt(session_id, bill_id, src_bill_id) 采纳" % r.get("sid")
return r
def _t_bill_adopt(args):
"""⑦ 清单采纳(决策 238,写入):把入库项目清单的定额+消耗量落到工作台会话。
bill_id=会话清单 id、src_bill_id=入库项目清单 id(都来自查询结果);走软件采纳同一条
API(术语表整套口径:新行覆盖/已有行追加、取价锚、可取消可追溯)。仅在用户明确要求
采纳时调用;每次一条,采纳后把结果如实告诉用户。"""
a = _api()
try:
sid = int(args.get("session_id") or 0)
bid = int(args.get("bill_id") or 0)
except (TypeError, ValueError):
return {"ok": False, "msg": "session_id / bill_id 都必须是整数 id"}
src = 0
snap = None
if args.get("ref"):
snap = _MATCH_CACHE.get((args.get("ref") or "").strip())
if not snap or snap.get("type") != "bill":
return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist(type=bill)重新匹配"}
try:
src = int(snap.get("bill_id") or 0)
except (TypeError, ValueError):
src = 0
if not src:
return {"ok": False, "msg": "该匹配行缺少来源清单 id,无法采纳"}
else:
try:
src = int(args.get("src_bill_id") or 0)
except (TypeError, ValueError):
return {"ok": False, "msg": "src_bill_id 必须是整数 id(或改传 ref 票据)"}
if not sid or not bid or not src:
return {"ok": False, "msg": "参数:session_id(工作台会话)+ bill_id(会话清单)+ src_bill_id(或 ref 票据)"}
with a.WRITE_LOCK: # 会话写库统一串行;采纳后分组缓存必撤(与页面路由同口径)
sc = a.sess.connect()
hc = a.conn()
try:
r = a.api_bill_adopt(sc, hc, {"session_id": sid, "bill_id": bid, "src_bill_id": src})
sc.commit()
if r.get("ok"):
try:
a._grp_cache_drop("session", sid)
except Exception:
pass
except Exception as e:
try:
sc.rollback()
except Exception:
pass
r = {"ok": False, "msg": "采纳失败:%s" % e}
finally:
sc.close()
hc.close()
return r
# ---- 决策 239(2026-10-29 主人定):历史价匹配 top-N + 工料机价格采纳 ----
# match_hist 返回行带 ref 票据:行数据快照(三价/名称/项目名)存本进程缓存,lme_adopt 只传
# ref——被采纳的数字全部由服务端快照取,智能体零转录、改不了价。缓存仅进程内,超限整体清空
#(语义=ref 失效请重新 match),不落盘、无泄漏面。
_MATCH_CACHE = {}
_MATCH_CACHE_MAX = 2000
def _match_ref(row):
if len(_MATCH_CACHE) >= _MATCH_CACHE_MAX:
_MATCH_CACHE.clear()
ref = uuid.uuid4().hex[:12]
_MATCH_CACHE[ref] = row
return ref
def _sess_row_ctx(sc, sid):
"""会话元信息 + 匹配停用词(与工作台比对路由同口径)。"""
a = _api()
s = sc.execute("SELECT name, src_name, base_period_m, period_from, period_to FROM sessions WHERE id=?",
(sid,)).fetchone()
if not s:
return None
pf = (s["period_from"] if "period_from" in s.keys() else None) or s["base_period_m"] or 0
pt = (s["period_to"] if "period_to" in s.keys() else None) or pf
sw = a._setting_get("global", "match_stopwords")
try:
a.match.set_stopwords(json.loads(sw)) if sw else a.match.set_stopwords([])
except Exception:
a.match.set_stopwords([])
return {"base": (pf, pt),
"self_name": (s["name"] or "").strip(),
"self_src": (s["src_name"] or "").split(";")[0].strip()}
def _t_match_hist(args):
"""⑧ 历史价匹配 top-N(决策 239,只读):对工作台的一行(清单或工料机)在全部入库项目/
信息价/市场价里找最像的历史价,按 档位+期次距离 排序返回 top-N。每行带 ref 票据——
bill_adopt / lme_adopt 用它采纳,不需要再传价格数字。"""
a = _api()
try:
sid = int(args.get("session_id") or 0)
rid = int(args.get("row_id") or 0)
except (TypeError, ValueError):
return {"ok": False, "msg": "session_id / row_id 必须是整数 id"}
typ = (args.get("type") or "bill").strip().lower()
if typ not in ("bill", "lme"):
return {"ok": False, "msg": "type 必须是 bill(清单)或 lme(工料机)"}
if not sid or not rid:
return {"ok": False, "msg": "参数:session_id + row_id(来自 recent_review_query 的行 id)"}
try:
limit = min(max(int(args.get("limit") or 5), 1), 20)
except (TypeError, ValueError):
limit = 5
sc = a.sess.connect()
hc = a.conn()
try:
ctx = _sess_row_ctx(sc, sid)
if ctx is None:
return {"ok": False, "msg": "会话不存在(%d)" % sid}
if typ == "lme":
row = sc.execute("SELECT * FROM s_lmes WHERE id=? AND session_id=?", (rid, sid)).fetchone()
if not row:
return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"}
res = a.match.match_lme(hc, row, ctx["base"], limit=limit,
self_name=ctx["self_name"], self_src=ctx["self_src"])
else:
row = sc.execute("SELECT * FROM s_bills WHERE id=? AND session_id=?", (rid, sid)).fetchone()
if not row:
return {"ok": False, "msg": "清单行不存在(可能已被删除,请刷新)"}
res = a.match.match_bill(hc, row, ctx["base"], [], [], [], limit,
self_name=ctx["self_name"], self_src=ctx["self_src"])
finally:
sc.close()
hc.close()
out = []
for r in res:
ref = _match_ref({"type": typ, **{k: r.get(k) for k in
("name", "attr", "spec", "unit", "price", "tax", "price_tax", "proj", "src", "src_id", "bill_id")}})
out.append({"ref": ref, "tier": r.get("tier"), "src": r.get("src"),
"name": r.get("name"), "spec": r.get("spec") or r.get("attr"),
"unit": r.get("unit"), "price": r.get("price"), "tax": r.get("tax"),
"price_tax": r.get("price_tax"), "proj": r.get("proj"),
"period": r.get("period"), "sim": r.get("sim")})
return {"ok": True, "total": len(out),
"hint": "挑最合适的一行,把它的 ref 传给 %s 采纳" % ("lme_adopt" if typ == "lme" else "bill_adopt"),
"rows": out}
def _t_lme_adopt(args):
"""⑨ 工料机价格采纳(决策 239,写入,仅在用户明确要求采纳时调用)。
lme_id=会话工料机行 id(recent_review_query type=lmes 的行)、ref=match_hist 返回的票据。
与页面比对框「采纳」同一条通道:三价改价端点(三价联动/编码同步/merged_codes/旧价锚)
+「采纳:名称+项目+旧三价」备注。被采纳的价格来自服务端快照,不接受调用方传数字。"""
a = _api()
try:
sid = int(args.get("session_id") or 0)
lid = int(args.get("lme_id") or 0)
except (TypeError, ValueError):
return {"ok": False, "msg": "session_id / lme_id 必须是整数 id"}
ref = (args.get("ref") or "").strip()
snap = _MATCH_CACHE.get(ref)
if not snap or snap.get("type") != "lme":
return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist 重新匹配再采纳"}
if not sid or not lid:
return {"ok": False, "msg": "参数:session_id + lme_id(工作台工料机行 id,来自 recent_review_query)"}
sc = a.sess.connect()
try:
sl = sc.execute("SELECT id, Number, Name FROM s_lmes WHERE id=? AND session_id=?", (lid, sid)).fetchone()
if not sl:
return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"}
proj = sc.execute("""SELECT id, ntp, taxrate, taxp FROM s_lme_proj
WHERE session_id=? AND code=? ORDER BY id LIMIT 1""",
(sid, sl["Number"] or "")).fetchone() if sl["Number"] else None
if not proj:
return {"ok": False, "msg": "找不到该项目级工料机行(编码 %s)——项目级汇总未生成或编码为空" % (sl["Number"] or "空")}
old = {"price": proj["ntp"], "tax": proj["taxrate"], "taxp": proj["taxp"]}
with a.WRITE_LOCK: # 采纳即改价(决策 158)+ 采纳备注(决策 219 旧价锚口径)
rp = a.api_lme_price(sc, {"session_id": sid, "id": proj["id"],
"ntp": snap.get("price"), "taxrate": snap.get("tax"),
"taxp": snap.get("price_tax")})
if not rp.get("ok"):
sc.rollback()
return {"ok": False, "msg": "采纳改价失败:" + (rp.get("msg") or "服务未响应")}
# 采纳备注文案与页面 adoptTxtFor 同口径:采纳:名称+项目+旧三价(0/空=「无」)
def p(v):
try:
return "无" if (v is None or v == "" or float(v) == 0) else v
except (TypeError, ValueError):
return "无"
txt = "采纳:%s+%s+%s|%s|%s" % (snap.get("name") or "", snap.get("proj") or "",
p(old["price"]), p(old["tax"]), p(old["taxp"]))
a.sess.save_lme_remark(sc, proj["id"], txt)
sc.commit()
finally:
sc.close()
return {"ok": True, "lme_id": proj["id"], "price": snap.get("price"),
"tax": snap.get("tax"), "price_tax": snap.get("price_tax"), "old": old,
"msg": "已采纳《%s》%s:除税 %s → %s" % (snap.get("name") or "", snap.get("proj") or "",
old["price"], snap.get("price"))}
def _t_attachment_download(args):
"""⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。
type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach);
@@ -311,6 +578,50 @@ def TOOLS():
"type": {"type": "string"}, "id": {"type": "integer"}},
"required": ["type", "id"]},
"run": _t_attachment_download},
{"name": "project_import",
"description": "整项目导入(写入)。把整项目模板 xlsx(「项目目录」Sheet 定目录树+"
"多对数据 Sheet,每对 分部分项N/措施项目N=序号 N 的单位工程)导入建为"
"手工工程。file_b64=xlsx 文件内容(base64);name/period_from(YYYY-MM) 必填,"
"province/city/district/bulid_unit 可选。同名手工工程再次导入=整项目覆盖。"
"导入成功后用 recent_review_query 查该工程清单,再按用户要求 bill_adopt。",
"inputSchema": {"type": "object", "properties": {
"name": {"type": "string"}, "period_from": {"type": "string"},
"period_to": {"type": "string"}, "file_b64": {"type": "string"},
"province": {"type": "string"}, "city": {"type": "string"},
"district": {"type": "string"}, "bulid_unit": {"type": "string"}},
"required": ["name", "period_from", "file_b64"]},
"run": _t_project_import},
{"name": "bill_adopt",
"description": "清单采纳(写入,仅在用户明确要求采纳时调用)。把入库项目清单的定额+消耗量"
"落到工作台会话清单上(软件采纳同一条通道:新行=整组覆盖,已有行=单价覆盖+"
"定额追加;可取消可追溯)。session_id=工作台会话、bill_id=会话清单 id、"
"src_bill_id=入库项目清单 id(id 必须来自查询结果)。每次采纳一条并把结果如实告诉用户。",
"inputSchema": {"type": "object", "properties": {
"session_id": {"type": "integer"}, "bill_id": {"type": "integer"},
"src_bill_id": {"type": "integer"}},
"required": ["session_id", "bill_id", "src_bill_id"]},
"run": _t_bill_adopt},
{"name": "match_hist",
"description": "历史价匹配 top-N(只读)。对工作台一行(清单或工料机)在全部入库项目/信息价/"
"市场价里找最像的历史价,按档位+期次距离排序返回 top-N;每行带 ref 票据,"
"把它传给 bill_adopt / lme_adopt 即可采纳——不需要(也不允许)自己传价格数字。"
"session_id + row_id(来自 recent_review_query)+ type(bill/lme)+ limit(默认 5,上限 20)。",
"inputSchema": {"type": "object", "properties": {
"session_id": {"type": "integer"}, "row_id": {"type": "integer"},
"type": {"type": "string"}, "limit": {"type": "integer"}},
"required": ["session_id", "row_id"]},
"run": _t_match_hist},
{"name": "lme_adopt",
"description": "工料机价格采纳(写入,仅在用户明确要求采纳时调用)。把匹配到的历史价"
"(ref 票据)采纳到工作台工料机:与页面比对框「采纳」同一条通道(三价联动/"
"编码同步/merged_codes/旧价锚+采纳备注)。lme_id=工作台工料机行 id"
"(recent_review_query type=lmes 的行)+ ref(match_hist type=lme 返回的票据)。"
"价格数字来自服务端快照,不接受调用方传数字;每次一条,结果如实告知用户。",
"inputSchema": {"type": "object", "properties": {
"session_id": {"type": "integer"}, "lme_id": {"type": "integer"},
"ref": {"type": "string"}},
"required": ["session_id", "lme_id", "ref"]},
"run": _t_lme_adopt},
]