feat(performance): 매출 업데이트는 보고 있는 기간을 가져오기 + 카페24 환불 기준 비교

- 대시보드 [매출 업데이트]가 최근 7일 고정이 아니라 지금 보고 있는 기간(오늘까지)을 가져온다
  ("이번달"이면 1일~오늘). 모듈 권한자 92일까지, 더 긴 기간(최대 366일)은 관리자만. 미래 기간은 400
- 카페24 매출 대조에 "환불 기준 비교": 환불완료일(완료) vs 환불접수일(전체 상태·상태별),
  실제 환불액만 / 적립금·예치금 포함 — 9/23~27 순매출이 카페24보다 크게 나오는 원인 확인용

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-29 17:21:08 +09:00
parent fb7c29833e
commit a19c1f4cab
7 changed files with 79 additions and 14 deletions
+29 -3
View File
@@ -243,11 +243,13 @@ class Cafe24Adapter(MarketplaceAdapter):
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": "pay_date", "embed": "items"}, ORDER_LIMIT)
def refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
def refunds(self, ctx: AdapterContext, start: date, end: date,
date_type: str = "refund_date") -> Iterable[dict[str, Any]]:
"""환불 목록. date_type: refund_date(환불완료일, 기본) / accepted_refund_date(환불접수일)."""
for s, e in _chunks(start, end):
yield from self._paged(ctx, "/admin/refunds", "refunds",
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": "refund_date"}, REFUND_LIMIT)
"date_type": date_type}, REFUND_LIMIT)
def market_ids(self, ctx: AdapterContext, refunds: list[dict[str, Any]]) -> dict[str, tuple[Any, Any, Any]]:
"""환불의 원 주문 (market_id, order_place_id, order_place_name) — 주문일 60일 구간·100건씩 묶어 조회.
@@ -394,8 +396,32 @@ class Cafe24Adapter(MarketplaceAdapter):
ch["refund_amount"] += _won(r.get("actual_refund_amount"))
channels_out = sorted(({**v, "names": sorted(v["names"])} for v in by_channel.values()),
key=lambda v: v["total"], reverse=True)
# 환불 기준 비교 — 카페24 "환불합계"가 어느 기준인지 확정하는 용도.
# 완료일(refund_date, 완료 T) vs 접수일(accepted_refund_date, 상태 T/F/M 전부)
# 각각 실제 환불액만 / 적립금·예치금 환불 포함
def rsum(items: Iterable[dict[str, Any]]) -> dict[str, int]:
out = {"count": 0, "actual_refund_amount": 0, "used_points": 0, "used_credits": 0}
for x in items:
out["count"] += 1
for k in ("actual_refund_amount", "used_points", "used_credits"):
out[k] += _won(x.get(k))
out["with_points"] = out["actual_refund_amount"] + out["used_points"] + out["used_credits"]
return out
accepted = list(self.refunds(ctx, day, day, "accepted_refund_date"))
status_names = {"T": "환불완료", "F": "환불전", "M": "환불보류"}
refund_basis = {
"completed": rsum(rows),
"accepted_all": rsum(accepted),
"accepted_by_status": [
{"status": s, "label": status_names.get(s, s or "(없음)"),
**rsum(x for x in accepted if str(x.get("status") or "") == s)}
for s in sorted({str(x.get("status") or "") for x in accepted})
],
}
return {"date": day.isoformat(), "orders": groups, "refunds": refunds, "unpaid_orders": unpaid,
"by_channel": channels_out,
"by_channel": channels_out, "refund_basis": refund_basis,
"by_payment": sorted(by_payment.values(), key=lambda v: v["total"], reverse=True),
"formula": "결제합계 = 상품구매금액 + 배송비 − 할인(" + ", ".join(DISCOUNT_FIELDS) +
") − 쿠폰(" + ", ".join(COUPON_FIELDS) + ")"}
+10 -4
View File
@@ -37,6 +37,7 @@ router = APIRouter(prefix="/performance", tags=["performance"])
MAX_EVENT_DAYS = 31
MAX_BACKFILL_DAYS = 366
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
@@ -128,7 +129,8 @@ def settings_page(request: Request):
# ════════════════════════════════════════════════════════════
@router.post("/api/sync")
def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""기본은 최근 N일(PERFORMANCE_SYNC_DAYS). from/to 로 기간을 지정한 수집(과거 매출 가져오기)은 관리자만."""
"""from/to 가 없으면 최근 N일(PERFORMANCE_SYNC_DAYS). 기간 지정은 대시보드 [매출 업데이트](보고 있는 기간)와
설정 [과거 매출 가져오기]가 쓴다 — 모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
store, user = common.require_store(request)
_, sync = common.services(request, store)
codes = [str(c) for c in (payload.get("codes") or []) if get_adapter(str(c))]
@@ -137,16 +139,20 @@ def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JS
if start or end:
from app.store import is_admin # noqa: WPS433
if not is_admin(user):
raise HTTPException(status_code=403, detail="기간을 지정한 수집은 관리자만 할 수 있습니다.")
end = end or today_kst()
start = start or end
if end < start:
start, end = end, start
if end > today_kst():
end = today_kst()
if (end - start).days + 1 > MAX_BACKFILL_DAYS:
if start > end:
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
days = (end - start).days + 1
if days > MAX_BACKFILL_DAYS:
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
raise HTTPException(status_code=403,
detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
results = sync.sync_all(start=start, end=end, codes=codes or None, user=user["email"])
return JSONResponse({"results": results, "last_update_at": store.last_update_at()})
@@ -64,7 +64,8 @@
<div class="perf-update">
<span class="perf-muted" id="perf-last-update">마지막 업데이트
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
<button type="button" class="erp-btn erp-btn-primary" id="perf-sync-btn"{% if running %} disabled{% endif %}>
<button type="button" class="erp-btn erp-btn-primary" id="perf-sync-btn"{% if running %} disabled{% endif %}
title="지금 보고 있는 기간({{ period.label }}, 오늘까지)의 매출을 쇼핑몰에서 다시 가져옵니다">
{% if running %}업데이트 중…{% else %}매출 업데이트{% endif %}
</button>
</div>
@@ -231,8 +232,11 @@
"codes": codes,
"daily": chart_daily,
"share": chart_share,
"period_kind": period_kind
"period_kind": period_kind,
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"today": today
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930f" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930g" defer></script>{% endblock %}
@@ -143,4 +143,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930f" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930g" defer></script>{% endblock %}
@@ -480,6 +480,11 @@ def test_cafe24_normalize_matches_daily_report():
assert ch["auction"]["kind"] == "unknown" and ch["auction"]["target"] == "cafe24"
assert ch["NCHECKOUT"]["kind"] == "self" and ch["NCHECKOUT"]["label"] == "네이버페이"
assert ch["KAKAOPAY"]["label"] == "톡체크아웃" and ch["mobile"]["label"] == "모바일웹"
# 환불 기준 비교: 완료일(완료만) vs 접수일(전체 상태) — 가짜 API 는 두 기준에 같은 목록을 돌려준다
rb = rec["refund_basis"]
assert rb["completed"]["count"] == 3 and rb["completed"]["actual_refund_amount"] == 12_610 + 20_000 + 9_000
assert rb["accepted_all"]["count"] == 4 and rb["accepted_all"]["with_points"] == 12_610 + 20_000 + 9_000 + 5_000
assert {s["status"]: s["count"] for s in rb["accepted_by_status"]} == {"T": 3, "F": 1}
# 기기: PC 채널(self)이어도 휴대폰 주문(order_from_mobile=T)은 모바일
assert ch["self"]["mobile_orders"] == 1 and ch["self"]["pc_orders"] == 0 and ch["self"]["mobile_total"] == 47_000
assert ch["NCHECKOUT"]["pc_orders"] == 1 and ch["mobile"]["mobile_orders"] == 1