diff --git a/B06_Section/B06_Section_Cross_Refresh.ts b/B06_Section/B06_Section_Cross_Refresh.ts index ec199c0e2..2b8ee8076 100644 --- a/B06_Section/B06_Section_Cross_Refresh.ts +++ b/B06_Section/B06_Section_Cross_Refresh.ts @@ -54,7 +54,7 @@ import { import type { ProfileAlignment } from "../B05_Profile/logic/B05_Profile_UI_Profile_Alignment"; import { readAlignment, toDesignProfile } from "../B05_Profile/logic/B05_Profile_UI_Profile_Data"; import { useStationKeys } from "./B06_Section_Station_Keys"; -import { hasStaleDesigns } from "./B06_Section_UI_Section_Common"; +import { hasStaleDesigns, staleKey } from "./B06_Section_UI_Section_Common"; import { applyStructureAreaRows, structureAreaRows } from "./B06_Section_Structure_Layouts"; import { withPipeOptions } from "./B06_Section_Section_Adjusts"; @@ -156,16 +156,26 @@ export function holdScreenAlignment(line: ScreenLine): () => void { }; } -/** 낡음 판정을 화면 선 기준으로 — 저장분 선끼리 견주면 화면과 반대 판정이 났다(341 부록 2 4장). */ -export function staleAgainstScreen(detail: SectionDetailResponse, routeId: number): boolean { +/** 화면 선을 얹은 견줌 꼴 — 화면 선이 없으면 상세 그대로. */ +function againstScreen(detail: SectionDetailResponse, routeId: number) { const screen = screenLine?.(routeId); - if (!screen) return hasStaleDesigns(detail); - return hasStaleDesigns({ + if (!screen) return detail; + return { longitudinal: { design_profiles: [toDesignProfile(screen, detail.longitudinal.design_profiles?.[0])], }, cross_sections: detail.cross_sections, - }); + }; +} + +/** 낡음 판정을 화면 선 기준으로 — 저장분 선끼리 견주면 화면과 반대 판정이 났다(341 부록 2 4장). */ +export function staleAgainstScreen(detail: SectionDetailResponse, routeId: number): boolean { + return hasStaleDesigns(againstScreen(detail, routeId)); +} + +/** 화면 선 기준 낡은 측점 지문(모두 맞으면 "") — 상세 가게가 같은 낡음에 cross 를 되풀이하지 않게(387-8). */ +export function staleKeyAgainstScreen(detail: SectionDetailResponse, routeId: number): string { + return staleKey(againstScreen(detail, routeId)); } /** diff --git a/B06_Section/B06_Section_Section_Store.ts b/B06_Section/B06_Section_Section_Store.ts index 818a387d2..a78f05d03 100644 --- a/B06_Section/B06_Section_Section_Store.ts +++ b/B06_Section/B06_Section_Section_Store.ts @@ -31,7 +31,7 @@ import { withDraftAdjusts, withPipeOptions } from "./B06_Section_Section_Adjusts import type { CrossSectionPatch, SectionDetailResponse } from "./B06_Section_Api_Fetch"; import { forgetCanon, keepCanon, sessionDetail } from "./B06_Section_Section_Canon"; import { fetchSectionDetail, saveSections } from "./B06_Section_Api_Fetch"; -import { USER_TOUCHED_KEYS } from "./B06_Section_Cross_Refresh"; +import { staleKeyAgainstScreen, USER_TOUCHED_KEYS } from "./B06_Section_Cross_Refresh"; import { kindChangedChainages, STRUCTURE_ADJUST_KEYS } from "./B06_Section_Api_Culvert_Options"; import type { PipelineStation } from "../A00_Common/design/logic/design_pipeline_types"; import { @@ -74,7 +74,11 @@ async function withDraftWalls( await withDraftShapes(detail, projectId); withDraftAdjusts(detail, projectId, routeId); // 저장 안 한 조정창 4축 · 구간 · 형식(387-4 · B05 만 열어도) await withPipeOptions(detail, projectId); // 관 옵션 벽 높이 · 형태 · 흙막이 단(387-4b) - return withStructureAreas(detail); + withStructureAreas(detail); + // 초안 자리 미리 뜬 횡단 = 서버가 저장 계획선으로 셈 · 묶음 cross 뒤에 얹힐 수 있음 — 다 돈 뒤 지금 계획선과 + // 갈리면 cross 한 번 더(387-8 · 낡음 판정 = 가게 몫 · 종단 판이 접혀 그리기가 안 돌아도) + recrossSaved(projectId, keyOf(projectId, routeId), detail, routeId); + return detail; } /** @@ -175,20 +179,36 @@ export async function swapSectionStations( return { detail: swap.detail, moves: swap.moves }; } +/** 상세마다 마지막으로 cross 를 부탁한 낡음 지문 — 다시 셈이 못 고친 낡음에 되풀이하지 않음(387-8). */ +const askedStale = new WeakMap(); + /** 저장 노선 측점을 갈아끼움 — 그 차례 cross 는 옛 상세를 봐서 새 상세 설계 · 면적이 안 셈 → 묶음이 다 돈 뒤(새 측점 * 종단 · 화면 선이 선 뒤 · 그 전에 세면 계획고 0.5 mm 갈림) cross 한 번 더(387-4b · B05 만 연 면적 = B06). 노선 초안 - * 동안은 묶음 새 노선 상세가 맡음. 묶음은 늦게 불러옴(가게 ↔ 묶음 순환 없음). */ -function recrossSaved(projectId: string, key: string, detail: SectionDetailResponse): void { + * 동안은 묶음 새 노선 상세가 맡음. 묶음은 늦게 불러옴(가게 ↔ 묶음 순환 없음). + * `staleOf`(노선 번호)를 주면 화면 선 대비 낡을 때만 · 같은 낡음은 한 번만(387-8 · 묶음이 아직 안 섰으면 그 첫 차례 몫). */ +function recrossSaved( + projectId: string, + key: string, + detail: SectionDetailResponse, + staleOf?: number, +): void { void Promise.all([ import("../A00_Common/design/design_pipeline_cross"), import("../A00_Common/design/design_pipeline_page"), ]) .then(async ([cross, page]) => { - await page.reconcilePagePipeline(projectId); + // 낡음 확인 = 지금 차례만 기다림(맞춤은 묶음 몫 · 읽을 때마다 맞추면 되돌리기 차례가 갈림) + if (staleOf === undefined) await page.reconcilePagePipeline(projectId); + else await page.pagePipeline(projectId)?.settled(); // 그 사이 다른 상세 · 다시 셈 창구 없음(묶음만 · 시험) · 노선 초안 = 안 부탁 if (cache.get(key) !== detail) return; - if (!page.pipelineOwnsCross(projectId) || page.pagePipeline(projectId)?.input("route")) - return; + const pipe = page.pagePipeline(projectId); + if (!page.pipelineOwnsCross(projectId) || pipe?.input("route")) return; + if (staleOf !== undefined) { + const stale = pipe?.generation ? staleKeyAgainstScreen(detail, staleOf) : ""; + if (!stale || askedStale.get(detail) === stale) return; + askedStale.set(detail, stale); + } cross.forceCross(); page.pipelineCross(projectId); }) diff --git a/resources/tester/helper_387_8_folded_profile.cjs b/resources/tester/helper_387_8_folded_profile.cjs new file mode 100644 index 000000000..cd0e0dc96 --- /dev/null +++ b/resources/tester/helper_387_8_folded_profile.cjs @@ -0,0 +1,209 @@ +/* 387-8 헬퍼 — 종단 판이 접힘(그리기 · 그리기 낡음 판정 없음) + 관 초안 둔 채 다시 열기: 진짜 상세 가게 + * (`B06_Section_Section_Store`) · 진짜 낡음 판정(`B06_Section_Cross_Refresh` staleKeyAgainstScreen)이 묶음 cross + * 뒤에 얹힌 미리 뜬 측점(서버가 옛 계획고로 셈)을 보고 묶음에 cross 한 번 더 부탁하는지. 묶음 · 초안 얹기 · 서버는 가짜 — + * 가짜 cross = 상세 측점마다 계획고를 지금 계획선으로(면적 = 계획고 함수). 짝 = `test_387_8_folded_profile.py`. + */ +const fs = require("fs"); +const path = require("path"); +const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript")); +const CATALOG = require("./helper_322_catalog_module.cjs"); + +const ROOT = path.join(__dirname, "..", ".."); +const P = "P387"; +const ROUTE = 7; +const PLAN = 100; // 지금 계획선(평평) + +function memoryStorage() { + const map = new Map(); + return { + getItem: (k) => (map.has(k) ? map.get(k) : null), + setItem: (k, v) => map.set(k, String(v)), + removeItem: (k) => map.delete(k), + key: (i) => [...map.keys()][i] ?? null, + get length() { + return map.size; + }, + }; +} +globalThis.window = { sessionStorage: memoryStorage(), localStorage: memoryStorage() }; + +const anyModule = (extra = {}) => + new Proxy(extra, { get: (t, key) => (key in t ? t[key] : () => undefined) }); + +/** 가짜 계산 묶음 — 부탁 수 · 강제 수 · cross = 상세 계획고 맞춤. */ +const pipe = { generation: 1, route: null, crosses: 0, forced: 0, fix: true }; +const areaOf = (elevation) => Math.round((elevation - 90) * 1000) / 1000; +function cross() { + pipe.crosses += 1; + if (!pipe.fix) return; + for (const section of storeDetail().cross_sections) { + section.design = { + ...section.design, + design_elevation_m: PLAN, + cut_area_m2: areaOf(PLAN), + }; + } +} +let previewAt = null; // 관 초안 자리(미리 뜬 측점) +const STUBS = { + "design_pipeline_page.ts": { + reconcilePagePipeline: async () => 0, + pipelineOwnsCross: () => true, + pagePipeline: () => ({ + generation: pipe.generation, + input: () => pipe.route, + settled: async () => undefined, + }), + pipelineCross: () => cross(), + }, + "design_pipeline_cross.ts": { forceCross: () => void (pipe.forced += 1) }, + // 초안 측점 — 관 초안 자리에 서버가 미리 뜬 횡단(저장 계획선 = 옛 계획고 102)을 얹음 + "B06_Section_Section_Drafts.ts": { + forgetDraftStations: () => undefined, + withDraftShapes: async () => undefined, + withDraftStations: async (detail) => { + if (previewAt === null || detail.cross_sections.some((s) => s.preview)) return; + detail.cross_sections.push({ + chainage_m: previewAt, + kind: "irregular", + preview: true, + samples: [], + design: { design_elevation_m: 102, cut_area_m2: areaOf(102) }, + }); + detail.cross_sections.sort((a, b) => a.chainage_m - b.chainage_m); + }, + }, + "B05_Profile_Api_PlusStations.ts": { + loadSavedPlusStations: async () => undefined, + plusStationsOf: () => [], + }, + "B05_Profile_Api_Pipes_Draft.ts": { readPendingPipes: () => null }, + "design_page_data.ts": { pagePipes: async () => ({ pipe_points: [] }) }, + "B06_Section_Api_Fetch.ts": anyModule(), + "B06_Section_Api_Culvert_Options.ts": anyModule({ STRUCTURE_ADJUST_KEYS: [] }), + "B06_Section_Swap_Bus.ts": anyModule(), + "B06_Section_Station_Keys.ts": anyModule({ KEYED_STATES: [] }), + "B06_Section_UI_Page_Persist.ts": anyModule(), + "B06_Section_UI_Standard_Panel.ts": anyModule(), + "B06_Section_Cross_Design_Session.ts": anyModule(), + "common_util_cross_design.ts": anyModule(), + "B06_Section_UI_Cross_Culvert_Wire.ts": anyModule(), + "B06_Section_UI_Cross_Ford_Geom.ts": anyModule(), + "B06_Section_UI_Cross_Box_Geom.ts": anyModule(), + "B06_Section_UI_IrregularStations.ts": anyModule({ PIPE_DISPLAY_NAME: {} }), + "B05_Profile_UI_IrregularStations.ts": anyModule({ PIPE_DISPLAY_NAME: {} }), + "config_frontend.ts": anyModule({ PIPE_TYPES: [] }), +}; + +const cache = new Map(); +const resolve = (base) => + [base, `${base}.ts`, path.join(base, "index.ts")].find( + (p) => fs.existsSync(p) && fs.statSync(p).isFile(), + ) ?? `${base}.ts`; +function loadTs(full) { + const stub = STUBS[path.basename(full)]; + if (stub) return stub; + if (cache.has(full)) return cache.get(full); + const js = ts.transpileModule(fs.readFileSync(full, "utf8"), { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }).outputText; + const box = { exports: {} }; + cache.set(full, box.exports); + const near = (request) => { + if (CATALOG.isCatalogRequest(request)) return CATALOG; + const alias = { "@util/": "common_util", "@ui/": "ui_template", "@config/": "config" }; + for (const [prefix, dir] of Object.entries(alias)) + if (request.startsWith(prefix)) + return loadTs(resolve(path.join(ROOT, dir, request.slice(prefix.length)))); + return loadTs(resolve(path.join(path.dirname(full), request))); + }; + new Function("exports", "module", "require", js)(box.exports, box, near); + return box.exports; +} + +const B06 = (f) => path.join(ROOT, "B06_Section", `${f}.ts`); +const store = loadTs(B06("B06_Section_Section_Store")); +const { writeState } = loadTs(path.join(ROOT, "A00_Common", "b_page_state.ts")); +const storeDetail = () => store.peekSectionDetail(P); + +/** 저장 정본 — 격자 0 · 20 · 40 · 60(지금 계획선으로 셈한 설계) · 계획선 평평 100. */ +const canon = () => ({ + longitudinal: { + design_profiles: [ + { + samples: [ + { chainage_m: 0, elevation_m: PLAN }, + { chainage_m: 60, elevation_m: PLAN }, + ], + }, + ], + }, + cross_sections: [0, 20, 40, 60].map((c) => ({ + chainage_m: c, + kind: c === 0 ? "bp" : "regular", + samples: [], + design: { design_elevation_m: PLAN, cut_area_m2: areaOf(PLAN) }, + })), +}); +const tick = () => new Promise((r) => setTimeout(r, 20)); +const sum = () => + Math.round(storeDetail().cross_sections.reduce((a, s) => a + s.design.cut_area_m2, 0) * 1000) / + 1000; +const mixed = () => + storeDetail() + .cross_sections.filter((s) => s.design.design_elevation_m !== PLAN) + .map((s) => s.chainage_m); +const counts = () => ({ crosses: pipe.crosses, forced: pipe.forced }); + +async function open(fresh = true) { + if (fresh) { + store.invalidateSectionDetail(P); + writeState("section-detail", canon(), P, ROUTE); + } + await store.loadSectionDetail(P, ROUTE); + await tick(); +} + +(async () => { + const out = {}; + // 펼친 때 기준 — 미리 뜬 측점이 첫 cross 전에 얹혀 같이 셈 + previewAt = 30; + await open(); + cross(); + out.expanded = { sum: sum(), mixed: mixed() }; + // 접힌 종단 판 + 관 초안 다시 열기 — 미리 뜬 측점이 cross 뒤에 얹힘(그리기 판정 없음) → 가게가 한 번 더 부탁 + Object.assign(pipe, { crosses: 0, forced: 0 }); + await open(); + out.folded = { sum: sum(), mixed: mixed(), ...counts() }; + // 같은 상세 다시 읽음(보기 전환) — 낡음 없음 = 부탁 없음 + await open(false); + out.again = counts(); + // 다시 셈이 못 고치는 낡음 — 한 번만 부탁(되풀이 없음) + Object.assign(pipe, { crosses: 0, forced: 0, fix: false }); + await open(); + await open(false); + await open(false); + out.unfixed = counts(); + pipe.fix = true; + // 묶음이 아직 안 섬(첫 차례 몫) · 노선 초안(묶음 새 노선 상세 몫) = 안 부탁 + Object.assign(pipe, { crosses: 0, forced: 0, generation: 0 }); + await open(); + out.notStarted = counts(); + Object.assign(pipe, { crosses: 0, forced: 0, generation: 1, route: { rev: 1 } }); + await open(); + out.routeDraft = counts(); + pipe.route = null; + // 관 초안 없음 — 낡음 없음 = 부탁 없음 + Object.assign(pipe, { crosses: 0, forced: 0 }); + previewAt = null; + await open(); + out.noDraft = { sum: sum(), ...counts() }; + process.stdout.write(JSON.stringify(out)); +})().catch((error) => { + process.stderr.write(String(error && error.stack ? error.stack : error)); + process.exit(1); +}); diff --git a/resources/tester/test_387_8_folded_profile.py b/resources/tester/test_387_8_folded_profile.py new file mode 100644 index 000000000..2e3f29cb6 --- /dev/null +++ b/resources/tester/test_387_8_folded_profile.py @@ -0,0 +1,55 @@ +"""387-8 종단 판이 접혀도(그리기 낡음 판정 없음) 관 초안 둔 채 다시 열기 = 펼친 때 값 — 미리 뜬 측점 안 섞임. + +· 관 초안 자리 미리 뜬 횡단(서버가 저장 계획선 = 옛 계획고로 셈)이 묶음 cross 뒤에 얹히면 상세 가게가 묶음이 다 돈 뒤 + 화면 선 기준 낡음을 보고 cross 한 번 더(낡음 판정 = 가게 몫 · 원칙 4 — 보기가 숨어도 계산 · 판정은 돎) +· 같은 낡음 = 한 번만 · 묶음이 아직 안 섬 · 노선 초안 = 안 부탁 + +./venv/Scripts/python.exe -m pytest resources/tester/test_387_8_folded_profile.py -q +""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +HELPER = Path(__file__).parent / "helper_387_8_folded_profile.cjs" + + +@pytest.fixture(scope="module") +def out() -> dict: + done = subprocess.run( # noqa: S603 — 고정 실행 파일 + ["node", str(HELPER)], cwd=str(ROOT), capture_output=True, text=True, encoding="utf-8" + ) + assert done.returncode == 0, done.stderr + return json.loads(done.stdout) + + +def test_접힌_종단_판_다시_열기_펼친_때와_같음(out: dict) -> None: + assert out["folded"]["mixed"] == [] and out["expanded"]["mixed"] == [] + assert out["folded"]["sum"] == out["expanded"]["sum"] + assert (out["folded"]["crosses"], out["folded"]["forced"]) == (1, 1) + + +def test_되풀이_없음(out: dict) -> None: + assert out["again"] == {"crosses": 1, "forced": 1} # 다시 읽어도 더 안 부탁 + assert out["unfixed"] == {"crosses": 1, "forced": 1} # 못 고친 낡음 = 한 번만 + + +@pytest.mark.parametrize("case", ["notStarted", "routeDraft", "noDraft"]) +def test_안_부탁(out: dict, case: str) -> None: + assert (out[case]["crosses"], out[case]["forced"]) == (0, 0) + + +def test_부르는_곳() -> None: + store = (ROOT / "B06_Section/B06_Section_Section_Store.ts").read_text(encoding="utf-8") + walls = store.split("async function withDraftWalls", 1)[1].split("\n}\n", 1)[0] + assert "recrossSaved(projectId, keyOf(projectId, routeId), detail, routeId);" in walls + body = store.split("function recrossSaved", 1)[1].split("\n}\n", 1)[0] + assert "staleKeyAgainstScreen(detail, staleOf)" in body and "askedStale" in body + # 종단 판 그리기는 기다림 표시만(다시 셈 부탁 없음 · 387-4) + preview = (ROOT / "B05_Profile/B05_Profile_UI_Profile_Preview.ts").read_text(encoding="utf-8") + assert "forceCross" not in preview