feat(847-1): 기계 작업량 방식에 따라 안 고른 쪽 숨김 · 시간당 식이면 기계 굳음 · 기계 밖 겹분수 55 줄 나눔

- 숨김 규칙(formula_doc_render hiddenByWork) — 금액 줄에서 따라가 시간당 식 줄이 더 안 읽는 기호만 숨김(옵션 가로 · 공식 묶음 · 산출근거) · 보이기만(문서 값 · 식 그대로)
- 기계 굳음 — 시간당으로 바꿀 때 그 줄 기계를 덮음 `기계`에 담음 · 셈은 그 줄 단가를 굳은 기계로 다시 부름(계산기 단가 범위) · 작업량 식 · 변수도 그 기계 것 · 셈 답 `작업량.고정` · `기호`
- 덮음 열쇠 = 그 줄 단가 기호(옵션이 기계를 바꿔도 같은 줄) › 기계 열쇠(846-1 옛 꼴 그대로 읽음) · 서버 정리 기본 변수 = 굳은 기계 작업량 칸 · 사본 부름에 굳은 기계 식 문서
- 기계 창으로 바꿈 — 새 기계 작업량 식 · 규격 변수로 다시 차림(같은 식 = 현장 변수 남김 · 다른 식 = 버림 + 알림 · 맞는 식 없음 = 품셈 일당 + 알림)
- 수량 칸 = 「1 ÷ 시간당 작업량」 읽기 글 · 방식 하나뿐인 줄 = 고르기 없음
- 기계 밖 두 층 분수 = 짝 나란히 · 곱의 분수 항 펼침 · 중간 줄 이름(문서 키 사전)
- 시험: test_847_1_work_hide 새로 · test_846_2 「식 없는 기계 잠김 글」 → 고르기 없음(요구 884 차림 바뀜) · test_846_1 셈 답 `기호` 칸 더함 · test_802_4b2 소스 글자 보는 줄(옵션 호출 글 · 사본 단추 글) 지움(규칙 — 결과 시험 아님 · 읽기만은 같은 시험의 403 이 봄)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 11:56:32 +09:00
co-authored by Claude Opus 5.5
parent f07734cf98
commit 114c3100f1
22 changed files with 650 additions and 107 deletions
+3 -1
View File
@@ -4,6 +4,7 @@
* 값 = 화면 값(`given`) › 문서 값 · 고침은 부른 쪽 `set`(M01 = 화면 값만 · M02 사본 = 문서 값) · `lock` = 읽기만
* 목록이 모두 기계 원문번호(`0101-0007`)면 글 = 「이름 규격 (원문번호)」(요구 692-2 · 값은 그대로 · 이름은 한 번 받아 둠)
* `view` 있음 + 기계 목록 = 곁에 [조회](827-1 · 기계 창 읽기 전용 · 고른 기계)
* `hide` = 안 그릴 기호(847-1 시간당 식 줄이 안 읽게 된 옵션 · 값은 그대로)
* ========================================================================== */
import { createButton } from "@ui/ui_template_button";
@@ -60,12 +61,13 @@ export function buildOptions(
lock: boolean,
set: (key: string, v: DocVar, value: unknown) => void,
view?: (code: string) => void,
hide: Set<string> = new Set(),
): HTMLElement[] {
const out: HTMLElement[] = [];
for (const v of doc?.변수 ?? []) {
const kind = v.연결?.갈래;
const k = v.열쇠;
if (!k || (kind !== "선택" && kind !== "입력")) continue;
if (!k || (kind !== "선택" && kind !== "입력") || hide.has(varId(v))) continue;
const label = v.이름 || varId(v);
const now = k in given ? given[k] : v.연결?.값;
if (kind === "선택") {
+31 -3
View File
@@ -2,6 +2,9 @@
* formula_doc_render.ts
* 수식 문서 닿는 기호(PLAN 802-3 · 804-6) — 줄 쌓기 산출근거(`line_stack_out.ts`)가 씀
* reach = 지금 탄 갈래로 닿는 기호(만약 안 탄 갈래 · 숨김 자리 인자 빼고)
* hiddenByWork(847-1 · 요구 884 · 885) = 시간당 식 기계 줄 때문에 안 쓰이게 된 기호 — 금액 줄에서 따라가
* (그 줄 수량 = 작업량 자리를 「1 ÷ Q」 로 · 굳은 기계 = 기계 입력 글) 닿던 것 가운데 이제 어느 살아 있는 줄도
* 안 읽는 것(옵션 · 공식 묶음 · 산출근거에서 숨김 · 보이기만 — 문서 값 · 식 그대로) · 시간당 줄 없음 = 빈 묶음
* 옛 수식 문서 탭의 조판 그림(renderNode · 값 식 · 수 바꿈)은 804-6 에 걷음
* ========================================================================== */
@@ -17,6 +20,9 @@ import {
tryParse,
type Values,
} from "../common_util/common_util_formula_doc_view";
import type { DocAnswer } from "../common_util/common_util_formula_doc_calc";
import { fixedVar, HOURLY, machineOf, swap } from "../common_util/common_util_formula_doc_work";
import { workAt } from "../common_util/common_util_line_stack_work";
/** 탄 갈래로 부르는 이름(만약 안 탄 갈래 · 숨김 자리 인자 빼고) */
function namesTaken(n: Node, vals: Values, out: string[] = []): string[] {
@@ -48,8 +54,9 @@ function namesTaken(n: Node, vals: Values, out: string[] = []): string[] {
const RESERVED_MONEY = new Set(["노무비", "재료비", "경비", "번지", "단계"]);
/** 정의 영역에 보일 기호 — 식 줄 · 금액 줄 · 결과에서 지금 탄 갈래로 닿는 것(보이는 차례) */
export function reach(doc: FormulaDoc, vals: Values, showOff = false): string[] {
/** 정의 영역에 보일 기호 — 식 줄 · 금액 줄 · 결과에서 지금 탄 갈래로 닿는 것(보이는 차례) ·
* `fromMoney` = 식 줄을 뿌리로 안 삼음(금액 줄 · 결과에서만 따라감) */
export function reach(doc: FormulaDoc, vals: Values, showOff = false, fromMoney = false): string[] {
const vars = new Map((doc.변수 ?? []).map((v) => [varId(v), v]));
const lines = new Map((doc.식 ?? []).map((l) => [String(l.기호 ?? ""), l.식]));
const money = new Set((doc.금액 ?? []).map((l) => String(l.기호 ?? "")).filter(Boolean));
@@ -68,7 +75,7 @@ export function reach(doc: FormulaDoc, vals: Values, showOff = false): string[]
const n = tryParse(text);
if (n) namesTaken(n, vals).forEach(visit);
};
for (const l of doc.식 ?? []) {
for (const l of fromMoney ? [] : (doc.식 ?? [])) {
visit(String(l.기호 ?? ""));
from(l.식);
}
@@ -80,3 +87,24 @@ export function reach(doc: FormulaDoc, vals: Values, showOff = false): string[]
if (doc.결과) visit(String(doc.결과));
return out;
}
/** 시간당 식 기계 줄 때문에 아무 살아 있는 줄도 안 읽게 된 기호(셈 답 줄 `작업량.꼴` = 시간당) */
export function hiddenByWork(doc: FormulaDoc, a: DocAnswer | null | undefined): Set<string> {
const money = doc.금액 ?? [];
const hits = money.flatMap((_, i) => {
const w = workAt(a, i);
return w && w.꼴 === HOURLY ? [{ i, w }] : [];
});
if (!hits.length) return new Set();
const now = JSON.parse(JSON.stringify(doc)) as FormulaDoc;
const vars = new Map((now.변수 ?? []).map((v) => [varId(v), v]));
for (const { i, w } of hits) {
now.금액![i].수량 = swap(doc, money[i].수량);
const m = w.고정 ? machineOf(vars, money[i]) : null;
const v = m?.main ? vars.get(m.name) : undefined;
if (v) v.연결 = fixedVar(v, { 방식: HOURLY, 기계: w.고정 }).연결;
}
const vals = (a?.값 ?? {}) as Values;
const after = new Set(reach(now, vals, false, true));
return new Set(reach(doc, vals, false, true).filter((x) => !after.has(x)));
}
+51 -14
View File
@@ -20,7 +20,10 @@ import { varId, type FormulaDoc, type MoneyLine } from "../common_util/common_ut
import { isNum, type DocAnswer } from "../common_util/common_util_formula_doc_calc";
import { lineMap, offLine, type Values } from "../common_util/common_util_formula_doc_view";
import type { DocTable } from "../common_util/common_util_formula_doc_table";
import { coverOf } from "../common_util/common_util_formula_doc_cover";
import { coverOf, type CoverEntry } from "../common_util/common_util_formula_doc_cover";
import { HOURLY, Q_NEW, swap, workKey } from "../common_util/common_util_formula_doc_work";
import { workAt } from "../common_util/common_util_line_stack_work";
import { machineText } from "./formula_doc_options";
import {
dropSyms,
docOf,
@@ -49,11 +52,12 @@ import {
} from "../common_util/common_util_line_stack_pick";
import { shownUnitOf, type TableLook } from "../common_util/common_util_line_stack_unit";
import { createUnitPick, NO_UNIT } from "../M02_MasterTemplete/DataFlow/M02_DF_UnitPick";
import { reach } from "./formula_doc_render";
import { hiddenByWork, reach } from "./formula_doc_render";
import { attachDrag } from "./line_stack_drag";
import type { WorkSpec } from "../common_util/common_util_formula_doc_work";
import { openMachineWindow, type MachineCtx } from "./line_stack_machine";
import { buildMachineCtl, machineOfLine } from "./line_stack_machine_ctl";
import { buildMachineCtl, lineCall } from "./line_stack_machine_ctl";
import { putWork, swapMachine } from "./line_stack_machine_work";
import { openStackPick, type StackTake } from "./line_stack_pick";
import { buildBlock, sourceTag } from "./line_stack_rows";
import { lt, type LsKey } from "./line_stack_text";
@@ -160,6 +164,8 @@ function moneyBody(h: EditHooks, i: number): HTMLElement[] {
const shown = (t: unknown): string => aliasText(String(t ?? ""), alias);
const real = (t: string): string => aliasText(t.trim(), alias, true);
const head: HTMLElement[] = [];
const w = kind === "기계" ? workAt(h.answer, i) : null;
const hourly = w?.꼴 === HOURLY; // 847-1 시간당 식 줄 — 기계 = 굳은 기계 · 수량 = 읽기 글
if (own && v) {
// 이름 단추(요구 687-9) — 누르면 찾아 넣기 창이 그 이름을 찾은 채 열림 · 고르면 바꿈
const link = v.연결 ?? {};
@@ -181,8 +187,22 @@ function moneyBody(h: EditHooks, i: number): HTMLElement[] {
});
if (kind === "재료") void askFileWide(h.machine, d, own, p); // 827-3 같은 파일 같은 재료
};
// 847-1 시간당 식 줄 = 굳은 기계를 덮음으로 바꿈(문서 줄 연결은 그대로 — 일당으로 되돌리면 옵션 기계)
const wkey = w ? workKey(coverOf(d), w) : "";
const want = hourly ? (coverOf(d)[wkey] as CoverEntry | undefined)?.작업량 : undefined;
const fixed = hourly && w?.고정 ? w.고정 : "";
const swapFixed = (p: Picked): void => {
const got = swapMachine(want ?? { 방식: HOURLY }, w!, p, p.키 === link.키, h.work?.(fixed) ?? []); // prettier-ignore
h.change((doc) => putWork(doc, wkey, got.next));
if (got.note) showToast(got.note, "info");
};
const label = fixed
? want?.이름 || machineText(fixed, () => h.change(() => undefined)) || name
: size && !name.includes(size)
? `${name} ${size}`
: name;
const pick = createButton({
label: (size && !name.includes(size) ? `${name} ${size}` : name) || "—",
label: label || "—",
variant: "ghost",
tone: "link",
size: 24,
@@ -191,10 +211,10 @@ function moneyBody(h: EditHooks, i: number): HTMLElement[] {
kind === "기계" && h.machine // 827-1 기계 창
? openMachineWindow({
ctx: h.machine,
drafts: draftsOf(d),
now: machineNow(d, link as { 갈래?: string; 입력?: Record<string, string> }),
drafts: fixed ? [] : draftsOf(d),
now: fixed || machineNow(d, link as { 갈래?: string; 입력?: Record<string, string> }), // prettier-ignore
query,
pick: swap,
pick: fixed ? swapFixed : swap,
})
: openStackPick(kind, swap, undefined, query),
});
@@ -217,8 +237,9 @@ function moneyBody(h: EditHooks, i: number): HTMLElement[] {
});
t.dataset.mctlToggle = String(i);
head.push(t);
const m = machineOfLine(h.answer, link);
if (m && coverOf(d)[m]) head.push(createBadge(lt("Ctl_Changed"), "info", { size: 18 }));
const m = lineCall(d, h.answer, link, i);
if (coverOf(d)[m.work] || coverOf(d)[String(m.given.기계 ?? "")])
head.push(createBadge(lt("Ctl_Changed"), "info", { size: 18 }));
}
const mark = machineMark(found, link);
if (mark) head.push(mark);
@@ -279,7 +300,11 @@ function moneyBody(h: EditHooks, i: number): HTMLElement[] {
el("span", { className: "lstk-kind", text: lt(bare ? "K_소계" : KIND_KEY[kind]) }),
...head,
// 율 · 식 줄(자원 없음)에 수량이 없으면 칸 안 보임(한 줄 유지)
...(own || String(line.수량 ?? "") ? [qtyBox(h, i, shown, real)] : []),
...(hourly
? [workQtyBox(h.doc, line.수량, shown)]
: own || String(line.수량 ?? "")
? [qtyBox(h, i, shown, real)]
: []),
unit,
...(line.비목 === "묶음" || bare
? []
@@ -337,6 +362,18 @@ function qtyBox(
return el("span", { className: "lstk-qty", children: tag ? [f, tag] : [f] });
}
/** 847-1 시간당 식 줄 수량 = 「1 ÷ 시간당 작업량」 읽기 글(손으로 못 고침 — 변수는 제어 구역) */
function workQtyBox(doc: FormulaDoc, qty: unknown, shown: (t: unknown) => string): HTMLElement {
const f = field(lt("Qty"), shown(swap(doc, qty)).replace(Q_NEW, lt("Work_Head")), () => undefined); // prettier-ignore
const input = f.querySelector("input");
if (input) {
input.disabled = true;
input.title = lt("Work_Qty_Note");
}
f.dataset.workQty = "";
return el("span", { className: "lstk-qty", children: [f] });
}
/** [+ 줄] 고르개 값 → 새 줄 */
function addLine(h: EditHooks, at: number, kind: string): void {
if (["인력", "재료", "기계", "단가산출"].includes(kind))
@@ -439,13 +476,13 @@ export function buildEdit(h: EditHooks): HTMLElement {
const vals = (h.answer.값 ?? {}) as Values;
const taken = new Set(reach(h.doc, vals));
const every = new Set(reach(h.doc, {}, true));
const gone = hiddenByWork(h.doc, h.answer); // 847-1 시간당 식 줄이 안 읽게 된 기호
const unused = (id: string): boolean => (every.has(id) && !taken.has(id)) || gone.has(id);
const steps = lineMap(h.doc);
const off = (line: StackItem["줄"][number]): boolean =>
line.꼴 === "금액"
? offLine((h.doc.금액 ?? [])[line.i] ?? {}, vals, steps)
: line.꼴 === "공식" &&
line.기호.length > 0 &&
line.기호.every((id) => every.has(id) && !taken.has(id));
: line.꼴 === "공식" && line.기호.length > 0 && line.기호.every(unused);
const items = h.items.map((it, i) => {
const folded = h.open.has(`fold:${i}`);
const itemGrip = grip();
@@ -501,7 +538,7 @@ export function buildEdit(h: EditHooks): HTMLElement {
"l",
),
]
: buildBlock(h, i, j, line, (id) => every.has(id) && !taken.has(id));
: buildBlock(h, i, j, line, unused);
// 금액 · 글 = 한 줄(X 끝) · 공식 묶음 = 머리 줄 끝에 X
const card = el("div", {
className: `lstk-line k-${line.꼴}`,
+6 -2
View File
@@ -78,6 +78,8 @@ interface Shown {
spec: string;
lines: HTMLElement[];
logic?: string | null;
/** 847-1 그 기계 값 칸 `작업량` */
work?: unknown;
}
const kindOf = (no: string): Kind =>
@@ -226,7 +228,7 @@ export function openMachineWindow(o: MachineWindowOptions): void {
lines.push(createText(mt("Win_Draft"), "muted"));
if (d.시간당)
lines.push(createText(`${mt("Server_Hourly")} ${hourlyText(d.시간당 as MyHourly)}`));
return { name: d.줄.이름, spec: d.줄.규격, lines, logic: d.시간당?.로직 };
return { name: d.줄.이름, spec: d.줄.규격, lines, logic: d.시간당?.로직, work: d.줄.값?.작업량 }; // prettier-ignore
}
// 지금 줄 = 이 단가산출 사본 값(있으면)
const copy = c.kind === "now" && ctx.copyRow ? await ctx.copyRow(c.no).catch(() => null) : null;
@@ -243,6 +245,7 @@ export function openMachineWindow(o: MachineWindowOptions): void {
spec: row?.규격 ?? m?.규격 ?? c.규격,
lines,
logic: m?.시간당.로직,
work: (m?.값 as Record<string, unknown> | undefined)?.작업량,
};
}
const b = await briefOf(c.no, c.key);
@@ -253,13 +256,14 @@ export function openMachineWindow(o: MachineWindowOptions): void {
spec: row?.규격 ?? b?.규격 ?? c.규격,
lines,
logic: b?.시간당.ok ? b.시간당.로직 : null,
work: (b?.값 as Record<string, unknown> | undefined)?.작업량,
};
};
const pickedOf = (c: Cand, s: Shown): Picked | null => {
if (!s.logic) return null;
const no = c.kind === "mine" && c.mine ? machineArg(c.mine.원문번호) : `'${c.no}'`;
return { 키: s.logic, 이름: s.name, 입력: { 기계: no }, ...(s.spec ? { 규격: s.spec } : {}) };
return { 키: s.logic, 이름: s.name, 입력: { 기계: no }, ...(s.spec ? { 규격: s.spec } : {}), 작업량: s.work }; // prettier-ignore
};
const choose = async (c: Cand): Promise<void> => {
+26 -14
View File
@@ -5,6 +5,7 @@
* ㉡ 조종원 = 인력 줄(노임 고르기 · 인/일 · 더하기 · 빼기 · 기본 = 기계 값 조종원 · 직종)
* ㉢ 잡품 = 재료 줄(재료 · 유가 고르기 · 수량 · 율 % · 기본 = 밑 재료 줄 · 품셈 잡재료율)
* ㉣ 시간당 작업량(846-2 · 맨 위) = 일당 / 시간당 식 고르기 · 시간당 변수 칸(`line_stack_machine_work`)
* 굳은 기계(847-1) = 값 · 조종원 · 잡품은 그 기계 것(덮음 열쇠 = 그 기계) · 작업량 덮음은 줄 기계 열쇠(`lineCall`)
* 고침 = 문서 칸 `기계덮음`(캐시 · [저장] 때 서버가 정본으로 다시 셈) · 원본과 같으면 지움(`putCover`)
* 기본값 = 덮음 없이 셈한 그 기계 식 답 + 기계 줄 인력 · 잡품 목록(`defaultsOf` · `rowEntry` · 842-3) ·
* 읽기(M01 기초) = 칸 잠김 · 단추 없음
@@ -18,6 +19,7 @@ import { eqText } from "@ui/ui_template_equation";
import { el, showToast } from "@ui/ui_template_elements";
import { createInputField, createSelectField } from "@ui/ui_template_input";
import { varId, type FormulaDoc, type Link } from "../common_util/common_util_formula_doc";
import { WORK, workKey, type WorkCover } from "../common_util/common_util_formula_doc_work";
import type { DocAnswer } from "../common_util/common_util_formula_doc_calc";
import {
coverOf,
@@ -37,7 +39,7 @@ import { workAt, workOfMachine } from "../common_util/common_util_line_stack_wor
import { sites, type WorkSpec } from "../common_util/common_util_formula_doc_work";
import { machineCellName } from "../common_util/common_util_machine_symbol_name";
import { openFindPicker } from "../M02_MasterTemplete/M02_MasterTemplete_Find_Pick";
import { buildWorkGroup } from "./line_stack_machine_work";
import { buildWorkGroup, putWork } from "./line_stack_machine_work";
import { openStackPick } from "./line_stack_pick";
import { lt } from "./line_stack_text";
@@ -61,18 +63,27 @@ export interface CtlHooks {
const FUELS = ["경유", "휘발유", "실내등유"];
/** 그 줄 기계 열쇠 — 부를 입력을 지금 값으로 셈(옵션 · 만약 식 기호도) · 기계 줄 아님 = "" */
export const machineOfLine = (answer: DocAnswer, link: Link | undefined): string =>
link?.갈래 === "단가산출"
? machineKey(subInputs(link, (answer.값 ?? {}) as Record<string, unknown>))
: "";
/** 그 기계 줄 부름 — 입력 · 기계 식 문서 · 작업량 덮음 열쇠(줄 기계) · 굳은 기계(847-1)면 입력 기계 = 그 기계 */
export function lineCall(
doc: FormulaDoc,
answer: DocAnswer,
link: Link | undefined,
at?: number,
): { given: Record<string, unknown>; key: string; work: string; want?: WorkCover } {
const given = subInputs(link, (answer.값 ?? {}) as Record<string, unknown>);
const w = at === undefined ? null : workAt(answer, at);
const work = w ? workKey(coverOf(doc), w) : machineKey(given);
const want = w ? (coverOf(doc)[work] as CoverEntry | undefined)?.[WORK] : undefined;
if (w?.고정) given.기계 = w.고정;
return { given, key: (w?.고정 && want?.키) || String(link?.키 ?? ""), work, want };
}
/** 그 기계 줄의 기계 열쇠 · 식 · 원본 기본값 — 기계 식이 아니면 null */
export function ctlOf(h: CtlHooks, link: Link | undefined) {
export function ctlOf(h: CtlHooks, link: Link | undefined, at?: number) {
if (link?.갈래 !== "단가산출" || !link.키) return null;
const given = subInputs(link, (h.answer.값 ?? {}) as Record<string, unknown>);
const { given, key } = lineCall(h.doc, h.answer, link, at);
const machine = machineKey(given);
const sub = h.subDoc(link.키);
const sub = h.subDoc(key);
if (!machine || !sub) return null;
const orig = h.calc(sub, given);
const vals = (orig.값 ?? {}) as Record<string, unknown>;
@@ -127,7 +138,7 @@ export function buildMachineCtl(
link: Link | undefined,
at?: number,
): HTMLElement | null {
const got = ctlOf(h, link);
const got = ctlOf(h, link, at);
if (!got) return null;
const { machine, sub, vals, base } = got;
const entry: CoverEntry = got.entry ?? {};
@@ -279,19 +290,20 @@ export function buildMachineCtl(
]),
],
});
// ㉣ 시간당 작업량(846-2)
// ㉣ 시간당 작업량(846-2) — 덮음 열쇠 = 줄 기계(굳은 기계면 값 칸 열쇠와 다름 · 847-1)
const info = (at === undefined ? null : workAt(h.answer, at)) ?? workOfMachine(h.answer, machine);
const wkey = info ? workKey(coverOf(h.doc), info) : machine;
const work = info
? buildWorkGroup({
doc: h.doc,
info,
kind: info.꼴 === "시간당" ? (sites(h.doc, h.doc.금액?.[at ?? -1]?.수량)[0]?.꼴 ?? "일당") : info.꼴, // prettier-ignore
entry: entry.작업량,
specs: h.work?.(machine) ?? [],
entry: (coverOf(h.doc)[wkey] as CoverEntry | undefined)?.작업량,
specs: h.work?.(info.고정 ?? wkey) ?? [],
subDoc: h.subDoc,
vals: (h.answer.값 ?? {}) as Record<string, unknown>,
ro,
put: (w) => put({ ...entry, 작업량: w }),
put: (w) => h.change((d) => putWork(d, wkey, w)),
})
: [];
const box = el("div", {
+61 -3
View File
@@ -6,6 +6,9 @@
* 식 문서 기본 · 고친 칸 「고침」 + [원래 값]) + 시간당 작업량 값
* 고침 = `기계덮음.<기계>.작업량 {방식 시간당, 식, 변수?}`(기본과 같은 변수 뺌 · 일당 = 칸 지움) · 읽기 = 잠김
* 기계 보기(`workVarRows`) = 같은 변수 칸으로 기계 작업량 줄 변수(기계 정본 값)를 고침
* 847-1(요구 884 · 885) — 방식이 하나뿐인 줄(기계에 맞는 식 없음) = 고르기 없이 그 풀이만 ·
* 시간당으로 바꿈 = 그 줄 기계를 굳힘(덮음 `기계`) · 기계 창으로 바꿈(`swapMachine`) = 새 기계 작업량 식 · 규격 변수로
* 다시 차림(같은 식 = 고친 현장 변수 남김 · 다른 식 = 버림 + 알림 · 맞는 식 없음 = 품셈 일당으로 + 알림)
* ========================================================================== */
import { createBadge } from "@ui/ui_template_badge";
@@ -17,12 +20,24 @@ import { createSegment } from "@ui/ui_template_segment";
import type { FormulaDoc } from "../common_util/common_util_formula_doc";
import { isNum } from "../common_util/common_util_formula_doc_calc";
import {
COVER,
coverOf,
machineKey,
type CoverEntry,
} from "../common_util/common_util_formula_doc_cover";
import {
fits,
HOURLY,
normUnit,
pruneWork,
specsOf,
workDefaults,
WORK,
type WorkCover,
type WorkInfo,
type WorkSpec,
} from "../common_util/common_util_formula_doc_work";
import type { Picked } from "../common_util/common_util_line_stack_pick";
import type { Values } from "../common_util/common_util_formula_doc_view";
import { varUnit } from "../common_util/common_util_line_stack_unit";
import { workUnit } from "../common_util/common_util_line_stack_work";
@@ -122,11 +137,54 @@ export interface WorkGroupOpts {
put: (w: WorkCover | undefined) => void;
}
/** 작업량 덮음 한 줄 고침(줄 기계 열쇠 · 값 칸 덮음은 그대로) — 없음 = 지움 · 비면 칸 지움 */
export function putWork(doc: FormulaDoc, key: string, w: WorkCover | undefined): void {
const all: Record<string, CoverEntry> = { ...coverOf(doc) };
const one: CoverEntry = { ...(all[key] ?? {}) };
const kept = pruneWork(w);
if (kept) one[WORK] = kept;
else delete one[WORK];
if (Object.keys(one).length) all[key] = one;
else delete all[key];
const box = doc as FormulaDoc & { [COVER]?: unknown };
if (Object.keys(all).length) box[COVER] = all;
else delete box[COVER];
}
/** 시간당 식 줄 기계를 기계 창 고른 것으로(847-1) — 새 덮음 · 알림 글(없으면 "") · 맞는 식 없음 = undefined(일당) */
export function swapMachine(
w: WorkCover,
info: WorkInfo,
p: Picked,
sameKey: boolean,
oldSpecs: WorkSpec[],
): { next: WorkCover | undefined; note: string } {
const specs = specsOf(p.작업량);
const ok = fits(specs, normUnit(info.단위));
if (!ok.length) return { next: undefined, note: lt("Work_Swap_None") };
const pick = w.식 && ok.includes(w.식) ? w.식 : ok[0];
const spec = specs.find((s) => s.식 === pick);
// 같은 식 = 현장 변수 남김(기계 규격 칸은 새 기계 값) · 다른 식 = 변수 버림
const own = new Set([...Object.keys(spec?.변수 ?? {}), ...oldSpecs.flatMap((s) => Object.keys(s.변수 ?? {}))]); // prettier-ignore
const vars = pick === w.식 ? Object.fromEntries(Object.entries(w.변수 ?? {}).filter(([k]) => !own.has(k))) : {}; // prettier-ignore
const lost = pick !== w.식 && Object.keys(w.변수 ?? {}).length > 0;
const next: WorkCover = {
방식: HOURLY,
식: pick,
...(Object.keys(vars).length ? { 변수: vars } : {}),
기계: machineKey(p.입력),
...(sameKey ? {} : { 키: p.키 }),
이름: [p.이름, p.규격].filter(Boolean).join(" "),
};
return { next, note: lost ? lt("Work_Swap_Lost") : "" };
}
/** 제어 구역 「시간당 작업량」 묶음 */
export function buildWorkGroup(o: WorkGroupOpts): HTMLElement[] {
const hourly = o.entry?.방식 === HOURLY;
const formulas = o.info.식들 ?? [];
const first = o.kind === "식" ? "식" : "일당";
const single = !formulas.length && !hourly; // 847-1 방식 하나뿐 = 고르기 없음
const seg = createSegment({
options: [
{ value: "일당", label: lt(first === "식" ? "Work_식" : "Work_일당") },
@@ -140,7 +198,8 @@ export function buildWorkGroup(o: WorkGroupOpts): HTMLElement[] {
value: hourly ? HOURLY : "일당",
size: 24,
ariaLabel: lt("Work_Way"),
onChange: (v) => o.put(v === HOURLY ? { 방식: HOURLY, 식: formulas[0] } : undefined),
// 847-1 시간당 = 그 줄 기계를 굳힘(옵션이 정하던 기계를 더 안 읽음)
onChange: (v) => o.put(v === HOURLY ? { 방식: HOURLY, 식: formulas[0], 기계: o.info.기계 } : undefined), // prettier-ignore
});
if (o.ro) seg.root.querySelectorAll("button").forEach((b) => (b.disabled = true));
seg.root.dataset.workWay = hourly ? HOURLY : first;
@@ -155,8 +214,7 @@ export function buildWorkGroup(o: WorkGroupOpts): HTMLElement[] {
],
});
const note = (text: string, cls = "lstk-empty"): HTMLElement => el("div", { className: cls, text }); // prettier-ignore
const locked = !formulas.length && !hourly ? [note(lt("Work_None"))] : []; // 식 없는 기계 = 잠김 까닭
const out: HTMLElement[] = [head, el("div", { className: "lstk-work", children: [seg.root, ...locked] })]; // prettier-ignore
const out: HTMLElement[] = [head, ...(single ? [] : [el("div", { className: "lstk-work", children: [seg.root] })])]; // prettier-ignore
if (!hourly) {
const rows = workRows(o.info, { doc: o.doc, vals: o.vals, miss: () => undefined });
// 방식 작은 글은 고르기가 보임 — 풀이만
+33 -16
View File
@@ -7,6 +7,7 @@
* 같은 계산기로 셈해 같은 꼴로 펼침(손료 식 · 연료 · 운전사 · 노 · 재 · 경 · 계) · 비목 수는 글(링크 꼴 없음 · 요구 687-11) ·
* 공식 줄 단가산출 결과 = 수 누름(▸) · 접으면 한 줄 · 출력엔 펼친 것만
* 기계 줄 작업량(846-2) = 「시간당 작업량 = …」 줄 먼저 · 비목 줄 「÷ 70 ㎥/시간」(`line_stack_work`)
* 847-1 시간당 식 줄 = 굳은 기계 이름 · 펼침도 그 기계 · 그 줄이 안 읽게 된 기호 = 숨김(`hiddenByWork`)
* 값 = 계산기 셈 답 그대로(`calcDoc` · 줄 `answer.줄` · 합 `노무비` …) — 여기서 다시 셈 안 함 · 조판 = KaTeX(`line_stack_tex.ts`)
* ========================================================================== */
@@ -22,7 +23,12 @@ import {
} from "../common_util/common_util_formula_doc";
import { calcDoc, isNum, type DocAnswer } from "../common_util/common_util_formula_doc_calc";
import type { DocCache } from "../common_util/common_util_formula_doc_cache";
import { coverDoc, coverOf, type Cover } from "../common_util/common_util_formula_doc_cover";
import {
coverDoc,
coverOf,
type Cover,
type CoverEntry,
} from "../common_util/common_util_formula_doc_cover";
import {
decide,
hasIf,
@@ -32,7 +38,7 @@ import {
type Values,
} from "../common_util/common_util_formula_doc_view";
import { machineText } from "./formula_doc_options";
import { reach } from "./formula_doc_render";
import { hiddenByWork, reach } from "./formula_doc_render";
import {
kindOf,
nodeOf,
@@ -42,7 +48,7 @@ import {
type StackDoc,
} from "../common_util/common_util_line_stack";
import { placeNames } from "../common_util/common_util_line_stack_copy";
import { splitFrac } from "../common_util/common_util_line_stack_frac";
import { fracDepth, splitFrac } from "../common_util/common_util_line_stack_frac";
import { stackLevels, tableAlias } from "../common_util/common_util_line_stack_pick";
import {
AMOUNT_UNIT,
@@ -52,7 +58,8 @@ import {
shownUnitOf,
} from "../common_util/common_util_line_stack_unit";
import { workAt } from "../common_util/common_util_line_stack_work";
import { partName } from "../common_util/common_util_machine_symbol_name";
import { workKey } from "../common_util/common_util_formula_doc_work";
import { partName, partUnit } from "../common_util/common_util_machine_symbol_name";
import { katexNode, symTex, tex, txt, valTex, type TexCtx } from "./line_stack_tex";
import { lt } from "./line_stack_text";
import { workQty, workRows } from "./line_stack_work";
@@ -127,7 +134,8 @@ function rows(
// 펼친 문서 줄 = 금액 칸 없이(부른 쪽 칸과 섞이지 않게)
const push = (r: Omit<Row, "depth" | "lv">): void =>
void out.push({ ...r, depth, lv, loc, ...(depth ? { cols: undefined } : {}) });
const shown = new Set(reach(doc, vals)); // 지금 탄 갈래로 닿는 기호만
const gone = hiddenByWork(doc, a); // 847-1 시간당 식 줄이 안 읽게 된 기호
const shown = new Set(reach(doc, vals).filter((x) => !gone.has(x))); // 지금 탄 갈래로 닿는 기호만
const steps = lineMap(doc);
const place = placeNames(doc, stackOf(doc)); // 번지 읽는 이름(804-5)
const look = (p: Record<string, unknown>): unknown => h.cache.links.table(p);
@@ -163,11 +171,14 @@ function rows(
res,
];
};
/** 847-1 굳은 기계 줄 단가 기호 → 그 기계 · 기계 식 문서 */
const fixedCall = new Map<string, { 기계: string; 키?: string }>();
const subOf = (id: string): FormulaDoc | null => {
const k = vars.get(id)?.연결;
if (k?.갈래 !== "단가산출" || !k.키 || k.키.includes("{")) return null;
const key = fixedCall.get(id)?.키 ?? k?.키;
if (k?.갈래 !== "단가산출" || !key || key.includes("{")) return null;
try {
return h.cache.links.doc(k.키) ?? null;
return h.cache.links.doc(key) ?? null;
} catch {
if (h.cache.takeMissing()) h.miss();
return null;
@@ -205,6 +216,7 @@ function rows(
const raw = subOf(id);
if (!h.open.has(path) || !raw || depth >= MAX_DEPTH) return;
const given = subInputs(vars.get(id)?.연결, vals);
if (fixedCall.has(id)) given.기계 = fixedCall.get(id)!.기계;
const sub = coverDoc(raw, given, h.cover);
const got = calcDoc(sub, h.cache.links, given, [], new Map(), h.cover);
if (h.cache.takeMissing()) h.miss();
@@ -232,17 +244,18 @@ function rows(
if (t !== undefined && hasVar(t)) {
flush();
const n = nodeOf(t)!;
if (!machine) {
if (!machine && fracDepth(n) <= 1) {
push({ h: formula(id, n, v, unit(id), vals, {}) });
continue;
}
// 845-2 기계경비식 — 겹분수 = 중간 줄(상여 · 휴지 · 손료계수) + 남는 안쪽 분수 ÷ 한 줄(그림만)
const tree = hasIf(n) ? decide(n, vals) : n;
const cut = splitFrac(id, tree, alias, taken, vals, partName(id));
// 845-2 기계경비식 — 겹분수 = 중간 줄(상여 · 휴지 · 손료계수) + 남는 안쪽 분수 ÷ 한 줄(그림만) ·
// 847-1 기계 밖 두 층 줄도 같은 규칙(만약 그대로 · 곱의 분수 항 펼침 · 중간 줄 이름 = 문서 키)
const tree = machine && hasIf(n) ? decide(n, vals) : n;
const cut = splitFrac(id, tree, alias, taken, vals, partName(id, String(doc.키 ?? "")), !machine); // prettier-ignore
const vs = { ...vals, ...cut.vals };
const more = { decided: true, frac: 1 };
const more = machine ? { decided: true, frac: 1 } : { frac: 1 };
// 중간 줄 단위 = 그 이름이 기계 칸(손료계수)이면 그 칸 단위 · 상여 · 휴지 = 비(무차원)
for (const r of cut.rows) push({ h: formula(r.id, r.node, vs[r.id], machineUnit(r.id), vs, more) }); // prettier-ignore
for (const r of cut.rows) push({ h: formula(r.id, r.node, vs[r.id], partUnit(r.id) || machineUnit(r.id), vs, more) }); // prettier-ignore
push({ h: formula(id, cut.node, v, unit(id), vs, more) });
continue;
}
@@ -308,8 +321,13 @@ function rows(
});
if (Object.keys(at).length) scope.번지 = at;
const spec = (line as { 규격?: string }).규격;
const name =
spec && !String(line.이름 ?? "").includes(spec)
// 846-2 작업량 · 847-1 굳은 기계(이름 · 펼침 = 그 기계)
const w = workAt(a, i);
const want = w?.고정 ? (h.cover?.[workKey(h.cover, w)] as CoverEntry | undefined)?.작업량 : undefined; // prettier-ignore
if (w?.고정 && priceSym(line)) fixedCall.set(priceSym(line)!, { 기계: w.고정, 키: want?.키 });
const name = w?.고정
? want?.이름 || machineText(w.고정, () => h.redraw?.()) || String(line.이름 ?? "")
: spec && !String(line.이름 ?? "").includes(spec)
? `${line.이름 ?? ""} ${spec}`.trim()
: String(line.이름 ?? ""); // 이름에 규격이 들면 한 번만(814-1)
const qty =
@@ -322,7 +340,6 @@ function rows(
const glue = (...xs: (string | HTMLElement)[]): HTMLElement =>
el("span", { className: "lstk-pack", children: xs.filter((x) => x !== "") });
// 846-2 작업량 — 「시간당 작업량」 줄 먼저 · 수량 = 「÷ 시간당 작업량」
const w = workAt(a, i);
const wq = (): HTMLElement[] | null => workQty(doc, qty, w, scope, alias); // 줄마다 새 요소
const byWork = wq() !== null;
const workHead = (): void => {
+8 -2
View File
@@ -54,6 +54,7 @@ import {
import { docFoot } from "./formula_doc_foot";
import { askRenew } from "./formula_doc_renew";
import { buildOptions } from "./formula_doc_options";
import { hiddenByWork } from "./formula_doc_render";
import { ft } from "./formula_doc_text";
import { addTaken, type Taken } from "../common_util/common_util_line_stack_copy";
import { machineWork } from "../common_util/common_util_line_stack_work";
@@ -315,8 +316,13 @@ export function createStackScreen(opt: StackScreenOptions) {
// 가져온 식 = 옵션 가로 안 그림(819-1 · 요구 787 — 값은 왼쪽 공식 묶음에 같이 보임)
const options = (doc as { 가져온?: unknown }).가져온
? []
: buildOptions(doc, given, !!cp && !opt.admin, setOption, (no) =>
openMachineWindow({ ctx: machineCtx(), drafts: [], now: no, query: "" }),
: buildOptions(
doc,
given,
!!cp && !opt.admin,
setOption,
(no) => openMachineWindow({ ctx: machineCtx(), drafts: [], now: no, query: "" }),
hiddenByWork(doc, answer), // 847-1 시간당 식 줄이 안 읽게 된 옵션
);
const busy = dirty();
const tools = [
+12
View File
@@ -119,6 +119,18 @@ const TEXT = {
Work_None: ["시간당 작업량 식 없는 기계", "No hourly output formula for this machine"],
Work_Wait: ["작업량 식 불러오는 중", "Loading output formula"],
Work_Vars: ["작업량 변수", "Output variables"],
Work_Swap_None: [
"고른 기계에 맞는 시간당 작업량 식이 없어 품셈 일당으로 돌아감",
"No hourly output formula for this machine — back to daily output",
],
Work_Swap_Lost: [
"작업량 식이 바뀌어 고친 작업량 변수를 버림",
"Output formula changed — edited output variables were dropped",
],
Work_Qty_Note: [
"시간당 식 — 수량은 시간당 작업량으로 정해짐(변수는 기계 제어 구역)",
"Hourly formula — quantity follows output per hour (edit variables in the machine panel)",
],
Win_Ctl_Note: [
"기계 내부 값(가격 · 연료 · 조종원 · 잡품)은 단가산출 왼쪽 기계 줄의 ▸ 에서 고침",
"Edit machine internals from the ▸ on the left machine line",
+1 -1
View File
@@ -483,7 +483,7 @@ function money(run: Run, doc: FormulaDoc, rules: Record<string, Rule>) {
: text !== null && text !== undefined && text !== ""
? run.expr(text, where, { ...scope, ...(more as Record<string, Val>) })
: 1;
const price = run.expr(line.단가, where, scope);
const price = run.expr(line.단가, where, { ...scope, ...(more as Record<string, Val>) }); // 847-1 굳은 기계 단가
const kind = line.비목 as string;
let parts: Bundle = {};
let bare: number | null = null; // 비목 없는 합 밖 줄(소계 보임 · 810-2) — 금액만
+60 -10
View File
@@ -10,6 +10,10 @@
* 덮음 = `기계덮음` 기계 칸 `작업량: {방식: '시간당', 식, 변수?}` — 그 기계 줄의 작업량 자리를 `1 ÷ Q` 로 바꿈
* (Q = 그 식을 식 문서 기본 › 기계 변수 › 덮음 변수로 셈) · 다른 곱(율 등) 그대로 · 못 함 = 그 줄 멈춤(까닭)
* 부착 기계(브레이커 · 집게 입력) 줄 = 그 부착 기계 열쇠(굴착기 줄과 따로)
* 덮음 열쇠(847-1) = 그 줄 단가 기호(옵션이 기계를 바꿔도 같은 줄) › 기계 열쇠(846-1 옛 꼴)
* 굳은 기계(847-1 · 요구 885) = 덮음 `기계`(시간당으로 바꿀 때 그 줄 기계 · 기계 창으로 바꾼 기계) — 그 줄 단가를
* 그 기계(`키` = 기계 식 문서가 다를 때)로 다시 부르고 작업량 식 · 변수도 그 기계 것(옵션이 정하던 기계를 안 읽음) ·
* `이름` = 화면 이름만 · 부착 기계 줄 = 굳힘 없음
* 셈 답 기계 줄 칸 `작업량` = {기계, 꼴(일당 · 식 · 시간당), 율, 값, 단위, 식들, 변수?, 까닭?}(산출근거 자료)
* 파이썬 · TS 짝 — 짝 = resources/master_data/scripts/master_doc_work.py · 거울 시험 test_846_1_machine_work.py
* · 계산기(`common_util_formula_doc_calc.ts` money)가 줄마다 `lineWork` 를 부름 · 화면 · DOM · fetch 없음
@@ -45,10 +49,19 @@ export interface WorkCover {
방식: string;
식?: string;
변수?: Record<string, unknown>;
/** 굳은 기계 입력 글(따옴표 뗌) */
기계?: string;
/** 굳은 기계의 기계 식 문서(줄 연결과 다를 때만) */
키?: string;
/** 화면 이름(셈 안 봄) */
이름?: string;
}
const FIXED = ["기계", "키", "이름"] as const;
/** 셈 답 기계 줄 `작업량` */
export interface WorkInfo {
기계: string;
/** 그 줄 단가 기호(847-1 덮음 열쇠) */
기호?: string;
꼴: string;
율: string;
값: number | null;
@@ -56,6 +69,8 @@ export interface WorkInfo {
식들: string[];
변수?: Record<string, unknown>;
까닭?: string;
/** 굳은 기계(덮음 `기계`) */
고정?: string;
}
interface Site {
꼴: string;
@@ -301,15 +316,25 @@ export function pruneWork(
const out: WorkCover = { 방식: HOURLY };
if (want.식) out.식 = String(want.식);
if (got.length) out.변수 = Object.fromEntries(got);
for (const k of FIXED) if (want[k]) out[k] = String(want[k]);
return out;
}
/** 그 줄 작업량 덮음 열쇠 — 단가 기호 › 기계 열쇠(옛 꼴) 가운데 덮음이 있는 것 · 없으면 단가 기호(새로 씀) */
export function workKey(
cover: Cover | null | undefined,
info: { 기계: string; 기호?: string },
): string {
const has = (k?: string): boolean => !!k && !!(cover?.[k] as { [WORK]?: WorkCover } | undefined)?.[WORK]; // prettier-ignore
return has(info.기호) ? info.기호! : has(info.기계) ? info.기계 : (info.기호 ?? info.기계);
}
/** 문서 `기계덮음` 의 시간당 작업량 식 키(파이썬 `cover_calls` 짝) */
export function coverCalls(doc: FormulaDoc | null | undefined): string[] {
const got = (doc as { 기계덮음?: Cover } | null | undefined)?.기계덮음;
return Object.values(got && typeof got === "object" ? got : {}).flatMap((e) => {
const w = (e as { [WORK]?: WorkCover })?.[WORK];
return w && w.방식 === HOURLY && w.식 ? [String(w.식)] : [];
return w && w.방식 === HOURLY && w.식 ? [String(w.식), ...(w.키 ? [String(w.키)] : [])] : []; // 847-1 굳은 기계 식 문서
});
}
@@ -326,6 +351,8 @@ export interface WorkRun {
expr(text: unknown, where?: string, scope?: Scope): unknown;
ev(node: Node, scope: Scope | undefined, where: string): unknown;
sub(p: Record<string, unknown>, name: string): unknown;
link(v: DocVar, name: string): unknown;
mark(stop: { why: string }): unknown;
}
/** 계산기 몫(계산기 → 이 파일 부름만 · 거꾸로 import 없음) */
export interface WorkKit {
@@ -336,19 +363,33 @@ export interface WorkKit {
plainText: (v: unknown) => string;
}
function machineOf(run: WorkRun, line: { 단가?: unknown }): string | null {
/** 기계 줄 단가 기호 → {작업 기계 입력 식, 단가 기호, 본 기계 칸인지(부착 기계 아님)} · 기계 줄 아님 = null */
export function machineOf(
vars: Map<string, DocVar>,
line: { 단가?: unknown },
): { expr: string; name: string; main: boolean } | null {
const node = parseOr(line.단가);
for (const name of node ? names(node) : []) {
const link = (run.vars.get(name)?.연결 ?? {}) as { 갈래?: string; 입력?: Record<string, unknown> }; // prettier-ignore
const link = (vars.get(name)?.연결 ?? {}) as { 갈래?: string; 입력?: Record<string, unknown> }; // prettier-ignore
const given = link.입력 ?? {};
if (link.갈래 === "단가산출" && "기계" in given) {
const tool = Object.entries(given).filter(([k]) => k !== "기계" && !NOT_MACHINE.includes(k));
return String(tool.length ? tool[tool.length - 1][1] : given.기계);
const expr = String(tool.length ? tool[tool.length - 1][1] : given.기계);
return { expr, name, main: !tool.length };
}
}
return null;
}
/** 굳은 기계로 단가 기호 연결을 바꾼 변수(기계 입력 = 그 기계 · 기계 식 문서 = `키` 있으면 그것) */
export function fixedVar(v: DocVar, want: WorkCover): DocVar {
const link = v.연결 ?? {};
return {
...v,
연결: { ...link, 입력: { ...(link.입력 ?? {}), 기계: `'${want.기계}'` }, ...(want.키 ? { 키: want.키 } : {}) }, // prettier-ignore
};
}
/** 기계 줄 하나 → [바꾼 수량 글 | 멈춤(표지는 계산기가 담) | null, 범위 더함, 답 칸 | null] */
export function lineWork(
run: WorkRun,
@@ -356,8 +397,9 @@ export function lineWork(
scope: Scope,
kit: WorkKit,
): [string | { why: string } | null, Record<string, unknown>, WorkInfo | null] {
const expr = machineOf(run, line);
if (expr === null) return [null, {}, null];
const got = machineOf(run.vars, line);
if (got === null) return [null, {}, null];
const expr = got.expr;
const where = String(line.이름 ?? "");
/** 흔적 없는 셈 — 표지 · 기억한 값을 되돌림(진짜 셈이 표지를 다시 냄) */
const quiet = <T>(fn: () => T): T => {
@@ -379,18 +421,19 @@ export function lineWork(
return kit.bad(v) ? null : !!v;
};
const found = sites(run.doc, line.수량, test);
const want = (run.cover?.[key] as { [WORK]?: WorkCover } | undefined)?.[WORK];
const want = (run.cover?.[workKey(run.cover, { 기계: key, 기호: got.name })] as { [WORK]?: WorkCover } | undefined)?.[WORK]; // prettier-ignore
const hourly = !!want && want.방식 === HOURLY;
if (!found.length && !hourly) return [null, {}, null];
const fixed = hourly && got.main && want!.기계 ? String(want!.기계) : ""; // 847-1 굳은 기계
let specs: WorkSpec[] = [];
try {
specs = specsOf(run.links.element({ 키: `EQ:${key}`, 칸: WORK }));
specs = specsOf(run.links.element({ 키: `EQ:${fixed || key}`, 칸: WORK }));
} catch (e) {
if (!(e instanceof kit.Gap) && !(e instanceof kit.Broken)) throw e;
}
const unit = found.length ? found[0].단위 : "";
const info: WorkInfo = {
기계: key, 꼴: found.length ? found[0].꼴 : "", 율: found.length ? found[0].율 : "",
기계: key, 기호: got.name, 꼴: found.length ? found[0].꼴 : "", 율: found.length ? found[0].율 : "",
값: null, 단위: unit, 식들: fits(specs, unit),
}; // prettier-ignore
if (!hourly) {
@@ -409,6 +452,7 @@ export function lineWork(
: "";
info.꼴 = HOURLY;
info.율 = pick;
if (fixed) info.고정 = fixed;
if (why) {
info.까닭 = why;
return [new kit.Stop(`${where} 시간당 거절 — ${why}`, "시간당 거절", where), {}, info];
@@ -429,5 +473,11 @@ export function lineWork(
return [new kit.Stop(`${where} ${info.까닭}`, "시간당 거절", where), {}, info];
}
info.값 = q;
return [swap(run.doc, line.수량), { [Q_NEW]: q }, info];
const more: Scope = { [Q_NEW]: q };
if (fixed) {
const price = run.link(fixedVar(run.vars.get(got.name)!, want!), got.name); // 단가 = 굳은 기계
if (price instanceof kit.Stop) run.mark(price);
more[got.name] = price;
}
return [swap(run.doc, line.수량), more, info];
}
+21 -13
View File
@@ -8,6 +8,7 @@
* ③ 분수 안 덧셈 묶음이 또 분수를 품으면 = 중간 줄(그림 사전 `partName` — 「손료계수」)
* ④ 그래도 남는 안쪽 분수 = 조판이 ÷ 한 줄로(`TexCtx.frac`)
* 그리기만 — 문서 식 · 값 · 금액 불변 · 중간 줄 값 = 같은 식 조각을 같은 셈(`evalNode`) · 화면 없음(시험이 Node 로 돌림)
* 기계 밖 문서(847-1) = 두 층 넘는 줄만 같은 규칙 + 곱의 분수 항(「× (1 ÷ L)」)을 사슬로 펼침(`lift`)
* ========================================================================== */
import type { Node } from "./common_util_formula_doc";
@@ -36,31 +37,37 @@ export function fracDepth(n: Node): number {
}
}
/** 왼쪽으로 쌓인 곱 · 나눗셈 사슬 → [연산, 항] */
function chain(n: Node): ["*" | "/", Node][] {
if (n[0] === "bin" && (n[1] === "*" || n[1] === "/"))
return [...chain(n[2]), [n[1] as "*" | "/", n[3]]];
/** 왼쪽으로 쌓인 곱 · 나눗셈 사슬 → [연산, 항] · `lift` = 곱한 분수 항 「× (a ÷ b)」 → 「× a ÷ b」 */
function chain(n: Node, lift = false): ["*" | "/", Node][] {
if (n[0] === "bin" && (n[1] === "*" || n[1] === "/")) {
const r = n[3];
if (lift && n[1] === "*" && isFrac(r)) return [...chain(n[2], lift), ["*", r[2]], ["/", r[3]]];
return [...chain(n[2], lift), [n[1] as "*" | "/", r]];
}
return [["*", n]];
}
const product = (xs: Node[]): Node => xs.reduce((a, b) => ["bin", "*", a, b]);
const isFrac = (n: Node): n is ["bin", string, Node, Node] => n[0] === "bin" && n[1] === "/";
function isFrac(n: Node): n is ["bin", string, Node, Node] {
return n[0] === "bin" && n[1] === "/";
}
/** ① ÷ 둘 넘는 사슬 = 「a ÷ b」 짝을 나란히 — 감싸개 · 괄호 안까지 */
export function regroup(n: Node): Node {
export function regroup(n: Node, lift = false): Node {
const re = (x: Node): Node => regroup(x, lift);
switch (n[0]) {
case "neg":
return ["neg", regroup(n[1])];
return ["neg", re(n[1])];
case "pct":
return ["pct", regroup(n[1])];
return ["pct", re(n[1])];
case "call":
return ["call", n[1], n[2].map(regroup)];
return ["call", n[1], n[2].map(re)];
case "bin": {
const items = chain(n);
const items = chain(n, lift);
if (items.length < 2 || items.filter(([o]) => o === "/").length < 2)
return ["bin", n[1], regroup(n[2]), regroup(n[3])];
return ["bin", n[1], re(n[2]), re(n[3])];
const out: Node[] = [];
for (const [o, raw] of items) {
const x = regroup(raw);
const x = re(raw);
const last = out[out.length - 1];
if (o === "*" || !last) out.push(x);
else if (isFrac(last))
@@ -90,6 +97,7 @@ export function splitFrac(
taken: Set<string>,
vals: Values,
part?: string,
lift = false,
): { rows: FracRow[]; node: Node; vals: Values } {
const rows: FracRow[] = [];
const got: Values = {};
@@ -106,7 +114,7 @@ export function splitFrac(
// 감싸개(버림 등)는 그대로 두고 안쪽만
const inner = (x: Node, fn: (y: Node) => Node): Node =>
hidden(x) ? ["call", x[1], [inner(x[2][0], fn), ...x[2].slice(1)]] : fn(x);
let node = inner(regroup(n), (x) => {
let node = inner(regroup(n, lift), (x) => {
// ② 분자 · 분모 짝(곱 사슬의 분수 항)
const factors = (y: Node): Node[] =>
y[0] === "bin" && y[1] === "*" ? [...factors(y[2]), y[3]] : [y];
@@ -100,6 +100,8 @@ export interface Picked {
규격?: string;
단위?: string;
입력?: Record<string, string>;
/** 847-1 고른 기계의 값 칸 `작업량`(기계 창 — 시간당 식 줄 기계 바꿈) */
작업량?: unknown;
}
const SIGN: Record<string, string> = { 인력: "w", 재료: "P", 기계: "P", 단가산출: "B" };
+22 -4
View File
@@ -6,7 +6,8 @@
* 기계경비식 밖 문서 · 사용자가 손으로 바꾼 기호(사전에 없는 꼴)는 그대로 · 이름이 겹치면 그 기호만 그대로
* 화면 없음(시험이 Node 로 돌림) · 기계 제어 구역(836-1)도 `machineAlias` 로 같은 이름
* 인력 · 잡품 줄 여럿(842-3 — 덮음이 더한 `w_조종원N` · `P_잡품N`) = 줄마다 「인력N」 · 「잡품N」
* 겹분수 중간 줄 이름(845-2 `partName`) — 산출근거가 손료 식을 「손료계수」 줄 + 「손료」 줄로 나눠 그림
* 겹분수 중간 줄 이름(845-2 `partName`) — 산출근거가 손료 식을 「손료계수」 줄 + 「손료」 줄로 나눠 그림 ·
* 기계 밖 문서(847-1) = 문서 키로(원문 말 줄임 · 단위 `partUnit`)
* ========================================================================== */
import type { FormulaDoc } from "./common_util_formula_doc";
@@ -135,6 +136,23 @@ export function machineAlias(doc: FormulaDoc): Record<string, string> {
/** 기계 칸 이름(상각비계수 …) → 짧은 이름 · 없으면 그대로 — 기계 제어 구역(836-1) 값 칸 이름표 */
export const machineCellName = (col: string): string => CELL[col] ?? col;
/** 겹분수 중간 줄 이름(845-2 · `splitFrac` ③) — 손료 식 분자 안 「(상각 + 정비) × (1 + 가산 ÷ 100) + 관리」 */
const PART: Record<string, string> = { C_손료: "손료계수" };
export const partName = (id: string): string | undefined => PART[id];
/** 겹분수 중간 줄 이름(845-2 · `splitFrac` ③) — 손료 식 분자 안 「(상각 + 정비) × (1 + 가산 ÷ 100) + 관리」 ·
* 기계 밖(847-1) = 문서 키 → 분수 안 덧셈 묶음 이름(원문 말 줄임) */
const PART: Record<string, string> = {
C_손료: "손료계수",
GC000377: "손실 보정", // 1 - 손실률
GC000801: "할증률", // 형식 가산 + 튜브 증감
GC000871: "할증률", // 부속 · 공장제작 · 설치높이 · 장소
GC001174: "1회 소요시간", // 입환 + 적재시 주행 + 공차시 주행 + 적재 적하
GC001176: "평균 이동거리", // 평균간격 + 블록간 거리 ÷ 시공본수
GC001188: "1회 소요시간", // 위치 이동 + 낙추횟수 ÷ 1분당 낙추횟수
GF000327: "할증계수", // 1 + 계항 · 지질 · 산지비탈면
};
const PART_UNIT: Record<string, string> = {
할증률: "%",
"1회 소요시간": "분",
"평균 이동거리": "m",
};
export const partName = (id: string, doc = ""): string | undefined => PART[id] ?? PART[doc];
/** 기계 밖 중간 줄 단위 */
export const partUnit = (name: string): string => PART_UNIT[name] ?? "";
@@ -414,7 +414,7 @@ def _money(run: _Run, doc: dict, rules: dict):
if text not in (None, "")
else Decimal(1)
)
price = run.expr(line.get("단가"), where, scope)
price = run.expr(line.get("단가"), where, {**scope, **more}) # 847-1 굳은 기계 단가
kind = line.get("비목")
parts, why, bare = {}, None, None
if isinstance(qty, Stop) or isinstance(price, Stop):
@@ -452,12 +452,18 @@ def prune_doc(doc: dict, links) -> dict:
base = defaults_of(sub, ans.get("값") or {}, row_entry(sub, lists_of(links, dict(given))))
if one := prune({k: v for k, v in cover[m].items() if k != mw.WORK}, base):
kept[m] = one
works = { # 작업량(846-1) = 기계 줄 답이 읽은 작업 기계(부착 기계 포함)
w["기계"] for a in (top, *memo.values()) for x in a.get("줄") or [] if (w := x.get(mw.WORK))
}
for m in sorted(works & set(cover)):
works: dict = {} # 작업량(846-1) = 기계 줄 답이 읽은 작업 기계(부착 기계 포함) · 847-1 단가 기호 열쇠도
for a in (top, *memo.values()):
for x in a.get("줄") or []:
if w := x.get(mw.WORK):
works.setdefault(w["기계"], w["기계"])
if w.get("기호"):
works.setdefault(w["기호"], w["기계"])
for m in sorted(set(works) & set(cover)):
want = cover[m].get(mw.WORK)
if want and (one := mw.prune_work(want, _work_base(links, m, want))):
if want and (
one := mw.prune_work(want, _work_base(links, want.get("기계") or works[m], want))
):
kept[m] = {**kept.get(m, {}), mw.WORK: one}
return {**rest, COVER: kept} if kept else rest
@@ -10,6 +10,9 @@
덮음 = `기계덮음` 기계 칸 `작업량: {방식: '시간당', 식?, 변수?}` — 그 기계 줄의 작업량 자리를 `1 ÷ Q` 로 바꿈
(Q = 덮음 식 › 단위 맞는 첫 식을 식 문서 기본 › 기계 변수 › 덮음 변수로 셈) · 다른 곱(율 등) 그대로 ·
기계에 작업량 칸 없음 · 단위 맞는 식 없음 · Q 못 셈 = 그 줄 멈춤(까닭).
굳은 기계(847-1 · 요구 885) = 덮음 `기계`(시간당으로 바꿀 때 그 줄 기계 · 기계 창으로 바꾼 기계) — 그 줄 단가를
그 기계(`키` = 기계 식 문서가 다를 때)로 다시 부르고 작업량 식 · 변수도 그 기계 것 · `이름` = 화면 이름만 ·
부착 기계 줄 = 굳힘 없음 · 덮음 열쇠 = 그 줄 단가 기호 › 기계 열쇠(846-1 옛 꼴).
셈 답 기계 줄 칸 `작업량` = {기계, 꼴(일당 · 식 · 시간당), 율, 값, 단위, 식들, 변수?, 까닭?}(산출근거 자료).
파이썬 · TS 짝 — 짝 = `common_util/common_util_formula_doc_work.ts` · 거울 시험
`resources/tester/test_846_1_machine_work.py`.
@@ -23,6 +26,7 @@ from decimal import Decimal
import master_doc as md
WORK = "작업량"
FIXED = ("기계", "키", "이름") # 847-1 굳은 기계 · 기계 식 문서 · 화면 이름
HOURLY, DAILY = "시간당", "일당"
Q_NEW = "Q_시간당작업량" # 셈 범위 이름(문서 기호 아님)
EIGHT = Decimal(8)
@@ -265,6 +269,7 @@ def prune_work(want, base: dict | None = None) -> dict | None:
out["식"] = str(want["식"])
if got:
out["변수"] = got
out |= {k: str(want[k]) for k in FIXED if want.get(k)}
return out
@@ -286,19 +291,27 @@ def clean_work(want, where: str) -> dict:
):
raise ValueError(f"{where} 작업량 변수 — {{열쇠: 수 · 글}}")
out["변수"] = {str(k): v for k, v in vals.items() if v not in (None, "")}
for k in FIXED: # 847-1 굳은 기계
if want.get(k) not in (None, ""):
if not isinstance(want[k], str):
raise ValueError(f"{where} 작업량 {k} — 글")
out[k] = want[k]
return out
def cover_calls(doc: dict) -> list[str]:
"""문서 `기계덮음` 의 시간당 작업량 식 키 — 사본 부름 닫힌 묶음에 더함(`M02_Doc_Copy.calls`)."""
"""문서 `기계덮음` 의 시간당 작업량 식 키 · 굳은 기계 식 문서 키(847-1) — 사본 부름 닫힌 묶음에 더함
(`M02_Doc_Copy.calls`)."""
got = doc.get("기계덮음") if isinstance(doc, dict) else None
return [
str(w["식"])
str(w[k])
for e in (got.values() if isinstance(got, dict) else [])
if isinstance(e, dict)
and isinstance(w := e.get(WORK), dict)
and w.get("방식") == HOURLY
and w.get("식")
for k in ("식", "키")
if w.get(k)
]
@@ -307,7 +320,7 @@ NOT_MACHINE = ("지역", "보정작업", "조종원직종", "계약종별") #
def _machine_of(run, line: dict):
"""금액 줄 단가가 부르는 기계 식 변수 → (작업 기계 입력 식, 변수 이름) · 기계 줄 아님 = None ·
"""금액 줄 단가가 부르는 기계 식 변수 → (작업 기계 입력 식, 변수 이름, 본 기계 칸인지) · 기계 줄 아님 = None ·
부착 기계(브레이커 · 집게 입력) 줄 = 그 부착 기계(일하는 기계 — 굴착기 줄과 따로)."""
node = _parse(line.get("단가"))
for name in md.names(node) if node is not None else []:
@@ -315,10 +328,26 @@ def _machine_of(run, line: dict):
given = link.get("입력") or {}
if link.get("갈래") == "단가산출" and "기계" in given:
tool = [v for k, v in given.items() if k != "기계" and k not in NOT_MACHINE]
return str(tool[-1] if tool else given["기계"]), name
return str(tool[-1] if tool else given["기계"]), name, not tool
return None
def work_key(cover, machine: str, sym: str | None) -> str:
"""그 줄 작업량 덮음 열쇠 — 단가 기호 › 기계 열쇠(옛 꼴) 가운데 덮음이 있는 것 · 없으면 단가 기호."""
has = lambda k: bool(k) and isinstance((cover or {}).get(k), dict) and bool(cover[k].get(WORK)) # noqa: E731
return sym if has(sym) else machine if has(machine) else (sym or machine)
def fixed_var(var: dict, want: dict) -> dict:
"""굳은 기계로 단가 기호 연결을 바꾼 변수(기계 입력 = 그 기계 · 기계 식 문서 = `키` 있으면 그것)."""
link = var.get("연결") or {}
return {
**var,
"연결": {**link, "입력": {**(link.get("입력") or {}), "기계": f"'{want['기계']}'"},
**({"키": want["키"]} if want.get("키") else {})},
} # fmt: skip
def line_work(run, line: dict, scope: dict):
"""기계 줄 하나 → (바꾼 수량 글 | 멈춤(표지는 계산기가 담) | None, 범위 더함 {}, 답 칸 | None) —
계산기 `_money` 가 부름."""
@@ -350,16 +379,17 @@ def line_work(run, line: dict, scope: dict):
return None if mc._bad(v) else bool(v)
found = sites(run.doc, line.get("수량"), test)
want = ((run.cover or {}).get(key) or {}).get(WORK)
want = ((run.cover or {}).get(work_key(run.cover, key, got[1])) or {}).get(WORK)
hourly = isinstance(want, dict) and want.get("방식") == HOURLY
if not found and not hourly:
return None, {}, None
fixed = str(want["기계"]) if hourly and got[2] and want.get("기계") else "" # 847-1 굳은 기계
try:
specs = specs_of(run.links.element({"키": f"EQ:{key}", "칸": WORK}))
specs = specs_of(run.links.element({"키": f"EQ:{fixed or key}", "칸": WORK}))
except (mc.Gap, mc.Broken):
specs = []
unit = found[0]["단위"] if found else ""
info = {"기계": key, "꼴": found[0]["꼴"] if found else "", "율": found[0]["율"] if found else "",
info = {"기계": key, "기호": got[1], "꼴": found[0]["꼴"] if found else "", "율": found[0]["율"] if found else "",
"값": None, "단위": unit, "식들": fits(specs, unit)} # fmt: skip
if not hourly:
v = quiet(lambda: run.ev(found[0]["노드"], scope, where))
@@ -377,6 +407,8 @@ def line_work(run, line: dict, scope: dict):
else ""
)
info |= {"꼴": HOURLY, "율": pick}
if fixed:
info["고정"] = fixed
if why:
info["까닭"] = why
return mc.Stop(f"{where} 시간당 거절 — {why}", "시간당 거절", where), {}, info
@@ -392,4 +424,10 @@ def line_work(run, line: dict, scope: dict):
info["까닭"] = f"작업량 식 {pick} 못 셈" + (f" — {q.why}" if mc._bad(q) else "")
return mc.Stop(f"{where} {info['까닭']}", "시간당 거절", where), {}, info
info["값"] = q
return swap(run.doc, line.get("수량")), {Q_NEW: q}, info
more = {Q_NEW: q}
if fixed: # 단가 = 굳은 기계
price = run.link(fixed_var(run.vars[got[1]], want), got[1])
if isinstance(price, mc.Stop):
run.mark(price)
more[got[1]] = price
return swap(run.doc, line.get("수량")), more, info
+17 -2
View File
@@ -228,6 +228,8 @@ const load = makeLoader({
const out = load("A00_Common/line_stack_out.ts");
const edit = load("A00_Common/line_stack_edit.ts");
const opts = load("A00_Common/formula_doc_options.ts");
const render = load("A00_Common/formula_doc_render.ts");
const mwork = load("A00_Common/line_stack_machine_work.ts");
const ls = load("common_util/common_util_line_stack.ts");
const unit = load("common_util/common_util_line_stack_unit.ts");
const cacheMod = load("common_util/common_util_formula_doc_cache.ts");
@@ -287,11 +289,13 @@ function left(c) {
const walk = (n) => {
for (const ch of n.children) {
if (ch.cls().includes("lstk-frow") || ch.cls().includes("lstk-work")) rows.push({ sym: ch.dataset.sym ?? ch.dataset.mctlField ?? "", t: textOf(ch) });
if ("workQty" in ch.dataset) rows.push({ sym: "수량", t: textOf(ch), 잠김: ch.querySelector("input")?.disabled === true }); // 847-1
walk(ch);
}
};
walk(root);
return [...opts.buildOptions(doc, {}, true, noop).map((x) => ({ sym: `opt:${x.dataset.option}`, t: textOf(x) })), ...rows];
const hide = render.hiddenByWork(doc, a); // 847-1 화면과 같음(line_stack_screen)
return [...opts.buildOptions(doc, {}, true, noop, undefined, hide).map((x) => ({ sym: `opt:${x.dataset.option}`, t: textOf(x) })), ...rows];
}
/** 셈 답 요약(846-2 — 계 · 줄마다 작업량 · 금액) */
@@ -312,7 +316,7 @@ function guard(c, machine) {
for (const r of rows) {
if (r.cls.includes("subhead")) sub = machine.has(r.t.replace(/ \[[^\]]*\]$/, ""));
const texs = [...r.t.matchAll(/⟦([^⟧]*)⟧/g)].map((m) => m[1]);
if ((r.cls.includes("is-sub") ? sub : c.기계) && Math.max(0, ...texs.map(depth)) > 1) bad.push(["겹분수", r.t]);
if ((c.밖 || (r.cls.includes("is-sub") ? sub : c.기계)) && Math.max(0, ...texs.map(depth)) > 1) bad.push(["겹분수", r.t]); // 847-1 밖 = 기계 밖 문서도
// 머리 [결과 단위] = 문서 결과단위 글 그대로(자료 몫 — 「원(원문 단위 없음)」 등 설명 포함)
if (!/head/.test(r.cls) && /따름|원문 단위 없음|수\(단위/.test(r.t)) bad.push(["메타 단위", r.t]);
const m = MONEY.exec(r.t);
@@ -332,6 +336,17 @@ if (input.할일 === "전수") {
const g = guard(c, machineNames);
return { 키: c.키, ...g, ...(show.has(c.키) ? { 오른쪽: right(c), 왼쪽: left(c), 셈: sums(c) } : {}) };
});
} else if (input.할일 === "숨김") {
// 847-1 — 숨긴 기호 · 덮음 고침(putWork) · 기계 바꿈(swapMachine)
res = {
숨김: input.문서들.map((c) => {
const cache = cacheMod.createDocCache();
cache.merge(c.연결 || {});
return [...render.hiddenByWork(c.문서, calc.calcDoc(c.문서, cache.links, {}))].sort();
}),
덮음: (input.덮음 || []).map(([doc, key, w]) => (mwork.putWork(doc, key, w), doc)),
바꿈: (input.바꿈 || []).map(([w, info, p, same, old]) => mwork.swapMachine(w, info, p, same, old)),
};
} else if (input.할일 === "단위") {
res = {
글: input.글.map((u) => unit.unitText(u)),
@@ -155,10 +155,6 @@ def test_권한_회사층_일반계정_읽기만(world):
)
assert any(c["키"] == "GC000267" for c in found["후보"])
assert "줄" in screen.doc_table("company", key, "QC000431", None, _session())
scr = _src("A00_Common/line_stack_screen.ts")
assert "buildOptions(doc, given, !!cp && !opt.admin," in scr # 사본 읽기만 = 옵션 잠금
copy_src = _src("A00_Common/formula_doc_copy.ts")
assert "if (!edit) return [];" in copy_src and 'createBadge(ft("Read_Only")' in copy_src
# ── ④ 꺼진 줄(TS 판정 그대로 · Node) ─────────────────────────────────
+9 -2
View File
@@ -74,8 +74,15 @@ def test_터파기_일당_지금_금액_시간당_작업량_70(links):
ans = mc.calc(links.doc(DIG), links)
line = _line(ans, "굴착기")
work = line[mw.WORK]
assert work == {"기계": NO, "꼴": "일당", "율": "Q_시공 ÷ (8 × Q_굴착기^표)", "값": D(70),
"단위": "㎥/hr", "식들": [TPL]} # fmt: skip
assert work == {
"기계": NO,
"기호": "P_굴착기무한궤",
"꼴": "일당",
"율": "Q_시공 ÷ (8 × Q_굴착기^표)",
"값": D(70),
"단위": "㎥/hr",
"식들": [TPL],
} # fmt: skip 847-1 기호 = 덮음 열쇠
price = line["단가"]
want = {k: _cut(price[k] * 1 * 8 / D(560)) for k in COSTS} # 대수 1 × 8 ÷ 560
assert line["비목"] == want and ans["셈됨"]
+5 -2
View File
@@ -180,12 +180,15 @@ def test_전수_일당_시간당_차림_어긋남_0(every):
assert off == {} # 시간당 식 화면 셈 = 서버 셈
def test_식_없는_기계_잠김_글(base, every):
def test_식_없는_기계_고르기_없음(base, every):
"""847-1(요구 884) — 방식이 하나뿐인 줄 = 고르기 없이 그 풀이만(옛 잠김 글 대신)."""
_, _, _, nofit = every
assert nofit
c, _ = _case(base, nofit[0], base[0][nofit[0]])
g = _js({"할일": "전수", "문서들": [c], "보기": [c["키"]]})[0]
assert any("시간당 작업량 식 없는 기계" in r["t"] for r in g["왼쪽"])
rows = [r["t"].strip() for r in g["왼쪽"]]
assert not any("시간당 식" in t for t in rows) # 고르기 없음
assert any("시간당 작업량" in t for t in rows) # 일당 풀이는 그대로
def test_기계_보기_서버_작업량_연결():
+224
View File
@@ -0,0 +1,224 @@
# -*- coding: utf-8 -*-
"""PLAN 847-1(요구 884 · 885) — 기계 작업량 방식에 따라 안 고른 쪽 숨김 · 시간당 식이면 기계 굳음 · 기계 밖 겹분수.
① GC000088 품셈 일당 = 유형 · 용수 · 깊이 · 시공량 보임 · 1,893 원 · 숨김 0
② 시간당 식(굳음 0201-0100) = 유형 · 용수 · 깊이 · 시공량 · 대수 숨음 · 금액 = 굳히기 전 시간당과 같음 ·
수량 칸 = 「1 ÷ 시간당 작업량」 잠긴 글 · 산출근거 = 식 풀이만(시공량 줄 없음) · 화면 셈 = 서버 셈
③ 기계를 0.6㎥ 로 = 버킷 용량 따라옴 · 금액 = 손셈(단가 ÷ 작업량) · 서버 정리가 덮음을 그대로 둠
④ 덮음 고침 — 일당으로 되돌림 = 덮음 칸 지움(문서 바이트 같음) · 기계 바꿈 규칙(같은 식 = 현장 변수 남김 ·
다른 식 = 버림 + 알림 · 식 없음 = 일당 + 알림)
⑤ 기계 셋 문서(GC000102)에서 굴착기 줄만 = 다른 줄이 읽는 시공량은 남음
⑥ 둘 다 가능한 줄 전수 — 줄마다 시간당으로 바꿔 숨긴 옵션을 다른 값으로 바꿔도 금액 그대로(살아 있는 길이
읽는 것을 숨긴 건수 0) · 차림 멈춤 0
⑦ 기계 밖 겹분수 — 그 줄들이 두 층 넘지 않음(그리기만 · 금액 그대로)
"""
from __future__ import annotations
import copy
import importlib
import json
from decimal import Decimal
import pytest
from resources.tester import test_846_2_work_view as w2
mcv = importlib.import_module("master_doc_cover")
P88 = "P_굴착기무한궤" # GC000088 굴착기 줄 단가 기호 = 덮음 열쇠(847-1)
WORK = "작업량"
base = w2.base # 모듈 차림(문서 · 연결)
def _hourly(doc: dict, machine: str, key: str, **more) -> dict:
out = copy.deepcopy(doc)
out["기계덮음"] = {machine: {WORK: {"방식": "시간당", "식": key, **more}}}
return out
def _num(v):
return None if v is None else float(Decimal(str(v)))
@pytest.fixture(scope="module")
def gc88(base):
d = base[0]["GC000088"]
docs = {
"일당": d,
"시간당": _hourly(d, "0201-0100", "GC001147"), # 846-1 옛 꼴(기계 열쇠 · 굳힘 없음)
"굳음": _hourly(d, P88, "GC001147", 기계="0201-0100"),
"0.6": _hourly(d, P88, "GC001147", 기계="0201-0060", 이름="굴착기 0.6㎥"),
}
cases, py = [], {}
for k, doc in docs.items():
c, a = w2._case(base, k, doc)
cases.append(c)
py[k] = a
got = {g["키"]: g for g in w2._js({"할일": "전수", "문서들": cases, "보기": list(docs)})}
hide = w2._js({"할일": "숨김", "문서들": cases})["숨김"]
return got, py, dict(zip(docs, hide)), cases
def _opts(g) -> list[str]:
return [r["sym"] for r in g["왼쪽"] if r["sym"].startswith("opt:")]
def test_일당_그대로(gc88):
got, py, hide, _ = gc88
g = got["일당"]
assert hide["일당"] == []
assert {"opt:Type", "opt:용수", "opt:깊이"} <= set(_opts(g))
assert any("시공량" in r["t"] for r in g["오른쪽"])
assert not any(r["sym"] == "수량" for r in g["왼쪽"]) # 일당 = 지금 수량 칸
assert _num(py["일당"]["계"]) == g["셈"]["계"] == 1893
def test_시간당_굳음_숨김_금액(gc88):
got, py, hide, _ = gc88
g = got["굳음"]
assert set(hide["굳음"]) >= {"Type", "Q_용수", "H_깊이", "Q_시공", "Q_굴착기^표", "S_굴착기"}
assert not {"opt:Type", "opt:용수", "opt:깊이"} & set(_opts(g))
assert {"opt:지역", "opt:보정작업"} <= set(_opts(g)) # 단가가 읽는 옵션은 남음
# 굳히기 전 시간당(옵션 기계)과 금액 같음 · 화면 셈 = 서버 셈
assert _num(py["굳음"]["계"]) == _num(py["시간당"]["계"]) == g["셈"]["계"] == 1635
w = next(r[WORK] for r in g["셈"]["줄"] if r[WORK])
assert w["꼴"] == "시간당" and w["고정"] == "0201-0100"
qty = next(r for r in g["왼쪽"] if r["sym"] == "수량")
assert qty["t"] == "[1 ÷ 시간당 작업량]" and qty["잠김"]
right = [r["t"] for r in g["오른쪽"]]
assert not any("시공량" in t or "Q_{\\text{시공}}" in t for t in right) # 일당 시공량 줄 없음
assert any(t.startswith("시간당 식") for t in right)
assert g["bad"] == [] and g["같음"]
def test_기계_바꿈_버킷_따라옴_손셈(gc88, base):
got, py, _, cases = gc88
g = got["0.6"]
w = next(r[WORK] for r in py["0.6"]["줄"] if r.get(WORK))
assert w["고정"] == "0201-0060" and str(w["변수"]["버킷용량"]) == "0.6"
# 손셈 — Q = 3,600 × q × K × f × E ÷ cm · 비목마다 단가 ÷ Q(줄 끝수 버림 1 자리)
docs, links = base
price = w2.dc.mc.calc(
docs["GC000267"], links, {"기계": "0201-0060", "지역": "전국평균", "보정작업": "해당 없음"}
)
q = Decimal("3600") * Decimal("0.6") * Decimal("0.9") * Decimal("0.7") * Decimal("0.75") / 20
assert Decimal(str(w["값"])) == q.quantize(Decimal("0.001"))
cut = sum(int(price[k] / q * 10) / Decimal(10) for k in ("노무비", "재료비", "경비"))
assert _num(py["0.6"]["계"]) == g["셈"]["계"] == float(int(cut))
# 서버 정리 = 굳은 기계 작업량 칸 기준 · 덮음 그대로
doc = next(c["문서"] for c in cases if c["키"] == "0.6")
kept = mcv.prune_doc(doc, links)
assert kept["기계덮음"][P88][WORK] == {
"방식": "시간당", "식": "GC001147", "기계": "0201-0060", "이름": "굴착기 0.6㎥"
} # fmt: skip
def test_덮음_고침_되돌림_기계_바꿈_규칙(base):
d = base[0]["GC000088"]
h = _hourly(d, P88, "GC001147", 기계="0201-0100")
info = {"기계": "0201-0100", "기호": P88, "꼴": "시간당", "단위": "㎥/hr", "식들": ["GC001147"]}
spec = [{"식": "GC001147", "단위": "㎥/hr", "변수": {"버킷용량": 1}}]
p06 = {"키": "GC000267", "이름": "굴착기", "규격": "0.6㎥", "입력": {"기계": "'0201-0060'"},
"작업량": [{"식": "GC001147", "단위": "㎥/hr", "변수": {"버킷용량": 0.6}}]} # fmt: skip
dozer = {
**p06,
"입력": {"기계": "'0101-0019'"},
"작업량": [{"식": "GC001144", "단위": "㎥/day"}],
}
other = {**p06, "작업량": [{"식": "GC009999", "단위": "㎥/hr"}]}
mine = {
"방식": "시간당",
"식": "GC001147",
"기계": "0201-0100",
"변수": {"E입력": 0.8, "버킷용량": 0.9},
}
got = w2._js(
{
"할일": "숨김",
"문서들": [],
"덮음": [[h, P88, None]],
"바꿈": [
[mine, info, p06, True, spec],
[mine, info, dozer, False, spec],
[mine, info, other, True, spec],
],
} # fmt: skip
)
norm = w2.dc.ml._norm # 헬퍼에 넘긴 꼴(Decimal → 수)
assert json.dumps(got["덮음"][0], ensure_ascii=False) == json.dumps(norm(d), ensure_ascii=False)
same, none, diff = got["바꿈"]
assert same["next"] == {"방식": "시간당", "식": "GC001147", "변수": {"E입력": 0.8},
"기계": "0201-0060", "이름": "굴착기 0.6㎥"} and same["note"] == "" # fmt: skip
assert "next" not in none and "일당" in none["note"]
assert (
diff["next"]["식"] == "GC009999" and "변수" not in diff["next"] and "버림" in diff["note"]
)
def test_기계_셋_문서_한_줄만(base):
d = base[0]["GC000102"]
_, a = w2._case(base, "x", d)
dig = next(r[WORK] for r in a["줄"] if r.get(WORK) and r[WORK]["기계"] == "0201-0060")
h = _hourly(d, dig["기호"], dig["식들"][0], 기계="0201-0060")
c, ha = w2._case(base, "한 줄", h)
hide = set(w2._js({"할일": "숨김", "문서들": [c]})["숨김"][0])
assert "Q_굴착기^표" in hide and "Q_시공" not in hide # 다른 줄(모터그레이더 · 롤러)이 읽음
kinds = [r[WORK]["꼴"] for r in ha["줄"] if r.get(WORK)]
assert kinds.count("시간당") == 1 and len(kinds) == 4 # 굴착기 줄만 시간당
def _alts(v: dict) -> list:
link = v.get("연결") or {}
now = link.get("값")
if link.get("갈래") == "선택":
return [x for x in link.get("목록") or [] if str(x) != str(now)]
try:
return [float(now) * 1.5 + 1]
except (TypeError, ValueError):
return []
def test_전수_둘_다_가능_숨김이_살아_있는_길을_안_가림(base):
docs, links = base
lines, cases = [], []
for key, doc in sorted(docs.items()):
_, a = w2._case(base, key, doc)
for w in [r[WORK] for r in a.get("줄") or [] if isinstance(r, dict) and r.get(WORK)]:
if not w["식들"] or w["꼴"] == "시간당":
continue
h = _hourly(doc, w["기호"], w["식들"][0], 기계=w["기계"])
c, ha = w2._case(base, f"{key}~{w['기계']}", h)
lines.append((key, h, ha))
cases.append(c)
assert len(lines) >= 140
hides = w2._js({"할일": "숨김", "문서들": cases})["숨김"]
shown = w2._js({"할일": "전수", "문서들": cases, "보기": []})
assert all(g["같음"] for g in shown) and len(shown) == len(cases) # 차림 멈춤 0
leak, tried = [], 0
for (key, h, ha), hide in zip(lines, hides):
vars_ = {v.get("열쇠"): v for v in h.get("변수") or [] if v.get("열쇠")}
for name, v in vars_.items():
if w2.dc.md.var_id(v) not in hide:
continue
for alt in _alts(v):
tried += 1
got = w2.dc.mc.calc(h, links, {name: alt})
if got.get("계") != ha.get("계"):
leak.append((key, name, alt))
assert tried >= 20
assert leak == [] # 살아 있는 길이 읽는 옵션을 숨긴 건수 0
def test_기계_밖_겹분수_두_층_넘는_줄_0(base):
keys = sorted({"GC000041", "GC000169", "GC000176", "GC000183", "GC000189", "GC000191",
"GC000274", "GC000346", "GC000377", "GC000490", "GC000491", "GC000493",
"GC000505", "GC000801", "GC000871", "GC001174", "GC001176", "GC001188",
"GC001191", "GF000115", "GF000117", "GF000284", "GF000327"}) # fmt: skip
cases = []
for k in keys:
c, _ = w2._case(base, k, base[0][k])
cases.append({**c, "밖": True})
got = w2._js({"할일": "전수", "문서들": cases, "보기": []})
bad = {g["키"]: [b[1][:90] for b in g["bad"] if b[0] == "겹분수"] for g in got}
assert {k: v for k, v in bad.items() if v} == {}
assert all(g["같음"] for g in got)