Merge remote-tracking branch 'origin/main_laptop_1' into sub_laptop_2

This commit is contained in:
2026-11-17 21:29:00 +09:00
50 changed files with 539 additions and 647 deletions
+64
View File
@@ -0,0 +1,64 @@
/* formula_doc_foot.css — 수식 화면 맨 아래 합계 상자(PLAN 737-1 · 803-2a · 856-4 — M01 LogicLab_Style 에서 옮김) */
.m01lab__total {
margin: var(--spacing-8) 0 0;
font-weight: 700;
text-align: right;
}
/* 737-1 맨 아래 한 줄 4 칸(노무비 · 재료비 · 경비 · 계) — 화면(모달) 바닥에 붙음 · 칸마다 이름 위 · 값 아래 */
.m01lab__foot {
position: sticky;
bottom: 0;
z-index: 2;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: var(--spacing-8);
margin-top: var(--m01lab-box-gap, var(--spacing-12));
padding: var(--spacing-8) var(--spacing-12);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
background: var(--color-surface-raised);
}
/* 합계 줄이 화면 바닥에 붙으려면 메인 칸이 굴림 칸(overflow:auto)이 아니어야 함 — 메인은 높이가 안 묶여 안 굴렀음 */
.ui-workflow-layout__main:has(.m01lab__foot) {
overflow: clip;
}
.m01lab__sums {
display: contents;
}
.m01lab__foot .ui-calc-row {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 0;
min-height: 0;
}
.m01lab__foot .ui-calc-row > :empty {
display: none;
}
.m01lab__foot .ui-calc-row__out {
padding: 0;
text-align: left;
}
.m01lab__foot .m01lab__total {
display: flex;
flex-direction: column;
margin: 0;
text-align: left;
}
.m01lab__foot .m01lab__total > :first-child {
color: var(--color-text-secondary);
font-weight: var(--font-weight-regular, 400);
}
.m01lab__foot .m01lab__total > :last-child {
font-variant-numeric: tabular-nums;
}
+38 -9
View File
@@ -1,20 +1,49 @@
/* =============================================================================
* formula_doc_foot.ts
* 수식 탭 맨 아래 합계 상자(PLAN 803-2a · 요구 667-2) — 단가산출 상세 탭과 같은 부품(`buildFoot` · 노무비 · 재료비 · 경비 · 계)
* 값 = 계산기 셈 그대로(여기서 다시 셈 안 함) · 셈 못 함 = 「—」
* 수식 탭 맨 아래 합계 상자(PLAN 803-2a · 요구 667-2 · 737-1) — 노무비 · 재료비 · 경비 · 계 네 칸 · 화면(모달) 바닥에 붙음
* 값 = 계산기 셈 그대로(여기서 다시 셈 안 함) · 셈 못 함 = 「—」 · 856-4 = M01 `LogicLab_Foot` 을 여기로(쓰는 곳 하나)
* ========================================================================== */
import { createCalcFormulaRow } from "@ui/ui_template_calc_row";
import { el } from "@ui/ui_template_elements";
import { formatMoney } from "../common_util/common_util_money";
import type { DocAnswer } from "../common_util/common_util_formula_doc_calc";
import { buildFoot } from "../M01_MasterData/M01_MasterData_UI_LogicLab_Foot";
import "../M01_MasterData/M01_MasterData_UI_LogicLab_Style.css";
import { ft } from "./formula_doc_text";
import "./formula_doc_foot.css";
const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
const PARTS = [
["labor", "노무비"],
["material", "재료비"],
["cost", "경비"],
] as const;
export function docFoot(a: DocAnswer): HTMLElement {
const done = !!a.셈됨 && typeof a.계 === "number";
return buildFoot(
{ labor: num(a.노무비), material: num(a.재료비), cost: num(a.경비) },
done,
num(a.계),
);
const sums = { labor: num(a.노무비), material: num(a.재료비), cost: num(a.경비) };
const total = num(a.계);
const cells = PARTS.map(([k, label]) => {
const out = el("span", {
className: "ui-calc-row__out is-key",
text: done ? formatMoney(sums[k]) : "—",
});
const row = createCalcFormulaRow(label, null, out);
row.dataset.group = k;
row.dataset.subtotal = done ? String(sums[k]) : "";
return row;
});
return el("div", {
className: "m01lab__foot",
children: [
el("div", { className: "m01lab__sums", children: cells }),
el("p", {
className: "m01lab__total",
attrs: { "data-sum": done ? String(total) : "" },
children: [
el("span", { text: `${ft("Sum")} ` }),
el("span", { text: done ? formatMoney(total) : "—" }),
],
}),
],
});
}
+6 -3
View File
@@ -56,7 +56,7 @@ import {
unswap,
} from "../common_util/common_util_line_stack_pick";
import { shownUnitOf, type TableLook } from "../common_util/common_util_line_stack_unit";
import { createUnitPick, NO_UNIT } from "../M02_MasterTemplete/DataFlow/M02_DF_UnitPick";
import { createUnitPick, NO_UNIT } from "@ui/ui_template_unit_pick";
import { hiddenByWork, reach } from "./formula_doc_render";
import { attachDrag } from "./line_stack_drag";
import type { WorkSpec } from "../common_util/common_util_formula_doc_work";
@@ -64,7 +64,7 @@ import { openMachineWindow, type MachineCtx } from "./line_stack_machine";
import { dropCover } from "../common_util/common_util_formula_doc_cover_drop";
import { buildMachineCtl, lineCall } from "./line_stack_machine_ctl";
import { putWork, swapMachine } from "./line_stack_machine_work";
import { openStackPick, type StackTake } from "./line_stack_pick";
import { openStackPick, type StackFind, type StackTake } from "./line_stack_pick";
import { buildBlock, sourceTag } from "./line_stack_rows";
import { lt, type LsKey } from "./line_stack_text";
@@ -99,6 +99,8 @@ export interface EditHooks {
upper?: Cover | null;
/** 848-3 M01 기초 제어 구역 엶(시스템 관리자) — M02 = 층(`machine.scope`)이 엶 */
ctlEdit?: boolean;
/** 856-4 찾아 넣기 창(페이지가 넘김) */
find: StackFind;
}
const field = (
@@ -229,7 +231,7 @@ function moneyBody(h: EditHooks, i: number): HTMLElement[] {
query,
pick: fixed ? swapFixed : swap,
})
: openStackPick(kind, swap, undefined, query),
: openStackPick(h.find, kind, swap, undefined, query),
});
pick.classList.add("lstk-res");
pick.title = `${lt("Repick")}${res ? ` — ${res}` : ""}`;
@@ -406,6 +408,7 @@ function readQty(text: string, note: string, tag: string): HTMLElement {
function addLine(h: EditHooks, at: number, kind: string): void {
if (["인력", "재료", "기계", "단가산출"].includes(kind))
return openStackPick(
h.find,
kind as MoneyKind,
(p) => h.change((d, items) => void addPicked(d, items[at], kind as MoneyKind, p)),
h.take,
+1 -1
View File
@@ -14,7 +14,7 @@ import { openModal } from "@ui/ui_template_modal";
import { createText } from "@ui/ui_template_text";
import { isDraftNo, type DraftItem } from "../common_util/common_util_line_stack_draft";
import type { Picked } from "../common_util/common_util_line_stack_pick";
import { call, type Layer } from "../M02_MasterTemplete/M02_MasterTemplete_Api_Fetch";
import { call, type Layer } from "../common_util/common_util_m02_call";
import {
listMyMachines,
machineArg,
+66
View File
@@ -0,0 +1,66 @@
/* =============================================================================
* line_stack_machine_cell.ts
* 기계 제어 구역 칸 부품(PLAN 856-4) — 수 칸 · 「바뀜」 표시(출처 테두리 · 원래 값 풍선)
* 제어 구역(`line_stack_machine_ctl`) · 작업량 묶음(`line_stack_machine_work`)이 같이 씀 — 둘이 서로 부르던 고리 끊음
* ========================================================================== */
import { setUiDiff, type UiDiff } from "@ui/ui_template_button";
import { el, showToast } from "@ui/ui_template_elements";
import { createInputField } from "@ui/ui_template_input";
import { MINE, type Source } from "../common_util/common_util_formula_doc_cover";
import { lt } from "./line_stack_text";
/** 출처(848-3) — 나 · 위 층. 테두리는 나만(892) · 풍선(원래 값)은 둘 다 */
export type DiffSrc = UiDiff | "upper";
export const diffOf = (src: Source | undefined): DiffSrc | null =>
src === undefined ? null : src === MINE ? "mine" : "upper";
/** 칸 묶음 안 입력 · 고르기 · 이름 단추에 「바뀜」 상태(나만) · 풍선(원래 값) */
export function markDiff(box: HTMLElement, diff: DiffSrc | null, was?: string): void {
const own = ["ui-input", "ui-select", "ui-btn"].some((c) => box.classList.contains(c));
const nodes = own ? [box] : ["ui-input", "ui-select", "lstk-res"].flatMap((c) => [...box.querySelectorAll<HTMLElement>(`.${c}`)]); // prettier-ignore
for (const n of nodes) {
setUiDiff(n, diff === "mine" ? "mine" : null);
if (diff && was !== undefined)
n.title = `${n.title ? `${n.title} — ` : ""}${lt("Ctl_Was")} ${was}`;
}
}
const num = (t: string): number | null => {
const n = Number(t.trim().replace(/,/g, ""));
return t.trim() !== "" && Number.isFinite(n) ? n : null;
};
/** 수 칸 — 빈 글 = 원래대로(null) · 음수 · 글 = 알림 · 단위 = 칸 바로 뒤(공식 묶음 값 칸과 같은 자리 · 845-2 ㉥) */
export function numBox(
label: string,
value: unknown,
unit: string,
ro: boolean,
set: (n: number | null) => void,
hint = "",
): HTMLElement {
const f = createInputField({
value: value === undefined || value === null ? "" : String(value),
placeholder: hint,
compact: true,
size: 24,
});
f.root.classList.add("lstk-f-s");
f.input.setAttribute("aria-label", label);
f.input.title = label;
f.input.disabled = ro;
f.input.addEventListener("change", () => {
const t = f.input.value;
const n = num(t);
if (t.trim() === "") return set(null);
if (n === null || n < 0) {
f.input.value = value === undefined || value === null ? "" : String(value);
return void showToast(lt("Ctl_Bad"), "warning");
}
set(n);
});
return unit
? el("span", { className: "lstk-qty", children: [f.root, el("span", { className: "lstk-unit", text: unit })] }) // prettier-ignore
: f.root;
}
+12 -65
View File
@@ -16,10 +16,10 @@
* 「고침」 글 배지 없음(테두리로) · 칸 풍선 = 원래 값 · M01 기초(시스템 관리자) = ① 없음 → 기초 고침 = 「나」
* ========================================================================== */
import { createButton, createIconButton, setUiDiff, type UiDiff } from "@ui/ui_template_button";
import { createButton, createIconButton } from "@ui/ui_template_button";
import { eqText } from "@ui/ui_template_equation";
import { el, showToast } from "@ui/ui_template_elements";
import { createInputField, createSelectField } from "@ui/ui_template_input";
import { el } from "@ui/ui_template_elements";
import { createSelectField } from "@ui/ui_template_input";
import { varId, type FormulaDoc, type Link } from "../common_util/common_util_formula_doc";
import { WORK, workKey, type WorkCover } from "../common_util/common_util_formula_doc_work";
import type { DocAnswer } from "../common_util/common_util_formula_doc_calc";
@@ -28,7 +28,6 @@ import {
defaultsOf,
layeredCover,
machineKey,
MINE,
partsOf,
putCover,
rowEntry,
@@ -38,7 +37,6 @@ import {
type CrewRow,
type CoverEntry,
type MiscRow,
type Source,
} from "../common_util/common_util_formula_doc_cover";
import { subInputs, type StackDoc } from "../common_util/common_util_line_stack";
import type { Picked } from "../common_util/common_util_line_stack_pick";
@@ -46,9 +44,9 @@ import { machineUnit } from "../common_util/common_util_line_stack_unit";
import { attachHost, workAt, workOfMachine } from "../common_util/common_util_line_stack_work";
import { sites, type WorkSpec } from "../common_util/common_util_formula_doc_work";
import { machineCellName } from "../common_util/common_util_machine_symbol_name";
import { openFindPicker } from "../M02_MasterTemplete/M02_MasterTemplete_Find_Pick";
import { buildWorkGroup, putWork } from "./line_stack_machine_work";
import { openStackPick } from "./line_stack_pick";
import { openStackPick, type StackFind } from "./line_stack_pick";
import { diffOf, markDiff, numBox } from "./line_stack_machine_cell";
import { lt } from "./line_stack_text";
export interface CtlHooks {
@@ -69,22 +67,8 @@ export interface CtlHooks {
work?: (machine: string) => WorkSpec[];
/** 848-3 ① 위 층 고침(SK 읽기 답 `위덮음` · M01 = 없음) */
upper?: Cover | null;
}
/** 출처(848-3) — 나 · 위 층. 테두리는 나만(892) · 풍선(원래 값)은 둘 다 */
export type DiffSrc = UiDiff | "upper";
export const diffOf = (src: Source | undefined): DiffSrc | null =>
src === undefined ? null : src === MINE ? "mine" : "upper";
/** 칸 묶음 안 입력 · 고르기 · 이름 단추에 「바뀜」 상태(나만) · 풍선(원래 값) */
export function markDiff(box: HTMLElement, diff: DiffSrc | null, was?: string): void {
const own = ["ui-input", "ui-select", "ui-btn"].some((c) => box.classList.contains(c));
const nodes = own ? [box] : ["ui-input", "ui-select", "lstk-res"].flatMap((c) => [...box.querySelectorAll<HTMLElement>(`.${c}`)]); // prettier-ignore
for (const n of nodes) {
setUiDiff(n, diff === "mine" ? "mine" : null);
if (diff && was !== undefined)
n.title = `${n.title ? `${n.title} — ` : ""}${lt("Ctl_Was")} ${was}`;
}
/** 856-4 찾아 넣기 창(페이지가 넘김) */
find: StackFind;
}
const FUELS = ["경유", "휘발유", "실내등유"];
@@ -120,45 +104,6 @@ export function ctlOf(h: CtlHooks, link: Link | undefined, at?: number) {
return { machine, sub, vals, base, up, top: upperOf(base, up), entry: coverOf(h.doc)[machine] };
}
const num = (t: string): number | null => {
const n = Number(t.trim().replace(/,/g, ""));
return t.trim() !== "" && Number.isFinite(n) ? n : null;
};
/** 수 칸 — 빈 글 = 원래대로(null) · 음수 · 글 = 알림 · 단위 = 칸 바로 뒤(공식 묶음 값 칸과 같은 자리 · 845-2 ㉥) */
export function numBox(
label: string,
value: unknown,
unit: string,
ro: boolean,
set: (n: number | null) => void,
hint = "",
): HTMLElement {
const f = createInputField({
value: value === undefined || value === null ? "" : String(value),
placeholder: hint,
compact: true,
size: 24,
});
f.root.classList.add("lstk-f-s");
f.input.setAttribute("aria-label", label);
f.input.title = label;
f.input.disabled = ro;
f.input.addEventListener("change", () => {
const t = f.input.value;
const n = num(t);
if (t.trim() === "") return set(null);
if (n === null || n < 0) {
f.input.value = value === undefined || value === null ? "" : String(value);
return void showToast(lt("Ctl_Bad"), "warning");
}
set(n);
});
return unit
? el("span", { className: "lstk-qty", children: [f.root, el("span", { className: "lstk-unit", text: unit })] }) // prettier-ignore
: f.root;
}
const kind = (text: string): HTMLElement => el("span", { className: "lstk-kind", text });
/** 기계 제어 구역 — `link` = 그 기계 줄 단가 기호 연결 · `at` = 그 금액 줄 차례(작업량) */
@@ -243,7 +188,7 @@ export function buildMachineCtl(
lt("K_인력"),
crewName(r, i),
ro,
() => openStackPick("인력", (p) => setCrew(swapAt(crew, i, { ...r, 키: p.키, 이름: p.이름 })), undefined, crewName(r, i)), // prettier-ignore
() => openStackPick(h.find, "인력", (p) => setCrew(swapAt(crew, i, { ...r, 키: p.키, 이름: p.이름 })), undefined, crewName(r, i)), // prettier-ignore
[numBox(lt("Ctl_Crew_Qty"), r.인, lt("Ctl_Per_Day"), ro, (n) => setCrew(swapAt(crew, i, { ...r, 인: n ?? 0 })))], // prettier-ignore
"노무비",
() => setCrew(crew.filter((_, k) => k !== i)),
@@ -265,7 +210,7 @@ export function buildMachineCtl(
return [r.줄, fuel].filter(Boolean).join(" · ");
};
const pickMat = (done: (p: Picked) => void, query: string): void =>
openFindPicker({
h.find({
layer: "system",
owner: null,
title: `${lt("Find_Title")} — ${lt("Ctl_Misc")}`,
@@ -363,7 +308,9 @@ export function buildMachineCtl(
lt("Ctl_Crew"),
entry.조종원 !== undefined,
() =>
openStackPick("인력", (p) => setCrew([...crew, { 키: p.키, 이름: p.이름, 인: 1 }])),
openStackPick(h.find, "인력", (p) =>
setCrew([...crew, { 키: p.키, 이름: p.이름, 인: 1 }]),
),
() => put({ ...entry, 조종원: undefined }),
ro,
),
+4
View File
@@ -69,6 +69,7 @@ import { sheetWorkCard, sheetWorkOut, type SheetWorkOpts } from "./line_stack_ma
import { buildOut } from "./line_stack_out";
import "./line_stack.css";
import "./line_stack_machine_sheet.css";
import type { StackFind } from "./line_stack_pick";
export interface MachineSimilar {
key: string;
@@ -91,6 +92,8 @@ export interface MachineSheetOptions {
findSimilar?: (q: string) => Promise<MachineSimilar[]>;
onSimilar?: (item: MachineSimilar) => void;
onChange?: () => void;
/** 856-4 찾아 넣기 창(조종원 · 잡품 고르기 — 페이지가 넘김) */
find: StackFind;
}
export interface MachineSheetState {
@@ -287,6 +290,7 @@ export function createMachineSheet(o: MachineSheetOptions) {
readOnly: ro,
lists: () => engineVals(orig, mine),
lock,
find: o.find,
},
{ ...link, 키: info.키 },
);
+1 -1
View File
@@ -47,7 +47,7 @@ import type { Picked } from "../common_util/common_util_line_stack_pick";
import type { Values } from "../common_util/common_util_formula_doc_view";
import { varUnit } from "../common_util/common_util_line_stack_unit";
import { workUnit } from "../common_util/common_util_line_stack_work";
import { diffOf, markDiff, numBox, type DiffSrc } from "./line_stack_machine_ctl";
import { diffOf, markDiff, numBox, type DiffSrc } from "./line_stack_machine_cell";
import { lt } from "./line_stack_text";
import { workRows } from "./line_stack_work";
+1 -1
View File
@@ -12,7 +12,7 @@ import { showToast } from "@ui/ui_template_elements";
import { askConfirm } from "@ui/ui_template_modal";
import type { FormulaDoc } from "../common_util/common_util_formula_doc";
import type { Picked } from "../common_util/common_util_line_stack_pick";
import { call, type Layer } from "../M02_MasterTemplete/M02_MasterTemplete_Api_Fetch";
import { call, type Layer } from "../common_util/common_util_m02_call";
import { at } from "../M02_MasterTemplete/M02_MasterTemplete_Hopyo_Api";
import { placeNote } from "../M01_MasterData/M01_MasterData_Api_Fetch";
import type { MachineCtx } from "./line_stack_machine";
+41 -5
View File
@@ -1,7 +1,8 @@
/* =============================================================================
* line_stack_pick.ts
* 줄 쌓기 고르기 창(PLAN 804-3 · 804-4 · 요구 678-1 · 678-3 · 680-1 · 681)
* 찾아 넣기 = M02 [항목 추가] 창 그대로(`openFindPicker` · 탭 M01 전체 · 찾기 칸 · 표) — 줄 갈래마다 그 종류만
* 찾아 넣기 = M02 [항목 추가] 창 그대로(`openFindPicker` · 탭 M01 전체 · 찾기 칸 · 표) — 줄 갈래마다 그 종류만 ·
* 창은 페이지가 넘김(`StackFind` · 856-4 — 공용 화면은 M02 를 부르지 않음)
* 인력(노임 LB) · 재료(자재 MT) · 기계(EQ → 시간당 경비 로직 + 기계='원문번호') · 다른 단가산출(M01 단가산출 로직)
* 기계 + M02 개인 층(821-3) = 품셈 기계 위 「내 기계」 묶음 · 머리 [새 기계 만들기] — 고름 = 로직 + 기계='개인 EQP…'
* 재료 + M02 개인 층(840-4) = M01 재료 위 「내 재료」 묶음 — 고름 = 요소 PM 키(M01 재료와 같은 꼴)
@@ -22,11 +23,45 @@ import type { DocTable } from "../common_util/common_util_formula_doc_table";
import type { MoneyKind } from "../common_util/common_util_line_stack";
import type { Picked } from "../common_util/common_util_line_stack_pick";
import { showToast } from "@ui/ui_template_elements";
import type { Layer } from "../M02_MasterTemplete/M02_MasterTemplete_Api_Fetch";
import { openFindPicker, type FindKind } from "../M02_MasterTemplete/M02_MasterTemplete_Find_Pick";
import type { Layer } from "../common_util/common_util_m02_call";
import { lt } from "./line_stack_text";
const KINDS: Partial<Record<MoneyKind, FindKind>> = {
/** 찾아 넣기 종류 — logic = M01 단가산출 · 기초 · labor = 인력 · material = 재료 · machine = 기계 · oil = 유가 · sk = M02 단가산출 · pre = 일위대가 */
export type StackFindKind = "logic" | "labor" | "material" | "machine" | "oil" | "sk" | "pre";
/** 고른 M01 요소 중 공용 화면이 읽는 칸 */
interface FoundElement {
코드: string;
이름: string;
규격: string;
단위: string;
/** 기계(804-3) — 시간당 경비 로직 키 · 기종 원문번호 */
로직?: string;
원문번호?: string;
}
/** 찾아 넣기 창 옵션 — 공용 화면이 쓰는 칸만(M02 `FindPickOptions` 와 같은 뜻) */
export interface StackFindOptions {
layer: Layer;
owner: string | null;
title?: string;
kinds?: StackFindKind[];
query?: string;
/** 돈 아닌 기초(작업량 등 결과)만 */
results?: boolean;
logic: (x: { 키: string; 이름: string; 결과단위: string }) => void;
ref?: (r: { 층: string; 주인: string | null; 키: string }) => void;
element?: (e: FoundElement) => void;
machine?: (e: FoundElement) => void;
oil?: (e: FoundElement) => void;
mine?: { owner: string | null };
mineMat?: { owner: string | null };
}
/** 찾아 넣기 창(856-4) — 페이지가 넘김(M01 · M02 = M02 `openFindPicker`) */
export type StackFind = (o: StackFindOptions) => void;
const KINDS: Partial<Record<MoneyKind, StackFindKind>> = {
인력: "labor",
재료: "material",
기계: "machine",
@@ -44,6 +79,7 @@ export interface StackTake {
/** 찾아 넣기 — 고르면 `done(고른 것)` · 닫으면 아무것도 안 함 · `m02` 있고 다른 단가산출 = 복사해 펼침 ·
* `query` = 찾기 칸에 넣고 연 결과(이름 단추 · 요구 687-9) */
export function openStackPick(
find: StackFind,
kind: MoneyKind,
done: (p: Picked) => void,
m02?: StackTake,
@@ -53,7 +89,7 @@ export function openStackPick(
if (!want) return;
const spec = (e: { 규격: string }) => (e.규격 ? { 규격: e.규격 } : {});
const copy = kind === "단가산출" && m02 ? m02 : null;
openFindPicker({
find({
layer: copy?.layer ?? "system",
owner: copy?.owner ?? null,
title: `${lt("Find_Title")} — ${lt(copy ? "K_복사" : (`K_${kind}` as never))}`,
+1 -2
View File
@@ -45,7 +45,6 @@ import {
tableAlias,
} from "../common_util/common_util_line_stack_pick";
import { shownUnitOf, unitText } from "../common_util/common_util_line_stack_unit";
import { openFindPicker } from "../M02_MasterTemplete/M02_MasterTemplete_Find_Pick";
import type { EditHooks } from "./line_stack_edit";
import { openTablePick } from "./line_stack_pick";
import { lt } from "./line_stack_text";
@@ -282,7 +281,7 @@ export function buildBlock(
variant: "ghost",
size: 24,
onClick: () =>
openFindPicker({
h.find({
layer: "system",
owner: null,
title: lt("K_단가산출"),
+5 -1
View File
@@ -70,7 +70,7 @@ import { hiddenByWork } from "./formula_doc_render";
import { ft } from "./formula_doc_text";
import { addTaken, type Taken } from "../common_util/common_util_line_stack_copy";
import { machineWork } from "../common_util/common_util_line_stack_work";
import type { Layer } from "../M02_MasterTemplete/M02_MasterTemplete_Api_Fetch";
import type { Layer } from "../common_util/common_util_m02_call";
import { applyDiff } from "./line_stack_diff";
import { buildEdit } from "./line_stack_edit";
import { openMachineWindow, type CopyAnswer, type MachineCtx } from "./line_stack_machine";
@@ -78,6 +78,7 @@ import { dropPath } from "../common_util/common_util_formula_doc_cover_drop";
import { buildOut } from "./line_stack_out";
import { lt } from "./line_stack_text";
import "./line_stack.css";
import type { StackFind } from "./line_stack_pick";
export interface StackScreenOptions {
/** 길 앞머리(`/m01/logic/doc`) — GET ?key · POST /preview · /save · /links */
@@ -94,6 +95,8 @@ export interface StackScreenOptions {
tools?: HTMLElement;
/** 저장 전 SK 문서(836-5 · 불러오기 미리 보기) — 빈 키일 때 이 문서를 서버가 읽어 줌(파일 안 읽음 · 안 씀) */
memory?: () => Record<string, unknown> | null;
/** 856-4 찾아 넣기 창(M01 · M02 = M02 `openFindPicker`) — 공용 화면은 M02 를 부르지 않음 */
find: StackFind;
}
type Docs = Record<string, FormulaDoc>;
@@ -408,6 +411,7 @@ export function createStackScreen(opt: StackScreenOptions) {
...(edit() || mem()
? [
buildEdit({
find: opt.find,
doc,
answer,
items,
+13 -8
View File
@@ -139,21 +139,26 @@ def _file_for(key: str) -> str:
def built(key: str) -> dict | None:
"""빌더가 지을 그 키 문서(옛 로직 줄 변환 · `build_수식문서_802_2`) · 로직 줄 없음 · 변환 틀림 = None."""
import master_doc_convert as cv
files, whole = store.loaded()
for data in files.values():
for data in store.loaded()[0].values():
if data.get("그룹") != "로직":
continue
for row in data.get("줄") or []:
if str(row.get("키")) == key:
try:
return cv.convert(whole, row)[0]
except Exception: # noqa: BLE001 — 변환 틀림 = 빌더 문서 없음(표지 안 담)
return None
return of_row(row)
return None
def of_row(row: dict) -> dict | None:
"""로직 줄(저장 전 고친 줄도) → 빌더와 같은 변환의 수식 문서 · 변환 틀림 = None —
[로직 복사/생성] 시험 계산(855 2-B4)이 저장하면 지을 문서로 셈."""
import master_doc_convert as cv
try:
return cv.convert(store.loaded()[1], row)[0]
except Exception: # noqa: BLE001 — 변환 틀림 = 빌더 문서 없음(표지 안 담)
return None
def make(key: str) -> bool:
"""[로직 복사/생성](`Store_Make.logic_new`) 뒤 수식 문서를 지어 씀 — 빌더(`build_수식문서_802_2`)와
같은 변환 · 같은 대조(옛 엔진 = 새 계산기 · 기본 + 옵션 표본 · 부르는 단가산출이 저장본)를 지난 것만
+4 -2
View File
@@ -310,8 +310,10 @@ def post_logic_formula_save(body: FormulaLogic) -> dict:
@router.post("/logic/formula/preview")
def post_logic_formula_preview(body: FormulaPreview) -> dict:
"""저장 전 시험 계산용 — 별칭을 원문으로 되돌린 로직 줄만(저장 안 함)."""
return _call(make.logic_formula_preview, body.로직, body.별칭)
"""저장 전 시험 계산용 — 별칭을 원문으로 되돌린 로직 줄 + 저장하면 지을 수식 문서
{logic, 문서}(저장 안 함 · 화면은 `문서` 를 `/logic/doc/preview` 로 셈 · 855 2-B4)."""
got = _call(make.logic_formula_preview, body.로직, body.별칭)
return {**got, "문서": doc_screen.of_row(got["logic"])}
# ── 수식 문서(802-3) — 단가산출 기초 정본 · 화면은 같은 계산기로 즉시 셈 ──
@@ -47,6 +47,7 @@ import { buildHeadBar } from "./M01_MasterData_UI_Head";
import { fetchSessionUser } from "../A06_Login/A06_Login_Api_Fetch";
import "./M01_MasterData_UI_Logic_Style.css";
import { createEmpty } from "@ui/ui_template_empty";
import { openFindPicker } from "../M02_MasterTemplete/M02_MasterTemplete_Find_Pick";
/** 저장 안 한 로직 하나 — origKey null = 새 로직 · row null = 지움 */
interface Draft {
@@ -99,6 +100,7 @@ export async function mountM01LogicLab(
.catch(() => false);
// 수식 = 줄 쌓기(804-2 · 804-6 옛 수식 문서 탭 걷음) — 수식 문서 · 캐시 m01_doc_drafts
const stack = createStackScreen({
find: openFindPicker, // 856-4 찾아 넣기 창(M02 창 · M01 전체 탭만)
base: "/m01/logic/doc",
admin,
cache: "m01_doc_drafts",
@@ -4,7 +4,8 @@
* 줄을 고치거나 더한 뒤 자체 로직(GX)으로 저장.
*
* [본떠 만들기] → GET /logic/formula(별칭 폼) → 별칭 표 바꾸기·로직 부르기 갈래 고르기·
* 식 줄 고치기·더하기 → [시험 계산](POST /logic/formula/preview 로 원문 되돌린 뒤 /calc 재사용)
* 식 줄 고치기·더하기 → [시험 계산](POST /logic/formula/preview 가 원문으로 되돌린 줄을 수식 문서로 지어 줌 →
* 문서 셈 `/logic/doc/preview` · 855 2-B4 — 저장하면 지을 문서와 같은 변환)
* → [저장](POST /logic/formula/save) → afterSave 로 새 키를 알림(정본은 손대지 않음).
* ========================================================================== */
@@ -30,6 +31,7 @@ import { buildCalc } from "./M01_MasterData_UI_Logic_Calc";
import { fetchTables, type TableHead } from "./M01_MasterData_Api_Fetch";
import { tx } from "./M01_MasterData_UI_Logic_Text";
import { tl } from "./M01_MasterData_UI_LogicLab_Text";
import type { FormulaDoc } from "../common_util/common_util_formula_doc";
import "./M01_MasterData_UI_LogicLab_Style.css";
import { createBadge } from "@ui/ui_template_badge";
import { createText } from "@ui/ui_template_text";
@@ -263,7 +265,7 @@ export async function openCopyScreen(opt: CopyOptions): Promise<void> {
const aliasHost = el("div", { className: "m01-logic__scroll" });
const linesHost = el("div", { className: "m01-logic__scroll" });
const calcHost = el("div", { className: "m01lab__calc" });
const values: Record<string, string> = {};
const given: Record<string, unknown> = {}; // 시험 계산에서 고른 옵션 — 줄을 고쳐도 남음
let timer: number | undefined;
const refreshCalc = (): void => {
@@ -272,15 +274,9 @@ export async function openCopyScreen(opt: CopyOptions): Promise<void> {
};
const runPreview = async (): Promise<void> => {
try {
const preview = await previewLogicFormula(row, marks);
buildCalc(calcHost, {
savedKey: null,
file: got.file,
row: preview.logic,
dirty: () => true,
values,
onLines: () => undefined,
});
// 답의 `문서` = 저장하면 지을 수식 문서(서버 변환 · 못 지음 = null)
const preview = (await previewLogicFormula(row, marks)) as { 문서?: FormulaDoc | null };
buildCalc(calcHost, preview.문서 ?? null, given);
} catch (error) {
calcHost.replaceChildren(createText(error instanceof Error ? error.message : "", "error"));
}
@@ -1,53 +0,0 @@
/* =============================================================================
* M01_MasterData_UI_LogicLab_Foot.ts
* 화면(모달) 바닥에 붙는 비목 소계 줄(737-1 · PLAN 748-3) — 단가산출 상세(노무비 · 재료비 · 경비 · 계 네 칸) ·
* 텍스트 수식(노무비 · 재료비 · 경비 세 칸 · 계 칸 없음 — 중복 표기) 두 보기가 같이 씀.
* 값 = 서버 셈 그대로(여기서 다시 셈 안 함) · 계산 전 「—」.
* ========================================================================== */
import { createCalcFormulaRow } from "@ui/ui_template_calc_row";
import { el } from "@ui/ui_template_elements";
import { formatMoney } from "../common_util/common_util_money";
import { tl } from "./M01_MasterData_UI_LogicLab_Text";
export type FootKey = "labor" | "material" | "cost";
const LABEL: Record<FootKey, string> = { labor: "노무비", material: "재료비", cost: "경비" };
export const FOOT_KEYS = Object.keys(LABEL) as FootKey[];
/** 비목 소계 줄 — `total` 을 주면 맨 끝 「계」 칸까지 네 칸(주지 않으면 세 칸) */
export function buildFoot(
sums: Record<FootKey, number>,
calculated: boolean,
total?: number,
): HTMLElement {
const cells = FOOT_KEYS.map((k) => {
const out = el("span", {
className: "ui-calc-row__out is-key",
text: calculated ? formatMoney(sums[k]) : "—",
});
const row = createCalcFormulaRow(LABEL[k], null, out);
row.dataset.group = k;
row.dataset.subtotal = calculated ? String(sums[k]) : "";
return row;
});
const foot = el("div", {
className: "m01lab__foot",
children: [
el("div", { className: "m01lab__sums", children: cells }),
...(total === undefined
? []
: [
el("p", {
className: "m01lab__total",
attrs: { "data-sum": calculated ? String(total) : "" },
children: [
el("span", { text: `${tl("Total")} ` }),
el("span", { text: calculated ? formatMoney(total) : "—" }),
],
}),
]),
],
});
if (total === undefined) foot.dataset.cols = "3";
return foot;
}
@@ -56,12 +56,6 @@
white-space: pre-wrap;
}
.m01lab__total {
margin: var(--spacing-8) 0 0;
font-weight: 700;
text-align: right;
}
.m01lab__modal {
overflow: auto;
}
@@ -148,69 +142,7 @@
overflow: auto;
}
/* 737-1 맨 아래 한 줄 4 칸(노무비 · 재료비 · 경비 · 계) — 화면(모달) 바닥에 붙음 · 칸마다 이름 위 · 값 아래 */
.m01lab__foot {
position: sticky;
bottom: 0;
z-index: 2;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: var(--spacing-8);
margin-top: var(--m01lab-box-gap, var(--spacing-12));
padding: var(--spacing-8) var(--spacing-12);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
background: var(--color-surface-raised);
}
/* 합계 줄이 화면 바닥에 붙으려면 메인 칸이 굴림 칸(overflow:auto)이 아니어야 함 — 메인은 높이가 안 묶여 안 굴렀음 */
.ui-workflow-layout__main:has(.m01lab__foot) {
overflow: clip;
}
.m01lab__sums {
display: contents;
}
/* 748-3 텍스트 수식 바닥 줄 = 세 칸(계 칸 없음) */
.m01lab__foot[data-cols="3"] {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
/* 748-3 비목 상자 사이 간격 = 바닥 고정 줄 위 여유(같은 값 · 두 보기) */
.m01-logic__editor {
--m01lab-box-gap: var(--spacing-12);
}
.m01lab__foot .ui-calc-row {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 0;
min-height: 0;
}
.m01lab__foot .ui-calc-row > :empty {
display: none;
}
.m01lab__foot .ui-calc-row__out {
padding: 0;
text-align: left;
}
.m01lab__foot .m01lab__total {
display: flex;
flex-direction: column;
margin: 0;
text-align: left;
}
.m01lab__foot .m01lab__total > :first-child {
color: var(--color-text-secondary);
font-weight: var(--font-weight-regular, 400);
}
.m01lab__foot .m01lab__total > :last-child {
font-variant-numeric: tabular-nums;
}
@@ -22,7 +22,6 @@ const TEXT = {
],
View_Equation: ["수식", "Equation"],
Subtotal: ["소계", "Subtotal"],
Total: ["계", "Total"],
Extra: ["덧줄", "Extra"],
Col_Name: ["이름", "Name"],
Col_Unit: ["단위", "Unit"],
+87 -252
View File
@@ -1,270 +1,105 @@
/* =============================================================================
* M01_MasterData_UI_Logic_Calc.ts
* 시험 계산 — 받을 값을 넣고 [계산] → 줄별 금액 · 비목 합 · 멈춘 까닭(엔진 글 그대로)
* 고친 로직은 저장 전 줄(`row`)을 같이 보내 메모리에서 셈(`POST /calc`) — 파일에 안 씀
* 셈 구동(입력 → 서버 → 답) = `_Logic_Drive.ts` — 로직 상세는 이 칸 없이 그 구동만 씀(799-2) · 이 칸은 로직 복사 화면이 씀
* 시험 계산(로직 복사 화면 · 855 2-B4) — 저장하면 지을 수식 문서(`/logic/formula/preview` 의 `문서`)를
* 문서 셈(`POST /m01/logic/doc/preview` · 줄 쌓기 화면과 같은 계산기)으로 셈 · 파일에 안 씀
* 옵션 가로(`formula_doc_options`) · 합계 상자(`formula_doc_foot`) = 줄 쌓기 화면 부품 그대로 — 금액 = 그 로직 수식 화면 금액
* 옵션을 바꾸면 바로 다시 셈(늦게 온 옛 답은 버림)
* ========================================================================== */
import { createButton, createSelectField, el, showToast } from "@ui/ui_template_elements";
import {
pctView,
searchElements,
type CalcAnswer,
type CalcLine,
type ElementBrief,
type LogicRow,
} from "./M01_MasterData_UI_Logic_Api";
import {
isMaterialKeyInput,
machineControl,
materialRows,
showItems,
} from "./M01_MasterData_UI_Logic_CalcPick";
import { autoFill, driveRun } from "./M01_MasterData_UI_Logic_Drive";
import { formatLineMoney, formatMoney, formatNumber } from "../common_util/common_util_money";
import { API_BASE_URL } from "@config/config_frontend";
import { el } from "@ui/ui_template_elements";
import { createText } from "@ui/ui_template_text";
import type { FormulaDoc } from "../common_util/common_util_formula_doc";
import type { DocAnswer } from "../common_util/common_util_formula_doc_calc";
import { formatNumber } from "../common_util/common_util_money";
import { docFoot } from "../A00_Common/formula_doc_foot";
import { buildOptions } from "../A00_Common/formula_doc_options";
import { hiddenByWork } from "../A00_Common/formula_doc_render";
import "../A00_Common/line_stack.css";
import { safeReason, tx } from "./M01_MasterData_UI_Logic_Text";
import { createBadge } from "@ui/ui_template_badge";
import { createDivider } from "@ui/ui_template_divider";
/** 고르기 값이 마스터 키(자재·기계·직종)면 이름으로 바꿔 보임 — 값 칸은 키 그대로 보냄 */
const KEY_RE = /^[A-Z]{2}\d{6}$/;
const KEY_GROUP: Record<string, string> = { MT: "재료", EQ: "기계", LB: "인력" };
/** 로직마다 다시 그려도 남는 이름 캐시 — 같은 키를 두 번 묻지 않음 */
const nameCache = new Map<string, string | null>();
/** 그릇마다 셈 차례 — 줄을 고쳐 다시 그려도 늦게 온 옛 답을 버림 */
const turns = new WeakMap<HTMLElement, number>();
async function keyName(key: string): Promise<string | null> {
if (nameCache.has(key)) return nameCache.get(key)!;
const group = KEY_GROUP[key.slice(0, 2)];
if (!group) return null;
let name: string | null = null;
try {
const found = await searchElements(group, key); // q = 키 그대로 — 「키」 칸 부분일치라 그 줄만 걸림
const hit = found.items.find((it) => it.ref === key);
name = hit ? `${hit.이름 ?? ""}${hit.규격 ? ` ${hit.규격}` : ""}`.trim() || null : null;
} catch {
name = null;
}
nameCache.set(key, name);
return name;
async function previewDoc(문서: FormulaDoc, 입력: Record<string, unknown>): Promise<DocAnswer> {
const r = await fetch(`${API_BASE_URL}/m01/logic/doc/preview`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ 문서: { ...문서, 키: "_새" }, 입력 }), // 저장 전 = 빈 키(줄 쌓기와 같음)
});
const data = (await r.json().catch(() => ({}))) as { 셈?: DocAnswer; detail?: unknown };
if (!r.ok || !data.셈)
throw new Error(typeof data.detail === "string" ? data.detail : r.statusText);
return data.셈;
}
export interface CalcContext {
/** 저장된 키 — 새 로직은 null */
savedKey: string | null;
/** 저장 전 새 초안이면 비움 — 서버가 임시 자리에 얹어 셈 */
file?: string;
row: LogicRow;
/** 잡힌 품목을 보이는 데 씀 — 재료 줄의 단가 요소 · 조건 글 → 요소 */
prices?: Record<string, ElementBrief | null>;
dirty: () => boolean;
/** 로직마다 넣은 값 — 다시 그려도 남음 */
values: Record<string, string>;
onLines?: (lines: CalcLine[] | null) => void;
function answerView(doc: FormulaDoc, a: DocAnswer): HTMLElement[] {
const stop =
!a.셈됨 && a.까닭
? [
el("div", {
className: "ui-banner ui-banner--danger m01-logic__reasons",
children: [
el("strong", { text: tx("Calc_Stopped") }),
el("div", { text: safeReason(a.까닭) }),
],
}),
]
: [];
if (!doc.결과) return [...stop, docFoot(a)]; // 줄 쌓기 아래 합계 상자와 같은 부품
const value =
typeof a.결과 === "number" ? `${formatNumber(a.결과)} ${doc.결과단위 ?? ""}`.trim() : "—";
return [
...stop,
el("dl", {
className: "m01-logic__sums",
children: [el("dt", { text: tx("Calc_Result") }), el("dd", { text: value })],
}),
];
}
const grid = (children: HTMLElement[]): HTMLElement =>
el("div", { className: "m01-logic__head", children });
const SUMS = ["노무비", "재료비", "경비", "계"];
/** 로직마다 첫 셈을 한 번만(다시 그려도 안 부름) */
const autoAsked = new WeakSet<Record<string, string>>();
export function buildCalc(host: HTMLElement, ctx: CalcContext): void {
// 그릇 폭 280px 고정 칸은 옛 테스트 컨테이너(UI_Test*, 걷힘)의 죽은 CSS 규칙 —
// 지금 쓰는 LogicLab 화면은 그 칸에 안 걸려 폭이 이미 넓음(실측 730px) · 따로 안 풂
const optionText = (o: string | number): string =>
(typeof o === "string" && nameCache.get(o)) || String(o);
const again = (): void => host.querySelector<HTMLButtonElement>("[data-calc-run]")?.click();
const fields = (ctx.row.입력 ?? [])
.filter((spec) => !isMaterialKeyInput(spec)) // 재료 키 목록은 표 모달로 바뀌어 걷음
.map((spec) => {
const name = spec.이름;
let control: HTMLElement;
const picks = spec.고르기;
const machine = machineControl(spec, ctx.values, again);
if (machine) {
control = machine;
} else if (picks?.length) {
const pick = createSelectField({
options: ["", ...picks.map(String)].map((o) => ({ value: o, text: optionText(o) })),
value: ctx.values[name] ?? "",
compact: true,
onChange: (v) => {
ctx.values[name] = v;
},
});
control = pick.root;
const keys = picks.filter((o): o is string => typeof o === "string" && KEY_RE.test(o));
if (keys.length) {
void Promise.all(keys.map(keyName)).then(() => {
pick.setOptions(
["", ...picks.map(String)].map((o) => ({ value: o, text: optionText(o) })),
ctx.values[name] ?? "",
);
});
}
} else {
const box = el("input", {
className: "ui-input ui-input--sm m01-logic__input",
attrs: { type: "text", inputmode: "decimal" },
});
if (spec.범위) box.placeholder = `${spec.범위[0]} ∼ ${spec.범위[1]}`;
box.value = ctx.values[name] ?? "";
box.addEventListener("input", () => {
ctx.values[name] = box.value;
});
control = box;
}
const label = spec.단위 ? `${name} (${spec.단위})` : name;
// 긴 이름 줄만 두 칸 차지 — 짧으면 4 열에 맞춰 나란히
const wide = label.length > 10;
return el("label", {
className: `m01-logic__field${wide ? " m01-logic__field--wide" : ""}`,
children: [el("span", { text: label }), control],
});
});
const materials = materialRows(ctx.row, ctx.prices ?? {}, ctx.values, again);
const out = el("div", { className: "m01-logic__calc-out" });
if (!fields.length && !autoAsked.has(ctx.values)) {
autoAsked.add(ctx.values); // 입력이 없으면 채울 것이 없음 — 열 때 한 번 바로 계산
queueMicrotask(again);
} else if (ctx.savedKey !== null && !autoAsked.has(ctx.values)) {
autoAsked.add(ctx.values);
void autoFill(ctx).then((filled) => {
if (!filled) return;
buildCalc(host, ctx); // 채운 값을 새로 그리고 바로 계산
again();
});
/** `doc` = 저장하면 지을 수식 문서(못 지음 = null) · `given` = 고른 옵션(다시 그려도 남음) */
export function buildCalc(
host: HTMLElement,
doc: FormulaDoc | null,
given: Record<string, unknown>,
): void {
const title = el("h3", { text: tx("Calc_Title") });
const note = el("p", { className: "ui-text ui-text--muted", text: tx("Calc_Draft") });
if (!doc) {
host.replaceChildren(title, createText(tx("Calc_NoDoc"), "error"));
return;
}
const money = (ctx.row.결과단위 ?? "").startsWith("원");
const run = async (): Promise<void> => {
const mine = (turns.get(host) ?? 0) + 1;
turns.set(host, mine);
try {
const { answer, draft } = await driveRun(ctx);
if (answer.ok && answer.lines) showItems(host, ctx.values, answer.lines);
out.replaceChildren(...answerView(answer, draft, money));
const answer = await previewDoc(doc, given);
if (turns.get(host) !== mine) return;
const options = buildOptions(
doc,
given,
false,
(k, v, x) => {
// 고르기 글 → 목록 값 그대로(수 45 를 글 「45」 로 보내면 표 줄을 못 찾음 · 줄 쌓기 `usable` 과 같음)
const list = v.연결?.갈래 === "선택" ? (v.연결.목록 ?? []) : [];
given[k] = list.find((o) => String(o) === String(x)) ?? x;
void run();
},
undefined,
hiddenByWork(doc, answer), // 줄 쌓기와 같이 — 시간당 식 줄이 안 읽게 된 옵션은 숨김
);
host.replaceChildren(
title,
note,
...(options.length ? [el("div", { className: "fdoc__options", children: options })] : []),
...answerView(doc, answer),
);
} catch (error) {
showToast(error instanceof Error ? error.message : tx("Load_Failed"), "error");
if (turns.get(host) !== mine) return;
host.replaceChildren(title, createText(error instanceof Error ? error.message : "", "error"));
}
};
const runButton = createButton({ label: tx("Calc_Run"), onClick: () => void run() });
runButton.setAttribute("data-calc-run", "");
host.replaceChildren(
el("h3", { text: tx("Calc_Title") }),
// 옵션 고르기 · 자재 고르기 두 격자(기본 4 열) — 사이 수평 구분선(709-1 부품)
...(fields.length || materials.length
? [
...(fields.length ? [grid(fields)] : []),
...(fields.length && materials.length ? [createDivider()] : []),
...(materials.length ? [grid(materials)] : []),
]
: [el("p", { className: "ui-text ui-text--muted", text: tx("Calc_NoInputs") })]),
runButton,
out,
);
}
/** 중간 값 이름이 돈 꼴(경비 · 노무비 · 공구손료 · 금액 · 단가 · 노임) — 1,000 미만이어도 돈 꼴 */
const MONEY_NAME = /(비|료|액|가|임)$/;
/** `money` = 결과가 돈(원) — 그때만 결과 값도 정수 · 수량·비율 결과는 소수 그대로 */
export function answerView(answer: CalcAnswer, draft: boolean, money: boolean): HTMLElement[] {
const note = draft
? [el("p", { className: "ui-text ui-text--muted", text: tx("Calc_Draft") })]
: [];
if (!answer.ok) {
return [
...note,
el("div", {
className: "ui-banner ui-banner--danger m01-logic__reasons",
children: [
el("strong", { text: tx("Calc_Stopped") }),
el("div", { text: safeReason(answer.reason) }),
],
}),
];
}
const parts: HTMLElement[] = [...note];
if (answer.lines) {
const visible = answer.lines.filter((line) => !line.옵션꺼짐); // 753-2 옵션으로 빠진 줄은 안 그림
const rows = visible.map((line) =>
el("tr", {
children: [
el("td", {
children: [
el("span", {
text: line.출처
? `${pctView(line).name} (${line.출처.replace(/[A-Z]{2}\d{6}\./g, "")})`
: pctView(line).name,
}),
...(line.단위경고
? [createBadge(`${tx("Calc_UnitWarn")} · ${line.단위경고}`, "warning")]
: []),
],
}),
el("td", { text: `${formatNumber(pctView(line).qty)} ${pctView(line).unit}` }),
el("td", { className: "m01-logic__money", text: formatLineMoney(line.금액) }),
],
}),
);
parts.push(
el("table", {
className: "ui-table ui-table--data m01-logic__grid",
children: [
el("thead", {
children: [
el("tr", {
children: [tx("Head_Name"), tx("Ho_Qty"), tx("Ho_Amount")].map((h) =>
el("th", { text: h }),
),
}),
],
}),
el("tbody", { children: rows }),
],
}),
);
}
if (answer.sums) {
parts.push(
el("dl", {
className: "m01-logic__sums",
children: SUMS.flatMap((k) => [
el("dt", { text: k === "계" ? tx("Calc_Sum") : k }),
el("dd", { className: "m01-logic__money", text: formatMoney(answer.sums?.[k] ?? 0) }),
]),
}),
);
}
if (answer.result !== undefined) {
parts.push(
el("dl", {
className: "m01-logic__sums",
children: [
el("dt", { text: tx("Calc_Result") }),
el("dd", { text: money ? formatMoney(answer.result) : formatNumber(answer.result) }),
],
}),
);
}
// 줄 묶음(객체)은 위 상세와 겹쳐 숨김 · 돈 로직의 큰 수는 정수
const middle = Object.entries(answer.middle ?? {}).filter(([, v]) => typeof v !== "object");
if (middle.length) {
parts.push(
el("h4", { text: tx("Middle_Title") }),
el("dl", {
className: "m01-logic__sums",
children: middle.flatMap(([k, v]) => [
el("dt", { text: k }),
el("dd", {
text:
money && typeof v === "number" && (Math.abs(v) >= 1000 || MONEY_NAME.test(k))
? formatLineMoney(v) // 751-3 중간 돈 = 버린 줄 합(0.1 원)
: formatNumber(v),
}),
]),
}),
);
}
return parts;
void run();
}
@@ -44,6 +44,10 @@ const TEXT = {
Calc_Run: ["계산", "Calculate"],
Calc_NoInputs: ["받을 값 없음", "No inputs"],
Calc_Draft: ["고친 줄로 계산(저장 전)", "Using unsaved edits"],
Calc_NoDoc: [
"수식 문서로 못 바꿈 — 고친 식을 확인하세요",
"Cannot build a formula document — check the edits",
],
Calc_Stopped: ["멈춤", "Stopped"],
Calc_Result: ["결과", "Result"],
Calc_Sum: ["계", "Total"],
@@ -32,6 +32,7 @@ import {
type MachineUses,
} from "./M01_MasterData_Machine_Api";
import type { Pick } from "./M01_MasterData_UI_Side";
import { openFindPicker } from "../M02_MasterTemplete/M02_MasterTemplete_Find_Pick";
export interface MachineDetailOptions {
target: string;
@@ -105,6 +106,7 @@ async function build(host: HTMLElement, opts: MachineDetailOptions, alive: () =>
const notice = el("div");
const form = createMachineSheet({
find: openFindPicker, // 856-4
orig: (orig ?? cur) as Row,
cur,
mine: false,
@@ -15,6 +15,7 @@ import { currentLanguageIndex } from "@ui/ui_template_locale";
import { createText } from "@ui/ui_template_text";
import { createStackScreen } from "../A00_Common/line_stack_screen";
import type { Pick } from "./M01_MasterData_UI_Side";
import { openFindPicker } from "../M02_MasterTemplete/M02_MasterTemplete_Find_Pick";
interface Part {
키: string;
@@ -47,6 +48,7 @@ export function renderParts(host: HTMLElement, pick: Pick, openLogic: (key: stri
/** 줄 쌓기 읽기 창 — 고침 없음 · [단가산출 기초에서 열기] = 수식 탭에서 고침 */
const show = (p: Part): void => {
partsStack ??= createStackScreen({
find: openFindPicker, // 856-4
base: "/m01/logic/doc",
admin: false,
cache: "m01_parts_view",
+2 -14
View File
@@ -1,23 +1,11 @@
/* =============================================================================
* M02_DF_Api.ts
* 단위 표준 표 읽기 — 서버 `GET /api/m02/df/standards`(`M02_DF_Router.py`)
* 부르는 곳 = 단위 고르기(`M02_DF_UnitPick`) · 옵션 기계 이름(`formula_doc_options`)
* 기계 이름 · 끈 기계 읽기 — 서버 `GET /api/m02/df/machine-names` · `machine-off`(`M02_DF_Router.py`)
* 부르는 곳 = 옵션 기계 이름(`formula_doc_options`) · 단위 표준 표 읽기는 단위 고르기(`ui_template_unit_pick`)로 옮김(856-4)
* ========================================================================== */
import { API_BASE_URL } from "@config/config_frontend";
/** 단위 표준 표 */
export interface CfStandards {
unit: { 이름: string; 줄: Record<string, unknown>[]; [k: string]: unknown };
saved: boolean;
}
export async function cfStandards(): Promise<CfStandards> {
const response = await fetch(`${API_BASE_URL}/m02/df/standards`, { credentials: "include" });
if (!response.ok) throw new Error(`표준 표 읽기 실패 (${response.status})`);
return (await response.json()) as CfStandards;
}
let machineNames: Promise<Record<string, string>> | null = null;
/** 기계 원문번호 → 「이름 규격」 — 한 번 받아 둠(못 받으면 빈 표 · 다음에 다시) */
+2 -1
View File
@@ -178,7 +178,8 @@ def remove(
at = refs.folder_of(r["층"], r["주인"]) / r["문서종류"] / f"{r['문서']}.json"
files[at] = r
done: list[dict[str, Any]] = []
# ponytail: 여러 파일을 차례로 씀(잠금 없음) — 실패하면 앞서 고친 파일을 앞판 바이트로 되돌림
# ponytail: 부르는 곳(`Precombo_Folders.edit`)의 `store.batch` 안 — 실패하면 앞서 고친 파일을
# 앞판 바이트로 되돌림(되돌림 몸을 `batch` 로 옮기는 것은 5-8)
for path, r in files.items():
raw = path.read_bytes()
try:
+17 -6
View File
@@ -205,6 +205,12 @@ def find(folder: Path, kind: str) -> dict[str, Any]:
# ── 합치기 ────────────────────────────────────────────────────────────
def merge(session: Session, folder: Path, kind: str, body: MergeBody) -> dict[str, Any]:
"""판 대조부터 마지막 쓰기까지 `store.batch` — 같은 층 지우기 · 나무 고침과 겹치면 진 쪽 409."""
with store.batch():
return _merge(session, folder, kind, body)
def _merge(session: Session, folder: Path, kind: str, body: MergeBody) -> dict[str, Any]:
mine = refs.where(folder)
raw = body.남김 or {}
keep_at: refs.Here = (str(raw.get("층") or ""), raw.get("주인") or None)
@@ -216,13 +222,13 @@ def merge(session: Session, folder: Path, kind: str, body: MergeBody) -> dict[st
gone = list(dict.fromkeys(str(k) for k in body.지움))
if not gone or (keep_at == mine and keep["키"] in gone):
raise _bad(400, "지울 문서를 고름 — 남김과 달라야 함")
with store.at(folder):
tree_doc, 판 = pre_folders._read(kind)
if 판 != body.판: # 없는 문서 검사 앞 — 겹쳐 진 쪽(그새 지워짐)은 409
raise _bad(409, {"stale": [pre_folders.file_of(kind)], "판": 판})
have = dict(_docs(mine, kind))
if miss := [k for k in gone if k not in have]:
raise _bad(404, f"이 층에 없는 문서 「{' · '.join(miss)}」")
with store.at(folder):
tree_doc, 판 = pre_folders._read(kind)
if 판 != body.판:
raise _bad(409, {"stale": [pre_folders.file_of(kind)], "판": 판})
marks = same.Same()
mark = marks.finger(kind, keep_doc)
if mark is None or any(marks.finger(kind, have[k]) != mark for k in gone):
@@ -259,7 +265,6 @@ def merge(session: Session, folder: Path, kind: str, body: MergeBody) -> dict[st
places = dict(tree_doc.get("자리") or {})
done, kept = [], []
when = datetime.now().isoformat(timespec="seconds")
# ponytail: 여러 파일을 차례로 씀(잠금 없음) — 동시에 같은 층을 합치면 앞 것이 이김
for key in gone:
if left[key]:
kept.append({"키": key, "쓰는곳": left[key]})
@@ -284,7 +289,13 @@ def merge(session: Session, folder: Path, kind: str, body: MergeBody) -> dict[st
def undo(session: Session, folder: Path, kind: str, key: str) -> dict[str, Any]:
"""`_합친것/<키>` 되돌림 — 문서 · 나무 자리 · 옮긴 참조(아직 남김을 가리키고 쓸 수 있는 곳)."""
"""`_합친것/<키>` 되돌림 — 문서 · 나무 자리 · 옮긴 참조(아직 남김을 가리키고 쓸 수 있는 곳) ·
한 `store.batch`(지움 기록 되돌림 `M02_Library_Delete.undo` 도 이 안)."""
with store.batch():
return _undo(session, folder, kind, key)
def _undo(session: Session, folder: Path, kind: str, key: str) -> dict[str, Any]:
mine = refs.where(folder)
rec_path = folder / GONE / f"{key}.json"
try:
@@ -3,10 +3,10 @@
* 마스터 템플릿 서버 호출 — 계약 `6_계약.md` 서버 길 · 시스템 층은 시스템 관리자만
* ========================================================================== */
import { API_BASE_URL } from "@config/config_frontend";
import { call, type Layer } from "../common_util/common_util_m02_call";
/** 층 이름 — 서버와 같은 글 */
export type Layer = "system" | "company" | "personal" | "project";
// 층 이름 · `/api/m02` 부름 = 공용 조각(856-4 — 줄 쌓기 공용 화면도 씀) · 여기서 그대로 내보냄
export { call, StaleError, type Layer } from "../common_util/common_util_m02_call";
/** 서버 종류 — 화면의 「표 양식」 = table · 「도면 양식」 = drawing · 「구조물 도면」 = structure ·
* 「면적산출」 = area(구조물집계표 열마다 한 통합문서) ·
* 「일위대가」 = labor(열마다 문서 · 39장) ·
@@ -31,42 +31,6 @@ export interface TemplateDoc {
문서: unknown;
}
/** 서버가 판 불일치로 막았을 때 · `detail` = 서버 몸 그대로(729-3 `{까닭, 남은줄}`) */
export class StaleError extends Error {
constructor(
message: string,
readonly detail?: unknown,
) {
super(message);
}
}
/** `/api/m02` 아래 길 부름 — 409 = StaleError · 그 밖 실패 = 서버 까닭 글(하위 폴더도 씀) */
export async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(`${API_BASE_URL}/m02${path}`, {
credentials: "include",
headers: { "Content-Type": "application/json" },
...init,
});
const body = (await response.json().catch(() => ({}))) as { detail?: unknown } & T;
if (response.status === 409)
throw new StaleError(reason(body.detail, response.status), body.detail);
if (!response.ok) throw new Error(reason(body.detail, response.status));
return body;
}
/** 서버가 막은 까닭 그대로 — 문장 · `{errors: [...]}` · 입력 검사 목록(`[{msg}]`) */
function reason(detail: unknown, status: number): string {
if (typeof detail === "string") return detail;
const why = (detail as { 까닭?: unknown } | null)?.까닭;
if (typeof why === "string") return why;
const list = Array.isArray(detail) ? detail : (detail as { errors?: unknown } | null)?.errors;
const lines = Array.isArray(list)
? list.map((x) => (typeof x === "string" ? x : String((x as { msg?: unknown })?.msg ?? "")))
: [];
return lines.filter(Boolean).join(" · ") || `HTTP ${status}`;
}
/** 지금 화면의 층 — 시스템 · 회사 · 개인 모두 `/layers/{층}` 아래(구조물집계표 · 조합 길 모두 · 읽기는
* 로그인 누구나 · 쓰기는 서버 층 권한 · 옛 `/api/m02/templates/*` 는 시스템 관리자 전용이라 안 씀) ·
* `owner` = 남의 층을 볼 때 주인(회사 `{C}` · 개인 `{C}/{U}` · 자기 층 = null · PLAN 27-1c) —
@@ -46,6 +46,7 @@ import { listLayerDocs, SANGEUN_KIND, type SangeunRow } from "./M02_MasterTemple
import { logicHeads as heads } from "./logic/M02_Find_Heads";
import "../M01_MasterData/M01_MasterData_UI_Logic_Style.css"; // 창 겉틀
import "./M02_MasterTemplete_Labor.css";
import type { StackFindKind } from "../A00_Common/line_stack_pick";
type Scope = Omit<LaborRef, "키">;
type Tab = "m01" | "sk" | "pre";
@@ -66,7 +67,7 @@ export interface M01Element {
}
/** 고를 수 있는 종류 — logic = M01 단가산출 · 기초 로직 · labor = 인력 · material = 재료 · machine = 기계 · sk = M02 단가산출 · pre = 일위대가 */
export type FindKind = "logic" | "labor" | "material" | "machine" | "oil" | "sk" | "pre";
export type FindKind = StackFindKind; // 856-4 — 공용 줄 쌓기 창 종류와 한 벌
export interface FindPickOptions {
layer: Layer;
@@ -21,6 +21,7 @@ import { openStackPick } from "../A00_Common/line_stack_pick";
import { call } from "./M02_MasterTemplete_Api_Fetch";
import { at, type HopyoScope } from "./M02_MasterTemplete_Hopyo_Api";
import { placeNote } from "../M01_MasterData/M01_MasterData_Api_Fetch";
import { openFindPicker } from "./M02_MasterTemplete_Find_Pick";
export interface MatCand {
키: string;
@@ -120,6 +121,7 @@ export function createMatPick(opt: { scope: HopyoScope; key: string; target: Hop
iconStart: "search",
onClick: () =>
openStackPick(
openFindPicker,
"재료",
(p) => set(k, { 키: p.키, 이름: p.이름, 규격: p.규격 ?? "", 단위: p.단위 ?? "" }),
undefined,
@@ -53,7 +53,7 @@ import { openMatModal, openRowModal } from "./M02_MasterTemplete_Labor_RowModal"
import { tc } from "./M02_MasterTemplete_Labor_Text";
import { insideKeys } from "./M02_Labor_LogicMats_Model";
import { valueLine } from "./M02_Labor_Values_Model";
import { createUnitPick, NO_UNIT } from "./DataFlow/M02_DF_UnitPick";
import { createUnitPick, NO_UNIT } from "@ui/ui_template_unit_pick";
import { libMeta } from "./M02_MasterTemplete_Labor_LibMeta";
import "../M01_MasterData/M01_MasterData_UI_Logic_Style.css";
import "../M01_MasterData/M01_MasterData_UI_LogicLab_Style.css";
@@ -10,6 +10,7 @@
import { createStackScreen } from "../A00_Common/line_stack_screen";
import { el } from "@ui/ui_template_elements";
import type { Layer } from "./M02_MasterTemplete_Api_Fetch";
import { openFindPicker } from "./M02_MasterTemplete_Find_Pick";
export interface SkEquationOptions {
scope: { layer: Layer; owner: string | null };
@@ -48,6 +49,7 @@ export function createSangeunTabs(opt: SkEquationOptions): {
} {
const tools = el("span", { className: "m02-sk__tools", attrs: { "data-sk-tools": "" } }); // [단가 갱신] · [재생성](808-1)
const stack = createStackScreen({
find: openFindPicker, // 856-4 찾아 넣기 창
base: "",
admin: opt.edit,
cache: "m02_sk_doc_drafts",
@@ -76,8 +76,14 @@ _BAD_NAME = re.compile(r'[\\/:*?"<>|\x00-\x1f]|\.\.')
# of undefined (reading 'length')") · CAD 쪽도 없으면 새로 채우지만(2026-09-27 sub1 고침)
# 뿌리도 처음부터 채움
_BLANK_LAYER = {"id": "기본", "name": "기본", "isVisible": True, "isLocked": False}
# ponytail: 저장은 한 번에 하나(프로세스 안 잠금) · 서버를 여럿 띄우면 파일 잠금으로
_LOCK = threading.Lock()
# ponytail: 저장은 한 번에 하나(프로세스 안 잠금 · 다시 들어감) · 서버를 여럿 띄우면 파일 잠금으로
_LOCK = threading.RLock()
def batch() -> threading.RLock:
"""여러 파일 쓰기 한 묶음(858 5-4) — 판 대조부터 마지막 쓰기까지 한 잠금 · 안에서 `write` ·
`delete` 를 불러도 됨(다시 들어가는 잠금) · 겹친 쪽은 잠금 뒤 판 대조에서 409."""
return _LOCK
class StoreError(Exception):
+1 -1
View File
@@ -12,7 +12,7 @@ import { createButton, createInputField, el, showToast } from "@ui/ui_template_e
import { openModal } from "@ui/ui_template_modal";
import { searchMaterials } from "../M01_MasterData/M01_MasterData_Api_Fetch";
import { call } from "./M02_MasterTemplete_Api_Fetch";
import { createUnitPick, NO_UNIT } from "./DataFlow/M02_DF_UnitPick";
import { createUnitPick, NO_UNIT } from "@ui/ui_template_unit_pick";
import { createBadge } from "@ui/ui_template_badge";
import { createText } from "@ui/ui_template_text";
import { createEmpty } from "@ui/ui_template_empty";
+2
View File
@@ -37,6 +37,7 @@ import { StaleError } from "./M02_MasterTemplete_Api_Fetch";
import { confirmMyMachineImpact } from "./M02_MyMachine_Impact";
import { mt } from "./M02_MyMachine_Text";
import "./M02_MyMachine.css";
import { openFindPicker } from "./M02_MasterTemplete_Find_Pick";
export interface MyMachineFormOptions {
owner: string | null;
@@ -109,6 +110,7 @@ export async function mountMyMachineForm(
let m01Same = false;
const sheet = createMachineSheet({
find: openFindPicker, // 856-4
orig: start,
mine: true,
readOnly: false,
+1 -1
View File
@@ -12,7 +12,7 @@ import { createButton } from "@ui/ui_template_button";
import { createDataTable } from "@ui/ui_template_data_table";
import { createInputField, el, showConfirmDialog, showToast } from "@ui/ui_template_elements";
import { createText } from "@ui/ui_template_text";
import { createUnitPick, NO_UNIT } from "./DataFlow/M02_DF_UnitPick";
import { createUnitPick, NO_UNIT } from "@ui/ui_template_unit_pick";
import {
addMyMaterial,
dropMyMaterial,
+7 -1
View File
@@ -181,7 +181,13 @@ def edit(
body: dict[str, Any], kind: str = "precombo", session: dict[str, Any] | None = None
) -> dict[str, Any]:
"""지금 층 자리 파일을 고쳐 씀(지우기면 문서 파일째 · 쓰는 곳 = `deleting.remove` · 몸 `확인`) →
새 나무 + 알림(지우기 = `기록` 되돌림 키) · 판 다르면 409."""
새 나무 + 알림(지우기 = `기록` 되돌림 키) · 판 다르면 409 · 판 대조부터 쓰기까지
`store.batch`."""
with store.batch():
return _edit(body, kind, session)
def _edit(body: dict[str, Any], kind: str, session: dict[str, Any] | None) -> dict[str, Any]:
doc, 판 = _read(kind)
if 판 != str(body.get("판") or ""):
raise store.StoreError(409, {"stale": [file_of(kind)], "판": 판})
+47
View File
@@ -0,0 +1,47 @@
/* =============================================================================
* common_util_m02_call.ts
* M02 서버 길 부름(PLAN 856-4) — 층 이름 · `/api/m02` 아래 부름 한 함수 · 409 = 판 다름.
* M02 화면(`M02_MasterTemplete_Api_Fetch` 가 그대로 내보냄)과 공용 줄 쌓기 화면(`A00_Common/line_stack_*`)이 같이 씀
* — 공용 화면이 M02 를 거꾸로 부르지 않게
* ========================================================================== */
import { API_BASE_URL } from "@config/config_frontend";
/** 층 이름 — 서버와 같은 글 */
export type Layer = "system" | "company" | "personal" | "project";
/** 서버가 판 불일치로 막았을 때 · `detail` = 서버 몸 그대로(729-3 `{까닭, 남은줄}`) */
export class StaleError extends Error {
constructor(
message: string,
readonly detail?: unknown,
) {
super(message);
}
}
/** `/api/m02` 아래 길 부름 — 409 = StaleError · 그 밖 실패 = 서버 까닭 글(하위 폴더도 씀) */
export async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(`${API_BASE_URL}/m02${path}`, {
credentials: "include",
headers: { "Content-Type": "application/json" },
...init,
});
const body = (await response.json().catch(() => ({}))) as { detail?: unknown } & T;
if (response.status === 409)
throw new StaleError(reason(body.detail, response.status), body.detail);
if (!response.ok) throw new Error(reason(body.detail, response.status));
return body;
}
/** 서버가 막은 까닭 그대로 — 문장 · `{errors: [...]}` · 입력 검사 목록(`[{msg}]`) */
function reason(detail: unknown, status: number): string {
if (typeof detail === "string") return detail;
const why = (detail as { 까닭?: unknown } | null)?.까닭;
if (typeof why === "string") return why;
const list = Array.isArray(detail) ? detail : (detail as { errors?: unknown } | null)?.errors;
const lines = Array.isArray(list)
? list.map((x) => (typeof x === "string" ? x : String((x as { msg?: unknown })?.msg ?? "")))
: [];
return lines.filter(Boolean).join(" · ") || `HTTP ${status}`;
}
@@ -1604,3 +1604,7 @@ b09원가에서는 확인할필요 없음. 어차피 m02의정보를 가져가
## 요구 899 (11-17 · 사용자 · 지금 M02 의 개인 · 회사 · 마스터 데이터는 개발 중 테스트 결과 — 삭제해도 됨)
추가로 현재 M02의 개인/회사/마스터 데이터는 프로그램 개발과정에서 테스트한 결과임. 삭제 해도됨.
## 요구 900 (11-17 · 사용자 · 중간 보고 필요 없음 · 전체 작업 마무리 뒤 한 번에 통합 보고 · 오전 11 시부터 한 것 전체)
중간중간 보고할 필요없음. 작업 마무리하고 한번에 보고할것. 오늘 오전 11시부타 작업했던것같은데 전체를 작업 마무리하고 통합보고 해줘. 중간중간에 나온 말든은 확인이 어려움. 난 이제 쉬러감.
+1 -1
View File
@@ -213,7 +213,7 @@ const noop = () => undefined;
const load = makeLoader({
katex: { render: (t, box) => (box.tex = t) },
formula_doc_options: { machineText: () => null, optionText: (x) => x, liveOptions: (l) => l, nameMachines: noop },
M02_DF_UnitPick: {
ui_template_unit_pick: {
NO_UNIT: "(단위 없음)",
createUnitPick: (o) => Object.assign(new FakeNode("select"), { value: o.value }),
},
+1 -1
View File
@@ -198,7 +198,7 @@ const stubs = {
M02_MasterTemplete_Labor_Grid: {
laborBlock: (cur) => ({ lines: cur.담은로직.map(() => ({ note: "", amounts: { sum: 1 } })) }),
},
M02_DF_UnitPick: { createUnitPick: () => box("div"), NO_UNIT: "-" },
ui_template_unit_pick: { createUnitPick: () => box("div"), NO_UNIT: "-" },
M02_MasterTemplete_Labor_Unlinked: { unlinkedBar: () => null },
M02_MasterTemplete_Labor_Text: { tc: (k) => k },
M02_MasterTemplete_Labor_LibMeta: { libMeta: () => [] },
-9
View File
@@ -49,12 +49,3 @@ def test_M01_시험계산도_율_규격():
got = m01_router.post_calc(m01_router.CalcBody(key="GF000227", inputs=given))
extra = [x for x in got["lines"] if x["이름"] == "제잡비"][0]
assert extra["율"] == 9 and extra["규격"] == "노무비의 %"
def test_화면_두_곳_pctView_한_벌():
api = (ROOT / "M01_MasterData/M01_MasterData_UI_Logic_Api.ts").read_text("utf-8")
assert "x.율 == null" in api and 'qty: x.율, unit: "%"' in api
rows = (ROOT / "M02_MasterTemplete/M02_MasterTemplete_Labor_Rows.ts").read_text("utf-8")
assert "const shown = pctView(x);" in rows and "qty: shown.qty," in rows
calc = (ROOT / "M01_MasterData/M01_MasterData_UI_Logic_Calc.ts").read_text("utf-8")
assert "formatNumber(pctView(line).qty)" in calc
-1
View File
@@ -121,7 +121,6 @@ def test_736_1_항목_추가_찾기_창_하나():
assert "material: lib.material," in pick
find = _text(M02 / "M02_MasterTemplete_Find_Pick.ts")
assert 'kind === "재료" && opt.material' in find and "? opt.material" in find
assert '"logic" | "labor" | "material" | "machine" | "oil" | "sk" | "pre"' in find # 785-3 oil
def test_736_2_빠진_길_둘_신규_자재_기계_탭():
@@ -4,9 +4,7 @@ import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
M01 = ROOT / "M01_MasterData"
SHEET_CSS = (ROOT / "A00_Common" / "calc_sheet.css").read_text(encoding="utf-8")
STYLE = (M01 / "M01_MasterData_UI_LogicLab_Style.css").read_text(encoding="utf-8")
def test_옵션_격자_폭_따라_6_4_3_2_1():
@@ -18,12 +16,3 @@ def test_옵션_격자_폭_따라_6_4_3_2_1():
assert "container-type: inline-size" in SHEET_CSS # 창 폭이 아니라 상자 폭 기준
def test_합계_한_줄_바닥_고정():
foot = STYLE[STYLE.index(".m01lab__foot {") :]
foot = foot[: foot.index("}")]
assert "position: sticky" in foot and "bottom: 0" in foot
assert "repeat(4, minmax(0, 1fr))" in foot
assert "overflow: clip" in STYLE # 메인 칸이 굴림 칸이면 바닥에 안 붙음
foot_ts = (M01 / "M01_MasterData_UI_LogicLab_Foot.ts").read_text(encoding="utf-8")
assert 'className: "m01lab__foot"' in foot_ts # 748-3 두 보기가 같은 바닥 줄 부품
assert 'data-cols="3"' in STYLE
@@ -73,10 +73,6 @@ def test_셈_구동은_화면_없이_상세는_구동만():
assert "createDrive" not in lab and "buildCalc" not in lab and "data-calc-run" not in lab
detail = _text(M01 / "M01_MasterData_UI_LogicLab_Detail.ts")
assert "calcHost" not in detail and "data-calc-run" not in detail and "rerun" not in detail
calc = _text(
M01 / "M01_MasterData_UI_Logic_Calc.ts"
) # 로직 복사 화면이 쓰는 시험 계산 칸 — 구동은 공용
assert "driveRun(ctx)" in calc and "runCalc" not in calc
m02 = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts")
assert "buildCalc" not in m02 and "calcHost" not in m02
@@ -177,7 +177,7 @@ def test_요소키_기호_이름_0_전수() -> None:
def test_단위_고르기_공용_친글() -> None:
edit = _src("A00_Common/line_stack_edit.ts")
assert "createUnitPick({" in edit and "free: true," in edit
pick = _src("M02_MasterTemplete/DataFlow/M02_DF_UnitPick.ts")
pick = _src("ui_template/ui_template_unit_pick.ts")
assert "if (opts.free && typed && !all.includes(typed)) shown.push(typed);" in pick
main = _src("main.py")
at = main.index("M02_MasterTemplete.DataFlow.M02_DF_Router")
@@ -275,7 +275,7 @@ def test_단위표_더한_단위_문서_전수() -> None:
assert len(lines) > 5000
missing = {u for u in lines if u and same.get(u, u) not in units}
assert not missing, missing
pick = _src("M02_MasterTemplete/DataFlow/M02_DF_UnitPick.ts")
pick = _src("ui_template/ui_template_unit_pick.ts")
assert (
'...(table["더한 단위"] ?? []),' in pick and '(u && table["같은 단위"]?.[u]) || u' in pick
)
+41 -51
View File
@@ -7,9 +7,8 @@
다르면 갈래 이름 + 지금 답 + 다시 뜨는 법으로 실패(건너뛰지 않음). 다시 뜸 =
`SHELF_858_WRITE=1 ./venv/Scripts/python.exe -m pytest resources/tester/test_858_shelf_golden.py`
(뜻한 바뀜일 때만 · 커밋 글에 까닭). 답 통째 전후 대조 = `SHELF_858_DUMP=tmp/<파일>.json`.
② 동시 쓰기 — 잠금 없는 나무 고침 · 나무 지우기 · 합치기를 같은 판으로 겹쳐 부름. 지금 사실을
그대로 단언(나무 = 둘 다 됨 · 뒤 것이 이김 · 지우기 + 합치기 = 앞 것이 이기고 뒤 것은 터짐) —
「5-4 에서 뒤집을 단언」 표시 줄은 5-4 가 바꿈.
② 동시 쓰기 — 나무 고침 · 나무 지우기 · 합치기를 같은 판으로 겹쳐 부름. 한 잠금(`store.batch` ·
5-4) 안에서 판 대조 → 앞 것만 이기고 뒤 것은 409 · 파일은 앞 것이 쓴 그대로(반쯤 써짐 없음).
"""
from __future__ import annotations
@@ -354,45 +353,36 @@ def test_서고_길_답_지문(shelf, world):
)
# ── ② 동시 쓰기 — 잠금 없는 여러 파일 쓰기(설계 858 1-4 「잠금 없는 쓰기」 · 5-4 몫) ─────────
def _two(first, second, meet: list[tuple[Any, str]], late: tuple[Any, str]):
"""둘을 같이 돌림 — 둘 다 판 대조를 지난 뒤 `meet` 함수 앞에서 만나고, 그 뒤 `second` 쪽
`late` 함수를 늦춤 → (먼저 답 · 나중 답 — 예외면 예외)."""
gate = threading.Barrier(2, timeout=10)
slow = threading.local()
saved = [(late[0], late[1], getattr(*late))] + [(o, n, None) for o, n in meet]
# ── ② 동시 쓰기 — 여러 파일 쓰기 한 잠금(설계 858 1-4 「잠금 없는 쓰기」 · 5-4) ─────────
def _race(win, lose, inside: tuple[Any, str]):
"""`win` 을 먼저 돌려 `inside`(판 대조 뒤 · 쓰기 앞) 안에서 붙잡아 둔 사이 `lose` 를 돌림 →
(win 답 · lose 답 — 예외면 예외). 잠금이 없으면 `lose` 도 옛 판으로 대조를 지나 둘 다 됨."""
entered = threading.Event()
held = threading.local()
real = getattr(*inside)
def later(*a, _real=saved[0][2], **k):
if getattr(slow, "on", False):
def hold(*a, **k):
if getattr(held, "on", False):
entered.set()
threading.Event().wait(0.3)
return _real(*a, **k)
return real(*a, **k)
setattr(*late, later) # 안쪽 = 늦춤 · 바깥 = 만남(같은 함수면 만난 뒤 늦춤)
for i, (owner, name, _) in enumerate(saved[1:], 1):
inner = getattr(owner, name)
saved[i] = (owner, name, inner)
def wait(*a, _inner=inner, **k):
gate.wait()
return _inner(*a, **k)
setattr(owner, name, wait)
def run(fn, is_late):
slow.on = is_late
def run(fn, is_win):
held.on = is_win
try:
return fn()
except Exception as error: # 지금 사실(터짐)도 답으로
except Exception as error: # 진 쪽 409 도 답으로
return error
setattr(*inside, hold)
try:
with ThreadPoolExecutor(2) as pool:
a = pool.submit(run, first, False)
b = pool.submit(run, second, True)
a = pool.submit(run, win, True)
assert entered.wait(10), "앞 것이 쓰기 자리에 못 닿음"
b = pool.submit(run, lose, False)
return a.result(), b.result()
finally:
for owner, name, real in reversed(saved):
setattr(owner, name, real)
setattr(*inside, real)
def _sk(me: Path, name: str, price: int, again: bool = False) -> str:
@@ -415,37 +405,40 @@ def _folders(me: Path) -> list[list[str]]:
return pre_folders.view("sangeun")["폴더"]
def test_동시_나무_고침_둘_다_됨_뒤_것이_이김(world):
def _lost(answer) -> bool:
return isinstance(answer, store.StoreError) and answer.status == 409
def test_동시_나무_고침_앞_것만_됨_뒤_것은_409(world):
me = world["personal"]
with store.at(me):
판 = pre_folders.view("sangeun")["판"]
first, second = _two(
first, second = _race(
_edit(me, {"op": "add-folder", "경로": [], "이름": "가", "판": 판}),
_edit(me, {"op": "add-folder", "경로": [], "이름": "나", "판": 판}),
[(pre_folders, "apply_many")],
(pre_folders, "atomic_write_json"),
(pre_folders, "apply_many"),
)
assert first["알림"]["경로"] == ["가"] and second["알림"]["경로"] == ["나"] # 둘 다 됨
assert _folders(me) == [["나"]] # 5-4 에서 뒤집을 단언 — 지금은 뒤 것이 이김(앞 「가」 사라짐)
assert first["알림"]["경로"] == ["가"] and _lost(second)
assert _folders(me) == [["가"]] # 앞 것만 — 뒤 「나」 는 판이 달라 안 씀
def test_동시_나무_지우기와_고침_둘_다_됨_뒤_것이_이김(world):
def test_동시_나무_고침과_지우기_앞_것만_됨_뒤_지우기는_409(world):
me = world["personal"]
gone = _sk(me, "지울것", 1000)
with store.at(me):
판 = pre_folders.view("sangeun")["판"]
first, second = _two(
first, second = _race(
_edit(me, {"op": "add-folder", "경로": [], "이름": "가", "판": 판}),
_edit(me, {"op": "delete", "대상": [{"키": gone}], "판": 판}),
[(pre_folders, "apply_many")],
(pre_folders, "atomic_write_json"),
(pre_folders, "apply_many"),
)
assert first["알림"]["경로"] == ["가"] and second["알림"]["기록"] # 둘 다 됨
assert not (me / "sangeun" / f"{gone}.json").exists()
assert _folders(me) == [] # 5-4 에서 뒤집을 단언 — 지금은 뒤 것(지우기)이 이김(「가」 사라짐)
assert first["알림"]["경로"] == ["가"] and _lost(second)
assert (me / "sangeun" / f"{gone}.json").is_file() # 지우기 = 안 됨 · 문서 그대로
assert _folders(me) == [["가"]]
assert not (me / same_router.GONE).exists() or not list((me / same_router.GONE).glob("*.json"))
def test_동시_지우기와_합치기_앞_것이_이기고_뒤_것은_터짐(world):
def test_동시_지우기와_합치기_앞_것만_됨_뒤_합치기는_409(world):
me = world["personal"]
gone = _sk(me, "겹침", 1000)
keep = _sk(me, "겹침", 1000, again=True)
@@ -454,16 +447,13 @@ def test_동시_지우기와_합치기_앞_것이_이기고_뒤_것은_터짐(wo
body = same_router.MergeBody(
남김={"층": "personal", "주인": "7/42", "키": keep}, 지움=[gone], 판=판
)
first, second = _two(
first, second = _race(
_edit(me, {"op": "delete", "대상": [{"키": gone}], "판": 판}),
lambda: same_router.merge(dict(USER), me, "sangeun", body),
[(pre_folders, "apply_many"), (same_router, "_user_index")],
(same_router, "_user_index"),
(pre_folders, "apply_many"),
)
assert first["알림"]["기록"] == gone # 지우기 = 됨(기록 키 = 그 문서)
# 5-4 에서 뒤집을 단언 — 지금은 뒤 합치기가 판 · 지문 대조를 지난 뒤 사라진 파일에서 터짐
# (화면 = 500) · 5-4 뒤 = 409 · 파일 앞판 그대로
assert isinstance(second, FileNotFoundError)
assert _lost(second) # 뒤 합치기 = 판이 달라 409(옛 = 사라진 파일에서 터짐 · 화면 500)
assert not (me / "sangeun" / f"{gone}.json").exists()
assert (me / "sangeun" / f"{keep}.json").is_file()
assert [p.stem for p in (me / same_router.GONE).glob("*.json")] == [gone] # 지우기 기록만
+15 -12
View File
@@ -209,11 +209,9 @@ def test_별칭_원문이_부르기가_아니면_막는다(client: TestClient) -
assert "찾기" in str(got["detail"])
def test_미리보기는_저장_없이_원문으로_되돌린_로직만_준다(client: TestClient) -> None:
"""3-4 화면의 [시험 계산] 이 쓰는 길 — `/calc` 의 `row`+`file` 로 그대로 넣어 씀."""
inputs = _inputs(STACK)
was = _sums(client, STACK, inputs)
def test_미리보기는_저장_없이_원문으로_되돌린_로직과_지을_문서를_준다(client: TestClient) -> None:
"""3-4 화면의 [시험 계산] 이 쓰는 길(855 2-B4) — 답의 `문서` 를 문서 셈(`/logic/doc/preview`)
으로 · 금액 = 그 로직 수식 문서 금액(옵션을 바꿔도)."""
view = _get(client, "/api/m01/logic/formula", key=STACK)
before_keys = _get(client, "/api/m01/logics")["logics"]
preview = _post(
@@ -224,13 +222,18 @@ def test_미리보기는_저장_없이_원문으로_되돌린_로직만_준다(c
after_keys = _get(client, "/api/m01/logics")["logics"]
assert after_keys == before_keys # 아무것도 저장 안 함
calc = _post(
client,
"/api/m01/calc",
{"key": STACK, "inputs": inputs, "row": preview["logic"], "file": view["file"]},
)
assert calc["ok"], calc
assert Decimal(str(calc["sums"]["계"])) == Decimal(str(was["계"]))
def total(doc: dict, given: dict) -> Decimal:
got = _post(client, "/api/m01/logic/doc/preview", {"문서": doc, "입력": given})
assert got["셈"]["셈됨"], got["셈"]
return Decimal(str(got["셈"]["계"]))
saved = _get(client, "/api/m01/logic/doc", key=STACK)["문서"]
draft = {**preview["문서"], "키": "_새"} # 화면이 보내는 꼴(저장 전 = 빈 키)
picks = [total(saved, {})]
for given in ({}, {"돌": "견치돌", "쌓기": "켜쌓기", "뒷길이": 45}):
assert total(draft, given) == total(saved, given)
picks.append(total(saved, given))
assert picks[0] != picks[-1] # 옵션이 금액을 바꿈(같음이 빈 대조가 아님)
def test_미리보기도_별칭_원문이_부르기가_아니면_막는다(client: TestClient) -> None:
@@ -1,4 +1,4 @@
/* 51-5 — 단위 고르기 단추(공용 M02_DF_UnitPick) 높이 · 글자 = [저장] 단추와 같음
/* 51-5 — 단위 고르기 단추(공용 ui_template_unit_pick) 높이 · 글자 = [저장] 단추와 같음
* 시작 화면: M02 마스터 템플릿 · 마스터 층(#/m02-master-template?open=구조물조합&root=master) · 시스템 관리자
* 부르는 법: orca eval --expression "$(tr '\n' ' ' < 이 파일)" (async 식 · JSON 글을 돌려줌)
* 하는 일: item1 → 일위대가 [수정] 상세 → 단위 단추 · [저장] 단추 높이 · 글자 크기 잼
@@ -1,6 +1,6 @@
/* =============================================================================
* M02_DF_UnitPick.ts
* 단가산출 흐름도 공용 단위 고르기 — 치면 걸러진 목록 · 고르기만(손글 안 받음 · `free` = 목록에 없는 친 글도 씀) · 「-」 = 없음
* ui_template_unit_pick.ts
* 공용 단위 고르기(856-4 — 옛 M02 `DataFlow/M02_DF_UnitPick`) — 치면 걸러진 목록 · 고르기만(손글 안 받음 · `free` = 목록에 없는 친 글도 씀) · 「-」 = 없음
* 목록 = 단위 표준(산림품셈 1-2-2) 단위 + 표의 「더한 단위」(수식 문서 줄 단위) + 부른 쪽이 주는 마스터 결과단위 등 + 원 · 「같은 단위」(kg → ㎏) 는 하나만
* 표준 표 읽는 길은 `setUnitSource` 로 바꿔 끼움(기본 = 서버 /standards) — 다른 판도 이것을 씀
* 글 [한, 영] 짝은 아래 TEXT
@@ -9,8 +9,8 @@
import { currentLanguageIndex } from "@ui/ui_template_locale";
import { createButton, el } from "@ui/ui_template_elements";
import type { UiSize } from "@ui/ui_template_button";
import { cfStandards } from "./M02_DF_Api";
import "./M02_DF_UnitPick.css";
import { API_BASE_URL } from "@config/config_frontend";
import "./ui_template_unit_pick.css";
import { createEmpty } from "@ui/ui_template_empty";
import "@ui/ui_template_list_row.css";
@@ -22,6 +22,18 @@ const TEXT = {
Pick: ["단위 고르기", "Pick a unit"],
} as const;
/** 단위 표준 표 */
interface CfStandards {
unit: { 이름: string; 줄: Record<string, unknown>[]; [k: string]: unknown };
saved: boolean;
}
async function cfStandards(): Promise<CfStandards> {
const response = await fetch(`${API_BASE_URL}/m02/df/standards`, { credentials: "include" });
if (!response.ok) throw new Error(`표준 표 읽기 실패 (${response.status})`);
return (await response.json()) as CfStandards;
}
const tu = (key: keyof typeof TEXT): string => TEXT[key][currentLanguageIndex === 1 ? 1 : 0];
/** 「없음」 을 뜻하는 단위 글 */