refactor(853-1): M01 화면 0 서버 길 15 와 본체 걷음 — 묶음 ② 고친 파일(앞 커밋 654b75b5c 는 지운 파일만 담김)

- 길 지움(화면 TS · 다른 서버 모듈 · 시험 세 곳에서 다시 찾음 · /openapi.json 524 → 509 뜻한 15 만): GET /groups · /sections · /table/options · /logic/combos · POST /logic/new · /logic/edit · /logic/delete · /logic/draft · /logic/sheet · /logic/sheet/check · /logic/equation(+ preview · links · save) · /logic/doc/links
- 본체 지움: M01_MasterData_Sheet.py · Equation.read · preview · save · Store_Make.sections · _counts · table_options · logic_edit · logic_delete · _own_only · logic_draft · Store.groups · Store_Combo.combo_preview · scripts/master_draft.py(지운 /logic/draft 만 부름)
- 남김: Equation.export_row · edit_row · links(M02 Sangeun_Equation 이 부름) · Doc.candidates(M02 /doc/links) · Store_Make._all_sections(M02 Hopyo_Clause) · logic_new(복사 · 수식 저장이 씀) · combos_of_logic(Doc.users) · combo_inputs(알약 규칙 입구 · 시험) · master_combo.run(M02 시험 대조 값) · /alias/suggest(main.py 가 따로 끼움 · 승인 화면과 한 벌)
- 화면 입구 지움: Api_Fetch.fetchGroups · GroupInfo · fetchSubs · Logic_Api.draftLogic + Draft 타입 6
- 시험: test_m01_draft 지움(죽은 해석기 · 길만 봄) · test_794_1 시트 길 시험 지우고 /save 다시 셈 시험만 남김 · test_796_1 수식 길 시험 지움 · test_800_2 는 살아 있는 export_row · edit_row 로 같은 셈 · test_m01_make 는 죽은 길 대신 /save · logic_new 로 같은 결과 · test_m01_combo 미리 보기 시험 지움 · /logic/combos 는 combos_of_logic 로 · test_m01_api · test_802_3 · test_799_2 · test_717_1(+helper) 죽은 길 줄만 고침

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:27:44 +09:00
co-authored by Claude Opus 5.5
parent 654b75b5cc
commit 8c3801e707
17 changed files with 77 additions and 639 deletions
@@ -10,12 +10,6 @@ import { logicApiPaths } from "./M01_MasterData_UI_Logic_Api";
/** 줄·표 한 개 — 파일 그대로(한글 칸). */
export type Row = Record<string, unknown>;
export interface GroupInfo {
group: string;
files: number;
rows: number;
}
export interface FileInfo {
file: string;
book: string | null;
@@ -115,9 +109,6 @@ async function get<T>(
return body;
}
export const fetchGroups = async (): Promise<GroupInfo[]> =>
(await get<{ groups: GroupInfo[] }>("/groups", {})).groups;
export const fetchFiles = async (group: string): Promise<FileInfo[]> =>
(await get<{ files: FileInfo[] }>(`/groups/${encodeURIComponent(group)}/files`, {})).files;
@@ -153,9 +144,6 @@ export const fetchSubsAll = (where: {
}): Promise<{ subs: SubInfo[]; states?: string[] }> =>
get("/subs", { file: where.file ?? "", group: where.group ?? "" });
export const fetchSubs = async (where: { file?: string; group?: string }): Promise<SubInfo[]> =>
(await fetchSubsAll(where)).subs;
export const fetchTables = (
group: string,
sub: string,
-40
View File
@@ -11,7 +11,6 @@ from __future__ import annotations
from typing import Any
from M01_MasterData import M01_MasterData_Store as store
from M01_MasterData import M01_MasterData_Store_Make as make
_ERR = (store.cm.mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError)
@@ -59,45 +58,6 @@ def edit_row(whole, row: dict, edits: list) -> tuple[dict, list[str]]:
return new, why
def read(key: str, inputs: dict | None = None) -> dict:
whole = store.loaded()[1]
try:
return {"ok": True, "수식": export_row(whole, whole.logic(key), inputs)}
except _ERR as e:
return {"ok": False, "reason": str(e) or type(e).__name__}
def preview(key: str, edits: list, inputs: dict | None = None) -> dict:
"""고침 미리 셈(저장 없음) — {되나, 까닭, 줄, 수식, 전, 후}."""
whole = store.loaded()[1]
row = whole.logic(key)
new, why = edit_row(whole, row, edits)
if why:
return {"되나": False, "까닭": why}
try:
before = meq.export(whole, key, _given(inputs))["합계"]
eq = export_row(whole, new, inputs)
except _ERR as e:
return {"되나": False, "까닭": [f"셈 막힘 — {e}"]}
return {"되나": True, "까닭": [], "줄": new, "수식": eq, "전": before, "후": eq["합계"]}
def links(ask: dict) -> dict:
"""새 기호 연결 후보(800-3) — {갈래: 표 | 요소 | 로직, 검색, 분류?} → {후보, 더있음} · 읽기만."""
return link.candidates(store.loaded()[1], ask)
def save(
key: str, edits: list, inputs: dict | None = None, version: str = "", confirmed: bool = False
) -> dict:
"""고침 저장 — 검사 통과 · 기존 M01 `/save`(정본 = 개정확인 · 판 다르면 409)."""
got = store.logic(key)
if version and version != got["version"]:
raise store.StoreError(409, {"stale": [got["file"]]})
new, why = edit_row(store.loaded()[1], got["logic"], edits)
if why:
raise store.StoreError(400, {"까닭": why})
change = {"op": "edit", "key": key, "row": new}
part = {"file": got["file"], "version": got["version"], "changes": [change]}
out = make.save([part], confirmed)
return {**out, **read(key, inputs)}
-142
View File
@@ -13,14 +13,11 @@ from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from M01_MasterData import M01_MasterData_Doc as doc_screen
from M01_MasterData import M01_MasterData_Equation as equation
from M01_MasterData import M01_MasterData_Machine as machine
from M01_MasterData import M01_MasterData_Machine_Impact as machine_impact
from M01_MasterData import M01_MasterData_Machine_Uses as machine_uses
from M01_MasterData import M01_MasterData_Parts as parts
from M01_MasterData import M01_MasterData_Sheet as line_sheet
from M01_MasterData import M01_MasterData_Store as store
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
from M01_MasterData import M01_MasterData_Store_List as store_list
from M01_MasterData import M01_MasterData_RateSheet as rate_sheet
from M01_MasterData import M01_MasterData_Store_Make as make
@@ -62,29 +59,12 @@ class SaveBody(BaseModel):
개정확인: bool = False # 로직 정본 줄 고침 = 「원문 개정 반영」 확인(713-1) · 없으면 409
class NewLogic(BaseModel):
logic: dict[str, Any]
owner: str = make.OWNERS[0]
class CopyLogic(BaseModel):
key: str
이름: str = ""
owner: str = make.OWNERS[0]
class EditLogic(BaseModel):
key: str
version: str
logic: dict[str, Any]
owner: str = ""
class DeleteLogic(BaseModel):
key: str
version: str
class FormulaLogic(BaseModel):
"""복사해서 만들기 — 별칭 꼴 식이 든 로직 줄과 그 별칭표(되돌릴 원문)."""
@@ -102,14 +82,6 @@ class FormulaPreview(BaseModel):
별칭: list[dict[str, Any]] = []
class DraftLogic(BaseModel):
text: str # 줄로 적은 식 — 줄마다 「이름 = 식」
decided: dict[str, Any] = {} # 변수마다 정한 것 {이름: {무엇, 단위, 비목, 요소·찾기·값}}
head: dict[str, Any] | None = None # 로직 머리(이름 · 결과단위 …) — 주면 로직 줄까지
save: bool = False
owner: str = make.OWNERS[0]
def _num(v):
"""Decimal → JSON 수(그냥 두면 글자로 나감)."""
if isinstance(v, Decimal):
@@ -128,11 +100,6 @@ def _call(fn, *args):
raise HTTPException(status_code=e.status, detail=e.detail) from e
@router.get("/groups")
def get_groups() -> dict:
return {"groups": _call(store.groups)}
@router.get("/groups/{group}/files")
def get_files(group: str) -> dict:
"""`판정규` = 머리 판의 해(「2026-01-01」 · 「2026」 → 「2026」) · 읽을 때 파생(파일 안 씀)."""
@@ -190,20 +157,6 @@ def get_table(file: str, key: str) -> dict:
return {**out, "기준파생": _num(mbs.basis(out["table"]))}
@router.get("/table/options")
def get_table_options(file: str, key: str) -> dict:
"""표 조건 칸의 값만 — 줄을 통째로 받지 않음."""
return _call(make.table_options, file, key)
@router.get("/sections")
def get_sections(
book: str, division: str = "", chapter: str = "", q: str = "", limit: int = 200
) -> dict:
"""원문 절 목록 — 만들기 첫 걸음."""
return _call(make.sections, book, division, chapter, q, limit)
@router.get("/logics")
def get_logics(
sub: str = "", detail: str = "", q: str = "", blocked: int | None = None, owner: str = ""
@@ -338,26 +291,11 @@ def post_save(body: SaveBody) -> dict:
return _call(make.save, [f.model_dump() for f in body.files], body.개정확인)
@router.post("/logic/new")
def post_logic_new(body: NewLogic) -> dict:
return _call(make.logic_new, body.logic, body.owner)
@router.post("/logic/copy")
def post_logic_copy(body: CopyLogic) -> dict:
return _call(make.logic_copy, body.key, body.이름, body.owner)
@router.post("/logic/edit")
def post_logic_edit(body: EditLogic) -> dict:
return _call(make.logic_edit, body.key, body.version, body.logic, body.owner)
@router.post("/logic/delete")
def post_logic_delete(body: DeleteLogic) -> dict:
return _call(make.logic_delete, body.key, body.version)
@router.get("/logic/formula")
def get_logic_formula(key: str) -> dict:
"""복사해서 만들기 — 로직 한 줄을 별칭 꼴 식 묶음으로."""
@@ -376,73 +314,6 @@ def post_logic_formula_preview(body: FormulaPreview) -> dict:
return _call(make.logic_formula_preview, body.로직, body.별칭)
@router.post("/logic/draft")
def post_logic_draft(body: DraftLogic) -> dict:
"""식으로 새 로직 만들기 — 변수 뽑기 · 검사 · 로직 줄로 옮기기(`save` 면 저장까지)."""
return _call(make.logic_draft, body.text, body.decided, body.head, body.save, body.owner)
class SheetRow(BaseModel):
row: dict[str, Any]
class SheetCheck(BaseModel):
row: dict[str, Any]
갈래: Literal["중간", "호표", "덧줄"]
차례: int
식: str
@router.post("/logic/sheet")
def post_logic_sheet(body: SheetRow) -> dict:
"""줄 식 시트(794-1) — 줄마다 이름 꼴 식 글 · 식 칸 이름표(셈 · 쓰기 없음)."""
return _call(line_sheet.names, body.row)
@router.post("/logic/sheet/check")
def post_logic_sheet_check(body: SheetCheck) -> dict:
"""시트 식 칸 칠 때마다 — {되나, 까닭, 식(엔진), 글(이름 꼴)} · 저장 때와 같은 엔진 검사."""
return _call(line_sheet.check, body.row, body.갈래, body.차례, body.식)
class EquationBody(BaseModel):
key: str
inputs: dict[str, Any] = {}
고침: list[dict[str, Any]] = []
version: str = ""
개정확인: bool = False
@router.post("/logic/equation")
def post_logic_equation(body: EquationBody) -> dict:
"""수식 탭(796-1) — 줄마다 이름식 · 값식 나무 · 풀이 · 변수표 · 합계(셈 · 쓰기 없음)."""
return _call(equation.read, body.key, body.inputs)
@router.post("/logic/equation/preview")
def post_logic_equation_preview(body: EquationBody) -> dict:
"""수식 고침 미리 셈 — {되나, 까닭, 줄, 수식, 전, 후} · 저장 안 함."""
return _call(equation.preview, body.key, body.고침, body.inputs)
class LinksBody(BaseModel):
갈래: str
검색: str = ""
분류: str = "인력"
@router.post("/logic/equation/links")
def post_logic_equation_links(body: LinksBody) -> dict:
"""새 기호 연결 후보(800-3) — 표 · 요소 · 로직 이름 찾기(읽기만)."""
return _call(equation.links, body.model_dump())
@router.post("/logic/equation/save")
def post_logic_equation_save(body: EquationBody) -> dict:
"""수식 고침 저장 — 검사 통과 뒤 `/save` 길(정본 = 개정확인 · 판 다르면 409)."""
return _call(equation.save, body.key, body.고침, body.inputs, body.version, body.개정확인)
# ── 수식 문서(802-3) — 단가산출 기초 정본 · 화면은 같은 계산기로 즉시 셈 ──
class DocBody(BaseModel):
문서: dict[str, Any]
@@ -486,20 +357,7 @@ def post_logic_remove(body: RemoveBody) -> dict:
return _call(doc_screen.remove, body.key, body.file, body.version, body.개정확인)
@router.post("/logic/doc/links")
def post_logic_doc_links(body: LinksBody) -> dict:
"""연결 후보 — 요소 · 표 · 단가산출(수식 문서) 이름 찾기(읽기만)."""
return _call(doc_screen.candidates, body.model_dump())
@router.get("/logic/doc/table")
def get_logic_doc_table(key: str) -> dict:
"""표 하나 — 조건 · 칸 고르기(읽기만)."""
return _call(doc_screen.table, key)
# ── 일위대가 조합 — 조합 길은 M02 층 길(`/api/m02/layers/{layer}/combos` · PLAN 27-2a) ──
@router.get("/logic/combos")
def get_logic_combos(key: str) -> dict:
"""이 단가산출 로직을 담은 조합 — 로직 쪽에서 거꾸로 봄."""
return _call(combo_store.combos_of_logic, key)
-10
View File
@@ -105,16 +105,6 @@ def _book(data: dict) -> str | None:
return data.get("원문") if isinstance(data.get("원문"), str) else None
def groups() -> list[dict]:
out = {g: {"group": g, "files": 0, "rows": 0} for g in cm.mf.GROUPS}
for data in cm.load(folder=FOLDER).values():
slot = out.get(data.get("그룹"))
if slot:
slot["files"] += 1
slot["rows"] += len(data.get(items_key(data)) or [])
return list(out.values())
def chapter_order(data: dict) -> int:
"""장 파일 머리 「차례」 — 없으면(자체 등) 맨 뒤."""
return data.get("차례") or 9999
@@ -253,23 +253,3 @@ def combo_delete(key: str, version: str) -> dict:
if store.read(FILE)[1] != version:
raise store.StoreError(409, {"stale": [FILE]})
return _write([{"op": "delete", "key": key}], version)
# ── 미리 보기 ─────────────────────────────────────────────────────────
def combo_preview(combo_: dict | str, inputs: dict | None = None) -> dict:
"""담은 로직마다 그 자리 입력값으로 값을 뽑아 비목별로 갈라 합침 — **저장하지 않음**.
`combo_` = 조합 줄 통째(저장 전 화면 상태) 또는 저장된 조합 키.
`inputs` = {로직 키: {입력 이름: 값}}.
"""
files = cm.load(folder=store.FOLDER)
whole = cm.mf.Master(files)
row = _find(_read()[0], combo_) if isinstance(combo_, str) else store._dec(combo_)
if not isinstance(row, dict):
raise store.StoreError(400, "조합 줄이 묶음 아님")
given = {
str(k): {kk: store._dec(vv) for kk, vv in (v or {}).items()}
for k, v in (inputs or {}).items()
}
got = mcb.run(whole, row, given)
return {"키": row.get("키"), "이름": row.get("이름"), "단위": row.get("단위"), **got}
-113
View File
@@ -69,42 +69,6 @@ def _all_sections(book: str) -> list[dict]:
return out
def _counts() -> dict[tuple[str, str], list[int]]:
"""(구분, 절 번호) → [표 수, 로직 수] — 아래 절까지 세도록 절 번호의 모든 앞마디에 얹음."""
out: dict[tuple[str, str], list[int]] = {}
for data in store.loaded()[0].values():
group = data.get("그룹")
at = 0 if group in cm.mf.TABLE_GROUPS else 1 if group == "로직" else None
if at is None:
continue
for row in data.get(store.items_key(data)) or []:
number, sub = str(row.get("원문번호") or ""), str(row.get("구분") or "")
parts = number.split("-")
for upto in range(1, len(parts) + 1):
out.setdefault((sub, "-".join(parts[:upto])), [0, 0])[at] += 1
return out
def sections(book: str, division: str = "", chapter: str = "", q: str = "", limit: int = 200):
"""원문 절 목록 — 만들기 첫 걸음(절을 고르면 그 절의 표만 보임)."""
if book not in BOOKS:
raise store.StoreError(404, f"없는 원문 「{book}」")
if division and division not in cm.DIVISIONS:
raise store.StoreError(404, f"없는 부문 「{division}」")
counts, hits = _counts(), []
for one in _all_sections(book):
if division and one["division"] != division:
continue
if chapter and one["chapterNo"] != str(chapter).zfill(2):
continue
if q and q.lower() not in f"{one['section']} {one['title']}".lower():
continue
sub = " ".join(x for x in (book, one["division"]) if x)
tables, logics = counts.get((sub, one["section"]), [0, 0])
hits.append({**one, "tables": tables, "logics": logics})
return {"total": len(hits), "sections": hits[: min(max(limit, 1), 1000)]}
# ── 로직 원문(출처 글 → 품셈 본문 절) ──────────────────────────────────
_NUMBER = re.compile(r"(?<![\d-])(\d+(?:-\d+)+)(?![\d-])(?:\s+(주[①-⑳]?|\d{1,2})(?![\d-]))?")
_ESCAPE = re.compile(r"\\([.\-*_()#\[\]>~`])") # 마크다운 이스케이프 `\.` `\-` …
@@ -242,30 +206,6 @@ def source(src: str) -> dict:
return {"source": src, "found": found}
# ── 표 조건 값 ─────────────────────────────────────────────────────────
def table_options(file: str, key: str) -> dict:
"""표 조건 칸의 값만 — 표 몸을 통째로 받지 않으려는 자리(만들기 입력 제안)."""
table = store.table(file, key)["table"]
conds = table.get("조건") or {}
values: dict[str, list] = {name: [] for name in conds}
for row in table.get("줄") or []:
for name in conds:
value = row.get(name)
if value is None or value in values[name]:
continue
values[name].append(value)
return {
"file": file,
"key": key,
"이름": table.get("이름"),
"조건": conds,
"범위규칙": table.get("범위규칙"),
"값칸": table.get("값칸") or {},
"count": len(table.get("줄") or []),
"값": values,
}
# ── 자체 로직 ──────────────────────────────────────────────────────────
def _own_path() -> Path:
return store.FOLDER / OWN
@@ -346,11 +286,6 @@ def _find(key: str) -> tuple[str, dict]:
return got["file"], got["logic"]
def _own_only(file: str, key: str) -> None:
if file != OWN:
raise store.StoreError(403, f"정본 로직 「{key}」 은 못 고침 — 본뜬 뒤 고칠 것")
def _clean(logic: dict, owner: str, key: str | None = None) -> dict:
"""서버가 잡는 칸 — 키·소유·구분·상세구분. 화면이 보낸 것은 안 씀."""
if not isinstance(logic, dict) or not str(logic.get("이름") or "").strip():
@@ -422,16 +357,6 @@ def logic_copy(key: str, 이름: str = "", owner: str = OWNERS[0]) -> dict:
return logic_new(copy, owner)
def logic_edit(key: str, version: str, logic: dict, owner: str = "") -> dict:
file, row = _find(key)
_own_only(file, key)
if store.read(OWN)[1] != version:
raise store.StoreError(409, {"stale": [OWN]})
fixed = _clean(logic, owner or str(row.get("소유") or OWNERS[0]), key)
done = _write([{"op": "edit", "key": key, "row": fixed}])
return {**done, "logic": store.logic(key)["logic"]}
# ── 복사해서 만들기 ────────────────────────────────────────────────────
def logic_formula(key: str) -> dict:
"""로직 한 줄을 별칭 꼴 식 묶음으로 펴 보임 — 되돌릴 원문은 `별칭` 에 그대로(정본은 안 바뀜)."""
@@ -469,41 +394,3 @@ def logic_from_formula(
if 본뜬키:
row["비고"] = " · ".join(x for x in (str(row.get("비고") or ""), f"{본뜬키} 를 본뜸") if x)
return logic_new(row, owner)
def logic_delete(key: str, version: str) -> dict:
file, _ = _find(key)
_own_only(file, key)
if store.read(OWN)[1] != version:
raise store.StoreError(409, {"stale": [OWN]})
return _write([{"op": "delete", "key": key}])
# ── 식으로 만들기 ──────────────────────────────────────────────────────
def logic_draft(
text: str,
decided: dict | None = None,
head: dict | None = None,
save: bool = False,
owner: str = OWNERS[0],
) -> dict:
"""줄로 적은 식 → 변수 · 검사(`_화면_계약.md` 8장).
`head`(이름 · 결과단위 …)가 오면 로직 한 줄까지 미리 보이고, `save` 면 다 정해진 때만
자체 로직으로 저장(키 GX 는 서버) · 덜 정했거나 걸리면 422 로 아무것도 안 씀.
"""
import master_draft as draft # store 가 scripts 를 길에 올린 뒤라야 함
got = draft.read(text, decided, head)
if head is None:
return {**got, "logic": None}
row, bad = draft.옮기기(text, decided, head)
got["문제"] = got["문제"] + [x for x in bad if x not in got["문제"]]
got["다됨"] = not got["문제"]
if save and got["문제"]:
raise store.StoreError(
422, {"errors": [f"{x['줄']}줄 · {x['말']}" for x in got["문제"]], "문제": got["문제"]}
)
if not save:
return {**got, "logic": row or None}
return {**got, **logic_new(row, owner)}
@@ -380,66 +380,3 @@ export const previewLogicFormula = (
로직: LogicRow,
별칭: FormulaAlias[],
): Promise<{ logic: LogicRow }> => request("/logic/formula/preview", { 로직, 별칭 });
/* ── 식으로 새 로직 만들기(계약 7장) ── */
export interface DraftFind {
표: string;
값칸: string;
조건: Record<string, string>;
}
/** 변수마다 정한 것 */
export interface DraftDecided {
무엇?: string;
단위?: string;
비목?: string;
요소?: string;
찾기?: DraftFind;
값?: string;
설명?: string;
}
export interface DraftVar {
이름: string;
처음: number;
갈래: "정의됨" | "미정" | "비목합";
정의줄: number | null;
쓰임: number[];
무엇: string | null;
단위: string | null;
비목: string | null;
정할것: string[];
}
export interface DraftProblem {
줄: number | null;
자리: number | null;
갈래: string;
말: string;
}
export interface DraftAnswer {
줄: { 줄: number; 이름: string; 식: string; 앞: number }[];
변수: DraftVar[];
결과: string;
문제: DraftProblem[];
다됨: boolean;
logic: LogicRow | null;
/** 저장했을 때만 */
file?: string;
version?: string;
key?: string;
}
export interface DraftHead {
이름: string;
결과단위: string;
원문번호?: string;
출처?: string;
비고?: string;
끝수?: string;
}
/** 검사·미리보기 · `save` 면 자체 로직(키 `GX`)으로 저장 — 문제가 있으면 422 */
export const draftLogic = (body: {
text: string;
decided: Record<string, DraftDecided>;
head?: DraftHead;
save?: boolean;
owner?: string;
}): Promise<DraftAnswer> => request("/logic/draft", body);
@@ -32,7 +32,7 @@ async function round(tag) {
await rows.fetchRows("기계.json", 1, 5, "q");
await rows.fetchPick("price", "q");
await note.loadTable(`T-${tag}`);
await rows.fetchGroups(); // 관리자 길 — 늘 /m01
await rows.fetchFiles("g"); // 관리자 길 — 늘 /m01
await api.saveFiles([]); // 저장 — 늘 /m01
return urls.splice(0).map((u) => u.split("?")[0]);
}
+1 -1
View File
@@ -40,7 +40,7 @@ def test_길_주입_없으면_m01_있으면_넘긴_길() -> None:
"/m02/calc-x/calc",
"/m02/calc-x/text",
]
assert admin == ["/m01/groups", "/m01/save"] # 관리자 · 저장 길은 늘 M01
assert admin == ["/m01/groups/g/files", "/m01/save"] # 관리자 · 저장 길은 늘 M01
@pytest.fixture(scope="module")
+9 -46
View File
@@ -1,9 +1,8 @@
# ruff: noqa: E501
"""794-1 M01 관리자 줄 식 시트 — 서버 길(`/logic/sheet` · `/logic/sheet/check`) 지킴.
"""794-1 M01 로직 줄 식 고침 저장 — `/save`(개정 확인) 뒤 다시 셈 · 틀린 식 422 · 시스템 관리자만.
- 799-2 — 시트 화면 · 모델(`_LogicLab_Sheet.ts` · `logic/M01_Logic_Sheet_Model.ts`)은 걷음 · 이 서버 길은 수식 탭 검사와 같은 엔진이라 남김
- 서버(사본 폴더): 이름 꼴 식 글 · 칠 때마다 검사(없는 이름 · 아래 줄 · 괄호 · 빈 식 · 길이 · 없는 자리) ·
검사 = 쓰기 없음 · 공구손료 식 1 → 2 % 저장(개정 확인 409 → 200) 뒤 셈 51,802 · 틀린 식 저장 422 · 시스템 관리자가 아니면 403
- 시트 서버 길(`/logic/sheet` · `/check`)은 화면 0 이라 853-1 에 걷음 — 남은 것은 살아 있는 `/save` · `/calc`
- 서버(사본 폴더): 공구손료 식 1 → 2 % 저장(개정 확인 409 → 200) 뒤 셈 51,802 · 틀린 식 저장 422 · 시스템 관리자가 아니면 403
"""
from __future__ import annotations
@@ -19,19 +18,14 @@ from fastapi.testclient import TestClient
from common_util.common_util_auth import require_system_admin, verify_session
from M01_MasterData import M01_MasterData_Router as m01_router
from M01_MasterData import M01_MasterData_Sheet as line_sheet
from M01_MasterData import M01_MasterData_Store as store
REAL = store.FOLDER
KEY = "GC000211" # 합판거푸집 설치 및 해체
INPUTS = {"자재지역": "포항", "유형": "보통", "사용횟수": "6회", "높이감률": 0, "지붕슬래브": "아님",
"폼타이": "아님", "폼타이규격": "12.7㎜", "측압": "3t/㎡", "구멍땜": 0} # fmt: skip
TOOL_1 = "(형틀목공 × [노임 형틀목공] + 보통인부 × [노임 보통인부]) × 1 / 100"
TOOL_2 = TOOL_1.replace("× 1 / 100", "× 2 / 100")
def _text(p: Path) -> str:
return p.read_text("utf-8")
TOOL_1 = "(형틀목공 * LB000007 + 보통인부 * LB000002) * 1 / 100" # 덧줄 첫 줄 엔진 식
TOOL_2 = TOOL_1.replace("* 1 / 100", "* 2 / 100")
def _hashes(folder: Path) -> dict[str, str]:
@@ -63,47 +57,18 @@ def _post(client: TestClient, url: str, body: dict, want: int = 200) -> dict:
return res.json()
def test_이름_꼴_검사_쓰기_없음(client: TestClient, folder: Path) -> None:
before, real = _hashes(folder), _hashes(REAL)
one = client.get("/api/m01/logic", params={"key": KEY}).json()
row = one["logic"]
names = _post(client, "/api/m01/logic/sheet", {"row": row})
assert names["덧줄"][0] == TOOL_1
assert names["중간"][3] == "[합판거푸집설치및해체일당].형틀목공 / 시공량"
assert (
len(names["호표"]) == len(row["호표"])
and {"글": "시공량", "갈래": "중간"} in names["이름표"]
)
ask = lambda part, at, text: _post( # noqa: E731
client, "/api/m01/logic/sheet/check", {"row": row, "갈래": part, "차례": at, "식": text}
)
good = ask("덧줄", 0, TOOL_2)
assert good["되나"] and good["식"] == "(형틀목공 * LB000007 + 보통인부 * LB000002) * 2 / 100"
assert good["글"] == TOOL_2
assert ask("덧줄", 0, "형틀목공 × [노임 없음]")["까닭"] == ["없는 이름 「[노임 없음]」"]
below = ask("중간", 0, "시공량 × 2") # 시공량 = 아래 줄
assert not below["되나"] and "시공량" in below["까닭"][0]
assert not ask("중간", 2, "(1 +")["되나"]
assert ask("호표", 0, " ")["까닭"] == ["식이 빔"]
assert not ask("호표", 0, "1" + " + 1" * 200)["되나"] # 길이 상한
assert ask("덧줄", 9, "1")["까닭"] == ["없는 자리 「덧줄 9」"]
assert ask("호표", 0, "형틀목공 × 2")["되나"]
assert row == client.get("/api/m01/logic", params={"key": KEY}).json()["logic"] # 줄 안 바뀜
assert _hashes(folder) == before and _hashes(REAL) == real
def test_저장_길_개정_확인_다시_셈_틀린_식_422(client: TestClient, folder: Path) -> None:
real = _hashes(REAL)
one = client.get("/api/m01/logic", params={"key": KEY}).json()
row = copy.deepcopy(one["logic"])
got = line_sheet.check(row, "덧줄", 0, TOOL_2)
row["덧줄"][0]["식"] = got["식"]
assert row["덧줄"][0]["식"] == TOOL_1
row["덧줄"][0]["식"] = TOOL_2
body = {"files": [{"file": one["file"], "version": one["version"],
"changes": [{"op": "edit", "key": KEY, "row": row}]}]} # fmt: skip
assert client.post("/api/m01/save", json=body).status_code == 409 # 정본 = 개정 확인
_post(client, "/api/m01/save", {**body, "개정확인": True})
saved = client.get("/api/m01/logic", params={"key": KEY}).json()
assert saved["logic"]["덧줄"][0]["식"] == got["식"]
assert saved["logic"]["덧줄"][0]["식"] == TOOL_2
sums = _post(client, "/api/m01/calc", {"key": KEY, "inputs": INPUTS})["sums"]
assert sums["계"] == 51802 and sums["경비"] == 765 # _분석_650-H2 4 장 공구손료 2 %
bad = copy.deepcopy(saved["logic"])
@@ -122,6 +87,4 @@ def test_시스템_관리자가_아니면_403(folder: Path) -> None:
)
app.dependency_overrides[verify_session] = lambda: {"role": "USER", "company_id": 1}
client = TestClient(app)
for url, body in (("/api/m01/logic/sheet", {"row": {}}),
("/api/m01/logic/sheet/check", {"row": {}, "갈래": "중간", "차례": 0, "식": "1"})): # fmt: skip
assert client.post(url, json=body).status_code == 403
assert client.post("/api/m01/save", json={"files": []}).status_code == 403
@@ -5,7 +5,6 @@
② 왕복 — M01 로직 식 전부: 엔진 식 → 나무 → 엔진 식 = 같은 식 나무 · 예시 셋 = 같은 금액.
③ 고침 — 식 고침 = 금액 바뀜 · 변수 더함 · 지움(쓰는 곳 막음) · 이름 · 기호 · 첨자 전파(식 그대로) ·
표시 자리 셈(고친 줄만) · 검사 까닭(없는 이름 · 괄호 · 순환 · 0 나눔 · 상한).
④ M01 길 — 읽기 · 미리 셈 · 저장(개정확인 · 임시 사본 폴더 · 정본 안 건드림).
변수표 칸 셈 값 바뀜 0 · M01 1,519 지문은 `test_791_1_engine_semantics.py`.
"""
@@ -14,17 +13,12 @@ from __future__ import annotations
import copy
import importlib
import json
import shutil
from decimal import Decimal as D
from functools import lru_cache
from pathlib import Path
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from M01_MasterData import M01_MasterData_Equation as eq_m01
from M01_MasterData import M01_MasterData_Router as router_module
from M01_MasterData import M01_MasterData_Store as store
mf = importlib.import_module("master_formula")
@@ -315,54 +309,3 @@ def test_검사_까닭():
assert why and "꼴 아님" in why[0]
_, why = edit(AFRAME, [{"할일": "표시", "열쇠": "무게", "표시": 9}])
assert why
# ── ④ M01 길 ──────────────────────────────────────────────────────────
@pytest.fixture
def client(tmp_path: Path, monkeypatch) -> TestClient:
for path in REAL.glob("*.json"):
if not path.name.startswith("_") or path.name == store.mk.BOOK.name:
shutil.copy(path, tmp_path / path.name)
shutil.copytree(REAL / "기계", tmp_path / "기계") # 기계 = 폴더(826-2)
monkeypatch.setattr(store, "FOLDER", tmp_path)
app = FastAPI()
app.include_router(router_module.router)
return TestClient(app)
def test_M01_길_읽기_미리셈_저장(client: TestClient):
file = "로직_건설품셈_01장_적용기준.json"
real = (REAL / file).read_bytes()
body = {"key": AFRAME, "inputs": {"운반회수": 0}}
got = client.post("/api/m01/logic/equation", json=body).json()
assert got["ok"] and got["수식"]["합계"]["노무비"] == 42917
edits = [
{"할일": "식", "자리": "중간:환산거리", "식": "환산계수 × L × 2"},
{"할일": "변수", "열쇠": "일운반회수", "기호": "n"},
]
pre = client.post("/api/m01/logic/equation/preview", json=body | {"고침": edits}).json()
assert pre["되나"] and pre["후"]["노무비"] > pre["전"]["노무비"]
assert (store.FOLDER / file).read_bytes() == real # 미리 셈 = 쓰기 없음
bad = client.post(
"/api/m01/logic/equation/preview", json=body | {"고침": [edits[0] | {"식": "x)"}]}
)
assert not bad.json()["되나"]
res = client.post("/api/m01/logic/equation/save", json=body | {"고침": edits})
assert res.status_code == 409 # 정본 = 개정 확인
res = client.post("/api/m01/logic/equation/save", json=body | {"고침": edits, "개정확인": True})
assert res.status_code == 200, res.text
assert res.json()["수식"]["합계"]["노무비"] == pre["후"]["노무비"]
saved = json.loads((store.FOLDER / file).read_text(encoding="utf-8"))
before = json.loads(real.decode("utf-8"))
rows = {r["키"]: r for r in saved["줄"]}
seeded = {r["키"]: r for r in before["줄"]}[AFRAME].get(meq.FIELD) or {} # 796-3 기본 기호
assert rows[AFRAME][meq.FIELD] == seeded | {"일운반회수": {"기호": "n"}}
assert {k: v for k, v in rows.items() if k != AFRAME} == {
r["키"]: r for r in before["줄"] if r["키"] != AFRAME
}
assert (REAL / file).read_bytes() == real # 정본 안 건드림
stale = client.post(
"/api/m01/logic/equation/save",
json=body | {"고침": edits, "version": "옛판", "개정확인": True},
)
assert stale.status_code == 409
@@ -3,7 +3,6 @@
- 걷은 파일은 없고 어디서도 안 부름 · 보기 = 수식 · 단가산출 상세 둘 · 기본정보는 맨 위
- 셈 구동은 화면 칸 없이 `_Logic_Drive.ts`(서버 셈) — M01 상세는 구동만 · 시험 계산 칸(`Logic_Calc`)은 로직 복사 화면 몫
- 서버 길은 남김(`/logic/sheet` · 시트 문서 칸 · 수식 검사가 같은 엔진)
"""
from __future__ import annotations
+30 -9
View File
@@ -17,8 +17,29 @@ OFF = {"폼타이": "아님", "측압": "3t/㎡"}
ON = {"폼타이": "사용", "측압": "4t/㎡"}
def _read(key, inputs):
"""로직 줄 → 수식(살아 있는 `export_row` — M02 사본과 한 벌)."""
whole = store.loaded()[1]
return eq.export_row(whole, whole.logic(key), inputs)
def _preview(key, edits, inputs):
"""고침 미리 셈 — `edit_row` 검사 뒤 전 · 후 합계(저장 없음)."""
whole = store.loaded()[1]
row = whole.logic(key)
new, why = eq.edit_row(whole, row, edits)
if why:
return {"되나": False, "까닭": why}
try:
before = eq.meq.export(whole, key, eq._given(inputs))["합계"]
got = eq.export_row(whole, new, inputs)
except eq._ERR as e:
return {"되나": False, "까닭": [f"셈 막힘 — {e}"]}
return {"되나": True, "까닭": [], "수식": got, "전": before, "후": got["합계"]}
def _defs(inputs):
return eq.read(KEY, inputs)["수식"]["정의"]
return _read(KEY, inputs)["정의"]
def _text(defs):
@@ -52,13 +73,13 @@ def test_unpicked_branches_hidden():
def test_live_edit_preview_changes_total():
spot = {"할일": "식", "자리": "호표:0", "식": "형틀목공 × 2"}
got = eq.preview(KEY, [spot], OFF)
got = _preview(KEY, [spot], OFF)
assert got["되나"] and got["후"]["계"] > got["전"]["계"]
def test_unknown_symbol_asks_link_then_links():
spot = {"할일": "식", "자리": "호표:0", "식": "형틀목공 × 2 + Z"}
got = eq.preview(KEY, [spot], OFF)
got = _preview(KEY, [spot], OFF)
assert not got["되나"] and "모르는 기호 「Z」" in got["까닭"][0]
for link in (
{"갈래": "상수", "값": "0"},
@@ -67,7 +88,7 @@ def test_unknown_symbol_asks_link_then_links():
{"갈래": "요소", "요소": "LB000007"},
):
add = {"할일": "연결", "열쇠": "Z", "이름": "새값", **link}
got = eq.preview(KEY, [add, spot], OFF)
got = _preview(KEY, [add, spot], OFF)
assert got["되나"], (link, got["까닭"])
assert any(d["기호"] == "Z" for d in got["수식"]["정의"])
@@ -80,18 +101,18 @@ def test_link_bad_input_blocked():
{"갈래": "상수", "값": "abc"},
]
for link in bad:
got = eq.preview(KEY, [{"할일": "연결", "열쇠": "Z", **link}], OFF)
got = _preview(KEY, [{"할일": "연결", "열쇠": "Z", **link}], OFF)
assert not got["되나"], link
def test_drop_guard_and_unused_input():
got = eq.preview(KEY, [{"할일": "지움", "열쇠": "사용횟수"}], OFF)
got = _preview(KEY, [{"할일": "지움", "열쇠": "사용횟수"}], OFF)
assert not got["되나"] and "쓰는 곳" in got["까닭"][0]
add = {"할일": "연결", "열쇠": "Y", "갈래": "입력"}
got = eq.preview(KEY, [add], OFF)
got = _preview(KEY, [add], OFF)
unused = [d for d in got["수식"]["정의"] if d["기호"] == "Y"]
assert unused and unused[0].get("안씀")
assert eq.preview(KEY, [add, {"할일": "지움", "열쇠": "Y"}], OFF)["되나"]
assert _preview(KEY, [add, {"할일": "지움", "열쇠": "Y"}], OFF)["되나"]
def test_candidates():
@@ -106,7 +127,7 @@ def test_candidates():
def test_groups_add_up_to_total():
"""800-4 — 묶음(블록 · 자원 · 덧줄) 소계 합 + 끝수 = 합계(비목마다) · 한 묶음 소계 = 노 + 재 + 경."""
for key in ("GF000089", "GC000211"):
eqn = eq.read(key, {})["수식"]
eqn = _read(key, {})
sub, total = eqn["소계"], eqn["합계"]
for k in ("노무비", "재료비", "경비"):
got = sum(float(r[k]) for r in sub["줄"]) + float(sub["끝수"][k])
+1 -8
View File
@@ -197,14 +197,7 @@ def test_표지_갈래(client, line, kind):
assert kind in {m["갈래"] for m in got["표지"]}
def test_연결_후보_표(client):
res = client.post(
"/api/m01/logic/doc/links", json={"갈래": "단가산출", "검색": "굴착기 시간당"}
)
hits = res.json()["후보"]
assert hits and all("입력" in h for h in hits)
res = client.post("/api/m01/logic/doc/links", json={"갈래": "표", "검색": "토사깍기 기계"})
assert any(h["키"] == "QF000249" for h in res.json()["후보"])
def test_표_하나(client):
table = client.get("/api/m01/logic/doc/table", params={"key": "QF000249"}).json()
assert "조건" in table and table["줄"]
assert "끊김" in client.get("/api/m01/logic/doc/table", params={"key": "LB000002"}).json()
-3
View File
@@ -73,11 +73,8 @@ def _labor_row(client: TestClient, number: str) -> tuple[dict, str]:
def test_그룹_파일_줄_쪽나눔_찾기(client: TestClient) -> None:
groups = {g["group"]: g for g in _get(client, "/api/m01/groups")["groups"]}
assert list(groups) == ["인력", "재료", "기계", "소요량", "계수", "환율", "요율", "로직"]
files = _get(client, "/api/m01/groups/인력/files")["files"]
assert LABOR in [f["file"] for f in files]
assert groups["인력"]["files"] == len(files)
page2 = _get(client, "/api/m01/rows", file=LABOR, page=2, size=10)
assert page2["page"] == 2 and len(page2["rows"]) == 10 and page2["total"] > 20
hit = _get(client, "/api/m01/rows", file=LABOR, q="보통인부")
+5 -68
View File
@@ -1,11 +1,10 @@
"""일위대가 조합(PLAN 4-2 · 27-2a) — 담은 단가산출 로직 목록만 두고 미리 보기로 비목별 합계.
"""일위대가 조합(PLAN 4-2 · 27-2a) — 담은 단가산출 로직 목록만 둠.
읽기 = M02 조합 저장소(`combos.one` · `combos.listing` · 서버 길은 없앰 732-1).
계약 `resources/master_data/_화면_계약.md` 9장 · 틀 `_틀.md` 10장 · 엔진 `scripts/master_combo.py`.
못박는 것
- 조합은 이름과 담은 로직 목록만 지님 — 수량·비율·계산 칸을 두지 않음.
- 미리 보기 합계 = 담은 로직 저마다의 시험 계산을 비목별로 더한 값(저장 없음).
- 검사 — 없는 로직 키 · 같은 로직 두 번 · 빈 조합 · 조합이 조합을 담음.
- 시험은 임시 사본에서 돌고, 사본의 조합 줄은 비워 시작 — 정본에 견본 조합이 있어도 없어도 같음.
"""
@@ -15,7 +14,6 @@ from __future__ import annotations
import json
import shutil
import sys
from decimal import Decimal
from pathlib import Path
import pytest
@@ -106,18 +104,6 @@ def _edit(client: TestClient, key: str, version: str, row: dict, want: int = 200
return done
def _inputs(key: str) -> dict:
"""그 로직의 일괄 시험 입력 한 벌(`check_master.시험입력`)."""
row = store.cm.master(REAL).logic(key)
return {k: str(v) for k, v in store.cm.시험입력(row).items()}
def _sums(client: TestClient, key: str, inputs: dict) -> dict:
got = _post(client, "/api/m01/calc", {"key": key, "inputs": inputs})
assert got["ok"] is True, got
return got["sums"]
def _make(client: TestClient, keys=SAMPLE, 이름="돌쌓기 한 벌", owner: str = "현장") -> dict:
body = {
"이름": 이름,
@@ -145,13 +131,11 @@ def test_조합_테이블ID_는_UA_이고_줄에_원문번호를_두지_않는
def test_조합은_요소_그룹이_아니다(client: TestClient) -> None:
"""조합은 제 길(`/combos`·`/combo`)로만 다룸 — 요소 길(`/groups`·`/rows`)에 끼지 않음.
"""조합은 제 길(`/combos`·`/combo`)로만 다룸 — 요소 길(`/groups/…/files`·`/rows`)에 끼지 않음.
끼우면 화면이 조합을 여느 요소 표처럼 `/rows` 로 펴 버림(줄 모양이 아주 다름).
"""
assert mcb.GROUP not in store.cm.mf.GROUPS
groups = [g["group"] for g in _get(client, "/api/m01/groups")["groups"]]
assert groups == ["인력", "재료", "기계", "소요량", "계수", "환율", "요율", "로직"]
assert client.get("/api/m01/groups/일위대가조합/files").status_code == 404
@@ -188,10 +172,10 @@ def test_목록은_소유_담은_수_폴더를_준다(client: TestClient) -> Non
def test_이_로직을_쓰는_조합을_거꾸로_본다(client: TestClient) -> None:
first = _make(client, 이름="돌쌓기 한 벌")["key"]
second = _make(client, keys=(STACK,), 이름="메쌓기만")["key"]
got = _get(client, "/api/m01/logic/combos", key=STACK)
got = combo_store.combos_of_logic(STACK) # 로직 지우기 전 쓰는 곳(`Doc.users`)이 부름
assert [c["키"] for c in got["combos"]] == [first, second]
assert got["combos"][0]["차례"] == [1] # 그 조합 안 몇 번째인지
assert _get(client, "/api/m01/logic/combos", key="GF000001")["combos"] == []
assert combo_store.combos_of_logic("GF000001")["combos"] == []
# ── 고치기 · 지우기 ───────────────────────────────────────────────────
@@ -298,55 +282,8 @@ def test_메모가_글자_아니면_막는다(client: TestClient) -> None:
assert any("메모」 가 글자 아님" in x for x in got["detail"]["errors"]), got
# ── 미리 보기 ─────────────────────────────────────────────────────────
# M02 미리 보기 길은 39-3 에 은퇴(일위대가 상세 = calc 길) — 같은 계산(`combo_preview`)을 바로 부름
def _preview(body: dict) -> dict:
got = combo_store.combo_preview(body["combo"], body["inputs"])
return json.loads(json.dumps(got, default=str, ensure_ascii=False))
def test_미리보기_합계가_담은_로직들의_시험_계산과_비목별로_같다(client: TestClient) -> None:
key = _make(client)["key"]
each = {k: _inputs(k) for k in SAMPLE}
want = {
name: sum(Decimal(str(_sums(client, k, each[k])[name])) for k in SAMPLE)
for name in ("노무비", "재료비", "경비", "계")
}
got = _preview({"combo": key, "inputs": each})
assert got["멈춤"] == [], got["멈춤"]
assert [one["로직"] for one in got["줄"]] == list(SAMPLE)
for name in ("노무비", "재료비", "경비", "계"):
assert Decimal(str(got[name])) == want[name], name
assert Decimal(str(got["계"])) > 0
# 줄마다도 그 로직 하나의 시험 계산과 같음
for one in got["줄"]:
mine = _sums(client, one["로직"], each[one["로직"]])
assert Decimal(str(one["계"])) == Decimal(str(mine["계"]))
def test_미리보기는_저장_전_조합_줄도_받고_아무것도_저장하지_않는다(client: TestClient) -> None:
before = _list(client)
row = {"이름": "저장 안 한 것", "담은로직": [{"로직": STACK, "메모": None}]}
got = _preview({"combo": row, "inputs": {STACK: _inputs(STACK)}})
assert got["멈춤"] == [] and Decimal(str(got["계"])) > 0
assert _list(client) == before # 아무것도 안 생김
def test_못_도는_줄은_까닭만_적고_나머지_합계는_낸다(client: TestClient) -> None:
key = _make(client, keys=(STACK, LAYER))["key"]
only = {STACK: _inputs(STACK)} # LAYER 입력은 안 줌 — 그 줄만 멈춤
got = _preview({"combo": key, "inputs": only})
stuck = [one for one in got["줄"] if not one["ok"]]
assert len(stuck) == 1 and stuck[0]["로직"] == LAYER and stuck[0]["까닭"]
assert len(got["멈춤"]) == 1
alone = _sums(client, STACK, only[STACK])
assert Decimal(str(got["계"])) == Decimal(str(alone["계"])) # 선 줄만 더함
def test_정본_로직은_조합을_만들어도_안_바뀐다(client: TestClient) -> None:
before = _get(client, "/api/m01/logic", key=STACK)
key = _make(client)["key"]
_preview({"combo": key, "inputs": {k: _inputs(k) for k in SAMPLE}})
_make(client)
after = _get(client, "/api/m01/logic", key=STACK)
assert after["version"] == before["version"] and after["logic"] == before["logic"]
+30 -45
View File
@@ -1,4 +1,4 @@
"""M01 「만들기」 API — 절 목록 · 절 거르기 · 표 조건 값 · 소유 거름 · 자체 로직 · 끝수.
"""M01 「만들기」 — 절로 표 거르기 · 소유 거름 · 자체 로직(만들기 · 본뜨기 · `/save` 고치기 · 지우기) · 끝수.
계약 `resources/master_data/_화면_계약.md` 2장·5장·6장. 임시 폴더 사본에서 씀.
"""
@@ -71,6 +71,17 @@ def _draft(끝수=None) -> dict:
}
def _new(owner: str) -> dict:
"""새 자체 로직 — 화면 길(`/logic/copy` · `/logic/formula/save`)이 함께 쓰는 `logic_new`."""
return make.logic_new(_draft(), owner)
def _own_save(client: TestClient, change: dict, version: str, want: int = 200) -> dict:
"""자체 로직 고치기 · 지우기 = M01 [저장](`/save`) 한 길."""
body = {"files": [{"file": make.OWN, "version": version, "changes": [change]}]}
return _post(client, "/api/m01/save", body, want)
# ── 끝수 ──────────────────────────────────────────────────────────────
def test_끝수_묶음이_계에_붙고_글자는_안_붙는다(client: TestClient) -> None:
plain = _post(client, "/api/m01/calc", {"key": "", "inputs": {}, "row": _draft()})
@@ -96,32 +107,13 @@ def test_끝수_묶음_모양을_검사가_잡는다() -> None:
assert any("대상" in x for x in found) and any("방법" in x for x in found)
# ── 절 목록 · 절 거르기 · 표 조건 값 ──────────────────────────────────
def test_절_목록과_절로_표_거르기(client: TestClient) -> None:
got = _get(client, "/api/m01/sections", book="산림품셈", chapter="13")
one = next(s for s in got["sections"] if s["section"] == "13-4-1")
assert one["title"].startswith("메쌓기") and one["chapter"] == "13장 구조물"
assert one["tables"] >= 1 and one["logics"] >= 1
assert client.get("/api/m01/sections", params={"book": "없는품셈"}).status_code == 404
# ── 절 거르기 ─────────────────────────────────────────────────────────
def test_절로_표_거르기(client: TestClient) -> None:
hits = _get(client, "/api/m01/tables", group="소요량", section="13-4", size=500)["tables"]
assert hits and all(store.in_section(t["원문번호"], "13-4") for t in hits)
assert not store.in_section("13-40", "13-4") and store.in_section("13-4", "13-4")
def test_표_조건_값만_받는다(client: TestClient) -> None:
listed = _get(client, "/api/m01/tables", group="소요량", section="13-4-1", size=50, q="메쌓기")[
"tables"
]
one = listed[0]
got = _get(client, "/api/m01/table/options", file=one["file"], key=one["키"])
assert got["count"] >= 1 and "줄" not in got
for name, kind in got["조건"].items():
assert name in got["값"]
if kind == "고르기":
assert len(got["값"][name]) == len(set(map(str, got["값"][name])))
def test_로직_목록을_소유로_거른다(client: TestClient) -> None:
every = _get(client, "/api/m01/logics")["logics"]
assert all("소유" in x for x in every)
@@ -132,12 +124,12 @@ def test_로직_목록을_소유로_거른다(client: TestClient) -> None:
# ── 자체 로직 ─────────────────────────────────────────────────────────
def test_자체_로직_만들기_본뜨기_고치기_지우기(client: TestClient) -> None:
made = _post(client, "/api/m01/logic/new", {"logic": _draft(), "owner": "현장"})
made = _new("현장")
assert made["key"].startswith("GX") and made["file"] == make.OWN
assert made["logic"]["구분"] == "자체" and made["logic"]["소유"] == "현장"
assert (store.FOLDER / make.OWN).is_file()
again = _post(client, "/api/m01/logic/new", {"logic": _draft(), "owner": "현장"})
again = _new("현장")
assert again["key"] != made["key"] # 원문번호가 같아도 키는 하나씩
copied = _post(client, "/api/m01/logic/copy", {"key": SAMPLE, "이름": "메쌓기 본뜸"})
@@ -146,33 +138,26 @@ def test_자체_로직_만들기_본뜨기_고치기_지우기(client: TestClien
assert copied["logic"]["상세구분"] == "13장 구조물"
fixed = dict(copied["logic"], 이름="고친 이름")
done = _post(
client,
"/api/m01/logic/edit",
{"key": copied["key"], "version": copied["version"], "logic": fixed},
)
change = {"op": "edit", "key": copied["key"], "row": fixed}
_own_save(client, change, copied["version"])
done = _get(client, "/api/m01/logic", key=copied["key"])
assert done["logic"]["이름"] == "고친 이름" and done["logic"]["키"] == copied["key"]
stale = {"key": copied["key"], "version": copied["version"], "logic": fixed}
_post(client, "/api/m01/logic/edit", stale, want=409)
_own_save(client, change, copied["version"], want=409) # 옛 판
gone = _post(
client, "/api/m01/logic/delete", {"key": copied["key"], "version": done["version"]}
)
assert gone["file"] == make.OWN
gone = _own_save(client, {"op": "delete", "key": copied["key"]}, done["version"])
assert gone["files"][0]["file"] == make.OWN
assert client.get("/api/m01/logic", params={"key": copied["key"]}).status_code == 404
def test_정본_로직은_못_고친다(client: TestClient) -> None:
got = _get(client, "/api/m01/logic", key=SAMPLE)
body = {"key": SAMPLE, "version": got["version"], "logic": got["logic"]}
_post(client, "/api/m01/logic/edit", body, want=403)
_post(client, "/api/m01/logic/delete", {"key": SAMPLE, "version": got["version"]}, want=403)
_post(client, "/api/m01/logic/new", {"logic": _draft(), "owner": "남의것"}, want=400)
def test_모르는_소유는_400(client: TestClient) -> None:
with pytest.raises(store.StoreError) as caught:
make.logic_new(_draft(), "남의것")
assert caught.value.status == 400
def test_만든_자체_로직이_시험_계산에_돈다(client: TestClient) -> None:
made = _post(client, "/api/m01/logic/new", {"logic": _draft(), "owner": "공용"})
made = _new("공용")
got = _post(client, "/api/m01/calc", {"key": made["key"], "inputs": {}})
assert got["ok"] is True and Decimal(str(got["sums"]["노무비"])) > 0
listed = _get(client, "/api/m01/logics", owner="공용")["logics"]
@@ -190,7 +175,7 @@ def test_일위대가가_담은_로직은_못_지운다(client: TestClient, tmp_
system, storage = tmp_path / "system", tmp_path / "storage"
monkeypatch.setattr(layers, "SYSTEM_ROOT", system)
monkeypatch.setattr(config_system, "STORAGE_BASE_DIR", str(storage))
made = _post(client, "/api/m01/logic/new", {"logic": _draft(), "owner": "현장"})
made = _new("현장")
key = made["key"]
docs = {
"회사 3": storage / "3/templates/labor/item1.json",
@@ -208,7 +193,7 @@ def test_일위대가가_담은_로직은_못_지운다(client: TestClient, tmp_
def delete(want: int) -> dict:
version = _get(client, "/api/m01/logic", key=key)["version"]
return _post(client, "/api/m01/logic/delete", {"key": key, "version": version}, want)
return _own_save(client, {"op": "delete", "key": key}, version, want)
errors = " ".join(delete(422)["detail"]["errors"])
for where in docs:
@@ -219,4 +204,4 @@ def test_일위대가가_담은_로직은_못_지운다(client: TestClient, tmp_
assert "일위대가 " not in " ".join(delete(422)["detail"]["errors"])
raw["줄"].pop()
combos.write_text(json.dumps(raw, ensure_ascii=False), encoding="utf-8")
assert delete(200)["file"] == make.OWN # 쓰는 곳 0 = 지워짐
assert delete(200)["files"][0]["file"] == make.OWN # 쓰는 곳 0 = 지워짐