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:
2026-11-20 16:03:18 +09:00
parent e9f57b6ff6
commit 62cc5e2778
34 changed files with 790 additions and 892 deletions
@@ -0,0 +1,188 @@
"""[말레이시아 실적](2026-11-20) — 실적 라우터를 /malaysia/performance 에 한 번 더 붙인 인스턴스(variant.MY).
틱톡·쇼피·라자다 그룹(쇼핑몰 + 라이브커머스 하위), 금액 = 센 정수(RM 소수 2자리), 광고비 채널 = 틱톡·쇼피·라자다.
"""
from __future__ import annotations
import importlib
from datetime import date
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common, dashboard, formula, manual_upload, variant
TODAY = date(2026, 10, 7)
D5 = date(2026, 10, 5)
def _row(code, name, sort, **kw):
return {"code": code, "name": name, "sort_order": sort, "enabled": True, "include_in_sales": True,
"manual_input": True, "is_custom": True, "is_group": False, "parent_code": None, **kw}
class _Store:
"""scripts/sql/malaysia_performance_db_seed.sql 과 같은 행 — 그룹 3 + 하위(쇼핑몰·라이브) 6."""
def __init__(self):
self.rows = []
for i, (c, n) in enumerate((("tiktok", "틱톡"), ("shopee", "쇼피"), ("lazada", "라자다"))):
self.rows += [_row(f"group_{c}", n, i * 10 + 10, is_group=True, include_in_sales=False, manual_input=False),
_row(f"custom_{c}_shop", f"{n} 쇼핑몰", i * 10 + 11, parent_code=f"group_{c}"),
_row(f"custom_{c}_live", f"{n} 라이브커머스", i * 10 + 12, parent_code=f"group_{c}")]
self.manual = {(D5, "custom_tiktok_shop"): 123_450, (D5, "custom_tiktok_live"): 10_005, # RM 1,234.50 · 100.05
(D5, "custom_shopee_shop"): 50_000}
self.ads = {(D5, "tiktok"): 26_691} # RM 266.91 → ROAS = 1,334.55 ÷ 266.91 = 500%
self.saved = []
def get_setting(self, key):
return None
def list_marketplaces(self):
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
def daily_amounts(self, start, end, codes):
return {k: v for k, v in self.manual.items() if start <= k[0] <= end and k[1] in codes}
manual_amounts = lambda self, start, end, codes, active_only=True: self.daily_amounts(start, end, codes) # noqa: E731
def rate_table(self):
return {}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def ad_amounts(self, start, end):
rows = {k: v for k, v in self.ads.items() if start <= k[0] <= end}
return rows, {k: "manual" for k in rows}
def set_manual_sale(self, code, d, amount, user="", formula=None):
self.saved.append(("sale", code, d, amount, formula))
def api_amount(self, code, d):
return 0
def set_ad_spend(self, channel, d, amount, *, source, user="", formula=None):
self.saved.append(("ad", channel, d, amount, formula))
@pytest.fixture()
def my():
token = variant._current.set(variant.MY)
yield
variant._current.reset(token)
@pytest.fixture()
def client(monkeypatch):
perf_router = importlib.import_module("app.modules.performance.router")
from app.modules.malaysia_performance import router as my_router
store = _Store()
user = {"email": "king@x", "name": "King", "is_admin": True}
class _Creds:
def configured_codes(self, adapters):
return {}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, user))
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
app.include_router(my_router)
c = TestClient(app)
c.store = store
return c
def test_amount_parsing_scales_to_sen():
assert formula.parse_amount("1,234.5", 100) == (123_450, None)
assert formula.parse_amount("RM 10.005", 100) == (1001, None) # 센 미만 반올림
assert formula.parse_amount("10.5+20", 100) == (3050, "10.5+20")
assert formula.parse_amount("1000+2000") == (3000, "1000+2000") # 한국 실적 그대로(원)
assert manual_upload.parse_amount("RM 12.34", 100) == 1234 and manual_upload.parse_amount(12.345, 100) == 1235
assert manual_upload.parse_amount("12,000") == 12000
def test_text_helpers(my):
assert variant.num_text(123_450) == "1,234.50" and variant.money_text(5) == "RM 0.05"
assert variant.input_text(123_450) == "1234.50" and variant.input_text(None) == ""
assert dashboard.amount_text(-10_005, dashboard.load_unit(None)) == "-100.05"
def test_text_helpers_kr_unchanged():
assert variant.current() is variant.KR
assert variant.num_text(1234) == "1,234" and variant.money_text(1234) == "₩1,234" and variant.input_text(5) == "5"
def test_get_store_follows_variant(my):
state = SimpleNamespace(performance_store="kr", malaysia_performance_store="my")
assert common.get_store(SimpleNamespace(app=SimpleNamespace(state=state))) == "my"
def test_group_sums_and_ad_line_under_group(my):
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
assert day5["cells"]["group_tiktok"]["gross"] == 133_455 # 쇼핑몰 + 라이브커머스
assert day5["total"]["gross"] == 183_455 # 그룹은 일 합계에 또 안 더함
assert day5["ads"]["group_tiktok"] == [{"label": "", "amount": 26_691, "roas": 500}]
def test_ad_dashboard_channels(my):
from app.modules.performance.ad_spend import build_ad_dashboard
ctx = build_ad_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY,
sales_codes=[m["code"] for m in dashboard._sales_marketplaces(_Store())])
assert ctx["codes"] == ["tiktok", "shopee", "lazada"] and ctx["upload_channels"] == []
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
assert day5["roas"]["tiktok"] == 500 and day5["roas"]["shopee"] is None
assert ctx["kpis"][1]["note"].startswith("총매출 RM ")
def test_pages_render_malaysia(client):
html = client.get("/malaysia/performance/?period=week&d=2026-10-07").text
assert 'data-base="/malaysia/performance"' in html and 'data-cents="1"' in html
assert 'href="/malaysia/performance/ads"' in html and 'id="perf-sync-btn"' not in html
assert "1,234.50" in html and "1,334.55" in html and 'data-manual-value="1234.50"' in html
assert 'data-group-cell="group_tiktok"' in html and "266.91" in html
ads = client.get("/malaysia/performance/ads?period=week&d=2026-10-07").text
assert ">틱톡" in ads and "구글" not in ads.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert '"manual_api": "/malaysia/performance/api/ad-spend/"' in ads
settings = client.get("/malaysia/performance/settings").text
assert "광고 API 연동" not in settings and "자동 업데이트" not in settings and "매출 단위" not in settings
# 같은 앱의 한국 실적은 그대로
kr = client.get("/performance/?period=week&d=2026-10-07").text
assert 'data-base="/performance"' in kr and "data-cents" not in kr
def test_api_saves_sen(client):
r = client.put("/malaysia/performance/api/manual-sales/custom_tiktok_live/2026-10-07", json={"amount": "12.34"})
assert r.status_code == 200, r.text
assert client.store.saved[-1] == ("sale", "custom_tiktok_live", TODAY, 1234, None)
r = client.put("/malaysia/performance/api/ad-spend/shopee/2026-10-07", json={"amount": "1.5*2"})
assert r.status_code == 200, r.text
assert client.store.saved[-1] == ("ad", "shopee", TODAY, 300, "1.5*2")
assert client.put("/malaysia/performance/api/ad-spend/google/2026-10-07", json={"amount": "1"}).status_code == 404
assert client.get("/malaysia/performance/health").json()["module"] == "malaysia_performance"
def test_sample_lists_malaysia_shops(client):
import io
import openpyxl
r = client.get("/malaysia/performance/api/manual-sales/sample.xlsx")
assert r.status_code == 200
head = next(openpyxl.load_workbook(io.BytesIO(r.content)).active.iter_rows(values_only=True))
assert head[:3] == ("날짜", "틱톡 쇼핑몰", "틱톡 라이브커머스") and len(head) == 7
@@ -1,216 +0,0 @@
"""틱톡 탭(2026-11-05) — 입력 검사·요청 매개변수·30일 나누기·매출 합산·환율·오류 안내·화면 데이터·다른 탭과 분리.
틱톡 서버는 가짜(httpx MockTransport)."""
from __future__ import annotations
import json
from datetime import date
from decimal import Decimal
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from app.modules.performance import ad_spend, fx
from app.modules.performance.ad_sources import tiktok_ads as tt
from app.modules.performance.ad_sources.registry import get_source
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, TokenExpired
TOKEN = "tiktoktoken0123456789abcdefSECRET"
class Creds:
def __init__(self, values):
self.values = values
def get(self, key):
return self.values.get(key, "")
def has(self, key):
return bool(self.values.get(key))
def ctx(**extra):
return AdapterContext(code="tiktok", credentials=Creds({"advertiser_id": "71234567", "access_token": TOKEN, **extra}), timeout_sec=5.0)
def server(monkeypatch, *, currency="KRW", report=None, gmv=None, seen=None):
"""가짜 틱톡 + 환율 서버. seen 에 (경로, 쿼리, 머리글)을 쌓는다."""
def handler(req: httpx.Request) -> httpx.Response:
url = urlparse(str(req.url))
q = {k: v[0] for k, v in parse_qs(url.query).items()}
if seen is not None:
seen.append((url.path, q, req.headers.get("access-token")))
if "business-api.tiktok.com" not in str(req.url):
return httpx.Response(200, json=[{"date": "2026-10-05", "base": "MYR", "quote": "KRW", "rate": 300}])
if url.path.endswith("/advertiser/info/"):
return httpx.Response(200, json={"code": 0, "data": {"list": [{"name": "DBX", "currency": currency, "timezone": "Asia/Seoul"}]}})
rows = gmv if url.path.endswith("/gmv_max/report/get/") else report
if isinstance(rows, httpx.Response):
return rows
return httpx.Response(200, json={"code": 0, "data": {"list": [
{"dimensions": {"stat_time_day": f"{d} 00:00:00"}, "metrics": m} for d, m in (rows or {}).items()]}})
monkeypatch.setattr(tt, "_http", lambda c: httpx.Client(transport=httpx.MockTransport(handler)))
def test_registered_but_not_a_channel():
"""틱톡은 광고 연동에는 있지만 광고비 탭 채널이 아니다(틱톡 탭에서만 보임)."""
assert get_source("tiktok").name == "틱톡"
assert "tiktok" not in ad_spend.CHANNEL_CODES
@pytest.mark.parametrize("values,word", [
({"advertiser_id": "abc", "access_token": TOKEN}, "광고 계정 ID"),
({"advertiser_id": "71234567", "access_token": "short"}, "액세스 토큰"),
({"advertiser_id": "71234567", "access_token": TOKEN, "shop_id": "x1"}, "틱톡샵 ID"),
])
def test_validation(values, word):
assert any(word in e for e in tt.TiktokAdsSource().validate_credentials(values))
def test_stored_values_pass_validation():
assert tt.TiktokAdsSource().validate_credentials({"advertiser_id": "71234567", "access_token": "__stored__"}) == []
def test_fetch_sums_revenue_and_splits_30_days(monkeypatch):
seen = []
server(monkeypatch, seen=seen, report={"2026-10-05": {
"spend": "1000", "impressions": "50", "clicks": "5", "complete_payment": "1", "onsite_shopping": "2",
"total_complete_payment_rate": "2000", "total_onsite_shopping_value": "1000.4"}})
days = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 9, 1), date(2026, 11, 3))
reports = [q for path, q, _ in seen if path.endswith("/report/integrated/get/")]
assert [(q["start_date"], q["end_date"]) for q in reports] == [
("2026-09-01", "2026-09-30"), ("2026-10-01", "2026-10-30"), ("2026-10-31", "2026-11-03")]
assert reports[0]["data_level"] == "AUCTION_ADVERTISER" and "stat_time_day" in json.loads(reports[0]["dimensions"])
assert not [p for p, _, _ in seen if p.endswith("/gmv_max/report/get/")] # 틱톡샵 ID 없으면 안 물음
assert all(h == TOKEN for _, _, h in seen) and not any(TOKEN in json.dumps(q) for _, q, _ in seen) # 토큰은 머리글로만
# 같은 날 응답이 쪽마다 오므로 3번 더해진다 — 가짜 서버가 기간과 무관하게 같은 줄을 주는 탓, 합산 동작 자체를 확인
d = days[0]
assert d.day == date(2026, 10, 5) and d.amount == 3000 and d.metrics[tt.M_REVENUE] == 9001
assert d.roas == Decimal("300.04") and d.metrics[tt.M_ORDERS] == 9
def test_gmv_max_added_only_with_shop_id(monkeypatch):
seen = []
server(monkeypatch, seen=seen, report={"2026-10-05": {"spend": "100", "total_onsite_shopping_value": "100"}},
gmv={"2026-10-05": {"cost": "100", "gross_revenue": "500", "orders": "3"}})
d = tt.TiktokAdsSource().fetch_days(ctx(shop_id="7555"), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.amount == 200 and d.metrics[tt.M_REVENUE] == 600 and d.roas == Decimal("300.00")
assert d.metrics[tt.M_GMV_REVENUE] == 500 and d.metrics[tt.M_GMV_COST] == 100 # 대조용으로 따로 남김
gmv_q = next(q for p, q, _ in seen if p.endswith("/gmv_max/report/get/"))
assert json.loads(gmv_q["store_ids"]) == ["7555"]
def test_foreign_currency_uses_that_day_rate(monkeypatch):
fx.clear_cache()
server(monkeypatch, currency="MYR", report={"2026-10-05": {"spend": "10", "total_onsite_shopping_value": "40"}})
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.amount == 3000 and d.metrics[tt.M_REVENUE] == 12000 and d.roas == Decimal("400.00")
fx.clear_cache()
def test_no_spend_means_no_roas(monkeypatch):
server(monkeypatch, report={"2026-10-05": {"spend": "0", "total_onsite_shopping_value": "40"}})
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.roas is None and d.metrics[tt.M_ROAS] is None
@pytest.mark.parametrize("code,exc", [(40102, TokenExpired), (40105, AuthFailed), (40100, ApiError), (40002, ApiError)])
def test_error_codes(monkeypatch, code, exc):
server(monkeypatch, report=httpx.Response(200, json={"code": code, "message": "bad"}))
with pytest.raises(exc) as got:
tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))
assert str(code) in str(got.value) and TOKEN not in str(got.value)
def test_connection_also_asks_report(monkeypatch):
"""연결 테스트가 보고서까지 물어야 지표 이름 오류를 저장 전에 잡는다."""
seen = []
server(monkeypatch, seen=seen)
msg = tt.TiktokAdsSource().test_connection(ctx())
assert "DBX" in msg and "KRW" in msg
assert any(p.endswith("/report/integrated/get/") for p, _, _ in seen)
class Store:
def __init__(self, rows=None, missing=False):
self.rows, self.missing = rows or [], missing
def ad_details(self, code, start, end):
assert code == "tiktok"
if self.missing:
raise ad_spend.AdMigrationNeeded("005")
return [r for r in self.rows if start.isoformat() <= r["date"] <= end.isoformat()]
def row(day, spend, sales):
return {"date": day, "amount": spend, "roas": None, "metrics": {tt.M_REVENUE: sales}, "source": "api"}
def test_dashboard_table_and_kpis():
store = Store([row("2026-10-05", 1000, 3000), row("2026-10-06", 1000, 1000), row("2026-09-05", 500, 500)])
ctx_ = ad_spend.build_tiktok_dashboard(store, kind="month", anchor=date(2026, 10, 15), today=date(2026, 10, 31),
holidays={"2026-10-09": "한글날"})
total = ctx_["table"][0]
assert total["kind"] == "total" and total["cells"]["spend"]["gross"] == 2000 and total["cells"]["sales"]["gross"] == 4000 and total["roas"] == 200
day = next(r for r in ctx_["table"] if r.get("date") == "2026-10-05")
assert day["roas"] == 300
assert next(r for r in ctx_["table"] if r.get("date") == "2026-10-09")["holiday"] == "한글날"
kpi = {k["key"]: k for k in ctx_["kpis"]}
assert kpi["spend"]["value"] == 2000 and kpi["sales"]["value"] == 4000 and kpi["roas"]["pct"] == 200
assert kpi["spend"]["delta"] == 300.0 and kpi["sales"]["delta"] == 700.0
assert ctx_["year"]["spend"] == 2500 and ctx_["year"]["sales"] == 4500 and ctx_["year"]["rows"][9]["roas"] == 200
assert ctx_["year"]["rows"][10]["future"] is True and ctx_["year"]["rows"][10]["roas"] is None
assert sum(p["gross"] for p in ctx_["chart_sales"]) == 4000 and sum(p["gross"] for p in ctx_["chart_spend"]) == 2000
def test_dashboard_without_table_or_data():
got = ad_spend.build_tiktok_dashboard(Store(missing=True), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
assert got["migration_needed"] is True and got["table"][0]["roas"] is None
assert {k["key"]: k for k in got["kpis"]}["roas"]["pct"] is None
def test_ads_tab_ignores_tiktok_rows():
"""perf_ad_spend 에 틱톡 줄이 있어도 광고비 탭 합계에 안 들어간다."""
class AdStore:
def ad_amounts(self, start, end):
return {(date(2026, 10, 5), "google"): 100, (date(2026, 10, 5), "tiktok"): 9000}, {}
def daily_amounts(self, start, end, codes):
return {}
got = ad_spend.build_ad_dashboard(AdStore(), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
assert got["table"][0]["total"]["gross"] == 100 and "tiktok" not in got["codes"]
assert {k["key"]: k for k in got["kpis"]}["spend"]["value"] == 100
def test_page_renders_after_ads_tab(monkeypatch):
"""진짜 라우터·템플릿 — 탭 순서, 열 순서, 값, 미설정 안내, 칸 입력 없음."""
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
store = Store([row("2026-10-05", 1000, 3000)])
user = {"email": "a@x", "name": "A", "role": "user"}
class Sync:
def configured(self):
return {"google": True, "tiktok": False}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
monkeypatch.setattr(perf_router, "_ad_services", lambda st: (None, Sync()))
monkeypatch.setattr(perf_router, "_auto_sync_ctx", lambda st, kind: None)
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 31))
app = FastAPI()
app.include_router(perf_router.router)
html = TestClient(app).get("/performance/tiktok").text
tabs = html.split('class="perf-tabs-main"', 1)[1]
assert tabs.index("광고비</a>") < tabs.index("틱톡</a>") and "perf-tab-tiktok is-active" in tabs
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert head.index("ROAS") < head.index("광고비") < head.index("매출")
assert "3,000" in html and "300%" in html
assert "틱톡 API 가 아직 설정되지 않았습니다" in html and "data-manual-code" not in html