Merge branch 'feat/perf-coupang-sales'
This commit is contained in:
@@ -8,12 +8,23 @@
|
||||
OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
|
||||
· 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
|
||||
· 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
|
||||
연결 테스트는 오늘 결제완료 발주서 1건을 실제로 조회해 키·IP 가 통하는지 확인한다.
|
||||
|
||||
매출 수집(fetch_orders)은 아직 — 어느 WING 화면과 맞출지 정한 뒤 구현한다.
|
||||
· 발주서 목록(v5 ordersheets, 주문일 기준, 상태별 조회) + 반품/취소 요청(v6 returnRequests, 접수일 기준, 금액 없음)
|
||||
· 매출내역(v1 revenue-history)은 매출인식일(구매확정 또는 배송완료+7일) 기준이라 결제일 기준 일별 매출과 다르다.
|
||||
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 필요 시 별도 연계.
|
||||
매출 수집 — 맞출 화면: WING → 비즈니스 인사이트 → **판매분석**(판매자배송 + 로켓그로스, 날짜 선택) 의 "매출(원)"
|
||||
(2026-10-12 사용자 지정). 판매분석 자체를 주는 Open API 는 없다(2026-10-12 developers.coupang.com API 목록 확인) —
|
||||
그래서 주문 API 두 개를 결제일(한국 시간)로 합친다:
|
||||
- 판매자배송: 발주서 목록(일단위 페이징) GET /v2/providers/openapi/apis/api/v5/vendors/{vendorId}/ordersheets
|
||||
?createdAtFrom=yyyy-mm-dd+09:00&createdAtTo=…&status=…&maxPerPage=50&nextToken=
|
||||
— 주문일 기준·한 번에 31일까지·상태(ACCEPT·INSTRUCT·DEPARTURE·DELIVERING·FINAL_DELIVERY·NONE_TRACKING)마다 따로.
|
||||
결제일(paidAt)로 다시 거른다(주문일 하루 앞부터 조회). 줄 금액 = orderPrice(판매가 × 수량, 쿠폰 할인 전).
|
||||
완료된 반품·결제 전 취소된 발주서는 이 목록에 없다(쿠팡 안내).
|
||||
- 로켓그로스: 주문 목록 GET /v2/providers/rg_open_api/apis/api/v1/vendors/{vendorId}/rg/orders
|
||||
?paidDateFrom=yyyymmdd&paidDateTo=yyyymmdd&nextToken= — 결제일 기준·30일까지·분당 50회.
|
||||
줄 금액 = unitSalesPrice × salesQuantity. 쿠팡 안내상 **출고된 주문만** 나온다(오늘 주문은 출고 뒤에 잡힐 수 있음).
|
||||
- SALE = 주문 하나(판매자배송 `coupang:{orderId}`, 로켓그로스 `coupang:rg:{orderId}`), 날짜 = 결제일.
|
||||
결제 뒤 취소된 줄(canceled·cancelCount)도 결제일 매출에 둔다(지난 날짜가 나중에 줄지 않게) — 금액은 참고로 따로.
|
||||
판매분석 "매출" 의 정확한 정의(할인 전·후, 취소 포함 여부)는 공개 문서가 없어 **설정 → 쇼핑몰 원본 데이터 확인**
|
||||
(reconcile)의 날짜별 후보 금액을 WING 숫자와 비교해 확정한다. 구매자 이름·연락처·주소는 저장·표시하지 않는다.
|
||||
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 여기에 넣지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,19 +32,42 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
from typing import Any
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any, Iterable
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
AdapterError,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
CredentialField,
|
||||
MarketplaceAdapter,
|
||||
NotConfigured,
|
||||
SaleEvent,
|
||||
)
|
||||
from .naver import field_summary, flatten
|
||||
|
||||
HOST = "https://api-gateway.coupang.com"
|
||||
ORDERS_PATH = "/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets"
|
||||
RG_ORDERS_PATH = "/v2/providers/rg_open_api/apis/api/v1/vendors/{vendor}/rg/orders"
|
||||
EVENT_PREFIX = "coupang:"
|
||||
RG_PREFIX = "coupang:rg:"
|
||||
STATUSES = ("ACCEPT", "INSTRUCT", "DEPARTURE", "DELIVERING", "FINAL_DELIVERY", "NONE_TRACKING")
|
||||
STATUS_KO = {"ACCEPT": "결제완료", "INSTRUCT": "상품준비중", "DEPARTURE": "배송지시", "DELIVERING": "배송중",
|
||||
"FINAL_DELIVERY": "배송완료", "NONE_TRACKING": "업체직송", "RG": "로켓그로스"}
|
||||
ORDER_SPAN_DAYS = 31 # 발주서 목록 한 번에 조회할 수 있는 기간(시작·끝 포함)
|
||||
RG_SPAN_DAYS = 30 # 로켓그로스 주문 목록 한 번에 조회할 수 있는 기간
|
||||
PAGE_SIZE = 50
|
||||
MAX_PAGES = 400 # 한 조회 2만 건 — 무한 반복 방지
|
||||
CALL_INTERVAL_SEC = 0.25 # 발주서 목록 호출 간격
|
||||
RG_CALL_INTERVAL_SEC = 1.25 # 로켓그로스 분당 50회 제한
|
||||
RETRY_429 = 3
|
||||
PROBE_MAX_DAYS = 31
|
||||
KST_OFFSET = timedelta(hours=9)
|
||||
# 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목)
|
||||
PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"})
|
||||
PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"})
|
||||
|
||||
|
||||
def signed_date(now: float | None = None) -> str:
|
||||
@@ -54,14 +88,163 @@ def build_query(params: dict[str, Any]) -> str:
|
||||
return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
"""금액 → 원 정수. 쿠팡 Money({"units": 15000, "nanos": 0})·숫자·문자열("27800") 모두."""
|
||||
if isinstance(value, dict):
|
||||
return _won(value.get("units")) + int(round((_num(value.get("nanos")) or 0) / 1e9))
|
||||
n = _num(value)
|
||||
return int(round(n)) if n is not None else 0
|
||||
|
||||
|
||||
def _num(value: Any) -> float | None:
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
try:
|
||||
return float(str(value).replace(",", "").strip() or 0)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _kst_day(value: Any) -> date | None:
|
||||
"""결제 시각 → 한국 날짜. ISO 문자열("2025-08-01T10:06:12+09:00", 시간대 없으면 한국 시간) 또는
|
||||
밀리초 타임스탬프(1746093162000, 로켓그로스)."""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
n = _num(value) if not isinstance(value, str) or value.strip().isdigit() else None
|
||||
if n is not None:
|
||||
secs = n / 1000 if n > 1e11 else n
|
||||
return (datetime.fromtimestamp(secs, tz=timezone.utc) + KST_OFFSET).date()
|
||||
s = str(value).strip().replace("Z", "+00:00")
|
||||
try:
|
||||
dt = datetime.fromisoformat(s if "T" in s or " " in s else s[:10])
|
||||
except ValueError:
|
||||
try:
|
||||
return date.fromisoformat(s[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
dt = (dt - dt.utcoffset()).replace(tzinfo=None) + KST_OFFSET # type: ignore[operator]
|
||||
return dt.date()
|
||||
|
||||
|
||||
def spans(start: date, end: date, days: int) -> list[tuple[date, date]]:
|
||||
"""[start, end] 를 days 일(시작·끝 포함) 이하 구간으로 자른다."""
|
||||
out, d = [], start
|
||||
while d <= end:
|
||||
e = min(end, d + timedelta(days=days - 1))
|
||||
out.append((d, e))
|
||||
d = e + timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def safe_order(o: dict[str, Any]) -> dict[str, Any]:
|
||||
"""개인정보 항목을 뺀 발주서(원본 확인·저장용)."""
|
||||
out = {k: v for k, v in o.items() if k not in PERSONAL_KEYS}
|
||||
if isinstance(out.get("orderItems"), list):
|
||||
out["orderItems"] = [{k: v for k, v in it.items() if k not in PERSONAL_ITEM_KEYS}
|
||||
for it in out["orderItems"] if isinstance(it, dict)]
|
||||
return out
|
||||
|
||||
|
||||
def line_records(o: dict[str, Any]) -> list[dict[str, str]]:
|
||||
"""발주서 하나 → 줄(orderItems)마다 평평한 기록 하나 — 원본 확인 표의 항목별 합계용."""
|
||||
base = flatten({k: v for k, v in safe_order(o).items() if k != "orderItems"})
|
||||
items = safe_order(o).get("orderItems") or [{}]
|
||||
return [{**base, **flatten(it, "orderItems")} for it in items]
|
||||
|
||||
|
||||
def seller_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""판매자배송 발주서 → 결제일이 [start, end] 인 줄. 같은 발주서가 두 번 와도(상태 사이 이동) 한 번만."""
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
out: list[dict[str, Any]] = []
|
||||
for o in orders:
|
||||
oid = str(o.get("orderId") or "")
|
||||
day = _kst_day(o.get("paidAt") or o.get("orderedAt"))
|
||||
if not oid or day is None or not (start <= day <= end):
|
||||
continue
|
||||
box = str(o.get("shipmentBoxId") or "")
|
||||
first = len(out)
|
||||
for it in o.get("orderItems") or []:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
key = (oid, box, str(it.get("vendorItemId") or ""), str(it.get("sequenceNo") or ""))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
qty = _won(it.get("shippingCount"))
|
||||
price = _won(it.get("orderPrice")) or _won(it.get("salesPrice")) * qty
|
||||
cancel_qty = _won(it.get("cancelCount")) + _won(it.get("holdCountForCancel"))
|
||||
canceled = bool(it.get("canceled")) or (qty > 0 and cancel_qty >= qty)
|
||||
cancel_amt = price if canceled else (_won(it.get("salesPrice")) * min(cancel_qty, qty) if cancel_qty else 0)
|
||||
out.append({
|
||||
"orderId": oid, "_day": day, "order_day": _kst_day(o.get("orderedAt")), "status": str(o.get("status") or ""),
|
||||
"amount": price, "discount": _won(it.get("discountPrice")), "canceled": cancel_amt, "qty": qty,
|
||||
"name": str(it.get("sellerProductName") or it.get("vendorItemName") or ""),
|
||||
"opt": str(it.get("sellerProductItemName") or ""), "ship": 0,
|
||||
})
|
||||
# 배송비는 발주서(묶음 배송)마다 한 번 — 그 발주서의 첫 새 줄에(참고용, 매출 제외). 같은 발주서가 또 오면 새 줄이 없어 안 더함
|
||||
if len(out) > first:
|
||||
out[first]["ship"] += _won(o.get("shippingPrice")) + _won(o.get("remotePrice"))
|
||||
return out
|
||||
|
||||
|
||||
def rg_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""로켓그로스 주문 → 결제일이 [start, end] 인 줄. 금액 = 단가 × 수량."""
|
||||
seen: set[tuple[str, str, int]] = set()
|
||||
out: list[dict[str, Any]] = []
|
||||
for o in orders:
|
||||
oid = str(o.get("orderId") or "")
|
||||
day = _kst_day(o.get("paidAt"))
|
||||
if not oid or day is None or not (start <= day <= end):
|
||||
continue
|
||||
for i, it in enumerate(o.get("orderItems") or []):
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
key = (oid, str(it.get("vendorItemId") or ""), i)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
qty = _won(it.get("salesQuantity"))
|
||||
out.append({"orderId": oid, "_day": day, "order_day": day, "status": "RG",
|
||||
"amount": _won(it.get("unitSalesPrice")) * qty, "discount": 0, "canceled": 0, "qty": qty,
|
||||
"name": str(it.get("productName") or ""), "opt": "", "ship": 0})
|
||||
return out
|
||||
|
||||
|
||||
def group_lines(lines: Iterable[dict[str, Any]], prefix: str) -> dict[str, dict[str, Any]]:
|
||||
"""줄 → 주문 하나(외부 사건 ID 기준)."""
|
||||
orders: dict[str, dict[str, Any]] = {}
|
||||
for ln in lines:
|
||||
eid = f"{prefix}{ln['orderId']}"
|
||||
o = orders.setdefault(eid, {"event_id": eid, "orderId": ln["orderId"], "_day": ln["_day"],
|
||||
"order_day": ln.get("order_day"), "amount": 0, "discount": 0, "canceled": 0,
|
||||
"ship": 0, "qty": 0, "names": [], "opt": "", "statuses": []})
|
||||
for k in ("amount", "discount", "canceled", "ship", "qty"):
|
||||
o[k] += int(ln.get(k) or 0)
|
||||
if ln["name"] and ln["name"] not in o["names"]:
|
||||
o["names"].append(ln["name"])
|
||||
o["opt"] = o["opt"] or ln.get("opt") or ""
|
||||
if ln["status"] and ln["status"] not in o["statuses"]:
|
||||
o["statuses"].append(ln["status"])
|
||||
return orders
|
||||
|
||||
|
||||
class CoupangAdapter(MarketplaceAdapter):
|
||||
code = "coupang"
|
||||
name = "쿠팡"
|
||||
auth_type = "api_key"
|
||||
docs_url = "https://developers.coupangcorp.com/"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
docs_url = "https://developers.coupang.com/"
|
||||
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
|
||||
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
|
||||
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
|
||||
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인). 매출은 판매자배송 + 로켓그로스 주문을 "
|
||||
"결제일로 합칩니다(WING 비즈니스 인사이트 → 판매분석 '매출'과 비교).")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last_call = 0.0
|
||||
self._last_rg_call = 0.0
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
@@ -71,42 +254,206 @@ class CoupangAdapter(MarketplaceAdapter):
|
||||
]
|
||||
|
||||
# ── 호출 ──────────────────────────────────────────────
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
def _vendor(self, ctx: AdapterContext) -> str:
|
||||
v = ctx.credentials.get("vendor_id").strip()
|
||||
if not v:
|
||||
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||
return v
|
||||
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> dict[str, Any]:
|
||||
"""GET — 호출 간격 유지(로켓그로스는 분당 50회), 429 는 잠깐 쉬고 다시."""
|
||||
import httpx # 지연 import
|
||||
|
||||
access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
|
||||
if not (access and secret):
|
||||
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||
query = build_query(params)
|
||||
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
||||
"Content-Type": "application/json;charset=UTF-8"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
body = {}
|
||||
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()
|
||||
if res.status_code in (401, 403):
|
||||
raise AuthFailed(
|
||||
f"쿠팡 인증 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
||||
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
||||
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
||||
if res.status_code >= 400:
|
||||
raise ApiError(f"쿠팡 API 오류({res.status_code}): {msg}")
|
||||
return body
|
||||
what = "로켓그로스 주문" if rg else "발주서"
|
||||
for attempt in range(RETRY_429 + 1):
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
gap = RG_CALL_INTERVAL_SEC if rg else CALL_INTERVAL_SEC
|
||||
last = self._last_rg_call if rg else self._last_call
|
||||
wait = gap - (time.monotonic() - last)
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
||||
"Content-Type": "application/json;charset=UTF-8"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
||||
finally:
|
||||
if rg:
|
||||
self._last_rg_call = time.monotonic()
|
||||
else:
|
||||
self._last_call = time.monotonic()
|
||||
if res.status_code == 429 and attempt < RETRY_429:
|
||||
time.sleep(2.0 * (2 ** attempt))
|
||||
continue
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
body = {}
|
||||
if not isinstance(body, dict):
|
||||
body = {"data": body}
|
||||
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()[:300]
|
||||
if res.status_code in (401, 403):
|
||||
raise AuthFailed(
|
||||
f"쿠팡 {what} 조회 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
||||
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
||||
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
||||
if res.status_code == 429:
|
||||
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
if res.status_code >= 400:
|
||||
raise ApiError(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||
code = body.get("code")
|
||||
if isinstance(code, int) and code >= 400:
|
||||
raise ApiError(f"쿠팡 {what} API 오류({code}): {msg}")
|
||||
return body
|
||||
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
|
||||
def _pages(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
token: str | None = None
|
||||
for _ in range(MAX_PAGES):
|
||||
body = self._get(ctx, path, {**params, "nextToken": token} if token else params, rg=rg)
|
||||
rows = [r for r in (body.get("data") or []) if isinstance(r, dict)] if isinstance(body.get("data"), list) else []
|
||||
out.extend(rows)
|
||||
nxt = str(body.get("nextToken") or "").strip()
|
||||
if not nxt or not rows or nxt == token:
|
||||
break
|
||||
token = nxt
|
||||
return out
|
||||
|
||||
def _seller_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가."""
|
||||
path = ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||
out: list[dict[str, Any]] = []
|
||||
for a, b in spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS):
|
||||
for st in STATUSES:
|
||||
rows = self._pages(ctx, path, {"createdAtFrom": f"{a.isoformat()}+09:00",
|
||||
"createdAtTo": f"{b.isoformat()}+09:00",
|
||||
"status": st, "maxPerPage": PAGE_SIZE})
|
||||
out.extend(rows)
|
||||
ctx.progress.step(items=len(rows))
|
||||
return out
|
||||
|
||||
def _rg_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||
path = RG_ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||
out: list[dict[str, Any]] = []
|
||||
for a, b in spans(start, end, RG_SPAN_DAYS):
|
||||
rows = self._pages(ctx, path, {"paidDateFrom": a.strftime("%Y%m%d"), "paidDateTo": b.strftime("%Y%m%d")}, rg=True)
|
||||
out.extend(rows)
|
||||
ctx.progress.step(items=len(rows))
|
||||
return out
|
||||
|
||||
def _plan(self, ctx: AdapterContext, start: date, end: date) -> None:
|
||||
ctx.progress.plan(len(spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS)) * len(STATUSES)
|
||||
+ len(spans(start, end, RG_SPAN_DAYS)), "조회")
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
self._plan(ctx, start, end)
|
||||
seller = seller_lines(self._seller_orders(ctx, start, end), start, end)
|
||||
rg = rg_lines(self._rg_orders(ctx, start, end), start, end)
|
||||
yield from group_lines(seller, EVENT_PREFIX).values()
|
||||
yield from group_lines(rg, RG_PREFIX).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 []]
|
||||
if o.get("canceled"):
|
||||
statuses.append("취소 포함")
|
||||
return [SaleEvent(
|
||||
event_type="SALE", external_event_id=str(o["event_id"]), external_order_id=oid,
|
||||
order_date=o.get("order_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
|
||||
|
||||
self.authenticate(ctx)
|
||||
vendor = ctx.credentials.get("vendor_id").strip()
|
||||
today = today_kst().isoformat()
|
||||
body = self._get(ctx, f"/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets",
|
||||
{"createdAtFrom": f"{today}+09:00", "createdAtTo": f"{today}+09:00",
|
||||
vendor = self._vendor(ctx)
|
||||
today = today_kst()
|
||||
body = self._get(ctx, ORDERS_PATH.format(vendor=vendor),
|
||||
{"createdAtFrom": f"{today.isoformat()}+09:00", "createdAtTo": f"{today.isoformat()}+09:00",
|
||||
"status": "ACCEPT", "maxPerPage": 1})
|
||||
n = len(body.get("data") or [])
|
||||
return (f"쿠팡 연결 정상(발주서 조회 권한 확인, 오늘 결제완료 {'있음' if n else '없음'}). "
|
||||
"매출 수집은 다음 단계에서 구현됩니다.")
|
||||
rg = self._get(ctx, RG_ORDERS_PATH.format(vendor=vendor),
|
||||
{"paidDateFrom": today.strftime("%Y%m%d"), "paidDateTo": today.strftime("%Y%m%d")}, rg=True)
|
||||
m = len(rg.get("data") or [])
|
||||
return (f"쿠팡 연결 정상(판매자배송 발주서·로켓그로스 주문 조회 권한 확인 — 오늘 결제완료 발주서 {'있음' if n else '없음'}, "
|
||||
f"로켓그로스 오늘 주문 {m}건{'+' if rg.get('nextToken') else ''}).")
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||
"""결제일 기준 기간(최대 31일)의 판매자배송 발주서·로켓그로스 주문을 실제로 불러, 날짜별 후보 금액을 나란히 —
|
||||
WING 판매분석 '매출(원)'과 같은 열을 찾아 규칙을 확정하는 용도. 저장하지 않고, 개인정보 항목은 빼고 보여 준다."""
|
||||
self.authenticate(ctx)
|
||||
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||
self._plan(ctx, day, to)
|
||||
probes: list[dict[str, Any]] = []
|
||||
seller_raw: list[dict[str, Any]] = []
|
||||
rg_raw: list[dict[str, Any]] = []
|
||||
try:
|
||||
seller_raw = self._seller_orders(ctx, day, to)
|
||||
probes.append({"key": "seller", "label": "판매자배송 발주서(주문일 하루 앞부터, 상태 6개)",
|
||||
"path": ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(seller_raw),
|
||||
"fields": field_summary([r for o in seller_raw for r in line_records(o)])})
|
||||
except AdapterError as exc:
|
||||
probes.append({"key": "seller", "label": "판매자배송 발주서", "path": ORDERS_PATH.format(vendor="{vendorId}"),
|
||||
"ok": False, "error": exc.message[:300]})
|
||||
try:
|
||||
rg_raw = self._rg_orders(ctx, day, to)
|
||||
probes.append({"key": "rg", "label": "로켓그로스 주문(결제일, 출고된 주문만)",
|
||||
"path": RG_ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(rg_raw),
|
||||
"fields": field_summary([{**flatten({k: v for k, v in o.items() if k != "orderItems"}),
|
||||
**flatten(it, "orderItems")}
|
||||
for o in rg_raw for it in (o.get("orderItems") or [{}])])})
|
||||
except AdapterError as exc:
|
||||
probes.append({"key": "rg", "label": "로켓그로스 주문", "path": RG_ORDERS_PATH.format(vendor="{vendorId}"),
|
||||
"ok": False, "error": exc.message[:300]})
|
||||
seller = seller_lines(seller_raw, day, to)
|
||||
rg = rg_lines(rg_raw, day, to)
|
||||
dates = [(day + timedelta(days=i)).isoformat() for i in range((to - day).days + 1)]
|
||||
|
||||
def per_day(lines: list[dict[str, Any]], fn: Any) -> dict[str, int]:
|
||||
out = {d: 0 for d in dates}
|
||||
for ln in lines:
|
||||
out[ln["_day"].isoformat()] += int(fn(ln))
|
||||
return out
|
||||
|
||||
def count(lines: list[dict[str, Any]], d: str) -> int:
|
||||
return len({ln["orderId"] for ln in lines if ln["_day"].isoformat() == d})
|
||||
|
||||
s_amt, s_net = per_day(seller, lambda x: x["amount"]), per_day(seller, lambda x: x["amount"] - x["discount"])
|
||||
s_live = per_day(seller, lambda x: x["amount"] - x["canceled"])
|
||||
s_qty, r_qty = per_day(seller, lambda x: x["qty"]), per_day(rg, lambda x: x["qty"])
|
||||
s_cancel, s_ship = per_day(seller, lambda x: x["canceled"]), per_day(seller, lambda x: x["ship"])
|
||||
r_amt = per_day(rg, lambda x: x["amount"])
|
||||
ok = {p["key"]: p["ok"] for p in probes}
|
||||
failed = {p["key"]: p.get("error", "") for p in probes if not p["ok"]}
|
||||
cands = [
|
||||
{"label": "① 현재 규칙: 판매자배송 판매가 + 로켓그로스", "days": {d: s_amt[d] + r_amt[d] for d in dates}},
|
||||
{"label": "② 판매자배송 판매가(쿠폰 할인 전)", "days": s_amt, "error": failed.get("seller")},
|
||||
{"label": "③ 판매자배송 할인 뒤(판매가 − 쿠폰·쿠팡 할인)", "days": s_net, "error": failed.get("seller")},
|
||||
{"label": "④ 판매자배송 취소분 뺀 판매가", "days": s_live, "error": failed.get("seller")},
|
||||
{"label": "⑤ 로켓그로스 단가 × 수량", "days": r_amt, "error": failed.get("rg")},
|
||||
{"label": "판매량: 판매자배송 + 로켓그로스(개)", "days": {d: s_qty[d] + r_qty[d] for d in dates}},
|
||||
]
|
||||
if not all(ok.values()):
|
||||
cands[0]["error"] = "일부 조회 실패 — 위 표 참고"
|
||||
days = [{"date": d, "orders": count(seller, d) + count(rg, d), "amount": s_amt[d] + r_amt[d],
|
||||
"claimed": s_cancel[d], "ship": s_ship[d]}
|
||||
for d in dates]
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||
"day_cols": {"amount": "매출(현재 규칙)", "claimed": "그중 판매자배송 취소분(참고)", "ship": "판매자배송 배송비(참고, 매출 제외)"},
|
||||
"refund_candidates": cands, "candidates_title": "매출 후보 비교 — WING 판매분석 '매출(원)'·'판매량'과 같은 열을 알려 주세요",
|
||||
"rule": "결제일(한국 시간) 기준 — 판매자배송 발주서 orderPrice(판매가 × 수량, 쿠폰 할인 전, 결제 뒤 취소분 포함) + "
|
||||
"로켓그로스 unitSalesPrice × salesQuantity(출고된 주문만). 배송비 제외"}
|
||||
|
||||
@@ -239,4 +239,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261012a" defer></script>{% endblock %}
|
||||
|
||||
@@ -136,13 +136,15 @@
|
||||
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
||||
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.<br>
|
||||
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.</p>
|
||||
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.<br>
|
||||
· <b>쿠팡</b>: 판매자배송 발주서 + 로켓그로스 주문을 결제일로 모아 날짜별 매출 후보(할인 전·후, 취소분 뺀 값, 로켓그로스 따로)와 판매량 — WING 비즈니스 인사이트 → 판매분석에서 같은 날짜의 "매출(원)"·"판매량"과 비교해 주세요.</p>
|
||||
<div class="perf-sample-form">
|
||||
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
||||
<option value="naver">네이버 스마트스토어</option>
|
||||
<option value="elevenst">11번가</option>
|
||||
<option value="gsshop">GS샵</option>
|
||||
<option value="toss">토스쇼핑</option>
|
||||
<option value="coupang">쿠팡</option>
|
||||
</select>
|
||||
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
||||
<span class="perf-muted">~</span>
|
||||
@@ -192,4 +194,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261012a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1064,15 +1064,18 @@ def test_coupang_hmac_and_connection_errors():
|
||||
seen = {}
|
||||
|
||||
def fake_get(url, headers=None, timeout=None, status=200, body=None):
|
||||
seen.setdefault("urls", []).append(url)
|
||||
seen["url"], seen["auth"] = url, headers["Authorization"]
|
||||
return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
|
||||
|
||||
orig = httpx.get
|
||||
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||
try:
|
||||
httpx.get = fake_get
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = fake_get, 0, 0
|
||||
msg = cp.CoupangAdapter().test_connection(ctx)
|
||||
assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"]
|
||||
assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"]
|
||||
first, rg = seen["urls"]
|
||||
assert "연결 정상" in msg and "로켓그로스" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in first
|
||||
assert "%2B09:00" in first and "SK-SECRET" not in seen["auth"]
|
||||
assert "/rg_open_api/apis/api/v1/vendors/A00012345/rg/orders?paidDateFrom=" in rg
|
||||
httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
|
||||
try:
|
||||
cp.CoupangAdapter().test_connection(ctx)
|
||||
@@ -1081,7 +1084,158 @@ def test_coupang_hmac_and_connection_errors():
|
||||
else:
|
||||
raise AssertionError("403 이면 인증 실패여야 합니다")
|
||||
finally:
|
||||
httpx.get = orig
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||
|
||||
|
||||
def _cp_sheet(order_id, box, paid, items, *, status="INSTRUCT", ship=3000):
|
||||
def money(n):
|
||||
return {"currencyCode": "KRW", "units": n, "nanos": 0}
|
||||
|
||||
return {"shipmentBoxId": box, "orderId": order_id, "orderedAt": paid, "paidAt": paid, "status": status,
|
||||
"orderer": {"name": "홍길동", "safeNumber": "0502-1111-2222"},
|
||||
"receiver": {"name": "홍길동", "addr1": "서울 비밀구 1", "receiverNumber": "+82-10-1234-5678"},
|
||||
"parcelPrintMessage": "문 앞", "shippingPrice": money(ship), "remotePrice": money(0),
|
||||
"orderItems": [{"sequenceNo": f"{i + 1:03d}", "vendorItemId": 100 + i, "vendorItemName": n,
|
||||
"sellerProductName": n, "sellerProductItemName": "1개", "shippingCount": q,
|
||||
"salesPrice": money(p), "orderPrice": money(p * q), "discountPrice": money(dc),
|
||||
"cancelCount": cc, "holdCountForCancel": 0, "canceled": cc >= q,
|
||||
"etcInfoValues": ["개인 메모"]}
|
||||
for i, (n, p, q, dc, cc) in enumerate(items)]}
|
||||
|
||||
|
||||
def _cp_rg(order_id, paid_ms, items):
|
||||
return {"vendorId": "A00012345", "orderId": order_id, "paidAt": paid_ms,
|
||||
"orderItems": [{"vendorItemId": 900 + i, "productName": n, "salesQuantity": q, "unitSalesPrice": str(p),
|
||||
"currency": "KRW"} for i, (n, p, q) in enumerate(items)]}
|
||||
|
||||
|
||||
def _cp_server(sheets_by_status, rg_pages):
|
||||
"""가짜 쿠팡 — 발주서는 상태별 목록(2쪽까지), 로켓그로스는 nextToken 쪽 넘김. 호출 기록을 남긴다."""
|
||||
import httpx
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
calls = []
|
||||
|
||||
def get(url, headers=None, timeout=None):
|
||||
u = urlparse(url)
|
||||
q = {k: v[0] for k, v in parse_qs(u.query).items()}
|
||||
calls.append((u.path, q))
|
||||
if u.path.endswith("/rg/orders"):
|
||||
i = int(q.get("nextToken") or 0)
|
||||
nxt = str(i + 1) if i + 1 < len(rg_pages) else ""
|
||||
return httpx.Response(200, json={"code": 200, "message": "SUCCESS", "data": rg_pages[i], "nextToken": nxt})
|
||||
rows = sheets_by_status.get(q["status"], [])
|
||||
if q.get("nextToken") == "p2":
|
||||
return httpx.Response(200, json={"code": 200, "data": rows[1:], "nextToken": ""})
|
||||
return httpx.Response(200, json={"code": 200, "data": rows[:1], "nextToken": "p2" if len(rows) > 1 else ""})
|
||||
|
||||
return get, calls
|
||||
|
||||
|
||||
KST_1012_0030_MS = 1791732600000 # 2026-10-12 00:30 KST = 10-11 15:30 UTC
|
||||
|
||||
|
||||
def test_coupang_collect_sales():
|
||||
"""쿠팡 매출 = 판매자배송 발주서 orderPrice(쿠폰 할인 전) + 로켓그로스 단가 × 수량, 결제일(한국 시간) 기준.
|
||||
상태 6개 모두 조회·쪽 넘김, 결제일이 기간 밖이면 뺌, 결제 뒤 취소된 줄도 결제일 매출, 같은 발주서 두 번 와도 한 번.
|
||||
구매자·수령자 정보는 저장하지 않는다."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
|
||||
sheets = {
|
||||
"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0), ("뚜껑", 3000, 1, 0, 0)]),
|
||||
_cp_sheet(2, 21, "2026-10-12T23:59:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])], # 결제 뒤 취소
|
||||
"FINAL_DELIVERY": [_cp_sheet(3, 31, "2026-10-11T23:50:00+09:00", [("밀폐용기", 12000, 1, 0, 0)]), # 전날 결제 — 뺌
|
||||
_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)])], # 같은 발주서 다시
|
||||
}
|
||||
rg_pages = [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])], [_cp_rg(71, KST_1012_0030_MS + 3600_000, [("컵", 5000, 1)])]]
|
||||
get, calls = _cp_server(sheets, rg_pages)
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(next(a for a in all_adapters() if a.code == "coupang"),
|
||||
{"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-SECRET"})
|
||||
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||
try:
|
||||
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||
finally:
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||
assert r["ok"], r
|
||||
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "coupang"}
|
||||
assert set(ev_) == {"coupang:1", "coupang:2", "coupang:rg:70", "coupang:rg:71"}, set(ev_)
|
||||
assert ev_["coupang:1"]["amount"] == 24000 + 3000 and ev_["coupang:1"]["quantity"] == 3 # 배송비 제외, 중복 없음
|
||||
assert ev_["coupang:1"]["discount_amount"] == 1000 and ev_["coupang:1"]["product_name"] == "밀폐용기 외 1건"
|
||||
assert ev_["coupang:2"]["amount"] == 12000 and "취소" in ev_["coupang:2"]["order_status"]
|
||||
assert ev_["coupang:rg:70"]["amount"] == 29700 and ev_["coupang:rg:70"]["sales_date"] == date(2026, 10, 12)
|
||||
assert ev_["coupang:rg:71"]["amount"] == 5000 # 다음 쪽(nextToken)
|
||||
assert {q["status"] for p, q in calls if p.endswith("/ordersheets")} == set(cp.STATUSES)
|
||||
sheet_q = next(q for p, q in calls if p.endswith("/ordersheets"))
|
||||
assert sheet_q["createdAtFrom"] == "2026-10-11+09:00" and sheet_q["createdAtTo"] == "2026-10-12+09:00" # 주문일 하루 앞부터
|
||||
assert any(q.get("nextToken") == "p2" and q["status"] == "INSTRUCT" for p, q in calls if p.endswith("/ordersheets"))
|
||||
rg_q = next(q for p, q in calls if p.endswith("/rg/orders"))
|
||||
assert rg_q["paidDateFrom"] == "20261012" and rg_q["paidDateTo"] == "20261012"
|
||||
assert "홍길동" not in repr(st.events) and "비밀구" not in repr(st.events) and "1234-5678" not in repr(st.events)
|
||||
|
||||
|
||||
def test_coupang_spans_and_money():
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
|
||||
assert cp.spans(date(2026, 1, 1), date(2026, 3, 5), 31) == [
|
||||
(date(2026, 1, 1), date(2026, 1, 31)), (date(2026, 2, 1), date(2026, 3, 3)), (date(2026, 3, 4), date(2026, 3, 5))]
|
||||
assert cp._won({"units": 15000, "nanos": 0}) == 15000 and cp._won("27,800") == 27800 and cp._won(None) == 0
|
||||
assert cp._kst_day("2026-10-12T00:10:00+09:00") == date(2026, 10, 12)
|
||||
assert cp._kst_day("2026-10-11T15:10:00Z") == date(2026, 10, 12) # UTC → 한국 날짜
|
||||
assert cp._kst_day(KST_1012_0030_MS) == date(2026, 10, 12)
|
||||
assert cp._kst_day("2026-10-12") == date(2026, 10, 12) and cp._kst_day("") is None
|
||||
|
||||
|
||||
def test_coupang_reconcile_candidates_hide_personal():
|
||||
"""원본 데이터 확인 — 날짜별 후보 금액(할인 전·후, 취소분 뺀 값, 로켓그로스)·판매량, 개인정보 항목은 아예 없음.
|
||||
로켓그로스만 실패해도 판매자배송 결과는 보여 준다."""
|
||||
import httpx
|
||||
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
from app.modules.performance.adapters.base import AdapterContext
|
||||
|
||||
class Creds(dict):
|
||||
def get(self, k, default=""):
|
||||
return dict.get(self, k, default)
|
||||
|
||||
def has(self, k):
|
||||
return bool(dict.get(self, k))
|
||||
|
||||
ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK"))
|
||||
sheets = {"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)]),
|
||||
_cp_sheet(2, 21, "2026-10-13T10:00:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])]}
|
||||
get, _calls = _cp_server(sheets, [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])]])
|
||||
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||
try:
|
||||
rec = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12), to=date(2026, 10, 13))
|
||||
cands = {c["label"][:1]: c for c in rec["refund_candidates"]}
|
||||
assert cands["①"]["days"] == {"2026-10-12": 24000 + 29700, "2026-10-13": 12000}
|
||||
assert cands["②"]["days"]["2026-10-12"] == 24000 and cands["③"]["days"]["2026-10-12"] == 23000
|
||||
assert cands["④"]["days"]["2026-10-13"] == 0 and cands["⑤"]["days"]["2026-10-12"] == 29700
|
||||
assert next(c for c in rec["refund_candidates"] if c["label"].startswith("판매량"))["days"]["2026-10-12"] == 5
|
||||
assert rec["days"][0] == {"date": "2026-10-12", "orders": 2, "amount": 53700, "claimed": 0, "ship": 3000}
|
||||
assert rec["days"][1]["claimed"] == 12000 and rec["candidates_title"]
|
||||
names = {f["name"] for p in rec["probes"] if p["ok"] for f in p["fields"]}
|
||||
assert "orderItems.orderPrice.units" in names and not any(n.startswith(("orderer", "receiver")) for n in names)
|
||||
assert "홍길동" not in repr(rec) and "비밀구" not in repr(rec) and "개인 메모" not in repr(rec) and "문 앞" not in repr(rec)
|
||||
|
||||
def deny_rg(url, headers=None, timeout=None): # 로켓그로스만 거부(403)
|
||||
if "/rg/orders" in url:
|
||||
return httpx.Response(403, json={"message": "Access Denied"})
|
||||
return get(url, headers, timeout)
|
||||
|
||||
httpx.get = deny_rg
|
||||
rec2 = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12))
|
||||
p = {x["key"]: x for x in rec2["probes"]}
|
||||
assert p["seller"]["ok"] and not p["rg"]["ok"] and "403" in p["rg"]["error"]
|
||||
assert rec2["refund_candidates"][0]["error"] and rec2["refund_candidates"][1]["days"]["2026-10-12"] == 24000
|
||||
finally:
|
||||
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||
|
||||
|
||||
def test_elevenst_connection():
|
||||
|
||||
@@ -987,7 +987,7 @@
|
||||
}
|
||||
});
|
||||
|
||||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑·쿠팡) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||||
const probe = document.getElementById("perf-probe");
|
||||
if (probe) probe.addEventListener("click", async function () {
|
||||
const day = document.getElementById("perf-probe-date").value;
|
||||
@@ -997,7 +997,8 @@
|
||||
const codeSel = document.getElementById("perf-probe-code");
|
||||
const code = codeSel ? codeSel.value : "elevenst";
|
||||
const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)",
|
||||
gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
||||
gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)",
|
||||
coupang: "쿠팡에서 불러오는 중… (판매자배송 상태 6개 + 로켓그로스, 수십 초)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
||||
out.innerHTML = '<p class="perf-muted">' + loading + "</p>";
|
||||
try {
|
||||
const to = document.getElementById("perf-probe-to").value || day;
|
||||
@@ -1038,7 +1039,7 @@
|
||||
// 환불 출처별(토스쇼핑) — 출처별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모)
|
||||
const rc = r.refund_candidates || [];
|
||||
const candDays = (r.days || []).map(function (d) { return d.date; });
|
||||
const cands = rc.length ? '<h4 class="perf-h" style="margin:14px 0 6px">환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불</h4>' +
|
||||
const cands = rc.length ? '<h4 class="perf-h" style="margin:14px 0 6px">' + esc(r.candidates_title || "환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불") + "</h4>" +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||||
rc.map(function (c) { return "<th>" + esc(c.label) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||||
candDays.map(function (dt) {
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
|
||||
|
||||
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑 = **구현됨**, 나머지 5개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑·쿠팡 = **구현됨**(쿠팡은 2026-10-12 — 매출 규칙은 WING 실데이터 대조 전), 나머지 4개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 단계에서 공식 API 문서로 확정**한다.
|
||||
|
||||
### 카페24 (`adapters/cafe24.py`, 구현됨)
|
||||
@@ -183,6 +183,23 @@
|
||||
+ 주문 상태별·클레임·정산 항목 합계. 화면 숫자와 다르면 출처별 열로 어느 쪽이 빠졌는지 본다.
|
||||
- 정산 줄의 다른 항목: 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`, 수수료 `payFee`·`productFee`.
|
||||
|
||||
### 쿠팡 (`adapters/coupang.py`, 구현됨 — 규칙 대조 전)
|
||||
|
||||
- 맞출 화면(2026-10-12 사용자 지정): WING → 비즈니스 인사이트 → **판매분석**, 판매자배송 + 로켓그로스, 날짜 선택 → **매출(원)**.
|
||||
판매분석 자체를 주는 Open API 는 없다(developers.coupang.com API 목록 확인) → 주문 API 두 개를 **결제일(한국 시간)** 로 합친다.
|
||||
- 인증: Vendor ID + Access Key + Secret Key, 요청마다 CEA HMAC 서명. 키는 '자체개발' + 이 서버 IP 를 허용 IP 에.
|
||||
- 판매자배송: 발주서 목록(일단위 페이징) `/v5/vendors/{vendorId}/ordersheets` — 주문일(`createdAtFrom/To`, `yyyy-mm-dd+09:00`,
|
||||
31일까지) × 상태 6개(ACCEPT·INSTRUCT·DEPARTURE·DELIVERING·FINAL_DELIVERY·NONE_TRACKING), 50건씩 `nextToken`. 주문일 하루 앞부터 불러
|
||||
`paidAt` 으로 다시 거른다. 줄 금액 = `orderPrice`(판매가 × 수량, 쿠폰 할인 전), 같은 발주서·줄은 한 번만. 결제 뒤 취소된 줄
|
||||
(`canceled`·`cancelCount`)도 결제일 매출(지난 날짜가 줄지 않게, 원본 확인에 따로). 완료 반품·결제 전 취소는 목록에 없다(쿠팡 안내).
|
||||
- 로켓그로스: `/rg_open_api/apis/api/v1/vendors/{vendorId}/rg/orders?paidDateFrom=yyyymmdd&paidDateTo=` — 결제일, 30일까지, 분당 50회
|
||||
(호출 간격 1.25초), `paidAt` 은 밀리초. 줄 금액 = `unitSalesPrice × salesQuantity`. **출고된 주문만** 나온다(쿠팡 안내 — 오늘 주문은 늦게 잡힐 수 있음).
|
||||
- 사건: 주문 하나 = SALE(판매자배송 `coupang:{orderId}`, 로켓그로스 `coupang:rg:{orderId}`), `replace_range`(접두어 `coupang:`).
|
||||
배송비는 매출 제외. 구매자·수령자·통관·배송 메모·직접 입력 항목은 저장·표시하지 않는다.
|
||||
- 원본 데이터 확인(쿠팡): 날짜별 **매출 후보** — ① 현재 규칙(판매자배송 판매가 + 로켓그로스) ② 판매자배송 판매가 ③ 할인 뒤
|
||||
④ 취소분 뺀 값 ⑤ 로켓그로스 + 판매량 — 를 WING 판매분석의 같은 날 "매출(원)"·"판매량" 과 비교해 규칙을 확정한다(`candidates_title`).
|
||||
로켓그로스만 거부돼도 판매자배송 결과는 보인다.
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
||||
|
||||
Reference in New Issue
Block a user