fix(ТСН): сборка не падает на повторе шифра внутри одной книги; apply не берёт сборку с проваленным аудитом
- В справочнике машин позиция 1-4-1 напечатана дважды (разные группы, цены 58,48 и 68,87): такой повтор — дефект источника, строка идёт в карантин, сборка остаётся годной. Дубли между разными документами по-прежнему ошибка сборки. - apply отказывается подменять живую базу, если staging собрался с audit_ok=0 (без --force). Раньше проверялся только verify_db, и база с проваленным аудитом могла уехать в работу. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -120,7 +120,7 @@ def build(snapshots: os.PathLike | str, out_path: os.PathLike | str) -> dict:
|
|||||||
con.execute("INSERT INTO meta VALUES('built_at',?)", (built_at,))
|
con.execute("INSERT INTO meta VALUES('built_at',?)", (built_at,))
|
||||||
|
|
||||||
seen: dict[tuple, float | None] = {}
|
seen: dict[tuple, float | None] = {}
|
||||||
seen_items: dict[str, float] = {}
|
seen_items: dict[str, tuple[float, int]] = {}
|
||||||
src_id = 0
|
src_id = 0
|
||||||
docs_n = works_n = values_n = items_n = 0
|
docs_n = works_n = values_n = items_n = 0
|
||||||
for meta, extract in _docs(snapshots):
|
for meta, extract in _docs(snapshots):
|
||||||
@@ -161,11 +161,23 @@ def build(snapshots: os.PathLike | str, out_path: os.PathLike | str) -> dict:
|
|||||||
for it in extract.get("items", []):
|
for it in extract.get("items", []):
|
||||||
key = it["code"]
|
key = it["code"]
|
||||||
price = it.get("price")
|
price = it.get("price")
|
||||||
if key in seen_items and abs((seen_items[key] or 0) - price) > 0.001:
|
if key in seen_items:
|
||||||
problems.append(f"ресурс {key} с разными ценами: "
|
prev_price, prev_source = seen_items[key]
|
||||||
f"{seen_items[key]} и {price}")
|
if abs((prev_price or 0) - price) > 0.001:
|
||||||
|
if prev_source == source_id:
|
||||||
|
# Повтор шифра ВНУТРИ одной книги — дефект источника
|
||||||
|
# (в справочнике машин позиция 1-4-1 напечатана дважды):
|
||||||
|
# строка в карантин, сборка остаётся годной.
|
||||||
|
con.execute(
|
||||||
|
"INSERT INTO quarantine(release_id, source_id, kind, code,"
|
||||||
|
" raw, reason) VALUES(1,?,?,?,?,?)",
|
||||||
|
(source_id, "price", key, str(price),
|
||||||
|
f"шифр повторяется в книге с другой ценой {prev_price}"))
|
||||||
|
else:
|
||||||
|
problems.append(f"ресурс {key} в разных документах с разными "
|
||||||
|
f"ценами: {prev_price} и {price}")
|
||||||
continue
|
continue
|
||||||
seen_items[key] = price
|
seen_items[key] = (price, source_id)
|
||||||
cur = con.execute(
|
cur = con.execute(
|
||||||
"INSERT OR IGNORE INTO price_items(release_id, source_id, book, kind,"
|
"INSERT OR IGNORE INTO price_items(release_id, source_id, book, kind,"
|
||||||
" code, name, unit, price, page) VALUES(1,?,?,?,?,?,?,?,?)",
|
" code, name, unit, price, page) VALUES(1,?,?,?,?,?,?,?,?)",
|
||||||
@@ -235,6 +247,15 @@ def apply(staging: os.PathLike | str, target: os.PathLike | str, force: bool = F
|
|||||||
check = tsn_ref.verify_db(staging)
|
check = tsn_ref.verify_db(staging)
|
||||||
if not check.get("ok"):
|
if not check.get("ok"):
|
||||||
return {"ok": False, "problems": [f"staging не прошёл проверку: {check.get('problem')}"]}
|
return {"ok": False, "problems": [f"staging не прошёл проверку: {check.get('problem')}"]}
|
||||||
|
con = sqlite3.connect(staging)
|
||||||
|
try:
|
||||||
|
audit_ok = con.execute("SELECT audit_ok FROM release").fetchone()[0]
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
if not audit_ok and not force:
|
||||||
|
return {"ok": False, "problems": [
|
||||||
|
"сборка не прошла собственный аудит (audit_ok=0): дубли с разными ценами — "
|
||||||
|
"живую базу не подменяю без --force"]}
|
||||||
if target.exists() and not force:
|
if target.exists() and not force:
|
||||||
old = tsn_ref.verify_db(target)
|
old = tsn_ref.verify_db(target)
|
||||||
if old.get("ok") and check.get("works", 0) < old.get("works", 0) * 0.7:
|
if old.get("ok") and check.get("works", 0) < old.get("works", 0) * 0.7:
|
||||||
|
|||||||
@@ -202,3 +202,40 @@ def test_build_refuses_same_resource_with_two_prices(tmp_path, monkeypatch):
|
|||||||
report = build_mod.build(tmp_path / "ext", tmp_path / "x.sqlite")
|
report = build_mod.build(tmp_path / "ext", tmp_path / "x.sqlite")
|
||||||
assert report["ok"] is False
|
assert report["ok"] is False
|
||||||
assert "разными ценами" in " ".join(report["problems"])
|
assert "разными ценами" in " ".join(report["problems"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_repeated_position_within_one_book_is_quarantined_not_fatal(tmp_path, monkeypatch):
|
||||||
|
"""В справочнике машин шифр 2.1-4-1 напечатан дважды (разные группы, разные цены).
|
||||||
|
Это дефект источника: строка в карантин, сборка остаётся годной."""
|
||||||
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path / "ext")
|
||||||
|
(tmp_path / "ext").mkdir()
|
||||||
|
_snap(tmp_path / "ext", "mach", "machine_book", _items_extract([
|
||||||
|
{"code": "2.1-4-1", "name": "Погрузчик", "unit": "маш.-ч", "price": 58.48, "page": 10},
|
||||||
|
{"code": "2.1-4-1", "name": "Погрузчик", "unit": "маш.-ч", "price": 68.87, "page": 10},
|
||||||
|
]), book="ТСН-2001.2")
|
||||||
|
report = build_mod.build(tmp_path / "ext", tmp_path / "x.sqlite")
|
||||||
|
assert report["ok"] is True, report["problems"]
|
||||||
|
con = sqlite3.connect(tmp_path / "x.sqlite")
|
||||||
|
try:
|
||||||
|
assert con.execute("SELECT COUNT(*) FROM price_items").fetchone()[0] == 1
|
||||||
|
assert con.execute("SELECT COUNT(*) FROM quarantine").fetchone()[0] == 1
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_apply_refuses_build_that_failed_its_own_audit(tmp_path, monkeypatch):
|
||||||
|
"""Сборка с audit_ok=0 не должна подменять живую базу без --force."""
|
||||||
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path / "ext")
|
||||||
|
(tmp_path / "ext").mkdir()
|
||||||
|
_snap(tmp_path / "ext", "a", "rate_book", _rate_extract(pz=30.0))
|
||||||
|
second = _rate_extract(pz=45.0)
|
||||||
|
second["works"][0]["ot"], second["works"][0]["em"] = 15.0, 30.0
|
||||||
|
_snap(tmp_path / "ext", "b", "rate_book", second)
|
||||||
|
staging = tmp_path / "bad.sqlite"
|
||||||
|
rep = build_mod.build(tmp_path / "ext", staging)
|
||||||
|
assert rep["ok"] is False
|
||||||
|
target = tmp_path / "live.sqlite"
|
||||||
|
target.write_bytes(b"old db content")
|
||||||
|
got = build_mod.apply(staging, target)
|
||||||
|
assert got["ok"] is False and "аудит" in " ".join(got["problems"]).lower()
|
||||||
|
assert target.read_bytes() == b"old db content"
|
||||||
|
|||||||
Reference in New Issue
Block a user