Files
smeta-web/regional_ref.py
T
anorandClaude Code 49b8f809ea fix(агент): отрицательный статус региона тоже подкладывается в контекст
Сопоставление названий учитывает короткие имена («Москва» → «в Москве»); для
не-ok статусов инъекция требует ответить только статусом и провенансом, не искать
в ФСНБ/ФГИС. Проверки зелёные.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-22 16:31:47 +10:00

114 lines
5.5 KiB
Python

#!/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",
"/data_fast/smeta-web-data/_external/tools/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",
"/data_fast/smeta-web-data/_external/derived/regional_ref/regional_ref.sqlite"))
def _resolve_region(region: str | None, registry=None) -> int | None:
if not region:
return None
try:
data = json.loads(Path(registry or DEFAULT_REGISTRY).read_text(encoding="utf-8"))
except Exception:
return None
want = region.strip().lower()
def _stem(name: str) -> str:
first = (name or "").lower().split()[0] if name else ""
return first[:-2] if len(first) > 7 else first[:-1]
for s in data.get("subjects", []):
name = (s.get("name") or "").lower()
if want == name or want in name or (_stem(name) and _stem(name) in want):
return int(s["code"])
return None
def lookup(code: str, subject_id: int | None = None, kind: str | None = None,
db: Path | str | None = None, registry: Path | str | None = None,
region: str | None = None) -> dict:
if subject_id is None:
subject_id = _resolve_region(region, registry)
if subject_id is None:
return {"status": "region_not_loaded", "base": "региональная",
"message": "регион не распознан", "subject": region}
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())