feat(performance): 카페24 일별 매출내역 붙여넣기로 날짜별 한 번에 비교
카페24 화면과 몇몇 날짜만 안 맞는데 어느 날·어느 쪽(결제/환불)인지,
저장값이 예전 규칙이라서인지 규칙 자체가 틀린 건지 구분할 방법이 없었다.
- GET /performance/api/marketplaces/{code}/daily-check?from=&to=&live=1 (관리자, 62일)
db = 저장된 날짜별 결제합계·결제 건수·환불합계(c24: 사건 전체 = 카페24 화면 범위)
live = 지금 API·현재 규칙으로 다시 계산(adapter.collect, 저장 안 함)
- 설정 → 카페24 매출 대조 카드에 "일별 한 번에 비교": 카페24 표 붙여넣기 →
날짜별 차이(저장값/API), 판정(일치 / 다시 가져오면 해결 / 규칙 차이(결제·환불)),
[다시 가져오기] 버튼, 날짜 클릭 시 그날 상세 대조
- 테스트 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -292,6 +292,25 @@ class PerformanceDBStore:
|
||||
).fetchall()
|
||||
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
|
||||
|
||||
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
||||
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||
id_prefix 가 있으면 이 어댑터가 다른 쇼핑몰 열로 보낸 사건까지 합친다(카페24 화면 합계와 같은 범위)."""
|
||||
where = "(marketplace_code = %s OR left(external_event_id, %s) = %s)" if id_prefix else "marketplace_code = %s"
|
||||
params: tuple = (code, len(id_prefix), id_prefix) if id_prefix else (code,)
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT sales_date, "
|
||||
" COALESCE(SUM(amount) FILTER (WHERE event_type = 'SALE'), 0)::BIGINT AS paid, "
|
||||
" COUNT(*) FILTER (WHERE event_type = 'SALE')::INT AS orders, "
|
||||
" COALESCE(-SUM(amount) FILTER (WHERE event_type <> 'SALE'), 0)::BIGINT AS refund, "
|
||||
" MAX(synced_at) AS synced_at "
|
||||
f"FROM perf_sales_events WHERE is_sample = FALSE AND sales_date BETWEEN %s AND %s AND {where} "
|
||||
"GROUP BY sales_date ORDER BY sales_date",
|
||||
(start, end, *params),
|
||||
).fetchall()
|
||||
return [{"date": r["sales_date"].isoformat(), "paid": int(r["paid"]), "orders": int(r["orders"]),
|
||||
"refund": int(r["refund"]), "synced_at": _iso(r["synced_at"])} for r in rows]
|
||||
|
||||
def list_events(self, code: str, start: date, end: date, *, limit: int = 500) -> list[dict[str, Any]]:
|
||||
"""금액 클릭 상세(Drill-down). raw_data 는 보내지 않는다."""
|
||||
with self._pool.connection() as conn:
|
||||
|
||||
@@ -11,6 +11,7 @@ JSON API — 관리자
|
||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
||||
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
||||
GET /performance/api/marketplaces/{code}/daily-check 일별 매출 비교(저장값 + 지금 API 값)
|
||||
PUT /performance/api/marketplaces/{code}/credentials 저장(암호화)
|
||||
POST /performance/api/marketplaces/{code}/test 연결 테스트(저장값 또는 새 입력값)
|
||||
POST /performance/api/sample-data 테스트 데이터 생성/삭제
|
||||
@@ -36,6 +37,7 @@ from .adapters.registry import all_adapters, get_adapter
|
||||
router = APIRouter(prefix="/performance", tags=["performance"])
|
||||
|
||||
MAX_EVENT_DAYS = 31
|
||||
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
||||
MAX_BACKFILL_DAYS = 366
|
||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
|
||||
@@ -286,6 +288,22 @@ def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="da
|
||||
return JSONResponse(sync.reconcile(code, day, user=user["email"]))
|
||||
|
||||
|
||||
@router.get("/api/marketplaces/{code}/daily-check")
|
||||
def api_daily_check(request: Request, code: str, from_: str = Query(..., alias="from"), to: str | None = None,
|
||||
live: bool = False) -> JSONResponse:
|
||||
"""쇼핑몰 화면 일별 매출과 날짜별 비교 — 저장값(db) + live=1 이면 지금 API 로 다시 계산한 값(저장 안 함)."""
|
||||
store, user = common.require_store(request, admin=True)
|
||||
_code_or_404(store, code)
|
||||
start = _parse_date(from_)
|
||||
end = _parse_date(to) or start
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
if (end - start).days + 1 > MAX_CHECK_DAYS:
|
||||
raise HTTPException(status_code=400, detail=f"일별 비교는 {MAX_CHECK_DAYS}일 이내만 가능합니다.")
|
||||
_, sync = common.services(request, store)
|
||||
return JSONResponse(sync.daily_check(code, start, end, live=live, user=user["email"]))
|
||||
|
||||
|
||||
@router.post("/api/sample-data")
|
||||
def api_sample_data(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
|
||||
@@ -152,6 +152,39 @@ class SyncService:
|
||||
status, message = self._failure(exc, ctx)
|
||||
return {"ok": False, "status": status, "label": STATUS_LABELS.get(status, status), "message": message}
|
||||
|
||||
def daily_check(self, code: str, start: date, end: date, *, live: bool = False, user: str = "") -> dict[str, Any]:
|
||||
"""쇼핑몰 화면 일별 매출과 날짜별로 맞춰 보는 용도. DB 는 바꾸지 않는다.
|
||||
db = 지금 저장된 값(날짜별 결제·환불·결제 건수)
|
||||
live = live=True 일 때 지금 API·현재 규칙으로 다시 계산한 값(매출 업데이트와 같은 계산, 저장 안 함).
|
||||
db 만 틀리고 live 가 맞으면 → 예전에 받은 뒤 규칙·주문이 바뀐 것(다시 가져오면 해결)."""
|
||||
adapter = get_adapter(code)
|
||||
if adapter is None:
|
||||
return {"ok": False, "message": "알 수 없는 쇼핑몰입니다."}
|
||||
prefix = adapter.event_prefix if adapter.replace_range else ""
|
||||
out: dict[str, Any] = {"ok": True, "db": self._store.daily_breakdown(code, start, end, id_prefix=prefix)}
|
||||
if not live:
|
||||
return out
|
||||
ctx = None
|
||||
try:
|
||||
ctx = self._ctx(adapter, user=user)
|
||||
_, events = adapter.collect(ctx, start, end)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
status, message = self._failure(exc, ctx)
|
||||
return {**out, "live_error": f"{STATUS_LABELS.get(status, status)} — {message}"}
|
||||
days: dict[str, dict[str, Any]] = {}
|
||||
for ev in events:
|
||||
d = sales_date_for(ev)
|
||||
if not (start <= d <= end):
|
||||
continue
|
||||
row = days.setdefault(d.isoformat(), {"date": d.isoformat(), "paid": 0, "orders": 0, "refund": 0})
|
||||
if ev.event_type == "SALE":
|
||||
row["paid"] += ev.amount
|
||||
row["orders"] += 1
|
||||
else:
|
||||
row["refund"] -= ev.amount
|
||||
out["live"] = sorted(days.values(), key=lambda r: r["date"])
|
||||
return out
|
||||
|
||||
# ── 테스트(모의) 데이터 ────────────────────────────────
|
||||
def generate_samples(self, start: date, end: date, codes: list[str]) -> int:
|
||||
from .adapters import mock # noqa: WPS433
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930c" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -239,4 +239,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930k" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930l" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930c" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -125,6 +125,18 @@
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-recon">대조</button>
|
||||
</div>
|
||||
<div id="perf-recon-result"></div>
|
||||
|
||||
<h3 class="perf-h" style="margin:18px 0 6px">일별 한 번에 비교</h3>
|
||||
<p class="perf-muted">카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다.
|
||||
[API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과
|
||||
규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.</p>
|
||||
<textarea class="erp-input perf-paste" id="perf-daily-paste" rows="5"
|
||||
placeholder="2026-09-29(화) 47 116 2,475,300 … 2,477,800 158,000 2,319,800"></textarea>
|
||||
<div class="perf-sample-form" style="margin-top:6px">
|
||||
<label class="perf-muted"><input type="checkbox" id="perf-daily-live" /> API 값도 계산(느림)</label>
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-daily-check">비교</button>
|
||||
</div>
|
||||
<div id="perf-daily-result"></div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
@@ -143,4 +155,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930k" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930l" defer></script>{% endblock %}
|
||||
|
||||
@@ -252,6 +252,22 @@ class FakeStore:
|
||||
if not (mine(k, v) and not v["is_sample"] and start <= v["sales_date"] <= end)}
|
||||
return self.upsert_events(code, events)
|
||||
|
||||
def daily_breakdown(self, code, start, end, *, id_prefix=""):
|
||||
days = {}
|
||||
for (c, _, eid), v in self.events.items():
|
||||
if v["is_sample"] or not (start <= v["sales_date"] <= end):
|
||||
continue
|
||||
if not (c == code or (id_prefix and eid.startswith(id_prefix))):
|
||||
continue
|
||||
r = days.setdefault(v["sales_date"].isoformat(), {"date": v["sales_date"].isoformat(), "paid": 0,
|
||||
"orders": 0, "refund": 0, "synced_at": None})
|
||||
if v["event_type"] == "SALE":
|
||||
r["paid"] += v["amount"]
|
||||
r["orders"] += 1
|
||||
else:
|
||||
r["refund"] -= v["amount"]
|
||||
return sorted(days.values(), key=lambda r: r["date"])
|
||||
|
||||
def upsert_events(self, code, events, *, is_sample=False):
|
||||
n = 0
|
||||
for e in events:
|
||||
@@ -634,6 +650,32 @@ def test_cafe24_scope_and_replace_range():
|
||||
("naver", "direct-naver-1"), ("cafe24", "sample")}, got
|
||||
|
||||
|
||||
def test_daily_check_db_vs_live():
|
||||
"""일별 비교: 저장값(카페24 경유 다른 마켓 열 포함) + 지금 API 값(저장 안 함)."""
|
||||
import app.modules.performance.sync as syncmod
|
||||
|
||||
st = FakeStore()
|
||||
d = date(2026, 9, 29)
|
||||
ev = lambda eid, t, amt, **kw: {"event_type": t, "external_event_id": eid, "external_order_id": "o",
|
||||
"event_date": d, "sales_date": d, "amount": amt, **kw}
|
||||
st.upsert_events("cafe24", [ev("c24:A-PAY", "SALE", 40_000), ev("c24:R1", "CANCEL", -5_000)])
|
||||
st.upsert_events("naver", [ev("c24:B-PAY", "SALE", 10_000), ev("direct-1", "SALE", 99_999)])
|
||||
fake = _FakeCafe24([[_c24_order("A"), _c24_order("B", market="shopn"), _c24_order("C")]],
|
||||
[[_c24_refund("C20260929-01", "A", 7_000)]])
|
||||
orig = syncmod.get_adapter
|
||||
syncmod.get_adapter = lambda c: fake
|
||||
try:
|
||||
svc = SyncService(st, CredentialService(st, lambda: ring()))
|
||||
only_db = svc.daily_check("cafe24", d, d)
|
||||
both = svc.daily_check("cafe24", d, d, live=True)
|
||||
finally:
|
||||
syncmod.get_adapter = orig
|
||||
assert "live" not in only_db
|
||||
assert both["db"] == [{"date": "2026-09-29", "paid": 50_000, "orders": 2, "refund": 5_000, "synced_at": None}]
|
||||
assert both["live"] == [{"date": "2026-09-29", "paid": 3 * 47_000, "orders": 3, "refund": 7_000}]
|
||||
assert len(st.events) == 4 # 저장값은 바뀌지 않음
|
||||
|
||||
|
||||
def test_registry_and_event_validation():
|
||||
codes = [a.code for a in all_adapters()]
|
||||
assert len(codes) == len(set(codes)) == 10
|
||||
|
||||
Reference in New Issue
Block a user