27ee92c0a6
원인: 품목 결제금액(배송비 제외)을 매출로, 취소·반품 완료일의 품목 금액을 환불로 잡아 카페24 화면(결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰, 환불합계 = 환불완료일 실제 환불액)과 달랐다. - SALE: 결제일 기준 주문 단위 결제합계(initial_order_amount — 결제 당시 금액) - CANCEL/RETURN: GET /admin/refunds 환불완료일, 실제 환불액(환불코드 R=반품) - 환불도 원 주문 market_id 로 자체몰만(다른 마켓 연동 주문 제외) - 기간 교체(replace_range): 동기화한 기간의 카페24 실데이터를 지우고 새로 넣음(한 트랜잭션, 테스트 데이터 제외) — 예전 품목 단위 행이 남아 이중 집계되지 않게 - 설정 화면 "카페24 매출 대조": 날짜별로 카페24 화면 열 순서대로 원천 금액 합산(자체몰/마켓 구분, 저장 안 함) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
532 lines
28 KiB
Python
532 lines
28 KiB
Python
"""실적 모듈 테스트 — 암호화·가리기·계산·인증정보·동기화. 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 (
|
|
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"] == "월 9/28" and rows[6]["label"] == "일 10/4"
|
|
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):
|
|
self.events = {k: v for k, v in self.events.items()
|
|
if not (k[0] == code and not v["is_sample"] and start <= v["sales_date"] <= end)}
|
|
return self.upsert_events(code, events)
|
|
|
|
def upsert_events(self, code, events, *, is_sample=False):
|
|
n = 0
|
|
for e in events:
|
|
self.events[(code, 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)
|
|
r = svc.sync_marketplace("elevenst", date(2026, 9, 29), date(2026, 9, 29))
|
|
assert r["status"] == "not_configured" # 키 미입력
|
|
creds.save(next(a for a in all_adapters() if a.code == "elevenst"), {"api_key": "k-123456"})
|
|
r = svc.sync_marketplace("elevenst", date(2026, 9, 29), date(2026, 9, 29))
|
|
assert r["status"] == "not_implemented" and "k-123456" not in r["message"]
|
|
t = svc.test_connection("elevenst", values={"api_key": "typed-only"})
|
|
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 "일별 매출내역" 기준
|
|
# ════════════════════════════════════════════════════════════
|
|
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": "0.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"}, # 취소 후 금액은 쓰지 않는다
|
|
"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):
|
|
self.orders_pages = orders_pages # 결제일 조회 페이지들
|
|
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]}
|
|
return {"orders": self.orders_pages[idx] if idx < len(self.orders_pages) else []}
|
|
|
|
|
|
def test_cafe24_normalize_matches_daily_report():
|
|
from app.modules.performance.adapters.base import AdapterContext
|
|
from app.modules.performance.adapters.cafe24 import order_total
|
|
|
|
ctx = AdapterContext(code="cafe24", credentials=None)
|
|
fake = _FakeCafe24(
|
|
[[_c24_order("A"), _c24_order("B", market="shopn"), _c24_order("C", paid="F")]],
|
|
[[_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}
|
|
# 결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰 (결제 당시 금액)
|
|
sale = by[("SALE", "A-PAY")]
|
|
assert sale.amount == 50_000 + 3_000 - 1_000 - 5_000 == 47_000
|
|
assert sale.event_date == date(2026, 9, 29) and sale.quantity == 2 and sale.product_name == "상품1 외 1건"
|
|
assert not any(e.external_order_id in ("B", "C") and e.event_type == "SALE" for e in events) # 마켓·미결제 제외
|
|
# 환불: 환불완료일, 실제 환불액, R→반품 / 그 밖→취소, 마켓 주문·미완료 환불 제외
|
|
assert by[("CANCEL", "C20260929-01")].amount == -12_610
|
|
assert by[("RETURN", "R20260929-02")].amount == -20_000
|
|
assert ("CANCEL", "C20260929-03") not in by and ("CANCEL", "C20260929-04") not in by
|
|
assert by[("CANCEL", "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({"initial_order_amount": {"order_price_amount": "1578300.00", "shipping_fee": "45500.00",
|
|
"coupon_discount_price": "57000.00"}}) == 1_566_800 # 9/29 화면값
|
|
# 대조: 자체몰/마켓 나눠 합산
|
|
rec = fake.reconcile(ctx, date(2026, 9, 29))
|
|
assert rec["orders"]["self"]["orders"] == 1 and rec["orders"]["self"]["total"] == 47_000
|
|
assert rec["orders"]["market"]["orders"] == 1 and rec["unpaid_orders"] == 1
|
|
assert rec["refunds"]["self"]["actual_refund_amount"] == 32_610 and rec["refunds"]["market"]["count"] == 1
|
|
# 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_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)
|
|
# 기간 교체: 그 기간의 예전 실데이터(품목 단위 등)는 지우고, 테스트 데이터·기간 밖은 남긴다
|
|
st = FakeStore()
|
|
st.upsert_events("cafe24", [{"event_type": "SALE", "external_event_id": "old-item-S", "external_order_id": "A",
|
|
"event_date": date(2026, 9, 29), "sales_date": date(2026, 9, 29), "amount": 1}])
|
|
st.upsert_events("cafe24", [{"event_type": "SALE", "external_event_id": "outside", "external_order_id": "Z",
|
|
"event_date": date(2026, 9, 1), "sales_date": date(2026, 9, 1), "amount": 1}])
|
|
st.upsert_events("cafe24", [{"event_type": "SALE", "external_event_id": "sample", "external_order_id": "S",
|
|
"event_date": date(2026, 9, 29), "sales_date": date(2026, 9, 29), "amount": 1}],
|
|
is_sample=True)
|
|
fake = _FakeCafe24([[_c24_order("A")]])
|
|
orig = syncmod.get_adapter
|
|
syncmod.get_adapter = lambda c: fake
|
|
try:
|
|
r = SyncService(st, CredentialService(st, lambda: ring())).sync_marketplace(
|
|
"cafe24", date(2026, 9, 29), date(2026, 9, 29))
|
|
finally:
|
|
syncmod.get_adapter = orig
|
|
ids = {k[2] for k in st.events if k[0] == "cafe24"}
|
|
assert r["ok"] and ids == {"A-PAY", "outside", "sample"}, ids
|
|
|
|
|
|
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")
|