Compare commits

...

6 Commits

Author SHA1 Message Date
sangwook yoo
f46dc788cc fix(pdf-import): 분석 타임아웃 120s→300s 확대 — 서버 정상 완료 직전 클라이언트 abort 방지
[작업내용] :
- 서버가 120,011ms 에 200 으로 정상 완료했는데 클라이언트 AbortController 가 정확히 120,000ms 에
  fetch 를 끊어 타임아웃 toast 가 뜨던 문제 — gemini-3.1-pro-preview(thinking 비활성 불가)
  + MEDIA_RESOLUTION_HIGH PDF 분석은 정상 응답도 2분을 넘길 수 있어 300초로 확대
- 추후 진단용으로 서버에 단계별 소요시간(fileReady/generate) debug 로그 추가

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 10:28:06 +09:00
sangwook yoo
8768182fa8 docs(claude): PDF 도면 임포트 아키텍처 노트 추가
[작업내용] :
- 임포트 파이프라인(모달→Gemini API→usePdfImport)과 '수동 확정과 동일 상태' 불변식,
  좌표 스케일 금지·viewport 줌 규칙을 Floor Plan 섹션에 문서화

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 10:10:36 +09:00
sangwook yoo
08ef577260 fix(gemini): floor-plan API 에 세션 인증·레이트리밋 추가
[작업내용] :
- iron-session 세션 검사 추가 — 페이지용 layout redirect 가 API 라우트를 보호하지 않아
  익명 요청으로 Gemini 과금이 가능하던 문제 차단(401)
- 사용자별 분당 5회 in-memory 레이트리밋(429) — 연타 업로드 과금 폭주 방지

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 10:07:01 +09:00
sangwook yoo
7b15b76054 fix(pdf-import): 좌표 축소 스케일 제거 — 치수 라벨 실측 정합(R1)
[작업내용] :
- fitAndCenter 가 큰 도면(9.6m 초과)에 scale<1 을 좌표에 곱해 'QLine 길이×10=표시 mm' 불변식을
  깨뜨리던 문제 해소 — 좌표는 실측 그대로 평행이동만 하는 centerOnCanvas 로 대체
- 화면맞춤은 fitViewport 로 분리: 캔버스 중앙 고정 viewportTransform 줌 + canvasZoomState 동기화
  (useCanvasEvent 의 setZoom 은 동일 zoom 값에서 translation 을 보존)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 10:06:33 +09:00
sangwook yoo
29fd4cbd59 fix(pdf-import): 분석 중 라우팅 이탈 시 늦은 결과 적용·플랜 덮어쓰기 차단
[작업내용] :
- 진행 중인 PDF 분석 요청을 pdfRunRef 로 추적, 모달 언마운트 시 AbortController.abort() 호출
- fetch 완료 후·저신뢰 confirm 후 두 지점에서 컨트롤러 동일성 가드 — 언마운트로 무효화된 늦은 결과가
  비워진 canvas 에 적용되고 saveCanvas 가 이전 플랜 DB 를 outline-only 로 덮어쓰던 데이터 손실 경로 차단

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 10:05:40 +09:00
sangwook yoo
c7757fabda fix(pdf-import): PDF 외곽선을 수동 확정 상태와 동일하게 생성 — 지붕형상 설정 차단 해소
[작업내용] :
- useLine.addLine 경유로 outerLine 생성 — attributes/planeSize/fontSize 부여(지붕형상 설정·처마/케라바 편집·재로드 복원에 필수)
- canvas.outerLineFix + outerLineFixState 설정 — 미설정 시 지붕형상 설정 진입이 wall.line.not.found 로 즉시 차단되던 문제 해소
- skeletonBuilder 가 소비하는 outerLinePoint 정점 circle 생성(수동 플로우와 동일)
- 조기 WALL 폴리곤 생성 제거 — 수동 플로우와 동일하게 지붕형상 설정 적용 시점에 WALL/ROOF 생성
- 짧은엣지 dedup 을 '직전 유지 정점' 기준으로 수정하고 닫힘 엣지(Gemini 닫힌 링 반환 포함)까지 검사, 임계값을 addLine 의 1unit 과 일치
- PDF 적용 후 외벽선 그리기 메뉴(진입 시 재드로잉 강등) 대신 지붕형상 설정 메뉴로 직행

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 10:05:09 +09:00
4 changed files with 164 additions and 44 deletions

View File

@ -56,6 +56,8 @@ A modal under `components/floor-plan/modal/<feature>` pairs with a hook under `h
**Plan persistence** (serialize/restore) is in `src/lib/canvas.js` and `src/util/canvas-util.js`. Recent commits (`a5e794b3`, `2aef32e0`) added a three-layer guard (entry / cache / save) and `SizeSetting` input guards against 0-area apertures/shadows/dormers — when touching plan load/save or size inputs, do not weaken or remove these guards without understanding the failure mode (`InvalidStateError` from corrupted plans).
**PDF 도면 임포트** — 배치면 초기설정 모달의 PDF 입력 모드 → `src/app/api/gemini/floor-plan/route.js`(Gemini 분석, 세션 인증 + 사용자별 분당 5회 레이트리밋) → `src/hooks/pdf-import/usePdfImport.js`. 임포트는 수동 외벽선 확정(`useOuterLineWall.handleFix`) 직후와 동일한 상태를 만들어야 한다: `useLine.addLine` 경유 outerLine 생성(attributes/planeSize/fontSize), `outerLinePoint` 정점 circle, `canvas.outerLineFix = true` + `outerLineFixState`, 이후 지붕형상 설정 메뉴 직행. **좌표에 축소 scale 을 곱하지 말 것** — 'QLine 길이×10 = 표시 mm' 불변식이 깨진다. 화면맞춤은 `viewportTransform` 줌 + `canvasZoomState` 동기화로만 처리한다.
### State — Recoil, split by domain
Atoms live under `src/store/` and are split by domain (`canvasAtom`, `roofAtom`, `estimateAtom`, `modalAtom`, `menuAtom`, `settingAtom`, …). When adding state, find the existing domain atom rather than introducing a new global. `RecoilWrapper.js` mounts the root; `QcastProvider.js` composes the rest of the global providers (session, global data, global loading) for the App Router root layout.

View File

@ -1,13 +1,33 @@
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { GoogleGenerativeAI, SchemaType } from '@google/generative-ai'
import { GoogleAIFileManager, FileState } from '@google/generative-ai/server'
import { sessionOptions } from '@/lib/session'
import { logger } from '@/util/logger'
const MAX_FILE_BYTES = 20 * 1024 * 1024 // 20MB
const MAX_VERTICES = 500
const DEFAULT_MODEL = 'gemini-3.1-pro-preview'
// Gemini 호출은 건당 과금이므로 사용자별 호출 빈도를 제한한다(프로세스 단위 in-memory).
const RATE_LIMIT_WINDOW_MS = 60 * 1000
const RATE_LIMIT_MAX_REQUESTS = 5
const rateLimitMap = new Map()
const isRateLimited = (key) => {
const now = Date.now()
const recent = (rateLimitMap.get(key) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS)
if (recent.length >= RATE_LIMIT_MAX_REQUESTS) {
rateLimitMap.set(key, recent)
return true
}
recent.push(now)
rateLimitMap.set(key, recent)
return false
}
const FLOOR_PLAN_SCHEMA = {
type: SchemaType.OBJECT,
properties: {
@ -133,6 +153,18 @@ export async function POST(req) {
const apiKey = process.env.GEMINI_API_KEY
const modelName = process.env.GEMINI_MODEL || DEFAULT_MODEL
// 페이지 인증(layout redirect)은 API 라우트에 적용되지 않으므로 세션을 직접 검사한다 — 익명 Gemini 과금 차단.
const session = await getIronSession(cookies(), sessionOptions)
if (!session?.isLoggedIn) {
return NextResponse.json({ error: { code: 'UNAUTHORIZED', message: '로그인이 필요합니다.' } }, { status: 401 })
}
if (isRateLimited(session.userId || 'unknown')) {
return NextResponse.json(
{ error: { code: 'RATE_LIMITED', message: '분석 요청이 너무 잦습니다. 잠시 후 다시 시도해주세요.' } },
{ status: 429 },
)
}
if (!apiKey) {
return NextResponse.json({ error: { code: 'NO_API_KEY', message: 'GEMINI_API_KEY 가 설정되지 않았습니다.' } }, { status: 500 })
}
@ -163,6 +195,7 @@ export async function POST(req) {
const buffer = Buffer.from(await file.arrayBuffer())
const uploadStarted = Date.now()
const uploadResult = await fileManager.uploadFile(buffer, {
mimeType: 'application/pdf',
displayName: file.name || 'floor-plan.pdf',
@ -170,6 +203,7 @@ export async function POST(req) {
uploadedFileName = uploadResult.file.name
await waitForFileActive(fileManager, uploadedFileName)
const fileReadyMs = Date.now() - uploadStarted
const genAI = new GoogleGenerativeAI(apiKey)
const model = genAI.getGenerativeModel({
@ -185,6 +219,7 @@ export async function POST(req) {
const prompt = buildPrompt({ pageMode, facadePages, floorPages })
const generateStarted = Date.now()
const result = await model.generateContent([
{
fileData: {
@ -196,6 +231,7 @@ export async function POST(req) {
])
const raw = result.response.text()
logger.debug('[gemini/floor-plan] timing(ms)', { fileReady: fileReadyMs, generate: Date.now() - generateStarted })
logger.debug('[gemini/floor-plan] raw response', raw)
logger.debug('[gemini/floor-plan] usageMetadata', result.response.usageMetadata)

View File

@ -40,7 +40,9 @@ const PDF_MAX_FILE_BYTES = 20 * 1024 * 1024
// (ms). ( 60s)+generateContent
// backstop . abort .
const PDF_ANALYZE_TIMEOUT_MS = 120 * 1000
// gemini-3.1-pro-preview thinking + MEDIA_RESOLUTION_HIGH PDF
// 2 ( 120s). .
const PDF_ANALYZE_TIMEOUT_MS = 300 * 1000
const PDF_PAGE_MODE = {
ALL: 'all',
@ -107,6 +109,16 @@ export default function PlacementShapeSetting({ id, pos = { x: 50, y: 180 }, pla
const [pdfAnalyzing, setPdfAnalyzing] = useState(false)
const { setIsGlobalLoading } = useContext(QcastContext)
const pdfInputRef = useRef(null)
// PDF ( ) abort ,
// canvas .
const pdfRunRef = useRef(null)
useEffect(() => {
return () => {
pdfRunRef.current?.controller?.abort()
pdfRunRef.current = null
}
}, [])
/**
* 치수 입력방법(복시도입력/실측값입력/도면 파일 업로드)
*/
@ -165,6 +177,7 @@ export default function PlacementShapeSetting({ id, pos = { x: 50, y: 180 }, pla
setPdfAnalyzing(true)
setIsGlobalLoading(true)
const controller = new AbortController()
pdfRunRef.current = { controller }
const timeoutId = setTimeout(() => controller.abort(), PDF_ANALYZE_TIMEOUT_MS)
let response = null
@ -188,6 +201,11 @@ export default function PlacementShapeSetting({ id, pos = { x: 50, y: 180 }, pla
setIsGlobalLoading(false)
}
// abort .
if (pdfRunRef.current?.controller !== controller) {
return false
}
// alert/confirm ( z-index alert ).
if (errorKey) {
swalFire({ text: getMessage(errorKey), type: 'alert' })
@ -216,6 +234,11 @@ export default function PlacementShapeSetting({ id, pos = { x: 50, y: 180 }, pla
if (!proceed) return false
}
// confirm
if (pdfRunRef.current?.controller !== controller) {
return false
}
const applied = await applyOuterline(payload.outerline, { unit: payload.unit || 'mm' })
if (!applied) {
swalFire({ text: getMessage('pdf.import.error.apply'), type: 'alert' })
@ -439,7 +462,12 @@ export default function PlacementShapeSetting({ id, pos = { x: 50, y: 180 }, pla
const hasRoofs = canvas.getObjects().some((obj) => obj.name === POLYGON_TYPE.ROOF)
// roofSizeSet
if (currentRoof?.roofSizeSet === '2') {
if (inputMode === INPUT_MODE.PDF) {
// PDF (outerLineFix)
// useOuterLineWall .
setSelectedMenu('outline')
setCurrentMenu(MENU.ROOF_COVERING.ROOF_SHAPE_SETTINGS)
} else if (currentRoof?.roofSizeSet === '2') {
setSelectedMenu('surface')
setCurrentMenu(MENU.BATCH_CANVAS.BATCH_DRAWING)
} else if (currentRoof?.roofSizeSet === '1') {

View File

@ -1,9 +1,10 @@
import { useSetRecoilState, useRecoilValue } from 'recoil'
import { canvasState } from '@/store/canvasAtom'
import { outerLinePointsState } from '@/store/outerLineAtom'
import { fabric } from 'fabric'
import { canvasState, canvasZoomState } from '@/store/canvasAtom'
import { outerLineFixState, outerLinePointsState } from '@/store/outerLineAtom'
import { outlineDisplaySelector } from '@/store/settingAtom'
import { POLYGON_TYPE } from '@/common/common'
import { QLine } from '@/components/fabric/QLine'
import { usePolygon } from '@/hooks/usePolygon'
import { useLine } from '@/hooks/useLine'
import { useSwal } from '@/hooks/useSwal'
import { useMessage } from '@/hooks/useMessage'
import { logger } from '@/util/logger'
@ -11,8 +12,9 @@ import { snapNearAxisEdges, cleanSelfIntersectingPolygon } from '@/util/qpolygon
import * as turf from '@turf/turf'
const MM_PER_CANVAS_UNIT = 10
const MAX_DIM = 1500
const MIN_CANVAS_UNIT_LENGTH = 0.5
// useLine.addLine 이 length < 1(=10mm) 라인을 생성하지 않으므로 동일 임계값으로 사전 제거한다.
const MIN_CANVAS_UNIT_LENGTH = 1
const VIEWPORT_FIT_RATIO = 0.6 // 화면맞춤 시 캔버스 대비 도면 최대 비율
const SIMPLIFY_TOLERANCE = 0.5 // canvas unit ≈ 5mm. 직선 위 잉여 정점/미세 엣지 제거(보수적)
const SNAP_ANGLE_TOL_DEG = 2 // 거의 수평/수직 엣지를 정확히 축정렬로 스냅
@ -33,31 +35,37 @@ const ensureCounterClockwise = (points) => {
return polygonArea(points) > 0 ? [...points].reverse() : points
}
const fitAndCenter = (points, canvas) => {
// 직전 '유지된' 정점과의 거리로 짧은 엣지를 제거한다. 닫힘 엣지(마지막→첫)도 동일 기준으로 검사 —
// Gemini 가 닫힌 링(첫점=끝점 중복)을 반환하는 경우가 여기서 함께 정리된다.
const dedupShortEdges = (points) => {
const out = []
points.forEach((p) => {
const prev = out[out.length - 1]
if (prev && Math.hypot(p.x - prev.x, p.y - prev.y) < MIN_CANVAS_UNIT_LENGTH) return
out.push(p)
})
while (out.length >= 3 && Math.hypot(out[out.length - 1].x - out[0].x, out[out.length - 1].y - out[0].y) < MIN_CANVAS_UNIT_LENGTH) {
out.pop()
}
return out
}
// 좌표에 축소 scale 을 곱하면 'QLine 길이×10 = 표시 mm' 불변식이 깨져 치수 라벨이 실측과 어긋난다.
// 좌표는 실측 그대로 평행이동만 하고, 화면맞춤은 fitViewport 의 zoom(viewportTransform)으로 분리 처리한다.
const centerOnCanvas = (points, canvas) => {
const xs = points.map((p) => p.x)
const ys = points.map((p) => p.y)
const minX = Math.min(...xs)
const minY = Math.min(...ys)
const maxX = Math.max(...xs)
const maxY = Math.max(...ys)
const width = maxX - minX
const height = maxY - minY
const targetWidth = (canvas?.getWidth?.() ?? 1000) * 0.6
const targetHeight = (canvas?.getHeight?.() ?? 1000) * 0.6
const maxAllowed = Math.min(MAX_DIM, Math.max(targetWidth, targetHeight))
let scale = 1
if (width > maxAllowed || height > maxAllowed) {
scale = Math.min(maxAllowed / width, maxAllowed / height)
}
const width = Math.max(...xs) - minX
const height = Math.max(...ys) - minY
const cx = (canvas?.getWidth?.() ?? 1000) / 2
const cy = (canvas?.getHeight?.() ?? 1000) / 2
return points.map((p) => ({
x: cx + (p.x - (minX + width / 2)) * scale,
y: cy + (p.y - (minY + height / 2)) * scale,
x: cx + (p.x - (minX + width / 2)),
y: cy + (p.y - (minY + height / 2)),
}))
}
@ -88,7 +96,10 @@ const normalizeGeometry = (points) => {
export function usePdfImport() {
const canvas = useRecoilValue(canvasState)
const setOuterLinePoints = useSetRecoilState(outerLinePointsState)
const { addPolygonByLines } = usePolygon()
const setOuterLineFix = useSetRecoilState(outerLineFixState)
const setCanvasZoom = useSetRecoilState(canvasZoomState)
const isOutlineDisplay = useRecoilValue(outlineDisplaySelector)
const { addLine } = useLine()
const { swalFire } = useSwal()
const { getMessage } = useMessage()
@ -114,21 +125,64 @@ export function usePdfImport() {
removable.forEach((obj) => canvas.remove(obj))
}
// 수동 그리기(useOuterLineWall.drawLine)와 동일하게 useLine.addLine 경유로 생성한다 —
// attributes/planeSize/fontSize 가 없으면 지붕형상 설정·처마/케라바 편집·재로드 복원이 깨진다.
const drawOuterLines = (points) => {
points.forEach((point, idx) => {
if (idx === 0) return
const prev = points[idx - 1]
const line = new QLine([prev.x, prev.y, point.x, point.y], {
stroke: '#000000',
addLine([prev.x, prev.y, point.x, point.y], {
stroke: 'black',
strokeWidth: 3,
idx,
selectable: true,
name: 'outerLine',
x1: prev.x,
y1: prev.y,
x2: point.x,
y2: point.y,
visible: isOutlineDisplay,
})
canvas.add(line)
})
}
// skeletonBuilder 등 지붕 생성 로직이 정점 위치를 'outerLinePoint' circle 에서 읽는다 — 수동 플로우와 동일하게 생성
const drawOuterLinePoints = (points) => {
points.forEach((point) => {
canvas.add(
new fabric.Circle({
left: point.x,
top: point.y,
visible: false,
name: 'outerLinePoint',
}),
)
})
}
// 도면이 화면보다 크면 캔버스 중앙 고정 줌으로 화면맞춤한다. canvasZoomState 를 함께 동기화하면
// useCanvasEvent 의 setZoom(동일 zoom 값) 은 translation 을 보존하므로 중앙 정렬이 유지된다.
const fitViewport = (points) => {
const xs = points.map((p) => p.x)
const ys = points.map((p) => p.y)
const width = Math.max(...xs) - Math.min(...xs)
const height = Math.max(...ys) - Math.min(...ys)
const targetWidth = canvas.getWidth() * VIEWPORT_FIT_RATIO
const targetHeight = canvas.getHeight() * VIEWPORT_FIT_RATIO
let zoomPercent = 100
if (width > targetWidth || height > targetHeight) {
zoomPercent = Math.max(1, Math.floor(Math.min(targetWidth / width, targetHeight / height) * 100))
}
const zoom = zoomPercent / 100
const cx = canvas.getWidth() / 2
const cy = canvas.getHeight() / 2
canvas.setViewportTransform([zoom, 0, 0, zoom, cx * (1 - zoom), cy * (1 - zoom)])
setCanvasZoom(zoomPercent)
}
const applyOuterline = async (mmPoints, options = {}) => {
if (!canvas) {
logger.warn('[usePdfImport] canvas 가 준비되지 않았습니다.')
@ -148,13 +202,7 @@ export function usePdfImport() {
}
let canvasPoints = toCanvasUnits(mmPoints)
canvasPoints = canvasPoints.filter((p, idx, arr) => {
if (idx === 0) return true
const prev = arr[idx - 1]
const dx = p.x - prev.x
const dy = p.y - prev.y
return Math.hypot(dx, dy) >= MIN_CANVAS_UNIT_LENGTH
})
canvasPoints = dedupShortEdges(canvasPoints)
if (canvasPoints.length < 3) {
swalFire({ text: getMessage('pdf.import.error.too.few.vertices'), type: 'alert' })
@ -162,7 +210,14 @@ export function usePdfImport() {
}
canvasPoints = normalizeGeometry(canvasPoints)
canvasPoints = fitAndCenter(canvasPoints, canvas)
canvasPoints = dedupShortEdges(canvasPoints) // 정규화 과정에서 생긴 미세 엣지 제거
if (canvasPoints.length < 3) {
swalFire({ text: getMessage('pdf.import.error.too.few.vertices'), type: 'alert' })
return false
}
canvasPoints = centerOnCanvas(canvasPoints, canvas)
canvasPoints = ensureCounterClockwise(canvasPoints)
const proceed = async () => {
@ -170,16 +225,15 @@ export function usePdfImport() {
const closedPoints = [...canvasPoints, canvasPoints[0]]
setOuterLinePoints(closedPoints)
drawOuterLines(closedPoints)
drawOuterLinePoints(closedPoints)
try {
const lines = canvas.getObjects().filter((obj) => obj.name === 'outerLine')
if (lines.length >= 3) {
addPolygonByLines(lines, { name: POLYGON_TYPE.WALL, fill: 'transparent', stroke: 'black' })
}
} catch (e) {
logger.warn('[usePdfImport] wall polygon 생성 실패', e?.message || e)
}
// 수동 확정(useOuterLineWall.handleFix) 직후와 동일한 상태로 만든다 — 이 플래그가 없으면
// 지붕형상 설정(useRoofShapeSetting/useRoofShapePassivitySetting) 진입이 'wall.line.not.found' 로 차단된다.
// WALL/ROOF 폴리곤은 수동 플로우와 동일하게 지붕형상 설정 적용 시점에 생성된다.
canvas.outerLineFix = true
setOuterLineFix(true)
fitViewport(closedPoints)
canvas.renderAll()
}