From 077c92fa324c2dbfb378226334c7a8a261b91790 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 30 Sep 2026 13:46:57 +0900 Subject: [PATCH] =?UTF-8?q?fix(performance):=20=EB=84=A4=EC=9D=B4=EB=B2=84?= =?UTF-8?q?=20=EB=A7=A4=EC=B6=9C=20=3D=20=ED=8C=90=EB=A7=A4=EB=B6=84?= =?UTF-8?q?=EC=84=9D=20"=ED=8C=90=EB=A7=A4=EA=B8=88=EC=95=A1(=EC=B4=9D)"?= =?UTF-8?q?=20=E2=80=94=20=EA=B2=B0=EC=A0=9C=20=EB=92=A4=20=EC=B7=A8?= =?UTF-8?q?=EC=86=8C=C2=B7=EB=B0=98=ED=92=88=20=ED=8F=AC=ED=95=A8,=20?= =?UTF-8?q?=EB=B0=B0=EC=86=A1=EB=B9=84=20=EC=A0=9C=EC=99=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 9/1 판매분석 매출 4,455,600원(판매금액(총)): 할인 뒤 금액, 배송비 별도, 환불은 환불일에 따로 빠짐 - 처음 규칙(취소·반품 빼고 배송비 더함)은 4,245,300원으로 달랐음 - 입금대기·미입금 취소만 제외, 결제 뒤 취소·반품도 결제일 매출에 포함 - 원본 데이터 확인 표에 결제 뒤 취소·반품분·배송비(참고) 열 추가 - performance.js 캐시 버전 20260930x, 테스트·문서 갱신 Co-Authored-By: Claude Opus 5.5 --- app/modules/performance/adapters/naver.py | 43 +++++++++++-------- .../templates/performance/index.html | 2 +- .../templates/performance/settings.html | 2 +- .../performance/tests/test_performance.py | 19 ++++---- app/static/performance.js | 13 +++--- docs/PERFORMANCE_MODULE.md | 21 +++++---- 6 files changed, 59 insertions(+), 41 deletions(-) diff --git a/app/modules/performance/adapters/naver.py b/app/modules/performance/adapters/naver.py index 753445a..258bd4f 100644 --- a/app/modules/performance/adapters/naver.py +++ b/app/modules/performance/adapters/naver.py @@ -7,14 +7,15 @@ 토큰은 약 3시간 — 암호화 저장(access_token·access_token_expires_at)해 두고 만료 5분 전에 새로 받는다. 커머스API센터 애플리케이션에 **API 호출 IP(이 서버 외부 IP)** 를 등록해야 호출된다. -매출 수집(1차 규칙 — 설정 화면 "원본 데이터 확인"으로 스마트스토어센터 화면과 맞춰 확정한다): +매출 수집 — 스마트스토어센터 **판매분석 "판매금액(총)"** 과 같은 기준(2026-09-30 사용자 확인: 9/1 매출 4,455,600원. +판매금액은 할인(판매자·네이버 부담) 뒤 금액, 배송비 332,486원은 별도, 환불 346,340원은 환불일에 따로 빠져 판매금액(순)): - 조건형 상품 주문 상세 조회 GET /v1/pay-order/seller/product-orders ?from=…&to=…&rangeType=PAYED_DATETIME&pageSize=&page= — 결제일 기준, 한 번에 24시간까지(하루씩 부른다), from 부터 180일 안의 주문만. 응답에 주문·상품주문 상세가 바로 들어 있다(네이버 안내: 소량·조회용 권장 API). - SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(order.paymentDate). - 금액 = 상품주문들의 최종 결제금액(productOrder.totalPaymentAmount) 합 + 배송비(deliveryFeeAmount − 배송비 할인, 주문에서 한 번). - - 취소·반품 완료(CANCELED·RETURNED)·미입금 취소(CANCELED_BY_NOPAYMENT) 상품주문은 뺀다. 기간을 통째로 다시 받아 - (replace_range) 나중에 취소된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 — 11번가와 같은 방식). + 금액 = 상품주문들의 결제금액(productOrder.totalPaymentAmount) 합 — 배송비 제외. + - 결제 뒤 취소·반품된 상품주문도 결제일 매출에 그대로 둔다(판매금액(총)). 입금대기·미입금 취소만 뺀다. + 그래서 지난 날짜 매출이 나중에 줄지 않는다. 환불(판매금액(순))은 아직 따로 만들지 않는다. - 구매자 이름·연락처·주소는 저장하지 않는다. """ @@ -49,8 +50,10 @@ CALL_INTERVAL_SEC = 0.35 # 초당 호출 제한(넘으면 429) — 호 RETRY_429 = 3 PROBE_MAX_DAYS = 31 -# 매출에서 빼는 상품주문 상태 — 취소 완료·반품 완료·미입금 취소 -EXCLUDED_STATUS = frozenset({"CANCELED", "RETURNED", "CANCELED_BY_NOPAYMENT"}) +# 매출에서 빼는 상품주문 상태 — 결제되지 않은 것만(입금대기·미입금 취소). 결제 뒤 취소·반품된 것은 판매분석 +# "판매금액(총)"처럼 결제일 매출에 그대로 둔다(환불은 판매분석에서도 환불일에 따로 빠진다). +EXCLUDED_STATUS = frozenset({"PAYMENT_WAITING", "CANCELED_BY_NOPAYMENT"}) +CLAIMED_STATUS = frozenset({"CANCELED", "RETURNED"}) # 결제 뒤 취소·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌 STATUS_KO = { "PAYMENT_WAITING": "입금대기", "PAYED": "결제완료", "DELIVERING": "배송중", "DELIVERED": "배송완료", "PURCHASE_DECIDED": "구매확정", "EXCHANGED": "교환", "CANCELED": "취소", "RETURNED": "반품", @@ -167,7 +170,9 @@ def field_summary(records: list[dict[str, str]]) -> list[dict[str, Any]]: def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]: - """상품주문 → 주문 하나로 합침(결제일이 [start, end] 이고 취소·반품 완료가 아닌 것만).""" + """상품주문 → 주문 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함). + 금액 = totalPaymentAmount 합(할인 뒤 상품 결제금액, 배송비 제외) = 판매분석 "판매금액(총)". + 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다.""" orders: dict[str, dict[str, Any]] = {} for c in items: po, od = c.get("productOrder") or {}, c.get("order") or {} @@ -176,10 +181,14 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic status = str(po.get("productOrderStatus") or "") if not oid or day is None or not (start <= day <= end) or status in EXCLUDED_STATUS: continue - o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "qty": 0, "discount": 0, - "names": [], "opt": "", "statuses": [], "order_day": _day(od.get("orderDate"))}) - o["amount"] += _won(po.get("totalPaymentAmount")) - o["ship"] = max(o["ship"], _won(po.get("deliveryFeeAmount")) - _won(po.get("deliveryDiscountAmount"))) + o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0, + "discount": 0, "names": [], "opt": "", "statuses": [], + "order_day": _day(od.get("orderDate"))}) + paid = _won(po.get("totalPaymentAmount")) + o["amount"] += paid + if status in CLAIMED_STATUS: + o["claimed"] += paid + o["ship"] += _won(po.get("deliveryFeeAmount")) - _won(po.get("deliveryDiscountAmount")) o["qty"] += _won(po.get("quantity")) o["discount"] += _won(po.get("productDiscountAmount")) name = str(po.get("productName") or "") @@ -188,8 +197,6 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic o["opt"] = o["opt"] or str(po.get("productOption") or "") if status and status not in o["statuses"]: o["statuses"].append(status) - for o in orders.values(): - o["amount"] += max(0, o.pop("ship")) return orders @@ -385,7 +392,8 @@ class NaverAdapter(MarketplaceAdapter): "ok": True, "count": len(items), "fields": field_summary([flatten(c) for c in items])}] for st, rows in sorted(by_status.items()): probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})" - + (" — 매출 제외" if st in EXCLUDED_STATUS else ""), "path": "productOrderStatus", + + (" — 매출 제외(미결제)" if st in EXCLUDED_STATUS else + " — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "productOrderStatus", "ok": True, "count": len(rows), "fields": [f for f in field_summary([flatten(c) for c in rows]) if f["sum"] is not None and f["name"].startswith("productOrder.")]}) @@ -394,8 +402,9 @@ class NaverAdapter(MarketplaceAdapter): d = day while d <= to: day_orders = [o for o in orders.values() if o["_day"] == d] - days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sum(o["amount"] for o in day_orders)}) + days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sum(o["amount"] for o in day_orders), + "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, - "rule": "주문별 totalPaymentAmount 합 + 배송비(deliveryFeeAmount − deliveryDiscountAmount, 한 번), " - "취소·반품 완료·미입금 취소 제외"} + "rule": "결제일 기준 상품주문 totalPaymentAmount 합(할인 뒤, 배송비 제외, 결제 뒤 취소·반품분 포함, " + "미입금 제외) = 판매분석 '판매금액(총)'. 취소·반품분·배송비는 참고"} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index e364ba2..2b66da0 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 3df6523..e431b23 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -175,4 +175,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 866caf4..f542030 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -1057,8 +1057,9 @@ def test_naver_sign_token_and_connection(): def test_naver_collect_sales(): - """네이버 매출 = 주문 단위, 결제일 기준. 상품주문 결제금액 합 + 배송비(주문에서 한 번, 배송비 할인 뺌). - 취소·반품 완료·미입금 취소 상품주문은 뺀다. 페이지를 넘겨 받고, 구매자 정보는 저장하지 않는다.""" + """네이버 매출 = 판매분석 "판매금액(총)" — 주문 단위, 결제일 기준, 상품주문 결제금액 합(배송비 제외). + 결제 뒤 취소·반품된 것도 포함, 미입금 취소만 뺀다(9/1 실데이터: 판매금액(총) 4,455,600, 배송비 별도). + 페이지를 넘겨 받고, 구매자 정보는 저장하지 않는다.""" import bcrypt import httpx @@ -1095,12 +1096,13 @@ def test_naver_collect_sales(): httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig assert r["ok"], r ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "naver"} - assert set(ev_) == {"naver:A", "naver:C"} # B 취소·D 미입금취소 제외 - assert ev_["naver:A"]["amount"] == 20000 + 5000 + 3000 # 배송비는 주문에서 한 번 + assert set(ev_) == {"naver:A", "naver:B", "naver:C"} # D 미입금취소만 제외 + assert ev_["naver:A"]["amount"] == 20000 + 5000 # 배송비 제외 + assert ev_["naver:B"]["amount"] == 9900 # 결제 뒤 취소도 결제일 매출(판매금액(총)) assert ev_["naver:A"]["quantity"] == 3 and ev_["naver:A"]["discount_amount"] == 1000 assert ev_["naver:A"]["sales_date"] == date(2026, 9, 9) and ev_["naver:A"]["product_name"] == "밀폐용기 외 1건" - assert ev_["naver:C"]["amount"] == 15000 # 반품 줄 제외, 무료배송(할인) 0 - assert ev_["naver:C"]["order_status"] == "구매확정" + assert ev_["naver:C"]["amount"] == 15000 + 7000 # 반품 줄도 포함 + assert ev_["naver:C"]["order_status"] == "구매확정/반품" assert ("2026-09-09", 2) in calls and ("2026-09-10", 2) not in calls # hasNext 일 때만 다음 쪽 assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events) @@ -1141,8 +1143,9 @@ def test_naver_reconcile_hides_personal(): assert f["productOrder.shippingAddress.baseAddress"]["personal"] assert not f["productOrder.productName"]["personal"] and f["productOrder.productName"]["sample"] == "밀폐용기" assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec) - assert rec["days"] == [{"date": "2026-09-09", "orders": 1, "amount": 23000}, {"date": "2026-09-10", "orders": 0, "amount": 0}] - assert any("매출 제외" in p["label"] for p in rec["probes"]) + assert rec["days"] == [{"date": "2026-09-09", "orders": 2, "amount": 29900, "claimed": 9900, "ship": 3000}, + {"date": "2026-09-10", "orders": 0, "amount": 0, "claimed": 0, "ship": 0}] + assert any("결제 뒤 취소·반품(매출 포함)" in p["label"] for p in rec["probes"]) if __name__ == "__main__": diff --git a/app/static/performance.js b/app/static/performance.js index c6ab617..075043c 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -861,13 +861,16 @@ // 날짜별 현재 규칙 매출(네이버) — 쇼핑몰 관리자 화면 매출과 나란히 비교 const days = (r.days || []).length ? '

날짜별 현재 규칙 매출

' + (r.rule ? '

규칙: ' + esc(r.rule) + "

" : "") + - '' + + '
결제일주문 수매출
' + + "" + r.days.map(function (d) { return '"; - }).join("") + '
결제일주문 수매출그중 결제 뒤 취소·반품(참고)배송비(참고, 매출 제외)
' + esc(d.date) + '' + fmt(d.orders) + - '' + fmt(d.amount) + "
합계' + - fmt(r.days.reduce(function (a, d) { return a + d.orders; }, 0)) + '' + - fmt(r.days.reduce(function (a, d) { return a + d.amount; }, 0)) + "
" : ""; + '' + fmt(d.amount) + '' + fmt(d.claimed || 0) + + '' + fmt(d.ship || 0) + ""; + }).join("") + '합계' + + ["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 || '

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

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

' + esc(err.message) + "

"; diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 309529f..d98fb92 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -29,7 +29,7 @@ 오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중). -**연동 현황**: 카페24·11번가·네이버 스마트스토어 = **구현됨**(네이버는 1차 규칙, 실데이터 대조 전), 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은 +**연동 현황**: 카페24·11번가·네이버 스마트스토어 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은 **연동 단계에서 공식 API 문서로 확정**한다. ### 카페24 (`adapters/cafe24.py`, 구현됨) @@ -102,7 +102,7 @@ - `replace_range` — 기간을 통째로 다시 받아 취소·반품된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 → 지난 날짜 금액이 나중에 줄 수 있음). 구매자 이름·아이디·연락처는 저장하지 않는다. -### 네이버 스마트스토어 (`adapters/naver.py`, 구현됨 — 1차 규칙) +### 네이버 스마트스토어 (`adapters/naver.py`, 구현됨) - 인증: 커머스API센터 애플리케이션 ID·시크릿 → 전자서명 `client_secret_sign = base64(bcrypt.hashpw("{client_id}_{timestamp ms}", client_secret))` → `POST https://api.commerce.naver.com/external/v1/oauth2/token`(form: client_id·timestamp·client_secret_sign· @@ -114,13 +114,16 @@ — 한 번에 **24시간까지**(하루씩 0시~23:59:59.999 +09:00), from 부터 180일 안 주문만(네이버 안내, GitHub discussions #1875·#2380). 응답 모양은 `data.contents[].content.{order, productOrder, …}` 로 보고 목록·`content` 유무가 달라도 받는다(`product_order_items`), 다음 쪽은 `pagination.hasNext`(없으면 100건 꽉 차면). 호출 간격 0.35초, 429 는 1·2·4초 쉬고 다시. -- **1차 매출 규칙**: SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(`order.paymentDate`). 금액 = 상품주문 - `totalPaymentAmount` 합 + 배송비(`deliveryFeeAmount − deliveryDiscountAmount`, 주문에서 최댓값 한 번). 할인 = `productDiscountAmount` 합. - 취소·반품 완료(`CANCELED`·`RETURNED`)·미입금 취소(`CANCELED_BY_NOPAYMENT`) 상품주문은 뺀다. `replace_range` — 기간을 다시 받으면 - 나중에 취소된 주문이 빠진다(11번가와 같은 방식). -- **확정 전 할 일**: 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택) — 결제일 기준 상품주문 전체의 항목별 합계, - 상태별 합계, 날짜별 "현재 규칙 매출"을 스마트스토어센터 화면 매출과 비교해 금액 항목(결제금액 vs 상품금액, 네이버 부담 할인, - 배송비 묶음 기준)을 확정한다. 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만. +- **매출 규칙 = 스마트스토어센터 판매분석 "판매금액(총)"**(2026-09-30 사용자 확인): 판매분석 9/1 매출 4,455,600원 = 판매금액(총) — + 할인(판매자·네이버 부담) 뒤 금액, **배송비(332,486원)는 별도**, 결제 뒤 취소·반품도 결제일에 포함하고 환불(346,340원)은 **환불일**에 + 따로 빼서 판매금액(순) 4,109,260원(예: 9/1 결제 0원인 상품에 환불 5건 75,040원). 주방세제 2.3L 16,640 = 17,900 − 네이버 부담 1,260. + 처음 규칙(취소·반품 빼고 배송비 더함)은 4,245,300원으로 달랐다. + - SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(`order.paymentDate`), 금액 = 상품주문 `totalPaymentAmount` 합(배송비 제외), + 할인 = `productDiscountAmount` 합. 결제 뒤 취소·반품(`CANCELED`·`RETURNED`)도 포함, 입금대기·미입금 취소만 뺀다 + → 지난 날짜 매출이 나중에 줄지 않는다. `replace_range`. + - 환불(판매금액(순))은 아직 사건으로 만들지 않는다 — 필요하면 클레임 완료일 기준 CANCEL/RETURN 을 추가. +- 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택): 결제일 기준 상품주문 전체의 항목별 합계, 상태별 합계, 날짜별 + 매출·그중 결제 뒤 취소/반품(참고)·배송비(참고). 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만. ### 연동 단계 체크리스트(쇼핑몰마다)