Files
themiz/scripts/forms.py
T

211 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Реестр форм документов: config/forms.json. --check | --zakon | --normy | --resolve "вид" | --show ID.
Решение владельца 08.10.2026: одно оформление на все формы (PROFILE, его держит document_guard.py) и в форме
только те документы, данные и сведения, которых требует закон. Карточка «из закона»: у каждого обязательного
раздела, сведения и приложения есть норма, и норма находится в корпусе (cite.py). Нет нормы в корпусе -
статус «требует проверки» с причиной, без выдумки.
"""
import argparse
import json
import re
import subprocess
import sys
from pathlib import Path
PATH = Path(__file__).resolve().parents[1] / "config" / "forms.json"
DATE = re.compile(r"^\d{2}\.\d{2}\.\d{4}$")
STR, LST = str, list
REQUIRED = { # поле -> тип
"form_id": STR, "title": STR, "plain_title": STR, "legal_regime": STR, "proceeding": STR,
"roles_allowed": LST, "side": STR, "stage": STR, "goal": STR, "legal_basis": LST,
"freshness": dict, "profile": STR, "sections": LST, "attachments": LST,
"citation_form": STR, "aliases": LST, "forbidden": LST,
}
LEVELS = {"BLOCK", "WARN", "PASS"}
PROFILE = "themiz-standard" # одно оформление для всех форм: PT Serif, кегли, поля - document_guard.py
IZ_ZAKONA, NA_PROVERKE = "из закона", "требует проверки"
CITE = Path(__file__).resolve().parent / "cite.py"
# Нормы, которые не задают содержание документа: порядок разрешения ходатайств и право их заявлять.
# Решение владельца 08.10.2026: состав не задан законом - максимум, как в исковом заявлении, по аналогии закона.
NE_SODERZHANIE = {"ст. 166 ГПК РФ", "ч. 1 ст. 35 ГПК РФ", "ч. 1 ст. 159 АПК РФ"}
def load(path=PATH):
return json.loads(Path(path).read_text(encoding="utf-8"))
def norm(s):
return " ".join(str(s).lower().split())
def _card(c, profiles):
e = []
fid = c.get("form_id", "?")
for k, t in REQUIRED.items():
v = c.get(k)
if not isinstance(v, t) or (t is not LST and not v) or (k not in ("attachments", "forbidden", "aliases") and not v):
e.append(f"{fid}: поле {k} отсутствует или пусто")
if "accepted" not in c:
e.append(f"{fid}: поле accepted отсутствует (null или {{by, date}})")
a = c.get("accepted")
if a is not None and not (isinstance(a, dict) and a.get("by") and DATE.match(str(a.get("date", "")))):
e.append(f"{fid}: accepted должен быть null или {{by, date ДД.ММ.ГГГГ}}")
if c.get("profile") not in profiles:
e.append(f"{fid}: profile {c.get('profile')!r} не из списка профилей")
for b in c.get("legal_basis") or []:
if not (isinstance(b, dict) and all(b.get(k) for k in ("norm", "edition", "source"))):
e.append(f"{fid}: legal_basis требует norm, edition, source")
fr = c.get("freshness")
if isinstance(fr, dict) and not (DATE.match(str(fr.get("checked", ""))) and isinstance(fr.get("recheck_days"), int)):
e.append(f"{fid}: freshness требует checked ДД.ММ.ГГГГ и recheck_days")
for s in c.get("sections") or []:
if not (isinstance(s, dict) and s.get("id") and s.get("title") and isinstance(s.get("required"), bool)):
e.append(f"{fid}: раздел требует id, title, required")
for x in c.get("attachments") or []:
if not (isinstance(x, dict) and x.get("name") and isinstance(x.get("required"), bool)):
e.append(f"{fid}: приложение требует name, required")
for f in c.get("forbidden") or []:
if not (isinstance(f, dict) and f.get("item") and str(f.get("reason", "")).strip()):
e.append(f"{fid}: forbidden требует item и непустую reason")
e += _zakon(c, fid)
for k in c.get("conditions") or []:
if not (isinstance(k, dict) and k.get("id") and k.get("text") and k.get("level") in LEVELS):
e.append(f"{fid}: условие требует id, text, level BLOCK|WARN|PASS")
return e
def _zakon(c, fid):
"""Статус карточки относительно закона. Без поля zakon - карточка не сверена (старый реестр)."""
z = c.get("zakon")
if z is None:
return []
status = z.get("status") if isinstance(z, dict) else None
if status == NA_PROVERKE:
return [] if str(z.get("prichina", "")).strip() else [f"{fid}: «{NA_PROVERKE}» без причины"]
if status != IZ_ZAKONA:
return [f"{fid}: zakon.status - «{IZ_ZAKONA}» или «{NA_PROVERKE}»"]
e = [f"{fid}: legal_basis без нормы" for b in c.get("legal_basis") or [] if NA_PROVERKE in str(b.get("norm", ""))]
e += [f"{fid}: обязательный раздел {x.get('id')} без нормы" for x in c.get("sections") or []
if x.get("required") and not str(x.get("norm", "")).strip()]
e += [f"{fid}: обязательное приложение «{x.get('name')}» без нормы" for x in c.get("attachments") or []
if x.get("required") and not str(x.get("norm", "")).strip()]
sv = c.get("svedeniya")
if not (isinstance(sv, list) and sv):
e.append(f"{fid}: нет сведений, которых требует закон (svedeniya)")
else:
e += [f"{fid}: сведение без нормы или текста" for x in sv
if not (isinstance(x, dict) and str(x.get("text", "")).strip() and str(x.get("norm", "")).strip())]
e += [f"{fid}: {x.get('norm')} не задает содержание документа - норма искового заявления по аналогии"
for x in [*(c.get("sections") or []), *(sv or [])] if isinstance(x, dict) and x.get("norm") in NE_SODERZHANIE]
return e
def normy(c):
"""Все нормы карточки «из закона»: основание, разделы, сведения, приложения."""
if (c.get("zakon") or {}).get("status") != IZ_ZAKONA:
return set()
items = [*(c.get("legal_basis") or []), *(c.get("sections") or []), *(c.get("svedeniya") or []), *(c.get("attachments") or [])]
return {str(x[k]).strip() for x in items if isinstance(x, dict) for k in ("norm", "po_analogii") if str(x.get(k, "")).strip()}
_DOLI = re.compile(r"(?:^|\s)(?:ч|п|пп)\.\s*(\d+(?:\.\d+)?)")
def _doli_est(norma, text):
"""Части и пункты нормы есть в тексте статьи: строка начинается с «N.» или «N)».
ponytail: номер ищется во всей статье, не внутри названной части; ловит несуществующие номера,
но не перестановку пункта между частями. Рост - разбор дерева статьи.
"""
starts = {m.group(1) for m in re.finditer(r"(?m)^\s*(\d+(?:\.\d+)?)[.)]", text)}
head = norma.split("ст.")[0]
if not any(re.match(r"\d+\.", line.strip()) for line in text.splitlines()): # ТК, СК: части не нумерованы - это абзацы
parts = len([b for b in re.split(r"\n\s*\n", text) if b.strip() and not b.lstrip().startswith("#")])
chasti = re.findall(r"(?:^|\s)ч\.\s*(\d+)", head)
return all(int(n) <= parts for n in chasti) and all(
d in starts for d in re.findall(r"(?:^|\s)(?:п|пп)\.\s*(\d+(?:\.\d+)?)", head))
return all(d in starts for d in _DOLI.findall(head))
def nenaidennye(found):
"""Нормы, которых cite.py не нашел в локальном корпусе, и нормы с частью или пунктом, которых в статье нет.
Одна норма - один вызов, без сети."""
bad = []
for n in sorted(found):
r = subprocess.run([sys.executable, str(CITE), "--json", n], capture_output=True, text=True)
try:
data = json.loads(r.stdout)
except ValueError:
data = {}
if not (data.get("found") is True and _doli_est(n, str(data.get("text", "")))):
bad.append(n)
return bad
def check(data):
forms, profiles = data.get("forms"), set(data.get("profiles") or [PROFILE])
if not isinstance(forms, list) or not forms:
return ["forms пуст"]
errs, ids, names = [], set(), {}
for c in forms:
errs += _card(c, profiles)
if c.get("form_id") in ids:
errs.append(f"{c.get('form_id')}: дубль form_id")
ids.add(c.get("form_id"))
for n in [c.get("title", "")] + list(c.get("aliases") or []):
if names.setdefault(norm(n), c.get("form_id")) != c.get("form_id"):
errs.append(f"{c.get('form_id')}: название {n!r} уже у {names[norm(n)]}")
return errs
def resolve(kind, data=None):
k = norm(kind)
hit = {c["form_id"] for c in (data or load())["forms"]
if k in [norm(c["title"]), *map(norm, c.get("aliases", []))]}
if len(hit) != 1:
raise LookupError(f"вид {kind!r}: найдено {len(hit)}")
return hit.pop()
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__)
g = p.add_mutually_exclusive_group(required=True)
g.add_argument("--check", action="store_true")
g.add_argument("--zakon", action="store_true", help="код 1, пока есть формы не из закона")
g.add_argument("--normy", action="store_true", help="каждая норма карточек «из закона» находится в корпусе")
g.add_argument("--resolve", metavar="ВИД")
g.add_argument("--show", metavar="ID")
a = p.parse_args(argv)
d = load()
if a.check:
errs = check(d)
print("\n".join(errs) or f"OK: форм {len(d['forms'])}")
return 1 if errs else 0
if a.zakon:
left = [f"{c['form_id']}: {(c.get('zakon') or {}).get('prichina') or 'не сверена'}" for c in d["forms"]
if (c.get("zakon") or {}).get("status") != IZ_ZAKONA]
print("\n".join(left) + f"\nне из закона: {len(left)} из {len(d['forms'])}" if left else f"OK: все {len(d['forms'])} из закона")
return 1 if left else 0
if a.normy:
bad = nenaidennye(set().union(*map(normy, d["forms"])))
print("\n".join(f"нет в корпусе: {n}" for n in bad) or "OK: все нормы найдены")
return 1 if bad else 0
if a.resolve:
try:
print(resolve(a.resolve, d))
except LookupError as ex:
print(ex, file=sys.stderr)
return 1
return 0
c = next((c for c in d["forms"] if c["form_id"] == a.show), None)
if not c:
print(f"нет формы {a.show}", file=sys.stderr)
return 1
print(json.dumps(c, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())