feat(실적): 틱톡 탭 삭제 + [말레이시아 실적] 모듈 추가
- 실적 틱톡 탭·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>
This commit is contained in:
@@ -57,7 +57,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
from . import calc, common
|
||||
from . import calc, common, variant
|
||||
from .adapters.registry import all_adapters, get_adapter
|
||||
|
||||
router = APIRouter(prefix="/performance", tags=["performance"])
|
||||
@@ -66,7 +66,7 @@ MAX_EVENT_DAYS = 31
|
||||
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
||||
MAX_BACKFILL_DAYS = 366
|
||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
||||
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)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
@@ -114,7 +114,7 @@ def _code_or_404(store: Any, code: str):
|
||||
@router.get("/health")
|
||||
def health(request: Request) -> JSONResponse:
|
||||
st = common.get_store(request)
|
||||
return JSONResponse({"ok": st is not None, "module": "performance",
|
||||
return JSONResponse({"ok": st is not None, "module": variant.current().module_key,
|
||||
"encryption_key": common.key_status()["ok"]})
|
||||
|
||||
|
||||
@@ -165,7 +165,7 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
|
||||
|
||||
from . import auto_sync # noqa: WPS433
|
||||
|
||||
if not auto_sync.enabled():
|
||||
if not auto_sync.enabled() or not variant.current().is_kr: # 말레이시아 실적은 API 수집 없음(수동 입력만)
|
||||
return None
|
||||
try:
|
||||
sched = auto_sync.load_schedules(store)[0][kind]
|
||||
@@ -179,11 +179,15 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
|
||||
"label": auto_sync.describe(sched)}
|
||||
|
||||
|
||||
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]:
|
||||
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str] | None:
|
||||
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
|
||||
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다."""
|
||||
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다.
|
||||
말레이시아 실적은 없음 — 진행 작업(jobs)은 한국 실적 것이라 보면 엉뚱하게 새로 고친다."""
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
if not variant.current().is_kr:
|
||||
return None
|
||||
|
||||
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
||||
return {"kind": kind, "seen": job.id if job else ""}
|
||||
|
||||
@@ -208,7 +212,7 @@ def _unit_ctx(store: Any, ctx: dict[str, Any]) -> None:
|
||||
|
||||
unit = load_unit(store)
|
||||
ctx["unit"] = unit
|
||||
ctx["unit_label"] = UNITS[unit][2]
|
||||
ctx["unit_label"] = UNITS[unit][2] if unit in UNITS else "RM"
|
||||
ctx["amt"] = lambda v: amount_text(v, unit)
|
||||
|
||||
|
||||
@@ -251,7 +255,7 @@ def ads_page(
|
||||
|
||||
|
||||
def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> None:
|
||||
"""[광고비 업데이트](2026-10-20, 광고비·틱톡 탭 공통) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
||||
"""[광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
||||
마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차."""
|
||||
from . import jobs # noqa: WPS433
|
||||
from .ad_sources.registry import get_source # noqa: WPS433
|
||||
@@ -269,33 +273,6 @@ def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> Non
|
||||
ctx["update_watch"] = _update_watch("ads", user)
|
||||
|
||||
|
||||
@router.get("/tiktok", response_class=HTMLResponse)
|
||||
def tiktok_page(
|
||||
request: Request,
|
||||
period: str = "month",
|
||||
d: str | None = None,
|
||||
from_: str | None = Query(None, alias="from"),
|
||||
to: str | None = None,
|
||||
):
|
||||
"""틱톡 탭(2026-11-05) — 일자별 ROAS·광고비·매출(광고 API 값, 읽기 전용). 설정 = 실적 설정 → 광고 API 연동."""
|
||||
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_tiktok_dashboard # noqa: WPS433
|
||||
|
||||
today = today_kst()
|
||||
ctx = build_tiktok_dashboard(store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays())
|
||||
_ad_update_ctx(store, user, ctx)
|
||||
ctx["tiktok_configured"] = any(s["code"] == "tiktok" for s in ctx["ad_sync_sources"])
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/tiktok.html",
|
||||
{**common.base_ctx(user, active_tab="tiktok", page_title="틱톡"), **ctx})
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings_page(request: Request):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
@@ -307,6 +284,12 @@ def settings_page(request: Request):
|
||||
store, user = g
|
||||
from .dashboard import build_settings # noqa: WPS433
|
||||
|
||||
if not variant.current().is_kr: # 말레이시아 실적 — 쇼핑몰(수동 입력)·보기 설정만(API 인증·광고 API·자동 업데이트 카드 없음)
|
||||
ctx = build_settings(store, configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
|
||||
_unit_ctx(store, ctx)
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/settings.html",
|
||||
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
||||
creds, _ = common.services(request, store)
|
||||
ad_creds, ad_sync = _ad_services(store)
|
||||
versions = creds.key_versions_in_use()
|
||||
@@ -536,7 +519,7 @@ def _cell_amount(raw: Any) -> tuple[int | None, str | None]:
|
||||
from .formula import FormulaError, parse_amount # noqa: WPS433
|
||||
|
||||
try:
|
||||
amount, formula = parse_amount(raw)
|
||||
amount, formula = parse_amount(raw, variant.current().scale)
|
||||
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:
|
||||
@@ -573,13 +556,31 @@ def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, An
|
||||
|
||||
@router.get("/api/manual-sales/sample.xlsx")
|
||||
def api_manual_sample(request: Request) -> Any:
|
||||
common.require_store(request)
|
||||
store, _ = common.require_store(request)
|
||||
if not variant.current().is_kr: # 말레이시아 실적 — 지금 수동 입력 쇼핑몰 이름으로 만든다(한국 샘플은 한국 쇼핑몰)
|
||||
return _manual_sample_from(store)
|
||||
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")
|
||||
|
||||
|
||||
def _manual_sample_from(store: Any) -> Any:
|
||||
import io # noqa: WPS433
|
||||
|
||||
import openpyxl # noqa: WPS433
|
||||
from fastapi.responses import Response # noqa: WPS433
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.append(["날짜", *[m["name"] for m in store.list_marketplaces() if m.get("manual_input") and not m.get("is_group")]])
|
||||
ws.append([today_kst().isoformat()])
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return Response(buf.getvalue(), headers={"Content-Disposition": 'attachment; 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:
|
||||
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
|
||||
@@ -593,7 +594,8 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
|
||||
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)
|
||||
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra,
|
||||
scale=variant.current().scale)
|
||||
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}
|
||||
@@ -622,9 +624,9 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
|
||||
# JSON API — 광고비(모듈 권한자 누구나)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _ad_channel(channel: str) -> str:
|
||||
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
||||
from .ad_spend import channel_names # noqa: WPS433
|
||||
|
||||
if channel not in CHANNEL_NAMES:
|
||||
if channel not in channel_names():
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||
return channel
|
||||
|
||||
@@ -636,14 +638,14 @@ MEMO_MAX = 1000
|
||||
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 .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:
|
||||
if code not in channel_names():
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 메모 종류입니다.")
|
||||
@@ -695,7 +697,7 @@ def api_ad_spend_details(request: Request, channel: str, from_: str = Query(...,
|
||||
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(),
|
||||
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)})
|
||||
|
||||
|
||||
@@ -716,7 +718,7 @@ def api_ad_spend_upload(
|
||||
_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]} 업로드 양식은 아직 정해지지 않았습니다.")
|
||||
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="파일을 고르세요.")
|
||||
@@ -744,7 +746,7 @@ def api_ad_spend_upload(
|
||||
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],
|
||||
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})
|
||||
|
||||
Reference in New Issue
Block a user