Merge branch 'feat/naver-ship-check'

This commit is contained in:
2026-10-19 16:13:18 +09:00
3 changed files with 69 additions and 0 deletions
+40
View File
@@ -204,6 +204,45 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic
return orders
def ship_check(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, Any]:
"""배송비 계산 후보 비교(진단, 2026-10-19) — 네이버는 배송비·배송비 할인을 상품주문마다 적어 같은 주문·배송 묶음 안에서
반복될 수 있다. 판매분석 '배송비'와 맞는 셈을 실데이터로 고르려고 후보 합계 + 주문별 상품주문 값(개인정보 없음)을 돌려준다."""
rows = []
for c in items:
po, od = c.get("productOrder") or {}, c.get("order") or {}
day = _day(od.get("paymentDate") or po.get("paymentDate"))
status = str(po.get("productOrderStatus") or "")
if day is None or not (start <= day <= end) or status in EXCLUDED_STATUS:
continue
rows.append({"order": str(od.get("orderId") or po.get("orderId") or ""), "package": str(po.get("packageNumber") or ""),
"status": status, "fee": _won(po.get("deliveryFeeAmount")), "discount": _won(po.get("deliveryDiscountAmount")),
"section": _won(po.get("sectionDeliveryFee")), "policy": str(po.get("deliveryPolicyType") or ""),
"pay": _won(po.get("totalPaymentAmount")), "qty": _won(po.get("quantity"))})
def per(key: str) -> dict[str, int]:
groups: dict[str, list[dict[str, Any]]] = {}
for r in rows:
groups.setdefault(r[key] or r["order"], []).append(r)
return {"groups": len(groups),
"max_fee": sum(max(x["fee"] for x in g) for g in groups.values()),
"max_fee_minus_max_discount": sum(max(0, max(x["fee"] for x in g) - max(x["discount"] for x in g)) for g in groups.values()),
"sum_fee_minus_sum_discount": sum(max(0, sum(x["fee"] - x["discount"] for x in g)) for g in groups.values()),
"with_fee": sum(1 for g in groups.values() if max(x["fee"] for x in g) > 0)}
orders: dict[str, list[dict[str, Any]]] = {}
for r in rows:
orders.setdefault(r["order"], []).append({k: r[k] for k in ("package", "status", "fee", "discount", "section", "policy", "pay", "qty")})
return {
"product_orders": len(rows),
"per_product_order": {"fee": sum(r["fee"] for r in rows), "discount": sum(r["discount"] for r in rows),
"fee_minus_discount": sum(r["fee"] - r["discount"] for r in rows),
"section": sum(r["section"] for r in rows)},
"per_order": per("order"), "per_package": per("package"),
"orders": [{"order": k, "lines": v} for k, v in sorted(orders.items())],
"note": "판매분석 '배송비'와 같은 값의 후보를 찾는다 — 지금 매출 규칙은 per_product_order.fee_minus_discount",
}
def refund_items(items: Iterable[dict[str, Any]], day: date) -> list[dict[str, Any]]:
"""클레임 완료일 조회 결과 → 환불 줄(상품주문 하나 = 한 줄). 취소·반품 완료만, 금액 = 그 상품주문 결제금액."""
out = []
@@ -467,5 +506,6 @@ class NaverAdapter(MarketplaceAdapter):
"claimed": sum(o["claimed"] for o in day_orders), "ship": sum(o["ship"] for o in day_orders)})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"ship_check": ship_check(items, day, to),
"rule": "결제일 기준 상품주문 totalPaymentAmount 합(할인 뒤, 배송비 제외, 결제 뒤 취소·반품분 포함, "
"미입금 제외) = 판매분석 '판매금액(총)'. 취소·반품분·배송비는 참고"}
@@ -2186,3 +2186,28 @@ def test_dashboard_manual_cells_and_order():
assert ctx["manual_codes"] == ["coupang"] and ctx["manual_cells"] == ["2026-10-05|coupang"]
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["cells"]["coupang"]["gross"] == 87000 and day5["cells"]["coupang"]["commission"] == 8700
def test_naver_ship_check_candidates():
"""배송비 진단(2026-10-19) — 같은 주문·배송 묶음에 반복되는 배송비·할인을 주문/묶음 단위로 센 후보를 함께 돌려준다."""
from app.modules.performance.adapters import naver as nv
def it(order, po, fee, dc, pkg, status="DELIVERING", pay=10000):
x = _naver_item(order, po, "2026-10-18", pay, status=status, ship=fee, ship_dc=dc)
x["content"]["productOrder"]["packageNumber"] = pkg
return x
items = [it("A", "A1", 3500, 0, "P1"), it("A", "A2", 3500, 3500, "P1"), # 묶음 2개 — 두 번째는 묶음 할인
it("B", "B1", 3500, 3500, "P2"), # 조건부 무료
it("C", "C1", 0, 0, "P3"), # 무료배송 상품
it("D", "D1", 3500, 0, "P4", status="CANCELED"),
it("E", "E1", 3500, 0, "P5", status="CANCELED_BY_NOPAYMENT")] # 미입금 — 제외
got = nv.ship_check([{"content": i["content"]} | {"productOrder": i["content"]["productOrder"], "order": i["content"]["order"]}
for i in items], date(2026, 10, 18), date(2026, 10, 18))
assert got["product_orders"] == 5
assert got["per_product_order"] == {"fee": 14000, "discount": 7000, "fee_minus_discount": 7000, "section": 0}
assert got["per_order"] == {"groups": 4, "max_fee": 10500, "max_fee_minus_max_discount": 3500,
"sum_fee_minus_sum_discount": 7000, "with_fee": 3}
assert got["per_package"]["groups"] == 4 and got["per_package"]["max_fee"] == 10500
assert [o["order"] for o in got["orders"]] == ["A", "B", "C", "D"] and len(got["orders"][0]["lines"]) == 2
assert "홍길동" not in repr(got) and "010-1234-5678" not in repr(got)
+4
View File
@@ -138,6 +138,10 @@
사용자 확인값: 10/18 배송비 87,500원·환불 66,100원 — 배포 뒤 10/18 주문 내역 맨 아래 합계와 비교해 맞는지 확인할 것
(환불이 다르면 배송비 환불·클레임 종류 포함 여부를 실데이터로 조정). `replace_range` 라 다시 받으면 그 기간 환불도 교체.
네이버는 조회 시작일 180일 제한이 있어 그보다 오래된 날은 다시 받을 수 없다(예전 규칙 그대로 남음).
- **배송비 대조(2026-10-19)**: 10/18 실데이터 — 상품주문 53건(주문 30건), `deliveryFeeAmount` 합 157,500(3,500×45)·`deliveryDiscountAmount` 합
119,000(3,500×34)·`sectionDeliveryFee` 0 → 지금 규칙(상품주문마다 배송비 − 할인) 38,500, 판매분석 배송비는 87,500(3,500×25).
배송비·할인이 상품주문마다 반복돼 주문/배송 묶음 단위로 세야 하는 것으로 보여, 진단 `GET /api/marketplaces/naver/reconcile?date=` 응답에
`ship_check`(상품주문·주문·배송 묶음(packageNumber) 단위 후보 합계 + 주문별 상품주문 배송비·할인·상태)를 추가 — 87,500 과 맞는 후보로 규칙 확정 예정.
- 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택): 결제일 기준 상품주문 전체의 항목별 합계, 상태별 합계, 날짜별
매출·그중 결제 뒤 취소/반품(참고)·배송비(참고). 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만.