"""M01 기계 저장 전 영향 목록(PLAN 848-5 · 요구서 889 6 장) — [저장] 전에 확인창이 부름 · 쓰기 없음. 몸 = 페이지 [저장] 묶음 그대로(`/save` 와 같은 꼴) — 기계 파일의 고침 줄만 봄(새 기계 · 지움 = 영향 없음). 고친 줄은 저장 때와 같은 손질(`Machine.fix` — 계수 다시 셈)을 거친 값으로 셈. 값 칸이 같으면 그 기계 뺌. 기계마다 = 쓰는 기초 직접 · 부름 사슬 · 그 칸을 따로 고쳐 둔 곳(기초 · 단가산출 ② 내 고침 · 위 층 ① 따로) · 쓰는 단가산출 층별 수 (프로젝트 사본 = 안 바뀜 · 따로 셈). 금액 = 고친 기계를 얹은 마스터(얕은 복사 — 정본 기억은 안 건드림)로 영향 기초(직접 + 부름 사슬)만 기본 옵션으로 전 · 후 다시 셈(`master_doc_calc.calc`) → 바뀐 기초 수 · 가장 크게(비율) 바뀐 다섯. """ from __future__ import annotations import copy from decimal import Decimal from typing import Any import master_doc_calc as mc # noqa: E402 (`store` 가 scripts 를 길에 둠) import master_doc_link as ml # noqa: E402 from M01_MasterData import M01_MasterData_Machine as machine from M01_MasterData import M01_MasterData_Machine_Uses as mu from M01_MasterData import M01_MasterData_Store as store TOP = 5 _BASE: dict[str, Any] = {} LINE_FIELDS = { "인력": "조종원", **{k: "조종원" for k in ("조종원", "조종원직종")}, "잡재료율": "잡품", } def same(a: Any, b: Any) -> bool: """값 같음 — 수는 수로(10000 = 10000.0) · 묶음 · 목록은 칸마다.""" if isinstance(a, dict) and isinstance(b, dict): return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a) if isinstance(a, list) and isinstance(b, list): return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b)) num = (int, float, Decimal) if isinstance(a, num) and isinstance(b, num) and not isinstance(a, bool): return Decimal(str(a)) == Decimal(str(b)) return a == b def changed_fields(old: dict, new: dict) -> list[str]: """값 칸 가운데 다른 것.""" a, b = old or {}, new or {} return [k for k in dict.fromkeys([*a, *b]) if not same(a.get(k), b.get(k))] def cover_hits(covers: dict[str, list[str]], names: tuple[str, ...], fields: list[str]) -> bool: """덮음 {입력 글: 칸} 이 그 기계(`names` = 원문번호 · 키)의 바뀐 칸을 덮는지.""" want = {LINE_FIELDS.get(f, f) for f in fields} return any(want & set(covers.get(n) or ()) for n in names) def _edits(batch: list[dict]) -> dict[str, dict]: """기계 고침 줄 {키: 손질한 줄} — 저장과 같은 `fix`(묶음은 복사본).""" part = next((p for p in batch if p.get("file") == machine.FILE), None) if not part: return {} part = copy.deepcopy(part) part["changes"] = [ c for c in part.get("changes") or [] if c.get("op") == "edit" and isinstance(c.get("row"), dict) ] machine.fix(part) return {str(c["key"]): c["row"] for c in part["changes"]} def _patched(whole, rows: dict[str, dict]): """고친 기계 줄을 얹은 마스터 — 색인 묶음만 새로(줄 · 다른 색인은 같이 씀).""" eq, nums = dict(whole.index.get("EQ") or {}), dict(whole.numbers.get("EQ") or {}) for key, row in rows.items(): old = eq.get(key) eq[key] = row code = str(row.get("원문번호") or "") if code and nums.get(code) is old: nums[code] = row out = copy.copy(whole) out.index = {**whole.index, "EQ": eq} out.numbers = {**whole.numbers, "EQ": nums} return out def _amount(doc: dict, links, memo: dict): got = mc.calc(doc, links, {}, memo=memo) return got.get("계") if "계" in got else got.get("결과") def impact(batch: list[dict]) -> dict[str, Any]: """{기계: [{키, 이름, 규격, 칸, 직접, 사슬, 고침{기초, 단가산출}, 단가산출{층: 수}}], 바뀜, 셈, 위}.""" whole = store.loaded()[1] stored = whole.index.get("EQ") or {} rows, out = {}, [] idx = mu.doc_index() for key, row in _edits(batch).items(): old = stored.get(key) fields = changed_fields((old or {}).get("값"), row.get("값")) if old else [] if not fields: continue rows[key] = {**row, "값": store._dec(row["값"])} code = str(old.get("원문번호") or "") direct = idx["직접"].get(code, set()) reach = mu.chain(direct, idx["부름"]) names = (code, key) sks = mu.sk_users(key, code, set()) out.append( { "키": key, "이름": old.get("이름"), "규격": old.get("규격"), "칸": fields, "직접": len(direct), "사슬": len(reach - direct), "고침": { "기초": sum(1 for c in idx["덮음"].values() if cover_hits(c, names, fields)), "단가산출": sum(1 for r in sks if cover_hits(r["덮음"], names, fields)), "위층": sum(1 for r in sks if cover_hits(r["위덮음"], names, fields)), }, "영향": reach, "단가산출키": (key, code), } ) if not out: return {"기계": [], "바뀜": 0, "셈": 0, "위": []} docs = idx["docs"] reach = set().union(*(m.pop("영향") for m in out)) if _BASE.get("docs") is not docs or _BASE.get("whole") is not whole: # 「전」 셈 = 판마다 한 번 _BASE.clear() _BASE.update(docs=docs, whole=whole, links=ml.Links(whole, docs), memo={}, amount={}) after, memo_b = ml.Links(_patched(whole, rows), docs), {} moved = [] for k in sorted(reach): if k not in _BASE["amount"]: _BASE["amount"][k] = _amount(docs[k], _BASE["links"], _BASE["memo"]) a, b = _BASE["amount"][k], _amount(docs[k], after, memo_b) if a != b: rate = ( abs(b - a) / abs(a) if isinstance(a, Decimal) and isinstance(b, Decimal) and a else Decimal(1) ) moved.append((rate, k, a, b)) moved.sort(key=lambda m: (-m[0], m[1])) changed = {m[1] for m in moved} for m in out: # 쓰는 단가산출 = 사본 · 덮음 · 바탕이 금액 바뀐 기초 key, code = m.pop("단가산출키") m["단가산출"] = mu.layer_counts(mu.sk_users(key, code, changed)) return { "기계": out, "바뀜": len(moved), "셈": len(reach), "위": [ { "키": k, "이름": docs[k].get("이름"), "단위": docs[k].get("결과단위"), "전": a, "후": b, } for _rate, k, a, b in moved[:TOP] ], }