diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py index 6c90731..5abd9a5 100644 --- a/app/modules/performance/adapters/cafe24.py +++ b/app/modules/performance/adapters/cafe24.py @@ -50,6 +50,12 @@ MAX_OFFSET = 15000 CHUNK_DAYS = 60 EVENT_PREFIX = "c24:" +# 매출 대조 전용 — 클레임 완료 주문 조회 날짜 유형과 "완료" 상태(입금전취소 C47~49 는 결제 전이라 제외) +CLAIM_DATE_TYPES = (("cancel_complete_date", "취소완료"), ("return_complete_date", "반품완료"), + ("exchange_complete_date", "교환완료")) +CLAIM_DONE = frozenset({"C40", "C41", "C42", "C43", "R40", "R41", "R42", "R43", "E40"}) +UNPAID_CANCEL = frozenset({"C47", "C48", "C49"}) + # 카페24 자체몰 주문 채널 — market_id 는 외부 마켓만이 아니라 주문 채널·간편결제도 담는다 # (실데이터 확인 2026-09-30: mobile=모바일웹, NCHECKOUT=네이버페이, KAKAOPAY=톡체크아웃). # 이 주문들은 카페24 자체몰 매출이다. 비교는 소문자로. @@ -251,6 +257,55 @@ class Cafe24Adapter(MarketplaceAdapter): {"start_date": s.isoformat(), "end_date": e.isoformat(), "date_type": date_type}, REFUND_LIMIT) + def claim_items(self, ctx: AdapterContext, day: date) -> dict[str, Any]: + """그날 취소완료·반품완료·교환완료된 주문의 클레임 품목(대조 전용). 환불 API 에 안 잡히는 건 + (네이버페이 취소 등)을 찾기 위한 것. 조회 실패는 errors 에 담고 계속한다. 개인정보 제외.""" + items: list[dict[str, Any]] = [] + errors: list[str] = [] + seen: set[str] = set() + full_cancel_shipping = 0 + for date_type, label in CLAIM_DATE_TYPES: + try: + orders = list(self._paged(ctx, "/admin/orders", "orders", + {"start_date": day.isoformat(), "end_date": day.isoformat(), + "date_type": date_type, "embed": "items"}, ORDER_LIMIT)) + except ApiError as exc: + errors.append(f"{label}: {exc}") + continue + for o in orders: + oid = str(o.get("order_id") or "") + its = o.get("items") or [] + claimed = [i for i in its if str(i.get("order_status") or "")[:1] in ("C", "R", "E") + and str(i.get("order_status") or "") not in UNPAID_CANCEL] + if claimed and len(claimed) == len(its) and oid not in seen and \ + all(str(i.get("order_status") or "") in CLAIM_DONE and str(i.get("order_status"))[:1] == "C" for i in its): + full_cancel_shipping += order_amounts(o)["shipping_fee"] + for i in claimed: + key = str(i.get("order_item_code") or f"{oid}-{i.get('item_no')}") + if key in seen: + continue + seen.add(key) + status = str(i.get("order_status") or "") + qty = int(i.get("quantity") or 0) + items.append({ + "via": label, "order_id": oid, "item_code": key, + "channel": str(o.get("order_place_name") or o.get("market_id") or ""), + "paid": o.get("paid") == "T", "pay_date": str(o.get("payment_date") or "")[:10], + "status": status, "status_text": str(i.get("status_text") or ""), + "done": status in CLAIM_DONE, + "claim_code": str(i.get("claim_code") or ""), + "product_name": str(i.get("product_name") or "")[:40], "quantity": qty, + "product_amount": (_won(i.get("product_price")) + _won(i.get("option_price"))) * qty, + "payment_amount": _won(i.get("payment_amount")), + "coupon": _won(i.get("coupon_discount_price")), + "naver_pay_claim_status": str(i.get("naver_pay_claim_status") or ""), + "cancel_date": str(i.get("cancel_date") or "")[:16], + "refund_date": str(i.get("refund_date") or "")[:16], + "return_confirmed_date": str(i.get("return_confirmed_date") or "")[:16], + }) + seen.add(oid) + return {"items": items, "errors": errors, "full_cancel_shipping": full_cancel_shipping} + def market_ids(self, ctx: AdapterContext, refunds: list[dict[str, Any]]) -> dict[str, tuple[Any, Any, Any]]: """환불의 원 주문 (market_id, order_place_id, order_place_name) — 주문일 60일 구간·100건씩 묶어 조회. 못 찾으면 자체몰.""" @@ -420,8 +475,60 @@ class Cafe24Adapter(MarketplaceAdapter): for s in sorted({str(x.get("status") or "") for x in accepted}) ], } + + # 환불 건별 목록(완료일 기준 + 접수일 기준, 환불코드로 합침) — 개인정보(이메일·계좌) 제외 + extra = markets | self.market_ids(ctx, [a for a in accepted if str(a.get("order_id")) not in markets]) + refund_list: dict[str, dict[str, Any]] = {} + for basis, items in (("completed", rows), ("accepted", accepted)): + for x in items: + code = str(x.get("refund_code") or "") + mid, place, place_name = extra.get(str(x.get("order_id")), ("self", None, None)) + e = refund_list.setdefault(code, { + "refund_code": code, "order_id": str(x.get("order_id") or ""), + "channel": str(place_name or mid or ""), "status": str(x.get("status") or ""), + "accepted_date": str(x.get("accepted_refund_date") or "")[:16].replace("T", " "), + "refund_date": str(x.get("refund_date") or "")[:16].replace("T", " "), + "quantity": int(x.get("quantity") or 0), + "actual_refund_amount": _won(x.get("actual_refund_amount")), + "used_points": _won(x.get("used_points")), "used_credits": _won(x.get("used_credits")), + "cancel_fee_amount": _won(x.get("cancel_fee_amount")), + "methods": [str(m) for m in (x.get("refund_methods") or []) if m], + "in_completed": False, "in_accepted": False, + }) + e["in_" + basis] = True + + claims = self.claim_items(ctx, day) + refunded_orders = {r["order_id"] for r in refund_list.values()} + for c in claims["items"]: + c["has_refund"] = c["order_id"] in refunded_orders + + def csum(pred) -> dict[str, int]: + sel = [c for c in claims["items"] if c["done"] and pred(c)] + return {"count": len(sel), "payment_amount": sum(c["payment_amount"] for c in sel), + "product_amount": sum(c["product_amount"] for c in sel)} + + comp = refund_basis["completed"] + no_refund = csum(lambda c: not c["has_refund"]) + claimed = csum(lambda c: True) + # 카페24 "환불합계" 후보 — 화면 값과 같은 줄을 찾는다(화면에서 값을 입력하면 강조) + candidates = [ + {"key": "completed", "label": "환불완료일 · 실제 환불액 (현재 적용)", "amount": comp["actual_refund_amount"]}, + {"key": "completed_pts", "label": "환불완료일 · 실제 환불액 + 적립금·예치금", "amount": comp["with_points"]}, + {"key": "accepted", "label": "환불접수일(전체 상태) · 실제 환불액", "amount": refund_basis["accepted_all"]["actual_refund_amount"]}, + {"key": "accepted_pts", "label": "환불접수일(전체 상태) · 실제 + 적립금·예치금", "amount": refund_basis["accepted_all"]["with_points"]}, + {"key": "claim_pay", "label": "취소·반품·교환 완료 품목 · 품목 결제금액", "amount": claimed["payment_amount"]}, + {"key": "claim_prod", "label": "취소·반품·교환 완료 품목 · 판매가(+옵션)×수량", "amount": claimed["product_amount"]}, + {"key": "claim_pay_ship", "label": "완료 품목 결제금액 + 전체취소 주문 배송비", + "amount": claimed["payment_amount"] + claims["full_cancel_shipping"]}, + {"key": "completed_plus_noref", "label": "환불완료 실제 환불액 + 환불 기록 없는 완료 품목 결제금액", + "amount": comp["actual_refund_amount"] + no_refund["payment_amount"]}, + {"key": "completed_pts_plus_noref", "label": "환불완료 (실제+적립금) + 환불 기록 없는 완료 품목 결제금액", + "amount": comp["with_points"] + no_refund["payment_amount"]}, + ] return {"date": day.isoformat(), "orders": groups, "refunds": refunds, "unpaid_orders": unpaid, "by_channel": channels_out, "refund_basis": refund_basis, + "refund_list": sorted(refund_list.values(), key=lambda r: r["refund_code"]), + "claims": claims, "refund_candidates": candidates, "by_payment": sorted(by_payment.values(), key=lambda v: v["total"], reverse=True), "formula": "결제합계 = 상품구매금액 + 배송비 − 할인(" + ", ".join(DISCOUNT_FIELDS) + ") − 쿠폰(" + ", ".join(COUPON_FIELDS) + ")"} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 3aec4ae..32d9c25 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} @@ -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 40789dd..d8883f5 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%} @@ -143,4 +143,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 7e96d23..31e48b1 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -407,8 +407,9 @@ def _c24_refund(code, oid, amount, status="T", order_date="2026-09-20T09:00:00+0 class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist=["Cafe24Adapter"]).Cafe24Adapter): - def __init__(self, orders_pages, refunds_pages=(), lookup=None): + def __init__(self, orders_pages, refunds_pages=(), lookup=None, claims=None): self.orders_pages = orders_pages # 결제일 조회 페이지들 + self.claims = claims or {} # date_type(취소/반품/교환 완료일) → 주문 목록 self.refunds_pages = list(refunds_pages) self.lookup = lookup or {} # order_id → market_id (환불 원 주문 조회) self.calls = [] @@ -424,6 +425,8 @@ class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist if params.get("date_type") == "order_date": # 원 주문 market_id 조회 ids = params["order_id"].split(",") return {"orders": [{"order_id": i, "market_id": self.lookup.get(i, "self")} for i in ids]} + if params.get("date_type", "").endswith("_complete_date"): + return {"orders": self.claims.get(params["date_type"], []) if idx == 0 else []} return {"orders": self.orders_pages[idx] if idx < len(self.orders_pages) else []} @@ -485,7 +488,32 @@ def test_cafe24_normalize_matches_daily_report(): assert rb["completed"]["count"] == 3 and rb["completed"]["actual_refund_amount"] == 12_610 + 20_000 + 9_000 assert rb["accepted_all"]["count"] == 4 and rb["accepted_all"]["with_points"] == 12_610 + 20_000 + 9_000 + 5_000 assert {s["status"]: s["count"] for s in rb["accepted_by_status"]} == {"T": 3, "F": 1} - # 기기: PC 채널(self)이어도 휴대폰 주문(order_from_mobile=T)은 모바일 + assert {c["key"] for c in rec["refund_candidates"]} >= {"completed", "completed_pts", "claim_pay"} + assert {r["refund_code"] for r in rec["refund_list"]} == {"C20260929-01", "R20260929-02", "C20260929-03", "C20260929-04"} + assert "1234567890" not in str(rec["refund_list"]) # 환불 계좌 미노출 + # 클레임 완료 품목: 환불 API 에 없는 취소(네이버페이 등)를 찾는다. 입금전취소·미완료는 합계 제외 + item = lambda code, st, pay, price=10_000, qty=1: {"order_item_code": code, "order_status": st, "quantity": qty, + "product_price": f"{price}.00", "option_price": "0.00", + "payment_amount": f"{pay}.00", "product_name": "상품"} + fake4 = _FakeCafe24([[]], [[_c24_refund("C1", "A", 9_000)]], claims={ + "cancel_complete_date": [ + {**_c24_order("A"), "items": [item("A-01", "C40", 9_000)]}, + {**_c24_order("N"), "market_id": "NCHECKOUT", "items": [item("N-01", "C40", 19_800, 20_000), item("N-02", "C40", 5_000, 5_000)]}, + {**_c24_order("U"), "items": [item("U-01", "C48", 7_000)]}, + {**_c24_order("P"), "items": [item("P-01", "C34", 3_000), item("P-02", "N40", 4_000)]}], + "return_complete_date": [{**_c24_order("N"), "items": [item("N-01", "C40", 19_800, 20_000)]}, + {**_c24_order("R"), "items": [item("R-01", "R40", 12_000, 6_000, 2)]}], + }) + rec4 = fake4.reconcile(ctx, date(2026, 9, 29)) + cl = {c["item_code"]: c for c in rec4["claims"]["items"]} + assert set(cl) == {"A-01", "N-01", "N-02", "P-01", "R-01"} # 입금전취소(U)·정상 품목 제외, 중복 제거 + assert cl["A-01"]["has_refund"] and not cl["N-01"]["has_refund"] and not cl["P-01"]["done"] + assert cl["R-01"]["product_amount"] == 12_000 + assert rec4["claims"]["full_cancel_shipping"] == 3_000 * 2 # A, N 전체취소(배송비 3,000씩) + cand = {c["key"]: c["amount"] for c in rec4["refund_candidates"]} + assert cand["claim_pay"] == 9_000 + 19_800 + 5_000 + 12_000 + assert cand["completed_plus_noref"] == 9_000 + 19_800 + 5_000 + 12_000 + # 기기: PC 채널(self)이어도 휴대폰 주문(order_from_mobile=T)은 모바일 assert ch["self"]["mobile_orders"] == 1 and ch["self"]["pc_orders"] == 0 and ch["self"]["mobile_total"] == 47_000 assert ch["NCHECKOUT"]["pc_orders"] == 1 and ch["mobile"]["mobile_orders"] == 1 # self 는 PC 전용이 아니다 — 주문경로(PC쇼핑몰/모바일웹)별로 한 줄씩(실데이터 확인) diff --git a/app/static/performance.css b/app/static/performance.css index 66e2ee4..d30ba31 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -208,3 +208,5 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; } .perf-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } .perf-update { margin-left: 0; } } + +.perf-table tr.perf-row-match > *{background:#e7f6ec;font-weight:600} diff --git a/app/static/performance.js b/app/static/performance.js index 3db180a..76803df 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -541,6 +541,47 @@ }).join("") + ""; })() : "") + + ((r.refund_candidates || []).length + ? '
| 후보 | 금액 | 차이 |
|---|---|---|
| ' + esc(c.label) + ' | ' + + won(c.amount) + ' | – |
| 환불코드 | 주문번호 | ' + + '채널 | 상태 | 접수일 | 완료일 | ' + + "수량 | 실제 환불액 | 적립금·예치금 | 환불수단 |
|---|---|---|---|---|---|---|---|---|---|
| ' + esc(x.refund_code) + " | " + esc(x.order_id) + " | " + esc(x.channel || "–") + + " | " + esc(st) + " | " + esc(x.accepted_date || "–") + " | " + esc(x.refund_date || "–") + + ' | ' + fmt(x.quantity) + ' | ' + won(x.actual_refund_amount) + + ' | ' + won(x.used_points + x.used_credits) + " | " + esc((x.methods || []).join(", ") || "–") + " |
' + esc(r.claims.errors.join(" / ")) + "
" : "") + + ((r.claims.items || []).length + ? '| 조회 | 주문번호 | ' + + '채널 | 상태 | 클레임 | 상품 | ' + + "수량 | 판매가×수량 | 품목 결제금액 | 쿠폰 | 환불 기록 |
|---|---|---|---|---|---|---|---|---|---|---|
| ' + esc(c.via) + " | " + esc(c.order_id) + + " | " + esc(c.channel || "–") + " | " + esc(c.status + (c.status_text ? " " + c.status_text : "")) + + " | " + esc(c.claim_code || "–") + " | " + esc(c.product_name) + ' | ' + fmt(c.quantity) + + ' | ' + won(c.product_amount) + ' | ' + won(c.payment_amount) + + ' | ' + won(c.coupon) + " | " + (c.has_refund ? "있음" : '없음') + " |
전체취소 주문 배송비 ' + won(r.claims.full_cancel_shipping) + + '. 흐린 줄은 아직 완료되지 않은 클레임(후보 합계에서 제외).
' + : '없음
') + : "") + ((r.by_channel || []).length ? '| market_id | 주문경로 | ' + @@ -586,6 +627,17 @@ : "") + '
|---|