+
+ {{ r.status_label }}
+ {% if r.last_error and r.status not in ('ok', 'disabled') %}
{{ r.last_error }}
{% endif %}
+
+
{{ when(r.last_success_sync_at) }}
+
+
+
+
+
+ {% endfor %}
+
+
+
+
+ 수수료율은 적용 시작일부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
+ 상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
+
+
+
+
+
+
인증정보 암호화
+
+
마스터 키
+
{% if key_info.ok %}설정됨 · 현재 v{{ key_info.current_version }}
+ {% set olds = key_info.versions | reject('equalto', key_info.current_version) | list %}
+ {% if olds %}(예전 키 v{{ olds | join(', v') }} 보관 중){% endif %}
+ {% else %}미설정{% endif %}
+
저장된 항목
+
{% for v, n in key_versions_in_use.items() %}v{{ v }}: {{ n }}개{% if not loop.last %}, {% endif %}{% else %}없음{% endfor %}
+
+ {% if stale_key_rows %}
+
예전 키로 암호화된 항목이 {{ stale_key_rows }}개 있습니다.
+
+ {% endif %}
+
+ API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
+ 서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
+
+
+
+
+
과거 매출 가져오기
+
[매출 업데이트]는 최근 며칠만 가져옵니다. 처음 연동했거나 빠진 기간이 있으면 기간을 지정해 한 번에
+ 가져오세요(연동된 쇼핑몰만, 최대 366일). 같은 주문은 덮어써서 여러 번 해도 중복되지 않습니다.
+
+
+ ~
+
+
+
+
+
+
+
+
11번가 원본 데이터 확인
+
11번가 셀러 API 의 주문·클레임·정산 조회 주소를 기간(최대 31일)으로 실제 불러, 어느 주소가 동작하는지와
+ 받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 주문 목록은 지금 그 상태인 주문만, 정산은 정산일 기준일 수 있어
+ 매출이 있던 날부터 넉넉히(예: 3주) 잡아 주세요. 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
+ 매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.
+
+
+ ~
+
+
+
+
+
+
+
+
카페24 매출 대조
+
카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
+ 바로 합산하며(저장하지 않음), 자체몰과 다른 마켓 연동 주문을 나눠 보여 줍니다.
+
+
+
+
+
+
+
일별 한 번에 비교
+
카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다.
+ [API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과
+ 규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.
+
+
+
+
+
+
+
+
+
+
테스트 데이터
+ 현재 {{ "{:,}".format(sample_count) }}건
+
실제 API 연동 전 화면 확인용 모의 매출입니다(사용 중인 쇼핑몰 대상). 실제 데이터와 구분되어 한 번에 지울 수 있습니다.
+
+
+ ~
+
+
+
+
+
+
+
+{% endblock %}
+
+{% block scripts %}{% endblock %}
diff --git a/app/modules/performance/tests/__init__.py b/app/modules/performance/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py
new file mode 100644
index 0000000..8810861
--- /dev/null
+++ b/app/modules/performance/tests/test_performance.py
@@ -0,0 +1,977 @@
+"""실적 모듈 테스트 — 암호화·가리기·계산·인증정보·동기화. DB/네트워크 없이 가짜 저장소로.
+
+ python -m app.modules.performance.tests.test_performance
+또는 pytest 로 실행 가능.
+"""
+
+from __future__ import annotations
+
+import os
+from datetime import date, timedelta
+from decimal import Decimal
+
+from app.modules.performance import calc
+from app.modules.performance.adapters import mock
+from app.modules.performance.adapters.base import (
+ ApiError,
+ AuthFailed,
+ CredentialField,
+ MarketplaceAdapter,
+ SaleEvent,
+)
+from app.modules.performance.adapters.registry import all_adapters
+from app.modules.performance.credentials import CredentialService, aad_for
+from app.modules.performance.security import crypto
+from app.modules.performance.security.redact import MASK, mask, redact_mapping, redact_text
+from app.modules.performance.sync import SyncService, event_row, sales_date_for
+
+KEY1 = "11" * 32
+KEY2 = "22" * 32
+
+
+def ring(version: int = 1, **old: str) -> crypto.KeyRing:
+ env = {"APP_ENCRYPTION_KEY": KEY1 if version == 1 else KEY2, "APP_ENCRYPTION_KEY_VERSION": str(version)}
+ env.update(old)
+ return crypto.KeyRing.from_env(env)
+
+
+# ════════════════════════════════════════════════════════════
+# 암호화
+# ════════════════════════════════════════════════════════════
+def test_crypto_roundtrip_and_format():
+ r = ring()
+ token = crypto.encrypt("my-secret-value", aad="perf:coupang:secret_key", ring=r)
+ assert token.startswith("v1:")
+ assert "my-secret-value" not in token
+ assert crypto.decrypt(token, aad="perf:coupang:secret_key", ring=r) == "my-secret-value"
+ # 같은 평문도 매번 다른 암호문(nonce)
+ assert token != crypto.encrypt("my-secret-value", aad="perf:coupang:secret_key", ring=r)
+
+
+def test_crypto_rejects_wrong_aad_tamper_and_key():
+ r = ring()
+ token = crypto.encrypt("abc", aad="perf:coupang:secret_key", ring=r)
+ for bad in (lambda: crypto.decrypt(token, aad="perf:naver:client_secret", ring=r),
+ lambda: crypto.decrypt(token[:-2] + ("A" if token[-2] != "A" else "B") + token[-1], aad="perf:coupang:secret_key", ring=r),
+ lambda: crypto.decrypt(token, aad="perf:coupang:secret_key",
+ ring=crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY2}))):
+ try:
+ bad()
+ except crypto.DecryptError as exc:
+ assert "abc" not in str(exc)
+ else:
+ raise AssertionError("복호화가 실패해야 합니다")
+
+
+def test_crypto_missing_or_bad_key():
+ for env in ({}, {"APP_ENCRYPTION_KEY": "short"}, {"APP_ENCRYPTION_KEY": KEY1, "APP_ENCRYPTION_KEY_VERSION": "0"}):
+ try:
+ crypto.KeyRing.from_env(env)
+ except crypto.CryptoConfigError:
+ pass
+ else:
+ raise AssertionError(f"설정 오류여야 합니다: {list(env)}")
+ # base64 32바이트 키도 받는다
+ import base64
+ b64 = base64.urlsafe_b64encode(bytes(range(32))).decode()
+ assert crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": b64}).current_version == 1
+ assert "11" * 4 not in repr(ring()) # 키 값이 repr 에 나오지 않음
+
+
+def test_crypto_rotation():
+ old = ring(1)
+ token = crypto.encrypt("rotate-me", aad="a", ring=old)
+ new = ring(2, APP_ENCRYPTION_KEY_V1=KEY1)
+ assert new.versions == [1, 2]
+ assert crypto.needs_reencrypt(token, new)
+ assert crypto.decrypt(token, aad="a", ring=new) == "rotate-me"
+ token2 = crypto.encrypt("rotate-me", aad="a", ring=new)
+ assert token2.startswith("v2:") and not crypto.needs_reencrypt(token2, new)
+ try:
+ crypto.decrypt(token, aad="a", ring=ring(2)) # 예전 키를 안 남기면 실패
+ except crypto.DecryptError as exc:
+ assert "v1" in str(exc)
+ else:
+ raise AssertionError("예전 키 없이는 복호화 실패해야 합니다")
+
+
+# ════════════════════════════════════════════════════════════
+# 가리기
+# ════════════════════════════════════════════════════════════
+def test_redact():
+ secret = "SK-live-9f8e7d6c5b4a"
+ msg = f"401 Unauthorized secret={secret} Authorization: Bearer abcdef123456 token=zzz999 other=ok"
+ out = redact_text(msg, [secret])
+ assert secret not in out and "abcdef123456" not in out and "zzz999" not in out
+ assert "other=ok" in out and MASK in out
+ assert "Cookie" not in redact_text("Cookie: sid=abc; x=1").replace(f"Cookie: {MASK}", "")
+ j = redact_text('{"access_token": "tok-123456", "vendor": "A001"}')
+ assert "tok-123456" not in j and "A001" in j
+ data = redact_mapping({"order": "1", "headers": {"Authorization": "x", "X-Api-Key": "y"}, "items": [{"password": "p"}]})
+ assert data["order"] == "1" and data["headers"]["Authorization"] == MASK
+ assert data["headers"]["X-Api-Key"] == MASK and data["items"][0]["password"] == MASK
+ assert mask("ABCDEFGHIJKL1234") == "ABCD****1234" and mask("short") == MASK
+ assert len(redact_text("x" * 1000)) <= 301
+
+
+# ════════════════════════════════════════════════════════════
+# 계산
+# ════════════════════════════════════════════════════════════
+def test_commission_rounding():
+ assert calc.commission(1_000_000, Decimal("10")) == 100_000
+ assert calc.commission(12_345, Decimal("10.8")) == 1_333 # 1333.26 → 1333
+ assert calc.commission(15, Decimal("10")) == 2 # 1.5 → 2 (half up)
+ assert calc.commission(-15, Decimal("10")) == -2 # 취소도 같은 규칙
+ assert calc.commission(100_000, Decimal("15.35")) == 15_350
+ assert calc.commission(0, Decimal("10")) == 0 and calc.commission(1000, Decimal("0")) == 0
+ m = calc.Money(gross=1_000_000, commission=100_000)
+ assert m.net == 900_000
+
+
+def test_rate_history():
+ rates = {"coupang": [(date(2026, 1, 1), Decimal("8")), (date(2026, 7, 1), Decimal("10"))]}
+ assert calc.rate_on(rates, "coupang", date(2025, 12, 31)) == 0
+ assert calc.rate_on(rates, "coupang", date(2026, 6, 30)) == 8
+ assert calc.rate_on(rates, "coupang", date(2026, 7, 1)) == 10
+ assert calc.rate_on(rates, "naver", date(2026, 7, 1)) == 0
+ cells = calc.build_cells({(date(2026, 6, 30), "coupang"): 100_000, (date(2026, 7, 1), "coupang"): 100_000}, rates)
+ assert cells[(date(2026, 6, 30), "coupang")].commission == 8_000
+ assert cells[(date(2026, 7, 1), "coupang")].commission == 10_000
+
+
+def test_periods():
+ wed = date(2026, 9, 30)
+ p = calc.resolve_period("week", wed)
+ assert (p.start, p.end) == (date(2026, 9, 28), date(2026, 10, 4)) # 월~일
+ assert p.start.weekday() == 0 and p.end.weekday() == 6 and p.days == 7
+ assert p.prev_anchor == date(2026, 9, 21)
+ m = calc.resolve_period("month", date(2026, 2, 15))
+ assert (m.start, m.end) == (date(2026, 2, 1), date(2026, 2, 28))
+ y = calc.resolve_period("year", wed)
+ assert (y.start, y.end) == (date(2026, 1, 1), date(2026, 12, 31))
+ c = calc.resolve_period("custom", wed, custom_from=date(2026, 9, 29), custom_to=date(2026, 9, 1))
+ assert (c.start, c.end) == (date(2026, 9, 1), date(2026, 9, 29))
+ # 진행 중인 주 — 전주 같은 요일까지만 비교
+ s, e, label = p.compare_range(today=wed)
+ assert (s, e) == (date(2026, 9, 21), date(2026, 9, 23)) and label.startswith("전주")
+ # 지난 주 — 전주 전체
+ s, e, _ = calc.resolve_period("week", date(2026, 9, 20)).compare_range(today=wed)
+ assert (s, e) == (date(2026, 9, 7), date(2026, 9, 13))
+ # 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
+ s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31))
+ assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28))
+ assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None
+
+
+def _cells_for(days, codes, amount=10_000):
+ return calc.build_cells({(d, c): amount for d in days for c in codes}, {"a": [(date(2000, 1, 1), Decimal("10"))]})
+
+
+def test_main_table_week():
+ p = calc.resolve_period("week", date(2026, 9, 30))
+ days = list(calc.daterange(p.start, p.end))
+ cells = _cells_for(days, ["a", "b"])
+ rows = calc.main_table(p, ["a", "b"], cells, today=date(2026, 9, 30), holidays={"2026-10-03": "개천절"})
+ assert [r["kind"] for r in rows] == ["day"] * 7 + ["week"]
+ assert rows[0]["label"] == "09/28(월)" and rows[6]["label"] == "10/04(일)"
+ assert rows[5]["holiday"] == "개천절" and rows[2]["today"] and rows[3]["future"]
+ week = rows[-1]
+ assert week["cells"]["a"] == {"gross": 70_000, "commission": 7_000, "net": 63_000}
+ assert week["cells"]["b"]["commission"] == 0 # 요율 없는 쇼핑몰 = 0%
+ assert week["total"]["gross"] == 140_000
+ assert rows[0]["total"]["gross"] == 20_000
+
+
+def test_main_table_month_and_year():
+ p = calc.resolve_period("month", date(2026, 9, 10))
+ cells = _cells_for(list(calc.daterange(p.start, p.end)), ["a"])
+ rows = calc.main_table(p, ["a"], cells, today=date(2026, 9, 30))
+ weeks = [r for r in rows if r["kind"] == "week"]
+ assert rows[-1]["kind"] == "total" and rows[-1]["total"]["gross"] == 300_000
+ assert sum(w["total"]["gross"] for w in weeks) == 300_000
+ assert weeks[0]["from"] == "2026-09-01" and weeks[0]["to"] == "2026-09-06" # 첫 주는 월 시작부터
+ y = calc.resolve_period("year", date(2026, 9, 10))
+ yrows = calc.main_table(y, ["a"], cells, today=date(2026, 9, 30))
+ assert len(yrows) == 13 and yrows[8]["total"]["gross"] == 300_000 and yrows[9]["future"]
+ ym = calc.year_months(2026, ["a"], cells, today=date(2026, 9, 30))
+ assert ym["rows"][9]["gross"] is None and ym["rows"][8]["gross"] == 300_000 and ym["total"]["gross"] == 300_000
+ ms = calc.month_summary(2026, 9, ["a"], cells)
+ assert ms["rows"][0]["share"] == 100.0 and ms["total"]["net"] == 270_000
+
+
+# ════════════════════════════════════════════════════════════
+# 가짜 저장소 + 인증정보
+# ════════════════════════════════════════════════════════════
+class FakeStore:
+ def __init__(self):
+ self.creds: dict[tuple[str, str], dict] = {}
+ self.events: dict[tuple[str, str, str], dict] = {}
+ self.status: dict[str, dict] = {}
+ self.running: set[str] = set()
+ self.markets = [{"code": a.code, "name": a.name, "enabled": True, "include_in_sales": True} for a in all_adapters()]
+
+ def credential_rows(self, code):
+ return {k: {**v, "updated_at": None} for (c, k), v in self.creds.items() if c == code}
+
+ def credential_keys_by_code(self):
+ out = {}
+ for c, k in self.creds:
+ out.setdefault(c, set()).add(k)
+ return out
+
+ def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""):
+ self.creds[(code, key)] = {"encrypted_value": encrypted_value, "key_version": key_version}
+
+ def delete_credential(self, code, key):
+ self.creds.pop((code, key), None)
+
+ def all_credential_rows(self):
+ return [{"marketplace_code": c, "credential_key": k, **v} for (c, k), v in self.creds.items()]
+
+ def list_marketplaces(self):
+ return self.markets
+
+ def start_run(self, code, **_):
+ if code in self.running:
+ return None
+ self.running.add(code)
+ return len(self.running)
+
+ def finish_run(self, run_id, **_):
+ self.running.clear()
+
+ def record_sync(self, code, *, status, ok, error=""):
+ self.status[code] = {"status": status, "ok": ok, "error": error}
+
+ def record_test(self, code, *, status, ok, error=""):
+ self.status[code] = {"status": status, "ok": ok, "error": error, "test": True}
+
+ def replace_events(self, code, start, end, events, *, id_prefix=""):
+ def mine(k, v):
+ return k[0] == code or (id_prefix and k[2].startswith(id_prefix))
+ self.events = {k: v for k, v in self.events.items()
+ if not (mine(k, v) and not v["is_sample"] and start <= v["sales_date"] <= end)}
+ return self.upsert_events(code, events)
+
+ def daily_breakdown(self, code, start, end, *, id_prefix=""):
+ days = {}
+ for (c, _, eid), v in self.events.items():
+ if v["is_sample"] or not (start <= v["sales_date"] <= end):
+ continue
+ if not (c == code or (id_prefix and eid.startswith(id_prefix))):
+ continue
+ r = days.setdefault(v["sales_date"].isoformat(), {"date": v["sales_date"].isoformat(), "paid": 0,
+ "orders": 0, "refund": 0, "synced_at": None})
+ if v["event_type"] == "SALE":
+ r["paid"] += v["amount"]
+ r["orders"] += 1
+ else:
+ r["refund"] -= v["amount"]
+ return sorted(days.values(), key=lambda r: r["date"])
+
+ def upsert_events(self, code, events, *, is_sample=False):
+ n = 0
+ for e in events:
+ target = e.get("marketplace_code") or code
+ self.events[(target, e["event_type"], e["external_event_id"])] = {**e, "is_sample": is_sample}
+ n += 1
+ return n
+
+
+def _coupang():
+ return next(a for a in all_adapters() if a.code == "coupang")
+
+
+def test_credentials_encrypted_and_never_returned():
+ st = FakeStore()
+ svc = CredentialService(st, lambda: ring())
+ ad = _coupang()
+ saved = svc.save(ad, {"vendor_id": "A00012345", "access_key": "AK-plain-111", "secret_key": "SK-plain-222",
+ "unknown": "x"}, user="t@x")
+ assert sorted(saved) == ["access_key", "secret_key", "vendor_id"]
+ for (code, key), row in st.creds.items():
+ assert "plain" not in row["encrypted_value"] and "A00012345" not in row["encrypted_value"]
+ assert row["encrypted_value"].startswith("v1:") and row["key_version"] == 1
+ info = svc.describe(ad)
+ as_text = repr(info)
+ assert "AK-plain-111" not in as_text and "SK-plain-222" not in as_text
+ by_key = {f["key"]: f for f in info["fields"]}
+ assert by_key["secret_key"]["has_value"] and "value" not in by_key["secret_key"]
+ assert by_key["vendor_id"]["value"] == "A00012345" and info["configured"]
+ # 빈 칸 = 유지, 다른 쇼핑몰 칸으로 옮긴 암호문은 풀리지 않음(AAD)
+ svc.save(ad, {"secret_key": "", "access_key": "AK-new"})
+ acc = svc.accessor("coupang")
+ assert acc.get("secret_key") == "SK-plain-222" and acc.get("access_key") == "AK-new"
+ moved = st.creds[("coupang", "secret_key")]["encrypted_value"]
+ try:
+ crypto.decrypt(moved, aad=aad_for("naver", "client_secret"), ring=ring())
+ except crypto.DecryptError:
+ pass
+ else:
+ raise AssertionError("다른 칸의 암호문은 복호화되면 안 됩니다")
+ # 재암호화(키 교체)
+ svc2 = CredentialService(st, lambda: ring(2, APP_ENCRYPTION_KEY_V1=KEY1))
+ assert svc2.reencrypt_all() == {"reencrypted": 3, "failed": 0}
+ assert all(r["key_version"] == 2 for r in st.creds.values())
+ assert svc2.accessor("coupang").get("secret_key") == "SK-plain-222"
+ assert svc2.configured_codes(list(all_adapters()))["coupang"] is True
+ assert svc2.configured_codes(list(all_adapters()))["naver"] is False
+ assert svc2.configured_codes(list(all_adapters()))["cafe24"] is True # 공통 연동
+
+
+# ════════════════════════════════════════════════════════════
+# 동기화
+# ════════════════════════════════════════════════════════════
+class _Leaky(MarketplaceAdapter):
+ code, name = "coupang", "쿠팡"
+
+ def credential_fields(self):
+ return [CredentialField("secret_key", "Secret", secret=True)]
+
+ def collect(self, ctx, start, end):
+ secret = ctx.credentials.get("secret_key")
+ raise AuthFailed(f"401 invalid signature for key {secret} Authorization: CEA abcdefg123")
+
+
+class _Good(MarketplaceAdapter):
+ code, name = "naver", "네이버"
+
+ def collect(self, ctx, start, end):
+ d = date(2026, 9, 29)
+ return 1, [
+ SaleEvent("SALE", "o1-S", "o1", d, 10_000, payment_date=d - timedelta(days=1), raw={"token": "t"}),
+ SaleEvent("CANCEL", "o1-C", "o1", d, -10_000),
+ ]
+
+
+def test_sync_isolation_redaction_and_dedupe():
+ import app.modules.performance.sync as syncmod
+
+ st = FakeStore()
+ creds = CredentialService(st, lambda: ring())
+ creds.save(_coupang(), {"vendor_id": "V", "access_key": "AK", "secret_key": "SUPER-SECRET-KEY-123"})
+ leaky, good = _Leaky(), _Good()
+ orig = syncmod.get_adapter
+ syncmod.get_adapter = lambda c: {"coupang": leaky, "naver": good}.get(c)
+ try:
+ svc = SyncService(st, creds)
+ r1 = svc.sync_marketplace("coupang", date(2026, 9, 23), date(2026, 9, 29))
+ r2 = svc.sync_marketplace("naver", date(2026, 9, 23), date(2026, 9, 29))
+ svc.sync_marketplace("naver", date(2026, 9, 23), date(2026, 9, 29)) # 두 번 = 중복 없음
+ finally:
+ syncmod.get_adapter = orig
+ assert not r1["ok"] and r1["status"] == "auth_failed"
+ assert "SUPER-SECRET-KEY-123" not in r1["message"] and "abcdefg123" not in r1["message"]
+ assert "SUPER-SECRET-KEY-123" not in st.status["coupang"]["error"]
+ assert r2["ok"] and r2["upserted"] == 2 and st.status["naver"]["status"] == "ok"
+ assert len([k for k in st.events if k[0] == "naver"]) == 2
+ sale = st.events[("naver", "SALE", "o1-S")]
+ assert sale["sales_date"] == date(2026, 9, 28) # 결제일 기준
+ assert st.events[("naver", "CANCEL", "o1-C")]["sales_date"] == date(2026, 9, 29) # 발생일 기준
+ assert sale["raw"]["token"] == MASK
+ # 이미 도는 중이면 건너뜀
+ st.running.add("naver")
+ syncmod.get_adapter = lambda c: good
+ try:
+ r3 = SyncService(st, creds).sync_marketplace("naver", date(2026, 9, 29), date(2026, 9, 29))
+ finally:
+ syncmod.get_adapter = orig
+ assert r3["skipped"]
+
+
+def test_not_implemented_and_mock():
+ st = FakeStore()
+ creds = CredentialService(st, lambda: ring())
+ svc = SyncService(st, creds)
+ gm = next(a for a in all_adapters() if a.code == "gmarket")
+ r = svc.sync_marketplace("gmarket", date(2026, 9, 29), date(2026, 9, 29))
+ assert r["status"] == "not_configured" # 키 미입력
+ secret = next(f.key for f in gm.visible_fields() if f.secret)
+ creds.save(gm, {f.key: ("k-123456" if f.key == secret else "v") for f in gm.visible_fields()})
+ r = svc.sync_marketplace("gmarket", date(2026, 9, 29), date(2026, 9, 29))
+ assert r["status"] == "not_implemented" and "k-123456" not in r["message"]
+ import httpx
+ orig_get, httpx.get = httpx.get, (lambda url, headers=None, timeout=None: httpx.Response(200, content=b""))
+ try:
+ t = svc.test_connection("elevenst", values={"api_key": "typed-only"})
+ finally:
+ httpx.get = orig_get
+ assert t["unsaved"] and "test" not in st.status.get("elevenst", {}) # 저장 안 한 값 시험은 상태 기록 안 함
+ a = mock.generate("naver", date(2026, 9, 1), date(2026, 9, 30))
+ b = mock.generate("naver", date(2026, 9, 1), date(2026, 9, 30))
+ assert [e.amount for e in a] == [e.amount for e in b] and a
+ for e in a:
+ e.validate()
+ assert (e.amount < 0) == (e.event_type in ("CANCEL", "RETURN"))
+ assert any(e.event_type == "CANCEL" for e in a)
+ n = svc.generate_samples(date(2026, 9, 1), date(2026, 9, 30), ["naver"])
+ assert n == len(a) and all(v["is_sample"] for v in st.events.values())
+ assert sales_date_for(a[0]) == a[0].payment_date
+ assert event_row(a[0])["sales_date"] == a[0].payment_date
+
+
+# ════════════════════════════════════════════════════════════
+# 카페24 어댑터(가짜 API 응답) — 카페24 "일별 매출내역" 기준
+# ════════════════════════════════════════════════════════════
+# 마켓 통합관리 경로 시험용 매핑 — 실제 MARKET_MAP 은 비어 있다(이 쇼핑몰은 마켓 통합관리 미사용)
+TEST_MARKET_MAP = {"shopn": "naver", "sk11st": "elevenst", "coupang": "coupang"}
+
+
+def _with_markets(fn):
+ import functools
+
+ @functools.wraps(fn)
+ def run():
+ from app.modules.performance.adapters import cafe24 as c24
+ saved = dict(c24.MARKET_MAP)
+ c24.MARKET_MAP.update(TEST_MARKET_MAP)
+ try:
+ fn()
+ finally:
+ c24.MARKET_MAP.clear()
+ c24.MARKET_MAP.update(saved)
+ return run
+
+
+def _c24_order(oid, market="self", paid="T", price=50_000, ship=3_000, coupon=5_000, member=1_000, items=2, **kw):
+ amt = {"order_price_amount": f"{price}.00", "shipping_fee": f"{ship}.00", "coupon_discount_price": f"{coupon}.00",
+ "membership_discount_amount": f"{member}.00", "points_spent_amount": "0.00",
+ "payment_amount": f"{price + ship - coupon - member}.00"}
+ return {"order_id": oid, "market_id": market, "paid": paid, "order_date": "2026-09-28T10:00:00+09:00",
+ "payment_date": "2026-09-29T11:21:35+09:00", "buyer_name": "홍길동", "receiver_address": "서울시",
+ "bank_account_no": "1234567890", "initial_order_amount": amt,
+ "actual_order_amount": {**amt, "order_price_amount": "0.00", "payment_amount": "0.00"}, # 취소 후 금액은 쓰지 않는다
+ "items": [{"order_item_code": f"{oid}-{i:02d}", "product_name": f"상품{i}", "quantity": 1}
+ for i in range(1, items + 1)], **kw}
+
+
+def _c24_refund(code, oid, amount, status="T", order_date="2026-09-20T09:00:00+09:00"):
+ return {"refund_code": code, "order_id": oid, "order_date": order_date, "refund_date": "2026-09-29T17:31:50+09:00",
+ "actual_refund_amount": f"{amount}.00", "used_points": "0.00", "used_credits": "0.00", "quantity": 1,
+ "order_item_code": [f"{oid}-01"], "status": status, "refund_bank_account_no": "1234567890"}
+
+
+class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist=["Cafe24Adapter"]).Cafe24Adapter):
+ def __init__(self, orders_pages, refunds_pages=(), lookup=None, claims=None):
+ self.orders_pages = orders_pages # 결제일 조회 페이지들
+ self.claims = claims or {} # date_type(취소/반품/교환 완료일) → 주문 목록
+ self.refunds_pages = list(refunds_pages)
+ self.lookup = lookup or {} # order_id → market_id (환불 원 주문 조회)
+ self.calls = []
+
+ def authenticate(self, ctx):
+ return None
+
+ def _get(self, ctx, path, params):
+ self.calls.append((path, params))
+ idx = params.get("offset", 0) // max(1, params.get("limit", 1))
+ if path == "/admin/refunds":
+ return {"refunds": self.refunds_pages[idx] if idx < len(self.refunds_pages) else []}
+ if params.get("date_type") == "order_date": # 원 주문 market_id 조회
+ ids = params["order_id"].split(",")
+ return {"orders": [{"order_id": i, "market_id": self.lookup.get(i, "self")} for i in ids]}
+ if params.get("date_type", "").endswith("_complete_date") or params.get("date_type") == "cancel_date":
+ return {"orders": self.claims.get(params["date_type"], []) if idx == 0 else []}
+ return {"orders": self.orders_pages[idx] if idx < len(self.orders_pages) else []}
+
+
+@_with_markets
+def test_cafe24_normalize_matches_daily_report():
+ from app.modules.performance.adapters.base import AdapterContext
+ from app.modules.performance.adapters.cafe24 import order_total, target_code
+
+ ctx = AdapterContext(code="cafe24", credentials=None)
+ fake = _FakeCafe24(
+ [[_c24_order("A", order_from_mobile="T", payment_method_name=["신용카드"]), _c24_order("B", market="shopn"),
+ _c24_order("C", paid="F"), _c24_order("D", market="auction", payment_method_name=["신용카드"]),
+ _c24_order("E", market="NCHECKOUT", payment_method_name=["네이버페이"]),
+ _c24_order("F", market="KAKAOPAY", payment_method_name=["카카오페이", "적립금"]),
+ _c24_order("G", market="mobile", order_from_mobile="T", payment_method_name=["무통장입금"])]],
+ [[_c24_refund("C20260929-01", "A", 12_610), _c24_refund("R20260929-02", "X", 20_000),
+ _c24_refund("C20260929-03", "M", 9_000), _c24_refund("C20260929-04", "A", 5_000, status="F")]],
+ lookup={"M": "shopn"},
+ )
+ fetched, events = fake.collect(ctx, date(2026, 9, 29), date(2026, 9, 29))
+ by = {(e.event_type, e.external_event_id): e for e in events}
+ # 결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰 (결제 당시 금액), 사건 ID 는 c24: 접두어
+ sale = by[("SALE", "c24:A-PAY")]
+ assert sale.amount == 50_000 + 3_000 - 1_000 - 5_000 == 47_000 and sale.marketplace_code == "cafe24"
+ assert sale.event_date == date(2026, 9, 29) and sale.quantity == 2 and sale.product_name == "상품1 외 1건"
+ # 마켓 연동 주문은 해당 쇼핑몰 열로, 연결표에 없는 마켓(옥션)은 카페24 열, 미결제는 제외
+ assert by[("SALE", "c24:B-PAY")].marketplace_code == "naver"
+ assert by[("SALE", "c24:D-PAY")].marketplace_code == "cafe24"
+ # 네이버페이·톡체크아웃·모바일웹은 카페24 자체몰 주문(실데이터 확인) — 네이버/카카오 열로 가면 안 된다
+ for oid in ("E", "F", "G"):
+ assert by[("SALE", f"c24:{oid}-PAY")].marketplace_code == "cafe24", oid
+ assert ("SALE", "c24:C-PAY") not in by
+ # 환불: 환불완료일, 실제 환불액, R→반품 / 그 밖→취소, 원 주문의 마켓 열로, 미완료 환불 제외
+ assert by[("CANCEL", "c24:C20260929-01")].amount == -12_610
+ assert by[("CANCEL", "c24:C20260929-01")].marketplace_code == "cafe24"
+ assert by[("RETURN", "c24:R20260929-02")].amount == -20_000
+ assert by[("CANCEL", "c24:C20260929-03")].marketplace_code == "naver"
+ assert ("CANCEL", "c24:C20260929-04") not in by
+ assert by[("CANCEL", "c24:C20260929-01")].event_date == date(2026, 9, 29)
+ for e in events:
+ assert "buyer_name" not in str(e.raw) and "1234567890" not in str(e.raw) # 개인정보 미저장
+ assert order_total({"naver_point": "151500.00", # 9/23 화면값
+ "initial_order_amount": {"order_price_amount": "1860800.00", "shipping_fee": "35000.00",
+ "coupon_discount_price": "21000.00", "payment_amount": "1713128.00",
+ "points_spent_amount": "10110.00"}}) == 1_874_738
+ assert target_code("self") == "cafe24" and target_code("SK11ST") == "elevenst"
+ assert target_code("unknown", "coupang") == "coupang" and target_code("unknown") == "cafe24"
+ assert target_code("NCHECKOUT", "NCHECKOUT") == "cafe24" and target_code("KAKAOPAY") == "cafe24"
+ assert target_code("naver") == "cafe24" and target_code("kakao") == "cafe24" # 결제수단과 헷갈리는 일반 이름 X
+ # 대조: 카페24 열(자체몰 채널+모르는 채널)/다른 쇼핑몰 열 + 주문 채널별
+ import app.timezone as _tz
+ _orig_today, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
+ try:
+ rec = fake.reconcile(ctx, date(2026, 9, 29))
+ finally:
+ _tz.today_kst = _orig_today
+ assert rec["orders"]["self"]["orders"] == 5 and rec["orders"]["self"]["total"] == 5 * 47_000 # A,D,E,F,G
+ assert rec["orders"]["market"]["orders"] == 1 and rec["unpaid_orders"] == 1 # B(스마트스토어)
+ assert rec["refunds"]["self"]["actual_refund_amount"] == 32_610 and rec["refunds"]["market"]["count"] == 1
+ ch = {b["market_id"]: b for b in rec["by_channel"]}
+ assert ch["shopn"]["kind"] == "market" and ch["shopn"]["target"] == "naver" and ch["shopn"]["refund_amount"] == 9_000
+ assert ch["auction"]["kind"] == "unknown" and ch["auction"]["target"] == "cafe24"
+ assert ch["NCHECKOUT"]["kind"] == "self" and ch["NCHECKOUT"]["label"] == "네이버페이"
+ assert ch["KAKAOPAY"]["label"] == "톡체크아웃" and ch["mobile"]["label"] == "모바일웹"
+ # 환불 기준 비교: 완료일(완료만) vs 접수일(전체 상태) — 가짜 API 는 두 기준에 같은 목록을 돌려준다
+ rb = rec["refund_basis"]
+ assert rb["completed"]["count"] == 3 and rb["completed"]["actual_refund_amount"] == 12_610 + 20_000 + 9_000
+ assert rb["accepted_all"]["count"] == 4 and rb["accepted_all"]["with_points"] == 12_610 + 20_000 + 9_000 + 5_000
+ assert {s["status"]: s["count"] for s in rb["accepted_by_status"]} == {"T": 3, "F": 1}
+ assert {c["key"] for c in rec["refund_candidates"]} >= {"completed", "completed_pts", "claim_pay"}
+ # 결제일 기준: 그날 결제된 카페24 열 주문(A,D,E,F,G)의 환불만 — X(결제 없음)·M(스마트스토어)·미완료 제외
+ bp = rec["refund_basis"]["by_pay_date"]
+ assert bp["count"] == 1 and bp["actual_refund_amount"] == 12_610
+ assert bp["amount_diff"] == 5 * 47_000 # 결제 당시 − 현재(가짜 현재 상품금액 0)
+ red = {x["order_id"]: x for x in rec["reduced_orders"]}
+ assert set(red) == {"A", "D", "E", "F", "G"} and red["A"]["refunded"] == 12_610 and red["D"]["refunded"] == 0
+ assert rec["reduced_orders"][-1]["order_id"] == "A" # 환불 기록으로 설명 안 되는 금액이 큰 순
+ assert {r["refund_code"] for r in rec["refund_list"]} == {"C20260929-01", "R20260929-02", "C20260929-03", "C20260929-04"}
+ assert "1234567890" not in str(rec["refund_list"]) # 환불 계좌 미노출
+ # 클레임 완료 품목: 환불 API 에 없는 취소(네이버페이 등)를 찾는다. 입금전취소·미완료는 합계 제외
+ item = lambda code, st, pay, price=10_000, qty=1: {"order_item_code": code, "order_status": st, "quantity": qty,
+ "product_price": f"{price}.00", "option_price": "0.00",
+ "payment_amount": f"{pay}.00", "product_name": "상품"}
+ fake4 = _FakeCafe24([[]], [[_c24_refund("C1", "A", 9_000)]], claims={
+ "cancel_complete_date": [
+ {**_c24_order("A"), "items": [item("A-01", "C40", 9_000)]},
+ {**_c24_order("N"), "market_id": "NCHECKOUT", "items": [item("N-01", "C40", 19_800, 20_000), item("N-02", "C40", 5_000, 5_000)]},
+ {**_c24_order("U"), "items": [item("U-01", "C48", 7_000)]},
+ {**_c24_order("P"), "items": [item("P-01", "C34", 3_000), item("P-02", "N40", 4_000)]}],
+ "return_complete_date": [{**_c24_order("N"), "items": [item("N-01", "C40", 19_800, 20_000)]},
+ {**_c24_order("R"), "items": [item("R-01", "R40", 12_000, 6_000, 2)]}],
+ })
+ rec4 = fake4.reconcile(ctx, date(2026, 9, 29))
+ cl = {c["item_code"]: c for c in rec4["claims"]["items"]}
+ assert set(cl) == {"A-01", "N-01", "N-02", "P-01", "R-01"} # 입금전취소(U)·정상 품목 제외, 중복 제거
+ assert cl["A-01"]["has_refund"] and not cl["N-01"]["has_refund"] and not cl["P-01"]["done"]
+ assert cl["R-01"]["product_amount"] == 12_000
+ assert rec4["claims"]["full_cancel_shipping"] == 3_000 * 2 # A, N 전체취소(배송비 3,000씩)
+ cand = {c["key"]: c["amount"] for c in rec4["refund_candidates"]}
+ assert cand["claim_pay"] == 9_000 + 19_800 + 5_000 + 12_000
+ assert cand["completed_plus_noref"] == 9_000 + 19_800 + 5_000 + 12_000
+ # 기기: PC 채널(self)이어도 휴대폰 주문(order_from_mobile=T)은 모바일
+ assert ch["self"]["mobile_orders"] == 1 and ch["self"]["pc_orders"] == 0 and ch["self"]["mobile_total"] == 47_000
+ assert ch["NCHECKOUT"]["pc_orders"] == 1 and ch["mobile"]["mobile_orders"] == 1
+ # self 는 PC 전용이 아니다 — 주문경로(PC쇼핑몰/모바일웹)별로 한 줄씩(실데이터 확인)
+ fake3 = _FakeCafe24([[_c24_order("P1", order_place_name="PC쇼핑몰"), _c24_order("P2", order_place_name="PC쇼핑몰"),
+ _c24_order("M1", order_place_name="모바일웹", order_from_mobile="T")]])
+ rows3 = {(b["market_id"], b["place"]): b for b in fake3.reconcile(ctx, date(2026, 9, 29))["by_channel"]}
+ assert rows3[("self", "PC쇼핑몰")]["orders"] == 2 and rows3[("self", "모바일웹")]["mobile_orders"] == 1
+ assert rows3[("self", "PC쇼핑몰")]["label"] == "자체몰"
+ # 결제수단별(카페24 열만 — 외부 마켓 B 제외)
+ pay = {p["method"]: p for p in rec["by_payment"]}
+ assert pay["신용카드"]["orders"] == 2 and pay["신용카드"]["total"] == 94_000
+ assert pay["카카오페이 + 적립금"]["orders"] == 1 and "네이버페이" in pay and "무통장입금" in pay
+ assert sum(p["orders"] for p in rec["by_payment"]) == 5
+ # 60일 단위 분할 + 페이지 넘김(1000건이면 다음 페이지)
+ page1 = [_c24_order(f"x-{i}") for i in range(1000)]
+ fake2 = _FakeCafe24([page1, [_c24_order("y")]])
+ got = list(fake2.paid_orders(ctx, date(2026, 7, 1), date(2026, 9, 30)))
+ calls = [p for path, p in fake2.calls if path == "/admin/orders"]
+ assert len(got) == 2002 # 60일 구간 2개 × (1000건 페이지 + 다음 페이지 1건)
+ assert calls[0]["start_date"] == "2026-07-01" and calls[0]["end_date"] == "2026-08-29"
+ assert calls[1]["offset"] == 1000 and all(c["limit"] == 1000 and c["date_type"] == "pay_date" for c in calls)
+
+
+def test_cafe24_refund_total_includes_points_and_naverpay_cancels():
+ """카페24 일별 매출 환불합계 = 환불 목록(실제 + 적립금·예치금) + 환불 목록에 없는 취소·반품(네이버페이 등).
+ 실데이터: 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800, 9/27 = 145,000 + 네이버페이 55,800."""
+ import app.timezone as _tz
+ from app.modules.performance.adapters.base import AdapterContext
+
+ ctx = AdapterContext(code="cafe24", credentials=None)
+ item = lambda code, st, price, qty=1, day="2026-09-26 15:00:00", **kw: {
+ "order_item_code": code, "order_status": st, "quantity": qty, "product_price": f"{price}.00",
+ "option_price": "0.00", "product_name": "상품", "cancel_date": day, **kw}
+ refund = {**_c24_refund("C20260926-01", "O1", 63_720), "used_points": "1080.00",
+ "refund_date": "2026-09-26T20:25:08+09:00"}
+ fake = _FakeCafe24([[]], [[refund]], claims={
+ "cancel_date": [
+ {**_c24_order("O1"), "items": [item("O1-01", "C40", 64_800)]}, # 환불 목록 있음 → 제외
+ {**_c24_order("NP1", market="NCHECKOUT"), "items": [item("NP1-01", "C40", 55_800),
+ item("NP1-02", "N40", 9_000)]}, # 정상 품목 제외
+ {**_c24_order("NP2", market="NCHECKOUT"), "items": [item("NP2-01", "C40", 20_000, 2,
+ coupon_discount_price="1000.00")]},
+ {**_c24_order("NP3", market="NCHECKOUT"), "items": [item("NP3-01", "C40", 5_000, day="2026-09-27 01:00:00")]},
+ {**_c24_order("NP4", market="NCHECKOUT"), "items": [item("NP4-01", "C00", 5_000)]}, # 취소신청만 → 제외
+ # 전체취소 두 품목 — 배송비(3,000)는 마지막 품목(NP5-02)에 한 번만. 앞 품목은 전날 취소(기간 밖)
+ {**_c24_order("NP5", market="NCHECKOUT"), "items": [item("NP5-01", "C40", 7_000, day="2026-09-25 10:00:00"),
+ item("NP5-02", "C40", 8_000)]},
+ {**_c24_order("KP1", market="KAKAOPAY"), "items": [item("KP1-01", "C40", 9_900)]}, # 톡체크아웃 → 제외
+ {**_c24_order("S1"), "items": [item("S1-01", "R40", 9_900)]}, # 자체몰 → 제외
+ ],
+ "return_complete_date": [{**_c24_order("NP1", market="NCHECKOUT"),
+ "items": [item("NP1-01", "C40", 55_800), item("NP1-02", "N40", 9_000)]}],
+ })
+ orig, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
+ try:
+ _, events = fake.collect(ctx, date(2026, 9, 26), date(2026, 9, 26))
+ rec = fake.reconcile(ctx, date(2026, 9, 26))
+ finally:
+ _tz.today_kst = orig
+ by = {e.external_event_id: e for e in events if e.event_type != "SALE"}
+ assert by["c24:C20260926-01"].amount == -(63_720 + 1_080) # 적립금 환불 포함
+ assert by["c24:NP1-01-CL"].amount == -55_800 and by["c24:NP1-01-CL"].event_type == "CANCEL"
+ assert by["c24:NP1-01-CL"].event_date == date(2026, 9, 26) and by["c24:NP1-01-CL"].marketplace_code == "cafe24"
+ assert by["c24:NP2-01-CL"].amount == -(40_000 - 1_000 + 3_000) # 판매가×수량 − 품목 쿠폰 + 전체취소 배송비
+ assert by["c24:NP5-02-CL"].amount == -(8_000 + 3_000) # 배송비는 마지막 품목에 한 번
+ # 다른 날·신청·환불 기록 있는 주문·톡체크아웃·자체몰 제외
+ assert set(by) == {"c24:C20260926-01", "c24:NP1-01-CL", "c24:NP2-01-CL", "c24:NP5-02-CL"}
+ rs = rec["refunds"]["self"]
+ assert rs["no_record_count"] == 3 and rs["no_record"] == 55_800 + 42_000 + 11_000
+ assert rs["total"] == 63_720 + 1_080 + 55_800 + 42_000 + 11_000
+ cand = {c["key"]: c["amount"] for c in rec["refund_candidates"]}
+ assert cand["applied"] == rs["total"]
+ assert {c["item_code"] for c in rec["no_record_claims"]} == {"NP1-01", "NP2-01", "NP5-02"}
+
+
+@_with_markets
+def test_cafe24_scope_and_replace_range():
+ import app.modules.performance.sync as syncmod
+ from app.modules.performance.adapters.base import AdapterContext
+ from app.modules.performance.adapters.cafe24 import Cafe24Adapter
+
+ ctx = AdapterContext(code="cafe24", credentials=None)
+ real = Cafe24Adapter()
+ real.shared_status = lambda c: {"connected": True, "scopes": "mall.read_product,mall.write_product"}
+ try:
+ real.authenticate(ctx)
+ except AuthFailed as exc:
+ assert "mall.read_order" in exc.message
+ else:
+ raise AssertionError("주문 권한 없으면 인증 실패여야 합니다")
+ real.shared_status = lambda c: {"connected": True, "scopes": "mall.read_product,mall.read_order"}
+ real.authenticate(ctx)
+
+ def ev(eid, day, **kw):
+ return {"event_type": "SALE", "external_event_id": eid, "external_order_id": "o",
+ "event_date": day, "sales_date": day, "amount": 1, **kw}
+
+ # 기간 교체: 기간 안 카페24 행(예전 품목 단위)·카페24 경유 네이버 행은 지우고,
+ # 네이버 직접 연동분·테스트 데이터·기간 밖은 남긴다
+ st = FakeStore()
+ d, out = date(2026, 9, 29), date(2026, 9, 1)
+ st.upsert_events("cafe24", [ev("old-item-S", d), ev("outside", out)])
+ st.upsert_events("naver", [ev("c24:OLD-PAY", d), ev("direct-naver-1", d)])
+ st.upsert_events("cafe24", [ev("sample", d)], is_sample=True)
+ fake = _FakeCafe24([[_c24_order("A"), _c24_order("B", market="shopn")]])
+ orig = syncmod.get_adapter
+ syncmod.get_adapter = lambda c: fake
+ try:
+ r = SyncService(st, CredentialService(st, lambda: ring())).sync_marketplace("cafe24", d, d)
+ finally:
+ syncmod.get_adapter = orig
+ got = {(k[0], k[2]) for k in st.events}
+ assert r["ok"], r
+ assert got == {("cafe24", "c24:A-PAY"), ("naver", "c24:B-PAY"), ("cafe24", "outside"),
+ ("naver", "direct-naver-1"), ("cafe24", "sample")}, got
+
+
+def test_cafe24_paid_total_matches_daily_report():
+ """카페24 결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트(결제 당시). 상품식과 다를 수 있다.
+ 실데이터 9/23: 1,713,128 + 10,110 + 0 + 151,500 = 1,874,738 (상품식 1,874,800)."""
+ from app.modules.performance.adapters.cafe24 import order_total, order_total_now
+
+ o = _c24_order("A", naver_point="3000.00") # 상품식 50,000 + 3,000 − 1,000 − 5,000 = 47,000
+ o["initial_order_amount"].update(payment_amount="42938.00", points_spent_amount="1000.00")
+ assert order_total(o) == 42_938 + 1_000 + 3_000 == 46_938
+ ev = _FakeCafe24([]).normalize_order(o)[0]
+ assert ev.amount == 46_938 and ev.discount_amount == 1_000 + 5_000
+ o["actual_order_amount"] = {**o["initial_order_amount"], "payment_amount": "20000.00"}
+ assert order_total_now(o) == 20_000 + 1_000 + 3_000
+ z = _c24_order("Z")
+ z["initial_order_amount"]["payment_amount"] = "0.00"
+ assert order_total(z) == 0 # 결제 필드가 모두 0이면 카페24도 0원
+ # 대조 진단: 원본 금액 필드 합계 + 이상 주문(개인정보 숫자 필드는 제외)
+ import app.timezone as _tz
+ from app.modules.performance.adapters.base import AdapterContext
+ from app.modules.performance.adapters.cafe24 import money_fields
+
+ got = money_fields({"bank_account_no": "1234567890", "order_price_amount": "100.50", "x": {"coupon_discount_price": 3}})
+ assert got == {"order_price_amount": 101, "x.coupon_discount_price": 3}
+ o2 = _c24_order("B", price=10_050)
+ o2["items"] = [{"order_item_code": "B-01", "product_price": "10000.00", "option_price": "0", "quantity": 1,
+ "order_status": "N40"}]
+ orig, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
+ try:
+ rec = _FakeCafe24([[o, o2]]).reconcile(AdapterContext(code="cafe24", credentials=None), date(2026, 9, 29))
+ finally:
+ _tz.today_kst = orig
+ assert rec["diag"]["order"]["naver_point"] == 3_000
+ assert rec["diag"]["initial"]["order_price_amount"] == 60_050 and "bank_account_no" not in rec["diag"]["order"]
+ odd = {x["order_id"]: x for x in rec["odd_orders"]}
+ assert odd["B"]["items_gross"] == 10_000 and odd["B"]["order_price_amount"] == 10_050
+
+
+@_with_markets
+def test_daily_check_db_vs_live():
+ """일별 비교: 저장값(카페24 경유 다른 마켓 열 포함) + 지금 API 값(저장 안 함)."""
+ import app.modules.performance.sync as syncmod
+
+ st = FakeStore()
+ d = date(2026, 9, 29)
+ ev = lambda eid, t, amt, **kw: {"event_type": t, "external_event_id": eid, "external_order_id": "o",
+ "event_date": d, "sales_date": d, "amount": amt, **kw}
+ st.upsert_events("cafe24", [ev("c24:A-PAY", "SALE", 40_000), ev("c24:R1", "CANCEL", -5_000)])
+ st.upsert_events("naver", [ev("c24:B-PAY", "SALE", 10_000), ev("direct-1", "SALE", 99_999)])
+ fake = _FakeCafe24([[_c24_order("A"), _c24_order("B", market="shopn"), _c24_order("C")]],
+ [[_c24_refund("C20260929-01", "A", 7_000)]])
+ orig = syncmod.get_adapter
+ syncmod.get_adapter = lambda c: fake
+ try:
+ svc = SyncService(st, CredentialService(st, lambda: ring()))
+ only_db = svc.daily_check("cafe24", d, d)
+ both = svc.daily_check("cafe24", d, d, live=True)
+ finally:
+ syncmod.get_adapter = orig
+ assert "live" not in only_db
+ assert both["db"] == [{"date": "2026-09-29", "paid": 50_000, "orders": 2, "refund": 5_000, "synced_at": None}]
+ assert both["live"] == [{"date": "2026-09-29", "paid": 3 * 47_000, "orders": 3, "refund": 7_000}]
+ assert len(st.events) == 4 # 저장값은 바뀌지 않음
+
+
+def test_cafe24_market_map_empty_by_default():
+ """마켓 통합관리 미사용 — 카페24로 들어온 주문은 market_id 가 무엇이든 카페24 열."""
+ from app.modules.performance.adapters.cafe24 import MARKET_MAP, target_code
+
+ assert MARKET_MAP == {}
+ assert target_code("shopn") == target_code("coupang", "coupang") == target_code("NCHECKOUT") == "cafe24"
+
+
+def test_coupang_hmac_and_connection_errors():
+ """쿠팡 CEA HMAC 서명(공식 예제 방식) + 연결 테스트 오류 구분. 비밀값은 메시지에 없다."""
+ import hashlib
+ import hmac as _hmac
+
+ import httpx
+
+ from app.modules.performance.adapters import coupang as cp
+ from app.modules.performance.adapters.base import AdapterContext
+
+ q = cp.build_query({"createdAtFrom": "2026-09-30+09:00", "status": "ACCEPT", "maxPerPage": 1})
+ assert q == "createdAtFrom=2026-09-30%2B09:00&status=ACCEPT&maxPerPage=1"
+ now = 1_790_000_000 # 2026-09-21 14:13:20 UTC
+ h = cp.authorization("GET", "/p", q, "AK", "SK", now=now)
+ dt = "260921T141320Z"
+ sig = _hmac.new(b"SK", f"{dt}GET/p{q}".encode(), hashlib.sha256).hexdigest()
+ assert h == f"CEA algorithm=HmacSHA256, access-key=AK, signed-date={dt}, signature={sig}"
+
+ class Creds(dict):
+ def get(self, k, default=""):
+ return dict.get(self, k, default)
+
+ def has(self, k):
+ return bool(dict.get(self, k))
+
+ ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK-1", secret_key="SK-SECRET"))
+ seen = {}
+
+ def fake_get(url, headers=None, timeout=None, status=200, body=None):
+ seen["url"], seen["auth"] = url, headers["Authorization"]
+ return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
+
+ orig = httpx.get
+ try:
+ httpx.get = fake_get
+ msg = cp.CoupangAdapter().test_connection(ctx)
+ assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"]
+ assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"]
+ httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
+ try:
+ cp.CoupangAdapter().test_connection(ctx)
+ except AuthFailed as exc:
+ assert "403" in exc.message and "자체개발" in exc.message and "SK-SECRET" not in exc.message
+ else:
+ raise AssertionError("403 이면 인증 실패여야 합니다")
+ finally:
+ httpx.get = orig
+
+
+def test_elevenst_connection():
+ """11번가: openapikey 헤더 + 결제완료 주문 조회(XML). 오류 코드·403 구분, 키는 메시지에 없음."""
+ import httpx
+
+ from app.modules.performance.adapters import elevenst as ev
+ from app.modules.performance.adapters.base import AdapterContext
+
+ class Creds(dict):
+ def get(self, k, default=""):
+ return dict.get(self, k, default)
+
+ def has(self, k):
+ return bool(dict.get(self, k))
+
+ ctx = AdapterContext(code="elevenst", credentials=Creds(api_key="KEY-11ST-SECRET"))
+ seen = {}
+ ok_xml = ('12'
+ '').encode("euc-kr")
+
+ def fake(status, content):
+ def get(url, headers=None, timeout=None):
+ seen["url"], seen["key"] = url, headers["openapikey"]
+ return httpx.Response(status, content=content)
+ return get
+
+ orig = httpx.get
+ try:
+ httpx.get = fake(200, ok_xml)
+ msg = ev.ElevenstAdapter().test_connection(ctx)
+ assert "연결 정상" in msg and "2건" in msg and seen["key"] == "KEY-11ST-SECRET"
+ assert "/rest/ordservices/complete/" in seen["url"]
+ err = '-1허용되지 않은 IP'
+ for status, body, kind in ((200, err.encode(), ApiError), (403, b"Forbidden", AuthFailed),
+ (200, b"IP not allowed", ApiError)):
+ httpx.get = fake(status, body)
+ try:
+ ev.ElevenstAdapter().test_connection(ctx)
+ except kind as exc:
+ assert "KEY-11ST-SECRET" not in exc.message
+ assert status == 403 or "허용되지 않은 IP" in exc.message or "XML 아님" in exc.message
+ else:
+ raise AssertionError("오류여야 합니다")
+ # 원본 데이터 확인: 살아 있는 주소는 항목 합계, 없는 주소(404)는 실패로. 개인정보 값은 숨김
+ rows = ("" + "".join(
+ f"{n}{a}홍길동상품{n}"
+ f"2026-09-29 10:00:00" for n, a in ((1, 10000), (2, 5500))) +
+ "").encode()
+
+ def route(url, headers=None, timeout=None):
+ if "/ordservices/complete/" in url:
+ return httpx.Response(200, content=rows)
+ if "/ordservices/purchaseconfirm/" in url:
+ return httpx.Response(404, content=b"not found")
+ if "/ordservices/" in url:
+ return httpx.Response(200, content=b"")
+ if "/claimservice/" in url:
+ return httpx.Response(200, content="-1"
+ "해당 건이 없습니다.".encode())
+ return httpx.Response(404, content=b"not found")
+ httpx.get = route
+ rec = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 29))
+ wide = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 1), to=date(2026, 9, 20)) # 7일씩 3번
+ assert wide["to"] == "2026-09-20" and {p["key"]: p.get("count") for p in wide["probes"]}["complete"] == 6
+ by = {p["key"]: p for p in rec["probes"]}
+ assert by["complete"]["ok"] and by["complete"]["count"] == 2 and by["shipping"]["count"] == 0
+ assert not by["purchaseconfirm"]["ok"] and "404" in by["purchaseconfirm"]["error"]
+ assert by["canceledorders"]["ok"] and by["canceledorders"]["count"] == 0 # 코드 -1 "해당 건이 없습니다" = 0건
+ f = {x["name"]: x for x in by["complete"]["fields"]}
+ assert f["ordPayAmt"]["sum"] == 15_500 and f["rcvrNm"]["personal"] and f["rcvrNm"]["sample"] == ""
+ assert f["prdNm"]["sample"] == "상품1" and "홍길동" not in repr(rec)
+ finally:
+ httpx.get = orig
+
+
+def test_elevenst_collect_sales():
+ """11번가 매출 = 주문 단위, 결제일 기준.
+ 정산된 주문은 정산 내역의 판매금액합계(selPrcAmt) 합 — 셀러오피스 "판매 상세내역"과 같다(배송비 줄 포함).
+ 정산 전 주문은 주문 상태 목록의 ordAmt + 배송비. 실데이터: 9/9 = 34,900, 9/10 = 83,800 + 배송비 3,000 = 86,800
+ (주문 목록의 dlvCst 는 0 이라 정산 값을 써야 맞음)."""
+ import httpx
+
+ import app.modules.performance.sync as syncmod # noqa: F401
+ import app.timezone as _tz
+
+ def line(no, seq, day, amt, pay, ship=0, qty=1):
+ return (f"{no}{seq}{day} 15:13:16"
+ f"{amt}{pay}{ship}{qty}"
+ f"밀폐용기홍길동18550503")
+
+ def stl(no, pay_day, amt, qty, cupn=0):
+ return (f"{no}1홍길동"
+ f"{pay_day}2026/09/19밀폐용기{qty}"
+ f"{amt}{amt - 100}{cupn}")
+ settlement = ("" + stl("20260909099415322", "2026/09/09", 34900, 1) +
+ stl("20260910099718265", "2026/09/10", 3000, 0) + stl("20260910099718265", "2026/09/10", 83800, 2, 11060) +
+ stl("20260801000000009", "2026/08/01", 9999, 1) + "").encode()
+ completed = ("" + line("20260909099415322", 1, "2026-09-09", 34900, 34900) +
+ line("20260910099718265", 1, "2026-09-10", 83800, 72740, qty=2) +
+ line("20260801000000001", 1, "2026-08-01", 5000, 5000) + "").encode()
+ packaging = ("" + line("20260911000000002", 1, "2026-09-11", 20000, 20000, ship=3000) +
+ line("20260911000000002", 2, "2026-09-11", 5000, 5000, ship=3000) +
+ line("20260911000000002", 2, "2026-09-11", 5000, 5000, ship=3000) + "").encode()
+ empty = "-1해당 건이 없습니다.".encode()
+ calls = []
+
+ def route(url, headers=None, timeout=None):
+ calls.append(url)
+ if "/settlement/" in url:
+ return httpx.Response(200, content=settlement if "/20260916/" in url else empty)
+ if "/ordservices/completed/" in url:
+ return httpx.Response(200, content=completed)
+ if "/ordservices/packaging/" in url:
+ return httpx.Response(200, content=packaging)
+ return httpx.Response(200, content=empty)
+
+ st = FakeStore()
+ creds = CredentialService(st, lambda: ring())
+ creds.save(next(a for a in all_adapters() if a.code == "elevenst"), {"api_key": "KEY-11ST"})
+ orig, orig_today = httpx.get, _tz.today_kst
+ httpx.get, _tz.today_kst = route, (lambda: date(2026, 9, 30))
+ try:
+ r = SyncService(st, creds).sync_marketplace("elevenst", date(2026, 9, 9), date(2026, 9, 11))
+ finally:
+ httpx.get, _tz.today_kst = orig, orig_today
+ assert r["ok"], r
+ ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "elevenst"}
+ assert set(ev_) == {"11st:20260909099415322", "11st:20260910099718265", "11st:20260911000000002"} # 8/1 제외
+ assert ev_["11st:20260909099415322"]["amount"] == 34_900 and ev_["11st:20260909099415322"]["sales_date"] == date(2026, 9, 9)
+ assert ev_["11st:20260910099718265"]["amount"] == 86_800 # 정산 값(배송비 줄 포함)
+ assert ev_["11st:20260910099718265"]["discount_amount"] == 11_060 and ev_["11st:20260910099718265"]["quantity"] == 2
+ assert ev_["11st:20260910099718265"]["order_status"] == "정산확정"
+ assert ev_["11st:20260911000000002"]["amount"] == 25_000 + 3_000 # 정산 전: ordAmt + 배송비 한 번, 중복 줄 1번
+ assert ev_["11st:20260911000000002"]["order_status"] == "발송대기"
+ assert "홍길동" not in repr(st.events) and "18550503" not in repr(st.events) # 구매자 정보 미저장
+ assert any("/20260930" in u for u in calls) and not any("/20261001" in u for u in calls) # 오늘까지만 더 불러옴
+
+
+def test_registry_and_event_validation():
+ codes = [a.code for a in all_adapters()]
+ assert len(codes) == len(set(codes)) == 10
+ for a in all_adapters():
+ keys = [f.key for f in a.credential_fields()]
+ assert len(keys) == len(set(keys)), a.code
+ assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
+ for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
+ SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
+ try:
+ bad.validate()
+ except ValueError:
+ pass
+ else:
+ raise AssertionError(f"검증 실패해야 함: {bad.event_type} {bad.amount}")
+
+
+if __name__ == "__main__":
+ os.environ.pop("APP_ENCRYPTION_KEY", None)
+ n = 0
+ for name, fn in sorted(globals().items()):
+ if name.startswith("test_") and callable(fn):
+ fn()
+ n += 1
+ print("ok", name)
+ print(f"{n} tests passed")
diff --git a/app/static/erp-dialog.css b/app/static/erp-dialog.css
index 8c3debb..5bdfb42 100644
--- a/app/static/erp-dialog.css
+++ b/app/static/erp-dialog.css
@@ -54,6 +54,11 @@
color: var(--color-callout-red, #c22b10);
}
+/* 성공 알림(erpAlert(msg, { tone: "ok" })) — 초록 체크 */
+.erp-dialog-icon.is-ok {
+ color: #0f8a3a;
+}
+
/* 확인(질문)용은 붉은 경고색 대신 차분한 검정으로 */
.erp-dialog-ask .erp-dialog-icon {
color: var(--color-rich-black, #0a0a0a);
diff --git a/app/static/erp-dialog.js b/app/static/erp-dialog.js
index 57ef137..bebf855 100644
--- a/app/static/erp-dialog.js
+++ b/app/static/erp-dialog.js
@@ -8,6 +8,7 @@
erpConfirm("지울까요?").then(function (ok) { if (ok) ... });
erpAlert("실패했습니다.").then(...)
erpPrompt("주소를 입력하세요", "https://").then(function (v) { if (v) ... }); // 취소면 null
+ erpAlert("저장했습니다.", { tone: "ok" }) // 성공 알림 — 경고 삼각형 대신 초록 체크
창 제목은 기본 "No.1 King ERP 프로그램". 화면마다 바꾸려면 그 화면 스크립트에서
window.ERP_DIALOG_TITLE = "..." 를 두거나, 한 번만 options.title 로 넘긴다.
@@ -31,6 +32,14 @@
'' +
"";
+ // 성공(tone: "ok") — 원 안의 체크.
+ var ICON_OK =
+ '";
+
function titleOf(options) {
return options.title || window.ERP_DIALOG_TITLE || TITLE;
}
@@ -54,8 +63,8 @@
body.className = "erp-dialog-body";
var icon = document.createElement("span");
- icon.className = "erp-dialog-icon";
- icon.innerHTML = ICON;
+ icon.className = "erp-dialog-icon" + (options.tone === "ok" ? " is-ok" : "");
+ icon.innerHTML = options.tone === "ok" ? ICON_OK : ICON;
var text = document.createElement("p");
text.className = "erp-dialog-message";
diff --git a/app/static/performance.css b/app/static/performance.css
new file mode 100644
index 0000000..1231438
--- /dev/null
+++ b/app/static/performance.css
@@ -0,0 +1,231 @@
+/* ════════════════════════════════════════════════════
+ 실적(쇼핑몰 통합 매출) — 정보 밀도 높은 관리자 대시보드.
+ 기존 ERP 토큰(erp.css :root) 위에서만 쓴다. 색은 증감·상태·주말에만.
+ ════════════════════════════════════════════════════ */
+/* 색 변수 — 창(.perf-modal)은 document.body 에 붙어 .perf 밖이라 같이 정의한다 */
+.perf, .perf-modal {
+ --perf-line: var(--color-subtle-ash);
+ --perf-soft: #fafafa;
+ --perf-up: #0f8a3a;
+ --perf-down: var(--color-callout-red);
+ --perf-sat: #1d4ed8;
+ --perf-sun: var(--color-callout-red);
+}
+.perf {
+ display: flex; flex-direction: column; gap: 12px;
+ font-variant-numeric: tabular-nums;
+}
+/* 공통 .erp-page 는 width:100% + padding 이라 부모보다 48px 넓어져 오른쪽이 잘린다.
+ 전역 규칙은 다른 모듈에 영향이 있어, 실적 화면이 들어 있을 때만 border-box 로 맞춘다. */
+.erp-page:has(> .perf) { box-sizing: border-box; }
+.perf, .perf > * { min-width: 0; }
+.perf-muted { color: var(--color-midtone-gray); font-size: 12px; }
+.perf-nowrap { white-space: nowrap; }
+.perf-center { text-align: center; }
+
+/* 탭 */
+.perf-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--perf-line); }
+.perf-tab {
+ padding: 8px 14px; font-size: 13px; font-weight: 500; color: var(--color-midtone-gray);
+ border-bottom: 2px solid transparent; margin-bottom: -1px;
+}
+.perf-tab:hover { color: var(--color-rich-black); }
+.perf-tab.is-active { color: var(--color-rich-black); border-bottom-color: var(--color-rich-black); }
+
+/* 도구 막대 */
+.perf-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
+.perf-quick, .perf-metric { display: inline-flex; border: 1px solid var(--perf-line); border-radius: 10px; padding: 2px; background: #fff; }
+.perf-seg {
+ border: 0; background: transparent; font: inherit; font-size: 12px; font-weight: 500;
+ padding: 5px 11px; border-radius: 8px; cursor: pointer; color: var(--color-rich-black); white-space: nowrap;
+}
+.perf-seg:hover { background: var(--color-ghost-gray); }
+.perf-seg.is-active { background: var(--color-deep-black); color: #fff; }
+a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited { color: #fff; }
+.perf-nav { display: inline-flex; align-items: center; gap: 6px; }
+.perf-nav-btn {
+ font-size: 12px; padding: 5px 9px; border: 1px solid var(--perf-line); border-radius: 8px; background: #fff;
+ white-space: nowrap;
+}
+.perf-nav-btn:hover { background: var(--color-ghost-gray); }
+.perf-nav-label { font-weight: 600; font-size: 14px; min-width: 200px; text-align: center; }
+.perf-custom { display: inline-flex; align-items: center; gap: 6px; }
+.perf-custom[hidden] { display: none; }
+/* 공통 .erp-input 의 min-width:240px 를 날짜칸에서만 푼다 */
+.perf .erp-input.perf-date { width: 150px; min-width: 0; flex: 0 0 auto; padding: 5px 8px !important; font-size: 12px !important; }
+.perf-modal .erp-input.perf-date { width: 150px; min-width: 0; }
+.perf-filter { position: relative; }
+.perf-filter > summary { list-style: none; cursor: pointer; }
+.perf-filter > summary::-webkit-details-marker { display: none; }
+.perf-filter-pop {
+ position: absolute; z-index: 20; top: calc(100% + 6px); left: 0; min-width: 220px;
+ background: #fff; border: 1px solid var(--perf-line); border-radius: 12px; padding: 10px;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, .1); display: flex; flex-direction: column; gap: 4px;
+}
+.perf-check { display: flex; align-items: center; gap: 6px; font-size: 13px; padding: 3px 2px; cursor: pointer; }
+.perf-filter-act { display: flex; justify-content: space-between; margin-top: 6px; }
+.perf-update { margin-left: auto; display: inline-flex; align-items: center; gap: 10px; }
+.perf-update b { color: var(--color-rich-black); font-weight: 600; }
+
+/* 알림 */
+.perf-notice {
+ font-size: 12.5px; padding: 8px 12px; border-radius: 10px; background: var(--perf-soft);
+ border: 1px solid var(--perf-line); display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center;
+}
+.perf-notice[hidden] { display: none; }
+.perf-notice.is-warn { background: #fff7f5; border-color: #f3d2ca; }
+.perf-notice.is-ok { background: #f3fbf5; border-color: #cdeccf; }
+.perf-problem { padding: 1px 8px; border-radius: 999px; background: #fbe9e6; color: var(--perf-down); font-weight: 500; }
+
+/* KPI */
+.perf-kpis { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px; }
+.perf-kpi { border: 1px solid var(--perf-line); border-radius: 12px; padding: 12px 14px; background: #fff; min-width: 0; }
+.perf-kpi.is-primary { border-color: #cfcfcf; box-shadow: inset 3px 0 0 var(--color-deep-black); }
+.perf-kpi-label { font-size: 12px; color: var(--color-midtone-gray); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.perf-kpi-value { font-size: 22px; font-weight: 600; letter-spacing: -.5px; margin: 2px 0; white-space: nowrap; }
+.perf-kpi.is-primary .perf-kpi-value { font-size: 24px; }
+.perf-kpi-delta { font-size: 12px; display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
+.perf-delta { font-weight: 600; }
+.perf-delta.is-up { color: var(--perf-up); }
+.perf-delta.is-down { color: var(--perf-down); }
+.perf-delta.is-flat { color: var(--color-midtone-gray); }
+
+/* 카드 */
+.perf-card { padding: 12px 14px; }
+.perf-card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; }
+.perf-h { margin: 0; font-size: 14px; font-weight: 600; }
+.perf-grid2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
+.perf-grid2 > .perf-card-wide { grid-column: 1 / -1; } /* 표가 넓은 카드(매출 대조)는 한 줄 전체 */
+.perf-foot { margin: 8px 0 0; line-height: 1.5; }
+
+/* 표 */
+.perf-table-wrap { overflow-x: auto; }
+.perf-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+.perf-table th, .perf-table td { padding: 6px 8px; border-bottom: 1px solid #efefef; white-space: nowrap; }
+.perf-table thead th {
+ font-size: 12px; font-weight: 500; color: var(--color-midtone-gray); text-align: right;
+ background: var(--perf-soft); border-bottom: 1px solid var(--perf-line); position: sticky; top: 0;
+}
+.perf-table thead th.perf-th-label { text-align: left; }
+.perf-td-label { text-align: left; font-weight: 500; }
+.perf-num { text-align: right; }
+.perf-zero { color: #c9c9c9; }
+.perf-na::before { content: ""; }
+.perf-th-total, .perf-td-total { background: #f6f6f6; font-weight: 600; }
+/* 날짜 열 너비 고정(210px) — 공휴일 이름이 날짜 오른쪽에 붙는다 */
+.perf-main thead th.perf-th-label, .perf-main .perf-td-label { width: 210px; min-width: 210px; max-width: 210px; box-sizing: border-box; overflow: hidden; text-overflow: ellipsis; }
+.perf-row-day.is-sat .perf-td-label { color: var(--perf-sat); }
+.perf-row-day.is-sun .perf-td-label { color: var(--perf-sun); }
+.perf-row-day.is-today .perf-td-label::after { content: "오늘"; margin-left: 6px; font-size: 10px; padding: 0 5px; border-radius: 999px; background: var(--color-deep-black); color: #fff; vertical-align: 1px; }
+.perf-row-day.is-future td, .perf-row-month.is-future td, .perf-year tr.is-future td { color: #c9c9c9; }
+.perf-hol { display: inline; margin-left: 6px; font-size: 11px; font-weight: 400; }
+.perf-row-week th, .perf-row-week td { background: #f3f3f3; font-weight: 600; border-bottom: 1px solid var(--perf-line); }
+.perf-row-week .perf-td-total { background: #e9e9e9; }
+.perf-row-total th, .perf-row-total td { background: var(--color-deep-black); color: #fff; font-weight: 600; border-bottom: 0; }
+.perf-row-total .perf-zero { color: #777; }
+td.is-link { cursor: pointer; }
+td.is-link:hover { background: #eef2ff; text-decoration: underline; }
+
+/* 표시 기준 전환 — 한 칸에 3값, data-metric 으로 하나만 보인다 */
+.perf .v { display: none; }
+.perf[data-metric="gross"] .v-gross,
+.perf[data-metric="commission"] .v-commission,
+.perf[data-metric="net"] .v-net { display: inline; }
+
+/* 비중 막대 */
+.perf-share { position: relative; min-width: 110px; }
+.perf-bar { position: absolute; left: 8px; bottom: 3px; height: 3px; width: calc((100% - 16px) * var(--w) / 100); background: #d4d4d4; border-radius: 2px; }
+
+/* 연간 요약 */
+.perf-year-sum { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 8px; }
+.perf-year-sum div { background: var(--perf-soft); border: 1px solid #efefef; border-radius: 10px; padding: 8px 10px; }
+.perf-year-sum span { display: block; font-size: 11.5px; color: var(--color-midtone-gray); }
+.perf-year-sum b { font-size: 16px; font-weight: 600; }
+
+/* 그래프(SVG, performance.js 가 그림) */
+.perf-chart { min-height: 220px; }
+.perf-chart svg { display: block; width: 100%; height: auto; }
+.perf-chart text { font-size: 10.5px; fill: var(--color-midtone-gray); font-family: var(--font-geist); }
+.perf-chart .bar { fill: #1f1f1f; }
+.perf-chart .bar.is-neg { fill: var(--perf-down); }
+.perf-chart .bar:hover { fill: #555; }
+.perf-chart .grid { stroke: #efefef; }
+.perf-chart .axis { stroke: #d4d4d4; }
+.perf-chart-empty { color: var(--color-midtone-gray); font-size: 12px; padding: 80px 0; text-align: center; }
+
+/* 상세(Drill-down) 창 */
+.perf-modal { position: fixed; inset: 0; z-index: 1000; background: rgba(0, 0, 0, .35); display: flex; align-items: center; justify-content: center; padding: 20px; }
+.perf-modal-card { background: #fff; border-radius: 14px; width: min(1100px, 100%); max-height: 88vh; display: flex; flex-direction: column; box-shadow: 0 20px 60px rgba(0, 0, 0, .25); }
+.perf-modal-card.is-narrow { width: min(560px, 100%); }
+.perf-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--perf-line); }
+.perf-modal-head h3 { margin: 0; font-size: 15px; font-weight: 600; }
+.perf-modal-body { padding: 12px 16px; overflow: auto; }
+.perf-modal-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--perf-line); flex-wrap: wrap; align-items: center; }
+.perf-modal-x { border: 0; background: none; font-size: 20px; cursor: pointer; color: var(--color-midtone-gray); }
+.perf-ev-cancel td { color: var(--perf-down); }
+
+/* 설정 */
+.perf-set-table td, .perf-set-table th { vertical-align: middle; }
+.perf-set-table thead th { text-align: left; }
+.perf-set-table thead th:nth-child(2), .perf-set-table thead th:nth-child(3) { text-align: center; }
+.perf-set-table thead th:nth-child(4) { text-align: right; padding-right: 60px; }
+.perf-rate-cell { white-space: nowrap; }
+.perf-rate { display: inline-block; min-width: 56px; text-align: right; font-weight: 600; margin-right: 4px; }
+.perf-pill { display: inline-block; font-size: 11.5px; padding: 1px 8px; border-radius: 999px; background: var(--color-ghost-gray); color: var(--color-midtone-gray); white-space: nowrap; }
+.perf-pill.is-ok { background: #e6f8e9; color: #0f8a3a; }
+.perf-pill.is-bad { background: #fbe9e6; color: var(--perf-down); }
+.perf-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; white-space: nowrap; }
+.perf-status i { width: 8px; height: 8px; border-radius: 50%; background: #bdbdbd; display: inline-block; }
+.perf-status.st-ok i { background: #10b33a; }
+.perf-status.st-auth_failed i, .perf-status.st-token_expired i, .perf-status.st-api_error i { background: var(--perf-down); }
+.perf-status.st-not_configured i { background: #e0a526; }
+.perf-status.st-disabled { color: var(--color-midtone-gray); }
+.perf-err { font-size: 11px; color: var(--perf-down); max-width: 260px; white-space: normal; line-height: 1.35; margin-top: 2px; }
+.perf-switch { position: relative; display: inline-block; width: 34px; height: 20px; cursor: pointer; }
+.perf-switch input { opacity: 0; width: 0; height: 0; position: absolute; }
+.perf-switch span { position: absolute; inset: 0; background: #d4d4d4; border-radius: 999px; transition: background .15s; }
+.perf-switch span::after { content: ""; position: absolute; left: 3px; top: 3px; width: 14px; height: 14px; background: #fff; border-radius: 50%; transition: transform .15s; }
+.perf-switch input:checked + span { background: var(--color-deep-black); }
+.perf-switch input:checked + span::after { transform: translateX(14px); }
+.perf-switch input:focus-visible + span { outline: 2px solid #93c5fd; outline-offset: 2px; }
+.perf-dl { display: grid; grid-template-columns: 90px 1fr; gap: 6px 10px; margin: 0; font-size: 13px; }
+.perf-dl dt { color: var(--color-midtone-gray); }
+.perf-dl dd { margin: 0; }
+.perf-sample-form { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
+.perf-form { display: flex; flex-direction: column; gap: 12px; }
+.perf-form-row { display: flex; flex-direction: column; gap: 4px; }
+.perf-form-row > label { font-size: 12px; font-weight: 500; }
+.perf-form-row .erp-input { width: 100%; box-sizing: border-box; }
+.perf-form-help { font-size: 11.5px; color: var(--color-midtone-gray); }
+.perf-secret-state { font-size: 11.5px; color: #0f8a3a; }
+.perf-secret-state.is-empty { color: var(--color-midtone-gray); }
+.perf-inline { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.perf-test-result { font-size: 12.5px; margin-right: auto; }
+.perf-test-result.is-ok { color: #0f8a3a; }
+.perf-test-result.is-bad { color: var(--perf-down); }
+
+@media (max-width: 1280px) {
+ .perf-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+}
+@media (max-width: 980px) {
+ .perf-grid2 { grid-template-columns: 1fr; }
+ .perf-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .perf-update { margin-left: 0; }
+}
+
+.perf-table tr.perf-row-match > *{background:#e7f6ec;font-weight:600}
+.perf-paste { width: 100%; min-height: 96px; font-family: ui-monospace, Consolas, monospace; font-size: 12px; white-space: pre; resize: vertical; box-sizing: border-box; }
+.perf-table tr.perf-row-diff > * { background: #fff7f5; }
+.perf-diff-bad { color: var(--perf-down); font-weight: 600; }
+.perf-diff-ok { color: #0f8a3a; }
+.perf-link { background: none; border: 0; padding: 0; color: inherit; font: inherit; text-decoration: underline dotted; cursor: pointer; }
+
+/* 주문 내역 창 — 열 제목은 가운데·굵게·150%, 창을 스크롤해도 위에 고정 */
+.perf-ev-wrap { overflow: visible; }
+.perf-ev-table thead th, .perf-ev-table thead th.perf-th-label {
+ text-align: center; font-weight: 700; font-size: 18px; color: var(--color-deep-black, #111);
+ position: sticky; top: -12px; z-index: 2;
+}
+.perf-ev-table thead th { background: var(--perf-soft, #fafafa); box-shadow: 0 1px 0 var(--perf-line, #e5e5e5); }
+/* 취소 행 — 행 전체를 기울임 + 취소선 + 회색 */
+.perf-ev-table tr.is-cancel td { font-style: italic; text-decoration: line-through; color: #9a9a9a; }
diff --git a/app/static/performance.js b/app/static/performance.js
new file mode 100644
index 0000000..7dcc954
--- /dev/null
+++ b/app/static/performance.js
@@ -0,0 +1,943 @@
+/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작.
+ *
+ * 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(/performance/api/…)로만.
+ * 인증정보 창은 저장된 비밀값을 받지 않는다(서버가 "저장됨" 여부만 준다).
+ */
+(function () {
+ "use strict";
+
+ // ── 공통 ─────────────────────────────────────────────
+ function el(tag, attrs, html) {
+ const n = document.createElement(tag);
+ Object.keys(attrs || {}).forEach(function (k) {
+ if (k === "class") n.className = attrs[k];
+ else if (k === "text") n.textContent = attrs[k];
+ else n.setAttribute(k, attrs[k]);
+ });
+ if (html != null) n.innerHTML = html;
+ return n;
+ }
+ function esc(s) {
+ return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
+ return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
+ });
+ }
+ function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
+ function won(n) { return n ? fmt(n) : '–'; }
+ // 축 눈금용 짧은 금액(1.2억 / 350만)
+ function short(n) {
+ 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") + "만";
+ return s + fmt(a);
+ }
+ function alertMsg(msg, opts) { return window.erpAlert ? window.erpAlert(msg, opts) : Promise.resolve(window.alert(msg)); }
+ function confirmMsg(msg) { return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg)); }
+
+ async function api(method, url, body) {
+ const res = await fetch(url, {
+ method: method,
+ credentials: "same-origin",
+ headers: body ? { "Content-Type": "application/json" } : {},
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ let data = null;
+ try { data = await res.json(); } catch (_) { data = null; }
+ if (!res.ok) {
+ const detail = data && data.detail;
+ throw new Error(typeof detail === "string" ? detail : "요청 실패 (" + res.status + ")");
+ }
+ return data || {};
+ }
+
+ // 간단한 창. 반환: { card, body, foot, close }
+ function openModal(title, opts) {
+ opts = opts || {};
+ const back = el("div", { class: "perf-modal" });
+ const card = el("div", { class: "perf-modal-card" + (opts.narrow ? " is-narrow" : ""), role: "dialog", "aria-modal": "true" });
+ const head = el("div", { class: "perf-modal-head" });
+ head.appendChild(el("h3", { text: title }));
+ const x = el("button", { type: "button", class: "perf-modal-x", "aria-label": "닫기" }, "×");
+ head.appendChild(x);
+ const body = el("div", { class: "perf-modal-body" });
+ const foot = el("div", { class: "perf-modal-foot" });
+ card.appendChild(head); card.appendChild(body); card.appendChild(foot);
+ back.appendChild(card);
+ document.body.appendChild(back);
+ function onKey(e) { if (e.key === "Escape") close(); }
+ function close() {
+ document.removeEventListener("keydown", onKey, true);
+ back.remove();
+ if (opts.onClose) opts.onClose();
+ }
+ x.addEventListener("click", close);
+ back.addEventListener("mousedown", function (e) { if (e.target === back) close(); });
+ document.addEventListener("keydown", onKey, true);
+ return { card: card, body: body, foot: foot, close: close };
+ }
+
+ // ════════════════════════════════════════════════════
+ // 대시보드
+ // ════════════════════════════════════════════════════
+ function initDashboard(root) {
+ const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
+ const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
+ const KEY = "perf_metric";
+
+ // 표시 기준 전환 — 서버가 세 값을 다 그려 두었고 CSS 가 하나만 보인다.
+ function setMetric(m) {
+ if (!METRIC_NAMES[m]) m = "gross";
+ root.dataset.metric = m;
+ root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
+ b.classList.toggle("is-active", b.dataset.metric === m);
+ });
+ try { localStorage.setItem(KEY, m); } catch (_) {}
+ drawDaily(m);
+ drawShare(m);
+ root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
+ }
+ root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
+ b.addEventListener("click", function () { setMetric(b.dataset.metric); });
+ });
+
+ // 직접선택 / 쇼핑몰 필터
+ const customBtn = document.getElementById("perf-custom-btn");
+ const customForm = document.getElementById("perf-custom");
+ if (customBtn && customForm) customBtn.addEventListener("click", function () {
+ customForm.hidden = !customForm.hidden;
+ if (!customForm.hidden) customForm.querySelector("input[type=date]").focus();
+ });
+ const checkAll = root.querySelector("[data-perf-check-all]");
+ if (checkAll) checkAll.addEventListener("click", function () {
+ const boxes = root.querySelectorAll(".perf-filter-pop input[type=checkbox]");
+ const allOn = Array.prototype.every.call(boxes, function (b) { return b.checked; });
+ boxes.forEach(function (b) { b.checked = !allOn; });
+ });
+ document.addEventListener("click", function (e) {
+ const f = document.getElementById("perf-filter");
+ if (f && f.open && !f.contains(e.target)) f.open = false;
+ });
+
+ // 매출 업데이트 — 서버가 쇼핑몰별로 따로 수집(한 곳 실패해도 나머지 반영)
+ const syncBtn = document.getElementById("perf-sync-btn");
+ const resultBox = document.getElementById("perf-sync-result");
+ if (syncBtn) syncBtn.addEventListener("click", async function () {
+ syncBtn.disabled = true;
+ const label = syncBtn.textContent;
+ syncBtn.textContent = "업데이트 중…";
+ try {
+ // 지금 보고 있는 기간(오늘까지)을 가져온다 — "이번달"이면 1일부터 오늘까지.
+ const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
+ if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
+ const res = await api("POST", "/performance/api/sync", { from: from, to: to });
+ // 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
+ // 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
+ const ok = [], bad = [], pending = [], unset = [], busy = [];
+ let changed = 0;
+ (res.results || []).forEach(function (r) {
+ const name = (data.names || {})[r.code] || r.code;
+ if (r.skipped) busy.push(name);
+ else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; }
+ else if (r.status === "not_implemented") pending.push(name);
+ else if (r.status === "not_configured") unset.push(name);
+ else bad.push(name + "(" + (r.label || r.status) + (r.message ? ": " + r.message : "") + ")");
+ });
+ const parts = [];
+ if (ok.length) parts.push("반영 " + esc(ok.join(", ")));
+ if (bad.length) parts.push("실패 " + esc(bad.join(", ")));
+ if (busy.length) parts.push("이미 진행 중 " + esc(busy.join(", ")));
+ if (pending.length) parts.push('연동 준비 중: ' + esc(pending.join(", ")) + "");
+ if (unset.length) parts.push('인증정보 미설정: ' + esc(unset.join(", ")) + "");
+ resultBox.innerHTML = parts.join(" · ") || "업데이트할 쇼핑몰이 없습니다.";
+ resultBox.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
+ resultBox.hidden = false;
+ if (res.last_update_at) {
+ const lu = document.querySelector("#perf-last-update b");
+ if (lu) lu.textContent = res.last_update_at.slice(0, 16).replace("T", " ");
+ }
+ if (changed > 0) setTimeout(function () { location.reload(); }, 1200);
+ } catch (err) {
+ resultBox.textContent = "업데이트 실패: " + err.message;
+ resultBox.className = "perf-notice is-warn";
+ resultBox.hidden = false;
+ } finally {
+ syncBtn.disabled = false;
+ syncBtn.textContent = label === "업데이트 중…" ? "매출 업데이트" : label;
+ }
+ });
+
+ // 금액 클릭 → 주문 상세
+ root.addEventListener("click", function (e) {
+ const td = e.target.closest("td.is-link");
+ if (!td) return;
+ openEvents(td.dataset.code, td.dataset.from, td.dataset.to);
+ });
+ async function openEvents(code, from, to) {
+ const name = (data.names || {})[code] || code;
+ const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
+ const m = openModal(title);
+ m.body.innerHTML = '
[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 칸은 저장된 값 사용). ' +
+ "[저장]은 연결 테스트 결과와 관계없이 저장합니다 — 쇼핑몰의 일시 장애로 테스트가 실패할 수 있기 때문입니다. " +
+ "저장 후 자동으로 한 번 더 연결 테스트를 합니다.
한 줄 = market_id × 주문경로. market_id "self"는 PC 전용이 아니라 자체몰 전체이며, 그 안에 PC쇼핑몰·모바일웹 경로가 섞여 있습니다. ' +
+ 'PC/모바일 주문은 카페24가 주문마다 주는 모바일 주문 여부(order_from_mobile) 기준입니다.
저장 ' + esc(String(x.synced_at).slice(5, 16).replace("T", " ")) + "
" : "") + "
";
+ }).join("");
+ const head = '
날짜
주문수 카페24 / 저장' + (lv ? " / API" : "") + "
" +
+ "
결제합계(카페24)
저장값 차이
" + (lv ? "
API 차이
" : "") +
+ "
환불합계(카페24)
저장값 차이
" + (lv ? "
API 차이
" : "") + '
판정
';
+ const foot = '
합계
' + won(sum.cp) + '
' +
+ diff(sum.dp, sum.cp) + "
" + (lv ? '
' + diff(sum.lp, sum.cp) + "
" : "") + '
' + won(sum.cr) +
+ '
' + diff(sum.dr, sum.cr) + "
" + (lv ? '
' + diff(sum.lr, sum.cr) + "
" : "") + "
";
+ const summary = bad
+ ? "저장값이 다른 날 " + bad + "일" + (lv ? " — 다시 가져오면 해결 " + stale + "일, 규칙 차이 " + rule + "일" : " — [API 값도 계산]을 켜고 다시 비교하면 원인을 나눠 볼 수 있습니다")
+ : "모든 날짜가 일치합니다.";
+ out.innerHTML = '
' + esc(summary) +
+ (r.live_error ? " API 계산 실패: " + esc(r.live_error) : "") + "
" +
+ (stale ? '" : "") +
+ '
' + head + "" + body + "" + foot + "
" +
+ '
차이 = 우리 값 − 카페24 값. 저장값은 카페24 수집분 전체(카페24 화면과 같은 범위)입니다.
';
+ } catch (err) {
+ out.innerHTML = '
' + esc(err.message) + "
";
+ } finally { dailyBtn.disabled = false; }
+ });
+ const dailyOut = document.getElementById("perf-daily-result");
+ if (dailyOut) dailyOut.addEventListener("click", async function (e) {
+ const dayBtn = e.target.closest("[data-recon-day]");
+ if (dayBtn && recon) {
+ document.getElementById("perf-recon-date").value = dayBtn.dataset.reconDay;
+ recon.click();
+ recon.scrollIntoView({ behavior: "smooth", block: "center" });
+ return;
+ }
+ const rs = e.target.closest("#perf-daily-resync");
+ if (!rs) return;
+ if (!(await confirmMsg(rs.dataset.from + " ~ " + rs.dataset.to + " 카페24 매출을 지금 규칙으로 다시 가져옵니다."))) return;
+ rs.disabled = true;
+ rs.textContent = "가져오는 중…";
+ try {
+ const res = await api("POST", "/performance/api/sync", { from: rs.dataset.from, to: rs.dataset.to, codes: ["cafe24"] });
+ const r0 = (res.results || [])[0];
+ if (r0 && !r0.ok) throw new Error((r0.label || r0.status) + ": " + (r0.message || ""));
+ dailyBtn.click();
+ } catch (err) {
+ alertMsg("다시 가져오기 실패: " + err.message);
+ rs.disabled = false;
+ }
+ });
+
+ // ── 11번가 원본 데이터 확인 — 후보 조회 주소별 동작 여부·항목 합계 ──
+ const probe = document.getElementById("perf-probe");
+ if (probe) probe.addEventListener("click", async function () {
+ const day = document.getElementById("perf-probe-date").value;
+ const out = document.getElementById("perf-probe-result");
+ if (!day) return;
+ probe.disabled = true;
+ out.innerHTML = '
";
+ } finally { probe.disabled = false; }
+ });
+
+ // ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
+ const backfill = document.getElementById("perf-backfill");
+ if (backfill) backfill.addEventListener("click", async function () {
+ const from = document.getElementById("perf-backfill-from").value;
+ const to = document.getElementById("perf-backfill-to").value;
+ const box = document.getElementById("perf-backfill-result");
+ if (!from || !to) return;
+ if (!(await confirmMsg(from + " ~ " + to + " 매출을 연동된 쇼핑몰에서 가져옵니다. 기간이 길면 몇 분 걸릴 수 있습니다."))) return;
+ const names = {};
+ root.querySelectorAll("tr[data-code]").forEach(function (tr) { names[tr.dataset.code] = tr.dataset.name; });
+ backfill.disabled = true;
+ backfill.textContent = "가져오는 중…";
+ box.hidden = true;
+ try {
+ const res = await api("POST", "/performance/api/sync", { from: from, to: to });
+ const ok = [], bad = [], rest = [];
+ (res.results || []).forEach(function (r) {
+ const name = names[r.code] || r.code;
+ if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
+ else if (r.skipped) rest.push(name + "(이미 진행 중)");
+ else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name);
+ else bad.push(name + "(" + (r.label || r.status) + ": " + (r.message || "") + ")");
+ });
+ box.innerHTML = [
+ ok.length ? "반영 " + esc(ok.join(", ")) : "",
+ bad.length ? "실패 " + esc(bad.join(", ")) : "",
+ rest.length ? '건너뜀(미연동·미설정): ' + esc(rest.join(", ")) + "" : "",
+ ].filter(Boolean).join(" · ") || "가져올 쇼핑몰이 없습니다.";
+ box.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
+ box.hidden = false;
+ } catch (err) {
+ box.textContent = "가져오기 실패: " + err.message;
+ box.className = "perf-notice is-warn";
+ box.hidden = false;
+ } finally {
+ backfill.disabled = false;
+ backfill.textContent = "가져오기";
+ }
+ });
+
+ // ── 테스트 데이터 / 재암호화 ──
+ const gen = document.getElementById("perf-sample-gen");
+ if (gen) gen.addEventListener("click", async function () {
+ gen.disabled = true;
+ try {
+ const res = await api("POST", "/performance/api/sample-data", {
+ action: "generate", from: document.getElementById("perf-sample-from").value,
+ to: document.getElementById("perf-sample-to").value,
+ });
+ await alertMsg("테스트 데이터 " + fmt(res.generated) + "건을 만들었습니다(같은 기간을 다시 만들면 덮어씀).");
+ location.reload();
+ } catch (err) { alertMsg(err.message); } finally { gen.disabled = false; }
+ });
+ const del = document.getElementById("perf-sample-del");
+ if (del) del.addEventListener("click", async function () {
+ if (!(await confirmMsg("테스트 데이터만 모두 삭제합니다. 실제 수집한 매출은 지우지 않습니다. 계속할까요?"))) return;
+ try {
+ const res = await api("POST", "/performance/api/sample-data", { action: "delete" });
+ await alertMsg("테스트 데이터 " + fmt(res.deleted) + "건을 삭제했습니다.");
+ location.reload();
+ } catch (err) { alertMsg(err.message); }
+ });
+ const rekey = document.getElementById("perf-rekey");
+ if (rekey) rekey.addEventListener("click", async function () {
+ if (!(await confirmMsg("예전 키로 암호화된 인증정보를 현재 키로 다시 암호화합니다. 계속할까요?"))) return;
+ try {
+ const res = await api("POST", "/performance/api/rekey");
+ await alertMsg("다시 암호화 " + res.reencrypted + "건" + (res.failed ? ", 실패 " + res.failed + "건(다시 입력 필요)" : ""));
+ location.reload();
+ } catch (err) { alertMsg(err.message); }
+ });
+ }
+
+ document.addEventListener("DOMContentLoaded", function () {
+ const dash = document.getElementById("perf-dash");
+ if (dash) initDashboard(dash);
+ const set = document.getElementById("perf-settings");
+ if (set) initSettings(set);
+ });
+})();
diff --git a/app/store.py b/app/store.py
index 6c29fbf..d635831 100644
--- a/app/store.py
+++ b/app/store.py
@@ -32,6 +32,7 @@ MODULE_KEYS: tuple[str, ...] = (
"dispatch",
"project",
"cafe24",
+ "performance",
"expense_approver",
"vacation_approver",
)
diff --git a/app/templates/erp_base.html b/app/templates/erp_base.html
index 6c4ce15..e657643 100644
--- a/app/templates/erp_base.html
+++ b/app/templates/erp_base.html
@@ -7,7 +7,7 @@
-
+
{% block head_extra %}{% endblock %}
@@ -177,7 +177,7 @@
{# 공용 확인/경고 창. defer 를 쓰지 않는다 — 아래 {% block scripts %} 의
인라인 스크립트가 곧바로 erpConfirm/erpAlert 을 쓸 수 있어야 한다. #}
-
+
{% block scripts %}{% endblock %}
diff --git a/docs/CAFE24_MODULE.md b/docs/CAFE24_MODULE.md
index ce739d1..80731d3 100644
--- a/docs/CAFE24_MODULE.md
+++ b/docs/CAFE24_MODULE.md
@@ -306,10 +306,10 @@ code → access/refresh token 교환
cafe24_oauth_tokens 저장
```
-- scope 는 `app/integrations/cafe24/config.py` 의 `PRODUCT_SCOPES` =
- `mall.read_product`, `mall.write_product`.
- 주문관리 추가 시 `ORDER_SCOPES` 를 합쳐 넘기고, 카페24 개발자센터 앱에서도
- 권한을 추가한 뒤 **재인증**하면 된다.
+- scope 는 `app/integrations/cafe24/config.py` 의 `DEFAULT_SCOPES` =
+ `mall.read_product`, `mall.write_product`, `mall.read_order`(실적 모듈 매출 수집, 읽기만).
+ 목록을 바꾸면 카페24 개발자센터 앱에도 그 권한이 있어야 하고(없으면 인증 거부),
+ **재인증**해야 새 권한이 토큰에 붙는다. 재인증 전 기존 토큰은 예전 권한 그대로 계속 동작한다.
- access token 은 만료 2분 전부터 자동 갱신된다. 갱신은 토큰 행을
`SELECT ... FOR UPDATE` 로 잠근 채 수행 — web 컨테이너와 worker 컨테이너가
동시에 refresh 해서 한쪽 토큰이 무효화되는 것을 막는다(카페24는 refresh
@@ -535,7 +535,8 @@ cafe24_oauth_tokens 저장
1. 로그인 → 앱 생성
2. Redirect URI 를 `.env` 의 `CAFE24_REDIRECT_URI` 와 **정확히 동일하게** 등록
(운영: `https://dbx.no1king.freeddns.org/cafe24/oauth/callback`)
-3. 권한(Scope)에 `mall.read_product`, `mall.write_product` 체크
+3. 권한(Scope)에 상품(Product) 읽기+쓰기, 주문(Order) 읽기 이상 체크
+ (`mall.read_product`, `mall.write_product`, `mall.read_order` — 주문은 실적 모듈이 매출 수집에 사용)
4. 발급된 Client ID / Client Secret 을 `.env` 에 기입
### 5-2. DB 초기화 (superuser 로 1회)
diff --git a/docs/DATABASES.md b/docs/DATABASES.md
index 097368c..c827909 100644
--- a/docs/DATABASES.md
+++ b/docs/DATABASES.md
@@ -11,6 +11,7 @@
| `cupang_db` | 쿠팡 밀크런 출고 묶음 / 출고 라인 / 입고센터 / 박스 입수량 규칙 |
| `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 |
| `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 |
+| `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 |
---
@@ -336,6 +337,44 @@ cd /opt/www/main && docker compose up -d --build web
---
+## performance_db 스키마 / 초기화
+
+DDL: `scripts/sql/performance_db_init.sql` (멱등). DB·역할(`performance_app`)·테이블·인덱스·트리거·쇼핑몰 10곳 seed 를
+한 번에 생성. **JSON 폴백 없음** — `PERFORMANCE_DB_URL` 미설정 시 모듈이 "설정 필요" 안내만 표시. 상세는 `docs/PERFORMANCE_MODULE.md`.
+
+| 테이블 | 용도 |
+| --- | --- |
+| `perf_marketplaces` | 쇼핑몰 코드·이름·사용 여부·매출 집계 여부·순서 |
+| `perf_commission_rates` | 수수료율 이력(`rate_percent NUMERIC(7,3)`, `effective_from`). 그날 유효한 요율로 과거 실적 계산 |
+| `perf_credentials` | API 인증정보. (쇼핑몰, 항목) 한 행 = **AES-256-GCM 암호문** + `key_version`. 토큰도 여기 |
+| `perf_connection_status` | 연결 상태·마지막 테스트/동기화·최근 오류(비밀값 가린 문구) |
+| `perf_sales_events` | 매출 사건(결제 +, 취소·반품 −, BIGINT 원). `UNIQUE(marketplace_code, event_type, external_event_id)`. `is_sample`=테스트 데이터 |
+| `perf_sync_runs` | 동기화 기록. `status='running'` 부분 유니크 인덱스로 같은 쇼핑몰 동시 실행 차단 |
+
+핵심 규칙:
+
+- 인증정보는 **암호문만** 저장. 마스터 키 `APP_ENCRYPTION_KEY` 는 DB 가 아닌 `.env` 에만 있다 —
+ DB 백업만으로는 복호화할 수 없고, **키를 잃으면 인증정보를 다시 입력해야 한다**(키는 별도 안전 보관).
+- 테스트 데이터 삭제는 `is_sample = TRUE` 조건 삭제만 한다(설정 화면 버튼).
+
+### 운영 서버 초기화 (1회, 사용자 승인 후)
+
+```bash
+read -s -p "performance_app password: " APP_PWD; echo
+docker exec -i postgres-db psql -U postgres \
+ -v app_password="$APP_PWD" \
+ < scripts/sql/performance_db_init.sql
+# main-app .env 에 추가:
+# PERFORMANCE_DB_URL=postgresql://performance_app:@postgres-db:5432/performance_db
+# APP_ENCRYPTION_KEY=$(openssl rand -hex 32) # 별도 안전한 곳에도 백업
+# APP_ENCRYPTION_KEY_VERSION=1
+cd /opt/www/main && docker compose up -d --build
+```
+
+> 멱등 스크립트. 기존 DB 가 있으면 DROP 하지 않음.
+
+---
+
## 백업 / 복구 (안전 절차)
### 백업
diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
index 0c45297..a66fd98 100644
--- a/docs/DEPLOYMENT.md
+++ b/docs/DEPLOYMENT.md
@@ -120,6 +120,10 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
| `VACATION_DB_URL` | 휴가 관리 DB DSN (예: `postgresql://vacation_app:@postgres-db:5432/vacation_db`). **필수** — 미설정 시 모듈 비활성(설정 필요 안내). 권한키 `vacation`/`vacation_approver` |
| `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` |
+| `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/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md
new file mode 100644
index 0000000..1069312
--- /dev/null
+++ b/docs/PERFORMANCE_MODULE.md
@@ -0,0 +1,193 @@
+# 실적(쇼핑몰 통합 매출) 모듈
+
+> `app/modules/performance/` · DB `performance_db` · URL `/performance/` · 권한키 `performance`
+> 여러 쇼핑몰의 주문/매출을 **수집 → DB 저장 → 화면 조회** 구조로 한 화면에서 본다.
+> API 장애·호출 제한이 있어도 이미 저장된 실적은 그대로 보인다.
+
+## 1. 구조 — 네 영역 분리
+
+| 영역 | 파일 | 역할 |
+|---|---|---|
+| ① 쇼핑몰 API 수집 | `adapters/base.py`, `adapters/<쇼핑몰>.py`, `adapters/registry.py`, `sync.py` | 어댑터 = 쇼핑몰 하나. `sync.py` 가 어댑터 결과를 공통 사건으로 DB 저장 |
+| ② 인증정보·보안 | `security/crypto.py`, `security/redact.py`, `credentials.py` | AES-256-GCM 암·복호화, 비밀값 가리기, 저장/화면 요약/재암호화 |
+| ③ 계산·저장 | `calc.py`, `db.py` | 기간·주(월~일)·수수료·반올림·집계(순수 함수) / performance_db |
+| ④ 화면 | `dashboard.py`, `router.py`, `common.py`, `templates/performance/`, `static/performance.{css,js}` | 화면 데이터 조립, 라우트·권한, UI |
+
+**쇼핑몰 추가 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄**(`perf_marketplaces`). 대시보드·설정·동기화는 자동으로 붙는다.
+
+## 2. 어댑터 공통 인터페이스 (`MarketplaceAdapter`)
+
+| 메서드 | 설명 |
+|---|---|
+| `credential_fields()` | 설정 화면 입력칸 정의(`CredentialField`: key/label/secret/required/help, `internal`=토큰 등 화면 비표시) |
+| `validate_credentials(values)` | 저장 전 검사(값을 오류 문구에 넣지 않음) |
+| `authenticate(ctx)` / `refresh_token(ctx)` | 토큰 발급·갱신. 새 토큰은 `ctx.credentials.set(key, value)` → 자동 암호화 저장 |
+| `test_connection(ctx)` | 성공 문구 반환, 실패는 `AdapterError` 계열 |
+| `fetch_orders` / `fetch_refunds(ctx, start, end)` | 원본 수집 |
+| `normalize_order` / `normalize_refund(raw)` | 원본 → `SaleEvent` 목록 |
+| `collect(ctx, start, end)` | 위를 묶어 (원본 건수, 사건 목록) — sync 서비스가 부른다 |
+
+오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
+
+**연동 현황**: 카페24 = **구현됨**, 나머지 9개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
+**연동 단계에서 공식 API 문서로 확정**한다.
+
+### 카페24 (`adapters/cafe24.py`, 구현됨)
+
+`auth_type="shared"` — 기존 `app/integrations/cafe24` OAuth 토큰(cafe24_db)과 클라이언트(재시도·429·토큰 자동 갱신)를
+재사용한다. 토큰에 `mall.read_order` 가 있어야 한다(`DEFAULT_SCOPES` 포함, 권한 추가 후 카페24 상품관리 → 시스템에서 재연결).
+
+**카페24 관리자 "일별 매출내역"과 같은 기준**으로 센다(처음의 품목 결제금액 방식은 배송비가 빠지고 환불 날짜 기준이 달라
+화면과 맞지 않아 교체).
+
+| 사건 | 조회 | 금액·날짜 |
+|---|---|---|
+| SALE(결제합계) | `GET /admin/orders` `date_type=pay_date`, `embed=items`, `paid=T` | +(실결제금액 + 적립금 + 예치금 + 네이버포인트), `initial_order_amount` + 주문 `naver_point`(결제 당시 금액 — 환불을 따로 빼므로 취소 후 금액 X), 결제일. 주문 1건 = 사건 1건(`{order_id}-PAY`) |
+| CANCEL / RETURN(환불합계) | `GET /admin/refunds` `date_type=refund_date`, `status=T` | −(실제 환불액 + 적립금·예치금 환불), 환불완료일. 환불코드 R… = 반품, 그 밖 = 취소. 사건 ID = 환불코드 |
+| CANCEL / RETURN(환불 목록 없는 취소·반품) | `GET /admin/orders` `date_type=cancel_date|return_complete_date`, `embed=items` — 품목 상태 C40~43/R40~43 이고 앞뒤 60일 환불 목록(완료일·접수일)에 그 주문이 없을 때 | −(판매가+옵션)×수량 − 품목 할인·쿠폰, 품목 취소일(반품은 반품완료일). 네이버페이 취소가 여기 해당 (네이버가 환불해 카페24 환불 목록에 없음). 사건 ID = `c24:{품목코드}-CL` (`unrefunded_claims`) |
+
+- 할인 = 회원·세트상품·앱·마켓 기타·배송비 할인, 쿠폰 = 상품쿠폰 + 배송비쿠폰(`DISCOUNT_FIELDS`/`COUPON_FIELDS`).
+- **기간 교체(`replace_range=True`)**: 결제·환불 모두 기간 안 날짜로 조회되므로 동기화 때 그 기간의 카페24 실데이터를 지우고
+ 새로 넣는다(한 트랜잭션, 테스트 데이터 제외). 규칙이 바뀌어도 예전 행이 남지 않는다 → 규칙을 고친 뒤에는 같은 기간을
+ [과거 매출 가져오기]로 다시 받으면 된다.
+- **주의 — `market_id` 는 외부 마켓만이 아니라 자체몰 주문 채널·간편결제도 담는다**(실데이터 확인 2026-09-30:
+ `mobile`=모바일웹, `NCHECKOUT`=네이버페이, `KAKAOPAY`=톡체크아웃). 이들은 `SELF_CHANNELS` 로 카페24 열.
+ 대조 도구의 "주문 채널별" 표가 채널마다 자체몰 채널 / 외부 마켓 / 알 수 없는 채널(→ 카페24 열)을 보여 준다.
+ `MARKET_MAP` 에는 결제수단과 헷갈릴 수 있는 일반 이름(naver, kakao)을 넣지 않는다.
+- **현재 `MARKET_MAP` 은 비어 있다** — 이 쇼핑몰은 카페24 마켓 통합관리를 쓰지 않는다(2026-09 사용자 확인). 카페24로 들어온
+ 주문은 모두 카페24 열이고 설정 화면의 "카페24 경유" 표시도 나오지 않는다. 아래는 나중에 마켓 통합관리를 쓸 때의 동작.
+- **마켓 연동 주문은 해당 쇼핑몰 열로**: 자체몰 채널은 카페24 열. 카페24 마켓 통합관리가 가져온
+ 다른 마켓 주문은 `MARKET_MAP`(market_id 또는 order_place_id → 우리 쇼핑몰 코드)으로 네이버·쿠팡·11번가 등 열에 넣는다
+ (`SaleEvent.marketplace_code`). 연결표에 없는 마켓은 카페24 열 — **전체 합계는 항상 카페24 일별 매출내역과 같다**
+ (9/28 대조로 자체몰+마켓 합계가 모든 줄에서 일치 확인). 환불은 원 주문을 100건씩 조회해 같은 열로. 네이버페이는 자체몰.
+- 카페24 가 만든 사건 ID 는 모두 `c24:` 접두어(`event_prefix`) — 다시 받을 때 카페24 열 + 다른 열의 `c24:` 행만 교체해
+ 그 쇼핑몰의 **직접 연동분은 건드리지 않는다**. 어떤 쇼핑몰을 직접 API 로 연동하면 같은 주문을 두 번 받지 않도록 그 마켓을
+ `MARKET_MAP` 에서 빼야 한다. 설정 화면 API 설정 칸의 "카페24 경유" 표시 = 카페24 수집 때 함께 반영되는 쇼핑몰.
+- 실제 market_id 값은 "카페24 매출 대조"의 마켓별 표(market_id / 주문경로 / 반영 열)로 확인하고, "(연결표 없음)"으로 나오는
+ 마켓이 우리 쇼핑몰이면 `MARKET_MAP` 에 추가한다.
+- 60일 단위 분할(한 호출 3개월 미만), orders limit 1000 / refunds limit 500 페이지. 개인정보는 저장하지 않는다.
+- **카페24 매출 대조**(설정 화면, `GET /api/marketplaces/cafe24/reconcile?date=`): 그날 결제 주문·환불을 카페24 화면 열 순서대로
+ (주문수·품목수·상품구매금액·배송비·할인·쿠폰·결제합계·환불합계·순매출) 자체몰/다른 마켓으로 나눠 합산. 저장하지 않음.
+ 카페24 화면과 다른 줄이 있으면 할인 항목 구성·마켓 포함 여부를 이 결과로 조정한다.
+- **일별 한 번에 비교**(같은 카드, `GET /api/marketplaces/{code}/daily-check?from=&to=&live=1`, 최대 62일): 카페24 일별
+ 매출내역 표를 붙여 넣으면(날짜 + 뒤 세 숫자 = 결제합계·환불합계·순매출, 첫 숫자 = 주문수) 날짜마다 저장값(`c24:` 사건 전체,
+ 다른 마켓 열 포함)과 지금 API·현재 규칙으로 다시 계산한 값(`adapter.collect`, 저장 안 함)을 비교한다.
+ 저장값만 틀림 → 예전 규칙으로 받은 것([다시 가져오기] 버튼), API 값도 틀림 → 규칙 차이(결제/환불) → 날짜 클릭으로 그날 대조.
+ 날짜를 눌러 연 대조 표에는 붙여넣은 카페24 열(주문수·품목수·상품구매금액·배송비·할인·쿠폰·실결제·적립금·예치금·결제·환불·순매출)과
+ 열별 차이가 같이 나온다.
+- **결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트**(initial_order_amount 의 payment_amount·points_spent_amount·
+ credits_spent_amount + 주문의 naver_point). "상품구매금액 + 배송비 − 할인 − 쿠폰"은 할인 필드에 안 잡히는 차이가 있어 쓰지 않음
+ (2026-09-23: 카페24 1,874,738 = 1,713,128 + 10,110 + 151,500, 상품식 1,874,800). 네 값이 모두 0인 주문도 0원
+ (9/25 가상계좌·휴대폰 9,900 — 카페24도 0원).
+- **환불 목록 없는 취소는 네이버페이(NCHECKOUT)만** 환불합계에 넣는다. 주문 전체가 취소·반품되면 배송비(− 배송비 할인·쿠폰)도
+ 그 주문의 마지막 클레임 품목에 한 번 더한다. 톡체크아웃·자체몰의 환불 기록 없는 취소는 카페24 환불합계에 없음
+ (9/4: 98,700 + 네이버페이 19,900 + 배송비 3,500 = 122,100 / 9/16: 톡체크아웃 취소 9,900 제외 → 201,100).
+
+### 11번가 (`adapters/elevenst.py`, 구현됨)
+
+- 인증: 셀러오피스 Open API Key → 헤더 `openapikey`. **셀러 API 는 등록 IP 에서만** 호출된다(Seller API 정보 수정 →
+ IP 직접 입력에 운영 서버 외부 IP, 셀링툴 사방넷과 함께 사용 가능). 응답은 XML(euc-kr 선언 → 직접 디코딩).
+- 없는 주소 = 500 + `-997 등록된 API 정보가 존재하지 않습니다`, 건 없음 = `-1 해당 건이 없습니다`(0건으로 처리).
+- 상세 문서가 로그인 뒤에만 있어 설정 화면 **"11번가 원본 데이터 확인"**(`reconcile(day, to)`, 후보 주소별 동작·항목 합계,
+ 개인정보 값 숨김)으로 실데이터를 보고 확정했다(2026-09-30).
+- 주문 상태 목록 4개(`/rest/ordservices/complete|packaging|shipping|completed/{yyyyMMddHHmm}/{…}`)는 **지금 그 상태인 주문만**
+ 준다. 배송완료 목록에 구매확정 주문도 남는다. 취소·반품된 주문은 목록에서 빠지고 `/rest/claimservice/canceledorders|…` 에 있다.
+- SALE = **주문 하나**(`11st:{ordNo}`), 날짜 = 결제일.
+ - **정산된 주문**: 정산 내역(`/rest/settlement/settlementList/{yyyyMMdd}/{yyyyMMdd}`, 정산확정일 `stlDy` 기준 → 기간 뒤 45일
+ (오늘까지)을 더 불러 결제일 `ordStlEndDt` 로 거름)의 **판매금액합계 `selPrcAmt` 합**. 셀러오피스 "판매 상세내역"과 같고
+ 배송비(도서산간 등)가 별도 줄로 들어 있다 — 9/10 주문 83,800 + 배송비 줄 3,000 = 86,800(주문 목록 `dlvCst` 는 0).
+ - **정산 전 주문**: 주문 상태 목록의 `ordAmt`(판매금액, 11번가 부담 쿠폰 전) + 배송비(`dlvCst` 최댓값 한 번). 기간 뒤 30일을 더
+ 불러 주문일로 거른다. 정산되면 다음 업데이트 때 정산 값으로 바뀐다.
+ - `ordAmt − ordPayAmt` = 정산 `cupnAmt` = 11번가 부담 할인(`discount_amount`). 수수료는 판매금액 기준(34,900 × 13% = 4,537).
+- `replace_range` — 기간을 통째로 다시 받아 취소·반품된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 → 지난 날짜
+ 금액이 나중에 줄 수 있음). 구매자 이름·아이디·연락처는 저장하지 않는다.
+
+### 연동 단계 체크리스트(쇼핑몰마다)
+
+- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
+- `SaleEvent` 규칙: 금액은 원 단위 **정수**, 결제 `+` / 취소·반품 `−`, `external_event_id` 는 쇼핑몰 안에서 사건을
+ 유일하게 가리키는 값(중복 방지 키), `order_date`/`payment_date`/`event_date` 를 섞지 말고 각각 채운다
+- 오류 메시지·`raw` 에 비밀값을 넣지 않는다(sync 가 한 번 더 가리지만 원칙은 넣지 않는 것)
+- `implemented = True`, 단위 테스트(원본 샘플 → 사건 변환) 추가
+
+## 3. 매출 기준·계산 (`calc.py`, `sync.sales_date_for`)
+
+- **집계 기준일(`sales_date`)**: 결제 = 결제일(`payment_date`, 없으면 `event_date`), 취소·반품 = **발생일**.
+ 지난주 실적이 나중에 바뀌지 않게 하려는 선택. `order_date`/`payment_date` 를 따로 보관하므로 기준을 바꿀 수 있다
+ (바꿀 곳은 `sales_date_for` 한 곳 + 기존 행 재계산).
+- **수수료** = `round_half_up(일·쇼핑몰 매출 합 × 그날 요율 / 100)` — `calc.commission()` 한 곳. 음수(취소)도 같은 규칙.
+ 주문별이 아니라 일·쇼핑몰 합계 단위 반올림이다.
+- **수수료율 이력**: `perf_commission_rates(effective_from)`. 어떤 날의 요율 = 그날 이전 가장 최근 시작일의 요율,
+ 첫 요율 이전은 0%. "처음부터(과거 전체)"는 `2000-01-01` 로 저장.
+- **주** = 월요일~일요일. **증감률**: 진행 중인 기간은 직전 기간의 **같은 경과일수**까지와 비교(전주 같은 기간),
+ 비교 대상이 0 이하면 표시하지 않음.
+- **월·연 누적 기준일**: 선택 기간이 오늘을 포함하면 오늘(이번주가 다음 달에 걸쳐도 "이번달"), 지난 기간이면 기간 끝.
+
+## 4. 인증정보 보안
+
+- 저장: 설정 화면 입력 → 서버에서 **AES-256-GCM**(`cryptography` AESGCM) → `perf_credentials`
+ (항목 하나 = 행 하나, `encrypted_value = "v{키버전}:{base64url(nonce+암호문+tag)}"`, `key_version`).
+- AAD = `perf:{쇼핑몰}:{항목}` — 암호문을 다른 칸으로 옮기면 복호화 실패.
+- 화면으로는 secret 항목의 **저장 여부만** 보낸다(원문·일부·길이 X). 일반 항목(Vendor ID 등)만 원문 표시.
+- 빈 칸 저장 = 기존 값 유지. 선택 항목은 "저장된 값 지우기".
+- 저장 정책: [연결 테스트]는 **입력한 새 값으로 시험하고 저장하지 않음**(상태도 기록 안 함). [저장]은 테스트 결과와 무관하게
+ 저장(쇼핑몰 일시 장애 대비) 후 자동으로 저장값 연결 테스트.
+- 오류 메시지·로그·`raw_data` 는 `security/redact.py` 로 key/secret/token/password/Authorization/Cookie 를 가린 뒤 저장.
+- 쇼핑몰 API 는 **백엔드에서만** 호출. 브라우저는 `/performance/api/*` 만 부른다.
+
+### 마스터 키
+
+| 변수 | 설명 |
+|---|---|
+| `APP_ENCRYPTION_KEY` | 현재 키(32바이트: `openssl rand -hex 32` 64자 hex 또는 base64). **DB·Git 에 넣지 않는다** |
+| `APP_ENCRYPTION_KEY_VERSION` | 현재 키 버전(기본 1) |
+| `APP_ENCRYPTION_KEY_V{n}` | 교체 중 남겨 두는 예전 키 |
+
+교체 절차: 새 키를 `APP_ENCRYPTION_KEY`, 버전 +1, 예전 키를 `APP_ENCRYPTION_KEY_V{예전}` 에 → 재기동 →
+설정 화면 [현재 키로 다시 암호화](`POST /performance/api/rekey`) → 예전 버전 0개 확인 후 `_V{n}` 삭제.
+**키를 잃으면 저장된 인증정보는 복구할 수 없다** — 키는 서버 `.env` 와 별도 안전한 곳에 백업한다
+(DB 백업만으로는 복호화 불가 — 의도된 설계).
+
+## 5. 권한 (서버에서 검사)
+
+| 기능 | 권한 |
+|---|---|
+| 대시보드 · 매출 업데이트 · 금액 상세 | `performance` (admin 자동) |
+| 설정 화면 · 수수료 · 인증정보 · 연결 테스트 · 테스트 데이터 · 재암호화 | `is_admin` |
+
+화면에서 설정 탭을 숨기는 것과 별개로 모든 설정 API 가 `common.require_store(admin=True)` 로 403 을 낸다.
+
+## 6. 동기화 (`sync.py`)
+
+- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·향후 cron/worker 공용. 기본 기간: 오늘 포함 최근
+ `PERFORMANCE_SYNC_DAYS`(기본 7)일.
+- **대시보드 [매출 업데이트]** = 지금 보고 있는 기간(오늘까지)을 `POST /api/sync {from, to}` 로 다시 가져온다
+ ("이번달"이면 1일~오늘). 모듈 권한자는 92일까지, 더 긴 기간(올해 등, 최대 366일)은 관리자만.
+- **과거 매출 가져오기**(설정 화면, 관리자): 같은 API 로 임의 기간(최대 366일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
+- 카페24 **환불합계 규칙(확정, 2026-09-29 실데이터)**: 카페24 "일별 매출내역" 환불합계 = 환불 목록의 (실제 환불액 + 적립금·예치금 환불)
+ + 환불 목록에 없는 취소·반품(네이버페이 등, 취소일 기준). 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800,
+ 9/27 = 145,000 + 네이버페이 55,800 = 200,800 으로 일치. 대조 도구에 환불합계 후보(값 입력 시 일치 줄 강조)·환불 건별·
+ 취소/반품 완료 품목·그날 결제 주문 중 줄어든 주문 표가 있어 규칙이 어긋나면 이것으로 다시 찾는다.
+- 같은 쇼핑몰 동시 실행 금지: `perf_sync_runs` 의 `status='running'` 부분 유니크 인덱스(30분 넘은 running 은 정리).
+- 쇼핑몰 하나 실패 → 그 쇼핑몰만 상태 오류(`perf_connection_status`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고
+ 상단에 오류 쇼핑몰만 표시.
+- 중복 방지: `UNIQUE(marketplace_code, event_type, external_event_id)` + `ON CONFLICT DO UPDATE`.
+
+## 7. 화면
+
+- **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…`
+ 기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행),
+ [총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
+ 월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내).
+- **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태
+ (정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), 마스터 키 상태·재암호화,
+ 테스트 데이터 생성/삭제(`is_sample`).
+
+## 8. 테스트
+
+```bash
+python -m app.modules.performance.tests.test_performance # 또는 pytest
+```
+
+암호화(왕복·AAD·변조·키 교체), 가리기, 수수료 반올림·요율 이력, 기간/주 계산, 표·누적 합계, 인증정보 비노출·재암호화,
+동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다.
diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md
index 47dbd06..58e040c 100644
--- a/docs/PROJECT_OVERVIEW.md
+++ b/docs/PROJECT_OVERVIEW.md
@@ -21,13 +21,14 @@
| 쿠팡 밀크런 | 쿠팡 출고 일정 관리 (`app/modules/cupang/`) — 월간 달력 / 출고 묶음(헤더+라인) / 상자 입수량 자동계산 / 로켓 매출 관리 / 엑셀 내보내기. 상품은 `itemcode_db` 읽기 전용 참조 |
| 휴가 (준비중) | 연차/반차/특별휴가 신청·잔여일수 관리 |
| 말레이시아 재고 | 말레이시아 창고 재고관리 (`app/modules/malaysia/`) — 낱개 입출고/조정, 세트 BOM, 일일 재고조사(세트 분해 자동 반영), 현재고 현황. 상품명은 `itemcode_db` 읽기 전용 참조 |
+| 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` |
### 권한 키 (`MODULE_KEYS`)
| 키 | 종류 | 설명 |
| --- | --- | --- |
| `corm` / `order` | 접근 | 외부 모듈 진입 |
-| `expense` / `vacation` / `cupang` / `malaysia` | 접근 | 내부 모듈 진입 |
+| `expense` / `vacation` / `cupang` / `malaysia` / `performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) |
| `expense_approver` | 결재 | 개인경비 승인/반려/정산 |
| `vacation_approver` | 결재 | 휴가 승인/반려 (모듈 미개발) |
@@ -91,6 +92,7 @@ app/modules//
| `cupang_db` | 쿠팡 밀크런 출고/입고센터/박스규칙 (`CUPANG_DB_URL` 필수, JSON 폴백 없음) |
| `vacation_db` | 휴가 신청/공휴일/연차잔여 (`VACATION_DB_URL` 필수, JSON 폴백 없음) |
| `malaysia_stock_db` | 말레이시아 창고 재고/세트BOM/재고조사 (`MALAYSIA_STOCK_DB_URL` 필수, JSON 폴백 없음) |
+| `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) |
> 신규 DB가 필요하면 **승인 요청 후** 생성하며, 이름은 `_db`로 끝낸다. 상세는 `DATABASES.md`.
diff --git a/scripts/sql/performance_db_init.sql b/scripts/sql/performance_db_init.sql
new file mode 100644
index 0000000..175ad01
--- /dev/null
+++ b/scripts/sql/performance_db_init.sql
@@ -0,0 +1,223 @@
+-- =====================================================================
+-- performance_db 초기화 스크립트 (PostgreSQL) — 실적(쇼핑몰 통합 매출) 모듈
+-- =====================================================================
+-- 멱등(idempotent): 여러 번 실행해도 안전. 기존 데이터를 삭제하지 않는다.
+--
+-- ⚠️ 실행 전 사용자 승인 + 백업 확인 필수. DROP/TRUNCATE 없음.
+--
+-- 실행 방법 (운영 PostgreSQL 컨테이너명: postgres-db):
+--
+-- 1) DB / 역할 / 스키마 생성 (superuser 로 1회)
+-- read -s -p "performance_app password: " APP_PWD; echo
+-- docker exec -i postgres-db psql -U postgres \
+-- -v app_password="$APP_PWD" \
+-- < scripts/sql/performance_db_init.sql
+--
+-- 2) main-app .env 에 추가
+-- PERFORMANCE_DB_URL=postgresql://performance_app:@postgres-db:5432/performance_db
+-- APP_ENCRYPTION_KEY=$(openssl rand -hex 32) # 쇼핑몰 인증정보 암호화 마스터 키
+-- APP_ENCRYPTION_KEY_VERSION=1
+--
+-- 3) main-app 재기동
+-- cd /opt/www/main && docker compose up -d --build
+--
+-- 주의:
+-- - 기존 DB 가 있으면 DROP 하지 않는다(CREATE DATABASE 는 미존재 시에만).
+-- - 비밀번호는 절대 Git 에 커밋하지 않는다. psql -v 로만 전달.
+-- - 쇼핑몰 API 인증정보는 이 DB 에 **암호문**으로만 들어간다(perf_credentials).
+-- 암호화 마스터 키(APP_ENCRYPTION_KEY)는 DB 에 저장하지 않는다.
+-- =====================================================================
+
+\set ON_ERROR_STOP on
+
+SELECT 'CREATE DATABASE performance_db ENCODING ''UTF8'' TEMPLATE template0'
+WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'performance_db')
+\gexec
+
+SELECT 'CREATE ROLE performance_app LOGIN PASSWORD ' || quote_literal(:'app_password')
+WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'performance_app')
+\gexec
+
+SELECT 'ALTER ROLE performance_app WITH LOGIN PASSWORD ' || quote_literal(:'app_password')
+\gexec
+
+GRANT CONNECT ON DATABASE performance_db TO performance_app;
+
+\connect performance_db
+
+CREATE OR REPLACE FUNCTION perf_set_updated_at() RETURNS trigger AS $$
+BEGIN
+ NEW.updated_at := now();
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+-- ════════════════════════════════════════════════════════════
+-- 1) 쇼핑몰 기본 설정 — 사용 여부 / 매출 집계 여부 / 표시 순서
+-- 어댑터(코드)가 쇼핑몰의 "종류"를 정의하고, 이 표는 운영 설정만 담는다.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_marketplaces (
+ code TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ include_in_sales BOOLEAN NOT NULL DEFAULT TRUE,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+DROP TRIGGER IF EXISTS trg_perf_marketplaces_updated ON perf_marketplaces;
+CREATE TRIGGER trg_perf_marketplaces_updated
+ BEFORE UPDATE ON perf_marketplaces
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+INSERT INTO perf_marketplaces (code, name, sort_order) VALUES
+ ('cafe24', '카페24', 10),
+ ('naver', '네이버 스마트스토어', 20),
+ ('coupang', '쿠팡', 30),
+ ('ohouse', '오늘의집', 40),
+ ('gmarket', 'G마켓', 50),
+ ('kakao', '카카오', 60),
+ ('gsshop', 'GS샵', 70),
+ ('elevenst', '11번가', 80),
+ ('lotteon', '롯데ON', 90),
+ ('toss', '토스쇼핑', 100)
+ON CONFLICT (code) DO NOTHING;
+
+-- ════════════════════════════════════════════════════════════
+-- 2) 수수료율 이력 — 적용 시작일(effective_from)부터 다음 변경 전까지 그 요율.
+-- 과거 실적은 그 날짜에 유효했던 요율로 계산한다(요율을 바꿔도 과거가 안 바뀜).
+-- rule_type 은 향후 상품별/카테고리별/정액 수수료 확장용(현재 'marketplace' 만).
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_commission_rates (
+ id BIGSERIAL PRIMARY KEY,
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ rule_type TEXT NOT NULL DEFAULT 'marketplace'
+ CHECK (rule_type IN ('marketplace')),
+ rate_percent NUMERIC(7,3) NOT NULL CHECK (rate_percent >= 0 AND rate_percent <= 100),
+ effective_from DATE NOT NULL,
+ memo TEXT NOT NULL DEFAULT '',
+ created_by TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (marketplace_code, rule_type, effective_from)
+);
+CREATE INDEX IF NOT EXISTS idx_perf_rates_code_from
+ ON perf_commission_rates (marketplace_code, effective_from DESC);
+
+-- ════════════════════════════════════════════════════════════
+-- 3) 쇼핑몰 API 인증정보 — 항목 하나 = 행 하나, 값은 AES-256-GCM 암호문.
+-- encrypted_value 형식: "v{키버전}:{base64url(nonce + 암호문 + tag)}"
+-- key_version 은 마스터 키 교체(rotation) 때 재암호화 대상을 찾는 데 쓴다.
+-- access/refresh token 도 여기에 같은 방식으로 저장한다.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_credentials (
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ credential_key TEXT NOT NULL,
+ encrypted_value TEXT NOT NULL,
+ key_version INTEGER NOT NULL,
+ updated_by TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (marketplace_code, credential_key)
+);
+DROP TRIGGER IF EXISTS trg_perf_credentials_updated ON perf_credentials;
+CREATE TRIGGER trg_perf_credentials_updated
+ BEFORE UPDATE ON perf_credentials
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+-- ════════════════════════════════════════════════════════════
+-- 4) 연결 상태 — 연결 테스트/동기화 결과. last_error 는 비밀값을 가린 문구만.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_connection_status (
+ marketplace_code TEXT PRIMARY KEY REFERENCES perf_marketplaces(code),
+ status TEXT NOT NULL DEFAULT 'unknown'
+ CHECK (status IN ('ok', 'not_configured', 'auth_failed', 'token_expired',
+ 'api_error', 'not_implemented', 'unknown')),
+ last_test_at TIMESTAMPTZ,
+ last_test_ok BOOLEAN,
+ last_sync_at TIMESTAMPTZ,
+ last_success_sync_at TIMESTAMPTZ,
+ last_error TEXT NOT NULL DEFAULT '',
+ last_error_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+DROP TRIGGER IF EXISTS trg_perf_status_updated ON perf_connection_status;
+CREATE TRIGGER trg_perf_status_updated
+ BEFORE UPDATE ON perf_connection_status
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+-- ════════════════════════════════════════════════════════════
+-- 5) 매출 사건 — 결제(+), 취소(-), 반품(-). 금액은 원 단위 정수(BIGINT).
+-- sales_date = 집계 기준일. 결제는 결제일, 취소·반품은 발생일
+-- (지난 실적이 나중에 바뀌지 않게). order_date/payment_date 는 원래 날짜를
+-- 따로 보관해 기준을 바꿀 수 있게 한다.
+-- 중복 방지: UNIQUE(쇼핑몰, 사건 종류, 외부 사건 ID) — 같은 사건은 덮어쓴다.
+-- raw_data 는 비밀값을 가린 원본. is_sample = 테스트(모의) 데이터.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_sales_events (
+ id BIGSERIAL PRIMARY KEY,
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ event_type TEXT NOT NULL CHECK (event_type IN ('SALE', 'CANCEL', 'RETURN', 'ADJUST')),
+ external_event_id TEXT NOT NULL,
+ external_order_id TEXT NOT NULL,
+ external_line_id TEXT NOT NULL DEFAULT '',
+ order_date DATE,
+ payment_date DATE,
+ event_date DATE NOT NULL,
+ sales_date DATE NOT NULL,
+ product_name TEXT NOT NULL DEFAULT '',
+ option_name TEXT NOT NULL DEFAULT '',
+ quantity INTEGER NOT NULL DEFAULT 0,
+ amount BIGINT NOT NULL,
+ discount_amount BIGINT NOT NULL DEFAULT 0,
+ order_status TEXT NOT NULL DEFAULT '',
+ raw_data JSONB,
+ is_sample BOOLEAN NOT NULL DEFAULT FALSE,
+ synced_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (marketplace_code, event_type, external_event_id)
+);
+CREATE INDEX IF NOT EXISTS idx_perf_events_date_code ON perf_sales_events (sales_date, marketplace_code);
+CREATE INDEX IF NOT EXISTS idx_perf_events_order ON perf_sales_events (marketplace_code, external_order_id);
+CREATE INDEX IF NOT EXISTS idx_perf_events_sample ON perf_sales_events (is_sample) WHERE is_sample;
+DROP TRIGGER IF EXISTS trg_perf_events_updated ON perf_sales_events;
+CREATE TRIGGER trg_perf_events_updated
+ BEFORE UPDATE ON perf_sales_events
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+-- ════════════════════════════════════════════════════════════
+-- 6) 동기화 실행 기록 — 같은 쇼핑몰은 동시에 하나만(running 부분 유니크 인덱스).
+-- 웹/스케줄러 어디서 돌려도 중복 실행이 막힌다.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_sync_runs (
+ id BIGSERIAL PRIMARY KEY,
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ trigger TEXT NOT NULL DEFAULT 'manual' CHECK (trigger IN ('manual', 'schedule')),
+ range_from DATE,
+ range_to DATE,
+ status TEXT NOT NULL DEFAULT 'running'
+ CHECK (status IN ('running', 'success', 'failed')),
+ fetched_count INTEGER NOT NULL DEFAULT 0,
+ upserted_count INTEGER NOT NULL DEFAULT 0,
+ error TEXT NOT NULL DEFAULT '',
+ started_by TEXT NOT NULL DEFAULT '',
+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ finished_at TIMESTAMPTZ
+);
+CREATE UNIQUE INDEX IF NOT EXISTS uq_perf_sync_running
+ ON perf_sync_runs (marketplace_code) WHERE status = 'running';
+CREATE INDEX IF NOT EXISTS idx_perf_sync_runs_code ON perf_sync_runs (marketplace_code, started_at DESC);
+
+-- ════════════════════════════════════════════════════════════
+-- 권한 — 앱 계정은 DML 만
+-- ════════════════════════════════════════════════════════════
+GRANT USAGE ON SCHEMA public TO performance_app;
+GRANT SELECT, INSERT, UPDATE, DELETE ON
+ perf_marketplaces, perf_commission_rates, perf_credentials,
+ perf_connection_status, perf_sales_events, perf_sync_runs
+ TO performance_app;
+GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO performance_app;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO performance_app;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public
+ GRANT USAGE, SELECT ON SEQUENCES TO performance_app;