fix(performance): 카페24 매출을 카페24 "일별 매출내역" 기준으로(결제합계·환불합계) + 매출 대조 도구
원인: 품목 결제금액(배송비 제외)을 매출로, 취소·반품 완료일의 품목 금액을 환불로 잡아 카페24 화면(결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰, 환불합계 = 환불완료일 실제 환불액)과 달랐다. - SALE: 결제일 기준 주문 단위 결제합계(initial_order_amount — 결제 당시 금액) - CANCEL/RETURN: GET /admin/refunds 환불완료일, 실제 환불액(환불코드 R=반품) - 환불도 원 주문 market_id 로 자체몰만(다른 마켓 연동 주문 제외) - 기간 교체(replace_range): 동기화한 기간의 카페24 실데이터를 지우고 새로 넣음(한 트랜잭션, 테스트 데이터 제외) — 예전 품목 단위 행이 남아 이중 집계되지 않게 - 설정 화면 "카페24 매출 대조": 날짜별로 카페24 화면 열 순서대로 원천 금액 합산(자체몰/마켓 구분, 저장 안 함) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -245,6 +245,11 @@ class FakeStore:
|
||||
def record_test(self, code, *, status, ok, error=""):
|
||||
self.status[code] = {"status": status, "ok": ok, "error": error, "test": True}
|
||||
|
||||
def replace_events(self, code, start, end, events):
|
||||
self.events = {k: v for k, v in self.events.items()
|
||||
if not (k[0] == code and not v["is_sample"] and start <= v["sales_date"] <= end)}
|
||||
return self.upsert_events(code, events)
|
||||
|
||||
def upsert_events(self, code, events, *, is_sample=False):
|
||||
n = 0
|
||||
for e in events:
|
||||
@@ -379,88 +384,123 @@ def test_not_implemented_and_mock():
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 카페24 어댑터(가짜 API 응답)
|
||||
# 카페24 어댑터(가짜 API 응답) — 카페24 "일별 매출내역" 기준
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _c24_item(code, status="N40", price="30000.00", qty=1, pay="29000.00", **kw):
|
||||
return {"order_item_code": code, "order_status": status, "product_name": "냄비", "option_value": "",
|
||||
"product_price": price, "option_price": "0.00", "quantity": qty, "payment_amount": pay,
|
||||
"coupon_discount_price": "1000.00", "claim_quantity": 0, **kw}
|
||||
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"}
|
||||
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"}, # 취소 후 금액은 쓰지 않는다
|
||||
"items": [{"order_item_code": f"{oid}-{i:02d}", "product_name": f"상품{i}", "quantity": 1}
|
||||
for i in range(1, items + 1)], **kw}
|
||||
|
||||
|
||||
def _c24_order(oid, items, market="self", paid="T", **kw):
|
||||
return {"order_id": oid, "market_id": market, "paid": paid, "order_date": "2026-09-27T10:00:00+09:00",
|
||||
"payment_date": "2026-09-28T11:21:35+09:00", "buyer_name": "홍길동", "receiver_address": "서울시",
|
||||
"bank_account_no": "1234567890", "items": items, **kw}
|
||||
def _c24_refund(code, oid, amount, status="T", order_date="2026-09-20T09:00:00+09:00"):
|
||||
return {"refund_code": code, "order_id": oid, "order_date": order_date, "refund_date": "2026-09-29T17:31:50+09:00",
|
||||
"actual_refund_amount": f"{amount}.00", "used_points": "0.00", "used_credits": "0.00", "quantity": 1,
|
||||
"order_item_code": [f"{oid}-01"], "status": status, "refund_bank_account_no": "1234567890"}
|
||||
|
||||
|
||||
class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist=["Cafe24Adapter"]).Cafe24Adapter):
|
||||
def __init__(self, pages):
|
||||
self.pages = pages # date_type → [응답 orders 목록(페이지별)]
|
||||
def __init__(self, orders_pages, refunds_pages=(), lookup=None):
|
||||
self.orders_pages = orders_pages # 결제일 조회 페이지들
|
||||
self.refunds_pages = list(refunds_pages)
|
||||
self.lookup = lookup or {} # order_id → market_id (환불 원 주문 조회)
|
||||
self.calls = []
|
||||
|
||||
def authenticate(self, ctx):
|
||||
return None
|
||||
|
||||
def _get(self, ctx, params):
|
||||
self.calls.append(params)
|
||||
pages = self.pages.get(params["date_type"], [])
|
||||
idx = params.get("offset", 0) // 1000
|
||||
return {"orders": pages[idx] if idx < len(pages) else []}
|
||||
def _get(self, ctx, path, params):
|
||||
self.calls.append((path, params))
|
||||
idx = params.get("offset", 0) // max(1, params.get("limit", 1))
|
||||
if path == "/admin/refunds":
|
||||
return {"refunds": self.refunds_pages[idx] if idx < len(self.refunds_pages) else []}
|
||||
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]}
|
||||
return {"orders": self.orders_pages[idx] if idx < len(self.orders_pages) else []}
|
||||
|
||||
|
||||
def test_cafe24_normalize():
|
||||
from app.modules.performance.adapters.cafe24 import Cafe24Adapter, item_amount
|
||||
def test_cafe24_normalize_matches_daily_report():
|
||||
from app.modules.performance.adapters.base import AdapterContext
|
||||
from app.modules.performance.adapters.cafe24 import order_total
|
||||
|
||||
paid = _c24_order("20260928-01", [_c24_item("20260928-01-01"), _c24_item("20260928-01-02", pay="10000.00")])
|
||||
market = _c24_order("20260928-02", [_c24_item("20260928-02-01")], market="shopn") # 스마트스토어 연동 주문
|
||||
unpaid = _c24_order("20260928-03", [_c24_item("20260928-03-01", status="N00")], paid="F")
|
||||
canceled = _c24_order("20260928-01", [
|
||||
_c24_item("20260928-01-01", status="C40", cancel_date="2026-09-29 09:00:00"),
|
||||
_c24_item("20260928-01-02", status="N40")])
|
||||
precancel = _c24_order("20260928-04", [_c24_item("20260928-04-01", status="C48", cancel_date="2026-09-29 09:00:00")])
|
||||
returned = _c24_order("20260928-05", [_c24_item("20260928-05-01", status="R40", qty=3, pay="90000.00",
|
||||
claim_quantity=1, return_confirmed_date="2026-09-30 10:00:00")])
|
||||
fake = _FakeCafe24({"pay_date": [[paid, market, unpaid]],
|
||||
"cancel_complete_date": [[canceled, precancel]],
|
||||
"return_complete_date": [[returned]]})
|
||||
ctx = __import__("app.modules.performance.adapters.base", fromlist=["AdapterContext"]).AdapterContext(
|
||||
code="cafe24", credentials=None)
|
||||
fetched, events = fake.collect(ctx, date(2026, 9, 23), date(2026, 9, 30))
|
||||
by = {(e.event_type, e.external_line_id): e for e in events}
|
||||
assert fetched == 6
|
||||
assert by[("SALE", "20260928-01-01")].amount == 29_000 and by[("SALE", "20260928-01-02")].amount == 10_000
|
||||
assert by[("SALE", "20260928-01-01")].event_date == date(2026, 9, 28) # 결제일
|
||||
assert ("SALE", "20260928-02-01") not in by and ("SALE", "20260928-03-01") not in by # 마켓 주문·미결제 제외
|
||||
c = by[("CANCEL", "20260928-01-01")]
|
||||
assert c.amount == -29_000 and c.event_date == date(2026, 9, 29) and c.external_event_id == "20260928-01-01-C"
|
||||
assert ("CANCEL", "20260928-01-02") not in by and ("CANCEL", "20260928-04-01") not in by # 미취소·입금전취소 제외
|
||||
r = by[("RETURN", "20260928-05-01")]
|
||||
assert r.amount == -30_000 and r.quantity == -1 and r.event_date == date(2026, 9, 30) # 3개 중 1개 반품
|
||||
ctx = AdapterContext(code="cafe24", credentials=None)
|
||||
fake = _FakeCafe24(
|
||||
[[_c24_order("A"), _c24_order("B", market="shopn"), _c24_order("C", paid="F")]],
|
||||
[[_c24_refund("C20260929-01", "A", 12_610), _c24_refund("R20260929-02", "X", 20_000),
|
||||
_c24_refund("C20260929-03", "M", 9_000), _c24_refund("C20260929-04", "A", 5_000, status="F")]],
|
||||
lookup={"M": "shopn"},
|
||||
)
|
||||
fetched, events = fake.collect(ctx, date(2026, 9, 29), date(2026, 9, 29))
|
||||
by = {(e.event_type, e.external_event_id): e for e in events}
|
||||
# 결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰 (결제 당시 금액)
|
||||
sale = by[("SALE", "A-PAY")]
|
||||
assert sale.amount == 50_000 + 3_000 - 1_000 - 5_000 == 47_000
|
||||
assert sale.event_date == date(2026, 9, 29) and sale.quantity == 2 and sale.product_name == "상품1 외 1건"
|
||||
assert not any(e.external_order_id in ("B", "C") and e.event_type == "SALE" for e in events) # 마켓·미결제 제외
|
||||
# 환불: 환불완료일, 실제 환불액, R→반품 / 그 밖→취소, 마켓 주문·미완료 환불 제외
|
||||
assert by[("CANCEL", "C20260929-01")].amount == -12_610
|
||||
assert by[("RETURN", "R20260929-02")].amount == -20_000
|
||||
assert ("CANCEL", "C20260929-03") not in by and ("CANCEL", "C20260929-04") not in by
|
||||
assert by[("CANCEL", "C20260929-01")].event_date == date(2026, 9, 29)
|
||||
for e in events:
|
||||
assert "buyer_name" not in e.raw and "receiver_address" not in e.raw and "bank_account_no" not in e.raw
|
||||
# 금액: payment_amount 없으면 (판매가+옵션)×수량 − 할인
|
||||
assert item_amount({"product_price": "10000.00", "option_price": "500.00", "quantity": 2,
|
||||
"coupon_discount_price": "1000.00"}) == 20_000
|
||||
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 화면값
|
||||
# 대조: 자체몰/마켓 나눠 합산
|
||||
rec = fake.reconcile(ctx, date(2026, 9, 29))
|
||||
assert rec["orders"]["self"]["orders"] == 1 and rec["orders"]["self"]["total"] == 47_000
|
||||
assert rec["orders"]["market"]["orders"] == 1 and rec["unpaid_orders"] == 1
|
||||
assert rec["refunds"]["self"]["actual_refund_amount"] == 32_610 and rec["refunds"]["market"]["count"] == 1
|
||||
# 60일 단위 분할 + 페이지 넘김(1000건이면 다음 페이지)
|
||||
page1 = [_c24_order(f"x-{i}", []) for i in range(1000)]
|
||||
fake2 = _FakeCafe24({"pay_date": [page1, [paid]]})
|
||||
got = list(fake2.fetch_orders(ctx, date(2026, 7, 1), date(2026, 9, 30)))
|
||||
pay_calls = [c for c in fake2.calls if c["date_type"] == "pay_date"]
|
||||
page1 = [_c24_order(f"x-{i}") for i in range(1000)]
|
||||
fake2 = _FakeCafe24([page1, [_c24_order("y")]])
|
||||
got = list(fake2.paid_orders(ctx, date(2026, 7, 1), date(2026, 9, 30)))
|
||||
calls = [p for path, p in fake2.calls if path == "/admin/orders"]
|
||||
assert len(got) == 2002 # 60일 구간 2개 × (1000건 페이지 + 다음 페이지 1건)
|
||||
assert pay_calls[0]["start_date"] == "2026-07-01" and pay_calls[0]["end_date"] == "2026-08-29"
|
||||
assert pay_calls[1]["offset"] == 1000 and all(c["limit"] == 1000 and c["embed"] == "items" for c in pay_calls)
|
||||
assert any(c["start_date"] == "2026-08-30" for c in pay_calls)
|
||||
# 주문 권한 없는 토큰 → 인증 실패(재연결 안내)
|
||||
assert calls[0]["start_date"] == "2026-07-01" and calls[0]["end_date"] == "2026-08-29"
|
||||
assert calls[1]["offset"] == 1000 and all(c["limit"] == 1000 and c["date_type"] == "pay_date" for c in calls)
|
||||
|
||||
|
||||
def test_cafe24_scope_and_replace_range():
|
||||
import app.modules.performance.sync as syncmod
|
||||
from app.modules.performance.adapters.base import AdapterContext
|
||||
from app.modules.performance.adapters.cafe24 import Cafe24Adapter
|
||||
|
||||
ctx = AdapterContext(code="cafe24", credentials=None)
|
||||
real = Cafe24Adapter()
|
||||
real.shared_status = lambda ctx: {"connected": True, "scopes": "mall.read_product,mall.write_product"}
|
||||
real.shared_status = lambda c: {"connected": True, "scopes": "mall.read_product,mall.write_product"}
|
||||
try:
|
||||
real.authenticate(ctx)
|
||||
except AuthFailed as exc:
|
||||
assert "mall.read_order" in exc.message
|
||||
else:
|
||||
raise AssertionError("주문 권한 없으면 인증 실패여야 합니다")
|
||||
real.shared_status = lambda ctx: {"connected": True, "scopes": "mall.read_product,mall.read_order"}
|
||||
real.shared_status = lambda c: {"connected": True, "scopes": "mall.read_product,mall.read_order"}
|
||||
real.authenticate(ctx)
|
||||
# 기간 교체: 그 기간의 예전 실데이터(품목 단위 등)는 지우고, 테스트 데이터·기간 밖은 남긴다
|
||||
st = FakeStore()
|
||||
st.upsert_events("cafe24", [{"event_type": "SALE", "external_event_id": "old-item-S", "external_order_id": "A",
|
||||
"event_date": date(2026, 9, 29), "sales_date": date(2026, 9, 29), "amount": 1}])
|
||||
st.upsert_events("cafe24", [{"event_type": "SALE", "external_event_id": "outside", "external_order_id": "Z",
|
||||
"event_date": date(2026, 9, 1), "sales_date": date(2026, 9, 1), "amount": 1}])
|
||||
st.upsert_events("cafe24", [{"event_type": "SALE", "external_event_id": "sample", "external_order_id": "S",
|
||||
"event_date": date(2026, 9, 29), "sales_date": date(2026, 9, 29), "amount": 1}],
|
||||
is_sample=True)
|
||||
fake = _FakeCafe24([[_c24_order("A")]])
|
||||
orig = syncmod.get_adapter
|
||||
syncmod.get_adapter = lambda c: fake
|
||||
try:
|
||||
r = SyncService(st, CredentialService(st, lambda: ring())).sync_marketplace(
|
||||
"cafe24", date(2026, 9, 29), date(2026, 9, 29))
|
||||
finally:
|
||||
syncmod.get_adapter = orig
|
||||
ids = {k[2] for k in st.events if k[0] == "cafe24"}
|
||||
assert r["ok"] and ids == {"A-PAY", "outside", "sample"}, ids
|
||||
|
||||
|
||||
def test_registry_and_event_validation():
|
||||
|
||||
Reference in New Issue
Block a user