diff --git a/.env.example b/.env.example
index 5e44917..e29ac13 100644
--- a/.env.example
+++ b/.env.example
@@ -185,6 +185,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# 초기화: scripts/sql/performance_db_init.sql (docs/DATABASES.md 참고)
# PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/performance_db
#
+# 말레이시아 실적(app/modules/malaysia_performance — 실적 코드 그대로, DB 만 따로). 미설정 시 "설정 필요" 안내.
+# 만들기: scripts/sql/malaysia_performance_db_seed.sql 머리말(performance_db 구조 복사 + 쇼핑몰 seed), 역할은 performance_app 공유.
+# MALAYSIA_PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/malaysia_performance_db
+#
# 쇼핑몰 API 인증정보(ID·Key·Secret·Token)는 여기에 넣지 않는다 —
# 실적 → 설정 화면에서 입력하면 아래 마스터 키로 AES-256-GCM 암호화해 DB 에 저장한다.
# 마스터 키는 DB 에 저장되지 않으며, 잃어버리면 저장된 인증정보를 복구할 수 없다(별도 안전 보관).
diff --git a/CLAUDE.md b/CLAUDE.md
index 3ab76ce..8c3f3bf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -37,6 +37,7 @@
| --- | --- | --- | --- | --- | --- |
| `[프로젝트]` `[Project]` | `project/` | `project_db` | `project` | `docs/PROJECT_MODULE.md` (178KB, 절만) | `project*.js/css`, `erp-overdue.*` |
| `[실적]` | `performance/` | `performance_db` | `performance` | `docs/PERFORMANCE_MODULE.md` (절만) | `performance.*` |
+| `[말레이시아 실적]` | `malaysia_performance/`(얇은 마운트 — 코드는 `performance/` + `variant.py`) | `malaysia_performance_db` | `malaysia_performance` | (모듈 CLAUDE.md) | `performance.*` (실적과 공유) |
| `[카페24]` | `cafe24/` | `cafe24_db` | `cafe24` | `docs/CAFE24_MODULE.md` (절만) | `cafe24.css`, `cafe24-options.js` |
| `[쿠팡]` | `cupang/` | `cupang_db` | `cupang` | (모듈 CLAUDE.md 가 기준) | `cupang.*` |
| `[입출고]` | `inout/` | `inout_db` | `inout` | `docs/INOUT_MODULE.md` | `inout.*` |
@@ -59,6 +60,7 @@
- `itemcode_db` 읽기 전용 상품: 쿠팡·말레이시아재고·입출고 (`itemcode_ro` 권한).
- `app/integrations/cafe24/` 토큰: 카페24 + 실적(카페24 어댑터).
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
+- 실적 코드·화면(`performance/`·`performance.js/css`): 실적 + 말레이시아 실적(`variant.py`) — 바꾸면 둘 다 확인.
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail.
diff --git a/app/main.py b/app/main.py
index d830569..f58d24b 100644
--- a/app/main.py
+++ b/app/main.py
@@ -30,6 +30,8 @@ from .modules.live import build_live_store
from .modules.live import router as live_router
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
from .modules.malaysia import router as malaysia_router
+from .modules.malaysia_performance import build_malaysia_performance_store
+from .modules.malaysia_performance import router as malaysia_performance_router
from .modules.notice import build_notice_store
from .modules.notice import router as notice_router
from .modules.outreach import build_outreach_store
@@ -64,6 +66,7 @@ MODULE_LABELS: dict[str, str] = {
"project": "프로젝트 관리",
"cafe24": "카페24 상품관리",
"performance": "실적",
+ "malaysia_performance": "말레이시아 실적",
"asset": "자산관리",
"inout": "입출고 관리",
"outreach": "안내문 발송",
@@ -229,6 +232,8 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
+# 말레이시아 실적(틱톡·쇼피·라자다 수동 입력): 실적 모듈 코드 그대로, DB 만 따로(MALAYSIA_PERFORMANCE_DB_URL 없으면 "설정 필요").
+app.state.malaysia_performance_store = build_malaysia_performance_store(dsn=env("MALAYSIA_PERFORMANCE_DB_URL") or None)
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
# 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503).
app.state.notice_store = build_notice_store(app.state.project_store)
@@ -251,6 +256,7 @@ app.include_router(dispatch_router)
app.include_router(project_router)
app.include_router(cafe24_router)
app.include_router(performance_router)
+app.include_router(malaysia_performance_router) # /malaysia/performance — 실적 라우터 두 번째 마운트(라우트 이름은 실적이 먼저)
app.include_router(asset_router)
app.include_router(notice_router)
app.include_router(inout_router)
@@ -448,6 +454,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
"status": "ready",
"category": "관리",
},
+ {
+ "key": "malaysia_performance",
+ "title": "말레이시아 실적",
+ "subtitle": "Malaysia Sales",
+ "description": "틱톡·쇼피·라자다의 쇼핑몰·라이브커머스 매출(RM)과 광고비를 일자별로 입력하고 합계를 봅니다.",
+ "url": "/malaysia/performance/",
+ "health_url": "/malaysia/performance/health",
+ "status": "ready",
+ "category": "관리",
+ },
{
"key": "inout",
"title": "입출고 관리",
@@ -509,6 +525,7 @@ def _icon_svg(name: str) -> str:
"project": '',
"cafe24": '',
"performance": '',
+ "malaysia_performance": '',
"modules": '',
}
body = paths.get(name, paths["modules"])
diff --git a/app/modules/malaysia_performance/CLAUDE.md b/app/modules/malaysia_performance/CLAUDE.md
new file mode 100644
index 0000000..68dddbe
--- /dev/null
+++ b/app/modules/malaysia_performance/CLAUDE.md
@@ -0,0 +1,36 @@
+# [말레이시아 실적] — `app/modules/malaysia_performance/`, `malaysia_performance_db` (2026-11-20)
+
+> 이 폴더는 **얇은 마운트**(`__init__.py` 하나)다. 코드·템플릿·`performance.js/css` 는 전부 실적 모듈(`app/modules/performance/`) 것을 그대로 쓴다.
+> 실적과 다른 점은 `app/modules/performance/variant.py` 의 `MY` 한 곳. 실적 화면·기능을 고치면 이 화면에도 그대로 들어간다 — 둘 다 확인.
+
+## 구성
+
+- 주소 `/malaysia/performance/`(매출 실적) · `/ads`(광고비) · `/settings`(톱니). 권한키 `malaysia_performance`. 메뉴 "말레이시아 실적"(관리).
+- `main.py`: `app.state.malaysia_performance_store` = `MALAYSIA_PERFORMANCE_DB_URL`(없으면 "설정 필요"), `include_router` 는 실적 다음(라우트 이름은 실적이 먼저).
+- 요청 → 마운트 의존성 `variant.use_malaysia`(async) → ContextVar `MY` → `common.get_store`·권한·`base_ctx`·`ad_spend.channel_names/roas_sales`·`dashboard.sales_ad_channels/load_unit`·금액 파싱이 이 값을 본다.
+
+## 매출 실적
+
+- 쇼핑몰 = 틱톡·쇼피·라자다 **그룹**(합계 열), 각 그룹 하위 **쇼핑몰**·**라이브커머스** 두 칸(직접 추가 쇼핑몰 = 수동 입력 전용). 그룹 열 = 두 칸 합계, 일 합계 = 6칸 합계.
+ 코드 `group_<쇼핑몰>`·`custom_<쇼핑몰>_shop`·`custom_<쇼핑몰>_live` — `scripts/sql/malaysia_performance_db_seed.sql` 과 `variant.MY` 가 같아야 한다(이름은 설정에서 바꿔도 됨).
+- 금액 = **RM 소수 2자리**. 저장은 **센(0.01 RM) 정수**(`variant.MY.scale = 100`) — 계산·수수료·ROAS 코드는 실적 그대로.
+ 입력 `formula.parse_amount(raw, scale)`·엑셀 `manual_upload.parse_amount(v, scale)`(RM 글자 허용), 화면 `dashboard.amount_text(v, "rm")`·`variant.num_text/money_text/input_text`, JS `money()`(`.perf data-cents`).
+- 매출 업데이트 버튼·다음 업데이트·화면 자동 새로 고침 없음(API 수집 없음 — `jobs` 는 한국 실적 것). 엑셀 업로드 샘플은 지금 쇼핑몰 이름으로 만든다(`router._manual_sample_from`).
+- 그룹 칸 아래 주황 줄 = 그 쇼핑몰 광고비(ROAS%), ROAS = 쇼핑몰 + 라이브커머스 매출 ÷ 광고비(`variant.MY.ad_lines`·`ad_roas_sales`).
+
+## 광고비
+
+- 채널 = 틱톡·쇼피·라자다(`tiktok`·`shopee`·`lazada`), 날짜 칸 직접 입력만(업로드·광고 API 없음). 금액 RM(센 저장).
+
+## 설정
+
+- 쇼핑몰 표(사용·매출 집계·수동 입력·수수료율·이름·그룹·순서·추가/삭제) + 보기 설정 + 공통 보기 설정(열 숨기기). API 인증·광고 API·자동 업데이트·암호화 키·과거 매출·테스트 데이터 카드 없음, 매출 단위 = RM 고정.
+
+## DB
+
+- `malaysia_performance_db` = performance_db **구조만 복사**(`pg_dump --schema-only`) + seed. 역할 `performance_app` 공유. 만드는 순서는 seed 파일 머리말.
+- performance_db 에 새 마이그레이션을 만들면 이 DB 에도 적용한다.
+
+## 테스트
+
+- `app/modules/performance/tests/test_malaysia_variant.py`(센 파싱·그룹 합계·광고비 줄·화면 주소·API 저장 단위·샘플), `tests/js/perf_malaysia.browser.test.js`(렌더 `perf_my_*.html`).
diff --git a/app/modules/malaysia_performance/__init__.py b/app/modules/malaysia_performance/__init__.py
new file mode 100644
index 0000000..c964e9f
--- /dev/null
+++ b/app/modules/malaysia_performance/__init__.py
@@ -0,0 +1,22 @@
+"""[말레이시아 실적] — 실적 모듈(app/modules/performance) 코드·화면을 그대로 쓰는 두 번째 인스턴스(2026-11-20).
+
+주소 /malaysia/performance/…, 저장 malaysia_performance_db(실적과 같은 표 구조), 권한키 malaysia_performance.
+다른 점은 performance/variant.py MY 한 곳 — 틱톡·쇼피·라자다(쇼핑몰·라이브커머스) 수동 입력, RM 소수 2자리(센 정수 저장).
+"""
+
+from typing import Any
+
+from fastapi import APIRouter, Depends
+
+from ..performance import build_performance_store
+from ..performance import router as _performance_router
+from ..performance.variant import use_malaysia
+
+router = APIRouter(prefix="/malaysia")
+router.include_router(_performance_router, dependencies=[Depends(use_malaysia)])
+
+__all__ = ["router", "build_malaysia_performance_store"]
+
+
+def build_malaysia_performance_store(*, dsn: str | None) -> Any:
+ return build_performance_store(dsn=dsn)
diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md
index 3e4d657..145eca5 100644
--- a/app/modules/performance/CLAUDE.md
+++ b/app/modules/performance/CLAUDE.md
@@ -4,6 +4,14 @@
> 정적 파일: `app/static/performance.css`, `performance.js`. 템플릿: `templates/`. 테스트: `tests/`.
> 다른 모듈과 연결: 카페24 어댑터는 `app/integrations/cafe24` 토큰 재사용 · Project 주간 회의록 머리 카드가 `performance_store` 매출을 읽기 전용으로 씀 · `APP_ENCRYPTION_KEY` 는 입출고(Gmail 토큰)와 공유.
+## 두 인스턴스 — [실적] · [말레이시아 실적] (2026-11-20)
+
+- 같은 코드·템플릿·`performance.js` 를 `/performance`(한국, `performance_db`)와 `/malaysia/performance`(`malaysia_performance_db`)에 붙인다.
+ 다른 점은 **`variant.py` 한 곳**(`KR`·`MY`) — 저장소·권한키·주소·광고 채널·통화. 요청마다 `variant.current()`(ContextVar, 말레이시아 마운트 의존성 `use_malaysia`).
+- 고칠 때: 주소는 템플릿 `{{ pv.base }}`·JS `BASE`(`.perf data-base`)만 — **`/performance` 를 새로 하드코딩하지 말 것**.
+ 금액 글자는 `num`·`money_t`·`inval`(템플릿)·`money()`(JS) — 말레이시아는 센 정수(÷100, RM 소수 2자리, `data-cents`). 한국 전용 기능(API 수집·자동 업데이트·광고 API·카페24 열)은 `pv.is_kr` 로.
+- 상세 `app/modules/malaysia_performance/CLAUDE.md`. 마이그레이션은 두 DB 모두에.
+
## 구조 (네 영역 분리)
1. 수집 — `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리).
@@ -111,17 +119,9 @@
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
-## 틱톡 (`/performance/tiktok`, 2026-11-05, 마이그레이션 없음)
-
-- 광고비 탭 틀(기간 이동·KPI·표·그래프·연 누적), 표 열 = ROAS·광고비·매출. 값은 광고 API 만(읽기 전용, 칸 입력·메모 없음). 화면 데이터 `ad_spend.build_tiktok_dashboard`.
-- **틱톡 탭에서만 보임** — 채널 코드 `tiktok` 은 `ad_sources` 에는 있지만 `ad_spend.CHANNELS` 에는 넣지 않는다(넣으면 광고비 탭 합계에 들어감). 쇼핑몰 표(`perf_marketplaces`)에도 없어 매출 실적 합계·열과 무관. 저장은 다른 광고 API 처럼 `perf_ad_spend`(`source='api'`), 매출 = `metrics["매출"]`.
-- 설정 = 실적 설정 **광고 API 연동** 카드 → 틱톡 — 광고 계정 ID·장기 액세스 토큰·틱톡샵 ID(선택). [광고비 업데이트]·광고비 자동 업데이트에 함께 돈다.
-- `ad_sources/tiktok_ads.py` — `report/integrated/get`(30일씩), 매출 = 웹 구매금액 + 틱톡샵 매출, 틱톡샵 ID 가 있으면 `gmv_max/report/get` 비용·매출도 더함(항목별 값은 metrics 에 따로 저장). 외화 계정은 그날 환율로 원화(`fx`). ROAS = 매출 ÷ 광고비.
- **실제 토큰 대조 전**(2026-11-05) — 공식 문서를 읽지 못해 지표 이름은 이차 자료로 확인. 일반 보고서에 GMV Max 가 이미 들어 있으면 틱톡샵 ID 를 넣었을 때 중복되므로, 처음 쓸 때 광고 관리자 화면과 대조할 것.
-
## 광고비 (`/performance/ads`)
-- 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니.
+- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. (틱톡 탭은 2026-11-20 삭제 — 코드·`tiktok_ads.py`·데이터(마이그레이션 012) 모두)
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
- **카톡 플친** 열(`kakao_pf`, 메타 오른쪽, 2026-11-16) — 직접 입력, `NO_SALES` 라 ROAS 없음. 매출 탭 카페24 칸 아래 구글·메타 다음 줄, 일 합계 광고비에도 더함.
diff --git a/app/modules/performance/ad_sources/registry.py b/app/modules/performance/ad_sources/registry.py
index 040591b..d5d9a18 100644
--- a/app/modules/performance/ad_sources/registry.py
+++ b/app/modules/performance/ad_sources/registry.py
@@ -1,14 +1,12 @@
-"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다 —
-틱톡만 예외: 광고비 탭에 안 나오게 CHANNELS 에 넣지 않고 틱톡 탭이 따로 읽는다)."""
+"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
from __future__ import annotations
from .base import AdSource
from .google_ads import GoogleAdsSource
from .meta_ads import MetaAdsSource
-from .tiktok_ads import TiktokAdsSource
-_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource(), TiktokAdsSource())
+_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
_BY_CODE = {s.code: s for s in _SOURCES}
diff --git a/app/modules/performance/ad_sources/tiktok_ads.py b/app/modules/performance/ad_sources/tiktok_ads.py
deleted file mode 100644
index 1dd0fcb..0000000
--- a/app/modules/performance/ad_sources/tiktok_ads.py
+++ /dev/null
@@ -1,202 +0,0 @@
-"""틱톡 광고(TikTok API for Business v1.3) — 날짜별 광고비·매출·ROAS. 화면은 틱톡 탭(광고비 탭·매출 실적에는 안 나옴).
-
-인증(2026-11-05): 광고 계정(advertiser) ID 하나 + 장기 액세스 토큰(머리글 Access-Token). 토큰 앱에 보고서·광고 계정 읽기 권한이 있어야 한다.
-
-조회
- GET /report/integrated/get/ — report_type=BASIC · data_level=AUCTION_ADVERTISER · 차원 advertiser_id·stat_time_day.
- 매출 = 웹 구매금액(total_complete_payment_rate — 이름과 달리 금액) + 틱톡샵 매출(total_onsite_shopping_value).
- GET /gmv_max/report/get/ — 틱톡샵 ID 를 넣었을 때만. 비용(cost)·매출(gross_revenue)을 더한다.
- - 하루 단위 조회는 기간 제한이 있어 30일씩 나눠 묻는다.
- - 금액은 광고 계정 통화 → 그날 환율로 원화(fx.krw_rates, 메타와 같음).
- - ROAS(%) = 매출 ÷ 광고비 × 100(합친 값으로 계산 — 틱톡의 ROAS 칸은 더할 수 없다).
-공식 문서가 스크립트 화면이라 지표 이름을 이차 자료로 확인했다 — 연결 테스트가 어제 하루를 실제로 물어 지표 이름 오류까지 잡는다.
-"""
-
-from __future__ import annotations
-
-import json
-import re
-from datetime import date, timedelta
-from decimal import ROUND_HALF_UP, Decimal
-from typing import Any
-
-import httpx
-
-from app.timezone import today_kst
-
-from .. import fx
-from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, TokenExpired
-from .base import AdDay, AdSource
-from .meta_ads import _num, _won
-
-API_BASE = "https://business-api.tiktok.com/open_api/v1.3"
-MAX_DAYS = 366
-SPAN_DAYS = 30
-PAGE_SIZE = 100 # 계정 하나·30일 = 많아야 30줄이라 한 쪽이면 된다
-RATE_LIMIT = 40100
-
-REPORT_METRICS = ("spend", "impressions", "clicks", "complete_payment", "total_complete_payment_rate",
- "onsite_shopping", "total_onsite_shopping_value")
-GMV_METRICS = ("cost", "gross_revenue", "orders")
-
-# metrics 키 — 화면 이름 그대로 저장. 틱톡 탭은 M_REVENUE 를 매출로 읽는다(ad_spend.build_tiktok_dashboard).
-M_SPEND, M_REVENUE, M_ROAS = "광고비", "매출", "ROAS(%)"
-M_IMPR, M_CLICKS, M_ORDERS = "노출수", "클릭수", "구매수"
-M_WEB, M_SHOP, M_GMV_COST, M_GMV_REVENUE = "웹 구매금액", "틱톡샵 매출", "GMV Max 비용", "GMV Max 매출"
-
-
-def _http(ctx: AdapterContext) -> httpx.Client:
- """HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
- return httpx.Client(timeout=ctx.timeout_sec)
-
-
-def _spans(start: date, end: date) -> list[tuple[date, date]]:
- """기간을 SPAN_DAYS 일씩 나눈다."""
- out = []
- while start <= end:
- stop = min(start + timedelta(days=SPAN_DAYS - 1), end)
- out.append((start, stop))
- start = stop + timedelta(days=1)
- return out
-
-
-class TiktokAdsSource(AdSource):
- code = "tiktok"
- name = "틱톡"
- docs_url = "https://business-api.tiktok.com/portal/docs"
- note = ("TikTok API for Business 로 날짜별 광고비·매출·ROAS 를 가져와 틱톡 탭에 보여 줍니다(매출 실적·광고비 탭 합계에는 들어가지 않음). "
- "준비: 개발자 앱에서 광고 계정을 승인해 장기 액세스 토큰 발급(보고서·광고 계정 읽기 권한). 외화 계정은 그날 환율로 원화로 바꿉니다.")
-
- def credential_fields(self) -> list[CredentialField]:
- return [
- CredentialField("advertiser_id", "광고 계정 ID", placeholder="7123456789012345678",
- help="틱톡 광고 관리자 주소의 aadvid= 뒤 숫자."),
- CredentialField("access_token", "액세스 토큰", secret=True,
- help="광고 계정을 승인할 때 받은 장기 액세스 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
- CredentialField("shop_id", "틱톡샵 ID", required=False, placeholder="GMV Max 캠페인을 쓸 때만",
- help="GMV Max 캠페인은 일반 보고서와 따로 조회합니다 — 넣으면 그 비용·매출도 더합니다. 안 쓰면 비워 둡니다."),
- ]
-
- def validate_credentials(self, values: dict[str, str]) -> list[str]:
- errors = super().validate_credentials(values)
- advertiser = (values.get("advertiser_id") or "").strip()
- if advertiser and advertiser != "__stored__" and not re.fullmatch(r"\d{5,30}", advertiser):
- errors.append("광고 계정 ID 는 숫자여야 합니다.")
- shop = (values.get("shop_id") or "").strip()
- if shop and shop != "__stored__" and not re.fullmatch(r"\d{5,30}", shop):
- errors.append("틱톡샵 ID 는 숫자여야 합니다.")
- token = (values.get("access_token") or "").strip()
- if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
- errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
- return errors
-
- def _get(self, ctx: AdapterContext, client: httpx.Client, path: str, params: dict[str, Any]) -> dict[str, Any]:
- """틱톡은 오류도 HTTP 200 + code 로 준다. 토큰은 머리글로만 보내 주소·오류 문구에 들어가지 않는다."""
- ctx.progress.check()
- token = (ctx.credentials.get("access_token") or "").strip()
- try:
- resp = client.get(API_BASE + path, params=params, headers={"Access-Token": token})
- except httpx.HTTPError as exc:
- raise ApiError(f"틱톡 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
- try:
- body = resp.json()
- except ValueError:
- raise ApiError(f"틱톡 API 응답을 읽을 수 없습니다(HTTP {resp.status_code}).") from None
- code = body.get("code") if isinstance(body, dict) else None
- if resp.status_code == 200 and code == 0:
- return body.get("data") or {}
- text = f"틱톡 API 오류({code if code is not None else resp.status_code}): {str((body or {}).get('message') or '')[:200]}"
- if code == 40102:
- raise TokenExpired(text + " — 액세스 토큰을 다시 발급해 넣으세요.")
- if code == RATE_LIMIT:
- raise ApiError(text + " — 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.")
- if resp.status_code in (401, 403) or (isinstance(code, int) and 40100 < code < 40200):
- raise AuthFailed(text + " — 토큰과 광고 계정 ID, 앱 권한을 확인하세요.")
- raise ApiError(text)
-
- def _info(self, ctx: AdapterContext, client: httpx.Client) -> dict[str, Any]:
- advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
- rows = self._get(ctx, client, "/advertiser/info/", {
- "advertiser_ids": json.dumps([advertiser]), "fields": json.dumps(["name", "currency", "timezone"])}).get("list") or []
- if not rows:
- raise AuthFailed("이 토큰으로 볼 수 없는 광고 계정입니다 — 광고 계정 ID 와 승인 여부를 확인하세요.")
- return rows[0]
-
- def _rows(self, ctx: AdapterContext, client: httpx.Client, path: str, metrics: tuple[str, ...], start: date, end: date,
- **extra: Any) -> list[tuple[date, dict[str, Any]]]:
- """보고서 하나를 30일씩 물어 (날짜, 지표) 목록으로."""
- advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
- out = []
- for s, e in _spans(start, end):
- data = self._get(ctx, client, path, {
- "advertiser_id": advertiser, "dimensions": json.dumps(["advertiser_id", "stat_time_day"]), "metrics": json.dumps(metrics),
- "start_date": s.isoformat(), "end_date": e.isoformat(), "page": 1, "page_size": PAGE_SIZE, **extra})
- for r in data.get("list") or []:
- try:
- day = date.fromisoformat(str((r.get("dimensions") or {}).get("stat_time_day"))[:10])
- except ValueError:
- continue
- out.append((day, r.get("metrics") or {}))
- return out
-
- def _collect(self, ctx: AdapterContext, client: httpx.Client, start: date, end: date) -> dict[date, dict[str, Decimal]]:
- """날짜 → 항목 합(계정 통화)."""
- sums: dict[date, dict[str, Decimal]] = {}
-
- def day_of(d: date) -> dict[str, Decimal]:
- return sums.setdefault(d, {k: Decimal(0) for k in ("spend", "impr", "clicks", "orders", "web", "shop", "gmv_cost", "gmv")})
-
- for d, m in self._rows(ctx, client, "/report/integrated/get/", REPORT_METRICS, start, end,
- report_type="BASIC", data_level="AUCTION_ADVERTISER"):
- one = day_of(d)
- one["spend"] += _num(m.get("spend"))
- one["impr"] += _num(m.get("impressions"))
- one["clicks"] += _num(m.get("clicks"))
- one["orders"] += _num(m.get("complete_payment")) + _num(m.get("onsite_shopping"))
- one["web"] += _num(m.get("total_complete_payment_rate"))
- one["shop"] += _num(m.get("total_onsite_shopping_value"))
- shop_id = (ctx.credentials.get("shop_id") or "").strip()
- if shop_id:
- for d, m in self._rows(ctx, client, "/gmv_max/report/get/", GMV_METRICS, start, end, store_ids=json.dumps([shop_id])):
- one = day_of(d)
- one["orders"] += _num(m.get("orders"))
- one["gmv_cost"] += _num(m.get("cost"))
- one["gmv"] += _num(m.get("gross_revenue"))
- return sums
-
- def test_connection(self, ctx: AdapterContext) -> str:
- self.require_configured(ctx)
- yesterday = today_kst() - timedelta(days=1)
- with _http(ctx) as client:
- info = self._info(ctx, client)
- self._collect(ctx, client, yesterday, yesterday) # 지표 이름·GMV Max 권한까지 실제로 확인
- return f"연결됨 — {info.get('name') or '광고 계정'}({info.get('currency') or '?'}·{info.get('timezone') or '?'})"
-
- def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
- if end < start:
- start, end = end, start
- if (end - start).days + 1 > MAX_DAYS:
- raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
- self.require_configured(ctx)
- with _http(ctx) as client:
- currency = str(self._info(ctx, client).get("currency") or "").upper()
- if not re.fullmatch(r"[A-Z]{3}", currency):
- raise ApiError(f"광고 계정 통화({currency[:10] or '없음'})를 알 수 없습니다.")
- sums = self._collect(ctx, client, start, end)
- try:
- rates = fx.krw_rates(client, currency, start, end) if sums else {}
- except fx.FxError as exc:
- raise ApiError(f"{currency} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
- return [_day(d, sums[d], rates[d]) for d in sorted(sums)]
-
-
-def _day(day: date, a: dict[str, Decimal], rate: Decimal) -> AdDay:
- """합친 값(계정 통화) → 하루치(원화). ROAS 는 비율이라 반올림 전 값으로."""
- spend = (a["spend"] + a["gmv_cost"]) * rate
- revenue = (a["web"] + a["shop"] + a["gmv"]) * rate
- roas = (revenue / spend * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if spend > 0 else None
- return AdDay(day=day, amount=_won(spend), roas=roas, metrics={
- M_SPEND: _won(spend), M_REVENUE: _won(revenue), M_ROAS: float(roas) if roas is not None else None,
- M_WEB: _won(a["web"] * rate), M_SHOP: _won(a["shop"] * rate), M_GMV_COST: _won(a["gmv_cost"] * rate), M_GMV_REVENUE: _won(a["gmv"] * rate),
- M_IMPR: int(a["impr"]), M_CLICKS: int(a["clicks"]), M_ORDERS: int(a["orders"]),
- })
diff --git a/app/modules/performance/ad_spend.py b/app/modules/performance/ad_spend.py
index 7769188..2170b60 100644
--- a/app/modules/performance/ad_spend.py
+++ b/app/modules/performance/ad_spend.py
@@ -26,9 +26,8 @@ from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence
-from . import calc
+from . import calc, variant
from .ad_sources.base import ACCOUNTS_KEY
-from .ad_sources.tiktok_ads import M_REVENUE as TIKTOK_REVENUE_KEY
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
@@ -59,7 +58,17 @@ NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
NO_SALES = frozenset({"etc", "kakao_pf"}) # ROAS 를 계산하지 않는 채널 — 매출 탭 광고비 줄은 sales_ad_channels 에 적은 것만(카톡 플친 = 카페24)
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
ROAS_SALES_CODE["coupang_wing"] = "coupang"
-TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
+
+
+def channel_names() -> dict[str, str]:
+ """지금 인스턴스의 광고비 탭 채널(순서 = 표 열) — 한국 실적 = CHANNELS, 말레이시아 실적 = 틱톡·쇼피·라자다(variant.MY)."""
+ return dict(variant.current().ad_channels or CHANNELS)
+
+
+def roas_sales() -> dict[str, tuple[str, ...]]:
+ """광고 채널 → ROAS 매출 쇼핑몰 코드들(그 합계 ÷ 광고비). 말레이시아 = 쇼핑몰 + 라이브커머스."""
+ v = variant.current()
+ return dict(v.ad_roas_sales) if v.ad_channels else {ch: (c,) for ch, c in ROAS_SALES_CODE.items()}
def roas(sales: int, spend: int) -> int | None:
@@ -71,7 +80,7 @@ def roas(sales: int, spend: int) -> int | None:
def roas_basis(code: str) -> str:
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
- return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
+ return "" if code not in roas_sales() else channel_names().get(code, code)
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
@@ -96,8 +105,8 @@ def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
if code in FILE_ROAS:
return file_of(code) if file_of else None
- mcode = ROAS_SALES_CODE.get(code)
- return None if mcode is None else roas(sales_of(mcode), spend)
+ mcodes = roas_sales().get(code)
+ return None if mcodes is None else roas(sum(sales_of(m) for m in mcodes), spend)
ROCKET_DATE_COL = 0 # 1열 날짜
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
@@ -507,64 +516,14 @@ def _period_nav(period: Any, today: date) -> dict[str, Any]:
]}
-def build_tiktok_dashboard(store: Any, *, kind: str, anchor: date, today: date, custom_from: date | None = None,
- custom_to: date | None = None, holidays: Mapping[str, str] | None = None) -> dict[str, Any]:
- """틱톡 탭(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프, 열 = ROAS·광고비·매출. 광고 API 가 저장한 perf_ad_spend 만 읽는다.
- CHANNELS 에 없어 광고비 탭·매출 실적 합계에는 들어가지 않는다."""
- period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
- cmp_start, cmp_end, cmp_label = period.compare_range(today)
- ref = period.end if period.end < today else today if period.start <= today else period.start
- year_period = calc.resolve_period("year", ref)
- migration_needed = False
- try:
- rows = store.ad_details(TIKTOK, min(period.start, cmp_start, year_period.start), max(period.end, year_period.end))
- except AdMigrationNeeded:
- rows, migration_needed = [], True
- cells: dict[tuple[date, str], calc.Money] = {}
- for r in rows:
- d = date.fromisoformat(r["date"])
- cells[(d, "spend")] = calc.Money(gross=int(r["amount"] or 0))
- cells[(d, "sales")] = calc.Money(gross=int((r["metrics"] or {}).get(TIKTOK_REVENUE_KEY) or 0))
-
- table = calc.main_table(period, ("spend", "sales"), cells, today=today, holidays=holidays)
- for row in table:
- row["roas"] = roas(row["cells"]["sales"]["gross"], row["cells"]["spend"]["gross"])
- cur = {c: calc.sum_range(cells, [c], period.start, period.end).gross for c in ("spend", "sales")}
- prev = {c: calc.sum_range(cells, [c], cmp_start, cmp_end).gross for c in ("spend", "sales")}
- word = _period_word(period, today)
- spend_y = calc.year_months(year_period.start.year, ["spend"], cells, today=today)
- sales_y = calc.year_months(year_period.start.year, ["sales"], cells, today=today)
- year_rows = [{"label": a["label"], "future": a["future"], "spend": a["gross"], "sales": b["gross"],
- "roas": None if a["future"] else roas(b["gross"], a["gross"])}
- for a, b in zip(spend_y["rows"], sales_y["rows"])]
- return {
- "nav": _period_nav(period, today),
- "period": period,
- "period_kind": period.kind,
- "today": today.isoformat(),
- "kpis": [
- {"key": "spend", "label": f"{word} 광고비", "value": cur["spend"], "primary": True,
- "delta": calc.pct_change(cur["spend"], prev["spend"]), "cmp": cmp_label, "invert": True},
- {"key": "sales", "label": f"{word} 매출", "value": cur["sales"],
- "delta": calc.pct_change(cur["sales"], prev["sales"]), "cmp": cmp_label},
- {"key": "roas", "label": f"{word} ROAS", "pct": roas(cur["sales"], cur["spend"])},
- ],
- "table": table,
- "chart_sales": calc.daily_series(period, ["sales"], cells),
- "chart_spend": calc.daily_series(period, ["spend"], cells),
- "year": {"year": year_period.start.year, "rows": year_rows, "spend": spend_y["total"]["gross"], "sales": sales_y["total"]["gross"],
- "roas": roas(sales_y["total"]["gross"], spend_y["total"]["gross"])},
- "migration_needed": migration_needed,
- }
-
-
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
custom_from: date | None = None, custom_to: date | None = None,
holidays: Mapping[str, str] | None = None,
sales_codes: Sequence[str] = ()) -> dict[str, Any]:
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
- codes = list(CHANNEL_CODES)
+ names = channel_names()
+ codes = list(names)
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
cmp_start, cmp_end, cmp_label = period.compare_range(today)
ref = period.end if period.end < today else today if period.start <= today else period.start
@@ -594,7 +553,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
total_codes = list(sales_codes)
- need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes))
+ need = sorted({m for ms in roas_sales().values() for m in ms} | set(total_codes))
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
@@ -609,7 +568,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
- "note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
+ "note": f"총매출 {variant.money_text(sales_total)}" if sales_total else "매출 없음"},
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
]
@@ -641,7 +600,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"period_kind": period.kind,
"today": today.isoformat(),
"codes": codes,
- "names": dict(CHANNEL_NAMES),
+ "names": names,
"kpis": kpis,
"table": table,
"month": month,
@@ -649,7 +608,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"roas_basis": {c: roas_basis(c) for c in codes},
"detail_channels": sorted(DETAIL_CHANNELS),
"chart_daily": calc.daily_series(period, codes, cells),
- "chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
+ "chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
# 업로드로 들어온 칸(표시용) — "날짜|채널"
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
if s == "upload" and period.start <= d <= period.end),
@@ -660,7 +619,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"formula_cells": {f"{d.isoformat()}|{c}": f for (d, c), f in
(store.ad_formulas(period.start, period.end) if hasattr(store, "ad_formulas")
and not migration_needed else {}).items()},
- "upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
+ "upload_channels": [{"code": c, "name": names[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS if c in names],
"migration_needed": migration_needed,
# 날짜 칸 메모(마이그레이션 010) — "날짜|채널" → 메모
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
diff --git a/app/modules/performance/common.py b/app/modules/performance/common.py
index a710a6e..bf1f3da 100644
--- a/app/modules/performance/common.py
+++ b/app/modules/performance/common.py
@@ -12,7 +12,9 @@ from typing import Any
from fastapi import HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
-MODULE_KEY = "performance"
+from . import variant
+
+MODULE_KEY = "performance" # 한국 실적 — 요청마다는 variant.current().module_key(말레이시아 실적 = malaysia_performance)
MODULE_NAME = "실적"
CONFIG_HELP = (
@@ -20,10 +22,19 @@ CONFIG_HELP = (
"scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 "
"PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
)
+CONFIG_HELP_MY = (
+ "말레이시아 실적 모듈이 아직 설정되지 않았습니다. "
+ "app/modules/malaysia_performance/CLAUDE.md 대로 malaysia_performance_db 를 만들고 "
+ "MALAYSIA_PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
+)
+
+
+def config_help() -> str:
+ return CONFIG_HELP if variant.current().is_kr else CONFIG_HELP_MY
def get_store(request: Request) -> Any:
- return getattr(request.app.state, "performance_store", None)
+ return getattr(request.app.state, variant.current().store_attr, None)
def key_ring():
@@ -60,8 +71,9 @@ def require_user(request: Request) -> dict[str, Any]:
user = get_current_user_record(request)
if user is None:
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
- if not has_module(user, MODULE_KEY):
- raise HTTPException(status_code=403, detail=f"{MODULE_NAME} 모듈 권한이 없습니다.")
+ v = variant.current()
+ if not has_module(user, v.module_key):
+ raise HTTPException(status_code=403, detail=f"{v.module_name} 모듈 권한이 없습니다.")
return user
@@ -78,7 +90,7 @@ def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[s
user = require_admin(request) if admin else require_user(request)
st = get_store(request)
if st is None:
- raise HTTPException(status_code=503, detail=CONFIG_HELP)
+ raise HTTPException(status_code=503, detail=config_help())
return st, user
@@ -90,8 +102,9 @@ def guard(request: Request, *, admin: bool = False):
user = get_current_user_record(request)
if user is None:
return login_redirect(request)
- if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
- reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
+ v = variant.current()
+ if not has_module(user, v.module_key) or (admin and not is_admin(user)):
+ reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{v.module_name} 접근 권한이 없습니다."
return render_template(request, "denied.html",
{"reason": reason, "user": user, "is_admin": is_admin(user)}, status_code=403)
st = get_store(request)
@@ -106,21 +119,25 @@ def render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse
return render_template(
request, "denied.html",
- {"reason": CONFIG_HELP, "user": user, "is_admin": is_admin(user),
- "nav_items": build_erp_nav(user, active=MODULE_KEY)},
+ {"reason": config_help(), "user": user, "is_admin": is_admin(user),
+ "nav_items": build_erp_nav(user, active=variant.current().module_key)},
status_code=503,
)
-def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "실적") -> dict[str, Any]:
+def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "") -> dict[str, Any]:
from app.main import build_erp_nav # noqa: WPS433
from app.store import is_admin # noqa: WPS433
+ v = variant.current()
+ if not v.is_kr and page_title:
+ page_title = f"말레이시아 {page_title}"
return {
"user": user,
"is_admin": is_admin(user),
- "nav_items": build_erp_nav(user, active=MODULE_KEY),
+ "nav_items": build_erp_nav(user, active=v.module_key),
"active_tab": active_tab,
- "page_title": page_title,
- "page_subtitle": "쇼핑몰 통합 매출",
+ "page_title": page_title or v.module_name,
+ "page_subtitle": "쇼핑몰 통합 매출" if v.is_kr else "틱톡·쇼피·라자다 매출",
+ **variant.template_ctx(),
}
diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py
index 014cd60..c5e81d4 100644
--- a/app/modules/performance/dashboard.py
+++ b/app/modules/performance/dashboard.py
@@ -145,12 +145,21 @@ def load_hidden(store: Any) -> set[str]:
return set(_shared_setting(store, HIDDEN_SETTING) or ())
+RM_UNIT = "rm" # 말레이시아 실적(2026-11-20) — 금액 = 센 정수, 화면 = RM 소수 2자리(단위 설정 없음)
+
+
def load_unit(store: Any) -> str:
+ from . import variant # noqa: WPS433
+
+ if not variant.current().is_kr:
+ return RM_UNIT
return normalize_unit(_shared_setting(store, UNIT_SETTING))
def amount_text(value: Any, unit: str = "won") -> str:
- """금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
+ """금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림), RM 은 센 ÷ 100 소수 두 자리."""
+ if unit == RM_UNIT:
+ return f"{(Decimal(int(value)) / 100).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,.2f}"
div, places, _ = UNITS[normalize_unit(unit)]
if div == 1:
return f"{int(value):,}"
@@ -219,8 +228,10 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타·카톡 플친(자사몰 광고), 네이버 = 네이버 광고,
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
- from . import ad_spend # noqa: WPS433
+ from . import ad_spend, variant # noqa: WPS433
+ if variant.current().ad_lines: # 말레이시아 실적 — 쇼핑몰 그룹(합계) 칸 아래에 그 쇼핑몰 광고비
+ return dict(variant.current().ad_lines)
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친")), "naver": (("naver", ""),)}
for ch, c in ad_spend.ROAS_SALES_CODE.items():
out[c] = out.get(c, ()) + ((ch, ""),)
@@ -320,7 +331,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
r["total"] = s["total"]
if "cafe24" in codes:
r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"]
- _ad_lines(store, table, codes, cells, period, q_start, q_end)
+ _ad_lines(store, table, [*codes, *group_members], cells, period, q_start, q_end)
for r in table:
for g, members in group_members.items():
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
diff --git a/app/modules/performance/formula.py b/app/modules/performance/formula.py
index e6b8aec..55035ac 100644
--- a/app/modules/performance/formula.py
+++ b/app/modules/performance/formula.py
@@ -80,12 +80,13 @@ class _Parser:
return Decimal(tok)
-def parse_amount(raw: object) -> tuple[int | None, str | None]:
- """칸 입력 → (원 단위 금액, 계산식). 빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음."""
+def parse_amount(raw: object, scale: int = 1) -> tuple[int | None, str | None]:
+ """칸 입력 → (저장 단위 금액, 계산식). scale=100 = 센(말레이시아 실적 RM 소수 2자리 — 12.5 → 1250).
+ 빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음."""
text = str(raw if raw is not None else "").strip()
for a, b in _OPS.items():
text = text.replace(a, b)
- text = re.sub(r"[,\s원]", "", text)
+ text = re.sub(r"[,\s원]|RM", "", text, flags=re.IGNORECASE)
if text.startswith("="): # 엑셀 버릇으로 = 를 붙여도 된다
text = text[1:]
if text == "":
@@ -100,7 +101,7 @@ def parse_amount(raw: object) -> tuple[int | None, str | None]:
raise FormulaError("계산할 수 없는 식입니다.") from None
if p.peek() is not None:
raise FormulaError("계산식이 올바르지 않습니다.")
- amount = int(value.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
+ amount = int((value * scale).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
# 숫자 하나(앞 부호만 있는 것 포함)는 계산식이 아니다
is_formula = any(t in "+-*/()" for t in tokens[1:]) or (tokens[0] == "(")
return amount, (text if is_formula else None)
diff --git a/app/modules/performance/manual_upload.py b/app/modules/performance/manual_upload.py
index 34a1692..cd8bf73 100644
--- a/app/modules/performance/manual_upload.py
+++ b/app/modules/performance/manual_upload.py
@@ -77,8 +77,8 @@ def parse_date(value: Any) -> date | None:
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
-def parse_amount(value: Any) -> int | None:
- """금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError."""
+def parse_amount(value: Any, scale: int = 1) -> int | None:
+ """금액 칸 → 저장 단위 정수(원, scale=100 이면 센 — 말레이시아 실적 RM 소수 2자리). 빈 칸이면 None, 숫자가 아니면 ValueError."""
if value is None or isinstance(value, bool):
if value is None:
return None
@@ -86,7 +86,7 @@ def parse_amount(value: Any) -> int | None:
if isinstance(value, (int, float, Decimal)):
num = Decimal(str(value))
else:
- text = re.sub(r"[,\s원₩]", "", str(value))
+ text = re.sub(r"[,\s원₩]|RM", "", str(value), flags=re.IGNORECASE)
if text == "":
return None
try:
@@ -95,7 +95,7 @@ def parse_amount(value: Any) -> int | None:
raise ValueError from None
if not num.is_finite():
raise ValueError
- return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
+ return int((num * scale).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
@@ -111,7 +111,7 @@ def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[st
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
- extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult:
+ extra_names: Mapping[str, Iterable[str]] | None = None, scale: int = 1) -> ParseResult:
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
if not content:
raise UploadError("빈 파일입니다.")
@@ -160,7 +160,7 @@ def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: d
amounts: dict[int, int] = {}
for i, raw in cells.items():
try:
- amt = parse_amount(raw)
+ amt = parse_amount(raw, scale)
except ValueError:
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
continue
diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py
index 2b1efe2..d580e16 100644
--- a/app/modules/performance/router.py
+++ b/app/modules/performance/router.py
@@ -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})
diff --git a/app/modules/performance/templates/performance/_ad_update.html b/app/modules/performance/templates/performance/_ad_update.html
index fa9aa05..1c01b5b 100644
--- a/app/modules/performance/templates/performance/_ad_update.html
+++ b/app/modules/performance/templates/performance/_ad_update.html
@@ -1,4 +1,4 @@
-{# 광고비 업데이트(2026-10-20, 광고비·틱톡 탭 공통) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
+{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %}
diff --git a/app/modules/performance/templates/performance/_tabs.html b/app/modules/performance/templates/performance/_tabs.html
index e9b2b98..ce9b4af 100644
--- a/app/modules/performance/templates/performance/_tabs.html
+++ b/app/modules/performance/templates/performance/_tabs.html
@@ -1,19 +1,16 @@
-{# 실적 모듈 탭 — [매출 실적] [광고비] [틱톡] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
+{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
-
@@ -169,7 +175,7 @@
{{ year.year }}년 누적 광고비
-
광고비₩{{ "{:,}".format(year.total.gross) }}
+
광고비{{ money_t(year.total.gross) }}
@@ -195,12 +201,18 @@
+ {% if pv.is_kr %}
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다.
+ {% else %}
+
+ 금액 단위 RM. ROAS = 그 쇼핑몰(쇼핑몰 + 라이브커머스) 매출 ÷ 광고비 × 100. 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
+
+ {% endif %}
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index d55f12b..96a5251 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}
@@ -9,7 +9,7 @@
{%- endmacro -%}
{#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#}
{%- macro money(v) -%}
- {%- if unit == 'won' -%}₩{{ amt(v) }}{%- else -%}{{ amt(v) }}{{ unit_label }}{%- endif -%}
+ {%- if unit == 'won' -%}₩{{ amt(v) }}{%- elif unit == 'rm' -%}RM {{ amt(v) }}{%- else -%}{{ amt(v) }}{{ unit_label }}{%- endif -%}
{%- endmacro -%}
{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#}
{%- macro adl(lines) -%}
@@ -30,7 +30,7 @@
{%- endmacro -%}
{% block content %}
-
+
{% include "performance/_tabs.html" %}
@@ -44,7 +44,7 @@
{% include "performance/_period_nav.html" %}
-
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html
index 622fc0e..5f2e77c 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -1,15 +1,16 @@
{% extends "erp_base.html" %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
{% block content %}
-
+
{% include "performance/_tabs.html" %}
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
- {% if is_admin and not key_info.ok %}
+ {% set api_cols = pv.is_kr %}{#- 말레이시아 실적 = 수동 입력만(API 연동·연결 상태·동기화 칸 없음) -#}
+ {% if is_admin and pv.is_kr and not key_info.ok %}
암호화 마스터 키가 없습니다. {{ key_info.message }}
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
@@ -20,8 +21,9 @@
쇼핑몰 설정
{% if is_admin %}
- 사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
+ {% if api_cols %}사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있고, API 가 설정돼 있어도 매출 업데이트(수동·자동)에서 빠집니다.
+ {% else %}사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. 매출은 매출 실적 일자별 표의 날짜 칸에 직접 입력합니다(RM, 소수 2자리).{% endif %}
{% else %}
쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.
{% endif %}
@@ -35,9 +37,9 @@
수수료율은 적용 시작일부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
- {% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
+ {% if is_admin and api_cols %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
@@ -169,6 +171,7 @@
공통 보기 설정
모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.
+ {% if pv.is_kr %}{#- 말레이시아 실적은 RM 고정 -#}
매출 단위
@@ -180,6 +183,7 @@
예: 2,475,300원 →
{% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}
+ {% endif %}
숨길 쇼핑몰
@@ -192,7 +196,7 @@
{% endif %}
- {% if is_admin and auto_sync_settings %}
+ {% if is_admin and pv.is_kr and auto_sync_settings %}
{# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위,
기본 30분). [저장] = PUT /api/auto-sync-schedule, 스레드(auto_sync.py)가 1분 안에 반영. #}
{% set au = auto_sync_settings %}
@@ -249,13 +253,13 @@
{% endif %}
- {% if is_admin %}
+ {% if is_admin and pv.is_kr %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
광고 API 연동
- 광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 틱톡은 틱톡 탭에서만 보입니다(매출 실적·광고비 탭 합계 제외). 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
+ 광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.
{% if not ad_api_ready %}
@@ -347,4 +351,4 @@
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/templates/performance/tiktok.html b/app/modules/performance/templates/performance/tiktok.html
deleted file mode 100644
index 85c0b8a..0000000
--- a/app/modules/performance/templates/performance/tiktok.html
+++ /dev/null
@@ -1,155 +0,0 @@
-{% extends "erp_base.html" %}
-
-{% block head_extra %}{% endblock %}
-
-{%- macro won(v) -%}
- {%- if v is none -%}
- {%- elif v == 0 -%}–
- {%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
-{%- endmacro -%}
-{%- macro pct(p) -%}{%- if p is none -%}–{%- else -%}{{ "{:,}".format(p) }}%{%- endif -%}{%- endmacro -%}
-
-{% block content %}
-{#- 틱톡(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프. 값은 광고 API 만(읽기 전용, 직접 입력 없음). 매출 실적·광고비 탭 합계에는 안 들어간다. -#}
-
- {% include "performance/_tabs.html" %}
-
-
-
- {% for q in nav.quick %}
- {{ q.label }}
- {% endfor %}
-
-
-
- {% include "performance/_period_nav.html" %}
-
-
-
-
- ~
-
-
-
-
- {% include "performance/_ad_update.html" %}
-
-
-
- {% if migration_needed %}
-
광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005·006 을 적용해야 합니다.
- {% endif %}
- {% if not tiktok_configured %}
-
틱톡 API 가 아직 설정되지 않았습니다. {% if is_admin %}실적 설정 → 광고 API 연동에서{% else %}관리자가 실적 설정 → 광고 API 연동에서{% endif %} 틱톡 [설정]을 입력하면 데이터가 들어옵니다.
- {% endif %}
-
-
- {% for k in kpis %}
-
- {{ k.label }}
- {% if k.key == 'roas' %}
- {{ pct(k.pct) }}
- {% else %}
- ₩{{ "{:,}".format(k.value) }}
- {% if k.delta is none %}{{ k.cmp }} 비교 없음
- {% else %}
- {% set up = k.delta > 0 %}
-
- {% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%
- {{ k.cmp }} 대비
- {% endif %}
- {% endif %}
-
- {% endfor %}
-
- 틱톡 광고 API 값입니다. 매출 = 광고에 귀속된 구매금액(웹 구매 + 틱톡샵, 틱톡샵 ID 를 넣으면 GMV Max 포함)이며 틱톡샵 전체 판매액과는 다를 수 있습니다.
- ROAS = 매출 ÷ 광고비 × 100, 외화 계정은 그날 환율로 원화로 바꿉니다. 이 값은 매출 실적·광고비 탭 합계에 들어가지 않습니다.
- [광고비 업데이트]는 설정된 광고 API 전부를 함께 가져옵니다.
-
-
-
-
-{% endblock %}
-
-{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/tests/test_malaysia_variant.py b/app/modules/performance/tests/test_malaysia_variant.py
new file mode 100644
index 0000000..224d9f9
--- /dev/null
+++ b/app/modules/performance/tests/test_malaysia_variant.py
@@ -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("", 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
diff --git a/app/modules/performance/tests/test_tiktok_ads.py b/app/modules/performance/tests/test_tiktok_ads.py
deleted file mode 100644
index 9cc43dd..0000000
--- a/app/modules/performance/tests/test_tiktok_ads.py
+++ /dev/null
@@ -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("광고비") < tabs.index("틱톡") and "perf-tab-tiktok is-active" in tabs
- head = html.split("", 1)[1].split("", 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
diff --git a/app/modules/performance/variant.py b/app/modules/performance/variant.py
new file mode 100644
index 0000000..61fad66
--- /dev/null
+++ b/app/modules/performance/variant.py
@@ -0,0 +1,87 @@
+"""실적 모듈 인스턴스(2026-11-20) — 같은 코드·화면으로 [실적](한국)과 [말레이시아 실적]을 띄운다.
+
+app.main 이 router 를 두 번 붙인다: /performance(한국, 기본값) · /malaysia/performance(말레이시아 — 마운트 의존성
+use_malaysia 가 이 요청의 ContextVar 를 MY 로). 저장소·권한키·주소·광고 채널·통화는 current() 로 읽는다.
+데이터는 DB 로 나뉜다(같은 표 구조 — malaysia_performance_db, app/modules/malaysia_performance/CLAUDE.md).
+"""
+
+from __future__ import annotations
+
+from contextvars import ContextVar
+from dataclasses import dataclass, field
+from decimal import ROUND_HALF_UP, Decimal
+from typing import Any
+
+
+@dataclass(frozen=True)
+class Variant:
+ key: str # kr | my
+ base: str # 주소 앞부분(템플릿·JS 가 이 뒤에 /api/… 를 붙인다)
+ module_key: str # 권한키
+ module_name: str # 메뉴·탭 이름
+ store_attr: str # app.state 저장소 이름
+ db_name: str # 안내 문구용
+ scale: int = 1 # 금액 저장 단위 — 1 = 원, 100 = 센(RM 소수 2자리를 정수로 저장해 계산은 그대로)
+ currency: str = "₩"
+ # 광고비 탭 채널 — 비면 한국 실적 채널(ad_spend.CHANNELS)
+ ad_channels: tuple[tuple[str, str], ...] = ()
+ # 광고 채널 → ROAS 매출 쇼핑몰 코드들(합계) · 매출 실적 열(그룹) → 그 칸 아래 광고비 줄 [(채널, 줄 이름)]
+ ad_roas_sales: dict[str, tuple[str, ...]] = field(default_factory=dict)
+ ad_lines: dict[str, tuple[tuple[str, str], ...]] = field(default_factory=dict)
+
+ @property
+ def is_kr(self) -> bool:
+ return self.key == "kr"
+
+
+KR = Variant("kr", "/performance", "performance", "실적", "performance_store", "performance_db")
+
+# 쇼핑몰마다 그룹(합계 열) + 쇼핑몰·라이브커머스 하위 2개 — 코드는 scripts/sql/malaysia_performance_db_seed.sql 과 같다
+_MY_SHOPS = (("tiktok", "틱톡"), ("shopee", "쇼피"), ("lazada", "라자다"))
+MY = Variant(
+ "my", "/malaysia/performance", "malaysia_performance", "말레이시아 실적", "malaysia_performance_store",
+ "malaysia_performance_db", scale=100, currency="RM",
+ ad_channels=_MY_SHOPS,
+ ad_roas_sales={c: (f"custom_{c}_shop", f"custom_{c}_live") for c, _ in _MY_SHOPS},
+ ad_lines={f"group_{c}": ((c, ""),) for c, _ in _MY_SHOPS},
+)
+
+_current: ContextVar[Variant] = ContextVar("perf_variant", default=KR)
+
+
+def current() -> Variant:
+ return _current.get()
+
+
+async def use_malaysia() -> None:
+ """말레이시아 마운트 의존성 — async 라 요청 태스크 컨텍스트에 설정되고 동기 핸들러(스레드풀)로 복사된다."""
+ _current.set(MY)
+
+
+def num_text(value: Any) -> str:
+ """금액(저장 단위 정수) → 쉼표 숫자. 원 = 정수, 센 = RM 소수 2자리."""
+ v = current()
+ if v.scale == 1:
+ return f"{int(value or 0):,}"
+ return f"{(Decimal(int(value or 0)) / v.scale).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,.2f}"
+
+
+def money_text(value: Any) -> str:
+ """통화 기호 붙인 금액 — ₩1,234 / RM 1,234.50."""
+ v = current()
+ return f"₩{num_text(value)}" if v.scale == 1 else f"{v.currency} {num_text(value)}"
+
+
+def input_text(value: Any) -> str:
+ """날짜 칸 편집창에 보일 값(쉼표 없음) — 빈 값은 빈 글자."""
+ if value in (None, ""):
+ return ""
+ v = current()
+ if v.scale == 1:
+ return str(int(value))
+ return f"{Decimal(int(value)) / v.scale:.2f}"
+
+
+def template_ctx() -> dict[str, Any]:
+ """모든 실적 화면 공통 — pv(인스턴스), num·money·inval(금액 글자)."""
+ return {"pv": current(), "num": num_text, "money_t": money_text, "inval": input_text}
diff --git a/app/static/performance.css b/app/static/performance.css
index 11d4bbe..a83f3fc 100644
--- a/app/static/performance.css
+++ b/app/static/performance.css
@@ -43,7 +43,6 @@
.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); }
.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); }
-.perf-tab-tiktok.is-active, .perf-tab-tiktok.is-active:hover { background: var(--perf-tiktok, #e11d48); }
a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-tab-gear {
margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;
@@ -60,10 +59,6 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */
.perf-ads td.is-api .v-gross { color: #1e8e3e; }
-/* 틱톡 화면 — 광고비 화면 틀에 색만 바꿈 */
-.perf, .perf-modal { --perf-tiktok: #e11d48; }
-.perf-tiktok .perf-quick .perf-seg.is-active { background: var(--perf-tiktok); }
-.perf-tiktok .perf-chart .bar { fill: var(--perf-tiktok); }
.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */
.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; }
diff --git a/app/static/performance.js b/app/static/performance.js
index aad0396..67f80e6 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -1,6 +1,8 @@
/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작.
*
- * 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(/performance/api/…)로만.
+ * 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(BASE/api/…)로만.
+ * 같은 화면이 [실적](/performance)과 [말레이시아 실적](/malaysia/performance, 2026-11-20)에 쓰인다 — 주소는 .perf data-base,
+ * 말레이시아는 data-cents(금액 = 센 정수, 화면 = RM 소수 2자리).
* 인증정보 창은 저장된 비밀값을 받지 않는다(서버가 "저장됨" 여부만 준다).
*/
(function () {
@@ -22,17 +24,26 @@
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
});
}
+ const PERF_ROOT = document.querySelector(".perf");
+ const BASE = (PERF_ROOT && PERF_ROOT.dataset.base) || "/performance";
+ const CENTS = !!(PERF_ROOT && PERF_ROOT.dataset.cents); // 말레이시아 실적 — 금액 = 센(0.01 RM) 정수
+ const CUR = CENTS ? "RM" : "원";
function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
- function won(n) { return n ? fmt(n) : '–'; }
+ // 금액(저장 단위) → 글자. 원 = 정수, 센 = RM 소수 2자리(서버 variant.num_text 와 같음)
+ function money(n) {
+ return CENTS ? (Number(n || 0) / 100).toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : fmt(n);
+ }
+ function won(n) { return n ? money(n) : '–'; }
// 매출 단위(실적 설정 "공통 보기 설정", 모든 사용자 같음) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리)
function unitWon(n, unit) {
if (!n) return won(0);
if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR");
if (unit === "million") return (Math.round(n / 100000) / 10).toLocaleString("ko-KR", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
- return fmt(n);
+ return money(n);
}
// 축 눈금용 짧은 금액(1.2억 / 350만)
function short(n) {
+ if (CENTS) n = Math.round(n / 100);
const a = Math.abs(n), s = n < 0 ? "-" : "";
if (a >= 100000000) return s + (a / 100000000).toFixed(a >= 1000000000 ? 0 : 1).replace(/\.0$/, "") + "억";
if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만";
@@ -179,7 +190,7 @@
b.disabled = true;
b.textContent = "중지하는 중…";
try {
- const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
+ const r = await api("POST", BASE + "/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
encodeURIComponent(b.dataset.stop) + "/stop");
last = r.job;
renderSyncJob(m.body, r.job, false);
@@ -197,7 +208,7 @@
cancelBtn.disabled = true;
cancelBtn.textContent = "취소하는 중…";
try {
- const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel");
+ const r = await api("POST", BASE + "/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel");
last = r.job;
renderSyncJob(m.body, r.job, false);
} catch (err) {
@@ -207,7 +218,7 @@
}
});
(existing ? Promise.resolve({ job: existing, joined: true })
- : api("POST", startUrl || "/performance/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
+ : api("POST", startUrl || BASE + "/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
last = res.job;
jobId = res.job.id;
const joined = res.joined;
@@ -217,7 +228,7 @@
async function poll() {
if (closed) return;
try {
- const r = await api("GET", "/performance/api/sync/jobs/" + encodeURIComponent(res.job.id));
+ const r = await api("GET", BASE + "/api/sync/jobs/" + encodeURIComponent(res.job.id));
last = r.job;
renderSyncJob(m.body, r.job, joined);
if (r.job.finished) {
@@ -399,7 +410,7 @@
if (colw) colw.apply();
folded = folded.filter(function (c) { return c !== col; });
if (fold) folded.push(col);
- api("PUT", "/performance/api/my-col-fold", { kind: table.dataset.cfoldKind, cols: folded })
+ api("PUT", BASE + "/api/my-col-fold", { kind: table.dataset.cfoldKind, cols: folded })
.catch(function (err) { alertMsg("접은 열을 저장하지 못했습니다: " + err.message); });
});
}
@@ -408,7 +419,7 @@
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
- const MANUAL_API = data.manual_api || "/performance/api/manual-sales/";
+ const MANUAL_API = data.manual_api || BASE + "/api/manual-sales/";
const MANUAL_WORD = data.manual_word || "총매출";
const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다.";
@@ -421,7 +432,6 @@
b.classList.toggle("is-active", b.dataset.metric === m);
});
drawDaily(m, "perf-chart-daily", data.daily);
- drawDaily(m, "perf-chart-daily2", data.daily2); // 틱톡 탭 — 매출·광고비 두 그래프
drawShare(m);
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
}
@@ -498,7 +508,7 @@
'
1열에 날짜, 2열부터 쇼핑몰 이름을 머리글로 적고 그날 총매출을 넣습니다. ' +
"값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.