fix(manual): 手工导出骨架与导入边界修复,单位按目录自然序排列

- 上传口骨架收集改为空操作,骨架仅经升级入库(决策 231/补记十四)
- s_lme_lib 价格快照垫底,修手工会话组成子行价格落 0
- 导出编辑相交消解:删除块与闭合前插入冲突时重映射,防采纳定额丢失/碎 XML
- _span 识别自闭合标签,防容器配对失败留孤儿闭合
- 手工导入放开空名/同名/深层级校验
- 单位顺序改按左侧目录树序(单项入库序+组内编号自然序)
- 补齐手工导出/导入/MCP 切换相关测试
This commit is contained in:
lianjianwei2024
2026-10-28 16:20:34 +08:00
parent 34b14e74ec
commit 8250a265fb
29 changed files with 4033 additions and 1128 deletions

View File

@@ -41,8 +41,8 @@ import price_xlsx # 信息价 / 市场价 Excel 解析器(2026-1
import session_job as sess # 会话库(工作台)
import dyn_lme # 决策 188:动态工料机汇总引擎(方案A 现算,2026-10-24)
import lme_skeleton # 决策 197:工料机骨架库(后缀+字段签名组,代表件大骨架)
import classic_skeleton # 决策 229:经典整件骨架库(手工工程导出模板,连保留值存)
import export_manual # 决策 229:手工工程导出 cos/cos4(经典骨架当模板填空)
import classic_skeleton # 决策 231:经典整件骨架库(手工工程导出模板,连保留值存)
import export_manual # 决策 231:手工工程导出 cos/cos4(经典骨架当模板填空)
import match # 比对引擎(M4)
import export_cos as xcos # 导出回写(批次D,决策 70)
import formats # 导出格式适配器(2026-10-19:SWT/SWZ 骨架/填空)
@@ -554,7 +554,7 @@ def api_upload(body):
_sk.close()
except Exception:
pass
# 决策 229:经典整件骨架收集——后台导入与工作台打开工程同走本口(失败绝不挡上传)
# 决策 231:经典整件骨架收集——后台导入与工作台打开工程同走本口(失败绝不挡上传)
if classic_skeleton.suffix_of(name):
try:
_sk = conn()
@@ -3593,6 +3593,7 @@ def _adopt_summary_rows(sc, hc, sid, uw_id, src_bill_id):
# 本会话该母码已有子级则不覆盖(先采纳的/本项目原的子级为准)。取消采纳回收时随行撤下。
if not sc.execute("SELECT 1 FROM s_lme_res WHERE session_id=? AND p_code=? LIMIT 1",
(sid, code)).fetchone():
_lib_need = set()
for r in hc.execute("""SELECT res_code, qty, seq, name FROM lme_res
WHERE batch_id=(SELECT batch_id FROM bills WHERE id=?)
AND p_code=? ORDER BY seq, id""", (src_bill_id, code)):
@@ -3600,6 +3601,21 @@ def _adopt_summary_rows(sc, hc, sid, uw_id, src_bill_id):
continue
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(?,?,?,?,?,?)",
(sid, code, r["res_code"], r["qty"], r["seq"], r["name"]))
_lib_need.add(r["res_code"])
# 组成子码的名称/规格/单位/类别/单价快照(批次 lme_lib → 会话 s_lme_lib):
# 手工会话没有源文件、s_lme_lib 是空的——导出时这些码要各有一行自己的价
# (2026-10-28 主人实测易达映射源里组成子行编制价全空;原生件铁证:同表自有行)
if _lib_need and hc.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='lme_lib'").fetchone():
for lr in hc.execute("""SELECT code, name, spec, unit, kind, ntp, taxp FROM lme_lib
WHERE batch_id=(SELECT batch_id FROM bills WHERE id=?)
AND code IN (%s)""" % ",".join("?" * len(_lib_need)),
[src_bill_id] + sorted(_lib_need)):
sc.execute("""INSERT OR IGNORE INTO s_lme_lib
(session_id, code, name, spec, unit, kind, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?)""",
(sid, lr["code"], lr["name"], lr["spec"], lr["unit"],
lr["kind"], lr["ntp"], lr["taxp"]))
return n, code_map
@@ -3775,6 +3791,26 @@ def api_bill_adopt(sc, hc, body):
if new and new != rr["res_code"]:
sc.execute("UPDATE s_norm_res SET res_code=? WHERE id=?", (new, rr["id"]))
n_recode += 1
# 决策 231 补记五(主人 2026-10-28 定「采纳全部数据,包含子工料机」):把批次里
# 台班/配合比的**下一级组成**(lme_res,批次库)补进会话 s_lme_res(会话库)——
# 本会话没有该码的组成才补(源文件工程解析时已带,不重复);手工工程从此有子级数据。
try:
_codes = [r[0] for r in sc.execute(
"SELECT DISTINCT nr.res_code FROM s_norm_res nr "
"JOIN s_norms n ON n.id=nr.norm_id "
"JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id=?", (sid,))]
_have = {r[0] for r in sc.execute(
"SELECT DISTINCT p_code FROM s_lme_res WHERE session_id=?", (sid,))}
_todo = [c for c in _codes if c and c not in _have]
if _todo:
_ph = ",".join("?" * len(_todo))
for r in hc.execute(
"SELECT p_code, res_code, qty, seq, name FROM lme_res "
"WHERE p_code IN (%s) ORDER BY p_code, seq, id" % _ph, _todo):
sc.execute("INSERT INTO s_lme_res(session_id,p_code,res_code,qty,seq,name) "
"VALUES(?,?,?,?,?,?)", (sid, r[0], r[1], r[2], r[3], r[4]))
except Exception as _e:
print("!! 采纳补子级组成失败:%s" % _e, flush=True)
_pk = _pre.keys() if _pre is not None else []
_price0 = (_pre["x_price0"] if _pre is not None and "x_price0" in _pk and _pre["x_price0"] is not None
else (_pre["Price"] if _pre is not None else None))
@@ -3793,7 +3829,7 @@ _EXPORT_JOBS = {}
def _export_meta(sc, sid, fmt=""):
"""导出建议名(决策 92:先弹另存为再生成——对话框要预填 名字-审核版.原后缀,不能等生成完)。
决策 229:手工工程导出 fmt=cos4/cos/xlsx 三选(xlsx=每单位工程一个 Excel 的 zip 包)。"""
决策 231:手工工程导出 fmt=cos4/cos/xlsx 三选(xlsx=每单位工程一个 Excel 的 zip 包)。"""
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
if not srow:
return {"ok": False, "msg": "会话不存在"}
@@ -3807,6 +3843,8 @@ def _export_meta(sc, sid, fmt=""):
return {"ok": False, "msg": "手工工程导出请选格式:cos4 / cos / Excel"}
if not (srow["src_name"] or ""):
return {"ok": False, "msg": "没有源文件,无法按原格式导出"}
if (fmt or "").lower() == "cos4": # 补记十二:普通工程 cos4 也走经典骨架
return {"ok": True, "name": (proj_name or "工程") + "-审核版.cos4"}
ext = xcos._source_ext(srow["src_name"])
return {"ok": True, "name": (proj_name or "工程") + "-审核版" + ext}
@@ -3815,7 +3853,7 @@ def _export_session(sc, sid, fmt="", progress=None):
"""导出=拿原文件当模板外科手术。返回 (字节, 文件名, 错误)。
2026-10-19:SWT/SWZ 等新格式走 formats 适配器(骨架+填空);COS4/.COS 继续用
export_cos 的专用引擎(保留逐节点保真)。
决策 229:手工工程(无源文件)走经典整件骨架——fmt=cos4/cos 取骨架库代表件填空,
决策 231:手工工程(无源文件)走经典整件骨架——fmt=cos4/cos 取骨架库代表件填空,
fmt=xlsx 走 manual_import.export_excel_bytes(每单位工程一个 Excel 的 zip 包)。"""
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
if not srow:
@@ -3832,6 +3870,15 @@ def _export_session(sc, sid, fmt="", progress=None):
_h.close()
return None, None, "手工工程导出请选格式:cos4 / cos / Excel"
path = _src_path(srow["src_name"])
# 补记十二(2026-10-28 主人定「推翻:审核版不再基于原文件」):cos4 全量走经典骨架
# (骨架管导出、数据归软件);其余格式维持原格式导出。源文件在=按字段相近挑骨架,
# 不在也照导(挑最近收藏的骨架)。
if (fmt or "").lower() == "cos4":
_h = conn()
try:
return export_manual.export(sc, _h, sid, "cos4", progress, src_path=path)
finally:
_h.close()
if not path or not os.path.exists(path):
return None, None, "原文件已不在软件里(可能被清理),无法导出"
try:
@@ -5199,6 +5246,8 @@ def api_schema():
{"name*": "工程名", "period_from*": "年*12+月", "period_to": "止期次",
"tree*": "[{name, units:[{name, file?}]}],file=上传的 xlsx 路径(整单位工程覆盖)"},
{"session_id": 5, "imported": "[{uw,n_div,n_item,n_prelim}]"}),
r("GET", "/api/session/manual/export_unit", "单单位工程导 xlsx(决策 233;格式=231 Excel 通道单文件,可回导)",
{"session_id*": "会话id", "uw*": "单位工程id"}),
],
"查询": [
r("GET", "/api/session/raw/tree", "单位工程树",
@@ -5254,9 +5303,9 @@ def api_schema():
r("GET", "/api/session/edit/log", "字段编辑历史(红三角批注)"),
],
"导出": [
r("GET", "/api/session/export", "导出审核版(zip 流;文件名=工程名-审核版.原后缀;手工工程 fmt=cos4/cos/xlsx 三选,决策 229)",
r("GET", "/api/session/export", "导出审核版(zip 流;文件名=工程名-审核版.原后缀;手工工程 fmt=cos4/cos/xlsx 三选,决策 231)",
{"session_id*": "", "token": "可选:进度上报令牌(决策 92)", "fmt": "可选:手工工程导出格式 cos4/cos/xlsx"}),
r("GET", "/api/session/export/meta", "导出建议名(先弹另存为再生成,决策 92;手工工程带 fmt,决策 229)",
r("GET", "/api/session/export/meta", "导出建议名(先弹另存为再生成,决策 92;手工工程带 fmt,决策 231)",
{"session_id*": "", "fmt": "可选:手工工程导出格式 cos4/cos/xlsx"}),
r("GET", "/api/session/export/progress", "导出逐条目进度(轮询,决策 92)",
{"token*": ""}),
@@ -7813,6 +7862,22 @@ class Handler(SimpleHTTPRequestHandler):
self.send_header("Content-Disposition", self._cd(fn, "manual_import_template.xlsx"))
self.end_headers()
self.wfile.write(raw)
if p == "/api/session/manual/export_unit": # 手工工程:单单位工程导 xlsx(决策 233 方案a)
con = sess.connect()
try:
raw, fn, err = mimp.export_unit_xlsx(
con, int(one.get("session_id", 0) or 0), int(one.get("uw", 0) or 0))
finally:
con.close()
if err or not raw:
return self._json({"error": err or "导出失败"}, 400)
self._allow_cache = True # 下载不能带 no-store(同模板下载)
self.send_response(200)
self.send_header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Content-Disposition", self._cd(fn or "单位工程.xlsx", "manual_unit_export.xlsx"))
self.end_headers()
self.wfile.write(raw)
# ---- 询价附件(项目工料机专用)----
m = re.match(r"^/api/admin/batch/(\d+)/inq/lmes$", p) # 该项目全部工料机 + 绑定状态
if m:

View File

@@ -1,27 +1,29 @@
# -*- coding: utf-8 -*-
"""MCP 接入层(2026-10-15):把产品功能以 MCP 工具暴露给 AI harness(ZCode / WorkBuddy /
DeepSeek 等一切支持 MCP 或会发 HTTP 的 agent)。
"""MCP 接入层(2026-10-15 上线;2026-10-27 主人重定义:**只读**)。
- 传输:Streamable HTTP(POST /mcp,JSON-RPC 2.0,单响应 JSON;无 SSE/无会话态,stateless)
- 开关:全局设置 mcp_enabled(**默认关**——断开就是连不上,403);令牌 mcp_token
(首次开启自动生成,调用必须带 Authorization: Bearer <令牌>,/api/mcp/status 可查)
- 收费挂钩:license enforce 时未激活/过期 → 整个端点 403 LICENSE_REQUIRED(开关开了也断)
- 工具:全部复用 api_* 处理器(与界面同一套业务、写锁、分组缓存失效),**不另开第二通道**
- 收费挂钩:license enforce 时未激活/过期(套餐范围外且临时卡失效)→ 整个端点
403 LICENSE_REQUIRED(开关开了也断)
- 工具(2026-10-27 主人定,共 5 个,**全部只读,无任何增删改/导出**):
① bills_query 入库项目清单:编号/名称/项目特征/单价
② lme_prices 工料机单价
③ market_info_prices 市场价/信息价数据
④ recent_review_query 工作台最近审核(口径同 ①②)
⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律
不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch
(价格批次原件);不支持枚举、不支持全量下载
- 零新增依赖:JSON-RPC 手写,只依赖标准库
Agent 注意(与 /api/schema 的 notes 一致):id 随重开变化;采纳 新行=覆盖/已有行=追加;
工程量等数值一律字符串;导出前自动校验源文件哈希。
"""
import io
import base64
import json
import os
import re
import secrets
import threading
import zipfile
PROTO_VERSION = "2025-06-18"
_API = None # api_server 模块(bind 注入,避免循环导入)
ATT_MAX_DL = 20 * 1024 * 1024 # 单附件下载上限:超过请走软件界面下载
def bind(api_module):
@@ -64,10 +66,20 @@ def status():
"endpoint": "/mcp", "port": a.PORT, "license_enforced": bool(a.license_gate._cfg.get("enforce", True))}
# ---------------------------------------------------------------- 工具实现(复用 api_*)
# ---------------------------------------------------------------- 工具实现(只读)
def _read(fn):
"""只读工具:开只读连接跑 api_* 函数。"""
def _hist(fn):
"""历史库只读查询(入库项目 / 市场价信息价 / 附件绑定)。"""
a = _api()
con = a.conn()
try:
return fn(con)
finally:
con.close()
def _sess(fn):
"""会话库只读查询(工作台最近审核)。"""
a = _api()
sc = a.sess.connect()
try:
@@ -76,220 +88,229 @@ def _read(fn):
sc.close()
def _write(fn):
"""写工具:写锁 + 提交/回滚 + 分组缓存失效(与各路由分支同款守护)。"""
a = _api()
with a.WRITE_LOCK:
sc = a.sess.connect()
try:
r = fn(sc)
sc.commit()
_sid = (r.get("sid") or 0) if isinstance(r, dict) else 0
if isinstance(r, dict) and r.get("ok") and _sid:
a._grp_cache_drop("session", int(_sid))
return r
except Exception as e:
try:
sc.rollback()
except Exception:
pass
return {"ok": False, "msg": "操作失败:%s" % e}
finally:
sc.close()
def _t_sessions_list(args):
return _api().api_sessions()
def _t_project_open(args):
return _api().api_audit(args)
def _t_session_delete(args):
return _api().api_session_delete(args)
def _t_admin_import(args):
a = _api()
con = a.conn()
def _paging(args):
"""limit 归一:默认 50,1~200。"""
try:
return a.api_admin_import(con, args)
finally:
con.close()
return min(max(int(args.get("limit") or 50), 1), 200)
except (TypeError, ValueError):
return 50
def _t_tree(args):
return _api().api_raw_tree(args)
def _need_scope(args):
"""查询范围守卫:keyword 或 batch_id 至少给一个(防空量拖库)。"""
kw = (args.get("keyword") or "").strip()
try:
bid = int(args.get("batch_id") or 0)
except (TypeError, ValueError):
bid = 0
return kw, bid
def _t_uw_detail(args):
return _api().api_raw_uw(args)
def _rows(con, sql, params):
cur = con.execute(sql, params)
cols = [d[0] for d in cur.description]
return [dict(zip(cols, r)) for r in cur.fetchall()]
def _t_session_rows(args):
return _api().api_session_rows(args)
def _t_bills_query(args):
"""① 入库项目清单:Number(编号)/Name(名称)/Attr(项目特征)/Price(单价)。"""
kw, bid = _need_scope(args)
if not kw and not bid:
return {"ok": False, "msg": "请给 keyword(清单编号/名称关键词)或 batch_id 之一"}
lim = _paging(args)
sql = ("SELECT b.id, b.batch_id, t.Name AS batch_name, b.Number, b.Name, b.Attr, b.Price "
"FROM bills b JOIN batches t ON t.id = b.batch_id "
"WHERE t.kind='project'")
params = []
if bid:
sql += " AND b.batch_id=?"
params.append(bid)
if kw:
sql += " AND (b.Number LIKE ? OR b.Name LIKE ?)"
params += ["%%%s%%" % kw, "%%%s%%" % kw]
sql += " ORDER BY b.batch_id, b.x_seq LIMIT ?"
params.append(lim)
rows = _hist(lambda con: _rows(con, sql, params))
return {"ok": True, "total": len(rows), "rows": rows}
def _t_bill_op(args):
return _write(lambda sc: _api().api_bill_op(sc, args))
def _t_lme_prices(args):
"""② 工料机单价:NoTaxPrice(除税)/TaxRate(税率)/TaxPrice(含税)。"""
kw, bid = _need_scope(args)
if not kw and not bid:
return {"ok": False, "msg": "请给 keyword(工料机编号/名称/规格关键词)或 batch_id 之一"}
lim = _paging(args)
sql = ("SELECT l.id, l.batch_id, t.Name AS batch_name, l.Number, l.Name, "
"l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice "
"FROM lmes l JOIN batches t ON t.id = l.batch_id "
"WHERE t.kind='project'")
params = []
if bid:
sql += " AND l.batch_id=?"
params.append(bid)
if kw:
sql += " AND (l.Number LIKE ? OR l.Name LIKE ? OR l.Specification LIKE ?)"
params += ["%%%s%%" % kw] * 3
sql += " ORDER BY l.batch_id, l.id LIMIT ?"
params.append(lim)
rows = _hist(lambda con: _rows(con, sql, params))
return {"ok": True, "total": len(rows), "rows": rows}
def _t_norm_op(args):
return _write(lambda sc: _api().api_norm_op(sc, args))
def _t_market_info_prices(args):
"""③ 市场价/信息价数据(价格批次明细)。"""
kw, bid = _need_scope(args)
if not kw and not bid:
return {"ok": False, "msg": "请给 keyword(编号/名称关键词)或 batch_id(价格批次 id)之一"}
lim = _paging(args)
sql = ("SELECT p.id, p.batch_id, t.Name AS batch_name, t.x_publisher, p.Code, p.Name, "
"p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Class "
"FROM prices p JOIN batches t ON t.id = p.batch_id "
"WHERE t.kind IN ('info', 'market')")
params = []
if bid:
sql += " AND p.batch_id=?"
params.append(bid)
if kw:
sql += " AND (p.Code LIKE ? OR p.Name LIKE ?)"
params += ["%%%s%%" % kw, "%%%s%%" % kw]
sql += " ORDER BY p.batch_id, p.id LIMIT ?"
params.append(lim)
rows = _hist(lambda con: _rows(con, sql, params))
return {"ok": True, "total": len(rows), "rows": rows}
def _t_bill_adopt(args):
a = _api()
def run(sc):
hc = a.conn()
try:
return a.api_bill_adopt(sc, hc, args)
finally:
hc.close()
return _write(run)
def _t_bill_unadopt(args):
a = _api()
def run(sc):
hc = a.conn()
try:
return a.api_bill_unadopt(sc, hc, args)
finally:
hc.close()
return _write(run)
def _t_lme_merge_groups(args):
return _read(lambda sc: _api()._lme_merge_groups(sc, int(args.get("session_id", 0))))
def _t_lme_merge(args):
return _write(lambda sc: _api().api_lme_merge(sc, args))
def _t_session_remark(args):
a = _api()
def run(sc):
if args.get("lme_id"):
a.sess.save_lme_remark(sc, int(args.get("lme_id", 0)), args.get("remark", ""))
def _t_recent_review_query(args):
"""④ 工作台最近审核:不带 session_id → 最近会话列表;带 session_id+type → 行数据
(type=bills 口径同 ①,type=lmes 口径同 ②)。"""
try:
sid = int(args.get("session_id") or 0)
except (TypeError, ValueError):
sid = 0
typ = (args.get("type") or "").strip().lower()
kw = (args.get("keyword") or "").strip()
lim = _paging(args)
if not sid:
rows = _sess(lambda sc: _rows(
sc, "SELECT id, name, period_from, period_to, imported_at, x_total "
"FROM sessions ORDER BY imported_at DESC LIMIT ?", (lim,)))
return {"ok": True, "total": len(rows), "rows": rows,
"hint": "带 session_id + type(bills/lmes)查行数据"}
if typ not in ("bills", "lmes"):
return {"ok": False, "msg": "type 必须是 bills 或 lmes(不带 type 时返回会话列表)"}
if typ == "bills":
sql = ("SELECT id, Number, Name, Attr, Price, Unit, Quantity "
"FROM s_bills WHERE session_id=?")
else:
sql = ("SELECT id, Number, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice "
"FROM s_lmes WHERE session_id=?")
params = [sid]
if kw:
if typ == "bills":
sql += " AND (Number LIKE ? OR Name LIKE ?)"
else:
a.sess.save_remark(sc, int(args.get("bill_id", 0)), args.get("remark", ""))
return {"ok": True}
return _write(run)
sql += " AND (Number LIKE ? OR Name LIKE ? OR Specification LIKE ?)"
params += ["%%%s%%" % kw] * (2 if typ == "bills" else 3)
sql += " ORDER BY id LIMIT ?"
params.append(lim)
rows = _sess(lambda sc: _rows(sc, sql, params))
return {"ok": True, "total": len(rows), "rows": rows}
def _t_schema(args):
return _api().api_schema()
def _t_batch_tree(args):
return _api().api_admin_raw_tree(args)
def _t_batch_uw(args):
return _api().api_admin_raw_uw(args)
def _t_session_export(args):
"""导出 → 落盘 data/exports/,回文件路径(Agent 在本机直接可读)。"""
def _t_attachment_download(args):
"""⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。
type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach);
type=batch → 价格批次原件(batches.x_attach_sha)。"""
a = _api()
sc = a.sess.connect()
typ = (args.get("type") or "").strip().lower()
try:
raw, out_name, err = a._export_session(sc, int(args.get("session_id", 0) or 0))
finally:
sc.close()
if err:
return {"ok": False, "msg": err}
out_dir = os.path.join(a.DATA_DIR, "exports")
os.makedirs(out_dir, exist_ok=True)
fp = os.path.join(out_dir, "%d_%s" % (int(time.time()), out_name))
with open(fp, "wb") as f:
f.write(raw)
return {"ok": True, "path": fp, "bytes": len(raw), "name": out_name}
rid = int(args.get("id") or 0)
except (TypeError, ValueError):
rid = 0
if typ not in ("bill", "lme", "batch") or not rid:
return {"ok": False, "msg": "参数:type=bill|lme|batch + id(来自查询结果的行/批次 id)"}
def load(con):
if typ == "bill":
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
"FROM bill_attach a JOIN inquiry_files f ON f.id=a.file_id "
"WHERE a.bill_id=?", (rid,)), a.INQ_DIR
if typ == "lme":
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
"FROM lme_attach a JOIN inquiry_files f ON f.id=a.file_id "
"WHERE a.lme_id=?", (rid,)), a.INQ_DIR
return _rows(con, "SELECT at.original_name, at.stored_path, at.size, at.sha256 "
"FROM attachments at WHERE at.sha256="
"(SELECT x_attach_sha FROM batches WHERE id=?)", (rid,)), a.ATTACH_DIR
files, root = _hist(load)
if not files:
return {"ok": False, "msg": "没有绑定附件(或 id 不存在)"}
out = []
for f in files:
fp = os.path.realpath(os.path.join(a.DATA_DIR, f["stored_path"] or ""))
if os.path.commonpath([fp, os.path.realpath(root)]) != os.path.realpath(root):
return {"ok": False, "msg": "附件路径不合法,拒绝读取"}
try:
with open(fp, "rb") as fh:
raw = fh.read()
except OSError as e:
return {"ok": False, "msg": "附件读取失败:%s" % e}
if len(raw) > ATT_MAX_DL:
return {"ok": False, "msg": "《%s》超过 %d MB 下载上限,请在软件界面下载"
% ((f["original_name"] or "")[:40], ATT_MAX_DL // 1024 // 1024)}
out.append({"name": f["original_name"], "size": f["size"], "sha256": f["sha256"],
"content_base64": base64.b64encode(raw).decode("ascii")})
return {"ok": True, "files": out}
# ---------------------------------------------------------------- 工具清单
def _schema(paths, *names):
"""从 /api/schema 事实源里摘路由描述(保证工具描述与接口同源)。"""
try:
s = _api().api_schema()
out = []
for g in s["groups"].values():
for x in g:
if x["path"] in paths:
out.append(x)
return out
except Exception:
return []
def TOOLS():
a = _api()
return [
{"name": "sessions_list", "description": "会话台账(已有审核工程列表)",
"inputSchema": {"type": "object", "properties": {}}, "run": _t_sessions_list},
{"name": "project_open", "description": "打开工程→解析→建/续会话(同名=原地续用)。"
"path 必须是软件目录内的文件(先 upload_file)", "inputSchema": {"type": "object",
"properties": {k: {"type": "string"} for k in ("path", "name", "province", "city", "district",
"period_from", "period_to", "file_kind")},
"required": ["path", "name", "period_from"]}, "run": _t_project_open},
{"name": "session_delete", "description": "删会话(连同无引用的源文件副本)",
"inputSchema": {"type": "object", "properties": {"ids": {"type": "array", "items": {"type": "integer"}}},
"required": ["ids"]}, "run": _t_session_delete},
{"name": "upload_file", "description": "上传本机文件进软件(base64 内容),返回软件内 path",
"inputSchema": {"type": "object", "properties": {"name": {"type": "string"},
"content_base64": {"type": "string"}}, "required": ["name", "content_base64"]},
"run": lambda args: _api().api_upload(args)},
{"name": "admin_import", "description": "导入后台批次(=采纳源库)",
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "name": {"type": "string"},
"kind": {"type": "string"}, "force": {"type": "boolean"}}, "required": ["path", "name"]},
"run": _t_admin_import},
{"name": "session_tree", "description": "会话单位工程树",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}},
"required": ["session_id"]}, "run": _t_tree},
{"name": "uw_detail", "description": "单位工程内清单树(含定额/工料机)",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
"uw_id": {"type": "string"}, "tab": {"type": "string"}},
"required": ["session_id", "uw_id"]}, "run": _t_uw_detail},
{"name": "session_rows", "description": "清单/工料机行数据",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
"type": {"type": "string"}}, "required": ["session_id", "type"]}, "run": _t_session_rows},
{"name": "bill_op", "description": "清单增删改:insert_above/insert_below/del/tdel/untdel/edit",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
"op": {"type": "string"}, "bill_id": {"type": "integer"},
"fields": {"type": "object"}}, "required": ["op", "bill_id"]}, "run": _t_bill_op},
{"name": "norm_op", "description": "定额增删改:ntdel/unntdel/unadopt(取消采纳)或 fields 行内编辑",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
"op": {"type": "string"}, "norm_id": {"type": "integer"},
"fields": {"type": "object"}}}, "run": _t_norm_op},
{"name": "bill_adopt", "description": "采纳(新行=覆盖,已有行=追加,原定额转临删)",
"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": "bill_unadopt", "description": "清单级取消采纳",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
"bill_id": {"type": "integer"}}, "required": ["session_id", "bill_id"]},
"run": _t_bill_unadopt},
{"name": "lme_merge_groups", "description": "工料机合并分组(同名/近似)",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}},
"required": ["session_id"]}, "run": _t_lme_merge_groups},
{"name": "lme_merge", "description": "合并改价+隐藏",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
"groups": {"type": "array"}}, "required": ["session_id", "groups"]}, "run": _t_lme_merge},
{"name": "session_remark", "description": "清单审核备注(持久化)",
"inputSchema": {"type": "object", "properties": {"bill_id": {"type": "integer"},
"remark": {"type": "string"}}, "required": ["bill_id", "remark"]}, "run": _t_session_remark},
{"name": "session_export", "description": "导出审核版(zip 落盘 data/exports/,返回本机路径)",
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}},
"required": ["session_id"]}, "run": _t_session_export},
{"name": "api_schema", "description": "产品全部接口清单(工具未覆盖的功能用它走 HTTP)",
"inputSchema": {"type": "object", "properties": {}}, "run": _t_schema},
{"name": "bills_query",
"description": "查入库项目的清单:编号 Number、名称 Name、项目特征 Attr、单价 Price。"
"keyword(编号/名称关键词)或 batch_id 至少给一个;limit 默认 50 上限 200。"
"响应不含附件信息。",
"inputSchema": {"type": "object", "properties": {
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
"limit": {"type": "integer"}},
"required": []},
"run": _t_bills_query},
{"name": "lme_prices",
"description": "查入库项目的工料机单价:编号、名称、规格、单位、除税价 NoTaxPrice、"
"税率 TaxRate、含税价 TaxPrice。keyword 或 batch_id 至少一个。响应不含附件信息。",
"inputSchema": {"type": "object", "properties": {
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
"limit": {"type": "integer"}},
"required": []},
"run": _t_lme_prices},
{"name": "market_info_prices",
"description": "读市场价/信息价批次明细:Code、Name、Specification、Unit、三价、Class。"
"keyword(编号/名称)或 batch_id(价格批次 id)至少一个。",
"inputSchema": {"type": "object", "properties": {
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
"limit": {"type": "integer"}},
"required": []},
"run": _t_market_info_prices},
{"name": "recent_review_query",
"description": "读工作台最近审核:不带参数=最近会话列表;session_id + type(bills=清单"
"编号/名称/项目特征/单价,lmes=工料机单价)查该会话行数据,口径与"
"bills_query / lme_prices 一致。可选 keyword 过滤。",
"inputSchema": {"type": "object", "properties": {
"session_id": {"type": "integer"}, "type": {"type": "string"},
"keyword": {"type": "string"}, "limit": {"type": "integer"}},
"required": []},
"run": _t_recent_review_query},
{"name": "attachment_download",
"description": "下载绑定附件。**仅在用户明确要求下载附件时调用**(查询结果不含附件信息,"
"不得主动调用)。id 必须来自查询结果:type=bill/lme 用 bills_query/"
"lme_prices/recent_review_query 返回的行 id;type=batch 用价格批次 id"
"(批次原件)。不支持枚举或全量下载。",
"inputSchema": {"type": "object", "properties": {
"type": {"type": "string"}, "id": {"type": "integer"}},
"required": ["type", "id"]},
"run": _t_attachment_download},
]
@@ -314,7 +335,7 @@ def _dispatch(msg):
return False, _rpc_result(cid, {
"protocolVersion": PROTO_VERSION,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "造价审核", "version": "mcp-1.0"}})
"serverInfo": {"name": "造价审核", "version": "mcp-2.0"}})
if method == "ping":
return False, _rpc_result(cid, {})
if method == "tools/list":
@@ -343,7 +364,7 @@ def _dispatch(msg):
def handle_post(auth_header, body_text):
"""POST /mcp 入口。返回 (HTTP 状态码, 响应对象或 None[202])。
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时未激活/过期整端点断)。"""
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时套餐范围外且临时卡失效整端点断)。"""
a = _api()
if not enabled():
return 403, {"jsonrpc": "2.0", "id": None,