From 01000757f34bccd6598ec03bbdaae23224009fb5 Mon Sep 17 00:00:00 2001 From: king Date: Thu, 1 Oct 2026 10:16:29 +0900 Subject: [PATCH] =?UTF-8?q?feat(performance):=20=ED=86=A0=EC=8A=A4?= =?UTF-8?q?=EC=87=BC=ED=95=91=20=EC=9B=90=EB=B3=B8=20=EB=8D=B0=EC=9D=B4?= =?UTF-8?q?=ED=84=B0=20=ED=99=95=EC=9D=B8=EC=97=90=20=ED=99=98=EB=B6=88=20?= =?UTF-8?q?=ED=9B=84=EB=B3=B4=203=EA=B0=80=EC=A7=80(=EC=A0=95=EC=82=B0=20R?= =?UTF-8?q?EFUND=C2=B7=EC=A3=BC=EB=AC=B8=20=EC=B7=A8=EC=86=8C=20=EC=8B=9C?= =?UTF-8?q?=EA=B0=81=C2=B7=ED=81=B4=EB=A0=88=EC=9E=84=20=ED=99=98=EB=B6=88?= =?UTF-8?q?=20=EC=99=84=EB=A3=8C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 9/6 실데이터: 매출 29,600 일치, 환불 11,900 은 정산 건별 REFUND 에 없음(다른 날 주문을 9/6 에 환불) - 후보 ① 정산 REFUND(현재 규칙) ② orders/v2 canceledAt(기간 90일 전 주문까지) ③ claims refundedDt(isRefunded) — 날짜별 합계를 나란히 + 건별(주문번호·금액·메모), 화면 숫자와 같은 후보로 규칙을 정한다 - 클레임 목록 개인정보(연락처·수거 주소·요청 사유·사진) 값·합계 숨김, 송장번호 합계도 숨김 - performance.js 캐시 버전 20261001c, 테스트·문서 갱신 Co-Authored-By: Claude Opus 5.5 --- app/modules/performance/adapters/toss.py | 94 ++++++++++++++++++- .../templates/performance/index.html | 2 +- .../templates/performance/settings.html | 2 +- .../performance/tests/test_performance.py | 24 ++++- app/static/performance.js | 26 ++++- docs/PERFORMANCE_MODULE.md | 6 ++ 6 files changed, 145 insertions(+), 9 deletions(-) diff --git a/app/modules/performance/adapters/toss.py b/app/modules/performance/adapters/toss.py index f58ca87..cf644b7 100644 --- a/app/modules/performance/adapters/toss.py +++ b/app/modules/performance/adapters/toss.py @@ -77,7 +77,14 @@ STATUS_KO = { PERSONAL_KEYS = frozenset({ "ordererName", "ordererPhone", "ordererRealPhone", "receiverName", "receiverPhone", "receiverRealPhone", "address", "detailAddress", "zipCode", "shippingNote", "shippingTrackingNumber", + # 클레임 목록(order.* · 수거 주소 · 요청 사유 자유 입력 · 첨부 사진) + "ordererPhoneNumber", "receiverPhoneNumber", "returnAddress", "requestReason", "requestDetailReason", + "requestImages[]", }) +CLAIMS_PATH = "/api/v3/shopping-fep/claims" +CLAIM_PAGE_SIZE = 100 +CLAIM_MAX_PAGES = 100 # 클레임 목록은 날짜로 못 거른다(전체를 넘긴다) — 1만 건까지 +CANCEL_LOOKBACK_DAYS = 90 # 환불 후보(주문 취소 시각): 이만큼 전 주문까지 본다 def _won(value: Any) -> int: @@ -158,14 +165,42 @@ def refund_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list return out +def cancel_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]: + """환불 후보 — 주문 내역의 취소 시각(canceledAt 한국 날짜)이 [start, end] 인 주문상품. 금액 = price(판매가 × 수량).""" + out = [] + for it in items: + day = kst_day(it.get("canceledAt")) + if not it.get("orderId") or day is None or not (start <= day <= end): + continue + status = str(it.get("orderProductStatus") or "") + out.append({"orderId": str(it["orderId"]), "orderProductId": str(it.get("orderProductId") or ""), "_day": day, + "amount": _won(it.get("price")), "note": f"{STATUS_KO.get(status, status)} · 주문일 " + f"{kst_day(it.get('orderedAt')) or '?'}"}) + return out + + +def claim_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]: + """환불 후보 — 클레임 목록의 환불 완료(isRefunded, refundedDt 한국 날짜)가 [start, end] 인 것. + 금액 = order.price(문서: "상품 가격" — 수량을 곱한 값인지 실데이터로 확인), 수량은 note 에.""" + out = [] + for it in items: + day = kst_day(it.get("refundedDt")) + order = it.get("order") if isinstance(it.get("order"), dict) else {} + product = it.get("product") if isinstance(it.get("product"), dict) else {} + if not it.get("isRefunded") or day is None or not (start <= day <= end) or not order.get("id"): + continue + out.append({"orderId": str(order["id"]), "orderProductId": str(order.get("orderProductId") or ""), "_day": day, + "amount": _won(order.get("price")), "note": f"{it.get('type') or '?'}/{it.get('status') or '?'} · " + f"수량 {_won(product.get('quantity'))} · 주문일 {kst_day(order.get('createdDt')) or '?'}"}) + return out + + def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: - """원본 확인 표 — 항목별 채워진 줄·숫자 합계·예시 값(개인정보·자유 입력 항목은 값 숨김).""" + """원본 확인 표 — 항목별 채워진 줄·숫자 합계·예시 값(개인정보·자유 입력 항목은 값·합계 숨김).""" fields = field_summary([flatten(r) for r in rows]) for f in fields: - if f["name"] in PERSONAL_KEYS: - f["personal"], f["sample"] = True, "" - if not f["numeric"]: - f["sum"] = None + if f["name"].rsplit(".", 1)[-1] in PERSONAL_KEYS: + f["personal"], f["sample"], f["sum"] = True, "", None return fields @@ -331,6 +366,19 @@ class TossAdapter(MarketplaceAdapter): break return out + def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]: + """클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지.""" + out: list[dict[str, Any]] = [] + token = None + for _ in range(CLAIM_MAX_PAGES): + body = self._get(ctx, CLAIMS_PATH, {"size": CLAIM_PAGE_SIZE, **({"nextToken": token} if token else {})}) + rows = [r for r in body.get("items") or [] if isinstance(r, dict)] + out.extend(rows) + token = body.get("nextToken") + if not token or not rows or body.get("hasNext") is False: + break + return out + @staticmethod def _windows(start: date, end: date) -> list[tuple[date, date]]: windows = [] @@ -445,6 +493,41 @@ class TossAdapter(MarketplaceAdapter): + (" — 환불(순 거래액에서 뺌)" if kind == "REFUND" else ""), "path": "stepType", "ok": True, "count": len(rows), "fields": [f for f in summary(rows) if f["sum"] is not None]}) + + # ── 환불 후보 세 가지 — 파트너스 화면 "환불"과 어느 쪽이 같은지 날짜별로 나란히(실데이터로 규칙 확정용) ── + candidates: list[dict[str, Any]] = [ + {"key": "settlement", "label": "① 정산 REFUND 상품 줄(거래일) — 현재 규칙", "rows": refunds, "error": settle_err}] + # ② 주문 취소 시각 — 기간보다 CANCEL_LOOKBACK_DAYS 전 주문까지 본다(다른 날 주문을 이 기간에 취소한 것) + look_from = day - timedelta(days=CANCEL_LOOKBACK_DAYS) + try: + back = [r for a, b in self._windows(look_from, day - timedelta(days=1)) for r in self._window_items(ctx, a, b)] + canceled = cancel_rows(back + items, day, to) + cand_err = "" + except AdapterError as exc: + canceled, cand_err = [], exc.message[:300] + candidates.append({"key": "canceled", "label": f"② 주문 취소 시각(canceledAt, {CANCEL_LOOKBACK_DAYS}일 전 주문까지)", + "rows": canceled, "error": cand_err}) + # ③ 클레임 환불 완료 시각 — 클레임 목록은 날짜로 못 거른다(전체를 받아 refundedDt 로 거름) + try: + claims = self._claims(ctx) + claimed = claim_rows(claims, day, to) + probes.append({"key": "claims", "label": "클레임 목록(전체 — 날짜 조건 없음)", "path": CLAIMS_PATH, "ok": True, + "count": len(claims), "fields": summary(claims)}) + cand_err = "" + except AdapterError as exc: + claimed, cand_err = [], exc.message[:300] + probes.append({"key": "claims", "label": "클레임 목록", "path": CLAIMS_PATH, "ok": False, "error": cand_err}) + candidates.append({"key": "claims", "label": "③ 클레임 환불 완료(refundedDt, 금액 order.price)", + "rows": claimed, "error": cand_err}) + for c in candidates: + c["days"] = {} + for r in c["rows"]: + k = r["_day"].isoformat() + c["days"][k] = c["days"].get(k, 0) + r["amount"] + c["rows"] = [{"date": r["_day"].isoformat(), "orderId": r["orderId"], "orderProductId": r["orderProductId"], + "amount": r["amount"], "note": r.get("note") or f"정산 REFUND · 주문일 {r.get('order_day') or '?'}"} + for r in sorted(c["rows"], key=lambda x: (x["_day"], x["orderId"]))][:200] + days = [] orders = group_orders(items, day, to) d = day @@ -456,6 +539,7 @@ class TossAdapter(MarketplaceAdapter): "ship": sales - refund}) d += timedelta(days=1) return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days, + "refund_candidates": candidates, "day_cols": {"amount": "매출(주문일)", "claimed": "환불(환불일)", "ship": "순 거래액(저장되는 매출)"}, "rule": "순 거래액 = 매출 − 환불. 매출 = 주문일(orderedAt) 기준 주문상품 price(판매가 × 수량) 합(할인 전, " "배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외). 환불 = 정산 건별 REFUND 상품 줄의 " diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 49aa57c..8ee5001 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 9450650..520a0b2 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -179,4 +179,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 35a0ad0..49b7c55 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -568,10 +568,23 @@ def test_toss_reconcile_hides_personal(): _toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)] steps = [_toss_step("REFUND", 2, 21, "2026-09-10T11:00:00", -9900), _toss_step("REFUND", 2, None, "2026-09-10T11:00:00", -3000)] + # 다른 날(8/20) 주문을 9/10 에 취소 — 기간 앞(90일) 주문 조회에서만 보인다 + old = {**_toss_item(7, 71, "2026-08-20T10:00:00", 11900, status="CANCELED_PAYMENT"), "canceledAt": "2026-09-10T09:00:00"} + claims = [{"id": 1, "type": "RETURN", "status": "COMPLETED", "isRefunded": True, "refundedDt": "2026-09-10T12:00:00", + "requestReason": "단순 변심 010-5555-6666", "returnAddress": "서울시 반품동", + "order": {"id": 8, "orderProductId": 81, "price": 5000, "createdDt": "2026-08-25T10:00:00", + "ordererName": "홍길동", "ordererPhoneNumber": "010-1234-5678"}, + "product": {"id": 3, "name": "밀폐용기", "quantity": 1}}, + {"id": 2, "type": "CANCEL", "status": "REQUESTED", "isRefunded": False, "order": {"id": 9, "price": 777}}] + def get(url, params=None, headers=None, timeout=None): if url.endswith("/settlement-steps"): return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": steps, "nextToken": None}}) - return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": None}}) + if url.endswith("/claims"): + return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": claims, "nextToken": None, + "hasNext": False}}) + found = rows if params["startDate"] >= "2026-09-09" else [old] if params["startDate"] <= "2026-08-20" <= params["endDate"] else [] + return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}}) orig = (httpx.get, ts.CALL_INTERVAL_SEC) httpx.get, ts.CALL_INTERVAL_SEC = get, 0 @@ -594,6 +607,15 @@ def test_toss_reconcile_hides_personal(): labels = [p["label"] for p in rec["probes"]] assert any("결제 뒤 취소·반품(매출 포함)" in x for x in labels) assert any(x.startswith("정산 REFUND — 환불") for x in labels) and any("배송비 줄" in x for x in labels) + # 환불 후보 세 가지 — 날짜별 합계 + 건별 + cand = {c["key"]: c for c in rec["refund_candidates"]} + assert cand["settlement"]["days"] == {"2026-09-10": 9900} + assert cand["canceled"]["days"] == {"2026-09-10": 11900} and cand["canceled"]["rows"][0]["orderId"] == "7" + assert "주문일 2026-08-20" in cand["canceled"]["rows"][0]["note"] + assert cand["claims"]["days"] == {"2026-09-10": 5000} and len(cand["claims"]["rows"]) == 1 # 환불 안 된 클레임 제외 + cf = {x["name"]: x for x in next(p for p in rec["probes"] if p["key"] == "claims")["fields"]} + assert cf["requestReason"]["personal"] and cf["returnAddress"]["personal"] and cf["order.ordererPhoneNumber"]["personal"] + assert "010-5555-6666" not in repr(rec) and "반품동" not in repr(rec) def test_not_implemented_and_mock(): diff --git a/app/static/performance.js b/app/static/performance.js index 0475473..97ff1ee 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -1008,7 +1008,31 @@ ["orders", "amount", "claimed", "ship"].map(function (k) { return '' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + ""; }).join("") + "" : ""; - out.innerHTML = summary + days + (details || '

그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.

'); + // 환불 후보(토스쇼핑) — 후보별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모) + const rc = r.refund_candidates || []; + const candDays = (r.days || []).map(function (d) { return d.date; }); + const cands = rc.length ? '

환불 후보 — 쇼핑몰 화면 "환불"과 같은 열을 알려 주세요

' + + '' + + rc.map(function (c) { return ""; }).join("") + "" + + candDays.map(function (dt) { + return '" + rc.map(function (c) { + return '"; + }).join("") + ""; + }).join("") + '' + rc.map(function (c) { + if (c.error) return '"; + const t = Object.keys(c.days || {}).reduce(function (a, k) { return a + c.days[k]; }, 0); + return '"; + }).join("") + "
날짜" + esc(c.label) + "
' + esc(dt) + "' + (c.error ? "" : fmt((c.days || {})[dt] || 0)) + "
합계실패 ' + esc(c.error) + "' + fmt(t) + "
" + + rc.filter(function (c) { return !c.error && (c.rows || []).length; }).map(function (c) { + return '

' + esc(c.label) + " — " + fmt(c.rows.length) + "건

" + + '' + + '' + + c.rows.map(function (x) { + return '"; + }).join("") + "
날짜주문번호주문상품금액메모
' + esc(x.date) + "" + esc(x.orderId) + "" + esc(x.orderProductId) + + '' + fmt(x.amount) + '' + esc(x.note) + "
"; + }).join("") : ""; + out.innerHTML = summary + days + cands + (details ||'

그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.

'); } catch (err) { out.innerHTML = '

' + esc(err.message) + "

"; } finally { probe.disabled = false; } diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 6924dc3..bba03cb 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -171,6 +171,12 @@ 클레임 목록 API 는 날짜로 거를 수 없고(REQUESTED·REVOKED 만 7일 조회) 결제완료 단계의 고객 취소는 클레임으로 안 잡혀서 쓰지 않는다. - `replace_range`(접두어 `toss:` — 매출·환불 함께 교체). 진행 막대 = 주문 + 정산 31일 구간 수. 개인정보(주문자·수령인·주소·요청사항· 송장)는 저장 안 함. +- **실데이터 대조(2026-10-01, 9/6)**: 매출 29,600 = 주문 2건 `price` 합 **일치**(`orderedAt` 은 시간대 없이 한국 시간 — + 17:57 주문도 9/6). 환불 11,900 은 **정산 REFUND 에 없다**(9/6 거래일 정산 = PAY 2줄 + 배송비 2줄뿐, 9/6 주문은 둘 다 구매확정) → + 다른 날 주문을 9/6 에 환불한 건이 정산 건별에 안 나온다(구매확정 전 취소는 정산에 안 올라오는 듯). 그래서 원본 데이터 확인에 + **환불 후보 세 가지**(`refund_candidates`)를 날짜별로 나란히: ① 정산 REFUND(현재 규칙) ② 주문 `canceledAt`(기간 90일 전 주문까지 + 조회) ③ 클레임 목록 `refundedDt`(`isRefunded`, 금액 `order.price` — 클레임 목록은 날짜 조건이 없어 전체를 넘겨 거름, 최대 1만 건) + + 건별(주문번호·금액·메모). 화면 11,900 과 같은 후보로 수집 규칙을 바꾼다(**미확정**). - 정산 줄의 다른 항목: 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`, 수수료 `payFee`·`productFee`. - 대조: 설정 화면 "쇼핑몰 원본 데이터 확인" → 토스쇼핑 — 날짜별 **매출(주문일)·환불(환불일)·순 거래액**(`day_cols`)과 주문 상태별· 정산 stepType 별 항목 합계. 파트너스 화면 숫자와 다르면 금액 항목(`price` / `price − totalDiscountPrice`, 환불 `orderProductPrice` /