fix(performance): 카페24 환불 — 네이버페이만·전체취소 배송비 포함, 0원 결제 주문은 0원

9/4·9/16·9/25 대조 결과:
- 9/4 환불 122,100 = 환불 목록 98,700 + 네이버페이 취소 19,900 + 그 주문 배송비
  3,500 (주문 전체취소) — 우리는 배송비를 빠뜨려 −3,500 (9/14 −7,000 도 같은 유형)
- 9/16 환불 201,100 = 환불 목록 그대로 — 우리가 더 뺀 9,900 은 톡체크아웃
  (KAKAOPAY) 환불 기록 없는 취소. 카페24 는 네이버페이만 센다 (9/21 도 같은 유형)
- 9/25 결제: 실결제·적립금·네이버포인트는 카페24 와 같은데 합계만 +9,900 —
  네 값이 모두 0인 주문(가상계좌·휴대폰 9,900)을 상품식으로 넣었기 때문.
  카페24 는 0원 (9/11 +24,900 도 같은 유형)

- unrefunded_claims: 네이버페이(NCHECKOUT) 주문만, 주문 전체가 취소·반품되면
  배송비(− 배송비 할인·쿠폰)를 마지막 클레임 품목에 한 번 더함
- _paid_total: 상품식 대체 제거
- 대조 표에 품목별 배송비 포함액 표시, 테스트 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-29 23:03:50 +09:00
parent 2f86445077
commit 643ff25f27
6 changed files with 69 additions and 35 deletions
+34 -18
View File
@@ -11,7 +11,7 @@
(initial_order_amount 의 payment_amount·points_spent_amount·credits_spent_amount + 주문의 naver_point)
"상품구매금액 + 배송비 − 할인 − 쿠폰"은 할인 필드에 안 잡히는 차이(수십~수만 원)가 생겨 쓰지 않는다
(2026-09-23 실데이터: 카페24 1,874,738 = 1,713,128 + 10,110 + 151,500, 상품식은 1,874,800).
위 네 값이 모두 0인 주문(0원 결제 등)만 상품식으로 계산한다.
네 값이 모두 0인 주문도 0원(카페24와 같음).
환불은 따로 빼므로 취소 후 금액(actual_order_amount)이 아니라 결제 당시 금액을 쓴다.
- 환불합계(CANCEL/RETURN, −): GET /admin/refunds date_type=refund_date(환불완료일),
실제 환불액(actual_refund_amount). 환불코드가 R 로 시작하면 반품, 그 밖은 취소.
@@ -62,6 +62,7 @@ UNPAID_CANCEL = frozenset({"C47", "C48", "C49"})
# 환불 목록(/admin/refunds)에 없는 취소·반품(네이버페이 등) — 카페24 일별 매출 환불합계에는 들어간다(실데이터 확인)
NO_RECORD_DATE_TYPES = ("cancel_date", "return_complete_date")
NO_RECORD_DONE = frozenset({"C40", "C41", "C42", "C43", "R40", "R41", "R42", "R43"})
NO_RECORD_CHANNEL = "ncheckout" # 네이버페이만 — 톡체크아웃·자체몰의 환불 기록 없는 취소는 카페24 환불합계에 없다
REFUND_LOOKAROUND_DAYS = 60
# 카페24 자체몰 주문 채널 — market_id 는 외부 마켓만이 아니라 주문 채널·간편결제도 담는다
@@ -150,9 +151,9 @@ def goods_total(w: dict[str, int]) -> int:
def _paid_total(w: dict[str, int]) -> int:
"""결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트. 모두 0이면 참고식."""
paid = sum(w[k] for k in PAID_FIELDS) + w["naver_point"]
return paid if paid > 0 else goods_total(w)
"""결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트. 넷 다 0인 주문은 카페24도 0원으로 센다
(9/25 가상계좌·휴대폰 9,900 주문 — 상품식으로 넣으면 그만큼 많아짐)."""
return sum(w[k] for k in PAID_FIELDS) + w["naver_point"]
def order_total(order: dict[str, Any]) -> int:
@@ -369,9 +370,12 @@ class Cafe24Adapter(MarketplaceAdapter):
return {"items": items, "errors": errors, "full_cancel_shipping": full_cancel_shipping}
def unrefunded_claims(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
"""환불 목록에 기록이 없는 취소·반품 완료 품목(네이버페이 취소 등). 날짜 = 품목 취소일(반품은 반품완료일).
금액 = 판매가(+옵션)×수량 − 품목 할인·쿠폰. 앞뒤 60일 환불 목록(완료일·접수일)에 그 주문이 있으면 제외해
환불 목록 쪽과 두 번 빼지 않는다."""
"""환불 목록에 기록이 없는 네이버페이 취소·반품 완료 품목. 날짜 = 품목 취소일(반품은 반품완료일).
금액 = 판매가(+옵션)×수량 − 품목 할인·쿠폰. 주문 전체가 취소·반품되면 배송비(− 배송비 할인·쿠폰)도 환불로
보고 그 주문의 마지막 클레임 품목에 한 번 더한다. 앞뒤 60일 환불 목록(완료일·접수일)에 그 주문이 있으면
제외해 환불 목록 쪽과 두 번 빼지 않는다.
카페24 일별 매출 환불합계와 대조한 결과(2026-09): 네이버페이만 센다 — 톡체크아웃(KAKAOPAY)·자체몰의
환불 기록 없는 취소는 넣지 않는다(9/16 톡체크아웃 취소 9,900 제외, 9/4 네이버페이 전체취소 배송비 3,500 포함)."""
from app.timezone import today_kst # noqa: WPS433
found: dict[str, dict[str, Any]] = {}
@@ -380,32 +384,44 @@ class Cafe24Adapter(MarketplaceAdapter):
for o in self._paged(ctx, "/admin/orders", "orders",
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": date_type, "embed": "items"}, ORDER_LIMIT):
if NO_RECORD_CHANNEL not in (_key(o.get("market_id")), _key(o.get("order_place_id"))):
continue
oid = str(o.get("order_id") or "")
for i in o.get("items") or []:
its = o.get("items") or []
claimed: list[tuple[date, str, dict[str, Any]]] = []
for i in its:
status = str(i.get("order_status") or "")
if status not in NO_RECORD_DONE:
continue
keys = (("cancel_date", "refund_date", "return_confirmed_date") if status[:1] == "C"
else ("return_confirmed_date", "refund_date", "cancel_date"))
day = next((d for d in (_day(i.get(k)) for k in keys) if d), None)
if day is None or not (start <= day <= end):
if day is not None:
claimed.append((day, str(i.get("order_item_code") or f"{oid}-{i.get('item_no')}"), i))
if not claimed:
continue
all_claimed = len(claimed) == len(its)
w = order_amounts(o)
ship = max(0, w["shipping_fee"] - w["coupon_shipping_fee_amount"] - w["shipping_fee_discount_amount"])
last = max((d, k) for d, k, _ in claimed)
for day, key, i in claimed:
if not (start <= day <= end):
continue
key = str(i.get("order_item_code") or f"{oid}-{i.get('item_no')}")
status = str(i.get("order_status") or "")
qty = int(i.get("quantity") or 0)
amount = ((_won(i.get("product_price")) + _won(i.get("option_price"))) * qty
- _won(i.get("additional_discount_price")) - _won(i.get("coupon_discount_price"))
- _won(i.get("app_item_discount_amount")))
amount = max(0, (_won(i.get("product_price")) + _won(i.get("option_price"))) * qty
- _won(i.get("additional_discount_price")) - _won(i.get("coupon_discount_price"))
- _won(i.get("app_item_discount_amount")))
ship_refund = ship if all_claimed and (day, key) == last else 0
found[key] = {
"order_id": oid, "item_code": key, "status": status, "day": day,
"market_id": o.get("market_id"), "place_id": o.get("order_place_id"),
"place_name": o.get("order_place_name"), "order_date": _day(o.get("order_date")),
"quantity": qty, "amount": max(0, amount),
"quantity": qty, "amount": amount + ship_refund, "shipping_refund": ship_refund,
"product_name": str(i.get("product_name") or "")[:40],
"naver_pay_claim_status": str(i.get("naver_pay_claim_status") or ""),
# 대조용 — 주문 전체가 취소·반품됐는지, 그 주문 배송비(배송비 환불 여부 확인)
"order_all_claimed": all(str(x.get("order_status") or "") in NO_RECORD_DONE
for x in o.get("items") or []),
"order_shipping_fee": order_amounts(o)["shipping_fee"],
# 대조용 — 주문 전체가 취소·반품됐는지, 그 주문 배송비
"order_all_claimed": all_claimed, "order_shipping_fee": w["shipping_fee"],
"item_payment_amount": _won(i.get("payment_amount")),
"coupon": _won(i.get("coupon_discount_price")),
}
@@ -239,4 +239,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930o" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930p" defer></script>{% endblock %}
@@ -155,4 +155,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930o" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930p" defer></script>{% endblock %}
@@ -407,11 +407,12 @@ def test_not_implemented_and_mock():
# ════════════════════════════════════════════════════════════
def _c24_order(oid, market="self", paid="T", price=50_000, ship=3_000, coupon=5_000, member=1_000, items=2, **kw):
amt = {"order_price_amount": f"{price}.00", "shipping_fee": f"{ship}.00", "coupon_discount_price": f"{coupon}.00",
"membership_discount_amount": f"{member}.00", "points_spent_amount": "0.00", "payment_amount": "0.00"}
"membership_discount_amount": f"{member}.00", "points_spent_amount": "0.00",
"payment_amount": f"{price + ship - coupon - member}.00"}
return {"order_id": oid, "market_id": market, "paid": paid, "order_date": "2026-09-28T10:00:00+09:00",
"payment_date": "2026-09-29T11:21:35+09:00", "buyer_name": "홍길동", "receiver_address": "서울시",
"bank_account_no": "1234567890", "initial_order_amount": amt,
"actual_order_amount": {**amt, "order_price_amount": "0.00"}, # 취소 후 금액은 쓰지 않는다
"actual_order_amount": {**amt, "order_price_amount": "0.00", "payment_amount": "0.00"}, # 취소 후 금액은 쓰지 않는다
"items": [{"order_item_code": f"{oid}-{i:02d}", "product_name": f"상품{i}", "quantity": 1}
for i in range(1, items + 1)], **kw}
@@ -483,8 +484,10 @@ def test_cafe24_normalize_matches_daily_report():
assert by[("CANCEL", "c24:C20260929-01")].event_date == date(2026, 9, 29)
for e in events:
assert "buyer_name" not in str(e.raw) and "1234567890" not in str(e.raw) # 개인정보 미저장
assert order_total({"initial_order_amount": {"order_price_amount": "1578300.00", "shipping_fee": "45500.00",
"coupon_discount_price": "57000.00"}}) == 1_566_800 # 9/29 화면값
assert order_total({"naver_point": "151500.00", # 9/23 화면값
"initial_order_amount": {"order_price_amount": "1860800.00", "shipping_fee": "35000.00",
"coupon_discount_price": "21000.00", "payment_amount": "1713128.00",
"points_spent_amount": "10110.00"}}) == 1_874_738
assert target_code("self") == "cafe24" and target_code("SK11ST") == "elevenst"
assert target_code("unknown", "coupang") == "coupang" and target_code("unknown") == "cafe24"
assert target_code("NCHECKOUT", "NCHECKOUT") == "cafe24" and target_code("KAKAOPAY") == "cafe24"
@@ -513,7 +516,7 @@ def test_cafe24_normalize_matches_daily_report():
# 결제일 기준: 그날 결제된 카페24 열 주문(A,D,E,F,G)의 환불만 — X(결제 없음)·M(스마트스토어)·미완료 제외
bp = rec["refund_basis"]["by_pay_date"]
assert bp["count"] == 1 and bp["actual_refund_amount"] == 12_610
assert bp["amount_diff"] == 5 * 50_000 # 결제 당시 − 현재(가짜 현재 상품금액 0)
assert bp["amount_diff"] == 5 * 47_000 # 결제 당시 − 현재(가짜 현재 상품금액 0)
red = {x["order_id"]: x for x in rec["reduced_orders"]}
assert set(red) == {"A", "D", "E", "F", "G"} and red["A"]["refunded"] == 12_610 and red["D"]["refunded"] == 0
assert rec["reduced_orders"][-1]["order_id"] == "A" # 환불 기록으로 설명 안 되는 금액이 큰 순
@@ -586,8 +589,14 @@ def test_cafe24_refund_total_includes_points_and_naverpay_cancels():
coupon_discount_price="1000.00")]},
{**_c24_order("NP3", market="NCHECKOUT"), "items": [item("NP3-01", "C40", 5_000, day="2026-09-27 01:00:00")]},
{**_c24_order("NP4", market="NCHECKOUT"), "items": [item("NP4-01", "C00", 5_000)]}, # 취소신청만 → 제외
# 전체취소 두 품목 — 배송비(3,000)는 마지막 품목(NP5-02)에 한 번만. 앞 품목은 전날 취소(기간 밖)
{**_c24_order("NP5", market="NCHECKOUT"), "items": [item("NP5-01", "C40", 7_000, day="2026-09-25 10:00:00"),
item("NP5-02", "C40", 8_000)]},
{**_c24_order("KP1", market="KAKAOPAY"), "items": [item("KP1-01", "C40", 9_900)]}, # 톡체크아웃 → 제외
{**_c24_order("S1"), "items": [item("S1-01", "R40", 9_900)]}, # 자체몰 → 제외
],
"return_complete_date": [{**_c24_order("NP1", market="NCHECKOUT"), "items": [item("NP1-01", "C40", 55_800)]}],
"return_complete_date": [{**_c24_order("NP1", market="NCHECKOUT"),
"items": [item("NP1-01", "C40", 55_800), item("NP1-02", "N40", 9_000)]}],
})
orig, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
try:
@@ -599,14 +608,16 @@ def test_cafe24_refund_total_includes_points_and_naverpay_cancels():
assert by["c24:C20260926-01"].amount == -(63_720 + 1_080) # 적립금 환불 포함
assert by["c24:NP1-01-CL"].amount == -55_800 and by["c24:NP1-01-CL"].event_type == "CANCEL"
assert by["c24:NP1-01-CL"].event_date == date(2026, 9, 26) and by["c24:NP1-01-CL"].marketplace_code == "cafe24"
assert by["c24:NP2-01-CL"].amount == -(40_000 - 1_000) # 판매가×수량 − 품목 쿠폰
assert set(by) == {"c24:C20260926-01", "c24:NP1-01-CL", "c24:NP2-01-CL"} # 다른 날·신청·환불 기록 있는 주문 제외
assert by["c24:NP2-01-CL"].amount == -(40_000 - 1_000 + 3_000) # 판매가×수량 − 품목 쿠폰 + 전체취소 배송비
assert by["c24:NP5-02-CL"].amount == -(8_000 + 3_000) # 배송비는 마지막 품목에 한 번
# 다른 날·신청·환불 기록 있는 주문·톡체크아웃·자체몰 제외
assert set(by) == {"c24:C20260926-01", "c24:NP1-01-CL", "c24:NP2-01-CL", "c24:NP5-02-CL"}
rs = rec["refunds"]["self"]
assert rs["no_record_count"] == 2 and rs["no_record"] == 55_800 + 39_000
assert rs["total"] == 63_720 + 1_080 + 55_800 + 39_000
assert rs["no_record_count"] == 3 and rs["no_record"] == 55_800 + 42_000 + 11_000
assert rs["total"] == 63_720 + 1_080 + 55_800 + 42_000 + 11_000
cand = {c["key"]: c["amount"] for c in rec["refund_candidates"]}
assert cand["applied"] == rs["total"]
assert {c["item_code"] for c in rec["no_record_claims"]} == {"NP1-01", "NP2-01"}
assert {c["item_code"] for c in rec["no_record_claims"]} == {"NP1-01", "NP2-01", "NP5-02"}
def test_cafe24_scope_and_replace_range():
@@ -662,7 +673,9 @@ def test_cafe24_paid_total_matches_daily_report():
assert ev.amount == 46_938 and ev.discount_amount == 1_000 + 5_000
o["actual_order_amount"] = {**o["initial_order_amount"], "payment_amount": "20000.00"}
assert order_total_now(o) == 20_000 + 1_000 + 3_000
assert order_total(_c24_order("Z")) == 47_000 # 결제 필드가 모두 0이면 상품식
z = _c24_order("Z")
z["initial_order_amount"]["payment_amount"] = "0.00"
assert order_total(z) == 0 # 결제 필드가 모두 0이면 카페24도 0원
# 대조 진단: 원본 금액 필드 합계 + 이상 주문(개인정보 숫자 필드는 제외)
import app.timezone as _tz
from app.modules.performance.adapters.base import AdapterContext
+3 -2
View File
@@ -518,7 +518,7 @@
[" · 실제 환불액", rs.actual_refund_amount, rm.actual_refund_amount, "sub"],
[" · 적립금 환불", rs.used_points, rm.used_points, "sub"],
[" · 예치금 환불", rs.used_credits, rm.used_credits, "sub"],
["환불 목록 없는 취소·반품 품목 수(네이버페이 등)", rs.no_record_count, rm.no_record_count, "cnt"],
["환불 목록 없는 네이버페이 취소·반품 품목 수", rs.no_record_count, rm.no_record_count, "cnt"],
[" · 취소·반품 금액", rs.no_record, rm.no_record, "sub"],
["환불합계", rs.total, rm.total, "key", 11],
["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key", 12],
@@ -583,7 +583,7 @@
}).join("") + "</tbody></table>"
: "") +
((r.no_record_claims || []).length
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 목록에 없는 취소·반품 (환불합계에 넣은 건 — 네이버페이 등)</h4>' +
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 목록에 없는 네이버페이 취소·반품 (환불합계에 넣은 건 — 주문 전체취소면 배송비 포함)</h4>' +
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">품목</th>' +
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">반영일</th><th class="perf-th-label">상품</th>' +
"<th>수량</th><th>뺀 금액</th><th>품목 결제금액</th><th>쿠폰</th><th class=\"perf-th-label\">주문 전체취소</th><th>주문 배송비</th></tr></thead><tbody>" +
@@ -591,6 +591,7 @@
return '<tr><td class="perf-td-label">' + esc(c.order_id) + "</td><td>" + esc(c.item_code) + "</td><td>" + esc(c.place_name || c.market_id || "–") +
"</td><td>" + esc(c.status + (c.naver_pay_claim_status ? " / 네이버페이 " + c.naver_pay_claim_status : "")) + "</td><td>" + esc(c.day) +
"</td><td>" + esc(c.product_name) + '</td><td class="perf-num">' + fmt(c.quantity) + '</td><td class="perf-num">' + won(c.amount) +
(c.shipping_refund ? ' <span class="perf-muted">(배송비 ' + fmt(c.shipping_refund) + ")</span>" : "") +
'</td><td class="perf-num">' + won(c.item_payment_amount) + '</td><td class="perf-num">' + won(c.coupon) + "</td><td>" +
(c.order_all_claimed ? "<b>예</b>" : "아니오") + '</td><td class="perf-num">' + won(c.order_shipping_fee) + "</td></tr>";
}).join("") + "</tbody></table>"
+5 -1
View File
@@ -75,7 +75,11 @@
열별 차이가 같이 나온다.
- **결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트**(initial_order_amount 의 payment_amount·points_spent_amount·
credits_spent_amount + 주문의 naver_point). "상품구매금액 + 배송비 − 할인 − 쿠폰"은 할인 필드에 안 잡히는 차이가 있어 쓰지 않음
(2026-09-23: 카페24 1,874,738 = 1,713,128 + 10,110 + 151,500, 상품식 1,874,800). 네 값이 모두 0인 주문만 상품식.
(2026-09-23: 카페24 1,874,738 = 1,713,128 + 10,110 + 151,500, 상품식 1,874,800). 네 값이 모두 0인 주문도 0원
(9/25 가상계좌·휴대폰 9,900 — 카페24도 0원).
- **환불 목록 없는 취소는 네이버페이(NCHECKOUT)만** 환불합계에 넣는다. 주문 전체가 취소·반품되면 배송비(− 배송비 할인·쿠폰)도
그 주문의 마지막 클레임 품목에 한 번 더한다. 톡체크아웃·자체몰의 환불 기록 없는 취소는 카페24 환불합계에 없음
(9/4: 98,700 + 네이버페이 19,900 + 배송비 3,500 = 122,100 / 9/16: 톡체크아웃 취소 9,900 제외 → 201,100).
### 연동 단계 체크리스트(쇼핑몰마다)