Merge branch 'feat/performance' into feat/project — GS샵 매출 수집

This commit is contained in:
2026-09-30 14:53:29 +09:00
6 changed files with 152 additions and 11 deletions
+84 -3
View File
@@ -13,8 +13,17 @@
매출(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(같은 조건).
응답 줄의 항목 이름은 개발가이드 예시에 없어("property1") 설정 화면 "쇼핑몰 원본 데이터 확인"으로 실데이터를 보고
매출 규칙을 확정한다 — 그 전까지 매출 수집(fetch_orders)은 "연동 준비 중".
응답 줄 항목(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 문서에 주문 조회 없음) — 협력사 포털 주문 통계(총주문금액, 주문일)와는 기준이 달라
날짜별로 똑같이 맞출 수 없다.
매출 규칙(주문 통계의 금액도 할인 후 고객 결제 기준 — 7호세트 195,075 ÷ 5 = 39,015 = 45,900 × 85%):
- 매출 내역 한 줄 = 사건 하나(`gs:{ordNo}-{ordItemNo}-{ordType}-{saleAwareDt}`), 날짜 = 매출인식일.
- 금액 = custChrAmt(할인 후 고객 결제금액), 배송비 제외(네이버와 같은 기준). ordType 이 SALE 이 아니면(취소·반품 등)
음수로(RETURN). 할인 = dcTotAmt. 기간을 통째로 다시 받는다(replace_range).
"""
from __future__ import annotations
@@ -31,6 +40,7 @@ from .base import (
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
)
from .elevenst import field_summary
@@ -98,10 +108,33 @@ def _strs(row: dict[str, Any]) -> dict[str, str]:
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 입니다.")
@@ -187,6 +220,38 @@ class GsshopAdapter(MarketplaceAdapter):
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(그 밖, 음수). 금액 = custChrAmt(할인 후 고객 결제금액)."""
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("custChrAmt")))
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")), "supGiveAmt": _won(r.get("supGiveAmt")),
"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
@@ -210,6 +275,7 @@ class GsshopAdapter(MarketplaceAdapter):
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}
@@ -218,5 +284,20 @@ class GsshopAdapter(MarketplaceAdapter):
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])})
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes}
# 날짜별 현재 규칙 매출(custChrAmt, 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("custChrAmt"))) for r in sales if r not in ret) - sum(abs(_won(r.get("custChrAmt"))) 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("custChrAmt"))) 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": "매출인식일 기준 매출 내역 custChrAmt(할인 후 고객 결제금액) 합, SALE 이 아닌 줄은 빼기, 배송비 제외"}
@@ -239,4 +239,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930z" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930za" defer></script>{% endblock %}
@@ -177,4 +177,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930z" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930za" defer></script>{% endblock %}
@@ -1287,6 +1287,59 @@ def test_gsshop_token_connection_and_probe():
httpx.get = orig
def test_gsshop_collect_sales():
"""GS샵 매출 = 매출 내역 custChrAmt(할인 후 고객 결제금액), 매출인식일 기준, 배송비 제외.
SALE 이 아닌 줄은 음수(RETURN). 실데이터 9/3: 16,400 − 820 = 15,580 모양."""
import httpx
from app.modules.performance.adapters import gsshop as gs
key = "0123456789abcdef0123456789ABCDEF"
def line(no, item, day, sale, dc, typ="SALE", qty=1):
return {"rnum": 1, "saleAwareDt": day, "prdCd": 1064149860, "prdNm": "미라클통 황토 3200ml", "supCd": 1047142,
"ordNo": no, "ordItemNo": item, "orgOrdNo": no, "ordType": typ, "chrQty": qty, "salePrice": sale,
"dcTotAmt": dc, "custChrAmt": sale - dc, "supGiveAmt": int((sale - dc) * 0.9)}
rows = [line(3470403225, 1, 20260903, 16400, 820), line(3470403225, 2, 20260903, 32800, 1640, qty=2),
line(3470409999, 1, 20260904, 20000, 0, typ="RTN"), line(3470500000, 1, 20260912, 9900, 0)]
def get(url, params=None, headers=None, timeout=None):
if url.endswith("/shippingFee/period"):
return httpx.Response(200, json={"data": [{"saleAwareDt": 20260903, "prdNm": "배송비상품", "ordType": "SALE",
"ordNo": 3470403225, "ordItemNo": 3, "salePrice": 3500}],
"hasMorePage": False})
lo, hi = int(params["fromDate"]), int(params["toDate"])
return httpx.Response(200, json={"data": [r for r in rows if lo <= r["saleAwareDt"] <= hi], "hasMorePage": False})
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "gsshop"), {"vendor_code": "1047142", "api_key": key})
orig = httpx.get
httpx.get = get
try:
r = SyncService(st, creds).sync_marketplace("gsshop", date(2026, 9, 3), date(2026, 9, 4))
finally:
httpx.get = orig
assert r["ok"], r
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "gsshop"}
assert set(ev_) == {"gs:3470403225-1-SALE-20260903", "gs:3470403225-2-SALE-20260903", "gs:3470409999-1-RTN-20260904"}
assert ev_["gs:3470403225-1-SALE-20260903"]["amount"] == 15580 and ev_["gs:3470403225-1-SALE-20260903"]["discount_amount"] == 820
assert ev_["gs:3470403225-2-SALE-20260903"]["quantity"] == 2
ret = ev_["gs:3470409999-1-RTN-20260904"]
assert ret["event_type"] == "RETURN" and ret["amount"] == -20000 and ret["sales_date"] == date(2026, 9, 4)
assert sum(v["amount"] for v in ev_.values()) == 15580 + 31160 - 20000 # 배송비 3,500 제외
httpx.get = get
try:
rec = gs.GsshopAdapter().reconcile(__import__("app.modules.performance.adapters.base", fromlist=["x"]).AdapterContext(
code="gsshop", credentials=creds.accessor("gsshop")), date(2026, 9, 3), to=date(2026, 9, 4))
finally:
httpx.get = orig
assert rec["days"][0] == {"date": "2026-09-03", "orders": 1, "amount": 46740, "claimed": 0, "ship": 3500}
assert rec["days"][1]["amount"] == -20000 and rec["days"][1]["claimed"] == 20000
if __name__ == "__main__":
os.environ.pop("APP_ENCRYPTION_KEY", None)
n = 0
+3 -2
View File
@@ -963,8 +963,9 @@
// 날짜별 현재 규칙 매출(네이버) — 쇼핑몰 관리자 화면 매출과 나란히 비교
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
'<table class="perf-table"><thead><tr><th class="perf-th-label">결제일</th><th>주문 수</th><th>매출</th>' +
"<th>그중 결제 뒤 취소·반품(참고)</th><th>배송비(참고, 매출 제외)</th></tr></thead><tbody>" +
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>매출</th>' +
"<th>" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "</th><th>" +
esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "</th></tr></thead><tbody>" +
r.days.map(function (d) {
return '<tr><td class="perf-td-label">' + esc(d.date) + '</td><td class="perf-num">' + fmt(d.orders) +
'</td><td class="perf-num">' + fmt(d.amount) + '</td><td class="perf-num">' + fmt(d.claimed || 0) +
+10 -4
View File
@@ -29,7 +29,7 @@
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
**연동 현황**: 카페24·11번가·네이버 스마트스토어 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 단계에서 공식 API 문서로 확정**한다.
### 카페24 (`adapters/cafe24.py`, 구현됨)
@@ -125,7 +125,7 @@
- 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택): 결제일 기준 상품주문 전체의 항목별 합계, 상태별 합계, 날짜별
매출·그중 결제 뒤 취소/반품(참고)·배송비(참고). 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만.
### GS샵 (`adapters/gsshop.py`, 연결·원본 확인까지 — 매출 규칙 확정 전)
### GS샵 (`adapters/gsshop.py`, 구현됨)
- 문서: 협력사 포털 → 제휴 API → 개발가이드(`partners.gsshop.com/api/apiDevGuide`, 본문은 `/docs/withgs-api-docs.html` Redoc).
- 인증: 헤더 `supCd`(협력사코드) + `token` = base64(AES256(`yyyyMMddHHmmss` + 협력사코드)), 키는 제휴 API 메인 화면(로그인 후).
@@ -135,8 +135,14 @@
`atwithgs-api` 는 테스트용 — 두 곳 모두 응답). 입력칸 키는 처음 만든 `vendor_code`·`api_key` 그대로(라벨만 협력사코드·AES256 키).
- 매출: `GET /api/v2/settlement/out/sales/period?supCode&fromDate&toDate&pageIdx&rowsPerPage` — **매출인식일** 기준, 한 번에 10일,
쪽당 1만 건, `{data, hasMorePage, totalCount}`. 배송비는 `/shippingFee/period`. 응답 줄 항목 이름이 문서 예시에 없어
("property1") 설정 화면 "쇼핑몰 원본 데이터 확인"(GS샵)으로 항목별 합계를 보고 협력사 포털 매출 화면과 맞춰 규칙을 정한다.
그 전까지 매출 수집은 "연동 준비 중"(`implemented=False`).
("property1") 실데이터로 확인(2026-09-30, 9/3): `saleAwareDt`·`ordNo`·`ordItemNo`·`ordType`(SALE…)·`prdNm`·`chrQty`·
`salePrice`(할인 전, 줄 합계)·`dcTotAmt`·`custChrAmt`(= salePrice − dcTotAmt, 고객 결제금액)·`supGiveAmt`(협력사 지급액).
9/3: 211,100 − 19,528 = 191,572, 지급 179,435, 배송비 내역 7,000.
- **주문일 기준 조회 API 는 없다** — 협력사 포털 주문 통계(총주문금액·주문일, 할인 후 금액: 45,900 × 85% = 39,015)와는 날짜 기준이
달라 날마다 똑같이 맞지 않는다(매출인식일 = 정산 기준).
- **매출 규칙**: 매출 내역 한 줄 = 사건(`gs:{ordNo}-{ordItemNo}-{ordType}-{saleAwareDt}`), 날짜 = 매출인식일, 금액 = `custChrAmt`
(할인 후 고객 결제금액), 배송비 제외(네이버와 같은 기준). `ordType` 이 SALE 이 아니면 RETURN 음수. `replace_range`.
원본 데이터 확인에 날짜별 현재 규칙 매출·취소/반품·배송비(참고).
### 연동 단계 체크리스트(쇼핑몰마다)