refactor(856-1): 단가산출 상세 몸 걷기 — 줄 쌓기 한 벌 · 열 때 서버 셈 한 번
- 지움: M01 LogicLab_Ho · LogicLab_Cover · M02 Sangeun_Cover_Model · Sangeun_Undo · Sangeun_BaseHead · Labor_RowSk - Sangeun_Detail: 숨긴 몸 · 바탕 원값(bare) 셈 · 덮개 고침 · 재료 고름 · 키 글자 약속(SK-000000) 걷음 → 모드 옵션(page · ref · memory) - Sangeun_Tabs: 몸 그릇 · 숨김 걷음 · Sangeun_Cover: 뺀 줄 띠 걷음 · 셈 보기 덧칸 끔(머리 띠는 안 씀) · 머리 띠 타입만 둠(856-2 에서 파일째) - 일위대가 줄 모달: 로직 줄 · 셈 주입 줄 = 안내 한 줄(856-3 까지) · 상세 · [적용] 걷음 · 줄 패치 칸 · 타입 걷음(저장본 0) - M01 LogicLab_Detail: M02 몸 칸 걷음(M01 보기 그대로) · 지운 파일만 쓰던 글 키 16 · CSS 규칙 걷음 - 시험: 지운 몸만 붙든 시험 지움(717_3 · 722 · 748_0 · helper 728_2 · 748_0) · 섞인 파일은 몸 꼴 · 글 대조 함수 · 줄만 지움(서버 셈 시험 남김) · 856-0 단언 뒤집음 - 수치: 열 때 /sangeun/calc 2 → 1 · 숨은 몸 DOM 2 → 0 · 화면 파일 줄 −1.9 천 안팎 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,142 +0,0 @@
|
||||
/* =============================================================================
|
||||
* M01_MasterData_UI_LogicLab_Cover.ts
|
||||
* 단가산출 상세 줄 「그 자리 고침」(PLAN 722-2 · 내역 16 · 17-2) — 줄 모달 안 수량 · 단가 칸.
|
||||
* 고침 꼴 = M02 단가산출 덮개 칸과 같음(`qty` · `labor` · `material` · `expense` — `M02_Sangeun_Doc._covered` 규칙 중 품 · 단가)
|
||||
* M02(724) = 고침 칸의 값을 고침 고리(`HoEdit.set`)로 받아 덮개로 보관 — M01 시험 고침은 840-1 에 걷음
|
||||
* 서버 셈 = 줄 `단가`(손 단가) · 로직 줄 `값묶음`(노 · 재 · 경) · `수량` 글 — `master_pick._priced` · `bundled` 가 읽음
|
||||
* ========================================================================== */
|
||||
|
||||
import { createButton, createInputField, el } from "@ui/ui_template_elements";
|
||||
import { currentLanguageIndex } from "@ui/ui_template_locale";
|
||||
import { createText } from "@ui/ui_template_text";
|
||||
|
||||
/* ── 순수 셈 ── */
|
||||
/** 줄 하나 고침 — 품(수량) · 비목 단가(로직 줄은 셋 · 그 밖은 그 줄 비목 하나) */
|
||||
export interface LineCover {
|
||||
qty?: number;
|
||||
labor?: number;
|
||||
material?: number;
|
||||
expense?: number;
|
||||
}
|
||||
export const COVER_PARTS = { labor: "노무비", material: "재료비", expense: "경비" } as const;
|
||||
export type CoverPart = keyof typeof COVER_PARTS;
|
||||
|
||||
/* ── 순수 셈 끝 ── */
|
||||
|
||||
const TEXT = {
|
||||
Head: ["그 자리 고침 (시험 값)", "Edit here (trial value)"],
|
||||
Note: [
|
||||
"정본 · 마스터 값(노임 · 자재)은 안 바뀜 · 로직을 다시 열면 사라짐",
|
||||
"Source and master prices stay unchanged · cleared when reopened",
|
||||
],
|
||||
NoteM02: [
|
||||
"고친 값은 이 단가산출의 변경 항목으로 저장 — M01 은 안 바뀜",
|
||||
"Saved as this item's override — M01 stays unchanged",
|
||||
],
|
||||
Qty: ["수량(품)", "Quantity"],
|
||||
Price: ["단가", "Unit price"],
|
||||
Apply: ["적용", "Apply"],
|
||||
Undo: ["되돌림", "Undo"],
|
||||
Bad: ["0 이상 수만", "Numbers ≥ 0 only"],
|
||||
} as const satisfies Record<string, readonly [string, string]>;
|
||||
export const tc = (k: keyof typeof TEXT): string =>
|
||||
TEXT[k][currentLanguageIndex as 0 | 1] ?? TEXT[k][0];
|
||||
|
||||
export interface CoverFormOptions {
|
||||
/** 지금 값(덮기 전 셈 값) — 칸 처음 값 */
|
||||
qty: number | null;
|
||||
/** 단가 칸 — 로직 줄 = 셋(1 단위 비목 값) · 그 밖 = 그 줄 비목 하나 */
|
||||
prices: Partial<Record<CoverPart, number | null>>;
|
||||
/** 지금 든 고침(있으면 칸 처음 값 · [되돌림]) */
|
||||
cover?: LineCover;
|
||||
/** 「m02」 = 덮개 보관 안내 */
|
||||
scope?: "m01" | "m02";
|
||||
onApply: (cover: LineCover | null) => void;
|
||||
/** 모달 머리 단추 자리(닫기 왼쪽 · 748-1) — 주면 [적용] 이 거기로 */
|
||||
head?: HTMLElement;
|
||||
}
|
||||
|
||||
const num = (raw: string): number | null => {
|
||||
const v = Number(raw.replaceAll(",", "").trim());
|
||||
return raw.trim() !== "" && Number.isFinite(v) && v >= 0 ? v : null;
|
||||
};
|
||||
|
||||
/** 고침 칸 — 수량 · 단가(들) · [적용] [되돌림] · 바뀐 칸만 고침으로 넘김 */
|
||||
export function coverForm(o: CoverFormOptions): HTMLElement {
|
||||
const parts = Object.keys(o.prices) as CoverPart[];
|
||||
const field = (label: string, raw: number | null, mine?: number) => {
|
||||
const now = raw === null ? null : Number(raw.toPrecision(10)); // 칸 글 = 유효 10 자리 · 손대지 않으면 고침 아님
|
||||
const box = createInputField({
|
||||
label,
|
||||
value: String(mine ?? now ?? ""),
|
||||
compact: true,
|
||||
type: "text",
|
||||
});
|
||||
box.input.inputMode = "decimal";
|
||||
return { box, now };
|
||||
};
|
||||
const qty = field(tc("Qty"), o.qty, o.cover?.qty);
|
||||
const prices = parts.map((k) => ({
|
||||
k,
|
||||
...field(parts.length > 1 ? COVER_PARTS[k] : tc("Price"), o.prices[k] ?? null, o.cover?.[k]),
|
||||
}));
|
||||
const error = createText("", "error");
|
||||
error.hidden = true;
|
||||
const apply = (): void => {
|
||||
const next: LineCover = {};
|
||||
let bad = false;
|
||||
const take = (f: { box: { input: HTMLInputElement }; now: number | null }, was?: number) => {
|
||||
const v = num(f.box.input.value);
|
||||
if (v === null)
|
||||
return f.box.input.value.trim() === "" ? undefined : ((bad = true), undefined);
|
||||
return v !== f.now || was !== undefined ? v : undefined; // 셈 값 그대로면 고침 아님
|
||||
};
|
||||
const q = take(qty, o.cover?.qty);
|
||||
if (q !== undefined) next.qty = q;
|
||||
for (const p of prices) {
|
||||
const v = take(p, o.cover?.[p.k]);
|
||||
if (v !== undefined) next[p.k] = v;
|
||||
}
|
||||
error.textContent = tc("Bad");
|
||||
error.hidden = !bad;
|
||||
if (!bad) o.onApply(Object.keys(next).length ? next : null);
|
||||
};
|
||||
const applyButton = createButton({
|
||||
label: tc("Apply"),
|
||||
variant: "filled",
|
||||
size: 32,
|
||||
onClick: apply,
|
||||
});
|
||||
o.head?.append(applyButton);
|
||||
const actions = el("div", {
|
||||
className: "m01lab-cover__actions",
|
||||
children: [
|
||||
...(o.head ? [] : [applyButton]),
|
||||
...(o.cover
|
||||
? [
|
||||
createButton({
|
||||
label: tc("Undo"),
|
||||
variant: "ghost",
|
||||
size: 32,
|
||||
onClick: () => o.onApply(null),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
actions.hidden = !actions.childElementCount;
|
||||
return el("section", {
|
||||
className: "m01lab-cover",
|
||||
attrs: { "data-cover-form": "" },
|
||||
children: [
|
||||
el("strong", { text: tc("Head") }),
|
||||
createText(tc(o.scope === "m02" ? "NoteM02" : "Note"), "hint"),
|
||||
el("div", {
|
||||
className: "m01lab-cover__fields",
|
||||
children: [qty.box.root, ...prices.map((p) => p.box.root)],
|
||||
}),
|
||||
error,
|
||||
actions,
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -2,8 +2,7 @@
|
||||
* M01_MasterData_UI_LogicLab_Detail.ts
|
||||
* 「단가산출 로직」 상세 화면 — 컨테이너를 위에서 아래로
|
||||
* ① 기본정보(정본은 읽기 전용 · 비고만 고침 · 자체 로직은 이름 · 단위 · 출처도) ② 수식(줄 쌓기 804-2 · 804-6)
|
||||
* ③ M02 수식 문서 없는 줄(일위대가 줄 모달 등)만 단가산출 상세 몸(`cover` — 공용 부품 `_LogicLab_Ho.ts`)
|
||||
* 단가산출 상세 보기 · 자체 로직 시트 편집기 · 시험 고침은 840-1 에 걷음 — 자체 로직도 수식(줄 쌓기)에서 만들고 고침
|
||||
* 단가산출 상세 보기 · M02 상세 몸(856-1) · 자체 로직 시트 편집기 · 시험 고침은 840-1 에 걷음 — 자체 로직도 수식(줄 쌓기)에서 만들고 고침
|
||||
* ========================================================================== */
|
||||
|
||||
import { el } from "@ui/ui_template_elements";
|
||||
@@ -26,27 +25,10 @@ export interface DetailContext {
|
||||
onChange: () => void;
|
||||
/** 시스템 관리자 — 기본 로직 안내 글이 다름(시트에서 고침 / 보기만) */
|
||||
admin?: boolean;
|
||||
/** 717-2b M02 단가산출 — 수식 문서 없는 줄의 단가산출 상세 덩이(SK 셈 답 · 고침 표) */
|
||||
cover?: { ho: HTMLElement };
|
||||
/** 수식 탭 = 줄 쌓기 그릇(`A00_Common/line_stack_screen.ts` · 804-2 · 804-6) */
|
||||
stack?: HTMLElement;
|
||||
}
|
||||
|
||||
const section = (title: string, body: HTMLElement[], hint = ""): HTMLElement =>
|
||||
el("section", {
|
||||
className: "m01-logic__section m01lab__box",
|
||||
children: [
|
||||
el("div", {
|
||||
className: "m01-logic__section-head",
|
||||
children: [
|
||||
el("h3", { text: title }),
|
||||
...(hint ? [el("span", { className: "ui-text ui-text--muted", text: hint })] : []),
|
||||
],
|
||||
}),
|
||||
...body,
|
||||
],
|
||||
});
|
||||
|
||||
function infoBox(ctx: DetailContext): HTMLElement[] {
|
||||
const row = ctx.row;
|
||||
const own = isOwnLogic(row);
|
||||
@@ -140,7 +122,7 @@ function infoBox(ctx: DetailContext): HTMLElement[] {
|
||||
/** 자체 로직(키 GX…) — 정본은 아님 */
|
||||
export const isOwnLogic = (row: LogicRow): boolean => row.키.startsWith("GX");
|
||||
|
||||
/** 상세 화면(기본정보 · 수식 · M02 단가산출 상세 몸)을 `host` 에 쌓음 */
|
||||
/** 상세 화면(기본정보 · 수식)을 `host` 에 쌓음 */
|
||||
export function buildLabDetail(host: HTMLElement, ctx: DetailContext): void {
|
||||
// 다시 그리면 포커스가 빠짐 — 고치던 기본정보 칸을 기억해 되돌림
|
||||
const active = document.activeElement;
|
||||
@@ -148,11 +130,7 @@ export function buildLabDetail(host: HTMLElement, ctx: DetailContext): void {
|
||||
active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement
|
||||
? { node: active, from: active.selectionStart, to: active.selectionEnd }
|
||||
: null;
|
||||
host.replaceChildren(
|
||||
...infoBox(ctx),
|
||||
...(ctx.stack ? [ctx.stack] : []),
|
||||
...(ctx.cover ? [section(tl("Ho_Title"), [ctx.cover.ho])] : []),
|
||||
);
|
||||
host.replaceChildren(...infoBox(ctx), ...(ctx.stack ? [ctx.stack] : []));
|
||||
const own = kept?.node.dataset.own; // 기본정보 칸은 새로 만들어지므로 이름표로 다시 찾음
|
||||
const back = own ? host.querySelector<HTMLInputElement>(`[data-own="${own}"]`) : kept?.node;
|
||||
if (kept && back && (own || ctx.ownHost.contains(back))) {
|
||||
|
||||
@@ -1,689 +0,0 @@
|
||||
/* =============================================================================
|
||||
* M01_MasterData_UI_LogicLab_Ho.ts
|
||||
* 공용 「단가산출 상세」(PLAN 722-1 · 요구서 내역16 2장 6 · 7) — M01 단가산출 로직 상세가 씀 · (724) M02 단가산출 · 일위대가 모달도.
|
||||
* 하위 박스 = 서버 `묶음`(인력 · 재료 · 경비(장비) · 하위 — `/text` 줄 덧칸 714-1) · 계산 전 = 호표 종류로
|
||||
* · 장비 · 하위 로직 줄 = 박스 안 한 줄(노 · 재 · 경 몫 합) + 누르면 펼침(부른 로직 시간당 줄 · 몫 식 줄)
|
||||
* 박스 제목 바로 아래 = 그 박스 줄들이 쓰는 입력 고르기(`calc_sheet` 변수 칸 꼴 · 6 → 4 → 3 → 2 → 1 열 격자) +
|
||||
* 어느 박스도 안 쓰는 입력(공통 옵션)도 모든 박스에 같이(737-3 · 한 값 · 어디서 바꿔도 모두 따라감)
|
||||
* 「계산식」 열 = 값 든 식(「268,908 × 0.12」 · 서버 `글`) + 표 · 요소 · 로직 알약 + 그 줄 입력 칩 · 변수 이름 식(`이름글`)은 마우스 올리면
|
||||
* 맨 아래 = 한 줄 4 칸 — 비목 소계 셋(노무비 · 재료비 · 경비 — 장비 노무는 여기서 인력과 더해짐) + 계 · 화면(모달) 바닥에 붙음(737-1)
|
||||
* 줄 누름 = 그 줄 자료 모달(`_LogicLab_Modal.ts`) · 고침 고리(`edit`) 있으면 모달 안 「그 자리 고침」(`_LogicLab_Cover.ts`) · 값 = 서버 셈 그대로(박스 소계 · 비목 소계만 줄 금액 합 1 원 버림 751-3)
|
||||
* ========================================================================== */
|
||||
|
||||
import { createBadge } from "@ui/ui_template_badge";
|
||||
import { createCard } from "@ui/ui_template_card";
|
||||
import { el } from "@ui/ui_template_elements";
|
||||
import { currentLanguageIndex } from "@ui/ui_template_locale";
|
||||
import { emptyRow, tableRow, tableShell, type Column } from "@ui/ui_template_table";
|
||||
import { createText } from "@ui/ui_template_text";
|
||||
import { optionGrid, sheetFormula, varRow, type SheetUnfold } from "../A00_Common/calc_sheet";
|
||||
import type {
|
||||
CalcLine,
|
||||
ElementBrief,
|
||||
HoLine,
|
||||
LogicRow,
|
||||
NamedFormula,
|
||||
TextAnswer,
|
||||
TextLine,
|
||||
TextPiece,
|
||||
} from "./M01_MasterData_UI_Logic_Api";
|
||||
import { pctView } from "./M01_MasterData_UI_Logic_Api";
|
||||
import {
|
||||
formatLineMoney,
|
||||
formatMoney,
|
||||
formatNumber,
|
||||
formatPrice,
|
||||
} from "../common_util/common_util_money";
|
||||
import { tx } from "./M01_MasterData_UI_Logic_Text";
|
||||
import { coverForm, type CoverPart, type LineCover } from "./M01_MasterData_UI_LogicLab_Cover";
|
||||
import {
|
||||
condText,
|
||||
openMaterialModal,
|
||||
openNoteModal,
|
||||
openRefModal,
|
||||
openLogic,
|
||||
openTableModal,
|
||||
type PickCond,
|
||||
} from "./M01_MasterData_UI_LogicLab_Modal";
|
||||
import { buildFoot, FOOT_KEYS, type FootKey } from "./M01_MasterData_UI_LogicLab_Foot";
|
||||
import { rounddown } from "../B09_Estimation/B09_Estimation_Calc_Base";
|
||||
import { fragmentRow, type Fragment } from "./M01_MasterData_UI_LogicLab_Pill";
|
||||
import { tl } from "./M01_MasterData_UI_LogicLab_Text";
|
||||
|
||||
/* ── 순수 셈 ── */
|
||||
/** 박스로 묶을 줄 — 호표 차례 · 박스 이름 · 한 줄로 합칠지(장비 · 하위) · 금액 */
|
||||
export interface HoRowLike {
|
||||
idx: number;
|
||||
bundle: string;
|
||||
merge: boolean;
|
||||
amount: number | null;
|
||||
/** 합계 밖 줄(엔진 `합밖`) — 보이되 소계에 안 더함 */
|
||||
out?: boolean;
|
||||
}
|
||||
export interface HoMerged<T> {
|
||||
idx: number;
|
||||
몫: T[];
|
||||
금액: number | null;
|
||||
}
|
||||
export interface HoBox<T> {
|
||||
묶음: string;
|
||||
줄: (T | HoMerged<T>)[];
|
||||
소계: number;
|
||||
}
|
||||
const BOX_ORDER = ["인력", "재료", "경비", "하위"];
|
||||
|
||||
/** 줄 → 박스(인력 · 재료 · 경비 · 하위 차례) — 합칠 줄은 같은 박스 · 같은 호표 차례끼리 한 줄(몫 차례 그대로) ·
|
||||
* `always` 박스는 줄이 없어도 빈 박스로 */
|
||||
export function boxesOf<T extends HoRowLike>(list: T[], always: string[] = []): HoBox<T>[] {
|
||||
const boxes = new Map<string, HoBox<T>>();
|
||||
const take = (name: string): HoBox<T> => {
|
||||
let b = boxes.get(name);
|
||||
if (!b) boxes.set(name, (b = { 묶음: name, 줄: [], 소계: 0 }));
|
||||
return b;
|
||||
};
|
||||
always.forEach(take);
|
||||
const merged = new Map<string, HoMerged<T>>();
|
||||
for (const e of list) {
|
||||
const b = take(e.bundle);
|
||||
if (!e.out) b.소계 += e.amount ?? 0;
|
||||
if (!e.merge) {
|
||||
b.줄.push(e);
|
||||
continue;
|
||||
}
|
||||
const id = `${e.bundle}\n${e.idx}`;
|
||||
let m = merged.get(id);
|
||||
if (!m) {
|
||||
merged.set(id, (m = { idx: e.idx, 몫: [], 금액: null }));
|
||||
b.줄.push(m);
|
||||
}
|
||||
m.몫.push(e);
|
||||
m.금액 = m.금액 === null && e.amount === null ? null : (m.금액 ?? 0) + (e.amount ?? 0);
|
||||
}
|
||||
const rank = (x: string): number => (BOX_ORDER.includes(x) ? BOX_ORDER.indexOf(x) : 9);
|
||||
return [...boxes.values()].sort((a, b) => rank(a.묶음) - rank(b.묶음));
|
||||
}
|
||||
/* ── 순수 셈 끝 ── */
|
||||
|
||||
const TEXT = {
|
||||
인력: ["인력", "Labor"],
|
||||
재료: ["재료", "Material"],
|
||||
경비: ["경비(장비)", "Expense (equipment)"],
|
||||
하위: ["하위 로직", "Sub logic"],
|
||||
Common: ["공통 옵션", "Common options"],
|
||||
Basis: ["기준", "Basis"],
|
||||
Formula: ["계산식", "Formula"],
|
||||
Short: ["노 {a} · 재 {b} · 경 {c}", "L {a} · M {b} · E {c}"],
|
||||
Fold: ["누르면 펼침", "Click to expand"],
|
||||
Per: ["{n} — {v} 원/{u}", "{n} — {v} KRW/{u}"],
|
||||
Edited: ["시험 고침", "Trial edit"],
|
||||
EditedM02: ["변경 항목", "Override"],
|
||||
Out: ["합 밖", "Outside total"],
|
||||
} as const satisfies Record<string, readonly [string, string]>;
|
||||
const th = (k: keyof typeof TEXT): string => TEXT[k][currentLanguageIndex as 0 | 1] ?? TEXT[k][0];
|
||||
const boxName = (b: string): string => (b in TEXT ? th(b as keyof typeof TEXT) : b);
|
||||
|
||||
/** 고침 고리 — M01 = 시험 값(줄 사본) · M02 = 덮개 보관 · 열쇠 = 호표 줄 차례 */
|
||||
export interface HoEdit {
|
||||
covers: Record<number, LineCover>;
|
||||
set: (idx: number, cover: LineCover | null) => void;
|
||||
scope?: "m01" | "m02";
|
||||
/** (M02) 모달 덧 동작 — `head` = 닫기 왼쪽 단추(삭제) · `body` = 고침 칸 아래(기초 빼기 · 별도계상 등) */
|
||||
more?: (idx: number, close: () => void) => { head: HTMLElement[]; body: HTMLElement[] };
|
||||
}
|
||||
|
||||
/** 고친 줄 꼬리표 — M01 = 시험 고침 · M02 = 변경 항목 · 고침 없음 = "" */
|
||||
const editTag = (ctx: HoContext, idx: number): string =>
|
||||
ctx.edit?.covers[idx] ? th(ctx.edit.scope === "m02" ? "EditedM02" : "Edited") : "";
|
||||
|
||||
export interface HoContext {
|
||||
row: LogicRow;
|
||||
prices: Record<string, ElementBrief | null>;
|
||||
/** 마지막 시험 계산의 줄 — 호표 차례 뒤에 덧줄 */
|
||||
lines: CalcLine[] | null;
|
||||
/** 마지막 시험 계산의 읽는 식 줄(서버가 줌) */
|
||||
text: TextAnswer | null;
|
||||
/** 마지막으로 잘 받은 읽는 식 — `text` 가 멈춤이면 조각을 이걸로 */
|
||||
lastText?: TextAnswer;
|
||||
values: Record<string, string>;
|
||||
/** 박스 옵션 · 입력 칩 고침 — 시험 계산 입력 고침 + 다시 셈(없으면 고르기 · 칩 없음) */
|
||||
onInput?: (name: string, value: string) => void;
|
||||
/** 그 자리 고침 고리(없으면 모달은 보기만) */
|
||||
edit?: HoEdit;
|
||||
/** (M02 750-2) Ho 줄 차례 → SK 줄 cid — 읽는 식 줄을 `cid` 로 이음(이름 차례 추측 안 함) */
|
||||
cids?: string[];
|
||||
/** (M02 750-2) 재료 고름 = SK 문서 `고름`(줄 차례 → 고르는 길 · 없으면 모달은 보기만) — 없으면 시험 입력(M01) */
|
||||
pickMat?: (idx: number) => ((it: { ref: string; label: string }) => void) | undefined;
|
||||
}
|
||||
|
||||
type Group = "labor" | "material" | "cost" | "other";
|
||||
const OF_KIND: Record<string, Group> = { 인력: "labor", 재료: "material", 기계: "cost" };
|
||||
const OF_COST: Record<string, Group> = { 노무비: "labor", 재료비: "material", 경비: "cost" };
|
||||
const BOX_OF: Record<Group, string> = {
|
||||
labor: "인력",
|
||||
material: "재료",
|
||||
cost: "경비",
|
||||
other: "하위",
|
||||
};
|
||||
const COST_OF: Record<string, string> = { labor: "노무비", material: "재료비", cost: "경비" };
|
||||
const PART_OF: Record<Group, CoverPart> = {
|
||||
labor: "labor",
|
||||
material: "material",
|
||||
cost: "expense",
|
||||
other: "expense",
|
||||
};
|
||||
|
||||
/** 줄 종류가 셋 중 어디에도 안 들어가면 「그 밖」 — 다른 로직을 부르는 줄은 비목으로 */
|
||||
const groupOfHo = (item: HoLine): Group =>
|
||||
OF_KIND[item.종류] ?? (item.종류 === "로직" ? OF_COST[item.비목 ?? ""] : undefined) ?? "other";
|
||||
|
||||
interface Entry extends HoRowLike {
|
||||
group: Group;
|
||||
name: string;
|
||||
spec: string;
|
||||
unit: string;
|
||||
qty: string;
|
||||
/** 고른 수량 값(계산 답 `CalcLine.수량` · % 덧줄은 율) — 계산 전 「—」 */
|
||||
qtyValue: string;
|
||||
qtyFrag: Fragment[];
|
||||
/** 한 줄이 비목 몫으로 갈렸을 때 이 몫 이름(예 「노무비」) */
|
||||
share?: string;
|
||||
price: string;
|
||||
/** 갈리기 전 줄 단가(장비 한 줄 머리) */
|
||||
linePrice: string;
|
||||
extra: boolean;
|
||||
/** 계산 답 줄 · 서버 읽는 식 줄(붙기 전엔 없음) */
|
||||
line?: CalcLine;
|
||||
textLine?: TextLine;
|
||||
/** 고침 칸 — 로직 줄 = 노 · 재 · 경 · 그 밖 = 그 줄 비목 */
|
||||
logic: boolean;
|
||||
part: CoverPart;
|
||||
open: (self: Entry) => void;
|
||||
unitFrag?: Fragment[];
|
||||
piecesFrag?: Fragment[];
|
||||
unitRef?: string;
|
||||
unitText?: string;
|
||||
warn?: string;
|
||||
/** (M02 727-2) 출처 꼬리표 — 줄 덧칸 `꼬리표` · 칸 폭 고정 · 넘치면 말줄임 + 풍선 */
|
||||
source?: string;
|
||||
}
|
||||
|
||||
/** 서버 조각(`/text` 줄의 `조각`) → 칸 조각 — 요소·표·로직은 알약(글 = 조각 글) · 나머지는 글자 */
|
||||
function toFragments(pieces: TextPiece[], ctx: HoContext): Fragment[] {
|
||||
return pieces.map((piece): Fragment => {
|
||||
const dim = piece.깊이 ? { dim: true } : {};
|
||||
if (piece.kind !== "요소" && piece.kind !== "표" && piece.kind !== "로직")
|
||||
return { text: piece.글, ...dim };
|
||||
const ref = piece.참조;
|
||||
const open = (): void => {
|
||||
if (!ref) return openNoteModal(piece.글, tl("Pill_NoPick"));
|
||||
if (piece.kind === "표")
|
||||
openTableModal({ title: piece.글, table: ref.키, row: ref.줄 ?? ref.행, col: ref.열 });
|
||||
else if (piece.kind === "요소")
|
||||
openRefModal({ title: piece.글, ref: ref.키, prices: ctx.prices });
|
||||
else openLogic(ref.키);
|
||||
};
|
||||
return { pill: { label: piece.글, onClick: open }, ...dim };
|
||||
});
|
||||
}
|
||||
|
||||
/** 재료 고르기 줄 — `요소` 가 글 대신 {구분·상세구분·규격·대표} 객체 */
|
||||
const condOf = (item: HoLine): PickCond | null =>
|
||||
typeof item.요소 === "object" && item.요소 !== null ? (item.요소 as unknown as PickCond) : null;
|
||||
const condLabel = (cond: PickCond): string =>
|
||||
[cond.구분, cond.상세구분, cond.규격].filter(Boolean).join(" · ");
|
||||
const nameOf = (item: HoLine): string =>
|
||||
item.이름 ?? (condOf(item) ? condLabel(condOf(item)!) : item.요소);
|
||||
|
||||
/** 수량 칸 = 계산 답의 고른 수량(% 덧줄은 율) · 계산 전 「—」 */
|
||||
const qtyOf = (line?: CalcLine): string => (line ? formatNumber(pctView(line).qty) : "—");
|
||||
|
||||
/** 계산된 줄은 서버가 준 비목별 몫으로 나눔 — 로직을 부르는 줄 · 장비 줄도 노무비·재료비·경비로 갈림 */
|
||||
const spread = (e: Entry, line?: CalcLine): Entry[] => {
|
||||
const parts = Object.entries(line?.비목 ?? {}).filter(([, v]) => v !== 0);
|
||||
if (!parts.length) return [e];
|
||||
return parts.map(([k, v]) => ({
|
||||
...e,
|
||||
group: OF_COST[k] ?? "other",
|
||||
bundle: BOX_OF[OF_COST[k] ?? "other"],
|
||||
amount: v,
|
||||
...(parts.length > 1
|
||||
? {
|
||||
share: k,
|
||||
// 몫 줄 단가 = 단가 × (몫 금액 ÷ 줄 금액) — 곱하기 수량이 몫 금액과 맞게
|
||||
...(line && line.금액 && line.단가 != null
|
||||
? { price: formatPrice((line.단가 * v) / line.금액) }
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
};
|
||||
|
||||
/** 줄 모달 — 자료 보기 + (고리 있으면) 그 자리 고침 */
|
||||
function modalOf(e: Entry, ctx: HoContext, extra: { cond?: PickCond; item?: HoLine }): void {
|
||||
const middles: NamedFormula[] = ctx.row.중간 ?? [];
|
||||
const { cond, item } = extra;
|
||||
const line = e.line;
|
||||
const edit = ctx.edit;
|
||||
const perUnit = (k: string): number | null =>
|
||||
line && line.수량 ? ((line.원문?.비목 ?? line.비목)?.[k] ?? 0) / line.수량 : null; // 세부 줄 = 원문 몫(744-1)
|
||||
openMaterialModal({
|
||||
unitFrag: e.unitFrag,
|
||||
unitRef: line?.품목?.키 ?? e.unitRef,
|
||||
unitText: e.unitText,
|
||||
qtyFrag: e.piecesFrag,
|
||||
title: e.name,
|
||||
expr: e.qty,
|
||||
...(item ? (cond ? { cond, unit: item.단위 } : { element: item.요소 }) : {}),
|
||||
prices: ctx.prices,
|
||||
middles,
|
||||
values: ctx.values,
|
||||
// 재료 줄 = 시험 계산 자재 칸과 같은 모달 — 고르면 시험 입력으로 다시 셈(정본 안 바뀜)
|
||||
kind: item?.종류,
|
||||
usedSlot: line?.품목?.값칸,
|
||||
...(item?.종류 === "재료" && ctx.pickMat ? { onPick: ctx.pickMat(e.idx) } : {}),
|
||||
// 덧줄(%) = M02 덮개만 율 고침(M01 시험 값은 호표 줄만)
|
||||
...(edit && (e.extra ? edit.scope === "m02" : item)
|
||||
? {
|
||||
edit: (close: () => void, head: HTMLElement) => {
|
||||
const form = coverForm({
|
||||
head,
|
||||
qty: line ? pctView(line).qty : null,
|
||||
prices: e.extra
|
||||
? {}
|
||||
: e.logic
|
||||
? {
|
||||
labor: perUnit("노무비"),
|
||||
material: perUnit("재료비"),
|
||||
expense: perUnit("경비"),
|
||||
}
|
||||
: { [e.part]: line ? line.단가 : null },
|
||||
cover: edit.covers[e.idx],
|
||||
scope: edit.scope,
|
||||
onApply: (c) => (close(), edit.set(e.idx, c)),
|
||||
});
|
||||
const more = edit.more?.(e.idx, close);
|
||||
head.append(...(more?.head ?? []));
|
||||
return more?.body.length ? el("div", { children: [form, ...more.body] }) : form;
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
function entries(ctx: HoContext): Entry[] {
|
||||
const ho = ctx.row.호표 ?? [];
|
||||
const out: Entry[] = ho.flatMap((item, i) => {
|
||||
const line = ctx.lines?.[i];
|
||||
const cond = condOf(item);
|
||||
const brief = cond ? ctx.prices[condText(cond)] : ctx.prices[item.요소];
|
||||
const price = line ? line.단가 : brief?.값;
|
||||
const group = groupOfHo(item);
|
||||
const shown = price === undefined || price === null ? "" : formatPrice(price);
|
||||
const entry: Entry = {
|
||||
idx: i,
|
||||
group,
|
||||
bundle: BOX_OF[group],
|
||||
merge: false,
|
||||
name: nameOf(item),
|
||||
spec: item.규격 ?? brief?.규격 ?? "",
|
||||
unit: item.단위 ?? "",
|
||||
qty: item.수량,
|
||||
qtyValue: qtyOf(line),
|
||||
qtyFrag: [{ text: item.수량 }],
|
||||
price: shown,
|
||||
linePrice: shown,
|
||||
amount: line ? line.금액 : null,
|
||||
out: !!line?.합밖,
|
||||
warn: line?.단위경고,
|
||||
extra: false,
|
||||
line,
|
||||
logic: item.종류 === "로직",
|
||||
part: OF_COST[item.비목 ?? ""] ? PART_OF[OF_COST[item.비목 ?? ""]] : PART_OF[group],
|
||||
open: (self) => modalOf(self, ctx, { cond: cond ?? undefined, item }),
|
||||
source: tagOf(item),
|
||||
};
|
||||
return spread(entry, line);
|
||||
});
|
||||
(ctx.row.덧줄 ?? []).forEach((extra, i) => {
|
||||
const line = ctx.lines?.[ho.length + i];
|
||||
const group = OF_COST[extra.비목 ?? ""] ?? "other";
|
||||
const entry: Entry = {
|
||||
idx: ho.length + i,
|
||||
group,
|
||||
bundle: BOX_OF[group],
|
||||
merge: false,
|
||||
name: extra.이름,
|
||||
spec: "",
|
||||
unit: line ? pctView(line).unit : "",
|
||||
qty: extra.식,
|
||||
qtyValue: qtyOf(line),
|
||||
qtyFrag: [{ text: extra.식 }],
|
||||
price: "",
|
||||
linePrice: "",
|
||||
amount: line ? line.금액 : null,
|
||||
out: !!line?.합밖,
|
||||
extra: true,
|
||||
line,
|
||||
logic: false,
|
||||
part: PART_OF[group],
|
||||
open: (self) => modalOf(self, ctx, {}),
|
||||
source: tagOf(extra),
|
||||
};
|
||||
out.push(...spread(entry, line));
|
||||
});
|
||||
attachPieces(out, ctx);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 서버 `/text` 줄을 호표 줄 차례(덧줄은 덧줄 차례)로 이음 — 서버는 비목마다 호표 차례대로 줄을 주므로
|
||||
* 이름을 차례로 따라가며 줄 차례에 맞춤 · 붙은 줄의 `묶음` · `장비` 로 박스를 정함 ·
|
||||
* 끝내 못 찾으면 날식 대신 빈칸(계산 전 · 서버 실패면 식 글자 그대로) */
|
||||
function attachPieces(all: Entry[], ctx: HoContext): void {
|
||||
const source = ctx.text?.ok ? ctx.text : ctx.lastText;
|
||||
if (!source?.ok) {
|
||||
if (ctx.text) for (const e of all) e.qtyFrag = e.piecesFrag = []; // 멈춤 · 받은 조각 없음 — 날식 대신 빈칸
|
||||
return;
|
||||
}
|
||||
const names = [...(ctx.row.호표 ?? []).map(nameOf), ...(ctx.row.덧줄 ?? []).map((x) => x.이름)];
|
||||
const found = new Map<string, TextLine>();
|
||||
const byCid = new Map((ctx.cids ?? []).map((c, i) => [c, i])); // M02 750-2 — cid 로 이음
|
||||
for (const g of source.groups) {
|
||||
let from = 0;
|
||||
for (const line of g.줄) {
|
||||
if (ctx.cids && line.cid) {
|
||||
const at = byCid.get(line.cid);
|
||||
if (at !== undefined) found.set(`${g.비목}|${at}`, line);
|
||||
continue;
|
||||
}
|
||||
const at = names.findIndex((n, i) => i >= from && n === line.이름);
|
||||
if (at < 0) continue;
|
||||
found.set(`${g.비목}|${at}`, line);
|
||||
from = at + 1;
|
||||
}
|
||||
}
|
||||
const costs = Object.keys(OF_COST);
|
||||
const fresh = ctx.lines !== null; // 묶음은 지금 셈 답에서만(옛 답의 묶음으로 박스를 안 옮김)
|
||||
for (const e of all) {
|
||||
const own = costs.find((c) => OF_COST[c] === e.group);
|
||||
const line = [own, ...costs].map((c) => found.get(`${c}|${e.idx}`)).find(Boolean);
|
||||
const pieces = line?.조각;
|
||||
e.qtyFrag = e.piecesFrag = pieces?.length ? toFragments(pieces, ctx) : [];
|
||||
if (line?.요소조각?.length) {
|
||||
e.unitFrag = toFragments(line.요소조각, ctx);
|
||||
const first = line.요소조각.find((piece) => piece.kind === "요소");
|
||||
e.unitRef = first?.참조?.키;
|
||||
e.unitText = first?.글;
|
||||
}
|
||||
if (!line || !fresh) continue;
|
||||
e.textLine = line;
|
||||
if (line.묶음) e.bundle = line.묶음;
|
||||
e.merge = !!line.장비 || line.묶음 === "하위";
|
||||
}
|
||||
}
|
||||
|
||||
const COLS: Column[] = [
|
||||
{ label: tl("Col_Name"), width: "20%" },
|
||||
{ label: tl("Col_Qty"), width: "9%", align: "end" },
|
||||
{ label: tl("Col_Unit"), width: "7%" },
|
||||
{ label: th("Formula"), width: "38%" },
|
||||
{ label: tl("Col_Price"), width: "13%", align: "end" },
|
||||
{ label: tl("Col_Amount"), width: "13%", align: "end" },
|
||||
];
|
||||
|
||||
const money = (v: number | null): string => (v === null ? "" : formatLineMoney(v)); // 줄 0.1 원(751-3)
|
||||
|
||||
/** 계산식 칸 — 값 든 식(계산 뒤) · 계산 전 = 수량 식 · 알약 · 이름 식은 풍선(748-3 옵션 값 꼬리표 없음) */
|
||||
function formulaCell(e: Entry, text = ""): HTMLElement {
|
||||
const tline = e.textLine;
|
||||
const main = text || (tline ? sheetFormula(tline.글) : e.qty);
|
||||
const pills = e.qtyFrag.some((f) => "pill" in f) ? [fragmentRow(e.qtyFrag)] : [];
|
||||
const cell = el("div", {
|
||||
className: "m01lab__qty-cell",
|
||||
children: [el("div", { className: "m01lab__qty-text", text: main }), ...(text ? [] : pills)],
|
||||
});
|
||||
cell.title = tline?.이름글 ?? e.qty;
|
||||
return cell;
|
||||
}
|
||||
|
||||
const tagOf = (x: object): string | undefined => (x as { 꼬리표?: string }).꼬리표 || undefined;
|
||||
const sourceTag = (text: string): HTMLElement => {
|
||||
const [shown, ...tip] = text.split("\n"); // 첫 줄 = 보임 · 나머지 = 풍선(없으면 같은 글) — 740-2
|
||||
const tag = createBadge(shown, "neutral");
|
||||
tag.classList.add("m01lab__src");
|
||||
tag.title = tip.length ? tip.join(" ") : shown;
|
||||
return tag;
|
||||
};
|
||||
|
||||
function nameCell(e: Entry, label: string, tag: string): HTMLElement {
|
||||
return el("div", {
|
||||
children: [
|
||||
e.source
|
||||
? el("div", {
|
||||
className: "m01lab__namerow", // 이름 옆에 꼬리표 — 줄 높이 안 바뀜(740-2)
|
||||
children: [el("span", { text: label }), sourceTag(e.source)],
|
||||
})
|
||||
: el("div", { text: label }),
|
||||
...(e.share && label === e.name ? [createBadge(`${e.share} ${tl("Share")}`, "accent")] : []),
|
||||
...(e.spec ? [el("div", { className: "ui-text ui-text--muted", text: e.spec })] : []),
|
||||
...(e.out ? [createBadge(th("Out"), "warning")] : []),
|
||||
...(e.warn ? [createBadge(`${tx("Calc_UnitWarn")} · ${e.warn}`, "warning")] : []),
|
||||
...(tag ? [createBadge(tag, "accent")] : []),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/** 못 셈 줄(725 · M02 단가산출) — 금액 「—」 + 까닭 풍선 */
|
||||
const gapCell = (why: string): HTMLElement => el("span", { text: "—", attrs: { title: why } });
|
||||
|
||||
/** 보통 줄 · 몫 줄 — 누르면 그 줄 모달 */
|
||||
function lineRow(e: Entry, ctx: HoContext, label = e.name): HTMLTableRowElement {
|
||||
const tag = editTag(ctx, e.idx);
|
||||
const tr = tableRow(COLS, [
|
||||
nameCell(e, label, e.share ? "" : tag),
|
||||
e.qtyValue,
|
||||
e.unit,
|
||||
formulaCell(e),
|
||||
e.price,
|
||||
e.line?.까닭 ? gapCell(e.line.까닭) : money(e.amount),
|
||||
]);
|
||||
tr.classList.add("m01lab__line");
|
||||
if (e.extra) tr.classList.add("m01lab__line--extra");
|
||||
if (tag) tr.classList.add("is-changed");
|
||||
tr.tabIndex = 0;
|
||||
tr.dataset.line = e.name;
|
||||
tr.addEventListener("click", () => e.open(e));
|
||||
tr.addEventListener("keydown", (ev) => ev.key === "Enter" && e.open(e));
|
||||
return tr;
|
||||
}
|
||||
|
||||
/** 펼친 장비 줄 — 로직 줄 객체마다 기억(다시 셈 · 다시 그려도 펼친 채) */
|
||||
const opened = new WeakMap<object, Set<number>>();
|
||||
const openOf = (row: object): Set<number> => {
|
||||
let got = opened.get(row);
|
||||
if (!got) opened.set(row, (got = new Set()));
|
||||
return got;
|
||||
};
|
||||
|
||||
/** 서버 줄 덧칸 — 장비 줄 펼침(714-1b · 부른 기계경비 로직 시간당 줄) */
|
||||
type Unfoldable = TextLine & { 펼침?: SheetUnfold | null };
|
||||
|
||||
/** 장비 · 하위 한 줄 — 머리(노 · 재 · 경 몫 + 합) · 누르면 펼침(부른 로직 시간당 줄 · 몫 줄) */
|
||||
function mergedRows(m: HoMerged<Entry>, ctx: HoContext): HTMLTableRowElement[] {
|
||||
const first = m.몫[0];
|
||||
const share = (cost: string): string =>
|
||||
formatLineMoney(
|
||||
m.몫
|
||||
.filter((x) => (x.share ?? COST_OF[x.group]) === cost)
|
||||
.reduce((s, x) => s + (x.amount ?? 0), 0),
|
||||
);
|
||||
const short = th("Short")
|
||||
.replace("{a}", share("노무비"))
|
||||
.replace("{b}", share("재료비"))
|
||||
.replace("{c}", share("경비"));
|
||||
const tag = editTag(ctx, m.idx);
|
||||
const head = tableRow(COLS, [
|
||||
nameCell(first, `▸ ${first.name}`, tag),
|
||||
first.qtyValue,
|
||||
first.unit,
|
||||
formulaCell(first, short),
|
||||
first.linePrice,
|
||||
money(m.금액),
|
||||
]);
|
||||
head.classList.add("m01lab__line");
|
||||
if (tag) head.classList.add("is-changed");
|
||||
head.dataset.equip = first.name;
|
||||
head.title = th("Fold");
|
||||
head.tabIndex = 0;
|
||||
head.setAttribute("aria-expanded", "false");
|
||||
const unfold = m.몫.map((x) => (x.textLine as Unfoldable | undefined)?.펼침).find(Boolean);
|
||||
const subs: HTMLTableRowElement[] = [
|
||||
...(unfold
|
||||
? [
|
||||
tableRow(COLS, [
|
||||
{
|
||||
content: createText(
|
||||
th("Per")
|
||||
.replace("{n}", unfold.이름)
|
||||
.replace("{v}", formatPrice(unfold.계 ?? 0))
|
||||
.replace("{u}", unfold.단위 || "-"),
|
||||
"hint",
|
||||
),
|
||||
colSpan: COLS.length,
|
||||
},
|
||||
]),
|
||||
...unfold.줄.map((x) =>
|
||||
tableRow(COLS, [
|
||||
`${x.이름} (${x.비목})`,
|
||||
"",
|
||||
"",
|
||||
sheetFormula(x.글),
|
||||
"",
|
||||
money(x.금액),
|
||||
]),
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...m.몫.map((x) => lineRow(x, ctx, `${x.share ?? first.name}`)),
|
||||
];
|
||||
for (const s of subs) {
|
||||
s.classList.add("is-sub");
|
||||
s.hidden = true;
|
||||
s.dataset.part = first.name;
|
||||
}
|
||||
const label = head.querySelector("td > div > div") as HTMLElement;
|
||||
const keep = openOf(ctx.row);
|
||||
const show = (open: boolean): void => {
|
||||
head.setAttribute("aria-expanded", String(open));
|
||||
label.textContent = `${open ? "▾" : "▸"} ${first.name}`;
|
||||
subs.forEach((s) => (s.hidden = !open));
|
||||
if (open) keep.add(m.idx);
|
||||
else keep.delete(m.idx);
|
||||
};
|
||||
const toggle = (): void => show(head.getAttribute("aria-expanded") !== "true");
|
||||
if (keep.has(m.idx)) show(true);
|
||||
head.addEventListener("click", toggle);
|
||||
head.addEventListener("keydown", (ev) => {
|
||||
if (ev.key !== "Enter" && ev.key !== " ") return;
|
||||
ev.preventDefault();
|
||||
toggle();
|
||||
});
|
||||
return [head, ...subs];
|
||||
}
|
||||
|
||||
/** 옵션 고르기 줄들 — 이름 차례 · 고르기 있으면 고르기 · 아니면 글 칸 */
|
||||
function optionRows(names: string[], ctx: HoContext): HTMLElement[] {
|
||||
const onInput = ctx.onInput;
|
||||
if (!onInput) return [];
|
||||
return (ctx.row.입력 ?? [])
|
||||
.filter((s) => names.includes(s.이름))
|
||||
.map((s) => varRow(s, ctx.values[s.이름] ?? "", (v) => onInput(s.이름, v)));
|
||||
}
|
||||
|
||||
const usesOf = (b: HoBox<Entry>): string[] => [
|
||||
...new Set(
|
||||
b.줄.flatMap((r) => ("몫" in r ? r.몫 : [r]).flatMap((e) => e.textLine?.쓰는입력 ?? [])),
|
||||
),
|
||||
];
|
||||
|
||||
/** `common` = 어느 박스 줄도 안 쓰는 입력 — 737-3 모든 박스 맨 위 옵션 칸에 같이(한 값 · 어디서 바꿔도 모두 따라감) */
|
||||
function boxCard(
|
||||
b: HoBox<Entry>,
|
||||
ctx: HoContext,
|
||||
calculated: boolean,
|
||||
common: string[],
|
||||
): HTMLElement {
|
||||
const name = boxName(b.묶음);
|
||||
const lines = b.줄.flatMap((r) => ("몫" in r ? r.몫 : [r]));
|
||||
const basis = [...new Set(lines.map((e) => e.textLine?.기준단위).filter(Boolean))];
|
||||
const notes = [...new Set(lines.map((e) => e.textLine?.환산근거).filter(Boolean))];
|
||||
const { root, tbody } = tableShell(COLS, { density: "data" });
|
||||
root.classList.add("m01lab__ho");
|
||||
// 753-2 옵션으로 빠진 줄은 안 그림(옵션 칸 · 소계는 그대로 — 옵션을 바꾸면 보이는 줄이 바뀜)
|
||||
const off = (e: Entry): boolean => !!(e.line?.옵션꺼짐 || e.textLine?.옵션꺼짐);
|
||||
const rows = b.줄.filter((r) => !("몫" in r ? r.몫.every(off) : off(r)));
|
||||
tbody.append(
|
||||
...(rows.length
|
||||
? rows.flatMap((r) => ("몫" in r ? mergedRows(r, ctx) : [lineRow(r, ctx)]))
|
||||
: [emptyRow(COLS, tl("Empty_Group"))]),
|
||||
);
|
||||
const sub = tableRow(COLS, [
|
||||
{ content: `${name} ${tl("Subtotal")}`, colSpan: 5 },
|
||||
calculated ? formatMoney(rounddown(b.소계, 0)) : "—", // 751-3 소계 1 원 버림
|
||||
]);
|
||||
sub.classList.add("m01lab__subtotal");
|
||||
sub.dataset.box = b.묶음;
|
||||
sub.dataset.subtotal = calculated ? String(b.소계) : "";
|
||||
tbody.append(sub);
|
||||
const card = createCard({
|
||||
title: name,
|
||||
pad: 12,
|
||||
body: [
|
||||
...(basis.length ? [createText(`${th("Basis")} ${basis.join(" · ")}`, "muted")] : []),
|
||||
...(notes.length ? [createText(notes.join(" · "), "hint")] : []),
|
||||
...optionGrid(optionRows([...usesOf(b), ...common], ctx)),
|
||||
root,
|
||||
],
|
||||
});
|
||||
card.classList.add("m01lab__ho-box");
|
||||
card.dataset.hoBox = b.묶음;
|
||||
return card;
|
||||
}
|
||||
|
||||
/** 박스가 하나도 없을 때만 — 어느 박스 줄도 안 쓰는 입력 한 카드 */
|
||||
function commonCard(rows: HTMLElement[]): HTMLElement {
|
||||
const card = createCard({ title: th("Common"), pad: 12, body: optionGrid(rows) });
|
||||
card.classList.add("m01lab__ho-box");
|
||||
card.dataset.hoBox = "common";
|
||||
return card;
|
||||
}
|
||||
|
||||
/** 748-2 텍스트 수식 줄 → 그 줄 자료 모달 열기(상세 줄과 같은 모달 · 못 찾으면 없음) */
|
||||
export function lineOpener(ctx: HoContext): (line: TextLine) => (() => void) | undefined {
|
||||
const by = new Map<TextLine, () => void>();
|
||||
for (const e of entries(ctx)) if (e.textLine) by.set(e.textLine, () => e.open(e));
|
||||
return (line) => by.get(line);
|
||||
}
|
||||
|
||||
/** 공용 단가산출 상세 몸 — 박스들(맨 위 옵션 칸 · 공통 옵션 포함) · 맨 아래 한 줄(비목 소계 셋 · 계) */
|
||||
export function buildHo(ctx: HoContext): HTMLElement[] {
|
||||
const all = entries(ctx);
|
||||
const calculated = ctx.lines !== null;
|
||||
const boxes = boxesOf(all, ["인력", "재료", "경비"]);
|
||||
const used = new Set(boxes.flatMap(usesOf));
|
||||
const common = (ctx.row.입력 ?? []).map((s) => s.이름).filter((n) => !used.has(n));
|
||||
const sums = Object.fromEntries(
|
||||
FOOT_KEYS.map((g) => [
|
||||
g,
|
||||
rounddown(
|
||||
all.filter((e) => e.group === g && !e.out).reduce((s, e) => s + (e.amount ?? 0), 0),
|
||||
),
|
||||
]),
|
||||
) as Record<FootKey, number>; // 751-3 비목 소계 = 줄 합 1 원 버림 · 계 = 셋 합(서버와 같은 값)
|
||||
const total = FOOT_KEYS.reduce((s, g) => s + sums[g], 0);
|
||||
return [
|
||||
...(boxes.length || !common.length ? [] : [commonCard(optionRows(common, ctx))]),
|
||||
...boxes.map((b) => boxCard(b, ctx, calculated, common)),
|
||||
// 737-1 맨 아래 한 줄 4 칸(노무비 · 재료비 · 경비 · 계) — 화면(모달) 바닥에 붙음
|
||||
buildFoot(sums, calculated, total),
|
||||
];
|
||||
}
|
||||
@@ -35,47 +35,6 @@
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
/* 칸 폭 고정(`table-layout: fixed`) — 인력·재료·경비 세 표가 저마다 딴 `<table>` 이라
|
||||
내용 기준으로 폭이 갈리던 것을 막고 셋이 같은 폭으로 맞춰짐(일감35 이어 — 수량 칸 알약화). */
|
||||
.m01lab__ho {
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
/* 열 = 이름 · 수량 · 단위 · 로직 · 단가 · 금액 */
|
||||
.m01lab__ho th:nth-child(1) {
|
||||
width: 22%;
|
||||
}
|
||||
|
||||
.m01lab__ho th:nth-child(2) {
|
||||
width: 9%;
|
||||
}
|
||||
|
||||
.m01lab__ho th:nth-child(3) {
|
||||
width: 7%;
|
||||
}
|
||||
|
||||
.m01lab__ho th:nth-child(4) {
|
||||
width: 36%;
|
||||
}
|
||||
|
||||
.m01lab__ho th:nth-child(5),
|
||||
.m01lab__ho th:nth-child(6) {
|
||||
width: 13%;
|
||||
}
|
||||
|
||||
.m01lab__line {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.m01lab__line:hover,
|
||||
.m01lab__line:focus {
|
||||
background: var(--color-paper);
|
||||
}
|
||||
|
||||
.m01lab__line--extra {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.m01lab__expr {
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: var(--text-body-sm);
|
||||
@@ -83,11 +42,6 @@
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* 수량 칸 — 알약 + 사칙연산 글자를 이어 붙이고, 칸 폭을 넘으면 그 칸 폭 기준으로 줄바꿈 */
|
||||
.m01lab__qty-cell {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.m01lab__qty-frags {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -102,11 +56,6 @@
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.m01lab__subtotal td {
|
||||
font-weight: 600;
|
||||
background: var(--color-paper);
|
||||
}
|
||||
|
||||
.m01lab__total {
|
||||
margin: var(--spacing-8) 0 0;
|
||||
font-weight: 700;
|
||||
@@ -199,13 +148,6 @@
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* 722-1 공용 단가산출 상세 — 하위 박스(카드) 안 · 옵션 줄 · 표 사이 간격 · 맨 아래 비목 소계 */
|
||||
.m01lab__ho-box > .ui-card__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-8);
|
||||
}
|
||||
|
||||
/* 737-1 맨 아래 한 줄 4 칸(노무비 · 재료비 · 경비 · 계) — 화면(모달) 바닥에 붙음 · 칸마다 이름 위 · 값 아래 */
|
||||
.m01lab__foot {
|
||||
position: sticky;
|
||||
@@ -240,10 +182,6 @@
|
||||
--m01lab-box-gap: var(--spacing-12);
|
||||
}
|
||||
|
||||
.m01lab__ho-box + .m01lab__ho-box {
|
||||
margin-top: var(--m01lab-box-gap, var(--spacing-12));
|
||||
}
|
||||
|
||||
.m01lab__foot .ui-calc-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -276,29 +214,3 @@
|
||||
.m01lab__foot .m01lab__total > :last-child {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 722-2 줄 모달 「그 자리 고침」 */
|
||||
.m01lab-cover {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-8);
|
||||
padding: var(--spacing-12);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
|
||||
.m01lab-cover__fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: var(--spacing-8);
|
||||
}
|
||||
|
||||
.m01lab-cover__actions {
|
||||
display: flex;
|
||||
gap: var(--spacing-8);
|
||||
}
|
||||
|
||||
.m01lab__ho-box .ui-card__title {
|
||||
font-size: var(--text-body);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@@ -20,18 +20,12 @@ const TEXT = {
|
||||
"자체 로직 — 이름 · 단위 · 출처 · 비고는 여기서 · 식은 수식에서 고침",
|
||||
"Own logic — edit the info here · formulas in the Equation view",
|
||||
],
|
||||
Ho_Title: ["단가산출 상세", "Unit-price detail"],
|
||||
View_Equation: ["수식", "Equation"],
|
||||
Subtotal: ["소계", "Subtotal"],
|
||||
Share: ["몫", "Share"],
|
||||
Total: ["계", "Total"],
|
||||
Extra: ["덧줄", "Extra"],
|
||||
Col_Name: ["이름", "Name"],
|
||||
Col_Unit: ["단위", "Unit"],
|
||||
Col_Qty: ["수량", "Quantity"],
|
||||
Col_Price: ["단가", "Price"],
|
||||
Col_Amount: ["금액", "Amount"],
|
||||
Empty_Group: ["줄 없음", "No lines"],
|
||||
Modal_Close: ["닫기", "Close"],
|
||||
Pill_Tone: ["요소 연결", "Linked element"],
|
||||
Modal_Sum: ["한 줄 풀이", "In one line"],
|
||||
|
||||
@@ -111,6 +111,7 @@ export function openImported(o: ImportedOptions): void {
|
||||
layer: o.target.layer,
|
||||
owner: o.target.owner,
|
||||
readOnly,
|
||||
mode: sk ? "ref" : "memory", // 856-1 저장 전 = 가져온 식 문서째 보기
|
||||
onChanged: (d) => (dirty ||= d),
|
||||
});
|
||||
draw();
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
type SubBrief,
|
||||
} from "../M01_MasterData/M01_MasterData_UI_Logic_Api";
|
||||
import type { LaborCalc, LaborFixed, LaborRef, LaborSpec } from "./M02_MasterTemplete_Labor_Calc";
|
||||
import type { LinePatch } from "./logic/M02_Sangeun_Cover_Model";
|
||||
import {
|
||||
call,
|
||||
getActiveLayer,
|
||||
@@ -109,8 +108,6 @@ export interface LaborRow {
|
||||
자재표시?: Record<string, MatMarks>;
|
||||
/** 고정 줄(705-1 · 705-2 붙여넣기) — 숫자 그대로 · 로직 · 참조 없음 */
|
||||
고정?: LaborFixed;
|
||||
/** 그 줄 덮개(715-3 · 717-3 단가산출 모달) — 로직 줄 · SK 참조 줄 · 서버가 검사 */
|
||||
패치?: LinePatch;
|
||||
/** 넣어 펼친 줄 출처(740-1 · 740-2 꼬리표) — {층, 주인, 키, 이름, 때} · 셈에 안 씀 */
|
||||
본뜬?: Record<string, unknown>;
|
||||
}
|
||||
@@ -205,7 +202,6 @@ export function normalizeLabor(doc: unknown, column: string): LaborDoc {
|
||||
...(r.승격 === true && !r.참조 ? { 승격: true } : {}),
|
||||
...(r.참조 || r.고정 ? {} : cleanShown(r.자재표시)),
|
||||
...(r.고정 ? { 고정: r.고정 } : {}), // 705-1 — 읽을 때 떨구면 [저장]에서 줄이 사라짐
|
||||
...(r.패치 ? { 패치: r.패치 } : {}), // 717-3 — 떨구면 [저장]에서 줄 덮개가 사라짐
|
||||
...(r.본뜬 ? { 본뜬: r.본뜬 } : {}), // 740-2 — 출처 꼬리표
|
||||
})),
|
||||
자재: (d.자재 ?? []).map((m) => ({
|
||||
|
||||
@@ -1,31 +1,24 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete_Labor_RowModal.ts
|
||||
* 일위대가표 줄 누름 모달(PLAN 723-2 · 723-3 · 요구서_내역16 2장 4 · 5) — 일위대가표에서 빠진 줄 동작을 모달 안으로.
|
||||
* · 로직 줄(단가산출 문서 없음) · 셈 주입 SK 줄 = 머리(이름 · 「1 ㎡ 당」) ·
|
||||
* 단가산출 상세 줄 모드(717-2b · `Labor_RowSk` · 수식 보기 하나(836-3) · 옛 [항목 추가] · [율 줄 추가] 없음) ·
|
||||
* 일위대가표 줄 누름 모달(PLAN 723-2 · 요구서_내역16 2장 4 · 5 · 856-1) — 일위대가표에서 빠진 줄 동작을 모달 안으로.
|
||||
* · 로직 줄(단가산출 문서 없음) · 셈 주입 줄(프로젝트 사본) = 머리(이름 · 「1 ㎡ 당」 · 옵션 값 · 메모) + 안내 한 줄
|
||||
* (856-1 — 옛 단가산출 상세 몸 · [적용] 걷음 · 고침 = 단가산출 줄 쌓기 · 856-3 에서 줄 쌓기 보기로) ·
|
||||
* 로직 자재(바꾸기 · 기본 · 세 칸 · `Labor_LogicMats`)
|
||||
* · [적용] = 그 줄 덮개(M02 변경 항목) + 옵션(상세 옵션 칸 → 그 줄 입력값)
|
||||
* · 808-1(요구 701-4 · 5) — 옛 [옵션] · [단가산출로도 저장] · [항목 추가] · [율 줄 추가] 걷음 · 일위대가 줄 = 저장 때
|
||||
* M01 로직 줄 + 고침으로 펼쳐 담김(740-1 · `본뜬` = 온 단가산출) → 수식 문서 없음 = 수식 보기 없이 단가산출 상세 몸만 +
|
||||
* 안내(온 단가산출 이름 · 수식은 그 단가산출에서 고쳐 다시 담음)
|
||||
* · 사용자 자재 줄 = 자재 모달(세 칸 · `Labor_MatTable` 한 줄)
|
||||
* · 고침 = 그 줄 화면 캐시(저장은 [저장]) · 금액은 표가 다시 셈 → `watch` 로 받아 다시 그림
|
||||
* ========================================================================== */
|
||||
|
||||
import { createBanner } from "@ui/ui_template_banner";
|
||||
import { createButton, el, showToast } from "@ui/ui_template_elements";
|
||||
import { askConfirm, openModal } from "@ui/ui_template_modal";
|
||||
import { el, showToast } from "@ui/ui_template_elements";
|
||||
import { openModal } from "@ui/ui_template_modal";
|
||||
import { createText } from "@ui/ui_template_text";
|
||||
import type { ItemLogic } from "./M02_MasterTemplete_Api_Fetch";
|
||||
import type { LaborCalc, LaborMat, LaborRow, MatMarkKey } from "./M02_MasterTemplete_Labor_Api";
|
||||
import { logicMatRows } from "./M02_MasterTemplete_Labor_LogicMats";
|
||||
import { setLogicMark, setMark } from "./M02_MasterTemplete_Labor_MatMarks";
|
||||
import { matTable } from "./M02_MasterTemplete_Labor_MatTable";
|
||||
import { mountRowSk, type RowSkHandle } from "./M02_MasterTemplete_Labor_RowSk";
|
||||
import { tc } from "./M02_MasterTemplete_Labor_Text";
|
||||
import type { SkScope } from "./M02_MasterTemplete_Sangeun_Cover";
|
||||
import { releaseTied } from "./M02_Labor_LogicMats_Model";
|
||||
import { keepKnown, valueLine } from "./M02_Labor_Values_Model";
|
||||
import { valueLine } from "./M02_Labor_Values_Model";
|
||||
|
||||
/** 표가 다시 센 답을 받음 — 돌려준 함수 = 그만 받음 */
|
||||
export type CalcWatch = (fn: (calc: LaborCalc | null) => void) => () => void;
|
||||
@@ -36,11 +29,8 @@ export interface RowModalOptions {
|
||||
title: string;
|
||||
/** 일위대가 머리(이름 · 「1 ㎡ 당」) */
|
||||
head: string;
|
||||
/** 줄 분모(SK 단위 기본) */
|
||||
unit: string;
|
||||
scope: SkScope;
|
||||
readOnly: boolean;
|
||||
/** 셈 주입(프로젝트 복사본) — 단가산출 상세 없음 */
|
||||
/** 셈 주입(프로젝트 복사본) — 안내 글이 다름 */
|
||||
inject: boolean;
|
||||
/** 사용자 자재 코드 — 로직 자재 [바꾸기]로 같은 품목 막음 */
|
||||
userMats: string[];
|
||||
@@ -50,16 +40,18 @@ export interface RowModalOptions {
|
||||
}
|
||||
|
||||
const TEXT = {
|
||||
Apply: ["적용", "Apply"],
|
||||
NoDoc: [
|
||||
"M01 로직을 바로 쓴 줄 — 수식 탭은 단가산출 문서가 있어야 열림(단가산출을 만들어 담음) · 여기서는 단가산출 상세만",
|
||||
"Uses the M01 logic directly — the equation tab needs a build-up document",
|
||||
"M01 로직을 바로 담은 줄 — 단가산출 화면 없음 · 고침은 단가산출로 담아(일위대가 [로직 추가]) 그 줄에서",
|
||||
"Uses the M01 logic directly — add it as a build-up to edit",
|
||||
],
|
||||
FromSk: [
|
||||
"단가산출 「{k}」 에서 담아 온 줄(담을 때 펼침) — 수식은 그 단가산출에서 고쳐 다시 담음 · 여기서는 단가산출 상세만",
|
||||
"Copied from build-up 「{k}」 — edit its equation there and re-add",
|
||||
"단가산출 「{k}」 에서 담아 온 줄 — 고침은 그 단가산출에서 고쳐 다시 담음",
|
||||
"Copied from build-up 「{k}」 — edit it there and re-add",
|
||||
],
|
||||
Inject: [
|
||||
"프로젝트 사본 줄 — 단가산출 화면 없음 · 수식 고침은 M02 단가산출에서 고쳐 [재생성]",
|
||||
"Project copy line — edit the build-up in M02 and regenerate",
|
||||
],
|
||||
Discard: ["적용 안 한 고침이 있음 — 버리고 닫을까?", "Discard unapplied edits?"],
|
||||
} as const;
|
||||
const t = (k: keyof typeof TEXT): string => TEXT[k][0];
|
||||
|
||||
@@ -69,7 +61,6 @@ export function openRowModal(o: RowModalOptions): void {
|
||||
const info = el("div", { attrs: { "data-row-head": "" } });
|
||||
const mats = el("div", { attrs: { "data-row-mats": "" } });
|
||||
let calc: LaborCalc | null = null;
|
||||
const line = () => calc?.줄.find((l) => !row.참조 && l.로직 === row.로직);
|
||||
|
||||
const draw = (): void => {
|
||||
const values = valueLine(o.logic?.입력 ?? [], row.입력값);
|
||||
@@ -117,84 +108,25 @@ export function openRowModal(o: RowModalOptions): void {
|
||||
);
|
||||
};
|
||||
|
||||
/** 옵션 → 그 줄 입력값(로직 줄만 · 아는 입력만) · 같으면 참 */
|
||||
function setValues(next: Record<string, string | number>): boolean {
|
||||
if (row.참조) return true;
|
||||
const values = o.logic ? keepKnown(o.logic.입력, next).kept : next;
|
||||
if (JSON.stringify(values) === JSON.stringify(row.입력값)) return true;
|
||||
const before = row.입력값;
|
||||
row.입력값 = values;
|
||||
releaseTied(row, before, line()?.재료 ?? []); // 바뀐 입력에 걸린 고름 = 기본(103-1)
|
||||
return false;
|
||||
}
|
||||
|
||||
// 단가산출 상세 줄 모드(723-3) — 셈 주입(프로젝트 복사본)엔 없음 · 수식 단추 = 모달 머리(808-1)
|
||||
const slot = el("span", { className: "m02-main__tools" });
|
||||
const skHost = el("div", { attrs: { "data-row-sk-host": "" } });
|
||||
let sk: RowSkHandle | null = null;
|
||||
const skMount = (): void => {
|
||||
if (o.inject) return;
|
||||
sk?.destroy();
|
||||
sk = mountRowSk(skHost, {
|
||||
row,
|
||||
scope: o.scope,
|
||||
title: o.title,
|
||||
unit: o.unit,
|
||||
readOnly: !edit,
|
||||
slot,
|
||||
});
|
||||
};
|
||||
let close = (): void => {};
|
||||
const finish = (): void => {
|
||||
stop();
|
||||
sk?.destroy();
|
||||
};
|
||||
const apply = createButton({
|
||||
label: t("Apply"),
|
||||
variant: "filled",
|
||||
onClick: () => {
|
||||
const got = sk?.take() ?? null;
|
||||
if (got) {
|
||||
if (got.patch) row.패치 = got.patch;
|
||||
else delete row.패치;
|
||||
setValues(got.values);
|
||||
o.done(true);
|
||||
draw();
|
||||
}
|
||||
finish(); // [적용] = 그 줄에 남기고 닫음(저장은 페이지 [저장]) · 코드 닫기는 beforeClose 안 거침
|
||||
close();
|
||||
},
|
||||
});
|
||||
// 수식 문서 없는 줄(808-1) — 안내 한 줄(온 단가산출 = `본뜬`)
|
||||
// 안내 한 줄(856-1) — 로직 줄 = 온 단가산출(`본뜬`) · 셈 주입 = 프로젝트 사본
|
||||
const from = row.본뜬 && typeof row.본뜬.이름 === "string" ? row.본뜬.이름 : "";
|
||||
const noDoc =
|
||||
!row.참조 && !o.inject
|
||||
? createBanner({
|
||||
tone: "info",
|
||||
text: from ? t("FromSk").replace("{k}", from) : t("NoDoc"),
|
||||
})
|
||||
: null;
|
||||
apply.dataset.rowApply = "";
|
||||
const note = createBanner({
|
||||
tone: "info",
|
||||
text: o.inject ? t("Inject") : from ? t("FromSk").replace("{k}", from) : t("NoDoc"),
|
||||
});
|
||||
const stop = o.watch((c) => {
|
||||
calc = c;
|
||||
draw();
|
||||
});
|
||||
const tools = edit && !o.inject ? [apply] : [];
|
||||
({ close } = openModal({
|
||||
openModal({
|
||||
title: o.title,
|
||||
closeLabel: tc("In_Close"),
|
||||
width: "1100px",
|
||||
wide: true,
|
||||
actions: row.참조 ? [slot, ...tools] : tools, // 로직 줄 = 머리 단추 없음(상세만)
|
||||
beforeClose: async () => {
|
||||
if (sk?.take() && !(await askConfirm({ message: t("Discard"), danger: true }))) return false;
|
||||
finish();
|
||||
return true;
|
||||
},
|
||||
mount: (body) => body.append(info, ...(noDoc ? [noDoc] : []), skHost, mats),
|
||||
}));
|
||||
beforeClose: () => (stop(), true),
|
||||
mount: (body) => body.append(info, note, mats),
|
||||
});
|
||||
draw();
|
||||
skMount();
|
||||
}
|
||||
|
||||
export interface MatModalOptions {
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete_Labor_RowSk.ts
|
||||
* 일위대가 줄 모달 안 단가산출 상세 = 717-2b 단가산출(SK) 상세 「줄 모드」(PLAN 723-3 · 정함 4 · 5).
|
||||
* · 줄 → 이름 없는 SK 문서(`lineDoc` · 고름 · 자재표시 = 바탕 줄 정체 cid) → `mountSangeunDetail` 그대로 얹음
|
||||
* (보기 넷 · 공용 상세(724-1 `LogicLab_Ho`) 줄 모달 품 · 단가 덮개 · 줄 빼기 · 더하기 · 박스 옵션 · 입력 칩)
|
||||
* · `take()` = [적용] 때 그 줄에 남길 것 — 패치 `{덮개, 뺀줄, 더한줄}`(M02 변경 항목 · M01 안 바뀜 · 내역 17-2) +
|
||||
* 옵션(시험 입력 → 그 줄 `입력값` · 정함 5)
|
||||
* · 옛 [단가산출로도 저장] 걷음(808-1 · 요구 701-4 — 일위대가 줄은 단가산출을 담아서만)
|
||||
* ========================================================================== */
|
||||
|
||||
import { el } from "@ui/ui_template_elements";
|
||||
import { createText } from "@ui/ui_template_text";
|
||||
import { fetchAuto } from "../M01_MasterData/M01_MasterData_UI_Logic_Api";
|
||||
import type { LaborRow } from "./M02_MasterTemplete_Labor_Api";
|
||||
import { calcSangeun, type SkScope } from "./M02_MasterTemplete_Sangeun_Cover";
|
||||
import { mountSangeunDetail } from "./M02_MasterTemplete_Sangeun_Detail";
|
||||
import { cleanPatch, lineDoc, needsIds, type LinePatch } from "./logic/M02_Sangeun_Cover_Model";
|
||||
|
||||
export interface RowSkHandle {
|
||||
/** 고친 것(패치 · 옵션) — 없으면 null */
|
||||
take: () => { patch: LinePatch | null; values: Record<string, string> } | null;
|
||||
destroy: () => void;
|
||||
}
|
||||
|
||||
const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
/** 줄 모드 SK 상세를 `host` 에 — 바탕 줄 정체가 필요하면 먼저 셈 */
|
||||
export function mountRowSk(
|
||||
host: HTMLElement,
|
||||
o: {
|
||||
row: LaborRow;
|
||||
scope: SkScope;
|
||||
title: string;
|
||||
unit: string;
|
||||
readOnly: boolean;
|
||||
/** 모달 머리 칸(808-1) — 보기 고르기 · 수식 단추(옛 [항목 추가] · [율 줄 추가] 줄 없음) */
|
||||
slot?: HTMLElement;
|
||||
},
|
||||
): RowSkHandle {
|
||||
let handle: ReturnType<typeof mountSangeunDetail> | null = null;
|
||||
let alive = true;
|
||||
/** 자동값(상세가 빈 입력에 채움) — 손대지 않은 자동값은 줄에 안 남김(빈 값 = 자동값 그대로) */
|
||||
let auto: Record<string, unknown> = {};
|
||||
const before = cleanPatch(o.row.패치);
|
||||
const values0 = Object.fromEntries(
|
||||
Object.entries(o.row.입력값 ?? {}).map(([k, v]) => [k, String(v)]),
|
||||
);
|
||||
host.replaceChildren(createText("…", "muted"));
|
||||
void (async () => {
|
||||
let ids: string[] | null = null;
|
||||
try {
|
||||
if (needsIds(o.row))
|
||||
ids = (await calcSangeun(o.scope, lineDoc(o.row, null, null))).정체 ?? null;
|
||||
} catch {
|
||||
ids = null; // 정체 못 받음 = 고름 · 자재표시 없이(셈 까닭은 상세가 보임)
|
||||
}
|
||||
if (!alive) return;
|
||||
const doc = {
|
||||
...lineDoc(o.row, ids, before),
|
||||
...(before?.뺀더한줄 ? { 뺀더한줄: before.뺀더한줄 } : {}), // 되살림 기억(744-1 · 셈엔 안 듦)
|
||||
이름: o.title,
|
||||
단위: o.unit || "식",
|
||||
};
|
||||
const box = el("div", { attrs: { "data-row-sk": "" } });
|
||||
host.replaceChildren(box);
|
||||
handle = mountSangeunDetail(box, doc, {
|
||||
layer: o.scope.layer,
|
||||
owner: o.scope.owner,
|
||||
readOnly: o.readOnly,
|
||||
onChanged: () => undefined,
|
||||
slot: o.slot,
|
||||
});
|
||||
if (o.row.로직 && !o.row.참조) auto = await fetchAuto(o.row.로직).catch(() => ({}));
|
||||
})();
|
||||
return {
|
||||
take: () => {
|
||||
if (!handle) return null;
|
||||
const d = handle.getDoc();
|
||||
const patch = cleanPatch({
|
||||
덮개: d.덮개 as LinePatch["덮개"],
|
||||
뺀줄: d.뺀줄,
|
||||
더한줄: d.더한줄,
|
||||
뺀더한줄: d.뺀더한줄,
|
||||
});
|
||||
const values = o.row.참조
|
||||
? values0
|
||||
: Object.fromEntries(
|
||||
Object.entries(handle.getValues()).filter(
|
||||
([k, v]) =>
|
||||
String(v).trim() !== "" &&
|
||||
(k in values0 || auto[k] == null || String(auto[k]) !== String(v)),
|
||||
),
|
||||
);
|
||||
return same(patch, before) && same(values, values0) ? null : { patch, values };
|
||||
},
|
||||
destroy: () => {
|
||||
alive = false;
|
||||
handle?.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -77,7 +77,7 @@ export async function openSkEdit(opt: SkEditOptions): Promise<void> {
|
||||
readOnly: opt.readOnly,
|
||||
onChanged: (d) => (dirty = d && !opt.readOnly),
|
||||
onVersion: (v) => (version = v), // 수식 저장이 파일 판을 바꿈 — 문서 저장이 이어 받음
|
||||
source: true, // 페이지와 같은 길 — 수식 저장 단추는 이 [저장] 한 번에 모임
|
||||
mode: "page", // 페이지와 같은 길 — 수식 저장 단추는 이 [저장] 한 번에 모임
|
||||
slot,
|
||||
});
|
||||
const ok = createButton({
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* 금액 빠짐) → 그 줄 금액 · 합계 바로(짝 셈 `Labor_Calc.settle`) · 구조물 조합 · 공사 알약이 이어지면 그 값이 앞섬
|
||||
* · 합계 열 = 「기준단위 단가」(줄 1 단위) · 「수량 반영 금액」(× 수량)
|
||||
* · 머리 단추 = [항목 추가](736-1 · 자재는 찾기 창에서 고름 → 자재 목록) · 줄 우클릭 · 줄 끝 ⋯ = 위로 · 아래로 · 별칭 · 삭제
|
||||
* · 줄 누름 = 줄 모달(`Labor_RowModal` — 옵션 · 메모 · 켜쌓기율 · 로직 자재 바꾸기 · 세 칸 · 단가산출) ·
|
||||
* · 줄 누름 = 줄 모달(`Labor_RowModal` — 옵션 · 메모 · 켜쌓기율 · 로직 자재 바꾸기 · 세 칸 · 안내 한 줄 · 856-1) ·
|
||||
* 사전조합 참조 줄 = 서고 원본 모달(`Labor_RefEdit`) · 사용자 자재 줄 = 자재 모달(세 칸)
|
||||
* · 금액 = 서버 calc(최신 응답만 · 저장 안 함) · [저장]은 UI_Main(서버가 다시 셈)
|
||||
* · 안 이은 고정 줄(729-3) = 격자 위 띠 · [연결](`Labor_Unlinked` — 이음만 · 저장은 [저장])
|
||||
@@ -333,7 +333,7 @@ export function mountLaborTable(
|
||||
closed: () => alive && recalc(),
|
||||
});
|
||||
if (row.고정) return; // 고정 줄 = 숫자 그대로(이름 · 별칭은 우클릭)
|
||||
// 단가산출(SK) 줄 = 그 단가산출 문서 모달(수식 탭 · 806-1) — 셈 주입(프로젝트 복사본)엔 옛 줄 모달
|
||||
// 단가산출(SK) 줄 = 그 단가산출 문서 모달(수식 탭 · 806-1) — 셈 주입(프로젝트 복사본)엔 줄 모달(안내 · 856-3 까지)
|
||||
if (isSkRef(row.참조) && !opt.calc)
|
||||
return void openSkEdit({
|
||||
ref: row.참조,
|
||||
@@ -347,9 +347,7 @@ export function mountLaborTable(
|
||||
logic: logics.get(row.로직) ?? null,
|
||||
title: nameOf(row),
|
||||
head: head(),
|
||||
unit: lineOf(row)?.분모 ?? "",
|
||||
watch,
|
||||
scope: { layer: opt.layer, owner: library.owner },
|
||||
readOnly: !edit,
|
||||
inject: !!opt.calc,
|
||||
userMats: cur.자재.map((m) => m.코드),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* M02 단가산출(SK) 상세 · 고침 표(PLAN 717-2b) — 표 · 단추 · 배지는 부품 상자 · 여기는 자리 · 고친 칸 색만 */
|
||||
/* M02 단가산출(SK) 화면(PLAN 717-2b · 856-1) — 표 · 단추 · 배지는 부품 상자 · 여기는 자리만 */
|
||||
|
||||
.m02-sk {
|
||||
display: flex;
|
||||
@@ -29,55 +29,9 @@
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.m02-sk__tags,
|
||||
.m02-sk__basehead,
|
||||
.m02-sk__removed,
|
||||
.m02-sk__removed-item {
|
||||
.m02-sk__tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.m02-sk__removed {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* 748-0 둘째 기초 머리 줄 — 이름 · 수량 칸 · 단추 한 줄 */
|
||||
.m02-sk__basehead {
|
||||
gap: var(--spacing-8);
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.m02-sk__basename {
|
||||
flex: 0 1 16em;
|
||||
min-width: 0;
|
||||
align-self: center;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
/* 740-2 이름 + 출처 꼬리표 한 줄 — 이름이 말줄임으로 줄고 꼬리표는 그대로 */
|
||||
.m02-sk .m01lab__namerow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.m02-sk .m01lab__namerow > span:first-child {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 727-2 기초 출처 꼬리표 — 칸 폭 고정 · 넘치면 말줄임(풍선 = 온 글) · 이름 칸 폭을 안 바꿈 */
|
||||
.m02-sk .m01lab__src {
|
||||
display: inline-block;
|
||||
flex: none;
|
||||
max-width: 9em;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete_Sangeun_BaseHead.ts
|
||||
* 단가산출(SK) 둘째 기초 머리 줄(PLAN 748-0) — 기초마다 한 줄: 이름 · 「수량(기준단위 몇 개)」 칸 하나 ·
|
||||
* [되돌림](넣을 때 수량으로) · [기초 빼기]. 세부 품은 M01 원문 그대로 보임(머리 수량은 이 칸 하나로).
|
||||
* 값은 문서 `더한줄[k].수량`(화면배 t 로 나눈 화면 값) — 금액은 서버가 셈 · 여기는 칸 · 단추만.
|
||||
* ========================================================================== */
|
||||
|
||||
import { createBadge } from "@ui/ui_template_badge";
|
||||
import { createButton } from "@ui/ui_template_button";
|
||||
import { createCard } from "@ui/ui_template_card";
|
||||
import { el } from "@ui/ui_template_elements";
|
||||
import { createInputField } from "@ui/ui_template_input";
|
||||
import { t as L } from "@ui/ui_template_locale";
|
||||
import { createText } from "@ui/ui_template_text";
|
||||
import type { SkAnswer, SkDoc } from "./logic/M02_Sangeun_Cover_Model";
|
||||
|
||||
export interface BaseHeadOptions {
|
||||
doc: SkDoc;
|
||||
ans: SkAnswer | null;
|
||||
edit: boolean;
|
||||
/** 칸에서 고른 새 수량(화면 값) */
|
||||
onQty: (k: number, qty: number) => void;
|
||||
onReset: (k: number) => void;
|
||||
onDrop: (k: number, name: string) => void;
|
||||
}
|
||||
|
||||
const shown = (v: number): string => String(Number(v.toPrecision(8)));
|
||||
const same = (a: number, b: number): boolean => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a));
|
||||
|
||||
/** 둘째 기초(더한줄 로직)마다 머리 줄 한 상자 — 없으면 빈 목록 */
|
||||
export function baseHeads(o: BaseHeadOptions): HTMLElement[] {
|
||||
const t = o.ans?.화면배 ?? 1;
|
||||
const rows = (o.doc.더한줄 ?? []).flatMap((one, k) => {
|
||||
if (one.종류 !== "로직") return [];
|
||||
const line = o.ans?.줄.find((x) => x.cid === `add:#${k}`);
|
||||
const name = line?.이름 || String(one.로직 ?? "");
|
||||
const box = createInputField({
|
||||
label: L("M02_SangeunBaseQty"),
|
||||
value: shown(one.수량 / t),
|
||||
compact: true,
|
||||
size: 28,
|
||||
});
|
||||
box.input.inputMode = "decimal";
|
||||
box.input.disabled = !o.edit;
|
||||
box.input.dataset.baseQty = String(k);
|
||||
box.input.addEventListener("change", () => {
|
||||
const v = Number(box.input.value.replaceAll(",", "").trim());
|
||||
if (box.input.value.trim() === "" || !Number.isFinite(v) || v < 0)
|
||||
return box.setError(L("M02_SangeunBaseQtyBad"));
|
||||
box.setError(undefined);
|
||||
if (!same(v, one.수량 / t)) o.onQty(k, v);
|
||||
});
|
||||
const first = one.처음수량;
|
||||
return [
|
||||
el("div", {
|
||||
className: "m02-sk__basehead",
|
||||
attrs: { "data-base-head": String(k) },
|
||||
children: [
|
||||
el("span", { className: "m02-sk__basename", text: name }),
|
||||
...(line?.꼬리표 ? [createBadge(line.꼬리표, "neutral")] : []),
|
||||
box.root,
|
||||
...(line?.단위 ? [createText(line.단위, "muted")] : []),
|
||||
...(o.edit && first != null && !same(first, one.수량)
|
||||
? [
|
||||
createButton({
|
||||
label: L("M02_SangeunQtyUndo"),
|
||||
variant: "ghost",
|
||||
size: 28,
|
||||
onClick: () => o.onReset(k),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(o.edit
|
||||
? [
|
||||
createButton({
|
||||
label: L("M02_SangeunDropBase"),
|
||||
variant: "danger-ghost",
|
||||
size: 28,
|
||||
onClick: () => o.onDrop(k, name),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
}),
|
||||
];
|
||||
});
|
||||
if (!rows.length) return [];
|
||||
const card = createCard({ title: L("M02_SangeunBases"), pad: 12, body: rows });
|
||||
card.classList.add("m01lab__ho-box"); // 상자 제목 · 안 간격 = 공용 상세 상자와 같음
|
||||
card.dataset.baseHeads = "";
|
||||
return [card];
|
||||
}
|
||||
@@ -1,72 +1,50 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete_Sangeun_Cover.ts
|
||||
* 단가산출(SK) 셈 길 부름 · 뺀 줄 띠(PLAN 717-2b · 717-3 · 724-1)
|
||||
* 단가산출(SK) 셈 길 부름(PLAN 717-2b · 856-1) — 머리 띠 · 배지용(856-2 에서 문서 답으로 바꾸고 이 파일 지움)
|
||||
* · 셈 = `calcSangeun`(`POST /layers/{층}/sangeun/calc` · 저장 안 함 · 부르는 쪽이 최신 응답만 받음)
|
||||
* · 고침 표는 공용 상세(`M01_MasterData_UI_LogicLab_Ho` · 724-1) — 여기는 뺀 줄 되살림 띠만
|
||||
* ========================================================================== */
|
||||
|
||||
import { createBadge } from "@ui/ui_template_badge";
|
||||
import { createButton } from "@ui/ui_template_button";
|
||||
import { el } from "@ui/ui_template_elements";
|
||||
import { t as L } from "@ui/ui_template_locale";
|
||||
import { createText } from "@ui/ui_template_text";
|
||||
import { call, type Layer } from "./M02_MasterTemplete_Api_Fetch";
|
||||
import type { SkAnswer } from "./logic/M02_Sangeun_Cover_Model";
|
||||
import "./M02_MasterTemplete_Sangeun.css";
|
||||
|
||||
export interface SkScope {
|
||||
layer: Layer;
|
||||
owner: string | null;
|
||||
}
|
||||
|
||||
/** SK 문서 중 화면 머리가 만지는 칸 */
|
||||
export interface SkDoc {
|
||||
키?: string;
|
||||
이름?: string;
|
||||
단위?: string;
|
||||
바탕?: { 로직?: string; 참조?: { 층?: string; 주인?: string | null; 키?: string } } | null;
|
||||
입력값?: Record<string, unknown>;
|
||||
바탕판?: string;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
||||
/** 셈 답 중 머리 띠 · 배지가 읽는 칸 */
|
||||
export interface SkAnswer {
|
||||
까닭?: string | null;
|
||||
/** 못 셈 줄(725) — 그 줄만 빠지고 나머지 셈 */
|
||||
빠진줄?: { cid: string; 이름: string; 까닭: string }[];
|
||||
짝잃음?: { cid: string; 까닭: string }[];
|
||||
바탕판: string;
|
||||
머리?: string;
|
||||
}
|
||||
|
||||
const q = (scope: SkScope): string =>
|
||||
scope.owner && scope.layer !== "system" ? `?owner=${encodeURIComponent(scope.owner)}` : "";
|
||||
|
||||
/** 셈(저장 안 함) — 문서 = 화면 문서 · `given` = 시험 입력(빈 칸 뺌) · 서버가 M01 엔진 한 벌로 셈 */
|
||||
export function calcSangeun<T = SkAnswer>(
|
||||
/** 셈(저장 안 함) — 문서 = 화면 문서 · `given` = 시험 입력(빈 칸 뺌) */
|
||||
export function calcSangeun(
|
||||
scope: SkScope,
|
||||
doc: Record<string, unknown>,
|
||||
given: Record<string, string> = {},
|
||||
seen = true,
|
||||
): Promise<T> {
|
||||
): Promise<SkAnswer> {
|
||||
const 입력값 = Object.fromEntries(Object.entries(given).filter(([, v]) => String(v).trim()));
|
||||
return call<T>(`/layers/${scope.layer}/sangeun/calc${q(scope)}`, {
|
||||
return call<SkAnswer>(`/layers/${scope.layer}/sangeun/calc${q(scope)}`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ 문서: doc, 입력값, 보기: seen }), // 보기 false = 글 · 중간 덧칸 안 지음(바탕 원값 셈)
|
||||
body: JSON.stringify({ 문서: doc, 입력값, 보기: false }), // 보기 false = 글 · 중간 덧칸 안 지음(몸 걷음 · 856-1)
|
||||
});
|
||||
}
|
||||
|
||||
/** 뺀 줄(cid · 이름) 띠 — 고칠 수 있으면 [되살림] */
|
||||
export function removedStrip(
|
||||
removed: { cid: string; 이름: string }[],
|
||||
edit: boolean,
|
||||
onRestore: (cid: string) => void,
|
||||
): HTMLElement[] {
|
||||
if (!removed.length) return [];
|
||||
return [
|
||||
el("div", {
|
||||
className: "m02-sk__removed",
|
||||
attrs: { "data-removed": "" },
|
||||
children: [
|
||||
createText(L("M02_SangeunRemoved")),
|
||||
...removed.map((x) =>
|
||||
el("span", {
|
||||
className: "m02-sk__removed-item",
|
||||
children: [
|
||||
createBadge(x.이름, "neutral"),
|
||||
...(edit
|
||||
? [
|
||||
createButton({
|
||||
label: L("M02_SangeunRestore"),
|
||||
variant: "ghost",
|
||||
size: 22,
|
||||
onClick: () => onRestore(x.cid),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
}),
|
||||
),
|
||||
],
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete_Sangeun_Detail.ts
|
||||
* M02 단가산출(SK) 상세(PLAN 717-2b · 724-1 · 요구서 4장 3 · 4 · 13 · 17 · 24) — M01 「단가산출 로직」 상세 부품을 M02 길로.
|
||||
* 보기 둘(`_Sangeun_Tabs` · 799-2) = 수식(공용 수식 문서 화면 · 802-4b-2 · 저장 = 페이지 [저장] 한 번(804-8 · 수식 먼저 → 판 · 수식 칸 새로)) · 단가산출 상세(공용 상세 `LogicLab_Ho` · SK 셈 답 줄 = `hoView` · 줄 모달 그 자리 고침 =
|
||||
* HoEdit → SK 덮개 · 더한줄 · 줄 빼기 · 별도계상) · 기본정보 = 바탕 로직(맨 위 접힘) — 시트 · 인력·재료·경비 · 시험 계산 · 텍스트 수식은 걷음
|
||||
* 고침 = SK 덮개 · 더한줄(`Sangeun_Pick`) · 뺀줄(꼴 = 서버 `M02_Sangeun_Doc`) · 값 = 서버 셈 길 최신 응답만
|
||||
* 옵션 칸 = SK `입력값`(727-3 · 저장 · 열린입력만 시험 값) · [저장] = 화면 문서 → 서버가 다시 셈(원값 · 바탕판)
|
||||
* 둘째 기초(727-2) = 서버 `펼침` 세부 줄 · 인력 · 재료 · 경비 상자에 함께 + 꼬리표(기초 둘 이상) · 세부 덮개 ·
|
||||
* 뺀줄 · [기초 빼기] · M01 개정 알림 · 옵션 칸 = 바탕 입력 + 더한줄 기초 입력
|
||||
* [항목 추가] 기초 = 바탕 비었으면 바탕(727-2 · 단위가 비거나 「식」이면 기초 결과단위) · 있으면 더한줄 · 바탕 없이 줄만도 됨
|
||||
* 단가산출 화면(`source` · 804-8) = M01 과 같은 꼴 — 보기 고르기는 페이지 머리 줄(`slot`) · [항목 추가] · [율 줄 추가] 걷음
|
||||
* (줄 더하기 = 수식 탭 [+] 단가산출 복사) · 수식 고침도 페이지 [저장] 한 번에(`flush` 먼저) · 고침 알림 = 기본 + 수식
|
||||
* M02 단가산출(SK) 화면(PLAN 717-2b · 804-8 · 856-1) — 머리(이름 · 단위 · 단위 환산 · 바탕) · 머리 띠 · 줄 쌓기(`_Sangeun_Tabs`).
|
||||
* 모드(856-1 · 옛 키 글자 약속 `SK-000000` 대신) = page(단가산출 화면 · 일위대가 SK 모달 — 원문 패널 · 페이지 [저장] 한 번 ·
|
||||
* 수식 먼저 → 판 · 수식 칸 새로) · ref(저장한 SK — 줄 쌓기 자기 저장 · 불러오기 저장 뒤) · memory(저장 전 가져온 식 · 보기만)
|
||||
* 머리 띠(까닭 · M01 개정 · 빠진 줄 · 짝 잃음) · 머리 배지 = 서버 셈 길 최신 응답(856-2 에서 문서 답으로)
|
||||
* 옛 상세 몸(덮개 · 뺀줄 · 더한줄 · 재료 고름 · 줄 모달)은 856-1 에 걷음 — 고침은 줄 쌓기 한 벌
|
||||
* ========================================================================== */
|
||||
|
||||
import { createBadge } from "@ui/ui_template_badge";
|
||||
import { createBanner } from "@ui/ui_template_banner";
|
||||
import { createButton } from "@ui/ui_template_button";
|
||||
import { createCheckbox } from "@ui/ui_template_checkbox";
|
||||
import { el } from "@ui/ui_template_elements";
|
||||
import { createInputField } from "@ui/ui_template_input";
|
||||
import { t as L } from "@ui/ui_template_locale";
|
||||
@@ -23,47 +16,25 @@ import { createText } from "@ui/ui_template_text";
|
||||
import {
|
||||
fetchLogic,
|
||||
setLogicApiPaths,
|
||||
type CalcLine,
|
||||
type LogicInput,
|
||||
type LogicOne,
|
||||
type LogicRow,
|
||||
type TextAnswer,
|
||||
} from "../M01_MasterData/M01_MasterData_UI_Logic_Api";
|
||||
import { buildLabDetail } from "../M01_MasterData/M01_MasterData_UI_LogicLab_Detail";
|
||||
import { buildHo, type HoEdit } from "../M01_MasterData/M01_MasterData_UI_LogicLab_Ho";
|
||||
import { readTemplate, type Layer } from "./M02_MasterTemplete_Api_Fetch";
|
||||
import { baseHeads } from "./M02_MasterTemplete_Sangeun_BaseHead";
|
||||
import { calcSangeun, removedStrip } from "./M02_MasterTemplete_Sangeun_Cover";
|
||||
import { calcSangeun, type SkAnswer, type SkDoc } from "./M02_MasterTemplete_Sangeun_Cover";
|
||||
import { createSangeunTabs } from "./M02_MasterTemplete_Sangeun_Tabs";
|
||||
import { tl } from "../M01_MasterData/M01_MasterData_UI_LogicLab_Text";
|
||||
import { createSangeunSide, tabOf, type SourceTab } from "./M02_MasterTemplete_Sangeun_Side";
|
||||
import { baseUnitOf, buildUnitSwap, type SwapHow } from "./M02_MasterTemplete_Sangeun_Unit";
|
||||
import {
|
||||
dropBase,
|
||||
dropLine,
|
||||
goneRows,
|
||||
hoView,
|
||||
removedSubs,
|
||||
restoreLine,
|
||||
revisedAdds,
|
||||
rowsOf,
|
||||
setApart,
|
||||
setLineCover,
|
||||
type CoverRow,
|
||||
type HoView,
|
||||
type SkAnswer,
|
||||
type SkDoc,
|
||||
} from "./logic/M02_Sangeun_Cover_Model";
|
||||
import { resetQty, setQty } from "./logic/M02_Sangeun_Undo";
|
||||
import { createSangeunSide, tabOf } from "./M02_MasterTemplete_Sangeun_Side";
|
||||
import { buildUnitSwap, type SwapHow } from "./M02_MasterTemplete_Sangeun_Unit";
|
||||
|
||||
export type SangeunMode = "page" | "ref" | "memory";
|
||||
|
||||
export interface SangeunDetailOptions {
|
||||
layer: Layer;
|
||||
owner: string | null;
|
||||
readOnly: boolean;
|
||||
onChanged: (dirty: boolean) => void;
|
||||
/** 752-1 오른쪽 원문 패널 — 단가산출 화면만 켬(일위대가 줄 모달 안 상세는 끔) */
|
||||
source?: boolean;
|
||||
/** 수식 탭 저장 뒤 그 SK 새 판(페이지 [저장] 409 막음 · 802-4b-2) */
|
||||
/** 856-1 화면 모드 — 머리 글 */
|
||||
mode: SangeunMode;
|
||||
/** 수식 저장 뒤 그 SK 새 판(페이지 [저장] 409 막음 · 802-4b-2) */
|
||||
onVersion?: (version: string) => void;
|
||||
slot?: HTMLElement; // 페이지 머리 줄 빈 자리(804-8) — 보기 고르기를 M01 처럼 머리 줄에
|
||||
}
|
||||
@@ -77,49 +48,38 @@ export function mountSangeunDetail(
|
||||
opt: SangeunDetailOptions,
|
||||
): {
|
||||
getDoc: () => SkDoc;
|
||||
getValues: () => Record<string, string>;
|
||||
/** 페이지 [저장] 앞 — 수식 고침 저장 · 실패면 던짐 */
|
||||
flush: () => Promise<void>;
|
||||
destroy: () => void;
|
||||
} {
|
||||
setLogicApiPaths(LIB); // 상세 부품 길 = M02 로그인 길(717-1)
|
||||
setLogicApiPaths(LIB); // 바탕 정보 길 = M02 로그인 길(717-1)
|
||||
const doc = clone((doc0 ?? {}) as SkDoc);
|
||||
let saved = JSON.stringify(doc);
|
||||
const edit = !opt.readOnly;
|
||||
const page = opt.mode === "page";
|
||||
const scope = { layer: opt.layer, owner: opt.owner };
|
||||
const values: Record<string, string> = Object.fromEntries(
|
||||
Object.entries(doc.입력값 ?? {}).map(([k, v]) => [k, String(v)]),
|
||||
);
|
||||
let base: LogicOne | null = null;
|
||||
let text: TextAnswer | null = null;
|
||||
let lastText: TextAnswer | undefined;
|
||||
let ans: SkAnswer | null = null;
|
||||
let bare: SkAnswer | null = null;
|
||||
let fail = "";
|
||||
let extra: LogicInput[] = []; // 더한줄 로직 입력 중 바탕에 없는 것 = 옵션 칸(725-6 · 727-3)
|
||||
const inputsOf = new Map<string, LogicInput[]>();
|
||||
const infoOf = new Map<string, SourceTab>(); // 더한줄 로직 → 원문 탭(752-1)
|
||||
let extraKeys: string[] = [];
|
||||
const side = opt.source ? createSangeunSide() : null;
|
||||
const side = page ? createSangeunSide() : null;
|
||||
let seq = 0;
|
||||
let alive = true;
|
||||
|
||||
const head = el("div", { className: "m02-sk__head", attrs: { "data-sk-head": "" } });
|
||||
const notes = el("div");
|
||||
const editor = el("div", { className: "m01-logic__editor" });
|
||||
let refreshing: Promise<void> = Promise.resolve();
|
||||
const tabs = createSangeunTabs(editor, {
|
||||
const tabs = createSangeunTabs({
|
||||
edit,
|
||||
scope,
|
||||
onSaved: (v) => void (refreshing = formulaSaved(v)),
|
||||
page: opt.source ? () => report() : undefined, // 804-8 페이지 [저장] · [되돌림]
|
||||
page: page ? () => report() : undefined, // 804-8 페이지 [저장] · [되돌림]
|
||||
// 836-5 저장 전 가져온 식(불러오기 미리 보기) = 그 문서째 수식 보기
|
||||
memory: () =>
|
||||
doc.가져온 && !/^SK-(?!0{6})\d{6}$/.test(doc.키 ?? "")
|
||||
? (doc as Record<string, unknown>)
|
||||
: null,
|
||||
memory: opt.mode === "memory" ? () => doc as Record<string, unknown> : undefined,
|
||||
});
|
||||
/** 수식 탭 저장 = 파일 판 · `수식` 칸이 바뀜 — 페이지 판 · 이 화면 문서 `수식` 을 새로(상세 탭 셈이 씀) */
|
||||
/** 수식 저장 = 파일 판 · `수식` 칸이 바뀜 — 페이지 판 · 이 화면 문서 `수식` 을 새로 */
|
||||
async function formulaSaved(version: string): Promise<void> {
|
||||
opt.onVersion?.(version);
|
||||
try {
|
||||
@@ -134,7 +94,6 @@ export function mountSangeunDetail(
|
||||
/* 못 읽음 = 다음 열기 때 새로 */
|
||||
}
|
||||
}
|
||||
const ownHost = el("div");
|
||||
const main = el("div", {
|
||||
className: "m02-sk",
|
||||
attrs: { "data-sangeun-detail": doc.키 ?? "" },
|
||||
@@ -143,60 +102,20 @@ export function mountSangeunDetail(
|
||||
notes,
|
||||
...(opt.slot ? [] : [el("div", { className: "m02-sk__head", children: [tabs.tools] })]),
|
||||
tabs.host,
|
||||
editor,
|
||||
],
|
||||
});
|
||||
host.replaceChildren(side ? side.wrap(main) : main);
|
||||
opt.slot?.replaceChildren(
|
||||
el("span", { className: "ui-toolbar m02-main__tools", children: [tabs.tools] }),
|
||||
);
|
||||
tabs.draw(opt.mode === "memory" ? "" : (doc.키 ?? ""));
|
||||
|
||||
const opened = (): boolean => (doc.열린입력 ?? []).length > 0;
|
||||
// 바탕 없는 SK 의 지문 = 이름 · 단위 따라 바뀜 — 바탕이 있을 때만 M01 개정으로 봄(725-3) · 둘째 기초 지문(727-2)
|
||||
// 바탕 없는 SK 의 지문 = 이름 · 단위 따라 바뀜 — 바탕이 있을 때만 M01 개정으로 봄(725-3)
|
||||
const revisedBase = (): boolean =>
|
||||
!!(doc.바탕 && doc.바탕판 && ans?.바탕판 && doc.바탕판 !== ans.바탕판) ||
|
||||
revisedAdds(ans, doc).length > 0;
|
||||
!!(doc.바탕 && doc.바탕판 && ans?.바탕판 && doc.바탕판 !== ans.바탕판);
|
||||
const baseKey = (): string | null => doc.바탕?.로직 ?? null;
|
||||
|
||||
/** 바탕 없는 · 참조 바탕 SK 의 기본정보 자리 줄 */
|
||||
const standIn = (): LogicRow => ({
|
||||
키: doc.키 ?? "",
|
||||
원문번호: "",
|
||||
이름: doc.이름 ?? "",
|
||||
결과단위: `원/${doc.단위 ?? ""}`,
|
||||
출처: doc.바탕?.참조?.키 ?? L("M02_SangeunNoBase"),
|
||||
입력: extra,
|
||||
중간: [],
|
||||
호표: [],
|
||||
덧줄: [],
|
||||
});
|
||||
|
||||
/** 더한줄 로직들의 입력을 모음(같은 이름은 하나 · 바탕 입력에 있는 이름 뺌) */
|
||||
async function syncExtra(): Promise<void> {
|
||||
const keys = [
|
||||
...new Set((doc.더한줄 ?? []).flatMap((x) => ("로직" in x ? [String(x.로직)] : []))),
|
||||
];
|
||||
await Promise.all(
|
||||
keys
|
||||
.filter((k) => !inputsOf.has(k))
|
||||
.map((k) =>
|
||||
fetchLogic(k).then(
|
||||
(r) => {
|
||||
inputsOf.set(k, r.logic.입력 ?? []);
|
||||
infoOf.set(k, tabOf(r.logic));
|
||||
},
|
||||
() => void inputsOf.set(k, []),
|
||||
),
|
||||
),
|
||||
);
|
||||
extraKeys = keys;
|
||||
const seen = new Set<string>((base?.logic.입력 ?? []).map((i) => i.이름));
|
||||
extra = keys
|
||||
.flatMap((k) => inputsOf.get(k) ?? [])
|
||||
.filter((i) => !seen.has(i.이름) && seen.add(i.이름));
|
||||
}
|
||||
|
||||
/** 고침 알림 — 기본(이름 · 단위 · 옵션 · 덮개) + 수식 탭 */
|
||||
/** 고침 알림 — 기본(이름 · 단위 · 환산) + 수식 */
|
||||
function report(): void {
|
||||
if (alive) opt.onChanged(edit && (JSON.stringify(doc) !== saved || tabs.dirty()));
|
||||
}
|
||||
@@ -206,23 +125,16 @@ export function mountSangeunDetail(
|
||||
else drawHead();
|
||||
};
|
||||
|
||||
/** 머리 띠 · 배지 = 서버 셈 한 번(최신 응답만) */
|
||||
async function recalc(): Promise<void> {
|
||||
const mine = ++seq;
|
||||
await syncExtra();
|
||||
if (mine !== seq || !alive) return;
|
||||
const plain = { ...doc, 덮개: {}, 뺀줄: [], 더한줄: [] };
|
||||
try {
|
||||
const [got, was] = await Promise.all([
|
||||
calcSangeun(scope, doc, values),
|
||||
doc.바탕 ? calcSangeun(scope, plain, values, false) : Promise.resolve(null), // 바탕 원값 = 보기 덧칸 없이
|
||||
]);
|
||||
const got = await calcSangeun(scope, doc, values);
|
||||
if (mine !== seq || !alive) return; // 늦게 온 답 — 버림
|
||||
[ans, bare, fail] = [got, was, ""];
|
||||
text = got.글 ?? null; // 750-2 텍스트 수식 · 시험 계산 = 이 답 하나(바탕 로직 따로 셈 없음)
|
||||
if (text?.ok) lastText = text;
|
||||
[ans, fail] = [got, ""];
|
||||
} catch (error) {
|
||||
if (mine !== seq || !alive) return;
|
||||
[ans, text, fail] = [null, null, error instanceof Error ? error.message : String(error)];
|
||||
[ans, fail] = [null, error instanceof Error ? error.message : String(error)];
|
||||
}
|
||||
draw();
|
||||
}
|
||||
@@ -241,7 +153,6 @@ export function mountSangeunDetail(
|
||||
};
|
||||
const baseName = base ? `${base.logic.키} ${base.logic.이름}` : null;
|
||||
const baseText = baseName ?? doc.바탕?.참조?.키 ?? L("M02_SangeunNoBase");
|
||||
const revised = revisedBase();
|
||||
const swap = base
|
||||
? buildUnitSwap({
|
||||
result: base.logic.결과단위,
|
||||
@@ -265,8 +176,7 @@ export function mountSangeunDetail(
|
||||
children: [
|
||||
createText(`${L("M02_SangeunBase")} · ${baseText}`, "muted", 14),
|
||||
...(ans?.머리 ? [createBadge(ans.머리, "info")] : []),
|
||||
...(revised ? [createBadge(L("M02_SangeunRevisedBase"), "danger")] : []),
|
||||
...(opened() ? [createBadge(L("M02_SangeunScaleOnly"), "warning")] : []),
|
||||
...(revisedBase() ? [createBadge(L("M02_SangeunRevisedBase"), "danger")] : []),
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -275,13 +185,13 @@ export function mountSangeunDetail(
|
||||
function drawNotes(): void {
|
||||
const lost = ans?.짝잃음 ?? [];
|
||||
const gaps = ans?.빠진줄 ?? [];
|
||||
const revised = revisedBase();
|
||||
|
||||
notes.replaceChildren(
|
||||
...(fail || ans?.까닭
|
||||
? [createBanner({ tone: "danger", text: fail || String(ans?.까닭) })]
|
||||
: []),
|
||||
...(revised ? [createBanner({ tone: "warning", text: L("M02_SangeunRevisedNote") })] : []),
|
||||
...(revisedBase()
|
||||
? [createBanner({ tone: "warning", text: L("M02_SangeunRevisedNote") })]
|
||||
: []),
|
||||
...(gaps.length
|
||||
? [
|
||||
createBanner({
|
||||
@@ -307,151 +217,11 @@ export function mountSangeunDetail(
|
||||
if (!alive) return;
|
||||
drawHead();
|
||||
drawNotes();
|
||||
const rows = ans ? rowsOf(ans, bare, doc) : [];
|
||||
const names = new Map((bare ? rowsOf(bare, null, {}) : []).map((r) => [r.cid, r.이름]));
|
||||
const removed = [
|
||||
...(doc.뺀줄 ?? []).map((cid) => ({ cid, 이름: names.get(cid) ?? cid })),
|
||||
...removedSubs(ans),
|
||||
...goneRows(doc), // 뺀 더한줄(744-1)
|
||||
];
|
||||
const row = base ? { ...base.logic, 입력: [...(base.logic.입력 ?? []), ...extra] } : standIn();
|
||||
const view = ans ? hoView(ans, bare, base?.logic ?? null, doc) : null;
|
||||
tabs.draw(/^SK-(?!0{6})\d{6}$/.test(doc.키 ?? "") ? (doc.키 ?? "") : ""); // SK-000000 = 줄 문서(808-1)
|
||||
const hoCtx = {
|
||||
row: view ? { ...row, 호표: view.호표, 덧줄: view.덧줄 } : row,
|
||||
prices: base?.prices ?? {},
|
||||
lines: (view?.lines ?? null) as CalcLine[] | null,
|
||||
text,
|
||||
lastText,
|
||||
values,
|
||||
onInput,
|
||||
edit: view && edit ? hoEdit(view, rows) : undefined,
|
||||
cids: view?.cids,
|
||||
pickMat: (idx: number) => pickMat(view?.cids[idx]),
|
||||
};
|
||||
const ho = el("div", {
|
||||
attrs: { "data-sk-cover": "" },
|
||||
children: [
|
||||
...removedStrip(removed, edit, (cid) => (restoreLine(doc, cid), touch())),
|
||||
...baseHeads({
|
||||
doc,
|
||||
ans,
|
||||
edit,
|
||||
onQty: (k, qty) => {
|
||||
const one = doc.더한줄?.[k];
|
||||
if (one) setQty(one, qty * (ans?.화면배 ?? 1));
|
||||
touch();
|
||||
},
|
||||
onReset: (k) => {
|
||||
const one = doc.더한줄?.[k];
|
||||
if (one) resetQty(one);
|
||||
touch();
|
||||
},
|
||||
onDrop: (k, name) => (dropBase(doc, k, name), touch()),
|
||||
}),
|
||||
...buildHo(hoCtx),
|
||||
],
|
||||
});
|
||||
buildLabDetail(editor, {
|
||||
row: base?.logic ?? row,
|
||||
file: base?.file ?? "",
|
||||
reasons: base?.reasons ?? [],
|
||||
ownHost,
|
||||
onChange: () => undefined,
|
||||
cover: { ho },
|
||||
});
|
||||
// prettier-ignore
|
||||
side?.set([
|
||||
...(base ? [tabOf(base.logic)] : []),
|
||||
...extraKeys.flatMap((k) => (k === baseKey() ? [] : infoOf.has(k) ? [infoOf.get(k)!] : [])),
|
||||
], doc);
|
||||
side?.set(base ? [tabOf(base.logic)] : [], doc);
|
||||
}
|
||||
|
||||
/** 재료 고름(줄 모달) = SK 문서 `고름`(cid → MT) — 둘째 기초 세부 줄은 보기만 */
|
||||
function pickMat(cid: string | undefined): ((it: { ref: string }) => void) | undefined {
|
||||
if (!cid || cid.startsWith("add:#")) return undefined;
|
||||
return (it) => {
|
||||
doc.고름 = { ...(doc.고름 ?? {}), [cid]: it.ref };
|
||||
touch();
|
||||
};
|
||||
}
|
||||
|
||||
/** 공용 상세 고침 고리 — 열쇠 = Ho 줄 차례 → cid · 고침 = SK 덮개 · 더한줄(M01 안 바뀜 · 내역 17-2) ·
|
||||
* 모달 덧 동작 = 줄 빼기 · 더한 재료 별도계상 */
|
||||
function hoEdit(view: HoView, rows: CoverRow[]): HoEdit {
|
||||
const by = new Map(rows.map((r) => [r.cid, r]));
|
||||
const at = (idx: number): CoverRow | undefined => by.get(view.cids[idx]);
|
||||
return {
|
||||
covers: view.covers,
|
||||
scope: "m02",
|
||||
set: (idx, c) => {
|
||||
const r = at(idx);
|
||||
if (!r) return;
|
||||
setLineCover(doc, r, c, opened());
|
||||
touch();
|
||||
},
|
||||
more: (idx, close) => {
|
||||
const r = at(idx);
|
||||
if (!r) return { head: [], body: [] };
|
||||
const drop = createButton({
|
||||
label: L("M02_SangeunDrop"),
|
||||
variant: "danger-ghost",
|
||||
size: 32,
|
||||
onClick: () => (close(), dropLine(doc, r), touch()),
|
||||
});
|
||||
drop.dataset.skDrop = "";
|
||||
const sub = r.sub;
|
||||
const whole = sub
|
||||
? [
|
||||
createButton({
|
||||
label: L("M02_SangeunDropBase"),
|
||||
variant: "danger-ghost",
|
||||
size: 28,
|
||||
onClick: () => (
|
||||
close(),
|
||||
dropBase(doc, sub.k, ans?.줄.find((x) => x.cid === `add:#${sub.k}`)?.이름),
|
||||
touch()
|
||||
),
|
||||
}),
|
||||
]
|
||||
: [];
|
||||
const apart = r.apartPick
|
||||
? [
|
||||
createCheckbox(L("M02_SangeunApart"), {
|
||||
chip: true,
|
||||
size: 28,
|
||||
checked: r.apart,
|
||||
onChange: (on) => (close(), setApart(doc, r, on), touch()),
|
||||
}).root,
|
||||
]
|
||||
: [];
|
||||
const rest = [...apart, ...whole];
|
||||
return {
|
||||
head: [drop],
|
||||
body: rest.length ? [el("div", { className: "m02-sk__tags", children: rest })] : [],
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 옵션 칸(수식 탭 · 단가산출 상세) — 입력 고침 → SK `입력값`(727-3 · 열린입력 = 시험 값만) · 셈 */
|
||||
function onInput(name: string, v: string): void {
|
||||
values[name] = v;
|
||||
if (edit && !(doc.열린입력 ?? []).includes(name)) {
|
||||
const kept = { ...(doc.입력값 ?? {}) };
|
||||
if (String(v).trim()) kept[name] = v;
|
||||
else delete kept[name];
|
||||
doc.입력값 = kept;
|
||||
touch(false);
|
||||
}
|
||||
void recalc(); // 750-2 옵션 바꿈 = 서버 셈 한 번 — 수식 · 단가산출 상세가 그 답 하나로 다시 그려짐
|
||||
}
|
||||
|
||||
/** `fresh` = 막 넣은 바탕 — 단위가 비거나 「식」이면 기초 기준단위(「100본」 · 바꾸면 서버가 환산 · 728-2) */
|
||||
async function loadBase(fresh = false): Promise<void> {
|
||||
async function loadBase(): Promise<void> {
|
||||
const key = baseKey();
|
||||
base = null;
|
||||
text = null;
|
||||
if (key) {
|
||||
try {
|
||||
base = await fetchLogic(key);
|
||||
@@ -460,28 +230,17 @@ export function mountSangeunDetail(
|
||||
}
|
||||
}
|
||||
if (!alive) return;
|
||||
if (fresh && base && (!doc.단위 || doc.단위 === "식")) {
|
||||
doc.단위 = baseUnitOf(base.logic.결과단위) || doc.단위;
|
||||
touch(false);
|
||||
}
|
||||
draw();
|
||||
await recalc(); // 바탕 정체(bare) 먼저 — 시험 계산 칸 항목(재료 잡힌 품목)이 쓰임
|
||||
await recalc();
|
||||
}
|
||||
|
||||
void loadBase();
|
||||
return {
|
||||
getDoc: () => {
|
||||
if (ans?.바탕판 && doc.바탕) doc.바탕판 = ans.바탕판; // 저장 = 지금 바탕 확인(서버가 다시 적음)
|
||||
for (const l of ans?.줄 ?? []) {
|
||||
const one = l.바탕판
|
||||
? doc.더한줄?.[Number(/^add:#(\d+)$/.exec(l.cid)?.[1] ?? -1)]
|
||||
: undefined;
|
||||
if (one) one.바탕판 = l.바탕판; // 둘째 기초도 같음(727-2)
|
||||
}
|
||||
saved = JSON.stringify(doc);
|
||||
return clone(doc);
|
||||
},
|
||||
getValues: () => ({ ...values }), // 723-3 — 일위대가 줄 모달 [적용] = 옵션을 그 줄에 남김
|
||||
flush: async () => {
|
||||
if (!tabs.dirty()) return;
|
||||
if (!(await tabs.save())) throw new Error(tl("View_Equation"));
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete_Sangeun_Tabs.ts
|
||||
* M02 단가산출(SK) 상세 보기(PLAN 799-2 · 804-2 · 804-6 · 836-3) — 수식(줄 쌓기) 하나 · 보기 고르기 단추 없음.
|
||||
* M02 단가산출(SK) 수식 그릇(PLAN 799-2 · 804-2 · 804-6 · 836-3 · 856-1) — 줄 쌓기 하나 · 보기 고르기 단추 없음.
|
||||
* 수식 = 공용 줄 쌓기 화면(`A00_Common/line_stack_screen.ts` · M01 과 같은 꼴) — 길 앞머리만 M02 사본 길
|
||||
* (`/m02/layers/{층}/sangeun/{키}/doc` · 802-4a) · 층 쓰기 권한 없으면 읽기만
|
||||
* 저장(804-8 · `page` 있음 = 단가산출 화면) = 페이지 [저장] · [되돌림] 한 번에 — 탭 위 저장 단추 없음(M01 과 같음)
|
||||
* 수식 문서 없는 줄(일위대가 줄 모달 등) = 상세가 쥔 `editor`(단가산출 상세 몸)만 보임 — 빈 화면 없음
|
||||
* 저장 안 한 SK(일위대가 줄 모달 · 새 SK) = 「저장한 단가산출만」 글
|
||||
* [단가 갱신] · [재생성](808-1 · 요구 701-3) = `tools` — 머리 줄(수식 보기일 때만)
|
||||
* [단가 갱신] · [재생성](808-1 · 요구 701-3) = `tools` — 머리 줄
|
||||
* ========================================================================== */
|
||||
|
||||
import { createStackScreen } from "../A00_Common/line_stack_screen";
|
||||
@@ -20,7 +18,7 @@ export interface SkEquationOptions {
|
||||
onSaved: (version: string) => void;
|
||||
/** 페이지가 저장 · 되돌림을 맡음(804-8) — 수식 고침 있음이 바뀔 때 부름 */
|
||||
page?: () => void;
|
||||
/** 저장 전 불러온 단가산출 문서(836-5 · 미리 보기 835-1) — 있으면 그 문서째 수식 보기 · 없으면 null */
|
||||
/** 저장 전 불러온 단가산출 문서(836-5 · 미리 보기 835-1) — 그 문서째 수식 보기 */
|
||||
memory?: () => Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
@@ -34,11 +32,8 @@ export function skDocPath(scope: SkEquationOptions["scope"], key: string, path:
|
||||
return ask ? `${at}?${ask}` : at;
|
||||
}
|
||||
|
||||
/** 수식 그릇 — `editor` = 단가산출 상세 그릇(수식 문서 있을 때 숨김) */
|
||||
export function createSangeunTabs(
|
||||
editor: HTMLElement,
|
||||
opt: SkEquationOptions,
|
||||
): {
|
||||
/** 수식 그릇 */
|
||||
export function createSangeunTabs(opt: SkEquationOptions): {
|
||||
/** 수식 화면 단추([단가 갱신] · [재생성]) — 머리 줄 */
|
||||
tools: HTMLElement;
|
||||
host: HTMLElement;
|
||||
@@ -62,20 +57,10 @@ export function createSangeunTabs(
|
||||
tools,
|
||||
memory: opt.memory,
|
||||
});
|
||||
const show = (doc: boolean): void => {
|
||||
stack.root.hidden = tools.hidden = !doc;
|
||||
editor.hidden = doc;
|
||||
};
|
||||
show(true);
|
||||
return {
|
||||
tools,
|
||||
host: el("div", { className: "m02-sk__views", children: [stack.root] }),
|
||||
draw: (k: string) => {
|
||||
// 문서 없는 줄(일위대가 로직 줄 모달 등 · 페이지 아님) = 단가산출 상세 몸만(808-1 · 수식은 문서가 있어야)
|
||||
const doc = !!k || !!opt.page || !!opt.memory?.();
|
||||
show(doc);
|
||||
if (doc) stack.draw(k);
|
||||
},
|
||||
draw: (k: string) => stack.draw(k),
|
||||
canLeave: () => stack.canLeave(),
|
||||
dirty: () => stack.dirty(),
|
||||
save: () => stack.save(),
|
||||
|
||||
@@ -23,7 +23,7 @@ export function mountSangeunView(
|
||||
doc: unknown,
|
||||
opt: SangeunViewOptions,
|
||||
): { getDoc: () => Promise<unknown>; destroy: () => void } {
|
||||
const one = mountSangeunDetail(host, doc, { ...opt, owner: opt.owner ?? null, source: true }); // 752-1
|
||||
const one = mountSangeunDetail(host, doc, { ...opt, owner: opt.owner ?? null, mode: "page" }); // 752-1 · 856-1
|
||||
return {
|
||||
getDoc: () => one.flush().then(() => one.getDoc()),
|
||||
destroy: () => one.destroy(),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* M02_Born_Tag.ts
|
||||
* 넣은 줄 출처 꼬리표(740-2 · 요구 581) — 서버 `본뜬 {층, 주인, 키, 이름, 때}`(740-1) → 화면 글.
|
||||
* 순수 계산 — 화면 · fetch 없음. 첫 줄 = 줄 옆에 보이는 짧은 글 · 둘째 줄 = 풍선(키 · 이름 · 층 · 때).
|
||||
* 공용 상세 꼬리표 칸(`LogicLab_Ho` sourceTag)이 「\n」 앞만 보이고 전체를 풍선으로 씀.
|
||||
* 격자 비고 칸 · 줄 풍선이 「\n」 앞만 보이고 전체를 풍선으로 씀.
|
||||
* ========================================================================== */
|
||||
|
||||
export interface Born {
|
||||
@@ -40,14 +40,5 @@ export function bornText(born: unknown, before = ""): string {
|
||||
return `${shown}\n${tip}`;
|
||||
}
|
||||
|
||||
/** 단가산출 줄 열쇠(`add:#k` · `add:#k/…`) → 그 더한줄의 꼬리표 글 */
|
||||
export function bornOfCid(cid: string, adds: readonly object[] | undefined, before = ""): string {
|
||||
const hit = /^add:#(\d+)/.exec(cid);
|
||||
return bornText(
|
||||
hit ? (adds?.[Number(hit[1])] as { 본뜬?: unknown } | undefined)?.본뜬 : undefined,
|
||||
before,
|
||||
);
|
||||
}
|
||||
|
||||
/** 격자 비고 칸 글 — 「본뜬 SK-000012」 · 없으면 "" (첫 줄만) */
|
||||
export const bornNote = (born: unknown): string => bornText(born).split("\n")[0];
|
||||
|
||||
@@ -1,627 +0,0 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete/logic/M02_Sangeun_Cover_Model.ts
|
||||
* 단가산출(SK) 고침 꼴(PLAN 717-2b · 717-3 · 724-1 — SK 상세 · 일위대가 줄 모드 같이 씀) —
|
||||
* 서버 셈 답(`/layers/{층}/sangeun/calc`) → 공용 상세(`M01_MasterData_UI_LogicLab_Ho`) 줄 · 계산서 줄 ·
|
||||
* 고친 칸(`LineCover` · 호표 차례 열쇠) → SK 문서 덮개 · 더한줄 · 뺀줄(꼴 = 서버 `M02_Sangeun_Doc`).
|
||||
* 금액은 늘 서버가 셈 — 여기는 줄 모양 · 문서 칸 옮김만.
|
||||
* 줄 정체 cid = `kind:키#n`(바탕 줄) · `add:#k`(더한줄 k 째) · 덮개 원값 = 저장 때 서버가 다시 적음
|
||||
* (화면은 고친 첫때 바탕 값을 적어 둠 — 곁 글용) · 열린입력 있는 SK = 품은 배율만
|
||||
* 일위대가 줄 → 이름 없는 SK 문서 = `lineDoc`(서버 `M02_Labor_Patch.as_doc` 꼴)
|
||||
* 둘째 기초(727-2) = 더한줄 로직 줄을 서버 `펼침`(세부 줄)으로 바꿔 놓음 · 열쇠 `add:#k/세부 cid` ·
|
||||
* 고침 = 그 더한줄의 `덮개` · `뺀줄`(품 = 화면 품 ÷ 수량 · 1 기준단위 몫) · 꼬리표 = 기초 둘 이상일 때만
|
||||
* SK 단위 환산(728-2) = 서버가 화면 줄을 SK 1 단위 몫으로(`화면배`) — 문서 품 = 화면 품 × 화면배(율 빼고)
|
||||
* 화면 · fetch · sessionStorage 없음(`CLAUDE.md` 4장).
|
||||
* ========================================================================== */
|
||||
|
||||
import type { CalcLine, TextAnswer } from "../../M01_MasterData/M01_MasterData_UI_Logic_Api";
|
||||
import { bornOfCid } from "./M02_Born_Tag";
|
||||
import { forgetAdd, goneName, reviveAdd, setQty, resetQty } from "./M02_Sangeun_Undo";
|
||||
|
||||
export type CoverPart = "labor" | "material" | "expense";
|
||||
export const PART_OF: Record<string, CoverPart> = {
|
||||
노무비: "labor",
|
||||
재료비: "material",
|
||||
경비: "expense",
|
||||
};
|
||||
const PARTS: CoverPart[] = ["labor", "material", "expense"];
|
||||
|
||||
export interface SkCover {
|
||||
qty?: number;
|
||||
배율?: number;
|
||||
labor?: number;
|
||||
material?: number;
|
||||
expense?: number;
|
||||
원값?: { qty?: number; 단가?: number };
|
||||
}
|
||||
|
||||
export interface SkAdded {
|
||||
종류?: string;
|
||||
수량: number;
|
||||
단가?: number;
|
||||
/** 둘째 기초 세부 고침(727-2) — 열쇠 = 세부 cid */
|
||||
덮개?: Record<string, SkCover>;
|
||||
뺀줄?: string[];
|
||||
바탕판?: string;
|
||||
/** 넣을 때 수량(744-1) — [되돌림] 값 */
|
||||
처음수량?: number;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
||||
/** SK 문서 중 고침이 만지는 칸 */
|
||||
export interface SkDoc {
|
||||
키?: string;
|
||||
이름?: string;
|
||||
단위?: string;
|
||||
바탕?: { 로직?: string; 참조?: { 층?: string; 주인?: string | null; 키?: string } } | null;
|
||||
입력값?: Record<string, unknown>;
|
||||
열린입력?: string[];
|
||||
덮개?: Record<string, SkCover>;
|
||||
더한줄?: SkAdded[];
|
||||
뺀줄?: string[];
|
||||
/** 뺀 더한줄 기억(744-1) — [되살림] = 그 차례에 다시 끼움 */
|
||||
뺀더한줄?: { 차례: number; 줄: SkAdded }[];
|
||||
고름?: Record<string, string>;
|
||||
자재표시?: Record<string, unknown>;
|
||||
바탕판?: string;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
||||
export interface SkLine {
|
||||
이름: string;
|
||||
단위?: string;
|
||||
수량: number | null;
|
||||
단가: number | null;
|
||||
금액: number | null;
|
||||
비목?: Record<string, number | null>;
|
||||
묶음?: string | null;
|
||||
cid: string;
|
||||
율?: number;
|
||||
/** % 줄 밑 이름(「노무비의 %」 · 율 줄 「인력의 %」) */
|
||||
규격?: string;
|
||||
/** 못 셈 줄(725) — 금액 없음 · 계에 안 듦 */
|
||||
까닭?: string;
|
||||
/** 둘째 기초(727-2) — 세부 줄 · 뺀 세부 · 그 기초 지문 · 원문번호 */
|
||||
펼침?: SkLine[];
|
||||
뺀세부?: { cid: string; 이름: string }[];
|
||||
바탕판?: string;
|
||||
꼬리표?: string;
|
||||
/** 세부 줄 — 덮기 전 1 기준단위 품 · 단가 */
|
||||
바탕값?: { qty?: number; 단가?: number } | null;
|
||||
/** 둘째 기초 세부 줄(744-1) — 그 기초 1 기준단위 몫(M01 원문 · 머리 수량 안 곱함) · 화면 품 칸 */
|
||||
원문?: { 수량: number | null; 금액: number | null; 비목?: Record<string, number | null> };
|
||||
/** 재료 줄이 잡은 품목(시험 계산 재료 칸 · 줄 모달) */
|
||||
품목?: CalcLine["품목"];
|
||||
/** (753-1) 옵션으로 빠진 줄 — 화면은 안 그림 */
|
||||
옵션꺼짐?: boolean;
|
||||
/** (796-2d) 합계에 안 드는 줄 — 엔진 표지 */
|
||||
합밖?: boolean;
|
||||
}
|
||||
|
||||
export interface SkMat {
|
||||
차례: number;
|
||||
이름: string;
|
||||
단위?: string;
|
||||
수량: number | null;
|
||||
단가: number | null;
|
||||
금액: number | null;
|
||||
}
|
||||
|
||||
export interface SkAnswer {
|
||||
기준: Record<string, number> | null;
|
||||
줄: SkLine[];
|
||||
재료?: SkMat[];
|
||||
까닭?: string | null;
|
||||
/** 못 셈 줄(725 · 입력 없음 · 수량 없음) — 그 줄만 빠지고 나머지 셈 */
|
||||
빠진줄?: { cid: string; 이름: string; 까닭: string }[];
|
||||
정체: string[];
|
||||
짝잃음: { cid: string; 까닭: string; 바탕?: string }[];
|
||||
바탕판: string;
|
||||
머리?: string;
|
||||
/** 바탕 원문번호(참조 바탕 = 그 키) */
|
||||
꼬리표?: string | null;
|
||||
/** 바탕 기준단위 → SK 단위 배(728-2) · 화면 줄을 나눈 배(없으면 1 · 문서 품 = 화면 품 × 화면배) */
|
||||
배?: number;
|
||||
화면배?: number;
|
||||
/** 보기 덧칸(750-1) — 텍스트 수식 글(줄마다 cid · 금액 = SK 줄) · 시험 계산 중간값 · 몸 `보기: false` 면 없음 */
|
||||
글?: TextAnswer;
|
||||
중간?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CoverRow {
|
||||
cid: string;
|
||||
묶음: string;
|
||||
이름: string;
|
||||
단위: string;
|
||||
수량: number | null;
|
||||
단가: number | null;
|
||||
금액: number | null;
|
||||
/** 비목 몫 금액 */
|
||||
parts: Record<string, number>;
|
||||
/** % 덧줄 — 수량 = 율 · 단가 못 고침 */
|
||||
pct: boolean;
|
||||
/** 더한줄 차례 · 바탕 줄 = null */
|
||||
added: number | null;
|
||||
/** 기준 밖 재료(일위대가 자재목록으로 셈) — 금액이 계에 안 듦 */
|
||||
apart: boolean;
|
||||
covered: { qty: boolean; price: boolean };
|
||||
/** 덮개 배율(열린입력 SK) */
|
||||
배율: number | null;
|
||||
/** 바탕 값(덮개 · 더한줄 · 뺀줄 없이 셈) · 없으면 null */
|
||||
was: { qty: number | null; 단가: number | null } | null;
|
||||
/** 저장 때 적힌 원값이 지금 바탕 값과 다름(M01 개정) */
|
||||
revised: boolean;
|
||||
priceEdit: boolean;
|
||||
/** 더한 재료 줄 — 별도계상 고름(기본 계 안) */
|
||||
apartPick: boolean;
|
||||
/** 둘째 기초 세부 줄 — 더한줄 차례 · 세부 cid · 수량(배) · 바탕 줄 · 그 밖 = null */
|
||||
sub: { k: number; cid: string; scale: number } | null;
|
||||
/** 화면배(728-2) — 문서 품 = 화면 품 × t · `was` = 문서 몫 */
|
||||
t: number;
|
||||
/** (753-2) 옵션으로 빠진 줄 — 계산서에서 안 그림 */
|
||||
off: boolean;
|
||||
}
|
||||
|
||||
/* ── 순수 셈 ── */
|
||||
const BUNDLE_OF: Record<string, string> = { 노무비: "인력", 재료비: "재료", 경비: "경비" };
|
||||
const ADD_RE = /^add:#(\d+)$/;
|
||||
const SUB_RE = /^add:#(\d+)\/(.+)$/;
|
||||
|
||||
/** 세부 열쇠 `add:#k/세부 cid` → {k, cid} */
|
||||
export function subOf(key: string): { k: number; cid: string } | null {
|
||||
const m = SUB_RE.exec(key);
|
||||
return m ? { k: Number(m[1]), cid: m[2] } : null;
|
||||
}
|
||||
|
||||
/** 셈 답 줄 — 둘째 기초 줄은 세부 줄로 바꿔 놓음(정체도 같은 차례) */
|
||||
export function flatLines(ans: SkAnswer): SkLine[] {
|
||||
return ans.줄.flatMap((l) => l.펼침 ?? [l]);
|
||||
}
|
||||
function flatIds(ans: SkAnswer): string[] {
|
||||
const by = new Map(ans.줄.map((l) => [l.cid, l]));
|
||||
return ans.정체.flatMap((c) => by.get(c)?.펼침?.map((x) => x.cid) ?? [c]);
|
||||
}
|
||||
|
||||
/** 율 더한줄(778-4) 비율 — `add:#k` 의 고정 `비율` · 아니면 undefined */
|
||||
const rateOf = (doc: SkDoc, cid: string): { 비목: string } | undefined => {
|
||||
const hit = ADD_RE.exec(cid);
|
||||
const one = hit ? doc.더한줄?.[Number(hit[1])] : undefined;
|
||||
return (one?.고정 as { 비율?: { 비목: string } } | undefined)?.비율;
|
||||
};
|
||||
|
||||
/** 기초 수 — 로직 바탕 · 더한줄 로직 */
|
||||
const baseCount = (doc: SkDoc): number =>
|
||||
(doc.바탕?.로직 ? 1 : 0) + (doc.더한줄 ?? []).filter((x) => x.종류 === "로직").length;
|
||||
|
||||
/** 줄 꼬리표(기초 둘 이상일 때만) — 바탕 줄 = 바탕 원문번호 · 세부 줄 = 그 기초 원문번호 · 그 밖 = "" */
|
||||
export function tagsOf(ans: SkAnswer, doc: SkDoc): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
if (baseCount(doc) < 2) return out;
|
||||
for (const l of ans.줄) {
|
||||
if (l.펼침) for (const x of l.펼침) out.set(x.cid, l.꼬리표 ?? "");
|
||||
else if (!ADD_RE.test(l.cid) && ans.꼬리표) out.set(l.cid, ans.꼬리표);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 뺀 세부 줄(되살림 띠) */
|
||||
export const removedSubs = (ans: SkAnswer | null): { cid: string; 이름: string }[] =>
|
||||
(ans?.줄 ?? []).flatMap((l) => l.뺀세부 ?? []);
|
||||
|
||||
/** M01 개정된 둘째 기초 — 저장 때 지문 ≠ 지금 지문 */
|
||||
export function revisedAdds(ans: SkAnswer | null, doc: SkDoc): number[] {
|
||||
return (ans?.줄 ?? []).flatMap((l) => {
|
||||
const hit = ADD_RE.exec(l.cid);
|
||||
const one = hit ? doc.더한줄?.[Number(hit[1])] : undefined;
|
||||
return one?.바탕판 && l.바탕판 && one.바탕판 !== l.바탕판 ? [Number(hit![1])] : [];
|
||||
});
|
||||
}
|
||||
const COVER_KEYS = ["qty", "배율", ...PARTS] as const;
|
||||
|
||||
const partsOf = (l: { 비목?: Record<string, number | null> }): Record<string, number> =>
|
||||
Object.fromEntries(Object.entries(l.비목 ?? {}).map(([k, v]) => [k, v ?? 0]));
|
||||
|
||||
/** 바탕 값 — 바탕 셈(덮개 · 더한줄 · 뺀줄 없이)의 줄마다 품(덧줄 = 율) · 단가 */
|
||||
export function baseValues(
|
||||
bare: SkAnswer | null,
|
||||
): Map<string, { qty: number | null; 단가: number | null }> {
|
||||
const out = new Map<string, { qty: number | null; 단가: number | null }>();
|
||||
if (!bare) return out;
|
||||
for (const l of bare.줄) out.set(l.cid, { qty: l.율 ?? l.수량, 단가: l.단가 });
|
||||
for (const m of bare.재료 ?? []) {
|
||||
const cid = bare.정체[m.차례];
|
||||
if (cid && !out.has(cid)) out.set(cid, { qty: m.수량, 단가: m.단가 });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const near = (a: number | null | undefined, b: number | null | undefined): boolean =>
|
||||
a != null && b != null && Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
|
||||
|
||||
/** 셈 답 → 표 줄(엔진 줄 + 기준 밖 재료) */
|
||||
export function rowsOf(ans: SkAnswer, bare: SkAnswer | null, doc: SkDoc): CoverRow[] {
|
||||
const was = baseValues(bare);
|
||||
const t = ans.화면배 ?? 1;
|
||||
const rows: CoverRow[] = [];
|
||||
const row = (
|
||||
cid: string,
|
||||
l: {
|
||||
이름: string;
|
||||
단위?: string;
|
||||
수량: number | null;
|
||||
단가: number | null;
|
||||
금액: number | null;
|
||||
},
|
||||
parts: Record<string, number>,
|
||||
extra: {
|
||||
묶음?: string | null;
|
||||
율?: number;
|
||||
apart?: boolean;
|
||||
바탕값?: SkLine["바탕값"];
|
||||
옵션꺼짐?: boolean;
|
||||
},
|
||||
): CoverRow => {
|
||||
const hit = ADD_RE.exec(cid);
|
||||
const added = hit ? Number(hit[1]) : null;
|
||||
const at = subOf(cid);
|
||||
const one = added === null ? undefined : doc.더한줄?.[added];
|
||||
const owner = at ? doc.더한줄?.[at.k] : undefined;
|
||||
const cover = at ? owner?.덮개?.[at.cid] : added === null ? doc.덮개?.[cid] : undefined;
|
||||
const pct = (at?.cid ?? cid).startsWith("pct:") || !!rateOf(doc, cid); // 덧줄 · 율 줄(778-4)
|
||||
const keys = Object.keys(parts);
|
||||
const shown = added === null && !at ? (was.get(cid) ?? null) : null;
|
||||
const base = at
|
||||
? subWas(extra.바탕값)
|
||||
: shown && !pct && shown.qty != null
|
||||
? { ...shown, qty: shown.qty * t }
|
||||
: shown;
|
||||
const old = cover?.원값;
|
||||
return {
|
||||
cid,
|
||||
묶음: extra.묶음 || BUNDLE_OF[keys[0] ?? ""] || "하위",
|
||||
이름: l.이름,
|
||||
단위: pct ? "%" : (l.단위 ?? ""),
|
||||
수량: pct ? (extra.율 ?? l.수량) : l.수량,
|
||||
단가: pct ? null : l.단가,
|
||||
금액: l.금액,
|
||||
parts,
|
||||
pct,
|
||||
added,
|
||||
apart: !!extra.apart,
|
||||
covered: {
|
||||
qty: !!cover && ("qty" in cover || "배율" in cover),
|
||||
price: added === null ? PARTS.some((k) => cover?.[k] != null) : one?.단가 != null,
|
||||
},
|
||||
배율: cover?.배율 ?? null,
|
||||
was: base,
|
||||
revised:
|
||||
!!old &&
|
||||
!!base &&
|
||||
((old.qty != null && !near(old.qty, base.qty)) ||
|
||||
(old.단가 != null && !near(old.단가, base.단가))),
|
||||
priceEdit: !pct && (added === null || ["인력", "재료", "기계"].includes(String(one?.종류))),
|
||||
apartPick: one?.종류 === "재료",
|
||||
sub: at ? { ...at, scale: Number(owner?.수량 ?? 1) } : null,
|
||||
t: pct || at ? 1 : t, // 세부 줄 품 = M01 원문 그대로(744-1) — 화면배 안 곱함
|
||||
off: !!extra.옵션꺼짐,
|
||||
};
|
||||
};
|
||||
for (const l of flatLines(ans)) rows.push(row(l.cid, l, partsOf(l), l));
|
||||
const seen = new Set(rows.map((r) => r.cid));
|
||||
for (const m of ans.재료 ?? []) {
|
||||
const cid = ans.정체[m.차례];
|
||||
if (!cid || seen.has(cid)) continue;
|
||||
rows.push(row(cid, m, { 재료비: m.금액 ?? 0 }, { 묶음: "재료", apart: true }));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
const subWas = (v: SkLine["바탕값"]): CoverRow["was"] =>
|
||||
v ? { qty: v.qty ?? null, 단가: v.단가 ?? null } : null;
|
||||
|
||||
const memo = (base: CoverRow["was"]): SkCover["원값"] | undefined => {
|
||||
if (!base) return undefined;
|
||||
const out: { qty?: number; 단가?: number } = {};
|
||||
if (base.qty != null) out.qty = base.qty;
|
||||
if (base.단가 != null) out.단가 = base.단가;
|
||||
return Object.keys(out).length ? out : undefined;
|
||||
};
|
||||
|
||||
function putCover(doc: SkDoc, r: CoverRow, cover: SkCover): void {
|
||||
const owner = r.sub ? doc.더한줄?.[r.sub.k] : doc;
|
||||
if (!owner) return;
|
||||
const key = r.sub?.cid ?? r.cid;
|
||||
const covers = { ...(owner.덮개 ?? {}) };
|
||||
if (COVER_KEYS.some((k) => cover[k] != null)) {
|
||||
const old = cover.원값 ?? memo(r.was);
|
||||
covers[key] = { ...cover, ...(old ? { 원값: old } : {}) };
|
||||
} else delete covers[key];
|
||||
if (r.sub && !Object.keys(covers).length) delete owner.덮개;
|
||||
else owner.덮개 = covers;
|
||||
}
|
||||
|
||||
/** 공용 상세 고침 칸(`LogicLab_Cover.LineCover` 와 같은 꼴) — 품 · 비목 단가(로직 줄 = 1 단위 노 · 재 · 경) */
|
||||
export type LineCover = Pick<SkCover, "qty" | CoverPart>;
|
||||
|
||||
/** 공용 상세 고침 한 줄 → 문서 — 더한줄 = 그 줄 수량 · 단가(요소 줄만) · 바탕 줄 = 덮개
|
||||
* (열린입력 SK = 품 대신 배율 = 고친 품 ÷ 바탕 품 · 바탕 값과 같은 품 = 덮개 안 둠) · `c` null = 고침 풂 */
|
||||
export function setLineCover(doc: SkDoc, r: CoverRow, c: LineCover | null, opened: boolean): void {
|
||||
const price = r.priceEdit ? PARTS.map((k) => c?.[k]).find((v) => v != null) : undefined;
|
||||
if (r.added !== null) {
|
||||
const one = doc.더한줄?.[r.added];
|
||||
if (!one) return;
|
||||
if (c?.qty != null) setQty(one, c.qty * r.t);
|
||||
else if (!c) resetQty(one); // [되돌림] = 넣을 때 수량(744-1)
|
||||
if (price == null) delete one.단가;
|
||||
else one.단가 = price;
|
||||
return;
|
||||
}
|
||||
const cover: SkCover = {};
|
||||
// 세부 줄 품 = 화면 품 그대로(M01 원문 = 1 기준단위 몫 · 744-1) — 화면배 · 머리 수량 안 곱함
|
||||
const qty = c?.qty == null ? c?.qty : c.qty * r.t;
|
||||
const open = opened && !r.sub; // 열린입력 = 바탕 입력 — 세부 줄은 품 그대로
|
||||
// ponytail: 열린입력 배율 = 고친 품 ÷ 바탕 품(바탕 품 0 · 없음 = 품 고침 못 함)
|
||||
if (qty != null && open && r.was?.qty) cover.배율 = qty / r.was.qty;
|
||||
if (qty != null && !open && !near(qty, r.was?.qty)) cover.qty = qty;
|
||||
if (r.priceEdit) for (const k of PARTS) if (c?.[k] != null) cover[k] = c[k];
|
||||
if (cover.배율 != null && near(cover.배율, 1)) delete cover.배율;
|
||||
putCover(doc, r, cover);
|
||||
}
|
||||
|
||||
/** 줄 빼기 — 더한줄 = 그 줄 지움 · 바탕 줄 = 뺀줄에 cid(덮개 · 고름 · 자재표시도 지움) */
|
||||
export function dropLine(doc: SkDoc, r: CoverRow): void {
|
||||
const one = r.sub ? doc.더한줄?.[r.sub.k] : undefined;
|
||||
if (one && r.sub) {
|
||||
one.뺀줄 = [...(one.뺀줄 ?? []).filter((c) => c !== r.sub!.cid), r.sub.cid];
|
||||
if (one.덮개) delete one.덮개[r.sub.cid];
|
||||
return;
|
||||
}
|
||||
if (r.added !== null) {
|
||||
forgetAdd(doc, r.added, r.이름); // 뺀더한줄 기억 — 744-1 [되살림]
|
||||
return;
|
||||
}
|
||||
doc.뺀줄 = [...(doc.뺀줄 ?? []).filter((c) => c !== r.cid), r.cid];
|
||||
for (const k of ["덮개", "고름", "자재표시"] as const) {
|
||||
const map = { ...((doc[k] as Record<string, unknown> | undefined) ?? {}) };
|
||||
delete map[r.cid];
|
||||
(doc as Record<string, unknown>)[k] = map;
|
||||
}
|
||||
}
|
||||
|
||||
/** 더한 재료 줄 별도계상 — 켬 = 계 밖(재료 목록만 · 서버 자재표시) · 끔 = 칸 지움(기본 계 안) */
|
||||
export function setApart(doc: SkDoc, r: CoverRow, on: boolean): void {
|
||||
const one = r.added === null ? undefined : doc.더한줄?.[r.added];
|
||||
if (!one || one.종류 !== "재료") return;
|
||||
if (on) one.별도계상 = true;
|
||||
else delete one.별도계상;
|
||||
}
|
||||
|
||||
/** 뺀 줄 되살림 — 세부 열쇠면 그 더한줄의 뺀줄 */
|
||||
export function restoreLine(doc: SkDoc, cid: string): void {
|
||||
const gone = /^gone:(\d+)$/.exec(cid); // 뺀 더한줄(744-1) — 그 차례에 다시 끼움
|
||||
if (gone) return reviveAdd(doc, Number(gone[1]));
|
||||
const at = subOf(cid);
|
||||
const one = at ? doc.더한줄?.[at.k] : undefined;
|
||||
if (one && at) {
|
||||
one.뺀줄 = (one.뺀줄 ?? []).filter((c) => c !== at.cid);
|
||||
if (!one.뺀줄.length) delete one.뺀줄;
|
||||
return;
|
||||
}
|
||||
doc.뺀줄 = (doc.뺀줄 ?? []).filter((c) => c !== cid);
|
||||
}
|
||||
|
||||
/** 둘째 기초 통째 빼기 — 그 더한줄을 뺌(기억 744-1 · 되살림 띠 글 = `name`) */
|
||||
export function dropBase(doc: SkDoc, k: number, name = ""): void {
|
||||
forgetAdd(doc, k, name);
|
||||
}
|
||||
|
||||
/** 뺀 더한줄 되살림 띠 항목 — 열쇠 `gone:n` */
|
||||
export const goneRows = (doc: SkDoc): { cid: string; 이름: string }[] =>
|
||||
(doc.뺀더한줄 ?? []).map((g, n) => ({ cid: `gone:${n}`, 이름: goneName(g.줄) }));
|
||||
|
||||
/* ── 공용 상세(Ho) 줄 ── */
|
||||
/** Ho 호표 · 덧줄 꼴(`M01_MasterData_UI_Logic_Api` HoLine · NamedFormula 중 쓰는 칸) */
|
||||
export interface HoItem {
|
||||
종류: string;
|
||||
요소: string;
|
||||
이름?: string;
|
||||
규격?: string;
|
||||
단위?: string;
|
||||
수량: string;
|
||||
비목?: string;
|
||||
/** 출처 꼬리표(727-2 · 기초 둘 이상) */
|
||||
꼬리표?: string;
|
||||
}
|
||||
export interface HoExtra {
|
||||
이름: string;
|
||||
식: string;
|
||||
비목?: string;
|
||||
꼬리표?: string;
|
||||
}
|
||||
export interface HoView {
|
||||
호표: HoItem[];
|
||||
덧줄: HoExtra[];
|
||||
/** Ho 줄 차례(호표 → 덧줄)의 셈 줄 — 셈 전 · 못 셈 = null · 별도계상 빠진 줄 = 빈 칸 */
|
||||
lines: (SkLine | undefined)[] | null;
|
||||
/** Ho 줄 차례 → cid(고침 열쇠 옮김) */
|
||||
cids: string[];
|
||||
/** Ho 줄 차례 → 지금 고침(덮개 · 더한줄) */
|
||||
covers: Record<number, LineCover>;
|
||||
}
|
||||
|
||||
const KIND_OF: Record<string, string> = { labor: "인력", material: "재료", machine: "기계" };
|
||||
const ELEMENT_KINDS = ["인력", "재료", "기계"];
|
||||
|
||||
/** SK 셈 답 → 공용 상세 줄 — 줄 차례 = 서버 `정체`(바탕 남은 호표 · 더한줄 · 바탕 남은 덧줄) ·
|
||||
* 바탕 로직 줄을 알면(`base` + 바탕 셈 `bare.정체` 차례) 그 줄 그대로(식 · 요소 · 규격) ·
|
||||
* 더한줄 = 문서 줄 · 그 밖(참조 바탕) = 셈 줄로 지음 */
|
||||
export function hoView(
|
||||
ans: SkAnswer,
|
||||
bare: SkAnswer | null,
|
||||
base: { 호표?: HoItem[]; 덧줄?: HoExtra[] } | null,
|
||||
doc: SkDoc,
|
||||
): HoView {
|
||||
const head = base?.호표 ?? [];
|
||||
const known = new Map<string, HoItem | HoExtra>();
|
||||
if (base && bare)
|
||||
bare.정체.forEach((cid, i) => {
|
||||
const it = i < head.length ? head[i] : base.덧줄?.[i - head.length];
|
||||
if (it) known.set(cid, it);
|
||||
});
|
||||
const lineBy = new Map(flatLines(ans).map((l) => [l.cid, l]));
|
||||
const tags = tagsOf(ans, doc);
|
||||
const t = ans.화면배 ?? 1;
|
||||
const single = (l?: SkLine): string | undefined => {
|
||||
const parts = Object.entries(l?.비목 ?? {}).filter(([, v]) => v);
|
||||
return parts.length === 1 ? parts[0][0] : undefined;
|
||||
};
|
||||
/** 세부 줄 = 수량만 M01 원문(금액 · 비목은 상자 합 몫 그대로) */
|
||||
const shown = (l?: SkLine): SkLine | undefined =>
|
||||
l?.원문 ? { ...l, 수량: l.원문.수량 ?? l.수량 } : l;
|
||||
const ho: [string, HoItem][] = [];
|
||||
const extra: [string, HoExtra][] = [];
|
||||
for (const cid of flatIds(ans)) {
|
||||
const l = lineBy.get(cid);
|
||||
const name = l?.이름 ?? cid;
|
||||
const at = subOf(cid);
|
||||
const born = bornOfCid(cid, doc.더한줄, tags.get(cid) ?? ""); // 넣은 줄 출처(740-2) — 기초 번호 뒤에 붙임
|
||||
const tag = born ? { 꼬리표: born } : {};
|
||||
if ((at?.cid ?? cid).startsWith("pct:")) {
|
||||
extra.push([cid, { ...((known.get(cid) as HoExtra) ?? { 이름: name, 식: "" }), ...tag }]);
|
||||
continue;
|
||||
}
|
||||
const rate = rateOf(doc, cid); // 율 더한줄(778-4) = 비목 상자 % 줄(식 = 「인력의 %」)
|
||||
if (rate) {
|
||||
extra.push([cid, { 이름: name, 식: String(l?.규격 ?? ""), 비목: rate.비목, ...tag }]);
|
||||
continue;
|
||||
}
|
||||
if (at) {
|
||||
const kind = KIND_OF[at.cid.split(":")[0]] ?? "로직";
|
||||
const qty = String(l?.율 ?? l?.원문?.수량 ?? l?.수량 ?? ""); // 세부 품 = M01 원문(744-1)
|
||||
const item = { 종류: kind, 요소: "", 이름: name, 단위: l?.단위 ?? "", 수량: qty };
|
||||
ho.push([cid, { ...item, 비목: single(l), ...tag }]);
|
||||
continue;
|
||||
}
|
||||
const hit = ADD_RE.exec(cid);
|
||||
const a = hit ? doc.더한줄?.[Number(hit[1])] : undefined;
|
||||
const kind = a
|
||||
? ELEMENT_KINDS.includes(String(a.종류))
|
||||
? String(a.종류)
|
||||
: "로직"
|
||||
: (KIND_OF[cid.split(":")[0]] ?? "로직");
|
||||
const made: HoItem = {
|
||||
종류: kind,
|
||||
요소: typeof a?.요소 === "string" ? a.요소 : "",
|
||||
이름: name,
|
||||
단위: l?.단위 ?? String(a?.단위 ?? ""),
|
||||
수량: String(a ? a.수량 / t : (l?.율 ?? l?.수량 ?? "")),
|
||||
비목: typeof a?.비목 === "string" ? a.비목 : single(l),
|
||||
};
|
||||
ho.push([cid, { ...(a ? made : ((known.get(cid) as HoItem) ?? made)), ...tag }]);
|
||||
}
|
||||
const cids = [...ho, ...extra].map(([cid]) => cid);
|
||||
const covers: Record<number, LineCover> = {};
|
||||
cids.forEach((cid, i) => {
|
||||
const hit = ADD_RE.exec(cid);
|
||||
const a = hit ? doc.더한줄?.[Number(hit[1])] : undefined;
|
||||
const part = PART_OF[String(a?.비목 ?? "")];
|
||||
const own = rateOf(doc, cid) ? 1 : t; // 율 = 그대로
|
||||
if (a) covers[i] = { qty: a.수량 / own, ...(a.단가 != null && part ? { [part]: a.단가 } : {}) };
|
||||
const at = subOf(cid);
|
||||
const owner = at ? doc.더한줄?.[at.k] : undefined;
|
||||
const c = hit ? undefined : at ? owner?.덮개?.[at.cid] : doc.덮개?.[cid];
|
||||
if (!c) return;
|
||||
const l = lineBy.get(cid);
|
||||
const out: LineCover = {};
|
||||
const per = at || cid.startsWith("pct:") ? 1 : t; // 율 · 세부 품 = 그대로
|
||||
if (c.qty != null) out.qty = c.qty / per;
|
||||
else if (c.배율 != null && l) out.qty = l.율 ?? l.수량 ?? undefined;
|
||||
for (const k of PARTS) if (c[k] != null) out[k] = c[k];
|
||||
covers[i] = out;
|
||||
});
|
||||
return {
|
||||
호표: ho.map(([, x]) => x),
|
||||
덧줄: extra.map(([, x]) => x),
|
||||
lines: ans.줄.length ? cids.map((c) => shown(lineBy.get(c))) : null,
|
||||
cids,
|
||||
covers,
|
||||
};
|
||||
}
|
||||
|
||||
/* ── 일위대가 줄 → SK 문서(717-3 · 723-3 줄 모드) ── */
|
||||
export interface LinePatch {
|
||||
덮개?: Record<string, SkCover>;
|
||||
뺀줄?: string[];
|
||||
더한줄?: unknown[];
|
||||
/** 뺀 더한줄 기억(744-1) */
|
||||
뺀더한줄?: SkDoc["뺀더한줄"];
|
||||
}
|
||||
|
||||
/** 줄 꼴(일위대가 `담은로직[]` 한 줄 · 쓰는 칸만) */
|
||||
export interface PatchRow {
|
||||
로직?: string;
|
||||
참조?: { 층: string; 주인?: string | null; 키: string };
|
||||
입력값?: Record<string, unknown>;
|
||||
켜쌓기율?: number | null;
|
||||
고름?: Record<string, unknown>;
|
||||
자재표시?: Record<string, unknown>;
|
||||
패치?: LinePatch;
|
||||
}
|
||||
|
||||
const keyed = (value: Record<string, unknown> | undefined, ids: string[]) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(value ?? {}).flatMap(([n, v]) =>
|
||||
/^\d+$/.test(n) && Number(n) < ids.length ? [[ids[Number(n)], v]] : [],
|
||||
),
|
||||
);
|
||||
|
||||
/** 고름 · 자재표시가 있는 로직 줄 = 바탕 줄 정체가 먼저 있어야 함 */
|
||||
export const needsIds = (row: PatchRow): boolean =>
|
||||
!row.참조 &&
|
||||
(Object.keys(row.고름 ?? {}).length > 0 || Object.keys(row.자재표시 ?? {}).length > 0);
|
||||
|
||||
/** 줄 → 이름 없는 SK 문서 — `patch` null = 그 일위대가 고침 없는 원래 값 ·
|
||||
* 고름 · 자재표시(호표 차례 열쇠)는 바탕 줄 정체(`ids` · 셈 답 `정체`)로 cid 열쇠로 */
|
||||
export function lineDoc(
|
||||
row: PatchRow,
|
||||
ids: string[] | null,
|
||||
patch: LinePatch | null,
|
||||
): Record<string, unknown> {
|
||||
const head = {
|
||||
키: "SK-000000",
|
||||
이름: "줄",
|
||||
단위: "식",
|
||||
덮개: patch?.덮개 ?? {},
|
||||
뺀줄: patch?.뺀줄 ?? [],
|
||||
더한줄: patch?.더한줄 ?? [],
|
||||
줄모드: true, // 셈 = 일위대가 그 줄 셈(별도계상 기본 · 750-1 · 서버 `calc_doc`)
|
||||
};
|
||||
if (row.참조) return { ...head, 바탕: { 참조: row.참조 } };
|
||||
return {
|
||||
...head,
|
||||
...(row.켜쌓기율 != null ? { 켜쌓기율: row.켜쌓기율 } : {}),
|
||||
바탕: { 로직: row.로직 ?? "" },
|
||||
입력값: { ...(row.입력값 ?? {}) },
|
||||
고름: ids ? keyed(row.고름, ids) : {},
|
||||
자재표시: ids ? keyed(row.자재표시, ids) : {},
|
||||
};
|
||||
}
|
||||
|
||||
/** 빈 칸 · 원값 뺀 패치 — 다 비면 null(줄 칸 안 둠) */
|
||||
export function cleanPatch(patch: LinePatch | null | undefined): LinePatch | null {
|
||||
const covers = Object.fromEntries(
|
||||
Object.entries(patch?.덮개 ?? {}).flatMap(([cid, c]) => {
|
||||
const keep = Object.fromEntries(
|
||||
Object.entries(c ?? {}).filter(([k, v]) => k !== "원값" && typeof v === "number"),
|
||||
);
|
||||
return Object.keys(keep).length ? [[cid, keep]] : [];
|
||||
}),
|
||||
);
|
||||
const out: LinePatch = {
|
||||
...(Object.keys(covers).length ? { 덮개: covers } : {}),
|
||||
...(patch?.뺀줄?.length ? { 뺀줄: [...patch.뺀줄] } : {}),
|
||||
...(patch?.더한줄?.length ? { 더한줄: [...patch.더한줄] } : {}),
|
||||
...(patch?.뺀더한줄?.length ? { 뺀더한줄: [...patch.뺀더한줄] } : {}),
|
||||
};
|
||||
return Object.keys(out).length ? out : null;
|
||||
}
|
||||
/* ── 순수 셈 끝 ── */
|
||||
@@ -1,93 +0,0 @@
|
||||
/* =============================================================================
|
||||
* M02_MasterTemplete/logic/M02_Sangeun_Undo.ts
|
||||
* 단가산출(SK) 되돌리기 기억(PLAN 744-1 서버 · 748-0 화면) — 더한 기초 · 더한 항목 빼기 → 문서 `뺀더한줄`
|
||||
* `[{차례, 줄}]`(되살림 = 그 차례에 다시 끼움) · 더한 항목 수량 → `처음수량`(넣을 때 값) 되돌림.
|
||||
* 더한줄 지움 · 끼움 때 뒤 더한줄 열쇠 `add:#j[/…]`(덮개 · 고름 · 자재표시 · 율 줄 기준 목록 778-4)를
|
||||
* 한 칸씩 당김 · 밂(지운 줄을 가리킨 기준 열쇠는 버림 — 빈 목록 = 서버 짝잃음 알림).
|
||||
* 금액은 늘 서버가 셈 — 여기는 문서 칸 옮김만 · 화면 · fetch · sessionStorage 없음(`CLAUDE.md` 4장).
|
||||
* ========================================================================== */
|
||||
|
||||
import type { SkAdded, SkDoc } from "./M02_Sangeun_Cover_Model";
|
||||
|
||||
/* ── 순수 셈 ── */
|
||||
const KEYED = ["덮개", "고름", "자재표시"] as const;
|
||||
const KEY_RE = /^add:#(\d+)(.*)$/;
|
||||
|
||||
/** 문서 열쇠 맵의 `add:#j…` 를 옮김 — `drop` = 지운 j(그 열쇠는 버림) · 뒤 j 는 한 칸 당김 / `push` = 끼운 j 부터 한 칸 밂 */
|
||||
function moveKeys(doc: SkDoc, mode: { drop: number } | { push: number }): void {
|
||||
for (const name of KEYED) {
|
||||
const map = doc[name] as Record<string, unknown> | undefined;
|
||||
if (!map) continue;
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(map)) {
|
||||
const hit = KEY_RE.exec(key);
|
||||
if (!hit) {
|
||||
out[key] = value;
|
||||
continue;
|
||||
}
|
||||
const j = Number(hit[1]);
|
||||
if ("drop" in mode) {
|
||||
if (j === mode.drop) continue;
|
||||
out[j > mode.drop ? `add:#${j - 1}${hit[2]}` : key] = value;
|
||||
} else out[j >= mode.push ? `add:#${j + 1}${hit[2]}` : key] = value;
|
||||
}
|
||||
(doc as Record<string, unknown>)[name] = out;
|
||||
}
|
||||
for (const one of doc.더한줄 ?? []) {
|
||||
const rate = (one.고정 as { 비율?: { 기준?: unknown } } | undefined)?.비율;
|
||||
if (!rate || !Array.isArray(rate.기준)) continue;
|
||||
rate.기준 = (rate.기준 as string[]).flatMap((key) => {
|
||||
const hit = KEY_RE.exec(key);
|
||||
if (!hit) return [key];
|
||||
const j = Number(hit[1]);
|
||||
if ("drop" in mode)
|
||||
return j === mode.drop ? [] : [j > mode.drop ? `add:#${j - 1}${hit[2]}` : key];
|
||||
return [j >= mode.push ? `add:#${j + 1}${hit[2]}` : key];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** 더한줄 k 를 빼고 기억에 둠 — 이름은 되살림 띠 글(서버가 저장 때 다시 적음) */
|
||||
export function forgetAdd(doc: SkDoc, k: number, name: string): void {
|
||||
const one = doc.더한줄?.[k];
|
||||
if (!one) return;
|
||||
doc.뺀더한줄 = [
|
||||
...(doc.뺀더한줄 ?? []),
|
||||
{ 차례: k, 줄: JSON.parse(JSON.stringify({ ...one, ...(name ? { 이름: name } : {}) })) },
|
||||
];
|
||||
doc.더한줄 = (doc.더한줄 ?? []).filter((_, i) => i !== k);
|
||||
moveKeys(doc, { drop: k });
|
||||
}
|
||||
|
||||
/** 기억 n 번째를 그 차례에 다시 끼움(차례가 줄 수보다 크면 맨 끝) */
|
||||
export function reviveAdd(doc: SkDoc, n: number): void {
|
||||
const gone = doc.뺀더한줄?.[n];
|
||||
if (!gone) return;
|
||||
const list = [...(doc.더한줄 ?? [])];
|
||||
const at = Math.min(Math.max(gone.차례, 0), list.length);
|
||||
list.splice(at, 0, gone.줄);
|
||||
doc.더한줄 = list;
|
||||
moveKeys(doc, { push: at });
|
||||
const rest = (doc.뺀더한줄 ?? []).filter((_, i) => i !== n);
|
||||
if (rest.length) doc.뺀더한줄 = rest;
|
||||
else delete doc.뺀더한줄;
|
||||
}
|
||||
|
||||
/** 되살림 띠 글 — 줄 이름 · 없으면 로직 · 요소 · 참조 키 */
|
||||
export function goneName(one: SkAdded): string {
|
||||
const ref = (one.참조 as { 키?: string } | undefined)?.키;
|
||||
return String(one.이름 || one.로직 || one.요소 || ref || "");
|
||||
}
|
||||
|
||||
/** 더한줄 수량 고침 — 처음 값(옛 문서엔 없음)을 먼저 적어 둠 */
|
||||
export function setQty(one: SkAdded, qty: number): void {
|
||||
one.처음수량 ??= one.수량;
|
||||
one.수량 = qty;
|
||||
}
|
||||
|
||||
/** 더한줄 수량 처음 값으로 — 처음 값 모르면 그대로 */
|
||||
export function resetQty(one: SkAdded): void {
|
||||
if (one.처음수량 != null) one.수량 = one.처음수량;
|
||||
}
|
||||
|
||||
/* ── 순수 셈 끝 ── */
|
||||
@@ -1,44 +0,0 @@
|
||||
/* PLAN 728-2 헬퍼 — SK 고침 꼴(`logic/M02_Sangeun_Cover_Model.ts`)이 화면배(SK 1 단위 몫)를 문서 몫으로 되돌리는지.
|
||||
* 짝 = `test_728_2_sk_unit.py`. 결과 = 표준출력 JSON.
|
||||
*/
|
||||
const path = require("path");
|
||||
const { makeLoader } = require("./helper_ts_stub_loader.cjs");
|
||||
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const { load } = makeLoader({ root: ROOT });
|
||||
const m = load("M02_MasterTemplete", "logic", "M02_Sangeun_Cover_Model.ts");
|
||||
|
||||
// GF000287 단목베기 SK 단위 본 — 서버 화면 답 = 100본 몫 ÷100(화면배 100)
|
||||
const line = (cid, 이름, 수량, 금액) => ({
|
||||
cid,
|
||||
이름,
|
||||
단위: "인",
|
||||
수량,
|
||||
단가: 금액 / 수량,
|
||||
금액,
|
||||
비목: { 노무비: 금액 },
|
||||
});
|
||||
const ans = {
|
||||
기준: { 계: 1538.894 },
|
||||
줄: [line("labor:LB000101#0", "벌목부", 0.002, 506.486), line("add:#0", "보통인부", 0.5, 86034)],
|
||||
정체: ["labor:LB000101#0", "add:#0"],
|
||||
짝잃음: [],
|
||||
바탕판: "",
|
||||
배: 100,
|
||||
화면배: 100,
|
||||
};
|
||||
const bare = { ...ans, 줄: [ans.줄[0]], 정체: ["labor:LB000101#0"] };
|
||||
const doc = {
|
||||
단위: "본",
|
||||
바탕: { 로직: "GF000287" },
|
||||
더한줄: [{ 종류: "인력", 요소: "LB000002", 수량: 50 }],
|
||||
};
|
||||
const rows = m.rowsOf(ans, bare, doc);
|
||||
const out = { was: rows[0].was, t: rows.map((r) => r.t) };
|
||||
m.setLineCover(doc, rows[0], { qty: 0.003 }, false); // 화면 0.003 = 문서 0.3(100본 몫)
|
||||
m.setLineCover(doc, rows[1], { qty: 0.6 }, false); // 더한 인력 화면 0.6 = 문서 60
|
||||
out.cover = doc.덮개;
|
||||
out.added = doc.더한줄[0].수량;
|
||||
const view = m.hoView(ans, bare, null, doc);
|
||||
out.shown = view.covers;
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
@@ -1,102 +0,0 @@
|
||||
/* PLAN 748-0 헬퍼 — SK 고침 꼴(`logic/M02_Sangeun_Cover_Model.ts` · `M02_Sangeun_Undo.ts`):
|
||||
* 둘째 기초 세부 품 = M01 원문 · 고침 = 원문 몫 그대로 · 빼기 기억(뺀더한줄) · 되살림 · 수량 처음값 되돌림.
|
||||
* 짝 = `test_748_0_sk_undo.py`. 결과 = 표준출력 JSON.
|
||||
*/
|
||||
const path = require("path");
|
||||
const { makeLoader } = require("./helper_ts_stub_loader.cjs");
|
||||
|
||||
const { load } = makeLoader({ root: path.join(__dirname, "..", "..") });
|
||||
const m = load("M02_MasterTemplete", "logic", "M02_Sangeun_Cover_Model.ts");
|
||||
|
||||
// 둘째 기초 GF 한 줄 — 원문 0.871 · 머리 수량 0.01 이면 상자 몫 0.00871
|
||||
const detail = {
|
||||
cid: "add:#1/labor:LB000101#0",
|
||||
이름: "벌목부",
|
||||
단위: "인",
|
||||
수량: 0.00871,
|
||||
단가: 100000,
|
||||
금액: 871,
|
||||
비목: { 노무비: 871 },
|
||||
원문: { 수량: 0.871, 금액: 87100, 비목: { 노무비: 87100 } },
|
||||
바탕값: { qty: 0.871, 단가: 100000 },
|
||||
};
|
||||
const ans = {
|
||||
기준: { 계: 871 },
|
||||
줄: [
|
||||
{
|
||||
cid: "labor:LB000002#0",
|
||||
이름: "보통인부",
|
||||
단위: "인",
|
||||
수량: 1,
|
||||
단가: 100,
|
||||
금액: 100,
|
||||
비목: { 노무비: 100 },
|
||||
},
|
||||
{
|
||||
cid: "add:#0",
|
||||
이름: "추가 인력",
|
||||
단위: "인",
|
||||
수량: 2,
|
||||
단가: 100,
|
||||
금액: 200,
|
||||
비목: { 노무비: 200 },
|
||||
},
|
||||
{
|
||||
cid: "add:#1",
|
||||
이름: "둘째 기초",
|
||||
단위: "100㎥",
|
||||
수량: 0.01,
|
||||
단가: null,
|
||||
금액: 871,
|
||||
비목: { 노무비: 871 },
|
||||
펼침: [detail],
|
||||
},
|
||||
],
|
||||
정체: ["labor:LB000002#0", "add:#0", "add:#1"],
|
||||
짝잃음: [],
|
||||
바탕판: "",
|
||||
};
|
||||
const doc = {
|
||||
단위: "㎥",
|
||||
바탕: { 로직: "GF000099" },
|
||||
더한줄: [
|
||||
{ 종류: "인력", 요소: "LB000002", 수량: 2, 처음수량: 2 },
|
||||
{ 종류: "로직", 로직: "GF000316", 수량: 0.01, 처음수량: 0.01 },
|
||||
],
|
||||
고름: { "add:#1": "MT1" },
|
||||
};
|
||||
const out = {};
|
||||
const rows = m.rowsOf(ans, null, doc);
|
||||
const sub = rows.find((r) => r.cid === detail.cid);
|
||||
const view = m.hoView(ans, null, null, doc);
|
||||
const at = view.cids.indexOf(detail.cid);
|
||||
out.shownQty = view.호표[at].수량; // 원문 그대로
|
||||
out.lineQty = view.lines[at].수량;
|
||||
out.lineAmount = view.lines[at].금액; // 상자 몫 그대로
|
||||
out.t = sub.t;
|
||||
// 세부 품 고침 — 화면 0.9 = 문서 덮개 0.9(머리 수량 안 나눔)
|
||||
m.setLineCover(doc, sub, { qty: 0.9 }, false);
|
||||
out.cover = doc.더한줄[1].덮개;
|
||||
out.coverShown = m.hoView(ans, null, null, doc).covers[at].qty;
|
||||
// 더한 항목 수량 고침 → 처음값 되돌림
|
||||
const man = m.rowsOf(ans, null, doc).find((r) => r.cid === "add:#0");
|
||||
m.setLineCover(doc, man, { qty: 5 }, false);
|
||||
out.manQty = doc.더한줄[0].수량;
|
||||
m.setLineCover(doc, man, null, false);
|
||||
out.manBack = doc.더한줄[0].수량;
|
||||
// 더한 항목 빼기 → 기억 + 열쇠 당김 → 되살림
|
||||
m.dropLine(doc, man);
|
||||
out.afterDrop = { adds: doc.더한줄.length, gone: doc.뺀더한줄, pick: doc.고름 };
|
||||
out.goneRows = m.goneRows(doc);
|
||||
m.restoreLine(doc, "gone:0");
|
||||
out.afterBack = {
|
||||
adds: doc.더한줄.map((x) => x.요소 ?? x.로직),
|
||||
gone: doc.뺀더한줄 ?? null,
|
||||
pick: doc.고름,
|
||||
};
|
||||
// 둘째 기초 통째 빼기 → 되살림
|
||||
m.dropBase(doc, 1, "둘째 기초");
|
||||
out.baseGone = { adds: doc.더한줄.length, name: m.goneRows(doc)[0].이름, pick: doc.고름 };
|
||||
m.restoreLine(doc, "gone:0");
|
||||
out.baseBack = doc.더한줄.map((x) => x.요소 ?? x.로직);
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
@@ -98,7 +98,7 @@ for (let i = 0; i < 5; i++) {
|
||||
const { createSangeunTabs } = load("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts");
|
||||
const b2 = listeners;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const t = createSangeunTabs(new Fake("div"), { edit: false, scope: { layer: "system", owner: null } });
|
||||
const t = createSangeunTabs({ edit: false, scope: { layer: "system", owner: null } });
|
||||
out.tabs.push(listeners - b2);
|
||||
t.destroy();
|
||||
out.tabs.push(listeners - b2);
|
||||
|
||||
@@ -311,11 +311,11 @@ async function openSk(doc, opt = {}) {
|
||||
// ① 단가산출 화면(페이지) — 바탕 있음 · 없음
|
||||
out.page_base = await openSk(
|
||||
{ 키: "SK-000001", 이름: "견본", 단위: "㎡", 바탕: { 로직: "GC001109" } },
|
||||
{ source: true },
|
||||
{ mode: "page" },
|
||||
);
|
||||
out.page_nobase = await openSk({ 키: "SK-000002", 이름: "견본", 단위: "㎡" }, { source: true });
|
||||
out.page_nobase = await openSk({ 키: "SK-000002", 이름: "견본", 단위: "㎡" }, { mode: "page" });
|
||||
// 불러오기 미리 보기(저장 전 가져온 식)
|
||||
out.memory = await openSk({ 이름: "가져온", 단위: "식", 가져온: { 파일: "x" } });
|
||||
out.memory = await openSk({ 이름: "가져온", 단위: "식", 가져온: { 파일: "x" } }, { mode: "memory" });
|
||||
|
||||
// ③ 머리 띠 넷(견본 답) — 까닭 · M01 개정 · 빠진 줄 · 짝 잃음 + 머리 배지
|
||||
skAnswer = () =>
|
||||
@@ -328,12 +328,12 @@ async function openSk(doc, opt = {}) {
|
||||
});
|
||||
out.bands = await openSk(
|
||||
{ 키: "SK-000003", 이름: "띠", 단위: "㎡", 바탕: { 로직: "GC001109" }, 바탕판: "v1" },
|
||||
{ source: true },
|
||||
{ mode: "page" },
|
||||
);
|
||||
skAnswer = () => {
|
||||
throw new Error("서버 못 닿음");
|
||||
};
|
||||
out.bands_fail = await openSk({ 키: "SK-000004", 이름: "띠", 단위: "㎡" }, { source: true });
|
||||
out.bands_fail = await openSk({ 키: "SK-000004", 이름: "띠", 단위: "㎡" }, { mode: "page" });
|
||||
skAnswer = () => plainAns();
|
||||
|
||||
// ② 일위대가 표 줄 누름 — SK 참조 줄 · M01 로직 줄 · 셈 주입(프로젝트 사본) SK 줄
|
||||
|
||||
@@ -8,10 +8,6 @@
|
||||
- 상세 = M01 상세 부품(M02 길) · 부품 상자만 · 마스터 이동 단추 = 등록 없으면 숨김
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
@@ -24,7 +20,6 @@ from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
M02 = ROOT / "M02_MasterTemplete"
|
||||
MODEL = M02 / "logic" / "M02_Sangeun_Cover_Model.ts"
|
||||
BASE = "GC000278"
|
||||
|
||||
|
||||
@@ -32,163 +27,6 @@ def _text(p: Path) -> str:
|
||||
return p.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _node(body: str) -> object:
|
||||
born = _text(M02 / "logic" / "M02_Born_Tag.ts") # 740-2 — 모델이 쓰는 꼬리표 글(import 줄은 뺌)
|
||||
model = re.sub(r"^import .*$", "", _text(MODEL), flags=re.M)
|
||||
undo = re.sub(r"^import .*$", "", _text(M02 / "logic" / "M02_Sangeun_Undo.ts"), flags=re.M)
|
||||
# 751-3 모델이 가져오는 B09 `rounddown`(import 줄을 빼므로 같은 식을 둠)
|
||||
cut = "const rounddown = (v, p = 0) => { const s = 10 ** p; " + (
|
||||
"const a = Math.floor(Math.abs(v) * s + 1e-7) / s; return v < 0 ? -a : a; };"
|
||||
)
|
||||
src = "\n".join((born, undo, cut, model, body))
|
||||
out = subprocess.run(
|
||||
["node", "--experimental-strip-types", "--no-warnings",
|
||||
"--input-type=module-typescript", "-e", src],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60,
|
||||
) # fmt: skip
|
||||
assert out.returncode == 0, out.stderr
|
||||
return json.loads(out.stdout)
|
||||
|
||||
|
||||
SAMPLE = """
|
||||
const line = (cid, 이름, 수량, 단가, 비목, 묶음) => ({ cid, 이름, 단위: "인", 수량, 단가,
|
||||
금액: Object.values(비목).reduce((a, b) => a + b, 0), 비목, 묶음 });
|
||||
const bare = { 기준: null, 짝잃음: [], 바탕판: "x",
|
||||
정체: ["labor:A#0", "logic:G#0", "material:M#0", "pct:공구#0"],
|
||||
줄: [line("labor:A#0", "석공", 0.1, 1000, { 노무비: 100 }, "인력"),
|
||||
line("logic:G#0", "굴착기", 2, 50, { 노무비: 60, 재료비: 30, 경비: 10 }, "경비")],
|
||||
재료: [{ 차례: 2, 이름: "모르타르", 수량: 0.5, 단가: 200, 금액: 100 }] };
|
||||
"""
|
||||
|
||||
|
||||
@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음")
|
||||
def test_고침_꼴():
|
||||
body = (
|
||||
SAMPLE
|
||||
+ """
|
||||
const doc = { 덮개: {}, 뺀줄: [],
|
||||
더한줄: [{ 종류: "재료", 요소: "MT1", 비목: "재료비", 수량: 1 }] };
|
||||
const ans = { ...bare, 정체: [...bare.정체, "add:#0"],
|
||||
줄: [...bare.줄, line("add:#0", "더한 재료", 1, 300, { 재료비: 300 }, "재료")] };
|
||||
const rows = rowsOf(ans, bare, doc);
|
||||
const by = (cid) => rowsOf(ans, bare, doc).find((r) => r.cid === cid);
|
||||
const out = {};
|
||||
out.rows = rows.map((r) => [r.cid, r.묶음, r.apart, r.added, r.priceEdit]);
|
||||
setLineCover(doc, by("labor:A#0"), { qty: 0.2 }, false);
|
||||
out.qty = doc.덮개["labor:A#0"];
|
||||
setLineCover(doc, by("labor:A#0"), { qty: 0.1 }, false); // 바탕 값과 같음 = 덮개 지움
|
||||
out.qtyBack = doc.덮개["labor:A#0"] ?? null;
|
||||
setLineCover(doc, by("labor:A#0"), { labor: 1200 }, false);
|
||||
out.price = doc.덮개["labor:A#0"];
|
||||
setLineCover(doc, by("labor:A#0"), null, false); // 고침 풂
|
||||
out.unset = doc.덮개["labor:A#0"] ?? null;
|
||||
setLineCover(doc, by("logic:G#0"), { labor: 60, material: 30, expense: 10 }, false);
|
||||
out.split = doc.덮개["logic:G#0"];
|
||||
setLineCover(doc, by("add:#0"), { qty: 3, material: 350 }, false);
|
||||
out.added = doc.더한줄[0];
|
||||
out.pick = [by("add:#0").apartPick, by("labor:A#0").apartPick];
|
||||
setApart(doc, by("add:#0"), true);
|
||||
out.apartOn = doc.더한줄[0].별도계상 ?? null;
|
||||
setApart(doc, by("add:#0"), false);
|
||||
out.apartOff = doc.더한줄[0].별도계상 ?? null;
|
||||
const opened = { 덮개: {} };
|
||||
setLineCover(opened, by("labor:A#0"), { qty: 0.15 }, true); // 바탕 품 0.1 → 배율 1.5
|
||||
out.scale = opened.덮개["labor:A#0"];
|
||||
setLineCover(opened, by("labor:A#0"), { qty: 0.1 }, true);
|
||||
out.scaleBack = opened.덮개["labor:A#0"] ?? null;
|
||||
dropLine(doc, by("labor:A#0"));
|
||||
out.drop = [doc.뺀줄, doc.덮개["labor:A#0"] ?? null];
|
||||
restoreLine(doc, "labor:A#0");
|
||||
out.restore = doc.뺀줄;
|
||||
dropLine(doc, by("add:#0"));
|
||||
out.dropAdded = doc.더한줄.length;
|
||||
const covered = { 덮개: { "labor:A#0": { qty: 0.3, 원값: { qty: 0.09, 단가: 1000 } } } };
|
||||
out.revised = rowsOf(bare, bare, covered).find((r) => r.cid === "labor:A#0").revised;
|
||||
// 공용 상세 줄 — 바탕 줄 그대로 · 뺀 줄 없음 · 더한줄 · 별도계상 빠진 줄 = 빈 칸 · 덧줄
|
||||
const base = { 호표: [{ 종류: "인력", 요소: "A", 이름: "석공", 수량: "0.1*x" },
|
||||
{ 종류: "로직", 요소: "로직(G)", 수량: "2" }, { 종류: "재료", 요소: "M", 수량: "0.5" }],
|
||||
덧줄: [{ 이름: "공구손료", 식: "노무비 * 3 / 100" }] };
|
||||
const doc2 = { 덮개: { "labor:A#0": { qty: 0.3, 원값: { qty: 0.1 } } }, 뺀줄: ["logic:G#0"],
|
||||
더한줄: [{ 종류: "인력", 요소: "LB2", 이름: "보통인부", 비목: "노무비",
|
||||
수량: 0.01, 단가: 500 }] };
|
||||
const ans2 = { ...bare, 정체: ["labor:A#0", "material:M#0", "add:#0", "pct:공구#0"],
|
||||
줄: [line("labor:A#0", "석공", 0.3, 1000, { 노무비: 300 }, "인력"),
|
||||
line("add:#0", "보통인부", 0.01, 500, { 노무비: 5 }, "인력"),
|
||||
{ ...line("pct:공구#0", "공구손료", 9.15, 1, { 경비: 9.15 }, "경비"), 율: 3 }] };
|
||||
const v = hoView(ans2, bare, base, doc2);
|
||||
out.view = [v.호표.map((x) => [x.종류, x.요소, x.수량, x.비목 ?? null]), v.덧줄, v.cids,
|
||||
v.lines.map((l) => l?.cid ?? null), v.covers];
|
||||
out.viewRef = hoView(ans2, bare, null, doc2).호표[0];
|
||||
console.log(JSON.stringify(out));
|
||||
"""
|
||||
)
|
||||
got = _node(body)
|
||||
assert got["rows"] == [
|
||||
["labor:A#0", "인력", False, None, True],
|
||||
["logic:G#0", "경비", False, None, True],
|
||||
["add:#0", "재료", False, 0, True],
|
||||
["material:M#0", "재료", True, None, True],
|
||||
]
|
||||
assert got["qty"] == {"qty": 0.2, "원값": {"qty": 0.1, "단가": 1000}}
|
||||
assert got["qtyBack"] is None
|
||||
assert got["price"] == {"labor": 1200, "원값": {"qty": 0.1, "단가": 1000}}
|
||||
assert got["unset"] is None
|
||||
assert got["split"]["labor"] == 60 and got["split"]["material"] == 30
|
||||
assert got["split"]["expense"] == 10
|
||||
assert got["added"]["수량"] == 3 and got["added"]["단가"] == 350
|
||||
# 더한 재료 줄만 별도계상 고름 · 켬 = 칸 true · 끔 = 칸 지움(기본 계 안)
|
||||
assert got["pick"] == [True, False]
|
||||
assert got["apartOn"] is True and got["apartOff"] is None
|
||||
assert got["scale"]["배율"] == pytest.approx(1.5) and "qty" not in got["scale"]
|
||||
assert got["scaleBack"] is None
|
||||
assert got["drop"] == [["labor:A#0"], None]
|
||||
assert got["restore"] == [] and got["dropAdded"] == 0
|
||||
assert got["revised"] is True
|
||||
ho, extra, cids, lines, covers = got["view"]
|
||||
assert ho == [
|
||||
["인력", "A", "0.1*x", None], # 바탕 줄 그대로(식)
|
||||
["재료", "M", "0.5", None],
|
||||
["인력", "LB2", "0.01", "노무비"], # 더한줄
|
||||
]
|
||||
assert extra == [{"이름": "공구손료", "식": "노무비 * 3 / 100"}]
|
||||
assert cids == ["labor:A#0", "material:M#0", "add:#0", "pct:공구#0"]
|
||||
assert lines == ["labor:A#0", None, "add:#0", "pct:공구#0"] # 별도계상 빠진 재료 = 빈 칸
|
||||
assert covers == {"0": {"qty": 0.3}, "2": {"qty": 0.01, "labor": 500}}
|
||||
assert got["viewRef"] == { # 참조 바탕 = 셈 줄로 지음
|
||||
"종류": "인력", "요소": "", "이름": "석공", "단위": "인", "수량": "0.3", "비목": "노무비",
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def test_상세_부품_길_부품상자():
|
||||
view = _text(M02 / "M02_MasterTemplete_Sangeun_View.ts")
|
||||
detail = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts")
|
||||
cover = _text(M02 / "M02_MasterTemplete_Sangeun_Cover.ts")
|
||||
assert "mountSangeunDetail(host, doc," in view and "createEmpty" not in view
|
||||
assert 'read: "/m02/logic-lib"' in detail and "setLogicApiPaths(LIB)" in detail
|
||||
assert "buildLabDetail(editor" in detail and "cover: { ho }," in detail
|
||||
assert "buildCalc" not in detail # 799-2 시험 계산 보기 걷음
|
||||
assert (
|
||||
"openSangeunLinePicker" not in detail and "openRateLine" not in detail
|
||||
) # 840-1 [항목 추가] · [율 줄 추가] 걷음
|
||||
assert "if (mine !== seq || !alive) return" in detail # 최신 응답만
|
||||
# 724-1 — 단가산출 상세 = 공용 상세(Ho) · 고침 고리 = SK 덮개 · 옛 고침 표 걷음
|
||||
assert "...buildHo(hoCtx)" in detail and 'scope: "m02",' in detail
|
||||
assert "setLineCover(doc, r, c, opened());" in detail and "skCoverTable" not in detail
|
||||
ho = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts")
|
||||
assert "edit.more?.(e.idx, close)" in ho and '"EditedM02"' in ho
|
||||
for s in (detail, cover, _text(MODEL)):
|
||||
assert "<button" not in s and "<input" not in s and "<table" not in s
|
||||
assert "document.createElement" not in s and "sessionStorage." not in s
|
||||
lab = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Detail.ts")
|
||||
assert "ctx.cover.ho" in lab and "cover?.est" not in lab
|
||||
side = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_Side.ts")
|
||||
modal = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Modal.ts")
|
||||
assert "export const hasMasterJump" in side and "go.hidden = !hasMasterJump()" in modal
|
||||
assert (
|
||||
len(_text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab.ts").splitlines()) <= 637
|
||||
) # 794-1 시트 이음 10 줄
|
||||
|
||||
|
||||
def test_화면_문서_꼴_서버_저장_셈(world): # noqa: F811 — 가져온 fixture
|
||||
"""화면 꼴(덮개 + 원값 곁 글 · 로직 줄 나눈 단가 · 더한줄 · 뺀줄) → 저장 · 셈 = 손셈."""
|
||||
mine = world["personal"]
|
||||
@@ -235,15 +73,3 @@ def test_화면_문서_꼴_서버_저장_셈(world): # noqa: F811 — 가져온
|
||||
assert added["단가"] == pytest.approx(lines["labor:LB000002#0"]["단가"])
|
||||
gap = sum(x["금액"] for x in got["줄"]) - got["기준"]["계"] # 751-3 비목마다 1 원 버림
|
||||
assert -1e-6 <= gap < 3
|
||||
|
||||
|
||||
def test_725_바탕_없으면_개정_안_뜸_새_SK_나무_다시_읽음_더한줄_단가_찾음():
|
||||
"""725-3 바탕 없는 SK 는 이름 · 단위 따라 지문이 바뀌어도 M01 개정 아님 · 725-4 새 SK 뒤 나무 알림 ·
|
||||
`prices` 에 없는 요소 = 키로 찾아 옴."""
|
||||
detail = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts")
|
||||
assert "!!(doc.바탕 && doc.바탕판 && ans?.바탕판 && doc.바탕판 !== ans.바탕판)" in detail
|
||||
assert detail.count("const revised = revisedBase();") == 2
|
||||
modal = _text(M02 / "M02_MasterTemplete_Labor_RowModal.ts")
|
||||
assert "saveAsSk" not in modal # 808-1 옛 [단가산출로도 저장] 걷음 — 일위대가 줄은 저장 때 펼침
|
||||
lab = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Modal.ts")
|
||||
assert "lookup(element, element)" in lab and "Pill_NoValue" in lab
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
# ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀
|
||||
"""일위대가 줄 [단가산출 보기] 모달(PLAN 717-3 · 724-1) — 임시 storage · 순수 함수는 Node 로.
|
||||
|
||||
화면 문서(`logic/M02_Sangeun_Cover_Model.lineDoc`) = 서버 `M02_Labor_Patch.as_doc` 꼴
|
||||
(같은 고름 · 자재표시 cid) ·
|
||||
모달 셈 길(`/sangeun/calc` = `calc_doc`) 값 = 일위대가 셈의 그 줄 값 · 고친 칸 = 덮개 칸 이름 ·
|
||||
패치 정리 순수 함수 · `normalizeLabor` 가 줄 `패치` 를 지킴 ·
|
||||
화면 이음(모달 = 줄 모드 SK 상세 · 공용 상세).
|
||||
"""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
from M02_MasterTemplete import M02_Labor_Doc as labor
|
||||
from M02_MasterTemplete import M02_Labor_Patch as patch
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
from M02_MasterTemplete import M02_Sangeun_Doc as sd
|
||||
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PCT = "GC001109" # 원/㎡ · 인력 둘 + 「노무비 * 3 / 100」
|
||||
TWO_MATS = "GC000565" # 원/m · 재료 줄 둘
|
||||
COVER = {"덮개": {"labor:LB000036#0": {"qty": 0.5}}}
|
||||
|
||||
MODEL = r"""
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const root = process.argv[1];
|
||||
const ts = require(path.join(root, "config", "node_modules", "typescript"));
|
||||
const f = path.join(root, "M02_MasterTemplete", "logic", "M02_Sangeun_Cover_Model.ts");
|
||||
const js = ts.transpileModule(fs.readFileSync(f, "utf8"), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
const box = { exports: {} };
|
||||
new Function("exports", "module", "require", js)(box.exports, box, () => ({}));
|
||||
const m = box.exports;
|
||||
const job = JSON.parse(fs.readFileSync(0, "utf8"));
|
||||
const out = {};
|
||||
for (const [k, [fn, ...args]] of Object.entries(job)) out[k] = m[fn](...args);
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
"""
|
||||
|
||||
|
||||
def _node(job: dict) -> dict:
|
||||
node = shutil.which("node")
|
||||
if not node:
|
||||
pytest.skip("node 없음")
|
||||
got = subprocess.run(
|
||||
[node, "-e", MODEL, str(ROOT)],
|
||||
input=json.dumps(job, ensure_ascii=False),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert got.returncode == 0, got.stderr
|
||||
return json.loads(got.stdout)
|
||||
|
||||
|
||||
def _whole():
|
||||
return m01.loaded()[1]
|
||||
|
||||
|
||||
def test_화면_문서_서버_as_doc_꼴():
|
||||
"""고름 · 자재표시(호표 차례) → cid · 패치 · 참조 줄 = 서버 `as_doc` 와 같은 몸."""
|
||||
import master_pick as mp
|
||||
|
||||
whole = _whole()
|
||||
row = whole.logic(TWO_MATS)
|
||||
item = row["호표"][2]
|
||||
want = mp.search(whole, item["요소"], {}, item.get("단위"))[1]
|
||||
drop = {"뺀줄": ["material:" + row["호표"][1]["이름"] + "#0"]}
|
||||
one = {
|
||||
"로직": TWO_MATS,
|
||||
"입력값": {},
|
||||
"고름": {"2": want},
|
||||
"자재표시": {"2": {"별도계상": "직접계산"}},
|
||||
}
|
||||
ref = {"참조": {"층": "personal", "주인": None, "키": "SK-000001"}, "입력값": {}}
|
||||
ids = sd.line_ids(row)
|
||||
got = _node(
|
||||
{
|
||||
"logic": ["lineDoc", one, ids, drop],
|
||||
"ref": ["lineDoc", ref, None, COVER],
|
||||
"bare": ["lineDoc", one, None, None],
|
||||
"needs": ["needsIds", one],
|
||||
"needsRef": ["needsIds", ref],
|
||||
}
|
||||
)
|
||||
assert got["logic"].pop("줄모드") is True and got["ref"].pop("줄모드") is True # 750-1
|
||||
assert got["logic"] == patch.as_doc({**one, "패치": drop}, whole)
|
||||
assert got["ref"] == patch.as_doc({**ref, "패치": COVER}, whole)
|
||||
assert got["bare"]["고름"] == {} and got["bare"]["덮개"] == {}
|
||||
assert got["needs"] is True and got["needsRef"] is False
|
||||
|
||||
|
||||
def test_모달_셈_길_값_일위대가_줄_값(world):
|
||||
"""모달 셈(`calc_doc` · 저장 안 함) 기준 = 일위대가 셈 그 줄 기준 · 고친 줄 덮개 칸 = qty · 정체 = 바탕 줄."""
|
||||
whole = _whole()
|
||||
line = {"로직": PCT, "입력값": {}, "수량": {"손": 1}}
|
||||
doc = _node({"d": ["lineDoc", line, None, COVER]})["d"]
|
||||
bare = _node({"d": ["lineDoc", line, None, None]})["d"]
|
||||
with store.at(world["personal"]):
|
||||
got = calc.calc_doc(doc)
|
||||
was = calc.calc_doc(bare)
|
||||
mine = labor.calc(labor.clean({"담은로직": [{**line, "패치": COVER}]}), {})["줄"][0]
|
||||
plain = labor.calc(labor.clean({"담은로직": [line]}), {})["줄"][0]
|
||||
assert got["기준"] == pytest.approx(mine["기준"])
|
||||
assert was["기준"] == pytest.approx(plain["기준"])
|
||||
assert got["기준"]["계"] != was["기준"]["계"] # 품 0.5 로 바뀜
|
||||
assert was["정체"] == sd.line_ids(whole.logic(PCT))
|
||||
cover = [x for x in got["줄"] if x["cid"] == "labor:LB000036#0"][0]
|
||||
assert cover["덮개"] == ["qty"] and cover["수량"] == pytest.approx(0.5)
|
||||
|
||||
|
||||
def test_패치_정리_순수_함수():
|
||||
"""원값 뺌 · 빈 칸 뺌 · 다 비면 null(줄 칸 안 둠) — 덮개 고침 자체는 717-2b `setLineCover`."""
|
||||
one = {"덮개": {"labor:LB1#0": {"qty": 0.5, "원값": {"qty": 0.2}}, "x:a#0": {"원값": {}}}}
|
||||
got = _node(
|
||||
{
|
||||
"clean": ["cleanPatch", one],
|
||||
"empty": ["cleanPatch", {"덮개": {}, "뺀줄": [], "더한줄": []}],
|
||||
"none": ["cleanPatch", None],
|
||||
"keep": ["cleanPatch", {"뺀줄": ["a:b#0"]}],
|
||||
}
|
||||
)
|
||||
assert got["clean"] == {"덮개": {"labor:LB1#0": {"qty": 0.5}}} # 원값 = 서버 몫
|
||||
assert got["empty"] is None and got["none"] is None
|
||||
assert got["keep"] == {"뺀줄": ["a:b#0"]}
|
||||
|
||||
|
||||
def test_normalizeLabor_줄_패치_지킴():
|
||||
node = shutil.which("node")
|
||||
if not node:
|
||||
pytest.skip("node 없음")
|
||||
doc = {"담은로직": [{"로직": PCT, "패치": COVER}, {"로직": TWO_MATS}]}
|
||||
got = subprocess.run(
|
||||
[node, str(ROOT / "resources/tester/helper_m02_labor_normalize.cjs")],
|
||||
input=json.dumps({"doc": doc, "column": "c"}, ensure_ascii=False),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert got.returncode == 0, got.stderr
|
||||
rows = json.loads(got.stdout)["담은로직"]
|
||||
assert rows[0]["패치"] == COVER and "패치" not in rows[1]
|
||||
@@ -1,98 +0,0 @@
|
||||
"""722 M01 단가산출 상세 개편 지킴 시험 — 글 · 순수 함수(화면 · 서버 없음).
|
||||
|
||||
- 722-1 공용 단가산출 상세(`M01_MasterData_UI_LogicLab_Ho.ts`) — 하위 박스(서버 묶음) · 장비 한 줄 + 펼침 · 계산식 열 · 박스 옵션
|
||||
- 722-2 그 자리 고침(`M01_MasterData_UI_LogicLab_Cover.ts`) — M01 = 시험 값(줄 사본) · 정본 · 캐시 안 바뀜
|
||||
"""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
M01 = ROOT / "M01_MasterData"
|
||||
HO = M01 / "M01_MasterData_UI_LogicLab_Ho.ts"
|
||||
COVER = M01 / "M01_MasterData_UI_LogicLab_Cover.ts"
|
||||
|
||||
|
||||
def _text(p: Path) -> str:
|
||||
return p.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _pure(p: Path) -> str:
|
||||
s = _text(p)
|
||||
return s[s.index("/* ── 순수 셈 ── */") : s.index("/* ── 순수 셈 끝 ── */")]
|
||||
|
||||
|
||||
def _node(code: str):
|
||||
out = subprocess.run(
|
||||
["node", "--experimental-strip-types", "--no-warnings",
|
||||
"--input-type=module-typescript", "-e", code],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60,
|
||||
) # fmt: skip
|
||||
assert out.returncode == 0, out.stderr
|
||||
return json.loads(out.stdout)
|
||||
|
||||
|
||||
def test_상세가_공용_부품을_씀():
|
||||
detail = _text(M01 / "M01_MasterData_UI_LogicLab_Detail.ts")
|
||||
assert (
|
||||
"buildHo" not in detail and "trialEdit" not in detail
|
||||
) # 840-1 M01 상세 보기 걷음 — M02 줄 모달만 씀
|
||||
assert "...buildHo(hoCtx)" in _text(
|
||||
ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Detail.ts"
|
||||
)
|
||||
ho = _text(HO)
|
||||
# 부품 상자만 — 표 · 카드 · 계산 줄 · 변수 칸(calc_sheet) · 입력 칩(텍스트 수식)
|
||||
for part in (
|
||||
"tableShell(",
|
||||
"tableRow(",
|
||||
"createCard(",
|
||||
"varRow(",
|
||||
"sheetFormula(",
|
||||
):
|
||||
assert part in ho, part
|
||||
assert "inputChip(" not in ho # 748-3 줄마다 붙던 옵션 값 칩 걷음(위 옵션 칸이 대신)
|
||||
for s in (ho, _text(COVER)):
|
||||
assert 'el("table"' not in s and 'el("button"' not in s and 'el("input"' not in s
|
||||
assert "document.createElement" not in s and "sessionStorage" not in s
|
||||
assert "export function varRow(" in _text(ROOT / "A00_Common" / "calc_sheet.ts")
|
||||
for p in (HO, COVER, M01 / "M01_MasterData_UI_LogicLab.ts"):
|
||||
assert len(_text(p).splitlines()) <= (
|
||||
637 if p.name == "M01_MasterData_UI_LogicLab.ts" else 700 # 794-1 시트 이음 10 줄
|
||||
)
|
||||
|
||||
|
||||
def test_시험_고침은_M01_에서_걷음():
|
||||
lab = _text(M01 / "M01_MasterData_UI_LogicLab.ts")
|
||||
assert (
|
||||
"trial" not in lab and "drive" not in lab
|
||||
) # 840-1 — 시험 값 · 구동 걷음(수식에서 값을 바꾸고 [되돌림])
|
||||
cover = _text(COVER)
|
||||
assert "export const trial" not in cover and "applyCovers" not in cover
|
||||
assert "drafts" not in cover and "touch" not in cover and "/save" not in cover
|
||||
modal = _text(M01 / "M01_MasterData_UI_LogicLab_Modal.ts")
|
||||
assert "...(target.edit ? [target.edit(close, head)] : [])" in modal
|
||||
|
||||
|
||||
@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음")
|
||||
def test_박스_묶기():
|
||||
body = """
|
||||
const e = (idx, bundle, merge, amount) => ({ idx, bundle, merge, amount });
|
||||
const got = boxesOf([
|
||||
e(0, "인력", false, 10), e(1, "경비", true, 100), e(1, "경비", true, 20), e(1, "경비", true, 30),
|
||||
e(2, "하위", true, 5), e(2, "하위", true, null), e(3, "재료", false, null),
|
||||
], ["인력", "재료", "경비"]).map((b) => ({ 묶음: b.묶음, 소계: b.소계,
|
||||
줄: b.줄.map((r) => "몫" in r ? [r.idx, r.금액, r.몫.length] : r.idx) }));
|
||||
console.log(JSON.stringify(got));
|
||||
"""
|
||||
got = _node(_pure(HO) + "\n" + body)
|
||||
assert [b["묶음"] for b in got] == ["인력", "재료", "경비", "하위"]
|
||||
assert got[0] == {"묶음": "인력", "소계": 10, "줄": [0]}
|
||||
assert got[1] == {"묶음": "재료", "소계": 0, "줄": [3]}
|
||||
assert got[2] == {"묶음": "경비", "소계": 150, "줄": [[1, 150, 3]]} # 장비 한 줄 = 몫 셋 합
|
||||
assert got[3]["줄"] == [[2, 5, 2]]
|
||||
empty = _node(_pure(HO) + '\nconsole.log(JSON.stringify(boxesOf([], ["인력"])))')
|
||||
assert empty == [{"묶음": "인력", "줄": [], "소계": 0}]
|
||||
@@ -47,15 +47,3 @@ def test_화면_서고_상세는_일위대가표만():
|
||||
for label in ('tc("Up")', 'tc("Down")', 't("Alias")', 'tc("Remove")'):
|
||||
assert label in table # 우클릭 메뉴
|
||||
assert "fixed: (fx: LaborFixed, name: string)" in table # 721-2 고정 줄 이음
|
||||
|
||||
|
||||
def test_화면_줄_모달은_SK_상세_줄_모드_적용은_덮개와_옵션():
|
||||
modal, sk = (
|
||||
_src("M02_MasterTemplete_Labor_RowModal.ts"),
|
||||
_src("M02_MasterTemplete_Labor_RowSk.ts"),
|
||||
)
|
||||
detail = _src("M02_MasterTemplete_Sangeun_Detail.ts")
|
||||
assert "mountSangeunDetail(box, doc," in sk and "getValues: () => ({ ...values })" in detail
|
||||
assert "if (got.patch) row.패치 = got.patch;" in modal and "setValues(got.values);" in modal
|
||||
assert "AlsoSk" not in modal # 808-1 [단가산출로도 저장] 걷음 · 811-1 M01 기초 = SK 사본 참조
|
||||
assert "openRowSangeun" not in modal # 717-3 두 보기 갈음
|
||||
|
||||
@@ -105,11 +105,3 @@ def test_no_base_common_option_seoul(world): # noqa: F811
|
||||
assert got["기준"], {k: v for k, v in got.items() if k != "줄"}
|
||||
assert got["기준"]["계"] == pytest.approx(_m01(GF, {"지역": "서울", "보정작업": "해당 없음"}))
|
||||
assert float(got["기준"]["계"]) == 5660 # 751-3 끝수 · 840-5 굴착기 조종원 35,412 → 59,020/시간
|
||||
|
||||
|
||||
def test_screen_no_base_inputs_and_gap_dash():
|
||||
"""725-6 화면 — 바탕 없음 = 더한줄 로직 입력 모음 칸 · 못 셈 줄 금액 「—」 + 까닭 풍선."""
|
||||
ts = (ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Detail.ts").read_text("utf-8")
|
||||
assert "입력: extra" in ts and "syncExtra" in ts and "void recalc(); // 750-2" in ts
|
||||
ho = (ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts").read_text("utf-8")
|
||||
assert "e.line?.까닭 ? gapCell" in ho and "title: why" in ho
|
||||
|
||||
@@ -202,54 +202,3 @@ def test_727_3_옵션_저장_일위대가_그_옵션(world): # noqa: F811
|
||||
assert two["입력값"] == rock
|
||||
got = _run(world["personal"], two)
|
||||
assert _line(got, "add:#0")["금액"] == pytest.approx(_m01(GF, rock), rel=1e-9)
|
||||
|
||||
|
||||
def _model(ans, doc, script):
|
||||
body = (
|
||||
f"\nconst ans = {json.dumps(ans, ensure_ascii=False)};"
|
||||
f"\nconst doc = {json.dumps(doc, ensure_ascii=False)};\n{script}"
|
||||
)
|
||||
return _node(
|
||||
[
|
||||
"M02_MasterTemplete/logic/M02_Born_Tag.ts",
|
||||
"M02_MasterTemplete/logic/M02_Sangeun_Undo.ts",
|
||||
"M02_MasterTemplete/logic/M02_Sangeun_Cover_Model.ts",
|
||||
],
|
||||
body,
|
||||
)
|
||||
|
||||
|
||||
def test_727_2_화면_꼴_세부_줄_고침(world): # noqa: F811
|
||||
doc = _sk(world["personal"], 바탕={"로직": GF}, 더한줄=[{**SECOND, "수량": 2}])
|
||||
ans = _run(world["personal"], doc)
|
||||
got = _model(
|
||||
ans,
|
||||
doc,
|
||||
"""
|
||||
const rows = rowsOf(ans, null, doc);
|
||||
const view = hoView(ans, null, null, doc);
|
||||
const sub = rows.find((r) => r.cid === "add:#0/labor:LB000036#0");
|
||||
setLineCover(doc, sub, { qty: 0.072 }, false);
|
||||
const covered = JSON.parse(JSON.stringify(doc.더한줄[0]));
|
||||
dropLine(doc, rows.find((r) => r.cid === "add:#0/pct:공구손료 및 경장비#0"));
|
||||
const dropped = [...doc.더한줄[0].뺀줄];
|
||||
restoreLine(doc, "add:#0/pct:공구손료 및 경장비#0");
|
||||
const one = { ...doc, 더한줄: [] };
|
||||
console.log(JSON.stringify({
|
||||
cids: rows.map((r) => r.cid), boxes: rows.map((r) => r.묶음), sub, covered, dropped,
|
||||
back: doc.더한줄[0].뺀줄 ?? null, tags: view.호표.map((x) => x.꼬리표 ?? ""),
|
||||
extraTags: view.덧줄.map((x) => x.꼬리표 ?? ""), viewCids: view.cids,
|
||||
single: [...tagsOf(ans, one).values()],
|
||||
}));
|
||||
""",
|
||||
)
|
||||
assert "add:#0" not in got["cids"] and "add:#0/labor:LB000036#0" in got["cids"]
|
||||
assert got["sub"]["sub"] == {"k": 0, "cid": "labor:LB000036#0", "scale": 2}
|
||||
assert got["sub"]["수량"] == pytest.approx(0.036) and got["sub"]["묶음"] == "인력"
|
||||
assert got["covered"]["덮개"]["labor:LB000036#0"]["qty"] == pytest.approx(
|
||||
0.072
|
||||
) # 화면 품 그대로(M01 원문 몫 · 748-0 — 수량 2 로 안 나눔)
|
||||
assert got["covered"]["덮개"]["labor:LB000036#0"]["원값"] == {"qty": 0.018, "단가": 233250}
|
||||
assert got["dropped"] == DROP and got["back"] is None
|
||||
assert got["tags"] == ["9-12-1", "9-12-1", "3-2-1", "3-2-1"] # 바탕 둘 · 둘째 기초 인력 둘
|
||||
assert got["extraTags"] == ["3-2-1"] and got["single"] == [] # 기초 하나면 꼬리표 없음
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
@@ -91,7 +89,7 @@ def test_둘째_기초_수량_처음값_배(whole):
|
||||
src = (ROOT / "M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
assert "addBase(" not in src and "baseUnitOf(" in src # 840-1 [항목 추가] 걷음
|
||||
assert "addBase(" not in src # 840-1 [항목 추가] 걷음
|
||||
|
||||
|
||||
def test_돈_아닌_기초_고르기_창에서_뺌(whole):
|
||||
@@ -107,20 +105,3 @@ def test_돈_아닌_기초_고르기_창에서_뺌(whole):
|
||||
assert len(money) == 65 # 지금 M01(785-7 · 옛 21 = M01 기초 늘기 전)
|
||||
src = (ROOT / "M02_MasterTemplete/M02_MasterTemplete_Find_Pick.ts").read_text(encoding="utf-8")
|
||||
assert '!logic.결과단위.trim().startsWith("원")' in src
|
||||
|
||||
|
||||
def test_고침_꼴_화면배_되돌림():
|
||||
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
|
||||
["node", str(HERE / "helper_728_2_cover_unit.cjs")],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
timeout=60,
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr
|
||||
out = json.loads(proc.stdout)
|
||||
assert out["was"]["qty"] == pytest.approx(0.2) # 바탕 값 = 문서 몫(100본)
|
||||
assert out["cover"]["labor:LB000101#0"]["qty"] == pytest.approx(0.3)
|
||||
assert out["added"] == pytest.approx(60)
|
||||
assert out["shown"]["0"]["qty"] == pytest.approx(0.003) # 다시 그리면 화면 몫
|
||||
assert out["shown"]["1"]["qty"] == pytest.approx(0.6)
|
||||
|
||||
@@ -7,7 +7,6 @@ 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")
|
||||
HO = (M01 / "M01_MasterData_UI_LogicLab_Ho.ts").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_옵션_격자_폭_따라_6_4_3_2_1():
|
||||
@@ -27,10 +26,4 @@ def test_합계_한_줄_바닥_고정():
|
||||
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 "buildFoot(sums, calculated, total)" in HO
|
||||
assert 'data-cols="3"' in STYLE and ".m01lab__ho-box + .m01lab__ho-box" in STYLE
|
||||
|
||||
|
||||
def test_공통_옵션은_모든_박스에_같이():
|
||||
assert "optionRows([...usesOf(b), ...common], ctx)" in HO
|
||||
assert "commonCard(" in HO and "boxes.length ||" in HO # 박스 없을 때만 따로 카드
|
||||
assert 'data-cols="3"' in STYLE
|
||||
|
||||
@@ -9,17 +9,12 @@ ROOT = Path(__file__).resolve().parents[2]
|
||||
M02 = ROOT / "M02_MasterTemplete"
|
||||
MAIN = (M02 / "M02_MasterTemplete_UI_Main.ts").read_text(encoding="utf-8")
|
||||
ACTIONS = (M02 / "M02_MasterTemplete_Main_Actions.ts").read_text(encoding="utf-8")
|
||||
HO = (ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts").read_text(encoding="utf-8")
|
||||
COVER = (M02 / "logic" / "M02_Sangeun_Cover_Model.ts").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _born(expr: str):
|
||||
"""순수 TS(`logic/M02_Born_Tag.ts`)를 Node 로 돌려 JSON 답을 받음."""
|
||||
uri = (M02 / "logic" / "M02_Born_Tag.ts").as_uri()
|
||||
code = (
|
||||
f"import {{ bornText, bornOfCid, bornNote }} from '{uri}';"
|
||||
f"console.log(JSON.stringify({expr}));"
|
||||
)
|
||||
code = f"import {{ bornText, bornNote }} from '{uri}';console.log(JSON.stringify({expr}));"
|
||||
out = subprocess.run( # noqa: S603 — 고정 실행 파일
|
||||
["node", "--experimental-strip-types", "--no-warnings", "--input-type=module", "-e", code],
|
||||
capture_output=True,
|
||||
@@ -53,14 +48,6 @@ def test_꼬리표_없으면_빈칸_기초번호_뒤에_붙음():
|
||||
assert got.split("\n")[0] == "A1 · 본뜬 SK-000012"
|
||||
|
||||
|
||||
def test_줄_열쇠에서_그_더한줄_출처를_찾음():
|
||||
adds = json.dumps([{}, {"본뜬": BORN}], ensure_ascii=False)
|
||||
assert _born(f"bornOfCid('add:#1', {adds})").startswith("본뜬 SK-000012")
|
||||
assert _born(f"bornOfCid('add:#1/add:#0', {adds})").startswith("본뜬 SK-000012") # 펼침 세부
|
||||
assert _born(f"bornOfCid('add:#0', {adds})") == ""
|
||||
assert _born(f"bornOfCid('hopyo:X#3', {adds})") == ""
|
||||
|
||||
|
||||
def test_머리_단추_차례_초기화_삭제_저장():
|
||||
kids = MAIN[MAIN.index('className: "m02-main__head"') :]
|
||||
kids = kids[: kids.index("]")]
|
||||
@@ -83,11 +70,6 @@ def test_초기화는_미리보기_뒤_물음_뒤_씀():
|
||||
assert "옵션 · 기본정보는 그대로" in ACTIONS
|
||||
|
||||
|
||||
def test_공용_꼬리표_칸은_첫줄만_보이고_풍선에_나머지():
|
||||
assert 'text.split("\\n")' in HO
|
||||
assert "bornOfCid(" in COVER
|
||||
|
||||
|
||||
def test_격자_비고_칸은_첫줄만():
|
||||
assert _born(f"bornNote({json.dumps(BORN, ensure_ascii=False)})") == "본뜬 SK-000012"
|
||||
assert _born("bornNote(null)") == ""
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
"""748-0 지킴 — SK 둘째 기초 세부 품 = M01 원문(머리 수량 안 곱함) · 고침 꼴 · 빼기 기억 · 되살림 · 수량 처음값.
|
||||
(서버 짝 = `test_744_1_sk_detail_undo.py`)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def test_세부_원문_품_고침_빼기_되살림_처음값():
|
||||
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
|
||||
["node", str(HERE / "helper_748_0_sk_undo.cjs")],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
timeout=60,
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr
|
||||
out = json.loads(proc.stdout)
|
||||
assert float(out["shownQty"]) == pytest.approx(0.871) # 곱하지 않은 M01 원문
|
||||
assert out["lineQty"] == pytest.approx(0.871)
|
||||
assert out["lineAmount"] == pytest.approx(871) # 상자 몫은 그대로
|
||||
assert out["t"] == 1
|
||||
assert out["cover"]["labor:LB000101#0"]["qty"] == pytest.approx(0.9) # 머리 수량 안 나눔
|
||||
assert out["coverShown"] == pytest.approx(0.9) # 다시 그려도 같음
|
||||
assert out["manQty"] == 5 and out["manBack"] == 2 # [되돌림] = 넣을 때 수량
|
||||
drop = out["afterDrop"]
|
||||
assert drop["adds"] == 1 and drop["gone"][0]["차례"] == 0
|
||||
assert drop["pick"] == {"add:#0": "MT1"} # 뒤 더한줄 열쇠 당김
|
||||
assert out["goneRows"][0]["cid"] == "gone:0"
|
||||
back = out["afterBack"]
|
||||
assert back["adds"] == ["LB000002", "GF000316"] and back["gone"] is None
|
||||
assert back["pick"] == {"add:#1": "MT1"} # 되살림 = 밂
|
||||
assert out["baseGone"] == {"adds": 1, "name": "둘째 기초", "pick": {}}
|
||||
assert out["baseBack"] == ["LB000002", "GF000316"]
|
||||
@@ -10,84 +10,8 @@ def _ts(rel: str) -> str:
|
||||
return (ROOT / rel).read_text("utf-8")
|
||||
|
||||
|
||||
def test_detail_uses_only_sk_answer():
|
||||
ts = _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts")
|
||||
assert "text = got.글" in ts and "answer: async" not in ts and "buildCalc" not in ts
|
||||
assert "onText" not in ts and "onLines" not in ts # 바탕 `/calc` · `/text` 부름 걷음
|
||||
assert "dropText" not in ts and "baseCovers" not in ts and "applyCovers" not in ts
|
||||
assert "calcSangeun(scope, plain, values, false)" in ts # 바탕 원값 셈 = 보기 덧칸 없이
|
||||
assert "doc.고름 = " in ts and "pickMat" in ts # 재료 고름 = SK 문서 고름
|
||||
|
||||
|
||||
def test_text_lines_joined_by_cid():
|
||||
ho = _ts("M01_MasterData/M01_MasterData_UI_LogicLab_Ho.ts")
|
||||
assert "ctx.cids && line.cid" in ho and "pickMat" in ho
|
||||
api = _ts("M01_MasterData/M01_MasterData_UI_Logic_Api.ts")
|
||||
assert "cid?: string" in api and "나눔?: number" in api
|
||||
|
||||
|
||||
def test_calc_drive_is_screenless_and_m02_has_no_calc_hook():
|
||||
ts = _ts("M01_MasterData/M01_MasterData_UI_Logic_Calc.ts")
|
||||
assert "ctx.answer" not in ts and "CalcShown" not in ts # 799-2 M02 시험 계산 길 걷음
|
||||
drive = _ts("M01_MasterData/M01_MasterData_UI_Logic_Drive.ts")
|
||||
assert "runCalc(body)" in drive and "document." not in drive # 셈 구동 = 화면 없이
|
||||
|
||||
|
||||
def test_752_1_source_panel_only_on_sangeun_screen():
|
||||
"""752-1 원문 패널 — 단가산출 화면만 켬 · 일위대가 줄 모달 안 상세는 끔 · 기초마다 탭 · 좁은 폭 접힘."""
|
||||
side = _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Side.ts")
|
||||
assert "/m02/logic-lib/source" in side and "createSidePanels" in side
|
||||
assert "OPEN_FROM" in side and "createSegment" in side
|
||||
assert "source: true" in _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_View.ts")
|
||||
assert "source" not in _ts("M02_MasterTemplete/M02_MasterTemplete_Labor_RowSk.ts")
|
||||
detail = _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts")
|
||||
assert "opt.source ? createSangeunSide()" in detail and "side?.set(" in detail
|
||||
|
||||
|
||||
def test_753_2_option_off_flag_reaches_sheet_and_views():
|
||||
"""753-2 옵션으로 빠진 줄 — SK 줄 `옵션꺼짐` → 표 줄 `off` → 계산서 줄 `옵션꺼짐`(공용 계산서 · 상세 ·
|
||||
텍스트 수식 · 시험 계산이 안 그림) · 소계 · 금액은 그대로."""
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
if shutil.which("node") is None:
|
||||
pytest.skip("node 가 없음")
|
||||
m02 = ROOT / "M02_MasterTemplete"
|
||||
strip = lambda p: re.sub(r"^import .*$", "", p.read_text("utf-8"), flags=re.M) # noqa: E731
|
||||
src = "\n".join(
|
||||
[
|
||||
strip(m02 / "logic" / "M02_Born_Tag.ts"),
|
||||
strip(m02 / "logic" / "M02_Sangeun_Undo.ts"),
|
||||
# 751-3 모델이 가져오는 B09 `rounddown`(import 줄을 빼므로 같은 식을 둠)
|
||||
"const rounddown = (v, p = 0) => { const s = 10 ** p; "
|
||||
"const a = Math.floor(Math.abs(v) * s + 1e-7) / s; return v < 0 ? -a : a; };",
|
||||
strip(m02 / "logic" / "M02_Sangeun_Cover_Model.ts"),
|
||||
"""
|
||||
const line = (cid, 이름, 수량, 금액, 꺼짐) => ({ cid, 이름, 단위: "개", 수량, 단가: 100, 금액,
|
||||
비목: { 재료비: 금액 }, 묶음: "재료", ...(꺼짐 ? { 옵션꺼짐: true } : {}) });
|
||||
const ans = { 기준: null, 짝잃음: [], 바탕판: "x", 정체: ["material:A#0", "material:B#0"],
|
||||
줄: [line("material:A#0", "폼타이 12.7", 0, 0, true), line("material:B#0", "합판", 1, 100, false)] };
|
||||
const rows = rowsOf(ans, null, {});
|
||||
console.log(JSON.stringify({ off: rows.map((r) => r.off) }));
|
||||
""",
|
||||
]
|
||||
)
|
||||
out = subprocess.run(
|
||||
["node", "--experimental-strip-types", "--no-warnings",
|
||||
"--input-type=module-typescript", "-e", src],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60,
|
||||
) # fmt: skip
|
||||
assert out.returncode == 0, out.stderr
|
||||
got = json.loads(out.stdout)
|
||||
assert got["off"] == [True, False]
|
||||
sheet = (ROOT / "A00_Common" / "calc_sheet.ts").read_text("utf-8")
|
||||
assert "b.줄.filter(shown)" in sheet and "g.줄.filter(shown)" in sheet
|
||||
ho = (ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts").read_text("utf-8")
|
||||
assert "옵션꺼짐" in ho
|
||||
assert "옵션꺼짐" in (ROOT / "M01_MasterData" / "M01_MasterData_UI_Logic_Calc.ts").read_text(
|
||||
"utf-8"
|
||||
)
|
||||
|
||||
@@ -350,24 +350,3 @@ def test_겹침_율_열쇠_새_차례():
|
||||
|
||||
|
||||
# ── 화면 — 더한줄 지움 · 되살림 때 율 기준 열쇠 옮김(`logic/M02_Sangeun_Undo.ts`) ──────────
|
||||
def test_화면_더한줄_지움_되살림_율_열쇠():
|
||||
code = IMPORTS.sub(
|
||||
"", (ROOT / "M02_MasterTemplete/logic/M02_Sangeun_Undo.ts").read_text("utf-8")
|
||||
)
|
||||
doc = _doc([LABOR[0], LABOR[1], _rate(["add:#1@노무비", "add:#0", "labor:LB000038#0"])])
|
||||
body = (
|
||||
f"\nconst doc = {json.dumps(doc, ensure_ascii=False)};"
|
||||
"\nconst key = () => doc.더한줄.at(-1).고정.비율.기준;"
|
||||
"\nforgetAdd(doc, 0, ''); const a = key(); reviveAdd(doc, 0);"
|
||||
"\nconsole.log(JSON.stringify([a, key()]));"
|
||||
)
|
||||
got = subprocess.run(
|
||||
["node", "--experimental-strip-types", "--no-warnings",
|
||||
"--input-type=module-typescript", "-e", code + body],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60,
|
||||
) # fmt: skip
|
||||
assert got.returncode == 0, got.stderr
|
||||
assert json.loads(got.stdout) == [
|
||||
["add:#0@노무비", "labor:LB000038#0"], # 지운 줄 열쇠 버림 · 뒤 줄 당김(비목 꼬리 그대로)
|
||||
["add:#1@노무비", "labor:LB000038#0"], # 되살림 = 뒤 줄 밂
|
||||
]
|
||||
|
||||
@@ -129,4 +129,3 @@ def test_screen_same_part_first_tab():
|
||||
tabs = (root / "M02_MasterTemplete_Sangeun_Tabs.ts").read_text(encoding="utf-8")
|
||||
# 799-2 · 836-3 — 시트 · 인력·재료·경비 · 시험 계산 · 텍스트 수식 · 보기 고르기(단가산출 상세 탭) 걷음
|
||||
assert not re.findall(r'\{ value: "(\w+)", label: ', tabs) and "createSegment" not in tabs
|
||||
assert "show(true);" in tabs
|
||||
|
||||
@@ -8,13 +8,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from decimal import Decimal as D
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_Imported as imp
|
||||
@@ -22,7 +18,6 @@ from resources.tester.test_795_1_sk_copy import _calc, _doc, _imported_row
|
||||
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
HO = ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts"
|
||||
COSTS = ("노무비", "재료비", "경비")
|
||||
|
||||
|
||||
@@ -65,31 +60,3 @@ def test_plain_sample_has_no_tag(world):
|
||||
assert not any("합밖" in x for x in ans["줄"])
|
||||
kept = _sum(ans["줄"], True)
|
||||
assert all(int(kept[k]) == int(D(str(ans["기준"][k]))) for k in COSTS)
|
||||
|
||||
|
||||
@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음")
|
||||
def test_box_subtotal_skips_outside():
|
||||
src = HO.read_text(encoding="utf-8")
|
||||
pure = src[src.index("/* ── 순수 셈 ── */") : src.index("/* ── 순수 셈 끝 ── */")]
|
||||
body = """
|
||||
const e = (idx, bundle, amount, out) => ({ idx, bundle, merge: false, amount, out });
|
||||
const got = boxesOf([e(0, "인력", 10, false), e(1, "인력", 7, true), e(2, "재료", 5)], ["경비"]);
|
||||
console.log(JSON.stringify(got.map((b) => [b.묶음, b.소계, b.줄.length])));
|
||||
"""
|
||||
run = subprocess.run(
|
||||
["node", "--experimental-strip-types", "--no-warnings",
|
||||
"--input-type=module-typescript", "-e", pure + body],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60,
|
||||
) # fmt: skip
|
||||
assert run.returncode == 0, run.stderr
|
||||
assert json.loads(run.stdout) == [["인력", 10, 2], ["재료", 5, 1], ["경비", 0, 0]] # 줄은 보임
|
||||
|
||||
|
||||
def test_screen_wiring():
|
||||
src = HO.read_text(encoding="utf-8")
|
||||
assert src.count("out: !!line?.합밖,") == 2 # 호표 줄 · 덧줄
|
||||
assert "e.group === g && !e.out" in src # 맨 아래 합계
|
||||
assert 'createBadge(th("Out")' in src and len(src.splitlines()) <= 700
|
||||
assert "합밖?: boolean" in (
|
||||
ROOT / "M01_MasterData" / "M01_MasterData_UI_Logic_Api.ts"
|
||||
).read_text(encoding="utf-8")
|
||||
|
||||
@@ -78,7 +78,7 @@ def test_셈_구동은_화면_없이_상세는_구동만():
|
||||
) # 로직 복사 화면이 쓰는 시험 계산 칸 — 구동은 공용
|
||||
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 and "createSangeunTabs(editor" in m02
|
||||
assert "buildCalc" not in m02 and "calcHost" not in m02
|
||||
|
||||
|
||||
def test_파일_700줄_안():
|
||||
|
||||
@@ -218,7 +218,6 @@ def test_M02_수식탭_M01과_같은_단추_저장_한_번() -> None:
|
||||
tabs = _src("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts")
|
||||
assert "page: opt.page," in tabs and "save: () => stack.save()," in tabs
|
||||
detail = _src("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts")
|
||||
assert "page: opt.source ? () => report() : undefined," in detail
|
||||
assert "JSON.stringify(doc) !== saved || tabs.dirty()" in detail # 고침 알림 = 기본 + 수식
|
||||
assert (
|
||||
"addButton" not in detail and "rateButton" not in detail
|
||||
@@ -343,5 +342,3 @@ def test_808_1_수량_칸_식_글_꼬리표_글꼴_머리():
|
||||
screen = _src("A00_Common/line_stack_screen.ts")
|
||||
assert "opt.tools?.replaceChildren(...tools);" in screen
|
||||
assert "children: opt.tools ? [] : tools" in screen
|
||||
tabs = _src("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts")
|
||||
assert "stack.root.hidden = tools.hidden = !doc;" in tabs
|
||||
|
||||
@@ -56,7 +56,7 @@ def test_단가산출_줄은_SK_문서_모달_저장은_그_SK():
|
||||
r'saveTemplate\(\s*layer,\s*"sangeun",\s*opt\.ref\.키', modal
|
||||
) # 저장 = 그 SK 문서
|
||||
assert (
|
||||
"mountSangeunDetail(host, doc," in modal and "source: true" in modal
|
||||
"mountSangeunDetail(host, doc," in modal and 'mode: "page"' in modal
|
||||
) # 수식 탭 부품 그대로
|
||||
assert "await handle.flush();" in modal # 수식 저장 먼저 → 문서 저장
|
||||
assert "if (!opt.readOnly) head.append(ok);" in modal # 읽기만 = [저장] 없음
|
||||
@@ -130,13 +130,7 @@ def test_808_1_모달_머리_일원화():
|
||||
row = _src("M02_MasterTemplete_Labor_RowModal.ts")
|
||||
for gone in ("AlsoSk", "createCheckbox", "openLaborInput", "saveAsSk", "Labor_Option"):
|
||||
assert gone not in row, gone
|
||||
assert "actions: row.참조 ? [slot, ...tools] : tools," in row and 't("FromSk")' in row
|
||||
assert "slot: o.slot," in _src("M02_MasterTemplete_Labor_RowSk.ts")
|
||||
assert 't("FromSk")' in row
|
||||
detail = _src("M02_MasterTemplete_Sangeun_Detail.ts")
|
||||
assert "...(opt.slot ? [] : [" in detail # 머리 칸 있으면 머리 줄 없음
|
||||
assert "children: [tabs.tools]" in detail and "tabs.picker" not in detail
|
||||
assert r"/^SK-(?!0{6})\d{6}$/" in detail
|
||||
tabs = _src("M02_MasterTemplete_Sangeun_Tabs.ts")
|
||||
assert (
|
||||
"const doc = !!k || !!opt.page || !!opt.memory?.();" in tabs
|
||||
) # 836-3 · 836-5 문서 없는 줄 = 상세 몸만
|
||||
|
||||
@@ -61,13 +61,6 @@ def test_screen_memory_doc_stack_view() -> None:
|
||||
tabs = (ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Tabs.ts").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
assert (
|
||||
"const doc = !!k || !!opt.page || !!opt.memory?.();" in tabs
|
||||
and "memory: opt.memory," in tabs
|
||||
)
|
||||
detail = (ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Detail.ts").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
assert "doc.가져온 &&" in detail and "memory: () =>" in detail
|
||||
assert "memory: opt.memory," in tabs
|
||||
router = (ROOT / "M02_MasterTemplete" / "M02_Doc_Router.py").read_text(encoding="utf-8")
|
||||
assert '"/layers/{layer}/sangeun/-/doc/read"' in router and "write=body.본 is None" in router
|
||||
|
||||
@@ -31,35 +31,32 @@ def _run() -> dict:
|
||||
|
||||
def test_sk_page_open_calls_and_hidden_body() -> None:
|
||||
got = _run()
|
||||
# 바탕 있는 SK = 셈 두 번(바탕 원값 bare) · 바탕 없음 = 한 번 · 상세 몸 DOM 둘(덮개 그릇 · 호표) 숨김
|
||||
assert got["page_base"]["calc"] == 2
|
||||
assert got["page_nobase"]["calc"] == 1
|
||||
# 856-1 — 셈 한 번(머리 띠용 · 바탕 원값 bare 셈 걷음) · 숨은 상세 몸 DOM 0 · 줄 쌓기 한 번 그림
|
||||
for k in ("page_base", "page_nobase", "memory"):
|
||||
assert got[k]["body"] == 2, k
|
||||
assert got[k]["bodyShown"] == 0, k
|
||||
assert got[k]["calc"] == 1, k
|
||||
assert got[k]["body"] == 0, k
|
||||
assert got[k]["stack"]["shown"] is True, k
|
||||
assert {d["key"] for d in got["page_base"]["stack"]["draws"]} == {"SK-000001"}
|
||||
assert got["page_base"]["stack"]["draws"] == [{"key": "SK-000001", "memory": False}]
|
||||
# 불러오기 미리 보기(저장 전 가져온 식) = 빈 키 + 문서째
|
||||
assert all(d == {"key": "", "memory": True} for d in got["memory"]["stack"]["draws"])
|
||||
assert got["memory"]["calc"] == 1
|
||||
assert got["memory"]["stack"]["draws"] == [{"key": "", "memory": True}]
|
||||
|
||||
|
||||
def test_labor_row_click() -> None:
|
||||
sk, logic = _run()["labor"]
|
||||
# 단가산출 참조 줄 = 그 SK 문서 모달 · 줄 쌓기가 그 키로 보임 · 몸 안 보임
|
||||
# 단가산출 참조 줄 = 그 SK 문서 모달 · 줄 쌓기가 그 키로 보임
|
||||
assert sk["skModal"] == 1 and sk["stack"]["shown"] is True
|
||||
assert set(sk["stack"]["draws"]) == {"SK-000010"} and sk["body"] == 0
|
||||
# M01 로직 줄 = 옛 줄 모달 — 줄 쌓기 숨김 · 상세 몸 보임 · 안내 띠 하나 · 셈 둘(정체 + 상세)
|
||||
assert logic["skModal"] == 0 and logic["stack"]["shown"] is False
|
||||
assert logic["body"] == 1 and logic["banners"] == ["info"] and logic["calc"] == 2
|
||||
assert sk["stack"]["draws"] == ["SK-000010"] and sk["calc"] == 1
|
||||
# M01 로직 줄 = 줄 모달(안내 한 줄) · 상세 몸 · 줄 쌓기 · 셈 없음(856-1)
|
||||
assert logic["skModal"] == 0 and logic["stack"] is None
|
||||
assert logic["body"] == 0 and logic["banners"] == ["info"] and logic["calc"] == 0
|
||||
|
||||
|
||||
def test_labor_row_click_inject() -> None:
|
||||
sk, logic = _run()["labor_inject"]
|
||||
# 셈 주입(프로젝트 사본) = 옛 줄 모달 · 상세 없음 · 안내 띠 없음 · 셈 없음
|
||||
# 셈 주입(프로젝트 사본) = 줄 모달 · 안내 한 줄(856-3 까지) · 셈 없음
|
||||
for row in (sk, logic):
|
||||
assert row["modal"] and row["stack"] is None
|
||||
assert row["body"] == 0 and row["banners"] == [] and row["calc"] == 0
|
||||
assert row["body"] == 0 and row["banners"] == ["info"] and row["calc"] == 0
|
||||
|
||||
|
||||
def test_head_bands_four() -> None:
|
||||
|
||||
@@ -160,20 +160,11 @@ export const ui_locales_m2 = {
|
||||
M02_SangeunNoBase: ["바탕 없음", "No base"],
|
||||
M02_SangeunEdited: ["고친 줄", "Edited rows"],
|
||||
M02_SangeunUsers: ["쓰는 곳", "Used by"],
|
||||
M02_SangeunRemoved: ["뺀 줄", "Removed rows"],
|
||||
M02_SangeunUnit: ["단위(1 단위 값)", "Unit (value per 1)"],
|
||||
M02_SangeunNeed: ["비우면 저장 안 됨", "Required"],
|
||||
M02_SangeunSwapCoef: ["환산 계수", "Conversion factor"],
|
||||
M02_SangeunSwapWeight: ["단위중량", "Unit weight"],
|
||||
M02_SangeunSwapPick: ["고르세요", "Choose"],
|
||||
M02_SangeunDrop: ["삭제", "Delete"],
|
||||
M02_SangeunDropBase: ["기초 빼기", "Remove base"],
|
||||
M02_SangeunBases: ["더한 기초", "Added bases"],
|
||||
M02_SangeunBaseQty: ["수량(기준단위 몇 개)", "Quantity (base units)"],
|
||||
M02_SangeunBaseQtyBad: ["0 이상 수만", "Numbers ≥ 0 only"],
|
||||
M02_SangeunQtyUndo: ["되돌림", "Undo"],
|
||||
M02_SangeunRestore: ["되살리기", "Restore"],
|
||||
M02_SangeunApart: ["별도계상", "Counted separately"],
|
||||
M02_SangeunRevisedBase: ["M01 개정 — 확인", "M01 revised — check"],
|
||||
M02_SangeunRevisedNote: [
|
||||
"바탕 단가산출 기초가 저장 뒤 바뀜 — 고친 칸의 바탕 값을 확인하고 [저장]하면 새 판으로 맞춤",
|
||||
@@ -187,7 +178,6 @@ export const ui_locales_m2 = {
|
||||
"못 셈 줄 — 금액 빼고 나머지로 셈 · 줄을 빼거나 입력을 채움",
|
||||
"Lines not priced — total uses the rest · drop the line or fill its input",
|
||||
],
|
||||
M02_SangeunScaleOnly: ["열린 입력 — 품은 배율만", "Open inputs — quantity as multiplier only"],
|
||||
M02_SangeunSourceNone: ["원문 연결 없음 — 바탕 로직 없음", "No source — no base logic"],
|
||||
M02_SangeunColName: ["이름", "Name"],
|
||||
M02_SangeunColUnit: ["단위", "Unit"],
|
||||
|
||||
Reference in New Issue
Block a user