Merge remote-tracking branch 'origin/dev' into sub_laptop_8

This commit is contained in:
2026-11-18 22:44:18 +09:00
169 changed files with 1103 additions and 1270 deletions
+3
View File
@@ -10,6 +10,7 @@
* 고르면 줄이 생김(닫으면 안 생김) · 있는 줄 = 자원 이름 단추
* ========================================================================== */
import type { PlacedTable } from "../common_util/common_util_show_digits";
import { createBadge } from "@ui/ui_template_badge";
import { createButton, createIconButton, setUiDiff } from "@ui/ui_template_button";
import { createRowMenu } from "@ui/ui_template_context_menu";
@@ -93,6 +94,8 @@ export interface EditHooks {
lists?: (given: Record<string, unknown>) => Record<string, unknown> | null;
/** 845-2 표 한 칸 읽기(캐시) — 「줄 따름」 값의 고른 줄 단위 */
look?: TableLook;
/** 859-3 캐시 표 통째 — 표 값의 원문 글자 자리(보이는 자리) */
tableCache?: (ref: string) => PlacedTable | undefined;
/** 846-2 그 기계 작업량 줄 */
work?: (machine: string) => WorkSpec[];
/** 848-3 ① 위 층 고침(SK 읽기 답 `위덮음` · M01 = 없음) */
+19 -13
View File
@@ -59,8 +59,9 @@ import {
} from "../common_util/common_util_line_stack_unit";
import { workAt } from "../common_util/common_util_line_stack_work";
import { workKey } from "../common_util/common_util_formula_doc_work";
import { showValue } from "../common_util/common_util_show_digits";
import { partName, partUnit } from "../common_util/common_util_machine_symbol_name";
import { katexNode, symTex, tex, txt, valTex, type TexCtx } from "./line_stack_tex";
import { katexNode, symTex, tex, txt, type TexCtx } from "./line_stack_tex";
import { lt } from "./line_stack_text";
import { workQty, workRows } from "./line_stack_work";
@@ -143,9 +144,14 @@ function rows(
const alias = tableAlias(doc); // 표 값 기호 화면 이름(요구 683)
const machine = doc.부품?.갈래 === "기계경비식"; // 845-2 한 줄 분수 한 층(중간 줄로 나눔)
const taken = new Set([...vars.keys(), ...lines.keys(), ...Object.values(alias)]);
/** 수 글 — 고르기 · 코드 값(S_ · 직종 1048 등)은 쉼표 없이 */
/** 수 글 — 고르기 · 코드 값(S_ · 직종 1048 등)은 쉼표 없이 · 그 밖 = 보이는 자리 규칙(859-3) */
const code = (id: string): boolean => /^S(_|$)/.test(id);
const numText = (id: string, v: number): string => (code(id) ? String(v) : eqText(v));
const numText = (id: string, v: unknown, u?: string): string => {
if (code(id)) return String(v);
return showValue(doc, id, v, vals, h.cache.tableOf, u);
};
/** 조판 값 글(천 자리 쉼표 = TeX 「{,}」) */
const show = (id: string, v: unknown): string => numText(id, v).replace(/,/g, "{,}");
/** 식 줄 「기호 = 기호식 = 값식 = 결과 단위」 — 같은 꼴이 이어지면 한 번만(만약이 수 하나를 탄 줄) */
const formula = (
id: string,
@@ -156,13 +162,13 @@ function rows(
more: Partial<TexCtx>,
): (string | HTMLElement)[] => {
const res = isNum(v)
? katexNode(`${code(id) ? String(v) : valTex(v)}\\ ${u ? txt(u) : ""}`) // 단위 글 = TeX 안전(「%」 주석 · 「^」 첨자 막음)
? katexNode(`${show(id, v)}\\ ${u ? txt(u) : ""}`) // 단위 글 = TeX 안전(「%」 주석 · 「^」 첨자 막음)
: typeof v === "string" // 글 값(기계 원문번호 등 · 838-3) = 그 글 · 기계면 이름
? el("span", { text: machineText(v, () => h.redraw?.()) ?? v })
: missing(a, id);
const sym = tex(n, { side: "sym", vals: vs, alias, ...more });
const val = tex(n, { side: "val", vals: vs, alias, ...more });
const same = isNum(v) && val === valTex(v);
const val = tex(n, { side: "val", vals: vs, alias, show, ...more });
const same = isNum(v) && val === show(id, v);
return [
katexNode(symTex(alias[id] ?? id)),
...(sym === val ? [] : [" = ", katexNode(sym)]),
@@ -342,7 +348,7 @@ function rows(
const glue = (...xs: (string | HTMLElement)[]): HTMLElement =>
el("span", { className: "lstk-pack", children: xs.filter((x) => x !== "") });
// 846-2 작업량 — 「시간당 작업량」 줄 먼저 · 수량 = 「÷ 시간당 작업량」
const wq = (): HTMLElement[] | null => workQty(doc, qty, w, scope, alias); // 줄마다 새 요소
const wq = (): HTMLElement[] | null => workQty(doc, qty, w, scope, alias, show); // 줄마다 새 요소
const byWork = wq() !== null;
const workHead = (): void => {
if (!w) return;
@@ -359,8 +365,8 @@ function rows(
glue(
" × ",
mu.wrap && qn
? katexNode(`\\left(${tex(qn, { side: "val", vals: scope, inline: true, cost, alias })}\\right)`) // prettier-ignore
: exprNode(qty, "val", scope, true, cost, { alias }),
? katexNode(`\\left(${tex(qn, { side: "val", vals: scope, inline: true, cost, alias, show })}\\right)`) // prettier-ignore
: exprNode(qty, "val", scope, true, cost, { alias, show }),
mu.qty ? ` ${mu.qty}` : "",
),
];
@@ -383,7 +389,7 @@ function rows(
const by = (line as { 비목곱?: Record<string, string> }).비목곱?.[c]; // 848-7 그 비목만 더 곱함
const byNode = by ? nodeOf(by) : null;
const times = byNode
? [glue(" × ", katexNode(`\\left(${tex(byNode, { side: "val", vals: scope, inline: true, cost: c, alias })}\\right)`))] // prettier-ignore
? [glue(" × ", katexNode(`\\left(${tex(byNode, { side: "val", vals: scope, inline: true, cost: c, alias, show })}\\right)`))] // prettier-ignore
: [];
push({
h: [`${COST_SHOW[c]} : `, glue(`${eqText(bundle[c])}${priceUnit}`), ...qtyNode(c), ...times, ` = ${one(part)} ${AMOUNT_UNIT}`], // prettier-ignore
@@ -399,9 +405,9 @@ function rows(
? [
exprNode(line.단가, "sym", scope, true, undefined, { place, alias }),
" = ",
exprNode(line.단가, "val", scope, true, undefined, { alias }),
exprNode(line.단가, "val", scope, true, undefined, { alias, show }),
]
: [glue(exprNode(line.단가, "val", scope, true, undefined, { alias }), priceUnit)];
: [glue(exprNode(line.단가, "val", scope, true, undefined, { alias, show }), priceUnit)];
const c = String(line.비목);
const bare = !!line.합밖 && !line.비목; // 합 밖 소계(810-2) = 글에만 금액 · 비목 칸 빈칸
workHead();
@@ -462,7 +468,7 @@ function rows(
push({
h: [
katexNode(symTex(doc.결과)),
` = ${isNum(r) ? `${eqText(r)} ${doc.결과단위 ?? ""}` : "—"}`,
` = ${isNum(r) ? `${numText(doc.결과, r, String(doc.결과단위 ?? ""))} ${doc.결과단위 ?? ""}` : "—"}`,
],
cls: "total",
});
+6 -1
View File
@@ -10,6 +10,7 @@
* 표 값(804-3) = [표 · 칸] 단추 → 표 고르기 창(`line_stack_pick.ts`) · 값 칸 누름 = 그 줄 · 칸(`pickCell`)
* ========================================================================== */
import { showValue } from "../common_util/common_util_show_digits";
import { createButton, createIconButton } from "@ui/ui_template_button";
import { eqText } from "@ui/ui_template_equation";
import { el, showToast } from "@ui/ui_template_elements";
@@ -162,7 +163,11 @@ export function buildBlock(
const v = vals[id];
const mach = machineText(v, () => h.change(() => undefined)); // 838-3 기계 원문번호 = 이름
if (mach) return mach;
if (isNum(v) || typeof v === "string") return `${eqText(v)} ${unitOf(id)}`.trim();
if (isNum(v)) {
const t = showValue(d, id, v, vals, h.tableCache); // 859-3 보이는 자리 규칙(표 = 원문 글자 자리)
return `${t} ${unitOf(id)}`.trim();
}
if (typeof v === "string") return `${eqText(v)} ${unitOf(id)}`.trim();
if (v && typeof v === "object") {
const key = vars.get(id)?.연결?.키; // 845-2 묶음 값 = 그 문서 결과 단위(원/시간 등)
const u = unitOf(id) || unitText(key ? h.subDoc(key)?.결과단위 : "");
+1
View File
@@ -444,6 +444,7 @@ export function createStackScreen(opt: StackScreenOptions) {
calc: calcSub,
lists: (g) => listsOf((q) => cache.links.element(q), g),
look: (p) => cache.links.table(p),
tableCache: (k) => cache.tableOf(k),
work: (m) => machineWork((q) => cache.links.element(q), m),
upper,
ctlEdit: !cp && edit(), // 848-3 M01 기초 = 시스템 관리자
+6 -2
View File
@@ -27,6 +27,8 @@ export interface TexCtx {
decided?: boolean;
/** 남은 분수 층(845-2 — 0 이면 안쪽 ÷ 는 한 줄 · 없음 = 끝없음) */
frac?: number;
/** 859-3 값 식의 기호 값 글(보이는 자리 규칙 · TeX 쉼표 「{,}」) — 없으면 `valTex` */
show?: (id: string, v: unknown) => string;
}
const HIDE = new Set(["반올림", "올림", "버림"]);
@@ -101,8 +103,10 @@ export function tex(n: Node, c: TexCtx): string {
const id = c.alias?.[n[1]] ?? n[1];
if (c.side === "sym") return symTex(id);
let v = c.vals[n[1]];
if (v && typeof v === "object" && c.cost) v = (v as Values)[c.cost];
return v === null || v === undefined || typeof v === "object" ? miss(symTex(id)) : valTex(v);
const part = !!v && typeof v === "object" && !!c.cost; // 묶음 값의 비목(단가 · 자료 그대로)
if (part) v = (v as Values)[c.cost!];
if (v === null || v === undefined || typeof v === "object") return miss(symTex(id));
return c.show && isNum(v) && !part ? c.show(n[1], v) : valTex(v);
}
case "field": {
const [, of, key] = n;
+22 -11
View File
@@ -11,8 +11,8 @@
import { createBadge } from "@ui/ui_template_badge";
import { el } from "@ui/ui_template_elements";
import { eqText } from "@ui/ui_template_equation";
import { varId, type FormulaDoc, type Node } from "../common_util/common_util_formula_doc";
import { showDigits, showValue } from "../common_util/common_util_show_digits";
import {
calcDoc,
isNum,
@@ -30,7 +30,7 @@ import {
restOfQty,
workUnit,
} from "../common_util/common_util_line_stack_work";
import { katexNode, symTex, tex, txt, valTex } from "./line_stack_tex";
import { katexNode, symTex, tex, txt } from "./line_stack_tex";
import { lt, type LsKey } from "./line_stack_text";
export interface WorkRow {
@@ -51,7 +51,15 @@ export function workTag(kind: string, title = ""): HTMLElement {
const chain = (...xs: string[]): (string | HTMLElement)[] =>
xs.flatMap((x, i) => (i ? [" = ", katexNode(x)] : [katexNode(x)]));
const unitTex = (u: string): string => (u ? `\\ ${txt(u)}` : "");
const amount = (v: unknown, u: string): string => `${valTex(v)}${unitTex(u)}`;
/** 859-3 시간당 작업량 Q = 소수 3 자리(건설 8-1 [주]① 계산값의 맺음) */
const workText = (v: unknown): string => showDigits(v, "식", "Q");
const workAmount = (v: unknown, u: string): string =>
`${workText(v).replace(/,/g, "{,}")}${unitTex(u)}`;
/** 859-3 문서 값 글(보이는 자리 규칙 · TeX 쉼표) */
const docShow =
(doc: FormulaDoc, vals: Values) =>
(id: string, v: unknown): string =>
showValue(doc, id, v, vals).replace(/,/g, "{,}");
/** 작업량 틀 풀이 — 값 줄 + 결과 식 줄(없으면 빈 목록) */
export function hourlyRows(
@@ -64,13 +72,15 @@ export function hourlyRows(
const vals = (a.값 ?? {}) as Values;
const vars = new Map((tpl.변수 ?? []).map((v) => [varId(v), v]));
const unit = (id: string): string => workUnit(shownUnitOf(vars.get(id), vals, look));
const pack = parts.uses.map((id) =>
katexNode(`${symTex(id)} = ${isNum(vals[id]) ? amount(vals[id], unit(id)) : txt("—")}`),
const show = docShow(tpl, vals);
const pack = parts.uses.map(
(id) =>
katexNode(`${symTex(id)} = ${isNum(vals[id]) ? `${show(id, vals[id])}${unitTex(unit(id))}` : txt("—")}`), // prettier-ignore
);
const res = vals[parts.id];
const sym = tex(parts.node, { side: "sym", vals, frac: 1 });
const val = tex(parts.node, { side: "val", vals, frac: 1 });
const end = isNum(res) ? amount(res, workUnit(tpl.결과단위)) : txt("—");
const val = tex(parts.node, { side: "val", vals, frac: 1, show });
const end = isNum(res) ? workAmount(res, workUnit(tpl.결과단위)) : txt("—");
return [
...(pack.length ? [{ h: pack, cls: "packs" }] : []),
{ h: chain(symTex(parts.id), sym, val, end), cls: "work" },
@@ -99,14 +109,14 @@ export function workRows(w: WorkInfo, c: WorkCtx): WorkRow[] {
c.miss();
}
const tag = workTag(w.꼴, tpl?.이름 ?? w.율);
if (!tpl) return [{ h: [tag, `${head} = `, isNum(w.값) ? `${eqText(w.값)} ${u}`.trim() : lt("Work_Wait")] }]; // prettier-ignore
if (!tpl) return [{ h: [tag, `${head} = `, isNum(w.값) ? `${workText(w.값)} ${u}`.trim() : lt("Work_Wait")] }]; // prettier-ignore
const a = calcDoc(tpl, c.links!, w.변수 ?? {}, [], new Map(), {});
const name = el("span", { className: "lstk-hint", text: tpl.이름 ?? w.율 });
return [{ h: [tag, name] }, ...hourlyRows(tpl, a, c.look)];
}
if (!isNum(w.값)) return [];
const tag = workTag(w.꼴 || "일당");
const res = amount(w.값, u);
const res = workAmount(w.값, u);
const parts = w.꼴 === "일당" ? dailyParts(w.율) : null;
if (parts) {
const val = (n: Node): string => tex(n, { side: "val", vals: c.vals, inline: true });
@@ -130,13 +140,14 @@ export function workQty(
w: WorkInfo | null,
scope: Values,
alias?: Record<string, string>,
show?: (id: string, v: unknown) => string,
): HTMLElement[] | null {
if (!w || !isNum(w.값) || w.값 <= 0) return null;
const got = restOfQty(doc, qty);
if (!got) return null;
const by = katexNode(`{}\\div ${amount(w.값, workUnit(w.단위))}`); // {} = 두 항 사이 ÷ 간격
const by = katexNode(`{}\\div ${workAmount(w.값, workUnit(w.단위))}`); // {} = 두 항 사이 ÷ 간격
if (!got.rest) return [by];
return [by, katexNode(`\\times ${tex(got.rest, { side: "val", vals: scope, inline: true, alias })}`)]; // prettier-ignore
return [by, katexNode(`\\times ${tex(got.rest, { side: "val", vals: scope, inline: true, alias, show: show ?? docShow(doc, scope) })}`)]; // prettier-ignore
}
const nameOf = (doc: FormulaDoc, id: string): string =>
@@ -47,7 +47,7 @@ def plan_structure(item: Any) -> dict[str, Any]:
def structure_table() -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""구조물 종류(`/projects/structure-types` 꼴) · 정의(화면 `useCatalogDefinition` 꼴)."""
from B05_Profile.B05_Profile_Structures_Schema import _read_definition, _stamp
from M02_MasterTemplete.StructOptions.M02_SO_Options import with_visible
from M01_MasterData.StructOptions.M01_SO_Options import with_visible
types = [item.model_dump(mode="json") for item in with_visible().types]
return types, {"types": types, **_read_definition(*_stamp())}
@@ -18,7 +18,7 @@ from B05_Profile.B05_Profile_Structures_Schema import (
structure_type_map,
)
from common_util.common_util_json import atomic_write_json
from M02_MasterTemplete.StructOptions.M02_SO_Options import hidden_keys
from M01_MasterData.StructOptions.M01_SO_Options import hidden_keys
STRUCTURES_FILE_NAME = "structures.json"
_STAGE_DIR = os.path.join("B05_Profile", "route")
+1 -1
View File
@@ -51,7 +51,7 @@ from common_util.common_util_route_follow import (
from common_util.common_util_storage import resolve_stored_project_path
from common_util.common_util_structure_station import SAME_STATION_M, plan_stations
from config.config_db import get_db_pool
from M02_MasterTemplete.StructOptions.M02_SO_Options import TypesWithVisible, with_visible
from M01_MasterData.StructOptions.M01_SO_Options import TypesWithVisible, with_visible
logger = logging.getLogger(__name__)
+5 -4
View File
@@ -1,6 +1,6 @@
"""B05 구조물 타입 레지스트리·인스턴스 검증 모델.
구조물 타입 정의는 코드가 아니라 데이터(M02 마스터 `resources/master_template/구조물정의.json`
구조물 타입 정의는 코드가 아니라 데이터(M01 마스터 `resources/master_data/구조물정의/구조물정의.json`
`types` · PLAN 48-1)다. 리스트가 바뀌어도 코드를 고치지 않도록 분리했고, 프론트는
`GET /structure-types`로 같은 정본을 받는다. 정의 틀 = `docs/raw/M02_구조물옵션정의/정의_틀.md`.
@@ -27,7 +27,8 @@ STRUCTURE_SIDES = ("left", "right", "center", "cross")
DEFINITION_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"resources",
"master_template",
"master_data",
"구조물정의",
"구조물정의.json",
)
@@ -159,8 +160,8 @@ def is_station_planting_type(item: StructureType) -> bool:
return row is not None and row["station"] != "none"
#: 지난 판 정의(`판_N.json`) 폴더 — 정본 옆(M02 `M02_SO_Definition.HISTORY` 와 같은 이름)
HISTORY_DIRNAME = "구조물정의_이력"
#: 지난 판 정의(`판_N.json`) 폴더 — 정본 옆(M01 `M01_SO_Definition.HISTORY` 와 같은 이름)
HISTORY_DIRNAME = "이력"
def registry_schema_version() -> int:
@@ -2,7 +2,7 @@
* B05_Profile_UI_Structures_Define.ts
* 구조물 정의 → 「구조물 배치」 칸 모양 (PLAN 48-3 · 48-4) — 화면 요소 없는 순수 규칙.
*
* 정의(`resources/master_template/구조물정의.json` · GET /structure-types 가 실어 줌)를 읽어
* 정의(`resources/master_data/구조물정의/구조물정의.json` · GET /structure-types 가 실어 줌)를 읽어
* 칸 차례 · 격자 · 안 씀 · 규칙(상위 값 → 하위 선택지 · 보이기 · 기본값)을 낸다. 틀 =
* `docs/raw/M02_구조물옵션정의/정의_틀.md`. 선택지를 줄이면(숨김) 옛 값은 그 값만 남겨 보임.
* 그리기는 `_Structures_Panel_Options`(레지스트리 칸) · `_Structures_Define_Form`(시설 폼 칸).
@@ -243,7 +243,7 @@ def with_option_lines(things: list[Thing]) -> list[Thing]:
return things
try:
# 지연 import — M02 정의 저장소가 B07 엔진 import 차례에 끼지 않게
from M02_MasterTemplete.StructOptions.M02_SO_Options import with_visible
from M01_MasterData.StructOptions.M01_SO_Options import with_visible
payload = {
"things": [
+2 -2
View File
@@ -52,15 +52,15 @@ from B06_Section.B06_Section_Repository import (
)
from B08_Quantity.B08_Quantity_Router_Hydro import _project_root
from B08_Quantity.B08_Quantity_Summary_Sheet import _linked, _Sheet, unlinked_facilities
from common_util.common_util_structure_catalog import type_ids_with
from common_util.common_util_drainage_pipes import pipe_points_path_in, read_pipe_points_file
from common_util.common_util_structure_catalog import type_ids_with
from common_util.common_util_summary_item import GROUP_JOIN
from config.config_db import get_db_pool
from M01_MasterData.StructOptions import M01_SO_Definition as definition
from M02_MasterTemplete import M02_Item_Snapshot as snapshots
from M02_MasterTemplete import M02_Table_Fill as fill
from M02_MasterTemplete import M02_Template_Layers as layers
from M02_MasterTemplete.M02_Table_Fill_Spec import soil_tiers_from_designs
from M02_MasterTemplete.StructOptions import M02_SO_Definition as definition
router = APIRouter(prefix="/api/projects", tags=["B08 Summary"])
+2 -37
View File
@@ -7,9 +7,7 @@
precombo 사전조합 = `일위대가.json` {줄: {담은로직: [{참조, 수량: {손: 1}}]}, 참조사본} ·
`단가.json`(`M02_Item_Source.price_bundle` — 사본 단가 묶음 한 벌)
sangeun 단가산출(SK · 내 자료집 · 719-2) = precombo 와 한 꼴(SK = 수식 사본 · B9-5)
[업데이트](719-2) = 원본판이 다른 사본만 같은 폴더에 다시 굳힘(`changed` · `refresh_copy` ·
값 그대로 · 원본판 없는 옛 사본 = 그대로).
사본 = 원본이 바뀌거나 지워져도 그대로(굳힘) ·
사본 = 원본이 바뀌거나 지워져도 그대로(굳힘 · 859-2 프로젝트 안 다시 굳힘 없음) ·
대가 블록 = `Labor_Source.daega_inputs`(`libs` {폴더: 블록 id}) ·
단가 수요 = `Linked.linked_resource_keys` · 줄 연결 = {tab: dg, key: 블록 id, lib: 폴더} ·
[저장] 때 줄이 안 쓰는 사본은 지움(`prune`) · 층 읽기 권한 = 부르는 쪽(`M02_Layer_Access.grant`).
@@ -104,7 +102,7 @@ def _precombo_files(layer: str, owner: str | None, key: str, kind: str = "precom
def source_version(files: dict[str, Any]) -> str:
"""서고 사본 원본판(719-1) = 일위대가.json + 수식 문서(로직 몫 · 855-F B9-6) 지문 — 굳힌 SC · SK
문서(SK = 수식 사본) · 단가는 뺌(단가 바뀜은 [단가 갱신] 몫) · 값 덮기 전에 셈."""
문서(SK = 수식 사본) · 단가는 뺌 · 값 덮기 전에 셈."""
return version_of([files.get(LABOR_FILE), (files.get(doc_b09.FILE) or {}).get("문서")])
@@ -121,39 +119,6 @@ def _build(kind: str, layer: str, owner: str | None, key: str) -> tuple[dict, di
return files, files.pop("_원본")
def _source_of(manifest: dict[str, Any]) -> tuple[str, str, str | None, str]:
"""manifest → (종류, 층, 주인, 키)."""
kind, origin = str(manifest.get("종류")), manifest.get("원본") or {}
if kind == "combo":
return kind, origin.get("layer"), origin.get("owner"), origin.get("key")
ref = origin.get("참조") or {}
return kind, ref.get("층"), ref.get("주인"), ref.get("키")
def changed(project_root: str | Path) -> list[tuple[Path, dict[str, Any], dict, dict]]:
"""원본판이 지금 원본과 다른 사본 `(폴더, manifest, 새 파일들, 새 원본 표지)` — 원본판 없는 옛
사본 · 원본 없음 = 뺌(그대로)."""
out = []
for folder, manifest in copies(project_root):
if not manifest.get("원본판"):
continue
try:
files, origin = _build(*_source_of(manifest))
except (LookupError, ValueError, KeyError):
continue
if source_version(files) != manifest["원본판"]:
out.append((folder, manifest, files, origin))
return out
def refresh_copy(project_root: str | Path, one: tuple) -> None:
"""`changed` 한 줄 → 같은 폴더에 다시 굳힘(값 · 가져온이 그대로 · 원본판 새로)."""
folder, manifest, files, origin = one
keep = {k: v for k, v in manifest.items() if k not in ("값", "원값")}
fresh = {**keep, "원본": origin, "원본판": source_version(files), "가져온날": now_text()}
_write(project_root, folder.name, files, fresh, manifest.get("값") or {})
# ── 운반 값 사본(263-2) ────────────────────────────────────────────────
def _logic(code: str) -> dict[str, Any]:
"""M01 기초 이름 · 입력 꼴 — 지금 수식 문서(855-F B9-6) · 없는 기초 = 입력 없음."""
@@ -1,92 +0,0 @@
"""B09 [단가 갱신] = 프로젝트 사본 자원 단가 줄 갱신(PLAN 841-1 · 요구 854 · 866) — 서버 단독.
B09 금액 = 프로젝트 사본(구조물 사본 · 서고 사본)을 M02 엔진으로 셈한 값(B09 단가 책으로 다시 안 셈).
그래서 사본 값을 지금 M01 로 올리는 일 = 사본 `단가.json` 자원 줄(LB · MT · EQ · MO · FX)만 지금 M01 줄로
(로직 줄 · 일위대가 · 입력값 · 고른 자재 · 덮개 그대로 · M01 에서 지워진 키 = 마지막 값 그대로) —
M02 [단가 갱신](`M02_Sangeun_Copy.refresh`)과 같은 뜻 · 사용자가 누를 때만(프로젝트 안은 자동 아님).
미리 보기 = `OVER` 덮개(파일 안 씀 · 사본 읽는 곳이 `bundle` 로 읽음)로 같은 셈.
"""
from __future__ import annotations
from contextvars import ContextVar
from pathlib import Path
from typing import Any
from B09_Estimation import B09_Estimation_Bill_Library as library
from common_util.common_util_json import atomic_write_json
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Item_Prices as item_prices
from M02_MasterTemplete import M02_Sangeun_Copy as skc
from M02_MasterTemplete.M02_Item_Snapshot import linked_snapshots, structures_dir
from M02_MasterTemplete.M02_Item_Source import PRICE_FILE, read_json
#: 미리 보기 덮개 {사본 폴더 글: 새 `단가.json`} — 없으면 파일
OVER: ContextVar[dict[str, dict] | None] = ContextVar("b09_copy_prices", default=None)
def bundle(folder: Path) -> dict[str, Any]:
"""사본 `단가.json` — 미리 보기 덮개가 있으면 그것."""
over = OVER.get()
if over and str(folder) in over:
return over[str(folder)]
return read_json(folder / PRICE_FILE) or {}
def folders(root: str | Path) -> list[Path]:
"""연결된 구조물 사본 + 서고 사본 폴더."""
base = structures_dir(root)
out = [base / one["폴더"] for one in linked_snapshots(root).values()]
out += [folder for folder, _manifest in library.copies(root)]
return list(dict.fromkeys(out))
def _shown(row: dict[str, Any]) -> Any:
"""미리 보기 값 — 노임 · 유가 = 값 · 기계 = 가격(천원) · 자재 = 출처 값 묶음."""
value = row.get("값")
if isinstance(value, dict):
return value.get("가격")
if value is not None:
return value
return {k: row.get(k) for k in ("조달청", "물가자료", "유통물가", "물가정보", "거래가격")}
def refreshed(root: str | Path) -> tuple[dict[str, dict], list[dict[str, Any]]]:
"""({바뀐 사본 폴더 글: 새 `단가.json`}, 바뀐 자원 [{키, 이름, 전, 후}]) — 파일 안 씀."""
whole = skc.whole_()
news: dict[str, dict] = {}
changed: dict[str, dict[str, Any]] = {}
for folder in folders(root):
data = read_json(folder / PRICE_FILE)
if not isinstance(data, dict):
continue
out, hit = {}, False
for name, part in data.items():
slot = m01.items_key(part) if isinstance(part, dict) else ""
rows = part.get(slot) if slot else None
if not isinstance(rows, list):
out[name] = part
continue
fresh = []
for row in rows:
key = str((row or {}).get("키") or "")
live = whole.index.get(key[:2], {}).get(key) if key[:2] in skc.RES else None
new = item_prices.to_json(live) if live is not None else row
if new != row:
hit = True
changed.setdefault(
key,
{"키": key, "이름": new.get("이름"), "전": _shown(row), "후": _shown(new)},
)
fresh.append(new)
out[name] = {**part, slot: fresh}
if hit:
news[str(folder)] = out
return news, list(changed.values())
def write(news: dict[str, dict]) -> int:
"""새 `단가.json` 을 사본 폴더에 씀 — 쓴 사본 수."""
for folder, data in news.items():
atomic_write_json(Path(folder) / PRICE_FILE, data)
return len(news)
@@ -38,7 +38,6 @@ from B09_Estimation import B09_Estimation_Labor_Rule as rule
from B09_Estimation import B09_Estimation_Sangeun as sg
from B09_Estimation import B09_Estimation_Sangeun_Text as st
from B09_Estimation.B09_Estimation_Bill_Items import LAYER_WORD
from B09_Estimation.B09_Estimation_Copy_Prices import bundle
from B09_Estimation.B09_Estimation_Linked import sk_answer
from B09_Estimation.B09_Estimation_Supply import sk_money, supply_mark
from M02_MasterTemplete import M02_Item_Prices as item_prices
@@ -53,7 +52,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import (
linked_snapshots,
structures_dir,
)
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json
mf = item_prices.mf
@@ -186,7 +185,7 @@ class Builder:
M02 SK 셈과 같은 문서) · 줄 = 문서 답 금액 줄(이름 · 단위 · 수량 · 종류 = 답 ·
자원 키 · 하위 부름 = 셈 기록) — 노임 · 자재 · 기계경비(중기) · 하위 단가산출(산근) ·
% 줄 · 그 밖 = 줄 단가 `fixed` · 합밖 = `out` · cover = `P:` + SK 이름표(SK 를 고쳐
[재생성] 해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) ·
다시 지정해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) ·
수식 사본 없는 SK(형제 · 옛 칸) = None(부르는 줄이 까닭 · M02 처럼 못 셈)."""
got = sk_answer(doc)
if got is None or got.stopped or "결과" in got.ans:
@@ -429,7 +428,7 @@ class Builder:
labor = read_json(folder / LABOR_FILE)
if not isinstance(labor, dict):
return None
prices = bundle(folder) # 841-1 미리 보기 덮개
prices = read_json(folder / PRICE_FILE) or {}
values = read_json(folder / VALUES_FILE) or {}
picks = read_json(folder / PICKS_FILE) or {}
docs = dr.docs_of(folder) # 사본 수식 문서(855-F B9-3)
@@ -489,7 +488,7 @@ class Builder:
if not isinstance(doc, dict):
return None
whole = self.shelf.put_whole(
bundle(folder), dr.docs_of(folder)
(read_json(folder / PRICE_FILE) or {}), dr.docs_of(folder)
) # 사본 수식 문서(B9-3 · B9-6)
if manifest["종류"] == "sangeun": # 내 자료집 단가산출(719-2)
return self.sangeun(whole, ref, doc, copies, 1)
+3 -4
View File
@@ -17,7 +17,6 @@ from pathlib import Path
from typing import Any
from B09_Estimation import B09_Estimation_Doc_Run as dr
from B09_Estimation.B09_Estimation_Copy_Prices import bundle
from M02_MasterTemplete import M02_Item_Prices as item_prices
from M02_MasterTemplete import M02_Labor_Fixed as fixed
from M02_MasterTemplete.M02_Item_Snapshot import (
@@ -26,7 +25,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import (
linked_snapshots,
structures_dir,
)
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json
#: 원가 단가 목록에 오르는 자원 표
RESOURCE_TABLES = ("LB", "EQ", "MT", "MO")
@@ -38,7 +37,7 @@ def used_keys(folder: Path) -> list[str]:
if not isinstance(labor, dict):
return []
docs = dr.docs_of(folder) # 사본 수식 문서 — 셈 기록의 자원 키(855-F B9-3)
snapshot = dr.load(bundle(folder), docs)
snapshot = dr.load((read_json(folder / PRICE_FILE) or {}), docs)
values = read_json(folder / VALUES_FILE) or {}
picks = read_json(folder / PICKS_FILE) or {}
seen: list[str] = []
@@ -113,7 +112,7 @@ def frozen_rows(project_root: str | Path) -> dict[str, dict[str, Any]]:
out: dict[str, dict[str, Any]] = {}
for folder in _folders(project_root):
got = bundle(folder) # 841-1 미리 보기 덮개
got = read_json(folder / PRICE_FILE) or {}
for name, data in got.items():
if name.startswith("_") or not isinstance(data, dict):
continue
+7 -54
View File
@@ -1,12 +1,11 @@
"""B09 자재 단가 책 · 수요 모음(PLAN 144 · 841-1) — 서버 단독(M01 을 읽는 곳은 여기 하나).
841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책에서 걷음(B09 금액 = 사본을 M02 엔진으로 셈한 값 ·
`B09_Estimation_Copy_Prices`).
841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책에서 걷음(B09 금액 = 사본을 M02 엔진으로 셈한 값).
책에 남는 것 = 자재단가대비표(4 자재대 · 관급자재대 단가 고르기) 자재 줄.
자재 단가 = 프로젝트 한 벌 — 원가산출에서 한 번 굳힘(`price_book.json`) ·
값 = 사본 단가 기준 시점(795-4 · 구조물 지정 때 `단가.json` 자원 줄 · 없는 자원만 지금 M01 +
`now_keys`) · [단가 갱신] 때만 새로.
`now_keys`) · 다시 굳히지 않음(859-2 프로젝트 안 단가 갱신 없음).
줄 = 수요 따라(사용자 승인 ① · 10-9) — 엑셀 목록을 기본으로 깔지 않음:
연결된 사본이 부른 자재 키(`B09_Estimation_Linked` — 143-1 「연결된 사본」 원천 · 없으면 빈 표)
+ B08 총괄자재수량집계표 자재(M01 짝 없음 → 출처 빈칸 · 적용 단가는 사용자 입력)
@@ -16,7 +15,6 @@
from __future__ import annotations
import json
from decimal import Decimal
from typing import Any
@@ -103,58 +101,13 @@ def _convert(master, key: str) -> dict[str, Any]:
return material_input(_row(master, key))
def refresh_book(
keys: list[str], book: dict[str, Any] | None = None, frozen: dict[str, dict] | None = None
) -> dict[str, Any]:
"""[단가 갱신] — 수요 키 전부를 지금 M01 값으로 새로 굳힘 ·
M01 원본이 지워진 키(296) = 옛 책 줄 그대로(지우지도 바꾸지도 않음) ·
`frozen` = 첫 굳힘(795-4) — 사본 단가 기준 시점 값 · 없는 자원 = 지금 값(`now_keys`)."""
def make_book(keys: list[str], frozen: dict[str, dict] | None = None) -> dict[str, Any]:
"""첫 굳힘 — 수요 키 전부 · `frozen` = 사본 단가 기준 시점 값(795-4) · 없는 자원 = 지금 값
(`now_keys`) · None = 지금 M01."""
master = basis(frozen)
want = demand(master, keys)
rows = {key: _convert(master, key) for key in want["materials"]}
old = (book or {}).get("rows") or {}
rows.update({key: old[key] for key in want["missing"] if key in old})
return {
"made": utc_now_text(),
"rows": rows,
"labor_edition": labor_editions(keys), # 703-3 미리 보기 「노임 판 전 → 후」
"now_keys": now_keys(frozen, list(rows)),
}
def labor_editions(keys: list[str]) -> dict[str, str]:
"""노임 판(703-3) — 수요 노무 줄 구분(건설업 · 산림 …)마다 M01 `인력.json` 그 구분 `판`."""
files, master = m01.loaded()
groups = (files.get("인력.json") or {}).get("구분") or {}
out: dict[str, str] = {}
for key in [k for k in keys if k.startswith("LB") and _row(master, k)]:
kind = str((_row(master, key) or {}).get("구분") or "")
if (groups.get(kind) or {}).get("판"):
out[kind] = str(groups[kind]["판"])
return out
def book_diff(old: dict[str, Any] | None, new: dict[str, Any]) -> dict[str, int | bool]:
"""두 책 견줌(저장 꼴 JSON) — 새 줄 · 바뀐 줄 수(203-1 · 703-3 · 자재 줄만)."""
new = json.loads(json.dumps(new, ensure_ascii=False))
rows = (old or {}).get("rows") or {}
return {
"new": sum(key not in rows for key in new["rows"]),
"changed": sum(key in rows and rows[key] != row for key, row in new["rows"].items()),
}
def book_stale(book: dict[str, Any] | None, keys: list[str]) -> str | None:
"""203-1 [업데이트] 배지 — 지금 M01 로 새로 굳힌 책(`refresh_book`)과 견줌 · 다른 것 한 줄(같으면 None)."""
if book is None:
return "단가 아직 안 굳힘"
# 저장 꼴(JSON)로 견줌 · M01 원본이 지워진 줄 = 옛 줄 그대로(낡음 까닭에서 빠짐 · 296)
diff = book_diff(book, refresh_book(keys, book))
parts = [
f"새 단가 줄 {diff['new']}" if diff["new"] else "",
f"M01 에서 바뀐 단가 {diff['changed']}" if diff["changed"] else "",
]
return " · ".join(p for p in parts if p) or None
return {"made": utc_now_text(), "rows": rows, "now_keys": now_keys(frozen, list(rows))}
def extend_book(
@@ -163,7 +116,7 @@ def extend_book(
"""[저장] — 책에 없는 새 줄만 더함(있는 줄 · 계수 · 환율은 안 바꿈) · 책이 없으면 새로 굳힘 ·
새 줄 값 = 사본 단가 기준 시점(795-4 · `frozen`) · 없는 자원만 지금 M01(`now_keys`)."""
if book is None:
return refresh_book(keys, None, frozen or {})
return make_book(keys, frozen or {})
master = basis(frozen)
want = demand(master, keys)
rows = dict(book["rows"])
-173
View File
@@ -1,173 +0,0 @@
"""B09 [단가 갱신] · [재생성](PLAN 795-4 · 옛 [업데이트] 703-3) — 사본 로직은 만든 때 그대로 ·
[단가 갱신](기본 · 841-1) = 프로젝트 사본 자원 단가 줄(`B09_Estimation_Copy_Prices`) + 자재 단가 책만
지금 M01 값 · 미리 보기 `price_preview` = 바뀐 자원 · 총괄 전 → 후 ·
[재생성](사용자가 따로) = 아래 옛 [업데이트] — 단가 책 다시 굳힘 + 원본이 바뀐 구조물 사본 [재적용].
미리 보기(`preview`) = 바뀌는 단가 줄(새 줄 + 바뀐 줄 · 지금 수요) · 다시 가져올 구조물 사본
(연결된 것 중 원본이 바뀐 것만 · 원본 없음 = 그대로) · 지킬 고친 칸(덮개 칸 수 · 702-4 —
재적용 · 새 판 뒤에도 남음) · 노임 판(굳힌 판 → 지금 M01 판 · 옛 책 = 굳힌 날)
적용(`reapply_changed` → 부르는 쪽이 수요 다시 → `prices.refresh_book`) — 사본 먼저(수요가 바뀜) ·
덮개(사용자 값)는 안 건드림 · 사본 하나가 막혀도 나머지는 함(막힌 것 = 알림).
M02 단가산출(SK · 719-2) — 구조물 · 서고 사본의 SK 수식 사본을 원본 층에서 다시 굳힘(같은 이름표 ·
같은 cover → B09 덮개 · 입력값 · 고른 자재 그대로 · 855-F B9-5) ·
서고 사본도 원본판이 다르면 다시 ·
미리 보기 `단가산출` = 바뀌는 SK 줄 [{사본, 이름, 키, 판(새 · 바뀜 · 빠짐)}].
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from B09_Estimation import B09_Estimation_Bill_Library as library
from B09_Estimation import B09_Estimation_Prices as prices
from B09_Estimation.B09_Estimation_Calc_Labor import COPY
from M02_MasterTemplete import M02_Item_Copy as item_copy
from M02_MasterTemplete import M02_Item_Sangeun as item_sk
from M02_MasterTemplete.M02_Item_Snapshot import MANIFEST_NAME, linked_snapshots, structures_dir
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, build_source, read_json
REGEN = "재생성" # POST …/estimation/prices · preview 몸 `job`(795-4)
def _value(row: dict[str, Any] | None) -> Any:
return None if row is None else row.get("price", row.get("prices"))
def price_preview(
old: dict[str, Any] | None,
new: dict[str, Any],
before: dict,
after: dict,
cells: int,
copies: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""[단가 갱신] 미리 보기(795-4 · 841-1) — {할일, 바뀐자원 [{키, 이름, 전, 후}](사본 자원 줄 +
자재 단가 책), 전, 후(총괄 grand · 빈 줄 있으면 None), 대가 {전, 후}(일위대가 블록 합), 고친칸,
노임판} · 사본(로직)은 안 바뀜."""
was = json.loads(json.dumps((old or {}).get("rows") or {}, ensure_ascii=False))
now = json.loads(json.dumps(new["rows"], ensure_ascii=False))
rows = [
{"키": key, "이름": row.get("name") or "", "전": _value(was.get(key)), "후": _value(row)}
for key, row in now.items()
if was.get(key) != row
]
def grand(sheets: dict) -> Any:
return (((sheets.get("total") or {}).get("subtotals")) or {}).get("grand")
def daega(sheets: dict) -> float:
return sum(float(b.get("sum") or 0) for b in sheets.get("daega_blocks") or [])
seen = {r["키"] for r in copies or []}
return {
"할일": "단가갱신",
"바뀐자원": [*(copies or []), *(r for r in rows if r["키"] not in seen)],
"전": grand(before),
"후": grand(after),
"대가": {"전": daega(before), "후": daega(after)},
"고친칸": cells,
"노임판": {
"전": edition_text((old or {}).get("labor_edition")),
"후": edition_text(new.get("labor_edition")),
},
}
def changed_copies(root: str | Path) -> list[dict[str, Any]]:
"""연결된 구조물 사본 중 원본(층 · 마스터)이 바뀐 것 `[{폴더, 이름}]`."""
linked = {one["폴더"] for one in linked_snapshots(root).values()}
return [
{"폴더": it["폴더"], "이름": it["이름"] or it["폴더"]}
for it in item_copy.list_items(root)
if it["폴더"] in linked and it["마스터바뀜"]
]
def _sks(labor: Any) -> dict[str, dict]:
copies = (labor or {}).get("참조사본") or {}
return {rid: doc for rid, doc in copies.items() if item_sk.is_sangeun(doc)}
def sk_lines(old: Any, new: Any, where: str) -> list[dict[str, str]]:
"""사본 하나 전후 일위대가.json → 바뀌는 SK 줄(SK 문서 · 수식 사본이 다름)."""
was, now = _sks(old), _sks(new)
out = []
for rid in sorted(set(was) | set(now)):
a, b = was.get(rid) or {}, now.get(rid) or {}
if a == b:
continue
mark = "새" if not a else "빠짐" if not b else "바뀜"
out.append({"사본": where, "이름": (b or a).get("이름") or "", "키": rid.rsplit("|")[-1],
"판": mark}) # fmt: skip
return out
def sk_changes(root: str | Path, copies: list[dict], libs: list[tuple]) -> list[dict[str, str]]:
"""다시 가져올 구조물 사본(`changed_copies`) · 서고 사본(`library.changed`)의 바뀌는 SK 줄."""
out = []
for one in copies:
folder = structures_dir(root) / one["폴더"]
try:
fresh = build_source((read_json(folder / MANIFEST_NAME) or {})["원본"])
except (LookupError, ValueError, KeyError):
continue
out += sk_lines(read_json(folder / LABOR_FILE), fresh.get(LABOR_FILE), one["이름"])
for folder, manifest, files, origin in libs:
name = str(origin.get("name") or folder.name)
out += sk_lines(read_json(folder / LABOR_FILE), files.get(LABOR_FILE), name)
return out
def cover_cells(cover: dict[str, Any] | None) -> int:
"""고친 칸 수 — 덮개 칸(품 · 수량 · 단가) · 복사본 표지 뺌."""
return sum(
len(cell) for lines in (cover or {}).values() for cid, cell in lines.items() if cid != COPY
)
def edition_text(editions: dict[str, str] | None) -> str:
return " · ".join(f"{kind} {day[:7]}" for kind, day in sorted((editions or {}).items()))
def preview(
root: str | Path, book: dict[str, Any] | None, keys: list[str], cover: dict | None
) -> dict[str, Any]:
diff = prices.book_diff(book, prices.refresh_book(keys, book))
copies, libs = changed_copies(root), library.changed(root)
lib_names = [{"폴더": f.name, "이름": str(o.get("name") or f.name)} for f, _m, _f, o in libs]
before = (book or {}).get("labor_edition")
made = str((book or {}).get("made") or "")[:10]
return {
"단가줄": diff["new"] + diff["changed"],
"새줄": diff["new"],
"바뀐줄": diff["changed"],
"사본": copies + lib_names,
"단가산출": sk_changes(root, copies, libs),
"고친칸": cover_cells(cover),
"노임판": {
"전": edition_text(before) if before else (f"굳힌 날 {made}" if made else "안 굳힘"),
"후": edition_text(prices.labor_editions(keys)),
},
}
def reapply_changed(root: str | Path, who: dict[str, Any] | None = None) -> dict[str, list]:
"""원본이 바뀐 연결 사본 재적용 · 서고 사본 다시 굳힘 —
`{다시: [이름], 막힘: [이름 — 까닭]}`."""
done, stuck = [], []
for one in library.changed(root):
name = str(one[3].get("name") or one[0].name)
try:
library.refresh_copy(root, one)
done.append(name)
except (LookupError, ValueError, KeyError, OSError) as error:
stuck.append(f"{name} — {error}")
for one in changed_copies(root):
try:
item_copy.reapply(root, one["폴더"], who)
done.append(one["이름"])
except (LookupError, ValueError, KeyError, OSError) as error:
stuck.append(f"{one['이름']} — {error}")
return {"다시": done, "막힘": stuck}
+3 -80
View File
@@ -10,14 +10,6 @@
[초기화](요구 298-2 C1 · C3 · C4 · C5 · 301 · 본문 없음) — 사용자 값 전부(내역 · 자재 ·
원가 · 공기) · 단가 책 · `estimation` 설정 구획 지움 · 서고 사본 정리 · 견적서 파일 남김 →
답 = GET 꼴(기준 = 지금 B08 저장본 + 지금 M01 단가) · 단계 = [저장]과 같음
POST /api/projects/{id}/estimation/prices {user?, job?}
[단가 갱신](795-4 · 기본) — 수요 단가 전부를 지금 M01 값으로 새로 굳힘 · 사본(로직) 그대로 ·
job 「재생성」 = 원본이 바뀐 구조물 사본 재적용(703-3 · `B09_Estimation_Refresh`) 먼저 ·
user = 화면 캐시(296 · 지운 줄 · 그 사본은 수요에서 뺌 · 저장은 안 함) ·
M01 원본이 지워진 줄 = 굳힌 값 그대로 · 덮개 그대로 · 답 notes 첫 줄 = 바뀐 수
POST /api/projects/{id}/estimation/prices/preview {user?, job?}
미리 보기(쓰지 않음) — 단가 갱신 = 바뀐 자원 · 총괄 금액 전 → 후(795-4) ·
재생성 = 바뀌는 단가 줄 · 다시 가져올 사본 · 지킬 고친 칸 · 노임 판(703-3)
POST /api/projects/{id}/estimation/calc {user}
조작 중 서버 셈(702-3 · 단가연결 즉시 금액) — 화면 캐시로 GET 꼴 셈 · 저장 안 함
POST /api/projects/{id}/estimation/logic-preview {code, given, rate, picks}
@@ -73,13 +65,11 @@ from B08_Quantity.B08_Quantity_Router_Material import once as material_once
from B08_Quantity.B08_Quantity_Router_Milestone import read_data as read_milestone
from B08_Quantity.B08_Quantity_Router_Milestone import site_info
from B09_Estimation import B09_Estimation_Bill_Library as library
from B09_Estimation import B09_Estimation_Copy_Prices as copy_prices
from B09_Estimation import B09_Estimation_Daega_Paste as daega_paste
from B09_Estimation import B09_Estimation_Daega_Personal as personal
from B09_Estimation import B09_Estimation_Linked as linked
from B09_Estimation import B09_Estimation_Past as past
from B09_Estimation import B09_Estimation_Prices as prices
from B09_Estimation import B09_Estimation_Refresh as refresh
from B09_Estimation import B09_Estimation_Sangeun as sangeun
from B09_Estimation import B09_Estimation_Sangeun_Cover as sg_cover
from B09_Estimation import B09_Estimation_Store as store
@@ -246,12 +236,10 @@ async def payload(
draft: dict[str, Any] | None = None,
reuse_b08: bool = False,
keys: list[str] | None = None,
book: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""셈 답 한 벌 — keys = 방금 센 단가 수요(같은 저장 값 · [저장]) · 마스터 자국은 한 번만 ·
book = 안 쓴 단가 책(795-4 미리 보기 · 없으면 저장본)."""
"""셈 답 한 벌 — keys = 방금 센 단가 수요(같은 저장 값 · [저장]) · 마스터 자국은 한 번만."""
with m01_cache.steady():
return await _payload(project_id, root, draft, reuse_b08, keys, book)
return await _payload(project_id, root, draft, reuse_b08, keys)
async def _payload(
@@ -260,7 +248,6 @@ async def _payload(
draft: dict[str, Any] | None,
reuse_b08: bool,
keys: list[str] | None,
book: dict[str, Any] | None = None,
) -> dict[str, Any]:
notes: list[str] = []
b08 = await _b08_for(project_id, notes, reuse_b08)
@@ -269,7 +256,7 @@ async def _payload(
notes.append(
"연결된 구조물 조합 사본 없음 — 노무 · 경비 · 중기 단가 줄은 사본이 연결되면 생김"
)
book = book or await asyncio.to_thread(store.read_book, root)
book = await asyncio.to_thread(store.read_book, root)
frozen = await asyncio.to_thread(linked.frozen_rows, root) # 795-4 사본 단가 기준 시점
inputs = await asyncio.to_thread(prices.build_inputs, book, keys, b08["materials"], frozen)
if late := inputs["now"]:
@@ -292,9 +279,6 @@ async def _payload(
return {
"inputs": inputs,
"user": user,
"book": {"made": book.get("made")} if book else None,
# 203-1 [업데이트] 배지 까닭(지금 M01 과 다른 것 한 줄 · 같으면 None)
"stale": await asyncio.to_thread(prices.book_stale, book, keys),
"sheets": sheets,
"rate_candidates": rate_candidates(),
"rate_table": rate_table(),
@@ -365,67 +349,6 @@ async def estimation_reset(project_id: UUID) -> dict[str, Any]:
return await payload(project_id, root)
@router.post("/{project_id}/estimation/prices")
async def refresh_prices(
project_id: UUID,
body: dict[str, Any] | None = Body(None),
session: dict[str, Any] = Depends(verify_session),
) -> dict[str, Any]:
"""[단가 갱신](795-4 · 841-1) — 프로젝트 사본 자원 단가 줄 + 자재 단가 책을 지금 M01 값으로 ·
사본 로직 · 덮개 그대로 · job 「재생성」 = 원본이 바뀐 구조물 사본 재적용(703-3) 먼저."""
root = await _project_root(project_id)
raw = (body or {}).get("user")
draft = store.clean_user(raw) if isinstance(raw, dict) else None # 296 화면 캐시(저장 안 함)
regen = (body or {}).get("job") == refresh.REGEN
again = {"다시": [], "막힘": []}
if regen:
again = await asyncio.to_thread(refresh.reapply_changed, root, importer(session))
news, changed = await asyncio.to_thread(copy_prices.refreshed, root)
await asyncio.to_thread(copy_prices.write, news)
keys = await _demand(root, draft)
old = await asyncio.to_thread(store.read_book, root)
book = await asyncio.to_thread(prices.refresh_book, keys, old)
await asyncio.to_thread(store.write_book, root, book)
out = await payload(project_id, root, draft)
diff = prices.book_diff(old, book)
kept = draft or out.get("user") or {}
cells = refresh.cover_cells(kept.get("daega_cover")) + refresh.cover_cells(kept.get("sg_cover"))
head = f"재생성 — 구조물 사본 {len(again['다시'])} 다시 가져옴 · " if regen else "단가 갱신 — "
out["notes"] = [
f"{head}사본 {len(news)} · 자원 {len(changed)} · 자재 단가 줄 "
f"{diff['new'] + diff['changed']} 바뀜 · 고친 칸 {cells} 그대로",
*(f"재적용 못 함 {why}" for why in again["막힘"]),
*(out.get("notes") or []),
]
return out
@router.post("/{project_id}/estimation/prices/preview")
async def refresh_preview(
project_id: UUID, body: dict[str, Any] | None = Body(None)
) -> dict[str, Any]:
"""미리 보기 — 단가 갱신(795-4) = 바뀐 자원 · 총괄 금액 전 → 후 ·
재생성(703-3) = 바뀌는 단가 줄 · 다시 가져올 사본 · 지킬 고친 칸 · 노임 판."""
root = await _project_root(project_id)
raw = (body or {}).get("user")
draft = store.clean_user(raw) if isinstance(raw, dict) else None
keys = await _demand(root, draft)
book = await asyncio.to_thread(store.read_book, root)
user = draft if draft is not None else await asyncio.to_thread(store.read_user, root)
if (body or {}).get("job") == refresh.REGEN:
return await asyncio.to_thread(refresh.preview, root, book, keys, user.get("daega_cover"))
new = await asyncio.to_thread(prices.refresh_book, keys, book)
news, changed = await asyncio.to_thread(copy_prices.refreshed, root)
before = await payload(project_id, root, draft, True, keys)
token = copy_prices.OVER.set(news) # 841-1 사본 새 단가 = 덮개로만(파일 안 씀)
try:
after = await payload(project_id, root, draft, True, keys, new)
finally:
copy_prices.OVER.reset(token)
cells = refresh.cover_cells(user.get("daega_cover")) + refresh.cover_cells(user.get("sg_cover"))
return refresh.price_preview(book, new, before["sheets"], after["sheets"], cells, changed)
@router.post("/{project_id}/estimation/calc")
async def calc_estimation(project_id: UUID, body: dict[str, Any] = Body(...)) -> dict[str, Any]:
"""702-3 조작 중 서버 셈 — 화면 캐시(user)로 GET 꼴 셈 · 저장 안 함 · 단가 = 굳힌 책
+3 -4
View File
@@ -49,7 +49,6 @@ from B09_Estimation import B09_Estimation_Sangeun_Sum as ss
from B09_Estimation import B09_Estimation_Sangeun_Text as st
from B09_Estimation import B09_Estimation_Sheet as sheet
from B09_Estimation.B09_Estimation_Calc_Base import SUPPLY, gap, num, rounddown, total
from B09_Estimation.B09_Estimation_Copy_Prices import bundle
from B09_Estimation.B09_Estimation_Store import ref_rows
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
from M02_MasterTemplete import M02_Item_Prices as item_prices
@@ -60,7 +59,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import (
linked_snapshots,
structures_dir,
)
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json
PARTS = ("labor", "material", "expense")
@@ -114,7 +113,7 @@ def rows_of(folder: Path, whole: Any = None, docs: dict | None = None) -> list[d
return []
docs = dr.docs_of(folder) if docs is None else docs
if whole is None:
whole = dr.load(bundle(folder), docs)
whole = dr.load((read_json(folder / PRICE_FILE) or {}), docs)
values = read_json(folder / VALUES_FILE) or {}
picks = read_json(folder / PICKS_FILE) or {}
copies = labor.get("참조사본") or {}
@@ -557,7 +556,7 @@ def collect(
solver = Solver(supply)
for owner, folder in entries:
docs = dr.docs_of(folder) # 사본 수식 문서(855-F B9-3)
whole = solver.shelf.put_whole(bundle(folder), docs)
whole = solver.shelf.put_whole((read_json(folder / PRICE_FILE) or {}), docs)
for src in rows_of(folder, whole, docs):
solver.add(whole, src, owner)
hand_keys: dict[str, str] = {}
+36 -12
View File
@@ -41,11 +41,14 @@ def _won(v: Any) -> str:
return GAP if v is None else f"{v:,.0f}"
def _word(whole: Any, name: str, value: Any) -> str:
"""값 글 — 수 = 화면 수 꼴 · 기계 · 직종 원문번호 = 「이름 규격」(157-3 · 85-1 도우미)."""
def _word(whole: Any, name: str, value: Any, answer: Any = None, key: str = "") -> str:
"""값 글 — 수 = 화면 수 꼴(859-3 보이는 자리 · 기호 `key`) ·
기계 · 직종 원문번호 = 「이름 규격」(157-3 · 85-1 도우미)."""
if isinstance(value, str):
return labor_inputs._labels(whole, {"이름": name, "고르기": [value]}).get(value, value)
return mdt.eq_text(value) if _dec(value) is not None else str(value)
if _dec(value) is None:
return str(value)
return mdt.eq_text(value) if answer is None else _show(answer, key, value)
# ── 머리(입력 · 공식) ────────────────────────────────────────────────
@@ -90,7 +93,8 @@ class _Head:
return "값 없음"
if isinstance(v, dict):
return " · ".join(f"{c} {mdt.eq_text(v.get(c))}" for c in mdt.COSTS)
return " ".join(x for x in (_word(self.whole, self.names.get(i, i), v), self.unit(i)) if x)
word = _word(self.whole, self.names.get(i, i), v, self.answer, i)
return " ".join(x for x in (word, self.unit(i)) if x)
def formula(self, i: str, text: str) -> str:
"""「이름 = 이름식 = 값식 = 값 단위」 — 같은 글이 이어지면 한 번만."""
@@ -104,7 +108,9 @@ class _Head:
valued = md.text_of(_swap(node, self._num))
parts += [named, valued]
v = self.values.get(i)
bare = mdt.eq_text(v) if _dec(v) is not None else f"'{v}'" if isinstance(v, str) else None
bare = f"'{v}'" if isinstance(v, str) else None
if _dec(v) is not None:
bare = _show(self.answer, i, v)
out = [parts[0]]
for p in parts[1:]: # 같은 글 · 값 그대로인 식 = 한 번만(화면 공식 줄)
if p and p != out[-1] and p != bare:
@@ -115,7 +121,7 @@ class _Head:
def _num(self, name: str):
v = self.values.get(name)
d = _dec(v)
return ("var", mdt.eq_text(d)) if d is not None else None
return ("var", _show(self.answer, name, v)) if d is not None else None
def lines(self, times: Decimal) -> list[str]:
doc = self.doc
@@ -180,9 +186,14 @@ def _qty(answer: Any, n: int, units: dict, times: Decimal, rate: Decimal | None)
raw = (answer.ans.get("줄") or [{}] * (n + 1))[n].get("수량")
node = _decide(mdt.node_of(((answer.doc.get("금액") or [])[n]).get("수량")), answer)
values = answer.ans.get("값") or {}
shown = mdt.eq_text(raw)
line = (answer.doc.get("금액") or [])[n]
look = _look(answer)
shown = mdt.shown(answer.doc, mdt.node_of(line.get("수량")), raw, look, look.run.links)
if node is not None and not mdt.is_atom(node):
put = lambda s: ("var", mdt.eq_text(values[s])) if _dec(values.get(s)) is not None else None # noqa: E731
def put(s: str):
return ("var", _show(answer, s, values[s])) if _dec(values.get(s)) is not None else None
shown = f"({md.text_of(_swap(_bare(node), put))})"
text = mdt._u(shown, units["qty"])
if times != 1:
@@ -192,13 +203,25 @@ def _qty(answer: Any, n: int, units: dict, times: Decimal, rate: Decimal | None)
return text
def _look(answer: Any) -> Any:
"""셈 답 값 읽개(`master_doc_text._Look`) — 답마다 한 번."""
look = getattr(answer, "_look", None)
if look is None:
look = answer._look = mdt._Look(answer.doc, answer.ans, ml.Links(answer.whole, answer.docs))
return look
def _show(answer: Any, name: str, v: Any) -> str:
"""기호 값 글 — 859-3 보이는 자리 규칙(화면 줄 쌓기와 같음 · `master_doc_text.shown`)."""
look = _look(answer)
return mdt.shown(answer.doc, ("var", name), v, look, look.run.links)
def _decide(node: Any, answer: Any) -> Any:
"""만약 = 걸린 갈래만(화면 `decide` · 조건 = 셈 답 값 · `master_doc_text._Look`)."""
if node is None:
return None
look = getattr(answer, "_look", None)
if look is None:
look = answer._look = mdt._Look(answer.doc, answer.ans, ml.Links(answer.whole, answer.docs))
look = _look(answer)
def walk(n: Any) -> Any:
if not isinstance(n, tuple):
@@ -259,7 +282,8 @@ def _extra_text(ln: dict) -> str:
value, money = ln["price"][part], ln[part]
if ln.get("unit") == "%" and ln.get("qty"):
base = Decimal(str(value)) * 100 / Decimal(str(ln["qty"]))
return f"{head}{mdt.eq_text(base)} × {mdt.eq_text(ln['qty'])} % = {_amount(money)}"
base_text = mdt.mdd.show(base, "식", "", "원") # 859-3 원 단위 중간 값
return f"{head}{base_text} × {mdt.eq_text(ln['qty'])} % = {_amount(money)}"
return f"{head}{mdt.eq_text(value)} = {_amount(money)}"
+1 -1
View File
@@ -2,7 +2,7 @@
price_book.json 굳힌 자재 단가 한 벌 {"made": 시각, "rows": {키: 입력 줄}}(841-1 자재만 ·
옛 책의 노무 · 기계 줄 · 계수 · 환율은 안 읽음)
— [단가 갱신] 때만 M01 로 새로 ·
— 처음 굳힌 뒤 다시 안 굳힘(859-2) ·
[저장] 때 책에 없는 새 줄만 더함(있는 줄 안 바꿈)
user_values.json 사용자 값 {"materials": {자재 키: {applied?, supply?, quote?, quote_page?,
pick?}}, "estimate": {…},
+2 -133
View File
@@ -1,27 +1,15 @@
/* =============================================================================
* B09_Estimation_UI_Check.ts
* B09 좌측 「데이터 점검」 묶음(PLAN 203-1) — [단가 갱신] · 연결 점검(옛 「연결 점검」 탭 내용).
* B09 좌측 「내역 점검」 묶음(PLAN 203-1) — 연결 점검(옛 「연결 점검」 탭 내용 · 859-2 [단가 갱신] 걷음).
*
* [단가 갱신](795-4 · 옛 [업데이트] · 841-1) = 프로젝트 사본 자원 단가 · 자재 단가만 지금 M01 값 · 서버가 낡았다고 보면(`payload.stale` 까닭 한 줄)
* 단추에 점 배지(`is-pending`) · 굳힌 시각 · 까닭 = 공용 호버
* 미리 보기 고리 = 누름을 먼저 잡아 POST …/estimation/prices/preview(화면 캐시) →
* 「총괄 금액 전 → 후 · 바뀐 자원」 창 → [적용] = 원래 단추 일(단가만 · 사본 · 덮개 그대로) ·
* 창의 [재생성] = 재생성 미리 보기(703-3 · 다시 가져올 사본 · 고친 칸 · 노임 판) → [적용] =
* `job: 재생성`(사본 재적용 + 단가) · 닫기 = 안 함
* 연결 점검 = 「빈 줄 n」(설계내역서 금액 모르는 줄 · 안내 · 집계표와 같은 수 · 701-2) 목록 +
* 그 밖 확인 목록(일위대가 · 단가산출 · 재료 등 · 탭 · 키마다 하나)(누르면 그 탭 그 줄로 · 까닭 = 공용 호버) + 서버 알림 · M01 에 없는 키
* ========================================================================== */
import { API_BASE_URL } from "@config/config_frontend";
import { createButton, showToast } from "@ui/ui_template_elements";
import { attachHoverInfo } from "@ui/ui_template_hover_info";
import { openModal } from "@ui/ui_template_modal";
import { createBadge } from "@ui/ui_template_badge";
import { createText } from "@ui/ui_template_text";
import type { Row } from "./B09_Estimation_Calc_Base";
import { dateTimeText } from "../common_util/common_util_time";
import { readState } from "../A00_Common/b_page_state";
import { currentProjectId } from "../A00_Common/b_project_switch";
import { blankRows, tabName, type Link, type TabId } from "./B09_Estimation_UI_Tabs";
export interface CheckItem {
@@ -63,131 +51,14 @@ export function checkItems(
return { items, others, notes };
}
/** [단가 갱신] 호버 글 — 굳힌 시각 + 낡은 까닭 */
export function refreshTip(payload: Row | null): string {
const made = payload?.book?.made;
const when = made ? `단가 굳힘 ${dateTimeText(String(made))}` : "단가 아직 안 굳힘";
const stale = payload?.stale;
return `${when} · 누르면 미리 보기 → [적용] = 프로젝트 사본 자원 단가 · 자재 단가만 지금 M01 값 · 사본(로직) · 고친 칸 그대로 · 로직까지 새로 = 미리 보기의 [재생성]${stale ? ` · 단가 갱신 가능 — ${stale}` : ""}`;
}
/** [재생성] 미리 보기 글 줄(703-3 옛 [업데이트]) */
export function previewLines(got: Row): string[] {
const copies: Row[] = got.사본 || [];
const sks: Row[] = got.단가산출 || [];
const edition = got.노임판 || {};
return [
`바뀌는 자재 단가 줄 ${got.단가줄 ?? 0}(새 줄 ${got.새줄 ?? 0} · 값 바뀜 ${got.바뀐줄 ?? 0})`,
`다시 가져올 사본 ${copies.length}${copies.length ? ` — ${copies.map((c) => c.이름).join(" · ")}` : ""}`,
...(sks.length
? [`M02 단가산출 바뀜 ${sks.length} — ${sks.map((s) => `${s.이름}(${s.판})`).join(" · ")}`]
: []),
`고친 칸 ${got.고친칸 ?? 0} 지킴(일위대가 덮개 · 새 판 · 재적용 뒤에도 그대로)`,
`노임 판 ${edition.전 || "—"} → ${edition.후 || "—"}`,
];
}
const won = (v: unknown): string => (v == null ? "—" : Number(v).toLocaleString("ko-KR"));
/** 자원 단가 값 — 노임 · 기계 = 수 · 자재 = 출처별 값 */
function priceText(v: unknown): string {
if (v == null) return "새 줄";
if (typeof v !== "object") return won(v);
const got = Object.entries(v as Row).filter(([, x]) => x != null);
return got.length ? got.map(([k, x]) => `${k} ${won(x)}`).join(" / ") : "—";
}
/** [단가 갱신] 미리 보기 글 줄(795-4) — 총괄 금액 전 → 후 · 바뀐 자원 */
export function priceLines(got: Row): string[] {
const rows: Row[] = got.바뀐자원 || [];
const edition = got.노임판 || {};
const shown = 30;
return [
`총괄 금액 ${won(got.전)} → ${won(got.후)} 원 · 대가 합 ${won(got.대가?.전)} → ${won(got.대가?.후)} 원`,
`바뀐 자원 ${rows.length}(사본 자원 단가 · 자재 단가)`,
...rows
.slice(0, shown)
.map((r) => `· ${r.이름 || r.키} ${priceText(r.전)} → ${priceText(r.후)}`),
...(rows.length > shown ? [`… 외 ${rows.length - shown}`] : []),
`고친 칸 ${got.고친칸 ?? 0} · 구조물 사본(로직) 그대로 — 로직까지 새로는 [재생성]`,
`노임 판 ${edition.전 || "—"} → ${edition.후 || "—"}`,
];
}
const REGEN = "재생성";
/** [단가 갱신] 누름 앞 미리 보기 — [적용] 이면 원래 단추 일(`data-b09-job` = 할일) · 닫기 = 안 함 ·
* [재생성] = 재생성 미리 보기 → [적용] = 사본 재적용 + 단가(795-4 · 사용자가 따로 누를 때만) */
function attachPreview(refresh: HTMLElement, payload: () => Row | null): void {
let pass = false;
const open = (job?: string): void => {
const projectId = currentProjectId();
const user = readState<Row>("b09-estimation", projectId) ?? payload()?.user ?? {};
void fetch(`${API_BASE_URL}/projects/${projectId}/estimation/prices/preview`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(job ? { user, job } : { user }),
})
.then(async (response) => {
const got = (await response.json()) as Row;
if (!response.ok) throw new Error(String(got?.detail ?? response.status));
openModal({
title: job ? "재생성 미리 보기" : "단가 갱신 미리 보기",
closeLabel: "닫기",
width: "40rem",
mount: (body, close, head) => {
const apply = createButton({
label: "적용",
variant: "filled",
onClick: () => {
close();
pass = true;
if (job) refresh.dataset.b09Job = job;
refresh.click();
delete refresh.dataset.b09Job;
},
});
apply.dataset.b09RefreshApply = "";
if (!job) {
const regen = createButton({
label: REGEN,
variant: "ghost",
onClick: () => (close(), open(REGEN)),
});
regen.dataset.b09Regen = "";
head.append(regen);
}
head.append(apply);
const lines = job ? previewLines(got) : priceLines(got);
body.append(...lines.map((line) => createText(line)));
},
});
})
.catch((error) => showToast(`미리 보기 못 함 — ${String(error)}`, "error"));
};
refresh.addEventListener(
"click",
(event) => {
if (pass) return void (pass = false);
event.stopImmediatePropagation();
open();
},
true,
);
}
export interface CheckPanel {
/** 묶음 안 연결 점검 자리 */
list: HTMLElement;
draw: (payload: Row, sheets: Row) => void;
}
export function createCheckPanel(refresh: HTMLElement, goto: (link: Link) => void): CheckPanel {
let payload: Row | null = null;
export function createCheckPanel(goto: (link: Link) => void): CheckPanel {
let items: CheckItem[] = [];
attachHoverInfo(refresh, () => refreshTip(payload));
attachPreview(refresh, () => payload);
const box = document.createElement("div");
box.className = "b09-check";
attachHoverInfo(box, (row) => items[Number(row.dataset.i)]?.why, "[data-i]");
@@ -219,8 +90,6 @@ export function createCheckPanel(refresh: HTMLElement, goto: (link: Link) => voi
};
const draw = (next: Row, sheets: Row): void => {
payload = next;
refresh.classList.toggle("is-pending", Boolean(next.stale));
const made = checkItems(sheets, next);
items = [...made.items, ...made.others];
const blank = [
-22
View File
@@ -143,28 +143,6 @@ html.is-bm-route .b09-estimation > .b09-estimation__tabs:first-child {
background: color-mix(in srgb, var(--color-warning) 22%, var(--color-canvas));
}
/* 203-1 좌측 「데이터 점검」 — [업데이트] 필요 = 단추 위 점 배지(B05 [3D 업데이트] 꼴) */
.b09-options .ui-btn.is-pending {
position: relative;
border-color: var(--color-warning);
}
.b09-options .ui-btn.is-pending::after {
content: "";
position: absolute;
top: 4px;
right: 4px;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--color-warning);
}
/* 122 데이터 점검 [업데이트] — 제목 아래 틈 = 카드 왼쪽 여유와 같게(공용 카드 틈 8 + 4) */
.b09-options [data-b09-refresh] {
margin-top: var(--spacing-4);
}
/* 연결 점검 목록 — 이름 · 탭(작게) · 알림 글 */
.b09-check__head,
.b09-check__note {
+7 -27
View File
@@ -7,7 +7,7 @@
* 짝 계산(`…_Calc_*.ts`)으로 바로 다시 셈 · 새 산근(로직 연결) = 뒤에서 서버 셈(702-3 · `…_UI_Live`) ·
* [저장](702-3 · 왼쪽 아래 [초기화] 옆) = PUT → 서버 정본으로 다시 셈 · 저장 안 하고 단계 옮김 · [>] = 물음(저장 · 버림 · 머묾)
* [>] = 물음 → POST …/estimation/complete(단계 6 완료) → `DRAFT.next`(인쇄 미리보기 · 초안) · 실패면 머묾
* [초기화](요구 298-2) = 확인 창 → POST …/estimation/reset(사용자 값 · 단가 책 지움 · 견적서 남김) → 셈 값 · [단가 갱신] = POST …/prices(795-4)
* [초기화](요구 298-2) = 확인 창 → POST …/estimation/reset(사용자 값 · 단가 책 지움 · 견적서 남김) → 셈 값
* 호표 칸 누름 = 그 탭 그 줄로 이동 · 자동 저장 없음
* ========================================================================== */
@@ -338,14 +338,8 @@ export function renderB09Estimation(root: HTMLElement): void {
show(current);
};
// keep = 화면 캐시 그대로(296 [업데이트] — 지운 줄 · 고친 칸을 안 되살림) · 참 = 성공
const run = async (
path: string,
method: string,
done: string,
init?: Row,
keep = false,
): Promise<boolean> => {
// 참 = 성공
const run = async (path: string, method: string, done: string, init?: Row): Promise<boolean> => {
if (!projectId) return false;
showLoadingOverlay();
try {
@@ -353,8 +347,8 @@ export function renderB09Estimation(root: HTMLElement): void {
method,
...(init ? { body: JSON.stringify(init) } : {}),
});
if (!keep) clearState("b09-estimation", projectId);
apply(next, !keep);
clearState("b09-estimation", projectId);
apply(next, true);
showToast(done, "success");
return true;
} catch (error) {
@@ -372,21 +366,7 @@ export function renderB09Estimation(root: HTMLElement): void {
: Promise.resolve(true);
DRAFT.save = saveChanged; // 초안 [인쇄 미리보기] = 저장 뒤 이동(506-3)
DRAFT.blocked = () => (payload ? unfinished(sheets) : null); // 701-3 인쇄 · 확정 = 빈 줄 0
// 795-4 [단가 갱신] = 값만 · 미리 보기 창 [재생성] = `data-b09-job`(B09_Estimation_UI_Check)
const refresh = createButton({
label: "단가 갱신",
variant: "ghost",
onClick: () =>
void run(
"/estimation/prices",
"POST",
"단가를 지금 M01 값으로 새로 굳혔습니다.",
{ user, ...(refresh.dataset.b09Job ? { job: refresh.dataset.b09Job } : {}) },
true,
),
});
refresh.dataset.b09Refresh = "";
const check = createCheckPanel(refresh, (link) => show(link.tab, link.key));
const check = createCheckPanel((link) => show(link.tab, link.key));
// 298-2 [초기화] — 내역 · 단가 · 공기 · 요율 등 사용자 값 · 설정 모두 지움 → B08 수량 셈 값(견적서 파일 남김)
const reset = createButton({
label: L("Common_Btn_Reset"),
@@ -413,7 +393,7 @@ export function renderB09Estimation(root: HTMLElement): void {
save.dataset.b09Save = "";
// 카드 = 좌측 패널 공용 카드(269 · 「구조물 배치」 양식)
const section = createPanelCard("내역 점검", true); // 311 기본 접힘
section.append(refresh, check.list);
section.append(check.list);
// 303-1 · 304-1 하단 고정 줄 — [박스보기|호표보기] · [하이퍼링크|팝업] · 초안 단추 · [?][<][>][초기화]
const actions = createDock([save, reset], () => isGroupTab(current) && show(current));
const left = document.createElement("div");
@@ -63,7 +63,7 @@ export const buildLabor: TabBuild = ({ sheets }) =>
priceList(
sheets.labor || [],
"단가(원/인)",
"대가 · 산근이 쓰는 노임 = 프로젝트 사본(M02) 값 나열 · 새 값은 [단가 갱신]",
"대가 · 산근이 쓰는 노임 = 프로젝트 사본(M02) 값 나열 · 새 값은 구조물 다시 지정",
);
export const buildExpense: TabBuild = () => gone(priceList([], "기준가(천원)", "").columns);
@@ -290,7 +290,7 @@ export const buildMachine: TabBuild = ({ sheets }): TabTable => {
],
rows,
frozen: 2,
hint: "대가 · 산근이 쓰는 기계 시간당 = 프로젝트 사본(M02 단가산출) 값 나열 · 새 값은 [단가 갱신]",
hint: "대가 · 산근이 쓰는 기계 시간당 = 프로젝트 사본(M02 단가산출) 값 나열 · 새 값은 구조물 다시 지정",
};
};
@@ -287,7 +287,7 @@ function blockCard(ctx: TabContext, block: Row, noOf: Record<string, number>): H
? [
edit,
createText(
`품 · 단가 칸을 두 번 눌러 고침 · 색 칸 = ${TAG}(이 공사만 · [단가 갱신] · [재생성] 뒤에도 남음) · 우클릭 [${BACK}으로] · [저장] 때 서버가 다시 셈`,
`품 · 단가 칸을 두 번 눌러 고침 · 색 칸 = ${TAG}(이 공사만 · 구조물 다시 지정 뒤에도 남음) · 우클릭 [${BACK}으로] · [저장] 때 서버가 다시 셈`,
"muted",
),
]
+2 -4
View File
@@ -319,12 +319,10 @@ def logic_new(logic: dict, owner: str = OWNERS[0], source: str = "") -> dict:
def logic_copy(key: str, 이름: str = "", owner: str = OWNERS[0], more: dict | None = None) -> dict:
"""본떠 만들기 = [복사/생성] — 원본 문서를 새 자체 기초로 복제(정본도 본뜸) · 비고 끝에 본뜬 키 ·
"""본떠 만들기 = [복사/생성] — 원본 문서를 새 자체 기초로 복제(원본과 안 이어짐 · 비고 그대로) ·
`more` = 기본정보 창에서 고친 원문번호 · 결과단위 · 출처(빈 글은 원본 그대로)."""
_, doc = doc_store.find(key)
row = doc_store.head_of(doc)
note = " · ".join(x for x in (str(row.get("비고") or ""), f"{key} 를 본뜸") if x)
copy = {**row, "비고": note, **{k: v for k, v in (more or {}).items() if v}}
copy = {**doc_store.head_of(doc), **{k: v for k, v in (more or {}).items() if v}}
if 이름:
copy["이름"] = 이름
return logic_new(copy, owner, key)
+1 -1
View File
@@ -1,7 +1,7 @@
/* =============================================================================
* M01_MasterData_UI_Page.ts
* 마스터 요소 화면 — 좌측 도킹 패널(컨테이너: 인력·재료·기계·소요량·계수·환율·요율·단가산출 로직)
* · 일위대가 조합은 M02 마스터 템플릿(PLAN 27-2b) · 구조물 옵션 정의(716-1 · 화면은 M02 `StructOptions/`)
* · 일위대가 조합은 M02 마스터 템플릿(PLAN 27-2b) · 구조물 옵션 정의(716-1 · 859-5 화면 · 서버 = `StructOptions/`)
* / 우측 요소 표 · 표 목록 · 로직 편집 · 옵션 정의 · 별칭 모아 보기(815-2) ·
* 주소 `?open=로직|옵션|별칭` = 그 칸을 고른 채 열림(716-2)
*
+2 -5
View File
@@ -2,7 +2,7 @@
* M01_MasterData_UI_Side.ts
* 왼쪽 패널 — 공용 접기 컨테이너(`ui-collapsible ui-sidebar-section`)
* 인력 · 재료 · 기계 · 소요량 · 계수 · 환율 · 요율 · 단가산출 로직(일위대가 조합은 M02 · PLAN 27-2b)
* ─ 구분선 ─ 구조물 옵션 정의(716-1 · 화면 코드는 M02 `StructOptions/` 그대로 · 입구만 여기)
* ─ 구분선 ─ 구조물 옵션 정의(716-1 · 화면 코드 = `StructOptions/`(859-5) · 입구만 여기)
* · 별칭 모아 보기(815-2 · 누르면 본 칸에 별칭이 적힌 줄 · 승인 대기 · `M01_MasterData_UI_Alias`)
* 펼치면 하위 목록(거름 · 파일) · 환율/요율은 누르면 바로 표 · 로직은 안에 로직 목록
* ========================================================================== */
@@ -11,10 +11,7 @@ import { createSelectField, el, showToast } from "@ui/ui_template_elements";
import { attachCollapsible } from "@ui/ui_template_collapsible";
import { createDivider } from "@ui/ui_template_divider";
import { currentLanguageIndex, t as L } from "@ui/ui_template_locale";
import {
buildOptionsSection,
type OptionsSectionOptions,
} from "../M02_MasterTemplete/StructOptions/M02_SO_Options";
import { buildOptionsSection, type OptionsSectionOptions } from "./StructOptions/M01_SO_Options";
import { ALIAS_TITLE, buildAliasBoard, type AliasRow } from "./M01_MasterData_UI_Alias";
import { fetchFiles, fetchSubsAll, type FileInfo, type SubInfo } from "./M01_MasterData_Api_Fetch";
import { tx } from "./M01_MasterData_UI_Logic_Text";
@@ -1,10 +1,14 @@
/* =============================================================================
* M02_SO_Api.ts
* 구조물 정의 서버 호출 — 서버 = `M02_SO_Router.py`(마스터 템플릿 `구조물정의.json` 한 벌 · PLAN 48)
* M01_SO_Api.ts
* 구조물 정의 서버 호출 — 서버 = `M01_SO_Router.py`(마스터 템플릿 `구조물정의.json` 한 벌 · PLAN 48)
* ========================================================================== */
import { call } from "../M02_MasterTemplete_Api_Fetch";
import type { StructDef } from "./M02_SO_Def_Model";
import { call as callApi } from "../../common_util/common_util_m02_call";
import type { StructDef } from "./M01_SO_Def_Model";
/** `/api/m01` 아래 길 부름 */
const call = <T>(path: string, init: RequestInit = {}): Promise<T> =>
callApi<T>(path, init, "/m01");
/* --- 구조물 정의(PLAN 48 · 마스터 템플릿 `구조물정의.json` · 판 번호 · 이력) --- */
@@ -21,7 +25,7 @@ export const fetchStructureDef = (): Promise<StructDef> => call("/structure-defi
export const saveStructureDef = (판: number, 정의: StructDef): Promise<StructDef> =>
call("/structure-definition", { method: "PUT", body: JSON.stringify({ 판, 정의 }) });
/** 지난 판 목록(`구조물정의_이력/판_N.json`) */
/** 지난 판 목록(`구조물정의/이력/판_N.json`) */
export const fetchStructureDefHistory = (): Promise<DefVersion[]> =>
call("/structure-definition/history");
@@ -7,7 +7,7 @@
그림이 늘 기본값을 씀 · 앞 판에서 이미 숨긴 칸은 그대로 둠)
- 앞 판이 없으면(옛 판 읽기) 꼴만 검사
- 앞 판과 비교 — 종류 지우기 없음 · 자리꼴 · 정본 · 군 글자 고정 · 선택지 값 고정(이름은 이름 표로)
화면 짝 = `M02_SO_Def_Check.ts`(같은 글)
화면 짝 = `M01_SO_Def_Check.ts`(같은 글)
거울 시험 = `resources/tester/test_322_2_check_mirror.py`.
"""
@@ -19,7 +19,7 @@ from typing import Any
from common_util.common_util_structure_catalog import load_parts, resolve_catalog
BRANCHES = ("횡단도", "카드이름", "형상", "3D")
# 화면 글(322-2 다듬기 · TS `M02_SO_Def_Reflect` 짝) — 자리꼴 · 정본 한국어 · 부품 짧은 이름
# 화면 글(322-2 다듬기 · TS `M01_SO_Def_Reflect` 짝) — 자리꼴 · 정본 한국어 · 부품 짧은 이름
PLACE_KO = {"point": "점", "interval": "구간", "site": "터"}
OWNER_KO = {"pipe_points": "관 지점", "structures": "구조물"}
@@ -1,23 +1,23 @@
/* =============================================================================
* M02_SO_Def.ts
* M01_SO_Def.ts
* 구조물 정의 편집 화면(PLAN 48-2 · 메인 칸) — 탭 셋(322-2): 「한눈 표」(종류마다 반영 한 줄 ·
* `M02_SO_Def_Table`) · 「종류별」(왼쪽 구조물군 · 종류 목록 · 오른쪽 고른 종류 이름 · 반영 · 명세 이름 나무 ·
* 줄마다 보임 · 미리보기) · 「부품」(`M02_SO_Def_Parts`) ·
* 아래 검사(화면 = 서버 짝 `M02_SO_Def_Check`) · [저장](판 +1 · 목록 + enabled 함께 · 시스템 관리자만) ·
* `M01_SO_Def_Table`) · 「종류별」(왼쪽 구조물군 · 종류 목록 · 오른쪽 고른 종류 이름 · 반영 · 명세 이름 나무 ·
* 줄마다 보임 · 미리보기) · 「부품」(`M01_SO_Def_Parts`) ·
* 아래 검사(화면 = 서버 짝 `M01_SO_Def_Check`) · [저장](판 +1 · 목록 + enabled 함께 · 시스템 관리자만) ·
* 지난 판 목록(누르면 그 판을 읽기만으로 봄).
* 다른 역할은 읽기만. 고칠 사본은 저장 전까지 서버에 안 감 · 정본 = `구조물정의.json`(48-1).
* ========================================================================== */
import { createButton, createTag, el, showToast } from "@ui/ui_template_elements";
import { StaleError } from "../M02_MasterTemplete_Api_Fetch";
import { StaleError } from "../../common_util/common_util_m02_call";
import {
fetchStructureDef,
fetchStructureDefAt,
fetchStructureDefHistory,
saveStructureDef,
type DefVersion,
} from "./M02_SO_Api";
import { buildLayoutBlock } from "./M02_SO_Def_Layout";
} from "./M01_SO_Api";
import { buildLayoutBlock } from "./M01_SO_Def_Layout";
import {
baseShown,
clone,
@@ -25,19 +25,19 @@ import {
stepFamily,
stepType,
type StructDef,
} from "./M02_SO_Def_Model";
import { buildOptionsBlock } from "./M02_SO_Def_Options";
import { buildRulesBlock } from "./M02_SO_Def_Rules";
import { buildSpecBlock } from "./M02_SO_Def_Spec";
} from "./M01_SO_Def_Model";
import { buildOptionsBlock } from "./M01_SO_Def_Options";
import { buildRulesBlock } from "./M01_SO_Def_Rules";
import { buildSpecBlock } from "./M01_SO_Def_Spec";
import { specFor } from "../../A00_Common/design/logic/design_structure_pipe";
import { catalogProblems, type CheckDef } from "./M02_SO_Def_Check";
import { buildParts } from "./M02_SO_Def_Parts";
import { differs, setReflect, tidy } from "./M02_SO_Def_Reflect";
import { buildReflectBlock, buildTable } from "./M02_SO_Def_Table";
import { checkBox, pickBox, textBox } from "./M02_SO_Def_Ui";
import { addFromTemplate, templates } from "./M02_SO_Def_Add";
import { buildGroupBlock } from "./M02_SO_Groups";
import { to } from "./M02_SO_Text";
import { catalogProblems, type CheckDef } from "./M01_SO_Def_Check";
import { buildParts } from "./M01_SO_Def_Parts";
import { differs, setReflect, tidy } from "./M01_SO_Def_Reflect";
import { buildReflectBlock, buildTable } from "./M01_SO_Def_Table";
import { checkBox, pickBox, textBox } from "./M01_SO_Def_Ui";
import { addFromTemplate, templates } from "./M01_SO_Def_Add";
import { buildGroupBlock } from "./M01_SO_Groups";
import { to } from "./M01_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createEmpty } from "@ui/ui_template_empty";
import { createTabs } from "@ui/ui_template_tabs";
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Add.ts
* M01_SO_Def_Add.ts
* 종류 더하기(PLAN 323-7) — 본보기(구조물 정본 원본 종류)를 그대로 복사한 새 종류.
*
* 키 자동(`{본보기}_xxxxxx` · 만든 뒤 안 바뀜) · 이름 「{본보기} 2」(겹치면 3 …) · 군 · 자리꼴 · 옵션 · 표시 · 그룹 ·
@@ -8,7 +8,7 @@
* 명세도 본보기 키로 고름(`baseType`). 관 지점 정본 종류는 본보기에서 뺌(관 시설 폼 · 정본 목록이 따로).
* ========================================================================== */
import { clone, newKey, type StructDef } from "./M02_SO_Def_Model";
import { clone, newKey, type StructDef } from "./M01_SO_Def_Model";
/** 본보기로 고를 수 있는 종류 — 구조물 정본 · 원본(본보기 아님) · [키, 이름] (정의 차례). */
export const templates = (def: StructDef): Array<[string, string]> =>
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Check.ts
* M01_SO_Def_Check.ts
* 구조물 표 검사(PLAN 322-2 · 1-3 규칙) — 정의 `반영` · `부품` 꼴 · 표 줄과 부품이 맞음 · 만든 뒤 고정.
*
* · 반영 = `{종류: {목록 · 횡단도 · 카드이름 · 형상 · 형상칸 · 3D}}` · 값 = 부품 상자에 있는 것
@@ -9,7 +9,7 @@
* 그림이 늘 기본값을 씀 · 앞 판에서 이미 숨긴 칸은 그대로 둠)
* · 앞 판이 없으면(옛 판 읽기) 꼴만 검사
* · 앞 판과 비교 — 종류 지우기 없음 · 자리꼴 · 정본 · 군 글자 고정 · 선택지 값 고정(이름은 이름 표로)
* 서버 짝 = `M02_SO_Check.py`(같은 글) · 거울 시험 = `resources/tester/test_322_2_check_mirror.py`.
* 서버 짝 = `M01_SO_Check.py`(같은 글) · 거울 시험 = `resources/tester/test_322_2_check_mirror.py`.
* ========================================================================== */
import PARTS from "../../common_util/common_util_structure_parts.json" with { type: "json" };
@@ -17,7 +17,7 @@ import {
resolveCatalog,
type CatalogDefinition,
} from "../../common_util/common_util_structure_catalog";
import { OWNER_KO, PLACE_KO, shortName } from "./M02_SO_Def_Reflect";
import { OWNER_KO, PLACE_KO, shortName } from "./M01_SO_Def_Reflect";
type Branch = "횡단도" | "카드이름" | "형상" | "3D";
interface Part {
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Layout.ts
* M01_SO_Def_Layout.ts
* 구조물 정의 편집 화면(PLAN 48-2) — 고른 종류의 **배치 격자**(B05 · B06 좌측 구조물 칸 = 두 칸)
* 옵션마다 줄 · 칸 · 너비 + 미리보기(기준 측점은 맨 위 한 줄 · 겹치면 빨강).
* 자리를 안 정한 옵션은 차례대로 빈 칸을 채움 · 숫자를 고치면 그 옵션 자리만 정의 `배치` 에 남음.
@@ -15,9 +15,9 @@ import {
type Spot,
type StructDef,
type TypeDef,
} from "./M02_SO_Def_Model";
import { head, numberBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
} from "./M01_SO_Def_Model";
import { head, numberBox } from "./M01_SO_Def_Ui";
import { to } from "./M01_SO_Text";
export interface LayoutBlockOptions {
def: StructDef;
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Model.ts
* M01_SO_Def_Model.ts
* 구조물 정의 편집 화면(PLAN 48-2)의 자료 꼴 · 순수 손질 함수 — 화면 그리기 없음.
* 정본 = 마스터 템플릿 `구조물정의.json`(48-1 · 틀 `docs/raw/M02_구조물옵션정의/정의_틀.md`).
* 키는 만들 때 자동 · 안 바뀜 · 이름 자유 · 지움 = 「안 씀」(`enabled: false`).
@@ -226,7 +226,7 @@ export function overlaps(cells: Map<string, Spot>): string[] {
return [...bad];
}
/** 규칙 한 줄이 틀렸나 — 서버 검사(`M02_SO_Definition._rule_errors`)와 같은 뜻 */
/** 규칙 한 줄이 틀렸나 — 서버 검사(`M01_SO_Definition._rule_errors`)와 같은 뜻 */
export function ruleBad(def: StructDef, r: RuleDef): boolean {
const t = def.types.find((x) => x.type_id === r.종류);
const src = t?.options.find((o) => o.key === r.만약.옵션);
@@ -1,10 +1,10 @@
/* =============================================================================
* M02_SO_Def_Options.ts
* M01_SO_Def_Options.ts
* 구조물 정의 편집 화면(PLAN 48-2) — 고른 종류의 **옵션 목록**
* (이름 · 꼴 · 단위 · 기본값 · 보이기 · 들어갈 자리 · 안 씀 · 순서 · [옵션 더함]) +
* 고르기 꼴의 **선택지 목록**(이름 바꿈 · 빼기 · 순서 · [선택지 더함]).
* 옵션 키는 더할 때 자동 · 안 바뀜 · 선택지는 글이 곧 값(이름 바꿈 = 기본값 · 규칙도 같이) ·
* 저장은 화면 [저장](`M02_SO_Def.ts`).
* 저장은 화면 [저장](`M01_SO_Def.ts`).
* ========================================================================== */
import { createButton, createTag, el, showConfirmDialog } from "@ui/ui_template_elements";
@@ -16,10 +16,10 @@ import {
type OptionForm,
type StructDef,
type TypeDef,
} from "./M02_SO_Def_Model";
import { checkBox, head, moveButtons, pickBox, textBox } from "./M02_SO_Def_Ui";
import { buildPlaceSelect } from "./M02_SO_Groups";
import { to } from "./M02_SO_Text";
} from "./M01_SO_Def_Model";
import { checkBox, head, moveButtons, pickBox, textBox } from "./M01_SO_Def_Ui";
import { buildPlaceSelect } from "./M01_SO_Groups";
import { to } from "./M01_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createEmpty } from "@ui/ui_template_empty";
@@ -1,12 +1,12 @@
/* =============================================================================
* M02_SO_Def_Parts.ts
* M01_SO_Def_Parts.ts
* 구조물 정의 「부품」 탭(PLAN 322-2) — 코드가 그리는 방법(부품 상자 `common_util_structure_parts.json`).
* 갈래마다 부품 · 이름 · 읽는 칸 · 맞는 자리꼴 · 정본 · 쓰는 종류 · 켬/끔(정의 `부품` = 끈 것만).
* 끈 부품을 쓰는 종류는 그 갈래가 없음(카드 이름은 종류 이름)으로 — 표 줄(`resolveCatalog`)이 따름.
* ========================================================================== */
import { el } from "@ui/ui_template_elements";
import type { StructDef } from "./M02_SO_Def_Model";
import type { StructDef } from "./M01_SO_Def_Model";
import {
OWNER_KO,
PART_BOX,
@@ -15,9 +15,9 @@ import {
setPartOn,
shortName,
usersOf,
} from "./M02_SO_Def_Reflect";
import { checkBox, head } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
} from "./M01_SO_Def_Reflect";
import { checkBox, head } from "./M01_SO_Def_Ui";
import { to } from "./M01_SO_Text";
import { createText } from "@ui/ui_template_text";
type Branch = keyof typeof PART_BOX;
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Reflect.ts
* M01_SO_Def_Reflect.ts
* 구조물 표 편집(PLAN 322-2)의 순수 손질 — 정의 사본의 `반영` · `부품` · 목록 + enabled · 형상칸.
*
* · 지금 값 = 구조물 표 한 줄(`resolveCatalog` · 정의 반영 ⊕ 처음값 ⊕ 부품 끔)
@@ -14,7 +14,7 @@ import {
type CatalogDefinition,
type CatalogRow,
} from "../../common_util/common_util_structure_catalog";
import { clone, type StructDef } from "./M02_SO_Def_Model";
import { clone, type StructDef } from "./M01_SO_Def_Model";
export type ReflectField = "목록" | "횡단도" | "카드이름" | "형상" | "3D";
type Reflect = Partial<Record<ReflectField, string>> & { 형상칸?: Record<string, unknown> };
@@ -126,7 +126,7 @@ export function setPartOn(def: StructDef, key: string, on: boolean): void {
}
/** 못 숨김 칸 — 종류가 지금 쓰는 부품들이 읽는 칸 중 기본값도 비워 두는 뜻도 없는 옵션
* (숨기면 그림이 받을 값이 없음 · 검사 짝 `M02_SO_Def_Check`). */
* (숨기면 그림이 받을 값이 없음 · 검사 짝 `M01_SO_Def_Check`). */
export function readKeys(def: StructDef, typeId: string): Set<string> {
const row = rowsOf(def).get(typeId);
if (!row) return new Set();
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Rules.ts
* M01_SO_Def_Rules.ts
* 구조물 정의 편집 화면(PLAN 48-2) — 고른 종류의 **규칙 표**(정의 `규칙` 중 그 종류 것만)
* 「만약 상위 옵션 = 값들 중 하나 → 하위 옵션의 선택지 · 보이기 · 기본값」 한 줄씩 · [규칙 더함] · 지우기.
* 「그대로」 칸은 정의에 안 남김 · 셋 다 그대로면 틀린 줄(빨강) · 적용은 B05 · B06(48-4).
@@ -13,9 +13,9 @@ import {
type RuleDef,
type StructDef,
type TypeDef,
} from "./M02_SO_Def_Model";
import { head, pickBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
} from "./M01_SO_Def_Model";
import { head, pickBox } from "./M01_SO_Def_Ui";
import { to } from "./M01_SO_Text";
import { createEmpty } from "@ui/ui_template_empty";
import { createCheckbox } from "@ui/ui_template_checkbox";
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Spec.ts
* M01_SO_Def_Spec.ts
* 구조물 명세가 있는 종류(PLAN 52 · `STRUCTURE_SPECS`)의 이름 고치기 칸(52-11) — 나무 꼴
* 컨테이너 제목 › 항목 이름 › 값 이름 · 이름만 고침 · 키 · 필수/선택 · 꼴은 읽기만 ·
* 아래 미리보기 = B05 · B06 이 그리는 같은 명세 폼(`createSpecForm`)에 고친 이름을 얹음.
@@ -18,16 +18,16 @@ import {
} from "../../A00_Common/design/logic/design_structure_spec";
import { group } from "../../B05_Profile/B05_Profile_UI_Drainage_Facility_Fields";
import { field, optionControl } from "../../B05_Profile/B05_Profile_UI_Structures_Fields";
import type { StructDef, TypeDef } from "./M02_SO_Def_Model";
import type { StructDef, TypeDef } from "./M01_SO_Def_Model";
import {
groupNameRows,
setSpecName,
specNameRows,
type SpecNameRow,
} from "./M02_SO_Def_Spec_Model";
import { hiddenKeys, readKeys, setShown } from "./M02_SO_Def_Reflect";
import { checkBox, head, textBox } from "./M02_SO_Def_Ui";
import { to, type OptionsTextKey } from "./M02_SO_Text";
} from "./M01_SO_Def_Spec_Model";
import { hiddenKeys, readKeys, setShown } from "./M01_SO_Def_Reflect";
import { checkBox, head, textBox } from "./M01_SO_Def_Ui";
import { to, type OptionsTextKey } from "./M01_SO_Text";
import { createEmpty } from "@ui/ui_template_empty";
const TAG: Record<NonNullable<SpecNameRow["tag"]>, OptionsTextKey> = {
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Def_Spec_Model.ts
* M01_SO_Def_Spec_Model.ts
* 구조물 명세(PLAN 52 · `design_structure_spec`) 이름 고치기(52-11)의 자료 손질 — 화면 그리기 없음.
*
* · 명세 = 구조 정본(키 · 컨테이너 · 필수/선택 · 꼴) — 여기서는 **이름만** 고침
@@ -12,7 +12,7 @@
* ========================================================================== */
import type { StructureSpec } from "../../A00_Common/design/logic/design_structure_spec";
import type { StructDef, TypeDef } from "./M02_SO_Def_Model";
import type { StructDef, TypeDef } from "./M01_SO_Def_Model";
export interface SpecNameRow {
/** 0 = 컨테이너 · 1 = 항목 · 2 = 값 */
@@ -1,14 +1,14 @@
/* =============================================================================
* M02_SO_Def_Table.ts
* M01_SO_Def_Table.ts
* 구조물 정의 「한눈 표」 탭(PLAN 322-2) — 종류마다 B05 · B06 반영 한 줄.
* 군 · 종류(▲▼) · 이름 · 목록 · 자리꼴 · 정본(읽기만 「고정」) · 횡단도 · 카드 이름 · 형상(+ 형상칸) ·
* 알약 색 · 3D · 검사. 흐린 칸 = 처음 값(「기본」) · 진한 칸 = 바꾼 값 · [처음 값으로] = 그 종류 반영 지움.
* 칸 손질 = `M02_SO_Def_Reflect` · 검사 글 = `M02_SO_Def_Check`(서버 짝) · 「종류별」 탭이 같은 칸(`reflectCells`)을 씀.
* 칸 손질 = `M01_SO_Def_Reflect` · 검사 글 = `M01_SO_Def_Check`(서버 짝) · 「종류별」 탭이 같은 칸(`reflectCells`)을 씀.
* ========================================================================== */
import { createButton, createTag, el } from "@ui/ui_template_elements";
import type { CatalogRow } from "../../common_util/common_util_structure_catalog";
import { stepFamily, stepType, type StructDef, type TypeDef } from "./M02_SO_Def_Model";
import { stepFamily, stepType, type StructDef, type TypeDef } from "./M01_SO_Def_Model";
import { REVET_FORMS } from "../../B06_Section/logic/B06_Section_UI_Cross_Culvert_Const";
import {
isSet,
@@ -22,9 +22,9 @@ import {
setShapeOpt,
valueOf,
type ReflectField,
} from "./M02_SO_Def_Reflect";
import { checkBox, pickBox, textBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
} from "./M01_SO_Def_Reflect";
import { checkBox, pickBox, textBox } from "./M01_SO_Def_Ui";
import { to } from "./M01_SO_Text";
import { createText } from "@ui/ui_template_text";
type Pairs = ReadonlyArray<readonly [string, string]>;
@@ -1,12 +1,12 @@
/* =============================================================================
* M02_SO_Def_Ui.ts
* M01_SO_Def_Ui.ts
* 구조물 정의 편집 화면(PLAN 48-2)의 작은 입력 부품 — 글 · 숫자 · 체크 · 고르기 · 위아래 단추.
* 값은 받은 손잡이로 사본만 고침 · 글은 칸을 떠날 때(`change`) 다시 그림(초점 안 끊김).
* ========================================================================== */
import { createButton, el } from "@ui/ui_template_elements";
import { step } from "./M02_SO_Def_Model";
import { to } from "./M02_SO_Text";
import { step } from "./M01_SO_Def_Model";
import { to } from "./M01_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createCheckbox } from "@ui/ui_template_checkbox";
@@ -1,7 +1,7 @@
"""M02 구조물 정의 한 벌(PLAN 48-1) — 정본 `resources/master_template/구조물정의.json`.
"""M01 구조물 정의 한 벌(PLAN 48-1) — 정본 `resources/master_data/구조물정의/구조물정의.json`.
틀 = `docs/raw/M02_구조물옵션정의/정의_틀.md`. 읽기 = 로그인 누구나 · 쓰기 = 시스템 관리자만.
판 = 정수 · 저장마다 +1 · 앞 판은 `구조물정의_이력/판_N.json` 으로 남김(지난 정의 값 읽기용).
판 = 정수 · 저장마다 +1 · 앞 판은 `구조물정의/이력/판_N.json` 으로 남김(지난 정의 값 읽기용).
검사 = 칸 꼴 · 키 겹침 · 표시 · 그룹 · 배치 · 규칙 대상 있음 — 틀리면 422 · 낡은 판 409.
"""
@@ -17,12 +17,12 @@ from pydantic import ValidationError
from B05_Profile import B05_Profile_Structures_Schema as schema
from common_util.common_util_json import atomic_write_json
from common_util.common_util_time import utc_from_timestamp
from M01_MasterData.StructOptions.M01_SO_Check import catalog_errors
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete.StructOptions.M02_SO_Check import catalog_errors
FILE = "구조물정의.json"
HISTORY = "구조물정의_이력"
# 반영 · 부품 = 구조물 표 칸(322-2 · 없으면 처음값 · 검사 = `M02_SO_Check`)
HISTORY = "이력"
# 반영 · 부품 = 구조물 표 칸(322-2 · 없으면 처음값 · 검사 = `M01_SO_Check`)
TOP = {"판", "schema_version", "comment", "구조물군", "동작", "types", "반영", "부품"}
SECTIONS = {"종류": dict, "표시": dict, "그룹": dict, "배치": dict, "규칙": list}
SPOT = ("줄", "칸", "너비")
@@ -180,8 +180,8 @@ def _rule_errors(doc: dict[str, Any], keys: dict[str, dict[str, Any]]) -> list[s
def check(doc: Any, before: dict[str, Any] | None = None) -> list[str]:
"""정의 한 벌 검사 — 틀린 것 목록(빈 목록 = 통과). `before` = 지금 판(만든 뒤 고정 · 322-2)."""
from M02_MasterTemplete.StructOptions import M02_SO_Groups as groups
from M02_MasterTemplete.StructOptions import M02_SO_Options as options
from M01_MasterData.StructOptions import M01_SO_Groups as groups
from M01_MasterData.StructOptions import M01_SO_Options as options
if not isinstance(doc, dict):
return ["정의는 묶음이어야 함"]
@@ -1,6 +1,6 @@
"""M02 구조물 옵션 그룹 — 구조물 종류 안에 이름 붙은 묶음(PLAN 46-2).
정본 = 구조물 정의 한 벌(`M02_SO_Definition` · PLAN 48-1)의 「그룹」 칸 =
정본 = 구조물 정의 한 벌(`M01_SO_Definition` · PLAN 48-1)의 「그룹」 칸 =
`{type_id: [{"id": "g1a2b3c", "이름": "유입구 기슭막이", "옵션": [...], "형상"?: {...}}]}`
— 없는 종류 = 그룹 없음 · 빈 그룹(옵션 0)도 그룹 · 형상 = 길이 · 높이 · 전 · 후 받기 + 뜻.
@@ -26,7 +26,7 @@ logger = logging.getLogger(__name__)
def _load() -> tuple[dict[str, Any], str]:
"""(그룹 표 · 판) — 정의 한 벌(`M02_SO_Definition`)의 「그룹」 칸 · 판 = 정의 판 글."""
"""(그룹 표 · 판) — 정의 한 벌(`M01_SO_Definition`)의 「그룹」 칸 · 판 = 정의 판 글."""
doc = load_definition()
return doc.get("그룹") or {}, str(doc.get("판", 1))
@@ -144,7 +144,7 @@ def _clean(groups: Any, keys: dict[str, set[str]] | None = None) -> dict[str, li
def save(groups: Any, version: str) -> dict[str, Any]:
"""고쳐 씀 — 판이 같을 때만. 돌려주는 것 = 새 `listing()`."""
from M02_MasterTemplete.StructOptions.M02_SO_Definition import save_sections
from M01_MasterData.StructOptions.M01_SO_Definition import save_sections
save_sections({"그룹": _clean(groups)}, version)
return listing()
@@ -1,16 +1,16 @@
/* =============================================================================
* M02_SO_Groups.ts
* M01_SO_Groups.ts
* 구조물 정의 화면의 **옵션 그룹** 부품(PLAN 46-2 · 48-2) — 고른 종류의 그룹 목록
* (이름 · 위로 · 아래로 · 지우기 · 형상 칸 길이 · 높이 · 전 · 후 받기 켬끔과 뜻 · [그룹 추가]) ·
* 옵션 줄마다 「들어갈 자리」 고르기(본체 · 그룹).
* 값은 화면이 쥔 고칠 사본에만 — 저장은 화면 [저장](`M02_SO_Def.ts`).
* 그룹 하나 = 프로젝트 B05 · B06 폼의 보조 컨테이너 하나 · 옵션이 없어도 됨(서버 `M02_SO_Groups.py`).
* 값은 화면이 쥔 고칠 사본에만 — 저장은 화면 [저장](`M01_SO_Def.ts`).
* 그룹 하나 = 프로젝트 B05 · B06 폼의 보조 컨테이너 하나 · 옵션이 없어도 됨(서버 `M01_SO_Groups.py`).
* ========================================================================== */
import { createButton, el, showConfirmDialog } from "@ui/ui_template_elements";
import { SHAPE_KEYS, type GroupDef } from "./M02_SO_Def_Model";
import { checkBox, textBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
import { SHAPE_KEYS, type GroupDef } from "./M01_SO_Def_Model";
import { checkBox, textBox } from "./M01_SO_Def_Ui";
import { to } from "./M01_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createEmpty } from "@ui/ui_template_empty";
@@ -1,6 +1,6 @@
"""M02 구조물 옵션 보이기 — 구조물 종류마다 B05/B06 폼에 보일 옵션을 사용자가 체크.
정본 = 구조물 정의(`M02_SO_Definition` · PLAN 48-1) 「표시」 칸 = `{type_id: {option_key: false}}`
정본 = 구조물 정의(`M01_SO_Definition` · PLAN 48-1) 「표시」 칸 = `{type_id: {option_key: false}}`
— 없는 종류 · 키는 보임.
저장은 **숨김(false)만** 남김 — 「모두 보임」 = `{}`.
옵션 정의 · 옛 값은 그대로 — 폼이 그리는 것만 갈림(`GET /api/projects/structure-types` `visible`).
@@ -22,8 +22,8 @@ from B05_Profile.B05_Profile_Structures_Schema import (
load_structure_types,
registry_schema_version,
)
from M01_MasterData.StructOptions.M01_SO_Groups import groups_of
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete.StructOptions.M02_SO_Groups import groups_of
logger = logging.getLogger(__name__)
@@ -35,7 +35,7 @@ class OptionWithVisible(StructureOptionField):
class OptionGroup(BaseModel):
"""옵션 그룹 한 개(PLAN 46-2 · `M02_SO_Groups`) — 폼의 보조 컨테이너 하나 · 빈 옵션도 됨."""
"""옵션 그룹 한 개(PLAN 46-2 · `M01_SO_Groups`) — 폼의 보조 컨테이너 하나 · 빈 옵션도 됨."""
id: str
name: str
@@ -54,7 +54,7 @@ class TypesWithVisible(StructureTypesResponse):
def _load() -> tuple[dict[str, Any], str]:
"""(표시 표 · 판) — 정의 한 벌(`M02_SO_Definition`)의 「표시」 칸 · 판 = 정의 판 글."""
"""(표시 표 · 판) — 정의 한 벌(`M01_SO_Definition`)의 「표시」 칸 · 판 = 정의 판 글."""
doc = load_definition()
return doc.get("표시") or {}, str(doc.get("판", 1))
@@ -155,7 +155,7 @@ def _clean(shown: Any, keys: dict[str, set[str]] | None = None) -> dict[str, dic
def save(shown: Any, version: str) -> dict[str, Any]:
"""고쳐 씀 — 판이 같을 때만. 돌려주는 것 = 새 `listing()`."""
from M02_MasterTemplete.StructOptions.M02_SO_Definition import save_sections
from M01_MasterData.StructOptions.M01_SO_Definition import save_sections
save_sections({"표시": _clean(shown)}, version)
return listing()
@@ -1,15 +1,15 @@
/* =============================================================================
* M02_SO_Options.ts
* M01_SO_Options.ts
* 좌측 「구조물 옵션 정의」 줄(구조물 집계 양식 아래 별도 · 시스템 층) — 누르면 메인 칸에
* 정의 편집 화면(PLAN 48-2 · `M02_SO_Def.ts`) · 고쳐 씀은 시스템 관리자만 · 다른 역할은 읽기만.
* 정의 편집 화면(PLAN 48-2 · `M01_SO_Def.ts`) · 고쳐 씀은 시스템 관리자만 · 다른 역할은 읽기만.
* 옛 「보이기 · 그룹」 화면(46장)은 정의 화면의 옵션 줄 「보이기」 · 그룹 칸으로 들어감.
* ========================================================================== */
import { el } from "@ui/ui_template_elements";
import { openDefScreen } from "./M02_SO_Def";
import { openDefScreen } from "./M01_SO_Def";
import "@ui/ui_template_card.css";
import "./M02_SO_Style.css";
import { to } from "./M02_SO_Text";
import "./M01_SO_Style.css";
import { to } from "./M01_SO_Text";
export interface OptionsSectionOptions {
isAdmin: boolean;
@@ -1,4 +1,4 @@
"""M02 구조물 옵션 보이기 · 그룹 · 정의 길 — 정본 `M02_SO_Definition.py`(PLAN 48-1) 한 벌.
"""M02 구조물 옵션 보이기 · 그룹 · 정의 길 — 정본 `M01_SO_Definition.py`(PLAN 48-1) 한 벌.
`router` = 고쳐 씀 · 관리 읽기(`main.py` 가 `system_admin_only` 로 붙임) ·
`read_router` = 읽기만(로그인 누구나 · `main.py` 가 `protected` 로 붙임) · 정의 쓰기는 여기서
@@ -14,14 +14,14 @@ from pydantic import BaseModel
from B05_Profile.B05_Profile_Structures_Schema import definition_version
from common_util.common_util_auth import verify_session
from M01_MasterData.StructOptions import M01_SO_Definition as definition
from M01_MasterData.StructOptions import M01_SO_Groups as groups
from M01_MasterData.StructOptions import M01_SO_Options as options
from M02_MasterTemplete import M02_Layer_Access as access
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete.StructOptions import M02_SO_Definition as definition
from M02_MasterTemplete.StructOptions import M02_SO_Groups as groups
from M02_MasterTemplete.StructOptions import M02_SO_Options as options
router = APIRouter(prefix="/api/m02", tags=["M02 MasterTemplete"])
read_router = APIRouter(prefix="/api/m02", tags=["M02 MasterTemplete"])
router = APIRouter(prefix="/api/m01", tags=["M01 MasterData"])
read_router = APIRouter(prefix="/api/m01", tags=["M01 MasterData"])
class OptionsBody(BaseModel):
@@ -1,5 +1,5 @@
/* =============================================================================
* M02_SO_Text.ts
* M01_SO_Text.ts
* 좌측 「구조물 옵션 보이기」 줄 · 상세 화면(보이기 · 그룹) 글자 — [한국어, 영어]
* ========================================================================== */
+1 -1
View File
@@ -233,7 +233,7 @@ def rename_moved(base: Path, wanted: dict[str, tuple[str, dict[str, Any]]]) -> l
def group_names() -> dict[str, str]:
"""옵션 그룹 id → 이름(지금 정의) — 복사본 manifest `그룹` 으로 굳힘(142-2)."""
from M02_MasterTemplete.StructOptions.M02_SO_Groups import groups_of
from M01_MasterData.StructOptions.M01_SO_Groups import groups_of
return {g["id"]: g["name"] for rows in groups_of().values() for g in rows}
+3 -2
View File
@@ -133,8 +133,9 @@ def _fresh(folder: Path, kind: str, name: str, rec: Any, stamp: str | None, whol
deps.setdefault(str(p), file_stamp(p))
token = refs.SEEN.set(note)
try: # 셈마다 새 펼침 — 다른 항목 셈 기억을 나눠 쓰면 기댐이 빠짐
out = refs.summary(folder, kind, name, Expand(whole), [])
try: # 셈마다 새 펼침 — 다른 항목 셈 기억을 나눠 쓰면 기댐이 빠짐 · 지금 층 = 그 층(내 기계 · 자동 따라옴)
with store.at(folder):
out = refs.summary(folder, kind, name, Expand(whole), [])
finally:
refs.SEEN.reset(token)
out.pop("쓰는곳수", None)
@@ -5,7 +5,7 @@
* ========================================================================== */
import { createSelectField } from "@ui/ui_template_elements";
import { fetchStructureDef } from "./StructOptions/M02_SO_Api";
import { fetchStructureDef } from "../M01_MasterData/StructOptions/M01_SO_Api";
import { precomboClasses } from "./M02_MasterTemplete_UI_Side_Precombo";
import { tc } from "./M02_MasterTemplete_Labor_Text";
@@ -33,7 +33,7 @@ import { openStandardSheet } from "./M02_MasterTemplete_Labor_Sheet";
import type { LaborFixed, LaborRef } from "./M02_MasterTemplete_Labor_Calc";
import { tc } from "./M02_MasterTemplete_Labor_Text";
import { precomboClasses } from "./M02_MasterTemplete_UI_Side_Precombo";
import { fetchStructureDef } from "./StructOptions/M02_SO_Api";
import { fetchStructureDef } from "../M01_MasterData/StructOptions/M01_SO_Api";
import "../M01_MasterData/M01_MasterData_UI_Logic_Style.css"; // 창 겉틀
import "./M02_MasterTemplete_Labor.css";
import { openModal } from "@ui/ui_template_modal";
@@ -9,7 +9,7 @@
import type { TreeMenuItem } from "@ui/ui_template_tree";
import type { Kind } from "./M02_MasterTemplete_Api_Fetch";
import type { StructDef } from "./StructOptions/M02_SO_Def_Model";
import type { StructDef } from "../M01_MasterData/StructOptions/M01_SO_Def_Model";
import { tc } from "./M02_MasterTemplete_Labor_Text";
import type { Selection } from "./M02_MasterTemplete_UI_Main";
import {
+30 -2
View File
@@ -469,16 +469,44 @@ def update(key: str, raw: Any, ver: str | None = None) -> dict[str, Any]:
def delete(key: str) -> dict[str, Any]:
"""지움 — 이미 만든 단가산출은 사본의 마지막 값 그대로(「지운키」)."""
"""지움 — 쓰던 단가산출은 지우기 직전 값 그대로(`_hold` · 요구 902)."""
_user()
_old(key)
used = library_uses.machines().get(key, [])
with _LOCK:
_old(key)
used = library_uses.machines().get(key, [])
_hold(key, used)
(_dir() / f"{key}.json").unlink(missing_ok=True)
return {"지움": key, "쓰는곳": used}
def _hold(key: str, used: list[dict]) -> None:
"""쓰던 단가산출 값 사본(옛 칸 · 수식)의 그 기계 줄 = 지금 따라와 있던 줄로 굳힘 — 지운 키는 사본
마지막 줄을 읽음(`M02_Sk_AutoRenew._fresh`) · 굳은 사본(프로젝트 등)은 그대로 · 잠금 안에서 부름."""
from M02_MasterTemplete import M02_Sangeun_Copy as skc
from M02_MasterTemplete import M02_Sangeun_Doc as sd
from M02_MasterTemplete import M02_Sk_AutoRenew as renew
if not renew.on(): # 안 따라오는 층 = 사본 그대로
return
live = skc.whole_()
for one in used:
path = store._path(sd.KIND, str(one["키"]))
doc = json.loads(path.read_bytes())
if renew.frozen(doc.get(skc.FORM)):
continue
for part in (skc.KEY, skc.FORM):
copy = doc.get(part)
old = copy.get("단가") if isinstance(copy, dict) else None
if isinstance(old, list):
new = [
renew._fresh(r, live) if isinstance(r, dict) and r.get("키") == key else r
for r in old
]
copy |= {"단가": new, "단가판": skc._fp(new)}
atomic_write_json(path, doc)
def same(name: Any, spec: Any, skip: str = "") -> list[dict]:
"""같은 이름 · 규격 알림 — M01 기계 · 이 층 내 기계(표기 정규화 `M02_Machine_Find.norm`)."""
from M02_MasterTemplete.M02_Machine_Find import norm
+1 -1
View File
@@ -150,9 +150,9 @@ def _with_group_items(items: list[dict[str, Any]], project_root=None) -> list[di
복사본 `{구조물 id}__{그룹 id}`. 그룹 = 지금 정의 + 복사본에 굳힌 정의(142-2 · 이름 · 사라진
그룹도) · 미지정 그룹 = 「미지정」 알림에 셈."""
from common_util.common_util_summary_item import GROUP_JOIN
from M01_MasterData.StructOptions.M01_SO_Groups import groups_of
from M02_MasterTemplete.M02_Item_Snapshot import copied_groups
from M02_MasterTemplete.M02_Table_Fill_Spec import container_rows
from M02_MasterTemplete.StructOptions.M02_SO_Groups import groups_of
defined = groups_of()
out: list[dict[str, Any]] = []
@@ -44,6 +44,8 @@ export interface DocCache {
takeMissing: () => boolean;
/** 표 하나 넣음(고르기에서 받은 것) */
putTable: (ref: string, table: DocTable) => void;
/** 표 통째(859-3 보이는 자리 — 줄마다 원문 글자 자리 `자리`) · 없으면 undefined */
tableOf: (ref: string) => (DocTable & { 끊김?: string }) | undefined;
}
export function createDocCache(): DocCache {
@@ -99,5 +101,8 @@ export function createDocCache(): DocCache {
putTable(ref, table) {
tables.set(ref, table);
},
tableOf(ref) {
return tables.get(ref) ?? undefined;
},
};
}
+3 -3
View File
@@ -20,9 +20,9 @@ export class StaleError extends Error {
}
}
/** `/api/m02` 아래 길 부름 — 409 = StaleError · 그 밖 실패 = 서버 까닭 글(하위 폴더도 씀) */
export async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(`${API_BASE_URL}/m02${path}`, {
/** `/api/m02` 아래 길 부름(`base` = 다른 묶음 · M01 구조물 정의 `/m01`) — 409 = StaleError · 그 밖 실패 = 서버 까닭 글(하위 폴더도 씀) */
export async function call<T>(path: string, init: RequestInit = {}, base = "/m02"): Promise<T> {
const response = await fetch(`${API_BASE_URL}${base}${path}`, {
credentials: "include",
headers: { "Content-Type": "application/json" },
...init,
+154
View File
@@ -0,0 +1,154 @@
/* =============================================================================
* common_util_show_digits.ts
* 보이는 수의 자릿수 규칙 한 벌(PLAN 859-3 · 856-5 · 요구 898 · 902) — 셈 값 · 저장 값 · 금액은 그대로 · 그리는 글자만
* ⚠ 짝 = resources/master_data/scripts/master_doc_digits.py(같은 규칙 · 한쪽을 고치면 다른 쪽도) ·
* 거울 시험 resources/tester/test_859_3_show_digits.py
* 갈래(`digitKind`) = 문서 식 줄 → 「식」 · 변수 연결 표 → 「표」 · 입력 · 선택 → 「입력」 · 그 밖(요소 · 단가산출) → 「요소」
* 규칙(자리 값은 `RULE` 한 곳):
* 표 = 고른 표 줄의 원문 글자 자리(끝 0 살림 — 건설 · 산림 1-2-2 1 [주]② 「항목에서 제시한 소수자리 우선」 ·
* 서버가 표 캐시에 줄마다 `자리` 를 실음) · 글자 자리를 모르면(끝 0 빠진 자료 · 사용자가 바꾼 값) 자료 수 그대로
* 식 = 기호 Q 3 · n 2 · cm 3 자리(건설 8-1 [주]① 계산값의 맺음) ›
* 단위가 원(원/…) · 비목 이름(노무비 · 재료비 · 경비)이면 소수 한 자리(1-2-2 2 「일위대가표의 금액란 0.1 원」 준용) ›
* 그 밖 = 유효숫자 3 · 소수 최소 2 · 최대 6(1-2-2 3 시공단위 품 표 근사 · 정수는 정수)
* 입력 · 요소 = 자료 수 그대로(소수 여섯 자리까지 · 끝 0 뗌 — `eqText`)
* 수 꼴 = 천 단위 쉼표 · 반올림(Intl — 짧은 10 진 글 기준 0.5 올림) · 화면 · fetch 없음
* ========================================================================== */
import { varId, type DocVar, type FormulaDoc } from "./common_util_formula_doc";
import { findRow, type DocTable } from "./common_util_formula_doc_table";
import { evalNode, tryParse, type Values } from "./common_util_formula_doc_view";
/** 자리 값 표 — 사용자 확정 값이 바뀌면 여기만 고침(짝 PY `RULE`) */
export const RULE = {
/** 입력 · 요소 · 자리 모르는 표 값 = 최대 자리(끝 0 뗌) */
plain: 6,
/** 건설 8-1 [주]① — 식이 낸 값 · 기호 그대로 */
symbol: { Q: 3, n: 2, cm: 3 } as Record<string, number>,
/** 원 단위 중간 값(율 줄 단가 · 원/… 식 값) */
money: 1,
/** 단위 없는 비목 값(기계 시간당 식) = 원 */
moneyNames: ["노무비", "재료비", "경비"],
/** 그 밖 식 값 — 유효숫자 · 소수 최소(정수는 정수) · 최대 */
sig: 3,
min: 2,
max: 6,
};
export type DigitKind = "식" | "표" | "입력" | "요소";
/** 서버 표 캐시 줄마다 원문 글자 자리(끝 0 있는 칸만) — `master_doc_record` 가 실음 */
export type PlacedTable = DocTable & { 자리?: (Record<string, number> | null)[] | null };
const formats = new Map<string, Intl.NumberFormat>();
/** 소수 `hi` 자리 반올림 · 끝 0 은 `lo` 자리까지 뗌 · 천 단위 쉼표 */
export function fmt(n: number, lo: number, hi: number): string {
const k = `${lo}:${hi}`;
let f = formats.get(k);
if (!f) {
f = new Intl.NumberFormat("ko-KR", { minimumFractionDigits: lo, maximumFractionDigits: hi });
formats.set(k, f);
}
return f.format(n);
}
/** 짧은 10 진 글의 [소수 자리, 맨 앞 자리 지수] — 0.0278 → [4, -2] */
function digits(n: number): [number, number] {
const [m, e] = Math.abs(n).toExponential().split("e");
const exp = Number(e);
const frac = (m.split(".")[1] ?? "").length;
return [Math.max(0, frac - exp), exp];
}
/** 표 값의 원문 글자 자리 — 지금 조건으로 고른 줄의 그 칸 · 값이 그 줄 값과 같을 때만(사용자가 바꾼 값 = undefined) */
export function tablePlaces(
v: DocVar | undefined,
value: unknown,
vals: Values,
tableOf?: (ref: string) => PlacedTable | null | undefined,
): number | undefined {
const k = v?.연결;
const ref = String(k?.표 ?? "");
const col = k?.칸;
if (!tableOf || !ref || !col || ref.includes("{")) return undefined;
const 조건: Record<string, unknown> = {};
for (const [c, t] of Object.entries(k?.조건 ?? {})) {
const n = tryParse(t);
if (n) 조건[c] = evalNode(n, vals);
}
try {
const t = tableOf(ref);
if (!t?.줄) return undefined;
const row = findRow(t, 조건, col);
if (typeof row[col] !== "number" || row[col] !== value) return undefined;
return t.자리?.[t.줄.indexOf(row)]?.[col] ?? undefined;
} catch {
return undefined;
}
}
/** 값 갈래 — 식 · 표 · 입력 · 요소 */
export function digitKind(doc: Pick<FormulaDoc, "식">, name: string, v?: DocVar): DigitKind {
if ((doc.식 ?? []).some((x) => String(x.기호 ?? "") === name)) return "식";
const kind = v?.연결?.갈래;
if (kind === "표") return "표";
if (kind === "입력" || kind === "선택") return "입력";
return v ? "요소" : "식";
}
/** 보이는 수 글 — `places` = 표 원문 글자 자리(모르면 없음) · 수가 아니면 글 그대로 */
export function showDigits(
value: unknown,
kind: DigitKind = "요소",
name = "",
unit = "",
places?: number,
): string {
if (value === null || value === undefined || value === "") return "";
if (typeof value !== "number" || !Number.isFinite(value)) return String(value);
const [own, exp] = digits(value);
if (kind === "표") {
const p = Math.max(places ?? 0, own);
return p <= RULE.plain ? fmt(value, p, p) : fmt(value, 0, RULE.plain);
}
if (kind !== "식") return fmt(value, 0, RULE.plain);
if (Object.prototype.hasOwnProperty.call(RULE.symbol, name))
return fmt(value, 0, RULE.symbol[name]);
if (unit.trim().startsWith("원") || RULE.moneyNames.includes(name))
return fmt(value, 0, RULE.money);
if (Number.isInteger(value)) return fmt(value, 0, 0);
const hi = Math.max(RULE.min, Math.min(RULE.max, RULE.sig - 1 - exp));
return fmt(value, RULE.min, hi);
}
/** 값이 온 기호 — 식 줄이 기호 하나(만약 = 지금 탄 갈래)면 그 기호로 따라감(K = 만약(K_입력 > 0, K_입력, K_2) → K_2) */
export function digitSource(doc: Pick<FormulaDoc, "식">, name: string, vals: Values): string {
const lines = new Map((doc.식 ?? []).map((x) => [String(x.기호 ?? ""), x.식]));
let at = name;
for (let hop = 0; hop < 8 && lines.has(at); hop++) {
let n = tryParse(lines.get(at));
while (n && n[0] === "call" && n[1] === "만약" && n[2].length === 3) {
const t = evalNode(n[2][0], vals);
if (t === undefined) return at;
n = n[2][t ? 1 : 2];
}
if (!n || n[0] !== "var" || n[1] === at) return at;
at = n[1];
}
return at;
}
/** 문서 기호 값 글 한 벌 — 값이 온 기호의 갈래 · 표 원문 글자 자리 · 단위(`unit` = 부르는 쪽이 정한 단위) */
export function showValue(
doc: Pick<FormulaDoc, "식" | "변수">,
name: string,
value: unknown,
vals: Values,
tableOf?: (ref: string) => PlacedTable | null | undefined,
unit?: string,
): string {
const src = digitSource(doc, name, vals);
const v = (doc.변수 ?? []).find((x) => varId(x) === src);
const kind = digitKind(doc, src, v);
const places = kind === "표" ? tablePlaces(v, value, vals, tableOf) : undefined;
return showDigits(value, kind, src, unit ?? String(v?.단위 ?? ""), places);
}
+1 -1
View File
@@ -71,7 +71,7 @@ def parse_summary_item(value: Any) -> dict[str, Any] | None:
return {**out, "spec": spec.strip()} if spec is not None else out
#: 옵션 그룹 id(PLAN 46 · `M02_SO_Groups.GROUP_ID` 와 같은 규칙)
#: 옵션 그룹 id(PLAN 46 · `M01_SO_Groups.GROUP_ID` 와 같은 규칙)
_GROUP_ID = re.compile(r"^g[0-9a-z]{1,16}$")
#: 그룹 복사본 이름 잇개 — `{구조물 id}__{그룹 id}`(구조물 id 는 hex · 관은 `pipe@측점`)
GROUP_JOIN = "__"
+5 -5
View File
@@ -105,8 +105,8 @@ from M02_MasterTemplete.M02_MasterTemplete_Router_Drawing import router as m02_d
from M02_MasterTemplete.M02_MasterTemplete_Router_Items import router as m02_items_router
from M02_MasterTemplete.M02_MasterTemplete_Router_Layers import router as m02_layers_router
from M02_MasterTemplete.M02_Project_Items_Router import router as m02_project_items_router
from M02_MasterTemplete.StructOptions.M02_SO_Router import read_router as m02_so_read_router
from M02_MasterTemplete.StructOptions.M02_SO_Router import router as m02_so_router
from M01_MasterData.StructOptions.M01_SO_Router import read_router as m01_so_read_router
from M01_MasterData.StructOptions.M01_SO_Router import router as m01_so_router
from common_util.common_util_audit import note_api_call, record_call_burst
from common_util.common_util_auth import (
require_company,
@@ -557,9 +557,9 @@ app.include_router(
dependencies=protected,
)
# 마스터 템플릿 층(시스템·회사·개인·프로젝트)·도면 길은 로그인만(권한은 길 안에서) · 옛 시스템 전용 길은 걷음(894).
# 구조물 옵션 보이기 · 그룹(PLAN 46) — 고쳐 씀은 시스템 관리자 · 읽기는 로그인만
app.include_router(m02_so_router, dependencies=system_admin_only)
app.include_router(m02_so_read_router, dependencies=protected)
# M01 구조물 정의 · 옵션 보이기 · 그룹(PLAN 46 · 859-5) — 고쳐 씀은 시스템 관리자 · 읽기는 로그인만
app.include_router(m01_so_router, dependencies=system_admin_only)
app.include_router(m01_so_read_router, dependencies=protected)
app.include_router(m02_layers_router, dependencies=protected)
app.include_router(m02_items_router, dependencies=protected)
app.include_router(m02_combos_router, dependencies=protected)
@@ -0,0 +1,185 @@
# -*- coding: utf-8 -*-
"""보이는 수의 자릿수 규칙 한 벌(PLAN 859-3 · 856-5 · 요구 898 · 902) —
셈 값 · 저장 값 · 금액은 그대로 · 그리는 글자만.
⚠ 짝 = `common_util/common_util_show_digits.ts`(같은 규칙 · 한쪽을 고치면 다른 쪽도) ·
거울 시험 `resources/tester/test_859_3_show_digits.py`.
갈래(`kind_of`) = 문서 식 줄 → 「식」 · 변수 연결 표 → 「표」 · 입력 · 선택 → 「입력」 ·
그 밖(요소 · 단가산출) → 「요소」.
규칙(자리 값은 `RULE` 한 곳):
표 = 고른 표 줄의 원문 글자 자리(끝 0 살림 —
건설 · 산림 1-2-2 1 [주]② 「항목에서 제시한 소수자리 우선」) ·
글자 자리를 모르면(끝 0 빠진 자료 · 사용자가 바꾼 값) 자료 수 그대로
식 = 기호 Q 3 · n 2 · cm 3 자리(건설 8-1 [주]① 계산값의 맺음) ›
단위가 원(원/…) · 비목 이름(노무비 · 재료비 · 경비)이면 소수 한 자리
(1-2-2 2 「일위대가표의 금액란 0.1 원」 준용) ›
그 밖 = 유효숫자 3 · 소수 최소 2 · 최대 6(1-2-2 3 시공단위 품 표 근사 · 정수는 정수)
입력 · 요소 = 자료 수 그대로(소수 여섯 자리까지 · 끝 0 뗌 — `eqText`)
수 꼴 = 천 단위 쉼표 · 반올림(0.5 올림 · 짧은 10 진 글 기준 — 화면 `Intl` 과 같음).
"""
from __future__ import annotations
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
#: 자리 값 표 — 사용자 확정 값이 바뀌면 여기만 고침(짝 TS `RULE`)
RULE = {
"plain": 6, # 입력 · 요소 · 자리 모르는 표 값 = 최대 자리(끝 0 뗌)
"symbol": {"Q": 3, "n": 2, "cm": 3}, # 건설 8-1 [주]① — 식이 낸 값 · 기호 그대로
"money": 1, # 원 단위 중간 값(율 줄 단가 · 원/… 식 값)
"money_names": ("노무비", "재료비", "경비"), # 단위 없는 비목 값(기계 시간당 식) = 원
"sig": 3, # 그 밖 식 값 — 유효숫자
"min": 2, # 〃 소수 최소(정수는 정수)
"max": 6, # 〃 소수 최대
}
def dec(v) -> Decimal | None:
"""수 → Decimal(화면 double 의 짧은 10 진 글 · 글 · 참거짓 · 빈 값 = None)."""
if isinstance(v, bool) or v is None or isinstance(v, str):
return None
try:
d = Decimal(repr(float(v))) # 화면 수(double)와 같은 짧은 10 진 글
except (InvalidOperation, ValueError, TypeError, OverflowError):
return None
return d if d.is_finite() else None
def fmt(d: Decimal, lo: int, hi: int) -> str:
"""소수 `hi` 자리 반올림 · 끝 0 은 `lo` 자리까지 뗌 · 천 단위 쉼표
(Intl 과 같음 — 0 으로 반올림된 음수 = 「-0」)."""
q = d.quantize(Decimal(1).scaleb(-hi), ROUND_HALF_UP)
sign = "-" if q.is_signed() else ""
whole, _, frac = f"{abs(q):f}".partition(".")
frac = frac.rstrip("0")
frac += "0" * (lo - len(frac))
head = f"{int(whole):,}"
return f"{sign}{head}.{frac}" if frac else f"{sign}{head}"
def places_of(d: Decimal) -> int:
"""짧은 10 진 글의 소수 자리(0.10 → 1 · 3.0 → 0)."""
exp = d.normalize().as_tuple().exponent
return -exp if isinstance(exp, int) and exp < 0 else 0
def text_places(d: Decimal) -> int:
"""글자 그대로의 소수 자리(Decimal('0.10') → 2 · 표 파일 원문 글자)."""
exp = d.as_tuple().exponent
return -exp if isinstance(exp, int) and exp < 0 else 0
def row_places(row: dict) -> dict:
"""표 줄의 칸마다 원문 글자 자리 — 짧은 글보다 길 때만(끝 0 · 화면 캐시 `자리`)."""
out = {}
for col, v in row.items():
if isinstance(v, Decimal) and v.is_finite() and text_places(v) > places_of(v):
out[col] = text_places(v)
return out
def table_places(table: dict) -> list | None:
"""표 줄마다 `row_places`(끝 0 없는 줄 = None) · 표 통째 끝 0 없음 = None."""
got = [row_places(r) if isinstance(r, dict) else {} for r in table.get("줄") or []]
return [x or None for x in got] if any(got) else None
def table_value_places(link: dict, value, evaluate, get_table) -> int | None:
"""표 값의 원문 글자 자리 — 지금 조건으로 고른 줄(`find`)의 그 칸 글자 ·
값이 그 줄 값과 같을 때만(사용자가 바꾼 값 = None) ·
`evaluate(식 나무)` = 조건 값 · `get_table(키)` = 표(못 읽으면 None)."""
import master_doc as md
import master_doc_link as ml
ref, col = str(link.get("표") or ""), link.get("칸")
if not ref or not col or "{" in ref:
return None
conds = {}
for c, t in (link.get("조건") or {}).items():
try:
n = md.parse(t)
except md.DocError:
continue
conds[c] = evaluate(n)
try:
table = get_table(ref)
row = ml.find(table, conds, col) if table else None
except Exception: # noqa: BLE001 — 그림용 · 못 찾으면 자료 수 그대로
return None
if not row or dec(row.get(col)) is None or dec(row.get(col)) != dec(value):
return None
return row_places(row).get(col)
def kind_of(doc: dict, name: str, var: dict | None = None) -> str:
"""값 갈래 — 식 · 표 · 입력 · 요소."""
if any(str(x.get("기호") or "") == name for x in doc.get("식") or []):
return "식"
kind = ((var or {}).get("연결") or {}).get("갈래")
if kind == "표":
return "표"
if kind in ("입력", "선택"):
return "입력"
return "요소" if var is not None else "식"
def show(v, kind: str = "요소", name: str = "", unit: str = "", places: int | None = None) -> str:
"""보이는 수 글 — `places` = 표 원문 글자 자리(모르면 None) · 수가 아니면 글 그대로."""
if v is None or v == "":
return ""
if isinstance(v, bool):
return "true" if v else "false"
d = dec(v)
if d is None:
return str(v)
if kind == "표":
p = max(places or 0, places_of(d))
return fmt(d, p, p) if p <= RULE["plain"] else fmt(d, 0, RULE["plain"])
if kind != "식":
return fmt(d, 0, RULE["plain"])
if name in RULE["symbol"]:
return fmt(d, 0, RULE["symbol"][name])
if str(unit or "").strip().startswith("원") or name in RULE["money_names"]:
return fmt(d, 0, RULE["money"])
if d == d.to_integral_value():
return fmt(d, 0, 0)
hi = max(RULE["min"], min(RULE["max"], RULE["sig"] - 1 - d.adjusted()))
return fmt(d, RULE["min"], hi)
def source(doc: dict, name: str, evaluate) -> str:
"""값이 온 기호 — 식 줄이 기호 하나(만약 = 지금 탄 갈래)면 그 기호로 따라감 ·
`evaluate(식 나무)` = 그림용 값(모르면 None)."""
import master_doc as md
lines = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []}
at = name
for _ in range(8):
if at not in lines:
break
try:
n = md.parse(lines[at])
except md.DocError:
return at
while n and n[0] == "call" and n[1] == "만약" and len(n[2]) == 3:
t = evaluate(n[2][0])
if t is None:
return at
n = n[2][1 if t else 2]
if not n or n[0] != "var" or n[1] == at:
return at
at = n[1]
return at
def show_value(doc: dict, name: str, v, evaluate, get_table, unit: str | None = None) -> str:
"""문서 기호 값 글 한 벌(짝 TS `showValue`) — 값이 온 기호의 갈래 · 표 원문 글자 자리 · 단위."""
import master_doc as md
src = source(doc, name, evaluate)
var = next((x for x in doc.get("변수") or [] if md.var_id(x) == src), None)
kind = kind_of(doc, src, var)
places = None
if kind == "표" and var is not None:
places = table_value_places(var.get("연결") or {}, v, evaluate, get_table)
return show(v, kind, src, str((var or {}).get("단위") or "") if unit is None else unit, places)
@@ -5,15 +5,17 @@
브라우저가 같은 계산기(`common_util_formula_doc_calc.ts`)로 네트워크 없이 다시 셈.
화면 짝 = `common_util/common_util_formula_doc_cache.ts`(기록 → `DocLinks`).
- 요소 = 부른 꼴(payload) 그대로 + {값 | 빈 | 끊김}
- 표 = 표 통째(조건 · 값칸 · 줄) — 옵션 · 입력이 바뀌어도 화면이 줄을 찾음 · 표 아님 = {끊김}
- 표 = 표 통째(조건 · 값칸 · 줄) — 옵션 · 입력이 바뀌어도 화면이 줄을 찾음 · 표 아님 = {끊김} ·
줄마다 원문 글자 자리 `자리`(859-3)
- 단가산출 = 문서 통째(없으면 null)
`prefetch` = 식 · 옵션과 무관하게 글로 적힌 표 · 단가산출 키를 미리 담음(구멍 `{…}` 든 키는 셈 때만).
"""
from __future__ import annotations
import master_doc_calc as mc
import master_base as mf # 바탕 기반(색인 · 오류)
import master_doc_calc as mc
import master_doc_digits as mdd
class Rec:
@@ -52,6 +54,10 @@ class Rec:
return
keep = ("키", "원문번호", "이름", "조건", "범위규칙", "값칸", "줄")
self.표[ref] = {k: table[k] for k in keep if k in table}
if places := mdd.table_places(
table
): # 859-3 줄마다 원문 글자 자리(끝 0 · 화면이 수로 받으면 잃음)
self.표[ref]["자리"] = places
def table(self, p: dict):
self.see_table(str(p.get("표")))
@@ -9,7 +9,8 @@
`common_util/common_util_formula_doc_view.ts`(`offLine` — 선택으로 꺼진 줄).
금액 줄 = 「이름 : 단가 원/단위 × 수량 단위 = 금액 원」 · 묶음 줄 = 비목마다 「노무비 : …」 ·
계 = 「노무비 : 줄 + 줄 = 금액 원」 · 「합계 : 금액 원」.
수 꼴 = 화면과 같음 — 단가 · 수량 = `eqText`(소수 여섯 자리까지 · 셈 값 그대로) ·
수 꼴 = 화면과 같음 — 단가 · 수량 = 보이는 자리 규칙(859-3 · `master_doc_digits` ·
짝 `common_util_show_digits.ts`) ·
줄 금액 = 소수 한 자리 · 비목 · 합계 = 원(셈 답의 끝수 그대로 · 여기서 자르지 않음).
옮기지 않은 것(화면만) — 식 조판(KaTeX · 수량 식은 값 하나로) · 공식 줄 · 펼침 ·
작업량 줄(846-2) · 굳은 기계 이름(847-1) · 비목곱 인수 글(848-7 · 금액은 답 그대로) ·
@@ -23,6 +24,7 @@ from decimal import ROUND_FLOOR, ROUND_HALF_UP, Decimal, InvalidOperation
import master_doc as md
import master_doc_calc as mc
import master_doc_digits as mdd
COSTS = md.COSTS # 노무비 · 재료비 · 경비
COST_SHOW = {"노무비": "노무비", "재료비": "재료비", "경비": "경 비"}
@@ -211,6 +213,24 @@ def _num(v) -> Decimal | None:
return _dec(v)
def _table_of(links):
"""연결의 마스터 표 읽기(`Links.master` · 기록 `Rec.links.master`) — 없으면 None."""
master = getattr(links, "master", None) or getattr(
getattr(links, "links", None), "master", None
)
return master.get if master is not None else (lambda ref: None)
def shown(doc: dict, node, v, look: "_Look", links, money: bool = False) -> str:
"""금액 줄 단가 · 수량 값 글(859-3) — 기호 하나 = 그 변수 갈래 규칙(표 = 원문 글자 자리) ·
상수 = 자료 그대로 · 식 = 식 규칙(`money` = 단가 = 원 단위)."""
if node and node[0] == "var":
return mdd.show_value(doc, node[1], v, look.value, _table_of(links))
if node and node[0] == "num":
return mdd.show(v)
return mdd.show(v, "식", "", "원" if money else "")
def _u(text: str, unit: str) -> str:
return f"{text} {unit}" if unit else text
@@ -236,6 +256,7 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]:
sub = None
mu = money_units(line, node_of(line.get("단가")), node_of(line.get("수량")), pv, sub)
qty = got.get("수량")
qty_text = shown(doc, node_of(line.get("수량")), qty, look, links)
base = {
"i": i,
"이름": name,
@@ -244,8 +265,9 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]:
"꺼짐": look.off_line(line),
"합밖": bool(got.get("합밖")),
"묶음": line.get("묶음") or "",
"수량글": qty_text,
}
tail = "" if qty is None else " × " + _u(eq_text(qty), mu["qty"])
tail = "" if qty is None else " × " + _u(qty_text, mu["qty"])
if got.get("까닭") and got.get("금액") is None:
why = got["까닭"]
out.append({**base, "비목": line.get("비목"), "단가": None, "금액": None, "까닭": why,
@@ -260,12 +282,14 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]:
price = _u(eq_text(bundle.get(c)), mu["price"])
text = f"{COST_SHOW[c]} : {price}{tail} = {one(part)} {AMOUNT_UNIT}"
out.append({**base, "비목": c, "묶음줄": True, "단가": _num(bundle.get(c)),
"단가글": eq_text(bundle.get(c)),
"금액": _num(part), "글": text}) # fmt: skip
continue
amt, price = got.get("금액"), got.get("단가")
text = f"{name} : {_u(eq_text(price), mu['price'])}{tail} = {one(amt or 0)} {AMOUNT_UNIT}"
out.append({**base, "비목": line.get("비목"), "단가": _num(price), "금액": _num(amt),
"글": text}) # fmt: skip
price_text = shown(doc, node_of(line.get("단가")), price, look, links, money=True)
text = f"{name} : {_u(price_text, mu['price'])}{tail} = {one(amt or 0)} {AMOUNT_UNIT}"
out.append({**base, "비목": line.get("비목"), "단가": _num(price), "단가글": price_text,
"금액": _num(amt), "글": text}) # fmt: skip
return out
@@ -307,8 +331,8 @@ def sheet_groups(doc: dict, answer: dict, links) -> list[dict]:
if x.get("까닭"):
text = f"— {x['까닭']}"
else:
price = "—" if x["단가"] is None else _u(eq_text(x["단가"]), mu["price"])
qty = "" if x["수량"] is None else " * " + _u(eq_text(x["수량"]), mu["qty"])
price = "—" if x["단가"] is None else _u(x["단가글"], mu["price"])
qty = "" if x["수량"] is None else " * " + _u(x["수량글"], mu["qty"])
text = f"{price}{qty} = {one(x['금액'] or 0)}"
groups[c].append(
{
+3 -3
View File
@@ -6,13 +6,13 @@
"daega_inputs": "8b605fa95c5b9db4",
"수요": "23b0132a8a7f46f7",
"산근 값": "6072e1180a1b81e7",
"산근 글": "f5b884a2c49c91c6",
"산근 글": "82f35a5c891bab99",
"산근 관급 값": "6568e5cf9322b81c",
"산근 관급 글": "9397c1d1a5fe0dcd",
"산근 관급 글": "534a307c49079bfd",
"미리보기 hand:rate 값": "091690571b7dc54b",
"미리보기 hand:rate 글": "d17615784f25e4f5",
"미리보기 hand:pick 값": "6c7f426d37e31998",
"미리보기 hand:pick 글": "7836022de46b3072",
"미리보기 hand:pick 글": "ab9a393d7a550b0a",
"미리보기 hand:net 값": "e2809bd3259438b0",
"미리보기 hand:net 글": "0254ea22d7a23e43",
"B08 단위수량": "896710398b04b4fd"
@@ -41,7 +41,10 @@ const { loadForm } = loadTs(path.join(B05, "B05_Profile_UI_Structures_Panel_Comm
const entry = (required, value) => ({ required, isEmpty: () => value === "" });
// 동작 = 정의 종류 덧칸(앱의 `withDefinition` 과 같음 · 323-7 종류 키 대신 동작 이름)
const DEFINED = JSON.parse(
fs.readFileSync(path.join(ROOT, "resources", "master_template", "구조물정의.json"), "utf8"),
fs.readFileSync(
path.join(ROOT, "resources", "master_data", "구조물정의", "구조물정의.json"),
"utf8",
),
);
const behaviors = (typeId) => DEFINED.종류?.[typeId]?.동작 ?? [];
const type = (type_id, managed_by = null) => ({
+4 -1
View File
@@ -35,7 +35,10 @@ const { fordHeightM } = loadTs(
// 동작 = 정의 종류 덧칸(앱의 `withDefinition` 과 같음 · 323-7 종류 키 대신 동작 이름)
const DEFINED = JSON.parse(
fs.readFileSync(path.join(ROOT, "resources", "master_template", "구조물정의.json"), "utf8"),
fs.readFileSync(
path.join(ROOT, "resources", "master_data", "구조물정의", "구조물정의.json"),
"utf8",
),
);
const type = (type_id) => ({
type_id,
@@ -63,7 +63,10 @@ const ids = loadTs(path.join(design, "design_pipe_ids.ts"));
const { useDesignStore } = loadTs(path.join(design, "design_store.ts"));
const { readState } = loadTs(path.join(ROOT, "A00_Common", "b_page_state.ts"));
const TYPES = JSON.parse(
fs.readFileSync(path.join(ROOT, "resources", "master_template", "구조물정의.json"), "utf8"),
fs.readFileSync(
path.join(ROOT, "resources", "master_data", "구조물정의", "구조물정의.json"),
"utf8",
),
).types;
/** 가짜 종단도 — 받은 것 · 편집 옮김 기록. */
@@ -60,7 +60,7 @@ function load(full) {
const P = (...a) => path.join(ROOT, ...a);
const D = load(P("B06_Section", "B06_Section_Section_Drafts.ts"));
const def = JSON.parse(
fs.readFileSync(P("resources", "master_template", "구조물정의.json"), "utf8"),
fs.readFileSync(P("resources", "master_data", "구조물정의", "구조물정의.json"), "utf8"),
);
S.types = def.types.map((t) => ({
type_id: t.type_id,
+4 -1
View File
@@ -12,7 +12,10 @@ const ROOT = path.join(__dirname, "..", "..");
const B05 = (name) => path.join(ROOT, "B05_Profile", `${name}.ts`);
const B06 = (name) => path.join(ROOT, "B06_Section", `${name}.ts`);
const TYPES = JSON.parse(
fs.readFileSync(path.join(ROOT, "resources", "master_template", "구조물정의.json"), "utf8"),
fs.readFileSync(
path.join(ROOT, "resources", "master_data", "구조물정의", "구조물정의.json"),
"utf8",
),
).types;
class FakeStorage {
+4 -4
View File
@@ -1,4 +1,4 @@
/* PLAN 322-2 구조물 표 검사 · 편집 헬퍼 — 진짜 `M02_SO_Def_Check.ts` · `M02_SO_Def_Reflect.ts` ·
/* PLAN 322-2 구조물 표 검사 · 편집 헬퍼 — 진짜 `M01_SO_Def_Check.ts` · `M01_SO_Def_Reflect.ts` ·
* `design_structure_spec.ts` 를 그 자리에서 트랜스파일해 Node 로 돌림 · 결과 = 표준출력 JSON 한 벌.
* 입력 = argv[2] JSON `{cases: {이름: [정의, 앞 판|null]}, definition}`. 짝 = `test_322_2_check_mirror.py`.
*/
@@ -33,9 +33,9 @@ function load(file) {
return box.exports;
}
const SO = (name) => path.join(ROOT, "M02_MasterTemplete", "StructOptions", `${name}.ts`);
const check = load(SO("M02_SO_Def_Check"));
const reflect = load(SO("M02_SO_Def_Reflect"));
const SO = (name) => path.join(ROOT, "M01_MasterData", "StructOptions", `${name}.ts`);
const check = load(SO("M01_SO_Def_Check"));
const reflect = load(SO("M01_SO_Def_Reflect"));
const spec = load(path.join(ROOT, "A00_Common", "design", "logic", "design_structure_spec.ts"));
const { STRUCTURE_SPECS } = load(
path.join(ROOT, "A00_Common", "design", "logic", "design_structure_pipe.ts"),
+4 -1
View File
@@ -8,7 +8,10 @@ const path = require("path");
const ROOT = path.join(__dirname, "..", "..");
const ts = require(path.join(ROOT, "config", "node_modules", "typescript"));
const DEF = JSON.parse(
fs.readFileSync(path.join(ROOT, "resources", "master_template", "구조물정의.json"), "utf8"),
fs.readFileSync(
path.join(ROOT, "resources", "master_data", "구조물정의", "구조물정의.json"),
"utf8",
),
);
const TYPES = DEF.types.map((t) => ({ managed_by: null, enabled: true, ...t }));

Some files were not shown because too many files have changed in this diff Show More