Merge remote-tracking branch 'origin/dev' into sub_laptop_2
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"],
|
||||
|
||||
@@ -70,13 +70,54 @@ def _index(sk: dict, master: Any = None, doc: Any = None) -> Any:
|
||||
return master or imp._whole()
|
||||
|
||||
|
||||
# ── 엑셀 단가 그대로 엔진 줄(옛 셈 길 · SK 고침 얹은 것) ───────────────────
|
||||
# ── 엑셀 단가 그대로 고친 줄(가져온 로직 줄 + SK 고침 · 엔진 셈 없음) ─────────
|
||||
def _engine_adds(doc: dict) -> bool:
|
||||
"""값을 엔진 셈으로만 얻는 더한줄(형제 SK · 율 · 세부 고친 둘째 기초)이 있음 — 옛 길(`_old_ctx`)."""
|
||||
return any(
|
||||
one.get("참조") or sd.is_rate(one) or sd.sub_patched(one) for one in doc.get("더한줄") or []
|
||||
)
|
||||
|
||||
|
||||
def _ctx(sk: dict, whole: Any) -> tuple:
|
||||
"""엑셀 단가 기준 고친 줄 — 옛 셈 길(`OLD`)로 돌려 엔진에 넣은 (색인, 키, 입력, 답, 재료)."""
|
||||
"""엑셀 단가 기준 고친 줄(855 2-C2) — 가져온 로직 줄(`row_of`) + 수식 고침 · SK 고침(`sd.patched`) ·
|
||||
더한줄 고정 값(`fixed.line`) → (색인, 키, 입력, {정체}, None) · 옛 엔진 안 돎.
|
||||
안쪽 산근(형제 SK) 줄 값 = 0 자리값(`_attach` 가 형제 SK 연결 + 엑셀 값으로 갈음).
|
||||
`_engine_adds` 인 SK 만 옛 셈 길(그 더한줄 값이 엔진 답 — 2-C1 · 2-C5 몫)."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
from M02_MasterTemplete import M02_Sangeun_Copy as skc
|
||||
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
|
||||
|
||||
raw = {**sk, imp.KEY: {**sk[imp.KEY], "단가기준": "엑셀"}}
|
||||
doc = sd.clean(raw, None, whole)
|
||||
if _engine_adds(doc):
|
||||
return _old_ctx(raw, whole)
|
||||
w = skc.over(doc, whole)
|
||||
base = sd.empty_row(doc)
|
||||
base = {**base, "호표": [dict(x) for x in base.get("호표") or []]}
|
||||
for item in base["호표"]:
|
||||
if "참조" in item and item.get("값묶음") is None:
|
||||
item["값묶음"] = dict.fromkeys(imp.COSTS, Decimal(0))
|
||||
base, _ = eqm.on(base, doc, skc.over(doc, w))
|
||||
filled, lack = calc._fill(doc, w, dict(doc.get("입력값") or {}))
|
||||
got = sd.patched(base, filled, {}, {})
|
||||
items = got["줄"]["호표"]
|
||||
calc._direct(got["자재표시"], items)
|
||||
for at, cid in enumerate(got["정체"][: len(items)]):
|
||||
if cid.startswith("add:#") and int(cid[5:]) in lack:
|
||||
items[at] = calc._gap(items[at], lack[int(cid[5:])])
|
||||
row = {**got["줄"], "호표": [dict(x) for x in items]}
|
||||
calc._bundles(row, w, None, ()) # 더한줄 고정 줄 = 줄 값 · 이은 노임 · 자재(엔진 아님)
|
||||
key = str(doc.get("키") or "SK-000000")
|
||||
names = {str(i.get("이름")) for i in row.get("입력") or []}
|
||||
values = {k: v for k, v in (doc.get("입력값") or {}).items() if k in names}
|
||||
return _Row(w, key, {**row, "키": key}), key, values, {"정체": got["정체"]}, None
|
||||
|
||||
|
||||
def _old_ctx(raw: dict, whole: Any) -> tuple:
|
||||
"""옛 셈 길(`OLD`)로 돌려 엔진에 넣은 (색인, 키, 입력, 답, 재료) — `_engine_adds` SK 만."""
|
||||
from M02_MasterTemplete import M02_Doc_Sk as dsk
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
|
||||
raw = {**sk, imp.KEY: {**sk[imp.KEY], "단가기준": "엑셀"}}
|
||||
box: list = []
|
||||
token = dsk.OLD.set(True)
|
||||
try:
|
||||
@@ -407,7 +448,7 @@ def _numbers(doc: dict, keep: dict) -> None:
|
||||
|
||||
|
||||
def derive(sk: dict, ctx: tuple | None = None, whole: Any = None) -> dict:
|
||||
"""가져온 식 SK → 수식 문서(키 = SK 키) — `ctx` = 엑셀 단가 기준 옛 셈 길이 엔진에 넣은 것."""
|
||||
"""가져온 식 SK → 수식 문서(키 = SK 키) — `ctx` = 엑셀 단가 기준 고친 줄(`_ctx` · 옛 SK 셈 길이 넘긴 것도 같은 꼴)."""
|
||||
meta = sk[imp.KEY]
|
||||
if ctx is None:
|
||||
ctx = _ctx(sk, whole or imp._whole())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""M02 일위대가 실무자료 읽기(PLAN 324-1) — 설계내역서 엑셀 「일위대가」 시트 →
|
||||
호표 · 줄 · 갈래 · 검산.
|
||||
|
||||
읽기 = .xls `xlrd`(경고가 stdout 으로 안 나가게 logfile) · .xlsx `openpyxl`(빈 칸 None) ·
|
||||
읽기 = 책 한 벌 `M02_San_Workbook.read`(857-1 · .xls xlrd · .xlsx openpyxl · 빈 칸 None) ·
|
||||
시트 · 열은 머리 글(빈칸 뺌)로 찾음 — 호표 · 품명 · 규격 · 수량 · 단위 · 합계 · 노무비 ·
|
||||
재료비 · 경비 · 비고(돈 머리 = 단가 열 · 다음 열 = 금액).
|
||||
호표 줄 = 「제N호표」 · 호표 1 단위 값 = 금액 열 · 구성 줄 = 호표 칸 빔 · 품명 있음 ·
|
||||
@@ -25,7 +25,6 @@ STmate 꼴(「일위대가표」 · 「단가산출근거」 시트) = `M02_Hopy
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
from decimal import ROUND_FLOOR, Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
@@ -34,6 +33,7 @@ from M02_MasterTemplete import M02_Hopyo_Clause as hopyo_clause # 출처 풀이
|
||||
from M02_MasterTemplete import M02_Hopyo_ReadEst as hopyo_est # EST 단가산출 어댑터(776-2)
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as hopyo_stmate
|
||||
from M02_MasterTemplete import M02_Hopyo_UnitLine as unit_line
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook # 책 한 벌(857-1)
|
||||
|
||||
SHEET = "일위대가"
|
||||
SUMMARY = "일위대가총괄표"
|
||||
@@ -43,8 +43,7 @@ HEADS = ("호표", "품명", "규격", "수량", "단위", "비고")
|
||||
NO_SHEET = "일위대가 시트 없음"
|
||||
_HOPYO = re.compile(r"제\s*(\d+)\s*호표")
|
||||
_REF = re.compile(r"^(?:(단산|산근|단가산출)|(일위대가|일위|대가))(\d+)(?:참조|호표)?$")
|
||||
DRM = "문서 보안(DRM)으로 잠긴 파일 — 보안을 푼 사본으로 저장해 올림"
|
||||
_OLE = b"\xd0\xcf\x11\xe0"
|
||||
DRM = workbook.DRM
|
||||
_MACHINE_UNITS = ("hr", "시간", "h")
|
||||
_CODE_KIND = {
|
||||
"D": "단가산출",
|
||||
@@ -54,12 +53,7 @@ _CODE_KIND = {
|
||||
"S": "별도계상",
|
||||
"W": "별도계상",
|
||||
}
|
||||
# ponytail: 마지막 연 책 하나(올림 길 read_book → Grid.read 가 같은 바이트) — 여럿 동시면 다시 엶
|
||||
_OPENED: tuple[bytes, dict[str, list[list[Any]]], Any] | None = None
|
||||
|
||||
|
||||
class ExcelError(ValueError):
|
||||
"""엉터리 파일 · 시트 없음 — 길이 400 으로 답함."""
|
||||
ExcelError = workbook.BookError # 엉터리 파일 · 시트 없음 — 길이 400 으로 답함
|
||||
|
||||
|
||||
def _flat(value: Any) -> str:
|
||||
@@ -93,64 +87,6 @@ def _out(value: Decimal | None) -> int | float | None:
|
||||
return int(value) if value == value.to_integral_value() else float(value)
|
||||
|
||||
|
||||
# ── 파일 → 시트 표(줄마다 값 목록) ────────────────────────────────────────
|
||||
def _sheets(name: str, data: bytes, wanted: tuple[str, ...] = ()) -> dict[str, list[list[Any]]]:
|
||||
"""시트 이름 → 줄 목록 — 일위대가 · 총괄표 · 단가산출만 읽음(`wanted` = 더 읽을 시트)."""
|
||||
return _open(name, data, wanted)[0]
|
||||
|
||||
|
||||
def opened(name: str, data: bytes, wanted: tuple[str, ...] = ()) -> tuple[dict[str, Any], Any]:
|
||||
"""(시트 줄, xls 책 | None) — 방금 `read_book` 이 연 같은 바이트면 그 책(한 번 열기 · 776-2) ·
|
||||
아니면 엶. xls 책 = xlrd `formatting_info`(격자 서식)."""
|
||||
global _OPENED
|
||||
got, _OPENED = _OPENED, None
|
||||
if got is not None and got[0] is data: # read_book 은 목록 시트(LISTS)까지 읽어 둠
|
||||
return got[1], got[2]
|
||||
return _open(name, data, wanted)
|
||||
|
||||
|
||||
def _open(
|
||||
name: str, data: bytes, wanted: tuple[str, ...] = ()
|
||||
) -> tuple[dict[str, list[list[Any]]], Any]:
|
||||
keep = (SHEET, SUMMARY, hopyo_est.SHEET, *wanted)
|
||||
if not data:
|
||||
raise ExcelError("빈 파일")
|
||||
if b"DRMONE" in data[:256] and data[:4] not in (b"PK\x03\x04", _OLE):
|
||||
raise ExcelError(DRM)
|
||||
try:
|
||||
if data[:4] == b"PK\x03\x04" or name.lower().endswith(".xlsx"):
|
||||
import openpyxl
|
||||
|
||||
book = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
||||
if hopyo_stmate.is_stmate([t.strip() for t in book.sheetnames]):
|
||||
keep = (*hopyo_stmate.SHEETS, *wanted)
|
||||
out = {
|
||||
ws.title.strip(): [list(row) for row in ws.iter_rows(values_only=True)]
|
||||
for ws in book.worksheets
|
||||
if ws.title.strip() in keep
|
||||
}
|
||||
book.close()
|
||||
return out, None
|
||||
import xlrd
|
||||
|
||||
try:
|
||||
book = xlrd.open_workbook(
|
||||
file_contents=data, formatting_info=True, logfile=io.StringIO()
|
||||
)
|
||||
except Exception: # 서식 표가 깨진 파일 — 값만(격자는 그때 서식 없이 다시 엶)
|
||||
book = xlrd.open_workbook(file_contents=data, logfile=io.StringIO())
|
||||
rows = {
|
||||
sh.name.strip(): [sh.row_values(r) for r in range(sh.nrows)]
|
||||
for sh in book.sheets()
|
||||
if sh.name.strip() in keep
|
||||
}
|
||||
return rows, book
|
||||
except ExcelError:
|
||||
raise
|
||||
except Exception as error: # 라이브러리마다 다른 예외 — 깨진 파일 · 엑셀 아님
|
||||
raise ExcelError("엑셀 파일을 읽지 못함 — xls · xlsx 가 아니거나 깨진 파일") from error
|
||||
|
||||
|
||||
def _columns(rows: list[list[Any]], money: tuple[str, ...]) -> tuple[int, dict[str, int]]:
|
||||
"""(자료 첫 줄, {머리: 열}) — 머리 글은 앞 10 줄 안 「호표」 · 「품명」 이 든 줄."""
|
||||
for at, row in enumerate(rows[:10]):
|
||||
@@ -297,20 +233,23 @@ def _by_name(raw: list[list[dict[str, Any]]], blocks: dict[int, dict[str, Any]])
|
||||
|
||||
|
||||
# ── 읽기 ──────────────────────────────────────────────────────────────
|
||||
def read_book(name: str, data: bytes) -> dict[str, Any]:
|
||||
"""엑셀 → `{시트, 호표: [...], 검산: {어긋남: [글 …], 총괄표: 맞춘 수}}` — 값은 JSON 수."""
|
||||
global _OPENED
|
||||
sheets, xls = _open(name, data, LISTS)
|
||||
_OPENED = (data, sheets, xls) # 격자(`Grid.read`)가 이어 씀 — 한 번 열기
|
||||
if hopyo_stmate.is_stmate(sheets):
|
||||
return unit_line.settle(hopyo_clause.settle(hopyo_stmate.read(sheets)))
|
||||
def read_book(
|
||||
name: str, data: bytes, book: workbook.Book | None = None, blocks_only: bool = False
|
||||
) -> dict[str, Any]:
|
||||
"""엑셀 → `{시트, 호표: [...], 검산: {어긋남: [글 …], 총괄표: 맞춘 수}}` — 값은 JSON 수 ·
|
||||
`book` = 올림 길이 한 번 연 책(857-1) · `blocks_only`(올림 길) = 단가산출 시트가 있으면 일위대가
|
||||
시트 · 호표 없음도 받음(호표 빈 목록 · 단산만)."""
|
||||
book = book or workbook.read(name, data)
|
||||
sheets, loose = book.sheets, blocks_only and book.kind is not None
|
||||
if book.kind == "STmate":
|
||||
return unit_line.settle(hopyo_clause.settle(hopyo_stmate.read(sheets, loose)))
|
||||
rows = sheets.get(SHEET)
|
||||
if rows is None:
|
||||
if rows is None and not loose:
|
||||
raise ExcelError(NO_SHEET)
|
||||
start, cols = _columns(rows, ("합계", *COSTS))
|
||||
start, cols = _columns(rows, ("합계", *COSTS)) if rows is not None else (0, {})
|
||||
hopyos: list[dict[str, Any]] = []
|
||||
raw: list[list[dict[str, Any]]] = []
|
||||
for at, row in enumerate(rows[start:], start + 1):
|
||||
for at, row in enumerate((rows or [])[start:], start + 1):
|
||||
head = _flat(_cell(row, cols.get("호표")))
|
||||
name_ = _text(_cell(row, cols.get("품명")))
|
||||
hit = _HOPYO.fullmatch(head)
|
||||
@@ -347,7 +286,7 @@ def read_book(name: str, data: bytes) -> dict[str, Any]:
|
||||
line["갈래"] = kind_of(line)
|
||||
line["행"] = hopyos[-1]["행"][1] = at
|
||||
raw[-1].append(line)
|
||||
if not hopyos:
|
||||
if not hopyos and not loose:
|
||||
raise ExcelError(f"{SHEET} 시트에 호표(제N호표)가 없음")
|
||||
blocks = hopyo_est.read(sheets.get(hopyo_est.SHEET))
|
||||
_by_name(raw, blocks)
|
||||
|
||||
@@ -29,6 +29,7 @@ from openpyxl.xml.functions import fromstring, iterparse
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hopyo_excel
|
||||
from M02_MasterTemplete import M02_Hopyo_ReadEst as hopyo_basis # EST 단가산출 시트 이름
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as hopyo_stmate
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
LIST_E, HOPYO_S = hopyo_excel.LISTS
|
||||
LIST_S = hopyo_stmate.LISTS[0]
|
||||
@@ -241,11 +242,8 @@ def _xlsx_widths(
|
||||
return out
|
||||
|
||||
|
||||
def _xlsx(
|
||||
name: str, data: bytes, found: dict[str, list[list[Any]]] | None = None
|
||||
) -> dict[str, Any]:
|
||||
def _xlsx(name: str, data: bytes, found: dict[str, list[list[Any]]]) -> dict[str, Any]:
|
||||
# ponytail: xlsx 는 값 · 열 폭만(병합 · 서식은 openpyxl 비 read_only 로 무거움) — 필요하면 그때
|
||||
found = found or hopyo_excel._sheets(name, data, EXTRA)
|
||||
widths = _xlsx_widths(data, SHEETS)
|
||||
sheets = []
|
||||
for at, title in enumerate((n for n in SHEETS if n in found), 1):
|
||||
@@ -322,10 +320,13 @@ def _lists(rows: dict[str, Any], parsed: dict[str, Any]) -> dict[str, list[dict[
|
||||
return {"호표": pair(hopyo), "단산": pair(calc)}
|
||||
|
||||
|
||||
def read(name: str, data: bytes, parsed: dict[str, Any]) -> dict[str, Any]:
|
||||
def read(
|
||||
name: str, data: bytes, parsed: dict[str, Any], opened: workbook.Book | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""엑셀 → `{책: Workbook, 호표, 단산, 보기, 원본, 목록, 줄}` — `parsed` =
|
||||
`M02_Hopyo_Excel.read_book` 결과(행 범위)."""
|
||||
rows, xls = hopyo_excel.opened(name, data, EXTRA) # 읽기가 연 책 그대로(한 번 열기 · 776-2)
|
||||
`M02_Hopyo_Excel.read_book` 결과(행 범위) · `opened` = 올림 길이 한 번 연 책(857-1)."""
|
||||
opened = opened or workbook.read(name, data)
|
||||
rows, xls = opened.sheets, opened.xls
|
||||
book = _xlsx(name, data, rows) if xls is None else _xls(xls)
|
||||
keep = ("번", "이름", "행")
|
||||
ids = {s["이름"]: s["id"] for s in book["시트"]}
|
||||
|
||||
@@ -32,6 +32,7 @@ from M02_MasterTemplete import M02_Hopyo_Store as hopyo_store
|
||||
from M02_MasterTemplete import M02_Hopyo_View as hopyo_view_
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_MatPick as mat_pick
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as from_hopyo
|
||||
from M02_MasterTemplete.M02_MasterTemplete_Router_Items import Layer, Session, _call
|
||||
from M02_MasterTemplete.M02_MasterTemplete_Router_Items import _root as _layer_root
|
||||
@@ -79,16 +80,17 @@ def _upload(name: str, data: bytes, who: dict[str, Any]) -> dict[str, Any]:
|
||||
if not from_hopyo.has(store.root(), same["키"]): # 793-3b 전에 올린 HP
|
||||
cannot = from_hopyo.keep(store.root(), same["키"], name, data)
|
||||
return {**same, "이어서": True, **({"읽기불가": cannot} if cannot else {})}
|
||||
try:
|
||||
parsed = hopyo_excel.read_book(name, data)
|
||||
try: # 책 한 번(857-1) · 단가산출만 있는 엑셀(일위대가 시트 없음)도 받음 = 호표 빈 목록
|
||||
book = workbook.read(name, data)
|
||||
parsed = hopyo_excel.read_book(name, data, book, blocks_only=True)
|
||||
except hopyo_excel.ExcelError as error:
|
||||
raise store.StoreError(400, str(error)) from error
|
||||
try:
|
||||
grid = hopyo_grid.read(name, data, parsed)
|
||||
grid = hopyo_grid.read(name, data, parsed, book)
|
||||
except Exception: # 격자는 보기용 덤 — 못 만들어도 올리기는 됨(보기 창 404)
|
||||
grid = None
|
||||
# 산근 시트(793-3b 가져온 식 열기) = HP 를 목록에 보이기 전에 보관(814-1) · 못 씀 사유 → 화면 토스트(797-1)
|
||||
keep = lambda key: from_hopyo.keep(store.root(), key, name, data) # noqa: E731
|
||||
keep = lambda key: from_hopyo.keep(store.root(), key, name, data, book) # noqa: E731
|
||||
return hopyo_store.save(store.root(), name, parsed, who, grid, mark, keep)
|
||||
|
||||
|
||||
|
||||
@@ -65,7 +65,10 @@ _TAG = re.compile(r"&([A-Z][A-Z0-9_]*?)(?::[A-Z])?&") # 율 기준 표지 「&P
|
||||
|
||||
|
||||
def is_stmate(names: Any) -> bool:
|
||||
return SHEET in names and CALC in names
|
||||
"""STmate 꼴 — 종류 가름 한 말(`M02_San_Workbook.kind_of` · 857-1)."""
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
return workbook.kind_of(names) == "STmate"
|
||||
|
||||
|
||||
def _cell(row: list[Any], col: int) -> Any:
|
||||
@@ -351,10 +354,11 @@ def _hopyo_line(row: list[Any], one: dict[str, Any], at: int) -> dict[str, Any]:
|
||||
return line
|
||||
|
||||
|
||||
def read(sheets: dict[str, list[list[Any]]]) -> dict[str, Any]:
|
||||
"""STmate 시트 → HP 꼴 `{꼴, 시트, 호표, 단산, 검산}`(값은 JSON 수)."""
|
||||
def read(sheets: dict[str, list[list[Any]]], loose: bool = False) -> dict[str, Any]:
|
||||
"""STmate 시트 → HP 꼴 `{꼴, 시트, 호표, 단산, 검산}`(값은 JSON 수) ·
|
||||
`loose` = 호표 없음도 받음(857-1)."""
|
||||
hopyos, raw = _hopyos(sheets.get(SHEET) or [])
|
||||
if not hopyos:
|
||||
if not hopyos and not loose:
|
||||
raise hopyo_excel.ExcelError(f"{SHEET} 시트에 호표(제N호표)가 없음")
|
||||
table = _lists(sheets)
|
||||
blocks = _blocks(sheets.get(CALC) or [], table)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""M02 층 권한 한 벌 — 나무 · 항목(`Router_Items`) · 양식 · 남의 층 목록(`Router_Layers`)이 함께 씀
|
||||
(PLAN 27-1c). 화면 쪽 짝 = `M02_MasterTemplete_Layer.ts` 의 `accessFor`.
|
||||
(PLAN 27-1c). 화면 쪽 짝 = `M02_MasterTemplete_Layer.ts` 의 `accessFor` · 거울 시험
|
||||
`test_858_1_access_mirror.py`. 서고 지우기 · 합치기 쓰기 판단도 `can_write` 한 벌(858-B).
|
||||
|
||||
「회사 C 를 맡음」(`manages` · 39-6) = SYSTEM_ADMIN · 또는 C 의 회사 관리자(ADMIN · 마스터).
|
||||
system 읽기 = 로그인 누구나 · 수정 = SYSTEM_ADMIN
|
||||
@@ -94,6 +95,16 @@ def require(
|
||||
return got
|
||||
|
||||
|
||||
def can_write(session: dict[str, Any] | None, here: tuple[str, str | None]) -> bool:
|
||||
"""층 `here` = (층, 주인) 에 쓸 수 있나 — 읽기 못 함 · 회사 없음 · 모양 틀림도 False."""
|
||||
if session is None:
|
||||
return False
|
||||
try:
|
||||
return grant(session, here[0], here[1]).write
|
||||
except HTTPException:
|
||||
return False
|
||||
|
||||
|
||||
def folder(got: Grant, create: bool = False) -> Path:
|
||||
"""회사 · 개인 층 폴더 — 남의 층은 그 층 폴더가 있어야 함 · `create` = 쓰기(부르는 쪽이 소속을
|
||||
본 뒤 뼈대를 만듦)."""
|
||||
|
||||
@@ -22,8 +22,6 @@ from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from common_util.common_util_json import atomic_write_json
|
||||
from M02_MasterTemplete import M02_Labor_Ref as refs
|
||||
from M02_MasterTemplete import M02_Layer_Access as access
|
||||
@@ -37,13 +35,7 @@ _ADD = re.compile(r"^add:#(\d+)(.*)$")
|
||||
_PATCH = ("덮개", "고름", "자재표시")
|
||||
|
||||
|
||||
def can_write(session: dict[str, Any] | None, at: refs.Here) -> bool:
|
||||
if session is None:
|
||||
return False
|
||||
try:
|
||||
return access.grant(session, at[0], at[1]).write
|
||||
except HTTPException:
|
||||
return False
|
||||
can_write = access.can_write # 쓰기 판단 한 벌(858-B) — 이름은 5-8 에서 걷음
|
||||
|
||||
|
||||
def _hits(doc: dict[str, Any], rids: dict[str, str]) -> list[tuple[str, str]]:
|
||||
|
||||
@@ -34,6 +34,7 @@ from pydantic import BaseModel
|
||||
from common_util.common_util_auth import verify_session
|
||||
from common_util.common_util_json import atomic_write_json
|
||||
from M02_MasterTemplete import M02_Labor_Ref as refs
|
||||
from M02_MasterTemplete import M02_Layer_Access as access
|
||||
from M02_MasterTemplete import M02_Library_Delete as deleting
|
||||
from M02_MasterTemplete import M02_Library_Flat as flat
|
||||
from M02_MasterTemplete import M02_Library_Same as same
|
||||
@@ -106,7 +107,7 @@ def _user_index() -> dict[str, list[tuple[Path, str, str]]]:
|
||||
|
||||
|
||||
def _can_write(session: Session, at: refs.Here) -> bool:
|
||||
return deleting.can_write(session, at)
|
||||
return access.can_write(session, at)
|
||||
|
||||
|
||||
def _retarget(doc: dict[str, Any], olds: set[str], new: refs.Ref) -> dict[str, Any]:
|
||||
|
||||
@@ -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.코드),
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* `#/m02-master-template?open=구조물조합|옵션|도면|일위대가조합|단가산출&root=master|company|personal&owner=…&company=…&pre=…`
|
||||
* (옛 `?layer=` 도 root 로 읽음 · `pre` = 일위대가 사전조합 층 · 134-3) · 고칠 권한(`accessFor` — 서버 `M02_Layer_Access` 와 짝 · 27-1c) ·
|
||||
* 회사 없음 안내 · 회사용 읽기만일 때 [개인용 복사] 막대.
|
||||
* 짝 거울 시험 = `resources/tester/test_858_1_access_mirror.py`(`accessFor` ↔ 서버 `can_write` · `grant` 409).
|
||||
* ========================================================================== */
|
||||
|
||||
import { ROUTES } from "@config/config_frontend";
|
||||
|
||||
@@ -142,9 +142,18 @@ async def others_write(session: Session, got: access.Grant, folder: Path) -> Non
|
||||
pending.append((session, got))
|
||||
|
||||
|
||||
def _root(session: Session, layer: str, owner: str | None = None, write: bool = False) -> Path:
|
||||
def _root(
|
||||
session: Session,
|
||||
layer: str,
|
||||
owner: str | None = None,
|
||||
write: bool = False,
|
||||
personal: str | None = None,
|
||||
) -> Path:
|
||||
"""층 폴더(권한까지 · `M02_Layer_Access`) — 자기 회사 · 개인 층은 없으면 빈 뼈대를 만듦 ·
|
||||
남의 층 쓰기(맡은 회사 · 39-6)는 `others_write`."""
|
||||
남의 층 쓰기(맡은 회사 · 39-6)는 `others_write` · `personal` = 개인 층만 받는 종류(내 기계
|
||||
등)의 그 밖 층 404 글(858 5-2 — 층 폴더 찾기 한 벌)."""
|
||||
if personal and layer != "personal":
|
||||
raise HTTPException(status_code=404, detail=personal)
|
||||
got = access.require(session, layer, owner, write=write)
|
||||
if layer == "system":
|
||||
return store.FOLDER
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -43,6 +43,8 @@ COSTS = ("노무비", "재료비", "경비")
|
||||
RATIOS = ("내용시간", "연간표준가동시간", "상각비율", "정비비율", "연간관리비율")
|
||||
COEFS = ("상각비계수", "정비비계수", "관리비계수")
|
||||
NUMS = ("가격", *RATIOS, *COEFS, "손료계수", "주연료", "전력")
|
||||
# 기계 칸 단위 — 짝(표 셋): `common_util_line_stack_unit.ts` MACHINE_UNIT · `build_기계_건설품셈.py` UNIT ·
|
||||
# 거울 시험 `resources/tester/test_854_3_machine_unit_mirror.py`(칸을 더하거나 글을 바꾸면 셋 모두)
|
||||
UNITS = {
|
||||
"가격": "천원", "내용시간": "시간", "연간표준가동시간": "시간", "상각비율": "", "정비비율": "",
|
||||
"연간관리비율": "", **{k: "10^-7/시간" for k in (*COEFS, "손료계수")}, "주연료": "ℓ/hr",
|
||||
@@ -408,14 +410,14 @@ def _seed(key: str) -> dict:
|
||||
|
||||
|
||||
def _user() -> str:
|
||||
"""개인 층(`storage/{회사}/{사용자}/templates`) 사용자 번호 — 그 밖 층 = 404."""
|
||||
from M02_MasterTemplete import M02_Template_Layers as layers
|
||||
"""개인 층(`storage/{회사}/{사용자}/templates`) 사용자 번호 — 그 밖 층 = 404 · 층 판정 =
|
||||
`Labor_Ref.where` 한 벌(858 5-2)."""
|
||||
from M02_MasterTemplete import M02_Labor_Ref as refs
|
||||
|
||||
here = store.root().resolve()
|
||||
user, company = here.parent.name, here.parent.parent.name
|
||||
if not (user.isdigit() and company.isdigit()) or here != layers.personal_dir(company, user):
|
||||
layer, owner = refs.where(store.root())
|
||||
if layer != "personal" or not owner:
|
||||
raise _bad("내 기계는 개인 층만", 404)
|
||||
return user
|
||||
return owner.split("/")[1]
|
||||
|
||||
|
||||
def not_m01(raw: Any, skip: str = "") -> None:
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
`TOUCH` = 사본 단가 줄을 새 값으로(`renew`) · 실패 = 만든 파일 지움 · 고친 줄 되돌림(번호표는 그대로).
|
||||
사본 줄 보기(`copy_row`) = 그 SK 사본에 박힌 기계 줄 · 지금 줄 · 새 값 여부.
|
||||
개인 층만(`mym._user` — 그 밖 404).
|
||||
화면 짝 = `common_util/common_util_line_stack_draft.ts`(칸 이름 · 표지 꼴 「EQP초안-N」).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from common_util.common_util_auth import verify_session
|
||||
@@ -32,9 +32,7 @@ class MachineBody(BaseModel):
|
||||
|
||||
|
||||
def _folder(session: Session, layer: str, owner: str | None, write: bool = False):
|
||||
if layer != "personal":
|
||||
raise HTTPException(status_code=404, detail="내 기계는 개인 층만")
|
||||
return _root(session, layer, owner, write=write)
|
||||
return _root(session, layer, owner, write=write, personal="내 기계는 개인 층만")
|
||||
|
||||
|
||||
@router.get(PATH)
|
||||
|
||||
@@ -9,9 +9,7 @@ EST(.xls · .xlsx) = 단가산출 시트 블록 글(`M02_Hopyo_ReadEst.read`) +
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
import warnings
|
||||
from typing import Any
|
||||
|
||||
STM_SHEETS = (
|
||||
@@ -37,37 +35,21 @@ _X7, _X5 = "_x0007_", "_x0005_"
|
||||
_HEAD = re.compile(r"BDCOD\|([A-Z]\d+).*?POSS\|(\d+).*?POSE\|(\d+)")
|
||||
|
||||
|
||||
def sheets(name: str, data: bytes) -> dict[str, list[list[Any]]]:
|
||||
"""책 바이트 → {시트: 줄} (두 꼴 시트만)."""
|
||||
def sheets(name: str, data: bytes, book: Any = None) -> dict[str, list[list[Any]]]:
|
||||
"""책 바이트 → {시트: 줄} (두 꼴 시트만) · `book` = 올림 길이 한 번 연 책
|
||||
(857-1 `M02_San_Workbook`)."""
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
book = book or workbook.read(name, data)
|
||||
keep = STM_SHEETS + EST_SHEETS
|
||||
if data[:4] == b"PK\x03\x04" or name.lower().endswith(".xlsx"):
|
||||
import openpyxl
|
||||
|
||||
with warnings.catch_warnings(): # 인쇄 영역 이름 경고
|
||||
warnings.simplefilter("ignore")
|
||||
wb = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
||||
try:
|
||||
return {
|
||||
ws.title.strip(): [list(r) for r in ws.iter_rows(values_only=True)]
|
||||
for ws in wb.worksheets
|
||||
if ws.title.strip() in keep
|
||||
}
|
||||
finally:
|
||||
wb.close()
|
||||
import xlrd
|
||||
|
||||
wb = xlrd.open_workbook(file_contents=data, logfile=io.StringIO())
|
||||
return {
|
||||
sh.name.strip(): [sh.row_values(r) for r in range(sh.nrows)]
|
||||
for sh in wb.sheets()
|
||||
if sh.name.strip() in keep
|
||||
}
|
||||
return {k: v for k, v in book.sheets.items() if k in keep}
|
||||
|
||||
|
||||
def kind_of(book: dict[str, list]) -> str | None:
|
||||
if "단가산출근거" in book:
|
||||
return "STmate"
|
||||
return "EST" if "단가산출" in book else None
|
||||
"""종류 가름 한 말(`M02_San_Workbook.kind_of`)."""
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
return workbook.kind_of(book)
|
||||
|
||||
|
||||
# ── STmate ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
자리 = 개인 층 `실무자료/재료고름/<파일 지문>.json` {파일, 고름 {종: {키, 이름, 규격, 단위}}} — [끝내기] 뒤에도 남음 ·
|
||||
같은 파일(지문)을 다시 올리면 그대로 보임.
|
||||
판(`census`) = 그 HP 블록마다 재료 줄 판정(`자원["재료찾기"]` · 827-2)을 종으로 묶음 —
|
||||
첫 판 열 때 한 번 셈 → 산근 저장본 칸 `재료판`(HP 지울 때 같이 지움).
|
||||
첫 판 열 때 한 번 셈 → 산근 저장본 칸 `재료판` + `재료판지문`(M01 지문 · 다르면 다시 셈 ·
|
||||
857-1) · HP 지울 때 같이 지움.
|
||||
만들기(`using` → `M02_Sangeun_FromHopyo._emit` 이 `apply`) = 고른 종 줄: 이음 = 고른 키 · `재료찾기.고름`
|
||||
(문서 셈 = 우리 값 · 엑셀 값 기억 없음 · `M02_Doc_Import._attach`) · 별도계상 줄 = `고름` 만(줄 이음 · 단가 0 그대로).
|
||||
문서 머리 `가져온.재료` = [{기호, 종, 원래, 판정, 방법, 키, 후보, 단서, 별도계상?, 고름?, 처음}](`entry` ·
|
||||
@@ -29,6 +30,7 @@ from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
|
||||
DIRNAME = "재료고름"
|
||||
CENSUS = "재료판"
|
||||
MARK = "재료판지문" # 판을 셀 때 M01 지문(857-1 · 별칭 · 자재가 바뀌면 다시 셈)
|
||||
KINDS = (
|
||||
"규격 없음 — 고르기",
|
||||
"단위 다름 — 고르기", # 840-3
|
||||
@@ -179,9 +181,24 @@ def entry(item: dict, sym: str, excel: Any) -> dict | None:
|
||||
|
||||
|
||||
# ── 판(그 파일 재료 종) ──────────────────────────────────────────────────
|
||||
def _mark() -> str:
|
||||
"""판 무효 지문 = M01 지문(첫 층 파일 내용 · 기계 폴더 — 별칭 · 자재 칸 포함 ·
|
||||
`San_Basis_Index.stamp`)."""
|
||||
from M02_MasterTemplete import M02_San_Basis_Index as basis
|
||||
|
||||
return basis.stamp()
|
||||
|
||||
|
||||
def census(folder: str | Path, key: str) -> list[dict]:
|
||||
"""HP 블록마다 재료 줄 판정 → 종 [{종, 이름, 규격, 단위, 판정, 방법, 키, 후보, 단서, 별도계상, 블록, 줄,
|
||||
호표?(828-1 일위 구성 줄 · 코드 숫자)}]."""
|
||||
호표?(828-1 일위 구성 줄 · 코드 숫자)}] — 셈 동안 M01 한 벌(857-1 · 파일 자국 한 번)."""
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
|
||||
with m01.cache.steady():
|
||||
return _census(folder, key)
|
||||
|
||||
|
||||
def _census(folder: str | Path, key: str) -> list[dict]:
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
@@ -191,12 +208,13 @@ def census(folder: str | Path, key: str) -> list[dict]:
|
||||
saved = json.loads(path.read_bytes())
|
||||
except (OSError, ValueError) as e:
|
||||
raise store.StoreError(409, fh.RELOAD) from e
|
||||
if isinstance(saved.get(CENSUS), list):
|
||||
mark = _mark()
|
||||
if isinstance(saved.get(CENSUS), list) and saved.get(MARK) == mark:
|
||||
return saved[CENSUS]
|
||||
native = saved.get("원파일")
|
||||
src = native if isinstance(native, dict) else fh._excel_of(path, saved) if saved.get("시트") else {} # fmt: skip
|
||||
groups: dict[str, dict] = {}
|
||||
# ponytail: 블록마다 셈 전부(기계 찾기 포함 · 70 블록 10~20 초) — 첫 판 한 번 · 느리면 재료 줄만 도는 길
|
||||
# ponytail: 블록마다 셈 전부(기계 찾기 포함) — 첫 판 한 번 · 더 느리면 재료 줄만 도는 길
|
||||
for no in sorted(fn.numbers(src)) if src else []:
|
||||
with using(None):
|
||||
try:
|
||||
@@ -235,7 +253,7 @@ def census(folder: str | Path, key: str) -> list[dict]:
|
||||
if (n := int(str(b["코드"])[1:])) not in hp:
|
||||
hp.append(n)
|
||||
out_ = sorted(groups.values(), key=lambda g: (KINDS.index(g["판정"]) if g["판정"] in KINDS else 9, -len(g["블록"]), g["이름"])) # fmt: skip
|
||||
atomic_write_json(path, {**saved, CENSUS: out_})
|
||||
atomic_write_json(path, {**saved, CENSUS: out_, MARK: mark})
|
||||
return out_
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""M02 불러오기 책 한 벌(PLAN 857-1) — 올린 엑셀을 한 번만 열어 시트 줄 · xls 서식 책 · 종류를
|
||||
같이 넘김.
|
||||
|
||||
읽는 시트 = 호표 쪽(`M02_Hopyo_Excel` 일위대가 · 총괄표 · 단가산출 · 목록 ·
|
||||
`M02_Hopyo_Stmate.SHEETS`) + 산근 쪽(`M02_San_Book.STM_SHEETS` · `EST_SHEETS`) 합집합 ·
|
||||
호표 읽기 · 격자 · 산근 보관이 같은 책을 받음.
|
||||
종류 가름 한 말 = `kind_of` — 「단가산출근거」 = STmate · 「단가산출」 = EST · 그 밖 None.
|
||||
xls = xlrd `formatting_info`(격자 서식 · 깨진 서식 표 = 값만) · xlsx = openpyxl read_only · 값만.
|
||||
엉터리 · 빈 파일 · 문서 보안(DRM) = `BookError`(올림 길 400).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
DRM = "문서 보안(DRM)으로 잠긴 파일 — 보안을 푼 사본으로 저장해 올림"
|
||||
_OLE = b"\xd0\xcf\x11\xe0"
|
||||
|
||||
|
||||
class BookError(ValueError):
|
||||
"""엉터리 파일 · 시트 없음 — 길이 400 으로 답함."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Book:
|
||||
"""한 번 연 책 — `sheets` = {시트: 줄 목록}(합집합 시트만) · `xls` = xlrd 책 | None."""
|
||||
|
||||
name: str
|
||||
sheets: dict[str, list[list[Any]]]
|
||||
xls: Any
|
||||
kind: str | None
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def wanted() -> frozenset[str]:
|
||||
"""읽을 시트 이름 합집합(호표 쪽 + 산근 쪽)."""
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hx
|
||||
from M02_MasterTemplete import M02_Hopyo_ReadEst as hr
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as hs
|
||||
from M02_MasterTemplete import M02_San_Book as sb
|
||||
|
||||
return frozenset(
|
||||
(hx.SHEET, hx.SUMMARY, hr.SHEET, *hx.LISTS, *hs.SHEETS, *sb.STM_SHEETS, *sb.EST_SHEETS)
|
||||
)
|
||||
|
||||
|
||||
def kind_of(names: Any) -> str | None:
|
||||
"""시트 이름들 → STmate · EST · None(종류 가름 한 곳)."""
|
||||
if "단가산출근거" in names:
|
||||
return "STmate"
|
||||
return "EST" if "단가산출" in names else None
|
||||
|
||||
|
||||
def read(name: str, data: bytes) -> Book:
|
||||
"""책 바이트 → `Book`(한 번 열기)."""
|
||||
if not data:
|
||||
raise BookError("빈 파일")
|
||||
if b"DRMONE" in data[:256] and data[:4] not in (b"PK\x03\x04", _OLE):
|
||||
raise BookError(DRM)
|
||||
keep = wanted()
|
||||
try:
|
||||
if data[:4] == b"PK\x03\x04" or name.lower().endswith(".xlsx"):
|
||||
import openpyxl
|
||||
|
||||
with warnings.catch_warnings(): # 인쇄 영역 이름 경고
|
||||
warnings.simplefilter("ignore")
|
||||
book = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
||||
try:
|
||||
sheets = {
|
||||
ws.title.strip(): [list(row) for row in ws.iter_rows(values_only=True)]
|
||||
for ws in book.worksheets
|
||||
if ws.title.strip() in keep
|
||||
}
|
||||
finally:
|
||||
book.close()
|
||||
return Book(name, sheets, None, kind_of(sheets))
|
||||
import xlrd
|
||||
|
||||
try:
|
||||
xls = xlrd.open_workbook(
|
||||
file_contents=data, formatting_info=True, logfile=io.StringIO()
|
||||
)
|
||||
except Exception: # 서식 표가 깨진 파일 — 값만(격자는 서식 없이)
|
||||
xls = xlrd.open_workbook(file_contents=data, logfile=io.StringIO())
|
||||
sheets = {
|
||||
sh.name.strip(): [sh.row_values(r) for r in range(sh.nrows)]
|
||||
for sh in xls.sheets()
|
||||
if sh.name.strip() in keep
|
||||
}
|
||||
return Book(name, sheets, xls, kind_of(sheets))
|
||||
except BookError:
|
||||
raise
|
||||
except Exception as error: # 라이브러리마다 다른 예외 — 깨진 파일 · 엑셀 아님
|
||||
raise BookError("엑셀 파일을 읽지 못함 — xls · xlsx 가 아니거나 깨진 파일") from error
|
||||
@@ -47,7 +47,7 @@ def unreadable(data: bytes) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def keep(folder: str | Path, key: str, name: str, data: bytes) -> str | None:
|
||||
def keep(folder: str | Path, key: str, name: str, data: bytes, opened: Any = None) -> str | None:
|
||||
"""올린 엑셀 → 산근 시트 둠(STmate · EST 꼴만 · 못 읽으면 안 둠 — 올리기는 됨).
|
||||
돌려줌 = 못 읽은 사유(빈 파일 · DRM 암호 · 형식 오류) · 둠 · 산근 꼴 아님 = None."""
|
||||
from M02_MasterTemplete import M02_San_Book as book
|
||||
@@ -55,7 +55,7 @@ def keep(folder: str | Path, key: str, name: str, data: bytes) -> str | None:
|
||||
if why := unreadable(data):
|
||||
return why
|
||||
try:
|
||||
sheets = book.sheets(name, data)
|
||||
sheets = book.sheets(name, data, opened) # 올림 길이 한 번 연 책(857-1)
|
||||
except Exception as e: # noqa: BLE001 — 산근은 덤(가져온 식 열기만 막힘) · 사유는 돌려줌
|
||||
return f"엑셀 형식 오류 — {type(e).__name__}: {str(e)[:80]}"
|
||||
if not book.kind_of(sheets):
|
||||
|
||||
@@ -343,7 +343,54 @@ def _json(value: Any) -> Any:
|
||||
return labor._json(value)
|
||||
|
||||
|
||||
class _One:
|
||||
"""M01 색인 위에 가져온 줄 하나 — `logic(키)` 만 가로챔(문서 변환 색인 · 그 밖 그대로)."""
|
||||
|
||||
def __init__(self, whole: Any, key: str, row: dict) -> None:
|
||||
self._whole, self._key, self._row = whole, key, row
|
||||
|
||||
def logic(self, ref: str) -> dict:
|
||||
return self._row if ref == self._key else self._whole.logic(ref)
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._whole, name)
|
||||
|
||||
|
||||
def _doc_of(bare: dict, whole: Any) -> tuple[dict, list[str], dict]:
|
||||
"""검산 문서(855 2-C3) — 가져온 줄(엑셀 단가 · 고침 없음)을 줄 차례 그대로 문서로(다듬기 없음 ·
|
||||
금액 줄 k = 줄 정체 k) · 안쪽 산근 줄 = 형제 SK 연결(문서 셈 · 부르는 쪽 단가기준) →
|
||||
(문서, 줄 정체, {중간 이름: 기호})."""
|
||||
from M02_MasterTemplete import M02_Doc_Copy as dc
|
||||
|
||||
key = str(bare.get("키") or "SK-000000")
|
||||
row = {**row_of(bare), "키": key}
|
||||
row["호표"] = [dict(x) for x in row["호표"]]
|
||||
for item in row["호표"]: # 형제 SK 줄 = 아래에서 연결로 갈음 — 변환 자리값
|
||||
if item.get("참조") and item.get("값묶음") is None:
|
||||
item["값묶음"] = dict.fromkeys(COSTS, Decimal(0))
|
||||
master = _One(whole, key, row)
|
||||
doc, _ = dc.cv.convert(master, row, dc.given_of(master, key, bare.get("입력값")))
|
||||
by = {dc.md.var_id(v): v for v in doc.get("변수") or []}
|
||||
for item, line in zip(row["호표"], doc.get("금액") or []):
|
||||
var = by.get(str(line.get("단가") or "").removesuffix(".계"))
|
||||
if not item.get("참조") or var is None:
|
||||
continue
|
||||
ref = item["참조"]
|
||||
link = {
|
||||
"갈래": "단가산출",
|
||||
"키": ref["키"],
|
||||
"참조": {"층": ref["층"], "주인": ref.get("주인")},
|
||||
}
|
||||
if item.get("참조비목") in COSTS: # 안쪽 산근의 그 비목만(`Doc_Import._attach` 와 같음)
|
||||
link["칸"] = item["참조비목"]
|
||||
line["단가"], line["비목"] = dc.md.var_id(var), item["참조비목"]
|
||||
var["연결"] = link
|
||||
mids = {str(v.get("열쇠")): dc.md.var_id(v) for v in doc.get("변수") or []}
|
||||
return doc, sd.line_ids(row), mids
|
||||
|
||||
|
||||
def _run(doc: dict, whole: Any) -> dict:
|
||||
"""SK 셈(`to_price` 전 · 후 1 단위) — `Sangeun_Calc.run` 한 길(2-C1 몫 · 검산은 `_doc_of`)."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
|
||||
return calc.run(sd.clean(doc, None, whole), whole)
|
||||
@@ -366,8 +413,13 @@ def _same(mine: Any, excel: Any) -> bool:
|
||||
|
||||
|
||||
def check(doc: dict, whole: Any = None) -> dict[str, Any]:
|
||||
"""검산 — 가져온 줄(엑셀 단가 · 고침 없음)을 엔진으로 다시 셈 → 엑셀 금액 · 줄마다 맞댐 ·
|
||||
못 셈 = {같음 False, 까닭}."""
|
||||
"""검산 — 가져온 줄(엑셀 단가 · 고침 없음)을 문서 계산기로 다시 셈(855 2-C3 · 옛 엔진 안 돎) →
|
||||
엑셀 금액 · 글줄마다 맞댐(글줄 `자리` = 줄 정체 cid ↔ 검산 문서 금액 줄 같은 차례 · `mid:이름` =
|
||||
중간 변수 값 · `단계:이름` = 단계 계) · 못 셈 = {같음 False, 까닭}."""
|
||||
from M02_MasterTemplete import M02_Doc_Copy as dc
|
||||
from M02_MasterTemplete import M02_Doc_Import as dim
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
|
||||
whole = whole or _whole()
|
||||
meta = doc[KEY]
|
||||
bare = {k: doc.get(k) for k in ("키", "이름", "단위", "입력값", "환산")}
|
||||
@@ -375,17 +427,45 @@ def check(doc: dict, whole: Any = None) -> dict[str, Any]:
|
||||
src = meta.get("원본") or {}
|
||||
excel = src.get("엑셀금액") or {}
|
||||
try:
|
||||
got = _run(bare, whole)
|
||||
bare = sd.clean(bare, None, whole)
|
||||
times = calc.ratio_of(bare, row_of(bare), whole) # 1 단위 = 문서 셈 ÷ 배(옛 `1단위`)
|
||||
except sd.DocError as e:
|
||||
return {"같음": False, "까닭": str(e), "셈": None, "엑셀": excel, "줄": []}
|
||||
mine = _money(got)
|
||||
now = {x.get("cid"): x.get("금액") for x in got.get("줄") or []} | _inner(bare, whole)
|
||||
try:
|
||||
mine_doc, ids, mids = _doc_of(bare, whole)
|
||||
got = dim.run(mine_doc, bare, whole)
|
||||
except Exception as e: # noqa: BLE001 — 변환 · 셈 틀림 = 맞댈 값 없음
|
||||
got, ids, mids, mine_doc = {"셈됨": False, "까닭": str(e)}, [], {}, None
|
||||
money = dc.money(got) if got.get("셈됨") else None
|
||||
if (
|
||||
money is None
|
||||
and mine_doc is not None
|
||||
and not (mine_doc.get("금액") or mine_doc.get("결과"))
|
||||
):
|
||||
money = dict.fromkeys(dc.COSTS, Decimal(0)) # 빈 산근 = 엑셀 0 원(줄 없음 합)
|
||||
mine = {k: Decimal(str(v)) / times for k, v in money.items()} if money else None
|
||||
now = {cid: x.get("금액") for cid, x in zip(ids, got.get("줄") or [])}
|
||||
values = got.get("값") or {}
|
||||
now |= {f"mid:{k}": values[v] for k, v in mids.items() if isinstance(values.get(v), Decimal)}
|
||||
steps = got.get("단계") or {}
|
||||
steps = (
|
||||
steps
|
||||
if isinstance(steps, dict)
|
||||
else {x.get("이름"): x for x in steps if isinstance(x, dict)}
|
||||
)
|
||||
now |= {f"단계:{k}": (v or {}).get("계") for k, v in steps.items()}
|
||||
group = _groups(src.get("글줄"))
|
||||
lines = [x for x in (_compare(one, now, group=group) for one in src.get("글줄") or []) if x]
|
||||
ok = bool(mine) and excel != {} and _all_same(mine, excel)
|
||||
rate = (src.get("계약") or {}).get("낙찰률")
|
||||
ok = ok or bool(mine and rate and excel and _all_same(_contract(mine, rate), excel))
|
||||
why = None if ok else (got.get("까닭") or ("엑셀 금액 없음" if not excel else "금액 다름"))
|
||||
why = (
|
||||
None
|
||||
if ok
|
||||
else (
|
||||
(dc.why(got) if not money else "") or ("엑셀 금액 없음" if not excel else "금액 다름")
|
||||
)
|
||||
)
|
||||
ok = ok and all(x["같음"] for x in lines)
|
||||
return _json({"같음": ok, "까닭": why, "셈": mine, "엑셀": excel, "줄": lines})
|
||||
|
||||
@@ -403,28 +483,6 @@ def _contract(mine: dict, rate: float) -> dict:
|
||||
return out | {"계": sum(out.values())}
|
||||
|
||||
|
||||
def _inner(doc: dict, whole: Any) -> dict:
|
||||
"""엔진 날 셈의 중간 `mid:이름` · 단계 `단계:이름` 계(검산 맞댈 값) · 못 셈 = 빈."""
|
||||
from M02_MasterTemplete import M02_Sangeun_Calc as calc
|
||||
|
||||
m01, key = calc.labor.m01, str(doc.get("키") or "SK-000000")
|
||||
row = {**row_of(doc), "키": key}
|
||||
if any(x.get("참조") for x in row["호표"]): # 안쪽 산근 값 채움(797-1 · 셈 길과 같음)
|
||||
from M02_MasterTemplete.M02_Labor_Expand import Expand
|
||||
|
||||
row["호표"] = [dict(x) for x in row["호표"]]
|
||||
calc._bundles(row, whole, Expand(whole), ())
|
||||
over = calc._Over(whole, key, row)
|
||||
try:
|
||||
auto = {k: v for k, v in m01.mau.values(over, over.logic(key)).items() if v is not None}
|
||||
given = {**auto, **m01._dec(doc.get("입력값") or {})}
|
||||
got = calc.labor.mcut.engine(over, key, m01.cm.mf.run(over, key, given))
|
||||
except Exception: # noqa: BLE001 — 엔진 FormulaError · 셈 틀림 = 맞댈 값 없음
|
||||
return {}
|
||||
out = {f"mid:{k}": v for k, v in (got.get("중간") or {}).items()}
|
||||
return out | {f"단계:{x.get('이름')}": x.get("계") for x in got.get("단계") or []}
|
||||
|
||||
|
||||
def _groups(texts: Any) -> dict[str, Decimal]:
|
||||
"""첫 자리가 같은 값 든 글줄 여럿 → 첫 자리별 값 합(814-1 기계 노 · 재 · 경 세 글줄 = 묶은
|
||||
한 줄 · 노 줄만 딸린 기계까지 자리들)."""
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -137,10 +136,13 @@ def template_path(layer_dir: str | Path, kind: str, name: str) -> Path:
|
||||
|
||||
|
||||
def version_of(path: str | Path) -> str | None:
|
||||
"""파일 판 — 몸은 `Store.version_of` 한 벌(858 5-3 · Store 가 이 파일을 불러 안에서 부름)."""
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
|
||||
path = Path(path)
|
||||
if not path.is_file():
|
||||
return None
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()[:16]
|
||||
return store.version_of(path.read_bytes())
|
||||
|
||||
|
||||
def _modified(path: Path) -> str:
|
||||
@@ -176,11 +178,13 @@ def read_template(layer_dir: str | Path, kind: str, name: str) -> dict[str, Any]
|
||||
path = template_path(layer_dir, kind, name)
|
||||
if not path.is_file():
|
||||
return None
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
|
||||
raw = path.read_bytes()
|
||||
return {
|
||||
"종류": kind,
|
||||
"이름": name,
|
||||
"판": hashlib.sha256(raw).hexdigest()[:16],
|
||||
"판": store.version_of(raw),
|
||||
"문서": json.loads(raw.decode("utf-8")),
|
||||
}
|
||||
|
||||
@@ -257,16 +261,20 @@ def write_template(
|
||||
version: str | None = None,
|
||||
check_version: bool = False,
|
||||
) -> str:
|
||||
"""원자 쓰기 → 새 판. `check_version` 이면 `version` 이 지금 판과 같아야 함(새 파일은 None)."""
|
||||
"""원자 쓰기 → 새 판. `check_version` 이면 `version` 이 지금 판과 같아야 함(새 파일은 None) ·
|
||||
판 대조 · 쓰기 = `Store._LOCK` 안(858 5-3 — 대조와 쓰기 사이가 열려 있던 것)."""
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
|
||||
if not isinstance(document, dict):
|
||||
raise ValueError("양식 문서는 JSON 객체여야 합니다.")
|
||||
path = template_path(layer_dir, kind, name)
|
||||
if check_version:
|
||||
current = version_of(path)
|
||||
if current != (version or None):
|
||||
raise StaleTemplate(current)
|
||||
atomic_write_json(path, document)
|
||||
return version_of(path) or ""
|
||||
with store._LOCK:
|
||||
if check_version:
|
||||
current = version_of(path)
|
||||
if current != (version or None):
|
||||
raise StaleTemplate(current)
|
||||
atomic_write_json(path, document)
|
||||
return version_of(path) or ""
|
||||
|
||||
|
||||
def delete_template(
|
||||
|
||||
@@ -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.처음수량;
|
||||
}
|
||||
|
||||
/* ── 순수 셈 끝 ── */
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"갈래": {
|
||||
"precombo.고치기": "600ec92b1b7fabe4",
|
||||
"precombo.나무": "d08cff9db9575c99",
|
||||
"precombo.되돌림": "ce11ade1bd96129c",
|
||||
"precombo.만들기": "e53ad45acbf386bc",
|
||||
"precombo.목록": "20bd9f3f0803cb91",
|
||||
"precombo.복사": "ea957146cf361b70",
|
||||
"precombo.붙여넣기": "236bf55301ef9045",
|
||||
"precombo.쓰는곳": "8f68c3d2501f7a53",
|
||||
"precombo.읽기": "c822ceb7cedfc59d",
|
||||
"precombo.중복": "6f783eab99eb8095",
|
||||
"precombo.지우기": "a356d2496ae34f51",
|
||||
"precombo.합치기": "2010fbd1ab774d86",
|
||||
"sangeun.고치기": "e47e5593c71f5a56",
|
||||
"sangeun.나무": "991823a8c1fe1913",
|
||||
"sangeun.되돌림": "6ca25af01d1d38ab",
|
||||
"sangeun.만들기": "2155d280fd6d97ae",
|
||||
"sangeun.목록": "a75cf0387e16ed84",
|
||||
"sangeun.복사": "40edbd4d0644186f",
|
||||
"sangeun.붙여넣기": "57cfb7bb522a80d3",
|
||||
"sangeun.쓰는곳": "2c9ec1824709481f",
|
||||
"sangeun.읽기": "6f5b02af37f2b55b",
|
||||
"sangeun.중복": "e4d3ff3235a8d0b9",
|
||||
"sangeun.지우기": "db8b1e8ad9bef9eb",
|
||||
"sangeun.합치기": "5a6d9e24d05ae1af",
|
||||
"공유.거절": "9a38b16329ed7c68",
|
||||
"공유.목록": "eccff54e8114d69c",
|
||||
"공유.봄": "a3bdb64cc1be2935",
|
||||
"공유.승인": "ec5183ff8c81f5c8",
|
||||
"공유.요청": "762ba10d5af57643",
|
||||
"권한.같은회사남": "2d3d50a90583497d",
|
||||
"권한.남의회사관리": "a1213c908c70528f",
|
||||
"권한.시스템": "ee1c88a183b2740f",
|
||||
"권한.일반": "9a05899de41301f2",
|
||||
"권한.회사관리": "d6da88af7fe80323",
|
||||
"내기계.고치기": "3f00365dbfb77cee",
|
||||
"내기계.만들기": "20f5562f02c276f8",
|
||||
"내기계.목록": "064102da4c9740d6",
|
||||
"내기계.쓰는곳": "7bd823f7780c6f86",
|
||||
"내기계.읽기": "0e5467fc806d83ff",
|
||||
"내기계.지우기": "6db3b2b387f87ce7",
|
||||
"내기계.찾기": "feca2de012a206ee",
|
||||
"내재료.고치기": "60c0d3337d7dde06",
|
||||
"내재료.만들기": "9fec4ce2a9bbfb82",
|
||||
"내재료.목록": "9c5929426719e9ae",
|
||||
"내재료.지우기": "9c194d1b5367920e",
|
||||
"항목.나무": "abb5815352e81102",
|
||||
"항목.목록": "f7ff1a6372bf308f",
|
||||
"항목.복사": "b37ed4bfc45e5032",
|
||||
"항목.붙여넣기": "2324914f36f4b24e",
|
||||
"항목.지우기": "1fd673b8f7e3bab1"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
/* 856-0 헬퍼 — 단가산출 화면 · 일위대가 줄 누름 · 머리 띠 · M01 로직 상세(가짜 DOM · 진짜 코드)
|
||||
* 진짜 = M02 단가산출 화면(`Sangeun_Detail` 과 그 이웃) · 일위대가 표(`Labor_Table`) · 줄 모달 · M01 상세 그릇
|
||||
* 가짜 = 부품 상자(표지 붙은 빈 상자) · 줄 쌓기 화면(그린 키만 적음) · 서버 부름(길 · 몸을 적고 견본 답) */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const ROOT = path.resolve(__dirname, "..", "..");
|
||||
const ts = require(path.join(ROOT, "config", "node_modules", "typescript"));
|
||||
|
||||
const camel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
||||
class Fake {
|
||||
constructor(tag) {
|
||||
this.tagName = String(tag).toUpperCase();
|
||||
this.children = [];
|
||||
this.parentElement = null;
|
||||
this.dataset = {};
|
||||
this.attrs = {};
|
||||
this.style = { setProperty() {} };
|
||||
this.hidden = false;
|
||||
this.className = "";
|
||||
this.textContent = "";
|
||||
this.value = "";
|
||||
this.disabled = false;
|
||||
this.classList = { add() {}, remove() {}, toggle() {}, contains: () => false };
|
||||
}
|
||||
append(...xs) {
|
||||
for (const x of xs)
|
||||
if (x instanceof Fake) {
|
||||
x.parentElement = this;
|
||||
this.children.push(x);
|
||||
}
|
||||
}
|
||||
prepend(...xs) {
|
||||
this.append(...xs);
|
||||
}
|
||||
replaceChildren(...xs) {
|
||||
this.children = [];
|
||||
this.append(...xs);
|
||||
}
|
||||
remove() {}
|
||||
get firstChild() {
|
||||
return this.children[0] ?? null;
|
||||
}
|
||||
addEventListener() {}
|
||||
removeEventListener() {}
|
||||
setAttribute(k, v) {
|
||||
this.attrs[k] = v;
|
||||
if (k.startsWith("data-")) this.dataset[camel(k.slice(5))] = v;
|
||||
}
|
||||
removeAttribute() {}
|
||||
contains() {
|
||||
return false;
|
||||
}
|
||||
querySelector() {
|
||||
return null;
|
||||
}
|
||||
focus() {}
|
||||
}
|
||||
globalThis.window = globalThis;
|
||||
globalThis.addEventListener = () => {};
|
||||
globalThis.removeEventListener = () => {};
|
||||
globalThis.getComputedStyle = () => ({ overflowY: "visible" });
|
||||
globalThis.requestAnimationFrame = (f) => setTimeout(f, 0);
|
||||
globalThis.HTMLElement = Fake;
|
||||
globalThis.HTMLInputElement = class extends Fake {};
|
||||
globalThis.HTMLTextAreaElement = class extends Fake {};
|
||||
globalThis.document = {
|
||||
createElement: (t) => new Fake(t),
|
||||
body: new Fake("body"),
|
||||
activeElement: null,
|
||||
};
|
||||
globalThis.sessionStorage = { getItem: () => null, setItem() {}, removeItem() {} };
|
||||
|
||||
/** 표지 붙은 빈 상자 */
|
||||
const box = (tag, mark = {}, text = "") => {
|
||||
const n = new Fake(tag);
|
||||
for (const [k, v] of Object.entries(mark)) n.setAttribute(k, v);
|
||||
n.textContent = text;
|
||||
return n;
|
||||
};
|
||||
const el = (tag, o = {}) => {
|
||||
const n = box(tag, o.attrs ?? {}, o.text ?? "");
|
||||
n.className = o.className ?? "";
|
||||
n.append(...(o.children ?? []));
|
||||
return n;
|
||||
};
|
||||
const button = (o = {}) => box("button", { "data-button": o.label ?? "" });
|
||||
const input = (o = {}) => {
|
||||
const i = box("input");
|
||||
i.value = o.value ?? "";
|
||||
return { root: box("label", { "data-input": o.label ?? "" }, ""), input: i, setError() {} };
|
||||
};
|
||||
const modals = []; // 열린 모달 — 제목 · 몸
|
||||
const ui = {
|
||||
ui_template_elements: {
|
||||
el,
|
||||
createButton: button,
|
||||
createInputField: input,
|
||||
showToast() {},
|
||||
showConfirmDialog: async () => true,
|
||||
},
|
||||
ui_template_button: { createButton: button },
|
||||
ui_template_input: { createInputField: input },
|
||||
ui_template_banner: { createBanner: (o) => box("div", { "data-banner": o.tone }, o.text) },
|
||||
ui_template_badge: { createBadge: (text, tone) => box("span", { "data-badge": tone }, text) },
|
||||
ui_template_text: { createText: (text) => box("span", {}, text) },
|
||||
ui_template_checkbox: { createCheckbox: () => ({ root: box("label") }) },
|
||||
ui_template_card: { createCard: () => box("div") },
|
||||
ui_template_locale: { t: (k) => k, currentLanguageIndex: 0 },
|
||||
ui_template_modal: {
|
||||
openModal: (o) => {
|
||||
const body = box("div", { "data-modal": o.title });
|
||||
const head = box("div");
|
||||
const close = () => {};
|
||||
o.mount?.(body, close, head);
|
||||
modals.push({ title: o.title, body, head, actions: o.actions ?? [] });
|
||||
return { close };
|
||||
},
|
||||
askConfirm: async () => true,
|
||||
askText: async () => null,
|
||||
showConfirmDialog: async () => true,
|
||||
},
|
||||
ui_template_side_panels: {
|
||||
createSidePanels: () => ({ current: () => null, root: box("div"), wrap: (m) => m }),
|
||||
},
|
||||
ui_template_hopyo_grid: {
|
||||
hopyoGrid: (blocks) => ({
|
||||
at: new Map(blocks[0].lines.map((_, i) => [i, [0, i]])),
|
||||
columns: [],
|
||||
rows: [],
|
||||
}),
|
||||
createHopyoGrid: (_blocks, o) => ((grid.onRowClick = o.onRowClick), { root: box("table") }),
|
||||
hopyoCellClass: () => "",
|
||||
},
|
||||
};
|
||||
const grid = { onRowClick: null };
|
||||
|
||||
// 줄 쌓기 화면 = 그린 키 · 저장 전 문서만 적음
|
||||
const stacks = [];
|
||||
const screen = {
|
||||
createStackScreen: (opt) => {
|
||||
const s = { root: box("div", { "data-stack": "" }), draws: [], opt };
|
||||
stacks.push(s);
|
||||
return {
|
||||
root: s.root,
|
||||
draw: (k) => s.draws.push({ key: k, memory: !k && !!opt.memory?.() }),
|
||||
dirty: () => false,
|
||||
save: async () => true,
|
||||
discard: async () => {},
|
||||
canLeave: async () => true,
|
||||
destroy() {},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
// 서버 부름 — 길 · 몸을 적고 견본 답
|
||||
const calls = [];
|
||||
let skAnswer = () => ({});
|
||||
const api = {
|
||||
call: async (p, init) => {
|
||||
calls.push({ path: p, body: init?.body ? JSON.parse(init.body) : null });
|
||||
if (p.includes("/sangeun/calc")) return skAnswer();
|
||||
if (p.includes("/labor/")) return { 줄: [], 자재: [], 알약: [] };
|
||||
return {};
|
||||
},
|
||||
readTemplate: async (_l, _k, key) => ({ 문서: { 키: key, 이름: "견본", 단위: "㎡" }, 판: "1" }),
|
||||
saveTemplate: async () => ({}),
|
||||
getActiveLayer: () => "system",
|
||||
getActiveOwner: () => null,
|
||||
};
|
||||
const logicApi = {
|
||||
fetchLogic: async (k) => ({
|
||||
logic: { 키: k, 이름: "기초", 결과단위: "원/㎡", 입력: [] },
|
||||
prices: {},
|
||||
file: "",
|
||||
reasons: [],
|
||||
}),
|
||||
fetchAuto: async () => ({}),
|
||||
setLogicApiPaths() {},
|
||||
ApiError: class extends Error {},
|
||||
};
|
||||
|
||||
const stubs = {
|
||||
...ui,
|
||||
line_stack_screen: screen,
|
||||
M02_MasterTemplete_Api_Fetch: api,
|
||||
M01_MasterData_UI_Logic_Api: logicApi,
|
||||
M02_MasterTemplete_Sangeun_Side: {
|
||||
createSangeunSide: () => ({ wrap: (m) => m, set() {} }),
|
||||
tabOf: () => ({}),
|
||||
},
|
||||
M01_MasterData_UI_LogicLab_Ho: { buildHo: () => [box("div", { "data-ho": "" })] },
|
||||
M02_MasterTemplete_Sangeun_Unit: { buildUnitSwap: () => null, baseUnitOf: () => "" },
|
||||
M02_MasterTemplete_Labor_LogicMats: { logicMatRows: () => [] },
|
||||
M02_Labor_Values_Model: {
|
||||
valueLine: () => ({ text: "", empty: 0 }),
|
||||
keepKnown: (_a, b) => ({ kept: b }),
|
||||
},
|
||||
M02_MasterTemplete_Labor_Grid: {
|
||||
laborBlock: (cur) => ({ lines: cur.담은로직.map(() => ({ note: "", amounts: { sum: 1 } })) }),
|
||||
},
|
||||
M02_DF_UnitPick: { createUnitPick: () => box("div"), NO_UNIT: "-" },
|
||||
M02_MasterTemplete_Labor_Unlinked: { unlinkedBar: () => null },
|
||||
M02_MasterTemplete_Labor_Text: { tc: (k) => k },
|
||||
M02_MasterTemplete_Labor_LibMeta: { libMeta: () => [] },
|
||||
M02_MasterTemplete_Labor_National: { nationalRows: () => [] },
|
||||
};
|
||||
const real = new Set([
|
||||
"M02_MasterTemplete_Sangeun_Detail",
|
||||
"M02_MasterTemplete_Sangeun_Tabs",
|
||||
"M02_MasterTemplete_Sangeun_Cover",
|
||||
"M02_MasterTemplete_Sangeun_BaseHead",
|
||||
"M02_Sangeun_Cover_Model",
|
||||
"M02_Sangeun_Undo",
|
||||
"M02_Born_Tag",
|
||||
"M01_MasterData_UI_LogicLab_Detail",
|
||||
"M02_MasterTemplete_Labor_Table",
|
||||
"M02_MasterTemplete_Labor_SkEdit",
|
||||
"M02_MasterTemplete_Labor_RowModal",
|
||||
"M02_MasterTemplete_Labor_RowSk",
|
||||
"M02_MasterTemplete_Labor_Api",
|
||||
"M02_MasterTemplete_Labor_Calc",
|
||||
]);
|
||||
|
||||
const empty = () =>
|
||||
new Proxy(function () {}, {
|
||||
get: (_, k) => (k === "then" ? undefined : empty()),
|
||||
apply: () => undefined,
|
||||
});
|
||||
const cache = new Map();
|
||||
function load(at) {
|
||||
if (cache.has(at)) return cache.get(at);
|
||||
const js = ts.transpileModule(fs.readFileSync(at, "utf8"), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
const mod = { exports: {} };
|
||||
cache.set(at, mod.exports);
|
||||
const need = (p) => {
|
||||
if (p.endsWith(".css")) return {};
|
||||
const name = path.basename(p);
|
||||
if (stubs[name]) return stubs[name];
|
||||
if (p.startsWith("@config/")) return { API_BASE_URL: "" };
|
||||
if (!p.startsWith(".")) return empty();
|
||||
const r = `${path.resolve(path.dirname(at), p)}.ts`;
|
||||
return real.has(path.basename(r, ".ts")) && fs.existsSync(r) ? load(r) : empty();
|
||||
};
|
||||
new Function("exports", "module", "require", js)(mod.exports, mod, need);
|
||||
return mod.exports;
|
||||
}
|
||||
const M = (rel) => load(path.join(ROOT, rel));
|
||||
const tick = () => new Promise((r) => setTimeout(r, 0));
|
||||
const settle = async () => {
|
||||
for (let i = 0; i < 20; i++) await tick();
|
||||
};
|
||||
const walk = (n, fn) => {
|
||||
fn(n);
|
||||
for (const c of n.children) walk(c, fn);
|
||||
};
|
||||
const all = (root, pred) => {
|
||||
const out = [];
|
||||
walk(root, (n) => pred(n) && out.push(n));
|
||||
return out;
|
||||
};
|
||||
/** 숨은 조상까지 보고 보이는가 */
|
||||
const shown = (n) => {
|
||||
for (let x = n; x; x = x.parentElement) if (x.hidden) return false;
|
||||
return true;
|
||||
};
|
||||
const skCalls = () => calls.filter((c) => c.path.includes("/sangeun/calc"));
|
||||
const plainAns = (o = {}) => ({
|
||||
기준: null,
|
||||
줄: [
|
||||
{ 이름: "보통인부", cid: "labor:LB1#0", 수량: 1, 단가: 100, 금액: 100, 비목: { 노무비: 100 } },
|
||||
],
|
||||
정체: ["labor:LB1#0"],
|
||||
짝잃음: [],
|
||||
빠진줄: [],
|
||||
바탕판: "v1",
|
||||
...o,
|
||||
});
|
||||
|
||||
/** 단가산출 화면 한 벌 열기 — 부름 수 · 숨은 몸 · 줄 쌓기 그림 · 띠 */
|
||||
async function openSk(doc, opt = {}) {
|
||||
calls.length = 0;
|
||||
stacks.length = 0;
|
||||
const { mountSangeunDetail } = M("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts");
|
||||
const host = box("div");
|
||||
const h = mountSangeunDetail(host, doc, {
|
||||
layer: "system",
|
||||
owner: null,
|
||||
readOnly: false,
|
||||
onChanged() {},
|
||||
...opt,
|
||||
});
|
||||
await settle();
|
||||
const s = stacks[stacks.length - 1];
|
||||
const r = {
|
||||
calc: skCalls().length,
|
||||
body: all(host, (n) => "skCover" in n.dataset || "ho" in n.dataset).length, // 몸 DOM(덮개 그릇 · 호표)
|
||||
bodyShown: all(host, (n) => "skCover" in n.dataset && shown(n)).length,
|
||||
stack: s ? { shown: shown(s.root), draws: s.draws } : null,
|
||||
banners: all(host, (n) => "banner" in n.dataset).map((n) => n.dataset.banner),
|
||||
badges: all(host, (n) => "badge" in n.dataset).map((n) => [n.dataset.badge, n.textContent]),
|
||||
};
|
||||
h.destroy();
|
||||
return r;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const out = {};
|
||||
skAnswer = () => plainAns();
|
||||
// ① 단가산출 화면(페이지) — 바탕 있음 · 없음
|
||||
out.page_base = await openSk(
|
||||
{ 키: "SK-000001", 이름: "견본", 단위: "㎡", 바탕: { 로직: "GC001109" } },
|
||||
{ mode: "page" },
|
||||
);
|
||||
out.page_nobase = await openSk({ 키: "SK-000002", 이름: "견본", 단위: "㎡" }, { mode: "page" });
|
||||
// 불러오기 미리 보기(저장 전 가져온 식)
|
||||
out.memory = await openSk({ 이름: "가져온", 단위: "식", 가져온: { 파일: "x" } }, { mode: "memory" });
|
||||
|
||||
// ③ 머리 띠 넷(견본 답) — 까닭 · M01 개정 · 빠진 줄 · 짝 잃음 + 머리 배지
|
||||
skAnswer = () =>
|
||||
plainAns({
|
||||
까닭: "못 셈",
|
||||
빠진줄: [{ cid: "labor:LB2#1", 이름: "특별인부", 까닭: "입력 없음" }],
|
||||
짝잃음: [{ cid: "labor:LB9#0", 까닭: "줄 없음" }],
|
||||
바탕판: "v2",
|
||||
머리: "계",
|
||||
});
|
||||
out.bands = await openSk(
|
||||
{ 키: "SK-000003", 이름: "띠", 단위: "㎡", 바탕: { 로직: "GC001109" }, 바탕판: "v1" },
|
||||
{ mode: "page" },
|
||||
);
|
||||
skAnswer = () => {
|
||||
throw new Error("서버 못 닿음");
|
||||
};
|
||||
out.bands_fail = await openSk({ 키: "SK-000004", 이름: "띠", 단위: "㎡" }, { mode: "page" });
|
||||
skAnswer = () => plainAns();
|
||||
|
||||
// ② 일위대가 표 줄 누름 — SK 참조 줄 · M01 로직 줄 · 셈 주입(프로젝트 사본) SK 줄
|
||||
const { mountLaborTable } = M("M02_MasterTemplete/M02_MasterTemplete_Labor_Table.ts");
|
||||
const rows = [
|
||||
{
|
||||
참조: { 층: "system", 주인: null, 키: "SK-000010" },
|
||||
별칭: null,
|
||||
메모: null,
|
||||
수량: { 손: 1 },
|
||||
},
|
||||
{ 로직: "GC001109", 별칭: null, 메모: null, 입력값: {}, 수량: { 손: 1 } },
|
||||
];
|
||||
const click = async (calc) => {
|
||||
const res = [];
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const t = mountLaborTable(
|
||||
box("div"),
|
||||
{ 담은로직: JSON.parse(JSON.stringify(rows)), 자재: [], 단위: "㎡" },
|
||||
{
|
||||
mode: "precombo",
|
||||
layer: "system",
|
||||
column: "공통",
|
||||
readOnly: false,
|
||||
owner: null,
|
||||
onChanged() {},
|
||||
...(calc ? { calc: async () => ({ 줄: [], 자재: [] }) } : {}),
|
||||
},
|
||||
);
|
||||
await settle();
|
||||
modals.length = 0;
|
||||
stacks.length = 0;
|
||||
calls.length = 0;
|
||||
grid.onRowClick(i);
|
||||
await settle();
|
||||
const m = modals[0];
|
||||
const s = stacks[0];
|
||||
res.push({
|
||||
modal: m ? m.title : null,
|
||||
skModal: m ? all(m.body, (n) => "laborSk" in n.dataset).length : 0, // 그 SK 문서 모달(806-1)
|
||||
stack: s ? { shown: shown(s.root), draws: s.draws.map((d) => d.key) } : null,
|
||||
body: m ? all(m.body, (n) => "skCover" in n.dataset && shown(n)).length : 0,
|
||||
banners: m ? all(m.body, (n) => "banner" in n.dataset).map((n) => n.dataset.banner) : [],
|
||||
calc: skCalls().length,
|
||||
});
|
||||
t.destroy?.();
|
||||
}
|
||||
return res;
|
||||
};
|
||||
out.labor = await click(false);
|
||||
out.labor_inject = await click(true);
|
||||
|
||||
// ④ M01 로직 상세 그릇 — 기본정보 접힘 + 줄 쌓기
|
||||
const { buildLabDetail } = M("M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts");
|
||||
const host = box("div");
|
||||
const stack = box("div", { "data-stack": "" });
|
||||
buildLabDetail(host, {
|
||||
row: {
|
||||
키: "GC001109",
|
||||
원문번호: "1-1",
|
||||
이름: "기초",
|
||||
결과단위: "원/㎡",
|
||||
입력: [],
|
||||
중간: [],
|
||||
호표: [],
|
||||
덧줄: [],
|
||||
},
|
||||
file: "f.json",
|
||||
reasons: ["막힘"],
|
||||
ownHost: box("div"),
|
||||
onChange() {},
|
||||
stack,
|
||||
});
|
||||
out.m01 = host.children.map((n) => n.tagName + (n.dataset.stack !== undefined ? ":stack" : ""));
|
||||
console.log(JSON.stringify(out));
|
||||
})().catch((e) => {
|
||||
console.error(e.stack || String(e));
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
"""857-0 지킴 도우미 — 불러오기 지문(블록 × 두 판 · 검산 · 이음 / 엑셀 올림 · 호표 목록 · 칠 ·
|
||||
고정 줄 / 재료 이음 표).
|
||||
|
||||
- 블록 = 견본(원파일 EST · STC · 실무 엑셀)마다 `Doc_FromNative.emit` → 가져온 식 SK(저장 없음) →
|
||||
엑셀 판 · 우리 판 문서 셈(`Doc_Import.derive` + `run`) 노 · 재 · 경 · 계 +
|
||||
검산(`Sangeun_Imported.check` 같음 · 줄 같음 수) + 줄마다 이음(종류 · 이음 · 기계 찾기 ·
|
||||
재료 찾기 판정 · 키).
|
||||
- 올림 = 엑셀을 임시 개인 층에 올림(`Hopyo_Router._upload`) → 거절 글 | 목록(`Hopyo_View.listing`) ·
|
||||
칠(`Hopyo_Marks.blocks`) · 고정 줄(`Hopyo_Fixed.line_of` 이름 · 규격 · 단위 · 단가 · 이음 · 비율).
|
||||
- 재료 이음 표 = 일위대가 호표 자재 · 별도계상 줄 — 호표 길 키(`line_of`) ·
|
||||
단가산출 길 키(`San_Link.m01`).
|
||||
- 지문 = 갈래 열쇠(「블록 EST:거창#3」 등)마다 sha256 앞 16 자 · 견본 내용은 안 남김.
|
||||
- M01 한 벌 쥠(셈 동안 M01 파일이 안 바뀜 — 빠르게만 · 답 같음).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[1]
|
||||
for p in (str(ROOT), str(HERE)):
|
||||
if p not in sys.path:
|
||||
sys.path.insert(0, p)
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl")
|
||||
|
||||
KEYS = ("노무비", "재료비", "경비", "계")
|
||||
#: 기본(빠른) 표본 — 견본마다 블록 몇 개 · 올림 파일 몇 개(전수 = `S857_ALL=1`)
|
||||
QUICK_BLOCKS = {
|
||||
"EST:거창": 8,
|
||||
"STC:봉화": 8,
|
||||
"엑셀:북부청임도": 8,
|
||||
"엑셀:봉화": 8,
|
||||
"엑셀:2026수목": 8,
|
||||
}
|
||||
QUICK_UPLOAD = ("북부청임도", "봉화", "2026수목")
|
||||
|
||||
|
||||
def sources() -> dict[str, Path]:
|
||||
"""「갈래:이름」 → 견본 경로(없는 PC = 경로가 없음)."""
|
||||
import test_797_1a_import_flags as practice
|
||||
from test_810_1_estx import FILES as EST
|
||||
from test_810_1_stc import FILES as STC
|
||||
|
||||
out = {f"EST:{k}": v for k, v in EST.items()}
|
||||
out |= {f"STC:{k}": v for k, v in STC.items()}
|
||||
return out | {f"엑셀:{k}": v for k, v in practice.FILES.items()}
|
||||
|
||||
|
||||
def digest(value: Any) -> str:
|
||||
raw = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def hold_m01():
|
||||
"""M01 한 벌을 셈 동안 쥠(줄마다 파일 날짜 다시 재기 뺌)."""
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
|
||||
real, memo = m01.loaded, []
|
||||
|
||||
def once():
|
||||
if not memo:
|
||||
memo.append(real())
|
||||
return memo[0]
|
||||
|
||||
m01.loaded = once
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
m01.loaded = real
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def personal():
|
||||
"""임시 storage 개인 층(원본 storage · 마스터 안 씀)."""
|
||||
from config import config_system
|
||||
|
||||
old = config_system.STORAGE_BASE_DIR
|
||||
tmp = Path(tempfile.mkdtemp(prefix="t857_"))
|
||||
config_system.STORAGE_BASE_DIR = str(tmp / "storage")
|
||||
(tmp / "storage").mkdir()
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Template_Layers as layers
|
||||
|
||||
folder = layers.personal_dir(7, 42)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with store.at(folder):
|
||||
yield folder
|
||||
finally:
|
||||
config_system.STORAGE_BASE_DIR = old
|
||||
|
||||
|
||||
# ── 블록 ──────────────────────────────────────────────────────────────
|
||||
def saved_of(tag: str, path: Path) -> dict:
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
from M02_MasterTemplete import M02_San_Xlsx as sx
|
||||
|
||||
raw = path.read_bytes()
|
||||
if tag.startswith("엑셀:"):
|
||||
return fn.pack(sx.read(path.name, raw), path.name)
|
||||
return fn.read(path.name, raw)
|
||||
|
||||
|
||||
def _money(got: dict) -> Any:
|
||||
return {k: str(got.get(k)) for k in KEYS} if got.get("셈됨") else "못 셈"
|
||||
|
||||
|
||||
def _links(row: dict) -> list:
|
||||
out = []
|
||||
for it in row.get("호표") or []:
|
||||
res = it.get("자원") or {}
|
||||
find, mat = res.get("찾기") or {}, res.get("재료찾기") or {}
|
||||
out.append(
|
||||
[
|
||||
it.get("종류"),
|
||||
it.get("이음"),
|
||||
find.get("판정"),
|
||||
find.get("키"),
|
||||
mat.get("판정"),
|
||||
mat.get("키"),
|
||||
]
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def block(saved: dict, no: int) -> dict:
|
||||
"""블록 하나 → 지문 몸 {엑셀, 우리, 검산, 이음}."""
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
from M02_MasterTemplete import M02_Doc_Import as dim
|
||||
from M02_MasterTemplete import M02_Sangeun_Doc as sd
|
||||
from M02_MasterTemplete import M02_Sangeun_Imported as imp
|
||||
|
||||
whole = imp._whole()
|
||||
out = fn.emit(saved, no)
|
||||
row = out["로직"]
|
||||
sk = {
|
||||
"키": "SK-999999",
|
||||
"이름": row["이름"],
|
||||
"단위": str(row.get("결과단위", "/")).split("/", 1)[-1],
|
||||
}
|
||||
sk |= {"바탕": None, "입력값": {}, "덮개": {}, "뺀줄": [], "더한줄": []}
|
||||
sk[imp.KEY] = {"로직": row, "원본": out["원본"], "단가기준": "엑셀"}
|
||||
sk = sd.clean(sk, None, whole)
|
||||
got: dict[str, Any] = {"이음": _links(row)}
|
||||
for basis in ("엑셀", "우리"):
|
||||
one = {**sk, imp.KEY: {**sk[imp.KEY], "단가기준": basis}}
|
||||
try:
|
||||
got[basis] = _money(dim.run(dim.derive(one, None, whole), one, whole))
|
||||
except Exception as e: # noqa: BLE001 — 예외도 지문
|
||||
got[basis] = f"예외 {type(e).__name__}"
|
||||
try:
|
||||
c = imp.check(sk, whole)
|
||||
got["검산"] = [c["같음"], sum(1 for x in c["줄"] if x.get("같음")), len(c["줄"])]
|
||||
except Exception as e: # noqa: BLE001
|
||||
got["검산"] = f"예외 {type(e).__name__}"
|
||||
return got
|
||||
|
||||
|
||||
def blocks(full: bool) -> tuple[dict[str, str], int]:
|
||||
"""{「블록 갈래:이름#번」: 지문} · 건너뛴 견본 수."""
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
|
||||
out, skipped = {}, 0
|
||||
with hold_m01(), personal():
|
||||
for tag, path in sources().items():
|
||||
if not full and tag not in QUICK_BLOCKS:
|
||||
continue
|
||||
if not path or not path.exists():
|
||||
skipped += 1
|
||||
continue
|
||||
saved = saved_of(tag, path)
|
||||
nos = sorted(fn.numbers(saved))
|
||||
if not full:
|
||||
step = max(1, len(nos) // QUICK_BLOCKS[tag])
|
||||
nos = nos[::step][: QUICK_BLOCKS[tag]]
|
||||
for no in nos:
|
||||
out[f"블록 {tag}#{no}"] = digest(block(saved, no))
|
||||
return out, skipped
|
||||
|
||||
|
||||
# ── 엑셀 올림 · 호표 쪽 ─────────────────────────────────────────────────
|
||||
def _fixed(book: dict) -> list:
|
||||
from M02_MasterTemplete import M02_Hopyo_Fixed as hf
|
||||
|
||||
linker, out = hf.Linker(True), []
|
||||
for h in book.get("호표") or []:
|
||||
for ln in h.get("줄") or []:
|
||||
fx = hf.line_of(ln, h["줄"], {}, set(), linker)["고정"]
|
||||
out.append(
|
||||
[
|
||||
h["번"],
|
||||
ln.get("차례"),
|
||||
{k: fx.get(k) for k in ("이름", "규격", "단위", "단가", "이음", "비율")},
|
||||
]
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def mats(book: dict, clues: list) -> list:
|
||||
"""재료 이음 표 [호표, 차례, 갈래, 호표 길 키, 단가산출 길 키, 산근 판정 · 방법]."""
|
||||
from M02_MasterTemplete import M02_Hopyo_Fixed as hf
|
||||
from M02_MasterTemplete import M02_Hopyo_Match as hm
|
||||
from M02_MasterTemplete import M02_San_Link as sl
|
||||
from M02_MasterTemplete import M02_San_MatFind as smf
|
||||
|
||||
linker, out = hf.Linker(True), []
|
||||
for h in book.get("호표") or []:
|
||||
for ln in h.get("줄") or []:
|
||||
if hf.kind_of(ln) not in hm.MATERIAL_KINDS:
|
||||
continue
|
||||
a = (hf.line_of(ln, h["줄"], {}, set(), linker)["고정"]["이음"] or {}).get("자재")
|
||||
src = {k: ln.get(k) or "" for k in ("이름", "규격", "단위")}
|
||||
src |= {"종류": "자재", "코드": ln.get("코드") or ""}
|
||||
with smf.clues_on(clues):
|
||||
b, _ = sl.m01("재료", src, "")
|
||||
found = src.get("재료찾기") or {}
|
||||
out.append(
|
||||
[
|
||||
h["번"],
|
||||
ln.get("차례"),
|
||||
ln.get("갈래"),
|
||||
a,
|
||||
b,
|
||||
found.get("판정"),
|
||||
found.get("방법"),
|
||||
]
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def upload(tag: str, path: Path) -> dict[str, Any]:
|
||||
"""엑셀 하나 올림(임시 층) → {올림, 목록, 칠, 고정, 재료} 지문 몸."""
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
from M02_MasterTemplete import M02_Hopyo_Marks as marks
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
from M02_MasterTemplete import M02_Hopyo_Store as hstore
|
||||
from M02_MasterTemplete import M02_Hopyo_View as view
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_Book as sb
|
||||
from M02_MasterTemplete import M02_San_Xlsx as sx
|
||||
|
||||
data = path.read_bytes()
|
||||
try:
|
||||
row = router._upload(path.name, data, {"id": 42, "이름": "시험"})
|
||||
except store.StoreError as e:
|
||||
return {"올림": f"거절 {e.status} {e}"}
|
||||
folder, key = store.root(), row["키"]
|
||||
book = hstore.read(folder, key)
|
||||
listing = view.listing(folder, key, folder)
|
||||
sheets = sb.sheets(path.name, data)
|
||||
clues = (fn.pack(sx.read_sheets(sheets), path.name) if sb.kind_of(sheets) else {}).get("단서")
|
||||
return {
|
||||
"올림": {k: row.get(k) for k in ("시트", "호표수", "읽기불가")},
|
||||
"목록": {k: listing.get(k) for k in ("호표", "단산", "검산")},
|
||||
"칠": marks.blocks(folder, key),
|
||||
"고정": _fixed(book),
|
||||
"재료": mats(book, clues or []),
|
||||
}
|
||||
|
||||
|
||||
def uploads(full: bool) -> tuple[dict[str, str], dict[str, list], int]:
|
||||
"""({「올림 이름 갈래」: 지문}, {이름: 재료 이음 표}, 건너뛴 수)."""
|
||||
out, table, skipped = {}, {}, 0
|
||||
with hold_m01(), personal():
|
||||
for tag, path in sources().items():
|
||||
name = tag.split(":", 1)[1]
|
||||
if not tag.startswith("엑셀:") or (not full and name not in QUICK_UPLOAD):
|
||||
continue
|
||||
if not path or not path.exists():
|
||||
skipped += 1
|
||||
continue
|
||||
got = upload(tag, path)
|
||||
for part, body in got.items():
|
||||
out[f"올림 {name} {part}"] = digest(body)
|
||||
table[name] = got.get("재료") or []
|
||||
return out, table, skipped
|
||||
|
||||
|
||||
def mat_counts(table: dict[str, list]) -> dict[str, dict[str, int]]:
|
||||
"""재료 이음 전후 표(`m857_mat` 꼴) — 같음(이음) · 같음(못 이음) · 생김 · 풂 · 다른 품목."""
|
||||
out = {}
|
||||
for name, rows in table.items():
|
||||
c: dict[str, int] = {}
|
||||
for r in rows:
|
||||
a, b = r[3], r[4]
|
||||
if a == b:
|
||||
k = "같음(이음)" if a else "같음(못 이음)"
|
||||
else:
|
||||
k = "풀림" if a and not b else "생김" if b and not a else "다른 품목"
|
||||
c[k] = c.get(k, 0) + 1
|
||||
out[name] = c
|
||||
return out
|
||||
@@ -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)") == ""
|
||||
|
||||
@@ -7,6 +7,7 @@ from pathlib import Path
|
||||
import openpyxl
|
||||
|
||||
from M02_MasterTemplete import M02_Hopyo_Grid as grid
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
SS = ROOT / "A00_Common/spreadsheet"
|
||||
@@ -38,7 +39,7 @@ def test_xlsx_without_widths_is_empty_and_garbage_is_safe():
|
||||
|
||||
def test_xlsx_sheet_carries_widths():
|
||||
data = _xlsx({"A": 30})
|
||||
sheets = grid._xlsx("a.xlsx", data)["시트"]
|
||||
sheets = grid._xlsx("a.xlsx", data, workbook.read("a.xlsx", data).sheets)["시트"]
|
||||
assert sheets and sheets[0]["열"]["A"]["폭"] == 30.0
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PLAN 856-0 — 단가산출 화면 지킴(가짜 DOM · 진짜 코드 · `helper_856_0_sk_screen.cjs`).
|
||||
|
||||
① 단가산출 화면을 열 때 서버 `/sangeun/calc` 부름 수 · 숨은 상세 몸 DOM · 줄 쌓기 그림
|
||||
② 일위대가 표 줄 누름 — 단가산출(SK) 참조 줄 = 그 SK 줄 쌓기 · M01 로직 줄 · 셈 주입(프로젝트 사본) 줄
|
||||
③ 머리 띠 넷(까닭 · M01 개정 · 빠진 줄 · 짝 잃음)이 뜨는 경우 — 견본 답
|
||||
④ M01 로직 상세 그릇 = 기본정보 접힘 + 줄 쌓기
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from functools import lru_cache
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _run() -> dict:
|
||||
proc = subprocess.run(
|
||||
["node", os.path.join(HERE, "helper_856_0_sk_screen.cjs")],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr[-3000:]
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def test_sk_page_open_calls_and_hidden_body() -> None:
|
||||
got = _run()
|
||||
# 856-1 — 셈 한 번(머리 띠용 · 바탕 원값 bare 셈 걷음) · 숨은 상세 몸 DOM 0 · 줄 쌓기 한 번 그림
|
||||
for k in ("page_base", "page_nobase", "memory"):
|
||||
assert got[k]["calc"] == 1, k
|
||||
assert got[k]["body"] == 0, k
|
||||
assert got[k]["stack"]["shown"] is True, k
|
||||
assert got["page_base"]["stack"]["draws"] == [{"key": "SK-000001", "memory": False}]
|
||||
# 불러오기 미리 보기(저장 전 가져온 식) = 빈 키 + 문서째
|
||||
assert got["memory"]["stack"]["draws"] == [{"key": "", "memory": True}]
|
||||
|
||||
|
||||
def test_labor_row_click() -> None:
|
||||
sk, logic = _run()["labor"]
|
||||
# 단가산출 참조 줄 = 그 SK 문서 모달 · 줄 쌓기가 그 키로 보임
|
||||
assert sk["skModal"] == 1 and sk["stack"]["shown"] is True
|
||||
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"] == ["info"] and row["calc"] == 0
|
||||
|
||||
|
||||
def test_head_bands_four() -> None:
|
||||
got = _run()
|
||||
# 까닭(빨강) · M01 개정 · 빠진 줄 · 짝 잃음(노랑) + 머리 배지 · 개정 배지
|
||||
assert got["bands"]["banners"] == ["danger", "warning", "warning", "warning"]
|
||||
assert got["bands"]["badges"] == [["info", "계"], ["danger", "M02_SangeunRevisedBase"]]
|
||||
# 서버 못 닿음 = 빨강 하나
|
||||
assert got["bands_fail"]["banners"] == ["danger"]
|
||||
assert got["page_base"]["banners"] == [] and got["page_base"]["badges"] == []
|
||||
|
||||
|
||||
def test_m01_logic_detail_shape() -> None:
|
||||
# 기본정보 접힘 · 막힘 까닭 · 줄 쌓기 — 단가산출 상세 몸 칸 없음
|
||||
assert _run()["m01"] == ["DETAILS", "DIV", "DIV:stack"]
|
||||
@@ -0,0 +1,136 @@
|
||||
"""857-1 지킴 — 불러오기 책 한 번 · 종류 한 말 · 일위대가 시트 없는 엑셀 올림 ·
|
||||
「고를 재료」 판 무효 지문 · 판 셈 동안 M01 한 벌(`M01_MasterData_Store_Cache.steady`).
|
||||
|
||||
임시 storage 개인 층 · 실무 엑셀 견본(없는 PC = 건너뜀).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
import helper_857_import as h # noqa: E402
|
||||
|
||||
|
||||
def _path(name: str) -> Path:
|
||||
p = h.sources().get(f"엑셀:{name}")
|
||||
if not p or not p.exists():
|
||||
pytest.skip(f"견본 없음 — {name}")
|
||||
return p
|
||||
|
||||
|
||||
def _opens(monkeypatch) -> list[str]:
|
||||
import openpyxl
|
||||
import xlrd
|
||||
|
||||
seen: list[str] = []
|
||||
for mod, attr in ((openpyxl, "load_workbook"), (xlrd, "open_workbook")):
|
||||
real = getattr(mod, attr)
|
||||
|
||||
def wrap(*a, _real=real, _tag=attr, **k):
|
||||
seen.append(_tag)
|
||||
return _real(*a, **k)
|
||||
|
||||
monkeypatch.setattr(mod, attr, wrap)
|
||||
return seen
|
||||
|
||||
|
||||
def test_종류_한_말():
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as hs
|
||||
from M02_MasterTemplete import M02_San_Book as sb
|
||||
from M02_MasterTemplete import M02_San_Workbook as wb
|
||||
|
||||
for names, kind in (
|
||||
(["일위대가표", "단가산출근거"], "STmate"),
|
||||
(["단가산출근거"], "STmate"),
|
||||
(["일위대가", "단가산출"], "EST"),
|
||||
(["일위대가"], None),
|
||||
):
|
||||
assert wb.kind_of(names) == kind
|
||||
assert sb.kind_of(dict.fromkeys(names)) == kind
|
||||
assert hs.is_stmate(names) == (kind == "STmate")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["봉화", "북부청사방"])
|
||||
def test_올림_한_번에_책_한_번(monkeypatch, name):
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
|
||||
path = _path(name)
|
||||
seen = _opens(monkeypatch)
|
||||
with h.personal():
|
||||
row = router._upload(path.name, path.read_bytes(), {"id": 42, "이름": "시험"})
|
||||
assert row["호표수"] > 0 and not row.get("읽기불가")
|
||||
assert len(seen) == 1, seen
|
||||
|
||||
|
||||
def test_일위대가_시트_없는_엑셀도_올라감_호표_빈_목록_단산은_보임():
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hx
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
from M02_MasterTemplete import M02_Hopyo_Store as hstore
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
path = _path("2026수목")
|
||||
data = path.read_bytes()
|
||||
with pytest.raises(hx.ExcelError): # B09 내역서 길(그대로) — 일위대가 시트 없음 = 거절
|
||||
hx.read_book(path.name, data)
|
||||
with h.personal():
|
||||
row = router._upload(path.name, data, {"id": 42, "이름": "시험"})
|
||||
hp = hstore.read(store.root(), row["키"])
|
||||
assert row["호표수"] == 0 and hp["호표"] == []
|
||||
assert len(hp["단산"]) == 142 # 단가산출 시트 블록(둘 꼴 산근 수와 같음)
|
||||
assert fh.has(store.root(), row["키"]) # 가져온 식 열기 자료 보관
|
||||
|
||||
|
||||
def test_재료판_무효_지문_M01_이_바뀌면_다시_셈(monkeypatch):
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_MatPick as mp
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
path = _path("영덕계류")
|
||||
with h.personal():
|
||||
key = router._upload(path.name, path.read_bytes(), {"id": 42, "이름": "시험"})["키"]
|
||||
first = mp.census(store.root(), key)
|
||||
saved = json.loads(fh._path(store.root(), key).read_bytes())
|
||||
assert saved[mp.MARK] == mp._mark() and saved[mp.CENSUS] == first
|
||||
runs: list[int] = []
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
|
||||
emit = fn.emit
|
||||
monkeypatch.setattr(fn, "emit", lambda *a, **k: runs.append(1) or emit(*a, **k))
|
||||
assert mp.census(store.root(), key) == first and not runs # 같은 M01 = 저장본
|
||||
monkeypatch.setattr(mp, "_mark", lambda: "다른 M01")
|
||||
assert mp.census(store.root(), key) == first and runs # 지문 다름 = 다시 셈 · 답 같음
|
||||
|
||||
|
||||
def test_판_셈_동안_M01_파일_자국_한_번(monkeypatch):
|
||||
from M01_MasterData import M01_MasterData_Store_Cache as cache
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_MatPick as mp
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
path = _path("영덕계류")
|
||||
counts: list[int] = []
|
||||
real = cache._stamps
|
||||
monkeypatch.setattr(cache, "_stamps", lambda folder: counts.append(1) or real(folder))
|
||||
with h.personal():
|
||||
key = router._upload(path.name, path.read_bytes(), {"id": 42, "이름": "시험"})["키"]
|
||||
counts.clear()
|
||||
held = mp.census(store.root(), key)
|
||||
with_hold = len(counts)
|
||||
at = fh._path(store.root(), key)
|
||||
src = fh._excel_of(at, json.loads(at.read_bytes()))
|
||||
counts.clear()
|
||||
for no in sorted(fn.numbers(src)): # 안 쥔 셈(지금 길) — 블록마다 자국을 다시 잼
|
||||
with mp.using(None):
|
||||
fn.emit(src, no)
|
||||
bare = len(counts)
|
||||
assert held and with_hold <= 3 < bare
|
||||
@@ -0,0 +1,73 @@
|
||||
"""857-0 지킴 — 불러오기 지문(걸음 4 동안 「다름 0」 자 · 도우미 `helper_857_import`).
|
||||
|
||||
- 블록 = 원파일 EST · STC · 실무 엑셀 블록마다 엑셀 판 · 우리 판 문서 셈(노 · 재 · 경 · 계) ·
|
||||
검산 판정 · 줄 이음 판정.
|
||||
- 올림 = 실무 엑셀을 임시 개인 층에 올림 → 거절 | 호표 목록 · 칠 · 고정 줄 · 재료 이음 표.
|
||||
- 재료 이음 전후 표 = 호표 길 키 대 단가산출 길 키 갈래 수(857-4 의 기준).
|
||||
- 기본 = 빠른 표본(`QUICK_*`) · 전수 = 환경 `S857_ALL=1` · 견본 없는 PC = 그 갈래 건너뜀(수를 글로).
|
||||
- 다르면 실패 + 갈래 이름 — 뜻대로 바꾼 걸음만 다시 뜸(바뀐 갈래를 커밋 글에):
|
||||
`S857_ALL=1 ./venv/Scripts/python.exe resources/tester/test_857_import_golden.py --write`
|
||||
(뒤에 「블록」 · 「올림」 = 그 갈래만)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
import helper_857_import as h # noqa: E402
|
||||
|
||||
FILE = HERE / "golden_857_import.json"
|
||||
REDO = "S857_ALL=1 ./venv/Scripts/python.exe resources/tester/test_857_import_golden.py --write"
|
||||
ALL = os.environ.get("S857_ALL") == "1"
|
||||
|
||||
|
||||
def _want() -> dict:
|
||||
return json.loads(FILE.read_text("utf-8"))
|
||||
|
||||
|
||||
def _compare(got: dict[str, str], want: dict[str, str], skipped: int) -> None:
|
||||
if not got:
|
||||
pytest.skip(f"견본 없음 — 건너뜀 {skipped}")
|
||||
missing = sorted(k for k in got if k not in want)
|
||||
changed = sorted(k for k in got if k in want and want[k] != got[k])
|
||||
gone = sorted(k for k in want if k not in got) if ALL and not skipped else []
|
||||
assert not (missing or changed or gone), (
|
||||
f"지문 다름 — 바뀜 {len(changed)} {changed[:15]} · 새 {missing[:10]} · 빠짐 {gone[:10]}"
|
||||
f" · 건너뜀 {skipped}\n뜻대로 바꾼 걸음이면 다시 뜸: {REDO}"
|
||||
)
|
||||
if skipped:
|
||||
warnings.warn(f"견본 없어 건너뜀 {skipped}", stacklevel=2)
|
||||
|
||||
|
||||
def test_블록_두_판_검산_이음_지문_같음():
|
||||
got, skipped = h.blocks(ALL)
|
||||
_compare(got, _want()["블록"], skipped)
|
||||
|
||||
|
||||
def test_엑셀_올림_호표_목록_칠_고정_재료_지문_같음():
|
||||
got, table, skipped = h.uploads(ALL)
|
||||
_compare(got, _want()["올림"], skipped)
|
||||
want = _want()["재료표"]
|
||||
assert {k: v for k, v in h.mat_counts(table).items()} == {k: want[k] for k in table}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "--write" not in sys.argv or not ALL:
|
||||
sys.exit(f"다시 뜨기 = {REDO}")
|
||||
only = sys.argv[sys.argv.index("--write") + 1 :] # 갈래 하나만(블록 | 올림) · 없으면 둘 다
|
||||
blocks, skip_b = (_want()["블록"], 0) if only == ["올림"] else h.blocks(True)
|
||||
ups, table, skip_u = h.uploads(True) if only != ["블록"] else (_want()["올림"], None, 0)
|
||||
mats = h.mat_counts(table) if table is not None else _want()["재료표"]
|
||||
body = {"판": 1, "블록": blocks, "올림": ups, "재료표": mats}
|
||||
FILE.write_text(
|
||||
json.dumps(body, ensure_ascii=False, indent=1, sort_keys=True) + "\n", "utf-8", newline="\n"
|
||||
)
|
||||
print(f"블록 {len(blocks)} · 올림 {len(ups)} · 건너뜀 {skip_b + skip_u} → {FILE.name}")
|
||||
@@ -0,0 +1,88 @@
|
||||
"""858-B 권한 짝 거울 시험 — 화면 `M02_MasterTemplete_Layer.ts` 의 `accessFor` 와 서버
|
||||
`M02_Layer_Access`(`can_write` · `grant` 409 = 회사 없음)가 같은 답을 내는지.
|
||||
|
||||
사람 여덟 × 층 · 주인 열하나를 통째로 맞춤 — 고침(canWrite) · 회사부터 등록(needCompany).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from M02_MasterTemplete import M02_Layer_Access as access
|
||||
|
||||
LAYER = Path(__file__).resolve().parents[2] / "M02_MasterTemplete" / "M02_MasterTemplete_Layer.ts"
|
||||
|
||||
PEOPLE = {
|
||||
"시스템": {"id": "1", "role": "SYSTEM_ADMIN", "company_id": None},
|
||||
"시스템3": {"id": "1", "role": "SYSTEM_ADMIN", "company_id": 3},
|
||||
"관리자3": {"id": "5", "role": "ADMIN", "company_id": 3},
|
||||
"마스터3": {"id": "6", "role": "USER", "company_id": 3, "is_master": True},
|
||||
"일반3": {"id": "7", "role": "USER", "company_id": 3},
|
||||
"관리자9": {"id": "90", "role": "ADMIN", "company_id": 9},
|
||||
"회사없음": {"id": "8", "role": "USER", "company_id": None},
|
||||
"없음": None,
|
||||
}
|
||||
PLACES = [
|
||||
("system", None),
|
||||
("company", None), ("company", "3"), ("company", "9"),
|
||||
("personal", None), ("personal", "3/7"), ("personal", "3/5"), ("personal", "3/1"),
|
||||
("personal", "9/90"), ("personal", "9/91"), ("personal", "3/8"),
|
||||
] # fmt: skip
|
||||
|
||||
|
||||
def _server(user: dict | None, layer: str, owner: str | None) -> dict[str, bool]:
|
||||
session = None if user is None else {**user, "user_id": user["id"]}
|
||||
try:
|
||||
access.grant(session or {}, layer, owner)
|
||||
need = False
|
||||
except HTTPException as error:
|
||||
need = error.status_code == 409
|
||||
return {"canWrite": access.can_write(session, (layer, owner)), "needCompany": need}
|
||||
|
||||
|
||||
def _screen(cases: list) -> list[dict[str, bool]]:
|
||||
text = LAYER.read_text(encoding="utf-8")
|
||||
parts = [
|
||||
re.search(r"^export const ownOwner[\s\S]*?;\n", text, re.M),
|
||||
re.search(r"^export function accessFor[\s\S]*?^}", text, re.M),
|
||||
re.search(r"^export function manages[\s\S]*?^}", text, re.M),
|
||||
]
|
||||
assert all(parts), "ownOwner · accessFor · manages 를 못 찾음"
|
||||
script = (
|
||||
'type ManageLayer = "system" | "company" | "personal";\n'
|
||||
"interface SessionUser { id: string; role?: string; company_id?: number | null;"
|
||||
" is_master?: boolean }\n"
|
||||
"interface LayerAccess { canWrite: boolean; needCompany: boolean }\n"
|
||||
+ "\n".join(p.group(0).replace("export ", "") for p in parts)
|
||||
+ "\nconst cases = JSON.parse(process.argv[1]);"
|
||||
+ "\nconsole.log(JSON.stringify(cases.map((c) => accessFor(c[0], c[1], c[2]))));"
|
||||
)
|
||||
result = subprocess.run(
|
||||
["node", "--experimental-strip-types", "--no-warnings",
|
||||
"--input-type=module-typescript", "-e", script, json.dumps(cases)],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60,
|
||||
) # fmt: skip
|
||||
assert result.returncode == 0, result.stderr
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음")
|
||||
def test_화면_서버_권한_같음():
|
||||
combos = list(itertools.product(PEOPLE.items(), PLACES))
|
||||
screen = _screen([[layer, owner, user] for (_n, user), (layer, owner) in combos])
|
||||
differ = [
|
||||
(name, layer, owner, got, _server(user, layer, owner))
|
||||
for ((name, user), (layer, owner)), got in zip(combos, screen, strict=True)
|
||||
if got != _server(user, layer, owner)
|
||||
]
|
||||
assert differ == []
|
||||
writes = sum(s["canWrite"] for s in screen)
|
||||
assert 0 < writes < len(screen) # 고침 · 못 고침이 둘 다 나옴(빈 비교가 아님)
|
||||
@@ -0,0 +1,469 @@
|
||||
# ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀
|
||||
"""858 5-0 층 서고 지킴 — 서버 길 답 지문 · 동시 쓰기(임시 storage · 제품 코드 안 고침).
|
||||
|
||||
① 지문 — 견본 층(단가산출 · 일위대가 · 구조물 조합 항목 · 내 기계 · 내 재료 · 공유 요청)에서
|
||||
목록 · 나무 · 만들기 · 고치기 · 지우기 · 복사 · 붙여넣기 · 합치기 · 되돌림 · 쓰는 곳 · 권한 길을
|
||||
차례로 불러 답(상태 + 몸)을 갈래마다 지문으로 → `fixtures/m02_858_shelf_golden.json` 과 같음.
|
||||
다르면 갈래 이름 + 지금 답 + 다시 뜨는 법으로 실패(건너뛰지 않음). 다시 뜸 =
|
||||
`SHELF_858_WRITE=1 ./venv/Scripts/python.exe -m pytest resources/tester/test_858_shelf_golden.py`
|
||||
(뜻한 바뀜일 때만 · 커밋 글에 까닭). 답 통째 전후 대조 = `SHELF_858_DUMP=tmp/<파일>.json`.
|
||||
② 동시 쓰기 — 잠금 없는 나무 고침 · 나무 지우기 · 합치기를 같은 판으로 겹쳐 부름. 지금 사실을
|
||||
그대로 단언(나무 = 둘 다 됨 · 뒤 것이 이김 · 지우기 + 합치기 = 앞 것이 이기고 뒤 것은 터짐) —
|
||||
「5-4 에서 뒤집을 단언」 표시 줄은 5-4 가 바꿈.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from common_util.common_util_auth import verify_session
|
||||
from M02_MasterTemplete import M02_Labor_Router as labor_router
|
||||
from M02_MasterTemplete import M02_Library_Same_Router as same_router
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Router_Items as items_router
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Router_Layers as layers_router
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_MyMachine_Look as look_router
|
||||
from M02_MasterTemplete import M02_MyMachine_Router as machine_router
|
||||
from M02_MasterTemplete import M02_Precombo_Folders as pre_folders
|
||||
from M02_MasterTemplete import M02_Share_Request as share
|
||||
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
|
||||
|
||||
GOLD = Path(__file__).resolve().parent / "fixtures" / "m02_858_shelf_golden.json"
|
||||
WRITE = "SHELF_858_WRITE"
|
||||
USER = {"user_id": 42, "company_id": 7, "role": "USER", "is_master": False, "name": "갑"}
|
||||
NEIGHBOR = {**USER, "user_id": 43, "name": "을"} # 같은 회사 남
|
||||
ADMIN = {**USER, "user_id": 50, "role": "ADMIN", "name": "관리"} # 회사 7 관리자
|
||||
SYSADMIN = {**USER, "user_id": 1, "role": "SYSTEM_ADMIN", "name": "시스템"}
|
||||
STRANGER = {"user_id": 90, "company_id": 9, "role": "ADMIN", "is_master": False, "name": "남"}
|
||||
MEMBERS = {42: 7, 43: 7, 44: 7, 50: 7, 1: 7, 90: 9}
|
||||
P = "/api/m02/layers/personal"
|
||||
MASK = {"날짜", "때", "처리날짜", "수정일", "넣은날", "고친날"} # 실행마다 다른 시각
|
||||
PREFIX = {"sangeun": "SK", "precombo": "SC"}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def shelf(world, monkeypatch, tmp_path):
|
||||
async def member(owner: str) -> bool:
|
||||
company, _, user = owner.partition("/")
|
||||
return MEMBERS.get(int(user)) == int(company) if user else int(company) in (7, 9)
|
||||
|
||||
async def note(session: dict[str, Any], got: Any) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(items_router, "_member", member)
|
||||
monkeypatch.setattr(items_router, "_note", note)
|
||||
app = FastAPI()
|
||||
for one in (
|
||||
layers_router,
|
||||
items_router,
|
||||
labor_router,
|
||||
same_router,
|
||||
machine_router,
|
||||
look_router,
|
||||
share,
|
||||
):
|
||||
app.include_router(one.router)
|
||||
session = dict(USER)
|
||||
app.dependency_overrides[verify_session] = lambda: session
|
||||
return Shelf(TestClient(app), session, str(tmp_path))
|
||||
|
||||
|
||||
class Shelf:
|
||||
"""길을 부르고 답을 갈래마다 모음 — 갈래 = 「종류.일」."""
|
||||
|
||||
def __init__(self, client: TestClient, session: dict[str, Any], tmp: str):
|
||||
self.client, self.session, self.tmp = client, session, tmp
|
||||
self.got: dict[str, list[Any]] = {}
|
||||
self.seq: dict[str, dict[str, str]] = {} # 갈래마다 값 → 차례 표
|
||||
self.home: dict[str, str] = {} # 값 → 처음 본 갈래 표(길 글자용)
|
||||
|
||||
def who(self, person: dict[str, Any]) -> None:
|
||||
self.session.clear()
|
||||
self.session.update(person)
|
||||
|
||||
def go(self, branch: str, method: str, url: str, body: Any = None) -> Any:
|
||||
res = self.client.request(method, url, json=body)
|
||||
try:
|
||||
out = res.json()
|
||||
except ValueError:
|
||||
out = res.text
|
||||
who = self.session.get("user_id")
|
||||
local = self.seq.setdefault(branch, {})
|
||||
for raw, mark in self.home.items(): # 길 글자 속 uuid · 판도 같은 표로
|
||||
url = url.replace(raw, local.get(raw) or mark)
|
||||
row = [who, method, url, res.status_code, self.clean(out, branch)]
|
||||
self.got.setdefault(branch, []).append(row)
|
||||
return out
|
||||
|
||||
def clean(self, value: Any, branch: str) -> Any:
|
||||
"""실행마다 다른 것만 가림 — 임시 폴더 · 시각 · uuid 와 판(갈래 안 처음 본 차례 번호 — 같은
|
||||
값은 같은 번호라 「409 판 = 앞서 받은 판」 같은 이음은 그대로 잼 · 한 갈래가 바뀌어도 다른
|
||||
갈래 번호는 안 밀림)."""
|
||||
local = self.seq.setdefault(branch, {})
|
||||
if isinstance(value, dict):
|
||||
out = {}
|
||||
for k, v in value.items():
|
||||
if (k == "id" or k.endswith("판")) and isinstance(v, str) and v:
|
||||
out[k] = local.setdefault(v, f"<{k}{len(local) + 1}>")
|
||||
self.home.setdefault(v, f"<{branch}{out[k][1:]}")
|
||||
elif k in MASK and v is not None:
|
||||
out[k] = "<가림>"
|
||||
else:
|
||||
out[k] = self.clean(v, branch)
|
||||
return out
|
||||
if isinstance(value, list):
|
||||
return [self.clean(v, branch) for v in value]
|
||||
if isinstance(value, str):
|
||||
return value.replace(self.tmp, "<tmp>").replace(self.tmp.replace("\\", "/"), "<tmp>")
|
||||
return value
|
||||
|
||||
|
||||
def _finger(answers: list[Any]) -> str:
|
||||
text = json.dumps(answers, ensure_ascii=False, sort_keys=True, default=str)
|
||||
return hashlib.sha256(text.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
# ── 견본 ──────────────────────────────────────────────────────────────
|
||||
def _fixed(price: int, kind: str) -> dict[str, Any]:
|
||||
line = {"고정": {"이름": "운반", "단위": "식", "단가": {"경비": price}}}
|
||||
return {**line, "수량": 1 if kind == "sangeun" else {"손": 1}}
|
||||
|
||||
|
||||
def _doc(kind: str, name: str, price: int) -> dict[str, Any]:
|
||||
field = "더한줄" if kind == "sangeun" else "담은로직"
|
||||
return {"이름": f"sub4임시{name}", "단위": "m", field: [_fixed(price, kind)]}
|
||||
|
||||
|
||||
def _library(s: Shelf, world: dict[str, Any], kind: str) -> None:
|
||||
b = f"{kind}."
|
||||
lib, tree = f"{P}/library/{kind}", f"{P}/{kind}-tree"
|
||||
one = s.go(b + "만들기", "POST", lib, {"문서": _doc(kind, "가", 1000)})["이름"]
|
||||
two = s.go(b + "만들기", "POST", lib, {"문서": _doc(kind, "나", 2000)})["이름"]
|
||||
s.go(b + "만들기", "POST", lib, {"문서": _doc(kind, "가", 1000)}) # 같은 내용
|
||||
twin = s.go(b + "만들기", "POST", lib, {"문서": _doc(kind, "가", 1000), "새로": True})["이름"]
|
||||
s.go(b + "복사", "POST", lib, {"본뜬": {"층": "personal", "주인": "7/42", "키": two}})
|
||||
s.go(
|
||||
b + "복사",
|
||||
"POST",
|
||||
lib,
|
||||
{"본뜬": {"층": "personal", "주인": "7/42", "키": f"{PREFIX[kind]}-999999"}},
|
||||
)
|
||||
spare = s.go(b + "만들기", "POST", lib, {"문서": _doc(kind, "다", 3000), "새로": True})["이름"]
|
||||
s.go(b + "목록", "GET", f"{P}/templates")
|
||||
|
||||
read = s.go(b + "읽기", "GET", f"{P}/templates/{kind}/{one}")
|
||||
s.go(b + "읽기", "GET", f"{P}/templates/{kind}/{PREFIX[kind]}-999999")
|
||||
edited = {**read["문서"], "이름": "sub4임시가고침"}
|
||||
s.go(b + "고치기", "PUT", f"{P}/templates/{kind}/{one}", {"문서": edited, "판": read["판"]})
|
||||
s.go(b + "고치기", "PUT", f"{P}/templates/{kind}/{one}", {"문서": edited, "판": read["판"]})
|
||||
|
||||
판 = s.go(b + "나무", "GET", tree)["판"]
|
||||
for body in (
|
||||
{"op": "add-folder", "경로": [], "이름": "옹벽"},
|
||||
{"op": "add-folder", "경로": [], "이름": "옹벽"}, # 이미 있음
|
||||
{"op": "move", "키": one, "새경로": ["옹벽"]},
|
||||
{"op": "rename", "경로": ["옹벽"], "이름": "석축"},
|
||||
):
|
||||
got = s.go(b + "나무", "POST", tree, {**body, "판": 판})
|
||||
판 = got.get("판", 판)
|
||||
s.go(b + "나무", "POST", tree, {"op": "add-folder", "경로": [], "이름": "x", "판": "옛판"})
|
||||
|
||||
paste = {"from_layer": "personal", "대상": [{"경로": ["석축"]}], "경로": []}
|
||||
s.go(b + "붙여넣기", "POST", f"{tree}/paste", paste)
|
||||
s.go(b + "붙여넣기", "POST", f"{tree}/paste", {**paste, "대상": [{"경로": ["없음"]}]})
|
||||
|
||||
with store.at(world["personal"]): # 쓰는 곳 = 구조물 조합 열(740-1)
|
||||
ref = {"참조": {"층": "personal", "주인": "7/42", "키": two}, "수량": {"손": 2}}
|
||||
store.write("labor", f"u{kind}", "", {"열": f"u{kind}", "담은로직": [ref], "자재": []})
|
||||
s.go(b + "쓰는곳", "POST", f"{tree}/delete-check", {"대상": [{"키": two}]})
|
||||
s.go(b + "쓰는곳", "POST", f"{tree}/delete-check", {"대상": [{"경로": ["석축"]}]})
|
||||
|
||||
판 = s.go(b + "나무", "GET", tree)["판"]
|
||||
s.go(b + "지우기", "POST", tree, {"op": "delete", "대상": [{"키": two}], "판": 판})
|
||||
gone = s.go(
|
||||
b + "지우기", "POST", tree, {"op": "delete", "대상": [{"키": two}], "판": 판, "확인": True}
|
||||
)
|
||||
s.go(b + "지우기", "GET", f"{P}/templates/{kind}/{two}")
|
||||
s.go(b + "지우기", "GET", f"{P}/templates/labor/u{kind}")
|
||||
spare_판 = s.go(b + "읽기", "GET", f"{P}/templates/{kind}/{spare}")["판"]
|
||||
s.go(b + "지우기", "DELETE", f"{P}/templates/{kind}/{spare}") # 판 없음
|
||||
s.go(b + "지우기", "DELETE", f"{P}/templates/{kind}/{spare}?판={spare_판}")
|
||||
s.go(b + "지우기", "DELETE", f"{P}/templates/{kind}/{spare}?판={spare_판}")
|
||||
|
||||
record = (gone.get("알림") or {}).get("기록")
|
||||
s.go(b + "되돌림", "POST", f"{P}/{kind}-same/undo", {"키": record or "없음"})
|
||||
s.go(b + "되돌림", "GET", f"{P}/templates/labor/u{kind}")
|
||||
s.go(b + "되돌림", "POST", f"{P}/{kind}-same/undo", {"키": "없음"})
|
||||
|
||||
found = s.go(b + "중복", "GET", f"{P}/{kind}-same")
|
||||
keep = {"층": "personal", "주인": "7/42", "키": twin}
|
||||
merge = {"남김": keep, "지움": [one], "판": found["판"]}
|
||||
s.go(b + "합치기", "POST", f"{P}/{kind}-same/merge", {**merge, "판": "옛판"})
|
||||
s.go(b + "합치기", "POST", f"{P}/{kind}-same/merge", merge)
|
||||
s.go(b + "되돌림", "POST", f"{P}/{kind}-same/undo", {"키": one})
|
||||
s.go(b + "목록", "GET", f"{P}/templates")
|
||||
s.go(b + "나무", "GET", tree)
|
||||
|
||||
|
||||
def _items(s: Shelf) -> None:
|
||||
tree = f"{P}/tree"
|
||||
판 = s.go("항목.나무", "GET", tree)["판"]
|
||||
for body in (
|
||||
{"op": "add-folder", "경로": [], "이름": "배수"},
|
||||
{"op": "add-item", "경로": ["배수"], "이름": "sub4임시측구", "단위": "m"},
|
||||
{"op": "add-item", "경로": [], "이름": "sub4임시옹벽", "단위": "m"},
|
||||
{"op": "rename", "경로": ["배수"], "이름": "수로"},
|
||||
{"op": "move", "경로": ["sub4임시옹벽"], "새경로": ["수로"]},
|
||||
{"op": "add-folder", "경로": [], "이름": "수로"}, # 이미 있음
|
||||
):
|
||||
got = s.go("항목.나무", "POST", tree, {**body, "판": 판})
|
||||
판 = got.get("판", 판)
|
||||
s.go("항목.나무", "POST", tree, {"op": "add-folder", "경로": [], "이름": "x", "판": "옛판"})
|
||||
s.go("항목.목록", "GET", "/api/m02/items?layer=personal")
|
||||
s.go("항목.목록", "GET", "/api/m02/items")
|
||||
paste = {"from_layer": "personal", "대상": [{"경로": ["수로"]}], "경로": []}
|
||||
s.go("항목.붙여넣기", "POST", f"{P}/items/paste", paste)
|
||||
system = s.go("항목.목록", "GET", "/api/m02/items")
|
||||
key = system[0]["key"] if system else "없음"
|
||||
s.go("항목.복사", "POST", f"{P}/items/copy", {"from_layer": "system", "key": key})
|
||||
s.go("항목.복사", "POST", f"{P}/items/copy", {"from_layer": "system", "key": "SS-999999"})
|
||||
판 = s.go("항목.나무", "GET", tree)["판"]
|
||||
s.go("항목.지우기", "POST", tree, {"op": "delete", "경로": ["수로(1)"], "판": 판})
|
||||
s.go("항목.나무", "GET", tree)
|
||||
|
||||
|
||||
def _machines(s: Shelf) -> None:
|
||||
m = f"{P}/my-machines"
|
||||
easy = {"이름": "sub4임시기계", "규격": "1㎾", "방식": "바로"}
|
||||
easy["값"] = {"가격": 1000, "손료계수": 2000, "주연료": 0, "주연료종류": "경유"}
|
||||
made = s.go("내기계.만들기", "POST", m, {"줄": easy})
|
||||
key = made.get("줄", {}).get("키", "없음")
|
||||
s.go("내기계.목록", "GET", m)
|
||||
one = s.go("내기계.읽기", "GET", f"{m}/{key}")
|
||||
fixed = {**easy, "값": {**easy["값"], "가격": 3000}}
|
||||
s.go("내기계.고치기", "PUT", f"{m}/{key}", {"줄": fixed, "판": one.get("판")})
|
||||
s.go("내기계.고치기", "PUT", f"{m}/{key}", {"줄": fixed, "판": one.get("판")}) # 옛 판
|
||||
s.go("내기계.쓰는곳", "POST", f"{m}/{key}/impact", {"줄": fixed})
|
||||
s.go("내기계.찾기", "GET", f"{P}/my-machine-find?q=sub4")
|
||||
s.go("내기계.목록", "GET", "/api/m02/layers/company/my-machines")
|
||||
s.go("내기계.지우기", "DELETE", f"{m}/{key}")
|
||||
s.go("내기계.지우기", "GET", f"{m}/{key}")
|
||||
|
||||
|
||||
def _materials(s: Shelf) -> None:
|
||||
m = f"{P}/materials"
|
||||
bolt = {"이름": "sub4임시볼트", "규격": "M16", "단위": "EA", "값": 1200}
|
||||
key = s.go("내재료.만들기", "POST", m, bolt).get("키", "없음")
|
||||
s.go("내재료.만들기", "POST", m, {**bolt, "규격": "M20"})
|
||||
s.go("내재료.만들기", "POST", "/api/m02/layers/company/materials", bolt)
|
||||
s.go("내재료.목록", "GET", m)
|
||||
s.go("내재료.목록", "GET", "/api/m02/layers/company/materials")
|
||||
s.go("내재료.고치기", "PUT", f"{m}/{key}", {**bolt, "값": 1500})
|
||||
s.go("내재료.지우기", "DELETE", f"{m}/{key}")
|
||||
s.go("내재료.지우기", "DELETE", f"{m}/{key}")
|
||||
s.go("내재료.목록", "GET", m)
|
||||
|
||||
|
||||
def _share(s: Shelf) -> None:
|
||||
url = "/api/m02/share-requests"
|
||||
item = s.go("공유.요청", "GET", "/api/m02/items?layer=personal")[0]["key"]
|
||||
pre = s.go("공유.요청", "POST", f"{P}/library/precombo", {"문서": _doc("precombo", "공유", 7)})
|
||||
one = s.go("공유.요청", "POST", url, {"종류": "item", "키": item, "글": " 회사 공용 "})
|
||||
s.go("공유.요청", "POST", url, {"종류": "item", "키": item}) # 요청 중
|
||||
two = s.go("공유.요청", "POST", url, {"종류": "precombo", "키": pre["이름"]})
|
||||
s.go("공유.요청", "POST", url, {"종류": "precombo", "키": "SC-999999"})
|
||||
s.go("공유.목록", "GET", url)
|
||||
s.go("공유.승인", "POST", f"{url}/{one['id']}/approve", {"경로": []}) # 일반 = 403
|
||||
s.who(STRANGER)
|
||||
s.go("공유.목록", "GET", url)
|
||||
s.go("공유.승인", "POST", f"{url}/{one['id']}/approve", {"경로": []})
|
||||
s.who(ADMIN)
|
||||
s.go("공유.목록", "GET", url)
|
||||
s.go("공유.승인", "POST", f"{url}/{one['id']}/approve", {"경로": []})
|
||||
s.go("공유.승인", "POST", f"{url}/{one['id']}/approve", {"경로": []}) # 이미 끝남
|
||||
s.go("공유.거절", "POST", f"{url}/{two['id']}/reject", {"사유": " 겹침 "})
|
||||
s.go("공유.목록", "GET", "/api/m02/items?layer=company")
|
||||
s.who(USER)
|
||||
s.go("공유.목록", "GET", url)
|
||||
s.go("공유.봄", "POST", f"{url}/seen")
|
||||
s.go("공유.봄", "POST", f"{url}/seen")
|
||||
|
||||
|
||||
READS = { # 남의 층 읽기 길(주인 붙임)
|
||||
"목록": "/api/m02/layers/personal/templates",
|
||||
"단가산출나무": "/api/m02/layers/personal/sangeun-tree",
|
||||
"일위대가나무": "/api/m02/layers/personal/precombo-tree",
|
||||
"항목나무": "/api/m02/layers/personal/tree",
|
||||
"내기계": "/api/m02/layers/personal/my-machines",
|
||||
"내재료": "/api/m02/layers/personal/materials",
|
||||
}
|
||||
|
||||
|
||||
def _access(s: Shelf) -> None:
|
||||
people = {"일반": USER, "같은회사남": NEIGHBOR, "회사관리": ADMIN, "시스템": SYSADMIN}
|
||||
people["남의회사관리"] = STRANGER
|
||||
for n, (name, person) in enumerate(people.items()):
|
||||
s.who(person)
|
||||
for owner in ("7/42", "7/44"): # 44 = 아직 층 없음
|
||||
for what, url in READS.items():
|
||||
s.go(f"권한.{name}", "GET", f"{url}?owner={owner}")
|
||||
s.go(f"권한.{name}", "GET", "/api/m02/layers/company/sangeun-tree")
|
||||
s.go(f"권한.{name}", "GET", "/api/m02/layers/system/sangeun-tree")
|
||||
new = {"문서": _doc("sangeun", f"권한{name}", 90 + n)} # 사람마다 다른 내용
|
||||
s.go(f"권한.{name}", "POST", "/api/m02/layers/company/library/sangeun", new)
|
||||
s.go(f"권한.{name}", "POST", "/api/m02/layers/system/library/sangeun", new)
|
||||
s.go(f"권한.{name}", "POST", f"{P}/library/sangeun?owner=7/42", new)
|
||||
s.go(f"권한.{name}", "GET", f"{P}/sangeun-same?owner=7/42")
|
||||
s.who(USER)
|
||||
|
||||
|
||||
def test_서고_길_답_지문(shelf, world):
|
||||
for kind in ("sangeun", "precombo"):
|
||||
_library(shelf, world, kind)
|
||||
_items(shelf)
|
||||
_machines(shelf)
|
||||
_materials(shelf)
|
||||
_share(shelf)
|
||||
_access(shelf)
|
||||
now = {k: _finger(v) for k, v in sorted(shelf.got.items())}
|
||||
if dump := os.environ.get("SHELF_858_DUMP"): # 전후 답 통째 대조용(자기 tmp/ 에)
|
||||
Path(dump).write_text(
|
||||
json.dumps(shelf.got, ensure_ascii=False, indent=1, default=str), "utf-8"
|
||||
)
|
||||
if os.environ.get(WRITE):
|
||||
text = json.dumps({"갈래": now}, ensure_ascii=False, indent=1) + "\n"
|
||||
GOLD.write_bytes(text.encode()) # 줄 끝 LF
|
||||
was = json.loads(GOLD.read_bytes())["갈래"]
|
||||
bad = sorted(k for k in now.keys() | was.keys() if now.get(k) != was.get(k))
|
||||
if bad:
|
||||
shown = {k: shelf.got.get(k) for k in bad}
|
||||
text = json.dumps(shown, ensure_ascii=False, default=str)[:4000]
|
||||
pytest.fail(
|
||||
f"서고 길 답 지문이 다름 — 갈래 {bad}\n지금 답: {text}\n"
|
||||
f"뜻한 바뀜이면 다시 뜸: {WRITE}=1 ./venv/Scripts/python.exe -m pytest {__file__}"
|
||||
)
|
||||
|
||||
|
||||
# ── ② 동시 쓰기 — 잠금 없는 여러 파일 쓰기(설계 858 1-4 「잠금 없는 쓰기」 · 5-4 몫) ─────────
|
||||
def _two(first, second, meet: list[tuple[Any, str]], late: tuple[Any, str]):
|
||||
"""둘을 같이 돌림 — 둘 다 판 대조를 지난 뒤 `meet` 함수 앞에서 만나고, 그 뒤 `second` 쪽
|
||||
`late` 함수를 늦춤 → (먼저 답 · 나중 답 — 예외면 예외)."""
|
||||
gate = threading.Barrier(2, timeout=10)
|
||||
slow = threading.local()
|
||||
saved = [(late[0], late[1], getattr(*late))] + [(o, n, None) for o, n in meet]
|
||||
|
||||
def later(*a, _real=saved[0][2], **k):
|
||||
if getattr(slow, "on", False):
|
||||
threading.Event().wait(0.3)
|
||||
return _real(*a, **k)
|
||||
|
||||
setattr(*late, later) # 안쪽 = 늦춤 · 바깥 = 만남(같은 함수면 만난 뒤 늦춤)
|
||||
for i, (owner, name, _) in enumerate(saved[1:], 1):
|
||||
inner = getattr(owner, name)
|
||||
saved[i] = (owner, name, inner)
|
||||
|
||||
def wait(*a, _inner=inner, **k):
|
||||
gate.wait()
|
||||
return _inner(*a, **k)
|
||||
|
||||
setattr(owner, name, wait)
|
||||
|
||||
def run(fn, is_late):
|
||||
slow.on = is_late
|
||||
try:
|
||||
return fn()
|
||||
except Exception as error: # 지금 사실(터짐)도 답으로
|
||||
return error
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(2) as pool:
|
||||
a = pool.submit(run, first, False)
|
||||
b = pool.submit(run, second, True)
|
||||
return a.result(), b.result()
|
||||
finally:
|
||||
for owner, name, real in reversed(saved):
|
||||
setattr(owner, name, real)
|
||||
|
||||
|
||||
def _sk(me: Path, name: str, price: int, again: bool = False) -> str:
|
||||
from M02_MasterTemplete import M02_Library_Ask as ask
|
||||
|
||||
with store.at(me):
|
||||
return ask.create("sangeun", _doc("sangeun", name, price), again, None)["이름"]
|
||||
|
||||
|
||||
def _edit(me: Path, body: dict[str, Any]):
|
||||
def go():
|
||||
with store.at(me):
|
||||
return pre_folders.edit(body, "sangeun", dict(USER))
|
||||
|
||||
return go
|
||||
|
||||
|
||||
def _folders(me: Path) -> list[list[str]]:
|
||||
with store.at(me):
|
||||
return pre_folders.view("sangeun")["폴더"]
|
||||
|
||||
|
||||
def test_동시_나무_고침_둘_다_됨_뒤_것이_이김(world):
|
||||
me = world["personal"]
|
||||
with store.at(me):
|
||||
판 = pre_folders.view("sangeun")["판"]
|
||||
first, second = _two(
|
||||
_edit(me, {"op": "add-folder", "경로": [], "이름": "가", "판": 판}),
|
||||
_edit(me, {"op": "add-folder", "경로": [], "이름": "나", "판": 판}),
|
||||
[(pre_folders, "apply_many")],
|
||||
(pre_folders, "atomic_write_json"),
|
||||
)
|
||||
assert first["알림"]["경로"] == ["가"] and second["알림"]["경로"] == ["나"] # 둘 다 됨
|
||||
assert _folders(me) == [["나"]] # 5-4 에서 뒤집을 단언 — 지금은 뒤 것이 이김(앞 「가」 사라짐)
|
||||
|
||||
|
||||
def test_동시_나무_지우기와_고침_둘_다_됨_뒤_것이_이김(world):
|
||||
me = world["personal"]
|
||||
gone = _sk(me, "지울것", 1000)
|
||||
with store.at(me):
|
||||
판 = pre_folders.view("sangeun")["판"]
|
||||
first, second = _two(
|
||||
_edit(me, {"op": "add-folder", "경로": [], "이름": "가", "판": 판}),
|
||||
_edit(me, {"op": "delete", "대상": [{"키": gone}], "판": 판}),
|
||||
[(pre_folders, "apply_many")],
|
||||
(pre_folders, "atomic_write_json"),
|
||||
)
|
||||
assert first["알림"]["경로"] == ["가"] and second["알림"]["기록"] # 둘 다 됨
|
||||
assert not (me / "sangeun" / f"{gone}.json").exists()
|
||||
assert _folders(me) == [] # 5-4 에서 뒤집을 단언 — 지금은 뒤 것(지우기)이 이김(「가」 사라짐)
|
||||
|
||||
|
||||
def test_동시_지우기와_합치기_앞_것이_이기고_뒤_것은_터짐(world):
|
||||
me = world["personal"]
|
||||
gone = _sk(me, "겹침", 1000)
|
||||
keep = _sk(me, "겹침", 1000, again=True)
|
||||
with store.at(me):
|
||||
판 = pre_folders.view("sangeun")["판"]
|
||||
body = same_router.MergeBody(
|
||||
남김={"층": "personal", "주인": "7/42", "키": keep}, 지움=[gone], 판=판
|
||||
)
|
||||
first, second = _two(
|
||||
_edit(me, {"op": "delete", "대상": [{"키": gone}], "판": 판}),
|
||||
lambda: same_router.merge(dict(USER), me, "sangeun", body),
|
||||
[(pre_folders, "apply_many"), (same_router, "_user_index")],
|
||||
(same_router, "_user_index"),
|
||||
)
|
||||
assert first["알림"]["기록"] == gone # 지우기 = 됨(기록 키 = 그 문서)
|
||||
# 5-4 에서 뒤집을 단언 — 지금은 뒤 합치기가 판 · 지문 대조를 지난 뒤 사라진 파일에서 터짐
|
||||
# (화면 = 500) · 5-4 뒤 = 409 · 파일 앞판 그대로
|
||||
assert isinstance(second, FileNotFoundError)
|
||||
assert not (me / "sangeun" / f"{gone}.json").exists()
|
||||
assert (me / "sangeun" / f"{keep}.json").is_file()
|
||||
assert [p.stem for p in (me / same_router.GONE).glob("*.json")] == [gone] # 지우기 기록만
|
||||
@@ -182,8 +182,15 @@ def test_올리기_목록_읽기_지우기(client):
|
||||
def test_엉터리_시트없음_큰_파일_400(client, monkeypatch):
|
||||
bad = _post(client, data=b"garbage", name="a.xls")
|
||||
assert bad.status_code == 400 and "읽지 못함" in bad.json()["detail"]
|
||||
none = _post(client, data=NO_SHEET.read_bytes(), name=NO_SHEET.name)
|
||||
book = io.BytesIO()
|
||||
import openpyxl
|
||||
|
||||
openpyxl.Workbook().save(book) # 일위대가 · 단가산출 시트 둘 다 없음
|
||||
none = _post(client, data=book.getvalue(), name="빈책.xlsx")
|
||||
assert none.status_code == 400 and none.json()["detail"] == "일위대가 시트 없음"
|
||||
only = _post(client, data=NO_SHEET.read_bytes(), name=NO_SHEET.name) # 857-1 단가산출만 = 올라감
|
||||
assert only.status_code == 200 and only.json()["호표수"] == 0
|
||||
assert client.delete(URL.format("personal") + "/" + only.json()["키"]).status_code == 200
|
||||
monkeypatch.setattr(hopyo_router, "HOPYO_MAX_BYTES", 1000)
|
||||
big = _post(client)
|
||||
assert big.status_code == 400 and "20 MB" in big.json()["detail"]
|
||||
|
||||
@@ -16,6 +16,7 @@ from M02_MasterTemplete import M02_Hopyo_ReadEst as hb
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hx
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as st
|
||||
from M02_MasterTemplete import M02_Hopyo_Store as hs
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
from M02_MasterTemplete import M02_Template_Layers as layers
|
||||
from resources.tester import test_m02_hopyo_excel as base
|
||||
from resources.tester.test_m02_hopyo_excel import ROOT, _post, master_hash
|
||||
@@ -129,7 +130,7 @@ def test_기계_자원_하나로(books):
|
||||
def test_노임_이름_어긋남_0(books):
|
||||
names = hb.trade_names()
|
||||
for tag in FILES:
|
||||
sheets = hx._sheets(_path(tag).name, _path(tag).read_bytes())
|
||||
sheets = workbook.read(_path(tag).name, _path(tag).read_bytes()).sheets
|
||||
table = st._lists(sheets)
|
||||
res = [r for b in books[tag]["단산"] for r in b["자원"] if r["갈래"] == "L" and r["이름"]]
|
||||
assert res
|
||||
|
||||
@@ -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