From 7d96f2e738c120a54a2cf0c317e4e5879c01a55a Mon Sep 17 00:00:00 2001 From: king Date: Wed, 30 Sep 2026 01:14:32 +0900 Subject: [PATCH] =?UTF-8?q?fix(performance):=2011=EB=B2=88=EA=B0=80=20?= =?UTF-8?q?=EC=9B=90=EB=B3=B8=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8=20=E2=80=94=20"=ED=95=B4=EB=8B=B9=20=EA=B1=B4=20?= =?UTF-8?q?=EC=97=86=EC=9D=8C"=EC=9D=80=200=EA=B1=B4,=20=EA=B8=B0=EA=B0=84?= =?UTF-8?q?=20=EC=A1=B0=ED=9A=8C=C2=B7=EA=B5=AC=EB=A7=A4=ED=99=95=EC=A0=95?= =?UTF-8?q?=20=ED=9B=84=EB=B3=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 9/9 확인 결과: 취소·반품 주소는 코드 -1 "해당 건이 없습니다"(= 0건)인데 실패로 표시했고, 주문 목록 4개는 지금 그 상태인 주문만 주는 듯해 이미 구매확정된 9/9 주문이 어디에도 없었다. 정산 내역은 정산확정일 기준일 가능성이 있다. - 결과 문구가 "해당 건이 없습니다" 류면 오류가 아니라 0건 - 기간 조회(최대 31일, 7일씩 나눠 호출) — 매출일부터 정산확정일까지 넓게 확인 - 구매확정 목록 후보 주소 추가 - 테스트 갱신 Co-Authored-By: Claude Opus 5.5 --- app/modules/performance/adapters/elevenst.py | 47 ++++++++++++------- app/modules/performance/router.py | 4 +- app/modules/performance/sync.py | 4 +- .../templates/performance/index.html | 2 +- .../templates/performance/settings.html | 9 ++-- .../performance/tests/test_performance.py | 10 +++- app/static/performance.js | 6 ++- 7 files changed, 55 insertions(+), 27 deletions(-) diff --git a/app/modules/performance/adapters/elevenst.py b/app/modules/performance/adapters/elevenst.py index 7416777..c3cabf9 100644 --- a/app/modules/performance/adapters/elevenst.py +++ b/app/modules/performance/adapters/elevenst.py @@ -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 diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index e7e408c..cbec390 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -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") diff --git a/app/modules/performance/sync.py b/app/modules/performance/sync.py index b0c1792..12f01d8 100644 --- a/app/modules/performance/sync.py +++ b/app/modules/performance/sync.py @@ -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} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index eb8094b..d5bc6c3 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -239,4 +239,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html index 98537f4..3c3f8fd 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -118,11 +118,14 @@

11번가 원본 데이터 확인

-

11번가 셀러 API 의 주문·클레임 조회 주소를 그날(00:00~23:59)로 실제 불러, 어느 주소가 동작하는지와 - 받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 +

11번가 셀러 API 의 주문·클레임·정산 조회 주소를 기간(최대 31일)으로 실제 불러, 어느 주소가 동작하는지와 + 받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 주문 목록은 지금 그 상태인 주문만, 정산은 정산일 기준일 수 있어 + 매출이 있던 날부터 넉넉히(예: 3주) 잡아 주세요. 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.

+ ~ +
@@ -167,4 +170,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index 4989d20..c0a7820 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -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"not found") if "/ordservices/" in url: return httpx.Response(200, content=b"") + if "/claimservice/" in url: + return httpx.Response(200, content="-1" + "해당 건이 없습니다.".encode()) return httpx.Response(404, content=b"not found") 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) diff --git a/app/static/performance.js b/app/static/performance.js index 841c81a..7dcc954 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -833,9 +833,11 @@ const out = document.getElementById("perf-probe-result"); if (!day) return; probe.disabled = true; - out.innerHTML = '

11번가에서 불러오는 중… (주소 9개)

'; + out.innerHTML = '

11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)

'; 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 = '

' + esc((r.label ? r.label + " — " : "") + r.message) + "

"; return; } const summary = '' + '' +
조회주소결과건수