Files
Aislo/M02_MasterTemplete/M02_MasterTemplete_Api_Fetch.ts
T
eomsangdonandClaude Opus 5.5 cd824aca25 feat(spreadsheet): F 서버 재계산 · 산출근거 따로 저장 · M02 끼우기 · 금빛 시험
- common_util_spreadsheet_node.ts · common_util_spreadsheet.py · build:spreadsheet — [저장] 때 화면과 같은 TS 엔진을 Node 로 돌려 계산값 정본(브라우저 값 버림 · 못 풀면 503)
- M02 새 종류 basis — resources/master_template/basis/<열 id>.json(구조물집계표 열마다) · 층 복사 · 뼈대 검사 · 옛 구조물 문서 산출근거 49 벌 옮김(migrate_basis) · 새 열도 같이 만듦
- 상세 산출근거 카드 = 새 스프레드시트(import() 로 늦게 받음) · basis 읽기 · 저장
- ⚠ 임시 [스프레드시트 시험] 단추 — 빈 통합문서(시트 셋) · 저장 자리 tmp/spreadsheet_trial.json · 1단계 검증 뒤 지움
- 시험 resources/tester/spreadsheet/ — 저장 · 서버 다리 · 크기 예산 · M02 만 늦게 불러옴 · 실무 구조도 xlsx 세 벌 수식 2,699 칸 엑셀 캐시값 대조(엔진 빈 몸이면 건너뜀)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0168FQuoV7vDh5nhnSowW5cp
2026-09-27 20:12:39 +09:00

150 lines
6.1 KiB
TypeScript

/* =============================================================================
* M02_MasterTemplete_Api_Fetch.ts
* 마스터 템플릿 서버 호출 — 계약 `6_계약.md` 서버 길 · 시스템 층은 시스템 관리자만
* ========================================================================== */
import { API_BASE_URL } from "@config/config_frontend";
/** 층 이름 — 서버와 같은 글 */
export type Layer = "system" | "company" | "personal" | "project";
/** 서버 종류 — 화면의 「표 양식」 = table · 「도면 양식」 = drawing · 「구조물 도면」 = structure ·
* 「상세 산출근거」 = basis(구조물집계표 열마다 한 통합문서) */
export type Kind = "table" | "drawing" | "structure" | "basis";
export interface TemplateInfo {
종류: Kind;
이름: string;
판: string;
수정일: string;
}
export interface TemplateDoc {
종류: Kind;
이름: string;
/** 프로젝트 층에서 작업본이 아직 없으면(옛 프로젝트) 시스템 양식이 와서 null */
판: string | null;
문서: unknown;
}
/** 서버가 판 불일치로 막았을 때 */
export class StaleError extends Error {}
async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(`${API_BASE_URL}/m02${path}`, {
credentials: "include",
headers: { "Content-Type": "application/json" },
...init,
});
const body = (await response.json().catch(() => ({}))) as { detail?: unknown } & T;
if (response.status === 409)
throw new StaleError(typeof body.detail === "string" ? body.detail : "409");
if (!response.ok) {
const detail = body.detail;
throw new Error(typeof detail === "string" ? detail : `HTTP ${response.status}`);
}
return body;
}
const enc = encodeURIComponent;
const q = (projectId: string | null): string => (projectId ? `?project_id=${enc(projectId)}` : "");
const head = (layer: Layer): string =>
layer === "system" ? "/templates" : `/layers/${layer}/templates`;
const item = (layer: Layer, kind: Kind, name: string, projectId: string | null): string =>
`${head(layer)}/${kind}/${enc(name)}${layer === "system" ? "" : q(projectId)}`;
/** 시스템 길은 배열 · 층 길은 `{층, 양식: [...]}` — 둘 다 목록으로 */
export const listTemplates = async (
layer: Layer,
projectId: string | null,
): Promise<TemplateInfo[]> => {
const got = await call<TemplateInfo[] | { 양식: TemplateInfo[] }>(
layer === "system" ? head(layer) : `${head(layer)}${q(projectId)}`,
);
return Array.isArray(got) ? got : got.양식;
};
export const readTemplate = (
layer: Layer,
kind: Kind,
name: string,
projectId: string | null,
): Promise<TemplateDoc> => call(item(layer, kind, name, projectId));
export const saveTemplate = (
layer: Layer,
kind: Kind,
name: string,
projectId: string | null,
판: string,
문서: unknown,
): Promise<TemplateInfo> =>
call(item(layer, kind, name, projectId), { method: "PUT", body: JSON.stringify({ 판, 문서 }) });
/** 시스템 층만 지움 */
export const deleteTemplate = (kind: Kind, name: string, 판: string): Promise<{ ok: boolean }> =>
call(`/templates/${kind}/${enc(name)}?판=${enc(판)}`, { method: "DELETE" });
/** 개인·회사 층에서 지움 — 판이 맞을 때만(다르면 409) */
export const deleteLayerTemplate = (
layer: Layer,
kind: Kind,
name: string,
판: string,
): Promise<{ ok: boolean }> =>
call(`/layers/${layer}/templates/${kind}/${enc(name)}?판=${enc(판)}`, { method: "DELETE" });
/* --- 구조물 도면(종류 structure · 이름 = 구조물집계표 열 id) ---
* 읽기 · 저장 · 지우기는 위 readTemplate · saveTemplate · deleteTemplate 에 "structure" */
/** 구조물 도면 문서 — `도면` = 도면 양식과 같은 CAD 문서 · 산출근거는 따로(`basis` · 같은 열 id) */
export interface StructureDoc {
양식: "구조물도면";
종류: "structure";
판: number;
열: string;
도번: string;
도면: { entities: unknown[] } & Record<string, unknown>;
}
/** 시스템 층 구조물 도면 목록 */
export const listStructures = async (): Promise<TemplateInfo[]> =>
(await listTemplates("system", null)).filter((t) => t.종류 === "structure");
/** 새로 — 도번 자동 · 빈 도면 (+ 없으면 빈 산출근거 통합문서) · 이미 있으면 StaleError */
export const createStructure = (column: string): Promise<TemplateDoc> =>
call(`/structures/${enc(column)}`, { method: "POST" });
/** `{열 id: 도번}` — 집계표 도면 줄(없는 열은 키 없음 = 「없음」) */
export const fetchStructureNumbers = (): Promise<Record<string, string>> =>
call("/structures/numbers");
/* --- ⚠ 임시 — [스프레드시트 시험] 단추(1단계 검증 뒤 지움) · 저장 자리 = 서버 tmp 견본 --- */
export const readSpreadsheetTrial = (): Promise<{ 문서: unknown }> => call("/spreadsheet-trial");
export const saveSpreadsheetTrial = (문서: unknown): Promise<{ 문서: unknown }> =>
call("/spreadsheet-trial", { method: "PUT", body: JSON.stringify({ 문서 }) });
/* --- 프로젝트 층 단추 다섯 --- */
const project = (id: string, tail: string): string => `/projects/${enc(id)}/templates/${tail}`;
const post = (path: string, body: object = {}): Promise<unknown> =>
call(path, { method: "POST", body: JSON.stringify(body) });
export const resetProject = (id: string): Promise<unknown> => post(project(id, "reset"));
export const applyToProject = (
id: string,
from: { from: Layer; user_id?: string; project_id?: string; 종류?: Kind; 이름?: string },
): Promise<unknown> => post(project(id, "apply"), from);
export const saveProjectAs = (
id: string,
to: "personal" | "company",
종류: Kind,
이름: string,
): Promise<unknown> => post(project(id, "save-as"), { to, 종류, 이름 });
export const fetchSources = (id: string): Promise<unknown> => call(`/projects/${enc(id)}/sources`);
/** 설계값을 채운 표 문서 — 서버가 그때그때 채움 · 저장 안 함 */
export const readFilled = (id: string, name: string): Promise<TemplateDoc> =>
call(`/projects/${enc(id)}/tables/${enc(name)}/filled`);