diff --git a/app/modules/performance/adapters/toss.py b/app/modules/performance/adapters/toss.py index e525156..49d8e24 100644 --- a/app/modules/performance/adapters/toss.py +++ b/app/modules/performance/adapters/toss.py @@ -1,22 +1,371 @@ -"""토스쇼핑 — 판매자 API. +"""토스쇼핑 — 토스쇼핑 API(shopping-fep). -인증 방식·필드는 연동 단계에서 공식 문서로 확정한다. +문서: https://shopping-docs.toss.im/dev (전체 목록 llms.txt, 각 쪽 주소 뒤에 .md 를 붙이면 원문) + +인증(공식 방식): 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > 자체 개발 → [키 발급](호출 IP 입력) → + Access Key·Secret Key. OAuth2 client_credentials 로 토큰을 받는다. + POST https://oauth2.cert.toss.im/token (form: grant_type=client_credentials, client_id=Access Key, + client_secret=Secret Key, scope=toss-shopping-fep:write) + 응답 expires_in 은 약 1년 — 매번 새로 받으면 이용이 제한될 수 있어(문서 안내) 암호화 저장해 두고 재사용, + 401 이면 한 번만 새로 받는다. **키 발급 때 넣은 IP(이 서버 외부 IP)에서만 호출된다.** + API 는 https://shopping-fep.toss.im, 헤더 Authorization: Bearer {token}. HTTP 200 + resultType FAIL 로 오류를 준다. + 호출 제한: 셀러·API 별 읽기 초당 50회(넘으면 TOO_MANY_REQUEST). + +매출 수집 — 주문 내역 조회 GET /api/v3/shopping-fep/orders/v2?startDate=&endDate=&limit=50&nextCursor= + (한 번에 31일까지, 상태 생략 = 전체 상태, 커서 페이지). 줄 = 주문상품(orderProductId), 묶음 = 주문(orderId). + **잠정 규칙(토스쇼핑 파트너스 화면과 대조 전)**: + - SALE = 주문 하나(`toss:{orderId}`), 날짜 = 주문 시각(orderedAt, 한국 날짜 — 토스쇼핑은 주문 = 결제). + - 금액 = 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외. 할인(totalDiscountPrice = 토스쇼핑 할인 + + 토스페이 할인)은 discount_amount 로만 보관. 결제 전(BEFORE_PAYMENT)만 빼고, 결제 뒤 취소·반품도 주문일 매출에 둔다 + (원본 데이터 확인 표에 참고 열로 따로) → 지난 날짜 매출이 나중에 줄지 않는다(네이버와 같은 방식). + - 실데이터로 파트너스 화면 매출과 맞춰 본 뒤 규칙을 확정한다(설정 화면 "쇼핑몰 원본 데이터 확인"). + - 구매자·수령인 이름·연락처·주소·요청사항은 저장하지 않는다. """ from __future__ import annotations -from .base import CredentialField, MarketplaceAdapter +import re +import time +from datetime import date, datetime, timedelta, timezone +from typing import Any, Iterable + +from .base import ( + AdapterContext, + AdapterError, + ApiError, + AuthFailed, + CredentialField, + MarketplaceAdapter, + NotConfigured, + SaleEvent, + TokenExpired, +) +from .naver import field_summary, flatten + +TOKEN_URL = "https://oauth2.cert.toss.im/token" +HOST = "https://shopping-fep.toss.im" +ORDERS_PATH = "/api/v3/shopping-fep/orders/v2" +SCOPE = "toss-shopping-fep:write" +EVENT_PREFIX = "toss:" +PAGE_SIZE = 50 # 문서 최대 50 +WINDOW_DAYS = 31 # 한 번에 31일까지 +MAX_PAGES = 2000 # 한 구간 10만 건 — 무한 반복 방지 +TOKEN_MARGIN_SEC = 3600 # 만료 1시간 전이면 새로 받는다(토큰은 약 1년) +CALL_INTERVAL_SEC = 0.1 # 읽기 초당 50회 제한 — 넉넉히 +RETRY_429 = 3 +PROBE_MAX_DAYS = 31 +KST = timezone(timedelta(hours=9)) + +# 결제 전 주문만 매출에서 뺀다. 결제 뒤 취소·반품은 주문일 매출에 두고 원본 확인 표에 참고로 따로 보인다. +EXCLUDED_STATUS = frozenset({"BEFORE_PAYMENT"}) +CLAIMED_STATUS = frozenset({"CANCELED_PAYMENT", "COMPLETED_RETURN"}) +STATUS_KO = { + "BEFORE_PAYMENT": "결제전", "PAID": "결제완료", "PREPARING_PRODUCT": "상품준비중", "DELIVERING": "배송중", + "DELIVERED": "배송완료", "CONFIRMED_ORDER": "구매확정", "CLAIM_REQUESTED_CANCEL": "취소요청", + "CANCELED_PAYMENT": "결제취소", "CLAIM_REJECTED_CANCEL": "취소거절", "REQUESTED_EXCHANGE": "교환요청", + "ONGOING_EXCHANGE": "교환중", "COMPLETED_EXCHANGE": "교환완료", "CLAIM_REJECTED_EXCHANGE": "교환거절", + "REQUESTED_RETURN": "반품요청", "ONGOING_RETURN": "반품중", "COMPLETED_RETURN": "반품완료", + "CLAIM_REJECTED_RETURN": "반품거절", "CLAIM_COLLECTING": "수거중", "CLAIM_COLLECTED": "수거완료", + "CLAIM_DELIVERING": "재배송중", +} +# 원본 데이터 확인에서 값을 숨기는 항목(개인정보·자유 입력) +PERSONAL_KEYS = frozenset({ + "ordererName", "ordererPhone", "ordererRealPhone", "receiverName", "receiverPhone", "receiverRealPhone", + "address", "detailAddress", "zipCode", "shippingNote", "shippingTrackingNumber", +}) + + +def _won(value: Any) -> int: + try: + return int(round(float(str(value if value is not None else 0).replace(",", "")))) + except ValueError: + return 0 + + +def kst_day(value: Any) -> date | None: + """주문 시각 → 한국 날짜. 시간대가 붙어 있으면(Z, +00:00 …) 한국 시간으로 바꾸고, 없으면 한국 시간으로 본다.""" + s = str(value or "").strip() + if not s: + return None + try: + dt = datetime.fromisoformat(s.replace("Z", "+00:00")) + except ValueError: + m = re.match(r"(\d{4})-(\d{2})-(\d{2})", s) + if not m: + return None + try: + return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) + except ValueError: + return None + if dt.tzinfo is not None: + dt = dt.astimezone(KST) + return dt.date() + + +def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]: + """주문상품 → 주문 하나로 합침(주문일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함). + 금액 = price(판매가 × 수량) 합(할인 전, 배송비 제외). 할인·배송비·취소/반품분은 참고용으로 모은다. + 배송비는 묶음(deliveryFeeGroupId)마다 한 번만 센다.""" + orders: dict[str, dict[str, Any]] = {} + ship_groups: set[str] = set() + for it in items: + oid = str(it.get("orderId") or "") + day = kst_day(it.get("orderedAt")) + status = str(it.get("orderProductStatus") or "") + if not oid or day is None or not (start <= day <= end) or status in EXCLUDED_STATUS: + continue + o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0, + "discount": 0, "names": [], "opt": "", "statuses": []}) + price = _won(it.get("price")) + o["amount"] += price + if status in CLAIMED_STATUS: + o["claimed"] += price + group = str(it.get("deliveryFeeGroupId") or f"{oid}-{it.get('orderProductId')}") + if group not in ship_groups: + ship_groups.add(group) + o["ship"] += _won(it.get("deliveryFee")) + o["qty"] += _won(it.get("quantity")) + o["discount"] += _won(it.get("totalDiscountPrice")) + name = str(it.get("productName") or "") + if name and name not in o["names"]: + o["names"].append(name) + o["opt"] = o["opt"] or str(it.get("optionName") or "") + if status and status not in o["statuses"]: + o["statuses"].append(status) + return orders + + +def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """원본 확인 표 — 항목별 채워진 줄·숫자 합계·예시 값(개인정보·자유 입력 항목은 값 숨김).""" + fields = field_summary([flatten(r) for r in rows]) + for f in fields: + if f["name"] in PERSONAL_KEYS: + f["personal"], f["sample"] = True, "" + if not f["numeric"]: + f["sum"] = None + return fields class TossAdapter(MarketplaceAdapter): code = "toss" name = "토스쇼핑" - auth_type = "api_key" - note = "입력 항목은 연동 단계에서 토스쇼핑 판매자 API 문서로 확정합니다." + auth_type = "oauth" + implemented = True + replace_range = True + event_prefix = EVENT_PREFIX + docs_url = "https://shopping-docs.toss.im/dev" + note = ("토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발에서 발급한 Access Key·Secret Key 를 입력합니다. " + "키 발급 때 이 서버의 외부 IP 를 등록해야 호출됩니다.") + + def __init__(self) -> None: + self._last_call = 0.0 def credential_fields(self) -> list[CredentialField]: + # 키 이름(api_key·api_secret)은 처음 만든 입력칸 그대로 — 이미 저장한 값이 이어진다. return [ - CredentialField("seller_id", "판매자 ID"), - CredentialField("api_key", "API Key", secret=True), - CredentialField("api_secret", "API Secret", secret=True, required=False), + CredentialField("api_key", "Access Key", secret=True, + help="토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발의 Access Key"), + CredentialField("api_secret", "Secret Key", secret=True, + help="같은 화면의 Secret Key"), + CredentialField("access_token", "Access Token", secret=True, required=False, internal=True), + CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True), ] + + # ── 인증 ────────────────────────────────────────────── + def _token(self, ctx: AdapterContext, *, force: bool = False) -> str: + """저장된 토큰이 1시간 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장.""" + if not force: + tok = ctx.credentials.get("access_token") + try: + exp = float(ctx.credentials.get("access_token_expires_at") or 0) + except ValueError: + exp = 0.0 + if tok and exp - time.time() > TOKEN_MARGIN_SEC: + return tok + return self._issue_token(ctx) + + def _issue_token(self, ctx: AdapterContext) -> str: + import httpx # 지연 import + + access_key = ctx.credentials.get("api_key").strip() + secret_key = ctx.credentials.get("api_secret").strip() + if not access_key or not secret_key: + raise NotConfigured("Access Key 와 Secret Key 를 입력하세요.") + form = {"grant_type": "client_credentials", "client_id": access_key, "client_secret": secret_key, + "scope": SCOPE} + try: + res = httpx.post(TOKEN_URL, data=form, timeout=ctx.timeout_sec, + headers={"Accept": "application/json; charset=UTF-8"}) + except httpx.HTTPError as exc: + raise ApiError(f"토스 인증 서버 연결 실패: {type(exc).__name__}") from None + body = self._json(res) + if res.status_code >= 400 or not body.get("access_token"): + msg = self._err_text(body, res) + if res.status_code in (400, 401, 403): + raise AuthFailed(f"토스쇼핑 토큰 발급 실패({res.status_code}): {msg}. Access Key·Secret Key 와 " + "키 발급 때 등록한 IP(이 서버 외부 IP)를 확인하세요.") + raise ApiError(f"토스쇼핑 토큰 발급 오류({res.status_code}): {msg}") + tok = str(body["access_token"]) + expires_in = _won(body.get("expires_in")) or 24 * 3600 + ctx.credentials.set("access_token", tok) + ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in)) + return tok + + def authenticate(self, ctx: AdapterContext) -> None: + super().authenticate(ctx) + self._token(ctx) + + def refresh_token(self, ctx: AdapterContext) -> None: + self._token(ctx, force=True) + + # ── 호출 ────────────────────────────────────────────── + @staticmethod + def _json(res: Any) -> dict[str, Any]: + try: + body = res.json() + except ValueError: + return {} + return body if isinstance(body, dict) else {"data": body} + + @staticmethod + def _err_text(body: dict[str, Any], res: Any) -> str: + err = body.get("error") + if isinstance(err, dict): + parts = [str(err.get(k)) for k in ("errorCode", "errorType", "reason", "message") if err.get(k)] + else: + parts = [str(body.get(k)) for k in ("error", "error_description", "code", "message") if body.get(k)] + return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음" + + def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]: + """GET — 호출 간격 유지, 429·TOO_MANY_REQUEST 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더. + 성공이면 success 내용을 돌려준다(토스쇼핑은 HTTP 200 + resultType FAIL 로도 오류를 준다).""" + import httpx # 지연 import + + retried_auth = False + for attempt in range(RETRY_429 + 1): + ctx.progress.check() # [업데이트 취소]면 여기서 멈춤 + wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call) + if wait > 0: + time.sleep(wait) + headers = {"Authorization": f"Bearer {self._token(ctx)}", "Accept": "application/json"} + try: + res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec) + except httpx.HTTPError as exc: + raise ApiError(f"토스쇼핑 API 연결 실패: {type(exc).__name__}") from None + finally: + self._last_call = time.monotonic() + body = self._json(res) + err = body.get("error") if isinstance(body.get("error"), dict) else {} + limited = res.status_code == 429 or "TOO_MANY" in str(err.get("errorCode") or err.get("errorType") or "") + if limited and attempt < RETRY_429: + time.sleep(1.0 * (2 ** attempt)) + continue + if res.status_code == 401 and not retried_auth: + retried_auth = True + self._token(ctx, force=True) + continue + if res.status_code == 401: + raise TokenExpired(f"토스쇼핑 인증 만료·거부(401): {self._err_text(body, res)}") + if res.status_code == 403: + raise AuthFailed(f"토스쇼핑 권한 거부(403): {self._err_text(body, res)}. 키 발급 때 등록한 IP" + "(이 서버 외부 IP)를 확인하세요.") + if limited: + raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.") + if res.status_code >= 400: + raise ApiError(f"토스쇼핑 API 오류({res.status_code}): {self._err_text(body, res)}") + if body.get("resultType") == "FAIL": + raise ApiError(f"토스쇼핑 API 오류: {self._err_text(body, res)}") + success = body.get("success") + return success if isinstance(success, dict) else {} + raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.") + + def _window_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]: + """조회 기간 [a, b](31일 이하)의 주문상품 전체 — 모든 상태, 커서로 끝까지.""" + params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE} + out: list[dict[str, Any]] = [] + cursor = None + for _ in range(MAX_PAGES): + body = self._get(ctx, ORDERS_PATH, {**params, **({"nextCursor": cursor} if cursor else {})}) + rows = [r for r in body.get("results") or [] if isinstance(r, dict)] + out.extend(rows) + cursor = body.get("nextCursor") + if not cursor or not rows: + break + return out + + def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]: + windows = [] + a = start + while a <= end: + b = min(end, a + timedelta(days=WINDOW_DAYS - 1)) + windows.append((a, b)) + a = b + timedelta(days=1) + ctx.progress.plan(len(windows), "31일 구간") + for a, b in windows: + rows = self._window_items(ctx, a, b) + ctx.progress.step(items=len(rows)) + yield from rows + + # ── 수집 ────────────────────────────────────────────── + def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]: + yield from group_orders(self._items(ctx, start, end), start, end).values() + + def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]: + oid, day = str(o.get("orderId") or ""), o.get("_day") + if not oid or day is None: + return [] + names = o.get("names") or [] + name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else "" + statuses = [STATUS_KO.get(s, s) for s in o.get("statuses") or []] + return [SaleEvent( + event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}", external_order_id=oid, + order_date=day, payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)), + product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0), + discount_amount=max(0, int(o.get("discount") or 0)), order_status="/".join(statuses)[:50], + )] + + def test_connection(self, ctx: AdapterContext) -> str: + from app.timezone import today_kst # noqa: WPS433 + + # 입력한 새 값으로 시험할 수 있으니 저장된 토큰을 쓰지 않고 항상 새로 받는다. + super().authenticate(ctx) + self._token(ctx, force=True) + today = today_kst() + body = self._get(ctx, ORDERS_PATH, {"startDate": today.isoformat(), "endDate": today.isoformat(), "limit": 1}) + n = len(body.get("results") or []) + more = " 이상" if body.get("nextCursor") else "" + return f"토스쇼핑 API 연결 정상(토큰 발급·주문 조회 확인, 오늘 주문상품 {n}건{more})." + + # ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ───────── + def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]: + """기간(최대 31일)의 주문상품을 실제로 불러 항목별 합계·상태별 합계·날짜별 현재 규칙 매출을 돌려준다. + 토스쇼핑 파트너스 화면 매출과 어느 항목이 맞는지 실데이터로 확정하는 용도. 개인정보 항목은 값 없이 이름만.""" + self.authenticate(ctx) + to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1)) + try: + items = list(self._items(ctx, day, to)) + except AdapterError as exc: + return {"date": day.isoformat(), "to": to.isoformat(), "probes": [ + {"key": "orders", "label": "주문 내역", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]} + by_status: dict[str, list[dict[str, Any]]] = {} + for it in items: + by_status.setdefault(str(it.get("orderProductStatus") or "?"), []).append(it) + probes = [{"key": "orders", "label": "주문 내역(전체 상태, 주문상품 단위)", "path": ORDERS_PATH, + "ok": True, "count": len(items), "fields": summary(items)}] + for st, rows in sorted(by_status.items()): + probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})" + + (" — 매출 제외(결제 전)" if st in EXCLUDED_STATUS else + " — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), + "path": "orderProductStatus", "ok": True, "count": len(rows), + "fields": [f for f in summary(rows) if f["sum"] is not None]}) + days = [] + orders = group_orders(items, day, to) + d = day + while d <= to: + day_orders = [o for o in orders.values() if o["_day"] == d] + days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sum(o["amount"] for o in day_orders), + "claimed": sum(o["claimed"] for o in day_orders), "ship": sum(o["ship"] for o in day_orders)}) + d += timedelta(days=1) + return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days, + "rule": "주문일(orderedAt, 한국 날짜) 기준 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외, " + "결제 뒤 취소·반품분 포함, 결제 전 제외. 잠정 규칙 — 토스쇼핑 파트너스 매출과 비교해 확정"} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 464ea99..71102cf 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -239,4 +239,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 c940288..f380e4f 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -123,12 +123,14 @@ 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.
· 네이버: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.
· 11번가: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).
- · GS샵: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.

+ · GS샵: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.
+ · 토스쇼핑: 주문 내역(주문일 기준, 상태별 합계 포함)과 날짜별 "현재 규칙 매출" — 토스쇼핑 파트너스 매출과 비교해 주세요.

~ @@ -177,4 +179,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 0bcdc9a..febd679 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -379,6 +379,183 @@ def test_sync_isolation_redaction_and_dedupe(): assert r3["skipped"] + +def _toss_item(order_id, op_id, ordered_at, price, *, status="PAID", qty=1, dc=0, ship=0, group=None, name="밀폐용기"): + """토스쇼핑 주문 내역 조회 results[] 한 줄(주문상품) — 개인정보 항목 포함(저장 안 되는지 확인용).""" + return {"orderId": order_id, "orderProductId": op_id, "orderedAt": ordered_at, "orderProductStatus": status, + "productName": name, "optionName": "3개입", "quantity": qty, "price": price, "originPrice": price, + "totalDiscountPrice": dc, "tossShoppingDiscount": dc, "tossPayDiscount": 0, "tossPayPoint": 0, + "deliveryFee": ship, "deliveryFeeGroupId": group, + "ordererName": "홍길동", "ordererPhone": "010-1234-5678", "receiverName": "홍길동", + "receiverPhone": "010-1234-5678", "address": "서울시 어딘가", "detailAddress": "101호", "zipCode": "01234", + "shippingNote": "문 앞에 두세요 010-9999-8888"} + + +class _TossCreds(dict): + def get(self, k, default=""): + return dict.get(self, k, default) + + def has(self, k): + return bool(dict.get(self, k)) + + def set(self, k, v): + self[k] = v + + +def test_toss_token_and_connection(): + """토스쇼핑: Access Key·Secret Key → OAuth2 토큰(form, scope 고정) → Bearer 로 주문 내역 조회. + HTTP 200 + resultType FAIL 도 오류, 401 이면 토큰 한 번 새로 받기. 키·토큰은 오류 문구에 없음.""" + import httpx + + from app.modules.performance.adapters import toss as ts + from app.modules.performance.adapters.base import AdapterContext, AdapterError + + ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="ACCESS-KEY-1", api_secret="SECRET-KEY-1")) + seen = {"posts": [], "gets": []} + + def post(url, data=None, timeout=None, headers=None): + seen["posts"].append((url, dict(data))) + return httpx.Response(200, json={"access_token": f"TOKEN-{len(seen['posts'])}", "expires_in": 31535999, + "token_type": "Bearer", "scope": "toss-shopping-fep:write"}) + + def get(url, params=None, headers=None, timeout=None): + seen["gets"].append((url, dict(params), headers["Authorization"])) + return httpx.Response(200, json={"resultType": "SUCCESS", "success": { + "results": [_toss_item(1, 11, "2026-09-30T10:00:00", 12000)], "nextCursor": "c2"}}) + + orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC) + httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0 + try: + msg = ts.TossAdapter().test_connection(ctx) + assert "연결 정상" in msg and "1건 이상" in msg + url, form = seen["posts"][0] + assert url == "https://oauth2.cert.toss.im/token" + assert form == {"grant_type": "client_credentials", "client_id": "ACCESS-KEY-1", + "client_secret": "SECRET-KEY-1", "scope": "toss-shopping-fep:write"} + gurl, params, auth = seen["gets"][0] + assert gurl == "https://shopping-fep.toss.im/api/v3/shopping-fep/orders/v2" and auth == "Bearer TOKEN-1" + assert params["startDate"] == params["endDate"] and params["limit"] == 1 + assert ctx.credentials["access_token"] == "TOKEN-1" and int(ctx.credentials["access_token_expires_at"]) > 0 + # 저장된 토큰은 다시 쓴다(매번 발급하지 않음) — 401 이면 한 번만 새로 받는다 + n_posts = len(seen["posts"]) + statuses = iter([401, 200]) + httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response( + next(statuses), json={"resultType": "SUCCESS", "success": {"results": [], "nextCursor": None}}) + assert ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1)) == [] + assert len(seen["posts"]) == n_posts + 1 and ctx.credentials["access_token"] == f"TOKEN-{n_posts + 1}" + # HTTP 200 + resultType FAIL → API 오류 + httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response( + 200, json={"resultType": "FAIL", "error": {"errorCode": "INVALID_DATE_RANGE", "reason": "조회 기간 초과"}}) + try: + ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1)) + except AdapterError as exc: + assert exc.status == "api_error" and "INVALID_DATE_RANGE" in exc.message + else: + raise AssertionError("API 오류여야 합니다") + # 토큰 발급 거부 → 인증 실패(키는 문구에 없음) + httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response( + 401, json={"error": "invalid_client", "error_description": "client authentication failed"}) + try: + ts.TossAdapter().test_connection(ctx) + except AuthFailed as exc: + assert "invalid_client" in exc.message and "SECRET-KEY-1" not in exc.message + assert "ACCESS-KEY-1" not in exc.message + else: + raise AssertionError("인증 실패여야 합니다") + # 주문 조회 403(IP 미등록 등) → 인증 실패 + IP 안내, 토큰은 문구에 없음 + httpx.post = post + httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response( + 403, json={"resultType": "FAIL", "error": {"errorCode": "FORBIDDEN", "reason": "허용되지 않은 IP"}}) + try: + ts.TossAdapter().test_connection(ctx) + except AuthFailed as exc: + assert "허용되지 않은 IP" in exc.message and "TOKEN-" not in exc.message + else: + raise AssertionError("권한 거부여야 합니다") + finally: + httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig + + +def test_toss_collect_sales(): + """토스쇼핑 매출(잠정) = 주문 단위, 주문일(한국 날짜) 기준, 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외. + 결제 뒤 취소·반품도 포함, 결제 전만 뺀다. 31일 구간으로 나눠 부르고 커서로 끝까지 받는다. 구매자 정보는 저장 안 함.""" + import httpx + + from app.modules.performance.adapters import toss as ts + + pages = { + ("2026-08-01", None): ([_toss_item(1, 11, "2026-08-31T23:30:00+09:00", 20000, qty=2, dc=1000, ship=3000, group=7), + _toss_item(1, 12, "2026-08-31T23:30:00+09:00", 5000, ship=3000, group=7, name="뚜껑")], "p2"), + ("2026-08-01", "p2"): ([_toss_item(2, 21, "2026-08-31T16:00:00Z", 9900, status="CANCELED_PAYMENT"), # 9/1 01:00 KST + _toss_item(3, 31, "2026-08-31T09:00:00", 4000, status="BEFORE_PAYMENT")], None), + ("2026-09-01", None): ([_toss_item(4, 41, "2026-09-01T10:00:00", 15000, status="COMPLETED_RETURN")], None), + } + calls = [] + + def get(url, params=None, headers=None, timeout=None): + key = (params["startDate"], params.get("nextCursor")) + calls.append((params["startDate"], params["endDate"], params.get("nextCursor"))) + rows, cur = pages.get(key, ([], None)) + return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": cur}}) + + def post(url, data=None, timeout=None, headers=None): + return httpx.Response(200, json={"access_token": "TOKEN-T", "expires_in": 31535999}) + + st = FakeStore() + creds = CredentialService(st, lambda: ring()) + creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"}) + orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC) + httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0 + try: + r = SyncService(st, creds).sync_marketplace("toss", date(2026, 8, 1), date(2026, 9, 2)) + finally: + httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig + assert r["ok"], r + assert calls == [("2026-08-01", "2026-08-31", None), ("2026-08-01", "2026-08-31", "p2"), + ("2026-09-01", "2026-09-02", None)] # 31일 구간 + 커서 + ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "toss"} + assert set(ev_) == {"toss:1", "toss:2", "toss:4"} # 결제 전(3)만 제외 + assert ev_["toss:1"]["amount"] == 25000 and ev_["toss:1"]["discount_amount"] == 1000 # 할인 전·배송비 제외 + assert ev_["toss:1"]["quantity"] == 3 and ev_["toss:1"]["product_name"] == "밀폐용기 외 1건" + assert ev_["toss:1"]["sales_date"] == date(2026, 8, 31) + assert ev_["toss:2"]["amount"] == 9900 and ev_["toss:2"]["sales_date"] == date(2026, 9, 1) # UTC → 한국 날짜 + assert ev_["toss:4"]["amount"] == 15000 and ev_["toss:4"]["order_status"] == "반품완료" + assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events) + + +def test_toss_reconcile_hides_personal(): + import time as _t + + import httpx + + from app.modules.performance.adapters import toss as ts + from app.modules.performance.adapters.base import AdapterContext + + ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T", + access_token_expires_at=str(int(_t.time()) + 99999))) + rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1), + _toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)] + orig = (httpx.get, ts.CALL_INTERVAL_SEC) + httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response( + 200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": None}}) + ts.CALL_INTERVAL_SEC = 0 + try: + rec = ts.TossAdapter().reconcile(ctx, date(2026, 9, 9), to=date(2026, 9, 10)) + finally: + httpx.get, ts.CALL_INTERVAL_SEC = orig + allp = rec["probes"][0] + assert allp["ok"] and allp["count"] == 2 + f = {x["name"]: x for x in allp["fields"]} + assert f["price"]["sum"] == 29900 + for k in ("ordererName", "ordererPhone", "address", "zipCode", "shippingNote"): + assert f[k]["personal"] and f[k]["sample"] == "", k + assert not f["productName"]["personal"] and f["productName"]["sample"] == "밀폐용기" + assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec) and "010-9999-8888" not in repr(rec) + assert rec["days"] == [{"date": "2026-09-09", "orders": 2, "amount": 29900, "claimed": 9900, "ship": 6000}, + {"date": "2026-09-10", "orders": 0, "amount": 0, "claimed": 0, "ship": 0}] + assert any("결제 뒤 취소·반품(매출 포함)" in p["label"] for p in rec["probes"]) + + def test_not_implemented_and_mock(): st = FakeStore() creds = CredentialService(st, lambda: ring()) diff --git a/app/static/performance.js b/app/static/performance.js index 857d22e..bccac22 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -960,7 +960,7 @@ } }); - // ── 쇼핑몰 원본 데이터 확인(네이버·11번가) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ── + // ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ── const probe = document.getElementById("perf-probe"); if (probe) probe.addEventListener("click", async function () { const day = document.getElementById("perf-probe-date").value; @@ -970,7 +970,7 @@ const codeSel = document.getElementById("perf-probe-code"); const code = codeSel ? codeSel.value : "elevenst"; const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)", - gsshop: "GS샵에서 불러오는 중… (10일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)"; + gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)"; out.innerHTML = '

' + loading + "

"; try { const to = document.getElementById("perf-probe-to").value || day; @@ -993,7 +993,7 @@ (f.sum == null ? "" : fmt(f.sum)) + "" + (f.personal ? '개인정보(숨김)' : esc(f.sample)) + ""; }).join("") + ""; }).join(""); - // 날짜별 현재 규칙 매출(네이버) — 쇼핑몰 관리자 화면 매출과 나란히 비교 + // 날짜별 현재 규칙 매출(네이버·토스쇼핑) — 쇼핑몰 관리자 화면 매출과 나란히 비교 const days = (r.days || []).length ? '

날짜별 현재 규칙 매출

' + (r.rule ? '

규칙: ' + esc(r.rule) + "

" : "") + '' + diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 2a14f8c..a37a3fd 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -29,7 +29,7 @@ 오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중). -**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은 +**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑 = **구현됨**(토스쇼핑은 매출 규칙 잠정), 나머지 5개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은 **연동 단계에서 공식 API 문서로 확정**한다. ### 카페24 (`adapters/cafe24.py`, 구현됨) @@ -147,6 +147,29 @@ **GS샵 수수료율은 0%**. 배송비 제외, `ordType` 이 SALE 이 아니면 RETURN 음수. `replace_range`. 원본 데이터 확인에 날짜별 현재 규칙 매출·취소/반품·배송비(참고). +### 토스쇼핑 (`adapters/toss.py`, 구현됨 — 매출 규칙 잠정) + +- 문서: `https://shopping-docs.toss.im/dev` (공개, 전체 목록 `llms.txt`, 쪽 주소 뒤 `.md` = 원문). 문의는 문서의 디스코드. +- 인증: 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > **자체 개발** → [키 발급](**호출 IP 입력 — 운영 서버 외부 IP**, 등록된 + IP 만 호출 가능) → Access Key·Secret Key. `POST https://oauth2.cert.toss.im/token`(form: `grant_type=client_credentials`· + `client_id`=Access Key·`client_secret`=Secret Key·`scope=toss-shopping-fep:write`). 토큰 `expires_in` 약 1년 — 문서가 매번 발급하면 + 이용이 제한될 수 있다고 해서 `access_token`·`access_token_expires_at`(internal, 암호화)으로 저장해 재사용, 만료 1시간 전·401 이면 새로. + [연결 테스트]는 입력값으로 시험하므로 항상 새 토큰. 입력칸 키는 처음 만든 `api_key`(Access Key)·`api_secret`(Secret Key) 그대로 + (라벨만 변경 — 예전 "판매자 ID" 칸은 없앰). +- API: `https://shopping-fep.toss.im`, `Authorization: Bearer {token}`. 오류가 **HTTP 200 + `resultType: "FAIL"`**(`error.errorCode`· + `reason`)로도 온다. 읽기 초당 50회(넘으면 `TOO_MANY_REQUEST`) → 호출 간격 0.1초, 제한이면 1·2·4초 쉬고 다시. +- 수집: 주문 내역 조회 `GET /api/v3/shopping-fep/orders/v2?startDate&endDate&limit=50&nextCursor` — 한 번에 **31일**, 상태 생략 = + 전체, 커서(`nextCursor` null = 끝). 줄 = 주문상품(`orderProductId`), 주문 = `orderId`. 금액 항목: `price`(판매가 × 수량)· + `originPrice`(정상가 × 수량)·`totalDiscountPrice`(= `tossShoppingDiscount` + `tossPayDiscount`)·`tossPayPoint`·`deliveryFee` + (묶음 `deliveryFeeGroupId` 마다). 결제일 필드는 따로 없고 `orderedAt`(주문 = 결제) · `canceledAt` · `confirmedAt`. +- **매출 규칙(잠정, 파트너스 화면과 대조 전)**: SALE = 주문 하나(`toss:{orderId}`), 날짜 = `orderedAt` 의 한국 날짜, 금액 = + `price` 합(할인 전, 배송비 제외), 할인은 `discount_amount` 로만. 결제 전(`BEFORE_PAYMENT`)만 빼고 결제 뒤 취소·반품도 주문일 매출에 + 둔다(네이버와 같은 방식 → 지난 날짜 매출이 나중에 줄지 않음). `replace_range`. 개인정보(주문자·수령인·주소·요청사항·송장)는 저장 안 함. +- 정산 API `GET /settlement-steps`(`dateCondition` PAYOUT_DATE·PAYOUT_BASE_DATE·TRANSACTION_DATE…, 31일, `stepType` PAY|REFUND, + 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`)은 구매확정·취소된 건만 나온다 — 규칙 확정 때 필요하면 쓴다. +- 확정 방법: 설정 화면 "쇼핑몰 원본 데이터 확인" → 토스쇼핑, 매출이 있던 기간 → 날짜별 현재 규칙 매출·상태별 항목 합계를 토스쇼핑 + 파트너스 매출 화면과 비교해 맞는 항목(`price` / `price − totalDiscountPrice` / 취소 제외 여부)으로 규칙을 고친다. + ### 연동 단계 체크리스트(쇼핑몰마다) - 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
날짜주문 수매출