49 lines
9.2 KiB
Markdown
49 lines
9.2 KiB
Markdown
## Generated Next.js Repository Rules
|
||
|
||
- This frontend application was generated by `@kri/create-next-app`.
|
||
- Keep the generated Next.js routing, server/client boundary, authentication, environment, state, query, and application-shell conventions unless an approved task changes them.
|
||
- Prefer shadcn and approved KRI UI Registry components over new local primitives when a suitable component exists.
|
||
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`.
|
||
- Consume shared frontend behavior from `@kri/common` and the KRI UI Registry instead of copying provider implementations into this repository.
|
||
- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose.
|
||
- Run `npm run typecheck` and `npm run build` after relevant source or configuration changes.
|
||
|
||
## Survey Dashboard Data Schema (source: `public/tmp-doc/테이블 스키마.xlsx`)
|
||
|
||
Use these backend table/column names as the source of truth for frontend type, variable, and component naming (e.g. TanStack Query keys, DTO-free response types, prop names) so terminology stays consistent between frontend and backend.
|
||
|
||
- `t_wave` (분기/회차): `wave_cd`(PK, 예: `2601` = 2026년 1분기), `year`, `wave`, `label`(예: "1분기 재생에너지"), `is_open`.
|
||
- `wave_cd` 인코딩: 연도 뒤 2자리 + 분기 2자리(zero-padded), 예: 2026년 1분기 → `2601`.
|
||
- `t_wave_info` (조사 개요 항목, "조사 목적" 등): `wave_info_idx`(PK), `wave_cd`(FK), `wave_info_order`, `wave_info_title`, `wave_info_content`.
|
||
- `t_survey` (조사 대상군: 일반국민/전문가): `wave_cd`+`survey_cd`(PK), `survey_order`, `survey_title`(예: "일반국민 전화조사"), `survey_alias`(예: "일반국민").
|
||
- `t_survey_item` (조사 개요 세부 항목: 조사대상/조사지역/조사방법/조사기간/표본규모/표본오차): `survey_item_idx`(PK), `wave_cd`+`survey_cd`(FK), `survey_item_order`, `survey_item_title`, `survey_item_content`.
|
||
- `t_file` (결과보고서/인포그래픽 다운로드): `file_idx`(PK), `wave_cd`(FK), `file_order`, `file_title`, `file_type`(예: "PDF"), `file_name`.
|
||
- `t_part` (Ⅰ~Ⅳ 대분류): `wave_cd`+`part_cd`(PK), `part_order`, `part_title`(예: "Ⅰ. 에너지 및 재생에너지 정책").
|
||
- `t_part_item` (문항, 예: "1 재생에너지 중심의 에너지 전환 정책 평가"): `wave_cd`+`part_cd`+`part_item_cd`(PK), `part_item_order`, `part_item_title`, `chart_type`(예: "bar"), `part_item_comment`(각주 텍스트).
|
||
- `t_part_item_sub` (문항 아래 서브 그룹, 예: 3-1의 "확대 이유"/"감소 이유"): `wave_cd`+`part_cd`+`part_item_cd`+`part_item_sub_cd`(PK), `part_item_sub_title`.
|
||
- `t_part_item_base` (응답 모집단 N/보조 문구): `part_item_base_idx`(PK), `wave_cd`+`part_cd`+`part_item_cd`+`survey_cd`+`part_item_sub_cd`(nullable, FK), `base_count`(예: 1640), `base_pre_text`/`base_post_text`(nullable).
|
||
- `t_part_item_data` (차트 데이터 값): PK 컬럼명이 `t_part_item_data_idx`로 다른 테이블과 달리 테이블명 접두사가 붙어 있음(스키마 내 유일한 예외 — 연동 코드 작성 시 오탈자로 오인하지 말 것). `wave_cd`+`part_cd`+`part_item_cd`+`survey_cd`+`part_item_sub_cd`(nullable, FK), `part_item_data_order`, `part_item_data_label`(예: "매우 잘하고 있다"), `part_item_data_value`(`decimal(14,10)`, 예: `39.9` — 퍼센트 값으로 추정).
|
||
- 계층 구조: `t_wave` → (`t_wave_info` | `t_survey` → `t_survey_item` | `t_file` | `t_part` → `t_part_item` → (`t_part_item_sub`, `t_part_item_base`, `t_part_item_data`)).
|
||
- 복합키 패턴: 대부분 상위 테이블의 코드 컬럼(`wave_cd`, `part_cd`, `part_item_cd`, `survey_cd`, `part_item_sub_cd`)을 그대로 이어받는 자연복합키. 별도 대리키(`_idx`)는 `t_wave_info`, `t_survey_item`, `t_file`, `t_part_item_base`, `t_part_item_data`에만 존재.
|
||
|
||
## Backend API Integration (epolicy-dash-back, `http://localhost:6107`, OpenAPI at `/v3/api-docs`)
|
||
|
||
백엔드 연동이 완료되어 위 "프론트엔드 명명과의 정합성" 문제는 해소됨 — 영문 slug 라우팅(`survey.data.ts`/`menu.data.ts`)을 전부 제거하고 실제 `waveCd`/`partCd` 기반 동적 라우트와 API 응답 데이터로 완전히 교체했다.
|
||
|
||
- **라우트**: `/dashboard/[waveCd]` (조사 개요), `/dashboard/[waveCd]/[partCd]` (Part 상세, 하위 문항은 `#item-{partItemCd}` 앵커). 루트 `/`는 `GET /waves`를 서버에서 조회해 접근 가능한 첫 Wave로 리다이렉트한다.
|
||
- **헤더 분기탭·좌측 메뉴**는 하드코딩 config가 아니라 `GET /waves`(헤더)와 `GET /waves/{waveCd}`(사이드바, `parts[].items[]`)를 그대로 데이터 소스로 사용한다 (`AppMainLayout.tsx`). 새 분기/Part/문항이 추가돼도 프론트 코드 변경이 필요 없다.
|
||
- **BFF 프록시 패턴**: 브라우저 → `src/app/api/waves/[[...slug]]/route.ts`(GET 전용, CUD 없음) → `createServerApi()`(httpOnly 쿠키의 accessToken을 Bearer로 자동 첨부) → 실제 백엔드. `example` 리소스와 동일한 패턴이며, 신규 리소스 추가 시 이 구조를 그대로 복제하면 된다.
|
||
- **`userContext`/`ctx` 쿼리파라미터**: Swagger상 로그인/로그아웃/Wave API에 필수 파라미터로 보이지만, 실제로는 서버가 인증 헤더에서 자동으로 채우는 값이다 (curl로 직접 검증함 — 파라미터 없이 호출해도 정상 동작). 프론트에서 절대 수동으로 구성해 보내면 안 된다(클라이언트가 자기 `userRole`을 조작할 수 있게 되는 보안 문제).
|
||
- **Wave 접근 정책**: `GET /waves`는 `accessible` 플래그와 함께 모든 Wave를 반환한다 — 헤더 탭은 `accessible=false`면 `disabled` 처리만 하고 숨기지 않는다. Wave/Part 상세 API는 비공개 접근 시 `403 WAVE_ACCESS_DENIED`를 반환하며, `nextApi`의 기본 403 핸들러(로그아웃 리다이렉트)를 쓰면 안 되므로 `skipForbiddenHandler: true`를 지정하고 화면에서 직접 에러 메시지를 표시한다 (`src/lib/api-error-message.ts`).
|
||
- **파일 다운로드**: Wave 상세 응답의 `files[].downloadUrl`은 백엔드 서버 origin 기준 상대 경로이며 프론트 앱 origin과 다르다. `NEXT_PUBLIC_FILE_ORIGIN` 환경변수(백엔드와 동일 호스트, `.env.local`/`.env.development`/`.env.production`에 정의)와 결합해서 사용한다 (`src/lib/file-download.ts`). 경로를 직접 조합하지 않는다.
|
||
- **차트 라이브러리**: 프로젝트에 없었으므로 KriUiRegistry(`https://ui-registry.kric.com/r/kri-chart.json`)의 echarts 래퍼(`kri-chart`, `KriBarChart` 등)를 shadcn CLI로 설치했다 (`src/components/chart/`). 새 의존성(`echarts`, `echarts-for-react`)이 추가됐다.
|
||
- **차트/통계표 데이터 해석**: `resultGroups`가 렌더링 단위. 통계표는 모든 `categories`/`series.values`를 그대로 쓰고, 차트는 `category.chartVisible === true`인 인덱스만 category/series를 함께 필터링해서 사용한다 (`src/lib/chart-utils.ts`의 `toChartData`). `categories[i]`와 각 `series[n].values[i]`는 항상 같은 인덱스로 정렬되어 있다는 전제.
|
||
- **에러 응답**: RFC 7807(`application/problem+json`)이며 `errorToResponse`(`@kri/common/http`)가 그대로 BFF 응답에 프록시한다. 프론트는 `detail`보다 `code`(예: `WAVE_ACCESS_DENIED`, `WAVE_NOT_FOUND`, `PART_NOT_FOUND`)로 분기하는 걸 우선한다.
|
||
- **로그인 필터 vs 업무 오류 403 구분**: 인증 필터 단계에서 막힌 요청(토큰 없음/무효)은 바디 없는 401/403으로 온다. `WAVE_ACCESS_DENIED` 같은 업무 오류는 RFC7807 `code`가 있는 정상 JSON 응답이다. `code`가 없는 401/403은 세션이 실제로 무효하다는 뜻이므로 `/logout`으로 보내야 한다 (`src/lib/api-error-message.ts`의 `isSessionInvalid`). 반대로 클라이언트가 이미 로그아웃 상태(`useAuth()`의 `auth.user`가 없음)라면 애초에 API를 호출하지 않고 즉시 `/logout`으로 보낸다 (`AppMainLayout.tsx`) — 두 체크는 서로 다른 계층(클라이언트가 아는 상태 vs 서버가 판정한 토큰 유효성)이라 둘 다 필요하다.
|
||
|
||
### ⚠️ `nextApi`(브라우저 클라이언트) 필수 수정 사항 — 스캐폴딩 버그
|
||
|
||
`NEXT_PUBLIC_API_BASE=/api`(상대 경로)를 `createHttpClient`에 그대로 넘기면 **브라우저의 모든 API 호출이 예외 없이 즉시 실패**한다. `@kri/common`의 `createBaseUrl`이 내부적으로 `new URL(baseUrl)`을 base 인자 없이 호출하는데(`node_modules/@kri/common/dist/http/http-client.js`), 상대 경로만 단독으로 넘기면 브라우저 `URL` 생성자가 `document.baseURI`로 자동 보정해주지 않고 `TypeError: Failed to construct 'URL': Invalid URL`을 던진다. 원래 스캐폴딩(`@kri/create-next-app`)은 이 버그를 가진 채로 생성되며, `example` CRUD가 실사용된 적이 없어 지금까지 드러나지 않았었다.
|
||
|
||
`src/lib/http-client.ts`에서 브라우저에서는 `window.location.origin`과 결합해 절대 URL로 변환한 뒤 `createHttpClient`에 넘기도록 고쳐뒀다 — 이 파일을 재생성하거나 유사 패턴(`nextApi` 스타일 클라이언트)을 다른 프로젝트에 복제할 때 이 처리를 빠뜨리지 말 것.
|