diff --git a/app/integrations/cafe24/config.py b/app/integrations/cafe24/config.py index efa98fb..ad80757 100644 --- a/app/integrations/cafe24/config.py +++ b/app/integrations/cafe24/config.py @@ -33,7 +33,10 @@ STORE_SCOPES: tuple[str, ...] = ("mall.read_store", "mall.write_store") # 실제로 요청하는 scope 묶음. 개발자센터 앱에 등록된 권한과 어긋나면 인증이 # 거부되므로, 여기에 추가할 때는 앱 권한도 함께 확인해야 한다. # 쓰지 않는 권한은 요청하지 않는다 — 토큰이 유출돼도 피해 범위를 좁히기 위함. -DEFAULT_SCOPES: tuple[str, ...] = PRODUCT_SCOPES +# 주문은 읽기만(실적 모듈의 매출 수집) — 앱에 쓰기 권한이 있어도 요청하지 않는다. +# 이 목록을 바꾸면 카페24 상품관리 → 시스템에서 한 번 다시 연결해야 새 권한이 토큰에 붙는다 +# (기존 토큰은 예전 권한 그대로 계속 동작). +DEFAULT_SCOPES: tuple[str, ...] = PRODUCT_SCOPES + ("mall.read_order",) DEFAULT_API_VERSION = "2026-03-01" diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py index d931d8e..85cc105 100644 --- a/app/modules/performance/adapters/cafe24.py +++ b/app/modules/performance/adapters/cafe24.py @@ -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 diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index d5f7ae1..479905d 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -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()}) diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index ef87ca1..1ba74ca 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -235,4 +235,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html index 2cdec23..3dc985b 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -102,6 +102,19 @@

+
+

과거 매출 가져오기

+

[매출 업데이트]는 최근 며칠만 가져옵니다. 처음 연동했거나 빠진 기간이 있으면 기간을 지정해 한 번에 + 가져오세요(연동된 쇼핑몰만, 최대 366일). 같은 주문은 덮어써서 여러 번 해도 중복되지 않습니다.

+
+ + ~ + + +
+ +
+

테스트 데이터

현재 {{ "{:,}".format(sample_count) }}건
@@ -118,4 +131,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index bf78aeb..21d494b 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -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 diff --git a/app/static/performance.js b/app/static/performance.js index e61f20d..2be3082 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -470,6 +470,46 @@ } finally { btn.disabled = false; btn.textContent = label; } } + // ── 과거 매출 가져오기(기간 지정 수집, 관리자) ── + 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 () { 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/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index e1421cc..9758bd2 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -29,9 +29,27 @@ 오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중). -**현재(1단계)**: 10개 어댑터 모두 입력칸만 정의, 수집은 `NotImplementedYet`. 카페24는 `auth_type="shared"` — 기존 -`app/integrations/cafe24` OAuth 토큰(cafe24_db)을 재사용해 연결 상태만 확인한다(주문 수집 시 앱 권한에 -`mall.read_order` 추가 + 재연결 필요). 쇼핑몰별 입력칸은 **연동 단계에서 공식 API 문서로 확정**한다. +**연동 현황**: 카페24 = **구현됨**, 나머지 9개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은 +**연동 단계에서 공식 API 문서로 확정**한다. + +### 카페24 (`adapters/cafe24.py`, 구현됨) + +`auth_type="shared"` — 기존 `app/integrations/cafe24` OAuth 토큰(cafe24_db)과 클라이언트(재시도·429·토큰 자동 갱신)를 +재사용한다. 토큰에 `mall.read_order` 가 있어야 한다(`DEFAULT_SCOPES` 포함, 권한 추가 후 카페24 상품관리 → 시스템에서 재연결). +Admin API `GET /admin/orders`(문서 버전 2026-09-01 확인: 검색기간 한 호출 3개월 미만, limit ≤ 1000, offset ≤ 15000). + +| 사건 | 조회 | 대상 | 금액·날짜 | +|---|---|---|---| +| SALE | `date_type=pay_date`, `embed=items` | `paid=T` 주문의 모든 품목 | +품목 결제금액(`payment_amount`, 할인 반영·배송비 제외), 결제일 | +| CANCEL | `date_type=cancel_complete_date` | 품목 상태 C40~C43(취소완료). 입금전취소 C47~C49 제외 | −같은 품목 금액, 품목 `cancel_date` | +| RETURN | `date_type=return_complete_date` | 품목 상태 R40~R43(반품완료) | −품목 금액(부분 반품은 `claim_quantity/quantity` 비율), `return_confirmed_date` | + +- 사건 ID = `{order_item_code}-S|C|R` (중복 방지). 교환(E**)은 1단계에서 반영 안 함. +- **자체몰 주문만**(`market_id` = self/빈값). 카페24 로 연동돼 들어온 다른 마켓 주문(스마트스토어·쿠팡 등)은 해당 쇼핑몰 + 어댑터와 이중 집계되지 않게 제외. 네이버페이 결제(`order_place_id=NCHECKOUT`)는 자체몰 주문이라 포함. +- 기간은 60일씩 나눠 요청, 1000건 단위 페이지. 개인정보(구매자 이름·주소·연락처·계좌)는 저장하지 않고 raw 에는 금액·상태만. +- **실데이터로 확인할 것**: 품목 `payment_amount` 가 적립금·예치금 사용분을 어떻게 반영하는지, 부분 취소/반품 시 품목이 + 분리되는지(`claim_quantity` 해석). 카페24 관리자 화면 매출과 한 주 정도 대조 후 필요하면 규칙 조정. ### 연동 단계 체크리스트(쇼핑몰마다) @@ -92,6 +110,8 @@ - `SyncService.sync_all()` / `sync_marketplace()` — 버튼·향후 cron/worker 공용. 기본 기간: 오늘 포함 최근 `PERFORMANCE_SYNC_DAYS`(기본 7)일. +- **과거 매출 가져오기**(설정 화면, 관리자): `POST /api/sync {from, to}` — 기간 지정 수집(최대 366일, 미래는 오늘까지). + 처음 연동했거나 빠진 기간을 채울 때. 같은 사건은 덮어써서 여러 번 해도 중복 없음. 일반 사용자가 기간을 주면 403. - 같은 쇼핑몰 동시 실행 금지: `perf_sync_runs` 의 `status='running'` 부분 유니크 인덱스(30분 넘은 running 은 정리). - 쇼핑몰 하나 실패 → 그 쇼핑몰만 상태 오류(`perf_connection_status`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고 상단에 오류 쇼핑몰만 표시.