feat(performance): 카페24 주문 매출 수집 연동 + 과거 매출 가져오기
카페24 (Admin API GET /admin/orders, 문서 2026-09-01 기준) - 결제(SALE): date_type=pay_date, embed=items — 결제된 주문의 품목 결제금액(할인 반영·배송비 제외), 결제일 - 취소(CANCEL): cancel_complete_date, 품목 C40~C43 만 음수(입금전취소 C47~C49 제외) - 반품(RETURN): return_complete_date, 품목 R40~R43 음수, 부분 반품은 claim_quantity 비율 - 자체몰 주문만(market_id=self) — 카페24로 연동된 다른 마켓 주문은 이중 집계 방지로 제외 - 60일 단위 분할(한 호출 3개월 미만), limit 1000 페이지 넘김, 개인정보 미저장(raw 는 금액·상태만) - 기존 app/integrations/cafe24 토큰·클라이언트 재사용, 연결 테스트는 주문 권한까지 확인 - DEFAULT_SCOPES 에 mall.read_order 추가(읽기만) — 카페24 상품관리 → 시스템에서 재연결 필요 과거 매출 가져오기(설정, 관리자): 기간 지정 수집(최대 366일), 일반 사용자는 403 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,49 +1,252 @@
|
||||
"""카페24 — 공통 연동 계층(app/integrations/cafe24) 재사용.
|
||||
|
||||
카페24는 이미 OAuth 로 연결해 쓰고 있다(상품관리). 실적 설정에서 인증정보를 따로
|
||||
받지 않고, 같은 토큰 저장소(cafe24_db)의 연결 상태를 그대로 보여 준다.
|
||||
주문 수집(다음 단계)에는 카페24 앱 권한에 mall.read_order 추가 + 재연결이 필요하다
|
||||
(app/integrations/cafe24/config.py 의 ORDER_SCOPES).
|
||||
받지 않고, 같은 토큰 저장소(cafe24_db)와 클라이언트(재시도·429·토큰 자동 갱신)를 쓴다.
|
||||
주문 읽기 권한(mall.read_order)이 필요하다 — config.DEFAULT_SCOPES 에 포함, 권한 추가 후
|
||||
카페24 상품관리 → 시스템에서 한 번 다시 연결해야 한다.
|
||||
|
||||
수집 규칙 (Admin API GET /admin/orders, 문서 버전 2026-09-01 확인)
|
||||
- 결제(SALE): date_type=pay_date(결제일), embed=items. 결제된(paid=T) 주문의 품목마다
|
||||
품목 결제금액(payment_amount — 할인 반영, 배송비 제외)을 매출로. 사건 날짜 = 결제일.
|
||||
- 취소(CANCEL): date_type=cancel_complete_date. 품목 상태 C40~C43(취소완료)만,
|
||||
결제 때와 같은 품목 금액을 음수로. 입금전취소(C47~C49)는 매출이 아니었으므로 제외.
|
||||
- 반품(RETURN): date_type=return_complete_date. 품목 상태 R40~R43(반품완료)만 음수로.
|
||||
부분 반품(0 < claim_quantity < quantity)은 수량 비율로 나눈다.
|
||||
- 교환(E**)은 매출 변화 없음으로 보고 1단계에서는 반영하지 않는다.
|
||||
- 자체몰 주문만(market_id 가 self/빈값). 카페24 로 들어온 다른 마켓(스마트스토어·쿠팡 등)
|
||||
주문은 해당 쇼핑몰 어댑터와 이중 집계되지 않게 제외한다. 네이버페이 결제는 자체몰 주문이라 포함.
|
||||
- 한 호출 검색기간 3개월 미만 → 60일씩 나눠 요청. limit 최대 1000, offset 최대 15000.
|
||||
- 개인정보(구매자 이름·주소·연락처·계좌)는 저장하지 않는다 — raw 에는 금액·상태 필드만.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import AdapterContext, AuthFailed, MarketplaceAdapter, NotConfigured, TokenExpired
|
||||
from datetime import date, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
MarketplaceAdapter,
|
||||
NotConfigured,
|
||||
SaleEvent,
|
||||
TokenExpired,
|
||||
)
|
||||
|
||||
ORDER_SCOPE = "mall.read_order"
|
||||
PAGE_LIMIT = 1000
|
||||
MAX_OFFSET = 15000
|
||||
CHUNK_DAYS = 60
|
||||
CANCEL_DONE = {"C40", "C41", "C42", "C43"}
|
||||
RETURN_DONE = {"R40", "R41", "R42", "R43"}
|
||||
SELF_MARKETS = {"", "self", None}
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
"""카페24 금액 문자열("29000.00") → 원 단위 정수."""
|
||||
try:
|
||||
return int(Decimal(str(value or "0")).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
except (InvalidOperation, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _day(value: Any) -> date | None:
|
||||
""""2018-07-04T11:21:35+09:00" / "2017-07-10 15:55:51" → date (카페24 는 KST 로 준다)."""
|
||||
s = str(value or "").strip()
|
||||
if len(s) < 10:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(s[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def item_amount(item: dict[str, Any]) -> int:
|
||||
"""품목 결제금액. payment_amount 가 없으면 (판매가+옵션가)×수량 − 품목 할인으로 계산."""
|
||||
if item.get("payment_amount") not in (None, ""):
|
||||
return _won(item["payment_amount"])
|
||||
qty = int(item.get("quantity") or 0)
|
||||
gross = (_won(item.get("product_price")) + _won(item.get("option_price"))) * qty
|
||||
discounts = (_won(item.get("additional_discount_price")) + _won(item.get("coupon_discount_price"))
|
||||
+ _won(item.get("app_item_discount_amount")))
|
||||
return max(0, gross - discounts)
|
||||
|
||||
|
||||
def _raw(order: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""저장용 원본 — 금액·상태만(개인정보 제외)."""
|
||||
keys = ("order_item_code", "order_status", "status_code", "product_no", "product_code", "variant_code",
|
||||
"product_price", "option_price", "quantity", "claim_quantity", "additional_discount_price",
|
||||
"coupon_discount_price", "app_item_discount_amount", "payment_amount", "claim_code")
|
||||
return {
|
||||
"order_id": order.get("order_id"), "market_id": order.get("market_id"),
|
||||
"order_place_id": order.get("order_place_id"), "paid": order.get("paid"),
|
||||
**{k: item.get(k) for k in keys},
|
||||
}
|
||||
|
||||
|
||||
class Cafe24Adapter(MarketplaceAdapter):
|
||||
code = "cafe24"
|
||||
name = "카페24"
|
||||
auth_type = "shared"
|
||||
docs_url = "https://developers.cafe24.com/docs/api/admin/"
|
||||
note = "카페24 상품관리에서 연결한 OAuth 토큰을 함께 씁니다(여기서 따로 입력하지 않음)."
|
||||
implemented = True
|
||||
docs_url = "https://apidocs.cafe24.com/docs/admin/get-orders"
|
||||
note = ("카페24 상품관리에서 연결한 OAuth 토큰을 함께 씁니다(여기서 따로 입력하지 않음). "
|
||||
"주문 읽기 권한이 필요해 권한 추가 후 한 번 다시 연결해야 합니다.")
|
||||
|
||||
# ── 연결 ──────────────────────────────────────────────
|
||||
def is_configured(self, ctx: AdapterContext) -> bool:
|
||||
return True
|
||||
|
||||
def _repo(self, ctx: AdapterContext):
|
||||
return getattr(ctx.app_state, "cafe24_store", None) if ctx.app_state is not None else None
|
||||
|
||||
def shared_status(self, ctx: AdapterContext) -> dict:
|
||||
from app.integrations.cafe24.config import load_config # 지연 import
|
||||
from app.integrations.cafe24.tokens import TokenService # 지연 import
|
||||
|
||||
repo = self._repo(ctx)
|
||||
config = load_config()
|
||||
if repo is None:
|
||||
return {"connected": False, "missing": config.missing or ["CAFE24_DB_URL"], "needs_reauth": False}
|
||||
return TokenService(repo, config).status()
|
||||
|
||||
def authenticate(self, ctx: AdapterContext) -> None:
|
||||
st = self.shared_status(ctx)
|
||||
if not st.get("connected"):
|
||||
if st.get("missing"):
|
||||
raise NotConfigured("카페24 연동 환경변수가 설정되지 않았습니다.")
|
||||
if st.get("needs_reauth") and st.get("reason", "").startswith("refresh"):
|
||||
if st.get("needs_reauth") and str(st.get("reason", "")).startswith("refresh"):
|
||||
raise TokenExpired("카페24 연결이 만료되었습니다. 카페24 상품관리 → 시스템에서 재연결하세요.")
|
||||
raise AuthFailed("카페24에 연결되어 있지 않습니다. 카페24 상품관리 → 시스템에서 연결하세요.")
|
||||
if ORDER_SCOPE not in str(st.get("scopes") or ""):
|
||||
raise AuthFailed("카페24 토큰에 주문 읽기 권한(mall.read_order)이 없습니다. "
|
||||
"카페24 상품관리 → 시스템에서 다시 연결하세요.")
|
||||
|
||||
def shared_status(self, ctx: AdapterContext) -> dict:
|
||||
from app.integrations.cafe24.config import load_config # 지연 import
|
||||
from app.integrations.cafe24.tokens import TokenService # 지연 import
|
||||
def _client(self, ctx: AdapterContext):
|
||||
from app.integrations.cafe24 import build_cafe24_api # 지연 import
|
||||
|
||||
repo = getattr(ctx.app_state, "cafe24_store", None) if ctx.app_state is not None else None
|
||||
config = load_config()
|
||||
if repo is None:
|
||||
return {"connected": False, "missing": config.missing or ["CAFE24_DB_URL"], "needs_reauth": False}
|
||||
return TokenService(repo, config).status()
|
||||
return build_cafe24_api(self._repo(ctx)).client
|
||||
|
||||
def _get(self, ctx: AdapterContext, params: dict[str, Any]) -> dict[str, Any]:
|
||||
from app.integrations.cafe24.errors import ( # 지연 import
|
||||
Cafe24ApiError,
|
||||
Cafe24AuthError,
|
||||
Cafe24ConfigError,
|
||||
Cafe24RateLimitError,
|
||||
)
|
||||
|
||||
try:
|
||||
return self._client(ctx).get("/admin/orders", params=params)
|
||||
except Cafe24ConfigError as exc:
|
||||
raise NotConfigured(str(exc)) from None
|
||||
except Cafe24AuthError as exc:
|
||||
raise AuthFailed(str(exc)) from None
|
||||
except Cafe24RateLimitError as exc:
|
||||
raise ApiError(f"카페24 호출 제한(429): {exc}") from None
|
||||
except Cafe24ApiError as exc:
|
||||
status = getattr(exc, "status", None)
|
||||
if status == 403:
|
||||
raise AuthFailed(f"카페24 권한 오류(403): {exc}. 주문 권한 추가 후 재연결하세요.") from None
|
||||
raise ApiError(f"카페24 API 오류({status}): {exc}") from None
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
self.authenticate(ctx)
|
||||
st = self.shared_status(ctx)
|
||||
scopes = st.get("scopes") or ""
|
||||
if "mall.read_order" not in scopes:
|
||||
return "카페24 연결 정상. 주문 수집에는 주문 읽기 권한(mall.read_order) 추가가 필요합니다."
|
||||
return "카페24 연결 정상."
|
||||
today = today_kst()
|
||||
self._get(ctx, {"start_date": today.isoformat(), "end_date": today.isoformat(),
|
||||
"date_type": "pay_date", "limit": 1})
|
||||
return "카페24 연결 정상(주문 조회 권한 확인)."
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def _orders(self, ctx: AdapterContext, start: date, end: date, date_type: str) -> Iterable[dict[str, Any]]:
|
||||
"""기간을 60일씩 나눠 페이지를 넘기며 주문(+items)을 모두 가져온다."""
|
||||
s = start
|
||||
while s <= end:
|
||||
e = min(end, s + timedelta(days=CHUNK_DAYS - 1))
|
||||
offset = 0
|
||||
while True:
|
||||
if offset > MAX_OFFSET:
|
||||
raise ApiError(f"카페24 조회 건수가 너무 많습니다({s}~{e}). 기간을 줄여 다시 시도하세요.")
|
||||
data = self._get(ctx, {"start_date": s.isoformat(), "end_date": e.isoformat(),
|
||||
"date_type": date_type, "embed": "items",
|
||||
"limit": PAGE_LIMIT, "offset": offset})
|
||||
orders = data.get("orders") or []
|
||||
yield from orders
|
||||
if len(orders) < PAGE_LIMIT:
|
||||
break
|
||||
offset += PAGE_LIMIT
|
||||
s = e + timedelta(days=1)
|
||||
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
for o in self._orders(ctx, start, end, "pay_date"):
|
||||
yield {"kind": "paid", "order": o}
|
||||
|
||||
def fetch_refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
for o in self._orders(ctx, start, end, "cancel_complete_date"):
|
||||
yield {"kind": "cancel", "order": o}
|
||||
for o in self._orders(ctx, start, end, "return_complete_date"):
|
||||
yield {"kind": "return", "order": o}
|
||||
|
||||
@staticmethod
|
||||
def _is_self_order(order: dict[str, Any]) -> bool:
|
||||
return order.get("market_id") in SELF_MARKETS
|
||||
|
||||
def normalize_order(self, raw: dict[str, Any]) -> list[SaleEvent]:
|
||||
order = raw.get("order") or {}
|
||||
if not self._is_self_order(order) or order.get("paid") != "T":
|
||||
return []
|
||||
pay_day = _day(order.get("payment_date"))
|
||||
if pay_day is None:
|
||||
return []
|
||||
order_id = str(order.get("order_id") or "")
|
||||
events = []
|
||||
for item in order.get("items") or []:
|
||||
code = str(item.get("order_item_code") or "")
|
||||
if not code:
|
||||
continue
|
||||
events.append(SaleEvent(
|
||||
event_type="SALE", external_event_id=f"{code}-S", external_order_id=order_id,
|
||||
external_line_id=code, order_date=_day(order.get("order_date")), payment_date=pay_day,
|
||||
event_date=pay_day, amount=item_amount(item), product_name=str(item.get("product_name") or ""),
|
||||
option_name=str(item.get("option_value") or "") if isinstance(item.get("option_value"), str) else "",
|
||||
quantity=int(item.get("quantity") or 0), order_status=str(item.get("order_status") or ""),
|
||||
raw=_raw(order, item),
|
||||
))
|
||||
return events
|
||||
|
||||
def normalize_refund(self, raw: dict[str, Any]) -> list[SaleEvent]:
|
||||
order = raw.get("order") or {}
|
||||
if not self._is_self_order(order):
|
||||
return []
|
||||
kind = raw.get("kind")
|
||||
done, ev_type, suffix = (CANCEL_DONE, "CANCEL", "C") if kind == "cancel" else (RETURN_DONE, "RETURN", "R")
|
||||
order_id = str(order.get("order_id") or "")
|
||||
events = []
|
||||
for item in order.get("items") or []:
|
||||
code = str(item.get("order_item_code") or "")
|
||||
status = str(item.get("order_status") or "")
|
||||
if not code or status not in done:
|
||||
continue
|
||||
if kind == "cancel":
|
||||
day = _day(item.get("cancel_date")) or _day(order.get("cancel_date"))
|
||||
else:
|
||||
day = _day(item.get("return_confirmed_date")) or _day(item.get("refund_date"))
|
||||
if day is None:
|
||||
continue
|
||||
amount = item_amount(item)
|
||||
qty = int(item.get("quantity") or 0)
|
||||
claim = int(item.get("claim_quantity") or 0)
|
||||
if kind == "return" and 0 < claim < qty:
|
||||
amount = int((Decimal(amount) * claim / qty).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
qty = claim
|
||||
events.append(SaleEvent(
|
||||
event_type=ev_type, external_event_id=f"{code}-{suffix}", external_order_id=order_id,
|
||||
external_line_id=code, order_date=_day(order.get("order_date")),
|
||||
payment_date=_day(order.get("payment_date")), event_date=day, amount=-amount,
|
||||
product_name=str(item.get("product_name") or ""), quantity=-qty, order_status=status,
|
||||
raw=_raw(order, item),
|
||||
))
|
||||
return events
|
||||
|
||||
@@ -36,6 +36,7 @@ from .adapters.registry import all_adapters, get_adapter
|
||||
router = APIRouter(prefix="/performance", tags=["performance"])
|
||||
|
||||
MAX_EVENT_DAYS = 31
|
||||
MAX_BACKFILL_DAYS = 366
|
||||
|
||||
|
||||
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
||||
@@ -127,10 +128,26 @@ def settings_page(request: Request):
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@router.post("/api/sync")
|
||||
def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""기본은 최근 N일(PERFORMANCE_SYNC_DAYS). from/to 로 기간을 지정한 수집(과거 매출 가져오기)은 관리자만."""
|
||||
store, user = common.require_store(request)
|
||||
_, sync = common.services(request, store)
|
||||
codes = [str(c) for c in (payload.get("codes") or []) if get_adapter(str(c))]
|
||||
results = sync.sync_all(codes=codes or None, user=user["email"])
|
||||
start = _parse_date(payload.get("from"), field="시작일")
|
||||
end = _parse_date(payload.get("to"), field="종료일")
|
||||
if start or end:
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
if not is_admin(user):
|
||||
raise HTTPException(status_code=403, detail="기간을 지정한 수집은 관리자만 할 수 있습니다.")
|
||||
end = end or today_kst()
|
||||
start = start or end
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
if end > today_kst():
|
||||
end = today_kst()
|
||||
if (end - start).days + 1 > MAX_BACKFILL_DAYS:
|
||||
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
|
||||
results = sync.sync_all(start=start, end=end, codes=codes or None, user=user["email"])
|
||||
return JSONResponse({"results": results, "last_update_at": store.last_update_at()})
|
||||
|
||||
|
||||
|
||||
@@ -235,4 +235,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260929b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260929c" defer></script>{% endblock %}
|
||||
|
||||
@@ -102,6 +102,19 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">과거 매출 가져오기</h2></div>
|
||||
<p class="perf-muted">[매출 업데이트]는 최근 며칠만 가져옵니다. 처음 연동했거나 빠진 기간이 있으면 기간을 지정해 한 번에
|
||||
가져오세요(연동된 쇼핑몰만, 최대 366일). 같은 주문은 덮어써서 여러 번 해도 중복되지 않습니다.</p>
|
||||
<div class="perf-sample-form">
|
||||
<input class="erp-input perf-date" type="date" id="perf-backfill-from" value="{{ default_sample_from }}" />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" id="perf-backfill-to" value="{{ default_sample_to }}" />
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="perf-backfill">가져오기</button>
|
||||
</div>
|
||||
<div class="perf-notice" id="perf-backfill-result" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">테스트 데이터</h2>
|
||||
<span class="perf-muted">현재 {{ "{:,}".format(sample_count) }}건</span></div>
|
||||
@@ -118,4 +131,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260929b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260929c" defer></script>{% endblock %}
|
||||
|
||||
@@ -378,6 +378,91 @@ def test_not_implemented_and_mock():
|
||||
assert event_row(a[0])["sales_date"] == a[0].payment_date
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 카페24 어댑터(가짜 API 응답)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _c24_item(code, status="N40", price="30000.00", qty=1, pay="29000.00", **kw):
|
||||
return {"order_item_code": code, "order_status": status, "product_name": "냄비", "option_value": "",
|
||||
"product_price": price, "option_price": "0.00", "quantity": qty, "payment_amount": pay,
|
||||
"coupon_discount_price": "1000.00", "claim_quantity": 0, **kw}
|
||||
|
||||
|
||||
def _c24_order(oid, items, market="self", paid="T", **kw):
|
||||
return {"order_id": oid, "market_id": market, "paid": paid, "order_date": "2026-09-27T10:00:00+09:00",
|
||||
"payment_date": "2026-09-28T11:21:35+09:00", "buyer_name": "홍길동", "receiver_address": "서울시",
|
||||
"bank_account_no": "1234567890", "items": items, **kw}
|
||||
|
||||
|
||||
class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist=["Cafe24Adapter"]).Cafe24Adapter):
|
||||
def __init__(self, pages):
|
||||
self.pages = pages # date_type → [응답 orders 목록(페이지별)]
|
||||
self.calls = []
|
||||
|
||||
def authenticate(self, ctx):
|
||||
return None
|
||||
|
||||
def _get(self, ctx, params):
|
||||
self.calls.append(params)
|
||||
pages = self.pages.get(params["date_type"], [])
|
||||
idx = params.get("offset", 0) // 1000
|
||||
return {"orders": pages[idx] if idx < len(pages) else []}
|
||||
|
||||
|
||||
def test_cafe24_normalize():
|
||||
from app.modules.performance.adapters.cafe24 import Cafe24Adapter, item_amount
|
||||
|
||||
paid = _c24_order("20260928-01", [_c24_item("20260928-01-01"), _c24_item("20260928-01-02", pay="10000.00")])
|
||||
market = _c24_order("20260928-02", [_c24_item("20260928-02-01")], market="shopn") # 스마트스토어 연동 주문
|
||||
unpaid = _c24_order("20260928-03", [_c24_item("20260928-03-01", status="N00")], paid="F")
|
||||
canceled = _c24_order("20260928-01", [
|
||||
_c24_item("20260928-01-01", status="C40", cancel_date="2026-09-29 09:00:00"),
|
||||
_c24_item("20260928-01-02", status="N40")])
|
||||
precancel = _c24_order("20260928-04", [_c24_item("20260928-04-01", status="C48", cancel_date="2026-09-29 09:00:00")])
|
||||
returned = _c24_order("20260928-05", [_c24_item("20260928-05-01", status="R40", qty=3, pay="90000.00",
|
||||
claim_quantity=1, return_confirmed_date="2026-09-30 10:00:00")])
|
||||
fake = _FakeCafe24({"pay_date": [[paid, market, unpaid]],
|
||||
"cancel_complete_date": [[canceled, precancel]],
|
||||
"return_complete_date": [[returned]]})
|
||||
ctx = __import__("app.modules.performance.adapters.base", fromlist=["AdapterContext"]).AdapterContext(
|
||||
code="cafe24", credentials=None)
|
||||
fetched, events = fake.collect(ctx, date(2026, 9, 23), date(2026, 9, 30))
|
||||
by = {(e.event_type, e.external_line_id): e for e in events}
|
||||
assert fetched == 6
|
||||
assert by[("SALE", "20260928-01-01")].amount == 29_000 and by[("SALE", "20260928-01-02")].amount == 10_000
|
||||
assert by[("SALE", "20260928-01-01")].event_date == date(2026, 9, 28) # 결제일
|
||||
assert ("SALE", "20260928-02-01") not in by and ("SALE", "20260928-03-01") not in by # 마켓 주문·미결제 제외
|
||||
c = by[("CANCEL", "20260928-01-01")]
|
||||
assert c.amount == -29_000 and c.event_date == date(2026, 9, 29) and c.external_event_id == "20260928-01-01-C"
|
||||
assert ("CANCEL", "20260928-01-02") not in by and ("CANCEL", "20260928-04-01") not in by # 미취소·입금전취소 제외
|
||||
r = by[("RETURN", "20260928-05-01")]
|
||||
assert r.amount == -30_000 and r.quantity == -1 and r.event_date == date(2026, 9, 30) # 3개 중 1개 반품
|
||||
for e in events:
|
||||
assert "buyer_name" not in e.raw and "receiver_address" not in e.raw and "bank_account_no" not in e.raw
|
||||
# 금액: payment_amount 없으면 (판매가+옵션)×수량 − 할인
|
||||
assert item_amount({"product_price": "10000.00", "option_price": "500.00", "quantity": 2,
|
||||
"coupon_discount_price": "1000.00"}) == 20_000
|
||||
# 60일 단위 분할 + 페이지 넘김(1000건이면 다음 페이지)
|
||||
page1 = [_c24_order(f"x-{i}", []) for i in range(1000)]
|
||||
fake2 = _FakeCafe24({"pay_date": [page1, [paid]]})
|
||||
got = list(fake2.fetch_orders(ctx, date(2026, 7, 1), date(2026, 9, 30)))
|
||||
pay_calls = [c for c in fake2.calls if c["date_type"] == "pay_date"]
|
||||
assert len(got) == 2002 # 60일 구간 2개 × (1000건 페이지 + 다음 페이지 1건)
|
||||
assert pay_calls[0]["start_date"] == "2026-07-01" and pay_calls[0]["end_date"] == "2026-08-29"
|
||||
assert pay_calls[1]["offset"] == 1000 and all(c["limit"] == 1000 and c["embed"] == "items" for c in pay_calls)
|
||||
assert any(c["start_date"] == "2026-08-30" for c in pay_calls)
|
||||
# 주문 권한 없는 토큰 → 인증 실패(재연결 안내)
|
||||
real = Cafe24Adapter()
|
||||
real.shared_status = lambda ctx: {"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 ctx: {"connected": True, "scopes": "mall.read_product,mall.read_order"}
|
||||
real.authenticate(ctx)
|
||||
|
||||
|
||||
def test_registry_and_event_validation():
|
||||
codes = [a.code for a in all_adapters()]
|
||||
assert len(codes) == len(set(codes)) == 10
|
||||
|
||||
Reference in New Issue
Block a user