fix(performance): 11번가 원본 데이터 확인 — "해당 건 없음"은 0건, 기간 조회·구매확정 후보
9/9 확인 결과: 취소·반품 주소는 코드 -1 "해당 건이 없습니다"(= 0건)인데 실패로 표시했고, 주문 목록 4개는 지금 그 상태인 주문만 주는 듯해 이미 구매확정된 9/9 주문이 어디에도 없었다. 정산 내역은 정산확정일 기준일 가능성이 있다. - 결과 문구가 "해당 건이 없습니다" 류면 오류가 아니라 0건 - 기간 조회(최대 31일, 7일씩 나눠 호출) — 매출일부터 정산확정일까지 넓게 확인 - 구매확정 목록 후보 주소 추가 - 테스트 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import date
|
||||
from datetime import date, timedelta
|
||||
from typing import Any
|
||||
|
||||
from .base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
|
||||
@@ -65,8 +65,12 @@ PROBE_PATHS: tuple[tuple[str, str, str], ...] = (
|
||||
("canceledorders", "취소완료", "/rest/claimservice/canceledorders/{s}/{e}"),
|
||||
("returnorders", "반품신청", "/rest/claimservice/returnorders/{s}/{e}"),
|
||||
("returnedorders", "반품완료", "/rest/claimservice/returnedorders/{s}/{e}"),
|
||||
("settlement", "정산 내역", "/rest/settlement/settlementList/{d}/{d}"),
|
||||
("purchaseconfirm", "구매확정(후보)", "/rest/ordservices/purchaseconfirm/{s}/{e}"),
|
||||
("settlement", "정산 내역", "/rest/settlement/settlementList/{ds}/{de}"),
|
||||
)
|
||||
NO_DATA = re.compile(r"해당\s*건이\s*없|조회된?\s*(내역|건|데이터)이?\s*없") # 코드 -1 이어도 "0건"
|
||||
PROBE_CHUNK_DAYS = 7
|
||||
PROBE_MAX_DAYS = 31
|
||||
|
||||
# 개인정보로 보이는 항목 — 값은 보이지 않고 이름만(이름·연락처·주소·우편번호·아이디·메일·메모)
|
||||
PERSONAL = re.compile(r"(nm|name|tel|tlphn|phone|hp|addr|zip|mail|id|memo|msg|pcc|clearance|birth)$|rcvr|ordnm|buyer",
|
||||
@@ -139,29 +143,40 @@ class ElevenstAdapter(MarketplaceAdapter):
|
||||
raise ApiError(f"11번가 API 오류({res.status_code}): {detail}")
|
||||
if code == "not-xml":
|
||||
raise ApiError(f"11번가가 예상하지 못한 응답을 돌려줬습니다(XML 아님): {res.text[:120].strip()}")
|
||||
if code and code not in ("0", "200", "00"):
|
||||
if code and code not in ("0", "200", "00") and not NO_DATA.search(text):
|
||||
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
|
||||
return res.content
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "11번가 원본 데이터 확인") ─────────
|
||||
def reconcile(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
|
||||
"""후보 조회 주소마다 그날(00:00~23:59) 실제로 불러 동작 여부·주문 수·항목별 합계를 돌려준다.
|
||||
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||
"""후보 조회 주소마다 기간(day~to, 최대 31일, 7일씩 나눠)을 실제로 불러 동작 여부·줄 수·항목별 합계를 돌려준다.
|
||||
셀러 API 상세 문서가 로그인 뒤에만 있어, 어느 주소·항목이 셀러오피스 화면 매출과 맞는지 실데이터로 확정하는 용도.
|
||||
개인정보 항목(이름·연락처·주소·아이디 등)은 값 없이 이름만."""
|
||||
self.authenticate(ctx)
|
||||
d = day.strftime("%Y%m%d")
|
||||
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||
chunks = []
|
||||
s = day
|
||||
while s <= to:
|
||||
e = min(to, s + timedelta(days=PROBE_CHUNK_DAYS - 1))
|
||||
chunks.append((s, e))
|
||||
s = e + timedelta(days=1)
|
||||
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}
|
||||
row: dict[str, Any] = {"key": key, "label": label, "path": tmpl.split("/{")[0] + "/…"}
|
||||
records: list[dict[str, str]] = []
|
||||
error = ""
|
||||
for s, e in chunks:
|
||||
ds, de = s.strftime("%Y%m%d"), e.strftime("%Y%m%d")
|
||||
try:
|
||||
records += xml_records(self._get(ctx, tmpl.format(s=f"{ds}0000", e=f"{de}2359", ds=ds, de=de)))
|
||||
except AdapterError as exc:
|
||||
error = exc.message[:200]
|
||||
break
|
||||
if error:
|
||||
out.append({**row, "ok": False, "error": error})
|
||||
else:
|
||||
out.append({**row, "ok": True, "count": len(records), "fields": field_summary(records)})
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": out}
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
@@ -279,13 +279,13 @@ def api_test_connection(request: Request, code: str, payload: dict[str, Any] = B
|
||||
|
||||
|
||||
@router.get("/api/marketplaces/{code}/reconcile")
|
||||
def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date")) -> JSONResponse:
|
||||
def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse:
|
||||
"""쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
|
||||
store, user = common.require_store(request, admin=True)
|
||||
_code_or_404(store, code)
|
||||
day = _parse_date(date_)
|
||||
_, sync = common.services(request, store)
|
||||
return JSONResponse(sync.reconcile(code, day, user=user["email"]))
|
||||
return JSONResponse(sync.reconcile(code, day, to=_parse_date(to, field="종료일"), user=user["email"]))
|
||||
|
||||
|
||||
@router.get("/api/marketplaces/{code}/daily-check")
|
||||
|
||||
@@ -139,7 +139,7 @@ class SyncService:
|
||||
return [self.sync_marketplace(c, start, end, trigger=trigger, user=user) for c in targets]
|
||||
|
||||
# ── 쇼핑몰 화면과 대조 ────────────────────────────────
|
||||
def reconcile(self, code: str, day: date, *, user: str = "") -> dict[str, Any]:
|
||||
def reconcile(self, code: str, day: date, *, to: date | None = None, user: str = "") -> dict[str, Any]:
|
||||
"""어댑터가 지원하면(reconcile) 그날 원천 금액을 항목별로 합산해 돌려준다. DB 는 바꾸지 않는다."""
|
||||
adapter = get_adapter(code)
|
||||
if adapter is None or not hasattr(adapter, "reconcile"):
|
||||
@@ -147,7 +147,7 @@ class SyncService:
|
||||
ctx = None
|
||||
try:
|
||||
ctx = self._ctx(adapter, user=user)
|
||||
return {"ok": True, **adapter.reconcile(ctx, day)}
|
||||
return {"ok": True, **(adapter.reconcile(ctx, day, to=to) if to else adapter.reconcile(ctx, day))}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
status, message = self._failure(exc, ctx)
|
||||
return {"ok": False, "status": status, "label": STATUS_LABELS.get(status, status), "message": message}
|
||||
|
||||
@@ -239,4 +239,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930u" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
|
||||
|
||||
@@ -118,11 +118,14 @@
|
||||
|
||||
<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 class="perf-muted">11번가 셀러 API 의 주문·클레임·정산 조회 주소를 기간(최대 31일)으로 실제 불러, 어느 주소가 동작하는지와
|
||||
받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 주문 목록은 지금 그 상태인 주문만, 정산은 정산일 기준일 수 있어
|
||||
매출이 있던 날부터 넉넉히(예: 3주) 잡아 주세요. 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
|
||||
매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.</p>
|
||||
<div class="perf-sample-form">
|
||||
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" id="perf-probe-to" 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>
|
||||
@@ -167,4 +170,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930u" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
|
||||
|
||||
@@ -861,14 +861,22 @@ def test_elevenst_connection():
|
||||
def route(url, headers=None, timeout=None):
|
||||
if "/ordservices/complete/" in url:
|
||||
return httpx.Response(200, content=rows)
|
||||
if "/ordservices/purchaseconfirm/" in url:
|
||||
return httpx.Response(404, content=b"<html>not found</html>")
|
||||
if "/ordservices/" in url:
|
||||
return httpx.Response(200, content=b"<ns2:orders xmlns:ns2='x'/>")
|
||||
if "/claimservice/" in url:
|
||||
return httpx.Response(200, content="<ns2:orders xmlns:ns2='x'><ns2:result_code>-1</ns2:result_code>"
|
||||
"<ns2:result_text>해당 건이 없습니다.</ns2:result_text></ns2:orders>".encode())
|
||||
return httpx.Response(404, content=b"<html>not found</html>")
|
||||
httpx.get = route
|
||||
rec = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 29))
|
||||
wide = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 1), to=date(2026, 9, 20)) # 7일씩 3번
|
||||
assert wide["to"] == "2026-09-20" and {p["key"]: p.get("count") for p in wide["probes"]}["complete"] == 6
|
||||
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"]
|
||||
assert not by["purchaseconfirm"]["ok"] and "404" in by["purchaseconfirm"]["error"]
|
||||
assert by["canceledorders"]["ok"] and by["canceledorders"]["count"] == 0 # 코드 -1 "해당 건이 없습니다" = 0건
|
||||
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)
|
||||
|
||||
@@ -833,9 +833,11 @@
|
||||
const out = document.getElementById("perf-probe-result");
|
||||
if (!day) return;
|
||||
probe.disabled = true;
|
||||
out.innerHTML = '<p class="perf-muted">11번가에서 불러오는 중… (주소 9개)</p>';
|
||||
out.innerHTML = '<p class="perf-muted">11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)</p>';
|
||||
try {
|
||||
const r = await api("GET", "/performance/api/marketplaces/" + probe.dataset.code + "/reconcile?date=" + encodeURIComponent(day));
|
||||
const to = document.getElementById("perf-probe-to").value || day;
|
||||
const r = await api("GET", "/performance/api/marketplaces/" + probe.dataset.code + "/reconcile?date=" + encodeURIComponent(day) +
|
||||
"&to=" + encodeURIComponent(to));
|
||||
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>' +
|
||||
|
||||
Reference in New Issue
Block a user