Merge remote-tracking branches 'origin/sub_laptop_4' and 'origin/sub_laptop_6' into main_laptop_1
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
/* 요구 280-3 원인 3 헬퍼 — 노선 초안 동안 초안 측점 맞춤(`withDraftStations` · `withDraftShapes`)이 상세의 틀을 앎.
|
||||
* old = 옛 노선 틀 상세(저장 정본 · 새로고침 첫 화면) → 새 틀 초안 대신 저장분으로 · new = 묶음이 갈아끼운 새 틀 →
|
||||
* 저장분(옛 틀) 종류와 같은 m 로 견주지 않음 · null = 옛 동작(대조). 진짜 TS: Drafts · 측점 계획 · 형상 얹기 · 표.
|
||||
* 결과 = 표준출력 JSON. 짝 = `test_280_3_route_undo_facilities.py`. */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const ts = require(path.join(ROOT, "config", "node_modules", "typescript"));
|
||||
const CATALOG = require("./helper_322_catalog_module.cjs");
|
||||
|
||||
const S = {
|
||||
savedPipes: [],
|
||||
savedStructures: [],
|
||||
draftPipes: null,
|
||||
draftStructures: null,
|
||||
types: [],
|
||||
};
|
||||
const STUBS = {
|
||||
design_page_data: {
|
||||
forgetPageData: () => {},
|
||||
pagePipes: async () => ({ pipe_points: S.savedPipes }),
|
||||
pageStructures: async () => ({ structures: S.savedStructures }),
|
||||
},
|
||||
B05_Profile_Api_Structures: {
|
||||
fetchStructureTypes: async () => S.types,
|
||||
readPendingStructures: () => S.draftStructures,
|
||||
},
|
||||
B05_Profile_Api_Pipes_Draft: { readPendingPipes: () => S.draftPipes },
|
||||
B05_Profile_Api_PlusStations: { readPlusDraft: () => null },
|
||||
B06_Section_Station_Keys: { useStationKeys: () => {}, useStationOwners: () => {} },
|
||||
ui_template_elements: { showToast: () => {} },
|
||||
};
|
||||
const cache = new Map();
|
||||
function resolveTs(base) {
|
||||
for (const c of [`${base}.ts`, base]) if (fs.existsSync(c) && fs.statSync(c).isFile()) return c;
|
||||
throw new Error(`없음: ${base}`);
|
||||
}
|
||||
function load(full) {
|
||||
if (cache.has(full)) return cache.get(full).exports;
|
||||
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);
|
||||
const req = (r0) => {
|
||||
if (CATALOG.isCatalogRequest(r0)) return CATALOG;
|
||||
const r = r0.replace(/\.js$/, "");
|
||||
const stub = STUBS[r.split("/").pop()];
|
||||
if (stub) return stub;
|
||||
if (r.endsWith(".json"))
|
||||
return JSON.parse(fs.readFileSync(path.join(path.dirname(full), r), "utf8"));
|
||||
if (r.startsWith("@util/")) return load(resolveTs(path.join(ROOT, "common_util", r.slice(6))));
|
||||
if (r.startsWith("@ui/")) return STUBS[r.split("/").pop()] ?? {};
|
||||
if (r.startsWith(".")) return load(resolveTs(path.join(path.dirname(full), r)));
|
||||
return require(r);
|
||||
};
|
||||
new Function("exports", "module", "require", js)(box.exports, box, req);
|
||||
return box.exports;
|
||||
}
|
||||
const P = (...a) => path.join(ROOT, ...a);
|
||||
const D = load(P("B06_Section", "B06_Section_Section_Drafts.ts"));
|
||||
const def = JSON.parse(
|
||||
fs.readFileSync(P("resources", "master_template", "구조물정의.json"), "utf8"),
|
||||
);
|
||||
S.types = def.types.map((t) => ({
|
||||
type_id: t.type_id,
|
||||
group: t.group,
|
||||
placement: t.placement,
|
||||
managed_by: t.managed_by,
|
||||
name: t.name,
|
||||
options: (t.options || []).map((o) => ({ key: o.key, label: o.label, default: o.default })),
|
||||
}));
|
||||
|
||||
const sec = (m, kind, extra = {}) => ({
|
||||
station_id: `station_${String(Math.round(m * 1000)).padStart(12, "0")}`,
|
||||
chainage_m: m,
|
||||
label: "",
|
||||
kind,
|
||||
center_x: m,
|
||||
center_y: 0,
|
||||
center_z: 100,
|
||||
frame: { left_xy: [0, 1] },
|
||||
samples: [{ offset_m: 0, elevation_m: 100, valid: true }],
|
||||
design: { design_elevation_m: 100 },
|
||||
...extra,
|
||||
});
|
||||
const detailOf = (marks, len = 300) => {
|
||||
const grid = [];
|
||||
for (let m = 0; m <= len; m += 20) grid.push(m);
|
||||
const all = [...new Set([...grid, ...marks.map((x) => x.m)])].sort((a, b) => a - b);
|
||||
const cross = all.map((m, i) => {
|
||||
const mk = marks.find((x) => x.m === m);
|
||||
const kind = i === 0 ? "bp" : i === all.length - 1 ? "ep" : mk ? "irregular" : "regular";
|
||||
return sec(m, kind, mk ? { structure: mk.title, ...(m % 20 === 0 ? { grid: true } : {}) } : {});
|
||||
});
|
||||
return { longitudinal: { length_m: len, stations: [] }, cross_sections: cross };
|
||||
};
|
||||
const show = (detail) =>
|
||||
detail.cross_sections
|
||||
.filter((s) => s.kind === "irregular" || s.structure || s.preview)
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.chainage_m}:${s.kind}${s.grid ? "/grid" : ""}${s.preview ? "/preview" : ""}=${s.structure ?? "-"}[${Object.keys(
|
||||
s,
|
||||
)
|
||||
.filter(
|
||||
(k) =>
|
||||
![
|
||||
"station_id",
|
||||
"chainage_m",
|
||||
"label",
|
||||
"kind",
|
||||
"center_x",
|
||||
"center_y",
|
||||
"center_z",
|
||||
"frame",
|
||||
"samples",
|
||||
"design",
|
||||
"structure",
|
||||
"grid",
|
||||
"preview",
|
||||
].includes(k),
|
||||
)
|
||||
.join(",")}]`,
|
||||
);
|
||||
|
||||
const ud = (id, m) => ({
|
||||
structure_id: id,
|
||||
type_id: "cross_underdrain",
|
||||
placement: "point",
|
||||
chainage_m: m,
|
||||
start_m: null,
|
||||
end_m: null,
|
||||
options: {},
|
||||
});
|
||||
const rw = (id, s, a, e) => ({
|
||||
structure_id: id,
|
||||
type_id: "retaining_wall",
|
||||
placement: "interval",
|
||||
chainage_m: a,
|
||||
start_m: s,
|
||||
end_m: e,
|
||||
options: {},
|
||||
});
|
||||
|
||||
/** 상세 하나를 맞춘 뒤 — 숨김(빠진 측점) · 구조물 없는 사본 · 측점마다 카드 이름. */
|
||||
async function run(saved, draft, marks, frame) {
|
||||
S.savedStructures = saved;
|
||||
S.draftStructures = draft;
|
||||
const detail = detailOf(marks);
|
||||
const before = detail.cross_sections.map((s) => s.chainage_m);
|
||||
await D.withDraftStations(detail, "p", 1, frame);
|
||||
await D.withDraftShapes(detail, "p", false, frame);
|
||||
const after = detail.cross_sections.map((s) => s.chainage_m);
|
||||
return {
|
||||
hidden: before.filter((m) => !after.includes(m)),
|
||||
preview: detail.cross_sections.filter((s) => s.preview).map((s) => s.chainage_m),
|
||||
names: Object.fromEntries(
|
||||
detail.cross_sections.filter((s) => s.structure).map((s) => [s.chainage_m, s.structure]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const out = {};
|
||||
// 옛 틀 상세(저장 정본 · 새로고침) + 새 틀 초안(+20 m) — 저장분 자리 그대로여야 함
|
||||
const oldFrame = [ud("A", 100), rw("B", 153, 160, 167)];
|
||||
const oldMarks = [
|
||||
{ m: 100, title: "맹암거" },
|
||||
{ m: 153, title: "옹벽" },
|
||||
{ m: 160, title: "옹벽" },
|
||||
{ m: 167, title: "옹벽" },
|
||||
];
|
||||
const shifted = [ud("A", 120), rw("B", 173, 180, 187)];
|
||||
for (const frame of ["old", null])
|
||||
out[`old_${frame}`] = await run(oldFrame, shifted, oldMarks, frame);
|
||||
// 새 틀 상세(갈아끼움 뒤) — 옛 틀 B 중심 120 자리에 새 틀 A 가 옴(종류 다름) · 사본 · 숨김 없어야 함
|
||||
const savedB = [ud("A", 100), rw("B", 113, 120, 127)];
|
||||
const draftB = [ud("A", 120), rw("B", 133, 140, 147)];
|
||||
const newMarks = [
|
||||
{ m: 120, title: "맹암거" },
|
||||
{ m: 133, title: "옹벽" },
|
||||
{ m: 140, title: "옹벽" },
|
||||
{ m: 147, title: "옹벽" },
|
||||
];
|
||||
for (const frame of ["new", null])
|
||||
out[`new_${frame}`] = await run(savedB, draftB, newMarks, frame);
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
})().catch((error) => {
|
||||
process.stderr.write(String(error && error.stack ? error.stack : error));
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,481 @@
|
||||
/* 요구 280-3 헬퍼 — 노선 초안 중 ↶ · ↷ 가 관 · 구조물 · 추가 측점도 그 걸음 사진으로 묶음에 넣는지.
|
||||
* 판 = `helper_356_4_undo_grade.cjs` 그대로(진짜 종단도 · 묶음 · 상세 가게 · 페이지 사진첩 · 서버 창구만 가짜).
|
||||
* 걸음 — 끌기 1 → (계획고 ▲) → 시설 손 옮김(argv[4] = structure · pipe · plus · none) → 끌기 2 → ↶ → ↷.
|
||||
* 잼 — ↶ · ↷ 첫 차례 · 조용해진 뒤 묶음 측점 시설 누가거리 · 초안 상세 비정규 측점 대 측점 계획(가게 값).
|
||||
* 결과 = 표준출력 JSON. 짝 = `test_280_3_route_undo_facilities.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;
|
||||
},
|
||||
};
|
||||
}
|
||||
const winListeners = {};
|
||||
const windowBase = {
|
||||
sessionStorage: memoryStorage(),
|
||||
localStorage: memoryStorage(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
addEventListener: (type, fn) => (winListeners[type] ??= []).push(fn),
|
||||
removeEventListener: () => undefined,
|
||||
};
|
||||
globalThis.window = new Proxy(windowBase, {
|
||||
get: (t, key) => (key in t ? t[key] : undefined),
|
||||
set: (t, key, value) => ((t[key] = value), true),
|
||||
});
|
||||
|
||||
// 흙 배분 서버 — 늦게 답함 · 끊기면 버림
|
||||
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("@ui/")) return anyModule();
|
||||
if (request.endsWith(".css")) return {};
|
||||
if (request.endsWith(".json")) return require(path.join(path.dirname(full), request));
|
||||
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" };
|
||||
|
||||
/** 아무 화면 부품 — 무엇을 읽든 · 부르든 또 그것(DOM · 오버레이 · 도구줄 흉내). */
|
||||
function anyNode() {
|
||||
const box = { dataset: {}, style: {}, classList: { add() {}, remove() {}, toggle() {} } };
|
||||
return new Proxy(function node() {}, {
|
||||
get: (_t, key) => {
|
||||
if (key in box) return box[key];
|
||||
if (key === "then" || typeof key === "symbol") return undefined;
|
||||
return (box[key] = anyNode());
|
||||
},
|
||||
set: (_t, key, value) => ((box[key] = value), true),
|
||||
apply: () => anyNode(),
|
||||
});
|
||||
}
|
||||
const anyModule = (own = {}) =>
|
||||
new Proxy(own, {
|
||||
get: (t, key) =>
|
||||
key in t
|
||||
? t[key]
|
||||
: key === "__esModule"
|
||||
? true
|
||||
: typeof key === "symbol"
|
||||
? undefined
|
||||
: anyNode(),
|
||||
});
|
||||
globalThis.document = anyNode();
|
||||
globalThis.HTMLElement = function HTMLElement() {};
|
||||
|
||||
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"] = anyModule({
|
||||
fetchStructures: async () => ({ structures: job.structures }),
|
||||
fetchStructureTypes: async () => job.types,
|
||||
readPendingStructures: () => null,
|
||||
});
|
||||
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,
|
||||
};
|
||||
// 구조물 초안 얹기(측점 계획 · 형상) — 이 시험 밖 · 아무 일 없음
|
||||
STUBS["B06_Section_Section_Drafts"] = {
|
||||
withDraftStations: async () => undefined,
|
||||
withDraftShapes: async () => undefined,
|
||||
forgetDraftStations: () => undefined,
|
||||
supersedeDraftStations: () => undefined,
|
||||
};
|
||||
STUBS["B06_Section_Api_Fetch"] = {
|
||||
fetchSectionDetail: async () => JSON.parse(JSON.stringify(job.detail)),
|
||||
saveSections: async () => undefined,
|
||||
};
|
||||
// 횡단 다시 셈(브라우저 · B05 crossPreview · B06 카드 같은 창구) — 부른 횟수 · 면적은 서버와 달라짐(두 배)
|
||||
let refreshCalls = 0;
|
||||
const doubled = (detail) =>
|
||||
detail.cross_sections.forEach((section) => {
|
||||
if (!section.design) return;
|
||||
const design = { ...section.design };
|
||||
for (const [key, value] of Object.entries(design))
|
||||
if (key.endsWith("_m2") && typeof value === "number") design[key] = value * 2;
|
||||
section.design = design;
|
||||
});
|
||||
STUBS["B06_Section_Cross_Refresh"] = {
|
||||
refreshCrossDesigns: async ({ detail }) => {
|
||||
refreshCalls += 1;
|
||||
doubled(detail);
|
||||
return detail.cross_sections.map((s) => s.chainage_m);
|
||||
},
|
||||
// 화면 선 맡김 · 낡음 판정 = 진짜 `staleAgainstScreen` 그대로(화면 선 → 없으면 상세 자기 선)
|
||||
holdScreenAlignment: (line) => {
|
||||
screenLine = line;
|
||||
return () => undefined;
|
||||
},
|
||||
staleAgainstScreen: (detail, routeId) => {
|
||||
const screen = screenLine?.(routeId);
|
||||
if (!screen) return common.hasStaleDesigns(detail);
|
||||
return common.hasStaleDesigns({
|
||||
longitudinal: {
|
||||
design_profiles: [
|
||||
profileData.toDesignProfile(screen, detail.longitudinal.design_profiles?.[0]),
|
||||
],
|
||||
},
|
||||
cross_sections: detail.cross_sections,
|
||||
});
|
||||
},
|
||||
USER_TOUCHED_KEYS: [],
|
||||
};
|
||||
let screenLine = null;
|
||||
STUBS["B06_Section_UI_Cross_Detail"] = anyModule();
|
||||
STUBS["B06_Section_UI_Page_Common"] = anyModule({ L: (key) => key });
|
||||
// 그리기 — 진짜 `renderProfile` 의 낡음 판정 줄만(같은 함수 · 같은 인자) · SVG 는 안 그림
|
||||
const draws = [];
|
||||
let opened = null;
|
||||
STUBS["B05_Profile_UI_Profile_Render"] = {
|
||||
renderProfile: (ctx) => {
|
||||
const detail = ctx.detail();
|
||||
if (!detail) return;
|
||||
const alignment = ctx.alignment();
|
||||
const longitudinal = detail.longitudinal;
|
||||
const designProfiles = alignment
|
||||
? [profileData.toDesignProfile(alignment, longitudinal.design_profiles?.[0])]
|
||||
: (longitudinal.design_profiles ?? []);
|
||||
const key = common.staleKey({
|
||||
longitudinal: { design_profiles: designProfiles },
|
||||
cross_sections: detail.cross_sections,
|
||||
});
|
||||
// 저장 상세를 그림 = 묶음 새 노선 상세(preview)가 아님 · 그린 객체(가게 것인지 견줌)
|
||||
draws.push({ key, saved: !detail.cross_sections.some((s) => s.preview), ref: detail });
|
||||
ctx.onStaleDesigns?.(key);
|
||||
},
|
||||
};
|
||||
STUBS["B05_Profile_UI_Profile_Tools"] = anyModule();
|
||||
STUBS["design_profile_free_view"] = anyModule();
|
||||
STUBS["B06_Section_UI_Cross_Panel_Base"] = anyModule();
|
||||
globalThis.sessionStorage = window.sessionStorage;
|
||||
STUBS["common_util_view_window"] = { frameOf: (_root, fn) => fn() };
|
||||
for (const name of [
|
||||
"B05_Profile_UI_Profile_Balance",
|
||||
"B05_Profile_UI_Profile_Heights",
|
||||
"B05_Profile_UI_Profile_Zoom",
|
||||
"B05_Profile_UI_Profile_Drag",
|
||||
"B05_Profile_UI_Profile_MassHaul",
|
||||
"design_profile_overlays",
|
||||
"design_profile_viewport",
|
||||
"design_save",
|
||||
"B05_Profile_Api_Fetch",
|
||||
"common_util_mass_haul_balance_view",
|
||||
])
|
||||
STUBS[name] = anyModule();
|
||||
|
||||
const pageMod = load("A00_Common", "design", "design_pipeline_page.ts");
|
||||
const storeMod = load("A00_Common", "design", "design_store.ts");
|
||||
const sectionStore = load("B06_Section", "B06_Section_Section_Store.ts");
|
||||
const common = load("B06_Section", "B06_Section_UI_Section_Common.ts");
|
||||
const layouts = load("B06_Section", "B06_Section_Structure_Layouts.ts");
|
||||
const profileData = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Data.ts");
|
||||
const alignmentMod = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts");
|
||||
const baseMod = load("A00_Common", "design", "design_profile_base.ts");
|
||||
const pageState = load("A00_Common", "b_page_state.ts");
|
||||
const massHaul = load("common_util", "common_util_mass_haul.ts");
|
||||
const historyMod = load("B05_Profile", "B05_Profile_UI_Profile_History.ts");
|
||||
const profileMod = load("A00_Common", "design", "design_profile.ts");
|
||||
const designSync = load("B06_Section", "B06_Section_UI_Page_Design_Sync.ts");
|
||||
const designSession = load("B06_Section", "B06_Section_Cross_Design_Session.ts");
|
||||
const stationKeys = load("B06_Section", "B06_Section_Station_Keys.ts");
|
||||
// 진짜 다시 셈 창구(묶음 새 노선 상세를 안 고치는지만 봄 · 다른 곳은 위 가짜를 부름)
|
||||
const realRefresh = loadTs(path.join(ROOT, "B06_Section", "B06_Section_Cross_Refresh.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(30);
|
||||
const last = runs()[runs().length - 1];
|
||||
const count = runs().length + refreshCalls * 1000 + draws.length * 1e6;
|
||||
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 sliceRuns = (mark) =>
|
||||
runs()
|
||||
.slice(mark)
|
||||
.map((r) => ({
|
||||
sources: r.sources,
|
||||
outcome: r.outcome,
|
||||
restored: r.restored ?? null,
|
||||
why: r.restoreWhy ?? null,
|
||||
}));
|
||||
const finalOf = (detail) => {
|
||||
const [series] = massHaul.computeMassHaulSeries(
|
||||
detail.longitudinal,
|
||||
detail.cross_sections,
|
||||
job.conversion,
|
||||
undefined,
|
||||
["cross"],
|
||||
);
|
||||
const points = series?.result.points ?? [];
|
||||
return points.length ? points[points.length - 1].cumulative_volume_m3 : null;
|
||||
};
|
||||
const crossOf = (detail) =>
|
||||
JSON.stringify(detail.cross_sections.map((s) => [s.chainage_m, s.design, s.samples]));
|
||||
/** 서버 정본 흉내 — 저장 횡단 계획고 = 열 때 종단도 계획선(낡음 0 · 서버가 낸 상세와 같음). */
|
||||
function settleDesigns(detail) {
|
||||
const pa = detail.longitudinal.profile_alignment;
|
||||
const base = baseMod.listedBase(alignmentMod.toAlignmentBase(pa), detail, []);
|
||||
const samples = alignmentMod.buildAlignment(base, pa.edits).samples;
|
||||
const at = (c) => {
|
||||
const i = samples.findIndex((s) => s.chainage_m >= c);
|
||||
if (i < 0) return samples[samples.length - 1].elevation_m;
|
||||
if (i === 0) return samples[0].elevation_m;
|
||||
const a = samples[i - 1];
|
||||
const b = samples[i];
|
||||
return (
|
||||
a.elevation_m +
|
||||
((b.elevation_m - a.elevation_m) * (c - a.chainage_m)) / (b.chainage_m - a.chainage_m)
|
||||
);
|
||||
};
|
||||
detail.cross_sections.forEach((s) => (s.design.design_elevation_m = at(s.chainage_m)));
|
||||
}
|
||||
|
||||
const plan = load("common_util", "common_util_structure_station.ts");
|
||||
const plusApi = load("B05_Profile", "B05_Profile_Api_PlusStations.ts");
|
||||
const near = (a, b) => Math.abs(a - b) < 0.005;
|
||||
const r2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
async function run() {
|
||||
const P = "proj-2803";
|
||||
const R = 7;
|
||||
const mode = process.argv[4] ?? "structure";
|
||||
window.localStorage.setItem("frd_current_project_id", P);
|
||||
if (mode === "plus") plusApi.writePlusDraft(P, [Math.round(job.plusAt)]); // 열기 전 추가 측점 초안
|
||||
opened = await sectionStore.loadSectionDetail(P, R);
|
||||
settleDesigns(opened);
|
||||
stationKeys.useStationKeys(P, R, opened);
|
||||
const profile = profileMod.createDesignProfile({
|
||||
projectId: P,
|
||||
view: "profile",
|
||||
onSelectStation: () => undefined,
|
||||
});
|
||||
pageMod.routeDraftBridge(P, profile, {
|
||||
stationIntervalM: job.interval,
|
||||
structureAreas: ({ cross_sections: rows }) =>
|
||||
layouts.applyStructureAreaRows(rows, layouts.structureAreaRows(rows)),
|
||||
holdDraft: (routeId, saved) => {
|
||||
const hold = saved && sectionStore.holdSectionDetail(P, routeId, saved);
|
||||
return async (stations) => {
|
||||
if (!hold) {
|
||||
await sectionStore.swapSectionStations(P, routeId, stations);
|
||||
return "no-saved";
|
||||
}
|
||||
const back = await sectionStore.restoreSectionDetail(P, routeId, hold, stations);
|
||||
return !back ? "no-cache" : back.same ? "saved" : "saved-diff";
|
||||
};
|
||||
},
|
||||
});
|
||||
const show = (detail) => {
|
||||
profile.render(detail, job.interval, R);
|
||||
profile.setIrregularStations([]);
|
||||
};
|
||||
const stopListen = sectionStore.subscribeSectionDetail(P, R, (next) => show(next));
|
||||
const stopStore = storeMod.useDesignStore(P, null).subscribe("stations", (stations) => {
|
||||
if (stations?.length) void sectionStore.swapSectionStations(P, R, stations);
|
||||
});
|
||||
show(opened);
|
||||
profile.setEarthworkContext({ conversion: job.conversion });
|
||||
await quiet();
|
||||
|
||||
const bridge = pageMod.routeDraftBridge(P, profile);
|
||||
const designStore = storeMod.useDesignStore(P, null);
|
||||
historyMod.onPageHistory({
|
||||
restore: () => {
|
||||
const kept = designStore.get("routeDraft");
|
||||
bridge.edited(kept ? draftOf(kept.nodes) : null);
|
||||
},
|
||||
});
|
||||
const album = () => historyMod.pageHistory();
|
||||
const pipe = () => pageMod.pagePipeline(P);
|
||||
const gesture = () => (winListeners.keydown ?? []).forEach((fn) => fn({}));
|
||||
const step = async (fn) => {
|
||||
gesture();
|
||||
album().pause();
|
||||
await fn();
|
||||
await quiet();
|
||||
album().resume();
|
||||
};
|
||||
/** 측점 계획(가게 관 · 구조물 · 추가 측점) 대 묶음 측점 · 초안 상세 — 유령 · 빠짐(누가거리). */
|
||||
const facilityStations = (stations) =>
|
||||
stations
|
||||
.filter((s) => s.kind === "pipe" || s.kind === "structure" || s.kind === "plus")
|
||||
.map((s) => r2(s.chainageM));
|
||||
const measure = (stations) => {
|
||||
const p = pipe();
|
||||
const pipes = (designStore.get("pipes") ?? p.input("pipes")).filter((q) => !q.outside);
|
||||
const structures = designStore.get("structures") ?? p.input("structures");
|
||||
const plus = plusApi.plusStationsOf(P);
|
||||
const want = plan
|
||||
.planStations(pipes, structures, job.types, undefined, plus)
|
||||
.map((s) => r2(s.chainage_m));
|
||||
const got = [...new Set(facilityStations(stations))];
|
||||
const detail = pageMod.pipelineDetail(P);
|
||||
const irr = detail
|
||||
? detail.longitudinal.stations
|
||||
.filter((s) => s.kind === "irregular")
|
||||
.map((s) => r2(s.chainage_m))
|
||||
: [];
|
||||
const diff = (a, b) => a.filter((x) => !b.some((y) => near(x, y)));
|
||||
return {
|
||||
want,
|
||||
ghost: diff(got, want),
|
||||
missing: diff(want, got),
|
||||
detailGhost: detail ? diff(irr, want) : null, // 초안 상세 = 노선 초안 동안만
|
||||
detailMissing: detail ? diff(want, irr) : null,
|
||||
offs: JSON.stringify(p.input("alignment")?.station_offsets ?? {}),
|
||||
};
|
||||
};
|
||||
/** ↶ · ↷ 첫 차례 묶음 측점(맞춤 한 바퀴 전) — ground 단계 출력. */
|
||||
let first = null;
|
||||
pipe().subscribe((event) => {
|
||||
if (event.kind === "stage" && event.stage === "ground" && !first) first = event.value.stations;
|
||||
}, "280-3 잼");
|
||||
const replay = async (fn) => {
|
||||
first = null;
|
||||
fn();
|
||||
await quiet();
|
||||
return {
|
||||
first: first ? measure(first) : null,
|
||||
settled: measure(pipe().output("ground").stations),
|
||||
};
|
||||
};
|
||||
const stations = pipe().output("ground").stations;
|
||||
const [nx, ny] = job.nodes[1];
|
||||
const C = stations.reduce((a, b) =>
|
||||
Math.hypot(b.x - nx, b.y - ny) < Math.hypot(a.x - nx, a.y - ny) ? b : a,
|
||||
).chainageM;
|
||||
const out = { mode, open: measure(stations) };
|
||||
await step(() => bridge.edited(draftOf(shift(1, 6, -4))));
|
||||
out.drag1 = measure(pipe().output("ground").stations);
|
||||
await step(() => {
|
||||
const p = pipe();
|
||||
pageMod.pipelineGrade(
|
||||
P,
|
||||
alignmentMod.adjustStation(p.output("planline"), p.input("alignment"), C, 0.3),
|
||||
);
|
||||
});
|
||||
out.lift = measure(pipe().output("ground").stations);
|
||||
// 손 옮김 — 화면 폼 · 방향키와 같은 가게 쓰기(좌표 지움 = 누가거리가 정본)
|
||||
const by = (d) => (s) => ({ ...s, chainage_m: s.chainage_m + d, x: null, y: null });
|
||||
await step(() => {
|
||||
if (mode === "structure") {
|
||||
const list = designStore.get("structures") ?? pipe().input("structures");
|
||||
designStore.set(
|
||||
"structures",
|
||||
list.map((s, i) => (i === list.length - 1 ? by(3)(s) : s)),
|
||||
);
|
||||
} else if (mode === "pipe") {
|
||||
const list = designStore.get("pipes") ?? pipe().input("pipes");
|
||||
designStore.set(
|
||||
"pipes",
|
||||
list.map((q, i) => (i === 0 ? by(3)(q) : q)),
|
||||
);
|
||||
} else if (mode === "plus") {
|
||||
plusApi.writePlusDraft(
|
||||
P,
|
||||
plusApi.plusStationsOf(P).map((m) => m + 3),
|
||||
);
|
||||
}
|
||||
});
|
||||
out.moved = measure(pipe().output("ground").stations);
|
||||
await step(() => bridge.edited(draftOf(shift(1, 9, -6))));
|
||||
out.drag2 = measure(pipe().output("ground").stations);
|
||||
out.undo = await replay(() => album().undo());
|
||||
out.redo = await replay(() => album().redo());
|
||||
out.blocked = pipe().blockedWrites;
|
||||
stopListen();
|
||||
stopStore();
|
||||
pageMod.disposePagePipeline(P);
|
||||
return out;
|
||||
}
|
||||
|
||||
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,183 @@
|
||||
"""요구 280-3 — 노선 초안 중 ↶ · ↷ = 관 · 구조물 · 추가 측점도 그 걸음 사진(묶음 입력까지).
|
||||
|
||||
· 옛 흠 — ↶ 차례 follow 가 계획고 사진만 내고 시설은 안 내 묶음 측점이 마지막 끌기 누가거리에 남음
|
||||
(구조물 없는 구조물 측점 · 측점 없는 구조물) · 끌기 사이 손 옮김이 있으면 맞춤도 건너뛰어 오래 남음
|
||||
· 잼 — ↶ · ↷ 첫 차례 · 조용해진 뒤 묶음 측점 시설 · 초안 상세 비정규 측점 = 측점 계획(가게 값) · 유령 0 · 빠짐 0
|
||||
· 계획고 사진(356-4 ▲)은 그대로
|
||||
짝: `helper_280_3_route_undo_facilities.cjs`(판 = 356-4 · 실제 TS 를 Node 로 · 화면 부품 · 서버 창구만 가짜).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import test_349_0q_undo_echo as base
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
MODES = ("structure", "pipe", "plus", "none")
|
||||
PROJECT = base.ROOT / "storage/1/3/c725d747-50ae-46b0-87ce-4d4e56a53cf3" # 검증_sub4(읽기만)
|
||||
ROUTE = PROJECT / "B05_Profile/route"
|
||||
SECTION = PROJECT / "B06_Section"
|
||||
GRID = PROJECT / "B04_PreProcess/models/dtm_classification_smooth.npz"
|
||||
|
||||
|
||||
def build_job() -> dict:
|
||||
"""입력 한 벌 — 349-0q 꼴 · 검증_sub4 초기 노선 · 구조물 둘(점 · 구간)."""
|
||||
if not (GRID.is_file() and (SECTION / "longitudinal/longitudinal.json").is_file()):
|
||||
pytest.skip("검증_sub4 없음")
|
||||
curves = base._json(ROUTE / "planned_route_initial_curves.json")
|
||||
sections = sorted(
|
||||
(base._json(p) for p in (SECTION / "cross_sections").glob("cross_*.json")),
|
||||
key=lambda s: s["chainage_m"],
|
||||
)
|
||||
for i, section in enumerate(sections):
|
||||
section["design"] = {
|
||||
"ground_type": "soil",
|
||||
"design_elevation_m": section["center_z"],
|
||||
"cut_area_m2": 4.0 + (i % 5),
|
||||
"fill_area_m2": 1.5 + (i % 3),
|
||||
}
|
||||
pipes = [
|
||||
{"id": f"p{n}", "source": "manual", "facility": "pipe", **base._between(sections, n)}
|
||||
for n in (15, 20)
|
||||
]
|
||||
point = base._between(sections, 25)
|
||||
a, b = base._between(sections, 30), base._between(sections, 31)
|
||||
return {
|
||||
"line": base._csv(ROUTE / "planned_route_initial.csv"),
|
||||
"nodes": base._csv(ROUTE / "planned_route_initial_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 base.structure_type_map().values()
|
||||
],
|
||||
"pipes": pipes,
|
||||
"standard": base.STANDARD_CROSS_SECTION,
|
||||
"conversion": base.ONES,
|
||||
"structures": [
|
||||
{
|
||||
"structure_id": "s-2803a",
|
||||
"type_id": "cross_underdrain",
|
||||
"placement": "point",
|
||||
**point,
|
||||
},
|
||||
{
|
||||
"structure_id": "s-2803b",
|
||||
"type_id": "retaining_wall",
|
||||
"placement": "interval",
|
||||
"start_m": a["chainage_m"],
|
||||
"chainage_m": round((a["chainage_m"] + b["chainage_m"]) / 2, 2),
|
||||
"end_m": b["chainage_m"],
|
||||
"x": (a["x"] + b["x"]) / 2,
|
||||
"y": (a["y"] + b["y"]) / 2,
|
||||
},
|
||||
],
|
||||
"touched": {},
|
||||
"detail": {
|
||||
"longitudinal": base._json(SECTION / "longitudinal/longitudinal.json"),
|
||||
"cross_sections": sections,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _run(job: dict, mode: str) -> dict:
|
||||
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(base.dtm_grid_bytes(GRID))
|
||||
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
|
||||
[
|
||||
"node",
|
||||
str(HERE / "helper_280_3_route_undo_facilities.cjs"),
|
||||
str(path),
|
||||
str(grid),
|
||||
mode,
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
timeout=300,
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def runs() -> dict:
|
||||
job = build_job()
|
||||
# 추가 측점 — 끌면 밀리는 뒤쪽 두 측점 사이
|
||||
sections = job["detail"]["cross_sections"]
|
||||
job["plusAt"] = (sections[-5]["chainage_m"] + sections[-4]["chainage_m"]) / 2
|
||||
return {mode: _run(job, mode) for mode in MODES}
|
||||
|
||||
|
||||
def _clean(m: dict) -> None:
|
||||
assert m["ghost"] == [] and m["missing"] == [], m
|
||||
assert m["detailGhost"] in ([], None) and m["detailMissing"] in ([], None), m
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
def test_되돌리기_다시하기_시설_측점_같음(runs, mode):
|
||||
r = runs[mode]
|
||||
assert r["moved"]["want"] != r["drag2"]["want"] or mode == "none" # 끌기 2 가 시설을 옮김
|
||||
for key in ("undo", "redo"):
|
||||
_clean(r[key]["settled"])
|
||||
_clean(r[key]["first"]) # 맞춤 한 바퀴 전 첫 차례부터
|
||||
assert r[key]["settled"]["detailGhost"] is not None # 노선 초안 그대로(초안 상세를 잼)
|
||||
assert r["undo"]["settled"]["want"] == r["moved"]["want"] # ↶ = 끌기 2 전 시설 자리
|
||||
assert r["redo"]["settled"]["want"] == r["drag2"]["want"]
|
||||
assert r["blocked"] == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
def test_끌기_손옮김_사이_측점_같음(runs, mode):
|
||||
r = runs[mode]
|
||||
for key in ("open", "drag1", "lift", "moved", "drag2"):
|
||||
_clean(r[key])
|
||||
|
||||
|
||||
def test_계획고_사진_그대로(runs):
|
||||
r = runs["structure"]
|
||||
assert r["undo"]["settled"]["offs"] == r["moved"]["offs"] # ▲ 남음(356-4)
|
||||
assert r["redo"]["settled"]["offs"] == r["drag2"]["offs"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def frames() -> dict:
|
||||
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
|
||||
["node", str(HERE / "helper_280_3_draft_frame.cjs")],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
timeout=120,
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def test_옛_틀_상세는_저장분으로_맞춤(frames):
|
||||
r = frames["old_old"] # 새로고침 첫 화면 · 묶음 갈아끼움 전
|
||||
assert r["hidden"] == [] and r["preview"] == []
|
||||
assert r["names"] == {"100": "맹암거", "153": "옹벽", "160": "옹벽", "167": "옹벽"}
|
||||
old = frames["old_null"]
|
||||
assert (
|
||||
old["hidden"] and "180" in old["names"]
|
||||
) # 옛 동작 = 숨김 · 남의 자리 이름(시험이 흠을 잼)
|
||||
|
||||
|
||||
def test_새_틀_상세는_저장분_종류와_안_견줌(frames):
|
||||
r = frames["new_new"] # 묶음 갈아끼움 뒤
|
||||
assert r["hidden"] == [] and r["preview"] == []
|
||||
assert r["names"]["120"] == "맹암거"
|
||||
assert frames["new_null"]["preview"] == [120] # 옛 동작 = 구조물 없는 사본
|
||||
Reference in New Issue
Block a user