Закрытие «скачано но не заведено» (карта — docs/DATA_COVERAGE_MAP.md): - bim_parse: матричное приложение «по элементам прямых затрат» (ОТ/МАТ/ЭМ × ФЕР/ТЕР по зонам), 91099 записей; tool find_direct_costs_index. Голден Хабаровск 1 зона: ОТ 69,18/52,25, МАТ 12,40/11,36, ЭМ 17,17/14,50 (сверено независимо). - fgis_ref: справочная база цен ФГИС по ВСЕМ регионам (SQLite): цены 2022 + текущие + ГОСР + salary + КСР 174798; tools find_resource_price/find_salary/find_ksr. Расчётная цена с флагом. Данные в staging; активация (staging→живой) — отдельный шаг. +55 тестов, 630 зелёных. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
567 lines
26 KiB
Python
567 lines
26 KiB
Python
#!/usr/bin/env python3
|
||
"""build_fgis_ref — сборка справочной SQLite-базы цен ресурсов ФГИС ЦС из снапшотов.
|
||
|
||
Вход (только диск, сети нет): snapshots/fgis/split_form/<subj>/<zone>/<period>/
|
||
(xlsx «Сплит-форма» + meta.json), snapshots/fgis/salary/..., opendata/2 (КСР,
|
||
cp1251), opendata/6 (ценовые зоны, cp1251 «;»), reference.json (имена).
|
||
|
||
Money-гейты (неверная цена = неверная смета):
|
||
- код ресурса обязан матчить один из зафиксированных форматов ФГИС (сверено по
|
||
живой зоне 333/182: КСР-материалы, машины 91.xx, автоперевозки, ж/д, погрузка,
|
||
оплата труда) — иначе строка в карантин, не в базу;
|
||
- цена — число > 0; нечисловой мусор в ценовой ячейке → карантин ВСЕЙ строки
|
||
(не «0»); «-» — легальное «нет значения»;
|
||
- строка вовсе без цен (все «-», ресурс без данных в зоне) → счётчик, не запись;
|
||
- rows_loaded зоны вне 200К–320К → зона suspicious;
|
||
- любой брак/ошибка/подозрительная зона → exit 1 (fail-loud), но сборка ДОХОДИТ
|
||
до конца (инкрементальность: зона с тем же sha256 пропускается).
|
||
|
||
Схема НЕ плоская: номенклатура (код+имя+ед.) одинакова во всех 148 зонах, поэтому
|
||
дедуплицирована в items (~250К строк), по-зонные цены — узкая таблица prices
|
||
(~41.6М строк); иначе база раздувается с ~4 ГБ до ~15 ГБ.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import hashlib
|
||
import json
|
||
import re
|
||
import sqlite3
|
||
import sys
|
||
import time
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
from fgis_ref import norm_text, CODE_RE, SCHEMA_VERSION # noqa: E402
|
||
|
||
DDL = """
|
||
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
|
||
CREATE TABLE IF NOT EXISTS items(
|
||
item_id INTEGER PRIMARY KEY,
|
||
code TEXT NOT NULL, name TEXT NOT NULL, unit TEXT NOT NULL DEFAULT '',
|
||
name_norm TEXT NOT NULL,
|
||
UNIQUE(code, name, unit));
|
||
CREATE INDEX IF NOT EXISTS idx_items_code ON items(code);
|
||
CREATE TABLE IF NOT EXISTS gosr_groups(
|
||
group_rowid INTEGER PRIMARY KEY,
|
||
group_id INTEGER, group_name TEXT NOT NULL DEFAULT '',
|
||
UNIQUE(group_id, group_name));
|
||
CREATE TABLE IF NOT EXISTS prices(
|
||
subject_id INTEGER NOT NULL, zone_id INTEGER NOT NULL, period_id INTEGER NOT NULL,
|
||
item_id INTEGER NOT NULL REFERENCES items(item_id),
|
||
price_offsell REAL, price_base_2022 REAL, price_current REAL,
|
||
group_rowid INTEGER REFERENCES gosr_groups(group_rowid),
|
||
gosr_index REAL);
|
||
CREATE INDEX IF NOT EXISTS idx_prices_item ON prices(item_id, subject_id, zone_id, period_id);
|
||
CREATE INDEX IF NOT EXISTS idx_prices_zone ON prices(subject_id, zone_id, period_id);
|
||
CREATE TABLE IF NOT EXISTS zone_snapshots(
|
||
subject_id INTEGER, zone_id INTEGER, period_id INTEGER,
|
||
subject_name TEXT, zone_name TEXT, period_label TEXT,
|
||
letter_ref TEXT, salary_npa_ref TEXT,
|
||
sha256 TEXT, fetched_at TEXT,
|
||
rows_loaded INTEGER, rows_no_price INTEGER, rows_bad_price INTEGER, rows_bad_code INTEGER,
|
||
salary_sha256 TEXT, salary_loaded INTEGER,
|
||
suspicious INTEGER NOT NULL DEFAULT 0, note TEXT, built_at TEXT,
|
||
PRIMARY KEY(subject_id, zone_id, period_id));
|
||
CREATE TABLE IF NOT EXISTS salary(
|
||
subject_id INTEGER, zone_id INTEGER, period_id INTEGER,
|
||
code TEXT, rank TEXT, name TEXT, salary REAL);
|
||
CREATE INDEX IF NOT EXISTS idx_salary_zone ON salary(subject_id, zone_id, period_id);
|
||
CREATE TABLE IF NOT EXISTS ksr(
|
||
okpd2 TEXT, code TEXT, name TEXT, unit TEXT, is_group INTEGER, name_norm TEXT);
|
||
CREATE INDEX IF NOT EXISTS idx_ksr_code ON ksr(code);
|
||
CREATE TABLE IF NOT EXISTS zones_ref(
|
||
subject_code TEXT, subject_name TEXT, zone_name TEXT, zone_center TEXT,
|
||
municipalities TEXT);
|
||
"""
|
||
|
||
|
||
def _utcnow() -> str:
|
||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
|
||
|
||
def _sha256(path: Path) -> str:
|
||
h = hashlib.sha256()
|
||
with open(path, "rb") as f:
|
||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||
h.update(chunk)
|
||
return h.hexdigest()
|
||
|
||
|
||
def _price_cell(v) -> tuple[float | None, bool]:
|
||
"""Ценовая ячейка → (значение, валидна). «-»/пусто — легальное отсутствие;
|
||
число ≤ 0 или нечисловой мусор → (None, False) — карантин строки, НЕ «0»."""
|
||
if v is None:
|
||
return None, True
|
||
if isinstance(v, (int, float)):
|
||
return (float(v), True) if v > 0 else (None, False)
|
||
s = str(v).strip()
|
||
if s in ("-", "", "—"):
|
||
return None, True
|
||
try:
|
||
f = float(s.replace("\xa0", "").replace(" ", "").replace(",", "."))
|
||
except ValueError:
|
||
return None, False
|
||
return (f, True) if f > 0 else (None, False)
|
||
|
||
|
||
def _int_cell(v) -> int | None:
|
||
if v is None:
|
||
return None
|
||
if isinstance(v, (int, float)):
|
||
return int(v)
|
||
s = str(v).strip()
|
||
if s in ("-", "", "—"):
|
||
return None
|
||
try:
|
||
return int(float(s.replace(",", ".")))
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def _text_cell(v) -> str | None:
|
||
if v is None:
|
||
return None
|
||
s = str(v).strip()
|
||
return s if s not in ("", "-", "—") else None
|
||
|
||
|
||
def _is_numbering_row(r: tuple) -> bool:
|
||
return all(str(r[i]).strip() == str(i + 1) for i in range(3) if r[i] is not None) \
|
||
and r[0] is not None
|
||
|
||
|
||
def parse_split_form(path: Path) -> dict:
|
||
"""Разбор xlsx сплит-формы. Шапка ищется ПОИСКОМ строки «Код ресурса…»
|
||
(не по номеру: длина преамбулы плавает), строки данных валидируются по
|
||
формату кода и денежным гейтам."""
|
||
import openpyxl
|
||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||
try:
|
||
ws = wb[wb.sheetnames[0]]
|
||
out = {"letter_ref": None, "npa_ref": None, "subject_name_form": None,
|
||
"zone_name": None, "rows": [],
|
||
"no_price": 0, "bad_price": 0, "bad_code": 0}
|
||
in_data = False
|
||
just_after_header = False
|
||
for rowno, r in enumerate(ws.iter_rows(values_only=True), 1):
|
||
r = tuple(r) + (None,) * (9 - len(r))
|
||
c1 = str(r[0]).strip() if r[0] is not None else ""
|
||
if not in_data:
|
||
if c1.startswith("Реквизиты письма Минстроя"):
|
||
out["letter_ref"] = _text_cell(r[6])
|
||
elif c1.startswith("Реквизиты нормативного правового акта"):
|
||
out["npa_ref"] = _text_cell(r[6])
|
||
elif c1.startswith("Наименование субъекта"):
|
||
out["subject_name_form"] = _text_cell(r[6])
|
||
elif c1.startswith("Наименование зоны"):
|
||
out["zone_name"] = _text_cell(r[6])
|
||
elif c1.startswith("Код ресурса"):
|
||
in_data = True
|
||
just_after_header = True
|
||
elif rowno > 60:
|
||
raise ValueError("шапка «Код ресурса…» не найдена в первых 60 строках")
|
||
continue
|
||
if just_after_header and _is_numbering_row(r):
|
||
just_after_header = False
|
||
continue
|
||
just_after_header = False
|
||
if not c1:
|
||
if any(v is not None and str(v).strip() for v in r):
|
||
out["bad_code"] += 1 # строка без кода, но с данными — брак
|
||
continue
|
||
if not CODE_RE.fullmatch(c1):
|
||
out["bad_code"] += 1
|
||
continue
|
||
name = _text_cell(r[1])
|
||
if not name:
|
||
out["bad_code"] += 1
|
||
continue
|
||
offsell, ok1 = _price_cell(r[3])
|
||
base, ok2 = _price_cell(r[4])
|
||
current, ok3 = _price_cell(r[7])
|
||
gidx, ok4 = _price_cell(r[8])
|
||
if not (ok1 and ok2 and ok3 and ok4):
|
||
out["bad_price"] += 1
|
||
continue
|
||
if offsell is None and base is None and current is None:
|
||
out["no_price"] += 1
|
||
continue
|
||
out["rows"].append((c1, name, _text_cell(r[2]) or "",
|
||
offsell, base, current,
|
||
_int_cell(r[5]), _text_cell(r[6]) or "", gidx))
|
||
if not in_data:
|
||
raise ValueError("шапка «Код ресурса…» не найдена")
|
||
return out
|
||
finally:
|
||
wb.close()
|
||
|
||
|
||
def _current_snapshot(dirpath: Path, fname: str) -> tuple[Path, dict] | None:
|
||
"""current-файл снапшота ext_state (корень каталога) + meta; фолбэк —
|
||
максимальная rev-N при потерянном current."""
|
||
f = dirpath / fname
|
||
meta = {}
|
||
mp = dirpath / "meta.json"
|
||
if mp.exists():
|
||
try:
|
||
meta = json.loads(mp.read_text(encoding="utf-8"))
|
||
except (OSError, ValueError):
|
||
meta = {}
|
||
if f.exists():
|
||
return f, meta
|
||
revs = sorted((d for d in dirpath.glob("rev-*") if (d / fname).exists()),
|
||
key=lambda d: int(re.match(r"rev-(\d+)", d.name).group(1)))
|
||
if revs:
|
||
rd = revs[-1]
|
||
rmeta = {}
|
||
if (rd / "meta.json").exists():
|
||
try:
|
||
rmeta = json.loads((rd / "meta.json").read_text(encoding="utf-8"))
|
||
except (OSError, ValueError):
|
||
pass
|
||
return rd / fname, rmeta
|
||
return None
|
||
|
||
|
||
def _load_reference(ext_dir: Path) -> tuple[dict, dict]:
|
||
try:
|
||
data = json.loads((ext_dir / "reference.json").read_text(encoding="utf-8"))
|
||
ref = data.get("ref", data)
|
||
return dict(ref.get("subjects") or {}), dict(ref.get("periods") or {})
|
||
except (OSError, ValueError):
|
||
return {}, {}
|
||
|
||
|
||
def _newest_csv(dirpath: Path) -> Path | None:
|
||
files = sorted(dirpath.glob("*.csv"))
|
||
return files[-1] if files else None
|
||
|
||
|
||
class _Cache:
|
||
"""Кэши дедупликации items/gosr_groups (номенклатура общая для всех зон)."""
|
||
|
||
def __init__(self, con: sqlite3.Connection):
|
||
self.con = con
|
||
self.items: dict[tuple, int] = {}
|
||
self.groups: dict[tuple, int] = {}
|
||
for iid, code, name, unit in con.execute("SELECT item_id, code, name, unit FROM items"):
|
||
self.items[(code, name, unit)] = iid
|
||
for gid, g, gn in con.execute("SELECT group_rowid, group_id, group_name FROM gosr_groups"):
|
||
self.groups[(g, gn)] = gid
|
||
|
||
def item(self, code: str, name: str, unit: str) -> int:
|
||
key = (code, name, unit)
|
||
iid = self.items.get(key)
|
||
if iid is None:
|
||
cur = self.con.execute(
|
||
"INSERT INTO items(code, name, unit, name_norm) VALUES(?,?,?,?)",
|
||
(code, name, unit, norm_text(name)))
|
||
iid = cur.lastrowid
|
||
self.items[key] = iid
|
||
return iid
|
||
|
||
def group(self, group_id: int | None, group_name: str) -> int | None:
|
||
if group_id is None and not group_name:
|
||
return None
|
||
key = (group_id, group_name)
|
||
gid = self.groups.get(key)
|
||
if gid is None:
|
||
cur = self.con.execute(
|
||
"INSERT INTO gosr_groups(group_id, group_name) VALUES(?,?)",
|
||
(group_id, group_name))
|
||
gid = cur.lastrowid
|
||
self.groups[key] = gid
|
||
return gid
|
||
|
||
|
||
def _load_salary_file(path: Path, zone_id: int) -> tuple[list, int]:
|
||
"""(строки, отброшено): фильтр по priceZoneId — чужая зона в файле не грузится."""
|
||
data = json.loads(path.read_text(encoding="utf-8"))
|
||
rows, dropped = [], 0
|
||
for it in data.get("items") or []:
|
||
pz = it.get("priceZoneId")
|
||
if pz is not None and int(pz) != zone_id:
|
||
dropped += 1
|
||
continue
|
||
try:
|
||
sal = float(str(it["salary"]).replace(",", "."))
|
||
except (KeyError, ValueError):
|
||
dropped += 1
|
||
continue
|
||
if sal <= 0:
|
||
dropped += 1
|
||
continue
|
||
rows.append((it.get("code"), it.get("salaryRateRank"),
|
||
it.get("salaryRateName"), sal))
|
||
return rows, dropped
|
||
|
||
|
||
def _load_csv_table(con: sqlite3.Connection, ext_dir: Path, summary: dict) -> None:
|
||
"""КСР (opendata/2) и справочник ценовых зон (opendata/6) — перезагрузка
|
||
целиком при смене sha256 файла."""
|
||
ksr = _newest_csv(ext_dir / "snapshots" / "fgis" / "opendata" / "2")
|
||
if ksr is None:
|
||
summary["warnings"].append("КСР-классификатор (opendata/2) не найден")
|
||
else:
|
||
sha = _sha256(ksr)
|
||
old = con.execute("SELECT value FROM meta WHERE key='ksr_sha256'").fetchone()
|
||
if old and old[0] == sha:
|
||
pass
|
||
else:
|
||
con.execute("DELETE FROM ksr")
|
||
with open(ksr, encoding="cp1251", newline="") as f:
|
||
rows = []
|
||
for i, row in enumerate(csv.reader(f)):
|
||
if i == 0 or len(row) < 4 or not row[1].strip():
|
||
continue
|
||
okpd2, code, name, unit = (row[0].strip(), row[1].strip(),
|
||
row[2].strip(), row[3].strip())
|
||
is_group = 1 if (not okpd2 and not unit) else 0
|
||
rows.append((okpd2 or None, code, name, unit or None,
|
||
is_group, norm_text(name)))
|
||
con.executemany(
|
||
"INSERT INTO ksr(okpd2, code, name, unit, is_group, name_norm) "
|
||
"VALUES(?,?,?,?,?,?)", rows)
|
||
con.execute("INSERT OR REPLACE INTO meta(key, value) VALUES('ksr_sha256', ?)", (sha,))
|
||
summary["ksr_rows"] = con.execute("SELECT COUNT(*) FROM ksr").fetchone()[0]
|
||
if summary["ksr_rows"] == 0:
|
||
summary["warnings"].append("КСР-файл есть, но загружено 0 строк")
|
||
|
||
zr = _newest_csv(ext_dir / "snapshots" / "fgis" / "opendata" / "6")
|
||
if zr is None:
|
||
summary["warnings"].append("справочник ценовых зон (opendata/6) не найден")
|
||
else:
|
||
sha = _sha256(zr)
|
||
old = con.execute("SELECT value FROM meta WHERE key='zones_ref_sha256'").fetchone()
|
||
if not (old and old[0] == sha):
|
||
con.execute("DELETE FROM zones_ref")
|
||
with open(zr, encoding="cp1251", newline="") as f:
|
||
rows = [(r[0].strip(), r[1].strip(), r[2].strip(), r[3].strip(),
|
||
r[4].strip() or None)
|
||
for i, r in enumerate(csv.reader(f, delimiter=";"))
|
||
if i > 0 and len(r) >= 5 and r[0].strip()]
|
||
con.executemany(
|
||
"INSERT INTO zones_ref(subject_code, subject_name, zone_name, "
|
||
"zone_center, municipalities) VALUES(?,?,?,?,?)", rows)
|
||
con.execute("INSERT OR REPLACE INTO meta(key, value) VALUES('zones_ref_sha256', ?)",
|
||
(sha,))
|
||
summary["zones_ref_rows"] = con.execute("SELECT COUNT(*) FROM zones_ref").fetchone()[0]
|
||
|
||
|
||
def _zone_keys(ext_dir: Path, subjects: list[str] | None) -> list[tuple[int, int, int, bool]]:
|
||
"""(subject, zone, period, has_form) — объединение деревьев split_form и salary."""
|
||
keys: dict[tuple[int, int, int], bool] = {}
|
||
for kind, has_form in (("split_form", True), ("salary", False)):
|
||
root = ext_dir / "snapshots" / "fgis" / kind
|
||
if not root.is_dir():
|
||
continue
|
||
for sd in root.iterdir():
|
||
if not (sd.is_dir() and sd.name.isdigit()):
|
||
continue
|
||
if subjects and sd.name not in subjects:
|
||
continue
|
||
for zd in sd.iterdir():
|
||
if not (zd.is_dir() and zd.name.isdigit()):
|
||
continue
|
||
for pd in zd.iterdir():
|
||
if not (pd.is_dir() and pd.name.isdigit()):
|
||
continue
|
||
k = (int(sd.name), int(zd.name), int(pd.name))
|
||
keys[k] = keys.get(k, False) or has_form
|
||
return sorted((s, z, p, hf) for (s, z, p), hf in keys.items())
|
||
|
||
|
||
def build(ext_dir: Path | str, out: Path | str, subjects: list[str] | None = None,
|
||
expected_rows_range: tuple[int, int] = (200_000, 320_000)) -> dict:
|
||
ext_dir = Path(ext_dir)
|
||
out = Path(out)
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
summary = {
|
||
"zones_total": 0, "zones_built": 0, "zones_skipped_unchanged": 0,
|
||
"zones_errors": [], "zones_suspicious": [],
|
||
"rows_loaded_total": 0, "rows_no_price_total": 0,
|
||
"rows_bad_price_total": 0, "rows_bad_code_total": 0,
|
||
"salary_loaded_total": 0, "salary_missing": 0,
|
||
"ksr_rows": 0, "zones_ref_rows": 0, "warnings": [],
|
||
}
|
||
subj_names, period_labels = _load_reference(ext_dir)
|
||
if not subj_names:
|
||
summary["warnings"].append("reference.json не прочитан — имена субъектов из самих форм")
|
||
|
||
con = sqlite3.connect(out)
|
||
con.executescript(DDL)
|
||
con.execute("PRAGMA journal_mode=WAL")
|
||
con.execute("PRAGMA synchronous=NORMAL")
|
||
_load_csv_table(con, ext_dir, summary)
|
||
con.commit()
|
||
cache = _Cache(con)
|
||
|
||
lo, hi = expected_rows_range
|
||
for subj, zone, period, has_form in _zone_keys(ext_dir, subjects):
|
||
summary["zones_total"] += 1
|
||
key = f"{subj}/{zone}/{period}"
|
||
t0 = time.time()
|
||
try:
|
||
if not has_form:
|
||
raise ValueError("есть salary, но нет сплит-формы (split_form отсутствует)")
|
||
snap = _current_snapshot(
|
||
ext_dir / "snapshots" / "fgis" / "split_form" / str(subj) / str(zone) / str(period),
|
||
"fgis_split_form.xlsx")
|
||
if snap is None:
|
||
raise ValueError("xlsx сплит-формы не найден (ни current, ни rev-N)")
|
||
xlsx_path, xmeta = snap
|
||
xlsx_sha = _sha256(xlsx_path) # фактический файл — источник истины
|
||
sal_path = (ext_dir / "snapshots" / "fgis" / "salary" / str(subj) / str(zone)
|
||
/ str(period) / "salary_registry.json")
|
||
sal_sha = _sha256(sal_path) if sal_path.exists() else None
|
||
if sal_sha is None:
|
||
summary["salary_missing"] += 1
|
||
|
||
old = con.execute(
|
||
"SELECT sha256, salary_sha256 FROM zone_snapshots "
|
||
"WHERE subject_id=? AND zone_id=? AND period_id=?",
|
||
(subj, zone, period)).fetchone()
|
||
need_form = old is None or old[0] != xlsx_sha
|
||
need_sal = (sal_sha is not None) and (old is None or old[1] != sal_sha)
|
||
if not need_form and not need_sal:
|
||
summary["zones_skipped_unchanged"] += 1
|
||
continue
|
||
|
||
notes = []
|
||
if xmeta.get("sha256") and xmeta["sha256"] != xlsx_sha:
|
||
notes.append("sha256 в meta.json не совпал с файлом")
|
||
|
||
fields: dict = {}
|
||
if need_form:
|
||
parsed = parse_split_form(xlsx_path)
|
||
loaded = len(parsed["rows"])
|
||
suspicious = 0
|
||
if not (lo <= loaded <= hi):
|
||
suspicious = 1
|
||
notes.append(f"rows_loaded={loaded} вне диапазона {lo}–{hi}")
|
||
sname = subj_names.get(str(subj)) or parsed["subject_name_form"] or f"субъект {subj}"
|
||
con.execute("BEGIN")
|
||
con.execute("DELETE FROM prices WHERE subject_id=? AND zone_id=? AND period_id=?",
|
||
(subj, zone, period))
|
||
con.executemany(
|
||
"INSERT INTO prices(subject_id, zone_id, period_id, item_id, "
|
||
"price_offsell, price_base_2022, price_current, group_rowid, gosr_index) "
|
||
"VALUES(?,?,?,?,?,?,?,?,?)",
|
||
[(subj, zone, period, cache.item(c, n, u), po, pb, pc,
|
||
cache.group(gid, gn), gi)
|
||
for c, n, u, po, pb, pc, gid, gn, gi in parsed["rows"]])
|
||
fields.update(
|
||
subject_name=sname,
|
||
zone_name=parsed["zone_name"] or f"зона {zone}",
|
||
period_label=period_labels.get(str(period)) or f"период {period}",
|
||
letter_ref=parsed["letter_ref"], salary_npa_ref=parsed["npa_ref"],
|
||
sha256=xlsx_sha, fetched_at=xmeta.get("fetched_at"),
|
||
rows_loaded=loaded, rows_no_price=parsed["no_price"],
|
||
rows_bad_price=parsed["bad_price"], rows_bad_code=parsed["bad_code"],
|
||
suspicious=suspicious)
|
||
summary["rows_loaded_total"] += loaded
|
||
summary["rows_no_price_total"] += parsed["no_price"]
|
||
summary["rows_bad_price_total"] += parsed["bad_price"]
|
||
summary["rows_bad_code_total"] += parsed["bad_code"]
|
||
if suspicious:
|
||
summary["zones_suspicious"].append(key)
|
||
if parsed["bad_price"] or parsed["bad_code"]:
|
||
notes.append(f"карантин: bad_price={parsed['bad_price']} "
|
||
f"bad_code={parsed['bad_code']}")
|
||
else:
|
||
con.execute("BEGIN")
|
||
|
||
if need_sal:
|
||
sal_rows, sal_dropped = _load_salary_file(sal_path, zone)
|
||
con.execute("DELETE FROM salary WHERE subject_id=? AND zone_id=? AND period_id=?",
|
||
(subj, zone, period))
|
||
con.executemany(
|
||
"INSERT INTO salary(subject_id, zone_id, period_id, code, rank, name, salary) "
|
||
"VALUES(?,?,?,?,?,?,?)",
|
||
[(subj, zone, period, c, rk, n, s) for c, rk, n, s in sal_rows])
|
||
fields.update(salary_sha256=sal_sha, salary_loaded=len(sal_rows))
|
||
summary["salary_loaded_total"] += len(sal_rows)
|
||
if sal_dropped:
|
||
notes.append(f"salary: отброшено {sal_dropped} записей (чужая зона/брак)")
|
||
|
||
# merge с существующей строкой: обновление только salary не должно
|
||
# стирать поля формы (и наоборот)
|
||
cur = con.execute("SELECT * FROM zone_snapshots WHERE subject_id=? AND zone_id=? "
|
||
"AND period_id=?", (subj, zone, period))
|
||
colnames = [d[0] for d in cur.description]
|
||
row = dict(zip(colnames, cur.fetchone() or [None] * len(colnames)))
|
||
row.update(subject_id=subj, zone_id=zone, period_id=period,
|
||
built_at=_utcnow(), **fields)
|
||
if notes:
|
||
row["note"] = "; ".join(notes)
|
||
con.execute(
|
||
f"INSERT OR REPLACE INTO zone_snapshots({','.join(colnames)}) "
|
||
f"VALUES({','.join('?' * len(colnames))})",
|
||
[row[c] for c in colnames])
|
||
con.commit()
|
||
summary["zones_built"] += 1
|
||
print(f"[fgis_ref] {key}: loaded={fields.get('rows_loaded', '-')} "
|
||
f"salary={fields.get('salary_loaded', '-')} "
|
||
f"({time.time() - t0:.1f}s)", flush=True)
|
||
except Exception as e: # noqa: BLE001 — одна зона не роняет сборку, но идёт в отчёт
|
||
con.rollback()
|
||
summary["zones_errors"].append(f"{key}: {e}")
|
||
print(f"[fgis_ref] ОШИБКА {key}: {e}", flush=True)
|
||
|
||
con.execute("INSERT OR REPLACE INTO meta(key, value) VALUES('schema_version', ?)",
|
||
(str(SCHEMA_VERSION),))
|
||
con.execute("INSERT OR REPLACE INTO meta(key, value) VALUES('built_at', ?)", (_utcnow(),))
|
||
con.commit()
|
||
con.close()
|
||
|
||
summary["ok"] = (not summary["zones_errors"] and not summary["zones_suspicious"]
|
||
and summary["rows_bad_price_total"] == 0
|
||
and summary["rows_bad_code_total"] == 0)
|
||
return summary
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser(description="Сборка справочной базы цен ФГИС ЦС (SQLite)")
|
||
ap.add_argument("--ext-dir", help="корень _external (дефолт — ext_state.ext_dir())")
|
||
ap.add_argument("--out", default="./fgis_ref.sqlite")
|
||
ap.add_argument("--subjects", help="список subjectId через запятую (подмножество)")
|
||
args = ap.parse_args()
|
||
|
||
if args.ext_dir:
|
||
ext = Path(args.ext_dir)
|
||
else:
|
||
try:
|
||
import ext_state
|
||
ext = ext_state.ext_dir()
|
||
except Exception: # noqa: BLE001
|
||
print("--ext-dir не задан и ext_state недоступен", file=sys.stderr)
|
||
return 2
|
||
subjects = [s.strip() for s in args.subjects.split(",")] if args.subjects else None
|
||
|
||
t0 = time.time()
|
||
s = build(ext, Path(args.out), subjects=subjects)
|
||
print("\n=== ИТОГ СБОРКИ fgis_ref ===")
|
||
print(f"зон обработано: {s['zones_total']}, собрано: {s['zones_built']}, "
|
||
f"пропущено (без изменений): {s['zones_skipped_unchanged']}")
|
||
print(f"строк цен загружено: {s['rows_loaded_total']}, без цены (все «-»): "
|
||
f"{s['rows_no_price_total']}")
|
||
print(f"КАРАНТИН: bad_price={s['rows_bad_price_total']} bad_code={s['rows_bad_code_total']}")
|
||
print(f"ставки ОТ: {s['salary_loaded_total']} (зон без salary: {s['salary_missing']})")
|
||
print(f"КСР: {s['ksr_rows']} строк; ценовых зон в справочнике: {s['zones_ref_rows']}")
|
||
for w in s["warnings"]:
|
||
print(f"ВНИМАНИЕ: {w}")
|
||
for z in s["zones_suspicious"]:
|
||
print(f"ПОДОЗРИТЕЛЬНАЯ ЗОНА: {z}")
|
||
for e in s["zones_errors"]:
|
||
print(f"ОШИБКА: {e}")
|
||
print(f"время: {time.time() - t0:.0f}s; ok={s['ok']}")
|
||
return 0 if s["ok"] else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|