d9dd03ecc8
실적 설정 "보기 설정"에 표 열 너비 [자동(글자 길이)]·[수동 조절] 추가(쿠키 perf_colw). 수동이면 매출 실적·광고비 일자별 표 머리글 오른쪽 경계를 끌어 열 너비를 바꾸고, 바꾼 너비는 localStorage(perf_colw_sales/ads)에 유지. 경계 두 번 클릭 = 그 열만 자동, 설정 [조절한 너비 초기화]로 전부 되돌림. 그룹 접기·펴기 애니메이션과 연동. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1152 lines
62 KiB
Python
1152 lines
62 KiB
Python
"""실적 모듈 라우터 (prefix=/performance).
|
|
|
|
화면
|
|
GET /performance/ 대시보드(모듈 권한)
|
|
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
|
GET /performance/settings 실적 설정(관리자)
|
|
JSON API — 모듈 권한
|
|
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
|
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
|
|
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
|
|
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
|
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
|
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
|
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
|
|
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
|
|
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
|
|
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
|
|
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
|
|
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
|
|
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글·메타 머리글 클릭)
|
|
POST /performance/api/ad-sync [광고비 업데이트] — 설정된 광고 API 전부, 보는 기간(오늘까지), 진행 창 작업
|
|
(jobs kind="ads", 진행·취소·중지는 /api/sync/jobs/… 그대로), 92일 넘으면 관리자
|
|
GET /performance/api/ad-sync/current 진행 중인 광고비 업데이트(수동·자동) — 버튼이 진행 창을 다시 연다
|
|
POST /performance/api/ad-sources/{code}/sync 광고 API 채널 하나 가져오기(예전 [구글/메타 광고 불러오기], 화면 버튼은 2026-10-20 삭제)
|
|
JSON API — 관리자
|
|
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
|
|
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
|
|
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부, 직접 추가 행 이름·그룹(009)
|
|
POST /performance/api/marketplaces 쇼핑몰(수동 입력 전용)·그룹 직접 추가(009)
|
|
DELETE /performance/api/marketplaces/{code} 직접 추가 쇼핑몰·그룹 삭제(그 쇼핑몰 수동 입력·수수료도)
|
|
PUT /performance/api/marketplace-order 쇼핑몰 순서(설정 드래그 — 매출 실적 열 순서)
|
|
GET /performance/api/marketplaces/{code}/manual-days 수동 입력해 둔 날 수(삭제 확인 문구)
|
|
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
|
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
|
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
|
GET /performance/api/marketplaces/{code}/daily-check 일별 매출 비교(저장값 + 지금 API 값)
|
|
PUT /performance/api/marketplaces/{code}/credentials 저장(암호화)
|
|
POST /performance/api/marketplaces/{code}/test 연결 테스트(저장값 또는 새 입력값)
|
|
POST /performance/api/sample-data 테스트 데이터 생성/삭제
|
|
POST /performance/api/rekey 마스터 키 교체 후 재암호화
|
|
|
|
핸들러는 동기 DB 라 `def` 로 둔다(FastAPI 가 스레드풀에서 실행).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date, timedelta
|
|
from decimal import Decimal, InvalidOperation
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Body, File, Form, HTTPException, Query, Request, UploadFile
|
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
|
|
|
from app.timezone import today_kst
|
|
|
|
from . import calc, common
|
|
from .adapters.registry import all_adapters, get_adapter
|
|
|
|
router = APIRouter(prefix="/performance", tags=["performance"])
|
|
|
|
MAX_EVENT_DAYS = 31
|
|
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
|
MAX_BACKFILL_DAYS = 366
|
|
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
|
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
|
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
|
|
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
|
|
"먼저 적용해야 합니다.")
|
|
AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
|
|
"(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
|
|
AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저장하려면 performance_db 마이그레이션 007"
|
|
"(scripts/sql/performance_db_007_ad_api.sql)을 먼저 적용해야 합니다.")
|
|
|
|
|
|
def _ad_migration_help(exc: Exception) -> str:
|
|
text = str(exc)
|
|
return AD_MIGRATION_HELP_007 if "007" in text else AD_MIGRATION_HELP_006 if "006" in text else AD_MIGRATION_HELP
|
|
CUSTOM_MIGRATION_HELP = ("쇼핑몰 직접 추가·그룹을 쓰려면 performance_db 마이그레이션 009"
|
|
"(scripts/sql/performance_db_009_custom_marketplaces.sql)를 먼저 적용해야 합니다.")
|
|
MAX_MARKET_NAME = 30
|
|
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
|
"먼저 적용해야 합니다.")
|
|
|
|
|
|
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
|
if value in (None, ""):
|
|
return None
|
|
try:
|
|
return date.fromisoformat(str(value)[:10])
|
|
except ValueError:
|
|
raise HTTPException(status_code=400, detail=f"{field} 형식이 올바르지 않습니다(YYYY-MM-DD).") from None
|
|
|
|
|
|
def _holidays() -> dict[str, str]:
|
|
try:
|
|
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433 — 공휴일 표 공유(읽기 전용)
|
|
|
|
return dict(KR_HOLIDAYS)
|
|
except Exception: # noqa: BLE001
|
|
return {}
|
|
|
|
|
|
def _code_or_404(store: Any, code: str):
|
|
adapter = get_adapter(code)
|
|
if adapter is None or code not in {m["code"] for m in store.list_marketplaces()}:
|
|
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
|
|
return adapter
|
|
|
|
|
|
@router.get("/health")
|
|
def health(request: Request) -> JSONResponse:
|
|
st = common.get_store(request)
|
|
return JSONResponse({"ok": st is not None, "module": "performance",
|
|
"encryption_key": common.key_status()["ok"]})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 화면
|
|
# ════════════════════════════════════════════════════════════
|
|
@router.get("/", response_class=HTMLResponse)
|
|
def dashboard_page(
|
|
request: Request,
|
|
period: str = "month",
|
|
d: str | None = None,
|
|
from_: str | None = Query(None, alias="from"),
|
|
to: str | None = None,
|
|
m: list[str] = Query(default=[]),
|
|
metric: str = "net",
|
|
):
|
|
from app.main import render_template # noqa: WPS433
|
|
|
|
g = common.guard(request)
|
|
if not isinstance(g, tuple):
|
|
return g
|
|
store, user = g
|
|
from .dashboard import build_dashboard # noqa: WPS433
|
|
|
|
today = today_kst()
|
|
anchor = _parse_date(d) or today
|
|
creds, _ = common.services(request, store)
|
|
ctx = build_dashboard(
|
|
store, kind=period, anchor=anchor, today=today,
|
|
custom_from=_parse_date(from_), custom_to=_parse_date(to), selected=m,
|
|
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
|
|
)
|
|
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
|
|
ctx["auto_sync"] = _auto_sync_ctx(store, "sales")
|
|
ctx["update_watch"] = _update_watch("sales", user)
|
|
_unit_ctx(request, ctx)
|
|
_colw_ctx(request, ctx)
|
|
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
|
|
|
|
|
def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
|
|
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. kind = sales(매출 실적) / ads(광고비),
|
|
일정은 실적 설정 "자동 업데이트"(2026-10-26, auto_sync.load_schedules). 회차가 지나면 화면이 같은 규칙
|
|
(schedule: 간격·요일·시작/끝, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정.
|
|
자동 업데이트가 꺼져 있거나(env·일정) 회차가 없으면 None."""
|
|
from app.timezone import now_kst # noqa: WPS433
|
|
|
|
from . import auto_sync # noqa: WPS433
|
|
|
|
if not auto_sync.enabled():
|
|
return None
|
|
try:
|
|
sched = auto_sync.load_schedules(store)[0][kind]
|
|
except Exception: # noqa: BLE001 — DB 오류: 카운트다운만 숨김
|
|
return None
|
|
now = now_kst()
|
|
nxt = auto_sync.next_slot(now, sched)
|
|
if nxt is None:
|
|
return None
|
|
return {"next_at": nxt.isoformat(), "now": now.isoformat(timespec="milliseconds"), "schedule": sched,
|
|
"label": auto_sync.describe(sched)}
|
|
|
|
|
|
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]:
|
|
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
|
|
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다."""
|
|
from . import jobs # noqa: WPS433
|
|
|
|
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
|
return {"kind": kind, "seen": job.id if job else ""}
|
|
|
|
|
|
@router.get("/api/update-status")
|
|
def api_update_status(request: Request, kind: str = "sales") -> JSONResponse:
|
|
"""지금 그 종류 업데이트가 도는지 · 마지막으로 끝난 업데이트(보는 사람이 시작한 것 제외) — 화면이 20초마다 본다.
|
|
메모리의 진행 작업만 보고 DB 는 안 읽는다."""
|
|
from . import jobs # noqa: WPS433
|
|
|
|
_, user = common.require_store(request)
|
|
if kind not in jobs.KINDS:
|
|
raise HTTPException(status_code=404, detail="알 수 없는 업데이트 종류입니다.")
|
|
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
|
return JSONResponse({"kind": kind, "running": jobs.running_job(kind) is not None, "done": job.id if job else "",
|
|
"user": job.user if job else ""})
|
|
|
|
|
|
def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None:
|
|
"""매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다."""
|
|
from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433
|
|
|
|
unit = normalize_unit(request.cookies.get(UNIT_COOKIE))
|
|
ctx["unit"] = unit
|
|
ctx["unit_label"] = UNITS[unit][2]
|
|
ctx["amt"] = lambda v: amount_text(v, unit)
|
|
|
|
|
|
def _colw_ctx(request: Request, ctx: dict[str, Any]) -> None:
|
|
"""일자별 표 열 너비(2026-10-27) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_colw)에 둔다.
|
|
manual 이면 표에 perf-colw-manual — performance.js initColWidths 가 머리글 경계 드래그 + 너비 기억(localStorage)."""
|
|
from .dashboard import COLW_COOKIE, normalize_colw # noqa: WPS433
|
|
|
|
ctx["colw"] = normalize_colw(request.cookies.get(COLW_COOKIE))
|
|
|
|
|
|
@router.get("/ads", response_class=HTMLResponse)
|
|
def ads_page(
|
|
request: Request,
|
|
period: str = "month",
|
|
d: str | None = None,
|
|
from_: str | None = Query(None, alias="from"),
|
|
to: str | None = None,
|
|
):
|
|
from app.main import render_template # noqa: WPS433
|
|
|
|
g = common.guard(request)
|
|
if not isinstance(g, tuple):
|
|
return g
|
|
store, user = g
|
|
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
|
from .dashboard import _sales_marketplaces # noqa: WPS433
|
|
|
|
today = today_kst()
|
|
ctx = build_ad_dashboard(
|
|
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
|
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
|
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
|
)
|
|
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
|
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.
|
|
from . import jobs # noqa: WPS433
|
|
from .ad_sources.registry import get_source # noqa: WPS433
|
|
from .ad_sync import last_ad_update_at # noqa: WPS433
|
|
|
|
_, ad_sync = _ad_services(store)
|
|
try:
|
|
configured = ad_sync.configured()
|
|
except Exception: # noqa: BLE001 — 007 미적용 등: 버튼만 숨김
|
|
configured = {}
|
|
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in configured.items() if ok]
|
|
ctx["ad_last_update_at"] = last_ad_update_at(store)
|
|
ctx["ad_running"] = jobs.running_job("ads") is not None
|
|
ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
|
|
ctx["update_watch"] = _update_watch("ads", user)
|
|
_colw_ctx(request, ctx)
|
|
return render_template(request, "performance/ads.html",
|
|
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
|
|
|
|
|
@router.get("/settings", response_class=HTMLResponse)
|
|
def settings_page(request: Request):
|
|
from app.main import render_template # noqa: WPS433
|
|
|
|
# 모듈 권한자 누구나 들어온다 — 일반 사용자는 수수료율만(쇼핑몰 표의 다른 칸·다른 카드는 템플릿이 관리자에게만 그린다).
|
|
g = common.guard(request)
|
|
if not isinstance(g, tuple):
|
|
return g
|
|
store, user = g
|
|
from .dashboard import build_settings # noqa: WPS433
|
|
|
|
creds, _ = common.services(request, store)
|
|
ad_creds, ad_sync = _ad_services(store)
|
|
versions = creds.key_versions_in_use()
|
|
for v, n in ad_creds.key_versions_in_use().items(): # 광고 API 인증정보도 같은 마스터 키
|
|
versions[v] = versions.get(v, 0) + n
|
|
ctx = build_settings(
|
|
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
|
|
key_versions_in_use=versions, sample_count=store.sample_count(),
|
|
)
|
|
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
|
|
ctx["ad_api_ready"] = store.ad_api_ready()
|
|
ctx["auto_sync_settings"] = _auto_sync_settings_ctx(store) # 카드는 관리자에게만(템플릿)
|
|
_unit_ctx(request, ctx)
|
|
_colw_ctx(request, ctx)
|
|
return render_template(request, "performance/settings.html",
|
|
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
|
|
|
|
|
def _auto_sync_settings_ctx(store: Any) -> dict[str, Any]:
|
|
"""실적 설정 "자동 업데이트" 카드(2026-10-26) — 종류마다 일정·다음 회차, 011 적용 여부, env 로 꺼졌는지."""
|
|
from app.timezone import now_kst # noqa: WPS433
|
|
|
|
from . import auto_sync # noqa: WPS433
|
|
|
|
try:
|
|
schedules, ready = auto_sync.load_schedules(store)
|
|
error = ""
|
|
except Exception as exc: # noqa: BLE001 — DB 오류여도 설정 화면은 뜬다
|
|
schedules, ready, error = auto_sync.normalize(None), True, f"일정을 읽지 못했습니다({type(exc).__name__}) — 기본 일정을 보여 줍니다."
|
|
now = now_kst()
|
|
kinds = []
|
|
for k in auto_sync.KINDS:
|
|
nxt = auto_sync.next_slot(now, schedules[k])
|
|
kinds.append({"kind": k, "name": auto_sync.KIND_NAMES[k], "schedule": schedules[k],
|
|
"label": auto_sync.describe(schedules[k]), "next_at": nxt.isoformat() if nxt else ""})
|
|
return {"kinds": kinds, "ready": ready, "env_on": auto_sync.enabled(), "days": auto_sync.sync_days(),
|
|
"error": error, "weekdays": auto_sync.WEEKDAYS, "step": auto_sync.INTERVAL_STEP,
|
|
"max": auto_sync.INTERVAL_MAX}
|
|
|
|
|
|
@router.put("/api/auto-sync-schedule")
|
|
def api_auto_sync_schedule(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
"""자동 업데이트 일정 저장(2026-10-26, 관리자, 마이그레이션 011) — {sales: 일정, ads: 일정}. 스레드가 1분 안에 반영."""
|
|
from app.timezone import now_kst # noqa: WPS433
|
|
|
|
from . import auto_sync # noqa: WPS433
|
|
from .db import SettingsMigrationNeeded # noqa: WPS433
|
|
|
|
store, user = common.require_store(request, admin=True)
|
|
value = {}
|
|
for k in auto_sync.KINDS:
|
|
try:
|
|
value[k] = auto_sync.validate_schedule(payload.get(k))
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=f"{auto_sync.KIND_NAMES[k]}: {exc}") from None
|
|
try:
|
|
store.set_setting(auto_sync.SETTING_KEY, value, user=user.get("email", ""))
|
|
except SettingsMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail="일정을 저장하려면 performance_db 마이그레이션 011"
|
|
"(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None
|
|
now = now_kst()
|
|
out = {}
|
|
for k, sched in value.items():
|
|
nxt = auto_sync.next_slot(now, sched)
|
|
out[k] = {"schedule": sched, "label": auto_sync.describe(sched), "next_at": nxt.isoformat() if nxt else ""}
|
|
return JSONResponse({"ok": True, "env_on": auto_sync.enabled(), **out})
|
|
|
|
|
|
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
|
|
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
|
|
from .ad_sources.registry import all_sources # noqa: WPS433
|
|
from .adapters.base import STATUS_LABELS # noqa: WPS433
|
|
|
|
statuses = store.ad_source_statuses()
|
|
rows = []
|
|
for s in all_sources():
|
|
st = statuses.get(s.code, {})
|
|
status = st.get("status") or ("unknown" if configured.get(s.code) else "not_configured")
|
|
rows.append({"code": s.code, "name": s.name, "configured": bool(configured.get(s.code)), "status": status,
|
|
"status_label": STATUS_LABELS.get(status, status), "last_test_at": st.get("last_test_at"),
|
|
"last_error": st.get("last_error") or "", "last_error_at": st.get("last_error_at"),
|
|
"last_sync_at": st.get("last_sync_at"), "last_success_sync_at": st.get("last_success_sync_at")})
|
|
return rows
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# JSON API — 모듈 권한
|
|
# ════════════════════════════════════════════════════════════
|
|
@router.post("/api/sync")
|
|
def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
|
"""from/to 가 없으면 최근 N일(PERFORMANCE_SYNC_DAYS). 기간 지정은 대시보드 [매출 업데이트](보고 있는 기간)와
|
|
설정 [과거 매출 가져오기]가 쓴다 — 모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
|
|
store, user = common.require_store(request)
|
|
_, sync = common.services(request, store)
|
|
codes = [str(c) for c in (payload.get("codes") or []) if get_adapter(str(c))]
|
|
start = _parse_date(payload.get("from"), field="시작일")
|
|
end = _parse_date(payload.get("to"), field="종료일")
|
|
if start or end:
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
end = end or today_kst()
|
|
start = start or end
|
|
if end < start:
|
|
start, end = end, start
|
|
if end > today_kst():
|
|
end = today_kst()
|
|
if start > end:
|
|
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
|
|
days = (end - start).days + 1
|
|
if days > MAX_BACKFILL_DAYS:
|
|
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
|
|
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
|
|
raise HTTPException(status_code=403,
|
|
detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
|
|
if payload.get("background"):
|
|
return JSONResponse(_start_background_sync(store, sync, start=start, end=end, codes=codes or None,
|
|
user=user["email"]))
|
|
results = sync.sync_all(start=start, end=end, codes=codes or None, user=user["email"])
|
|
return JSONResponse({"results": results, "last_update_at": store.last_update_at()})
|
|
|
|
|
|
def _start_background_sync(store: Any, sync: Any, *, start: date | None, end: date | None,
|
|
codes: list[str] | None, user: str) -> dict[str, Any]:
|
|
"""수집을 스레드로 돌리고 작업 번호를 바로 돌려준다. 이미 돌고 있는 업데이트가 있으면 새로 시작하지 않고
|
|
그 작업을 보여 준다(같은 쇼핑몰 동시 실행은 어차피 막혀 있다)."""
|
|
import logging # noqa: WPS433
|
|
import threading # noqa: WPS433
|
|
|
|
from . import jobs # noqa: WPS433
|
|
|
|
live = jobs.running_job()
|
|
if live is not None:
|
|
return {"job": live.snapshot(), "joined": True}
|
|
job = jobs.create_job(user=user, start=start, end=end)
|
|
|
|
def run() -> None:
|
|
error = ""
|
|
try:
|
|
sync.sync_all(start=start, end=end, codes=codes, user=user, job=job)
|
|
except Exception as exc: # noqa: BLE001 — 스레드 밖으로 새지 않게, 화면에는 "오류"로
|
|
logging.getLogger("performance.sync").exception("background sync failed")
|
|
error = f"업데이트 중 오류: {type(exc).__name__}"
|
|
last = None
|
|
try:
|
|
last = store.last_update_at()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
job.finish(error=error, last_update_at=last)
|
|
|
|
threading.Thread(target=run, name=f"perf-sync-{job.id}", daemon=True).start()
|
|
return {"job": job.snapshot(), "joined": False}
|
|
|
|
|
|
@router.get("/api/sync/jobs/{job_id}")
|
|
def api_sync_job(request: Request, job_id: str) -> JSONResponse:
|
|
common.require_store(request)
|
|
from . import jobs # noqa: WPS433
|
|
|
|
job = jobs.get_job(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
|
|
return JSONResponse({"job": job.snapshot()})
|
|
|
|
|
|
@router.post("/api/sync/jobs/{job_id}/cancel")
|
|
def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
|
|
"""[업데이트 취소] — 시작한 사람 또는 관리자. 돌고 있는 쇼핑몰은 다음 API 호출 직전에 멈추고(저장 전이면 DB 그대로),
|
|
기다리는 쇼핑몰은 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 그대로 남는다."""
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
from . import jobs # noqa: WPS433
|
|
|
|
_, user = common.require_store(request)
|
|
job = jobs.get_job(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
|
|
if job.user and job.user != user["email"] and not is_admin(user):
|
|
raise HTTPException(status_code=403, detail="업데이트를 시작한 사람이나 관리자만 취소할 수 있습니다.")
|
|
job.cancel(user["email"])
|
|
return JSONResponse({"job": job.snapshot()})
|
|
|
|
|
|
@router.post("/api/sync/jobs/{job_id}/shops/{code}/stop")
|
|
def api_sync_stop_shop(request: Request, job_id: str, code: str) -> JSONResponse:
|
|
"""쇼핑몰별 [중지] — 시작한 사람 또는 관리자. 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, 기존 매출 그대로)
|
|
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰은 차례가 오면 건너뛴다. 저장 중·끝난 쇼핑몰은 409."""
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
from . import jobs # noqa: WPS433
|
|
|
|
_, user = common.require_store(request)
|
|
job = jobs.get_job(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
|
|
if job.user and job.user != user["email"] and not is_admin(user):
|
|
raise HTTPException(status_code=403, detail="업데이트를 시작한 사람이나 관리자만 중지할 수 있습니다.")
|
|
if not job.stop_shop(code):
|
|
raise HTTPException(status_code=409, detail="이미 끝났거나 저장 중인 쇼핑몰은 중지할 수 없습니다.")
|
|
return JSONResponse({"job": job.snapshot()})
|
|
|
|
|
|
@router.get("/api/sync/current")
|
|
def api_sync_current(request: Request) -> JSONResponse:
|
|
common.require_store(request)
|
|
from . import jobs # noqa: WPS433
|
|
|
|
job = jobs.running_job()
|
|
return JSONResponse({"job": job.snapshot() if job else None})
|
|
|
|
|
|
@router.get("/api/events")
|
|
def api_events(request: Request, code: str, from_: str = Query(..., alias="from"), to: str | None = None) -> JSONResponse:
|
|
store, _ = common.require_store(request)
|
|
_code_or_404(store, code)
|
|
start = _parse_date(from_)
|
|
end = _parse_date(to) or start
|
|
if end < start:
|
|
start, end = end, start
|
|
if (end - start).days + 1 > MAX_EVENT_DAYS:
|
|
raise HTTPException(status_code=400, detail=f"상세 조회는 {MAX_EVENT_DAYS}일 이내만 가능합니다.")
|
|
rows = store.list_events(code, start, end)
|
|
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
|
|
|
|
|
def _cell_amount(raw: Any) -> tuple[int | None, str | None]:
|
|
"""날짜 칸 입력(매출 수동 입력·광고비) → (금액, 계산식). 빈 칸 = 지움."""
|
|
from .formula import FormulaError, parse_amount # noqa: WPS433
|
|
|
|
try:
|
|
amount, formula = parse_amount(raw)
|
|
except FormulaError as exc:
|
|
raise HTTPException(status_code=400, detail=f"{exc} (숫자 또는 1000+2000 같은 계산식)") from None
|
|
if amount is not None and abs(amount) > MAX_MANUAL_AMOUNT:
|
|
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
|
return amount, formula
|
|
|
|
|
|
@router.put("/api/manual-sales/{code}/{day}")
|
|
def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 앞으로의 날도 가능(2026-10-21). amount 가 비면 지움(그날은 다시 API 값).
|
|
amount 는 숫자 또는 계산식(1000+2000 — formula.parse_amount)."""
|
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
|
|
|
store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정)
|
|
_code_or_404(store, code)
|
|
d = _parse_date(day)
|
|
m = next((x for x in store.list_marketplaces() if x["code"] == code), {})
|
|
if not m.get("manual_input"):
|
|
raise HTTPException(status_code=400, detail="이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).")
|
|
amount, formula = _cell_amount(payload.get("amount"))
|
|
try:
|
|
store.set_manual_sale(code, d, amount, user=user.get("email", ""), formula=formula)
|
|
except ManualMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
|
api_amount = store.api_amount(code, d)
|
|
shown = api_amount if amount is None else amount
|
|
# 그날 수수료·수수료 차감 매출도 돌려준다 — 화면이 새로고침 전에도 보고 있는 기준(기본 = 차감 매출) 숫자를 바로 바꾸게
|
|
rate_table = getattr(store, "rate_table", None)
|
|
money = calc.build_cells({(d, code): shown}, rate_table() if rate_table else {})[(d, code)].as_dict()
|
|
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount, "formula": formula,
|
|
"amount": shown, "api_amount": api_amount,
|
|
"commission": money["commission"], "net": money["net"]})
|
|
|
|
|
|
@router.get("/api/manual-sales/sample.xlsx")
|
|
def api_manual_sample(request: Request) -> Any:
|
|
common.require_store(request)
|
|
if not MANUAL_SAMPLE_PATH.is_file():
|
|
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
|
|
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
|
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
|
|
|
|
|
@router.post("/api/manual-sales/upload")
|
|
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
|
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
|
|
from . import manual_upload # noqa: WPS433
|
|
from .dashboard import _short_name # noqa: WPS433
|
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
|
|
|
store, user = common.require_store(request) # 날짜 칸 수동 입력과 같은 권한(모듈 권한자 누구나)
|
|
content = file.file.read(manual_upload.MAX_FILE_BYTES + 1)
|
|
# 직접 추가 쇼핑몰(009)도 대상 — 어댑터 = 수동 입력 전용(이름은 DB), 그룹 행은 어댑터가 없어 빠진다
|
|
markets = [m for m in store.list_marketplaces() if get_adapter(m["code"]) is not None and m["enabled"]]
|
|
extra = {m["code"]: tuple(n for n in (get_adapter(m["code"]).name, _short_name(m["name"])) if n) for m in markets}
|
|
try:
|
|
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
|
|
except manual_upload.UploadError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from None
|
|
names = {m["code"]: m["name"] for m in markets}
|
|
if res.errors:
|
|
return JSONResponse(status_code=400, content={
|
|
"detail": f"잘못된 칸이 {len(res.errors)}개{'+' if len(res.errors) > manual_upload.MAX_ERRORS else ''} 있어 "
|
|
"아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
|
"errors": res.errors[:manual_upload.MAX_ERRORS], "ignored": res.ignored})
|
|
try:
|
|
saved = store.set_manual_sales_bulk(res.entries, user=user.get("email", ""))
|
|
except ManualMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
|
counts: dict[str, int] = {}
|
|
for code, _, _ in res.entries:
|
|
counts[code] = counts.get(code, 0) + 1
|
|
days = sorted({d for _, d, _ in res.entries})
|
|
return JSONResponse({
|
|
"ok": True, "saved": saved,
|
|
"by_shop": [{"code": c, "name": names.get(c, c), "count": counts[c]} for c in res.columns if counts.get(c)],
|
|
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None,
|
|
"ignored": res.ignored,
|
|
})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# JSON API — 광고비(모듈 권한자 누구나)
|
|
# ════════════════════════════════════════════════════════════
|
|
def _ad_channel(channel: str) -> str:
|
|
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
|
|
|
if channel not in CHANNEL_NAMES:
|
|
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
|
return channel
|
|
|
|
|
|
MEMO_MAX = 1000
|
|
|
|
|
|
@router.put("/api/cell-memos/{kind}/{code}/{day}")
|
|
def api_cell_memo(request: Request, kind: str, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
"""날짜 칸 메모(2026-10-22, 마이그레이션 010) — kind = sales(매출 실적, 쇼핑몰) / ad(광고비, 광고 채널).
|
|
memo 가 비면 지움. 칸에 금액을 넣을 수 있는 사람(모듈 권한자 누구나)이 쓴다."""
|
|
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
|
from .db import MemoMigrationNeeded # noqa: WPS433
|
|
|
|
store, user = common.require_store(request)
|
|
if kind == "sales":
|
|
_code_or_404(store, code)
|
|
elif kind == "ad":
|
|
if code not in CHANNEL_NAMES:
|
|
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
|
else:
|
|
raise HTTPException(status_code=404, detail="알 수 없는 메모 종류입니다.")
|
|
d = _parse_date(day)
|
|
if d is None:
|
|
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
|
|
memo = str(payload.get("memo") or "").replace("\r\n", "\n").strip()
|
|
if len(memo) > MEMO_MAX:
|
|
raise HTTPException(status_code=400, detail=f"메모는 {MEMO_MAX:,}자까지 쓸 수 있습니다.")
|
|
try:
|
|
store.set_cell_memo(kind, code, d, memo or None, user=user.get("email", ""))
|
|
except MemoMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail="메모를 쓰려면 performance_db 마이그레이션 010"
|
|
"(scripts/sql/performance_db_010_cell_memos.sql)을 먼저 적용해야 합니다.") from None
|
|
return JSONResponse({"ok": True, "kind": kind, "code": code, "date": d.isoformat(), "memo": memo})
|
|
|
|
|
|
@router.put("/api/ad-spend/{channel}/{day}")
|
|
def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
|
|
|
store, user = common.require_store(request)
|
|
_ad_channel(channel)
|
|
d = _parse_date(day)
|
|
if d is None:
|
|
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
|
|
amount, formula = _cell_amount(payload.get("amount"))
|
|
try:
|
|
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""), formula=formula)
|
|
except AdMigrationNeeded as exc:
|
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
|
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount, "formula": formula,
|
|
"amount": amount or 0})
|
|
|
|
|
|
@router.get("/api/ad-spend/{channel}/details")
|
|
def api_ad_spend_details(request: Request, channel: str, from_: str = Query(..., alias="from"), to: str = Query(...)) -> JSONResponse:
|
|
"""일자별 보고서 항목(네이버 — 노출수·클릭수·전환수 …) + 광고비·ROAS. 최대 366일."""
|
|
from . import ad_spend # noqa: WPS433
|
|
|
|
store, _ = common.require_store(request)
|
|
_ad_channel(channel)
|
|
if channel not in ad_spend.DETAIL_CHANNELS:
|
|
raise HTTPException(status_code=400, detail="이 채널은 일자별 상세 자료가 없습니다.")
|
|
start, end = _parse_date(from_, field="시작일"), _parse_date(to, field="종료일")
|
|
if start is None or end is None or end < start or (end - start).days > 365:
|
|
raise HTTPException(status_code=400, detail="기간을 확인하세요(최대 366일).")
|
|
try:
|
|
rows = store.ad_details(channel, start, end)
|
|
except ad_spend.AdMigrationNeeded as exc:
|
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
|
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
|
|
"to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
|
|
|
|
|
|
@router.post("/api/ad-spend/upload")
|
|
def api_ad_spend_upload(
|
|
request: Request,
|
|
channel: str = Query(...),
|
|
files: list[UploadFile] | None = File(None),
|
|
file: UploadFile | None = File(None),
|
|
modified: list[str] = Form(default=[]),
|
|
) -> JSONResponse:
|
|
"""광고비 파일 업로드(여러 파일 가능, 2026-10-14) — 파일에 있는 날만 덮어쓴다. 같은 날짜가 여러 파일에 있으면
|
|
파일 날짜(브라우저가 보낸 수정 시각 modified, 파일 순서대로 ms)가 최신인 파일 값. 잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다."""
|
|
from . import ad_spend # noqa: WPS433
|
|
from .manual_upload import MAX_FILE_BYTES, UploadError # noqa: WPS433
|
|
|
|
store, user = common.require_store(request)
|
|
_ad_channel(channel)
|
|
parser = ad_spend.PARSERS.get(channel)
|
|
if parser is None:
|
|
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
|
|
uploads = list(files or []) + ([file] if file is not None else [])
|
|
if not uploads:
|
|
raise HTTPException(status_code=400, detail="파일을 고르세요.")
|
|
if len(uploads) > ad_spend.MAX_UPLOAD_FILES:
|
|
raise HTTPException(status_code=400, detail=f"한 번에 {ad_spend.MAX_UPLOAD_FILES}개 파일까지 올릴 수 있습니다.")
|
|
parsed = []
|
|
for i, up in enumerate(uploads):
|
|
name = up.filename or f"파일{i + 1}"
|
|
try:
|
|
mtime = float(modified[i]) if i < len(modified) and str(modified[i]).strip() else 0.0
|
|
except ValueError:
|
|
mtime = 0.0
|
|
try:
|
|
parsed.append((name, mtime, parser(up.file.read(MAX_FILE_BYTES + 1), today=today_kst(), filename=name)))
|
|
except UploadError as exc:
|
|
raise HTTPException(status_code=400, detail=(f"[{name}] " if len(uploads) > 1 else "") + str(exc)) from None
|
|
res, overlap = ad_spend.merge_results(parsed)
|
|
if res.errors:
|
|
return JSONResponse(status_code=400, content={
|
|
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
|
"errors": res.errors[:60]})
|
|
report = {"roas": res.roas, "metrics": res.metrics} if (res.roas or res.metrics) else {}
|
|
try:
|
|
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""), **report)
|
|
except ad_spend.AdMigrationNeeded as exc:
|
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
|
days = sorted(d for d, _ in res.entries)
|
|
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
|
|
"total": sum(a for _, a in res.entries), "skipped": res.skipped, "files": len(uploads),
|
|
"overlap_days": len(overlap), "empty_days": [d.isoformat() for d in res.empty_days[:62]],
|
|
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# JSON API — 광고 API 연동(구글 광고). 인증정보·연결 테스트는 관리자, 가져오기는 모듈 권한자(92일 넘으면 관리자)
|
|
# ════════════════════════════════════════════════════════════
|
|
def _ad_services(store: Any):
|
|
"""(광고 인증정보 서비스, 광고 가져오기 서비스)."""
|
|
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
|
|
|
|
creds = ad_credentials(store, common.key_ring)
|
|
return creds, AdSyncService(store, creds)
|
|
|
|
|
|
def _ad_source_or_404(code: str):
|
|
from .ad_sources.registry import get_source # noqa: WPS433
|
|
|
|
src = get_source(code)
|
|
if src is None:
|
|
raise HTTPException(status_code=404, detail="알 수 없는 광고 연동입니다.")
|
|
return src
|
|
|
|
|
|
@router.get("/api/ad-sources/{code}/credentials")
|
|
def api_ad_source_credentials(request: Request, code: str) -> JSONResponse:
|
|
"""입력칸 + 저장 여부만(비밀 원문 없음) — 쇼핑몰 API 설정 창과 같은 모양."""
|
|
store, _ = common.require_store(request, admin=True)
|
|
src = _ad_source_or_404(code)
|
|
creds, _ = _ad_services(store)
|
|
info = creds.describe(src)
|
|
if not store.ad_api_ready():
|
|
info["decrypt_error"] = AD_MIGRATION_HELP_007
|
|
return JSONResponse({"code": code, "name": src.name, "shared": False, "note": src.note, "docs_url": src.docs_url,
|
|
"key": common.key_status(), **info})
|
|
|
|
|
|
@router.put("/api/ad-sources/{code}/credentials")
|
|
def api_ad_source_save(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
|
|
|
store, user = common.require_store(request, admin=True)
|
|
src = _ad_source_or_404(code)
|
|
if not common.key_status()["ok"]:
|
|
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
|
creds, _ = _ad_services(store)
|
|
values = _clean_values(src, payload)
|
|
clear = [str(k) for k in (payload.get("clear") or [])]
|
|
merged = creds.merged_values(src, values)
|
|
for k in clear:
|
|
if k in merged and not values.get(k):
|
|
merged[k] = ""
|
|
errors = src.validate_credentials(merged)
|
|
if errors:
|
|
raise HTTPException(status_code=400, detail=" ".join(errors))
|
|
try:
|
|
saved = creds.save(src, values, clear=clear, user=user["email"])
|
|
except AdMigrationNeeded as exc:
|
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
|
return JSONResponse({"saved": saved, **creds.describe(src)})
|
|
|
|
|
|
@router.post("/api/ad-sources/{code}/test")
|
|
def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
|
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값)."""
|
|
store, user = common.require_store(request, admin=True)
|
|
src = _ad_source_or_404(code)
|
|
_, ad_sync = _ad_services(store)
|
|
values = {k: v for k, v in _clean_values(src, payload).items() if v.strip()}
|
|
cleared = _cleared_keys(src, payload, values)
|
|
return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None))
|
|
|
|
|
|
def _ad_sync_period(payload: dict[str, Any], user: dict[str, Any]) -> tuple[date, date]:
|
|
"""광고 가져오기 기간 — from·to(없으면 최근 N일), 오늘 뒤는 자름. 모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
from .auto_sync import sync_days # noqa: WPS433
|
|
|
|
today = today_kst()
|
|
end = _parse_date(payload.get("to"), field="종료일") or today
|
|
start = _parse_date(payload.get("from"), field="시작일") or (end - timedelta(days=sync_days() - 1))
|
|
if end < start:
|
|
start, end = end, start
|
|
end = min(end, today)
|
|
if start > end:
|
|
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
|
|
days = (end - start).days + 1
|
|
if days > MAX_BACKFILL_DAYS:
|
|
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
|
|
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
|
|
raise HTTPException(status_code=403, detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
|
|
return start, end
|
|
|
|
|
|
@router.post("/api/ad-sync")
|
|
def api_ad_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
|
"""[광고비 업데이트](2026-10-20) — 설정된 광고 API 전부를 백그라운드 진행 창 작업으로. 이미 돌고 있는 광고비 업데이트
|
|
(다른 사람·자동 업데이트)가 있으면 새로 시작하지 않고 그 작업을 돌려준다(joined)."""
|
|
import threading # noqa: WPS433
|
|
|
|
from . import jobs # noqa: WPS433
|
|
from .ad_sync import run_ad_job # noqa: WPS433
|
|
|
|
store, user = common.require_store(request)
|
|
live = jobs.running_job("ads")
|
|
if live is not None:
|
|
return JSONResponse({"job": live.snapshot(), "joined": True})
|
|
start, end = _ad_sync_period(payload, user)
|
|
_, ad_sync = _ad_services(store)
|
|
if not any(ad_sync.configured().values()):
|
|
raise HTTPException(status_code=400, detail="설정된 광고 API 가 없습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
|
|
job = jobs.create_job(user=user["email"], start=start, end=end, kind="ads")
|
|
threading.Thread(target=run_ad_job, args=(store, common.key_ring, job, start, end),
|
|
kwargs={"user": user["email"]}, name=f"perf-ad-sync-{job.id}", daemon=True).start()
|
|
return JSONResponse({"job": job.snapshot(), "joined": False})
|
|
|
|
|
|
@router.get("/api/ad-sync/current")
|
|
def api_ad_sync_current(request: Request) -> JSONResponse:
|
|
common.require_store(request)
|
|
from . import jobs # noqa: WPS433
|
|
|
|
job = jobs.running_job("ads")
|
|
return JSONResponse({"job": job.snapshot() if job else None})
|
|
|
|
|
|
@router.post("/api/ad-sources/{code}/sync")
|
|
def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
|
"""광고 API 채널 하나 가져오기(진행 창 없이) — 기간(from·to, 없으면 최근 N일). 오늘 뒤는 잘라낸다.
|
|
모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만. 화면은 [광고비 업데이트](/api/ad-sync)를 쓴다."""
|
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
|
from .ad_sync import AdSyncBusy # noqa: WPS433
|
|
|
|
store, user = common.require_store(request)
|
|
src = _ad_source_or_404(code)
|
|
start, end = _ad_sync_period(payload, user)
|
|
_, ad_sync = _ad_services(store)
|
|
if not ad_sync.configured().get(code):
|
|
raise HTTPException(status_code=400, detail=f"{src.name} API 가 설정되지 않았습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
|
|
try:
|
|
res = ad_sync.sync(code, start, end, user=user["email"])
|
|
except AdSyncBusy as exc:
|
|
raise HTTPException(status_code=409, detail=str(exc)) from None
|
|
except AdMigrationNeeded as exc:
|
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
|
if not res.get("ok"):
|
|
return JSONResponse(status_code=502, content={"detail": f"{src.name} 가져오기 실패 — {res.get('message')}", **res})
|
|
return JSONResponse(res)
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
|
# ════════════════════════════════════════════════════════════
|
|
def _market_or_404(store: Any, code: str) -> dict[str, Any]:
|
|
"""DB 행(그룹 포함)."""
|
|
m = next((x for x in store.list_marketplaces() if x["code"] == code), None)
|
|
if m is None or (get_adapter(code) is None and not m.get("is_group")):
|
|
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
|
|
return m
|
|
|
|
|
|
def _clean_market_name(store: Any, raw: Any, *, code: str = "") -> str:
|
|
"""직접 추가 행 이름 — 엑셀 업로드 머리글로도 쓰여 다른 쇼핑몰·그룹과 겹치면 안 된다."""
|
|
name = " ".join(str(raw or "").split())
|
|
if not name:
|
|
raise HTTPException(status_code=400, detail="이름을 입력하세요.")
|
|
if len(name) > MAX_MARKET_NAME:
|
|
raise HTTPException(status_code=400, detail=f"이름은 {MAX_MARKET_NAME}자까지입니다.")
|
|
if any(m["code"] != code and m["name"].strip().lower() == name.lower() for m in store.list_marketplaces()):
|
|
raise HTTPException(status_code=400, detail=f"같은 이름({name})이 이미 있습니다.")
|
|
return name
|
|
|
|
|
|
def _set_parent(store: Any, code: str, parent: str | None) -> dict[str, Any] | None:
|
|
from .db import CustomMigrationNeeded # noqa: WPS433
|
|
|
|
if parent:
|
|
g = next((x for x in store.list_marketplaces() if x["code"] == parent), None)
|
|
if g is None or not g.get("is_group"):
|
|
raise HTTPException(status_code=400, detail="그룹을 찾지 못했습니다.")
|
|
try:
|
|
return store.set_marketplace_parent(code, parent or None)
|
|
except CustomMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=CUSTOM_MIGRATION_HELP) from None
|
|
|
|
|
|
@router.post("/api/marketplaces")
|
|
def api_add_marketplace(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
"""직접 추가(009) — kind="shop" 수동 입력 전용 쇼핑몰(맨 뒤, 사용·매출 집계·수동 입력 켬), kind="group" 그룹."""
|
|
import secrets # noqa: WPS433
|
|
|
|
from .adapters.registry import CUSTOM_PREFIX, GROUP_PREFIX # noqa: WPS433
|
|
from .db import CustomMigrationNeeded # noqa: WPS433
|
|
|
|
store, _ = common.require_store(request, admin=True)
|
|
kind = payload.get("kind") or "shop"
|
|
if kind not in ("shop", "group"):
|
|
raise HTTPException(status_code=400, detail="kind 는 shop 또는 group 입니다.")
|
|
name = _clean_market_name(store, payload.get("name"))
|
|
code = (GROUP_PREFIX if kind == "group" else CUSTOM_PREFIX) + secrets.token_hex(4)
|
|
try:
|
|
row = store.add_custom_marketplace(code, name, is_group=kind == "group")
|
|
except CustomMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=CUSTOM_MIGRATION_HELP) from None
|
|
if kind == "shop" and payload.get("parent_code"):
|
|
row = _set_parent(store, code, str(payload["parent_code"])) or row
|
|
return JSONResponse({"marketplace": row})
|
|
|
|
|
|
@router.delete("/api/marketplaces/{code}")
|
|
def api_delete_marketplace(request: Request, code: str) -> JSONResponse:
|
|
"""직접 추가한 쇼핑몰·그룹만 — 쇼핑몰이면 수동 입력 매출·수수료율도 지운다, 그룹이면 하위 쇼핑몰은 그룹 없음."""
|
|
store, _ = common.require_store(request, admin=True)
|
|
m = _market_or_404(store, code)
|
|
if not m.get("is_custom"):
|
|
raise HTTPException(status_code=400, detail="기본 쇼핑몰은 삭제할 수 없습니다(사용을 끄세요).")
|
|
if not store.delete_custom_marketplace(code):
|
|
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
|
|
return JSONResponse({"ok": True})
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/manual-days")
|
|
def api_manual_days(request: Request, code: str) -> JSONResponse:
|
|
"""수동 입력해 둔 날 수 — 직접 추가 쇼핑몰 삭제 확인 문구용."""
|
|
store, _ = common.require_store(request, admin=True)
|
|
_market_or_404(store, code)
|
|
return JSONResponse({"days": store.manual_day_count(code)})
|
|
|
|
|
|
@router.put("/api/marketplace-order")
|
|
def api_marketplace_order(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
"""설정 드래그 순서 — 화면에 보이는 순서(그룹 뒤에 하위) 그대로 codes. 매출 실적 열 순서가 된다."""
|
|
store, _ = common.require_store(request, admin=True)
|
|
known = {m["code"] for m in store.list_marketplaces()}
|
|
codes = [str(c) for c in (payload.get("codes") or []) if str(c) in known]
|
|
if len(set(codes)) != len(codes):
|
|
raise HTTPException(status_code=400, detail="순서 목록에 같은 쇼핑몰이 두 번 있습니다.")
|
|
if not codes:
|
|
raise HTTPException(status_code=400, detail="순서 목록이 비었습니다.")
|
|
store.reorder_marketplaces(codes)
|
|
return JSONResponse({"ok": True})
|
|
|
|
|
|
@router.put("/api/marketplaces/{code}")
|
|
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
store, _ = common.require_store(request, admin=True)
|
|
m = _market_or_404(store, code)
|
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
|
|
|
adapter = get_adapter(code)
|
|
if adapter is not None and adapter.manual_only and payload.get("manual_input") is False:
|
|
raise HTTPException(status_code=400, detail="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
|
|
# 직접 추가 행(009) — 이름·그룹. 그룹으로 묶을 수 있는 건 직접 추가한 쇼핑몰만(그룹 안에 그룹 없음)
|
|
if "name" in payload or "parent_code" in payload:
|
|
if not m.get("is_custom"):
|
|
raise HTTPException(status_code=400, detail="기본 쇼핑몰은 이름·그룹을 바꿀 수 없습니다.")
|
|
if "parent_code" in payload and m.get("is_group"):
|
|
raise HTTPException(status_code=400, detail="그룹은 다른 그룹에 넣을 수 없습니다.")
|
|
row = None
|
|
if "name" in payload:
|
|
row = store.rename_marketplace(code, _clean_market_name(store, payload.get("name"), code=code))
|
|
if "parent_code" in payload:
|
|
row = _set_parent(store, code, str(payload.get("parent_code") or "") or None)
|
|
if not any(k in payload for k in ("enabled", "include_in_sales", "manual_input")):
|
|
return JSONResponse({"marketplace": row})
|
|
if m.get("is_group"):
|
|
raise HTTPException(status_code=400, detail="그룹은 이름만 바꿀 수 있습니다.")
|
|
|
|
try:
|
|
row = store.update_marketplace(
|
|
code,
|
|
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
|
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
|
manual_input=bool(payload["manual_input"]) if "manual_input" in payload else None,
|
|
)
|
|
except ManualMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
|
return JSONResponse({"marketplace": row})
|
|
|
|
|
|
@router.post("/api/marketplaces/{code}/rates")
|
|
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
store, user = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
|
_code_or_404(store, code)
|
|
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
|
try:
|
|
rate = Decimal(raw)
|
|
except InvalidOperation:
|
|
raise HTTPException(status_code=400, detail="수수료율은 숫자로 입력하세요(예: 5, 10.8, 15.35).") from None
|
|
if not rate.is_finite() or rate < 0 or rate > 100:
|
|
raise HTTPException(status_code=400, detail="수수료율은 0 ~ 100 사이여야 합니다.")
|
|
if rate != rate.quantize(Decimal("0.001")):
|
|
raise HTTPException(status_code=400, detail="수수료율은 소수점 셋째 자리까지 입력할 수 있습니다.")
|
|
effective_from = _parse_date(payload.get("effective_from"), field="적용 시작일")
|
|
if effective_from is None:
|
|
raise HTTPException(status_code=400, detail="적용 시작일을 입력하세요.")
|
|
store.set_rate(code, rate_percent=rate, effective_from=effective_from,
|
|
memo=str(payload.get("memo") or "")[:200], user=user["email"])
|
|
return JSONResponse({"rates": store.list_rates(code)})
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/rates")
|
|
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
|
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
|
_code_or_404(store, code)
|
|
return JSONResponse({"rates": store.list_rates(code)})
|
|
|
|
|
|
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
|
|
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
|
|
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
|
_code_or_404(store, code)
|
|
if not store.delete_rate(code, rate_id):
|
|
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
|
return JSONResponse({"rates": store.list_rates(code)})
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/credentials")
|
|
def api_get_credentials(request: Request, code: str) -> JSONResponse:
|
|
"""입력칸 정의 + 저장 여부만. secret 항목의 원문은 보내지 않는다."""
|
|
store, _ = common.require_store(request, admin=True)
|
|
adapter = _code_or_404(store, code)
|
|
creds, _ = common.services(request, store)
|
|
info = creds.describe(adapter)
|
|
return JSONResponse({"code": code, "name": adapter.name, "shared": adapter.uses_shared_integration,
|
|
"note": adapter.note, "docs_url": adapter.docs_url,
|
|
"key": common.key_status(), **info})
|
|
|
|
|
|
def _clean_values(adapter, payload: dict[str, Any]) -> dict[str, str]:
|
|
allowed = {f.key for f in adapter.visible_fields()}
|
|
values = payload.get("values") or {}
|
|
if not isinstance(values, dict):
|
|
raise HTTPException(status_code=400, detail="values 형식이 올바르지 않습니다.")
|
|
return {k: str(v) for k, v in values.items() if k in allowed and v is not None}
|
|
|
|
|
|
@router.put("/api/marketplaces/{code}/credentials")
|
|
def api_save_credentials(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
store, user = common.require_store(request, admin=True)
|
|
adapter = _code_or_404(store, code)
|
|
if adapter.uses_shared_integration:
|
|
raise HTTPException(status_code=400, detail=f"{adapter.name}은(는) 공통 연동을 사용해 여기서 입력하지 않습니다.")
|
|
if not common.key_status()["ok"]:
|
|
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
|
creds, _ = common.services(request, store)
|
|
values = _clean_values(adapter, payload)
|
|
clear = [str(k) for k in (payload.get("clear") or [])]
|
|
merged = creds.merged_values(adapter, values)
|
|
for k in clear:
|
|
if k in merged and not values.get(k):
|
|
merged[k] = ""
|
|
errors = adapter.validate_credentials(merged)
|
|
if errors:
|
|
raise HTTPException(status_code=400, detail=" ".join(errors))
|
|
saved = creds.save(adapter, values, clear=clear, user=user["email"])
|
|
return JSONResponse({"saved": saved, **creds.describe(adapter)})
|
|
|
|
|
|
@router.post("/api/marketplaces/{code}/test")
|
|
def api_test_connection(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
|
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용), clear = 화면에서 비운 항목은 빈 값으로.
|
|
광고 API 시험(/api/ad-sources/{code}/test)과 같은 요청·응답 계약 — 공통 설정 창이 둘 다 쓴다(검토 F09)."""
|
|
store, user = common.require_store(request, admin=True)
|
|
adapter = _code_or_404(store, code)
|
|
_, sync = common.services(request, store)
|
|
values = {k: v for k, v in _clean_values(adapter, payload).items() if v.strip()}
|
|
cleared = _cleared_keys(adapter, payload, values)
|
|
result = sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None)
|
|
return JSONResponse(result)
|
|
|
|
|
|
def _cleared_keys(source: Any, payload: dict[str, Any], values: dict[str, str]) -> set[str]:
|
|
"""요청의 clear 중 이 연동의 화면 항목이면서 새 값이 없는 것 — 연결 시험에서 빈 값으로 본다."""
|
|
allowed = {f.key for f in source.visible_fields()}
|
|
return {str(k) for k in (payload.get("clear") or []) if str(k) in allowed and str(k) not in values}
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/reconcile")
|
|
def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse:
|
|
"""쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
|
|
store, user = common.require_store(request, admin=True)
|
|
_code_or_404(store, code)
|
|
day = _parse_date(date_)
|
|
_, sync = common.services(request, store)
|
|
return JSONResponse(sync.reconcile(code, day, to=_parse_date(to, field="종료일"), user=user["email"]))
|
|
|
|
|
|
@router.get("/api/marketplaces/{code}/daily-check")
|
|
def api_daily_check(request: Request, code: str, from_: str = Query(..., alias="from"), to: str | None = None,
|
|
live: bool = False) -> JSONResponse:
|
|
"""쇼핑몰 화면 일별 매출과 날짜별 비교 — 저장값(db) + live=1 이면 지금 API 로 다시 계산한 값(저장 안 함)."""
|
|
store, user = common.require_store(request, admin=True)
|
|
_code_or_404(store, code)
|
|
start = _parse_date(from_)
|
|
end = _parse_date(to) or start
|
|
if end < start:
|
|
start, end = end, start
|
|
if (end - start).days + 1 > MAX_CHECK_DAYS:
|
|
raise HTTPException(status_code=400, detail=f"일별 비교는 {MAX_CHECK_DAYS}일 이내만 가능합니다.")
|
|
_, sync = common.services(request, store)
|
|
return JSONResponse(sync.daily_check(code, start, end, live=live, user=user["email"]))
|
|
|
|
|
|
@router.post("/api/sample-data")
|
|
def api_sample_data(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
store, _ = common.require_store(request, admin=True)
|
|
action = payload.get("action")
|
|
if action == "delete":
|
|
return JSONResponse({"deleted": store.delete_sample_events(), "sample_count": store.sample_count()})
|
|
if action != "generate":
|
|
raise HTTPException(status_code=400, detail="action 은 generate 또는 delete 입니다.")
|
|
today = today_kst()
|
|
start = _parse_date(payload.get("from")) or today.replace(month=1, day=1)
|
|
end = _parse_date(payload.get("to")) or today
|
|
if end < start:
|
|
start, end = end, start
|
|
if (end - start).days > 400:
|
|
raise HTTPException(status_code=400, detail="테스트 데이터는 한 번에 400일까지 만들 수 있습니다.")
|
|
codes = [m["code"] for m in store.list_marketplaces() if m["enabled"] and get_adapter(m["code"]) is not None]
|
|
_, sync = common.services(request, store)
|
|
n = sync.generate_samples(start, end, codes)
|
|
return JSONResponse({"generated": n, "sample_count": store.sample_count()})
|
|
|
|
|
|
@router.post("/api/rekey")
|
|
def api_rekey(request: Request) -> JSONResponse:
|
|
store, _ = common.require_store(request, admin=True)
|
|
if not common.key_status()["ok"]:
|
|
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
|
creds, _ = common.services(request, store)
|
|
ad_creds, _ = _ad_services(store)
|
|
shop, ad = creds.reencrypt_all(), ad_creds.reencrypt_all() # 광고 API 인증정보도 같은 마스터 키
|
|
versions = creds.key_versions_in_use()
|
|
for v, n in ad_creds.key_versions_in_use().items():
|
|
versions[v] = versions.get(v, 0) + n
|
|
return JSONResponse({"reencrypted": shop["reencrypted"] + ad["reencrypted"], "failed": shop["failed"] + ad["failed"],
|
|
"versions_in_use": versions})
|