fix(저장): 349-0u 덧 노선을 저장한 [저장] — 세션 관 초안이 서버 따라감을 덮지 않음
- 노선 저장 전 · 뒤 정본 관을 받아 초안을 얹음(rebasePipeDraft) — 옛 자리 그대로인 관 = 서버가 옮긴 자리 · 옵션 고침은 그대로 · 사용자가 옮긴 · 새로 놓은 관 그대로 · 지운 관 없음 · 서버가 새로 놓은 교차 관 붙음 - 관 초안이 없거나 노선 저장이 없으면 전과 같음 - 따라감 미리보기 — 좌표 없는 초안 관 중 안 옮긴 것은 정본 좌표로(서버 노선 저장과 같은 측점) - 시험 test_349_0u_save_rebase(실제 design_save · 서버 따라감 = project_pipe_points) · test_349_0u_follow_draft_xy 서버 대조 · design_store_save 가짜 보탬 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TteK8mfYZetk5P3bEZkyVZ
This commit is contained in:
@@ -303,13 +303,14 @@ function createPagePipeline(
|
||||
};
|
||||
},
|
||||
});
|
||||
/** 좌표 없는 관 · 구조물(세션 초안 — 배수유역도 · 구조물 목록이 정본 PUT 꼴로 씀)은 앞 노선 위 그 누가거리
|
||||
* 자리에서 따라감 — 안 붙이면 측점이 그대로 남음(349-0u). */
|
||||
const placed = (list: unknown, line: Vertex[]): unknown =>
|
||||
/** 좌표 없는 관 · 구조물(세션 초안 — 배수유역도 · 구조물 목록이 정본 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({
|
||||
@@ -323,8 +324,8 @@ function createPagePipeline(
|
||||
const { pipes, structures } = ctx.inputs;
|
||||
const inputs = {
|
||||
...ctx.inputs,
|
||||
pipes: placed(pipes, line),
|
||||
structures: placed(structures, line),
|
||||
pipes: placed(pipes, line, savedPipes as FollowingStructure[]),
|
||||
structures: placed(structures, line, []),
|
||||
};
|
||||
return followStage({ ...ctx, inputs });
|
||||
},
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -9,11 +9,12 @@
|
||||
* - `followStructures` ↔ 파이썬 `common_util_route_follow.follow_structures`(+ 0 ~ 연장 자름 ·
|
||||
* 노선과 거리 · `STRUCTURE_ROUTE_DRIFT_MAX_M` 넘으면 「노선에서 멀어짐」 · 버리지 않음).
|
||||
* - `projectOnPolyline` = shapely `LineString.project`(가장 가까운 첫 선분) · `distance`.
|
||||
* - `placeOnLine` 은 TS 만 — 좌표 없는 세션 초안(정본 PUT 꼴)을 따라가기 전 노선 위 자리로(349-0u).
|
||||
* - `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;
|
||||
@@ -47,14 +48,25 @@ export function projectOnPolyline(
|
||||
return best && walked > 0 ? { ...best, length_m: walked } : null;
|
||||
}
|
||||
|
||||
/** 좌표 없는 관 · 구조물(세션 초안 = 정본 PUT 꼴 · 좌표 뺌)에 그 누가거리의 `line` 위 자리를 붙인 사본 —
|
||||
* 좌표가 있거나 누가거리가 없으면 그대로(같은 객체). 연장 밖 누가거리는 끝 선분 위로 자름. */
|
||||
export function placeOnLine<S extends FollowingStructure>(
|
||||
/** 좌표 없는 관 · 구조물(세션 초안 = 정본 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];
|
||||
@@ -70,6 +82,34 @@ export function placeOnLine<S extends FollowingStructure>(
|
||||
});
|
||||
}
|
||||
|
||||
/** 노선을 저장한 [저장] — 세션 관 초안(목록 한 벌)을 서버가 따라 옮긴 관(`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;
|
||||
|
||||
@@ -199,6 +199,7 @@ async function run() {
|
||||
// 앞쪽(시작 쪽) 꺾임점을 크게 끌어 놓음 — 그 뒤 관 · 구조물은 길이가 는 만큼 뒤로
|
||||
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) {
|
||||
|
||||
@@ -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)(),
|
||||
},
|
||||
|
||||
@@ -24,6 +24,11 @@ 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
|
||||
|
||||
@@ -82,7 +87,12 @@ def r() -> dict:
|
||||
(_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"]
|
||||
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 = {
|
||||
@@ -165,3 +175,16 @@ 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]
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user