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:
@@ -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) + ")"}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -126,7 +126,10 @@
|
||||
const label = syncBtn.textContent;
|
||||
syncBtn.textContent = "업데이트 중…";
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/sync", {});
|
||||
// 지금 보고 있는 기간(오늘까지)을 가져온다 — "이번달"이면 1일부터 오늘까지.
|
||||
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
|
||||
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
|
||||
const res = await api("POST", "/performance/api/sync", { from: from, to: to });
|
||||
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
|
||||
// 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
|
||||
const ok = [], bad = [], pending = [], unset = [], busy = [];
|
||||
@@ -520,6 +523,24 @@
|
||||
return "<tr" + cls + '><th class="perf-td-label' + (x[3] === "sub" ? " perf-muted" : "") + '">' + esc(x[0]) +
|
||||
'</th><td class="perf-num">' + f(x[1]) + '</td><td class="perf-num">' + f(x[2]) + "</td></tr>";
|
||||
}).join("") + "</tbody></table>" +
|
||||
(r.refund_basis
|
||||
? (function () {
|
||||
const b = r.refund_basis;
|
||||
const row = function (label, x, cls) {
|
||||
return "<tr" + (cls ? ' class="' + cls + '"' : "") + '><th class="perf-td-label">' + label + '</th><td class="perf-num">' +
|
||||
fmt(x.count) + '</td><td class="perf-num">' + won(x.actual_refund_amount) + '</td><td class="perf-num">' +
|
||||
won(x.used_points + x.used_credits) + '</td><td class="perf-num">' + won(x.with_points) + "</td></tr>";
|
||||
};
|
||||
return '<h4 class="perf-h" style="margin:14px 0 6px">환불 기준 비교 — 카페24 화면의 그날 "환불합계"와 같은 칸을 찾아 주세요</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">기준</th><th>건수</th><th>실제 환불액</th>' +
|
||||
"<th>적립금·예치금 환불</th><th>합계(포함)</th></tr></thead><tbody>" +
|
||||
row("환불완료일 기준 · 완료 <span class='perf-pill is-ok'>현재 적용</span>", b.completed, "perf-row-week") +
|
||||
row("환불접수일 기준 · 전체 상태", b.accepted_all) +
|
||||
(b.accepted_by_status || []).map(function (s) {
|
||||
return row(" · 접수일 기준 " + esc(s.label), s);
|
||||
}).join("") + "</tbody></table>";
|
||||
})()
|
||||
: "") +
|
||||
((r.by_channel || []).length
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">주문 채널별</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">market_id</th><th class="perf-th-label">주문경로</th>' +
|
||||
|
||||
@@ -126,8 +126,11 @@
|
||||
|
||||
- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·향후 cron/worker 공용. 기본 기간: 오늘 포함 최근
|
||||
`PERFORMANCE_SYNC_DAYS`(기본 7)일.
|
||||
- **과거 매출 가져오기**(설정 화면, 관리자): `POST /api/sync {from, to}` — 기간 지정 수집(최대 366일, 미래는 오늘까지).
|
||||
처음 연동했거나 빠진 기간을 채울 때. 같은 사건은 덮어써서 여러 번 해도 중복 없음. 일반 사용자가 기간을 주면 403.
|
||||
- **대시보드 [매출 업데이트]** = 지금 보고 있는 기간(오늘까지)을 `POST /api/sync {from, to}` 로 다시 가져온다
|
||||
("이번달"이면 1일~오늘). 모듈 권한자는 92일까지, 더 긴 기간(올해 등, 최대 366일)은 관리자만.
|
||||
- **과거 매출 가져오기**(설정 화면, 관리자): 같은 API 로 임의 기간(최대 366일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
|
||||
- 카페24 **환불 기준**은 현재 환불완료일(refund_date)·실제 환불액. 대조 도구의 "환불 기준 비교"(완료일 vs 접수일, 적립금·예치금
|
||||
포함 여부)로 카페24 "환불합계"와 같은 기준을 확인한 뒤 확정한다(9/23~27 순매출이 카페24보다 크게 나온 원인 조사 중).
|
||||
- 같은 쇼핑몰 동시 실행 금지: `perf_sync_runs` 의 `status='running'` 부분 유니크 인덱스(30분 넘은 running 은 정리).
|
||||
- 쇼핑몰 하나 실패 → 그 쇼핑몰만 상태 오류(`perf_connection_status`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고
|
||||
상단에 오류 쇼핑몰만 표시.
|
||||
|
||||
Reference in New Issue
Block a user