# News Engine Console - 구현 계획 **현재 상태**: Phase 1 Backend 완료 ✅ (2025-11-04) --- ## 🎯 Phase 1: Backend 완성 ✅ (완료) ### 1.1 데이터 모델 구현 **models/keyword.py** ```python class Keyword: _id: ObjectId keyword: str category: str # 'people', 'topics', 'companies' status: str # 'active', 'inactive' pipeline_type: str # 'rss', 'translation', 'all' priority: int # 1-10 metadata: dict created_at: datetime updated_at: datetime created_by: str ``` **models/pipeline.py** ```python class Pipeline: _id: ObjectId name: str type: str # 'rss_collector', 'translator', 'image_generator' status: str # 'running', 'stopped', 'error' config: dict schedule: str # cron expression stats: PipelineStats last_run: datetime next_run: datetime ``` **models/user.py** ```python class User: _id: ObjectId username: str (unique) email: str (unique) hashed_password: str full_name: str role: str # 'admin', 'editor', 'viewer' disabled: bool created_at: datetime last_login: datetime ``` **models/application.py** ```python class Application: _id: ObjectId name: str client_id: str (unique) client_secret: str (hashed) redirect_uris: List[str] grant_types: List[str] scopes: List[str] owner_id: str created_at: datetime ``` ### 1.2 Pydantic 스키마 작성 **schemas/keyword.py** - KeywordCreate - KeywordUpdate - KeywordResponse - KeywordList **schemas/pipeline.py** - PipelineCreate - PipelineUpdate - PipelineResponse - PipelineStats - PipelineList **schemas/user.py** - UserCreate - UserUpdate - UserResponse - UserLogin **schemas/application.py** - ApplicationCreate - ApplicationUpdate - ApplicationResponse ### 1.3 서비스 레이어 구현 **services/keyword_service.py** - `async def get_keywords(filters, pagination)` - `async def create_keyword(keyword_data)` - `async def update_keyword(keyword_id, update_data)` - `async def delete_keyword(keyword_id)` - `async def toggle_keyword_status(keyword_id)` - `async def get_keyword_stats(keyword_id)` **services/pipeline_service.py** - `async def get_pipelines()` - `async def get_pipeline_stats(pipeline_id)` - `async def start_pipeline(pipeline_id)` - `async def stop_pipeline(pipeline_id)` - `async def restart_pipeline(pipeline_id)` - `async def get_pipeline_logs(pipeline_id, limit)` - `async def update_pipeline_config(pipeline_id, config)` **services/user_service.py** - `async def create_user(user_data)` - `async def authenticate_user(username, password)` - `async def get_user_by_username(username)` - `async def update_user(user_id, update_data)` - `async def delete_user(user_id)` **services/application_service.py** - `async def create_application(app_data)` - `async def get_applications(user_id)` - `async def regenerate_client_secret(app_id)` - `async def delete_application(app_id)` **services/monitoring_service.py** - `async def get_system_health()` - `async def get_service_status()` - `async def get_database_stats()` - `async def get_redis_stats()` - `async def get_recent_logs(limit)` ### 1.4 Redis 통합 **core/redis_client.py** ```python class RedisClient: async def get(key) async def set(key, value, expire) async def delete(key) async def publish(channel, message) async def subscribe(channel, callback) ``` **사용 케이스**: - 파이프라인 상태 캐싱 - 실시간 통계 업데이트 (Pub/Sub) - 사용자 세션 관리 - Rate limiting ### 1.5 API 엔드포인트 완성 ✅ **총 37개 엔드포인트 구현 완료** **keywords.py** (8 endpoints) ✅ - [x] GET / - 목록 조회 (필터링, 페이지네이션, 정렬 포함) - [x] POST / - 키워드 생성 - [x] GET /{id} - 상세 조회 - [x] PUT /{id} - 키워드 수정 - [x] DELETE /{id} - 키워드 삭제 - [x] POST /{id}/toggle - 활성화/비활성화 - [x] GET /{id}/stats - 키워드 통계 - [x] POST /bulk - 벌크 생성 **pipelines.py** (11 endpoints) ✅ - [x] GET / - 목록 조회 (필터링, 페이지네이션 포함) - [x] POST / - 파이프라인 생성 - [x] GET /{id} - 상세 조회 - [x] PUT /{id} - 파이프라인 수정 - [x] DELETE /{id} - 파이프라인 삭제 - [x] POST /{id}/start - 시작 - [x] POST /{id}/stop - 중지 - [x] POST /{id}/restart - 재시작 - [x] GET /{id}/logs - 로그 조회 - [x] PUT /{id}/config - 설정 업데이트 - [x] GET /types - 파이프라인 타입 목록 **users.py** (11 endpoints) ✅ - [x] GET / - 목록 조회 (역할/상태 필터링, 검색 포함) - [x] POST / - 사용자 생성 - [x] GET /me - 현재 사용자 정보 - [x] PUT /me - 현재 사용자 정보 수정 - [x] GET /{id} - 사용자 상세 조회 - [x] PUT /{id} - 사용자 수정 - [x] DELETE /{id} - 사용자 삭제 - [x] POST /login - 로그인 (JWT 발급) - [x] POST /register - 회원가입 - [x] POST /refresh - 토큰 갱신 - [x] POST /logout - 로그아웃 **applications.py** (7 endpoints) ✅ - [x] GET / - 목록 조회 - [x] POST / - Application 생성 - [x] GET /{id} - 상세 조회 - [x] PUT /{id} - 수정 - [x] DELETE /{id} - 삭제 - [x] POST /{id}/regenerate-secret - 시크릿 재생성 - [x] GET /my-apps - 내 Application 목록 **monitoring.py** (8 endpoints) ✅ - [x] GET / - 전체 모니터링 개요 - [x] GET /health - 헬스 체크 - [x] GET /system - 시스템 상태 (CPU, 메모리, 디스크) - [x] GET /services - 서비스별 상태 (MongoDB, Redis 등) - [x] GET /database - 데이터베이스 통계 - [x] GET /logs/recent - 최근 로그 - [x] GET /metrics - 메트릭 수집 - [x] GET /pipelines/activity - 파이프라인 활동 로그 ### 1.6 Pydantic v2 Migration ✅ **완료된 작업**: - [x] 모든 모델 Pydantic v2로 마이그레이션 (keyword, pipeline, user, application) - [x] ConfigDict 패턴 적용 (`model_config = ConfigDict(...)`) - [x] PyObjectId 제거, Optional[str] 사용 - [x] 서비스 레이어에서 ObjectId to string 변환 구현 - [x] fix_objectid.py 스크립트 생성 및 적용 (20 changes) ### 1.7 테스트 완료 ✅ **테스트 결과**: 100% 성공 (8/8 통과) - [x] Health Check API 테스트 - [x] Admin User 생성 테스트 - [x] Authentication/Login 테스트 - [x] Users API 완전 테스트 (11 endpoints) - [x] Keywords API 완전 테스트 (8 endpoints) - [x] Pipelines API 완전 테스트 (11 endpoints) - [x] Applications API 완전 테스트 (7 endpoints) - [x] Monitoring API 완전 테스트 (8 endpoints) **테스트 파일**: `backend/test_api.py` (700+ lines) ### 1.8 문서화 완료 ✅ - [x] API_DOCUMENTATION.md 작성 (2,058 lines, 44KB) - 37개 엔드포인트 전체 명세 - cURL 예제 - Python/Node.js/Browser 통합 예제 - 에러 처리 가이드 - 권한 매트릭스 - [x] PROGRESS.md 작성 (진도 추적 문서) - [x] README.md 업데이트 (Phase 1 완료 반영) - [x] TODO.md 업데이트 (현재 문서) --- ## 🎨 Phase 2: Frontend 구현 (다음 단계) ### 2.1 프로젝트 설정 ```bash cd frontend npm create vite@latest . -- --template react-ts npm install @mui/material @emotion/react @emotion/styled npm install @tanstack/react-query axios react-router-dom npm install recharts date-fns ``` ### 2.2 레이아웃 구현 **components/Layout/AppLayout.tsx** - Sidebar with navigation - Top bar with user info - Main content area **components/Layout/Sidebar.tsx** - Dashboard - Keywords - Pipelines - Users - Applications - Monitoring ### 2.3 페이지 구현 **pages/Dashboard.tsx** - 전체 통계 요약 - 파이프라인 상태 차트 - 최근 활동 로그 - 키워드 활용도 TOP 10 **pages/Keywords.tsx** - 키워드 목록 테이블 - 검색, 필터, 정렬 - 추가/수정/삭제 모달 - 활성화/비활성화 토글 - 키워드별 통계 차트 **pages/Pipelines.tsx** - 파이프라인 카드 그리드 - 상태별 필터 (Running, Stopped, Error) - 시작/중지 버튼 - 실시간 로그 스트림 - 통계 차트 **pages/Users.tsx** - 사용자 목록 테이블 - 역할 필터 (Admin, Editor, Viewer) - 추가/수정/삭제 모달 - 마지막 로그인 시간 **pages/Applications.tsx** - Application 카드 그리드 - Client ID/Secret 표시 - 생성/수정/삭제 - Secret 재생성 기능 **pages/Monitoring.tsx** - 시스템 헬스체크 대시보드 - 서비스별 상태 (MongoDB, Redis, etc.) - CPU/메모리 사용량 차트 - 실시간 로그 스트림 ### 2.4 API 클라이언트 **api/client.ts** ```typescript import axios from 'axios'; const apiClient = axios.create({ baseURL: import.meta.env.VITE_API_URL || 'http://localhost:8100/api/v1', headers: { 'Content-Type': 'application/json' } }); // Interceptors for auth token apiClient.interceptors.request.use(config => { const token = localStorage.getItem('access_token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); export default apiClient; ``` ### 2.5 TypeScript 타입 정의 **types/index.ts** - Keyword - Pipeline - User - Application - PipelineStats - SystemStatus --- ## 🐳 Phase 3: Docker & Kubernetes ### 3.1 Backend Dockerfile ```dockerfile FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8100 CMD ["python", "main.py"] ``` ### 3.2 Frontend Dockerfile ```dockerfile FROM node:18-alpine AS builder WORKDIR /app COPY package.json ./ RUN npm install COPY . . RUN npm run build FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html COPY nginx.conf /etc/nginx/conf.d/default.conf EXPOSE 80 ``` ### 3.3 Kubernetes 매니페스트 **k8s/namespace.yaml** ```yaml apiVersion: v1 kind: Namespace metadata: name: site11-console ``` **k8s/backend-deployment.yaml** - Deployment with 2 replicas - ConfigMap for env vars - Secret for sensitive data - Service (ClusterIP) **k8s/frontend-deployment.yaml** - Deployment with 2 replicas - Service (LoadBalancer or Ingress) --- ## 📊 Phase 4: 고급 기능 ### 4.1 실시간 업데이트 - WebSocket 연결 (파이프라인 상태) - Server-Sent Events (로그 스트림) - Redis Pub/Sub 활용 ### 4.2 알림 시스템 - 파이프라인 에러 시 알림 - 키워드 처리 완료 알림 - 이메일/Slack 통합 ### 4.3 스케줄링 - Cron 기반 파이프라인 스케줄 - 수동 실행 vs 자동 실행 - 스케줄 히스토리 ### 4.4 통계 & 분석 - 일/주/월별 처리 통계 - 키워드별 성과 분석 - 파이프라인 성능 메트릭 - CSV 다운로드 --- ## 🧪 Phase 5: 테스트 & 문서화 ### 5.1 Backend 테스트 - pytest fixtures - API endpoint tests - Integration tests - Coverage report ### 5.2 Frontend 테스트 - React Testing Library - Component tests - E2E tests (Playwright) ### 5.3 API 문서 - OpenAPI/Swagger 자동 생성 - API 예시 코드 - 에러 응답 명세 --- ## 🚀 우선순위 ### 즉시 시작 (다음 세션) 1. **MongoDB 스키마 및 인덱스 생성** - keywords, pipelines, users 컬렉션 - 인덱스 설계 2. **Pydantic 스키마 작성** - Request/Response 모델 - 유효성 검증 3. **키워드 관리 기능 완성** - KeywordService 구현 - CRUD API 완성 - 단위 테스트 4. **로그인 API 구현** - JWT 토큰 발급 - User 인증 ### 중기 목표 (1-2주) 1. 파이프라인 제어 API 완성 2. Frontend 기본 구조 3. Dashboard 페이지 4. Dockerfile 작성 ### 장기 목표 (1개월) 1. Frontend 전체 페이지 2. Kubernetes 배포 3. 실시간 모니터링 4. 알림 시스템 --- ## 📝 체크리스트 ### Phase 1: Backend ✅ 완료! (2025-11-04) - [x] 프로젝트 구조 - [x] 기본 설정 (config, database, auth) - [x] API 라우터 기본 구조 - [x] Pydantic v2 스키마 (keyword, pipeline, user, application) - [x] MongoDB 데이터 모델 (keyword, pipeline, user, application) - [x] 서비스 레이어 구현 (5개 전체) - [x] KeywordService (CRUD + stats + toggle + bulk) - [x] PipelineService (CRUD + control + logs + config) - [x] UserService (인증 + CRUD + 권한 관리) - [x] ApplicationService (OAuth2 + secret 관리) - [x] MonitoringService (시스템 헬스 + 메트릭 + 로그) - [x] Keywords API 완전 구현 (8 endpoints) - [x] Pipelines API 완전 구현 (11 endpoints) - [x] Users API 완전 구현 (11 endpoints + OAuth2 로그인) - [x] Applications API 완전 구현 (7 endpoints + secret 재생성) - [x] Monitoring API 완전 구현 (8 endpoints) - [x] **총 37개 API 엔드포인트 완전 구현** - [x] Pydantic v2 마이그레이션 (ObjectId 처리 포함) - [x] 전체 테스트 (100% 성공) - [x] API 문서화 (API_DOCUMENTATION.md, 2,058 lines) - [x] 프로젝트 문서화 (PROGRESS.md, README.md, TODO.md) - [ ] MongoDB 컬렉션 인덱스 최적화 (Phase 4로 이동) - [ ] Redis 통합 (캐싱 + Pub/Sub) (Phase 4로 이동) - [ ] 고급 에러 핸들링 (Phase 4로 이동) - [ ] 로깅 시스템 확장 (Phase 4로 이동) ### Phase 2: Frontend (다음 단계) - [ ] 프로젝트 설정 (Vite + React + TypeScript + MUI v7) - [ ] 레이아웃 및 라우팅 - [ ] 로그인 페이지 - [ ] Dashboard - [ ] Keywords 페이지 - [ ] Pipelines 페이지 - [ ] Users 페이지 - [ ] Applications 페이지 - [ ] Monitoring 페이지 ### Phase 3: DevOps - [ ] Backend Dockerfile - [ ] Frontend Dockerfile - [ ] docker-compose.yml - [ ] Kubernetes 매니페스트 - [ ] CI/CD 설정 --- ## 🎯 현재 상태 요약 ### ✅ Phase 1 완료 (2025-11-04) - **Backend API**: 37개 엔드포인트 완전 구현 (100% 완료) - **테스트**: 8개 테스트 스위트, 100% 성공 - **문서화**: API_DOCUMENTATION.md (2,058 lines), PROGRESS.md, README.md - **서버**: Port 8101에서 정상 작동 - **인증**: JWT + OAuth2 Password Flow 완전 구현 - **데이터베이스**: news_engine_console_db (MongoDB) ### 🚀 다음 단계 (Phase 2) 1. Frontend 프로젝트 설정 (Vite + React + TypeScript + MUI v7) 2. 레이아웃 및 라우팅 구조 구축 3. 로그인 페이지 구현 4. Dashboard 구현 5. Keywords/Pipelines/Users/Applications/Monitoring 페이지 구현 --- **다음 세션 시작 시**: - Phase 1 완료 확인 ✅ - Phase 2 Frontend 구현 시작 - API_DOCUMENTATION.md 참조하여 API 통합