ef38140673
- 탭: [매출 실적](검정) · [광고비](주황) 큰 탭 + 맨 오른쪽 설정 톱니(Material Symbols settings)
- /performance/ads: 연·월·일 표(채널 × 날짜)·추이·비중·월/연 누적, 매출 대비 광고비 KPI
- 날짜 칸 직접 입력(PUT /api/ad-spend/{channel}/{day}), 쿠팡(로켓) 광고 보고서 업로드
(CSV/엑셀, 1열 날짜·19열 청구금액(+부가가치세), 잘못된 줄 있으면 전부 거절)
- performance_db 마이그레이션 005 perf_ad_spend
- 설정 화면 쇼핑몰 순서 jsdom 기대값을 003 열 순서로 갱신(기존 실패)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
633 lines
33 KiB
Python
633 lines
33 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열 청구금액)
|
|
JSON API — 관리자
|
|
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
|
|
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
|
|
from decimal import Decimal, InvalidOperation
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Body, File, HTTPException, Query, Request, UploadFile
|
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
|
|
|
from app.timezone import today_kst
|
|
|
|
from . import 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)를 "
|
|
"먼저 적용해야 합니다.")
|
|
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 = "week",
|
|
d: str | None = None,
|
|
from_: str | None = Query(None, alias="from"),
|
|
to: str | None = None,
|
|
m: list[str] = Query(default=[]),
|
|
metric: str = "gross",
|
|
):
|
|
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 "gross"
|
|
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
|
|
|
|
|
@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)],
|
|
)
|
|
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)
|
|
ctx = build_settings(
|
|
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
|
|
key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(),
|
|
)
|
|
return render_template(request, "performance/settings.html",
|
|
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 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})
|
|
|
|
|
|
@router.put("/api/manual-sales/{code}/{day}")
|
|
def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
|
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지. amount 가 비면 지움(그날은 다시 API 값)."""
|
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
|
|
|
store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정)
|
|
_code_or_404(store, code)
|
|
d = _parse_date(day)
|
|
if d > today_kst():
|
|
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
|
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="이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).")
|
|
raw = payload.get("amount")
|
|
amount: int | None
|
|
if raw in (None, ""):
|
|
amount = None
|
|
else:
|
|
try:
|
|
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
|
except (InvalidOperation, ValueError):
|
|
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
|
if abs(amount) > MAX_MANUAL_AMOUNT:
|
|
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
|
try:
|
|
store.set_manual_sale(code, d, amount, user=user.get("email", ""))
|
|
except ManualMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
|
api_amount = store.api_amount(code, d)
|
|
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount,
|
|
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
|
|
|
|
|
|
@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)
|
|
known = {a.code: a for a in all_adapters()}
|
|
markets = [m for m in store.list_marketplaces() if m["code"] in known and m["enabled"]]
|
|
extra = {m["code"]: (known[m["code"]].name, _short_name(m["name"])) 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
|
|
|
|
|
|
@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="날짜가 필요합니다.")
|
|
if d > today_kst():
|
|
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
|
raw = payload.get("amount")
|
|
amount: int | None
|
|
if raw in (None, ""):
|
|
amount = None
|
|
else:
|
|
try:
|
|
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
|
except (InvalidOperation, ValueError):
|
|
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
|
if abs(amount) > MAX_MANUAL_AMOUNT:
|
|
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
|
try:
|
|
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
|
|
except AdMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
|
|
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount,
|
|
"amount": amount or 0})
|
|
|
|
|
|
@router.post("/api/ad-spend/upload")
|
|
def api_ad_spend_upload(request: Request, channel: str = Query(...), file: UploadFile = File(...)) -> JSONResponse:
|
|
"""광고비 파일 업로드 — 파일에 있는 날만 덮어쓴다. 잘못된 줄이 있으면 아무것도 저장하지 않는다."""
|
|
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]} 업로드 양식은 아직 정해지지 않았습니다.")
|
|
content = file.file.read(MAX_FILE_BYTES + 1)
|
|
try:
|
|
res = parser(content, today=today_kst(), filename=file.filename or "")
|
|
except UploadError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from None
|
|
if res.errors:
|
|
return JSONResponse(status_code=400, content={
|
|
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
|
"errors": res.errors})
|
|
try:
|
|
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""))
|
|
except ad_spend.AdMigrationNeeded:
|
|
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) 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,
|
|
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
|
# ════════════════════════════════════════════════════════════
|
|
@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)
|
|
_code_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="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
|
|
|
|
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 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용)."""
|
|
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()}
|
|
result = sync.test_connection(code, values=values or None, user=user["email"])
|
|
return JSONResponse(result)
|
|
|
|
|
|
@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"]]
|
|
_, 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)
|
|
return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()})
|