fix(860-10 ①②): B08 구조물 [업데이트] 단추 · 칩 배지 걷음 — 같은 항목 재선택 = 사본 새로 가져옴

- 구조물도 창 칩에서 [업데이트] 단추 · 「고침 있음」 · 「원본이 없어짐」 배지 · 그 셈(사본 목록 대조) 걷음
- 같은 항목을 [선택] 으로 다시 고르면 서버가 그 칸 사본을 M02 지금 값으로 다시 가져옴(입력값 · 고른자재는 같은 키면 살림 · 고친 흔적은 _지난 에 복사)
- 선택 창 아래 안내 글을 B08 에 맞게(바로 저장됨) — 공용 선택 창에 안내 글 넘기는 칸만 더함 · B05 글 불변
- 낡은 글 키 여덟 걷음 · 지킴 시험 새로(재선택) · 칩 단추 줄 시험 한 줄 고침

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 09:06:34 +09:00
co-authored by Claude Sonnet 5.5
parent 5308a718ad
commit 7e18a01550
8 changed files with 149 additions and 97 deletions
-10
View File
@@ -66,11 +66,6 @@
max-width: 100%;
}
.b08-link__chip.is-gone {
border-style: dashed;
border-color: var(--color-danger);
}
.b08-link__state {
overflow: hidden;
max-width: 18rem;
@@ -83,12 +78,7 @@
color: var(--color-danger);
}
.b08-link__badges,
.b08-link__buttons {
display: inline-flex;
gap: var(--spacing-4);
}
.b08-link__badges:empty {
display: none;
}
+8 -72
View File
@@ -6,9 +6,8 @@
* [선택] → 공용 고르기 모달(`openItemPicker` · 누를 때 `import()`) → 바로 저장
* = PUT …/items/{사본 id}/link(그 칸 하나만 정본에 · 서버가 사본 맞춤) → 집계표 다시 셈
* [연결 끊기](연결된 칸만) → 확인 창 → 같은 길에 null(그 칸만 비움 · 사본 폴더 그대로 · 156-1)
* [업데이트](연결된 칸만 · 163-4) = 칩 그린 뒤 `list(사본 폴더)` 로 배지(고침 있음 · 원본이 없어짐) ·
* 원본이 있으면 켬(859-2 「마스터 바뀜」 표시 걷음 · 다시 가져올지는 사용자가) → 확인 창 →
* 고르기 모달 [재적용]과 같은 길(`reapply`)
* 같은 항목을 다시 [선택] = 재선택 — 서버가 그 칸 사본을 M02 지금 값으로 다시 뜸(860-10 ·
* [업데이트] 단추 · 칩 배지 「고침 있음」 · 「원본이 없어짐」 걷음)
* 단추 = 작은 ghost(칩 안 · 163-1)
* B05/B06 세션 초안(구조물 · 관)이 있으면 막고 알림 — 그쪽 [저장]이 목록 통째로 덮어 연결이 사라짐
* ========================================================================== */
@@ -17,11 +16,7 @@ import { ui_locales } from "@ui/ui_template_locale";
import { createButton, showConfirmDialog, showToast } from "@ui/ui_template_elements";
import { attachCollapsible, createCollapsibleHead } from "@ui/ui_template_collapsible";
import { createBadge, type BadgeTone } from "@ui/ui_template_badge";
import {
projectItems,
structureFolder,
type ProjectItemInfo,
} from "@ui/ui_template_item_picker_project";
import { projectItems } from "@ui/ui_template_item_picker_project";
import { readPendingStructures } from "../B05_Profile/B05_Profile_Api_Structures";
import { readPendingPipes } from "../B05_Profile/B05_Profile_Api_Pipes_Draft";
import type { SummaryItem } from "../common_util/common_util_summary_item";
@@ -51,6 +46,7 @@ async function pickAndLink(
canCopy: true,
projectId,
structureId: slot.copy,
saveNote: L("B08_Quantity_Link_PickNote"),
});
if (result.action === "cancel") return false;
const item: SummaryItem | null = result.action === "apply" ? result.item : null;
@@ -84,67 +80,19 @@ async function unlink(projectId: string, facility: UnlinkedFacility, slot: Unlin
}
}
/** [업데이트] — 사본을 원본으로 덮음(입력값 · 고른자재는 같은 키면 서버가 살림) · 했으면 true. */
async function update(projectId: string, info: ProjectItemInfo): Promise<boolean> {
const ask =
L("B08_Quantity_Link_UpdateAsk") + (info.고침 ? ` ${L("B08_Quantity_Link_UpdateEdited")}` : "");
if (!(await showConfirmDialog(ask, L("B08_Quantity_Link_Update")))) return false;
try {
const got = await projectItems(projectId).reapply(info);
showToast(
got.covered.length
? `${L("B08_Quantity_Link_UpdateDone")} — ${got.covered.join(" · ")}`
: L("B08_Quantity_Link_UpdateNone"),
"success",
);
return true;
} catch (error) {
showToast(`${L("B08_Quantity_Link_UpdateFailed")} — ${String(error)}`, "error");
return false;
}
}
type ChipState = "is-linked" | "is-missing" | "is-edited" | "is-gone";
type ChipState = "is-linked" | "is-missing";
const CHIP_TONE: Record<ChipState, BadgeTone> = {
"is-linked": "success",
"is-missing": "danger",
"is-edited": "info",
"is-gone": "danger",
};
/** 칩 = 부품 배지(알약 20) 꼴 · 색 = 상태(연결 초록 · 미연결 빨강 · 고침 파랑 · 없어짐 빨강 점선) */
/** 칩 = 부품 배지(알약 20) 꼴 · 색 = 상태(연결 초록 · 미연결 빨강) */
function toneChip(chip: HTMLElement, state: ChipState): void {
const look = createBadge("", CHIP_TONE[state], { size: 20 });
chip.className = `${look.className} b08-link__chip ${state}`;
chip.dataset.size = look.dataset.size ?? "20";
}
/** 칩 배지 · 테두리 색 · [업데이트] — 사본 목록(원본판 대조)을 뒤에서 받아 칠함 · 못 받으면 단추 꺼진 채. */
async function paintCopyState(
projectId: string,
slot: UnlinkedSlot,
chip: HTMLElement,
badges: HTMLElement,
button: HTMLButtonElement,
): Promise<ProjectItemInfo | null> {
const folder = structureFolder(slot.copy);
const info = await projectItems(projectId)
.list(folder)
.then((rows) => rows.find((row) => row.폴더 === folder) ?? null)
.catch(() => null);
if (!info) return null;
const badge = (key: keyof typeof ui_locales, warn: boolean): HTMLElement =>
createBadge(L(key), warn ? "warning" : "neutral", { size: 18 });
if (info.고침) badges.append(badge("B08_Quantity_Link_Edited", false));
if (info.원본없음) badges.append(badge("B08_Quantity_Link_Gone", true));
// 테두리 상태 색(170-3) — 앞섬 = 없어짐 › 고침 › 연결
const tone = info.원본없음 ? "is-gone" : info.고침 ? "is-edited" : null;
if (tone) toneChip(chip, tone);
button.disabled = !!info.원본없음;
button.title = L(button.disabled ? "B08_Quantity_Link_Gone" : "B08_Quantity_Link_UpdateTip");
return info;
}
/** 「조합 연결」 칸 — 시설마다 한 줄(제목 + 칸 칩) · 공용 접기. `onLinked` = 저장 뒤(모달 닫고 다시 셈). */
export function linkSection(
projectId: string,
@@ -184,8 +132,6 @@ export function linkSection(
? (slot.item?.name ?? L("B08_Quantity_Link_Linked"))
: L("B08_Quantity_Summary_Unlinked");
state.title = state.textContent; // 칩이 좁으면 긴 조합 이름이 잘림
const badges = document.createElement("span");
badges.className = "b08-link__badges";
const buttons = document.createElement("span");
buttons.className = "b08-link__buttons";
const act = (label: string, run: () => Promise<boolean>): HTMLButtonElement =>
@@ -206,19 +152,9 @@ export function linkSection(
buttons.append(
act(L("B08_Quantity_Link_Pick"), () => pickAndLink(projectId, facility, slot)),
);
if (slot.linked) {
if (slot.linked)
buttons.append(act(L("B08_Quantity_Link_Unlink"), () => unlink(projectId, facility, slot)));
let info: ProjectItemInfo | null = null;
const updateButton = act(L("B08_Quantity_Link_Update"), () =>
info ? update(projectId, info) : Promise.resolve(false),
);
updateButton.disabled = true; // 원본판 대조를 받기 전엔 꺼 둠
buttons.append(updateButton);
void paintCopyState(projectId, slot, chip, badges, updateButton).then(
(got) => (info = got),
);
}
chip.append(name, state, badges, buttons);
chip.append(name, state, buttons);
line.append(chip);
}
section.append(line);
+23
View File
@@ -11,6 +11,7 @@
from __future__ import annotations
import re
import shutil
from collections.abc import Callable
from pathlib import Path
from typing import Any
@@ -19,6 +20,7 @@ from B05_Profile.B05_Profile_Structures_Repository import load_structures, save_
from common_util.common_util_drainage_pipes import pipe_points_path_in
from common_util.common_util_json import atomic_write_json
from common_util.common_util_summary_item import GROUP_JOIN
from common_util.common_util_time import kst_now
from M02_MasterTemplete import M02_Item_Personal as personal
from M02_MasterTemplete import M02_Item_Prices as prices
from M02_MasterTemplete import M02_Template_Layers as layers
@@ -27,6 +29,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import (
FOLDER_PATTERN,
LOCAL_FILES,
MANIFEST_NAME,
PAST_DIRNAME,
PICKS_FILE,
VALUES_FILE,
build_snapshot,
@@ -262,6 +265,26 @@ def reapply(
refresh = reapply # 25-1b 옛 이름(새로 가져오기)
def refresh_same(
project_root: str | Path, copy: str, item: dict[str, Any], who: dict[str, Any] | None = None
) -> dict[str, Any] | None:
"""B08 재선택(860-10) — 그 칸 사본이 이미 같은 항목이면 M02 지금 값으로 다시 뜸(입력값 ·
고른자재는 같은 키면 살림). 사본에서 고친 흔적이 있으면 `_지난/` 에 먼저 복사해 둠.
사본이 없거나 다른 항목이면 None(저장 뒤 사본 맞춤이 새로 뜸)."""
folder = folder_name(copy)
if not FOLDER_PATTERN.match(folder):
return None
target = structures_dir(project_root) / folder
manifest = read_json(target / MANIFEST_NAME)
if not same_item(manifest, item):
return None
if manifest.get("고침"):
past = target.parent / PAST_DIRNAME
past.mkdir(parents=True, exist_ok=True)
shutil.copytree(target, past / f"{folder}_{kst_now():%Y%m%d%H%M%S}")
return reapply(project_root, folder, who)
def prefetch(project_root: str | Path, owner_id: str, item: dict[str, Any]) -> dict[str, Any]:
"""구조물 복사본을 미리 가져옴(아직 [저장] 전) — 같은 항목이면 그대로 · 다르면 새로.
+11 -3
View File
@@ -10,8 +10,9 @@
POST …/items/{폴더}/reapply 재적용(입력값 · 고른자재는 같은 키면 살림 · `덮임` 알림)
POST …/items/{폴더}/save-as {to, 경로, 이름} 개인 층에 새 항목으로(단가 묶음은 안 가져감)
PUT …/items/{사본 id}/link {summary_item | null, facility} B08 바로 연결(154-2) — 그 시설
조합 칸 하나만 정본에 씀 → 사본 맞춤 → {폴더, snapshot_failed} · null = 끊기(156-1 ·
맞춤 안 함 · 사본 폴더 그대로)
조합 칸 하나만 정본에 씀 → 사본 맞춤 → {폴더, snapshot_failed, 덮임} · 같은 항목을 다시
고르면 사본을 M02 지금 값으로 다시 뜸(860-10) · null = 끊기(156-1 · 맞춤 안 함 ·
사본 폴더 그대로)
POST …/items/{폴더}/calc 복사본만으로 계산 — 층 셈 한 벌(142-1 · 줄 · 자재 ·
기준합 · 반영합 + 알약 · 빠진입력 · 빈 입력 = 자동값)
종류 = 도면 · 면적 · 입력값 · 고른자재 · 일위대가(읽기만 · 쓰면 400) ·
@@ -168,11 +169,18 @@ async def link_item(
except LookupError as error:
raise HTTPException(status_code=404, detail=str(error)) from error
root = await _root(session, project_id)
refreshed = None
if item is not None: # 같은 항목 재선택(860-10) = 그 칸 사본을 M02 지금 값으로 다시 뜸
refreshed = await _run(copies.refresh_same, root, copy, item, importer(session))
await _run(copies.link, root, copy, body.facility, item)
if item is None: # 끊기(156-1) — 맞춤은 고아 사본을 지우므로 안 부름 · 사본 폴더 그대로
return {"폴더": folder_name(copy), "snapshot_failed": []}
failed = await asyncio.to_thread(safe_sync, root, importer(session))
return {"폴더": folder_name(copy), "snapshot_failed": failed}
return {
"폴더": folder_name(copy),
"snapshot_failed": failed,
"덮임": refreshed["덮임"] if refreshed else None,
}
def _recalc(document: dict) -> dict:
+1 -1
View File
@@ -90,7 +90,7 @@ def test_집계_모든_시설_칸_끊으면_미연결(root, monkeypatch):
def test_화면_연결된_칸만_끊기_닫기_양식():
ui = (ROOT / "B08_Quantity/B08_Quantity_UI_Link.ts").read_text(encoding="utf-8")
assert "if (slot.linked) {" in ui
assert "if (slot.linked)" in ui
assert 'act(L("B08_Quantity_Link_Unlink"), () => unlink(projectId, facility, slot))' in ui
assert ".link(slot.copy, facility.facility, null)" in ui
assert 'showConfirmDialog(L("B08_Quantity_Link_UnlinkAsk")' in ui
@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*-
"""B08 구조물 재선택(860-10) — 같은 항목을 다시 고르면 그 칸 사본이 M02 지금 값으로 다시 뜸.
[업데이트] 단추를 걷고 [선택] 재선택으로만 새 값을 받음 — 임시 저장소.
"""
from __future__ import annotations
import json
import shutil
from pathlib import Path
import pytest
from config import config_system
from M02_MasterTemplete import M02_Item_Copy as copies
from M02_MasterTemplete import M02_Item_Snapshot as snap
from M02_MasterTemplete import M02_Template_Layers as layers
from resources.tester.helper_m02_master_sample import SAMPLE
MS = {"layer": "system", "owner": None, "key": "SS000022", "name": "돌쌓기"}
RV = {"layer": "system", "owner": None, "key": "SS000001", "name": "돌기슭막이 메쌓기 1.2m"}
STRUCTURES = [
{"structure_id": "st1", "type_id": "open_ditch", "placement": "point", "chainage_m": 400,
"summary_item": MS},
] # fmt: skip
@pytest.fixture
def env(tmp_path: Path, monkeypatch):
system = tmp_path / "master"
system.mkdir()
shutil.copy2(SAMPLE / layers.COMBO_FILE, system / layers.COMBO_FILE)
for kind in ("table", "structure", "area"):
shutil.copytree(SAMPLE / kind, system / kind)
monkeypatch.setattr(layers, "SYSTEM_ROOT", system)
monkeypatch.setattr(config_system, "STORAGE_BASE_DIR", str(tmp_path / "storage"))
found = tmp_path / "storage" / "3" / "12" / "proj"
route = found / "B05_Profile/route"
route.mkdir(parents=True)
(route / "structures.json").write_text(
json.dumps({"revision": 1, "structures": STRUCTURES}, ensure_ascii=False),
encoding="utf-8",
)
snap.sync_snapshots(found)
return found, system
def _source_file(system: Path) -> Path:
combo = json.loads((system / layers.COMBO_FILE).read_text(encoding="utf-8"))
row = next(r for r in combo["줄"] if r["키"] == MS["key"])
return system / "structure" / f"{row['열']}.json"
def _copy_dir(found: Path) -> Path:
return snap.structures_dir(found) / "st1"
def test_같은_항목_재선택은_M02_지금_값으로_새_사본(env):
found, system = env
source = _source_file(system)
old = json.loads(source.read_text(encoding="utf-8"))
assert json.loads((_copy_dir(found) / "도면.json").read_text(encoding="utf-8")) == old
new = {**old, "재선택시험": "새 값"}
source.write_text(json.dumps(new, ensure_ascii=False), encoding="utf-8")
# 사본은 굳어 있음 — 재선택 전엔 옛 값 그대로
assert json.loads((_copy_dir(found) / "도면.json").read_text(encoding="utf-8")) == old
got = copies.refresh_same(found, "st1", MS)
assert got is not None and "도면" in got["덮임"]
assert json.loads((_copy_dir(found) / "도면.json").read_text(encoding="utf-8")) == new
def test_입력값은_같은_키면_살리고_고침은_지난에_복사(env):
found, system = env
values = _copy_dir(found) / snap.VALUES_FILE
kept = {"로직": {"입력": {"값": 5, "확인": True}}}
# 사본에 없는 로직 키는 안 살아남음 — 있는 키만 살림(서버 규칙) · 여기선 빈 값 그대로 확인
values.write_text(json.dumps(kept, ensure_ascii=False), encoding="utf-8")
manifest = _copy_dir(found) / snap.MANIFEST_NAME
body = json.loads(manifest.read_text(encoding="utf-8"))
manifest.write_text(json.dumps({**body, "고침": True}, ensure_ascii=False), encoding="utf-8")
old_drawing = (_copy_dir(found) / "도면.json").read_text(encoding="utf-8")
copies.refresh_same(found, "st1", MS)
after = json.loads(manifest.read_text(encoding="utf-8"))
assert after["고침"] is False
past = list((_copy_dir(found).parent / snap.PAST_DIRNAME).iterdir())
assert len(past) == 1 and past[0].name.startswith("st1_")
assert (past[0] / "도면.json").read_text(encoding="utf-8") == old_drawing
assert json.loads((past[0] / snap.VALUES_FILE).read_text(encoding="utf-8")) == kept
def test_사본_없거나_다른_항목이면_안_함(env):
found, _ = env
assert copies.refresh_same(found, "st1", RV) is None # 다른 항목 = 맞춤이 새로 뜸
assert copies.refresh_same(found, "nope", MS) is None # 사본 없음
assert copies.refresh_same(found, "../x", MS) is None # 폴더 이름 모양이 아님
+8 -1
View File
@@ -66,6 +66,8 @@ export interface ItemPickerOptions {
projectId?: string | null;
/** 고르는 구조물의 id(`structure_id` · 관 지점 `pipe@측점`) — 복사본이 이 구조물 것 · 없으면(추가 전) 원본 보기만 */
structureId?: string | null;
/** 프로젝트 안 아래 안내 글 — 없으면 B05 · B06 용(「[적용] 뒤 구조물 [저장]을 눌러야 …」) */
saveNote?: string;
}
export type ItemPickerResult =
@@ -434,7 +436,12 @@ export function openItemPicker(opts: ItemPickerOptions): Promise<ItemPickerResul
const actions = el("div", {
className: "ui-item-picker__actions",
children: opts.projectId
? [el("span", { className: "ui-item-picker__saveline", text: NEW_TEXT.saveLine })]
? [
el("span", {
className: "ui-item-picker__saveline",
text: opts.saveNote ?? NEW_TEXT.saveLine,
}),
]
: [],
});
+2 -10
View File
@@ -54,16 +54,8 @@ export const ui_locales_b4 = {
B08_Quantity_Link_UnlinkAsk: "이 칸의 구조물 조합을 풂 — 이 공사 사본은 남음",
B08_Quantity_Link_Unlinked: "구조물 조합을 풀었음",
B08_Quantity_Link_UnlinkFailed: "연결을 끊지 못했습니다",
B08_Quantity_Link_Update: "업데이트",
B08_Quantity_Link_UpdateTip: "원본을 다시 가져와 이 사본에 덮음",
B08_Quantity_Link_UpdateAsk:
"원본을 다시 가져와 이 사본에 덮습니다 — 입력값 · 고른 자재는 살리고(같은 키) 도면 · 면적산출 · 일위대가는 원본 것으로 덮습니다.",
B08_Quantity_Link_UpdateEdited: "이 사본에서 고친 것이 덮입니다.",
B08_Quantity_Link_UpdateDone: "업데이트했습니다 — 덮인 것",
B08_Quantity_Link_UpdateNone: "업데이트했습니다 — 덮인 것 없음(원본과 같았음)",
B08_Quantity_Link_UpdateFailed: "업데이트하지 못했습니다",
B08_Quantity_Link_Edited: "고침 있음",
B08_Quantity_Link_Gone: "원본이 없어짐",
B08_Quantity_Link_PickNote:
"[적용]하면 바로 저장됨 — 같은 항목을 다시 선택하면 M02 의 지금 값으로 이 공사 사본을 새로 가져옴",
B08_Quantity_Link_Pending:
"B05 · B06 에 저장 안 한 조작이 있습니다 — B05 · B06 [저장] 먼저 누른 뒤 연결하세요.",
B05_Design_Leave: "B05 · B06 에 저장 안 한 조작이 있음",