"""[말레이시아 실적](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("", 1)[1].split("", 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