feat(performance): 11번가 원본 데이터 확인 도구 — 후보 조회 주소별 동작·항목 합계
11번가 셀러 API 의 주문·클레임 상세 문서는 로그인 뒤에만 있어 조회 주소와 금액 항목 이름을 공개 자료로 확정할 수 없다. 추측으로 매출 수집을 짜지 않고 실데이터로 확정하기 위해: - ElevenstAdapter.reconcile(day): 결제완료·발송대상·배송중·배송완료·취소신청· 취소완료·반품신청·반품완료·정산 후보 주소를 그날로 호출 → 동작 여부(404 등 오류), 건수, 항목별 채워진 줄·숫자 합계·예시 값. 개인정보 항목은 이름만(값 숨김) - 설정 화면 "11번가 원본 데이터 확인" 카드 - 테스트 추가 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,9 +13,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import re
|
import re
|
||||||
import xml.etree.ElementTree as ET
|
import xml.etree.ElementTree as ET
|
||||||
|
from datetime import date
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .base import AdapterContext, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
|
from .base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
|
||||||
|
|
||||||
HOST = "https://api.11st.co.kr"
|
HOST = "https://api.11st.co.kr"
|
||||||
|
|
||||||
@@ -53,6 +54,62 @@ def xml_result(content: bytes) -> tuple[str, str, int]:
|
|||||||
return code, text, orders
|
return code, text, orders
|
||||||
|
|
||||||
|
|
||||||
|
# 원본 데이터 확인용 후보 주소 — {s}/{e} = yyyyMMddHHmm, {d} = yyyyMMdd. 문서 미확인 경로가 섞여 있어
|
||||||
|
# 404 등 실패도 그대로 보여 준다(어느 주소가 살아 있는지 확인하는 것이 목적).
|
||||||
|
PROBE_PATHS: tuple[tuple[str, str, str], ...] = (
|
||||||
|
("complete", "결제완료(발주확인 전)", "/rest/ordservices/complete/{s}/{e}"),
|
||||||
|
("packaging", "발송처리 대상(발주확인 후)", "/rest/ordservices/packaging/{s}/{e}"),
|
||||||
|
("shipping", "배송중", "/rest/ordservices/shipping/{s}/{e}"),
|
||||||
|
("completed", "배송완료", "/rest/ordservices/completed/{s}/{e}"),
|
||||||
|
("cancelorders", "취소신청", "/rest/claimservice/cancelorders/{s}/{e}"),
|
||||||
|
("canceledorders", "취소완료", "/rest/claimservice/canceledorders/{s}/{e}"),
|
||||||
|
("returnorders", "반품신청", "/rest/claimservice/returnorders/{s}/{e}"),
|
||||||
|
("returnedorders", "반품완료", "/rest/claimservice/returnedorders/{s}/{e}"),
|
||||||
|
("settlement", "정산 내역", "/rest/settlement/settlementList/{d}/{d}"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 개인정보로 보이는 항목 — 값은 보이지 않고 이름만(이름·연락처·주소·우편번호·아이디·메일·메모)
|
||||||
|
PERSONAL = re.compile(r"(nm|name|tel|tlphn|phone|hp|addr|zip|mail|id|memo|msg|pcc|clearance|birth)$|rcvr|ordnm|buyer",
|
||||||
|
re.IGNORECASE)
|
||||||
|
NUMBER = re.compile(r"^-?\d+(\.\d+)?$")
|
||||||
|
SAFE = re.compile(r"^(prd|opt|slct|dlvEtprs|dlvMthd|clm|reason|stl|sel)", re.IGNORECASE) # 상품·옵션·클레임 사유 등은 보임
|
||||||
|
|
||||||
|
|
||||||
|
def xml_records(content: bytes) -> list[dict[str, str]]:
|
||||||
|
"""응답에서 주문(또는 클레임·정산) 한 줄씩 — 자식이 모두 글자 항목인 요소를 한 줄로 본다(태그 끝 이름 → 값)."""
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(_xml_text(content))
|
||||||
|
except ET.ParseError:
|
||||||
|
return []
|
||||||
|
out: list[dict[str, str]] = []
|
||||||
|
for el in root.iter():
|
||||||
|
kids = list(el)
|
||||||
|
if len(kids) >= 3 and all(len(k) == 0 for k in kids):
|
||||||
|
out.append({k.tag.rsplit("}", 1)[-1]: (k.text or "").strip() for k in kids})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def field_summary(records: list[dict[str, str]]) -> list[dict[str, Any]]:
|
||||||
|
"""항목별: 채워진 줄 수, 숫자면 합계, 개인정보 아니면 예시 값 하나."""
|
||||||
|
names: dict[str, dict[str, Any]] = {}
|
||||||
|
for r in records:
|
||||||
|
for k, v in r.items():
|
||||||
|
f = names.setdefault(k, {"name": k, "filled": 0, "numeric": True, "sum": 0.0, "sample": "",
|
||||||
|
"personal": bool(PERSONAL.search(k)) and not SAFE.match(k)})
|
||||||
|
if not v:
|
||||||
|
continue
|
||||||
|
f["filled"] += 1
|
||||||
|
if NUMBER.match(v) and f["numeric"]:
|
||||||
|
f["sum"] += float(v)
|
||||||
|
else:
|
||||||
|
f["numeric"] = False
|
||||||
|
if not f["sample"] and not f["personal"]:
|
||||||
|
f["sample"] = v[:40]
|
||||||
|
for f in names.values():
|
||||||
|
f["sum"] = int(round(f["sum"])) if f["numeric"] and f["filled"] else None
|
||||||
|
return list(names.values())
|
||||||
|
|
||||||
|
|
||||||
class ElevenstAdapter(MarketplaceAdapter):
|
class ElevenstAdapter(MarketplaceAdapter):
|
||||||
code = "elevenst"
|
code = "elevenst"
|
||||||
name = "11번가"
|
name = "11번가"
|
||||||
@@ -86,6 +143,26 @@ class ElevenstAdapter(MarketplaceAdapter):
|
|||||||
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
|
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
|
||||||
return res.content
|
return res.content
|
||||||
|
|
||||||
|
# ── 원본 데이터 확인(설정 화면 "11번가 원본 데이터 확인") ─────────
|
||||||
|
def reconcile(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
|
||||||
|
"""후보 조회 주소마다 그날(00:00~23:59) 실제로 불러 동작 여부·주문 수·항목별 합계를 돌려준다.
|
||||||
|
셀러 API 상세 문서가 로그인 뒤에만 있어, 어느 주소·항목이 셀러오피스 화면 매출과 맞는지 실데이터로 확정하는 용도.
|
||||||
|
개인정보 항목(이름·연락처·주소·아이디 등)은 값 없이 이름만."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
d = day.strftime("%Y%m%d")
|
||||||
|
out = []
|
||||||
|
for key, label, tmpl in PROBE_PATHS:
|
||||||
|
path = tmpl.format(s=f"{d}0000", e=f"{d}2359", d=d)
|
||||||
|
row: dict[str, Any] = {"key": key, "label": label, "path": path.split("/" + d)[0] + "/…"}
|
||||||
|
try:
|
||||||
|
body = self._get(ctx, path)
|
||||||
|
except AdapterError as exc:
|
||||||
|
out.append({**row, "ok": False, "error": exc.message[:200]})
|
||||||
|
continue
|
||||||
|
records = xml_records(body)
|
||||||
|
out.append({**row, "ok": True, "count": len(records), "fields": field_summary(records)})
|
||||||
|
return {"date": day.isoformat(), "probes": out}
|
||||||
|
|
||||||
def test_connection(self, ctx: AdapterContext) -> str:
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
from app.timezone import today_kst # noqa: WPS433
|
from app.timezone import today_kst # noqa: WPS433
|
||||||
|
|
||||||
|
|||||||
@@ -239,4 +239,4 @@
|
|||||||
} | tojson }}</script>
|
} | tojson }}</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20260930t" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20260930u" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -116,6 +116,18 @@
|
|||||||
<div class="perf-notice" id="perf-backfill-result" hidden></div>
|
<div class="perf-notice" id="perf-backfill-result" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card perf-card perf-card-wide">
|
||||||
|
<div class="perf-card-head"><h2 class="perf-h">11번가 원본 데이터 확인</h2></div>
|
||||||
|
<p class="perf-muted">11번가 셀러 API 의 주문·클레임 조회 주소를 그날(00:00~23:59)로 실제 불러, 어느 주소가 동작하는지와
|
||||||
|
받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
|
||||||
|
매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.</p>
|
||||||
|
<div class="perf-sample-form">
|
||||||
|
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe" data-code="elevenst">불러오기</button>
|
||||||
|
</div>
|
||||||
|
<div id="perf-probe-result"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="erp-card perf-card perf-card-wide">
|
<div class="erp-card perf-card perf-card-wide">
|
||||||
<div class="perf-card-head"><h2 class="perf-h">카페24 매출 대조</h2></div>
|
<div class="perf-card-head"><h2 class="perf-h">카페24 매출 대조</h2></div>
|
||||||
<p class="perf-muted">카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
|
<p class="perf-muted">카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
|
||||||
@@ -155,4 +167,4 @@
|
|||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20260930t" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20260930u" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -852,6 +852,26 @@ def test_elevenst_connection():
|
|||||||
assert status == 403 or "허용되지 않은 IP" in exc.message or "XML 아님" in exc.message
|
assert status == 403 or "허용되지 않은 IP" in exc.message or "XML 아님" in exc.message
|
||||||
else:
|
else:
|
||||||
raise AssertionError("오류여야 합니다")
|
raise AssertionError("오류여야 합니다")
|
||||||
|
# 원본 데이터 확인: 살아 있는 주소는 항목 합계, 없는 주소(404)는 실패로. 개인정보 값은 숨김
|
||||||
|
rows = ("<ns2:orders xmlns:ns2='x'>" + "".join(
|
||||||
|
f"<ns2:order><ordNo>{n}</ordNo><ordPayAmt>{a}</ordPayAmt><rcvrNm>홍길동</rcvrNm><prdNm>상품{n}</prdNm>"
|
||||||
|
f"<ordStlEndDt>2026-09-29 10:00:00</ordStlEndDt></ns2:order>" for n, a in ((1, 10000), (2, 5500))) +
|
||||||
|
"</ns2:orders>").encode()
|
||||||
|
|
||||||
|
def route(url, headers=None, timeout=None):
|
||||||
|
if "/ordservices/complete/" in url:
|
||||||
|
return httpx.Response(200, content=rows)
|
||||||
|
if "/ordservices/" in url:
|
||||||
|
return httpx.Response(200, content=b"<ns2:orders xmlns:ns2='x'/>")
|
||||||
|
return httpx.Response(404, content=b"<html>not found</html>")
|
||||||
|
httpx.get = route
|
||||||
|
rec = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 29))
|
||||||
|
by = {p["key"]: p for p in rec["probes"]}
|
||||||
|
assert by["complete"]["ok"] and by["complete"]["count"] == 2 and by["shipping"]["count"] == 0
|
||||||
|
assert not by["canceledorders"]["ok"] and "404" in by["canceledorders"]["error"]
|
||||||
|
f = {x["name"]: x for x in by["complete"]["fields"]}
|
||||||
|
assert f["ordPayAmt"]["sum"] == 15_500 and f["rcvrNm"]["personal"] and f["rcvrNm"]["sample"] == ""
|
||||||
|
assert f["prdNm"]["sample"] == "상품1" and "홍길동" not in repr(rec)
|
||||||
finally:
|
finally:
|
||||||
httpx.get = orig
|
httpx.get = orig
|
||||||
|
|
||||||
|
|||||||
@@ -826,6 +826,39 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── 11번가 원본 데이터 확인 — 후보 조회 주소별 동작 여부·항목 합계 ──
|
||||||
|
const probe = document.getElementById("perf-probe");
|
||||||
|
if (probe) probe.addEventListener("click", async function () {
|
||||||
|
const day = document.getElementById("perf-probe-date").value;
|
||||||
|
const out = document.getElementById("perf-probe-result");
|
||||||
|
if (!day) return;
|
||||||
|
probe.disabled = true;
|
||||||
|
out.innerHTML = '<p class="perf-muted">11번가에서 불러오는 중… (주소 9개)</p>';
|
||||||
|
try {
|
||||||
|
const r = await api("GET", "/performance/api/marketplaces/" + probe.dataset.code + "/reconcile?date=" + encodeURIComponent(day));
|
||||||
|
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; return; }
|
||||||
|
const summary = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">조회</th>' +
|
||||||
|
'<th class="perf-th-label">주소</th><th class="perf-th-label">결과</th><th>건수</th></tr></thead><tbody>' +
|
||||||
|
r.probes.map(function (p) {
|
||||||
|
return '<tr><td class="perf-td-label">' + esc(p.label) + '</td><td class="perf-muted">' + esc(p.path) + "</td><td>" +
|
||||||
|
(p.ok ? '<span class="perf-pill is-ok">동작</span>' : '<span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(p.error) + "</span>") +
|
||||||
|
'</td><td class="perf-num">' + (p.ok ? fmt(p.count) : "") + "</td></tr>";
|
||||||
|
}).join("") + "</tbody></table>";
|
||||||
|
const details = r.probes.filter(function (p) { return p.ok && p.count; }).map(function (p) {
|
||||||
|
return '<h4 class="perf-h" style="margin:14px 0 6px">' + esc(p.label) + " — " + fmt(p.count) + "줄</h4>" +
|
||||||
|
'<table class="perf-table"><thead><tr><th class="perf-th-label">항목</th><th>채워진 줄</th><th>숫자 합계</th>' +
|
||||||
|
'<th class="perf-th-label">예시 값</th></tr></thead><tbody>' +
|
||||||
|
p.fields.map(function (f) {
|
||||||
|
return '<tr><td class="perf-td-label">' + esc(f.name) + '</td><td class="perf-num">' + fmt(f.filled) + '</td><td class="perf-num">' +
|
||||||
|
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
|
||||||
|
}).join("") + "</tbody></table>";
|
||||||
|
}).join("");
|
||||||
|
out.innerHTML = summary + (details || '<p class="perf-muted" style="margin-top:8px">그날 조회된 주문이 없습니다. 셀러오피스에서 매출이 있던 날로 다시 해 보세요.</p>');
|
||||||
|
} catch (err) {
|
||||||
|
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||||
|
} finally { probe.disabled = false; }
|
||||||
|
});
|
||||||
|
|
||||||
// ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
|
// ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
|
||||||
const backfill = document.getElementById("perf-backfill");
|
const backfill = document.getElementById("perf-backfill");
|
||||||
if (backfill) backfill.addEventListener("click", async function () {
|
if (backfill) backfill.addEventListener("click", async function () {
|
||||||
|
|||||||
Reference in New Issue
Block a user