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" %} - + ~ @@ -55,7 +55,7 @@
쇼핑몰: {% if selected_all %}전체{% else %}{{ codes | length }}곳{% endif %} - + {% if period_kind == 'custom' %} @@ -73,6 +73,7 @@
+ {% if pv.is_kr %}{#- 말레이시아 실적은 API 수집 없음(수동 입력만) — 업데이트 줄 없음 -#}
마지막 업데이트 {{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }} @@ -86,10 +87,11 @@ {% if running %}업데이트 중 · 진행 보기{% else %}매출 업데이트{% endif %}
+ {% endif %} {% if no_marketplaces %} -
매출에 포함된 쇼핑몰이 없습니다. {% if is_admin %}실적 설정에서 쇼핑몰 사용을 켜세요.{% endif %}
+
매출에 포함된 쇼핑몰이 없습니다. {% if is_admin %}{{ pv.module_name }} 설정에서 쇼핑몰 사용을 켜세요.{% endif %}
{% endif %} {% if problems %} @@ -127,7 +129,7 @@

{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}

{% if unit != 'won' %}단위: {{ unit_label }}{% endif %} - 광고비(ROAS%) + 광고비(ROAS%) {% if manual_upload_names %} @@ -170,7 +172,7 @@ {% set gattr %}{% if sub %} data-group-child="{{ col.group }}"{% endif %}{% endset %} {% set gc0 %}{% if sub %}
{% endif %}{% endset %}{% set gc1 %}{% if sub %}
{% endif %}{% endset %} {% if col.kind == 'group' %} -
+ {% elif col.kind == 'diff' %}{#- 카페24(실적) = 카페24(전체) − 공동구매(dashboard._cafe24_real_column) — 계산 열이라 클릭·메모 없음, 광고비 줄은 카페24(전체)와 같음 -#} {%- set b = r.cells[col.base] %}{#- 일 행 = 공동구매 칸 저장 때 performance.js 가 base(카페24 총매출,수수료,차감) − 새 값으로 바로 바꿈 -#} @@ -179,7 +181,7 @@ {% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %} {% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) — 우클릭 메모 삽입·수정·삭제, 있으면 칸 오른쪽 위 빨간 삼각형 -#} + data-manual-value="{{ inval(m.gross) if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0">{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }} {% else %} {#- 메모(2026-10-22) — API 쇼핑몰 날짜 칸도 우클릭 메모(data-memo-code). 왼쪽 클릭은 그대로 주문 내역 -#} {% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) if r.kind == 'day' else none %} @@ -194,7 +196,7 @@ {% if manual_codes and period_kind != 'year' %}

✎ 표시 쇼핑몰은 날짜 칸을 눌러 총매출을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, - 비우고 저장하면 다시 API 수집값. 1000+2000 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.

+ 비우고 저장하면 {% if pv.is_kr %}다시 API 수집값{% else %}지움{% endif %}. {{ '1000+2000' if pv.is_kr else '10.5+20' }} 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.

{% endif %} @@ -278,11 +280,18 @@ + {% if pv.is_kr %}

매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며 일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다. 일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).

+ {% else %} +

+ 금액 단위 RM(소수 2자리). 쇼핑몰마다 쇼핑몰 매출과 라이브커머스 매출을 따로 입력하고, 쇼핑몰 그룹 열 = 두 매출 합계입니다. + 수수료는 그날 적용되는 수수료율로 계산하며 센(0.01 RM) 미만 반올림합니다. 일 합계·상단 금액·그래프·누적 = 모든 쇼핑몰·라이브커머스 합계. +

+ {% endif %} {% 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 @@
{% endif %} - {% if is_admin %} + {% if is_admin and api_cols %}{% endif %} - + {% if api_cols %}{% endif %} {% if is_admin %}{% endif %} @@ -51,7 +53,7 @@ {% if is_admin %}{% endif %} {{ r.name }}그룹 - + {% if is_admin %} - {% if is_admin %} + {% if is_admin and api_cols %} {% endif %} - + {% if api_cols %}{% endif %} {% if is_admin %} ", 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열부터 쇼핑몰 이름을 머리글로 적고 그날 총매출을 넣습니다. ' + "값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.

" + '

입력 가능한 쇼핑몰: ' + (shops || "없음") + "

" + - '

' + + '

' + "샘플 파일 받기

" + '' + '
'; @@ -518,7 +528,7 @@ fd.append("file", f); let res, body = null; try { - res = await fetch("/performance/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd }); + res = await fetch(BASE + "/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd }); try { body = await res.json(); } catch (_) { body = null; } } catch (err) { out.innerHTML = '

업로드 실패: ' + esc(err.message) + "

"; @@ -588,7 +598,7 @@ }); let res, body = null; try { - res = await fetch("/performance/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value), + res = await fetch(BASE + "/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value), { method: "POST", credentials: "same-origin", body: fd }); try { body = await res.json(); } catch (_) { body = null; } } catch (err) { @@ -624,7 +634,7 @@ let running = false; try { let cur = null; - try { cur = (await api("GET", "/performance/api/ad-sync/current")).job; } catch (_) { cur = null; } + try { cur = (await api("GET", BASE + "/api/ad-sync/current")).job; } catch (_) { cur = null; } let job; if (cur && !cur.finished) { job = await runSyncWithProgress(null, "광고비 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur); @@ -632,7 +642,7 @@ const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today; if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다."); job = await runSyncWithProgress({ from: from, to: to }, "광고비 업데이트 " + from + " ~ " + to, null, - "/performance/api/ad-sync"); + BASE + "/api/ad-sync"); } running = !!(job && !job.finished); const ok = [], bad = [], other = []; @@ -681,7 +691,7 @@ const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true }); m.body.innerHTML = '

불러오는 중…

'; try { - const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" + + const res = await api("GET", BASE + "/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" + encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end)); if (!res.rows || !res.rows.length) { m.body.innerHTML = '

이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).

'; return; } const cols = res.columns || []; @@ -770,7 +780,7 @@ try { // 이미 돌고 있는 업데이트(다른 사람·자동 업데이트 포함)가 있으면 새로 시작하지 않고 그 진행 창을 다시 연다 let cur = null; - try { cur = (await api("GET", "/performance/api/sync/current")).job; } catch (_) { cur = null; } + try { cur = (await api("GET", BASE + "/api/sync/current")).job; } catch (_) { cur = null; } let job; if (cur && !cur.finished) { job = await runSyncWithProgress(null, "매출 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur); @@ -855,7 +865,7 @@ }, 120); } function saveManual(td, text) { - const raw = String(text || "").replace(/[,\s원]/g, "").replace(/^=/, ""); + const raw = String(text || "").replace(/[,\s원]|RM/gi, "").replace(/^=/, ""); if (raw !== "" && !/^[-+*/().\d×÷xX]+$/.test(raw)) { return Promise.reject(new Error("숫자 또는 1000+2000 같은 계산식만 입력하세요.")); } @@ -864,7 +874,7 @@ return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" + encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : raw }); }).then(function (res) { - const manual = res.manual == null ? "" : String(res.manual); + const manual = res.manual == null ? "" : CENTS ? (res.manual / 100).toFixed(2) : String(res.manual); td.dataset.manualValue = manual; if (res.formula) td.dataset.formula = res.formula; else delete td.dataset.formula; td.classList.toggle("is-manual", manual !== ""); @@ -960,7 +970,7 @@ td.classList.toggle("has-memo", !!memo); } async function saveMemo(td, memo) { - const res = await api("PUT", "/performance/api/cell-memos/" + encodeURIComponent(MEMO_KIND) + "/" + + const res = await api("PUT", BASE + "/api/cell-memos/" + encodeURIComponent(MEMO_KIND) + "/" + encodeURIComponent(td.dataset.memoCode) + "/" + encodeURIComponent(td.dataset.date), { memo: memo }); setCellMemo(td, res.memo || ""); } @@ -1037,7 +1047,7 @@ const m = openModal(title, { wide: true }); // 넓은 창 + 상품명 줄바꿈 → 가로 스크롤 없이 m.body.innerHTML = '

불러오는 중…

'; try { - const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) + + const res = await api("GET", BASE + "/api/events?code=" + encodeURIComponent(code) + "&from=" + encodeURIComponent(from) + "&to=" + encodeURIComponent(to)); const rows = res.rows || []; if (!rows.length) { m.body.innerHTML = '

내역이 없습니다.

'; return; } @@ -1135,7 +1145,7 @@ const x = L + i * bw + bw * 0.15, w = Math.max(1, bw * 0.7); const y0 = y(0), y1 = y(v); g += '' + esc(p.label) + " " + fmt(v) + "원"; + '" width="' + w + '" height="' + Math.max(0.5, Math.abs(y1 - y0)) + '">' + esc(p.label) + " " + money(v) + " " + CUR + ""; if (i % every === 0) g += '' + esc(p.label) + ""; }); g += ''; @@ -1155,8 +1165,8 @@ const w = Math.max(0, (W - L - R) * Math.max(0, v) / maxV); const pct = total > 0 ? (Math.max(0, v) / total * 100).toFixed(1) : "0.0"; g += '' + esc(r.name) + "" + - '' + esc(r.name) + " " + fmt(v) + "원" + - '' + fmt(v) + " (" + pct + "%)"; + '' + esc(r.name) + " " + money(v) + " " + CUR + "" + + '' + money(v) + " (" + pct + "%)"; }); box.innerHTML = svg(W, H, g); } @@ -1201,7 +1211,7 @@ if (pending || asking || document.hidden) return; asking = true; try { - const st = await api("GET", "/performance/api/update-status?kind=" + encodeURIComponent(w.kind)); + const st = await api("GET", BASE + "/api/update-status?kind=" + encodeURIComponent(w.kind)); if (st.done && st.done !== seen && !st.running) { pending = true; reloadWhenFree(); } } catch (_) { /* 잠깐 끊김·로그아웃 — 다음 차례에 */ } finally { asking = false; } } @@ -1340,7 +1350,7 @@ } save.disabled = true; try { - const res = await api("PUT", "/performance/api/auto-sync-schedule", payload); + const res = await api("PUT", BASE + "/api/auto-sync-schedule", payload); rows.forEach(function (row) { const r = res[row.dataset.kind]; if (!r) return; @@ -1362,7 +1372,7 @@ b.addEventListener("click", async function () { const u = b.dataset.unit; try { - await api("PUT", "/performance/api/display-unit", { unit: u }); + await api("PUT", BASE + "/api/display-unit", { unit: u }); } catch (err) { alertMsg("저장 실패: " + err.message); return; @@ -1384,7 +1394,7 @@ root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (b) { b.addEventListener("click", function () { const v = b.dataset.colw; - document.cookie = "perf_colw=" + v + "; path=/performance; max-age=31536000; SameSite=Lax"; + document.cookie = "perf_colw=" + v + "; path=" + BASE + "; max-age=31536000; SameSite=Lax"; root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (x) { x.classList.toggle("is-active", x === b); x.setAttribute("aria-checked", x === b ? "true" : "false"); @@ -1407,7 +1417,7 @@ c.addEventListener("change", function () { const codes = hideBoxes.filter(function (x) { return x.checked; }).map(function (x) { return x.dataset.hide; }); hideSave = hideSave.then(function () { - return api("PUT", "/performance/api/hidden-marketplaces", { codes: codes }); + return api("PUT", BASE + "/api/hidden-marketplaces", { codes: codes }); }).catch(function (err) { c.checked = !c.checked; alertMsg("저장 실패: " + err.message); @@ -1424,7 +1434,7 @@ payload[box.dataset.field] = box.checked; box.disabled = true; try { - await api("PUT", "/performance/api/marketplaces/" + tr.dataset.code, payload); + await api("PUT", BASE + "/api/marketplaces/" + tr.dataset.code, payload); } catch (err) { box.checked = !box.checked; alertMsg("저장 실패: " + err.message); @@ -1438,12 +1448,12 @@ const tr = btn.closest("tr"); const code = tr.dataset.code, name = tr.dataset.name; // 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰 - const base = "/performance/api/" + (tr.dataset.api || "marketplaces") + "/"; + const base = BASE + "/api/" + (tr.dataset.api || "marketplaces") + "/"; if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1"); else if (btn.dataset.act === "creds") openCreds(code, name, base); else if (btn.dataset.act === "test") runTest(code, name, btn, base); else if (btn.dataset.act === "rename") openName(tr.dataset.group ? "그룹 이름 변경" : "쇼핑몰 이름 변경", name, function (v) { - return api("PUT", "/performance/api/marketplaces/" + code, { name: v }); + return api("PUT", BASE + "/api/marketplaces/" + code, { name: v }); }); else if (btn.dataset.act === "delete") deleteCustom(code, name, !!tr.dataset.group); }); @@ -1471,22 +1481,22 @@ } const addShop = document.getElementById("perf-add-shop"); if (addShop) addShop.addEventListener("click", function () { - openName("쇼핑몰 추가(수동 입력)", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "shop", name: v }); }); + openName("쇼핑몰 추가(수동 입력)", "", function (v) { return api("POST", BASE + "/api/marketplaces", { kind: "shop", name: v }); }); }); const addGroup = document.getElementById("perf-add-group"); if (addGroup) addGroup.addEventListener("click", function () { - openName("그룹 추가", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "group", name: v }); }); + openName("그룹 추가", "", function (v) { return api("POST", BASE + "/api/marketplaces", { kind: "group", name: v }); }); }); async function deleteCustom(code, name, isGroup) { let msg; if (isGroup) msg = "그룹 [" + name + "]을 삭제할까요? 하위 쇼핑몰은 지워지지 않고 그룹 없음이 됩니다."; else { let days = 0; - try { days = (await api("GET", "/performance/api/marketplaces/" + code + "/manual-days")).days || 0; } catch (_) { /* 확인 문구만 */ } + try { days = (await api("GET", BASE + "/api/marketplaces/" + code + "/manual-days")).days || 0; } catch (_) { /* 확인 문구만 */ } msg = "쇼핑몰 [" + name + "]을 삭제할까요?" + (days ? " 입력해 둔 매출 " + fmt(days) + "일치와 수수료율도 함께 지워지며 되돌릴 수 없습니다." : ""); } if (!(await confirmMsg(msg))) return; - try { await api("DELETE", "/performance/api/marketplaces/" + code); location.reload(); } + try { await api("DELETE", BASE + "/api/marketplaces/" + code); location.reload(); } catch (err) { alertMsg("삭제 실패: " + err.message); } } root.querySelectorAll("select[data-act-group]").forEach(function (sel) { @@ -1494,7 +1504,7 @@ sel.addEventListener("change", async function () { sel.disabled = true; try { - await api("PUT", "/performance/api/marketplaces/" + sel.closest("tr").dataset.code, { parent_code: sel.value }); + await api("PUT", BASE + "/api/marketplaces/" + sel.closest("tr").dataset.code, { parent_code: sel.value }); location.reload(); // 행이 그룹 아래로(또는 밖으로) 옮겨 그려진다 } catch (err) { sel.value = before; sel.disabled = false; alertMsg("저장 실패: " + err.message); } }); @@ -1532,7 +1542,7 @@ document.body.classList.remove("perf-dragging"); const order = currentOrder(); if (order.join(",") === start) return; - try { await api("PUT", "/performance/api/marketplace-order", { codes: order }); } + try { await api("PUT", BASE + "/api/marketplace-order", { codes: order }); } catch (err) { await alertMsg("순서 저장 실패: " + err.message); location.reload(); } } document.addEventListener("pointermove", move); @@ -1577,7 +1587,7 @@ ''; }).join("") + "
{{ m3(m) }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[col.base]) }}{{ gc1 }}{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }} 매출 집계 수동 입력수수료율API 설정API 설정 연결 상태마지막 동기화마지막 동기화
하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침)하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침) @@ -87,7 +89,7 @@ {% if r.manual_only %}수동 입력 전용 {% elif r.shared %}공통 연동 @@ -102,7 +104,7 @@ {% if r.last_error and r.status not in ('ok', 'disabled') %}
{{ r.last_error }}
{% endif %}
{{ when(r.last_success_sync_at) }}{{ when(r.last_success_sync_at) }} {% if r.is_custom %} @@ -138,7 +140,7 @@ {% endif %}

수수료율은 적용 시작일부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음). - {% 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 %} -
- -
-
-

{% if period_kind == 'year' %}월별 틱톡 실적{% else %}일자별 틱톡 실적{% endif %}

-
-
- - - - - - - - - - - {% for r in table %} - - - - - - - {% endfor %} - -
{% if period_kind == 'year' %}월{% else %}날짜{% endif %}ROAS광고비매출
- {{ r.label }}{% if r.holiday %}{{ r.holiday }}{% endif %} - {{ pct(r.roas) }}{{ won(r.cells.spend.gross) }}{{ won(r.cells.sales.gross) }}
-
-
- -
-
-

{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 매출 추이

-
-
-
-

{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이

-
-
-
- -
-

{{ year.year }}년 누적

-
- - - - {% for r in year.rows %} - - - - - - - {% endfor %} - - - - - - - - - -
월ROAS광고비매출
{{ r.label }}{% if not r.future %}{{ pct(r.roas) }}{% endif %}{{ won(r.spend) }}{{ won(r.sales) }}
합계{{ pct(year.roas) }}{{ won(year.spend) }}{{ won(year.sales) }}
-
-
- -

- 틱톡 광고 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("
"; } - try { renderHist((await api("GET", "/performance/api/marketplaces/" + code + "/rates")).rates || []); } + try { renderHist((await api("GET", BASE + "/api/marketplaces/" + code + "/rates")).rates || []); } catch (err) { m.body.querySelector("#perf-rate-hist").textContent = err.message; } m.body.addEventListener("click", async function (e) { @@ -1585,7 +1595,7 @@ if (!b) return; if (!(await confirmMsg("이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다."))) return; try { - renderHist((await api("DELETE", "/performance/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []); + renderHist((await api("DELETE", BASE + "/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []); m.changed = true; } catch (err) { alertMsg(err.message); } }); @@ -1593,7 +1603,7 @@ const rate = m.body.querySelector("#perf-rate-in").value.trim(); if (!rate) { m.body.querySelector("#perf-rate-in").focus(); return; } try { - const res = await api("POST", "/performance/api/marketplaces/" + code + "/rates", { + const res = await api("POST", BASE + "/api/marketplaces/" + code + "/rates", { rate_percent: rate, effective_from: all.checked ? "2000-01-01" : from.value, memo: m.body.querySelector("#perf-rate-memo").value, }); @@ -1609,7 +1619,7 @@ // ── API 인증정보 ── async function openCreds(code, name, base) { - base = base || "/performance/api/marketplaces/"; + base = base || BASE + "/api/marketplaces/"; const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } }); m.body.innerHTML = '

불러오는 중…

'; let info; @@ -1709,7 +1719,7 @@ const label = btn.textContent; btn.textContent = "확인 중…"; try { - const res = await api("POST", (base || "/performance/api/marketplaces/") + code + "/test", {}); + const res = await api("POST", (base || BASE + "/api/marketplaces/") + code + "/test", {}); await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined); location.reload(); } catch (err) { @@ -1765,7 +1775,7 @@ if (gen) gen.addEventListener("click", async function () { gen.disabled = true; try { - const res = await api("POST", "/performance/api/sample-data", { + const res = await api("POST", BASE + "/api/sample-data", { action: "generate", from: document.getElementById("perf-sample-from").value, to: document.getElementById("perf-sample-to").value, }); @@ -1777,7 +1787,7 @@ if (del) del.addEventListener("click", async function () { if (!(await confirmMsg("테스트 데이터만 모두 삭제합니다. 실제 수집한 매출은 지우지 않습니다. 계속할까요?"))) return; try { - const res = await api("POST", "/performance/api/sample-data", { action: "delete" }); + const res = await api("POST", BASE + "/api/sample-data", { action: "delete" }); await alertMsg("테스트 데이터 " + fmt(res.deleted) + "건을 삭제했습니다."); location.reload(); } catch (err) { alertMsg(err.message); } @@ -1786,7 +1796,7 @@ if (rekey) rekey.addEventListener("click", async function () { if (!(await confirmMsg("예전 키로 암호화된 인증정보를 현재 키로 다시 암호화합니다. 계속할까요?"))) return; try { - const res = await api("POST", "/performance/api/rekey"); + const res = await api("POST", BASE + "/api/rekey"); await alertMsg("다시 암호화 " + res.reencrypted + "건" + (res.failed ? ", 실패 " + res.failed + "건(다시 입력 필요)" : "")); location.reload(); } catch (err) { alertMsg(err.message); } diff --git a/app/store.py b/app/store.py index be76f06..6c50680 100644 --- a/app/store.py +++ b/app/store.py @@ -36,6 +36,7 @@ MODULE_KEYS: tuple[str, ...] = ( "project", "cafe24", "performance", + "malaysia_performance", "asset", "inout", "outreach", diff --git a/docs/DATABASES.md b/docs/DATABASES.md index 17beddd..1a6020e 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -12,6 +12,7 @@ | `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 | | `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 | | `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 | +| `malaysia_performance_db` | 말레이시아 실적(2026-11-20) — performance_db 와 **같은 표 구조**(구조만 복사), 틱톡·쇼피·라자다 쇼핑몰·라이브커머스 수동 매출·광고비. 금액 = 센(0.01 RM) 정수. 역할 `performance_app` 공유 | | `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목/상품 정보(단가·무게·은 함유량, 004)/모듈 설정(물류센터 이메일)·입고 요청 메일 기록(005) (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) | --- @@ -395,6 +396,10 @@ cd /opt/www/main && docker compose up -d --build web ## performance_db 스키마 / 초기화 +> **012(2026-11-20) 틱톡 데이터 삭제** — `scripts/sql/performance_db_012_drop_tiktok.sql`(틱톡 탭 삭제, 백업 후·승인 후). +> **malaysia_performance_db** — 이 DB 구조를 `pg_dump --schema-only` 로 복사 + `scripts/sql/malaysia_performance_db_seed.sql`(쇼핑몰 9행). +> 앞으로 performance_db 마이그레이션(013~)은 **두 DB 모두에** 적용한다(같은 코드가 두 DB 를 읽음). + DDL: `scripts/sql/performance_db_init.sql` (멱등). DB·역할(`performance_app`)·테이블·인덱스·트리거·쇼핑몰 10곳 seed 를 한 번에 생성. **JSON 폴백 없음** — `PERFORMANCE_DB_URL` 미설정 시 모듈이 "설정 필요" 안내만 표시. 상세는 `docs/PERFORMANCE_MODULE.md`. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 8474146..06c25fa 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -625,6 +625,7 @@ docker compose down # 컨테이너 제거 (볼륨 유지) | `ITEMCODE_DB_URL` | 상품 검색용 itemcode_db 읽기 전용 DSN. 미설정 시 검색 비활성(수동 입력). 테이블/컬럼은 `ITEMCODE_TABLE`/`ITEMCODE_CODE_COL`/`ITEMCODE_NAME_COL`/`ITEMCODE_TYPE_COL` 또는 `ITEMCODE_SEARCH_SQL` 로 지정 | | `DATA_DIR` | 영구 데이터 경로 (Docker 볼륨 마운트). 첨부파일은 `$DATA_DIR/uploads/expense/{item_id}/` 에 저장 | | `PERFORMANCE_DB_URL` | 실적 DB DSN (예: `postgresql://performance_app:@postgres-db:5432/performance_db`). **필수** — 미설정 시 실적 모듈 비활성(설정 필요 안내). 권한키 `performance` | +| `MALAYSIA_PERFORMANCE_DB_URL` | 말레이시아 실적 DB DSN (예: `postgresql://performance_app:@postgres-db:5432/malaysia_performance_db`, 역할은 실적과 공유). 미설정 시 말레이시아 실적만 "설정 필요" 안내. 만들기 = `scripts/sql/malaysia_performance_db_seed.sql` 머리말. 권한키 `malaysia_performance` | | `APP_ENCRYPTION_KEY` | 쇼핑몰 API 인증정보 암호화 마스터 키(32바이트, `openssl rand -hex 32`). DB 에 저장하지 않음. **분실 시 저장된 인증정보 복구 불가 — 별도 안전 보관**. 쇼핑몰별 ID/Key/Secret 은 `.env` 에 넣지 않고 실적 → 설정 화면에서 입력 | | `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) | | `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) | diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index ccfe462..d7f797a 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -26,6 +26,7 @@ | 안내문 발송 | 리스트(이메일·인스타 주소 + 이름)에 `{이름}`을 넣은 안내문 — 메일 일괄 발송(보내는 사람 본인 Gmail)·인스타 DM 반자동(문구 복사 + DM 창) (`app/modules/outreach/`, `outreach_db`) | | 라이브 커머스 | 말레이시아 라이브 방송의 호스트 정보(설정)와 스케줄표(호스트·날짜·시간·판매금액·장소·결과 이미지) (`app/modules/live/`, `live_db`) | | 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` | +| 말레이시아 실적 | 틱톡·쇼피·라자다 쇼핑몰·라이브커머스 매출(RM)·광고비 수동 입력 (`app/modules/malaysia_performance/` — 실적 코드를 `/malaysia/performance` 에 한 번 더 붙임, `performance/variant.py`) → `malaysia_performance_db` | ### 권한 키 (`MODULE_KEYS`) @@ -36,7 +37,7 @@ | 키 | 종류 | 설명 | | --- | --- | --- | | `corm` / `order` | 접근 | 외부 모듈 진입 | -| `expense` / `vacation` / `cupang` / `malaysia` / `performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) | +| `expense` / `vacation` / `cupang` / `malaysia` / `performance` / `malaysia_performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) | | `expense_approver` | 결재 | 개인경비 승인/반려/정산 | | `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 | | `outreach` | 접근 | 안내문 발송 — 리스트·메일 발송·DM·설정 | @@ -118,6 +119,7 @@ app/modules// | `outreach_db` | 안내문 발송 — 리스트·보낸 기록·제목/본문 설정·사진 (`OUTREACH_DB_URL` 필수, JSON 폴백 없음) | | `live_db` | 라이브 커머스 — 호스트 정보·방송 스케줄·결과 이미지 (`LIVE_DB_URL` 필수, JSON 폴백 없음) | | `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) | +| `malaysia_performance_db` | 말레이시아 실적 — performance_db 와 같은 표 구조, 금액 = 센 정수 (`MALAYSIA_PERFORMANCE_DB_URL`) | > 신규 DB 생성은 서버 실행 명령을 제공하고 사용자가 직접 진행한다 (사용자 지시: 2026-10-06). 대상·상태·백업 확인 명령을 제공하고 이름은 `_db`로 끝낸다. 기존 DB 삭제·덮어쓰기는 별도 승인 대상이다. 상세는 `DATABASES.md`. diff --git a/scripts/sql/malaysia_performance_db_seed.sql b/scripts/sql/malaysia_performance_db_seed.sql new file mode 100644 index 0000000..8580d28 --- /dev/null +++ b/scripts/sql/malaysia_performance_db_seed.sql @@ -0,0 +1,38 @@ +-- ===================================================================== +-- malaysia_performance_db 쇼핑몰 seed — [말레이시아 실적](2026-11-20) +-- ===================================================================== +-- 말레이시아 실적은 실적 모듈 코드를 그대로 쓰므로 표 구조 = performance_db(마이그레이션 012 까지)와 같다. +-- 그래서 DB 를 만들 때 performance_db 의 **구조만**(데이터 없이) 복사하고, 이 파일로 쇼핑몰만 넣는다. +-- 멱등(ON CONFLICT DO NOTHING). DROP/DELETE 없음. 역할은 실적과 같은 performance_app 을 쓴다. +-- +-- 실행 순서(운영 PostgreSQL 컨테이너 postgres-db, 경로 /opt/www/main — 사용자 승인 후): +-- 1) 빈 DB 만들기 + 접속 권한 +-- docker exec -i postgres-db psql -U postgres -c "CREATE DATABASE malaysia_performance_db ENCODING 'UTF8' TEMPLATE template0" +-- docker exec -i postgres-db psql -U postgres -c "GRANT CONNECT ON DATABASE malaysia_performance_db TO performance_app" +-- 2) performance_db 구조만 복사(표·인덱스·트리거·권한, 데이터 없음) +-- docker exec postgres-db pg_dump -U postgres --schema-only performance_db \ +-- | docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d malaysia_performance_db +-- 3) 이 파일 +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d malaysia_performance_db < scripts/sql/malaysia_performance_db_seed.sql +-- 4) .env 에 MALAYSIA_PERFORMANCE_DB_URL=postgresql://performance_app:<실적과 같은 비밀번호>@postgres-db:5432/malaysia_performance_db +-- +-- 코드는 app/modules/performance/variant.py MY 와 같아야 한다(광고비 ROAS·매출 칸 아래 광고비 줄이 이 코드로 찾음). +-- group_<쇼핑몰> = 합계 열(매출 없음), custom_<쇼핑몰>_shop = 쇼핑몰 매출, custom_<쇼핑몰>_live = 라이브커머스 매출. +-- 금액은 센(0.01 RM) 정수로 저장된다(화면 = RM 소수 2자리). +-- ===================================================================== + +\set ON_ERROR_STOP on + +INSERT INTO perf_marketplaces (code, name, sort_order, manual_input, include_in_sales, is_custom, is_group, parent_code) VALUES + ('group_tiktok', '틱톡', 10, FALSE, FALSE, TRUE, TRUE, NULL), + ('custom_tiktok_shop', '틱톡 쇼핑몰', 11, TRUE, TRUE, TRUE, FALSE, 'group_tiktok'), + ('custom_tiktok_live', '틱톡 라이브커머스', 12, TRUE, TRUE, TRUE, FALSE, 'group_tiktok'), + ('group_shopee', '쇼피', 20, FALSE, FALSE, TRUE, TRUE, NULL), + ('custom_shopee_shop', '쇼피 쇼핑몰', 21, TRUE, TRUE, TRUE, FALSE, 'group_shopee'), + ('custom_shopee_live', '쇼피 라이브커머스', 22, TRUE, TRUE, TRUE, FALSE, 'group_shopee'), + ('group_lazada', '라자다', 30, FALSE, FALSE, TRUE, TRUE, NULL), + ('custom_lazada_shop', '라자다 쇼핑몰', 31, TRUE, TRUE, TRUE, FALSE, 'group_lazada'), + ('custom_lazada_live', '라자다 라이브커머스', 32, TRUE, TRUE, TRUE, FALSE, 'group_lazada') +ON CONFLICT (code) DO NOTHING; + +SELECT 'malaysia_performance_db seed ready' AS status; diff --git a/scripts/sql/performance_db_012_drop_tiktok.sql b/scripts/sql/performance_db_012_drop_tiktok.sql new file mode 100644 index 0000000..0dd716b --- /dev/null +++ b/scripts/sql/performance_db_012_drop_tiktok.sql @@ -0,0 +1,28 @@ +-- ===================================================================== +-- performance_db 012 — 틱톡 탭 삭제(2026-11-20)에 따른 틱톡 광고 데이터 삭제 +-- ===================================================================== +-- ⚠️ 데이터 삭제 — 사용자 승인 + 백업 확인 후 실행. 되돌릴 수 없다(백업에서만 복구). +-- 틱톡 광고 API 로 받은 일 광고비·매출(perf_ad_spend channel_code='tiktok'), 틱톡 광고 API 인증정보(암호문)·연결 상태, +-- 틱톡 칸 메모만 지운다. 다른 채널·쇼핑몰은 건드리지 않는다. 표(테이블)는 지우지 않는다. +-- +-- 1) 지울 행 수 확인(읽기만) +-- docker exec -i postgres-db psql -U postgres -d performance_db -c "SELECT +-- (SELECT count(*) FROM perf_ad_spend WHERE channel_code='tiktok') AS spend, +-- (SELECT count(*) FROM perf_ad_credentials WHERE channel_code='tiktok') AS creds, +-- (SELECT count(*) FROM perf_ad_source_status WHERE channel_code='tiktok') AS status, +-- (SELECT count(*) FROM perf_cell_memos WHERE kind='ad' AND code='tiktok') AS memos;" +-- 2) 백업 +-- docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_012_$(date +%Y%m%d%H%M).sql +-- 3) 실행 +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_012_drop_tiktok.sql +-- 4) 1) 을 다시 실행해 모두 0 인지 확인 +-- ===================================================================== + +BEGIN; +DELETE FROM perf_ad_spend WHERE channel_code = 'tiktok'; +DELETE FROM perf_ad_credentials WHERE channel_code = 'tiktok'; +DELETE FROM perf_ad_source_status WHERE channel_code = 'tiktok'; +DELETE FROM perf_cell_memos WHERE kind = 'ad' AND code = 'tiktok'; +COMMIT; + +SELECT 'performance_db 012 tiktok data removed' AS status; diff --git a/tests/js/perf_malaysia.browser.test.js b/tests/js/perf_malaysia.browser.test.js new file mode 100644 index 0000000..b97bfdb --- /dev/null +++ b/tests/js/perf_malaysia.browser.test.js @@ -0,0 +1,79 @@ +// 말레이시아 실적(2026-11-20) — 실제 브라우저. 같은 performance.js 가 data-base(/malaysia/performance)로 저장하고 +// 금액을 RM 소수 2자리로 보이는지(저장 단위 = 센). +// python tests/js/render_performance.py +// NODE_PATH= PJ_TEST_BROWSER= node tests/js/perf_malaysia.browser.test.js +const fs = require("fs"), path = require("path"); +const { chromium } = require("playwright"); +const ROOT = path.join(__dirname, "..", ".."); +const fails = []; +function check(name, cond, extra) { + if (cond) console.log("PASS " + name); + else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); } +} +function load(file) { + const css = fs.readFileSync(path.join(ROOT, "app", "static", "performance.css"), "utf8"); + const js = fs.readFileSync(path.join(ROOT, "app", "static", "performance.js"), "utf8"); + return fs.readFileSync(path.join(__dirname, ".out", file), "utf8") + .replace(//, function () { return ""; }) + .replace(/"; }); +} + +(async function () { + const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {}); + try { + // 매출 실적 — 틱톡 라이브커머스 10/5 칸(RM 100.05)을 12.34 로 + const page = await browser.newPage({ viewport: { width: 1400, height: 900 } }); + const calls = []; + await page.route("**/*", function (r) { + if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load("perf_my_dash.html") }); + calls.push({ url: r.request().url(), body: r.request().postData() }); + r.fulfill({ status: 200, contentType: "application/json", + body: JSON.stringify({ ok: true, manual: 1234, amount: 1234, commission: 0, net: 1234, formula: null }) }); + }); + await page.goto("http://perf.test/malaysia/performance/"); + const sel = 'td.is-manual-cell[data-manual-code="custom_tiktok_live"][data-date="2026-10-05"]'; + await page.click(sel); + const prefill = await page.$eval(sel + " .perf-manual-input", function (i) { return i.value; }); + check("편집창 = RM 값(100.05)", prefill === "100.05", prefill); + await page.keyboard.press("Control+A"); + await page.keyboard.type("RM 12.34"); + await page.keyboard.press("Escape"); // 저장 뒤 새로고침(합계 다시 계산) 전에 칸 값을 본다 — Enter 는 다음 칸 편집으로 넘어감 + await page.click(sel); + await page.keyboard.press("Control+A"); + await page.keyboard.type("RM 12.34"); + await page.keyboard.press("Enter"); + await page.waitForTimeout(300); + const put = calls.find(function (c) { return /manual-sales/.test(c.url); }); + check("저장 주소 = /malaysia/performance/api/manual-sales/…", put && /\/malaysia\/performance\/api\/manual-sales\/custom_tiktok_live\/2026-10-05$/.test(put.url), put); + check("보낸 값 = 12.34(RM 글자 지움)", put && JSON.parse(put.body).amount === "12.34", put); + const cell = await page.$eval(sel, function (td) { return { gross: td.querySelector(".v-gross").textContent, v: td.dataset.manualValue }; }); + check("저장 뒤 칸 = 12.34, 편집값 12.34", cell.gross === "12.34" && cell.v === "12.34", cell); + const head = await page.$eval("#perf-chart-daily svg", function (s) { return s.querySelector("title").textContent; }); + check("그래프 말풍선 = RM", / RM$/.test(head) && /\d\.\d\d RM$/.test(head), head); + await page.close(); + + // 광고비 — 쇼피 10/5 칸에 계산식 + const ap = await browser.newPage({ viewport: { width: 1400, height: 900 } }); + const acalls = []; + await ap.route("**/*", function (r) { + if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load("perf_my_ads.html") }); + acalls.push({ url: r.request().url(), body: r.request().postData() }); + r.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, manual: 300, amount: 300, formula: "1.5*2" }) }); + }); + await ap.goto("http://perf.test/malaysia/performance/ads"); + const heads = await ap.$$eval(".perf-main thead th", function (ths) { return ths.map(function (t) { return t.textContent.trim(); }); }); + check("광고비 열 = 틱톡·쇼피·라자다", /틱톡/.test(heads[2]) && /쇼피/.test(heads[3]) && /라자다/.test(heads[4]) && heads.length === 5, heads); + const asel = 'td.is-manual-cell[data-manual-code="shopee"][data-date="2026-10-05"]'; + await ap.click(asel); + await ap.keyboard.type("1.5*2"); + await ap.keyboard.press("Enter"); + await ap.waitForTimeout(300); + const aput = acalls.find(function (c) { return /ad-spend/.test(c.url); }); + check("광고비 저장 주소 = /malaysia/performance/api/ad-spend/shopee/…", aput && /\/malaysia\/performance\/api\/ad-spend\/shopee\/2026-10-05$/.test(aput.url), aput); + const av = await ap.$eval(asel + " .v-gross", function (s) { return s.textContent; }); + check("광고비 칸 = 3.00", av === "3.00", av); + await ap.close(); + } finally { await browser.close(); } + console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS"); + process.exit(fails.length ? 1 : 0); +})(); diff --git a/tests/js/perf_tiktok.browser.test.js b/tests/js/perf_tiktok.browser.test.js deleted file mode 100644 index fee6af5..0000000 --- a/tests/js/perf_tiktok.browser.test.js +++ /dev/null @@ -1,63 +0,0 @@ -// 실적 틱톡 탭(2026-11-05) — 실제 브라우저(Chromium). -// python tests/js/render_performance.py -// NODE_PATH= PJ_TEST_BROWSER= node tests/js/perf_tiktok.browser.test.js -// 광고비 오른쪽 탭, ROAS·광고비·매출 열, 매출·광고비 그래프 둘, 합계 줄 스크롤 고정, 칸 입력 없음, 스크립트 오류 없음. -const fs = require("fs"), path = require("path"); -const { chromium } = require("playwright"); -const ROOT = path.join(__dirname, "..", ".."); -const fails = []; -function check(name, cond, extra) { - if (cond) console.log("PASS " + name); - else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); } -} - -(async function () { - const exe = process.env.PJ_TEST_BROWSER; - const browser = await chromium.launch(exe ? { executablePath: exe } : {}); - try { - const p = await (await browser.newContext({ viewport: { width: 1400, height: 800 } })).newPage(); - const errors = []; - p.on("pageerror", function (e) { errors.push(String(e)); }); - await p.route("**/*", function (r) { - const url = new URL(r.request().url()).pathname; - if (url.startsWith("/static/")) { - const f = path.join(ROOT, "app", url); - if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" }); - const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2"; - return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) }); - } - if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" }); - r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") }); - }); - await p.goto("http://erp.test/perf_tiktok_shell.html"); - await p.waitForTimeout(300); - const tabs = await p.locator(".perf-tabs-main .perf-tab").allInnerTexts(); - check("탭 순서 = 매출 실적·광고비·틱톡", tabs.map(function (t) { return t.replace(/^[a-z_]+\s*/, "").trim(); }).join() === "매출 실적,광고비,틱톡", tabs); - check("틱톡 탭이 켜짐", await p.locator(".perf-tab-tiktok.is-active").count() === 1); - const head = await p.locator("table.perf-main thead th").allInnerTexts(); - check("열 = 날짜·ROAS·광고비·매출", head.join() === "날짜,ROAS,광고비,매출", head); - const total = await p.locator("table.perf-main tbody tr").first().innerText(); - check("맨 위 기간 합계", total.includes("합계") && total.includes("210,000") && total.includes("630,000") && total.includes("300%"), total); - const day = await p.locator("table.perf-main tbody tr", { hasText: "400%" }).first().innerText(); - check("일자 줄 값", day.includes("120,000") && day.includes("480,000"), day); - check("매출 그래프", await p.locator("#perf-chart-daily svg rect.bar").count() > 0); - check("광고비 그래프", await p.locator("#perf-chart-daily2 svg rect.bar").count() > 0); - check("칸 입력 없음", await p.locator("[data-manual-code]").count() === 0); - check("업데이트 버튼", (await p.locator("#perf-ad-sync-btn").innerText()).includes("광고비 업데이트")); - await p.screenshot({ path: path.join(__dirname, ".out", "perf_tiktok.png") }); - await p.locator("table.perf-main").hover(); - await p.mouse.wheel(0, 500); - await p.waitForTimeout(250); - const stuck = await p.evaluate(function () { - const first = document.querySelector("table.perf-main tbody tr.perf-row-total:first-child th"); - const top = first.getBoundingClientRect().top; - return document.querySelector("table.perf-main thead th").getBoundingClientRect().bottom <= top + 2 && top >= 0 && top < 300; - }); - check("스크롤해도 제목·합계 줄 고정", stuck); - check("스크립트 오류 없음", errors.length === 0, errors); - } finally { - await browser.close(); - } - if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); } - console.log("\nALL OK"); -})(); diff --git a/tests/js/render_performance.py b/tests/js/render_performance.py index 640a921..0309845 100644 --- a/tests/js/render_performance.py +++ b/tests/js/render_performance.py @@ -19,9 +19,10 @@ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__) sys.path.insert(0, ROOT) OUT_DIR = os.path.join(ROOT, "tests", "js", ".out") -from app.modules.performance.ad_spend import build_ad_dashboard, build_tiktok_dashboard # noqa: E402 +from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402 from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402 from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402 +from app.modules.performance import variant # noqa: E402 BASE_STUB = ("{% block head_extra %}{% endblock %}
{% block content %}{% endblock %}
" "{% block scripts %}{% endblock %}") @@ -84,17 +85,11 @@ def env() -> jinja2.Environment: return e -class TiktokStore: - def ad_details(self, code, start, end): - rows = [("2026-10-02", 120000, 480000), ("2026-10-05", 90000, 150000), ("2026-09-20", 50000, 100000)] - return [{"date": d, "amount": a, "roas": None, "metrics": {"매출": b}, "source": "api"} for d, a, b in rows] - - def main() -> None: os.makedirs(OUT_DIR, exist_ok=True) e = env() base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": "", - "unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v), "colw": "auto"} + "unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v), "colw": "auto", **variant.template_ctx()} ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) # 다음 자동 업데이트(router._auto_sync_ctx 와 같은 모양) — 화면이 초 단위로 센다 # 일정 = 실적 설정 "자동 업데이트"(2026-10-26) — 화면이 schedule 로 다음 회차를 계산 @@ -123,12 +118,6 @@ def main() -> None: html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx) with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f: f.write(html) - # 틱톡 탭(2026-11-05) — 가상의 광고 API 값 - tk = build_tiktok_dashboard(TiktokStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays={"2026-10-03": "개천절"}) - tk.update(auto_sync=ctx["auto_sync"], update_watch={"kind": "ads", "seen": "job-old"}, tiktok_configured=True, ad_running=False, - ad_last_update_at=None, ad_sync_sources=[{"code": "tiktok", "name": "틱톡"}]) - with open(os.path.join(OUT_DIR, "perf_tiktok_shell.html"), "w", encoding="utf-8") as f: - f.write(shell.get_template("performance/tiktok.html").render(**sbase, active_tab="tiktok", **tk)) actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=["cafe24", "coupang"]) actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기] @@ -171,9 +160,29 @@ def main() -> None: html = shell.get_template("performance/ads.html").render(**{**sbase, "colw": "manual"}, active_tab="ads", **sactx) with open(os.path.join(OUT_DIR, "perf_ads_colw_shell.html"), "w", encoding="utf-8") as f: f.write(html) + render_malaysia(e, base) print("ok") +def render_malaysia(e: jinja2.Environment, base: dict) -> None: + """말레이시아 실적(2026-11-20) — perf_my_dash.html · perf_my_ads.html (perf_malaysia.browser.test.js). 금액 = 센.""" + from app.modules.performance.tests.test_malaysia_variant import _Store # noqa: WPS433 + + token = variant._current.set(variant.MY) + try: + mb = {**base, **variant.template_ctx(), "unit": "rm", "unit_label": "RM", "amt": lambda v: amount_text(v, "rm")} + ctx = build_dashboard(_Store(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) + ctx.update(auto_sync=None, update_watch=None) + with open(os.path.join(OUT_DIR, "perf_my_dash.html"), "w", encoding="utf-8") as f: + f.write(e.get_template("performance/index.html").render(**mb, active_tab="dashboard", metric="gross", **ctx)) + actx = build_ad_dashboard(_Store(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=[]) + actx.update(auto_sync=None, update_watch=None) + with open(os.path.join(OUT_DIR, "perf_my_ads.html"), "w", encoding="utf-8") as f: + f.write(e.get_template("performance/ads.html").render(**mb, active_tab="ads", **actx)) + finally: + variant._current.reset(token) + + class GroupStore(FakeStore): """카페24·네이버 + 그룹 '오프라인'(매장A·매장B) + 그룹 없는 직접 추가 '행사'."""