feat(агент): инструмент regional_rate — региональная расценка с провенансом
Отдельный MCP-инструмент читает regional_ref.sqlite только на чтение; отвечает «региональная база», различает найдено / кода нет / вид не загружен / регион не загружен / база недоступна; федеральную не подставляет. База и модуль монтируются в контейнер по образцу fgis_ref. Четыре проверки. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Запрос расценки/цены из региональной базы с провенансом.
|
||||
|
||||
Три состояния: регион не загружен, регион загружен и кода нет, запись найдена.
|
||||
Ответ всегда помечен как региональная база; федеральная ФСНБ не подставляется.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, json, os, sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_REGISTRY = Path(os.environ.get("REGIONAL_REGISTRY", "/app/reference_sources.json"))
|
||||
|
||||
def _subject_name(con, subject_id, registry=None):
|
||||
try:
|
||||
row = con.execute("select name from subjects where code=?", (subject_id,)).fetchone()
|
||||
if row and row["name"]:
|
||||
return row["name"]
|
||||
except sqlite3.Error:
|
||||
pass
|
||||
try:
|
||||
data = json.loads(Path(registry or DEFAULT_REGISTRY).read_text(encoding="utf-8"))
|
||||
for s in data.get("subjects", []):
|
||||
if int(s["code"]) == int(subject_id):
|
||||
return s.get("name")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
DEFAULT_DB = Path(os.environ.get("REGIONAL_REF_PATH", "/app/data/regional_ref.sqlite"))
|
||||
|
||||
def lookup(code: str, subject_id: int, kind: str | None = None,
|
||||
db: Path | str | None = None, registry: Path | str | None = None) -> dict:
|
||||
db = Path(db or os.environ.get("REGIONAL_REF_PATH", str(DEFAULT_DB)))
|
||||
if not Path(db).is_file():
|
||||
return {"status": "db_unavailable", "base": "региональная",
|
||||
"message": "региональная база недоступна", "subject_id": subject_id}
|
||||
con = sqlite3.connect(f"file:{db}?mode=ro", uri=True); con.row_factory = sqlite3.Row
|
||||
try:
|
||||
loaded = [r["kind"] for r in con.execute(
|
||||
"select distinct kind from sources where subject_id=?", (subject_id,))]
|
||||
if not loaded:
|
||||
return {"status": "region_not_loaded", "base": "региональная",
|
||||
"message": "регион не загружен в региональную базу",
|
||||
"subject_id": subject_id, "subject": _subject_name(con, subject_id, registry)}
|
||||
if kind and kind not in loaded:
|
||||
return {"status": "kind_not_loaded", "base": "региональная",
|
||||
"message": f"регион загружен, но вид {kind} в региональной базе не загружен",
|
||||
"subject_id": subject_id, "subject": _subject_name(con, subject_id, registry),
|
||||
"loaded_kinds": loaded}
|
||||
kinds = [kind] if kind else loaded
|
||||
for k in kinds:
|
||||
if k == "ТЕР":
|
||||
row = con.execute(
|
||||
"select w.code,w.name,w.unit,w.price,s.edition,s.act,"
|
||||
"s.file_sha,s.manifest_sha "
|
||||
"from works w join sources s on s.id=w.source_id "
|
||||
"where w.subject_id=? and w.kind=? and w.code=?",
|
||||
(subject_id, k, code)).fetchone()
|
||||
elif k == "ТССЦ":
|
||||
row = con.execute(
|
||||
"select p.code,p.name,p.unit,p.price_otp,p.price_smet,"
|
||||
"s.edition,s.act,s.file_sha,s.manifest_sha from prices p join sources s "
|
||||
"on s.id=p.source_id where p.subject_id=? and p.kind=? and p.code=?",
|
||||
(subject_id, k, code)).fetchone()
|
||||
else:
|
||||
row = None
|
||||
if row:
|
||||
return {"status": "ok", "base": "региональная",
|
||||
"subject_id": subject_id, "subject": _subject_name(con, subject_id, registry),
|
||||
"kind": k, **dict(row)}
|
||||
return {"status": "code_not_found", "base": "региональная",
|
||||
"message": "регион загружен, кода в региональной базе нет",
|
||||
"subject_id": subject_id, "subject": _subject_name(con, subject_id, registry),
|
||||
"code": code}
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("code"); ap.add_argument("--subject", type=int, required=True)
|
||||
ap.add_argument("--kind", choices=("ТЕР", "ТССЦ"))
|
||||
ap.add_argument("--db", default=str(DEFAULT_DB))
|
||||
a = ap.parse_args()
|
||||
print(json.dumps(lookup(a.code, a.subject, a.kind, a.db), ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user