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

This commit is contained in:
2026-10-16 18:13:43 +09:00
8 changed files with 825 additions and 13 deletions
+32 -11
View File
@@ -38,6 +38,7 @@ import type {
import { useDesignStore, type DesignStoreValues } from "./design_store";
import {
followStructures,
placeOnLine,
type FollowingStructure,
} from "../../common_util/common_util_route_follow";
import { fetchDetailPipePoints } from "../../B04_PreProcess/B04_PreProcess_Api_Fetch";
@@ -291,23 +292,43 @@ function createPagePipeline(
const groundDeps = groundStageDeps(projectId);
const crossStage = createCrossStage({ grid: groundDeps.grid }); // 미교차 넓힘 = 같은 지형 격자(349-0j)
const haulStage = createHaulStage(projectId, () => savedSource().routeId ?? undefined);
const followStage = createFollowStage({
savedLine,
saved: () => {
const before = beforeDraft ?? facilitiesNow();
return {
pipes: before.pipes ?? savedPipes,
structures: before.structures ?? savedStructures,
alignment: savedEdits(),
};
},
});
/** 좌표 없는 관 · 구조물(세션 초안 — 배수유역도 · 구조물 목록이 정본 PUT 꼴로 씀)은 안 옮긴 것 = 정본 좌표 ·
* 그 밖 = 앞 노선 위 그 누가거리 자리에서 따라감 — 안 붙이면 측점이 그대로 남음(349-0u). */
const placed = (list: unknown, line: Vertex[], saved: FollowingStructure[]): unknown =>
Array.isArray(list)
? placeOnLine(
list as FollowingStructure[],
line.map(([x, y]) => ({ x, y })),
saved,
)
: list;
const pipe = createDesignPipeline({
stages: {
route: createRouteStage({
minRadiusM: () => plan?.min_radius_m ?? 0,
savedLine: () => plan && { line: savedLine()!, curves: savedCurves() },
}),
follow: createFollowStage({
savedLine,
saved: () => {
const before = beforeDraft ?? facilitiesNow();
return {
pipes: before.pipes ?? savedPipes,
structures: before.structures ?? savedStructures,
alignment: savedEdits(),
};
},
}),
follow: (ctx) => {
const line = ctx.before.route?.line ?? savedLine() ?? [];
const { pipes, structures } = ctx.inputs;
const inputs = {
...ctx.inputs,
pipes: placed(pipes, line, savedPipes as FollowingStructure[]),
structures: placed(structures, line, []),
};
return followStage({ ...ctx, inputs });
},
stations: createStationsStage({ intervalM: options.stationIntervalM, types: () => types }),
ground: createGroundStage(groundDeps),
planline: createPlanlineStage({ savedBase: () => savedSource().base, savedLine }),
+29 -1
View File
@@ -20,7 +20,13 @@
* ========================================================================== */
import { hideLoadingOverlay, showLoadingOverlay, showToast } from "@ui/ui_template_elements";
import { flushPendingPipes } from "../../B05_Profile/B05_Profile_Api_Pipes_Draft";
import {
flushPendingPipes,
readPendingPipes,
writePendingPipes,
} from "../../B05_Profile/B05_Profile_Api_Pipes_Draft";
import { fetchDetailPipePoints } from "../../B04_PreProcess/B04_PreProcess_Api_Fetch";
import { rebasePipeDraft } from "../../common_util/common_util_route_follow";
import { flushPendingStructures } from "../../B05_Profile/B05_Profile_Api_Structures";
import {
flushUphillOverrides,
@@ -151,6 +157,26 @@ function defaultStep(
}
}
type SavedPipes = Awaited<ReturnType<typeof fetchDetailPipePoints>>["pipe_points"];
/** 세션 관 초안이 있으면 노선 저장 전 정본 관(id · 자리) — 없으면 · 못 받으면 null(얹기 안 함). */
const savedPipesIfDraft = (projectId: string): Promise<SavedPipes | null> =>
readPendingPipes(projectId)
? fetchDetailPipePoints(projectId)
.then((detail) => detail.pipe_points)
.catch(() => null)
: Promise.resolve(null);
/** 노선을 저장함 — 서버가 관을 새 노선으로 따라 옮김 · 새 교차 관을 놓음. 세션 관 초안(옛 노선 누가거리일 수
* 있음)을 그 위에 얹어 둠 — 관 차례가 서버 따라감을 덮지 않게(349-0u). 못 받으면 초안 그대로. */
async function rebasePendingPipes(projectId: string, before: SavedPipes): Promise<void> {
const draft = readPendingPipes(projectId);
const after = await fetchDetailPipePoints(projectId).catch(() => null);
if (!draft || !after) return;
const moved = after.pipe_points.map(({ lonlat: _lonlat, ...pipe }) => pipe);
writePendingPipes(projectId, rebasePipeDraft(draft, before, moved));
}
/**
* [저장] · [확정] — 세션에 쌓인 조작을 정해진 차례로 정본에 보낸다.
* 노선이 없으면 아무 일도 하지 않고 false. 끝까지 나가면 true.
@@ -173,8 +199,10 @@ export async function saveDesign(
if (step === "route") {
const body = await pendingRouteSave(ctx.projectId); // 안 바뀌었으면 null — 안 보냄
if (!body) continue;
const before = await savedPipesIfDraft(ctx.projectId);
routeSaved = await saveRouteDraft(ctx.projectId, body); // 실패 = throw(서버가 되살림)
if (routeSaved.route_id != null) routeId = routeSaved.route_id;
if (before) await rebasePendingPipes(ctx.projectId, before);
continue;
}
if (step === "cross") {
+65 -1
View File
@@ -9,10 +9,12 @@
* - `followStructures` ↔ 파이썬 `common_util_route_follow.follow_structures`(+ 0 ~ 연장 자름 ·
* 노선과 거리 · `STRUCTURE_ROUTE_DRIFT_MAX_M` 넘으면 「노선에서 멀어짐」 · 버리지 않음).
* - `projectOnPolyline` = shapely `LineString.project`(가장 가까운 첫 선분) · `distance`.
* - `placeOnLine` · `rebasePipeDraft` 는 TS 만 — 좌표 없는 세션 관 초안(정본 PUT 꼴)을 따라가기 전 자리로 ·
* 노선을 저장한 [저장]이 서버가 따라 옮긴 관 위에 초안을 얹음(349-0u).
* 거울 시험 = resources/tester/test_344_2_route_pairs.py.
* ========================================================================== */
import { snapStructureStation } from "./common_util_structure_station";
import { SAME_STATION_M, snapStructureStation } from "./common_util_structure_station";
/** 「노선에서 멀어짐」 거리(m) — 파이썬 `config_system.STRUCTURE_ROUTE_DRIFT_MAX_M` 짝(거울 시험이 대조). */
export const STRUCTURE_ROUTE_DRIFT_MAX_M = 20;
@@ -46,6 +48,68 @@ export function projectOnPolyline(
return best && walked > 0 ? { ...best, length_m: walked } : null;
}
/** 좌표 없는 관 · 구조물(세션 초안 = 정본 PUT 꼴 · 좌표 뺌)에 자리를 붙인 사본 — 같은 id · 같은 누가거리인
* `saved`(정본 · 좌표 있음)가 있으면 그 좌표(안 옮긴 것 = 서버 따라감과 같은 자리) · 없으면 그 누가거리의
* `line` 위 자리(연장 밖은 끝 선분 위로 자름). 좌표가 있거나 누가거리가 없으면 그대로(같은 객체). */
export function placeOnLine<S extends FollowingStructure & { id?: string | null }>(
items: ReadonlyArray<S>,
line: ReadonlyArray<XY>,
saved: ReadonlyArray<FollowingStructure & { id?: string | null }> = [],
): S[] {
const byId = new Map(saved.map((item) => [item.id, item]));
return items.map((item) => {
if ((item.x != null && item.y != null) || item.chainage_m == null) return item;
const was = item.id ? byId.get(item.id) : undefined;
if (
was?.x != null &&
was.y != null &&
was.chainage_m != null &&
Math.abs(was.chainage_m - item.chainage_m) <= SAME_STATION_M
)
return { ...item, x: was.x, y: was.y };
let walked = 0;
for (let index = 1; index < line.length; index += 1) {
const a = line[index - 1];
const b = line[index];
const span = Math.hypot(b.x - a.x, b.y - a.y);
if (span > 0 && (walked + span >= item.chainage_m || index === line.length - 1)) {
const t = Math.min(1, Math.max(0, (item.chainage_m - walked) / span));
return { ...item, x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
}
walked += span;
}
return item;
});
}
/** 노선을 저장한 [저장] — 세션 관 초안(목록 한 벌)을 서버가 따라 옮긴 관(`after`) 위에 얹은 목록(누가거리 순).
* 초안 관이 노선 저장 전 정본(`before`) 자리 그대로면(따라감 전 값) 서버 자리로(구간 끝 · 좌표도) · 사용자가
* 옮긴 · 새로 놓은 관은 그대로 · 서버가 새로 놓은 관(옛 정본에 없던 id)은 붙임 · 짝은 id. */
export function rebasePipeDraft<P extends FollowingPoint & { id?: string | null }>(
draft: ReadonlyArray<P>,
before: ReadonlyArray<FollowingPoint & { id?: string | null }>,
after: ReadonlyArray<P>,
): P[] {
const old = new Map(before.map((pipe) => [pipe.id, pipe]));
const moved = new Map(after.map((pipe) => [pipe.id, pipe]));
const mine = new Set(draft.map((pipe) => pipe.id));
const kept = draft.map((pipe) => {
const was = pipe.id ? old.get(pipe.id) : undefined;
const now = pipe.id ? moved.get(pipe.id) : undefined;
if (!was || !now || Math.abs(pipe.chainage_m - was.chainage_m) > SAME_STATION_M) return pipe;
const shift = now.chainage_m - pipe.chainage_m;
return {
...pipe,
chainage_m: now.chainage_m,
...(pipe.start_m != null ? { start_m: pipe.start_m + shift } : {}),
...(pipe.end_m != null ? { end_m: pipe.end_m + shift } : {}),
...(now.x != null && now.y != null ? { x: now.x, y: now.y } : {}),
};
});
const added = after.filter((pipe) => pipe.id && !old.has(pipe.id) && !mine.has(pipe.id));
return [...kept, ...added].sort((a, b) => a.chainage_m - b.chainage_m);
}
export interface FollowingPoint {
chainage_m: number;
x?: number | null;
@@ -0,0 +1,233 @@
/* PLAN 349-0u sub7 헬퍼 — 세션 관 · 구조물 초안에 좌표가 없어도(배수유역도 · 구조물 목록이 정본 PUT 꼴로 씀)
* 앞쪽 꺾임점을 끌면 follow 가 새 측점을 가게에 바로 · 되돌리기 = 초안 값 · 다시하기 = 다시 밂 · 조작 하나 =
* 묶음 한 번. 나머지 틀 = `helper_349_0d_follow_store.cjs` 그대로. 짝 = `test_349_0u_follow_draft_xy.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: job.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,
readRockBoundaryDefault: () => -0.5,
};
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-3490u";
const ids = (list) => (list ?? []).map((item) => [item.id ?? item.structure_id, item.chainage_m]);
const lengthOf = (line) =>
(line ?? []).reduce(
(sum, p, i) => (i ? sum + Math.hypot(p[0] - line[i - 1][0], p[1] - line[i - 1][1]) : 0),
0,
);
async function run() {
window.localStorage.setItem("frd_current_project_id", P);
const savedAlignment = job.detail.longitudinal.profile_alignment;
const savedBase = alignment.toAlignmentBase(savedAlignment);
const followed = [];
const link = {
pipelineSource: () => ({
base: savedBase,
edits: savedAlignment.edits,
detail: job.detail,
routeId: 7,
}),
adoptPipeline: (base, edits, draft) =>
pageMod.pipelineGrade(P, draft ? edits : savedAlignment.edits),
redraw: () => undefined,
side: null,
};
const store = storeMod.useDesignStore(P, null);
// 세션 초안 = 정본 PUT 꼴(좌표 뺌) — 배수유역도 · 구조물 목록이 열 때 · 고칠 때 씀
const draftPipes = job.pipes.map(({ x: _x, y: _y, ...pipe }) => pipe);
const draftStructures = job.structures.map(({ x: _x, y: _y, ...item }) => item);
store.set("pipes", draftPipes);
store.set("structures", draftStructures);
const bridge = pageMod.routeDraftBridge(P, link, {
stationIntervalM: job.interval,
onFacilitiesFollowed: (far) => followed.push(far),
});
pageMod.pipelineEarthwork(P, { conversion: job.conversion });
await quiet();
const pipe = pageMod.pagePipeline(P);
const savedLength = lengthOf(pipe.output("route")?.line);
const open = {
pipes: ids(store.get("pipes")),
structures: ids(store.get("structures")),
followed: [...followed],
};
const snapshot = {};
for (let i = 0; i < window.sessionStorage.length; i += 1) {
const key = window.sessionStorage.key(i);
snapshot[key] = window.sessionStorage.getItem(key);
}
const step = async (edit) => {
const mark = runs().length;
const before = followed.length;
bridge.edited(edit);
await quiet();
return {
runs: runs()
.slice(mark)
.map((r) => r.sources),
pipes: ids(store.get("pipes")),
structures: ids(store.get("structures")),
length: lengthOf(pipe.output("route")?.line),
followed: followed.slice(before),
blocked: pipe.blockedWrites,
};
};
// 앞쪽(시작 쪽) 꺾임점을 크게 끌어 놓음 — 그 뒤 관 · 구조물은 길이가 는 만큼 뒤로
const dragged = draftOf(shift(1, job.dx, job.dy));
const drag = await step(dragged);
drag.line = pipe.output("route")?.line; // 서버 따라감 대조(파이썬)
// 되돌리기 — 사진첩이 세션을 되쓴 뒤 초안 없음
for (const key of Object.keys(snapshot)) window.sessionStorage.setItem(key, snapshot[key]);
for (let i = window.sessionStorage.length - 1; i >= 0; i -= 1) {
const key = window.sessionStorage.key(i);
if (!(key in snapshot)) window.sessionStorage.removeItem(key);
}
const undo = await step(null);
const redo = await step(dragged);
const undo2 = await step(null);
pageMod.disposePagePipeline(P);
return {
savedLength,
open,
drag,
undo,
redo,
undo2,
draftPipes: ids(draftPipes),
draftStructures: ids(draftStructures),
};
}
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,148 @@
/* PLAN 349-0u 덧 sub7 헬퍼 — 노선을 저장한 [저장]에서 세션 관 초안(옛 노선 누가거리)이 서버가 따라 옮긴 관을
* 덮지 않음 · 사용자 관 고침만 얹음. 실제 `design_save.ts` · 관 초안 창구 · 가게를 Node 로 · 서버 창구 ·
* 화면 알림만 가짜. 노선 저장 전 GET = `before` · 뒤 GET = `after`(서버 따라감 + 새 교차 관).
* 덤 — `placeOnLine` 이 안 옮긴 관에 정본 좌표를 씀. 입력 argv[2] JSON. 짝 = `test_349_0u_save_rebase.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,
};
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 calls = [];
const sent = [];
let routeSavedOnServer = false;
let routeBody = null;
const withLonlat = (list) => list.map((pipe) => ({ ...pipe, lonlat: [0, 0] }));
STUBS["ui_template_elements"] = {
showLoadingOverlay: () => undefined,
hideLoadingOverlay: () => undefined,
showToast: () => undefined,
};
STUBS["B04_PreProcess_Api_Fetch"] = {
fetchDetailPipePoints: async () => {
calls.push("GET");
return { pipe_points: withLonlat(routeSavedOnServer ? job.after : job.before) };
},
saveDetailPipePoints: async (_projectId, pipes) => {
calls.push("PUT");
sent.push(pipes);
return {};
},
};
STUBS["B05_Profile_Api_Structures"] = { flushPendingStructures: async () => undefined };
STUBS["B05_Profile_Api_Fetch"] = {
flushUphillOverrides: async () => undefined,
saveProfileAlignment: async () => ({}),
};
STUBS["B05_Profile_UI_Profile_Edit"] = {
markAlignmentSaved: () => undefined,
pendingAlignment: () => null,
};
STUBS["B06_Section_Api_Culvert_Options"] = { flushCulvertOptions: async () => undefined };
STUBS["B05_Profile_UI_RouteEdit_Apply"] = {
pendingRouteSave: async () => routeBody,
saveRouteDraft: async () => {
calls.push("ROUTE");
routeSavedOnServer = true;
return { route_id: 8 };
},
carryAfterRouteSave: async () => 0,
routeSaveSummary: () => "",
rebuildAfterRouteSave: async () => undefined,
};
const save = load("A00_Common", "design", "design_save.ts");
const drafts = load("B05_Profile", "B05_Profile_Api_Pipes_Draft.ts");
const follow = load("common_util", "common_util_route_follow.ts");
const P = "proj-3490u-save";
async function once(route, draft) {
calls.length = 0;
sent.length = 0;
routeSavedOnServer = false;
routeBody = route ? { draft: {} } : null;
drafts.writePendingPipes(P, draft);
let failure = null;
const ok = await save.saveDesign({
projectId: P,
routeId: () => 7,
cross: async () => undefined,
failed: (error) => (failure = String(error && error.stack ? error.stack : error)),
});
if (failure) throw new Error(failure);
return { ok, calls: [...calls], sent: [...sent], left: drafts.readPendingPipes(P) };
}
async function run() {
window.localStorage.setItem("frd_current_project_id", P);
const rebased = await once(true, job.draft);
const noDraft = await once(true, null);
const noRoute = await once(false, job.draft);
// 덤 — 좌표 없는 초안 관: 같은 id · 같은 누가거리 정본이면 그 좌표(노선 밖이어도) · 아니면 노선 위
const placed = follow.placeOnLine(
[{ id: "a", chainage_m: 40 }, { id: "b", chainage_m: 60 }, { chainage_m: 70 }],
[
{ x: 0, y: 0 },
{ x: 100, y: 0 },
],
[
{ id: "a", chainage_m: 40, x: 40.4, y: 3 },
{ id: "b", chainage_m: 55, x: 55, y: 0 },
],
);
return { rebased, noDraft, noRoute, placed };
}
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);
});
@@ -53,7 +53,13 @@ const STUBS = {
},
"../../B05_Profile/B05_Profile_Api_Pipes_Draft": {
flushPendingPipes: () => record("pipes")(),
readPendingPipes: () => null, // 관 초안 없음 — 노선 저장 뒤 얹기(349-0u)는 안 돎
writePendingPipes: () => undefined,
},
"../../B04_PreProcess/B04_PreProcess_Api_Fetch": {
fetchDetailPipePoints: async () => ({ pipe_points: [] }),
},
"../../common_util/common_util_route_follow": { rebasePipeDraft: (draft) => draft },
"../../B05_Profile/B05_Profile_Api_Structures": {
flushPendingStructures: () => record("structures", failStructures)(),
},
@@ -0,0 +1,190 @@
"""PLAN 349-0u sub7 — 세션 관 · 구조물 초안에 좌표가 없어도 노선 따라 측점이 밀림(349-0d 되살림).
· 세션 초안 = 정본 PUT 꼴(좌표 뺌) — 앞쪽 꺾임점을 크게 끌면 그 뒤 관 · 구조물 측점이
길이 는 만큼 뒤로
· 되돌리기 = 초안 값 그대로 · 다시하기 = 다시 밂 · 조작 하나 = 묶음 한 번 · 입력 쓰기 막음 0
짝: `helper_349_0u_follow_draft_xy.cjs`(실제 TS 를 Node 로 · 서버 창구만 가짜 · 검증_sub7).
"""
from __future__ import annotations
import csv
import json
import math
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_drainage_pipes import ( # noqa: E402
PipePoint,
project_pipe_points,
)
from common_util.common_util_route_geometry import RouteVertex # 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"))
def _structure(sid: str, line: list[list[float]], ratio: float, off: float) -> dict:
"""노선 위(off 0) · 옆(off m) 점 구조물 — 저장 노선 누가거리 · 좌표."""
lengths = [math.dist(a, b) for a, b in zip(line, line[1:])]
at = sum(lengths) * ratio
walked = 0.0
for (a, b), length in zip(zip(line, line[1:]), lengths):
if walked + length >= at:
t = (at - walked) / length
dx, dy = (b[0] - a[0]) / length, (b[1] - a[1]) / length
x, y = a[0] + dx * length * t - dy * off, a[1] + dy * length * t + dx * off
break
walked += length
return {
"structure_id": sid,
"type_id": "erosion_check",
"placement": "point",
"chainage_m": round(at, 2),
"start_m": None,
"end_m": None,
"x": x,
"y": y,
"options": {},
}
@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 = [ # 서버 GET 처럼 id 붙음
{**pipe, "id": f"p{i}"}
for i, pipe in enumerate(
_json(PROJECT / "B04_PreProcess/drainage/edits/pipe_points.json")["points"]
)
]
line = _csv(ROUTE / "planned_route.csv")
structures = [_structure("s-near", line, 0.5, 0.0), _structure("s-far", line, 0.7, 30.0)]
job = {
"line": line,
"structures": structures,
"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,
"dx": -60.0,
"dy": 0.0,
"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_0u_follow_draft_xy.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 _moved(before: list, after: list) -> list[float]:
return [b[1] - a[1] for a, b in zip(before, after)]
def test_앞쪽_꺾임점_끌기_측점_밀림(r):
d = r["drag"]
assert d["runs"] == [["route"]], d["runs"]
assert d["blocked"] == 0
grow = d["length"] - r["savedLength"]
assert grow > 5, grow # 앞쪽 길이 늚
pipes = _moved(r["draftPipes"], d["pipes"])
assert len(d["pipes"]) == len(r["draftPipes"])
# 끈 꼭짓점 뒤 관 = 길이 는 만큼(정수 m 맞춤 · 1 m 안) — 대부분 그 뒤
tail = [m for (_, c), m in zip(r["draftPipes"], pipes) if c > r["draftPipes"][2][1]]
assert tail and all(abs(m - grow) <= 1.0 for m in tail), (grow, pipes)
s = _moved(r["draftStructures"], d["structures"])
assert all(abs(m - grow) <= 1.0 for m in s), (grow, s)
assert len(d["followed"]) == 1
def test_되돌리기_초안_값(r):
for u in (r["undo"], r["undo2"]):
assert u["runs"] == [["route"]], u["runs"]
assert u["pipes"] == r["draftPipes"]
assert u["structures"] == r["draftStructures"]
assert abs(u["length"] - r["savedLength"]) < 1e-6
assert u["blocked"] == 0
def test_다시하기_다시_밂(r):
d, again = r["drag"], r["redo"]
assert again["runs"] == [["route"]], again["runs"]
assert again["pipes"] == d["pipes"] and again["structures"] == d["structures"]
assert again["blocked"] == 0
def test_열기만_가게_그대로(r):
o = r["open"]
assert o["pipes"] == r["draftPipes"] and o["structures"] == r["draftStructures"]
assert o["followed"] == []
def test_따라감_서버와_같음(r):
"""좌표 없는 초안도 안 옮긴 관 = 정본 좌표 — 서버 노선 저장과 같은 측점."""
line, walked, vertices = r["drag"]["line"], 0.0, []
for i, (x, y) in enumerate(line):
walked += math.dist(line[i - 1], (x, y)) if i else 0.0
vertices.append(RouteVertex(x=x, y=y, z=0.0, chainage_m=walked))
pipes = _json(PROJECT / "B04_PreProcess/drainage/edits/pipe_points.json")["points"]
server = project_pipe_points(
[PipePoint(chainage_m=p["chainage_m"], x=p["x"], y=p["y"]) for p in pipes], vertices
)
assert [c for _, c in r["drag"]["pipes"]] == [p.chainage_m for p in server]
+122
View File
@@ -0,0 +1,122 @@
"""PLAN 349-0u 덧 sub7 — 노선을 저장한 [저장]에서 세션 관 초안이 서버 따라감을 덮지 않음.
· 초안 관이 노선 저장 전 정본 자리 그대로(따라감 전 값) = 서버가 옮긴 자리(옵션 고침은 얹음)
· 사용자가 옮긴 · 새로 놓은 관 = 그대로 · 지운 관 = 없음 · 서버가 새로 놓은 교차 관 = 붙음
· 노선 저장 없음 = 초안 그대로 · 초안 없음 = 관 GET · PUT 없음
· 서버 따라감 = 실제 `project_pipe_points`(검증_sub7 관 · 노선 꼭짓점 하나 옮김)
짝: `helper_349_0u_save_rebase.cjs`(실제 `design_save.ts` 를 Node 로 · 서버 창구만 가짜).
"""
from __future__ import annotations
import copy
import csv
import json
import math
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 common_util.common_util_drainage_pipes import ( # noqa: E402
parse_pipe_points,
project_pipe_points,
)
from common_util.common_util_route_geometry import RouteVertex # 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
PIPES = PROJECT / "B04_PreProcess/drainage/edits/pipe_points.json"
LINE = PROJECT / "B05_Profile/route/planned_route.csv"
def _vertices(line: list[list[float]]) -> list[RouteVertex]:
walked, out = 0.0, []
for i, (x, y) in enumerate(line):
walked += math.dist(line[i - 1], (x, y)) if i else 0.0
out.append(RouteVertex(x=x, y=y, z=0.0, chainage_m=walked))
return out
@pytest.fixture(scope="module")
def case() -> dict:
if not (PIPES.is_file() and LINE.is_file()):
pytest.skip("검증_sub7 없음")
with LINE.open(encoding="utf-8") as handle:
line = [[float(r["x"]), float(r["y"])] for r in csv.DictReader(handle)]
raw = json.loads(PIPES.read_text(encoding="utf-8"))["points"]
before = [{**pipe, "id": f"p{i}"} for i, pipe in enumerate(raw)]
# 서버 노선 저장 — 앞쪽 꼭짓점을 서쪽으로 크게 옮긴 새 노선에 좌표 투영 + 새 교차 관 하나
moved = copy.deepcopy(line)
moved[1] = [moved[1][0] - 60.0, moved[1][1]]
points = project_pipe_points(parse_pipe_points(before), _vertices(moved))
after = [point.as_dict() for point in points]
after.append({"chainage_m": 30.0, "source": "spacing", "id": "p-new", "x": 1.0, "y": 2.0})
# 세션 초안 = 정본 PUT 꼴(좌표 뺌 · 옛 노선 누가거리) — p1 옵션 고침 · p3 사용자가 7 m 옮김 ·
# p5 지움 · 새 관 하나(id 없음)
draft = [{k: v for k, v in pipe.items() if k not in ("x", "y")} for pipe in before]
draft[1]["options"] = {**draft[1].get("options", {}), "pipe_count": 3}
draft[3]["chainage_m"] += 7.0
del draft[5]
draft.append({"chainage_m": 333.0, "source": "user"})
job = {"before": before, "after": after, "draft": draft}
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "job.json"
path.write_text(json.dumps(job), encoding="utf-8")
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", str(HERE / "helper_349_0u_save_rebase.cjs"), str(path)],
capture_output=True,
text=True,
encoding="utf-8",
timeout=120,
)
assert proc.returncode == 0, proc.stderr
return {**job, "out": json.loads(proc.stdout)}
def test_노선_저장_뒤_관_차례가_서버_따라감_위에(case):
r = case["out"]["rebased"]
assert r["ok"] and r["calls"] == ["GET", "ROUTE", "GET", "PUT"], r["calls"]
sent = {p.get("id", "user"): p for p in r["sent"][0]}
after = {p["id"]: p for p in case["after"]}
before = {p["id"]: p for p in case["before"]}
assert set(sent) == ({p["id"] for p in case["before"]} - {"p5"}) | {"p-new", "user"}
for pid in sent.keys() - {"p3", "user"}:
assert sent[pid]["chainage_m"] == after[pid]["chainage_m"], pid # 서버 자리
moved = [p for p in before if p in after and after[p]["chainage_m"] != before[p]["chainage_m"]]
assert moved # 실제로 서버가 옮긴 관이 있음
assert sent["p1"]["options"]["pipe_count"] == 3 # 사용자 옵션 고침은 얹음
assert sent["p3"]["chainage_m"] == before["p3"]["chainage_m"] + 7.0 # 사용자가 옮긴 자리
assert sent["user"]["chainage_m"] == 333.0
chain = [p["chainage_m"] for p in r["sent"][0]]
assert chain == sorted(chain)
assert r["left"] is None # 내보낸 뒤 초안 비움
def test_초안_없으면_관_안_건드림(case):
r = case["out"]["noDraft"]
assert r["ok"] and r["calls"] == ["ROUTE"], r["calls"]
def test_노선_그대로면_초안_그대로(case):
r = case["out"]["noRoute"]
assert r["ok"] and r["calls"] == ["PUT"], r["calls"]
assert r["sent"][0] == case["draft"]
def test_안_옮긴_관은_정본_좌표(case):
a, b, c = case["out"]["placed"]
assert (a["x"], a["y"]) == (40.4, 3) # 같은 id · 같은 누가거리 = 정본 좌표(노선 밖이어도)
assert (b["x"], b["y"]) == (60, 0) # 옮긴 관 = 노선 위 그 누가거리
assert (c["x"], c["y"]) == (70, 0)