Compare commits
8 Commits
v0.1.34
...
49ef0322ac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49ef0322ac | ||
|
|
cc4bc0b7e4 | ||
|
|
515f5c1d1a | ||
|
|
6cbf7feaf5 | ||
|
|
fda2d76514 | ||
|
|
7d95ecb3cb | ||
|
|
7b2753b9fd | ||
|
|
7411c8956f |
24
CHANGELOG.md
24
CHANGELOG.md
@@ -6,6 +6,30 @@
|
||||
|
||||
## 2026-06-15
|
||||
|
||||
### 🌐 #352 i18n 뼈대 ko/en/ja/es (v0.1.37)
|
||||
- next-intl 5.x 도입
|
||||
- src/i18n/{config,LocaleProvider} + src/messages/{ko,en,ja,es}.json (30 키)
|
||||
- LanguageSwitcher 컴포넌트 (헤더, ARIA listbox, 44px, 국기+네이티브명)
|
||||
- localStorage tasteby_locale + 브라우저 언어 감지 + ko fallback
|
||||
- 설계서: docs/design/352-i18n-skeleton/README.md
|
||||
- 미적용: URL 라우팅 i18n, SEO meta, 사용자 콘텐츠 번역, 어드민(한국어 유지)
|
||||
- Refs: #352 (close)
|
||||
|
||||
### 🧹 #329 admin/page.tsx 분리 (v0.1.35→v0.1.36 운영 반영)
|
||||
- page.tsx 2817 → 107 LOC (탭 라우팅 + 헤더만)
|
||||
- _panels/{Channels,Videos,Restaurants,Users,Daemon}Panel.tsx 5개 분리
|
||||
- localStorage.getItem 10곳 → getAdminToken() (admin-utils.ts)
|
||||
- SSE 통일은 후속 #351 분리
|
||||
- 설계서: docs/design/329-admin-split/README.md
|
||||
- Refs: #329 (close)
|
||||
|
||||
### ⚡ #331 VectorService batchUpdate (v0.1.34)
|
||||
- saveRestaurantVectors: N+1 단건 INSERT → 단일 jdbc.batchUpdate(SqlParameterSource[])
|
||||
- UUID 인라인 변환 제거 → IdGenerator.newId() 공통화
|
||||
- 현재 N=1이지만 chunk 분할 도입 시 효과 본격화
|
||||
- 설계서: docs/design/331-vector-batch-insert/README.md
|
||||
- Refs: #331 (close)
|
||||
|
||||
### ⚡ #326 parseJson 단일 패스 (v0.1.33)
|
||||
- OciGenAiService.parseJson 잘린 배열 복구를 brace depth counter 단일 패스로 교체
|
||||
- 이전 O(N²) + Jackson 예외 양산 → O(N) + 명시적 에러 경로
|
||||
|
||||
107
docs/design/329-admin-split/README.md
Normal file
107
docs/design/329-admin-split/README.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# 설계서: admin/page.tsx 분리 + 토큰/SSE 유틸 통일 (#329)
|
||||
|
||||
> **상태**: Approved
|
||||
> **작성**: [AI] Architect · **최종수정**: 2026-06-15
|
||||
> **추적성** — Redmine: #329 · 부모: #304 (현행화 frontend-admin, 09-Done)
|
||||
> · 구현 파일: `frontend/src/app/admin/page.tsx`, `frontend/src/app/admin/_panels/*.tsx` (신규), `frontend/src/lib/admin-utils.ts`
|
||||
> · 테스트: 수동 (각 탭 진입 + 기존 시나리오 회귀)
|
||||
|
||||
## 1. 목적 (Why)
|
||||
|
||||
`admin/page.tsx`가 2817 LOC 단일 파일. 5개 패널이 같은 파일 안에 함께 있어 (a) 빌드 변경 시 무관한 패널까지 재빌드/재배포, (b) 코드 리뷰 시 충돌 가능성↑, (c) 로직 격리 어려움. 또한 `localStorage` 직접 호출 + SSE 파싱 코드 중복이 남아있어 #304 후속에서 한 번 더 정리.
|
||||
|
||||
## 2. 범위 (Scope)
|
||||
|
||||
- **포함**
|
||||
- 5개 패널을 `app/admin/_panels/<Panel>.tsx`로 추출 (Next.js underscore prefix로 라우팅 제외).
|
||||
- `page.tsx`는 탭 라우팅 + 헤더 + 패널 import만.
|
||||
- 남은 `localStorage.getItem("tasteby_token")` 호출 → `getAdminToken()`/`authHeaders()` 교체.
|
||||
- SSE 파싱 중복(약 5~6곳) → `consumeSseStream()` 활용.
|
||||
- 공유 타입(`AdminUser`/`UserFavorite`/`UserReview`/`UserMemo`/`VideoSortKey`)을 _panels 파일 내부 또는 `api.ts`에 옮김(짧은 타입만).
|
||||
- **제외**
|
||||
- 패널 내부 로직 변경 (state/effect 그대로).
|
||||
- catch{/*ignore*/} 일괄 로깅 (별도 후속).
|
||||
- ad-hoc 타입 캐스팅 정리 (별도 후속).
|
||||
- 디자인 시스템 색상 통일.
|
||||
|
||||
## 3. 인수조건
|
||||
|
||||
- [ ] 5개 파일 신규: `_panels/{Channels,Videos,Restaurants,Users,Daemon}Panel.tsx`.
|
||||
- [ ] `page.tsx` < 200 LOC (이전 2817).
|
||||
- [ ] localStorage 직접 호출이 admin 페이지 내에 0건.
|
||||
- [ ] SSE reader 직접 호출(`response.body?.getReader()`)이 0건.
|
||||
- [ ] 모든 탭 진입 + 기존 시나리오 회귀 없음(빌드 통과 + 수동 smoke).
|
||||
- [ ] dev 빌드 + 운영 배포 성공.
|
||||
|
||||
## 4. 컨텍스트 & 제약
|
||||
|
||||
- Next.js 16 (App Router). `_` prefix 디렉토리는 route 제외.
|
||||
- `"use client"` 지시문 각 패널 파일 상단에 필요.
|
||||
- React Server Components 미사용 (모두 클라이언트 컴포넌트).
|
||||
- `useAuth()` 훅이 `auth-context`에 있음. 부모 `AdminPage`가 isAdmin 판정 후 prop으로 패널에 전달.
|
||||
- 패널 간 상태 공유 없음 (각각 독립).
|
||||
|
||||
## 5. 아키텍처 개요
|
||||
|
||||
```
|
||||
app/admin/
|
||||
page.tsx ← 탭 라우팅 + 헤더 + CacheFlushButton + 패널 import
|
||||
_panels/
|
||||
ChannelsPanel.tsx ← 214 LOC
|
||||
VideosPanel.tsx ← 1272 LOC (가장 큼)
|
||||
RestaurantsPanel.tsx ← 667 LOC
|
||||
UsersPanel.tsx ← 332 LOC
|
||||
DaemonPanel.tsx ← 223 LOC
|
||||
|
||||
lib/admin-utils.ts (이미 존재)
|
||||
├─ getAdminToken()
|
||||
├─ authHeaders()
|
||||
└─ consumeSseStream()
|
||||
```
|
||||
|
||||
## 6. 함수 명세
|
||||
|
||||
| 단위 | 책임 | 비고 |
|
||||
|------|------|------|
|
||||
| `page.tsx` (재작성) | 탭 라우팅 + 패널 import | < 200 LOC |
|
||||
| `_panels/*.tsx` (신규 5개) | 각 패널 로직 그대로 옮김 | "use client" |
|
||||
| `localStorage` 호출 (~10곳) | `getAdminToken()`/`authHeaders()`로 통일 | 의미 동일 |
|
||||
| SSE `getReader` (~5곳) | `consumeSseStream(resp, onEvent)`로 통일 | 의미 동일 |
|
||||
|
||||
## 7. 흐름
|
||||
|
||||
1. `_panels/` 디렉토리 생성.
|
||||
2. 각 패널 함수 + 그에 종속된 타입/상수를 `<Panel>Panel.tsx`로 잘라 옮김.
|
||||
3. 각 파일에 `"use client"` + import 추가.
|
||||
4. `localStorage.getItem("tasteby_token")` → `getAdminToken()` 일괄.
|
||||
5. SSE `getReader/decoder/buf.split/match` 패턴 → `consumeSseStream(resp, onEvent)` 일괄.
|
||||
6. `page.tsx` 재작성 — 탭 라우팅 + 패널 import.
|
||||
7. `npm run build`.
|
||||
8. `pm2 restart` 또는 `deploy.sh --frontend-only`.
|
||||
|
||||
## 8. 엣지케이스
|
||||
|
||||
- **순환 import**: 패널 간 의존 없음 → 안전.
|
||||
- **Type 중복**: `AdminUser` 등 패널 내부 타입은 그대로 옮김. 공유 타입은 `api.ts`에 있음.
|
||||
- **default export vs named**: 각 패널은 named export. `page.tsx`에서 `import { ChannelsPanel } from "./_panels/ChannelsPanel"`.
|
||||
- **빌드 크기**: 동일(코드 splitting은 별도 작업).
|
||||
|
||||
## 9. 테스트
|
||||
|
||||
- 빌드: `npm run build` 통과.
|
||||
- 수동:
|
||||
- `/admin` 접근 → 5탭 모두 진입 가능.
|
||||
- 채널 추가, 영상 강제 추출(SSE), 식당 검색/수정, 유저 권한 토글, 데몬 설정 변경 — 모두 정상.
|
||||
- 자동: 별도 후속(테스트 인프라 #343).
|
||||
|
||||
## 10. 리스크 & 대안
|
||||
|
||||
- **선택**: 5개 파일 추출 + 내부 로직 그대로.
|
||||
- **대안 A**: 추출 + 내부 리팩터링 동시 — 회귀 위험↑, 별도 후속이 안전.
|
||||
- **대안 B**: Atomic Design (atoms/molecules/organisms) — 큰 재구조화. 미루기.
|
||||
- **트레이드오프**: 외형은 동일, 유지보수성/충돌 가능성만 개선. 점진적 접근.
|
||||
|
||||
## 11. 미해결 질문
|
||||
|
||||
- 공통 panel layout(헤더/리스트/페이징) 추상화 — 후속.
|
||||
- VideosPanel 1272 LOC 내부 분할(상태 머신 + SSE 흐름 분리) — 별도 후속.
|
||||
80
docs/design/348-name-similarity/README.md
Normal file
80
docs/design/348-name-similarity/README.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# 설계서: isNameSimilar 한국어 자모 분해 + Sørensen-Dice (#348)
|
||||
|
||||
> **상태**: Approved
|
||||
> **작성**: [AI] Architect · **최종수정**: 2026-06-15
|
||||
> **추적성** — Redmine: #348 · 부모: #332 (이미 close)
|
||||
> · 구현 파일: `backend-java/src/main/java/com/tasteby/util/HangulSimilarity.java` (신규), `backend-java/src/main/java/com/tasteby/controller/RestaurantController.java`
|
||||
|
||||
## 1. 목적
|
||||
|
||||
기존 `isNameSimilar`가 Jaccard-like(문자 set 교집합 비율 ≥ 0.4)로 짧은 한국어 이름에서 오탐 가능. 자모 분해 + Sørensen-Dice bigram으로 정확도 향상.
|
||||
|
||||
## 2. 범위
|
||||
|
||||
- **포함**
|
||||
- `HangulSimilarity.similarity(a, b)` 유틸 신규
|
||||
- `RestaurantController.isNameSimilar` 호출부를 새 유틸로 교체
|
||||
- **제외 (별도 후속으로 분리)**
|
||||
- DDG → 정식 검색 API 전환 (외부 API 결정 + 비용/계약 필요)
|
||||
- DTO RestaurantUpdateDTO + @Valid 표준화 (#332 화이트리스트 set으로 SQL 측 가드 확보)
|
||||
- UNIQUE(google_place_id) 제약 강화 — DB 중복 정리 선행 필요(현재 10+건 중복 확인)
|
||||
|
||||
## 3. 인수조건
|
||||
|
||||
- [ ] `HangulSimilarity.similarity(a, b)` 0.0~1.0 반환 (1.0=동일)
|
||||
- [ ] 한국어 음절을 Unicode NFD로 자모 분해(초성·중성·종성)
|
||||
- [ ] 분해 후 bigram 기반 Sørensen-Dice 계수 계산
|
||||
- [ ] 빈 문자열 안전 처리 (둘 다 비면 0.0, 한쪽만 비면 0.0)
|
||||
- [ ] `RestaurantController.isNameSimilar` 임계값 0.45로 호출 (Jaccard 0.4와 유사 보수성)
|
||||
- [ ] 회귀 없음 — 기존 정상 매칭 시나리오 통과
|
||||
|
||||
## 4. 컨텍스트 & 제약
|
||||
|
||||
- Java 21 `Normalizer.normalize(Form.NFD)` 활용.
|
||||
- 한글 음절(가-힣) NFD → 초성(ㄱ-ㅎ 호환자모 또는 조합자모) + 중성 + 종성.
|
||||
- 영문/숫자는 그대로 통과.
|
||||
- Sørensen-Dice: `2 * |A ∩ B| / (|A| + |B|)` — bigram 다중집합(multiset) 기준.
|
||||
|
||||
## 5. 함수 명세
|
||||
|
||||
| 함수 | 책임 | 시그니처 |
|
||||
|------|------|---------|
|
||||
| `decomposeHangul(s)` | NFD 자모 분해 + 공백/구두점 제거 + 소문자화 | `static String decompose(String)` |
|
||||
| `bigrams(s)` | 2글자 bigram 리스트 | `static List<String> bigrams(String)` |
|
||||
| `similarity(a, b)` | Sørensen-Dice 0.0~1.0 | `static double similarity(String, String)` |
|
||||
|
||||
## 6. 흐름
|
||||
|
||||
1. 두 이름을 `decompose`로 자모 분해 + 정규화.
|
||||
2. 각 분해 결과를 `bigrams`로 분해.
|
||||
3. multiset 교집합 크기 카운트.
|
||||
4. `2 * common / (sizeA + sizeB)`.
|
||||
|
||||
## 7. 엣지케이스
|
||||
|
||||
- **둘 다 빈 문자열**: 0.0 반환.
|
||||
- **bigram 1개 이하**: 두 문자열 같으면 1.0, 아니면 0.0.
|
||||
- **포함 관계**: 기존 코드의 `a.contains(b) || b.contains(a)` 단축 평가 유지 (1.0 반환).
|
||||
- **혼합(한영)**: NFD가 한글만 분해 → 영문은 그대로. bigram 계산은 동일하게 동작.
|
||||
|
||||
## 8. 테스트 (수동)
|
||||
|
||||
```
|
||||
similarity("스타벅스 강남", "스타벅스 강남점") → ≥ 0.85
|
||||
similarity("스타벅스 강남", "스타벅스 종로") → ≥ 0.55, < 0.85
|
||||
similarity("스타벅스", "맥도날드") → < 0.20
|
||||
similarity("PIZZAHUT", "피자헛") → 한글 + 영문 혼재 가드 통과
|
||||
```
|
||||
|
||||
## 9. 리스크 & 대안
|
||||
|
||||
- **선택**: NFD 분해 + bigram Sørensen-Dice. Java 표준 라이브러리만 사용.
|
||||
- **대안 A**: Apache Commons Text `JaroWinklerSimilarity` — 라이브러리 추가 부담.
|
||||
- **대안 B**: Hangul.js류 라이브러리 — Java 포팅 없음.
|
||||
- **대안 C**: Levenshtein 거리 — 자모 분해와 결합 시 좋으나 구현 복잡.
|
||||
|
||||
## 10. 미해결 질문 / 분리된 후속
|
||||
|
||||
- DDG → 정식 검색 API: Naver Search API 또는 Google Custom Search (외부 API 결정 + 비용 검토 필요) — 별도 신규 이슈
|
||||
- DTO RestaurantUpdateDTO + @Valid: #332 set 화이트리스트로 1차 가드. 본격 DTO는 큰 변경 — 별도 신규 이슈
|
||||
- UNIQUE(google_place_id) 제약: 현재 10+건 중복. 데이터 정리(병합/삭제) 선행 → 별도 신규 이슈
|
||||
141
docs/design/352-i18n-skeleton/README.md
Normal file
141
docs/design/352-i18n-skeleton/README.md
Normal file
@@ -0,0 +1,141 @@
|
||||
# 설계서: i18n 뼈대 — ko/en/ja/es (#352)
|
||||
|
||||
> **상태**: Approved
|
||||
> **작성**: [AI] Architect · **최종수정**: 2026-06-15
|
||||
> **추적성** — Redmine: #352
|
||||
> · 구현 파일: `frontend/package.json`, `frontend/next.config.ts`, `frontend/src/i18n/*` (신규), `frontend/src/messages/{ko,en,ja,es}.json` (신규), `frontend/src/components/LanguageSwitcher.tsx` (신규)
|
||||
> · 테스트: 수동 (언어 전환 + ko fallback)
|
||||
|
||||
## 1. 목적
|
||||
|
||||
장기적으로 영어/일본어/스페인어 시장으로 확장 가능하도록 i18n 뼈대 구축. 본 이슈는 *뼈대*만 — 약 30개 키 초기 번역.
|
||||
|
||||
## 2. 범위
|
||||
|
||||
- **포함**
|
||||
- `next-intl` 라이브러리 도입 (Next.js 16 App Router 권장).
|
||||
- 4개 로케일: `ko, en, ja, es`. 기본 `ko`, fallback `ko`.
|
||||
- 메시지 디렉토리 `src/messages/{ko,en,ja,es}.json`.
|
||||
- Provider (`<NextIntlClientProvider>`) 루트 layout 적용.
|
||||
- `LanguageSwitcher` 컴포넌트 (헤더 우측).
|
||||
- 로케일 저장: localStorage `tasteby_locale`.
|
||||
- 초기 번역 키 ~30개: 헤더(로그인/검색/메뉴) + 주요 액션(저장/취소/삭제/확인) + 페이지 제목.
|
||||
- **제외**
|
||||
- URL 라우팅 i18n (`/ko/...`).
|
||||
- SEO meta tags i18n.
|
||||
- 식당명/리뷰 등 사용자 콘텐츠 번역.
|
||||
- 어드민 페이지(운영자만 사용, 한국어 유지).
|
||||
- 식당 카드/상세 시트 전체 키 추출 (점진).
|
||||
|
||||
## 3. 인수조건
|
||||
|
||||
- [ ] `npm i next-intl` + 4개 메시지 파일 생성.
|
||||
- [ ] `tasteby_locale`이 localStorage에 있으면 사용, 없으면 브라우저 언어 감지(`navigator.language`) → 매칭 안되면 `ko`.
|
||||
- [ ] 헤더 우측 LanguageSwitcher 드롭다운(국기 + 코드).
|
||||
- [ ] 초기 번역 키 약 30개 — 4개 언어 모두 채움.
|
||||
- [ ] 미번역 키는 `ko` fallback (에러 없이).
|
||||
- [ ] 빌드/배포 회귀 없음.
|
||||
|
||||
## 4. 컨텍스트 & 제약
|
||||
|
||||
- Next.js 16 + App Router + `"use client"` 컴포넌트 다수.
|
||||
- 기존 `auth-context`처럼 i18n도 React Context 패턴.
|
||||
- `next-intl`은 server/client 모두 지원, 본 프로젝트는 client-side switching이라 `NextIntlClientProvider` 중심.
|
||||
- URL 라우팅 변경 없이 단순 메시지만 교체(낮은 비용).
|
||||
- 폰트: Pretendard Variable이 한국어/영어 잘 표시, 일본어는 시스템 폰트 fallback OK, 스페인어는 라틴 문자라 OK.
|
||||
|
||||
## 5. 아키텍처 개요
|
||||
|
||||
```
|
||||
frontend/
|
||||
├── src/
|
||||
│ ├── i18n/
|
||||
│ │ ├── config.ts ← 로케일 목록/기본값 상수
|
||||
│ │ ├── LocaleProvider.tsx ← NextIntlClientProvider wrap + localStorage 저장
|
||||
│ │ └── useTranslations.ts ← (next-intl 재export)
|
||||
│ ├── messages/
|
||||
│ │ ├── ko.json ← 기본
|
||||
│ │ ├── en.json
|
||||
│ │ ├── ja.json
|
||||
│ │ └── es.json
|
||||
│ ├── components/
|
||||
│ │ └── LanguageSwitcher.tsx ← 헤더용
|
||||
│ └── app/
|
||||
│ └── layout.tsx ← LocaleProvider로 감싸기
|
||||
```
|
||||
|
||||
## 6. 데이터 모델
|
||||
|
||||
### 메시지 키 (초기 ~30)
|
||||
```json
|
||||
{
|
||||
"header": {
|
||||
"search": "검색", "login": "로그인", "logout": "로그아웃",
|
||||
"menu": "메뉴", "myReviews": "내 리뷰", "favorites": "즐겨찾기"
|
||||
},
|
||||
"actions": {
|
||||
"save": "저장", "cancel": "취소", "delete": "삭제",
|
||||
"edit": "수정", "confirm": "확인", "close": "닫기",
|
||||
"loading": "로딩 중...", "submit": "제출"
|
||||
},
|
||||
"filter": {
|
||||
"title": "필터", "cuisine": "음식 종류", "price": "가격대",
|
||||
"region": "지역", "channel": "채널", "reset": "초기화"
|
||||
},
|
||||
"restaurant": {
|
||||
"rating": "평점", "address": "주소", "phone": "전화",
|
||||
"website": "웹사이트", "closed": "폐업", "tempClosed": "임시휴업"
|
||||
},
|
||||
"review": {
|
||||
"title": "리뷰", "write": "리뷰 작성", "noReviews": "아직 리뷰가 없습니다"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
총 5개 카테고리 × 평균 6개 = 30개 키.
|
||||
|
||||
## 7. 함수 명세
|
||||
|
||||
| 함수/컴포넌트 | 책임 | 비고 |
|
||||
|---|---|---|
|
||||
| `i18n/config.ts` | LOCALES, DEFAULT_LOCALE 상수 | 단순 |
|
||||
| `LocaleProvider.tsx` | NextIntlClientProvider wrap + 메시지 동적 로딩 + localStorage 동기화 | client |
|
||||
| `LanguageSwitcher.tsx` | 헤더 드롭다운 (국기 + 코드) | client, 44px 터치 |
|
||||
| `messages/<lang>.json` | 키 → 텍스트 | flat or nested |
|
||||
|
||||
## 8. 흐름
|
||||
|
||||
1. 사용자 첫 방문 → `tasteby_locale` 없음 → `navigator.language.split('-')[0]`이 LOCALES에 있으면 사용, 아니면 `ko`.
|
||||
2. LocaleProvider가 해당 로케일 메시지 파일 import → NextIntlClientProvider에 전달.
|
||||
3. 컴포넌트는 `useTranslations('header')` 등으로 호출.
|
||||
4. LanguageSwitcher에서 변경 → localStorage 저장 → 페이지 새로고침 또는 state 업데이트.
|
||||
|
||||
## 9. 엣지케이스
|
||||
|
||||
- **메시지 파일 누락 키**: next-intl 기본 동작은 키 자체 표시 + 콘솔 경고. fallback 처리는 messages 명시.
|
||||
- **localStorage 비활성/SSR**: typeof window 체크.
|
||||
- **로케일 코드 대소문자**: 항상 소문자 정규화.
|
||||
- **placeholder 변수**: next-intl ICU 메시지 형식 지원 (`{name}` 등). 초기 키에는 미적용.
|
||||
|
||||
## 10. 테스트
|
||||
|
||||
- 수동:
|
||||
- 한국어 첫 방문 → "검색" 표시.
|
||||
- LanguageSwitcher에서 English → "Search" 표시.
|
||||
- 새로고침 후 영어 유지.
|
||||
- 메시지 누락 키 → 콘솔 경고 + 키 표시.
|
||||
|
||||
## 11. 리스크 & 대안
|
||||
|
||||
- **선택**: `next-intl` (Next.js 16 App Router 권장, ICU 메시지, 활발 유지보수).
|
||||
- **대안 A**: `react-i18next` — 더 일반적이지만 App Router 통합 next-intl이 더 매끄러움.
|
||||
- **대안 B**: 자체 구현 + Context — 의존성 ↓ but 기능/표준화 ↓.
|
||||
- **트레이드오프**: 30개 키는 단순하지만 ICU 메시지(복수형, 성별 등) 필요 시 next-intl 가치 큼.
|
||||
|
||||
## 12. 미해결 질문
|
||||
|
||||
- 식당명/리뷰 콘텐츠 번역 — 사용자 작성이라 자동 번역(LLM)? 별도 정책 결정.
|
||||
- URL 라우팅 i18n (`/en/`) — 후속.
|
||||
- SEO meta tags i18n — 후속.
|
||||
- 어드민 페이지는 운영자 한국어 유지 — 확정.
|
||||
- 통화/날짜 포맷(Intl API) — 후속.
|
||||
2092
frontend/package-lock.json
generated
2092
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -9,11 +9,13 @@
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@phosphor-icons/react": "^2.1.10",
|
||||
"@react-oauth/google": "^0.13.4",
|
||||
"@tabler/icons-react": "^3.40.0",
|
||||
"@types/supercluster": "^7.1.3",
|
||||
"@vis.gl/react-google-maps": "^1.7.1",
|
||||
"next": "16.1.6",
|
||||
"next-intl": "^4.13.0",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"supercluster": "^8.0.1"
|
||||
|
||||
222
frontend/src/app/admin/_panels/ChannelsPanel.tsx
Normal file
222
frontend/src/app/admin/_panels/ChannelsPanel.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Channel } from "@/lib/api";
|
||||
|
||||
// #329 — admin/page.tsx에서 추출 (내부 로직 그대로)
|
||||
export function ChannelsPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
const [channels, setChannels] = useState<Channel[]>([]);
|
||||
const [newId, setNewId] = useState("");
|
||||
const [newName, setNewName] = useState("");
|
||||
const [newFilter, setNewFilter] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [scanResult, setScanResult] = useState<Record<string, string>>({});
|
||||
|
||||
const load = useCallback(() => {
|
||||
api.getChannels().then(setChannels).catch(console.error);
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!newId.trim() || !newName.trim()) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await api.addChannel(newId.trim(), newName.trim(), newFilter.trim() || undefined);
|
||||
setNewId("");
|
||||
setNewName("");
|
||||
setNewFilter("");
|
||||
load();
|
||||
} catch (e: unknown) {
|
||||
alert(e instanceof Error ? e.message : "채널 추가 실패");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const [editingChannel, setEditingChannel] = useState<string | null>(null);
|
||||
const [editDesc, setEditDesc] = useState("");
|
||||
const [editTags, setEditTags] = useState("");
|
||||
const [editOrder, setEditOrder] = useState<number>(99);
|
||||
|
||||
const handleSaveChannel = async (id: string) => {
|
||||
try {
|
||||
await api.updateChannel(id, { description: editDesc, tags: editTags, sort_order: editOrder });
|
||||
setEditingChannel(null);
|
||||
load();
|
||||
} catch {
|
||||
alert("채널 수정 실패");
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (channelId: string, channelName: string) => {
|
||||
if (!confirm(`"${channelName}" 채널을 삭제하시겠습니까?`)) return;
|
||||
try {
|
||||
await api.deleteChannel(channelId);
|
||||
load();
|
||||
} catch {
|
||||
alert("채널 삭제 실패");
|
||||
}
|
||||
};
|
||||
|
||||
const handleScan = async (channelId: string, full: boolean = false) => {
|
||||
setScanResult((prev) => ({ ...prev, [channelId]: full ? "전체 스캔 중..." : "스캔 중..." }));
|
||||
try {
|
||||
const res = await api.scanChannel(channelId, full);
|
||||
setScanResult((prev) => ({
|
||||
...prev,
|
||||
[channelId]: `${res.total_fetched}개 조회, ${res.new_videos}개 신규${(res as Record<string, unknown>).filtered ? `, ${(res as Record<string, unknown>).filtered}개 필터링` : ""}`,
|
||||
}));
|
||||
} catch {
|
||||
setScanResult((prev) => ({ ...prev, [channelId]: "스캔 실패" }));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{isAdmin && <div className="bg-surface rounded-lg shadow p-4 mb-6">
|
||||
<h2 className="font-semibold mb-3">채널 추가</h2>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
placeholder="YouTube Channel ID"
|
||||
value={newId}
|
||||
onChange={(e) => setNewId(e.target.value)}
|
||||
className="border rounded px-3 py-2 flex-1 text-sm bg-surface text-gray-900"
|
||||
/>
|
||||
<input
|
||||
placeholder="채널 이름"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
className="border rounded px-3 py-2 flex-1 text-sm bg-surface text-gray-900"
|
||||
/>
|
||||
<input
|
||||
placeholder="제목 필터 (선택)"
|
||||
value={newFilter}
|
||||
onChange={(e) => setNewFilter(e.target.value)}
|
||||
className="border rounded px-3 py-2 w-40 text-sm bg-surface text-gray-900"
|
||||
/>
|
||||
<button
|
||||
onClick={handleAdd}
|
||||
disabled={loading}
|
||||
className="bg-brand-600 text-white px-4 py-2 rounded text-sm hover:bg-brand-700 disabled:opacity-50"
|
||||
>
|
||||
추가
|
||||
</button>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
<div className="bg-surface rounded-lg shadow">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-brand-50 border-b border-brand-100 text-brand-800 text-sm font-semibold">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-3">채널 이름</th>
|
||||
<th className="text-left px-4 py-3">Channel ID</th>
|
||||
<th className="text-left px-4 py-3">제목 필터</th>
|
||||
<th className="text-left px-4 py-3">설명</th>
|
||||
<th className="text-left px-4 py-3">태그</th>
|
||||
<th className="text-center px-4 py-3">순서</th>
|
||||
<th className="text-right px-4 py-3">영상 수</th>
|
||||
{isAdmin && <th className="text-left px-4 py-3">액션</th>}
|
||||
<th className="text-left px-4 py-3">스캔 결과</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{channels.map((ch) => (
|
||||
<tr key={ch.id} className="border-b hover:bg-brand-50/50">
|
||||
<td className="px-4 py-3 font-medium">{ch.channel_name}</td>
|
||||
<td className="px-4 py-3 text-gray-500 font-mono text-xs">
|
||||
{ch.channel_id}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm">
|
||||
{ch.title_filter ? (
|
||||
<span className="px-2 py-0.5 bg-brand-50 text-brand-700 rounded text-xs">
|
||||
{ch.title_filter}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-400 text-xs">전체</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs">
|
||||
{editingChannel === ch.id ? (
|
||||
<input value={editDesc} onChange={(e) => setEditDesc(e.target.value)}
|
||||
className="border rounded px-2 py-1 text-xs w-32 bg-surface text-gray-900" placeholder="설명" />
|
||||
) : (
|
||||
<span className="text-gray-600 cursor-pointer" onClick={() => {
|
||||
if (!isAdmin) return;
|
||||
setEditingChannel(ch.id); setEditDesc(ch.description || ""); setEditTags(ch.tags || ""); setEditOrder(ch.sort_order ?? 99);
|
||||
}}>{ch.description || <span className="text-gray-400">-</span>}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs">
|
||||
{editingChannel === ch.id ? (
|
||||
<div className="flex gap-1">
|
||||
<input value={editTags} onChange={(e) => setEditTags(e.target.value)}
|
||||
className="border rounded px-2 py-1 text-xs w-40 bg-surface text-gray-900" placeholder="태그 (쉼표 구분)" />
|
||||
<button onClick={() => handleSaveChannel(ch.id)} className="text-brand-600 text-xs hover:underline">저장</button>
|
||||
<button onClick={() => setEditingChannel(null)} className="text-gray-400 text-xs hover:underline">취소</button>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-gray-500 cursor-pointer" onClick={() => {
|
||||
if (!isAdmin) return;
|
||||
setEditingChannel(ch.id); setEditDesc(ch.description || ""); setEditTags(ch.tags || ""); setEditOrder(ch.sort_order ?? 99);
|
||||
}}>{ch.tags ? ch.tags.split(",").map(t => t.trim()).join(", ") : <span className="text-gray-400">-</span>}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center text-xs">
|
||||
{editingChannel === ch.id ? (
|
||||
<input type="number" value={editOrder} onChange={(e) => setEditOrder(Number(e.target.value))}
|
||||
className="border rounded px-2 py-1 text-xs w-14 text-center bg-surface text-gray-900" min={1} />
|
||||
) : (
|
||||
<span className="text-gray-500">{ch.sort_order ?? 99}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right font-medium">
|
||||
{ch.video_count > 0 ? (
|
||||
<span className="px-2 py-0.5 bg-green-50 text-green-700 rounded text-xs">{ch.video_count}개</span>
|
||||
) : (
|
||||
<span className="text-gray-400 text-xs">0</span>
|
||||
)}
|
||||
</td>
|
||||
{isAdmin && <td className="px-4 py-3 flex gap-3">
|
||||
<button
|
||||
onClick={() => handleScan(ch.channel_id)}
|
||||
className="text-brand-600 hover:underline text-sm"
|
||||
>
|
||||
스캔
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleScan(ch.channel_id, true)}
|
||||
className="text-purple-600 hover:underline text-sm"
|
||||
>
|
||||
전체 스캔
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(ch.id, ch.channel_name)}
|
||||
className="text-red-500 hover:underline text-sm"
|
||||
>
|
||||
삭제
|
||||
</button>
|
||||
</td>}
|
||||
<td className="px-4 py-3 text-gray-600">
|
||||
{scanResult[ch.channel_id] || "-"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{channels.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={7} className="px-4 py-8 text-center text-gray-400">
|
||||
등록된 채널이 없습니다
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── 영상 관리 ─── */
|
||||
type VideoSortKey = "status" | "channel_name" | "title" | "published_at";
|
||||
|
||||
231
frontend/src/app/admin/_panels/DaemonPanel.tsx
Normal file
231
frontend/src/app/admin/_panels/DaemonPanel.tsx
Normal file
@@ -0,0 +1,231 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import type { DaemonConfig } from "@/lib/api";
|
||||
|
||||
// #329 — admin/page.tsx에서 추출
|
||||
export function DaemonPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
const [config, setConfig] = useState<DaemonConfig | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [running, setRunning] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<string | null>(null);
|
||||
|
||||
// Editable fields
|
||||
const [scanEnabled, setScanEnabled] = useState(false);
|
||||
const [scanInterval, setScanInterval] = useState(60);
|
||||
const [processEnabled, setProcessEnabled] = useState(false);
|
||||
const [processInterval, setProcessInterval] = useState(60);
|
||||
const [processLimit, setProcessLimit] = useState(10);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
api.getDaemonConfig().then((cfg) => {
|
||||
setConfig(cfg);
|
||||
setScanEnabled(cfg.scan_enabled);
|
||||
setScanInterval(cfg.scan_interval_min);
|
||||
setProcessEnabled(cfg.process_enabled);
|
||||
setProcessInterval(cfg.process_interval_min);
|
||||
setProcessLimit(cfg.process_limit);
|
||||
}).catch(console.error).finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
setResult(null);
|
||||
try {
|
||||
await api.updateDaemonConfig({
|
||||
scan_enabled: scanEnabled,
|
||||
scan_interval_min: scanInterval,
|
||||
process_enabled: processEnabled,
|
||||
process_interval_min: processInterval,
|
||||
process_limit: processLimit,
|
||||
});
|
||||
setResult("설정 저장 완료");
|
||||
load();
|
||||
} catch (e: unknown) {
|
||||
setResult(e instanceof Error ? e.message : "저장 실패");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRunScan = async () => {
|
||||
setRunning("scan");
|
||||
setResult(null);
|
||||
try {
|
||||
const res = await api.runDaemonScan();
|
||||
setResult(`채널 스캔 완료: 신규 ${res.new_videos}개 영상`);
|
||||
load();
|
||||
} catch (e: unknown) {
|
||||
setResult(e instanceof Error ? e.message : "스캔 실패");
|
||||
} finally {
|
||||
setRunning(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRunProcess = async () => {
|
||||
setRunning("process");
|
||||
setResult(null);
|
||||
try {
|
||||
const res = await api.runDaemonProcess(processLimit);
|
||||
setResult(`영상 처리 완료: ${res.restaurants_extracted}개 식당 추출`);
|
||||
load();
|
||||
} catch (e: unknown) {
|
||||
setResult(e instanceof Error ? e.message : "처리 실패");
|
||||
} finally {
|
||||
setRunning(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <p className="text-gray-500">로딩 중...</p>;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Schedule Config */}
|
||||
<div className="bg-surface rounded-lg shadow p-6">
|
||||
<h2 className="text-lg font-semibold mb-4">스케줄 설정</h2>
|
||||
<p className="text-xs text-gray-500 mb-4">
|
||||
데몬이 실행 중일 때, 아래 설정에 따라 자동으로 채널 스캔 및 영상 처리를 수행합니다.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Scan config */}
|
||||
<div className="border rounded-lg p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">채널 스캔</h3>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={scanEnabled}
|
||||
onChange={(e) => setScanEnabled(e.target.checked)}
|
||||
disabled={!isAdmin}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span className={`text-sm ${scanEnabled ? "text-green-600 font-medium" : "text-gray-500"}`}>
|
||||
{scanEnabled ? "활성" : "비활성"}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">주기 (분)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={scanInterval}
|
||||
onChange={(e) => setScanInterval(Number(e.target.value))}
|
||||
disabled={!isAdmin}
|
||||
min={1}
|
||||
className="border rounded px-3 py-1.5 text-sm w-32"
|
||||
/>
|
||||
</div>
|
||||
{config?.last_scan_at && (
|
||||
<p className="text-xs text-gray-400">마지막 스캔: {config.last_scan_at}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Process config */}
|
||||
<div className="border rounded-lg p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">영상 처리</h3>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={processEnabled}
|
||||
onChange={(e) => setProcessEnabled(e.target.checked)}
|
||||
disabled={!isAdmin}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span className={`text-sm ${processEnabled ? "text-green-600 font-medium" : "text-gray-500"}`}>
|
||||
{processEnabled ? "활성" : "비활성"}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">주기 (분)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={processInterval}
|
||||
onChange={(e) => setProcessInterval(Number(e.target.value))}
|
||||
disabled={!isAdmin}
|
||||
min={1}
|
||||
className="border rounded px-3 py-1.5 text-sm w-32"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">처리 건수</label>
|
||||
<input
|
||||
type="number"
|
||||
value={processLimit}
|
||||
onChange={(e) => setProcessLimit(Number(e.target.value))}
|
||||
disabled={!isAdmin}
|
||||
min={1}
|
||||
max={50}
|
||||
className="border rounded px-3 py-1.5 text-sm w-32"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{config?.last_process_at && (
|
||||
<p className="text-xs text-gray-400">마지막 처리: {config.last_process_at}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isAdmin && (
|
||||
<div className="mt-4">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="px-4 py-2 bg-brand-600 text-white text-sm rounded hover:bg-brand-700 disabled:opacity-50"
|
||||
>
|
||||
{saving ? "저장 중..." : "설정 저장"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Manual Triggers */}
|
||||
<div className="bg-surface rounded-lg shadow p-6">
|
||||
<h2 className="text-lg font-semibold mb-4">수동 실행</h2>
|
||||
<p className="text-xs text-gray-500 mb-4">
|
||||
스케줄과 관계없이 즉시 실행합니다. 처리 시간이 걸릴 수 있습니다.
|
||||
</p>
|
||||
|
||||
<div className="flex gap-3">
|
||||
{isAdmin && (
|
||||
<>
|
||||
<button
|
||||
onClick={handleRunScan}
|
||||
disabled={running !== null}
|
||||
className="px-4 py-2 bg-green-600 text-white text-sm rounded hover:bg-green-700 disabled:opacity-50"
|
||||
>
|
||||
{running === "scan" ? "스캔 중..." : "채널 스캔 실행"}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleRunProcess}
|
||||
disabled={running !== null}
|
||||
className="px-4 py-2 bg-purple-600 text-white text-sm rounded hover:bg-purple-700 disabled:opacity-50"
|
||||
>
|
||||
{running === "process" ? "처리 중..." : "영상 처리 실행"}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{result && (
|
||||
<p className={`mt-3 text-sm ${result.includes("실패") || result.includes("API") ? "text-red-600" : "text-green-600"}`}>
|
||||
{result}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Config updated_at */}
|
||||
{config?.updated_at && (
|
||||
<p className="text-xs text-gray-400 text-right">설정 수정일: {config.updated_at}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
676
frontend/src/app/admin/_panels/RestaurantsPanel.tsx
Normal file
676
frontend/src/app/admin/_panels/RestaurantsPanel.tsx
Normal file
@@ -0,0 +1,676 @@
|
||||
"use client";
|
||||
import { getAdminToken } from "@/lib/admin-utils";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Restaurant, VideoLink } from "@/lib/api";
|
||||
|
||||
// #329 — admin/page.tsx에서 추출
|
||||
export function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
const [restaurants, setRestaurants] = useState<Restaurant[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [page, setPage] = useState(0);
|
||||
const [nameSearch, setNameSearch] = useState("");
|
||||
const [selected, setSelected] = useState<Restaurant | null>(null);
|
||||
const [editForm, setEditForm] = useState<Record<string, string>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [videos, setVideos] = useState<VideoLink[]>([]);
|
||||
const [tablingSearching, setTablingSearching] = useState(false);
|
||||
const [bulkTabling, setBulkTabling] = useState(false);
|
||||
const [bulkTablingProgress, setBulkTablingProgress] = useState({ current: 0, total: 0, name: "", linked: 0, notFound: 0 });
|
||||
const [catchtableSearching, setCatchtableSearching] = useState(false);
|
||||
const [bulkCatchtable, setBulkCatchtable] = useState(false);
|
||||
const [bulkCatchtableProgress, setBulkCatchtableProgress] = useState({ current: 0, total: 0, name: "", linked: 0, notFound: 0 });
|
||||
type RestSortKey = "name" | "region" | "cuisine_type" | "price_range" | "rating" | "business_status";
|
||||
const [sortKey, setSortKey] = useState<RestSortKey>("name");
|
||||
const [sortAsc, setSortAsc] = useState(true);
|
||||
const perPage = 20;
|
||||
|
||||
const handleSort = (key: RestSortKey) => {
|
||||
if (sortKey === key) setSortAsc(!sortAsc);
|
||||
else { setSortKey(key); setSortAsc(true); }
|
||||
};
|
||||
const sortIcon = (key: RestSortKey) => sortKey !== key ? " ↕" : sortAsc ? " ↑" : " ↓";
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
api
|
||||
.getRestaurants({ limit: 500 })
|
||||
.then(setRestaurants)
|
||||
.catch(console.error)
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// #322/#323 LLM 검증 UI
|
||||
const [verifyPending, setVerifyPending] = useState<number | null>(null);
|
||||
const [verifying, setVerifying] = useState(false);
|
||||
const [verifyResult, setVerifyResult] = useState<string | null>(null);
|
||||
|
||||
const loadVerifyPending = useCallback(() => {
|
||||
api.getVerifyPending().then((r) => setVerifyPending(r.pending)).catch(() => setVerifyPending(null));
|
||||
}, []);
|
||||
useEffect(() => { loadVerifyPending(); }, [loadVerifyPending]);
|
||||
|
||||
const handleVerifyAll = async () => {
|
||||
if (!isAdmin) return;
|
||||
if (!confirm(`미검증 식당 ${verifyPending ?? "?"}건을 LLM으로 일괄 검증합니다.\n잘못 등록된 데이터/프랜차이즈를 자동으로 숨김 처리합니다.\n진행할까요?`)) return;
|
||||
setVerifying(true);
|
||||
setVerifyResult(null);
|
||||
try {
|
||||
const r = await api.verifyAll(10);
|
||||
setVerifyResult(`${r.processed}건 검증 완료`);
|
||||
loadVerifyPending();
|
||||
load();
|
||||
} catch (e) {
|
||||
setVerifyResult(`실패: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setVerifying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleHidden = async (r: Restaurant) => {
|
||||
if (!isAdmin) return;
|
||||
const becomingHidden = !r.hidden;
|
||||
const reason = becomingHidden ? (prompt("숨김 사유(선택)", "manual") ?? "manual") : "";
|
||||
try {
|
||||
await api.setRestaurantHidden(r.id, becomingHidden, reason || "manual");
|
||||
load();
|
||||
} catch (e) {
|
||||
alert(`실패: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const filtered = restaurants.filter((r) => {
|
||||
if (nameSearch && !r.name.toLowerCase().includes(nameSearch.toLowerCase())) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const sorted = [...filtered].sort((a, b) => {
|
||||
let av: string | number = a[sortKey] ?? "";
|
||||
let bv: string | number = b[sortKey] ?? "";
|
||||
if (sortKey === "rating") {
|
||||
av = a.rating ?? 0;
|
||||
bv = b.rating ?? 0;
|
||||
}
|
||||
const cmp = av < bv ? -1 : av > bv ? 1 : 0;
|
||||
return sortAsc ? cmp : -cmp;
|
||||
});
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(sorted.length / perPage));
|
||||
const paged = sorted.slice(page * perPage, (page + 1) * perPage);
|
||||
|
||||
const handleSelect = (r: Restaurant) => {
|
||||
if (selected?.id === r.id) {
|
||||
setSelected(null);
|
||||
setVideos([]);
|
||||
return;
|
||||
}
|
||||
setSelected(r);
|
||||
api.getRestaurantVideos(r.id).then(setVideos).catch(() => setVideos([]));
|
||||
setEditForm({
|
||||
name: r.name || "",
|
||||
address: r.address || "",
|
||||
region: r.region || "",
|
||||
cuisine_type: r.cuisine_type || "",
|
||||
price_range: r.price_range || "",
|
||||
phone: r.phone || "",
|
||||
website: r.website || "",
|
||||
latitude: r.latitude != null ? String(r.latitude) : "",
|
||||
longitude: r.longitude != null ? String(r.longitude) : "",
|
||||
});
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!selected) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const data: Record<string, unknown> = { ...editForm };
|
||||
if (editForm.latitude) data.latitude = parseFloat(editForm.latitude);
|
||||
else data.latitude = null;
|
||||
if (editForm.longitude) data.longitude = parseFloat(editForm.longitude);
|
||||
else data.longitude = null;
|
||||
await api.updateRestaurant(selected.id, data as Partial<Restaurant>);
|
||||
load();
|
||||
setSelected(null);
|
||||
} catch (e) {
|
||||
alert("저장 실패: " + (e instanceof Error ? e.message : String(e)));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!selected) return;
|
||||
if (!confirm(`"${selected.name}" 식당을 삭제하시겠습니까?\n연결된 영상 매핑, 리뷰, 벡터도 함께 삭제됩니다.`)) return;
|
||||
try {
|
||||
await api.deleteRestaurant(selected.id);
|
||||
setSelected(null);
|
||||
load();
|
||||
} catch {
|
||||
alert("삭제 실패");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="flex">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="식당 이름 검색..."
|
||||
value={nameSearch}
|
||||
onChange={(e) => { setNameSearch(e.target.value); setPage(0); }}
|
||||
onKeyDown={(e) => e.key === "Escape" && setNameSearch("")}
|
||||
className="border border-r-0 rounded-l px-3 py-2 text-sm w-48 bg-surface text-gray-900"
|
||||
/>
|
||||
{nameSearch ? (
|
||||
<button
|
||||
onClick={() => { setNameSearch(""); setPage(0); }}
|
||||
className="border rounded-r px-2 py-2 text-sm text-gray-400 hover:text-gray-600 hover:bg-gray-100"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => load()}
|
||||
className="border rounded-r px-2 py-2 text-sm text-gray-400 hover:text-gray-600 hover:bg-gray-100"
|
||||
title="새로고침"
|
||||
>
|
||||
↻
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{isAdmin && (<>
|
||||
{/* #322/#323 — LLM 검증 */}
|
||||
<div className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
|
||||
<span>미검증 {verifyPending ?? "?"}건</span>
|
||||
<button
|
||||
onClick={handleVerifyAll}
|
||||
disabled={verifying || verifyPending === 0}
|
||||
className="px-3 py-1 text-xs rounded bg-amber-500 hover:bg-amber-600 text-white disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{verifying ? "검증 중..." : "LLM 검증"}
|
||||
</button>
|
||||
{verifyResult && <span className="text-amber-600">{verifyResult}</span>}
|
||||
</div>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const pending = await fetch(`/api/restaurants/tabling-pending`, {
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
}).then(r => r.json());
|
||||
if (pending.count === 0) { alert("테이블링 미연결 식당이 없습니다"); return; }
|
||||
if (!confirm(`테이블링 미연결 식당 ${pending.count}개를 벌크 검색합니다.\n식당당 5~15초 소요됩니다. 진행할까요?`)) return;
|
||||
setBulkTabling(true);
|
||||
setBulkTablingProgress({ current: 0, total: pending.count, name: "", linked: 0, notFound: 0 });
|
||||
try {
|
||||
const res = await fetch("/api/restaurants/bulk-tabling", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
});
|
||||
const reader = res.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^data:(.+)$/);
|
||||
if (!m) continue;
|
||||
const evt = JSON.parse(m[1]);
|
||||
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||
setBulkTablingProgress(p => ({
|
||||
...p, current: evt.current, total: evt.total || p.total, name: evt.name,
|
||||
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||
}));
|
||||
} else if (evt.type === "complete") {
|
||||
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) { alert("벌크 테이블링 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||
finally { setBulkTabling(false); load(); }
|
||||
}}
|
||||
disabled={bulkTabling}
|
||||
className="px-3 py-1.5 text-xs bg-brand-500 text-white rounded hover:bg-brand-600 disabled:opacity-50"
|
||||
>
|
||||
{bulkTabling ? `테이블링 검색 중 (${bulkTablingProgress.current}/${bulkTablingProgress.total})` : "벌크 테이블링 연결"}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (!confirm("테이블링 매핑을 전부 초기화하시겠습니까?")) return;
|
||||
try {
|
||||
await fetch("/api/restaurants/reset-tabling", {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
});
|
||||
alert("테이블링 매핑 초기화 완료");
|
||||
load();
|
||||
} catch (e) { alert("실패: " + e); }
|
||||
}}
|
||||
className="px-3 py-1.5 text-xs bg-red-50 text-red-600 border border-red-200 rounded hover:bg-red-100"
|
||||
>
|
||||
테이블링 초기화
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (!confirm("캐치테이블 매핑을 전부 초기화하시겠습니까?")) return;
|
||||
try {
|
||||
await fetch("/api/restaurants/reset-catchtable", {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
});
|
||||
alert("캐치테이블 매핑 초기화 완료");
|
||||
load();
|
||||
} catch (e) { alert("실패: " + e); }
|
||||
}}
|
||||
className="px-3 py-1.5 text-xs bg-red-50 text-red-600 border border-red-200 rounded hover:bg-red-100"
|
||||
>
|
||||
캐치테이블 초기화
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const pending = await fetch(`/api/restaurants/catchtable-pending`, {
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
}).then(r => r.json());
|
||||
if (pending.count === 0) { alert("캐치테이블 미연결 식당이 없습니다"); return; }
|
||||
if (!confirm(`캐치테이블 미연결 식당 ${pending.count}개를 벌크 검색합니다.\n식당당 5~15초 소요됩니다. 진행할까요?`)) return;
|
||||
setBulkCatchtable(true);
|
||||
setBulkCatchtableProgress({ current: 0, total: pending.count, name: "", linked: 0, notFound: 0 });
|
||||
try {
|
||||
const res = await fetch("/api/restaurants/bulk-catchtable", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
});
|
||||
const reader = res.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^data:(.+)$/);
|
||||
if (!m) continue;
|
||||
const evt = JSON.parse(m[1]);
|
||||
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||
setBulkCatchtableProgress(p => ({
|
||||
...p, current: evt.current, total: evt.total || p.total, name: evt.name,
|
||||
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||
}));
|
||||
} else if (evt.type === "complete") {
|
||||
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) { alert("벌크 캐치테이블 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||
finally { setBulkCatchtable(false); load(); }
|
||||
}}
|
||||
disabled={bulkCatchtable}
|
||||
className="px-3 py-1.5 text-xs bg-violet-500 text-white rounded hover:bg-violet-600 disabled:opacity-50"
|
||||
>
|
||||
{bulkCatchtable ? `캐치테이블 검색 중 (${bulkCatchtableProgress.current}/${bulkCatchtableProgress.total})` : "벌크 캐치테이블 연결"}
|
||||
</button>
|
||||
</>)}
|
||||
<span className="text-sm text-gray-400 ml-auto">
|
||||
{nameSearch ? `${sorted.length} / ` : ""}총 {restaurants.length}개 식당
|
||||
</span>
|
||||
</div>
|
||||
{bulkTabling && bulkTablingProgress.name && (
|
||||
<div className="bg-brand-50 rounded p-3 mb-4 text-sm">
|
||||
<div className="flex justify-between mb-1">
|
||||
<span>{bulkTablingProgress.current}/{bulkTablingProgress.total} - {bulkTablingProgress.name}</span>
|
||||
<span className="text-xs text-gray-500">연결: {bulkTablingProgress.linked} / 미발견: {bulkTablingProgress.notFound}</span>
|
||||
</div>
|
||||
<div className="w-full bg-brand-200 rounded-full h-1.5">
|
||||
<div className="bg-brand-500 h-1.5 rounded-full transition-all" style={{ width: `${(bulkTablingProgress.current / bulkTablingProgress.total) * 100}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{bulkCatchtable && bulkCatchtableProgress.name && (
|
||||
<div className="bg-violet-50 rounded p-3 mb-4 text-sm">
|
||||
<div className="flex justify-between mb-1">
|
||||
<span>{bulkCatchtableProgress.current}/{bulkCatchtableProgress.total} - {bulkCatchtableProgress.name}</span>
|
||||
<span className="text-xs text-gray-500">연결: {bulkCatchtableProgress.linked} / 미발견: {bulkCatchtableProgress.notFound}</span>
|
||||
</div>
|
||||
<div className="w-full bg-violet-200 rounded-full h-1.5">
|
||||
<div className="bg-violet-500 h-1.5 rounded-full transition-all" style={{ width: `${(bulkCatchtableProgress.current / bulkCatchtableProgress.total) * 100}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-surface rounded-lg shadow overflow-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-brand-50 border-b border-brand-100 text-brand-800 text-sm font-semibold">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-3 cursor-pointer select-none hover:bg-gray-100" onClick={() => handleSort("name")}>이름{sortIcon("name")}</th>
|
||||
<th className="text-left px-4 py-3 cursor-pointer select-none hover:bg-gray-100" onClick={() => handleSort("region")}>지역{sortIcon("region")}</th>
|
||||
<th className="text-left px-4 py-3 cursor-pointer select-none hover:bg-gray-100" onClick={() => handleSort("cuisine_type")}>음식 종류{sortIcon("cuisine_type")}</th>
|
||||
<th className="text-left px-4 py-3 cursor-pointer select-none hover:bg-gray-100" onClick={() => handleSort("price_range")}>가격대{sortIcon("price_range")}</th>
|
||||
<th className="text-center px-4 py-3 cursor-pointer select-none hover:bg-gray-100" onClick={() => handleSort("rating")}>평점{sortIcon("rating")}</th>
|
||||
<th className="text-center px-4 py-3 cursor-pointer select-none hover:bg-gray-100" onClick={() => handleSort("business_status")}>상태{sortIcon("business_status")}</th>
|
||||
<th className="text-center px-4 py-3">검증</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{paged.map((r) => (
|
||||
<tr
|
||||
key={r.id}
|
||||
onClick={() => handleSelect(r)}
|
||||
className={`border-b cursor-pointer hover:bg-brand-50/50 ${selected?.id === r.id ? "bg-brand-50" : ""}`}
|
||||
>
|
||||
<td className="px-4 py-3 font-medium">{r.name}</td>
|
||||
<td className="px-4 py-3 text-gray-600 text-xs">{r.region || "-"}</td>
|
||||
<td className="px-4 py-3 text-gray-600 text-xs">{r.cuisine_type || "-"}</td>
|
||||
<td className="px-4 py-3 text-gray-600 text-xs">{r.price_range || "-"}</td>
|
||||
<td className="px-4 py-3 text-center text-xs">
|
||||
{r.rating ? (
|
||||
<span><span className="text-yellow-500">★</span> {r.rating}</span>
|
||||
) : "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
{r.business_status === "CLOSED_PERMANENTLY" ? (
|
||||
<span className="px-1.5 py-0.5 bg-red-100 text-red-700 rounded text-[10px] font-semibold">폐업</span>
|
||||
) : r.business_status === "CLOSED_TEMPORARILY" ? (
|
||||
<span className="px-1.5 py-0.5 bg-yellow-100 text-yellow-700 rounded text-[10px] font-semibold">임시휴업</span>
|
||||
) : (
|
||||
<span className="text-xs text-gray-400">-</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{r.hidden ? (
|
||||
<button
|
||||
onClick={() => handleToggleHidden(r)}
|
||||
disabled={!isAdmin}
|
||||
title={r.hidden_reason || "manual"}
|
||||
className="px-1.5 py-0.5 bg-red-100 text-red-700 rounded text-[10px] font-semibold hover:bg-red-200 disabled:opacity-50"
|
||||
>
|
||||
숨김 {r.hidden_reason ? `(${r.hidden_reason.slice(0, 12)})` : ""}
|
||||
</button>
|
||||
) : r.verified_at ? (
|
||||
<button
|
||||
onClick={() => handleToggleHidden(r)}
|
||||
disabled={!isAdmin}
|
||||
title="검증 통과 — 클릭하면 숨김"
|
||||
className="px-1.5 py-0.5 bg-green-100 text-green-700 rounded text-[10px] font-semibold hover:bg-green-200 disabled:opacity-50"
|
||||
>
|
||||
OK
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-xs text-gray-400">미검증</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!loading && filtered.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={7} className="px-4 py-8 text-center text-gray-400">
|
||||
식당 데이터가 없습니다
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2 mt-4">
|
||||
<button onClick={() => setPage(0)} disabled={page === 0} className="px-3 py-1 rounded border text-sm disabled:opacity-30 hover:bg-gray-100">«</button>
|
||||
<button onClick={() => setPage(page - 1)} disabled={page === 0} className="px-3 py-1 rounded border text-sm disabled:opacity-30 hover:bg-gray-100">‹</button>
|
||||
<span className="text-sm text-gray-600 px-2">{page + 1} / {totalPages}</span>
|
||||
<button onClick={() => setPage(page + 1)} disabled={page >= totalPages - 1} className="px-3 py-1 rounded border text-sm disabled:opacity-30 hover:bg-gray-100">›</button>
|
||||
<button onClick={() => setPage(totalPages - 1)} disabled={page >= totalPages - 1} className="px-3 py-1 rounded border text-sm disabled:opacity-30 hover:bg-gray-100">»</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 식당 상세/수정 패널 */}
|
||||
{selected && (
|
||||
<div className="mt-6 bg-surface rounded-lg shadow p-4">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-semibold text-base">{selected.name}</h3>
|
||||
<button onClick={() => setSelected(null)} className="text-gray-400 hover:text-gray-600 text-xl leading-none">x</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{[
|
||||
{ key: "name", label: "이름" },
|
||||
{ key: "address", label: "주소" },
|
||||
{ key: "region", label: "지역" },
|
||||
{ key: "cuisine_type", label: "음식 종류" },
|
||||
{ key: "price_range", label: "가격대" },
|
||||
{ key: "phone", label: "전화" },
|
||||
{ key: "website", label: "웹사이트" },
|
||||
{ key: "latitude", label: "위도" },
|
||||
{ key: "longitude", label: "경도" },
|
||||
].map(({ key, label }) => (
|
||||
<div key={key}>
|
||||
<label className="text-xs text-gray-500">{label}</label>
|
||||
<input
|
||||
value={editForm[key] || ""}
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, [key]: e.target.value }))}
|
||||
className="w-full border rounded px-2 py-1.5 text-sm bg-surface text-gray-900"
|
||||
disabled={!isAdmin}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{selected.business_status && (
|
||||
<p className="mt-3 text-xs text-gray-500">
|
||||
Google 상태: <span className="font-medium">{selected.business_status}</span>
|
||||
{selected.rating && <> / ★ {selected.rating} ({selected.rating_count?.toLocaleString()})</>}
|
||||
</p>
|
||||
)}
|
||||
{selected.google_place_id && (
|
||||
<p className="mt-1">
|
||||
<a
|
||||
href={`https://www.google.com/maps/place/?q=place_id:${selected.google_place_id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-brand-600 hover:underline text-xs"
|
||||
>
|
||||
Google Maps에서 보기
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
{/* 테이블링 연결 */}
|
||||
{isAdmin && (
|
||||
<div className="mt-4 border-t pt-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<h4 className="text-xs font-semibold text-gray-500">테이블링</h4>
|
||||
{selected.tabling_url === "NONE" ? (
|
||||
<span className="text-xs text-gray-400">검색완료-없음</span>
|
||||
) : selected.tabling_url ? (
|
||||
<a href={selected.tabling_url} target="_blank" rel="noopener noreferrer"
|
||||
className="text-brand-600 hover:underline text-xs">{selected.tabling_url}</a>
|
||||
) : (
|
||||
<span className="text-xs text-gray-400">미연결</span>
|
||||
)}
|
||||
<button
|
||||
onClick={async () => {
|
||||
setTablingSearching(true);
|
||||
try {
|
||||
const results = await api.searchTabling(selected.id);
|
||||
if (results.length === 0) {
|
||||
alert("테이블링에서 검색 결과가 없습니다");
|
||||
} else {
|
||||
const best = results[0];
|
||||
if (confirm(`"${best.title}"\n${best.url}\n\n이 테이블링 페이지를 연결할까요?`)) {
|
||||
await api.setTablingUrl(selected.id, best.url);
|
||||
setSelected({ ...selected, tabling_url: best.url });
|
||||
load();
|
||||
}
|
||||
}
|
||||
} catch (e) { alert("검색 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||
finally { setTablingSearching(false); }
|
||||
}}
|
||||
disabled={tablingSearching}
|
||||
className="px-2 py-0.5 text-[11px] bg-brand-500 text-white rounded hover:bg-brand-600 disabled:opacity-50"
|
||||
>
|
||||
{tablingSearching ? "검색 중..." : "테이블링 검색"}
|
||||
</button>
|
||||
{selected.tabling_url && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
await api.setTablingUrl(selected.id, "");
|
||||
setSelected({ ...selected, tabling_url: null });
|
||||
load();
|
||||
}}
|
||||
className="px-2 py-0.5 text-[11px] text-red-500 border border-red-200 rounded hover:bg-red-50"
|
||||
>
|
||||
연결 해제
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* 캐치테이블 연결 */}
|
||||
{isAdmin && (
|
||||
<div className="mt-4 border-t pt-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<h4 className="text-xs font-semibold text-gray-500">캐치테이블</h4>
|
||||
{selected.catchtable_url === "NONE" ? (
|
||||
<span className="text-xs text-gray-400">검색완료-없음</span>
|
||||
) : selected.catchtable_url ? (
|
||||
<a href={selected.catchtable_url} target="_blank" rel="noopener noreferrer"
|
||||
className="text-brand-600 hover:underline text-xs">{selected.catchtable_url}</a>
|
||||
) : (
|
||||
<span className="text-xs text-gray-400">미연결</span>
|
||||
)}
|
||||
<button
|
||||
onClick={async () => {
|
||||
setCatchtableSearching(true);
|
||||
try {
|
||||
const results = await api.searchCatchtable(selected.id);
|
||||
if (results.length === 0) {
|
||||
alert("캐치테이블에서 검색 결과가 없습니다");
|
||||
} else {
|
||||
const best = results[0];
|
||||
if (confirm(`"${best.title}"\n${best.url}\n\n이 캐치테이블 페이지를 연결할까요?`)) {
|
||||
await api.setCatchtableUrl(selected.id, best.url);
|
||||
setSelected({ ...selected, catchtable_url: best.url });
|
||||
load();
|
||||
}
|
||||
}
|
||||
} catch (e) { alert("검색 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||
finally { setCatchtableSearching(false); }
|
||||
}}
|
||||
disabled={catchtableSearching}
|
||||
className="px-2 py-0.5 text-[11px] bg-violet-500 text-white rounded hover:bg-violet-600 disabled:opacity-50"
|
||||
>
|
||||
{catchtableSearching ? "검색 중..." : "캐치테이블 검색"}
|
||||
</button>
|
||||
{selected.catchtable_url && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
await api.setCatchtableUrl(selected.id, "");
|
||||
setSelected({ ...selected, catchtable_url: null });
|
||||
load();
|
||||
}}
|
||||
className="px-2 py-0.5 text-[11px] text-red-500 border border-red-200 rounded hover:bg-red-50"
|
||||
>
|
||||
연결 해제
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{videos.length > 0 && (
|
||||
<div className="mt-4 border-t pt-3">
|
||||
<h4 className="text-xs font-semibold text-gray-500 mb-2">연결된 영상 ({videos.length})</h4>
|
||||
<div className="space-y-1.5 max-h-32 overflow-y-auto">
|
||||
{videos.map((v) => (
|
||||
<div key={v.video_id} className="flex items-center gap-2 text-xs">
|
||||
<span className="px-1.5 py-0.5 bg-red-50 text-red-600 rounded text-[10px] font-medium shrink-0">
|
||||
{v.channel_name}
|
||||
</span>
|
||||
<a href={v.url} target="_blank" rel="noopener noreferrer" className="text-brand-600 hover:underline truncate">
|
||||
{v.title}
|
||||
</a>
|
||||
<span className="text-gray-400 shrink-0">{v.published_at?.slice(0, 10)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 mt-4">
|
||||
{isAdmin && <button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="px-4 py-2 text-sm bg-brand-600 text-white rounded hover:bg-brand-700 disabled:opacity-50"
|
||||
>
|
||||
{saving ? "저장 중..." : "저장"}
|
||||
</button>}
|
||||
<button
|
||||
onClick={() => setSelected(null)}
|
||||
className="px-4 py-2 text-sm border rounded text-gray-600 hover:bg-gray-100"
|
||||
>
|
||||
{isAdmin ? "취소" : "닫기"}
|
||||
</button>
|
||||
{isAdmin && <button
|
||||
onClick={handleDelete}
|
||||
className="px-4 py-2 text-sm text-red-500 border border-red-200 rounded hover:bg-red-50 ml-auto"
|
||||
>
|
||||
식당 삭제
|
||||
</button>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/* ─── 유저 관리 ─── */
|
||||
interface AdminUser {
|
||||
id: string;
|
||||
email: string | null;
|
||||
nickname: string | null;
|
||||
avatar_url: string | null;
|
||||
is_admin: boolean;
|
||||
provider: string | null;
|
||||
created_at: string | null;
|
||||
favorite_count: number;
|
||||
review_count: number;
|
||||
memo_count: number;
|
||||
}
|
||||
|
||||
interface UserFavorite {
|
||||
id: string;
|
||||
name: string;
|
||||
address: string | null;
|
||||
region: string | null;
|
||||
cuisine_type: string | null;
|
||||
rating: number | null;
|
||||
business_status: string | null;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
interface UserReview {
|
||||
id: string;
|
||||
restaurant_id: string;
|
||||
rating: number;
|
||||
review_text: string | null;
|
||||
visited_at: string | null;
|
||||
created_at: string | null;
|
||||
restaurant_name: string | null;
|
||||
}
|
||||
|
||||
interface UserMemo {
|
||||
id: string;
|
||||
restaurant_id: string;
|
||||
rating: number | null;
|
||||
memo_text: string | null;
|
||||
visited_at: string | null;
|
||||
created_at: string;
|
||||
restaurant_name: string | null;
|
||||
}
|
||||
|
||||
383
frontend/src/app/admin/_panels/UsersPanel.tsx
Normal file
383
frontend/src/app/admin/_panels/UsersPanel.tsx
Normal file
@@ -0,0 +1,383 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
// #329 — admin/page.tsx에서 추출
|
||||
interface AdminUser {
|
||||
id: string;
|
||||
email: string | null;
|
||||
nickname: string | null;
|
||||
avatar_url: string | null;
|
||||
is_admin: boolean;
|
||||
provider: string | null;
|
||||
created_at: string | null;
|
||||
favorite_count: number;
|
||||
review_count: number;
|
||||
memo_count: number;
|
||||
}
|
||||
|
||||
interface UserFavorite {
|
||||
id: string;
|
||||
name: string;
|
||||
address: string | null;
|
||||
region: string | null;
|
||||
cuisine_type: string | null;
|
||||
rating: number | null;
|
||||
business_status: string | null;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
interface UserReview {
|
||||
id: string;
|
||||
restaurant_id: string;
|
||||
rating: number;
|
||||
review_text: string | null;
|
||||
visited_at: string | null;
|
||||
created_at: string | null;
|
||||
restaurant_name: string | null;
|
||||
}
|
||||
|
||||
interface UserMemo {
|
||||
id: string;
|
||||
restaurant_id: string;
|
||||
rating: number | null;
|
||||
memo_text: string | null;
|
||||
visited_at: string | null;
|
||||
created_at: string;
|
||||
restaurant_name: string | null;
|
||||
}
|
||||
|
||||
export function UsersPanel() {
|
||||
const [users, setUsers] = useState<AdminUser[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(0);
|
||||
const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
|
||||
const [favorites, setFavorites] = useState<UserFavorite[]>([]);
|
||||
const [reviews, setReviews] = useState<UserReview[]>([]);
|
||||
const [memos, setMemos] = useState<UserMemo[]>([]);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const perPage = 20;
|
||||
|
||||
const loadUsers = useCallback(async (p: number) => {
|
||||
try {
|
||||
const res = await api.getAdminUsers({ limit: perPage, offset: p * perPage });
|
||||
setUsers(res.users);
|
||||
setTotal(res.total);
|
||||
} catch (e) {
|
||||
console.error("Failed to load users:", e);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadUsers(page);
|
||||
}, [page, loadUsers]);
|
||||
|
||||
const handleSelectUser = async (u: AdminUser) => {
|
||||
if (selectedUser?.id === u.id) {
|
||||
setSelectedUser(null);
|
||||
setFavorites([]);
|
||||
setReviews([]);
|
||||
setMemos([]);
|
||||
return;
|
||||
}
|
||||
setSelectedUser(u);
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
const [favs, revs, mems] = await Promise.all([
|
||||
api.getAdminUserFavorites(u.id),
|
||||
api.getAdminUserReviews(u.id),
|
||||
api.getAdminUserMemos(u.id),
|
||||
]);
|
||||
setFavorites(favs);
|
||||
setReviews(revs);
|
||||
setMemos(mems);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-bold">유저 관리 ({total}명)</h2>
|
||||
|
||||
{/* Users Table */}
|
||||
<div className="bg-surface rounded-lg shadow overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-brand-50 border-b border-brand-100 text-brand-800 text-sm font-semibold">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-2">사용자</th>
|
||||
<th className="text-left px-4 py-2">이메일</th>
|
||||
<th className="text-center px-4 py-2">관리자</th>
|
||||
<th className="text-center px-4 py-2">찜</th>
|
||||
<th className="text-center px-4 py-2">리뷰</th>
|
||||
<th className="text-center px-4 py-2">메모</th>
|
||||
<th className="text-left px-4 py-2">가입일</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => (
|
||||
<tr
|
||||
key={u.id}
|
||||
onClick={() => handleSelectUser(u)}
|
||||
className={`border-t cursor-pointer transition-colors ${
|
||||
selectedUser?.id === u.id
|
||||
? "bg-brand-50"
|
||||
: "hover:bg-brand-50/50"
|
||||
}`}
|
||||
>
|
||||
<td className="px-4 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{u.avatar_url ? (
|
||||
<img
|
||||
src={u.avatar_url}
|
||||
alt=""
|
||||
className="w-7 h-7 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-7 h-7 rounded-full bg-gray-200 flex items-center justify-center text-xs font-semibold text-gray-500">
|
||||
{(u.nickname || u.email || "?").charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<span className="font-medium">
|
||||
{u.nickname || "-"}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-gray-500">{u.email || "-"}</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
<button
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
try {
|
||||
await api.updateAdminUserAdmin(u.id, !u.is_admin);
|
||||
setUsers((prev) => prev.map((x) => x.id === u.id ? { ...x, is_admin: !u.is_admin } : x));
|
||||
} catch (err) {
|
||||
console.error("Failed to update admin:", err);
|
||||
alert("관리자 권한 변경에 실패했습니다.");
|
||||
}
|
||||
}}
|
||||
className={`inline-block px-2 py-0.5 rounded-full text-xs font-medium transition-colors ${
|
||||
u.is_admin
|
||||
? "bg-green-100 text-green-700 hover:bg-green-200"
|
||||
: "bg-gray-100 text-gray-400 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
{u.is_admin ? "ON" : "OFF"}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
{u.favorite_count > 0 ? (
|
||||
<span className="inline-block px-2 py-0.5 bg-red-50 text-red-600 rounded-full text-xs font-medium">
|
||||
{u.favorite_count}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-300">0</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
{u.review_count > 0 ? (
|
||||
<span className="inline-block px-2 py-0.5 bg-brand-50 text-brand-600 rounded-full text-xs font-medium">
|
||||
{u.review_count}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-300">0</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
{u.memo_count > 0 ? (
|
||||
<span className="inline-block px-2 py-0.5 bg-purple-50 text-purple-600 rounded-full text-xs font-medium">
|
||||
{u.memo_count}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-300">0</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-gray-400 text-xs">
|
||||
{u.created_at?.slice(0, 10) || "-"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<button
|
||||
onClick={() => setPage((p) => Math.max(0, p - 1))}
|
||||
disabled={page === 0}
|
||||
className="px-3 py-1 text-sm border rounded disabled:opacity-30"
|
||||
>
|
||||
이전
|
||||
</button>
|
||||
<span className="text-sm text-gray-600">
|
||||
{page + 1} / {totalPages}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
|
||||
disabled={page >= totalPages - 1}
|
||||
className="px-3 py-1 text-sm border rounded disabled:opacity-30"
|
||||
>
|
||||
다음
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Selected User Detail */}
|
||||
{selectedUser && (
|
||||
<div className="bg-surface rounded-lg shadow p-5 space-y-4">
|
||||
<div className="flex items-center gap-3 pb-3 border-b">
|
||||
{selectedUser.avatar_url ? (
|
||||
<img
|
||||
src={selectedUser.avatar_url}
|
||||
alt=""
|
||||
className="w-12 h-12 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center text-lg font-semibold text-gray-500">
|
||||
{(selectedUser.nickname || selectedUser.email || "?").charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<div className="font-bold">{selectedUser.nickname || "-"}</div>
|
||||
<div className="text-sm text-gray-500">{selectedUser.email || "-"}</div>
|
||||
<div className="text-xs text-gray-400">
|
||||
{selectedUser.provider} · 가입: {selectedUser.created_at?.slice(0, 10)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{detailLoading ? (
|
||||
<p className="text-sm text-gray-500">로딩 중...</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
{/* Favorites */}
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm mb-2 text-red-600">
|
||||
찜한 식당 ({favorites.length})
|
||||
</h3>
|
||||
{favorites.length === 0 ? (
|
||||
<p className="text-xs text-gray-400">찜한 식당이 없습니다.</p>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-64 overflow-y-auto">
|
||||
{favorites.map((f) => (
|
||||
<div
|
||||
key={f.id}
|
||||
className="flex items-center justify-between border rounded px-3 py-2 text-xs"
|
||||
>
|
||||
<div>
|
||||
<span className="font-medium">{f.name}</span>
|
||||
{f.region && (
|
||||
<span className="ml-1.5 text-gray-400">{f.region}</span>
|
||||
)}
|
||||
{f.cuisine_type && (
|
||||
<span className="ml-1.5 text-gray-400">· {f.cuisine_type}</span>
|
||||
)}
|
||||
{f.business_status === "CLOSED_PERMANENTLY" && (
|
||||
<span className="ml-1.5 px-1 bg-red-100 text-red-600 rounded text-[10px]">
|
||||
폐업
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{f.rating && (
|
||||
<span className="text-yellow-500 shrink-0">
|
||||
★ {f.rating}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Reviews */}
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm mb-2 text-brand-600">
|
||||
작성한 리뷰 ({reviews.length})
|
||||
</h3>
|
||||
{reviews.length === 0 ? (
|
||||
<p className="text-xs text-gray-400">작성한 리뷰가 없습니다.</p>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-64 overflow-y-auto">
|
||||
{reviews.map((r) => (
|
||||
<div
|
||||
key={r.id}
|
||||
className="border rounded px-3 py-2 text-xs space-y-0.5"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">
|
||||
{r.restaurant_name || "알 수 없음"}
|
||||
</span>
|
||||
<span className="text-yellow-500 shrink-0">
|
||||
{"★".repeat(Math.round(r.rating))} {r.rating}
|
||||
</span>
|
||||
</div>
|
||||
{r.review_text && (
|
||||
<p className="text-gray-600 line-clamp-2">
|
||||
{r.review_text}
|
||||
</p>
|
||||
)}
|
||||
<div className="text-gray-400 text-[10px]">
|
||||
{r.visited_at && `방문: ${r.visited_at} · `}
|
||||
{r.created_at?.slice(0, 10)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Memos */}
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm mb-2 text-purple-600">
|
||||
작성한 메모 ({memos.length})
|
||||
</h3>
|
||||
{memos.length === 0 ? (
|
||||
<p className="text-xs text-gray-400">작성한 메모가 없습니다.</p>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-64 overflow-y-auto">
|
||||
{memos.map((m) => (
|
||||
<div
|
||||
key={m.id}
|
||||
className="border border-purple-200 rounded px-3 py-2 text-xs space-y-0.5 bg-purple-50/30"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">
|
||||
{m.restaurant_name || "알 수 없음"}
|
||||
</span>
|
||||
{m.rating && (
|
||||
<span className="text-yellow-500 shrink-0">
|
||||
{"★".repeat(Math.round(m.rating))} {m.rating}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{m.memo_text && (
|
||||
<p className="text-gray-600 line-clamp-2">
|
||||
{m.memo_text}
|
||||
</p>
|
||||
)}
|
||||
<div className="text-gray-400 text-[10px]">
|
||||
{m.visited_at && `방문: ${m.visited_at} · `}
|
||||
{m.created_at?.slice(0, 10)}
|
||||
<span className="ml-1 text-purple-400">비공개</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── 데몬 설정 ─── */
|
||||
1283
frontend/src/app/admin/_panels/VideosPanel.tsx
Normal file
1283
frontend/src/app/admin/_panels/VideosPanel.tsx
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,7 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { GoogleLogin } from "@react-oauth/google";
|
||||
import LoginMenu from "@/components/LoginMenu";
|
||||
import LanguageSwitcher from "@/components/LanguageSwitcher";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Restaurant, Channel, Review, Memo } from "@/lib/api";
|
||||
import { useAuth } from "@/lib/auth-context";
|
||||
@@ -719,6 +720,8 @@ export default function Home() {
|
||||
</>
|
||||
)}
|
||||
<div className="flex-1" />
|
||||
{/* #352 — Language switcher */}
|
||||
<LanguageSwitcher />
|
||||
{/* Desktop user area */}
|
||||
{authLoading ? null : user ? (
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { GoogleOAuthProvider } from "@react-oauth/google";
|
||||
import { AuthProvider } from "@/lib/auth-context";
|
||||
import { LocaleProvider } from "@/i18n/LocaleProvider";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || "";
|
||||
@@ -9,7 +10,9 @@ const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || "";
|
||||
export function Providers({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
<LocaleProvider>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</LocaleProvider>
|
||||
</GoogleOAuthProvider>
|
||||
);
|
||||
}
|
||||
|
||||
57
frontend/src/components/LanguageSwitcher.tsx
Normal file
57
frontend/src/components/LanguageSwitcher.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useLocale } from "@/i18n/LocaleProvider";
|
||||
import { LOCALES, LOCALE_LABELS } from "@/i18n/config";
|
||||
|
||||
// #352 — 헤더용 언어 전환 드롭다운. 44px 터치 영역 + ARIA listbox 패턴.
|
||||
export default function LanguageSwitcher() {
|
||||
const { locale, setLocale } = useLocale();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-label="언어 선택 / Select language"
|
||||
className="min-h-[44px] min-w-[44px] px-2 py-1.5 flex items-center gap-1 text-sm rounded-lg hover:bg-brand-50 touch-manipulation"
|
||||
>
|
||||
<span aria-hidden="true">{LOCALE_LABELS[locale].flag}</span>
|
||||
<span className="text-xs text-gray-500 uppercase">{locale}</span>
|
||||
</button>
|
||||
{open && (
|
||||
<>
|
||||
<button
|
||||
aria-hidden="true"
|
||||
tabIndex={-1}
|
||||
className="fixed inset-0 z-40 cursor-default"
|
||||
onClick={() => setOpen(false)}
|
||||
/>
|
||||
<ul
|
||||
role="listbox"
|
||||
aria-label="언어 목록"
|
||||
className="absolute right-0 mt-1 bg-surface rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 z-50 min-w-[160px]"
|
||||
>
|
||||
{LOCALES.map((l) => (
|
||||
<li key={l}>
|
||||
<button
|
||||
role="option"
|
||||
aria-selected={l === locale}
|
||||
onClick={() => { setLocale(l); setOpen(false); }}
|
||||
className={`w-full text-left px-3 py-2 text-sm flex items-center gap-2 hover:bg-brand-50 ${
|
||||
l === locale ? "font-semibold text-brand-700" : "text-gray-700"
|
||||
}`}
|
||||
>
|
||||
<span aria-hidden="true">{LOCALE_LABELS[l].flag}</span>
|
||||
<span>{LOCALE_LABELS[l].native}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
56
frontend/src/i18n/LocaleProvider.tsx
Normal file
56
frontend/src/i18n/LocaleProvider.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
"use client";
|
||||
|
||||
import { NextIntlClientProvider } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { DEFAULT_LOCALE, LOCALE_STORAGE_KEY, Locale, detectBrowserLocale, isLocale } from "./config";
|
||||
|
||||
// #352 — 메시지 파일을 정적 import (Tree-shaking 가능, 클라이언트 번들에 4언어 모두 포함되지만
|
||||
// 30개 키 수준이라 부담 미미. 키가 늘어나면 동적 import로 분할 검토)
|
||||
import ko from "@/messages/ko.json";
|
||||
import en from "@/messages/en.json";
|
||||
import ja from "@/messages/ja.json";
|
||||
import es from "@/messages/es.json";
|
||||
|
||||
const MESSAGES: Record<Locale, typeof ko> = { ko, en, ja, es };
|
||||
|
||||
interface LocaleContextValue {
|
||||
locale: Locale;
|
||||
setLocale: (l: Locale) => void;
|
||||
}
|
||||
|
||||
import { createContext, useContext } from "react";
|
||||
const LocaleContext = createContext<LocaleContextValue | null>(null);
|
||||
|
||||
export function useLocale() {
|
||||
const ctx = useContext(LocaleContext);
|
||||
if (!ctx) throw new Error("useLocale must be used within LocaleProvider");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function LocaleProvider({ children }: { children: React.ReactNode }) {
|
||||
// SSR 단계는 기본 로케일로 시작 (hydration mismatch 방지)
|
||||
const [locale, setLocaleState] = useState<Locale>(DEFAULT_LOCALE);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
const saved = localStorage.getItem(LOCALE_STORAGE_KEY);
|
||||
const initial: Locale = isLocale(saved) ? saved : detectBrowserLocale();
|
||||
if (initial !== locale) setLocaleState(initial);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const setLocale = (l: Locale) => {
|
||||
setLocaleState(l);
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem(LOCALE_STORAGE_KEY, l);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<LocaleContext.Provider value={{ locale, setLocale }}>
|
||||
<NextIntlClientProvider locale={locale} messages={MESSAGES[locale]}>
|
||||
{children}
|
||||
</NextIntlClientProvider>
|
||||
</LocaleContext.Provider>
|
||||
);
|
||||
}
|
||||
28
frontend/src/i18n/config.ts
Normal file
28
frontend/src/i18n/config.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
// #352 i18n 뼈대 — 로케일 목록/기본값
|
||||
|
||||
export const LOCALES = ["ko", "en", "ja", "es"] as const;
|
||||
export type Locale = (typeof LOCALES)[number];
|
||||
|
||||
export const DEFAULT_LOCALE: Locale = "ko";
|
||||
export const LOCALE_STORAGE_KEY = "tasteby_locale";
|
||||
|
||||
export const LOCALE_LABELS: Record<Locale, { flag: string; label: string; native: string }> = {
|
||||
ko: { flag: "🇰🇷", label: "Korean", native: "한국어" },
|
||||
en: { flag: "🇺🇸", label: "English", native: "English" },
|
||||
ja: { flag: "🇯🇵", label: "Japanese", native: "日本語" },
|
||||
es: { flag: "🇪🇸", label: "Spanish", native: "Español" },
|
||||
};
|
||||
|
||||
export function isLocale(value: string | null | undefined): value is Locale {
|
||||
return value != null && (LOCALES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 브라우저 언어 감지 → 지원 로케일이면 그것, 아니면 기본값.
|
||||
* SSR-safe (typeof window 체크 호출자).
|
||||
*/
|
||||
export function detectBrowserLocale(): Locale {
|
||||
if (typeof navigator === "undefined") return DEFAULT_LOCALE;
|
||||
const code = navigator.language.split("-")[0].toLowerCase();
|
||||
return isLocale(code) ? code : DEFAULT_LOCALE;
|
||||
}
|
||||
41
frontend/src/messages/en.json
Normal file
41
frontend/src/messages/en.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"header": {
|
||||
"search": "Search",
|
||||
"login": "Sign In",
|
||||
"logout": "Sign Out",
|
||||
"menu": "Menu",
|
||||
"myReviews": "My Reviews",
|
||||
"favorites": "Favorites"
|
||||
},
|
||||
"actions": {
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"edit": "Edit",
|
||||
"confirm": "OK",
|
||||
"close": "Close",
|
||||
"loading": "Loading...",
|
||||
"submit": "Submit"
|
||||
},
|
||||
"filter": {
|
||||
"title": "Filter",
|
||||
"cuisine": "Cuisine",
|
||||
"price": "Price Range",
|
||||
"region": "Region",
|
||||
"channel": "Channel",
|
||||
"reset": "Reset"
|
||||
},
|
||||
"restaurant": {
|
||||
"rating": "Rating",
|
||||
"address": "Address",
|
||||
"phone": "Phone",
|
||||
"website": "Website",
|
||||
"closed": "Permanently Closed",
|
||||
"tempClosed": "Temporarily Closed"
|
||||
},
|
||||
"review": {
|
||||
"title": "Reviews",
|
||||
"write": "Write a Review",
|
||||
"noReviews": "No reviews yet"
|
||||
}
|
||||
}
|
||||
41
frontend/src/messages/es.json
Normal file
41
frontend/src/messages/es.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"header": {
|
||||
"search": "Buscar",
|
||||
"login": "Iniciar sesión",
|
||||
"logout": "Cerrar sesión",
|
||||
"menu": "Menú",
|
||||
"myReviews": "Mis reseñas",
|
||||
"favorites": "Favoritos"
|
||||
},
|
||||
"actions": {
|
||||
"save": "Guardar",
|
||||
"cancel": "Cancelar",
|
||||
"delete": "Eliminar",
|
||||
"edit": "Editar",
|
||||
"confirm": "Aceptar",
|
||||
"close": "Cerrar",
|
||||
"loading": "Cargando...",
|
||||
"submit": "Enviar"
|
||||
},
|
||||
"filter": {
|
||||
"title": "Filtro",
|
||||
"cuisine": "Tipo de cocina",
|
||||
"price": "Rango de precios",
|
||||
"region": "Región",
|
||||
"channel": "Canal",
|
||||
"reset": "Restablecer"
|
||||
},
|
||||
"restaurant": {
|
||||
"rating": "Calificación",
|
||||
"address": "Dirección",
|
||||
"phone": "Teléfono",
|
||||
"website": "Sitio web",
|
||||
"closed": "Cerrado permanentemente",
|
||||
"tempClosed": "Cerrado temporalmente"
|
||||
},
|
||||
"review": {
|
||||
"title": "Reseñas",
|
||||
"write": "Escribir una reseña",
|
||||
"noReviews": "Aún no hay reseñas"
|
||||
}
|
||||
}
|
||||
41
frontend/src/messages/ja.json
Normal file
41
frontend/src/messages/ja.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"header": {
|
||||
"search": "検索",
|
||||
"login": "ログイン",
|
||||
"logout": "ログアウト",
|
||||
"menu": "メニュー",
|
||||
"myReviews": "マイレビュー",
|
||||
"favorites": "お気に入り"
|
||||
},
|
||||
"actions": {
|
||||
"save": "保存",
|
||||
"cancel": "キャンセル",
|
||||
"delete": "削除",
|
||||
"edit": "編集",
|
||||
"confirm": "確認",
|
||||
"close": "閉じる",
|
||||
"loading": "読み込み中...",
|
||||
"submit": "送信"
|
||||
},
|
||||
"filter": {
|
||||
"title": "フィルター",
|
||||
"cuisine": "料理ジャンル",
|
||||
"price": "価格帯",
|
||||
"region": "地域",
|
||||
"channel": "チャンネル",
|
||||
"reset": "リセット"
|
||||
},
|
||||
"restaurant": {
|
||||
"rating": "評価",
|
||||
"address": "住所",
|
||||
"phone": "電話",
|
||||
"website": "ウェブサイト",
|
||||
"closed": "閉店",
|
||||
"tempClosed": "一時休業"
|
||||
},
|
||||
"review": {
|
||||
"title": "レビュー",
|
||||
"write": "レビューを書く",
|
||||
"noReviews": "まだレビューがありません"
|
||||
}
|
||||
}
|
||||
41
frontend/src/messages/ko.json
Normal file
41
frontend/src/messages/ko.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"header": {
|
||||
"search": "검색",
|
||||
"login": "로그인",
|
||||
"logout": "로그아웃",
|
||||
"menu": "메뉴",
|
||||
"myReviews": "내 리뷰",
|
||||
"favorites": "즐겨찾기"
|
||||
},
|
||||
"actions": {
|
||||
"save": "저장",
|
||||
"cancel": "취소",
|
||||
"delete": "삭제",
|
||||
"edit": "수정",
|
||||
"confirm": "확인",
|
||||
"close": "닫기",
|
||||
"loading": "로딩 중...",
|
||||
"submit": "제출"
|
||||
},
|
||||
"filter": {
|
||||
"title": "필터",
|
||||
"cuisine": "음식 종류",
|
||||
"price": "가격대",
|
||||
"region": "지역",
|
||||
"channel": "채널",
|
||||
"reset": "초기화"
|
||||
},
|
||||
"restaurant": {
|
||||
"rating": "평점",
|
||||
"address": "주소",
|
||||
"phone": "전화",
|
||||
"website": "웹사이트",
|
||||
"closed": "폐업",
|
||||
"tempClosed": "임시휴업"
|
||||
},
|
||||
"review": {
|
||||
"title": "리뷰",
|
||||
"write": "리뷰 작성",
|
||||
"noReviews": "아직 리뷰가 없습니다"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user