chore(853-2): 걸음 0 묶음 ① — 화면 0 서버 길 16 · 그 길만 부르던 본체 · 죽은 화면 래퍼 걷음
- 길: sangeun from-line · formula-check · copy · equation(셋) · block · labor copy · 프로젝트 양식 reset · apply · save-as · sources · drawing-import · drawing-fields · logic-lib machine-parts · logic-lib/auto - 본체: Calc.from_line · Formula.check_doc 외 셋 · Equation 읽기 · 미리 셈 · Equation_Full 파일 · Block 끊기 · 잇기 · 수식 탭 · Labor_Copy.preview · Router_Layers 가져오기 도우미 - 화면: Api_Fetch 래퍼 여덟 · sangeunFromLine - 시험: 죽은 길만 보던 796-2c · 796-2e 파일 지움 · 함수째 지움(715-3 · 733-2 · 792-1 · 796-2b · router_drawing · template_layers · structure_panel 글자 시험) · 살아 있는 결과는 [저장] 길로 고침(795-2 · 796-2b) · 813-2 = M01 parts.of_machine 바로 - 남김: Sangeun_Copy.preview(옛 엔진 셈 거울 — 걸음 2) · B07 이 쓰는 reset_project · B09 가 쓰는 _company_projects - 검증: /openapi.json 524 → 508(뜻한 16 만) · 빌더 --check 같음 · 핵심 시험 99 통과 · 관련 시험 687 통과 · typecheck 0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,8 +11,6 @@ SK 사본(`M02_Sangeun_Copy` · 795-1) 한 벌 — 문서 칸 `사본` 꼴 ·
|
||||
사본 정함(`settle` · 셈 · 저장 첫머리) = 받은 사본 먼저(열 복사 · 층 복사 = 원본 사본 그대로 · 판은
|
||||
서버가 다시 셈) → 없으면 저장본(일위대가 = labor/<열> · SC = precombo/<키>) → [저장] 때 없으면 새로
|
||||
찍음 · 사본에 없는 새 줄만 지금 M01 에서 더함 · 사본 없는 옛 문서 = 셈은 옛 길.
|
||||
길(`M02_Labor_Router`) POST …/labor/{열 | SC 키}/copy/{price|regen} {doc, 수량?} →
|
||||
{doc(사본할일), 전, 후, 바뀐자원 | 못얹은}(저장 없음).
|
||||
짝(CLAUDE.md 5장 ①) `M02_MasterTemplete_Labor_Calc.ts` = 서버 기준 값을 받아 수량 · 반영 · 합만 —
|
||||
사본은 기준 값에만 닿음(짝 안 고침 · 거울 시험 `test_795_2_sc_copy`).
|
||||
"""
|
||||
@@ -174,38 +172,3 @@ def combo(expand: Any, doc: dict, trail: tuple[str, ...]) -> dict[str, Any]:
|
||||
def mark(ans: dict, doc: dict) -> dict:
|
||||
"""셈 답 덧칸 `사본` {시점, 단가시점, M01새판, 지운키, 단가새값} — 사본 없음 = 칸 없음."""
|
||||
return skc.mark(ans, doc)
|
||||
|
||||
|
||||
# ── [단가 갱신] · [재생성] 미리 셈(저장 없음) ──────────────────────────
|
||||
def _money(ans: dict) -> dict:
|
||||
return {k: ans.get(k) for k in ("기준합", "반영합")}
|
||||
|
||||
|
||||
def _lost(ans: dict) -> dict[str, dict]:
|
||||
got = {}
|
||||
for n, line in enumerate(ans.get("줄") or []):
|
||||
for x in line.get("짝잃음") or []:
|
||||
if isinstance(x, dict):
|
||||
got[f"{n}|{x.get('cid')}"] = {**x, "줄": n}
|
||||
return got
|
||||
|
||||
|
||||
def preview(doc: dict, job: str, given: dict | None = None) -> dict[str, Any]:
|
||||
"""{doc(할일 얹음), 전, 후, 바뀐자원 · 못얹은} — `doc` = 정리한 문서 · 재생성 ⊃ 단가갱신."""
|
||||
from M02_MasterTemplete import M02_Labor_Doc as labor
|
||||
|
||||
new = REGEN if REGEN in (doc.get(JOB), job) else job
|
||||
after_doc = {**doc, JOB: new}
|
||||
before, after = labor.calc(doc, given), labor.calc(after_doc, given)
|
||||
out: dict[str, Any] = {"doc": after_doc, "전": _money(before), "후": _money(after)}
|
||||
if job == PRICE:
|
||||
copy = skc.taken(doc.get(KEY)) or _stored(doc)
|
||||
out["바뀐자원"] = skc.refresh(copy, skc.whole_())[1] if copy else []
|
||||
else:
|
||||
was = _lost(before)
|
||||
out["못얹은"] = [
|
||||
{"줄": x["줄"], "cid": x.get("cid"), "까닭": x.get("까닭") or "새 사본에 그 줄 없음"}
|
||||
for c, x in _lost(after).items()
|
||||
if c not in was
|
||||
]
|
||||
return out
|
||||
|
||||
@@ -58,32 +58,6 @@ def _calc(column: str, body: CalcBody) -> dict[str, Any]:
|
||||
return {**got, "알약": labor.pills(doc)}
|
||||
|
||||
|
||||
_JOBS = {"price": lc.PRICE, "regen": lc.REGEN}
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/labor/{column}/copy/{how}")
|
||||
def labor_copy(
|
||||
layer: Layer,
|
||||
column: str,
|
||||
how: str,
|
||||
body: CalcBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""로직 사본(795-2) — price [단가 갱신] · regen [재생성] · 일위대가 열 · 사전조합 SC 키 ·
|
||||
답 = 할일 얹은 doc(화면 캐시 · [저장] 때 서버가 적용) + 전 · 후 합 + 바뀐자원 | 못얹은."""
|
||||
if how not in _JOBS:
|
||||
raise HTTPException(status_code=404, detail="price · regen")
|
||||
return _call(_root(session, layer, owner), _copy_job, column, body, _JOBS[how])
|
||||
|
||||
|
||||
def _copy_job(column: str, body: CalcBody, job: str) -> dict[str, Any]:
|
||||
"""미리 셈은 정리한 문서로 · 답 doc = 보낸 화면 문서 + 할일(SC · 일위대가 꼴 그대로)."""
|
||||
got = lc.preview(_doc(column, body.doc), job, body.수량)
|
||||
sent = body.doc if body.doc is not None else store.read("labor", column)["문서"]
|
||||
return {**got, "doc": {**sent, lc.JOB: got["doc"][lc.JOB]}}
|
||||
|
||||
|
||||
def _pills(column: str) -> dict[str, Any]:
|
||||
return {"열": column, "알약": labor.pills(_doc(column, None))}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from M01_MasterData import M01_MasterData_Parts as parts
|
||||
from M01_MasterData import M01_MasterData_Router as m01
|
||||
from M02_MasterTemplete import M02_Machine_Hourly as machine
|
||||
|
||||
@@ -80,9 +79,3 @@ def get_machine_hourly(key: str) -> dict:
|
||||
def get_machine_rows(keys: str) -> dict:
|
||||
"""기계 창(827-1) — M01 기계 키 · 원문번호 쉼표 목록(60 까지) → 줄 값 + 시간당."""
|
||||
return {"rows": machine.brief([k for k in keys.split(",") if k.strip()])}
|
||||
|
||||
|
||||
@router.get("/machine-parts")
|
||||
def get_machine_parts(no: str) -> dict:
|
||||
"""줄 쌓기 기계 넣기(813-2) — 기계 원문번호 → 그 기종 작업량 틀(문서째)."""
|
||||
return m01._call(parts.of_machine, no)
|
||||
|
||||
@@ -281,14 +281,6 @@ export interface StructureSheet {
|
||||
도면: { entities: unknown[] } & Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 시스템 층 구조물 도면 목록 */
|
||||
export const listStructures = async (): Promise<TemplateInfo[]> =>
|
||||
(await listTemplates("system", null)).filter((t) => t.종류 === "structure");
|
||||
|
||||
/** 새로 — 도번 자동 · 빈 도면 (+ 없으면 빈 면적산출 통합문서) · 이미 있으면 StaleError */
|
||||
export const createStructure = (column: string): Promise<TemplateDoc> =>
|
||||
scoped(`/structures/${enc(column)}`, { method: "POST" });
|
||||
|
||||
/** 한 열의 번호 — 도번 `SD` · 면적번 `SA` + 같은 8자리
|
||||
* [종류][분류1][분류2][분류3](없는 쪽은 빈 글) */
|
||||
export interface StructureNumbers {
|
||||
@@ -382,11 +374,6 @@ export const clearPart = (
|
||||
{ method: "POST" },
|
||||
);
|
||||
|
||||
/** 다른 열(`from`) 구조물 도면 내용을 받는 열(`column`)로 가져옴 — 도번 · 열은 받는 쪽 그대로 */
|
||||
export const copyStructure = async (column: string, from: string): Promise<void> => {
|
||||
await scoped(`/structures/${enc(column)}/copy?from=${enc(from)}`, { method: "POST" });
|
||||
};
|
||||
|
||||
/** 면적산출 알약 하나 — 로직 물량 「이름|단위」(`로직` · `배`) · 자재 「자재|MT키」(`자재`) */
|
||||
export interface LaborPill {
|
||||
키: string;
|
||||
@@ -401,11 +388,6 @@ export interface LaborPill {
|
||||
export const fetchLaborPills = (column: string): Promise<{ 열: string; 알약: LaborPill[] }> =>
|
||||
call(owned(activeLayer, `/layers/${activeLayer}/labor/${enc(column)}/pills`));
|
||||
|
||||
/** 다른 열(`from`) 면적산출 내용(알약 연결 포함)을 받는 열(`column`)로 가져옴 — 면적번 · 열은 그대로 */
|
||||
export const copyArea = async (column: string, from: string): Promise<void> => {
|
||||
await scoped(`/area/${enc(column)}/copy?from=${enc(from)}`, { method: "POST" });
|
||||
};
|
||||
|
||||
/** 회사 · 개인 층의 집계표 항목(열 하나 + 도면 · 면적 파일)을 내 개인 층으로 복사 —
|
||||
* 새 SS 키로 만들고 `본뜬` 표시 · `fromOwner` = 회사 층 회사 · 개인 층 「회사/사용자」 */
|
||||
export const copyItemToPersonal = (body: {
|
||||
@@ -418,27 +400,6 @@ export const copyItemToPersonal = (body: {
|
||||
body: JSON.stringify({ from_layer: body.fromLayer, from_owner: body.fromOwner, key: body.key }),
|
||||
});
|
||||
|
||||
/* --- 프로젝트 층 단추 다섯 --- */
|
||||
const project = (id: string, tail: string): string => `/projects/${enc(id)}/templates/${tail}`;
|
||||
const post = (path: string, body: object = {}): Promise<unknown> =>
|
||||
call(path, { method: "POST", body: JSON.stringify(body) });
|
||||
|
||||
export const resetProject = (id: string): Promise<unknown> => post(project(id, "reset"));
|
||||
|
||||
export const applyToProject = (
|
||||
id: string,
|
||||
from: { from: Layer; user_id?: string; project_id?: string; 종류?: Kind; 이름?: string },
|
||||
): Promise<unknown> => post(project(id, "apply"), from);
|
||||
|
||||
export const saveProjectAs = (
|
||||
id: string,
|
||||
to: "personal" | "company",
|
||||
종류: Kind,
|
||||
이름: string,
|
||||
): Promise<unknown> => post(project(id, "save-as"), { to, 종류, 이름 });
|
||||
|
||||
export const fetchSources = (id: string): Promise<unknown> => call(`/projects/${enc(id)}/sources`);
|
||||
|
||||
/** 설계값을 채운 표 문서 — 서버가 그때그때 채움 · 저장 안 함 */
|
||||
export const readFilled = (id: string, name: string): Promise<TemplateDoc> =>
|
||||
call(`/projects/${enc(id)}/tables/${enc(name)}/filled`);
|
||||
|
||||
@@ -54,12 +54,6 @@ def get_logic(key: str) -> dict:
|
||||
return _read(m01.logic, key)
|
||||
|
||||
|
||||
@router.get("/logic-lib/auto", dependencies=[Depends(verify_session)])
|
||||
def get_logic_auto(key: str) -> dict:
|
||||
"""견본 입력 — 미리 보기용 자동값."""
|
||||
return _read(m01.auto, key)
|
||||
|
||||
|
||||
@router.get("/logic-lib/inputs", dependencies=[Depends(verify_session)])
|
||||
def get_logic_inputs(keys: str = "") -> dict:
|
||||
"""일위대가 입력 모달 — 로직 키들(쉼표)의 입력 목록 + 자동값(`M02_Labor_Inputs`)."""
|
||||
|
||||
@@ -1,97 +1,20 @@
|
||||
"""M02 도면 양식 서버 길 — 외부 도각 파일 불러오기 · 자리표 키 목록 (PLAN 10-3).
|
||||
"""M02 구조물 도면에 얹는 도각 길(`/structure-frame` · 56장) — B07 시스템 양식 도각을 그대로 다시 쓴다.
|
||||
|
||||
양식을 읽고 쓰는 길은 `M02_MasterTemplete_Router.py`(시스템 층)·`_Router_Layers.py`(층)가 맡는다.
|
||||
여기는 도면 양식 편집 화면만 쓰는 두 길 — B07 의 불러오기 엔진 · 표제란 값을 그대로 다시 쓴다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from uuid import UUID
|
||||
|
||||
import ezdxf
|
||||
from fastapi import APIRouter, File, UploadFile
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from B07_DesignDetail.B07_DesignDetail_Engine_Frame_Import import import_frame_file
|
||||
from B07_DesignDetail.B07_DesignDetail_Engine_Template import (
|
||||
entities_bbox,
|
||||
frame_document,
|
||||
frame_entities,
|
||||
frame_guide_area,
|
||||
usable_bbox,
|
||||
validate_template_entities,
|
||||
)
|
||||
from B07_DesignDetail.B07_DesignDetail_Router import title_block_fields
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/m02", tags=["M02 MasterTemplete"])
|
||||
|
||||
# 도각 파일 상한 — A1 도각 한 장은 보통 1MB 아래다. 큰 도면 전체를 올리는 실수를 막는다.
|
||||
_IMPORT_MAX_BYTES = 20 * 1024 * 1024
|
||||
|
||||
# 자리표 `{{키}}` 로 쓸 수 있는 키 — 도면을 그릴 때 채워지는 것만 둔다.
|
||||
# 프로젝트 값은 B07 `title_block_fields` 가 · 도면 값은 도면을 그리는 엔진이 채운다.
|
||||
DRAWING_FIELDS: tuple[tuple[str, str, str], ...] = (
|
||||
("공사명", "프로젝트", "프로젝트 이름"),
|
||||
("위치", "프로젝트", "사업 위치"),
|
||||
("시행청", "프로젝트", "발주 기관"),
|
||||
("연도기번", "프로젝트", "프로젝트 번호"),
|
||||
("사업량", "프로젝트", "사업량"),
|
||||
("설계일자", "프로젝트", "설계 일자"),
|
||||
("용역회사", "프로젝트", "회사 이름"),
|
||||
("설계자", "프로젝트", "설계자 이름"),
|
||||
("과업책임자", "프로젝트", "과업책임자 이름"),
|
||||
("분야별책임자", "프로젝트", "분야별책임자 이름"),
|
||||
("회사로고", "프로젝트", "회사 로고 그림"),
|
||||
("설계자서명", "프로젝트", "설계자 서명 그림"),
|
||||
("과업책임자서명", "프로젝트", "과업책임자 서명 그림"),
|
||||
("분야별책임자서명", "프로젝트", "분야별책임자 서명 그림"),
|
||||
("도면명", "도면", "도면 이름"),
|
||||
("도면번호", "도면", "도면 목록 순번"),
|
||||
("축척_A1", "도면", "A1 축척 분모"),
|
||||
("축척_A3", "도면", "A3 축척 분모"),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/drawing-import")
|
||||
async def import_drawing_file(file: UploadFile = File(...)) -> JSONResponse:
|
||||
"""외부 도각 파일(DXF·DWG)을 읽어 **편집 화면에 실을 도면**으로 돌려준다 — 저장하지 않는다."""
|
||||
try:
|
||||
data = await file.read()
|
||||
if not data:
|
||||
raise ValueError("빈 파일입니다.")
|
||||
if len(data) > _IMPORT_MAX_BYTES:
|
||||
raise ValueError("도각 파일이 너무 큽니다(20MB 넘음).")
|
||||
entities = await asyncio.to_thread(import_frame_file, file.filename or "", data)
|
||||
validate_template_entities(entities)
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "success",
|
||||
"drawing": frame_document(entities),
|
||||
"entity_count": len(entities),
|
||||
}
|
||||
)
|
||||
except ValueError as exc:
|
||||
return JSONResponse(status_code=400, content={"status": "error", "message": str(exc)})
|
||||
except (OSError, UnicodeError, ezdxf.DXFError):
|
||||
# 엉터리 파일 — 읽는 라이브러리가 ValueError 아닌 것으로 던짐(DXF 아님 · 글자 깨짐).
|
||||
# 던진 글에 임시 폴더 경로가 섞여 있어 그대로 내지 않는다.
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
"status": "error",
|
||||
"message": "도각 파일을 읽지 못했습니다 — DXF 가 아니거나 깨진 파일입니다.",
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("M02 도각 불러오기 실패: %s", file.filename)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"status": "error", "message": "도각 파일을 읽지 못했습니다."},
|
||||
)
|
||||
|
||||
|
||||
# 얹은 도각 층 — 화면이 돌려줄 때 이 층을 통째로 뺌 · 불러온 DXF 층(`b08-frame`)과 갈라 둠
|
||||
STRUCTURE_FRAME_LAYER = "m02-structure-frame"
|
||||
|
||||
@@ -138,23 +61,3 @@ def structure_frame(number: str | None = None, name: str | None = None) -> dict:
|
||||
async def get_structure_frame(number: str | None = None) -> JSONResponse:
|
||||
"""구조물 도면 상세 · 카드 미리보기가 얹는 도각(56장) · `number` = 장 도번(82-2)."""
|
||||
return JSONResponse({"status": "success", **structure_frame(number)})
|
||||
|
||||
|
||||
@router.get("/drawing-fields")
|
||||
async def get_drawing_fields(project_id: UUID | None = None) -> JSONResponse:
|
||||
"""자리표 키 목록. project_id 를 주면 그 프로젝트의 표제란 값도 함께(미리보기용)."""
|
||||
try:
|
||||
values = await title_block_fields(project_id) if project_id else {}
|
||||
except Exception:
|
||||
logger.exception("M02 자리표 값 조회 실패: project_id=%s", project_id)
|
||||
values = {}
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "success",
|
||||
"fields": [
|
||||
{"key": key, "source": source, "label": label}
|
||||
for key, source, label in DRAWING_FIELDS
|
||||
],
|
||||
"values": values,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
⚠ 등록은 `main.py`(로그인만) · 시스템 · 회사 · 개인 층 권한은 `M02_Layer_Access`(나무 · 항목 길과
|
||||
한 벌 · PLAN 27-1c · `owner` = 회사 `{C}` · 개인 `{C}/{U}`) · 남의 층 목록 = `/layers/{층}/owners`:
|
||||
project 같은 회사 프로젝트 · 작업본 쓰기 · `_initial/` 은 안 씀 ·
|
||||
가져오기(apply · sources)는 같은 회사 사람 개인 층도 읽음
|
||||
project 같은 회사 프로젝트 · 작업본 쓰기 · `_initial/` 은 안 씀
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +14,7 @@ from typing import Any, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from pydantic import BaseModel
|
||||
|
||||
from B06_Section.B06_Section_Repository import (
|
||||
get_cross_section_designs,
|
||||
@@ -50,27 +49,6 @@ class SaveBody(BaseModel):
|
||||
문서: dict[str, Any]
|
||||
|
||||
|
||||
class TargetBody(BaseModel):
|
||||
종류: str | None = None
|
||||
이름: str | None = None
|
||||
|
||||
|
||||
class ApplyBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
from_: Layer = Field(alias="from")
|
||||
user_id: int | None = None
|
||||
project_id: str | None = None
|
||||
종류: str | None = None
|
||||
이름: str | None = None
|
||||
|
||||
|
||||
class SaveAsBody(BaseModel):
|
||||
to: Literal["personal", "company"]
|
||||
종류: str
|
||||
이름: str
|
||||
|
||||
|
||||
# ── DB (시험이 바꿔 끼움) ─────────────────────────────
|
||||
|
||||
|
||||
@@ -89,16 +67,6 @@ async def _project_row(project_id: str) -> dict[str, Any] | None:
|
||||
return dict(zip(keys, row, strict=True))
|
||||
|
||||
|
||||
async def _user_company(user_id: int) -> int | None:
|
||||
pool = get_db_pool()
|
||||
async with pool.acquire() as connection, connection.cursor() as cursor:
|
||||
await cursor.execute(
|
||||
"SELECT company_id FROM users WHERE id = %s AND deleted_at IS NULL", (user_id,)
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
async def _company_users(company_id: int) -> list[dict[str, Any]]:
|
||||
pool = get_db_pool()
|
||||
async with pool.acquire() as connection, connection.cursor() as cursor:
|
||||
@@ -145,7 +113,6 @@ async def _cross_designs(project_id: str) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
_is_system_admin = access.is_system_admin
|
||||
_is_company_admin = access.is_company_admin
|
||||
|
||||
|
||||
async def _project(session: dict[str, Any], project_id: str | None) -> dict[str, Any]:
|
||||
@@ -170,15 +137,6 @@ def _company_of(session: dict[str, Any], project: dict[str, Any] | None) -> int:
|
||||
return int(company_id)
|
||||
|
||||
|
||||
async def _same_company_user(session: dict[str, Any], user_id: int, company_id: int) -> None:
|
||||
"""남의 개인 양식 = 그 회사를 맡은 사람만(39-6 · 층 길과 한 규칙) · 그 회사 사람이어야 함."""
|
||||
if user_id == session.get("user_id"):
|
||||
return
|
||||
access.grant(session, "personal", f"{company_id}/{user_id}")
|
||||
if await _user_company(user_id) != company_id:
|
||||
raise HTTPException(status_code=403, detail="같은 회사 사람의 양식만 볼 수 있습니다.")
|
||||
|
||||
|
||||
async def _layer_dir(
|
||||
session: dict[str, Any],
|
||||
layer: str,
|
||||
@@ -450,147 +408,6 @@ async def delete_layer_template(
|
||||
# ── 프로젝트 길 ───────────────────────────────────────
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/templates/reset")
|
||||
async def reset_project_templates(
|
||||
project_id: str,
|
||||
body: TargetBody | None = None,
|
||||
session: dict[str, Any] = Depends(verify_session),
|
||||
) -> dict[str, Any]:
|
||||
project = await _project(session, project_id)
|
||||
target = body or TargetBody()
|
||||
try:
|
||||
done = await asyncio.to_thread(
|
||||
layers.reset_project, project["root"], kind=target.종류, name=target.이름
|
||||
)
|
||||
except ValueError as error:
|
||||
raise _bad(error) from error
|
||||
return {"초기화": done}
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/templates/apply")
|
||||
async def apply_project_templates(
|
||||
project_id: str,
|
||||
body: ApplyBody,
|
||||
session: dict[str, Any] = Depends(verify_session),
|
||||
) -> dict[str, Any]:
|
||||
"""다른 층 양식을 작업본에 덮어씀 — [회사 양식 적용] · [양식 가져오기].
|
||||
|
||||
`_initial/` 은 그대로 — 초기화 기준은 안 바뀜.
|
||||
"""
|
||||
project = await _project(session, project_id)
|
||||
ref: dict[str, Any] = {}
|
||||
if body.from_ == "project":
|
||||
if not body.project_id or body.project_id == project_id:
|
||||
raise HTTPException(status_code=400, detail="가져올 다른 프로젝트를 고르세요.")
|
||||
other = await _project(session, body.project_id)
|
||||
if other["company_id"] != project["company_id"]:
|
||||
raise HTTPException(status_code=403, detail="같은 회사 프로젝트만 가져옵니다.")
|
||||
source = layers.project_dir(other["root"])
|
||||
ref = {"project_id": body.project_id, "프로젝트": other.get("name")}
|
||||
elif body.from_ == "personal":
|
||||
owner = body.user_id if body.user_id is not None else int(session["user_id"])
|
||||
await _same_company_user(session, owner, int(project["company_id"]))
|
||||
source = layers.personal_dir(project["company_id"], owner)
|
||||
ref = {"user_id": owner}
|
||||
elif body.from_ == "company":
|
||||
source = layers.company_dir(project["company_id"])
|
||||
else:
|
||||
source = layers.system_dir()
|
||||
try:
|
||||
done = await asyncio.to_thread(
|
||||
layers.copy_templates,
|
||||
source,
|
||||
layers.project_dir(project["root"]),
|
||||
source_layer=body.from_,
|
||||
kind=body.종류,
|
||||
name=body.이름,
|
||||
source_ref=ref,
|
||||
)
|
||||
except ValueError as error:
|
||||
raise _bad(error) from error
|
||||
if not done:
|
||||
raise HTTPException(status_code=404, detail="가져올 양식이 없습니다.")
|
||||
return {"적용": done, "from": body.from_}
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/templates/save-as")
|
||||
async def save_project_template_as(
|
||||
project_id: str,
|
||||
body: SaveAsBody,
|
||||
session: dict[str, Any] = Depends(verify_session),
|
||||
) -> dict[str, Any]:
|
||||
"""작업본 한 벌을 [내 양식으로 저장] · [회사 공식으로 저장]."""
|
||||
project = await _project(session, project_id)
|
||||
if body.to == "company" and not _is_company_admin(session):
|
||||
raise HTTPException(status_code=403, detail="회사 공식 양식은 회사 관리자만.")
|
||||
if body.to == "company":
|
||||
target = layers.company_dir(project["company_id"])
|
||||
else:
|
||||
target = layers.personal_dir(project["company_id"], session["user_id"])
|
||||
try:
|
||||
done = await asyncio.to_thread(
|
||||
layers.copy_templates,
|
||||
layers.project_dir(project["root"]),
|
||||
target,
|
||||
source_layer="project",
|
||||
kind=body.종류,
|
||||
name=body.이름,
|
||||
source_ref={"project_id": project_id, "프로젝트": project.get("name")},
|
||||
)
|
||||
except ValueError as error:
|
||||
raise _bad(error) from error
|
||||
if not done:
|
||||
raise HTTPException(status_code=404, detail="프로젝트 작업본에 그 양식이 없습니다.")
|
||||
return {"저장": done, "to": body.to}
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}/sources")
|
||||
async def list_sources(
|
||||
project_id: str,
|
||||
session: dict[str, Any] = Depends(verify_session),
|
||||
) -> dict[str, Any]:
|
||||
"""가져올 수 있는 것 — 시스템 · 회사 공식 · 같은 회사 사람 개인 · 같은 회사 다른 프로젝트."""
|
||||
project = await _project(session, project_id)
|
||||
company_id = int(project["company_id"])
|
||||
|
||||
def _people(users: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
rows = []
|
||||
for user in users:
|
||||
found = layers.list_templates(layers.personal_dir(company_id, user["user_id"]))
|
||||
if found:
|
||||
rows.append({**user, "양식": found})
|
||||
return rows
|
||||
|
||||
def _projects(projects: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
rows = []
|
||||
for other in projects:
|
||||
if other["project_id"] == str(project_id) or not other.get("storage_path"):
|
||||
continue
|
||||
try:
|
||||
root = Path(resolve_stored_project_path(other["storage_path"]))
|
||||
except ValueError:
|
||||
continue
|
||||
found = layers.list_templates(layers.project_dir(root))
|
||||
if found:
|
||||
rows.append(
|
||||
{"project_id": other["project_id"], "name": other["name"], "양식": found}
|
||||
)
|
||||
return rows
|
||||
|
||||
users = [ # 남의 개인 = 그 회사를 맡은 사람만(39-6)
|
||||
u
|
||||
for u in await _company_users(company_id)
|
||||
if u["user_id"] == session.get("user_id") or access.manages(session, company_id)
|
||||
]
|
||||
projects = await _company_projects(company_id)
|
||||
return {
|
||||
"system": await asyncio.to_thread(layers.list_templates, layers.system_dir()),
|
||||
"company": await asyncio.to_thread(layers.list_templates, layers.company_dir(company_id)),
|
||||
"personal": await asyncio.to_thread(_people, users),
|
||||
"project": await asyncio.to_thread(_projects, projects),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}/tables/{name}/filled")
|
||||
async def filled_table(
|
||||
project_id: str,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete_Sangeun_Cover.ts
|
||||
* 단가산출(SK) 셈 길 부름 · 뺀 줄 띠(PLAN 717-2b · 717-3 · 724-1)
|
||||
* · 셈 = `calcSangeun`(`POST /layers/{층}/sangeun/calc` · 저장 안 함 · 부르는 쪽이 최신 응답만 받음) ·
|
||||
* [단가산출로 저장] = `sangeunFromLine`(`/sangeun/from-line`)
|
||||
* · 셈 = `calcSangeun`(`POST /layers/{층}/sangeun/calc` · 저장 안 함 · 부르는 쪽이 최신 응답만 받음)
|
||||
* · 고침 표는 공용 상세(`M01_MasterData_UI_LogicLab_Ho` · 724-1) — 여기는 뺀 줄 되살림 띠만
|
||||
* ========================================================================== */
|
||||
|
||||
@@ -12,8 +11,7 @@ import { el } from "@ui/ui_template_elements";
|
||||
import { t as L } from "@ui/ui_template_locale";
|
||||
import { createText } from "@ui/ui_template_text";
|
||||
import { call, type Layer } from "./M02_MasterTemplete_Api_Fetch";
|
||||
import { withSameAsk } from "./M02_MasterTemplete_Library_SameAsk";
|
||||
import type { PatchRow, SkAnswer } from "./logic/M02_Sangeun_Cover_Model";
|
||||
import type { SkAnswer } from "./logic/M02_Sangeun_Cover_Model";
|
||||
import "./M02_MasterTemplete_Sangeun.css";
|
||||
|
||||
export interface SkScope {
|
||||
@@ -37,21 +35,6 @@ export function calcSangeun<T = SkAnswer>(
|
||||
});
|
||||
}
|
||||
|
||||
/** [단가산출로 저장] — 그 층 새 SK · 답 = 새 키 + 그 SK 참조 줄 · 같은 내용이 있으면 물음(733-3 ·
|
||||
* 그것을 씀 = 그 키 · 그래도 새로) · 취소 = null */
|
||||
export const sangeunFromLine = (
|
||||
scope: SkScope,
|
||||
line: PatchRow & Record<string, unknown>,
|
||||
이름: string,
|
||||
단위: string,
|
||||
): Promise<{ 이름: string; 줄: Record<string, unknown> } | null> =>
|
||||
withSameAsk((extra) =>
|
||||
call(`/layers/${scope.layer}/sangeun/from-line${q(scope)}`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ 줄: line, 이름, 단위, ...extra }),
|
||||
}),
|
||||
);
|
||||
|
||||
/** 뺀 줄(cid · 이름) 띠 — 고칠 수 있으면 [되살림] */
|
||||
export function removedStrip(
|
||||
removed: { cid: string; 이름: string }[],
|
||||
|
||||
@@ -8,22 +8,19 @@
|
||||
[재생성] = 끊은 기초의 줄은 안 바꿈(자원 단가만 — 단가는 SK 사본 `단가` · [단가 갱신] 한 길).
|
||||
다시 잇기 = `끊음` · `수식고침` 뗌 + 표지 `다시잇기`(서버만 · 셈·저장 첫머리 `Copy.settle` 이 그 기초가 닿는
|
||||
닫힌 묶음을 지금 M01 줄로 갈음하고 표지 뗌 — 고친 것 버림).
|
||||
길(`M02_Sangeun_Router`): POST …/sangeun/block/{unlink|relink} {문서, 차례} → {문서, 전, 후}(저장 없음) ·
|
||||
POST …/sangeun/equation[/preview] 몸 `블록` = 더한줄 차례 → 그 끊은 기초의 수식(고침 통째 미리 셈).
|
||||
화면 길(끊기 · 다시 잇기 · 끊은 기초 수식 탭)은 걷음(894) — 남은 것 = 저장 문서의 `끊음` · `수식고침` 꼴 · 셈.
|
||||
저장 = SK [저장](서버가 다시 얹어 검사 · 셈 · 브라우저 값 안 받음 — 끊음 줄은 사본과 같은 `taken` 꼴 검사).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from M02_MasterTemplete import M02_Item_Prices as prices
|
||||
from M02_MasterTemplete import M02_Sangeun_Copy as skc
|
||||
from M02_MasterTemplete import M02_Sangeun_Doc as sd
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
|
||||
|
||||
CUT, EDIT, REJOIN = "끊음", eqm.KEY, "다시잇기"
|
||||
CUT, EDIT = "끊음", eqm.KEY
|
||||
MANY = 400 # 끊은 기초가 닿는 줄 상한
|
||||
_OWN: dict[int, tuple[Any, Any, Any]] = {}
|
||||
|
||||
@@ -95,118 +92,3 @@ def names(doc: Any) -> list[str]:
|
||||
"""끊은 기초 이름들([단가 갱신] · [재생성] 보고)."""
|
||||
adds = (doc.get("더한줄") if isinstance(doc, dict) else None) or []
|
||||
return [str(x.get("이름") or x.get("로직")) for x in adds if is_block(x) and x.get(CUT)]
|
||||
|
||||
|
||||
# ── 끊기 · 다시 잇기 ───────────────────────────────────────────────────
|
||||
def _one(doc: Any, at: Any) -> dict:
|
||||
adds = (doc.get("더한줄") if isinstance(doc, dict) else None) or []
|
||||
if not isinstance(at, int) or isinstance(at, bool) or not 0 <= at < len(adds):
|
||||
raise sd.DocError(f"더한 기초 차례 「{at}」 없음")
|
||||
if not is_block(adds[at]):
|
||||
raise sd.DocError("더한줄이 기초(로직) 아님")
|
||||
return adds[at]
|
||||
|
||||
|
||||
def _put(doc: dict, at: int, one: dict) -> dict:
|
||||
return {**doc, "더한줄": [one if k == at else x for k, x in enumerate(doc["더한줄"])]}
|
||||
|
||||
|
||||
def _closure(doc: dict, code: str) -> list[dict]:
|
||||
"""`code` 가 닿는 닫힌 묶음(자원 단가 빼고) — 사본 있으면 사본 줄 그대로 · 없으면 지금 M01."""
|
||||
over = doc[skc.KEY]["로직"] if skc.has(doc) else None
|
||||
got = prices.collect([code], None, None, over)
|
||||
got.pop("_빠진", None)
|
||||
whole = skc.over(doc, skc.whole_())
|
||||
keys = [str(r.get("키")) for data in got.values() for r in data[prices.m01.items_key(data)]]
|
||||
rows = [
|
||||
whole.index[k[:2]][k]
|
||||
for k in keys
|
||||
if k[:2] not in skc.RES and k in whole.index.get(k[:2], {})
|
||||
]
|
||||
return prices.to_json(rows)
|
||||
|
||||
|
||||
def unlink(doc: Any, at: int) -> dict:
|
||||
"""[연결 끊기] — 그 기초가 닿는 닫힌 묶음을 이 SK 안에 굳힘(금액 그대로)."""
|
||||
one = _one(doc, at)
|
||||
if one.get(CUT):
|
||||
raise sd.DocError("이미 연결을 끊은 기초")
|
||||
if any(one.get(k) not in (None, {}, []) for k in sd.BODY):
|
||||
raise sd.DocError("넣은 SK 몸은 이미 이 SK 안 사본 — 연결 끊기 없음")
|
||||
rows = _closure(skc.settle(doc), str(one["로직"]))
|
||||
if not rows:
|
||||
raise sd.DocError(f"기초 「{one['로직']}」 줄을 못 찾음")
|
||||
cut = {"시점": datetime.now().isoformat(timespec="seconds"), "로직": rows}
|
||||
return _put(doc, at, {**one, CUT: cut})
|
||||
|
||||
|
||||
def relink(doc: Any, at: int) -> dict:
|
||||
"""[다시 잇기] — 끊음 · 고침 버림 + 표지(셈·저장 때 사본을 지금 M01 줄로 갈음)."""
|
||||
one = _one(doc, at)
|
||||
if not one.get(CUT):
|
||||
raise sd.DocError("연결된 기초")
|
||||
keep = {k: v for k, v in one.items() if k not in (CUT, EDIT)}
|
||||
return _put(doc, at, {**keep, REJOIN: True})
|
||||
|
||||
|
||||
def change(doc: Any, at: Any, how: str) -> dict:
|
||||
"""길 몸 — {문서, 전, 후}(전후 SK 금액 · 끊기 전후 같음)."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation_Full as full
|
||||
|
||||
new = (unlink if how == "unlink" else relink)(doc, at)
|
||||
money = [full.total(full.answer(d, None)) for d in (doc, new)]
|
||||
return {"문서": new, "전": money[0], "후": money[1]}
|
||||
|
||||
|
||||
# ── 수식 탭 ────────────────────────────────────────────────────────────
|
||||
def _setup(doc: Any, at: Any) -> tuple[dict, Any, dict]:
|
||||
if not isinstance(doc, dict):
|
||||
raise sd.DocError("단가산출 문서가 묶음 아님")
|
||||
one = _one(doc, at)
|
||||
if not one.get(CUT):
|
||||
raise sd.DocError("연결된 기초 — 먼저 [연결 끊기]")
|
||||
doc = skc.settle(doc)
|
||||
return doc, skc.over(doc, skc.whole_()), doc["더한줄"][at]
|
||||
|
||||
|
||||
def view(whole: Any, doc: dict, one: dict, edits: list | None, inputs: dict | None) -> tuple:
|
||||
"""(수식, 못 얹은 까닭) — 고친 줄을 그대로 그림(세부 덮개 · 뺀줄 얹기 전 = 고침 주소 그대로)."""
|
||||
row, why, mine = row_of(whole, one, edits)
|
||||
if why:
|
||||
return None, why
|
||||
code = str(one["로직"])
|
||||
given = {k: v for k, v in (one.get("입력값") or {}).items() if str(v).strip()}
|
||||
given = {**(doc.get("입력값") or {}), **(inputs or {}), **given}
|
||||
return eqm.export(mine, {**row, "키": code}, given), []
|
||||
|
||||
|
||||
def read(doc: Any, at: Any, inputs: dict | None = None) -> dict[str, Any]:
|
||||
"""{ok, 수식 | reason} — 끊은 기초 수식(자기 고침 얹음)."""
|
||||
doc, whole, one = _setup(doc, at)
|
||||
eq, why = view(whole, doc, one, None, inputs)
|
||||
return {"ok": False, "reason": " · ".join(why)} if why else {"ok": True, "수식": eq}
|
||||
|
||||
|
||||
def preview(doc: Any, at: Any, edits: list, inputs: dict | None = None) -> dict[str, Any]:
|
||||
"""고침 통째 미리 셈(저장 없음) — {되나, 까닭, 줄, 수식, 전(기초 고침 없음), 후, 금액전, 금액후(SK)}."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation_Full as full
|
||||
|
||||
doc, whole, one = _setup(doc, at)
|
||||
eq, why = view(whole, doc, one, edits, inputs)
|
||||
if why:
|
||||
return {"되나": False, "까닭": why}
|
||||
bare = {k: v for k, v in one.items() if k != EDIT}
|
||||
mine = {**bare, EDIT: edits} if edits else bare
|
||||
plain = view(whole, doc, bare, None, inputs)[0] if edits else eq
|
||||
row = row_of(whole, bare, edits)[0]
|
||||
money = [full.total(full.answer(d, inputs)) for d in (doc, _put(doc, at, mine))]
|
||||
return {
|
||||
"되나": True,
|
||||
"까닭": [],
|
||||
"줄": {**row, "입력": []}, # 입력 칸 = SK 쪽 것만(끊은 기초 입력은 더한 기초 자리에서)
|
||||
"수식": eq,
|
||||
"전": plain["합계"],
|
||||
"후": eq["합계"],
|
||||
"금액전": money[0],
|
||||
"금액후": money[1],
|
||||
}
|
||||
|
||||
@@ -612,25 +612,3 @@ def calc_doc(doc: Any, given: dict | None = None, seen: bool = True) -> dict[str
|
||||
except sd.DocError as e:
|
||||
raise _fail(e) from e
|
||||
return skc.mark(const.answer(got, clean, doc, given, (me,)), clean) # 790-2 · 795-1
|
||||
|
||||
|
||||
def from_line(
|
||||
line: Any, name: str, unit: str, new: bool = False, use: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""[단가산출로 저장](715-3) — 일위대가 줄(바탕 · 입력값 · 고름 · 줄 덮개) → 지금 층 새 SK ·
|
||||
답 = `{이름: 새 키, 줄: 그 SK 참조 줄}`(일위대가 문서는 화면 [저장] 때 바뀜) ·
|
||||
같은 층 같은 내용 SK = 409(733-2) → `new` 그래도 새로 · `use` 그 SK(새로 안 만듦)."""
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
from M02_MasterTemplete import M02_Labor_Patch as patch
|
||||
from M02_MasterTemplete import M02_Library_Ask as ask
|
||||
|
||||
if not isinstance(line, dict):
|
||||
raise store.StoreError(400, "줄이 묶음 아님")
|
||||
doc = patch.to_sangeun(line, name, unit, m01.loaded()[1])
|
||||
key = ask.ask(sd.KIND, doc, new, use) or refs.create(sd.KIND, doc)["이름"]
|
||||
at = refs.here()
|
||||
keep = {k: line[k] for k in ("별칭", "메모", "수량") if k in line}
|
||||
return {
|
||||
"이름": key,
|
||||
"줄": {"참조": {"층": at[0], "주인": at[1], "키": key}, **keep},
|
||||
}
|
||||
|
||||
@@ -8,16 +8,9 @@
|
||||
모든 셈 길(화면 · 저장 원값 · B09 · 펼침) 같은 줄 · 못 얹은 고침(재생성 뒤 자리 없음 등) =
|
||||
고침 없는 바탕 + 짝잃음 cid `수식` · 저장(`strict`) = 400 · [재생성] = 새 사본에 같은 고침
|
||||
다시 얹음(못 얹음 = 795-1 `못얹은`).
|
||||
길(`M02_Sangeun_Router` · 저장 없음):
|
||||
POST …/sangeun/equation {문서, inputs?} → {ok, 수식 | reason}(층 읽기)
|
||||
POST …/sangeun/equation/preview {문서, inputs?, 고침} → {되나, 까닭, 줄, 수식, 전, 후}
|
||||
(고침 = `수식고침` 통째 · 전 = 고침 없는 사본 합계 · 층 쓰기)
|
||||
저장 = SK [저장](화면 캐시 `수식고침` → `clean_doc` 이 다시 얹어 검사 · 셈 ·
|
||||
브라우저 값 안 받음).
|
||||
수식 탭 화면 길(읽기 · 미리 셈 · 합계 소계)은 걷음(894) — 남은 것 = 저장 문서 `수식고침` 꼴 · 셈 · 저장 검사.
|
||||
저장 = SK [저장](`clean_doc` 이 다시 얹어 검사 · 셈 · 브라우저 값 안 받음).
|
||||
바탕 참조 SK(`바탕.참조`) = 수식 없음(바탕 SK 의 고침은 그 SK 가 얹음).
|
||||
합계 · 소계(796-2c) = SK 셈 답 기준(`M02_Sangeun_Equation_Full` — 더한 기초 · 뺀줄 · 덮개 · 율 줄 ·
|
||||
합밖) · 줄 값 = 식 덮개 · 상수 · 표값 · 변수줄을 얹은 식(고침 주소는 바탕 차례 그대로) ·
|
||||
전 = 고침 없는 SK 금액.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -78,15 +71,6 @@ def _stand(row: dict) -> tuple[dict, str]:
|
||||
return (row, key) if key[:2] in ("GC", "GF", "GX") else ({**row, "키": STAND}, key)
|
||||
|
||||
|
||||
def export(whole: Any, row: dict, inputs: dict | None) -> dict:
|
||||
"""수식 읽기 — 입력 = 받은 값 › 자동값(SK 셈 `run_line` 과 같음 · 기본 제안값이 안 덮음)."""
|
||||
stand, key = _stand(row)
|
||||
eqn = _eqn()
|
||||
auto = eqn.meq.ma.values(eqn.me.swap(whole, stand), stand)
|
||||
given = {**{k: v for k, v in auto.items() if v is not None}, **(inputs or {})}
|
||||
return eqn.export_row(whole, stand, given) | {"열쇠": key}
|
||||
|
||||
|
||||
def apply(row: dict, edits: list, whole: Any) -> tuple[dict, list[str]]:
|
||||
"""바탕 줄 + 고침 → (새 줄, 까닭) — 같은 줄 · 같은 고침 = 메모(셈 길마다 다시 검사 안 함)."""
|
||||
tag = (_hash(row), _hash(edits))
|
||||
@@ -116,74 +100,3 @@ def strict(base: dict) -> None:
|
||||
for x in base.get("짝잃음") or []:
|
||||
if x.get("cid") == LOST and "바탕" not in x:
|
||||
raise sd.DocError(x["까닭"])
|
||||
|
||||
|
||||
# ── 길 ──────────────────────────────────────────────────────────────
|
||||
def _plain(doc: Any) -> tuple[dict, Any, dict]:
|
||||
"""(정한 문서, 사본 색인, 고침 없는 바탕 줄) — 바탕 참조 · 빈 SK = DocError."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
|
||||
if not isinstance(doc, dict):
|
||||
raise sd.DocError("단가산출 문서가 묶음 아님")
|
||||
base = doc.get("바탕") or {}
|
||||
if "참조" in base:
|
||||
raise sd.DocError("바탕 참조 단가산출 — 수식은 바탕 단가산출에서")
|
||||
doc = calc.skc.settle(doc)
|
||||
whole = calc.skc.over(doc, calc.labor.m01.loaded()[1])
|
||||
bare = {k: v for k, v in doc.items() if k != KEY}
|
||||
row = calc._base_of(bare, whole, calc.refs.read_ref, ())["줄"]
|
||||
if not row.get("중간") and not row.get("호표") and not row.get("결과"):
|
||||
raise sd.DocError("수식 없음 — 바탕 로직 · 가져온 식이 없는 단가산출")
|
||||
return doc, whole, row
|
||||
|
||||
|
||||
def _tree(doc: dict, whole: Any, base: dict, inputs: dict | None, ans: dict | None) -> dict:
|
||||
"""수식 = 바탕 줄(+ 고침 · 식 덮개 · 상수 · 표값 · 변수줄) + SK 셈 답 합계 · 소계(796-2c)."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Const as const
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation_Full as full
|
||||
|
||||
try:
|
||||
shown = const.formulas(base, doc)
|
||||
except Exception: # noqa: BLE001 — 틀린 식 덮개 = 바탕 그대로(짝잃음은 셈 길이 알림)
|
||||
shown = base
|
||||
return full.attach(export(whole, shown, inputs), doc, whole, base, inputs, ans)
|
||||
|
||||
|
||||
def read(doc: Any, inputs: dict | None = None) -> dict[str, Any]:
|
||||
"""{ok, 수식} — 저장본 · 화면 캐시 고침 얹은 수식(못 얹음 = 바탕 그대로 + 까닭)."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation_Full as full
|
||||
|
||||
eqn = _eqn()
|
||||
try:
|
||||
doc, whole, row = _plain(doc)
|
||||
now, lost = on(row, doc, whole)
|
||||
out = {"ok": True, "수식": _tree(doc, whole, now, inputs, full.answer(doc, inputs))}
|
||||
except (sd.DocError, *eqn._ERR) as e:
|
||||
return {"ok": False, "reason": str(e) or type(e).__name__}
|
||||
return out | ({"reason": lost[0]["까닭"]} if lost else {})
|
||||
|
||||
|
||||
def links(doc: Any, ask: dict) -> dict[str, Any]:
|
||||
"""새 기호 연결 후보(800-3) — M01 과 같은 후보 길(읽기만)."""
|
||||
return _eqn().links(ask)
|
||||
|
||||
|
||||
def preview(doc: Any, edits: list, inputs: dict | None = None) -> dict[str, Any]:
|
||||
"""고침 통째 미리 셈(저장 없음) — {되나, 까닭, 줄, 수식, 전(고침 없는 사본 SK 금액), 후}."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation_Full as full
|
||||
|
||||
eqn = _eqn()
|
||||
try:
|
||||
doc, whole, row = _plain(doc)
|
||||
new, why = apply(row, edits, whole) if edits else (row, [])
|
||||
if why:
|
||||
return {"되나": False, "까닭": why}
|
||||
bare = {k: v for k, v in doc.items() if k != KEY}
|
||||
mine = {**bare, KEY: edits} if edits else bare
|
||||
ans = full.answer(mine, inputs)
|
||||
eq = _tree(mine, whole, new, inputs, ans)
|
||||
before = full.total(full.answer(bare, inputs) if edits else ans)
|
||||
before = before or export(whole, row, inputs)["합계"]
|
||||
except (sd.DocError, *eqn._ERR) as e:
|
||||
return {"되나": False, "까닭": [f"셈 막힘 — {e}"]}
|
||||
return {"되나": True, "까닭": [], "줄": new, "수식": eq, "전": before, "후": eq["합계"]}
|
||||
|
||||
@@ -1,240 +0,0 @@
|
||||
"""M02 단가산출(SK) 수식 탭 — SK 셈 답 기준 소계 · 합계 · 고친 칸 표지(PLAN 796-2c · 요구 657).
|
||||
|
||||
수식 탭 줄(`M02_Sangeun_Equation`) = 바탕 사본 줄(+ 수식고침). 그 위에 SK 셈 답
|
||||
(`M02_Sangeun_Calc.calc_doc` = 화면 · 저장 · B09 가 쓰는 한 벌)을 얹어 화면 금액 = SK 금액
|
||||
(셈은 안 바꿈 · 보이기만):
|
||||
합계 = 셈 답 `기준`(노 · 재 · 경 · 계 · 1 단위) — 바탕 줄만 셈한 합계 대신
|
||||
소계 = 셈 답 `줄` → 돈 묶음(801-3 · `master_equation_group`) — 더한 · 부른 단가산출(갈래 블록) 하나씩
|
||||
{cid, 이름, 상태, 수량, 노 · 재 · 경 · 계, 덮개?, 원래?, 까닭?, 나무?} + 직접 줄(인력 · 재료 · 기계 ·
|
||||
덧줄 · 율) 한 묶음 {갈래 직접, 이름, 노 · 재 · 경 · 계, 낱줄?(더함 · 덮음 줄)} +
|
||||
끝수(합계 − 묶음 합 · 까닭 글) · 밖(합계 밖 줄 — 엔진이 합계에서 뺌 · 이름 · 밖금액)
|
||||
상태 = 바탕(그대로) · 덮음(품 · 단가 · 상수 · 표값 · 식 덮개 · 변수줄) ·
|
||||
더함(더한줄) · 뺌(뺀줄 · 금액 0)
|
||||
나무 = 더한 기초(더한줄 로직)의 수식(세부 덮개 · 뺀줄 얹은 줄) — 화면은 접힘 블록
|
||||
표지 = 수식 탭 줄에 고친 칸 {표지[갈래], 원래, 지금, 뺌} — 줄 값 = 식 덮개 · 상수 · 표값 ·
|
||||
변수줄을 얹은 식(`M02_Sangeun_Const.formulas`) · 품 · 단가 덮개는 줄 값에 안 얹고
|
||||
`지금` 으로 보임(고침 주소 = 바탕 차례 그대로)
|
||||
셈 답이 안 서는 SK(틀린 문서 · 돈 아닌 로직) = 바탕 줄 합계 그대로 + `답까닭`.
|
||||
시험 `resources/tester/test_796_2c_m02_equation_full.py`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from M02_MasterTemplete import M02_Sangeun_Doc as sd
|
||||
|
||||
COSTS = ("노무비", "재료비", "경비")
|
||||
SUMS = (*COSTS, "계")
|
||||
_ADD = re.compile(r"^add:#(\d+)$")
|
||||
_HEAD = {"labor": "자원", "material": "자원", "machine": "자원", "logic": "블록", "pct": "덧줄"}
|
||||
_ADD_KIND = {"인력": "자원", "재료": "자원", "기계": "자원"}
|
||||
_WORD = {"labor": "인력", "material": "재료", "machine": "기계"} # 직접 묶음 이름(801-3)
|
||||
|
||||
|
||||
def _d(value: Any) -> Decimal:
|
||||
return Decimal(str(value)) if value is not None else Decimal(0)
|
||||
|
||||
|
||||
def _errors() -> tuple:
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
|
||||
return (sd.DocError, store.StoreError, ArithmeticError, KeyError, TypeError, ValueError)
|
||||
|
||||
|
||||
def answer(doc: dict, inputs: dict | None) -> dict | None:
|
||||
"""SK 셈 답 — 못 셈(틀린 문서 · 돈 아닌 로직) = None."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
|
||||
try:
|
||||
got = calc.calc_doc(doc, inputs or None, False)
|
||||
except _errors():
|
||||
return None
|
||||
return got if got.get("기준") else None
|
||||
|
||||
|
||||
def total(ans: dict | None) -> dict | None:
|
||||
return {k: _d(ans["기준"].get(k)) for k in SUMS} if ans else None
|
||||
|
||||
|
||||
# ── 행 ────────────────────────────────────────────────────────────────
|
||||
def _kind(cid: str, adds: list) -> str:
|
||||
hit = _ADD.match(cid)
|
||||
if not hit:
|
||||
return _HEAD.get(cid.split(":", 1)[0], "자원")
|
||||
one = adds[int(hit[1])] if int(hit[1]) < len(adds) else {}
|
||||
if sd.is_rate(one):
|
||||
return "율"
|
||||
return _ADD_KIND.get(str(one.get("종류")), "블록")
|
||||
|
||||
|
||||
def _word(cid: str, adds: list) -> str:
|
||||
"""직접 줄의 자원 갈래 말 — 인력 · 재료 · 기계(그 밖 = 빈 글)."""
|
||||
hit = _ADD.match(cid)
|
||||
if not hit:
|
||||
return _WORD.get(cid.split(":", 1)[0], "")
|
||||
one = adds[int(hit[1])] if int(hit[1]) < len(adds) else {}
|
||||
return str(one.get("종류")) if one.get("종류") in _ADD_KIND else ""
|
||||
|
||||
|
||||
def _row(cid: str, kind: str, name: str, state: str, parts: dict | None, **more: Any) -> dict:
|
||||
cost = {k: _d((parts or {}).get(k)) for k in COSTS}
|
||||
return {
|
||||
"cid": cid,
|
||||
"갈래": kind,
|
||||
"이름": name,
|
||||
"상태": state,
|
||||
**cost,
|
||||
"계": sum(cost.values(), Decimal(0)),
|
||||
**{k: v for k, v in more.items() if v not in (None, [], "")},
|
||||
}
|
||||
|
||||
|
||||
def rows(doc: dict, ans: dict, tree: Any, out_ids: set[str] = frozenset()) -> list[dict]:
|
||||
"""셈 답 줄 → 행(셈 답 순서) + 뺀줄(금액 0) — `tree(더한줄 차례)` = 더한 기초 수식."""
|
||||
adds = doc.get("더한줄") or []
|
||||
spots = (ans.get("시트") or {}).get("자리") or {}
|
||||
out = []
|
||||
for line in ans.get("줄") or []:
|
||||
cid = str(line.get("cid") or "")
|
||||
hit = _ADD.match(cid)
|
||||
info = spots.get(cid) or {}
|
||||
cover = [k for k in info.get("덮개") or [] if k != "뺌"] or [
|
||||
k for k in line.get("덮개") or []
|
||||
]
|
||||
k = int(hit[1]) if hit else -1
|
||||
state = "더함" if hit else "덮음" if cover else "바탕"
|
||||
one = adds[k] if 0 <= k < len(adds) else {}
|
||||
if hit and one.get("종류") == "로직" and sd.sub_patched({**one, "끊음": None}):
|
||||
cover = cover or ["세부"]
|
||||
outside = cid in out_ids # 합계 밖 줄(가져온 식 `합밖` · 제외 단계) — 합에 안 듦
|
||||
out.append(
|
||||
_row(
|
||||
cid,
|
||||
_kind(cid, adds),
|
||||
str(line.get("이름") or info.get("이름") or ""),
|
||||
state,
|
||||
None if outside else line.get("비목"),
|
||||
합밖=outside or None,
|
||||
밖금액=sum((_d(v) for v in (line.get("비목") or {}).values()), Decimal(0))
|
||||
if outside
|
||||
else None,
|
||||
수량=line.get("수량"),
|
||||
종류=_word(cid, adds),
|
||||
덮개=cover,
|
||||
원래=info.get("원래") if state == "덮음" else None,
|
||||
까닭=line.get("까닭") or info.get("까닭"),
|
||||
나무=tree(k) if hit and one.get("종류") == "로직" else None,
|
||||
블록=k if hit and one.get("종류") == "로직" else None, # 더한 기초 차례(연결 끊기)
|
||||
끊음=True if one.get("끊음") else None,
|
||||
)
|
||||
)
|
||||
for cid in doc.get("뺀줄") or []: # 지운 줄 — 금액 0 · 원래 금액만 보임
|
||||
info = spots.get(cid) or {}
|
||||
out.append(
|
||||
_row(
|
||||
cid,
|
||||
_kind(cid, adds),
|
||||
str(info.get("이름") or ""),
|
||||
"뺌",
|
||||
None,
|
||||
원래=info.get("원래"),
|
||||
까닭=info.get("까닭"),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _why(ans: dict) -> str:
|
||||
"""끝수 까닭 — 합계는 엔진이 비목마다 합쳐 버린 값 · 행은 줄마다 버린 값."""
|
||||
text = ["줄마다 버린 값의 합 ≠ 엔진 비목 합(품셈 1-2-2 끝수)"]
|
||||
if _d(ans.get("화면배") or 1) != 1:
|
||||
text.append(f"단위 환산 ÷ {ans['화면배']}")
|
||||
rate = ans.get("켜쌓기율")
|
||||
if rate not in (None, 100):
|
||||
text.append(f"켜쌓기율 {rate} %")
|
||||
return " · ".join(text)
|
||||
|
||||
|
||||
# ── 더한 기초 수식 ─────────────────────────────────────────────────────
|
||||
def _basic_tree(whole: Any, doc: dict, one: dict, inputs: dict | None) -> dict | None:
|
||||
"""더한줄 로직 하나의 수식 — 세부 덮개 · 뺀줄 얹은 줄 · 입력 = 줄 값 › 공통 옵션 › 자동."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
|
||||
|
||||
if any(one.get(k) not in (None, {}, []) for k in sd.BODY):
|
||||
return None
|
||||
if one.get("끊음"): # 끊은 기초(796-2e) = 자기 사본 줄 + 수식 고침(고침 주소 그대로)
|
||||
from M02_MasterTemplete import M02_Sangeun_Block as blk
|
||||
|
||||
return blk.view(whole, doc, one, None, inputs)[0]
|
||||
code = str(one["로직"])
|
||||
mine = {k: v for k, v in (one.get("입력값") or {}).items() if str(v).strip()}
|
||||
given = {**(doc.get("입력값") or {}), **(inputs or {}), **mine}
|
||||
try:
|
||||
row = sd.patched(whole.logic(code), one)["줄"]
|
||||
return eqm.export(whole, {**row, "키": code}, given)
|
||||
except Exception: # noqa: BLE001 — 엔진 FormulaError · 기초 하나가 틀려도 나머지는 그림
|
||||
return None
|
||||
|
||||
|
||||
# ── 줄 표지 ────────────────────────────────────────────────────────────
|
||||
def _mark(eq: dict, base: dict, ans: dict, doc: dict) -> None:
|
||||
"""수식 탭 줄에 고친 칸 표지 — 자리 = 바탕 cid(호표 · 덧줄) · `mid:이름`."""
|
||||
spots = (ans.get("시트") or {}).get("자리") or {}
|
||||
ids = sd.line_ids(base)
|
||||
heads = len(base.get("호표") or [])
|
||||
for line in eq.get("줄") or []:
|
||||
if line["갈래"] == "중간":
|
||||
spot = f"mid:{line['열쇠']}"
|
||||
elif line["갈래"] == "호표":
|
||||
spot = ids[line["차례"]] if line.get("차례", 0) < len(ids) else ""
|
||||
elif line["갈래"] == "덧줄":
|
||||
at = heads + line.get("차례", 0)
|
||||
spot = ids[at] if at < len(ids) else ""
|
||||
else:
|
||||
continue
|
||||
info = spots.get(spot) or {}
|
||||
kinds = list(info.get("덮개") or [])
|
||||
if not kinds:
|
||||
continue
|
||||
line["표지"] = [k for k in kinds if k != "뺌"]
|
||||
line["원래"], line["지금"] = info.get("원래"), info.get("지금")
|
||||
if "뺌" in kinds:
|
||||
line["뺌"] = True
|
||||
|
||||
|
||||
def _outside(base: dict) -> set[str]:
|
||||
"""합계 밖 줄 cid — 엔진이 비목 합에서 빼는 줄(`master_formula_sum.skipped`)."""
|
||||
import master_cut as mcut # M01 이 길을 둔 뒤(수식 탭 export 가 먼저)
|
||||
|
||||
if not mcut.ms.uses(base):
|
||||
return set()
|
||||
ids = sd.line_ids(base)
|
||||
return {ids[i] for i in mcut.ms.skipped(base) if i < len(ids)}
|
||||
|
||||
|
||||
# ── 붙이기 ────────────────────────────────────────────────────────────
|
||||
def attach(
|
||||
eq: dict, doc: dict, whole: Any, base: dict, inputs: dict | None, ans: dict | None
|
||||
) -> dict:
|
||||
"""수식 `eq` 에 SK 셈 답 합계 · 소계 · 표지를 얹음(제자리) — 답 없음 = `답까닭` 만."""
|
||||
import master_equation_group as grp # M01 이 길을 둔 뒤
|
||||
|
||||
if ans is None:
|
||||
return eq | {"답까닭": "단가산출 셈 답이 서지 않음 — 바탕 줄 합계를 보임"}
|
||||
_mark(eq, base, ans, doc)
|
||||
adds = doc.get("더한줄") or []
|
||||
table = rows(
|
||||
doc,
|
||||
ans,
|
||||
lambda k: _basic_tree(whole, doc, adds[k], inputs) if k >= 0 else None,
|
||||
_outside(base),
|
||||
)
|
||||
got = grp.bundles(table) # 801-3 묶음 — 부른 · 더한 단가산출 하나씩 + 직접 줄 한 묶음
|
||||
now = total(ans) or {}
|
||||
rest = {k: now[k] - sum((r[k] for r in got["줄"]), Decimal(0)) for k in SUMS}
|
||||
eq["합계"] = now
|
||||
eq["소계"] = {"줄": got["줄"], "밖": got["밖"], "끝수": rest, "끝수까닭": _why(ans)}
|
||||
return eq
|
||||
@@ -527,92 +527,3 @@ def name_table(base: dict, clean: dict) -> list[dict]:
|
||||
out += [{"글": f"번지.{x['번지']}", "갈래": "번지"} for x in lines if x.get("번지")]
|
||||
out += [{"글": f"단계.'{x.get('이름')}'", "갈래": "단계"} for x in base.get("단계") or []]
|
||||
return out
|
||||
|
||||
|
||||
# ── 검사 길(시트가 칠 때마다 · 셈 없음) ──────────────────────────────
|
||||
def check_doc(doc: Any, spot: str, text: str) -> dict[str, Any]:
|
||||
"""식 글 하나 → {되나, 까닭, 알림, 식(엔진), 글(이름 꼴)} — 자리 = 중간 `mid:이름`(변수 줄
|
||||
포함) · 호표 · 덧줄 cid · `add:#k` · 문서 = 화면 캐시(그 자리 옛 식은 빼고 봄)."""
|
||||
from M02_MasterTemplete import M02_Labor_Ref as refs
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
|
||||
text = str(text or "").strip()
|
||||
out: dict[str, Any] = {"되나": False, "까닭": [], "알림": [], "식": None, "글": None}
|
||||
if not text:
|
||||
return out | {"까닭": ["식이 빔"]}
|
||||
if bad := limits(text):
|
||||
return out | {"까닭": bad}
|
||||
whole, doc = _whole(), _without(doc if isinstance(doc, dict) else {}, spot)
|
||||
try:
|
||||
clean_ = sd.clean(doc, None, whole)
|
||||
base = calc._base_of(clean_, whole, refs.read_ref, ())["줄"]
|
||||
except sd.DocError as e:
|
||||
return out | {"까닭": [f"문서 · {e}"]}
|
||||
got, why = to_engine(text, base)
|
||||
if why:
|
||||
return out | {"까닭": why}
|
||||
out |= {"식": got, "글": to_name(got, base)}
|
||||
trial, why = _put(clean_, base, spot, got)
|
||||
if why:
|
||||
return out | {"까닭": [why]}
|
||||
bad = [b["까닭"].removeprefix("식 — ") for b in settle(base, trial)[1] if b["cid"] == spot]
|
||||
return out | {"되나": not bad, "까닭": bad, "알림": _risks(got, base, trial)}
|
||||
|
||||
|
||||
def _without(doc: dict, spot: str) -> dict:
|
||||
"""그 자리 옛 식을 뺀 문서(옛 식이 틀려도 문서 검사가 안 막게)."""
|
||||
out = dict(doc)
|
||||
if isinstance(out.get("식덮개"), dict):
|
||||
out["식덮개"] = {k: v for k, v in out["식덮개"].items() if k != spot}
|
||||
if isinstance(out.get("변수줄"), list):
|
||||
out["변수줄"] = [
|
||||
{**x, "식": "0"} if isinstance(x, dict) and f"mid:{x.get('이름')}" == spot else x
|
||||
for x in out["변수줄"]
|
||||
]
|
||||
hit = _ADD.match(spot)
|
||||
if hit and isinstance(out.get("더한줄"), list) and int(hit[1]) < len(out["더한줄"]):
|
||||
adds = list(out["더한줄"])
|
||||
adds[int(hit[1])] = {k: v for k, v in dict(adds[int(hit[1])]).items() if k != "수량식"}
|
||||
out["더한줄"] = adds
|
||||
return out
|
||||
|
||||
|
||||
def _put(doc: dict, base: dict, spot: str, text: str) -> tuple[dict, str | None]:
|
||||
"""문서 그 자리에 식(엔진) — (새 문서, 못 넣는 까닭)."""
|
||||
names = [x["이름"] for x in doc.get("변수줄") or []]
|
||||
hit = _ADD.match(spot)
|
||||
if spot.startswith("mid:") and spot[4:] in names:
|
||||
lines = [{**x, "식": text} if x["이름"] == spot[4:] else x for x in doc["변수줄"]]
|
||||
return {**doc, "변수줄": lines}, None
|
||||
if spot in _places(base):
|
||||
if spot in (doc.get("상수덮개") or {}) or spot in (doc.get("표값덮개") or {}):
|
||||
return doc, "상수 · 표값 덮개가 있는 줄 — [M01 원래로] 뒤 식 고침"
|
||||
return {**doc, "식덮개": {**(doc.get("식덮개") or {}), spot: text}}, None
|
||||
adds = doc.get("더한줄") or []
|
||||
if hit and int(hit[1]) < len(adds):
|
||||
one = adds[int(hit[1])]
|
||||
if sd.is_rate(one) or one.get("종류") == "로직":
|
||||
return doc, "율 줄 · 로직 줄 수량은 수만"
|
||||
adds = [{**x, "수량식": text} if k == int(hit[1]) else x for k, x in enumerate(adds)]
|
||||
return {**doc, "더한줄": adds}, None
|
||||
return doc, f"없는 자리 「{spot}」"
|
||||
|
||||
|
||||
def _risks(text: str, base: dict, doc: dict) -> list[str]:
|
||||
"""0 나눔 위험 — 나누는 쪽 이름이 입력값 0 · 고르기에 0."""
|
||||
mf, out = _eng(), []
|
||||
given = doc.get("입력값") or {}
|
||||
try:
|
||||
tree = mf.parse(text)
|
||||
except (mf.FormulaError, RecursionError):
|
||||
return out
|
||||
picks = {str(x.get("이름")): x.get("고르기") or [] for x in base.get("입력") or []}
|
||||
for node in mf.walk(tree):
|
||||
if node[0] == "bin" and node[1] == "/":
|
||||
for n in (x[1] for x in mf.walk(node[3]) if x[0] == "name"):
|
||||
zero = str(given.get(n)) in ("0", "0.0") or any(
|
||||
str(c) == "0" for c in picks.get(n, [])
|
||||
)
|
||||
if zero and f"「{n}」" not in " ".join(out):
|
||||
out.append(f"「{n}」 가 0 이면 0 나눔")
|
||||
return out
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
"""M02 단가산출(SK) 셈 길(PLAN 715-1b) — `POST /api/m02/layers/{층}/sangeun/calc` ·
|
||||
[단가산출로 저장](715-3) `POST /api/m02/layers/{층}/sangeun/from-line`(층 쓰기 권한) ·
|
||||
일위대가 [+ 줄] M01 기초 = 그 층 SK 사본(811-1 · `M02_Labor_SkRow`) `…/sangeun/from-logic`(층 쓰기) ·
|
||||
식 칸 검사(792-1) `POST /api/m02/layers/{층}/sangeun/formula-check`(셈 없음 · 층 읽기 권한) ·
|
||||
가져온 식(793-2 · `M02_Sangeun_Imported`) `…/sangeun/imported`(만들기 · 층 쓰기) · `/price` ·
|
||||
`/link`(화면 캐시 문서 고침 · 저장 없음 · 층 읽기 · 기초로 바꾸기 없음 · 809-1) ·
|
||||
불러오기 단산 블록 → 가져온 식(793-3b · `M02_Sangeun_FromHopyo`) `…/sangeun/from-hopyo`
|
||||
(늘 개인 층 쓰기 · 몸 `문서` = 미리 보기에서 고친 문서) · 미리 보기 `…/from-hopyo/preview`(층 읽기 · 안 씀 · 835-1).
|
||||
로직 사본(795-1 · `M02_Sangeun_Copy`) `…/sangeun/copy/price` [단가 갱신] · `/regen` [재생성]
|
||||
(화면 캐시 문서에 할일 얹음 · 저장 없음 · 층 읽기).
|
||||
수식 탭(796-2b · `M02_Sangeun_Equation`) `…/sangeun/equation`(층 읽기) · `/preview`(고침 미리 셈 ·
|
||||
층 쓰기) — 저장 없음 · 고침 = 화면 캐시 `수식고침` → [저장].
|
||||
더한 기초 [연결 끊기](796-2e · `M02_Sangeun_Block`) `…/sangeun/block/unlink` · `/relink`(화면 캐시 문서 고침 ·
|
||||
저장 없음 · 층 읽기) · 끊은 기초 수식 = 같은 equation 길 몸 `블록`(더한줄 차례).
|
||||
|
||||
저장 안 함 · 로그인 사용자 · 층 읽기 권한(`Router_Items._root`) · 화면은 최신 응답만.
|
||||
몸 = `문서`(저장 전 화면 문서) 또는 `키`(그 층 저장본) + `입력값`(열린입력 · 시험 값) ·
|
||||
@@ -30,12 +22,8 @@ from pydantic import BaseModel
|
||||
from common_util.common_util_auth import verify_session
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_MatPick as mat_pick
|
||||
from M02_MasterTemplete import M02_Sangeun_Block as blk
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
from M02_MasterTemplete import M02_Sangeun_Copy as skc
|
||||
from M02_MasterTemplete import M02_Sangeun_Doc as sd
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
|
||||
from M02_MasterTemplete import M02_Sangeun_Formula as fx
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as from_hopyo
|
||||
from M02_MasterTemplete import M02_Sangeun_Imported as imp
|
||||
from M02_MasterTemplete import M02_Sangeun_QtyLinks as qty
|
||||
@@ -60,26 +48,6 @@ def _calc(body: SangeunCalcBody) -> dict[str, Any]:
|
||||
return calc.calc_doc(doc, body.입력값, body.보기)
|
||||
|
||||
|
||||
class FromLineBody(BaseModel):
|
||||
줄: dict[str, Any]
|
||||
이름: str
|
||||
단위: str
|
||||
새로: bool = False # 같은 내용 409 뒤 — 그래도 새로(733-2)
|
||||
씀: str | None = None # 같은 내용 409 뒤 — 그 SK 씀
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/sangeun/from-line")
|
||||
def sangeun_from_line(
|
||||
layer: Layer,
|
||||
body: FromLineBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""[단가산출로 저장](715-3) — 일위대가 줄 → 그 층 새 단가산출 · 답 = 새 키 + 바꿀 참조 줄."""
|
||||
folder = _root(session, layer, owner, write=True)
|
||||
return _call(folder, calc.from_line, body.줄, body.이름, body.단위, body.새로, body.씀)
|
||||
|
||||
|
||||
class FromLogicBody(BaseModel):
|
||||
로직: str
|
||||
새로: bool = False
|
||||
@@ -113,23 +81,6 @@ def calc_sangeun(
|
||||
return _call(_root(session, layer, owner), _calc, body)
|
||||
|
||||
|
||||
class FormulaCheckBody(BaseModel):
|
||||
문서: dict[str, Any]
|
||||
자리: str
|
||||
식: str
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/sangeun/formula-check")
|
||||
def check_formula(
|
||||
layer: Layer,
|
||||
body: FormulaCheckBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""식 칸 검사(792-1) — {되나, 까닭, 알림, 식(엔진), 글(이름 꼴)} · 셈 · 저장 없음."""
|
||||
return _call(_root(session, layer, owner), fx.check_doc, body.문서, body.자리, body.식)
|
||||
|
||||
|
||||
class ImportedBody(BaseModel):
|
||||
로직: dict[str, Any]
|
||||
원본: dict[str, Any] | None = None
|
||||
@@ -256,103 +207,3 @@ def sangeun_imported_edit(
|
||||
raise HTTPException(status_code=404, detail="price · link · qty · qty-pick · qty-drop")
|
||||
fn, *args = _EDIT[how](body)
|
||||
return _call(_root(session, layer, owner), _sd(fn), *args)
|
||||
|
||||
|
||||
class CopyBody(BaseModel):
|
||||
문서: dict[str, Any]
|
||||
입력값: dict[str, Any] | None = None
|
||||
|
||||
|
||||
_JOBS = {"price": skc.PRICE, "regen": skc.REGEN}
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/sangeun/copy/{how}")
|
||||
def sangeun_copy(
|
||||
layer: Layer,
|
||||
how: str,
|
||||
body: CopyBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""로직 사본(795-1) — price [단가 갱신] · regen [재생성] · 답 = 할일 얹은 문서(화면 캐시 ·
|
||||
[저장] 때 서버가 적용) + 전 · 후 금액 + 바뀐자원 | 못얹은."""
|
||||
if how not in _JOBS:
|
||||
raise HTTPException(status_code=404, detail="price · regen")
|
||||
args = (body.문서, _JOBS[how], body.입력값)
|
||||
return _call(_root(session, layer, owner), _sd(skc.preview), *args)
|
||||
|
||||
|
||||
class EquationBody(BaseModel):
|
||||
문서: dict[str, Any]
|
||||
inputs: dict[str, Any] | None = None
|
||||
고침: list[Any] | None = None
|
||||
블록: int | None = None # 끊은 더한 기초 차례(796-2e) — 없으면 바탕 줄
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/sangeun/equation")
|
||||
def sangeun_equation(
|
||||
layer: Layer,
|
||||
body: EquationBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""수식 탭 읽기(796-2b) — 사본(가져온 식) 줄 + 문서 `수식고침` → {ok, 수식 | reason}."""
|
||||
if body.블록 is not None:
|
||||
return _call(_root(session, layer, owner), _sd(blk.read), body.문서, body.블록, body.inputs)
|
||||
return _call(_root(session, layer, owner), _sd(eqm.read), body.문서, body.inputs)
|
||||
|
||||
|
||||
class LinksBody(BaseModel):
|
||||
문서: dict[str, Any] | None = None
|
||||
갈래: str
|
||||
검색: str = ""
|
||||
분류: str = "인력"
|
||||
블록: int | None = None
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/sangeun/equation/links")
|
||||
def sangeun_equation_links(
|
||||
layer: Layer,
|
||||
body: LinksBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""새 기호 연결 후보(800-3) — 표 · 요소 · 로직 이름 찾기(읽기만)."""
|
||||
ask = {k: getattr(body, k) for k in ("갈래", "검색", "분류")}
|
||||
return _call(_root(session, layer, owner), _sd(eqm.links), body.문서 or {}, ask)
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/sangeun/equation/preview")
|
||||
def sangeun_equation_preview(
|
||||
layer: Layer,
|
||||
body: EquationBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""수식 고침 미리 셈(796-2b · 층 쓰기 · 저장 없음) — 고침 = `수식고침` 통째 →
|
||||
{되나, 까닭, 줄, 수식, 전, 후}."""
|
||||
folder = _root(session, layer, owner, write=True)
|
||||
if body.블록 is not None:
|
||||
args = (body.문서, body.블록, body.고침 or [], body.inputs)
|
||||
return _call(folder, _sd(blk.preview), *args)
|
||||
return _call(folder, _sd(eqm.preview), body.문서, body.고침 or [], body.inputs)
|
||||
|
||||
|
||||
class BlockBody(BaseModel):
|
||||
문서: dict[str, Any]
|
||||
차례: int
|
||||
|
||||
|
||||
@router.post("/layers/{layer}/sangeun/block/{how}")
|
||||
def sangeun_block(
|
||||
layer: Layer,
|
||||
how: str,
|
||||
body: BlockBody,
|
||||
owner: str | None = None,
|
||||
session: Session = Depends(verify_session),
|
||||
) -> dict:
|
||||
"""더한 기초 연결(796-2e) — unlink [연결 끊기] · relink [다시 잇기] · 답 = 고친 문서(화면 캐시 ·
|
||||
[저장] 때 서버가 다시 셈) + 전 · 후 SK 금액."""
|
||||
if how not in ("unlink", "relink"):
|
||||
raise HTTPException(status_code=404, detail="unlink · relink")
|
||||
return _call(_root(session, layer, owner), _sd(blk.change), body.문서, body.차례, how)
|
||||
|
||||
@@ -100,19 +100,6 @@ def test_ref_line_cover_only_that_line(world):
|
||||
assert store.read("sangeun", sk)["판"] == before
|
||||
|
||||
|
||||
def test_save_as_sangeun(world):
|
||||
"""[단가산출로 저장] — 새 SK(바탕 · 입력값 · 고름 cid · 덮개) · 참조 줄 · 같은 1 단위 값."""
|
||||
one = {"로직": PCT, "패치": COVER, "수량": {"손": 2}, "별칭": "내 줄"}
|
||||
with store.at(world["personal"]):
|
||||
line_value = labor.calc(labor.clean({"담은로직": [one]}), {})["줄"][0]["기준"]
|
||||
got = calc.from_line(one, "줄로 만든", "㎡")
|
||||
doc = store.read("sangeun", got["이름"])["문서"]
|
||||
value = calc.calc_doc(doc)["기준"]
|
||||
assert got["줄"] == {"참조": {**MINE, "키": got["이름"]}, "수량": {"손": 2}, "별칭": "내 줄"}
|
||||
assert doc["바탕"] == {"로직": PCT} and doc["덮개"]["labor:LB000036#0"]["qty"] == 0.5
|
||||
assert value["계"] == pytest.approx(line_value["계"])
|
||||
|
||||
|
||||
def test_refusals(world):
|
||||
with store.at(world["personal"]):
|
||||
with pytest.raises(store.StoreError, match="단위가 빔"):
|
||||
|
||||
@@ -9,11 +9,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from M02_MasterTemplete import M02_Labor_Ref as refs
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
from M02_MasterTemplete import M02_Template_Layers as layers
|
||||
from resources.tester import test_706_1_share_request as share_t
|
||||
from resources.tester.test_706_1_share_request import URL, _as, _client
|
||||
@@ -58,20 +56,6 @@ def test_새로_만들기_같은_내용_409_씀_새로(world):
|
||||
assert client.post(url, json=copy).status_code == 200 # 같은 층 [복사] = 안 물음
|
||||
|
||||
|
||||
def test_단가산출로_저장_같은_내용_409_씀_새로(world):
|
||||
mine = layers.personal_dir(7, 42)
|
||||
line = {"로직": TEN, "수량": {"손": 2}, "별칭": "내 줄"}
|
||||
with store.at(mine):
|
||||
first = calc.from_line(line, "줄로 만든", "㎡")
|
||||
with pytest.raises(store.StoreError) as e:
|
||||
calc.from_line(line, "또 만든", "㎡")
|
||||
assert e.value.status == 409 and e.value.detail["같은것"][0]["키"] == first["이름"]
|
||||
used = calc.from_line(line, "또 만든", "㎡", use=first["이름"])
|
||||
assert used == first and _count(mine, "sangeun") == 1 # 줄 = 그 SK 참조
|
||||
made = calc.from_line(line, "또 만든", "㎡", new=True)
|
||||
assert made["이름"] != first["이름"] and _count(mine, "sangeun") == 2
|
||||
|
||||
|
||||
def test_공유_승인_회사_같은_내용_409_씀_새로(world):
|
||||
client = _client(world)
|
||||
_as(world)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 금액 = 서버 셈 = _분석_650-H2 4 장 견본(인력운반 「할증율 20」 변수 줄 + 보통인부 품 식
|
||||
× (1 + 할증율 / 100) = 51,501) · 합판거푸집 줄 식 고침 · 공구손료 식 2 % = 51,802(790-2 같은 값)
|
||||
- 이름 꼴(`×` · `[노임 형틀목공]` · `[별칭]`) ↔ 엔진 식 왕복 = M01 로직 견본 식 전부 같음
|
||||
- 검사 까닭 — 없는 이름 · 괄호 · 순환 · 0 나눔 · 길이 · 괄호 깊이 · 변수 줄 수 · 자리 겹침
|
||||
- 꼴 상한 — 변수 줄 수 · 이름 꼴 · 자리 겹침 · 괄호 깊이(식 칸 검사 길은 894 에서 걷음)
|
||||
- 옛 SK(식 칸 없음) = 꼴 · 금액 그대로 · 저장 = 엔진 식 · 틀린 식 저장 400 · 셈 답 덧칸
|
||||
- B09 사본 굳힘(`GX9#####`) 줄 = 식 칸 그대로 · 다시 셈 같은 금액
|
||||
- 799-2 — TS 거울(`Formula_Model.ts` · `Const_Model.ts`)은 시트 탭과 함께 걷음 · 서버만 지킴
|
||||
@@ -133,29 +133,6 @@ def test_이름_꼴_양방향():
|
||||
assert fx.to_engine(fx.to_name(str(x[f]), one), one) == (str(x[f]), [])
|
||||
|
||||
|
||||
# ── 검사 ─────────────────────────────────────────────────────────────
|
||||
def _check(spot, text, doc=None):
|
||||
return fx.check_doc(doc or _plus(), spot, text)
|
||||
|
||||
|
||||
def test_검사_까닭():
|
||||
ok = _check(MAN, PLUS)
|
||||
assert ok["되나"] and ok["식"] == PLUS.replace("×", "*") and ok["글"] == PLUS
|
||||
assert _check(MAN, "무게 / 없는것")["까닭"] == ["모르는 이름 「없는것」"]
|
||||
assert "「)」 없음" in _check(MAN, "(무게 / 2")["까닭"][0]
|
||||
assert _check("mid:할증율", "할증율 + 1")["까닭"] == ["순환 — 「할증율」 이 자기 자신을 씀"]
|
||||
two = _plus(
|
||||
변수줄=[{"이름": "가", "식": "1", "자리": ""}, {"이름": "나", "식": "가", "자리": ""}]
|
||||
)
|
||||
assert _check("mid:가", "나 + 1", two)["까닭"] == ["순환 — 가 → 나 → 가"]
|
||||
assert _check("mid:할증율", "운반무게 / 0")["까닭"] == ["0 으로 나눔"]
|
||||
assert _check(MAN, "무게 / 운반회수")["알림"] == ["「운반회수」 가 0 이면 0 나눔"]
|
||||
assert _check(MAN, "1" + " + 1" * 80)["까닭"] == [f"식이 {fx.LONG} 자를 넘음"]
|
||||
assert _check(MAN, "(" * 13 + "1" + ")" * 13)["까닭"] == [f"괄호가 {fx.DEEP} 겹을 넘음"]
|
||||
assert _check("add:#3", "1")["까닭"] == ["없는 자리 「add:#3」"]
|
||||
assert _check(MAN, " ")["까닭"] == ["식이 빔"]
|
||||
|
||||
|
||||
def test_꼴_상한_겹침():
|
||||
whole = _whole()
|
||||
many = [{"이름": f"v{i}", "식": "1", "자리": ""} for i in range(fx.MANY + 1)]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"""795-2 일위대가 · 사전조합(SC) 로직 사본 — 임시 storage · M01 은 메모리 덮개(정본 안 고침).
|
||||
|
||||
① 저장 때 사본 · M01 로직 바꿔도 일위대가 · SC 금액 그대로 · 배지 ② 노임 바꿔도 [단가 갱신] 전엔
|
||||
그대로 · 누르면 따라감 ③ [재생성] 뒤 줄 덮개 다시 얹힘 · 못 얹은 칸 알림 ④ 층 복사 · 열 복사 =
|
||||
그대로 · 누르면 따라감 ③ [재생성] 뒤 줄 덮개 다시 얹힘 ④ 층 복사 · 열 복사 =
|
||||
사본 그대로 ⑤ TS 짝(Labor_Calc.ts settle) 같은 금액 ⑥ 사본 없는 옛 문서 = 옛 길.
|
||||
"""
|
||||
|
||||
@@ -95,7 +95,7 @@ def test_copy_stamped_logic_change_kept(world, monkeypatch):
|
||||
|
||||
|
||||
def test_price_refresh_only_on_press(world, monkeypatch):
|
||||
"""② 노임 바꿈 → 그대로 · [단가 갱신] 미리 셈 = 새로 찍은 문서 값 · [저장] 때 적용."""
|
||||
"""② 노임 바꿈 → 그대로 · [단가 갱신] = [저장] 때 적용 · 새로 찍은 문서 값."""
|
||||
me = world["personal"]
|
||||
sc = _sc(me, [{"로직": PCT, "수량": {"손": 1}}])
|
||||
was = _calc(me, sc)["기준합"]["계"]
|
||||
@@ -103,18 +103,14 @@ def test_price_refresh_only_on_press(world, monkeypatch):
|
||||
assert _calc(me, sc)["기준합"]["계"] == was and _unit(me, sc) == was
|
||||
fresh = _calc(me, _sc(me, [{"로직": PCT, "수량": {"손": 1}}]))["기준합"]["계"]
|
||||
assert fresh != was
|
||||
with store.at(me):
|
||||
got = lc.preview(labor.clean({**_read(me, "precombo", sc), "열": sc}), lc.PRICE)
|
||||
assert got["전"]["기준합"]["계"] == was and got["후"]["기준합"]["계"] == fresh
|
||||
assert [x["키"] for x in got["바뀐자원"]] == [LB]
|
||||
_write(me, "precombo", sc, {**_read(me, "precombo", sc), lc.JOB: got["doc"][lc.JOB]})
|
||||
_write(me, "precombo", sc, {**_read(me, "precombo", sc), lc.JOB: lc.PRICE})
|
||||
saved = _read(me, "precombo", sc)
|
||||
assert lc.JOB not in saved and _unit(me, sc) == fresh
|
||||
assert _calc(me, sc)["사본"]["단가새값"] is False
|
||||
|
||||
|
||||
def test_regen_reapplies_line_cover(world, monkeypatch):
|
||||
"""③ [재생성] — 줄 덮개(cid) 새 사본에 다시 얹힘 · 없어진 줄 덮개 = 못얹은 · 배지 꺼짐."""
|
||||
"""③ [재생성] — 줄 덮개(cid) 새 사본에 다시 얹힘 · 배지 꺼짐."""
|
||||
me = world["personal"]
|
||||
two = {"덮개": {f"labor:{LB}#0": {"qty": 0.5}, "labor:LB000002#0": {"qty": 0.7}}}
|
||||
_labor(me, [{"로직": PCT, "수량": {"손": 1}, "패치": two}])
|
||||
@@ -122,15 +118,12 @@ def test_regen_reapplies_line_cover(world, monkeypatch):
|
||||
row["호표"] = [x for n, x in enumerate(row["호표"]) if n != 1] # 둘째 줄 없앤 새 판
|
||||
_fake(monkeypatch, [row])
|
||||
assert not _calc(me, COL)["줄"][0].get("짝잃음") # 사본 = 옛 판 그대로
|
||||
with store.at(me):
|
||||
got = lc.preview(labor.clean(_read(me, "labor", COL)), lc.REGEN)
|
||||
assert [x["cid"] for x in got["못얹은"]] == ["labor:LB000002#0"]
|
||||
assert got["전"]["기준합"]["계"] != got["후"]["기준합"]["계"]
|
||||
_write(me, "labor", COL, got["doc"])
|
||||
was = _calc(me, COL)["기준합"]["계"]
|
||||
_write(me, "labor", COL, {**_read(me, "labor", COL), lc.JOB: lc.REGEN})
|
||||
doc = _read(me, "labor", COL)
|
||||
assert doc["담은로직"][0]["패치"]["덮개"][f"labor:{LB}#0"] == {"qty": 0.5}
|
||||
now = _calc(me, COL)
|
||||
assert now["사본"]["M01새판"] is False and now["기준합"]["계"] == got["후"]["기준합"]["계"]
|
||||
assert now["사본"]["M01새판"] is False and now["기준합"]["계"] != was
|
||||
|
||||
|
||||
def test_layer_and_column_copy_keep_copy(world, monkeypatch):
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀
|
||||
"""796-2b M02 단가산출 수식 탭 — 사본 줄 수식 · 고침 = 금액 · 저장 = 사본 위 정본(임시 storage).
|
||||
"""796-2b M02 단가산출 저장 문서 `수식고침` — 고침 = 금액 · 저장 = 사본 위 정본(임시 storage).
|
||||
|
||||
① 사본 줄 수식 읽기 = SK 금액 ② 고침 미리 셈 = 금액 바뀜(저장 없음) ③ [저장] = 서버가 다시 얹어 셈 ·
|
||||
틀린 고침 400 · M01 그대로 ④ 변수 더함 · 지움(쓰는 곳 막음) · 기호 · 첨자 전파 ⑤ 권한 = 층 쓰기
|
||||
옛 수식 탭 화면 길(읽기 · 미리 셈)은 894 에서 걷음 — 남은 것 = 저장 · 셈.
|
||||
③ [저장] = 서버가 다시 얹어 셈 · 틀린 고침 400 · M01 그대로 ④ 변수 더함 · 지움(쓰는 곳 막음) · 기호
|
||||
⑥ 가져온 식 SK 같은 길 ⑦ M01 바뀌어도 그대로 · [재생성] = 고침 다시 얹음 · 못 얹음 알림.
|
||||
"""
|
||||
|
||||
@@ -11,15 +11,12 @@ from __future__ import annotations
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
from M02_MasterTemplete import M02_Labor_Doc as labor
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_Copy as skc
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
|
||||
from M02_MasterTemplete import M02_Sangeun_Imported as imp
|
||||
from M02_MasterTemplete import M02_Sangeun_Router as router
|
||||
from resources.tester.test_795_1_sk_copy import (
|
||||
_calc,
|
||||
_doc,
|
||||
@@ -45,122 +42,58 @@ KEY = "GC000211" # 합판거푸집 — 중간 시공량 · 형틀목공 · 보
|
||||
DOUBLE = [{"할일": "식", "자리": "호표:0", "식": "형틀목공 × 2", "까닭": "sub2임시 시험"}]
|
||||
|
||||
|
||||
def _line(eq, key, kind=None):
|
||||
return next(x for x in eq["줄"] if x.get("열쇠") == key and (kind is None or x["갈래"] == kind))
|
||||
|
||||
|
||||
def _read(folder, doc):
|
||||
with store.at(folder):
|
||||
return eqm.read(doc)
|
||||
|
||||
|
||||
def _preview(folder, doc, edits):
|
||||
with store.at(folder):
|
||||
return eqm.preview(doc, edits)
|
||||
|
||||
|
||||
def test_read_copy_row_equals_sk_amount(world):
|
||||
"""① 사본 줄 수식 — 합계 = SK 금액 = M01 셈 · 키보드 글."""
|
||||
me = world["personal"]
|
||||
key = _sk(me, 바탕={"로직": KEY})
|
||||
got = _read(me, _doc(me, key))
|
||||
assert got["ok"], got
|
||||
eq = got["수식"]
|
||||
assert eq["열쇠"] == KEY and eq["합계"]["계"] == _sum(me, key)
|
||||
assert eq["합계"]["계"] == labor.run_line(_live(), KEY, {})["기준"]["계"]
|
||||
assert _line(eq, "형틀목공", "호표")["입력글"] == "Q_형틀목공"
|
||||
|
||||
|
||||
def test_edit_changes_amount_save_is_canonical(world):
|
||||
"""② · ③ 고침 미리 셈 = 금액 바뀜 · [저장] = 고침 목록 남음 · 서버 셈 = 미리 셈 · M01 그대로."""
|
||||
"""③ 고침 [저장] = 고침 목록 남음 · 서버 셈 = 금액 바뀜 · 원래 대비 · M01 그대로 · 틀린 고침 400."""
|
||||
me = world["personal"]
|
||||
key = _sk(me, 바탕={"로직": KEY})
|
||||
was = _sum(me, key)
|
||||
m01_row = copy.deepcopy(_live().logic(KEY))
|
||||
got = _preview(me, _doc(me, key), DOUBLE)
|
||||
assert got["되나"], got["까닭"]
|
||||
assert got["전"]["계"] == was and got["후"]["계"] > was
|
||||
assert got["줄"]["호표"][0]["수량"] == "형틀목공 * 2"
|
||||
assert _sum(me, key) == was # 미리 셈 = 저장 없음
|
||||
doc = {**_doc(me, key), eqm.KEY: DOUBLE}
|
||||
_save(me, key, doc)
|
||||
saved = _doc(me, key)
|
||||
assert saved[eqm.KEY][0]["까닭"] == "sub2임시 시험"
|
||||
assert saved["사본"]["로직"][0]["호표"][0]["수량"] == m01_row["호표"][0]["수량"] # 사본 = 원래
|
||||
now = _calc(me, saved)
|
||||
assert now["기준"]["계"] == got["후"]["계"]
|
||||
after = now["기준"]["계"]
|
||||
assert after > was
|
||||
assert now["원래"]["계"] == was # 원래 대비 = 고침 없는 사본
|
||||
assert _read(me, saved)["수식"]["합계"]["계"] == got["후"]["계"]
|
||||
assert _live().logic(KEY) == m01_row # M01 정본 안 바뀜
|
||||
bad = {**saved, eqm.KEY: [{"할일": "식", "자리": "호표:0", "식": "없는값 × 2"}]}
|
||||
with pytest.raises(store.StoreError):
|
||||
_save(me, key, bad)
|
||||
assert _sum(me, key) == got["후"]["계"]
|
||||
assert _sum(me, key) == after
|
||||
|
||||
|
||||
def test_variables_add_drop_rename(world):
|
||||
"""④ 변수 더함 → 식에서 부름 · 쓰는 변수 지움 막음 · 기호 · 첨자 = 쓰는 식 모두."""
|
||||
"""④ 변수 더함 → 식에서 부름(금액 바뀜) · 쓰는 변수 지움 = 저장 400 · 기호 = 금액 그대로."""
|
||||
me = world["personal"]
|
||||
key = _sk(me, 바탕={"로직": KEY})
|
||||
doc = _doc(me, key)
|
||||
was = _calc(me, doc)["기준"]
|
||||
add = [
|
||||
{"할일": "더함", "갈래": "중간", "열쇠": "할증", "식": "1.5", "뒤": "보통인부"},
|
||||
{"할일": "식", "자리": "호표:1", "식": "보통인부 × 할증"},
|
||||
]
|
||||
got = _preview(me, doc, add)
|
||||
assert got["되나"], got["까닭"]
|
||||
assert got["후"]["노무비"] > got["전"]["노무비"]
|
||||
assert "할증" in [v["열쇠"] for v in got["수식"]["변수표"]]
|
||||
got = _preview(me, doc, [{"할일": "지움", "열쇠": "시공량"}])
|
||||
assert not got["되나"] and "형틀목공" in " ".join(got["까닭"])
|
||||
_save(me, key, {**doc, eqm.KEY: add})
|
||||
assert _calc(me, _doc(me, key))["기준"]["노무비"] > was["노무비"]
|
||||
with pytest.raises(store.StoreError):
|
||||
_save(me, key, {**_doc(me, key), eqm.KEY: [{"할일": "지움", "열쇠": "시공량"}]})
|
||||
sign = [{"할일": "변수", "열쇠": "시공량", "기호": "Q", "아래": "d", "이름": "하루 시공량"}]
|
||||
got = _preview(me, doc, sign)
|
||||
assert got["되나"] and got["후"] == got["전"] # 이름만 — 금액 그대로
|
||||
assert "Q_d" in _line(got["수식"], "형틀목공", "중간")["입력글"]
|
||||
assert "Q_d" in _line(got["수식"], "보통인부", "중간")["입력글"]
|
||||
_save(me, key, {**doc, eqm.KEY: sign})
|
||||
again = _read(me, _doc(me, key))["수식"]
|
||||
assert next(v for v in again["변수표"] if v["열쇠"] == "시공량")["기호"] == "Q"
|
||||
|
||||
|
||||
def _session(role="USER"):
|
||||
return {"role": role, "company_id": 7, "user_id": 42}
|
||||
|
||||
|
||||
def test_permission_layer_write(world, monkeypatch):
|
||||
"""⑤ 미리 셈 = 그 층 쓰기 — 마스터 = 시스템 관리자 · 회사 = 회사 관리자 · 개인 = 본인."""
|
||||
me = world["personal"]
|
||||
key = _sk(me, 바탕={"로직": KEY})
|
||||
body = router.EquationBody(문서=_doc(me, key), 고침=DOUBLE)
|
||||
for layer in ("system", "company"):
|
||||
with pytest.raises(HTTPException) as e:
|
||||
router.sangeun_equation_preview(layer, body, None, _session())
|
||||
assert e.value.status_code == 403
|
||||
got = router.sangeun_equation_preview("personal", body, None, _session())
|
||||
assert got["되나"] and got["후"]["계"] > got["전"]["계"]
|
||||
got = router.sangeun_equation("personal", body, None, _session())
|
||||
assert got["ok"] and got["수식"]["합계"]["계"] == got["수식"]["합계"]["계"]
|
||||
monkeypatch.setattr(router, "_root", lambda *a, **k: me)
|
||||
admin = router.sangeun_equation_preview("system", body, None, _session("SYSTEM_ADMIN"))
|
||||
assert admin["되나"]
|
||||
_save(me, key, {**_doc(me, key), eqm.KEY: sign})
|
||||
assert _calc(me, _doc(me, key))["기준"]["계"] == was["계"] # 이름만 — 금액 그대로
|
||||
|
||||
|
||||
def test_imported_same_path(world):
|
||||
"""⑥ 가져온 식 SK(바탕 null · 가져온.로직) — 같은 읽기 · 고침 · 저장."""
|
||||
"""⑥ 가져온 식 SK(바탕 null · 가져온.로직) — 같은 고침 · 저장."""
|
||||
me = world["personal"]
|
||||
with store.at(me):
|
||||
key = imp.create(_imported_row(), None, "sub2임시 가져온")["이름"]
|
||||
doc = _doc(me, key)
|
||||
got = _read(me, doc)
|
||||
assert got["ok"], got
|
||||
assert got["수식"]["합계"]["계"] == _sum(me, key)
|
||||
was = _calc(me, doc)["기준"]["노무비"]
|
||||
edit = [{"할일": "식", "자리": "호표:0", "식": "0.5 × 2"}]
|
||||
got = _preview(me, doc, edit)
|
||||
assert got["되나"], got["까닭"]
|
||||
assert got["후"]["노무비"] == pytest.approx(got["전"]["노무비"] * 2, abs=1)
|
||||
_save(me, key, {**doc, eqm.KEY: edit})
|
||||
now = _calc(me, _doc(me, key))
|
||||
assert now["기준"]["노무비"] == pytest.approx(got["후"]["노무비"], abs=1)
|
||||
assert now["기준"]["노무비"] == pytest.approx(was * 2, abs=1)
|
||||
assert _doc(me, key)["가져온"]["로직"]["호표"][0]["수량"] == "0.5" # 엑셀 줄 그대로
|
||||
|
||||
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
# ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀
|
||||
"""796-2c M02 수식 탭이 SK 셈 답 전체를 그림 — 더한 기초 · 뺀줄 · 덮개 · 율 줄 · 참조 · 가져온 식.
|
||||
|
||||
견본 셋(임시 storage · M01 그대로):
|
||||
A 거푸집 + 더한 기초(굴착기) + 더한 인력 + 뺀줄 + 품 덮개 + 식 덮개
|
||||
B 포장 + 단가 덮개 + 율 줄 + 참조 SK
|
||||
C 가져온 식 + 더한 인력 + 품 덮개
|
||||
지킴: 수식 탭 합계 = SK 셈 답 `기준`(원 단위까지) · 행 합 + 끝수 = 합계(비목마다) ·
|
||||
상태(덮음 · 더함 · 뺌) · 고친 칸 표지(원래 · 지금) · 더한 기초 수식 나무 ·
|
||||
미리 셈 전/후 = SK 금액 · SK 금액 전후 같음.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal as D
|
||||
|
||||
import pytest
|
||||
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
|
||||
from M02_MasterTemplete import M02_Sangeun_Imported as imp
|
||||
from resources.tester.test_795_1_sk_copy import _calc, _doc, _imported_row, _save, _sk
|
||||
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
|
||||
|
||||
SUMS = ("노무비", "재료비", "경비", "계")
|
||||
BASIC = {
|
||||
"종류": "로직",
|
||||
"로직": "GF000089",
|
||||
"수량": 2,
|
||||
"입력값": {},
|
||||
} # 토사깍기(기계) — 굴착기 0.7㎥ 시간당 × 1 / 작업량(813-2 GC001148 지움 뒤)
|
||||
MAN = {"종류": "인력", "요소": "LB000002", "이름": "sub2임시 인부", "단위": "인", "수량": 1}
|
||||
FORM = "GC000211" # 합판거푸집 — 형틀목공 · 보통인부 · 중간 시공량
|
||||
MINE = {"층": "personal", "주인": "7/42"}
|
||||
|
||||
|
||||
def _d(v) -> D:
|
||||
return D(str(v))
|
||||
|
||||
|
||||
def _read(folder, doc, inputs=None):
|
||||
with store.at(folder):
|
||||
got = eqm.read(doc, inputs)
|
||||
assert got["ok"], got
|
||||
return got["수식"]
|
||||
|
||||
|
||||
def _rows(eq) -> dict:
|
||||
"""묶음(801-3) — 더한 · 부른 단가산출 = cid 로 · 직접 줄 묶음 속 더함 · 덮음 줄 = 이름으로."""
|
||||
got = {r["cid"]: r for r in eq["소계"]["줄"] if "cid" in r}
|
||||
for r in eq["소계"]["줄"]:
|
||||
got |= {x["이름"]: x for x in r.get("낱줄", [])}
|
||||
return got
|
||||
|
||||
|
||||
def _closes(eq, ans) -> None:
|
||||
"""합계 = SK 셈 답 원 단위까지 · 행 합 + 끝수 = 합계 · 끝수 작음."""
|
||||
sub = eq["소계"]
|
||||
for k in SUMS:
|
||||
assert eq["합계"][k] == _d(ans["기준"][k]), k
|
||||
assert sum((r[k] for r in sub["줄"]), D(0)) + sub["끝수"][k] == eq["합계"][k], k
|
||||
assert abs(sub["끝수"]["계"]) < 2, sub["끝수"]
|
||||
|
||||
|
||||
def _line(eq, kind, key):
|
||||
return next(x for x in eq["줄"] if x["갈래"] == kind and x["열쇠"] == key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def made(world):
|
||||
me = world["personal"]
|
||||
plain = _sk(me, 바탕={"로직": FORM}) # 고침 없는 같은 바탕 — 원래 값 대조용
|
||||
key = _sk(
|
||||
me,
|
||||
바탕={"로직": FORM},
|
||||
더한줄=[dict(BASIC), dict(MAN)],
|
||||
뺀줄=["labor:LB000002#0"],
|
||||
덮개={"labor:LB000007#0": {"qty": 0.5}},
|
||||
식덮개={"mid:시공량": "50"},
|
||||
)
|
||||
return me, key, plain
|
||||
|
||||
|
||||
def test_A_added_removed_covered_total_equals_sk(made):
|
||||
me, key, plain = made
|
||||
doc, bare = _doc(me, key), _calc(me, _doc(me, plain))
|
||||
ans = _calc(me, doc)
|
||||
eq = _read(me, doc)
|
||||
_closes(eq, ans)
|
||||
rows = _rows(eq)
|
||||
# 덮음 — 형틀목공 품 덮개 · 원래 = 고침 없는 SK 의 같은 줄 금액
|
||||
cover = rows["형틀목공"] # 직접 묶음 속 덮은 줄(이름)
|
||||
was = next(x for x in bare["줄"] if x["cid"] == "labor:LB000007#0")["금액"]
|
||||
assert cover["상태"] == "덮음"
|
||||
assert _d(cover["원래"]) == _d(was)
|
||||
assert cover["계"] == D("137895") # 품 0.5 × 단가 275,790
|
||||
# 뺌 — 지운 줄 = 묶음 아님(식 줄 표지로만 · 아래 `out["뺌"]`)
|
||||
assert "labor:LB000002#0" not in rows and "보통인부" not in rows
|
||||
# 더함 — 기초(토사깍기 2,190 × 2) = 묶음 · 인력 = 직접 묶음 속 더한 줄 · 기초는 수식 나무
|
||||
basic = rows["add:#0"]
|
||||
man = next(x for r in eq["소계"]["줄"] for x in r.get("낱줄", []) if x["상태"] == "더함")
|
||||
assert basic["상태"] == man["상태"] == "더함" and basic["갈래"] == "블록"
|
||||
assert [r["갈래"] for r in eq["소계"]["줄"]] == ["블록", "직접"]
|
||||
assert basic["계"] > 0 and man["계"] > 0
|
||||
assert basic["나무"]["열쇠"] == "GF000089" and basic["나무"]["줄"]
|
||||
# 나무 합계 × 수량 = 행(같은 입력)
|
||||
assert abs(basic["나무"]["합계"]["계"] * 2 - basic["계"]) <= 2
|
||||
# 고친 칸 표지 — 수식 탭 줄(식 덮개 · 품 · 뺌)
|
||||
mid = _line(eq, "중간", "시공량")
|
||||
assert mid["표지"] == ["식"] and mid.get("원래") is not None and "50" in mid["식"]
|
||||
assert _line(eq, "호표", "형틀목공")["표지"] == ["품"]
|
||||
out = _line(eq, "호표", "보통인부")
|
||||
assert out["뺌"] is True and out["표지"] == []
|
||||
# 고침 없는 SK(plain)는 표지도 더함도 없음 — 합계 = 같은 바탕 금액
|
||||
flat = _read(me, _doc(me, plain))
|
||||
assert {r.get("상태", "바탕") for r in flat["소계"]["줄"]} == {"바탕"}
|
||||
assert [r["갈래"] for r in flat["소계"]["줄"]] == ["직접"] # 801-3 한 묶음 · 낱줄 없음
|
||||
assert flat["합계"]["계"] == _d(bare["기준"]["계"])
|
||||
assert not any("표지" in x for x in flat["줄"])
|
||||
|
||||
|
||||
def test_A_preview_before_after_and_save_same(made):
|
||||
"""고침 미리 셈 전/후 = SK 금액 · 저장 뒤 셈 = 미리 셈 · 더한 것도 합계에 듦."""
|
||||
me, key, _ = made
|
||||
doc = _doc(me, key)
|
||||
was = _calc(me, doc)["기준"]["계"]
|
||||
edit = [{"할일": "식", "자리": "호표:3", "식": "0.038 × 2", "까닭": "sub2임시 2c"}]
|
||||
with store.at(me):
|
||||
got = eqm.preview(doc, edit)
|
||||
assert got["되나"], got["까닭"]
|
||||
assert got["전"]["계"] == _d(was) and got["후"]["계"] != got["전"]["계"]
|
||||
_save(me, key, {**doc, eqm.KEY: edit})
|
||||
now = _calc(me, _doc(me, key))
|
||||
assert _d(now["기준"]["계"]) == got["후"]["계"]
|
||||
eq = _read(me, _doc(me, key))
|
||||
_closes(eq, now)
|
||||
|
||||
|
||||
def test_B_unit_cover_rate_and_reference(world):
|
||||
"""B 단가 덮개 · 율 줄 · 참조 SK 가 소계에 들고 합계 = SK 금액."""
|
||||
me = world["personal"]
|
||||
ref = _sk(me, 바탕={"로직": FORM})
|
||||
rate = {
|
||||
"고정": {
|
||||
"이름": "sub2임시 율",
|
||||
"단가": {},
|
||||
"이음": {},
|
||||
"비율": {"기준": "인력", "비목": "경비"},
|
||||
}
|
||||
}
|
||||
adds = [{**rate, "수량": 3}, {"참조": {**MINE, "키": ref}, "수량": 1}]
|
||||
key = _sk(
|
||||
me,
|
||||
바탕={"로직": "GC001109"},
|
||||
더한줄=adds,
|
||||
덮개={"labor:LB000002#0": {"labor": 200000}},
|
||||
)
|
||||
doc, ans = _doc(me, key), _calc(me, _doc(me, key))
|
||||
eq = _read(me, doc)
|
||||
_closes(eq, ans)
|
||||
rows = _rows(eq)
|
||||
pool = next(r for r in eq["소계"]["줄"] if r["갈래"] == "직접")
|
||||
price = next(x for x in pool["낱줄"] if x["상태"] == "덮음")
|
||||
assert price["원래"] is not None and "sub2임시 율" in pool["이름"] and pool["경비"] > 0
|
||||
assert rows["add:#1"]["갈래"] == "블록" and rows["add:#1"]["상태"] == "더함"
|
||||
assert _line(eq, "호표", price["이름"])["표지"] == ["단가"]
|
||||
|
||||
|
||||
def test_C_imported_sk_same_rule(world):
|
||||
"""C 가져온 식 SK — 더한 인력 · 품 덮개 · 합계 = SK 금액."""
|
||||
me = world["personal"]
|
||||
with store.at(me):
|
||||
key = imp.create(_imported_row(), None, "sub2임시 가져온")["이름"]
|
||||
doc = _doc(me, key)
|
||||
cid = next(x["cid"] for x in _calc(me, doc)["줄"] if x["cid"].startswith("labor:"))
|
||||
_save(me, key, {**doc, "더한줄": [dict(MAN)], "덮개": {cid: {"qty": 1}}})
|
||||
doc = _doc(me, key)
|
||||
ans = _calc(me, doc)
|
||||
eq = _read(me, doc)
|
||||
_closes(eq, ans)
|
||||
rows = _rows(eq)
|
||||
assert [x["상태"] for x in eq["소계"]["줄"][-1]["낱줄"]] == ["덮음", "더함"], rows
|
||||
|
||||
|
||||
def test_plain_sk_has_answer_table(world):
|
||||
"""고침 없는 SK = 답까닭 없음 · 소계 표 있음."""
|
||||
me = world["personal"]
|
||||
key = _sk(me, 바탕={"로직": FORM})
|
||||
eq = _read(me, _doc(me, key))
|
||||
assert "답까닭" not in eq and eq["소계"]["줄"]
|
||||
|
||||
|
||||
def test_D_imported_outside_total_line_not_in_sum(world):
|
||||
"""D 가져온 식 `합밖` 줄 = 합계에 안 듦 → 묶음 아님 · `밖` 글 · 끝수에 안 섞임."""
|
||||
me = world["personal"]
|
||||
row = _imported_row()
|
||||
row["호표"][1] = {**row["호표"][1], "합밖": True}
|
||||
with store.at(me):
|
||||
key = imp.create(row, None, "sub2임시 합밖")["이름"]
|
||||
doc = _doc(me, key)
|
||||
ans = _calc(me, doc)
|
||||
eq = _read(me, doc)
|
||||
_closes(eq, ans)
|
||||
out = eq["소계"]["밖"]
|
||||
assert len(out) == 1 and out[0]["밖금액"] > 0
|
||||
assert abs(eq["소계"]["끝수"]["계"]) < 1
|
||||
@@ -1,186 +0,0 @@
|
||||
# ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀
|
||||
"""796-2e M02 단가산출 더한 기초 블록 [연결 끊기] · [다시 잇기] (임시 storage · M01 은 메모리 덮개).
|
||||
|
||||
① 연결 블록 = 원본(M01) 바뀜을 [재생성] 에서 따라감 ② [연결 끊기] = 금액 그대로 · 이 SK 안 자기 사본 ·
|
||||
원본 바뀜 안 따라감([재생성] 도) ③ 끊은 기초 줄 고침 = 금액 바뀜(미리 셈 = 저장 뒤 서버 셈 · 틀린 고침 400 ·
|
||||
M01 안 바뀜) ④ [다시 잇기] = 고친 것 버림 · 원본 따라감 ⑤ [단가 갱신] = 연결 · 끊은 둘 다 자원 단가 따라감
|
||||
⑥ 꼴 검사(연결 기초에 고침 · 이미 끊음 · 차례 밖).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_Block as blk
|
||||
from M02_MasterTemplete import M02_Sangeun_Copy as skc
|
||||
from M02_MasterTemplete import M02_Sangeun_Doc as sd
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation_Full as full
|
||||
from resources.tester.test_795_1_sk_copy import _calc, _changed, _doc, _fake, _live, _save, _sk
|
||||
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
|
||||
|
||||
FORM = "GC000211" # 합판거푸집
|
||||
BASIC = "GF000089" # 토사깍기(기계) · 굴착기 시간당 — 호표 0 = 시간당 기계 × (1 / 작업량)
|
||||
ADD = {"종류": "로직", "로직": BASIC, "수량": 2, "입력값": {}, "이름": "sub3임시 굴착기"}
|
||||
ONLY = "LB000048" # 굴착기 기초에만 닿는 노임(거푸집엔 안 닿음)
|
||||
DOUBLE = [{"할일": "식", "자리": "호표:0", "식": "3 / 작업량", "까닭": "sub3임시 시험"}]
|
||||
|
||||
|
||||
def _sum(folder, doc):
|
||||
return _calc(folder, doc)["기준"]["계"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def made(world):
|
||||
me = world["personal"]
|
||||
key = _sk(me, 바탕={"로직": FORM}, 더한줄=[copy.deepcopy(ADD)])
|
||||
return me, key
|
||||
|
||||
|
||||
def _cut(me, key):
|
||||
"""끊어서 저장한 SK — (끊기 전 금액, 끊은 문서)."""
|
||||
doc = _doc(me, key)
|
||||
with store.at(me):
|
||||
got = blk.change(doc, 0, "unlink")
|
||||
assert got["전"]["계"] == got["후"]["계"] # 끊기 전후 같음
|
||||
_save(me, key, got["문서"])
|
||||
return got["전"]["계"], _doc(me, key)
|
||||
|
||||
|
||||
def test_unlink_keeps_amount_and_freezes_rows(made):
|
||||
"""② 끊기 = 금액 그대로 · 닫힌 묶음(하위 로직 포함) 이 SK 안에 · 저장 뒤도 같음 · 수식 탭 표지."""
|
||||
me, key = made
|
||||
was = _sum(me, _doc(me, key))
|
||||
plain = _calc(me, _doc(me, key))
|
||||
assert plain["기준"]["계"] == was
|
||||
row_before = copy.deepcopy(_live().logic(BASIC))
|
||||
price, doc = _cut(me, key)
|
||||
assert price == was and _sum(me, doc) == was
|
||||
cut = doc["더한줄"][0]["끊음"]
|
||||
keys = {r["키"] for r in cut["로직"]}
|
||||
assert BASIC in keys and "GC000267" in keys and "GF000088" in keys # 하위 로직까지
|
||||
assert not any(k[:2] in skc.RES for k in keys) # 단가는 SK 사본 한 곳
|
||||
assert _live().logic(BASIC) == row_before # M01 안 바뀜
|
||||
with store.at(me):
|
||||
eq = full.attach({"줄": []}, doc, skc.over(doc, skc.whole_()), {}, None, _calc(me, doc))
|
||||
block = next(r for r in eq["소계"]["줄"] if r.get("블록") == 0)
|
||||
assert block["끊음"] is True and block["나무"] and block["상태"] == "더함"
|
||||
assert not block.get("덮개") # 끊기만으로 「세부」 고침 표지 없음
|
||||
|
||||
|
||||
def test_connected_follows_original_on_regen_cut_does_not(made, monkeypatch):
|
||||
"""①·② 원본 바뀜 — 연결 = 따라감(836-2 개인 층 = 자동 · [재생성] 도) · 끊음 = [재생성] 도 안 따라감."""
|
||||
me, key = made
|
||||
was = _sum(me, _doc(me, key))
|
||||
_fake(monkeypatch, [_changed(_live().logic(BASIC))]) # 호표 0 수량 × 2 (원본 바뀜)
|
||||
assert _sum(me, _doc(me, key)) > was # 836-2 개인 층 = 누르기 전에도 자동 따라옴(옛 「그대로」)
|
||||
with store.at(me):
|
||||
got = skc.preview(_doc(me, key), skc.REGEN)
|
||||
assert got["후"]["계"] > was and "끊은기초" not in got # 연결 = 원본 따라감
|
||||
monkeypatch.undo()
|
||||
price, doc = _cut(me, key)
|
||||
assert price == was
|
||||
_fake(monkeypatch, [_changed(_live().logic(BASIC))])
|
||||
with store.at(me):
|
||||
got = skc.preview(doc, skc.REGEN)
|
||||
assert got["전"]["계"] == got["후"]["계"] == was # 끊음 = 안 따라감
|
||||
assert got["끊은기초"] == ["sub3임시 굴착기"] # 보고 한 줄
|
||||
_save(me, key, got["문서"])
|
||||
assert _sum(me, _doc(me, key)) == was
|
||||
|
||||
|
||||
def test_price_refresh_follows_in_both(made, monkeypatch):
|
||||
"""⑤ [단가 갱신] — 연결 · 끊은 기초 모두 자원 단가는 따라감(요구 656-1) · 끊은 기초 줄은 그대로."""
|
||||
me, key = made
|
||||
was = _sum(me, _doc(me, key))
|
||||
row = copy.deepcopy(_live().get(ONLY))
|
||||
row["값"] = row["값"] * 2
|
||||
_fake(monkeypatch, [row])
|
||||
with store.at(me):
|
||||
fresh = skc.preview(_doc(me, key), skc.PRICE)
|
||||
assert fresh["후"]["계"] > was and [x["키"] for x in fresh["바뀐자원"]] == [ONLY]
|
||||
monkeypatch.undo()
|
||||
_, doc = _cut(me, key)
|
||||
_fake(monkeypatch, [row])
|
||||
with store.at(me):
|
||||
cut = skc.preview(doc, skc.PRICE)
|
||||
assert cut["후"]["계"] == fresh["후"]["계"] and cut["끊은기초"] == ["sub3임시 굴착기"]
|
||||
_save(me, key, cut["문서"])
|
||||
assert _sum(me, _doc(me, key)) == fresh["후"]["계"]
|
||||
|
||||
|
||||
def test_edit_cut_block_changes_amount_and_saves(made):
|
||||
"""③ 끊은 기초 줄 고침 — 미리 셈 = 금액 바뀜 · 저장 뒤 서버 셈 같음 · 틀린 고침 400 · M01 안 바뀜."""
|
||||
me, key = made
|
||||
price, doc = _cut(me, key)
|
||||
row_before = copy.deepcopy(_live().logic(BASIC))
|
||||
with store.at(me):
|
||||
got = blk.preview(doc, 0, DOUBLE)
|
||||
read = blk.read(doc, 0)
|
||||
assert read["ok"] and got["되나"], got
|
||||
assert got["금액전"]["계"] == price and got["금액후"]["계"] > price
|
||||
assert got["수식"]["합계"]["계"] > got["전"]["계"] # 기초 1 단위 시간당 값
|
||||
item = {**doc["더한줄"][0], blk.EDIT: DOUBLE}
|
||||
_save(me, key, {**doc, "더한줄": [item]})
|
||||
saved = _doc(me, key)
|
||||
assert saved["더한줄"][0][blk.EDIT][0]["까닭"] == "sub3임시 시험"
|
||||
assert _sum(me, saved) == got["금액후"]["계"] # 서버 셈 = 미리 셈
|
||||
assert _live().logic(BASIC) == row_before
|
||||
with store.at(me):
|
||||
eq = full.attach(
|
||||
{"줄": []}, saved, skc.over(saved, skc.whole_()), {}, None, _calc(me, saved)
|
||||
)
|
||||
block = next(r for r in eq["소계"]["줄"] if r.get("블록") == 0)
|
||||
assert block["나무"]["합계"]["계"] == got["수식"]["합계"]["계"] # 접힘 블록 = 고친 수식
|
||||
bad = [{"할일": "식", "자리": "호표:0", "식": "없는값 / 작업량"}]
|
||||
with store.at(me):
|
||||
assert not blk.preview(saved, 0, bad)["되나"]
|
||||
with pytest.raises(store.StoreError):
|
||||
_save(me, key, {**saved, "더한줄": [{**saved["더한줄"][0], blk.EDIT: bad}]})
|
||||
assert _sum(me, _doc(me, key)) == got["금액후"]["계"]
|
||||
|
||||
|
||||
def test_relink_drops_edits_and_follows_original(made, monkeypatch):
|
||||
"""④ [다시 잇기] — 고친 것 버림 · 원본 따라감(저장 뒤 표지 없음) · 금액 = 새로 찍은 SK."""
|
||||
me, key = made
|
||||
was = _sum(me, _doc(me, key))
|
||||
_, doc = _cut(me, key)
|
||||
item = {**doc["더한줄"][0], blk.EDIT: DOUBLE}
|
||||
_save(me, key, {**doc, "더한줄": [item]})
|
||||
edited = _doc(me, key)
|
||||
assert _sum(me, edited) > was
|
||||
_fake(monkeypatch, [_changed(_live().logic(BASIC))]) # 원본 바뀜
|
||||
fresh = _sum(me, _doc(me, _sk(me, 바탕={"로직": FORM}, 더한줄=[copy.deepcopy(ADD)])))
|
||||
assert fresh > was
|
||||
with store.at(me):
|
||||
got = blk.change(edited, 0, "relink")
|
||||
one = got["문서"]["더한줄"][0]
|
||||
assert "끊음" not in one and blk.EDIT not in one and one[blk.REJOIN] is True
|
||||
assert got["전"]["계"] > was and got["후"]["계"] == fresh # 고침 버림 + 원본 따라감
|
||||
_save(me, key, got["문서"])
|
||||
saved = _doc(me, key)
|
||||
assert blk.REJOIN not in saved["더한줄"][0] and "끊음" not in saved["더한줄"][0]
|
||||
assert _sum(me, saved) == fresh
|
||||
|
||||
|
||||
def test_shape_checks(made):
|
||||
"""⑥ 연결 기초에 고침 · 이미 끊음 · 차례 밖 · 연결 기초 다시 잇기 · 끊은 기초 줄 모양."""
|
||||
me, key = made
|
||||
doc = _doc(me, key)
|
||||
with store.at(me):
|
||||
with pytest.raises(sd.DocError, match="연결을 끊은 기초만"):
|
||||
sd.clean({**doc, "더한줄": [{**ADD, blk.EDIT: DOUBLE}]})
|
||||
with pytest.raises(sd.DocError, match="없음"):
|
||||
blk.unlink(doc, 3)
|
||||
with pytest.raises(sd.DocError, match="연결된 기초"):
|
||||
blk.relink(doc, 0)
|
||||
with pytest.raises(sd.DocError, match="연결된 기초"):
|
||||
blk.read(doc, 0)
|
||||
cut = blk.unlink(doc, 0)
|
||||
with pytest.raises(sd.DocError, match="이미 연결을 끊은"):
|
||||
blk.unlink(cut, 0)
|
||||
broken = {**cut["더한줄"][0], "끊음": {"로직": [{"키": "GC999999"}]}}
|
||||
with pytest.raises(sd.DocError, match="줄 없음"):
|
||||
sd.clean({**cut, "더한줄": [broken]}, None, skc.whole_())
|
||||
@@ -23,7 +23,6 @@ from M02_MasterTemplete import M02_Labor_Ref as refs
|
||||
from M02_MasterTemplete import M02_Machine_Hourly as machine
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_Emit as em
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
from M02_MasterTemplete import M02_Sangeun_Imported as imp
|
||||
from resources.tester.test_m02_hopyo_excel import _post, client # noqa: F401
|
||||
@@ -128,7 +127,6 @@ def test_nested_stmate_follows_inner(world) -> None:
|
||||
assert len(inner) == 1 and inner[0]["값묶음"]["노무비"] == 6216 # 엑셀 얼린 값은 곁에 남음
|
||||
ref = inner[0]["참조"]
|
||||
assert made["검산"]["같음"] is True and made["검산"]["셈"]["계"] == 67383
|
||||
assert eqm.read(doc)["ok"] is True # 수식 탭도 안쪽 값을 채워 읽음
|
||||
assert fh.make(folder, KEY, 2200)["이름"] == made["이름"] # 다시 올려도 같은 SK
|
||||
assert refs.users(ref) # 쓰는 곳에 바깥 SK
|
||||
with pytest.raises(store.StoreError) as why:
|
||||
@@ -158,7 +156,7 @@ def test_nested_est_by_part_matches_excel(world) -> None:
|
||||
doc = _read(made["이름"])
|
||||
inner = [x for x in doc[imp.KEY]["로직"]["호표"] if x.get("참조")]
|
||||
assert len(inner) == 1 and "참조비목" not in inner[0]
|
||||
assert made["검산"]["같음"] is True and eqm.read(doc)["ok"] is True
|
||||
assert made["검산"]["같음"] is True
|
||||
# 엑셀 단가 그대로 금액 = 굳힌 값 합과 같음
|
||||
frozen = sum(float(v) for v in inner[0]["값묶음"].values())
|
||||
assert float(made["검산"]["셈"]["계"]) == pytest.approx(
|
||||
|
||||
@@ -18,7 +18,6 @@ from M01_MasterData import M01_MasterData_Doc as doc_store
|
||||
from M01_MasterData import M01_MasterData_Parts as parts
|
||||
from M01_MasterData import M01_MasterData_Router as m01_router
|
||||
from M01_MasterData import M01_MasterData_Store as store
|
||||
from M02_MasterTemplete import M02_Logic_Lib_Read as lib_read
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Router_Combos as combos
|
||||
|
||||
cv = importlib.import_module("master_doc_convert")
|
||||
@@ -96,7 +95,7 @@ def test_기계_부품():
|
||||
assert {"GC001147", "GF000088"} <= tpl and len(tpl) == 15
|
||||
coef = m01_router.get_parts("계수식")["계수식"]
|
||||
assert {x["키"] for x in coef} == {"GC001143", "GC001191", "GC001192", "GC001193"}
|
||||
one = lib_read.get_machine_parts("0201-0070")
|
||||
one = parts.of_machine("0201-0070")
|
||||
assert one["기계"] == {"이름": "굴착기(무한궤도)", "규격": "0.7㎥", "상세구분": "굴착기"}
|
||||
by = {t["키"]: t for t in one["틀"]}
|
||||
assert by["GC001147"]["규격"] == "버킷용량" and by["GF000088"]["문서"]["결과"] == "Q"
|
||||
|
||||
@@ -191,7 +191,6 @@ def test_담을_로직_읽기는_로그인이면_됨(world):
|
||||
assert user.get("/api/m02/logic-lib/logic", params={"key": A}).json()["logic"]["키"] == A
|
||||
assert user.get("/api/m02/logic-lib/logic", params={"key": "GF999999"}).status_code == 404
|
||||
assert user.get("/api/m02/logic-lib/subs").json()["subs"]
|
||||
assert user.get("/api/m02/logic-lib/auto", params={"key": A}).status_code == 200
|
||||
|
||||
|
||||
# ── 나무 길 없음(PLAN 39-2) ────────────────────────────────────────────
|
||||
|
||||
@@ -1,72 +1,15 @@
|
||||
"""M02 도면 양식 서버 길 — 자리표 키 목록 · 도각 파일 불러오기 (PLAN 10-3)."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
"""M02 구조물 도면에 얹는 도각 길(56장) — 자리표 · 도각 불러오기 길은 894 에서 걷음."""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from M02_MasterTemplete.M02_MasterTemplete_Router_Drawing import DRAWING_FIELDS, router
|
||||
from M02_MasterTemplete.M02_MasterTemplete_Router_Drawing import router
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router)
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_fields_cover_system_placeholders():
|
||||
# 시스템 도면 양식에 박힌 자리표는 전부 키 목록에 있다 — 없으면 화면이 모르는 칸이 생긴다.
|
||||
keys = {key for key, _, _ in DRAWING_FIELDS}
|
||||
used = set()
|
||||
for path in Path("resources/master_template/drawing").glob("00_*.json"):
|
||||
text = json.dumps(json.loads(path.read_text(encoding="utf-8")), ensure_ascii=False)
|
||||
used |= {match.strip() for match in re.findall(r"\{\{\s*([^}]+?)\s*\}\}", text)}
|
||||
assert used and used <= keys, used - keys
|
||||
|
||||
|
||||
def test_fields_without_project():
|
||||
response = client.get("/api/m02/drawing-fields")
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert [item["key"] for item in body["fields"]] == [key for key, _, _ in DRAWING_FIELDS]
|
||||
assert body["values"] == {}
|
||||
|
||||
|
||||
def test_import_rejects_other_files():
|
||||
response = client.post(
|
||||
"/api/m02/drawing-import", files={"file": ("a.txt", b"hello", "text/plain")}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "DXF" in response.json()["message"]
|
||||
|
||||
|
||||
def test_import_dxf():
|
||||
import ezdxf
|
||||
|
||||
document = ezdxf.new()
|
||||
document.modelspace().add_line((0, 0), (100, 50))
|
||||
stream = io.StringIO()
|
||||
document.write(stream)
|
||||
response = client.post(
|
||||
"/api/m02/drawing-import",
|
||||
files={"file": ("frame.dxf", stream.getvalue().encode("utf-8"), "application/dxf")},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert body["entity_count"] == 1
|
||||
assert body["drawing"]["entities"][0]["type"] == "Line"
|
||||
|
||||
|
||||
def test_import_garbage_is_400_not_500():
|
||||
for data in (b"garbage\x00\xff", b"", b"0\nSECTION\n2\nENTITIES\n0\nLINE\n10\nabc\n"):
|
||||
response = client.post(
|
||||
"/api/m02/drawing-import", files={"file": ("bad.dxf", data, "application/dxf")}
|
||||
)
|
||||
assert response.status_code == 400, (data, response.text)
|
||||
assert response.json()["message"]
|
||||
|
||||
|
||||
def test_structure_frame_origin_at_zero():
|
||||
# 56장 — 구조물 도면에 얹는 도각: 외곽 좌하단 (0,0) · 잠금 도각 층 · 원본 양식은 그대로
|
||||
from B07_DesignDetail.B07_DesignDetail_Engine_Template import entities_bbox, template_entities
|
||||
|
||||
@@ -46,7 +46,7 @@ def test_소스가_700줄을_넘지_않음():
|
||||
[
|
||||
(
|
||||
"M02_MasterTemplete_Api_Fetch.ts",
|
||||
["createStructure", "fetchStructureNumbers"], # readTemplate 은 39-4 에서 뺌
|
||||
["fetchStructureNumbers"], # readTemplate 은 39-4 · createStructure 는 894 에서 뺌
|
||||
PANEL,
|
||||
),
|
||||
# 산출근거 저장은 컨테이너가 안 함 — [산출근거 수정] 이 여는 메인 칸 전체 편집이 함
|
||||
@@ -65,24 +65,6 @@ def test_컨테이너가_쓰는_이름이_내보내진_것(source: str, names: l
|
||||
assert name in used, name
|
||||
|
||||
|
||||
def test_sub2_가_부르는_이름과_모양():
|
||||
"""브레인 확정 이름 · 모양 — sub2 가 이대로 부름(바꾸면 브레인에게)."""
|
||||
body = _text(M02 / "M02_MasterTemplete_Api_Fetch.ts")
|
||||
for name in ("copyStructure", "copyArea"):
|
||||
assert re.search(
|
||||
rf"export const {name} = async \(column: string, from: string\): Promise<void>", body
|
||||
), name
|
||||
assert "fetchStructureNumbers = (): Promise<Record<string, StructureNumbers>>" in body
|
||||
assert re.search(
|
||||
r"interface StructureNumbers \{\s*도번: string;\s*면적번: string;\s*/\*\* 일위대가[^*]*\*/\s*일위대가번: string;(\s*/\*\*[^*]*\*/)?\s*일위대가합계\?: number;\s*합계기준\?: boolean;(\s*/\*\*[^*]*\*/)?(\s*합계\w+\?: [^;]+;)*\s*\}",
|
||||
body,
|
||||
)
|
||||
assert re.search(r'export type Kind = [^;]*"area" \| "labor"', body) # 재료산출 없앰
|
||||
assert '"material"' not in re.search(r"export type Kind = [^;]*;", body).group(
|
||||
0
|
||||
) # 50-3 서고 종류 더함
|
||||
|
||||
|
||||
def test_집계표만_컨테이너를_붙임():
|
||||
"""다른 표 양식에는 안 붙음 — 프로젝트 층 아님 · 이름이 집계표일 때만."""
|
||||
body = _text(MAIN)
|
||||
|
||||
@@ -48,9 +48,6 @@ def world(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
|
||||
found = projects.get(str(project_id))
|
||||
return dict(found) if found else None
|
||||
|
||||
async def user_company(user_id: int) -> int | None:
|
||||
return users.get(user_id)
|
||||
|
||||
async def company_users(company_id: int) -> list[dict[str, Any]]:
|
||||
return [{"user_id": u, "name": f"u{u}"} for u, c in users.items() if c == company_id]
|
||||
|
||||
@@ -62,7 +59,6 @@ def world(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
|
||||
]
|
||||
|
||||
monkeypatch.setattr(router_module, "_project_row", project_row)
|
||||
monkeypatch.setattr(router_module, "_user_company", user_company)
|
||||
monkeypatch.setattr(router_module, "_company_users", company_users)
|
||||
monkeypatch.setattr(router_module, "_company_projects", company_projects)
|
||||
|
||||
@@ -108,35 +104,13 @@ def test_작업본_저장_판_다르면_409_초기화는_초기본으로(world:
|
||||
assert saved.status_code == 200
|
||||
stale = client.put(_url(), json={"판": got["판"], "문서": {"판": 3, "열": []}})
|
||||
assert stale.status_code == 409
|
||||
reset = client.post(f"/api/m02/projects/{P1}/templates/reset", json={})
|
||||
assert "table/구조물집계표" in reset.json()["초기화"]
|
||||
assert "table/구조물집계표" in layers.reset_project(_root(world, P1)) # [초기화] = B07 길
|
||||
assert client.get(_url()).json()["문서"] == {"판": 1, "열": []}
|
||||
initial = _root(world, P1) / "templates/_initial/table/구조물집계표.json"
|
||||
assert layers.read_template(initial.parent.parent, "table", "구조물집계표")["문서"]["판"] == 1
|
||||
|
||||
|
||||
def test_회사_공식_저장은_관리자만_적용은_작업본만(world: dict[str, Any]) -> None:
|
||||
client, session = world["client"], world["session"]
|
||||
client.put(_url(), json={"판": client.get(_url()).json()["판"], "문서": {"회사": 1, "열": []}})
|
||||
body = {"to": "company", "종류": "table", "이름": "구조물집계표"}
|
||||
assert client.post(f"/api/m02/projects/{P1}/templates/save-as", json=body).status_code == 403
|
||||
session["role"] = "ADMIN"
|
||||
assert client.post(f"/api/m02/projects/{P1}/templates/save-as", json=body).status_code == 200
|
||||
applied = client.post(f"/api/m02/projects/{P2}/templates/apply", json={"from": "company"})
|
||||
assert applied.status_code == 200
|
||||
root2 = _root(world, P2, user=43)
|
||||
assert layers.read_template(root2 / "templates", "table", "구조물집계표")["문서"] == {
|
||||
"회사": 1,
|
||||
"열": [],
|
||||
}
|
||||
assert (
|
||||
layers.read_template(root2 / "templates/_initial", "table", "구조물집계표")["문서"]["판"]
|
||||
== 1
|
||||
)
|
||||
assert layers.read_manifest(root2 / "templates")["table/구조물집계표"]["층"] == "company"
|
||||
|
||||
|
||||
def test_개인_양식은_본인만_쓰고_같은_회사는_읽어_가져옴(
|
||||
def test_개인_양식은_본인만_쓰고_같은_회사_관리자는_읽음(
|
||||
world: dict[str, Any], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
client, session = world["client"], world["session"]
|
||||
@@ -146,8 +120,6 @@ def test_개인_양식은_본인만_쓰고_같은_회사는_읽어_가져옴(
|
||||
notes.append(got.owner)
|
||||
|
||||
monkeypatch.setattr(items_router, "_note", note)
|
||||
body = {"to": "personal", "종류": "table", "이름": "구조물집계표"}
|
||||
assert client.post(f"/api/m02/projects/{P1}/templates/save-as", json=body).status_code == 200
|
||||
mine = f"/api/m02/layers/personal/templates/table/구조물집계표?project_id={P1}"
|
||||
assert client.get(mine).status_code == 200
|
||||
session.update(user_id=43)
|
||||
@@ -172,44 +144,8 @@ def test_개인_양식은_본인만_쓰고_같은_회사는_읽어_가져옴(
|
||||
)
|
||||
assert put.status_code == 200
|
||||
assert (world["storage"] / "7/43/templates/table/내표.json").is_file()
|
||||
got = client.post(
|
||||
f"/api/m02/projects/{P2}/templates/apply", json={"from": "personal", "user_id": 42}
|
||||
)
|
||||
assert got.status_code == 403 # 일반 = 남 개인 못 가져옴(39-6)
|
||||
session["role"] = "ADMIN"
|
||||
got = client.post(
|
||||
f"/api/m02/projects/{P2}/templates/apply", json={"from": "personal", "user_id": 42}
|
||||
)
|
||||
assert got.status_code == 200 # 회사 관리자 = 같은 회사 개인 가져옴
|
||||
assert client.get(mine.replace(P1, P_OTHER)).status_code == 403
|
||||
far = client.post(
|
||||
f"/api/m02/projects/{P2}/templates/apply", json={"from": "personal", "user_id": 90}
|
||||
)
|
||||
assert far.status_code == 403
|
||||
|
||||
|
||||
def test_가져오기는_같은_회사_프로젝트만_목록도(world: dict[str, Any]) -> None:
|
||||
client = world["client"]
|
||||
ok = client.post(
|
||||
f"/api/m02/projects/{P1}/templates/apply", json={"from": "project", "project_id": P2}
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
bad = client.post(
|
||||
f"/api/m02/projects/{P1}/templates/apply", json={"from": "project", "project_id": P_OTHER}
|
||||
)
|
||||
assert bad.status_code == 403
|
||||
sources = client.get(f"/api/m02/projects/{P1}/sources").json()
|
||||
assert [row["project_id"] for row in sources["project"]] == [P2]
|
||||
assert {row["이름"] for row in sources["system"]} == {"구조물집계표", "A1_도각"}
|
||||
for user in (42, 43): # 개인 층 둘 — 일반은 내 것만 · 회사 관리자는 회사 사람 전부(39-6)
|
||||
layers.write_template(layers.personal_dir(7, user), "table", "표", {"열": []})
|
||||
assert [row["user_id"] for row in sources_of(client)] == [42]
|
||||
world["session"]["role"] = "ADMIN"
|
||||
assert [row["user_id"] for row in sources_of(client)] == [42, 43]
|
||||
|
||||
|
||||
def sources_of(client: TestClient) -> list[dict[str, Any]]:
|
||||
return client.get(f"/api/m02/projects/{P1}/sources").json()["personal"]
|
||||
|
||||
|
||||
def test_시스템_층은_읽기만_이름은_막음(world: dict[str, Any]) -> None:
|
||||
|
||||
Reference in New Issue
Block a user