Files
Aislo/B06_Section/B06_Section_Section_Drafts.ts
T
eomsangdonandClaude Opus 5.5 c45814f910 feat(구조물표): 323-4 형상 얹기 한 벌(TS · 파이썬 짝) — 저장분 · 초안 · 미리 뜬 횡단 같은 길(저장 전 그림 = 저장 뒤 그림) · 빈칸 경고 한 꼴(카드 칩 「종류 칸 빈칸」) · 3D 지문 = 그림 자료 통째 · C군 벽 3D 한 번 · 소단 원천 = 표 형상 berm
- 짝 `common_util_structure_attach.ts` attachShapes ↔ `B06_Section_Engine_Attach.py` attach_shapes — 열쇠 걷고 관 세트 → 벽 → 포장 → 맹암거 → 빈칸 경고(측점 계획 자리 · 「옹벽 높이」 · 「배관 관경」 · 「맹암거 암거 높이」 · 「물넘이포장 월류 높이」)
- 서버 `_read_section_detail` · 재생성 응답 = attach_saved_shapes 하나 · 화면 `withDraftShapes`(현황 = 초안 ?? 저장분 · 초안 없어지면 저장분으로 한 번) — decorate 관 세트 · withDraftPipeKinds · 맹암거 · 포장 · 벽 블록 걷음 · 구조물 초안 없을 때 미리 뜬 횡단에 포장 · 벽 · 맹암거 빠지던 것 · 반폭 넓힘 뒤 날 상세(초안 빠짐) 고침
- 파이썬 얹기 = 목록 함수(culvert_sets_from · attach_culvert_specs · wall_specs_from · attach_wall_specs · underdrains_from · attach_underdrain_specs) + 옛 파일 함수는 감쌈
- 3D 지문 = SHAPE_KEYS(`common_util_structure_shape_keys.ts`) + 조작값 통째(손 해시 걷음 · 벽 기초 · 단 · 포장 · 맹암거 빠짐) · C군 벽 = 기준 측점과 가장 가까운 측점에서만 시작 ~ 끝 스윕(`wallSweepAt`)
- 소단 = 표 형상 berm(BERM_TYPE_ID 걷음 · 화면 isBermType · 서버 catalog_row)
- 시험: test_323_4_attach_mirror(42종 + 빈칸 · 서버 = 화면 · 옛 자리 걷힘 · 벽 한 번 · 지문) · 전수 표 ★ 둘(물넘이포장 걸친 격자 100 = 서버와 같음 · STAGE 4) · 옛 도움 파일 = 측점 → 형상 차례

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ji4nuyLVHcxrXWHTdb5nRD
2026-10-14 17:26:53 +09:00

250 lines
11 KiB
TypeScript

/* =============================================================================
* B06_Section_Section_Drafts.ts
* 초안 측점 한 벌(272 · 273-2) — 관 · 구조물을 놓거나 옮긴 초안을 공유 상세(횡단 카드 · 유토곡선)에 맞춘다.
*
* · 옛 자리 구조물 측점(서버가 [저장] 때 다시 맞추기 전) = 숨김 — 쥐고 있다가 초안이 다시 그 자리를
* 심거나 초안이 없어지면 돌려 놓음.
* · 새 자리(서버 횡단 없음) = 서버가 미리 떠 준 횡단을 캐시에 얹음(`preview-stations` · 파일 · DB
* 안 씀) — [저장] 때 서버가 같은 계산으로 정본에 씀. 한 번 뜬 자리는 기억해 다시 안 물음.
*
* 심는 자리 · 카드 이름 = 측점 계획 한 벌(`planStations` · 서버 `resolve_extra_stations` 짝 · 322-3) ·
* 그림 자료 = 형상 얹기 한 벌(`withDraftShapes` → `attachShapes` · 서버 `attach_shapes` 짝 · 323-4). 일반 측점
* 자리(No.N+0 · BP · EP)에 새로 놓은 구조물도 그 자리 구조물 없는 사본에 이름 · 형상(219 흠 · 322-3).
* ========================================================================== */
import { fetchDetailPipePoints } from "../B04_PreProcess/B04_PreProcess_Api_Fetch";
import {
fetchStructures,
fetchStructureTypes,
readPendingStructures,
type StructureInstance,
type StructureType,
} from "../B05_Profile/B05_Profile_Api_Structures";
import { readPendingPipes, type PendingPipes } from "../B05_Profile/B05_Profile_Api_Pipes_Draft";
import { registryDefaults } from "@util/common_util_culvert_sets";
import { attachShapes } from "@util/common_util_structure_attach";
import {
pipeStationMarks,
planStations,
SAME_STATION_M,
structureStationMarks,
type PlannedStation,
} from "../common_util/common_util_structure_station";
import {
previewStructureSections,
type CrossSection,
type SectionDetailResponse,
} from "./B06_Section_Api_Fetch";
type Pipes = PendingPipes;
const near = (a: number, b: number): boolean => Math.abs(a - b) < SAME_STATION_M;
const byChainage = (a: { chainage_m: number }, b: { chainage_m: number }) =>
a.chainage_m - b.chainage_m;
/** 저장된 관 · 구조물 — 한쪽 초안만 있을 때 심는 자리 셈에 씀 · 저장 뒤(`forgetDraftStations`) 다시 받음. */
const saved = new Map<string, Promise<[Pipes, StructureInstance[]]>>();
/** 미리 뜬 횡단(`프로젝트:노선:누가거리`) — 못 뜬 자리는 null(다시 안 물음) · 저장 뒤 비움. */
const previews = new Map<string, CrossSection | null>();
/** 초안이 빼 둔 옛 자리 측점. */
const parked = new WeakMap<SectionDetailResponse, CrossSection[]>();
/** 상세마다 마지막 맞춤 번호 — 늦게 끝난 옛 맞춤이 새 맞춤을 덮지 않게. */
const turns = new WeakMap<SectionDetailResponse, number>();
/** 저장 · 노선 바뀜 뒤 — 쥔 저장분 · 미리 뜬 횡단을 버림. */
export function forgetDraftStations(projectId: string): void {
saved.delete(projectId);
for (const key of [...previews.keys()]) if (key.startsWith(`${projectId}:`)) previews.delete(key);
}
/** 종류 바꿈(318-4) — 그 자리 미리 뜬 횡단 설계에 얹혔던 조정값 사본을 걷음(조작이 캐시에 쓴 것). */
export function forgetPreviewAdjusts(
projectId: string,
chainageM: number,
keys: readonly string[],
): void {
for (const [key, section] of previews) {
if (
!key.startsWith(`${projectId}:`) ||
!section?.design ||
!near(section.chainage_m, chainageM)
)
continue;
const design = section.design as unknown as Record<string, unknown>;
for (const name of keys) delete design[name];
}
}
function savedOf(projectId: string): Promise<[Pipes, StructureInstance[]]> {
let hit = saved.get(projectId);
if (!hit) {
hit = Promise.all([
fetchDetailPipePoints(projectId).then((res) => res.pipe_points as Pipes),
fetchStructures(projectId).then((res) => res.structures),
]);
hit.catch(() => saved.delete(projectId));
saved.set(projectId, hit);
}
return hit;
}
async function previewOf(
projectId: string,
routeId: number,
chainages: number[],
): Promise<CrossSection[]> {
const key = (at: number) => `${projectId}:${routeId}:${at.toFixed(3)}`;
const ask = chainages.filter((at) => !previews.has(key(at)));
if (ask.length) {
const got = await previewStructureSections(projectId, ask);
ask.forEach((at) => previews.set(key(at), got.find((s) => near(s.chainage_m, at)) ?? null));
}
return chainages.flatMap((at) => previews.get(key(at)) ?? []);
}
/** 일반 측점 자리(grid · 272)의 「구조물 없는 꼴」(217) — 저장분에서 시설 · 이름만 뺀 사본(한 벌을 다시 씀 ·
* 지형 쪽 고친 값은 그 측점 것 그대로) · 새 종류는 그 위에 얹음(`decorate`) · 측점은 남으므로 숨기지 않음. */
const bares = new WeakMap<CrossSection, CrossSection>();
function bareOf(section: CrossSection): CrossSection {
let copy = bares.get(section);
if (!copy) {
copy = { ...section, preview: true };
const record = copy as unknown as Record<string, unknown>;
for (const key of ["culvert", "ford", "box", "ford_pavement", "structure"]) delete record[key];
bares.set(section, copy);
}
return copy;
}
/** 미리 뜬 횡단 · 일반 측점 자리 사본에 카드 이름(그림 자료는 `withDraftShapes` 가 모든 측점에 한 번). */
function decorate(fresh: CrossSection[], planned: readonly PlannedStation[]): void {
for (const section of fresh) {
section.preview = true;
// 카드 이름 = 측점 계획 이름(322-3 · 같은 m 는 관이 먼저)
const hit = planned.find((station) => near(station.chainage_m, section.chainage_m));
if (hit) section.structure = hit.title;
else delete section.structure; // 구조물이 다 빠진 일반 측점 자리(217)
}
}
/** 현황 = 종류마다 초안 ?? 저장분 + 종류 표 — 측점 계획 · 형상 얹기가 같은 것(못 받으면 null). */
function statusOf(
projectId: string,
pipesDraft: Pipes | null,
structuresDraft: StructureInstance[] | null,
): Promise<[Pipes, StructureInstance[], StructureType[]] | null> {
return Promise.all([
pipesDraft ?? savedOf(projectId).then(([pipes]) => pipes),
structuresDraft ?? savedOf(projectId).then(([, structures]) => structures),
fetchStructureTypes(true),
]).catch(() => null);
}
/** 초안으로 그림 자료를 얹은 상세 — 초안이 없어지면 저장분으로 한 번 다시 얹음. */
const drafted = new WeakSet<SectionDetailResponse>();
/**
* 모든 측점 그림 자료 = 형상 얹기 한 벌(323-4 · 서버 `attach_shapes` 짝) — 현황 = 초안 ?? 저장분 ·
* 저장 전 그림 = 저장 뒤 그림. 초안이 없고 앞서 초안으로 얹은 적도 없으면 서버가 얹은 그대로.
*/
export async function withDraftShapes(
detail: SectionDetailResponse,
projectId: string,
): Promise<void> {
const pipesDraft = readPendingPipes(projectId);
const structuresDraft = readPendingStructures(projectId);
const drafts = !!(pipesDraft || structuresDraft);
if (!drafts && !drafted.has(detail)) return;
const inputs = await statusOf(projectId, pipesDraft, structuresDraft);
if (!inputs) return;
attachShapes(detail.cross_sections as unknown as Array<Record<string, unknown>>, ...inputs);
if (drafts) drafted.add(detail);
else drafted.delete(detail);
}
/**
* 초안에 맞춰 상세의 횡단 목록을 고친다 — 옛 자리 숨김 · 새 자리 미리 뜬 횡단 얹음. 초안이 없으면
* 서버 목록 그대로(빼 둔 것 돌려 놓음). 미리 뜨기를 못 하면(샘플링 조건 없음 · 끊김) 새 자리는
* 종전처럼 [저장] 뒤에 섬.
*/
export async function withDraftStations(
detail: SectionDetailResponse,
projectId: string,
routeId: number,
): Promise<void> {
const turn = (turns.get(detail) ?? 0) + 1;
turns.set(detail, turn);
const pipesDraft = readPendingPipes(projectId);
const structuresDraft = readPendingStructures(projectId);
const all = [
...detail.cross_sections.filter((section) => !section.preview),
...(parked.get(detail) ?? []),
].sort(byChainage);
let live = all;
let stale: CrossSection[] = [];
let fresh: CrossSection[] = [];
if (pipesDraft || structuresDraft) {
const inputs = await statusOf(projectId, pipesDraft, structuresDraft);
if (inputs) {
const [pipes, structures, types] = inputs;
const planned = planStations(pipes, structures, types, registryDefaults(types));
const planted = planned.map((station) => station.chainage_m);
// 구조물 측점에서 종류를 바꿈 = 「구조물 없는 상태」부터 새 종류로(요구 213) — 저장분 횡단은 빼 두고
// 새 자리처럼 미리 뜬 횡단을 씀 · 저장분 종류로 되돌리면 빼 둔 횡단이 돌아옴
const [oldPipes, oldStructures] = await savedOf(projectId).catch(
(): [Pipes, StructureInstance[]] => [[], []],
);
const byType = new Map(types.map((type) => [type.type_id, type]));
const kindsAt = (ps: Pipes, ss: StructureInstance[], at: number): string =>
[
...ps
.filter((pipe) => pipeStationMarks(pipe).some((m) => near(m.chainage_m, at)))
.map((pipe) => `p:${pipe.facility ?? "pipe"}`),
...ss
.filter((s) =>
structureStationMarks(s, byType.get(s.type_id)).some((m) => near(m.chainage_m, at)),
)
.map((s) => `s:${s.type_id}`),
]
.sort()
.join(",");
const replaced = (section: CrossSection): boolean => {
const was = kindsAt(oldPipes, oldStructures, section.chainage_m);
return was !== "" && was !== kindsAt(pipes, structures, section.chainage_m);
};
// 일반 측점 자리(grid · 272)는 측점이 남음 — 종류가 바뀌거나 빠지면 구조물 없는 사본에 새 종류(217)
const isStale = (section: CrossSection): boolean =>
section.kind === "irregular" &&
(section.grid
? replaced(section)
: planted.every((at) => !near(at, section.chainage_m)) || replaced(section));
// 일반 측점 자리(No.N+0 · BP · EP)에 새로 놓은 구조물 = 그 자리 구조물 없는 사본에 이름 · 형상(219) —
// 구조물 측점(irregular)은 위 종류 대조가 맡음 · 옛 것은 빼 둠(초안이 없어지면 돌아옴)
const retitled = all.filter(
(section) =>
section.kind !== "irregular" &&
planned.some((station) => near(station.chainage_m, section.chainage_m)),
);
stale = [...all.filter(isStale), ...retitled];
const bare = [...all.filter(isStale).filter((section) => section.grid), ...retitled].map(
bareOf,
);
live = [...all.filter((section) => !stale.includes(section)), ...bare];
const missing = planted.filter(
(at, index) =>
planted.findIndex((other) => near(other, at)) === index &&
live.every((section) => !near(section.chainage_m, at)),
);
fresh = missing.length ? await previewOf(projectId, routeId, missing).catch(() => []) : [];
if (fresh.length || bare.length) decorate([...fresh, ...bare], planned);
}
}
if (turns.get(detail) !== turn) return; // 더 새 맞춤이 돎 — 그쪽이 얹음
detail.cross_sections.splice(
0,
detail.cross_sections.length,
...[...live, ...fresh].sort(byChainage),
);
parked.set(detail, stale);
}