From a19c1f4cab6491b7374dad1a8cf38550df437755 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 29 Sep 2026 17:21:08 +0900 Subject: [PATCH] =?UTF-8?q?feat(performance):=20=EB=A7=A4=EC=B6=9C=20?= =?UTF-8?q?=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8=EB=8A=94=20=EB=B3=B4?= =?UTF-8?q?=EA=B3=A0=20=EC=9E=88=EB=8A=94=20=EA=B8=B0=EA=B0=84=EC=9D=84=20?= =?UTF-8?q?=EA=B0=80=EC=A0=B8=EC=98=A4=EA=B8=B0=20+=20=EC=B9=B4=ED=8E=9824?= =?UTF-8?q?=20=ED=99=98=EB=B6=88=20=EA=B8=B0=EC=A4=80=20=EB=B9=84=EA=B5=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 대시보드 [매출 업데이트]가 최근 7일 고정이 아니라 지금 보고 있는 기간(오늘까지)을 가져온다 ("이번달"이면 1일~오늘). 모듈 권한자 92일까지, 더 긴 기간(최대 366일)은 관리자만. 미래 기간은 400 - 카페24 매출 대조에 "환불 기준 비교": 환불완료일(완료) vs 환불접수일(전체 상태·상태별), 실제 환불액만 / 적립금·예치금 포함 — 9/23~27 순매출이 카페24보다 크게 나오는 원인 확인용 Co-Authored-By: Claude Opus 5.5 --- app/modules/performance/adapters/cafe24.py | 32 +++++++++++++++++-- app/modules/performance/router.py | 14 +++++--- .../templates/performance/index.html | 10 ++++-- .../templates/performance/settings.html | 2 +- .../performance/tests/test_performance.py | 5 +++ app/static/performance.js | 23 ++++++++++++- docs/PERFORMANCE_MODULE.md | 7 ++-- 7 files changed, 79 insertions(+), 14 deletions(-) diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py index 0def30a..6c90731 100644 --- a/app/modules/performance/adapters/cafe24.py +++ b/app/modules/performance/adapters/cafe24.py @@ -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) + ")"} diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index bfdf077..83f5bb6 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -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()}) diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index b2300db..3aec4ae 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -64,7 +64,8 @@
마지막 업데이트 {{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }} -
@@ -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 }} {% 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 6ec6b29..40789dd 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -143,4 +143,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 19a239f..7e96d23 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -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 diff --git a/app/static/performance.js b/app/static/performance.js index e9c8f08..3db180a 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -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 "' + esc(x[0]) + '' + f(x[1]) + '' + f(x[2]) + ""; }).join("") + "" + + (r.refund_basis + ? (function () { + const b = r.refund_basis; + const row = function (label, x, cls) { + return "' + label + '' + + fmt(x.count) + '' + won(x.actual_refund_amount) + '' + + won(x.used_points + x.used_credits) + '' + won(x.with_points) + ""; + }; + return '

환불 기준 비교 — 카페24 화면의 그날 "환불합계"와 같은 칸을 찾아 주세요

' + + '' + + "" + + row("환불완료일 기준 · 완료 현재 적용", b.completed, "perf-row-week") + + row("환불접수일 기준 · 전체 상태", b.accepted_all) + + (b.accepted_by_status || []).map(function (s) { + return row(" · 접수일 기준 " + esc(s.label), s); + }).join("") + "
기준건수실제 환불액적립금·예치금 환불합계(포함)
"; + })() + : "") + ((r.by_channel || []).length ? '

주문 채널별

' + '' + diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 3f5751b..472ef22 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -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`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고 상단에 오류 쇼핑몰만 표시.
market_id주문경로