"""실적 모듈 공용 가드/서비스 생성 — router.py 가 쓴다(순환 import 방지로 분리). 권한(프론트에서 메뉴를 숨기는 것과 별개로 **서버에서** 항상 검사): - 실적 대시보드/매출 업데이트/상세 조회 : 모듈 권한 `performance` (admin 은 자동) - 실적 설정(수수료·API 인증정보·연결 테스트·테스트 데이터) : 관리자(is_admin)만 """ from __future__ import annotations from typing import Any from fastapi import HTTPException, Request from fastapi.responses import HTMLResponse, RedirectResponse MODULE_KEY = "performance" MODULE_NAME = "실적" CONFIG_HELP = ( "실적 모듈이 아직 설정되지 않았습니다. " "scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 " "PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요." ) def get_store(request: Request) -> Any: return getattr(request.app.state, "performance_store", None) def key_ring(): """마스터 키 — 호출할 때마다 환경변수에서 읽는다(DB 에는 없다).""" from .security.crypto import KeyRing # noqa: WPS433 return KeyRing.from_env() def key_status() -> dict[str, Any]: """설정 화면용 — 키가 설정됐는지/버전만. 키 값은 절대 넣지 않는다.""" from .security.crypto import CryptoConfigError # noqa: WPS433 try: ring = key_ring() except CryptoConfigError as exc: return {"ok": False, "message": str(exc), "current_version": None, "versions": []} return {"ok": True, "message": "", "current_version": ring.current_version, "versions": ring.versions} def services(request: Request, store: Any): """(CredentialService, SyncService).""" from .credentials import CredentialService # noqa: WPS433 from .sync import SyncService # noqa: WPS433 creds = CredentialService(store, key_ring) return creds, SyncService(store, creds, app_state=request.app.state) def require_user(request: Request) -> dict[str, Any]: from app.main import get_current_user_record # noqa: WPS433 from app.store import has_module # noqa: WPS433 user = get_current_user_record(request) if user is None: raise HTTPException(status_code=401, detail="로그인이 필요합니다.") if not has_module(user, MODULE_KEY): raise HTTPException(status_code=403, detail=f"{MODULE_NAME} 모듈 권한이 없습니다.") return user def require_admin(request: Request) -> dict[str, Any]: from app.store import is_admin # noqa: WPS433 user = require_user(request) if not is_admin(user): raise HTTPException(status_code=403, detail="실적 설정은 관리자만 변경할 수 있습니다.") return user def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[str, Any]]: user = require_admin(request) if admin else require_user(request) st = get_store(request) if st is None: raise HTTPException(status_code=503, detail=CONFIG_HELP) return st, user def guard(request: Request, *, admin: bool = False): """페이지 진입부. tuple(store, user) 이 아니면 그대로 응답으로 돌려준다.""" from app.main import get_current_user_record, render_template # noqa: WPS433 from app.store import has_module, is_admin # noqa: WPS433 user = get_current_user_record(request) if user is None: return RedirectResponse(url="/login", status_code=303) if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)): reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다." return render_template(request, "denied.html", {"reason": reason, "user": user, "is_admin": is_admin(user)}, status_code=403) st = get_store(request) if st is None: return render_config_needed(request, user) return st, user def render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse: from app.main import build_erp_nav, render_template # noqa: WPS433 from app.store import is_admin # noqa: WPS433 return render_template( request, "denied.html", {"reason": CONFIG_HELP, "user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active=MODULE_KEY)}, status_code=503, ) def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "실적") -> dict[str, Any]: from app.main import build_erp_nav # noqa: WPS433 from app.store import is_admin # noqa: WPS433 return { "user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active=MODULE_KEY), "active_tab": active_tab, "page_title": page_title, "page_subtitle": "쇼핑몰 통합 매출", }