62cc5e2778
- 실적 틱톡 탭·tiktok_ads 광고 API·테스트 삭제, 틱톡 데이터 삭제 SQL(performance_db 012) - 말레이시아 실적: 실적 라우터·화면을 /malaysia/performance 에 한 번 더 마운트, 차이는 performance/variant.py(KR·MY) 한 곳 — 저장소·권한키·주소·광고 채널·통화 - 틱톡·쇼피·라자다 그룹(쇼핑몰 + 라이브커머스 하위, 그룹 열 = 합계), 광고비 채널 3개 - 금액 RM 소수 2자리 = 센 정수 저장(입력·엑셀 scale, 화면 num/money, JS money) - malaysia_performance_db = performance_db 구조 복사 + seed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
144 lines
5.6 KiB
Python
144 lines
5.6 KiB
Python
"""실적 모듈 공용 가드/서비스 생성 — 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
|
|
|
|
from . import variant
|
|
|
|
MODULE_KEY = "performance" # 한국 실적 — 요청마다는 variant.current().module_key(말레이시아 실적 = malaysia_performance)
|
|
MODULE_NAME = "실적"
|
|
|
|
CONFIG_HELP = (
|
|
"실적 모듈이 아직 설정되지 않았습니다. "
|
|
"scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 "
|
|
"PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
|
|
)
|
|
CONFIG_HELP_MY = (
|
|
"말레이시아 실적 모듈이 아직 설정되지 않았습니다. "
|
|
"app/modules/malaysia_performance/CLAUDE.md 대로 malaysia_performance_db 를 만들고 "
|
|
"MALAYSIA_PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
|
|
)
|
|
|
|
|
|
def config_help() -> str:
|
|
return CONFIG_HELP if variant.current().is_kr else CONFIG_HELP_MY
|
|
|
|
|
|
def get_store(request: Request) -> Any:
|
|
return getattr(request.app.state, variant.current().store_attr, 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="로그인이 필요합니다.")
|
|
v = variant.current()
|
|
if not has_module(user, v.module_key):
|
|
raise HTTPException(status_code=403, detail=f"{v.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, login_redirect # noqa: WPS433
|
|
|
|
user = get_current_user_record(request)
|
|
if user is None:
|
|
return login_redirect(request)
|
|
v = variant.current()
|
|
if not has_module(user, v.module_key) or (admin and not is_admin(user)):
|
|
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{v.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=variant.current().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
|
|
|
|
v = variant.current()
|
|
if not v.is_kr and page_title:
|
|
page_title = f"말레이시아 {page_title}"
|
|
return {
|
|
"user": user,
|
|
"is_admin": is_admin(user),
|
|
"nav_items": build_erp_nav(user, active=v.module_key),
|
|
"active_tab": active_tab,
|
|
"page_title": page_title or v.module_name,
|
|
"page_subtitle": "쇼핑몰 통합 매출" if v.is_kr else "틱톡·쇼피·라자다 매출",
|
|
**variant.template_ctx(),
|
|
}
|