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

This commit is contained in:
2026-10-16 11:53:49 +09:00
18 changed files with 1199 additions and 89 deletions
@@ -65,6 +65,8 @@ const drafts = loadTs("B06_Section/B06_Section_Section_Drafts.ts", {
}
},
},
// 측점 열쇠 세우기(344-3) — 이 시험 몫 아님
"./B06_Section_Station_Keys": { useStationKeys: () => {}, useStationOwners: () => {} },
"./B06_Section_Api_Fetch": {
previewStructureSections: async (_projectId, chainages) => {
asked.push(chainages);
+26
View File
@@ -0,0 +1,26 @@
/* 344-3 · 346-2 2파 시험 묶음 진입점 — 진짜 모듈을 vite ssr 로 한 벌 묶어 Node 헬퍼가 부름.
* 측점 열쇠(옛 초안 옮김 · 노선 밖 고침) · cross · masshaul · haul 단계를 화면 · 서버 없이 잰다.
*/
export {
carryStationDrafts,
chainageOfKey,
keyAt,
readKeyed,
useStationKeys,
useStructureIds,
} from "../../B06_Section/B06_Section_Station_Keys";
export {
crossDesignChoices,
readShoulderExtends,
writeCrossDesignChoice,
writeShoulderExtend,
} from "../../B06_Section/B06_Section_Cross_Design_Session";
export {
createRockBoundaryStore,
readRockBoundarySession,
} from "../../B06_Section/B06_Section_UI_Page_Persist";
export { createCrossStage, groundSamples } from "../../B06_Section/B06_Section_Cross_Stage";
export { createMassHaulStage } from "../../B05_Profile/logic/B05_Profile_MassHaul_Stage";
export { createHaulStage } from "../../B05_Profile/B05_Profile_Api_HaulPlan";
export { buildAlignment, emptyEdits } from "../../B05_Profile/B05_Profile_UI_Profile_Alignment";
export { readState, stateKey, writeState } from "../../A00_Common/b_page_state";
@@ -0,0 +1,240 @@
/* 344-3 · 346-2 2파 헬퍼 — vite ssr 로 묶은 진짜 모듈(helper_344_3_entry.ts)을 부르고 결과를 JSON 한 벌로.
* node helper_344_3_station_keys.mjs <묶음.mjs> <입력.json>
* 입력 = { standard: 파이썬 config 표준단면, policy: 종단 정책 }.
*/
import { readFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
const store = () => {
const m = new Map();
return {
getItem: (k) => (m.has(k) ? m.get(k) : null),
setItem: (k, v) => m.set(k, String(v)),
removeItem: (k) => m.delete(k),
key: (i) => [...m.keys()][i] ?? null,
get length() {
return m.size;
},
clear: () => m.clear(),
};
};
globalThis.window = globalThis;
globalThis.sessionStorage = store();
globalThis.localStorage = store();
const any = new Proxy(function () {}, {
get: (_t, k) => (k === Symbol.toPrimitive ? () => 0 : any),
apply: () => any,
construct: () => any,
});
globalThis.document = any;
globalThis.requestAnimationFrame = (run) => setTimeout(run, 0);
const [bundlePath, inputPath] = process.argv.slice(2);
const m = await import(pathToFileURL(bundlePath).href);
const input = JSON.parse(readFileSync(inputPath, "utf8"));
const P = "p344";
const R = 7;
const R2 = 8;
const raw = (name, route) => m.readState(name, P, route) ?? {};
const keysOf = (name, route) =>
Object.keys(raw(name, route))
.filter((k) => k !== "@at")
.sort();
const section = (chainage_m, kind, extra = {}) => ({
station_id: `s${chainage_m}`,
chainage_m,
kind,
label: String(chainage_m),
samples: [],
...extra,
});
const detailOf = (sections) => ({
longitudinal: {
stations: sections,
profile_alignment: { policy: { station_interval_m: 20 } },
},
cross_sections: sections,
});
const choice = (ground) => ({
ground_type: ground,
section_mode: "right_cut",
ditch_side: "right",
ditch_type: "l_type",
paved: true,
two_stage_slope: true,
ditch_choice: false,
});
const out = {};
/* 1. 옛 초안(누가거리 열쇠) → 측점 열쇠로 옮김 · 지금 측점에 없는 것은 남겨 둠 */
const oldRoute = detailOf([
section(0, "bp"),
section(20, "regular"),
section(40, "regular"),
section(45.054, "irregular", { structure: "파형강관 D800", culvert: {} }),
section(52.5, "irregular", { structure: "대피로" }),
section(60, "regular"),
section(70, "ep"),
]);
m.useStructureIds(P, [{ structure_id: "st-1", chainage_m: 52.5 }]);
m.useStationKeys(P, R, oldRoute);
m.writeState(
"crossdesign",
{
"20.00": choice("soil"),
45.05: choice("blasting_rock"),
"52.50": choice("soil"),
"60.00": choice("soil"),
"99.00": choice("soil"),
},
P,
R,
);
out.legacyRead = [...m.crossDesignChoices(P, R).keys()].sort((a, b) => a - b);
out.legacyKeys = keysOf("crossdesign", R);
/* 2. 쓰기 = 측점 열쇠 · 누가거리로 다시 읽음 · 암 경계 저장소도 같은 열쇠 */
m.writeCrossDesignChoice(P, R, 40, choice("ripping_rock"));
m.writeShoulderExtend(P, R, 40, "left", 0.5);
out.writeKey = keysOf("crossdesign", R).includes("grid:2");
out.shoulderKeys = keysOf("shoulderext", R);
const rock = m.createRockBoundaryStore({
sessionKey: () => m.stateKey("rockb", P, R),
detail: () => oldRoute,
refreshCard: () => undefined,
recompute: () => undefined,
});
rock.control.adjust(20, -0.3);
out.rockKeys = keysOf("rockb", R);
rock.load();
out.rockLoaded = Object.fromEntries(rock.offsets);
out.rockSession = m.readRockBoundarySession(P, R);
/* 3. 구조물 id 를 아직 모를 때(첫 열기) — 쓴 때 자리(@at)로 그 측점 고침을 읽음 */
m.useStructureIds(P, []);
m.useStationKeys(P, R, oldRoute);
out.hintKeyNow = m.keyAt(P, R, 52.5);
out.hintRead = m.crossDesignChoices(P, R).has(52.5);
/* 4. 노선이 바뀜 — 측점 열쇠로 넘김 · 넘김 = 카드 선택 넷 · 암 경계 · 노견 확장 안 넘김 · 사라진 측점 = 노선 밖 */
m.writeState("pipe-ids", { next: 2, ids: [{ id: "pipe-s1", at: 47 }] }, P); // 관이 47 m 로 옮김
m.useStructureIds(P, [{ structure_id: "st-1", chainage_m: 55 }]);
m.useStationKeys(
P,
R2,
detailOf([
section(0, "bp"),
section(20, "regular"),
section(40, "regular"),
section(47, "irregular", { structure: "파형강관 D800", culvert: {} }),
section(55, "irregular", { structure: "대피로" }),
section(58, "ep"),
]),
);
// 옛 노선 목록(st-1 은 52.5 · 관 장부는 옛 자리 기준으로 이미 열쇠가 섬)
out.outside = m.carryStationDrafts(P, R, R2);
out.carriedKeys = keysOf("crossdesign", R2);
out.carriedChoice = raw("crossdesign", R2)["grid:1"];
out.carriedRead = [...m.crossDesignChoices(P, R2).keys()].sort((a, b) => a - b);
out.carriedRock = m.readRockBoundarySession(P, R2);
out.carriedShoulder = keysOf("shoulderext", R2);
/* 5. cross 단계 — 가짜 입력 · 같은 입력 0 · 측점 하나 고침 = 1 · 범위 밖 재사용 */
const grid = [0, 20, 40, 60, 80, 100];
const groundAt = (c) => 100 + 0.05 * c - 3 * Math.sin(c / 17);
const base = {
policy: input.policy,
onlyExplicitCurves: false,
basePvi: grid.map((c, i) => ({ chainage_m: c, elevation_m: groundAt(c) + (i % 2 ? 0.8 : -0.6) })),
chainage: Array.from({ length: 101 }, (_, i) => i),
ground: Array.from({ length: 101 }, (_, i) => groundAt(i)),
stations: grid.map((c) => ({ station_id: `s${c}`, chainage_m: c })),
};
const profile = m.buildAlignment(base, m.emptyEdits());
const side = (c, sign) =>
Array.from({ length: 24 }, (_, i) => ({
offsetM: (i + 1) * 0.5,
z: groundAt(c) + sign * 0.3 * (i + 1) * 0.5,
}));
const ground = {
stations: grid.map((c, i) => ({
key: i === 0 ? "end:BP" : i === grid.length - 1 ? "end:EP" : `grid:${i}`,
chainageM: c,
x: c,
y: 0,
azimuthDeg: 90,
left: [0, 1],
kind: i === 0 || i === grid.length - 1 ? "end" : "grid",
id: null,
ground: { centerZ: groundAt(c), left: side(c, 1), right: side(c, -1) },
planRadiusM: null,
curveOuterSide: null,
curveWideningM: null,
})),
longitudinal: { chainageM: [], z: [] },
};
const samples = m.groundSamples(ground.stations[1]);
out.samplesSorted = samples.every((s, i) => i === 0 || s.offset_m > samples[i - 1].offset_m);
out.samplesCount = samples.length;
const { stage, counts } = m.createCrossStage();
const ctxOf = (cross, range, prev, prof = profile) => ({
generation: 1,
range,
signal: new AbortController().signal,
inputs: { route: null, alignment: null, cross, pipes: null, structures: null },
out: { profile: prof, ground },
before: {},
prev,
});
const crossInput = { standard: input.standard, byKey: { "grid:2": { groundType: "soil" } } };
const first = stage(ctxOf(crossInput, null, null));
out.crossFirst = { ...counts(), keys: Object.keys(first.byKey).length };
out.crossHasArea = Object.values(first.byKey).every((r) => Number.isFinite(r.cutAreaM2));
stage(ctxOf(crossInput, null, first));
out.crossSame = counts();
const touched = { ...crossInput, byKey: { ...crossInput.byKey, "grid:3": { groundType: "soil" } } };
const third = stage(
ctxOf(touched, { sources: ["cross"], fromM: 60, toM: 60, keys: ["grid:3"] }, first),
);
out.crossOne = counts();
out.crossOneChanged = third.byKey["grid:3"].detail.ground_type;
const edited = m.buildAlignment(base, { station_offsets: { "40.000": 0.4 }, curve_radii: {} });
stage(ctxOf(touched, { sources: ["grade"], fromM: 20, toM: 60, keys: [] }, third, edited));
out.crossGrade = counts();
/* 6. masshaul 단계 — 계열 · 흙 배분 입력 */
const conversion = {
soil: { loose: 1.25, compacted: 0.9 },
ripping_rock: { loose: 1.5, compacted: 1.2 },
blasting_rock: { loose: 1.65, compacted: 1.35 },
};
const massStage = m.createMassHaulStage(() => ({ conversion }));
const mass = massStage({ ...ctxOf(crossInput, null, null), out: { profile, cross: first } });
out.massSeries = mass.series.map((s) => s.basis);
out.massHaulInput = Array.isArray(mass.haulInput?.points);
/* 7. haul 단계 — 같은 열쇠 안 물음 · 끊김 = 앞 배분 그대로 */
const posts = [];
globalThis.fetch = async (_url, init) => {
if (init.signal?.aborted) throw new Error("aborted");
posts.push(1);
return { ok: true, json: async () => ({ haul_plan: { n: posts.length } }) };
};
const haul = m.createHaulStage(P, () => R);
const haulCtx = (masshaul, prev, signal = new AbortController().signal) => ({
...ctxOf(crossInput, null, prev),
signal,
out: { masshaul },
});
const plan1 = await haul(haulCtx(mass, null));
const plan2 = await haul(haulCtx(mass, plan1));
const other = massStage({
...ctxOf(crossInput, null, null),
out: { profile: edited, cross: third },
});
const aborted = new AbortController();
aborted.abort();
const plan3 = await haul(haulCtx(other, plan1, aborted.signal));
out.haul = { posts: posts.length, plan1, plan2, plan3 };
process.stdout.write(JSON.stringify(out));
@@ -0,0 +1,88 @@
# -*- coding: utf-8 -*-
"""344-3 측점 열쇠 거울 — `common_util_station_key.py` ↔ `common_util_station_key.ts` 같은 열쇠.
일반 grid:k(누가거리 ÷ 간격 반올림 · 0.5 는 위로) · 관 pipe:<id> · 구조물 structure:<id> ·
시종점 end:BP/EP · id 모름 at:<0.01 m> · 옛 열쇠(누가거리 글) · at: 의 누가거리.
"""
import json
import subprocess
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from common_util.common_util_station_key import ( # noqa: E402
chainage_key,
loose_chainage,
station_key,
)
TS = PROJECT_ROOT / "common_util" / "common_util_station_key.ts"
TYPESCRIPT = PROJECT_ROOT / "config" / "node_modules" / "typescript"
CASES = [
("bp", 0.0, 20.0, None, "structure"),
("ep", 812.345, 20.0, None, "structure"),
("regular", 40.0, 20.0, None, "structure"),
("regular", 50.0, 20.0, None, "structure"), # 2.5 → 3(위로)
("regular", 69.996, 20.0, None, "structure"),
("regular", 40.0, None, None, "structure"),
("irregular", 85.054, 20.0, "pipe-s3", "pipe"),
("irregular", 85.054, 20.0, "st-7", "structure"),
("irregular", 85.054, 20.0, None, "structure"),
("irregular", 1.005, 20.0, None, "structure"),
("pipe", 12.344, 20.0, "pipe-s1", "structure"),
("structure", 12.345, 20.0, None, "structure"),
]
LOOSE = ["85.05", "at:85.05", "grid:4", "pipe:pipe-s3", "-1.5", "end:BP"]
SCRIPT = r"""
const ts = require(process.argv[1]);
const fs = require("fs");
const src = fs.readFileSync(process.argv[2], "utf8");
const opts = { compilerOptions: { module: ts.ModuleKind.CommonJS } };
const js = ts.transpileModule(src, opts).outputText;
const box = { exports: {} };
new Function("exports", "module", js)(box.exports, box);
const m = box.exports;
const input = JSON.parse(process.argv[3]);
process.stdout.write(JSON.stringify({
keys: input.cases.map((c) => m.stationKey(c[0], c[1], c[2], c[3], c[4])),
chainage: input.cases.map((c) => m.chainageKey(c[1])),
loose: input.loose.map((k) => m.looseChainage(k)),
}));
"""
def test_파이썬과_TS_열쇠_같음():
proc = subprocess.run(
[
"node",
"-e",
SCRIPT,
str(TYPESCRIPT),
str(TS),
json.dumps({"cases": CASES, "loose": LOOSE}),
],
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
assert proc.returncode == 0, proc.stderr
out = json.loads(proc.stdout)
assert out["keys"] == [station_key(*case) for case in CASES]
assert out["chainage"] == [chainage_key(case[1]) for case in CASES]
assert out["loose"] == [loose_chainage(key) for key in LOOSE]
def test_열쇠_규칙():
assert station_key("bp", 0.0, 20.0) == "end:BP"
assert station_key("ep", 812.3, 20.0) == "end:EP"
assert station_key("regular", 50.0, 20.0) == "grid:3"
assert station_key("irregular", 85.054, 20.0, "pipe-s3", "pipe") == "pipe:pipe-s3"
assert station_key("irregular", 85.054, 20.0) == "at:85.05"
assert loose_chainage("85.05") == 85.05 and loose_chainage("grid:4") is None
+124
View File
@@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
"""344-3 · 346-2 2파 — 세션 횡단 초안 측점 열쇠 · cross · masshaul · haul 단계.
못박는 것
- 옛 초안(누가거리 열쇠)은 읽을 때 측점 열쇠로 옮김 · 지금 측점에 없는 것은 지우지 않고 남김.
- 쓰기 = 측점 열쇠(grid · pipe · structure) · 부르는 쪽은 누가거리로 읽음 · 암 경계 저장소도 같음.
- 구조물 id 를 아직 모를 때(첫 열기)도 쓴 때 자리로 그 측점 고침을 읽음.
- 노선이 바뀜 = 측점 열쇠로 넘김(관 · 구조물은 옮긴 자리로) · 넘김 = 카드 선택 넷 · 암 경계 ·
단면 유형 · 측구 방향 · 포장 · 노견 확장은 안 넘김 · 사라진 측점 = 「노선 밖 고침 N 건」.
- cross 단계: 같은 입력 다시 셈 0 · 측점 하나 고침 = 1 · 범위 밖 재사용.
- masshaul 단계 = 계열 + 흙 배분 입력 · haul 단계 = 같은 열쇠 안 물음 · 끊김 = 앞 배분 그대로.
Node 헬퍼 `helper_344_3_station_keys.mjs` 가 vite ssr 로 묶은 진짜 모듈(`helper_344_3_entry.ts`)을
부름.
"""
import json
import shutil
import subprocess
import sys
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 config.config_system import STANDARD_CROSS_SECTION # noqa: E402
FIXTURE = HERE / "fixtures" / "b05_192_1_moved_pipe_longitudinal.json"
@pytest.fixture(scope="module")
def out(tmp_path_factory):
work = tmp_path_factory.mktemp("b344")
build = subprocess.run(
[
"node",
str(ROOT / "config" / "node_modules" / "vite" / "bin" / "vite.js"),
"build",
"--configLoader",
"runner",
"--ssr",
"../resources/tester/helper_344_3_entry.ts",
"--outDir",
str(work),
"--logLevel",
"error",
],
cwd=ROOT,
capture_output=True,
text=True,
encoding="utf-8",
timeout=300,
)
assert build.returncode == 0, build.stderr
bundle = work / "bundle.mjs"
shutil.copy(work / "helper_344_3_entry.js", bundle)
policy = json.loads(FIXTURE.read_text(encoding="utf-8"))["profile_alignment"]["policy"]
source = work / "input.json"
source.write_text(
json.dumps({"standard": STANDARD_CROSS_SECTION, "policy": policy}, default=str),
encoding="utf-8",
)
proc = subprocess.run(
["node", str(HERE / "helper_344_3_station_keys.mjs"), str(bundle), str(source)],
cwd=ROOT,
capture_output=True,
text=True,
encoding="utf-8",
timeout=120,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_옛_초안은_읽을_때_측점_열쇠로_옮김(out):
assert out["legacyRead"] == [20, 45.05, 52.5, 60]
assert out["legacyKeys"] == ["99.00", "grid:1", "grid:3", "pipe:pipe-s1", "structure:st-1"]
def test_쓰기는_측점_열쇠_읽기는_누가거리(out):
assert out["writeKey"] is True
assert out["shoulderKeys"] == ["grid:2"]
assert out["rockKeys"] == ["grid:1"]
assert out["rockLoaded"] == {"20.00": -0.8}
assert out["rockSession"] == {"20.00": -0.8}
def test_구조물_id_모를_때도_쓴_자리로_읽음(out):
assert out["hintKeyNow"] == "at:52.50"
assert out["hintRead"] is True
def test_노선_바뀜_측점_열쇠로_넘김(out):
assert out["outside"] == 2 # 60 m(노선이 짧아짐) · 99 m(옛 노선에도 없던 옛 초안)
assert out["carriedKeys"] == ["grid:1", "grid:2", "pipe:pipe-s1", "structure:st-1"]
assert out["carriedRead"] == [20, 40, 47, 55] # 관 · 구조물은 옮긴 자리로
assert out["carriedChoice"] == {
"ground_type": "soil",
"ditch_type": "l_type",
"ditch_choice": False,
"two_stage_slope": True,
}
assert out["carriedRock"] == {"20.00": -0.8}
assert out["carriedShoulder"] == []
def test_cross_단계_국부_연산(out):
assert out["samplesSorted"] is True and out["samplesCount"] == 49
assert out["crossFirst"] == {"computed": 6, "reused": 0, "keys": 6}
assert out["crossHasArea"] is True
assert out["crossSame"] == {"computed": 0, "reused": 6}
assert out["crossOne"] == {"computed": 1, "reused": 5}
assert out["crossOneChanged"] == "soil"
assert out["crossGrade"]["computed"] <= 3 and out["crossGrade"]["reused"] >= 3
def test_masshaul_haul_단계(out):
assert out["massSeries"] == ["cross", "longitudinal"]
assert out["massHaulInput"] is True
assert out["haul"] == {"posts": 1, "plan1": {"n": 1}, "plan2": {"n": 1}, "plan3": {"n": 1}}
@@ -64,7 +64,8 @@ def test_등록표_밖에서_날문자열_세션_키를_안_쓴다():
def test_옛_암경계_키가_코드에_안_남아_있다():
"""실사고 자리 못박기 — 읽는 쪽이 등록표를 거치는지."""
persist = (ROOT / "B06_Section" / "B06_Section_UI_Page_Persist.ts").read_text(encoding="utf-8")
assert 'readState<Record<string, number>>("rockb"' in persist, "등록표를 안 거침"
# 344-3 — 측점 열쇠 창구(readKeyed → 등록표 readState)로 읽음
assert 'readKeyed<number>("rockb", projectId, routeId)' in persist, "등록표를 안 거침"
# 옛 키가 **코드로** 되살아나는 것만 막는다 — 주석에 사연으로 적힌 것은 남겨 둔다.
code = "\n".join(
line for line in persist.splitlines() if not line.lstrip().startswith(("*", "//", "/*"))
+2 -1
View File
@@ -202,7 +202,8 @@ def test_암경계선은_등록표_키로_읽는다():
persist = (PROJECT_ROOT / "B06_Section" / "B06_Section_UI_Page_Persist.ts").read_text(
encoding="utf-8"
)
assert 'readState<Record<string, number>>("rockb"' in persist
# 344-3 — 측점 열쇠 창구(readKeyed → 등록표 readState)로 읽음
assert 'readKeyed<number>("rockb", projectId, routeId)' in persist
# ── ⑦ 저장된 표준 횡단면이 새 탭에서 안 서던 것 (`72e50b3e`) ───────────────────