Merge remote-tracking branch 'origin/sub_laptop_7' into main_laptop_1

This commit is contained in:
2026-10-16 15:20:50 +09:00
3 changed files with 361 additions and 6 deletions
+17 -6
View File
@@ -195,6 +195,16 @@ function createPagePipeline(
let canon: { routeId: unknown; samples: unknown; detail: SectionDetailResponse | null } | null =
null;
let shown: SectionDetailResponse | null = null;
/** 이 묶음이 지은 새 노선 상세들 — 횡단 보기 카드가 그것을 종단도에 그려도 저장 정본이 아님. */
const drafted = new WeakSet<SectionDetailResponse>();
let lastSaved: ReturnType<ProfileLink["pipelineSource"]> | null = null;
/** 종단도가 내준 저장 기준 — 종단도가 묶음 새 노선 상세를 그리는 동안은 그 앞 저장 기준(고리 끊음 ·
* 새 노선 상세 → 정본으로 오인 → 처음부터 다시 → 새 상세 … 349-0g). */
const savedSource = (): ReturnType<ProfileLink["pipelineSource"]> => {
const now = link.pipelineSource();
if (now.detail && drafted.has(now.detail)) return lastSaved ?? { ...now, detail: null };
return (lastSaved = now);
};
let ready = false;
let started = false;
/** 앞 종단이 노선 초안으로 셈한 것인가 — 초안을 버리면 저장 기준으로 다시 그림. */
@@ -214,7 +224,7 @@ function createPagePipeline(
(plan?.curves ?? []).map(({ start, apex, end, radius_m }) => ({ start, apex, end, radius_m }));
/** 저장 정본이 바뀌었나(새로 받은 상세 · 새 노선) — 바뀌었으면 잡아 둠. */
const canonChanged = (): boolean => {
const { detail = null, routeId } = link.pipelineSource();
const { detail = null, routeId } = savedSource();
const samples = detail?.longitudinal.samples;
if (canon && canon.routeId === routeId && canon.samples === samples) return false;
canon = { routeId, samples, detail };
@@ -238,7 +248,7 @@ function createPagePipeline(
return crossSource.source;
};
const crossStage = createCrossStage();
const haulStage = createHaulStage(projectId, () => link.pipelineSource().routeId ?? undefined);
const haulStage = createHaulStage(projectId, () => savedSource().routeId ?? undefined);
const pipe = createDesignPipeline({
stages: {
route: createRouteStage({
@@ -258,7 +268,7 @@ function createPagePipeline(
}),
stations: createStationsStage({ intervalM: options.stationIntervalM, types: () => types }),
ground: createGroundStage(groundStageDeps(projectId)),
planline: createPlanlineStage({ savedBase: () => link.pipelineSource().base, savedLine }),
planline: createPlanlineStage({ savedBase: () => savedSource().base, savedLine }),
profile: profileStage,
// 단면 유형 기본값 = 새 지형 상단측(서버 노선 저장 규칙) — 단계 본문은 그대로 부름
cross: (ctx) =>
@@ -320,7 +330,7 @@ function createPagePipeline(
pipe.subscribe((event) => {
if (event.kind !== "stage" || (event.stage !== "profile" && event.stage !== "cross")) return;
const draft = pipe.input("route") !== null;
const saved = link.pipelineSource().detail ?? null;
const saved = savedSource().detail ?? null;
const ground = pipe.output("ground");
const profile = pipe.output("profile") as ProfileAlignment | null;
shown =
@@ -334,6 +344,7 @@ function createPagePipeline(
options.stationIntervalM ?? profile.policy.station_interval_m,
)
: null;
if (shown) drafted.add(shown);
if (event.stage === "cross") return void (draft && link.redraw?.());
const base = pipe.output("planline");
const edits = (pipe.input("alignment") as AlignmentEdits | null) ?? emptyEdits();
@@ -363,14 +374,14 @@ function createPagePipeline(
const route = store.get("routeDraft");
return {
route,
alignment: (route && readAlignmentDraft(DRAFT_ROUTE_ID)) || link.pipelineSource().edits,
alignment: (route && readAlignmentDraft(DRAFT_ROUTE_ID)) || savedSource().edits,
cross: crossNow()?.input ?? null,
pipes: store.get("pipes") ?? savedPipes,
structures: store.get("structures") ?? savedStructures,
};
};
const start = (): void => {
if (disposed || !ready || !link.pipelineSource().base) return;
if (disposed || !ready || !savedSource().base) return;
canonChanged();
started = true;
void pipe.start(inputsNow());
@@ -0,0 +1,231 @@
/* PLAN 349-0g sub7 헬퍼 — 노선 초안을 둔 채 횡단 보기(B06)가 묶음 새 노선 상세를 종단도에 그려도 묶음이 다시
* 안 돎(고리 없음) · 누가토량 그대로. B06 흉내 = 묶음 profile · cross 알림마다 새 상세를 종단도에 render
* (`design_profile.render` → 처음부터 다시 · 유토곡선 설정 → 횡단 입력)과 같은 부름.
* 진짜 TS 를 트랜스파일해 Node 로 · 서버 창구만 가짜(`helper_349_pipeline_once` 와 같은 틀).
* 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0g_draft_b06_loop.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 job = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
function memoryStorage() {
const map = new Map();
return {
getItem: (key) => (map.has(key) ? map.get(key) : null),
setItem: (key, value) => map.set(key, String(value)),
removeItem: (key) => map.delete(key),
key: (index) => [...map.keys()][index] ?? null,
get length() {
return map.size;
},
};
}
globalThis.window = {
sessionStorage: memoryStorage(),
localStorage: memoryStorage(),
setTimeout,
clearTimeout,
};
// 흙 배분 서버 — 늦게 답함 · 끊기면 버림
globalThis.fetch = (url, init) =>
new Promise((resolve, reject) => {
const timer = setTimeout(
() => resolve({ ok: true, json: async () => ({ haul_plan: { blocks: [], url } }) }),
20,
);
init.signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(new Error("aborted"));
});
});
const STUBS = {};
const cache = new Map();
function loadTs(full) {
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 },
}).outputText;
const box = { exports: {} };
cache.set(full, box.exports);
const localRequire = (request) => {
if (CATALOG.isCatalogRequest(request)) return CATALOG;
const key = Object.keys(STUBS).find((name) => request.endsWith(name));
if (key) return STUBS[key];
if (request.startsWith("@config/")) return { API_BASE_URL: "http://fake" };
if (request.startsWith("@util/"))
return loadTs(path.join(ROOT, "common_util", `${request.slice(6)}.ts`));
if (request.startsWith(".")) return loadTs(path.join(path.dirname(full), `${request}.ts`));
return require(request);
};
new Function("exports", "module", "require", js)(box.exports, box, localRequire);
return box.exports;
}
const load = (...parts) => loadTs(path.join(ROOT, ...parts));
const sampler = load("common_util", "common_util_surface_sampler.ts");
const bytes = fs.readFileSync(process.argv[3]);
const grid = sampler.parseDtmGrid(
bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length),
);
const local = { grid, design: "las" };
STUBS["B05_Profile_Api_Replan"] = {
analysisTerrain: () => "las",
fetchRoutePlan: async () => ({
planned: job.line,
curves: job.curves,
min_radius_m: job.minRadius,
station_snap: job.stationSnap,
}),
};
STUBS["B05_Profile_Api_Structures"] = {
fetchStructures: async () => ({ structures: [] }),
fetchStructureTypes: async () => job.types,
};
STUBS["B05_Profile_Api_TerrainGrid"] = {
loadDesignTerrainGrid: async () => local,
groundStageDeps: () => ({ grid: () => local, remote: async () => [] }),
};
STUBS["B04_PreProcess_Api_Fetch"] = {
fetchDetailPipePoints: async () => ({
pipe_points: job.pipes.map((pipe) => ({ ...pipe, lonlat: [0, 0] })),
}),
};
STUBS["B06_Section_UI_Standard_Panel"] = { effectiveStandardCross: () => job.standard };
const pageMod = load("A00_Common", "design", "design_pipeline_page.ts");
const storeMod = load("A00_Common", "design", "design_store.ts");
const alignment = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts");
const page = load("A00_Common", "b_page_state.ts");
const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
const runs = () => globalThis.__aisloPipeline?.runs ?? [];
/** 묶음이 조용해질 때까지 — 마지막 기록이 끝나고 새 기록이 더 안 생김(고리면 계속 생김). */
async function quiet() {
let seen = -1;
for (let i = 0; i < 400; i += 1) {
await tick(15);
const last = runs()[runs().length - 1];
const count = runs().length;
if (count === seen && (!last || last.outcome !== "running")) return;
seen = count;
}
throw new Error("묶음이 조용해지지 않음");
}
const n = job.nodes.length;
const draftOf = (nodes) => ({
nodes,
curveOn: Array(n).fill(true),
curveRadius: Array(n).fill(null),
curveLock: Array(n).fill(null),
curveArc: Array(n).fill(null),
stationSnap: job.stationSnap,
});
const shift = (index, dx, dy) =>
job.nodes.map((node, i) => (i === index ? [node[0] + dx, node[1] + dy] : node));
const chainagesOf = (stations) => (stations ?? []).map((s) => s.chainageM);
const P = "proj-3490g";
async function run() {
window.localStorage.setItem("frd_current_project_id", P);
const savedAlignment = job.detail.longitudinal.profile_alignment;
const savedBase = alignment.toAlignmentBase(savedAlignment);
let detail = job.detail; // 종단도가 지금 그린 상세
let b06 = false;
const link = {
pipelineSource: () => ({ base: savedBase, edits: savedAlignment.edits, detail, routeId: 7 }),
adoptPipeline: (base, edits, draft) =>
pageMod.pipelineGrade(P, draft ? edits : savedAlignment.edits),
redraw: () => undefined,
side: null,
};
const bridge = pageMod.routeDraftBridge(P, link, { stationIntervalM: job.interval });
/** 횡단 보기 render — 카드 상세(새 노선 상세 ?? 저장)를 종단도에 · 유토곡선 설정. */
const renderB06 = () => {
detail = pageMod.pipelineDetail(P) ?? job.detail;
pageMod.restartPagePipeline(P);
pageMod.pipelineEarthwork(P, { conversion: job.conversion });
};
pageMod.pipelineEarthwork(P, { conversion: job.conversion });
await quiet();
const pipe = pageMod.pagePipeline(P);
let drawn = pageMod.pipelineDetail(P);
pipe.subscribe((event) => {
if (!b06 || event.kind !== "stage" || (event.stage !== "profile" && event.stage !== "cross"))
return;
const next = pageMod.pipelineDetail(P);
if (next === drawn) return;
drawn = next;
void Promise.resolve().then(renderB06);
});
const final = () => pipe.output("masshaul")?.haulInput?.final_cumulative_m3 ?? null;
const cut = () =>
Object.values(pipe.output("cross")?.byKey ?? {}).reduce((s, c) => s + (c.cutAreaM2 ?? 0), 0);
// B05 — 꼭짓점 한 번 끌어 놓기
let mark = runs().length;
bridge.edited(draftOf(shift(1, -8, 0)));
await quiet();
const b05 = {
runs: runs()
.slice(mark)
.map((r) => r.sources),
final: final(),
cut: cut(),
};
// B06 로 — 그리기 여러 번
b06 = true;
mark = runs().length;
for (let i = 0; i < 5; i += 1) {
renderB06();
await quiet();
}
const inB06 = {
runs: runs().slice(mark).length,
final: final(),
cut: cut(),
drawnIsDraft: detail === pageMod.pipelineDetail(P),
};
// B06 에서 조작 하나(계획고) = 한 번
mark = runs().length;
const edits = {
station_offsets: { [alignment.chainageKey(savedBase.stations[4].chainage_m)]: 0.3 },
curve_radii: {},
};
pageMod.pipelineGrade(P, edits);
await quiet();
const grade = {
runs: runs()
.slice(mark)
.map((r) => r.sources),
};
// B05 로 돌아옴
b06 = false;
mark = runs().length;
detail = job.detail;
pageMod.restartPagePipeline(P);
await quiet();
const back = { runs: runs().slice(mark).length, blocked: pipe.blockedWrites };
pageMod.disposePagePipeline(P);
page.clearDrafts(P);
return { b05, inB06, grade, back };
}
run()
.then((out) => {
process.stdout.write(JSON.stringify(out));
process.exit(0);
})
.catch((error) => {
process.stderr.write(String(error && error.stack ? error.stack : error));
process.exit(1);
});
@@ -0,0 +1,113 @@
"""PLAN 349-0g sub7 — 노선 초안을 둔 채 횡단 보기(B06) → 묶음 고리 없음 · 누가토량 그대로.
· B05 꼭짓점 한 번 끌기 = 한 번
· B06 그리기 여러 번(카드가 새 노선 상세를 종단도에 render) = 0 번
· 누가토량 · 횡단 면적 B05 와 같음
· B06 에서 계획고 조작 하나 = 한 번 · B05 로 돌아와도 안 돎 · 입력 쓰기 막음 0
짝: `helper_349_0g_draft_b06_loop.cjs`(실제 TS 를 Node 로 · 서버 창구만 가짜 · 검증_sub7 노선).
"""
from __future__ import annotations
import csv
import json
import subprocess
import sys
import tempfile
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from B05_Profile.B05_Profile_Structures_Schema import structure_type_map # noqa: E402
from common_util.common_util_surface_sampler import dtm_grid_bytes # noqa: E402
from config.config_system_design import STANDARD_CROSS_SECTION # noqa: E402
pytestmark = pytest.mark.skipif(
not (ROOT / "config" / "node_modules" / "typescript").is_dir(),
reason="프론트엔드 의존성 미설치",
)
PROJECT = ROOT / "storage/1/3/6d3b2812-6d5a-4168-a932-40e4ae303d5a" # 검증_sub7
ROUTE = PROJECT / "B05_Profile/route"
SECTION = PROJECT / "B06_Section"
GRID = PROJECT / "B04_PreProcess/models/dtm_classification_smooth.npz"
ONES = {g: {"loose": 1.0, "compacted": 1.0} for g in ("soil", "ripping_rock", "blasting_rock")}
def _csv(path: Path) -> list[list[float]]:
with path.open(encoding="utf-8") as handle:
return [[float(r["x"]), float(r["y"])] for r in csv.DictReader(handle)]
def _json(path: Path):
return json.loads(path.read_text(encoding="utf-8"))
@pytest.fixture(scope="module")
def r() -> dict:
if not (GRID.is_file() and (SECTION / "longitudinal/longitudinal.json").is_file()):
pytest.skip("검증_sub7 없음")
curves = _json(ROUTE / "planned_route_curves.json")
sections = sorted(
(_json(p) for p in (SECTION / "cross_sections").glob("cross_*.json")),
key=lambda s: s["chainage_m"],
)
pipes = _json(PROJECT / "B04_PreProcess/drainage/edits/pipe_points.json")["points"]
job = {
"line": _csv(ROUTE / "planned_route.csv"),
"nodes": _csv(ROUTE / "planned_route_nodes.csv"),
"curves": [
{k: c[k] for k in ("start", "apex", "end", "radius_m")} for c in curves["curves"]
],
"stationSnap": bool(curves.get("station_snap")),
"minRadius": curves["min_radius_m"],
"interval": 20.0,
"types": [
{"type_id": t.type_id, "group": t.group, "placement": t.placement}
for t in structure_type_map().values()
],
"pipes": pipes,
"standard": STANDARD_CROSS_SECTION,
"conversion": ONES,
"detail": {
"longitudinal": _json(SECTION / "longitudinal/longitudinal.json"),
"cross_sections": sections,
},
}
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "job.json"
path.write_text(json.dumps(job), encoding="utf-8")
grid = Path(folder) / "grid.bin"
grid.write_bytes(dtm_grid_bytes(GRID))
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", str(HERE / "helper_349_0g_draft_b06_loop.cjs"), str(path), str(grid)],
capture_output=True,
text=True,
encoding="utf-8",
timeout=300,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_b05_끌기_한_번(r):
assert r["b05"]["runs"] == [["route"]], r["b05"]["runs"]
def test_b06_그리기_돌지_않음_누가토량_같음(r):
b = r["inB06"]
assert b["drawnIsDraft"]
assert b["runs"] == 0
assert b["final"] == r["b05"]["final"]
assert b["cut"] == r["b05"]["cut"]
def test_b06_조작_하나_한_번_돌아와도_안_돎(r):
assert r["grade"]["runs"] == [["grade"]], r["grade"]["runs"]
assert r["back"]["runs"] == 0
assert r["back"]["blocked"] == 0