diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py index 85ef0ad..e8ce8b0 100644 --- a/app/modules/performance/adapters/cafe24.py +++ b/app/modules/performance/adapters/cafe24.py @@ -172,6 +172,38 @@ def is_self_market(market_id: Any) -> bool: return channel_kind(market_id) == "self" +# 대조 진단 — 이름에 이 말이 들어간 숫자 필드만 합산(계좌·연락처 같은 개인정보 숫자는 이름이 달라 제외) +DIAG_WORDS = ("price", "amount", "discount", "point", "fee", "credit", "mileage", "sale", "benefit", "incentive", "coupon") + + +def _num(value: Any) -> Decimal | None: + if isinstance(value, bool) or value is None: + return None + try: + d = Decimal(str(value).strip()) + except (InvalidOperation, ValueError): + return None + return d if d.is_finite() else None + + +def money_fields(obj: Any) -> dict[str, int]: + """dict 의 금액성 숫자 필드(이름에 DIAG_WORDS) → 원 단위. 중첩은 한 단계까지 "부모.자식".""" + out: dict[str, int] = {} + if not isinstance(obj, dict): + return out + for k, v in obj.items(): + if isinstance(v, dict): + for k2, v2 in money_fields(v).items(): + out[f"{k}.{k2}"] = v2 + continue + if not any(w in str(k).lower() for w in DIAG_WORDS): + continue + n = _num(v) + if n is not None: + out[str(k)] = int(n.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + return out + + def _chunks(start: date, end: date) -> Iterable[tuple[date, date]]: s = start while s <= end: @@ -504,10 +536,30 @@ class Cafe24Adapter(MarketplaceAdapter): unpaid = 0 paid_self: dict[str, int] = {} # 그날 결제된 카페24 열 주문 → (결제 당시 − 현재) 금액 reduced: dict[str, dict[str, Any]] = {} # 그중 금액이 줄어든 주문(취소·반품) — 환불 기록과 대조 + # 진단 — 어떤 원본 필드가 카페24 화면 열과 맞는지 찾는 용도(결제 주문 전체, 개인정보 제외) + diag = {"order": {}, "initial": {}, "actual": {}, "item": {}} + odd: list[dict[str, Any]] = [] # 판매가×수량 합이 주문 상품금액과 다르거나 100원 단위가 아닌 주문 for o in self.paid_orders(ctx, day, day): if o.get("paid") != "T": unpaid += 1 continue + for part, src in (("order", {k: v for k, v in o.items() if not isinstance(v, (dict, list))}), + ("initial", o.get("initial_order_amount")), ("actual", o.get("actual_order_amount"))): + for k, v in money_fields(src).items(): + diag[part][k] = diag[part].get(k, 0) + v + its = o.get("items") or [] + for i in its: + for k, v in money_fields(i).items(): + diag["item"][k] = diag["item"].get(k, 0) + v + gross = sum((_won(i.get("product_price")) + _won(i.get("option_price"))) * int(i.get("quantity") or 0) for i in its) + opa = order_amounts(o)["order_price_amount"] + if (gross != opa or opa % 100) and len(odd) < 60: + odd.append({"order_id": str(o.get("order_id") or ""), + "channel": str(o.get("order_place_name") or o.get("market_id") or ""), + "order_price_amount": opa, "items_gross": gross, "total": order_total(o), + "items": [{"code": str(i.get("order_item_code") or ""), "status": str(i.get("order_status") or ""), + "quantity": int(i.get("quantity") or 0), + "fields": {k: v for k, v in money_fields(i).items() if v}} for i in its]}) ch = channel(o.get("market_id"), o.get("order_place_id"), o.get("order_place_name")) total = order_total(o) ch["orders"] += 1 @@ -680,5 +732,6 @@ class Cafe24Adapter(MarketplaceAdapter): for c in no_record], "reduced_orders": sorted(reduced.values(), key=lambda r: r["diff"] - r["refunded"], reverse=True), "by_payment": sorted(by_payment.values(), key=lambda v: v["total"], reverse=True), + "diag": {part: dict(sorted(v.items())) for part, v in diag.items()}, "odd_orders": odd, "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 4e803cd..d858243 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 cd9c2e9..28e5235 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -155,4 +155,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 f989bd1..91c9c30 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -661,6 +661,24 @@ def test_cafe24_item_additional_discount(): assert order_total(o) == 47_000 - 62 ev = _FakeCafe24([]).normalize_order(o)[0] assert ev.amount == 46_938 and ev.discount_amount == 62 + 1_000 + 5_000 + # 대조 진단: 원본 금액 필드 합계 + 이상 주문(개인정보 숫자 필드는 제외) + import app.timezone as _tz + from app.modules.performance.adapters.base import AdapterContext + from app.modules.performance.adapters.cafe24 import money_fields + + assert money_fields({"bank_account_no": "1234567890", "order_price_amount": "100.50", "x": {"coupon_discount_price": 3}}) == {"order_price_amount": 101, "x.coupon_discount_price": 3} + o2 = _c24_order("B", price=10_050) + o2["items"] = [{"order_item_code": "B-01", "product_price": "10000.00", "option_price": "0", "quantity": 1, + "additional_discount_price": "0.00", "order_status": "N40"}] + orig, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29)) + try: + rec = _FakeCafe24([[o, o2]]).reconcile(AdapterContext(code="cafe24", credentials=None), date(2026, 9, 29)) + finally: + _tz.today_kst = orig + assert rec["diag"]["item"]["additional_discount_price"] == 62 + assert rec["diag"]["initial"]["order_price_amount"] == 60_050 and "bank_account_no" not in rec["diag"]["order"] + odd = {x["order_id"]: x for x in rec["odd_orders"]} + assert odd["B"]["items_gross"] == 10_000 and odd["B"]["order_price_amount"] == 10_050 # 현재 금액: 취소된 품목의 추가할인은 빼지 않는다 o["actual_order_amount"] = dict(o["initial_order_amount"]) o["items"][1]["order_status"] = "C40" diff --git a/app/static/performance.js b/app/static/performance.js index 811c1bc..9436234 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -658,6 +658,37 @@ }).join(""); })() + "" : "") + + (r.diag + ? (function () { + // 판매가 합계 − 카페24 상품구매금액 = 찾는 금액(예: 9/23 → 62). 같은 값인 필드를 강조. + const gap = shopCols ? (s.order_price_amount + m.order_price_amount) - shopCols[2] : null; + const PART = { initial: "주문 금액(결제 당시 initial_order_amount)", actual: "주문 금액(현재 actual_order_amount)", + item: "품목(items) 합계", order: "주문 최상위 필드" }; + const cells = ["initial", "actual", "item", "order"].map(function (p) { + const f = r.diag[p] || {}; + const keys = Object.keys(f).filter(function (k) { return f[k]; }); + return '
' + esc(PART[p]) + "
" + + (keys.length ? '' + keys.map(function (k) { + return ""; + }).join("") + "
' + esc(k) + + '' + fmt(f[k]) + "
" : '

0 아닌 값 없음

') + "
"; + }).join(""); + const odd = (r.odd_orders || []).map(function (o) { + return '' + esc(o.order_id) + "" + esc(o.channel || "–") + '' + + fmt(o.items_gross) + '' + fmt(o.order_price_amount) + '' + fmt(o.total) + + '' + o.items.map(function (i) { + return esc(i.code + " " + i.status + " ×" + i.quantity + " — " + + Object.keys(i.fields).map(function (k) { return k + "=" + fmt(i.fields[k]); }).join(", ")); + }).join("
") + ""; + }).join(""); + return '

원본 금액 필드 합계 (진단 — 그날 결제 주문 전체)' + + (gap ? ' · 판매가 합계 − 카페24 상품구매금액 = ' + fmt(gap) + " (같은 값 강조)" : "") + "

" + + '
' + cells + "
" + + (odd ? '

상품금액이 100원 단위가 아니거나 판매가×수량 합과 다른 주문

' + + '' + + '' + odd + "
주문번호채널판매가×수량주문 상품금액결제합계(계산)품목 금액 필드(0 제외)
" : ""); + })() + : "") + '

' + esc(r.formula) + ". 미결제 주문 " + fmt(r.unpaid_orders) + "건 제외. \"알 수 없는 채널\"은 카페24 열에 넣습니다 — 외부 마켓이면 어느 쇼핑몰인지 알려 주세요.

"; const target = document.getElementById("perf-recon-target");