Files
dbx-main/app/modules/performance/adapters/gsshop.py
T
king da63b93302 feat(performance): 매출 업데이트 취소 버튼
- 진행 창 [업데이트 취소](시작한 사람·관리자) → POST /api/sync/jobs/{id}/cancel
- 어댑터가 API 호출 직전마다 ctx.progress.check() — 취소면 Cancelled 로 멈추고 저장하지 않음(기존 매출 그대로),
  차례가 안 온 쇼핑몰은 취소됨으로 건너뜀, 이미 끝난 쇼핑몰 결과는 유지
- 취소 실행은 perf_sync_runs failed + 업데이트 취소, 연결 상태는 바꾸지 않음
- 테스트 1개 추가(30개 통과), performance.js/css 캐시 버전, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:06:25 +09:00

309 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""GS샵 — GSSHOP 제휴 API(협력사 API V3, partners.gsshop.com → 제휴 API → 개발가이드).
인증(개발가이드 2026-09-30 확인): 요청 헤더
supCd = 협력사코드
token = AES256( Sysdate("yyyyMMddHHmmss") + 협력사코드 ) 예: "20181017174913" + "1036018"
AES256 암복호화 키는 partners.gsshop.com/api/apiMain 에 로그인하면 보인다.
암호화 모드(CBC/ECB, IV)와 키를 바이트로 쓰는 법은 문서에 없다 → 키 변형(글자 그대로 / 16진수 풀기 / 앞 32자,
key_variants) × 모드(CBC·IV=키 앞 16바이트 → ECB → CBC·IV=0) 순서로 시도하고 통과한 조합을 기억한다. 출력은 base64.
(포털 "운영 KEY" 는 16진수처럼 보이는 글자 — 32자면 글자 그대로 AES256, 64자면 16진수로 풀어 32바이트일 수 있다.)
token 이 틀리면 HTTP 200 + {"result":"fail","message":"키 인증 중 오류…","code":"401 UNAUTHORIZED"}.
주소: 운영 https://withgs-api.gsshop.com (개발가이드의 예시 주소 atwithgs-api 는 테스트용 — 두 곳 모두 응답 확인).
매출(Settlement API 1.0): GET /api/v2/settlement/out/sales/period?supCode=&fromDate=&toDate=&pageIdx=&rowsPerPage=
— 매출인식일(YYYYMMDD) 기준, 한 번에 10일까지, 쪽당 최대 1만 건. 응답 {data:[…], hasMorePage, totalCount, …}.
배송비는 /api/v2/settlement/out/sales/shippingFee/period(같은 조건).
응답 줄 항목(2026-09-30 실데이터 9/3 — 개발가이드 예시에는 없음): saleAwareDt(매출인식일), ordNo·ordItemNo·orgOrdNo,
ordType(SALE …), prdCd·prdNm, chrQty(수량), salePrice(할인 전 판매가 — 줄 합계), dcTotAmt(할인 합계),
custChrAmt(고객 결제금액 = salePrice − dcTotAmt), supGiveAmt(협력사 지급액, 수수료 차감), sup*DcAmt(협력사 부담 할인).
9/3: salePrice 211,100 − dcTotAmt 19,528 = custChrAmt 191,572, supGiveAmt 179,435, 배송비 내역 7,000.
**주문일 기준 조회 API 는 없다**(V3 문서에 주문 조회 없음) — 협력사 포털 주문 통계(총주문금액, 주문일)와는 기준이 달라
날짜별로 똑같이 맞출 수 없다.
매출 규칙 — 협력사 포털 주문 통계의 금액 = **supGiveAmt(협력사 지급액)**(2026-09-30, 9월 실데이터로 확인):
미라미라클 6호세트 포털 176,715 ÷ 9 = 19,635 = API 줄 supGiveAmt 19,635(판매가 23,100·고객 결제 20,330),
7호세트 39,015 = 45,900 × 85%, 주부체험 세트 8,910 = 9,900 × 90% — 상품마다 GS 수수료율이 달라 판매가 × 요율로는 못 맞춘다.
9/1~9/29: 지급액 4,972,689 / 포털 순주문 4,823,074(차이는 주문일 ↔ 매출인식일 기준 차이·취소분).
- 매출 내역 한 줄 = 사건 하나(`gs:{ordNo}-{ordItemNo}-{ordType}-{saleAwareDt}`), 날짜 = 매출인식일.
- 금액 = supGiveAmt, 배송비 제외. 이미 GS 수수료를 뺀 금액이라 **실적 설정의 GS샵 수수료율은 0%** 로 둔다.
ordType 이 SALE 이 아니면(취소·반품 등) 음수로(RETURN). 할인 = dcTotAmt. 기간을 통째로 다시 받는다(replace_range).
"""
from __future__ import annotations
import base64
from datetime import date, datetime, timedelta
from typing import Any, Iterable
from .base import (
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
)
from .elevenst import field_summary
HOST = "https://withgs-api.gsshop.com"
SALES_PATH = "/api/v2/settlement/out/sales/period"
SHIPPING_PATH = "/api/v2/settlement/out/sales/shippingFee/period"
DAILY_SALES_PATH = "/api/v2/settlement/out/sales"
CHUNK_DAYS = 10 # 기간 조회는 시작일부터 10일 이내
ROWS_PER_PAGE = 10000
MAX_PAGES = 50
PROBE_MAX_DAYS = 31
TOKEN_MODES = ("cbc-keyiv", "ecb", "cbc-zeroiv")
MODE_LABEL = {"cbc-keyiv": "AES/CBC(IV=키 앞 16바이트)", "ecb": "AES/ECB", "cbc-zeroiv": "AES/CBC(IV=0)"}
KEY_LABEL = {"text": "키 글자 그대로", "hex": "키 16진수 풀기", "first32": "키 앞 32자"}
def key_variants(aes_key: str) -> list[tuple[str, bytes]]:
"""AES 키로 쓸 수 있는 바이트 후보(시도 순서). 하나도 없으면 길이 오류."""
raw = aes_key.strip().encode("utf-8")
out: list[tuple[str, bytes]] = []
if len(raw) in (16, 24, 32):
out.append(("text", raw))
txt = aes_key.strip()
if len(txt) in (32, 48, 64) and all(c in "0123456789abcdefABCDEF" for c in txt):
out.append(("hex", bytes.fromhex(txt)))
if len(raw) > 32:
out.append(("first32", raw[:32]))
if not out:
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(raw)}자). 제휴 API 메인 화면의 운영 KEY 를 "
"[복사] 버튼으로 복사해 그대로 붙여 넣으세요.")
return out
def make_token(aes_key: str | bytes, sup_cd: str, now: datetime, mode: str) -> str:
"""token = base64(AES(yyyyMMddHHmmss + 협력사코드)), PKCS7(=PKCS5) 패딩. aes_key 가 글자면 그대로 바이트로."""
from cryptography.hazmat.primitives import padding # 지연 import
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = aes_key if isinstance(aes_key, bytes) else aes_key.encode("utf-8")
if len(key) not in (16, 24, 32):
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(key)}바이트 — 16·24·32 중 하나여야 함). "
"제휴 API 메인 화면의 키를 그대로 붙여 넣으세요.")
plain = (now.strftime("%Y%m%d%H%M%S") + sup_cd).encode("utf-8")
padder = padding.PKCS7(128).padder()
data = padder.update(plain) + padder.finalize()
if mode == "ecb":
cipher = Cipher(algorithms.AES(key), modes.ECB())
elif mode == "cbc-zeroiv":
cipher = Cipher(algorithms.AES(key), modes.CBC(b"\0" * 16))
else:
cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]))
enc = cipher.encryptor()
return base64.b64encode(enc.update(data) + enc.finalize()).decode("ascii")
def _rows(body: dict[str, Any]) -> list[dict[str, Any]]:
data = body.get("data")
return [r for r in data if isinstance(r, dict)] if isinstance(data, list) else []
def _strs(row: dict[str, Any]) -> dict[str, str]:
"""원본 확인용 — 값은 모두 글자로(중첩은 JSON 글자 그대로 짧게)."""
return {str(k): ("" if v is None else str(v)) for k, v in row.items()}
EVENT_PREFIX = "gs:"
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 _yyyymmdd(value: Any) -> date | None:
s = "".join(ch for ch in str(value or "") if ch.isdigit())[:8]
if len(s) < 8:
return None
try:
return date(int(s[:4]), int(s[4:6]), int(s[6:8]))
except ValueError:
return None
class GsshopAdapter(MarketplaceAdapter):
code = "gsshop"
name = "GS샵"
auth_type = "api_key"
implemented = True
replace_range = True
event_prefix = EVENT_PREFIX
docs_url = "https://partners.gsshop.com/api/apiDevGuide"
note = ("GS SHOP 협력사 포털(partners.gsshop.com) → 제휴 API 메인 화면의 협력사코드와 "
"운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.")
def __init__(self) -> None:
self._mode: dict[str, tuple[str, str]] = {} # 협력사코드 → 통과한 (키 변형, 암호화 모드)
def credential_fields(self) -> list[CredentialField]:
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
return [
CredentialField("vendor_code", "협력사코드(supCd)", help="예: 1036018"),
CredentialField("api_key", "운영 KEY(AES256 암복호화 키)", secret=True,
help="제휴 API 메인 화면의 운영 KEY — [복사] 버튼으로 복사해 붙여 넣기"),
]
# ── 호출 ──────────────────────────────────────────────
def _creds(self, ctx: AdapterContext) -> tuple[str, str]:
sup = ctx.credentials.get("vendor_code").strip()
key = ctx.credentials.get("api_key").strip()
if not sup or not key:
raise NotConfigured("협력사코드와 AES256 키를 입력하세요.")
return sup, key
def _call(self, ctx: AdapterContext, path: str, params: dict[str, Any], how: tuple[str, str]) -> dict[str, Any]:
import httpx # 지연 import
from app.timezone import now_kst # noqa: WPS433
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
sup, key = self._creds(ctx)
key_bytes = dict(key_variants(key))[how[0]]
headers = {"supCd": sup, "token": make_token(key_bytes, sup, now_kst(), how[1]), "Accept": "application/json"}
try:
res = httpx.get(f"{HOST}{path}", params={"supCode": sup, **params}, headers=headers, timeout=ctx.timeout_sec)
except httpx.HTTPError as exc:
raise ApiError(f"GS샵 API 연결 실패: {type(exc).__name__}") from None
try:
body = res.json()
except ValueError:
raise ApiError(f"GS샵이 예상하지 못한 응답을 돌려줬습니다({res.status_code}): {res.text[:150].strip()}") from None
if not isinstance(body, dict):
body = {"data": body}
code = str(body.get("code") or "")
msg = str(body.get("message") or "")[:200]
if res.status_code in (401, 403) or (str(body.get("result")) == "fail" and ("401" in code or "403" in code)):
raise AuthFailed(f"GS샵 인증 거부({code or res.status_code}): {msg}")
if res.status_code >= 400 or str(body.get("result")) == "fail":
raise ApiError(f"GS샵 API 오류({code or res.status_code}): {msg or res.text[:150].strip()}")
return body
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""토큰 만드는 법(키 변형 × 암호화 모드)을 모르면 순서대로 시도 — 통과한 조합을 기억한다."""
sup, key = self._creds(ctx)
known = self._mode.get(sup)
if known:
return self._call(ctx, path, params, known)
tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES]
last: AuthFailed | None = None
for how in tries:
try:
body = self._call(ctx, path, params, how)
except AuthFailed as exc:
last = exc
continue
self._mode[sup] = how
return body
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. "
"협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.")
def _pages(self, ctx: AdapterContext, path: str, lo: date, hi: date) -> list[dict[str, Any]]:
"""[lo, hi] 를 10일씩 나눠 쪽을 넘겨 모두 받는다."""
out: list[dict[str, Any]] = []
s = lo
while s <= hi:
e = min(hi, s + timedelta(days=CHUNK_DAYS - 1))
for page in range(1, MAX_PAGES + 1):
body = self._get(ctx, path, {"fromDate": s.strftime("%Y%m%d"), "toDate": e.strftime("%Y%m%d"),
"pageIdx": page, "rowsPerPage": ROWS_PER_PAGE})
rows = _rows(body)
out.extend(rows)
if not body.get("hasMorePage") or not rows:
break
ctx.progress.step(items=len(out))
s = e + timedelta(days=1)
return out
# ── 수집 ──────────────────────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
"""매출인식일이 [start, end] 인 매출 내역 줄. 같은 사건 ID 가 두 번 나오면 뒤에 번호를 붙여 둘 다 남긴다."""
ctx.progress.plan(max(1, ((end - start).days + CHUNK_DAYS) // CHUNK_DAYS), "구간")
seen: dict[str, int] = {}
for r in self._pages(ctx, SALES_PATH, start, end):
day = _yyyymmdd(r.get("saleAwareDt"))
if day is None or not (start <= day <= end):
continue
base = f"{r.get('ordNo')}-{r.get('ordItemNo')}-{r.get('ordType') or 'SALE'}-{day.strftime('%Y%m%d')}"
n = seen.get(base, 0)
seen[base] = n + 1
yield {**r, "_day": day, "_id": base if n == 0 else f"{base}-{n + 1}"}
def normalize_order(self, r: dict[str, Any]) -> list[SaleEvent]:
"""매출 내역 한 줄 → SALE(ordType=SALE) 또는 RETURN(그 밖, 음수). 금액 = supGiveAmt(협력사 지급액 — 포털 주문 통계 금액)."""
oid, day = str(r.get("ordNo") or ""), r.get("_day")
if not oid or day is None:
return []
kind = str(r.get("ordType") or "SALE").upper()
amount = abs(_won(r.get("supGiveAmt")))
is_sale = kind == "SALE"
return [SaleEvent(
event_type="SALE" if is_sale else "RETURN", external_event_id=f"{EVENT_PREFIX}{r['_id']}",
external_order_id=oid, external_line_id=str(r.get("ordItemNo") or ""), event_date=day,
payment_date=day if is_sale else None, amount=amount if is_sale else -amount,
product_name=str(r.get("prdNm") or "")[:200], quantity=abs(_won(r.get("chrQty"))),
discount_amount=abs(_won(r.get("dcTotAmt"))), order_status=kind[:50],
raw={"salePrice": _won(r.get("salePrice")), "custChrAmt": _won(r.get("custChrAmt")),
"orgOrdNo": str(r.get("orgOrdNo") or ""), "prdCd": str(r.get("prdCd") or "")},
)]
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
self.authenticate(ctx)
sup, _ = self._creds(ctx)
self._mode.pop(sup, None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다
day = today_kst() - timedelta(days=1)
body = self._get(ctx, DAILY_SALES_PATH, {"stdDate": day.strftime("%Y%m%d"), "pageIdx": 1, "rowsPerPage": 10})
total = body.get("totalCount")
return (f"GS샵 연결 정상(매출 내역 조회 확인, 어제 매출 {total if total is not None else len(_rows(body))}건, "
f"토큰 {self._how_label(sup)}).")
def _how_label(self, sup: str) -> str:
v, m = self._mode.get(sup, ("", ""))
return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}"
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""매출 내역·배송비 내역을 기간(최대 31일, 10일씩)으로 실제 불러 항목별 합계를 돌려준다(저장 안 함).
응답 항목 이름이 개발가이드에 없어 협력사 포털 매출 화면과 맞는 항목을 실데이터로 확정하는 용도."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
probes = []
got: dict[str, list[dict[str, Any]]] = {}
for key, label, path in (("sales", "매출 내역(매출인식일 기준)", SALES_PATH),
("shipping", "배송비 내역(매출인식일 기준)", SHIPPING_PATH)):
row: dict[str, Any] = {"key": key, "label": label, "path": path}
try:
rows = self._pages(ctx, path, day, to)
except AdapterError as exc:
probes.append({**row, "ok": False, "error": exc.message[:300]})
continue
got[key] = rows
probes.append({**row, "ok": True, "count": len(rows), "fields": field_summary([_strs(r) for r in rows])})
# 날짜별 현재 규칙 매출(supGiveAmt, SALE 아닌 줄은 음수) — 협력사 포털 매출 화면과 나란히 비교
days = []
d = day
while d <= to:
sales = [r for r in got.get("sales", []) if _yyyymmdd(r.get("saleAwareDt")) == d]
ret = [r for r in sales if str(r.get("ordType") or "SALE").upper() != "SALE"]
amt = sum(abs(_won(r.get("supGiveAmt"))) for r in sales if r not in ret) - sum(abs(_won(r.get("supGiveAmt"))) for r in ret)
days.append({"date": d.isoformat(), "orders": len({str(r.get("ordNo")) for r in sales if r not in ret}),
"amount": amt, "claimed": sum(abs(_won(r.get("supGiveAmt"))) for r in ret),
"ship": sum(_won(r.get("salePrice")) for r in got.get("shipping", [])
if _yyyymmdd(r.get("saleAwareDt")) == d)})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"day_cols": {"claimed": "그중 취소·반품(음수로 반영)", "ship": "배송비(참고, 매출 제외)"},
"rule": "매출인식일 기준 매출 내역 supGiveAmt(협력사 지급액 = 포털 주문 통계 금액) 합, SALE 이 아닌 줄은 빼기, "
"배송비 제외. 주문 통계는 주문일 기준이라 날마다 같지는 않고 기간이 길수록 가까워진다"}