/* ============================================================================= * common_util_line_stack_diff.ts * 바뀐 자리 지도(PLAN 848-8 · 요구 889) — 지금 문서를 위 층 문서와 칸 단위로 맞댐 · 화면 · DOM · fetch 없음(시험이 Node 로 돌림) * 위 층(서버 읽기 답 `층바탕.위`) = M01 기초 = 빌더가 지은 문서 · M02 단가산출 = 그 기초 문서(지금) · 가져온 식 = 불러올 때 문서 * 그 위(`층바탕.빌더` · SK 만) = 기초가 손고침일 때 빌더 문서 — 기초에서 관리자가 바꾼 칸(주황) * 칸 경로 = `v:<기호>`(값 정의 — 연결 · 식 줄 · 이름 · 옵션 · 공식 값 · 표 값 · 자원) · `u:<기호>`(단위) · * `m:<금액 줄>:<이름 | 단가 | 수량 | 단위 | 비목>` · `t:<항목>`(제목) · `g:<항목>.<줄>`(글 줄) * 금액 줄 짝 = 단가 글(같으면 차례대로) › 남은 줄은 이름 · 줄 틀 = 더한 줄 · 차례 바뀐 줄 · 빠진 줄 = 항목마다 되살림 목록 * 견줌 = 수 · 수 글 같음 · 빈 칸 = 없음 · 글 사이 띄어쓰기 무시(표시 탓 다름 0) * 되돌림 = 칸 하나(`resetPath`) · 빠진 줄 되살림(`restoreLines` — 그 줄이 부르는 기호까지) — 부른 쪽 `change` 안에서 * ========================================================================== */ import { names, varId, type DocVar, type FormulaDoc, type MoneyLine, } from "./common_util_formula_doc"; import { newVar, nodeOf, stackOf, usesOf, type StackDoc, type StackItem, } from "./common_util_line_stack"; export type DiffKind = "mine" | "upper"; /** 칸 표시 — `was` = 되돌릴 값(나) · 바꾸기 전 값(위) · `back` = 되돌릴 값이 있음 */ export interface DiffMark { diff: DiffKind; was: unknown; back: boolean; } export interface DocDiff { marks: Map; /** 지금 금액 줄 → 줄 틀(더한 줄 · 차례 바뀐 줄) */ lines: Map; /** 지금 항목 → 빠진 줄(`src` 문서 금액 차례) */ gone: Map; /** 지금 금액 줄 → 위 층 금액 줄(-1 = 더한 줄) */ match: number[]; } export const LINE_FIELDS = ["이름", "단가", "수량", "단위", "비목"] as const; type Line = MoneyLine & { 규격?: string }; /** 견줌 꼴 — 수 글 = 수 · 빈 값 = undefined · 글 띄어쓰기 뺌 · 묶음 칸 차례 정렬 */ export function canon(x: unknown): unknown { if (x === null || x === undefined) return undefined; if (typeof x === "string") { const t = x.replace(/\s+/g, ""); if (!t) return undefined; const n = Number(t.replace(/,/g, "")); return /^-?[\d,]*\.?\d+$/.test(t) && Number.isFinite(n) ? n : t; } if (Array.isArray(x)) return x.length ? x.map(canon) : undefined; if (typeof x === "object") { const out: Record = {}; for (const k of Object.keys(x).sort()) { const v = canon((x as Record)[k]); if (v !== undefined) out[k] = v; } return Object.keys(out).length ? out : undefined; } return x; } export const same = (a: unknown, b: unknown): boolean => JSON.stringify(canon(a)) === JSON.stringify(canon(b)); const varsOf = (d: FormulaDoc): Map => new Map((d.변수 ?? []).map((v) => [varId(v), v])); const stepsOf = (d: FormulaDoc): Map => new Map((d.식 ?? []).map((l) => [String(l.기호 ?? ""), String(l.식 ?? "")])); /** 칸 경로 값(`v:` = {연결, 식, 이름} · 없는 기호 = undefined) */ function valueAt(vars: Map, steps: Map, id: string) { const v = vars.get(id); const s = steps.get(id); return v || s !== undefined ? { 변수: !!v || undefined, 연결: v?.연결, 식: s, 이름: v?.이름 } : undefined; } const lineVal = (l: Line | undefined, f: string): unknown => !l ? undefined : f === "이름" ? { 이름: l.이름, 규격: l.규격 } : (l as Record)[f]; /** 금액 줄 짝 — 지금 차례 → 위 층 차례(-1 = 없음) */ export function matchLines(now: MoneyLine[], up: MoneyLine[]): number[] { const pool = new Map(); up.forEach((l, j) => { const k = JSON.stringify(canon(l.단가)); pool.set(k, [...(pool.get(k) ?? []), j]); }); const out = now.map((l) => pool.get(JSON.stringify(canon(l.단가)))?.shift() ?? -1); const free = up.map((_, j) => j).filter((j) => !out.includes(j)); now.forEach((l, i) => { if (out[i] >= 0 || canon(l.이름) === undefined) return; const at = free.findIndex((j) => same(up[j].이름, l.이름)); if (at >= 0) out[i] = free.splice(at, 1)[0]; }); return out; } /** 차례가 바뀐 짝 줄 — 가장 긴 오름 차례에 안 든 것 */ function movedOf(match: number[]): Set { const at = match.map((b, i) => [b, i]).filter(([b]) => b >= 0); const len: number[] = []; const prev: number[] = []; at.forEach(([b], k) => { len[k] = 1; prev[k] = -1; for (let p = 0; p < k; p++) if (at[p][0] < b && len[p] + 1 > len[k]) [len[k], prev[k]] = [len[p] + 1, p]; }); const keep = new Set(); for (let k = len.indexOf(Math.max(0, ...len)); k >= 0; k = prev[k]) keep.add(at[k][1]); return new Set(at.map(([, i]) => i).filter((i) => !keep.has(i))); } const itemOfLine = (items: StackItem[]): Map => { const out = new Map(); items.forEach((it, k) => it.줄.forEach((l) => l.꼴 === "금액" && out.set(l.i, k))); return out; }; /** 지금 항목 → 위 층 항목(그 항목 금액 줄의 짝 · 없으면 같은 차례) */ function itemsMatch(now: StackItem[], up: StackItem[], match: number[]): number[] { const upOf = itemOfLine(up); const out = now.map((it) => { const l = it.줄.find((x) => x.꼴 === "금액" && match[x.i] >= 0); return l && l.꼴 === "금액" ? (upOf.get(match[l.i]) ?? -1) : -1; }); out.forEach((b, k) => { if (b < 0 && k < up.length && !out.includes(k)) out[k] = k; }); return out; } /** 지금 문서 대 위 층 · (있으면) 그 위 — 바뀐 자리 지도 */ export function docDiff(now: StackDoc, up: StackDoc, top?: StackDoc | null): DocDiff { const out = mineDiff(now, up); if (!top) return out; const t = mineDiff(up, top); // 위 층 좌표 — 위 층에서 바뀐 칸 const put = (p: string, m: DiffMark | undefined): void => { if (m && !out.marks.has(p)) out.marks.set(p, { diff: "upper", was: m.was, back: false }); }; for (const [p, m] of t.marks) if (/^[vu]:/.test(p)) put(p, m); const ni = stackOf(now); const im = itemsMatch(ni, stackOf(up), out.match); out.match.forEach((b, i) => { if (b < 0) return; for (const f of LINE_FIELDS) put(`m:${i}:${f}`, t.marks.get(`m:${b}:${f}`)); if (t.lines.has(b) && !out.lines.has(i)) out.lines.set(i, "upper"); }); const back = new Set(matchLines(now.금액 ?? [], top.금액 ?? [])); // 되살린 줄 = 빠짐 아님 im.forEach((b, k) => { if (b < 0) return; put(`t:${k}`, t.marks.get(`t:${b}`)); const at = (t.gone.get(b)?.at ?? []).filter((x) => !back.has(x)); if (at.length && !out.gone.has(k)) out.gone.set(k, { diff: "upper", src: top, at }); }); return out; } function mineDiff(now: StackDoc, up: StackDoc): DocDiff { const marks = new Map(); const mark = (p: string, a: unknown, b: unknown): void => { if (!same(a, b)) marks.set(p, { diff: "mine", was: b, back: canon(b) !== undefined }); }; const [nv, uv, ns, us] = [varsOf(now), varsOf(up), stepsOf(now), stepsOf(up)]; for (const id of new Set([...nv.keys(), ...ns.keys()])) { mark(`v:${id}`, valueAt(nv, ns, id), valueAt(uv, us, id)); if (uv.has(id) || nv.get(id)?.단위) mark(`u:${id}`, nv.get(id)?.단위, uv.get(id)?.단위); } const [nl, ul] = [(now.금액 ?? []) as Line[], (up.금액 ?? []) as Line[]]; const match = matchLines(nl, ul); const lines = new Map(); match.forEach((b, i) => { if (b < 0) return void lines.set(i, "mine"); for (const f of LINE_FIELDS) mark(`m:${i}:${f}`, lineVal(nl[i], f), lineVal(ul[b], f)); }); for (const i of movedOf(match)) lines.set(i, "mine"); const [ni, ui] = [stackOf(now), stackOf(up)]; const im = itemsMatch(ni, ui, match); ni.forEach((it, k) => { const b = ui[im[k]]; mark(`t:${k}`, it.제목, b?.제목); const was = (b?.줄 ?? []).filter((l) => l.꼴 === "글"); let n = 0; it.줄.forEach( (l, j) => l.꼴 === "글" && mark(`g:${k}.${j}`, l.글, (was[n++] as { 글?: string })?.글), ); }); const gone = new Map(); const upOf = itemOfLine(ui); ul.forEach((_, b) => { if (match.includes(b) || !ni.length) return; const bi = upOf.get(b) ?? 0; const k = im.includes(bi) ? im.indexOf(bi) : Math.min(bi, ni.length - 1); const g = gone.get(k) ?? { diff: "mine" as DiffKind, src: up, at: [] }; g.at.push(b); gone.set(k, g); }); return { marks, lines, gone, match }; } // ── 되돌림(부른 쪽 `change` 안 · 문서 · 차림을 고침) ── const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; /** 칸 하나를 `was` 로(경로 꼴 그대로) */ export function resetPath(d: StackDoc, items: StackItem[], path: string, was: unknown): void { const [kind, rest] = [path.slice(0, 1), path.slice(2)]; if (kind === "v") return setValue(d, rest, was as ReturnType); if (kind === "u") { const v = (d.변수 ?? []).find((x) => varId(x) === rest); if (v && canon(was) === undefined) delete v.단위; else if (v) v.단위 = String(was); return; } if (kind === "m") { const [i, f] = [Number(rest.split(":")[0]), rest.split(":")[1]]; const l = (d.금액 ?? [])[i] as Line | undefined; if (!l) return; const put = (k: string, x: unknown): void => { if (x === undefined || x === null) delete (l as Record)[k]; else (l as Record)[k] = clone(x); }; if (f === "이름") { const w = (was ?? {}) as { 이름?: string; 규격?: string }; put("이름", w.이름); put("규격", w.규격); } else put(f, was); return; } if (kind === "t" && items[Number(rest)]) items[Number(rest)].제목 = String(was ?? ""); if (kind === "g") { const [k, j] = rest.split(".").map(Number); const l = items[k]?.줄[j]; if (l?.꼴 === "글") l.글 = String(was ?? ""); } } function setValue(d: StackDoc, id: string, was: ReturnType): void { d.변수 = (d.변수 ?? []).filter((x) => varId(x) !== id || was?.변수); let v = d.변수.find((x) => varId(x) === id); if (was?.변수 && !v) d.변수.push((v = newVar(id, undefined))); if (v) { if (was?.연결 === undefined) delete v.연결; else v.연결 = clone(was.연결); if (was?.이름 === undefined) delete v.이름; else v.이름 = was.이름; } d.식 = (d.식 ?? []).filter((l) => String(l.기호 ?? "") !== id); if (was?.식 !== undefined) d.식.push({ 기호: id, 식: was.식 }); } /** 빠진 줄 되살림 — `src` 금액 줄 `at` 을 제 그룹(`home` · 그룹째 빠졌으면 제목째 새로 · 제목 없음 = 항목 `k`)에 * (앞 짝 줄 뒤) · 그 줄이 부르는 기호 중 없는 것도 */ export function restoreLines( d: StackDoc, items: StackItem[], src: StackDoc, at: number[], k: number, ): void { const it = items[k]; if (!it) return; const have = new Set([...varsOf(d).keys(), ...stepsOf(d).keys()]); const uses = usesOf(src); const [sv, ss] = [varsOf(src), stepsOf(src)]; const pull = (id: string): void => { if (have.has(id) || (!sv.has(id) && !ss.has(id))) return; have.add(id); if (sv.has(id)) (d.변수 ??= []).push(clone(sv.get(id)!)); if (ss.has(id)) (d.식 ??= []).push({ 기호: id, 식: ss.get(id)! }); (uses.get(id) ?? []).forEach(pull); }; const match = matchLines(d.금액 ?? [], src.금액 ?? []); const srcItems = stackOf(src); const srcOf = itemOfLine(srcItems); for (const b of [...at].sort((x, y) => x - y)) { const line = clone((src.금액 ?? [])[b]); if (!line) continue; for (const t of [line.수량, line.단가]) { const n = nodeOf(t); if (n) names(n).forEach(pull); } const n = (d.금액 ??= []).push(line) - 1; match[n] = b; const into = home(items, srcItems, srcOf.get(b) ?? -1) ?? it; let p = 0; // 앞 짝 줄 뒤 into.줄.forEach((l, j) => { if (l.꼴 === "금액" && match[l.i] >= 0 && match[l.i] < b) p = j + 1; }); into.줄.splice(p, 0, { 꼴: "금액", i: n }); } } /** 되살릴 줄의 제 그룹(848-10) — `src` 그룹 제목이 있으면 그 제목 항목 › 없으면 새 항목 * (`src` 차례에서 앞 그룹들 뒤) · 제목 없음 = undefined(누른 항목) */ function home(items: StackItem[], src: StackItem[], si: number): StackItem | undefined { const title = src[si]?.제목 ?? ""; if (!title) return undefined; const have = items.find((x) => x.제목 === title); if (have) return have; const before = new Set(src.slice(0, si).map((x) => x.제목)); let at = 0; items.forEach((x, j) => before.has(x.제목) && (at = j + 1)); const it: StackItem = { 제목: title, 줄: [] }; items.splice(at, 0, it); return it; }