[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 칸은 저장된 값 사용). ' +
+ "[저장]은 연결 테스트 결과와 관계없이 저장합니다 — 쇼핑몰의 일시 장애로 테스트가 실패할 수 있기 때문입니다. " +
+ "저장 후 자동으로 한 번 더 연결 테스트를 합니다.
";
+ m.body.innerHTML = html;
+ const saveBtn = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "저장");
+ m.foot.appendChild(saveBtn);
+ saveBtn.addEventListener("click", async function () {
+ saveBtn.disabled = true;
+ try {
+ await api("PUT", "/performance/api/marketplaces/" + code + "/credentials", { values: typed(), clear: cleared() });
+ m.changed = true;
+ m.body.querySelectorAll("input[type=password]").forEach(function (i) { i.value = ""; });
+ result.className = "perf-test-result";
+ result.textContent = "저장했습니다. 연결 확인 중…";
+ await test(false);
+ } catch (err) {
+ result.className = "perf-test-result is-bad";
+ result.textContent = "저장 실패: " + err.message;
+ } finally { saveBtn.disabled = false; }
+ });
+ }
+
+ function typed() {
+ const out = {};
+ m.body.querySelectorAll("input[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); });
+ return out;
+ }
+ function cleared() {
+ return Array.prototype.filter.call(m.body.querySelectorAll("input[data-clear]"), function (c) { return c.checked; })
+ .map(function (c) { return c.dataset.clear; });
+ }
+ async function test(withTyped) {
+ testBtn.disabled = true;
+ result.className = "perf-test-result";
+ result.textContent = "연결 확인 중…";
+ try {
+ const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", withTyped ? { values: typed() } : {});
+ result.className = "perf-test-result " + (res.ok ? "is-ok" : "is-bad");
+ result.textContent = (res.ok ? "● " : "● " + res.label + " — ") + res.message + (res.unsaved ? " (저장 안 한 값으로 시험)" : "");
+ if (!res.unsaved) m.changed = true;
+ } catch (err) {
+ result.className = "perf-test-result is-bad";
+ result.textContent = err.message;
+ } finally { testBtn.disabled = false; }
+ }
+ testBtn.addEventListener("click", function () { test(true); });
+ }
+
+ async function runTest(code, name, btn) {
+ btn.disabled = true;
+ const label = btn.textContent;
+ btn.textContent = "확인 중…";
+ try {
+ const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", {});
+ await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message);
+ location.reload();
+ } catch (err) {
+ alertMsg(err.message);
+ } finally { btn.disabled = false; btn.textContent = label; }
+ }
+
+ // ── 테스트 데이터 / 재암호화 ──
+ const gen = document.getElementById("perf-sample-gen");
+ if (gen) gen.addEventListener("click", async function () {
+ gen.disabled = true;
+ try {
+ const res = await api("POST", "/performance/api/sample-data", {
+ action: "generate", from: document.getElementById("perf-sample-from").value,
+ to: document.getElementById("perf-sample-to").value,
+ });
+ await alertMsg("테스트 데이터 " + fmt(res.generated) + "건을 만들었습니다(같은 기간을 다시 만들면 덮어씀).");
+ location.reload();
+ } catch (err) { alertMsg(err.message); } finally { gen.disabled = false; }
+ });
+ const del = document.getElementById("perf-sample-del");
+ if (del) del.addEventListener("click", async function () {
+ if (!(await confirmMsg("테스트 데이터만 모두 삭제합니다. 실제 수집한 매출은 지우지 않습니다. 계속할까요?"))) return;
+ try {
+ const res = await api("POST", "/performance/api/sample-data", { action: "delete" });
+ await alertMsg("테스트 데이터 " + fmt(res.deleted) + "건을 삭제했습니다.");
+ location.reload();
+ } catch (err) { alertMsg(err.message); }
+ });
+ const rekey = document.getElementById("perf-rekey");
+ if (rekey) rekey.addEventListener("click", async function () {
+ if (!(await confirmMsg("예전 키로 암호화된 인증정보를 현재 키로 다시 암호화합니다. 계속할까요?"))) return;
+ try {
+ const res = await api("POST", "/performance/api/rekey");
+ await alertMsg("다시 암호화 " + res.reencrypted + "건" + (res.failed ? ", 실패 " + res.failed + "건(다시 입력 필요)" : ""));
+ location.reload();
+ } catch (err) { alertMsg(err.message); }
+ });
+ }
+
+ document.addEventListener("DOMContentLoaded", function () {
+ const dash = document.getElementById("perf-dash");
+ if (dash) initDashboard(dash);
+ const set = document.getElementById("perf-settings");
+ if (set) initSettings(set);
+ });
+})();
diff --git a/app/store.py b/app/store.py
index 6c29fbf..d635831 100644
--- a/app/store.py
+++ b/app/store.py
@@ -32,6 +32,7 @@ MODULE_KEYS: tuple[str, ...] = (
"dispatch",
"project",
"cafe24",
+ "performance",
"expense_approver",
"vacation_approver",
)
diff --git a/docs/DATABASES.md b/docs/DATABASES.md
index 097368c..c827909 100644
--- a/docs/DATABASES.md
+++ b/docs/DATABASES.md
@@ -11,6 +11,7 @@
| `cupang_db` | 쿠팡 밀크런 출고 묶음 / 출고 라인 / 입고센터 / 박스 입수량 규칙 |
| `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 |
| `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 |
+| `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 |
---
@@ -336,6 +337,44 @@ cd /opt/www/main && docker compose up -d --build web
---
+## performance_db 스키마 / 초기화
+
+DDL: `scripts/sql/performance_db_init.sql` (멱등). DB·역할(`performance_app`)·테이블·인덱스·트리거·쇼핑몰 10곳 seed 를
+한 번에 생성. **JSON 폴백 없음** — `PERFORMANCE_DB_URL` 미설정 시 모듈이 "설정 필요" 안내만 표시. 상세는 `docs/PERFORMANCE_MODULE.md`.
+
+| 테이블 | 용도 |
+| --- | --- |
+| `perf_marketplaces` | 쇼핑몰 코드·이름·사용 여부·매출 집계 여부·순서 |
+| `perf_commission_rates` | 수수료율 이력(`rate_percent NUMERIC(7,3)`, `effective_from`). 그날 유효한 요율로 과거 실적 계산 |
+| `perf_credentials` | API 인증정보. (쇼핑몰, 항목) 한 행 = **AES-256-GCM 암호문** + `key_version`. 토큰도 여기 |
+| `perf_connection_status` | 연결 상태·마지막 테스트/동기화·최근 오류(비밀값 가린 문구) |
+| `perf_sales_events` | 매출 사건(결제 +, 취소·반품 −, BIGINT 원). `UNIQUE(marketplace_code, event_type, external_event_id)`. `is_sample`=테스트 데이터 |
+| `perf_sync_runs` | 동기화 기록. `status='running'` 부분 유니크 인덱스로 같은 쇼핑몰 동시 실행 차단 |
+
+핵심 규칙:
+
+- 인증정보는 **암호문만** 저장. 마스터 키 `APP_ENCRYPTION_KEY` 는 DB 가 아닌 `.env` 에만 있다 —
+ DB 백업만으로는 복호화할 수 없고, **키를 잃으면 인증정보를 다시 입력해야 한다**(키는 별도 안전 보관).
+- 테스트 데이터 삭제는 `is_sample = TRUE` 조건 삭제만 한다(설정 화면 버튼).
+
+### 운영 서버 초기화 (1회, 사용자 승인 후)
+
+```bash
+read -s -p "performance_app password: " APP_PWD; echo
+docker exec -i postgres-db psql -U postgres \
+ -v app_password="$APP_PWD" \
+ < scripts/sql/performance_db_init.sql
+# main-app .env 에 추가:
+# PERFORMANCE_DB_URL=postgresql://performance_app:@postgres-db:5432/performance_db
+# APP_ENCRYPTION_KEY=$(openssl rand -hex 32) # 별도 안전한 곳에도 백업
+# APP_ENCRYPTION_KEY_VERSION=1
+cd /opt/www/main && docker compose up -d --build
+```
+
+> 멱등 스크립트. 기존 DB 가 있으면 DROP 하지 않음.
+
+---
+
## 백업 / 복구 (안전 절차)
### 백업
diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
index 0c45297..a66fd98 100644
--- a/docs/DEPLOYMENT.md
+++ b/docs/DEPLOYMENT.md
@@ -120,6 +120,10 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
| `VACATION_DB_URL` | 휴가 관리 DB DSN (예: `postgresql://vacation_app:@postgres-db:5432/vacation_db`). **필수** — 미설정 시 모듈 비활성(설정 필요 안내). 권한키 `vacation`/`vacation_approver` |
| `ITEMCODE_DB_URL` | 상품 검색용 itemcode_db 읽기 전용 DSN. 미설정 시 검색 비활성(수동 입력). 테이블/컬럼은 `ITEMCODE_TABLE`/`ITEMCODE_CODE_COL`/`ITEMCODE_NAME_COL`/`ITEMCODE_TYPE_COL` 또는 `ITEMCODE_SEARCH_SQL` 로 지정 |
| `DATA_DIR` | 영구 데이터 경로 (Docker 볼륨 마운트). 첨부파일은 `$DATA_DIR/uploads/expense/{item_id}/` 에 저장 |
+| `PERFORMANCE_DB_URL` | 실적 DB DSN (예: `postgresql://performance_app:@postgres-db:5432/performance_db`). **필수** — 미설정 시 실적 모듈 비활성(설정 필요 안내). 권한키 `performance` |
+| `APP_ENCRYPTION_KEY` | 쇼핑몰 API 인증정보 암호화 마스터 키(32바이트, `openssl rand -hex 32`). DB 에 저장하지 않음. **분실 시 저장된 인증정보 복구 불가 — 별도 안전 보관**. 쇼핑몰별 ID/Key/Secret 은 `.env` 에 넣지 않고 실적 → 설정 화면에서 입력 |
+| `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) |
+| `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) |
---
diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md
new file mode 100644
index 0000000..e1421cc
--- /dev/null
+++ b/docs/PERFORMANCE_MODULE.md
@@ -0,0 +1,117 @@
+# 실적(쇼핑몰 통합 매출) 모듈
+
+> `app/modules/performance/` · DB `performance_db` · URL `/performance/` · 권한키 `performance`
+> 여러 쇼핑몰의 주문/매출을 **수집 → DB 저장 → 화면 조회** 구조로 한 화면에서 본다.
+> API 장애·호출 제한이 있어도 이미 저장된 실적은 그대로 보인다.
+
+## 1. 구조 — 네 영역 분리
+
+| 영역 | 파일 | 역할 |
+|---|---|---|
+| ① 쇼핑몰 API 수집 | `adapters/base.py`, `adapters/<쇼핑몰>.py`, `adapters/registry.py`, `sync.py` | 어댑터 = 쇼핑몰 하나. `sync.py` 가 어댑터 결과를 공통 사건으로 DB 저장 |
+| ② 인증정보·보안 | `security/crypto.py`, `security/redact.py`, `credentials.py` | AES-256-GCM 암·복호화, 비밀값 가리기, 저장/화면 요약/재암호화 |
+| ③ 계산·저장 | `calc.py`, `db.py` | 기간·주(월~일)·수수료·반올림·집계(순수 함수) / performance_db |
+| ④ 화면 | `dashboard.py`, `router.py`, `common.py`, `templates/performance/`, `static/performance.{css,js}` | 화면 데이터 조립, 라우트·권한, UI |
+
+**쇼핑몰 추가 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄**(`perf_marketplaces`). 대시보드·설정·동기화는 자동으로 붙는다.
+
+## 2. 어댑터 공통 인터페이스 (`MarketplaceAdapter`)
+
+| 메서드 | 설명 |
+|---|---|
+| `credential_fields()` | 설정 화면 입력칸 정의(`CredentialField`: key/label/secret/required/help, `internal`=토큰 등 화면 비표시) |
+| `validate_credentials(values)` | 저장 전 검사(값을 오류 문구에 넣지 않음) |
+| `authenticate(ctx)` / `refresh_token(ctx)` | 토큰 발급·갱신. 새 토큰은 `ctx.credentials.set(key, value)` → 자동 암호화 저장 |
+| `test_connection(ctx)` | 성공 문구 반환, 실패는 `AdapterError` 계열 |
+| `fetch_orders` / `fetch_refunds(ctx, start, end)` | 원본 수집 |
+| `normalize_order` / `normalize_refund(raw)` | 원본 → `SaleEvent` 목록 |
+| `collect(ctx, start, end)` | 위를 묶어 (원본 건수, 사건 목록) — sync 서비스가 부른다 |
+
+오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
+
+**현재(1단계)**: 10개 어댑터 모두 입력칸만 정의, 수집은 `NotImplementedYet`. 카페24는 `auth_type="shared"` — 기존
+`app/integrations/cafe24` OAuth 토큰(cafe24_db)을 재사용해 연결 상태만 확인한다(주문 수집 시 앱 권한에
+`mall.read_order` 추가 + 재연결 필요). 쇼핑몰별 입력칸은 **연동 단계에서 공식 API 문서로 확정**한다.
+
+### 연동 단계 체크리스트(쇼핑몰마다)
+
+- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
+- `SaleEvent` 규칙: 금액은 원 단위 **정수**, 결제 `+` / 취소·반품 `−`, `external_event_id` 는 쇼핑몰 안에서 사건을
+ 유일하게 가리키는 값(중복 방지 키), `order_date`/`payment_date`/`event_date` 를 섞지 말고 각각 채운다
+- 오류 메시지·`raw` 에 비밀값을 넣지 않는다(sync 가 한 번 더 가리지만 원칙은 넣지 않는 것)
+- `implemented = True`, 단위 테스트(원본 샘플 → 사건 변환) 추가
+
+## 3. 매출 기준·계산 (`calc.py`, `sync.sales_date_for`)
+
+- **집계 기준일(`sales_date`)**: 결제 = 결제일(`payment_date`, 없으면 `event_date`), 취소·반품 = **발생일**.
+ 지난주 실적이 나중에 바뀌지 않게 하려는 선택. `order_date`/`payment_date` 를 따로 보관하므로 기준을 바꿀 수 있다
+ (바꿀 곳은 `sales_date_for` 한 곳 + 기존 행 재계산).
+- **수수료** = `round_half_up(일·쇼핑몰 매출 합 × 그날 요율 / 100)` — `calc.commission()` 한 곳. 음수(취소)도 같은 규칙.
+ 주문별이 아니라 일·쇼핑몰 합계 단위 반올림이다.
+- **수수료율 이력**: `perf_commission_rates(effective_from)`. 어떤 날의 요율 = 그날 이전 가장 최근 시작일의 요율,
+ 첫 요율 이전은 0%. "처음부터(과거 전체)"는 `2000-01-01` 로 저장.
+- **주** = 월요일~일요일. **증감률**: 진행 중인 기간은 직전 기간의 **같은 경과일수**까지와 비교(전주 같은 기간),
+ 비교 대상이 0 이하면 표시하지 않음.
+- **월·연 누적 기준일**: 선택 기간이 오늘을 포함하면 오늘(이번주가 다음 달에 걸쳐도 "이번달"), 지난 기간이면 기간 끝.
+
+## 4. 인증정보 보안
+
+- 저장: 설정 화면 입력 → 서버에서 **AES-256-GCM**(`cryptography` AESGCM) → `perf_credentials`
+ (항목 하나 = 행 하나, `encrypted_value = "v{키버전}:{base64url(nonce+암호문+tag)}"`, `key_version`).
+- AAD = `perf:{쇼핑몰}:{항목}` — 암호문을 다른 칸으로 옮기면 복호화 실패.
+- 화면으로는 secret 항목의 **저장 여부만** 보낸다(원문·일부·길이 X). 일반 항목(Vendor ID 등)만 원문 표시.
+- 빈 칸 저장 = 기존 값 유지. 선택 항목은 "저장된 값 지우기".
+- 저장 정책: [연결 테스트]는 **입력한 새 값으로 시험하고 저장하지 않음**(상태도 기록 안 함). [저장]은 테스트 결과와 무관하게
+ 저장(쇼핑몰 일시 장애 대비) 후 자동으로 저장값 연결 테스트.
+- 오류 메시지·로그·`raw_data` 는 `security/redact.py` 로 key/secret/token/password/Authorization/Cookie 를 가린 뒤 저장.
+- 쇼핑몰 API 는 **백엔드에서만** 호출. 브라우저는 `/performance/api/*` 만 부른다.
+
+### 마스터 키
+
+| 변수 | 설명 |
+|---|---|
+| `APP_ENCRYPTION_KEY` | 현재 키(32바이트: `openssl rand -hex 32` 64자 hex 또는 base64). **DB·Git 에 넣지 않는다** |
+| `APP_ENCRYPTION_KEY_VERSION` | 현재 키 버전(기본 1) |
+| `APP_ENCRYPTION_KEY_V{n}` | 교체 중 남겨 두는 예전 키 |
+
+교체 절차: 새 키를 `APP_ENCRYPTION_KEY`, 버전 +1, 예전 키를 `APP_ENCRYPTION_KEY_V{예전}` 에 → 재기동 →
+설정 화면 [현재 키로 다시 암호화](`POST /performance/api/rekey`) → 예전 버전 0개 확인 후 `_V{n}` 삭제.
+**키를 잃으면 저장된 인증정보는 복구할 수 없다** — 키는 서버 `.env` 와 별도 안전한 곳에 백업한다
+(DB 백업만으로는 복호화 불가 — 의도된 설계).
+
+## 5. 권한 (서버에서 검사)
+
+| 기능 | 권한 |
+|---|---|
+| 대시보드 · 매출 업데이트 · 금액 상세 | `performance` (admin 자동) |
+| 설정 화면 · 수수료 · 인증정보 · 연결 테스트 · 테스트 데이터 · 재암호화 | `is_admin` |
+
+화면에서 설정 탭을 숨기는 것과 별개로 모든 설정 API 가 `common.require_store(admin=True)` 로 403 을 낸다.
+
+## 6. 동기화 (`sync.py`)
+
+- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·향후 cron/worker 공용. 기본 기간: 오늘 포함 최근
+ `PERFORMANCE_SYNC_DAYS`(기본 7)일.
+- 같은 쇼핑몰 동시 실행 금지: `perf_sync_runs` 의 `status='running'` 부분 유니크 인덱스(30분 넘은 running 은 정리).
+- 쇼핑몰 하나 실패 → 그 쇼핑몰만 상태 오류(`perf_connection_status`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고
+ 상단에 오류 쇼핑몰만 표시.
+- 중복 방지: `UNIQUE(marketplace_code, event_type, external_event_id)` + `ON CONFLICT DO UPDATE`.
+
+## 7. 화면
+
+- **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…`
+ 기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행),
+ [총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
+ 월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내).
+- **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태
+ (정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), 마스터 키 상태·재암호화,
+ 테스트 데이터 생성/삭제(`is_sample`).
+
+## 8. 테스트
+
+```bash
+python -m app.modules.performance.tests.test_performance # 또는 pytest
+```
+
+암호화(왕복·AAD·변조·키 교체), 가리기, 수수료 반올림·요율 이력, 기간/주 계산, 표·누적 합계, 인증정보 비노출·재암호화,
+동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다.
diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md
index 47dbd06..58e040c 100644
--- a/docs/PROJECT_OVERVIEW.md
+++ b/docs/PROJECT_OVERVIEW.md
@@ -21,13 +21,14 @@
| 쿠팡 밀크런 | 쿠팡 출고 일정 관리 (`app/modules/cupang/`) — 월간 달력 / 출고 묶음(헤더+라인) / 상자 입수량 자동계산 / 로켓 매출 관리 / 엑셀 내보내기. 상품은 `itemcode_db` 읽기 전용 참조 |
| 휴가 (준비중) | 연차/반차/특별휴가 신청·잔여일수 관리 |
| 말레이시아 재고 | 말레이시아 창고 재고관리 (`app/modules/malaysia/`) — 낱개 입출고/조정, 세트 BOM, 일일 재고조사(세트 분해 자동 반영), 현재고 현황. 상품명은 `itemcode_db` 읽기 전용 참조 |
+| 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` |
### 권한 키 (`MODULE_KEYS`)
| 키 | 종류 | 설명 |
| --- | --- | --- |
| `corm` / `order` | 접근 | 외부 모듈 진입 |
-| `expense` / `vacation` / `cupang` / `malaysia` | 접근 | 내부 모듈 진입 |
+| `expense` / `vacation` / `cupang` / `malaysia` / `performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) |
| `expense_approver` | 결재 | 개인경비 승인/반려/정산 |
| `vacation_approver` | 결재 | 휴가 승인/반려 (모듈 미개발) |
@@ -91,6 +92,7 @@ app/modules//
| `cupang_db` | 쿠팡 밀크런 출고/입고센터/박스규칙 (`CUPANG_DB_URL` 필수, JSON 폴백 없음) |
| `vacation_db` | 휴가 신청/공휴일/연차잔여 (`VACATION_DB_URL` 필수, JSON 폴백 없음) |
| `malaysia_stock_db` | 말레이시아 창고 재고/세트BOM/재고조사 (`MALAYSIA_STOCK_DB_URL` 필수, JSON 폴백 없음) |
+| `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) |
> 신규 DB가 필요하면 **승인 요청 후** 생성하며, 이름은 `_db`로 끝낸다. 상세는 `DATABASES.md`.
diff --git a/scripts/sql/performance_db_init.sql b/scripts/sql/performance_db_init.sql
new file mode 100644
index 0000000..175ad01
--- /dev/null
+++ b/scripts/sql/performance_db_init.sql
@@ -0,0 +1,223 @@
+-- =====================================================================
+-- performance_db 초기화 스크립트 (PostgreSQL) — 실적(쇼핑몰 통합 매출) 모듈
+-- =====================================================================
+-- 멱등(idempotent): 여러 번 실행해도 안전. 기존 데이터를 삭제하지 않는다.
+--
+-- ⚠️ 실행 전 사용자 승인 + 백업 확인 필수. DROP/TRUNCATE 없음.
+--
+-- 실행 방법 (운영 PostgreSQL 컨테이너명: postgres-db):
+--
+-- 1) DB / 역할 / 스키마 생성 (superuser 로 1회)
+-- read -s -p "performance_app password: " APP_PWD; echo
+-- docker exec -i postgres-db psql -U postgres \
+-- -v app_password="$APP_PWD" \
+-- < scripts/sql/performance_db_init.sql
+--
+-- 2) main-app .env 에 추가
+-- PERFORMANCE_DB_URL=postgresql://performance_app:@postgres-db:5432/performance_db
+-- APP_ENCRYPTION_KEY=$(openssl rand -hex 32) # 쇼핑몰 인증정보 암호화 마스터 키
+-- APP_ENCRYPTION_KEY_VERSION=1
+--
+-- 3) main-app 재기동
+-- cd /opt/www/main && docker compose up -d --build
+--
+-- 주의:
+-- - 기존 DB 가 있으면 DROP 하지 않는다(CREATE DATABASE 는 미존재 시에만).
+-- - 비밀번호는 절대 Git 에 커밋하지 않는다. psql -v 로만 전달.
+-- - 쇼핑몰 API 인증정보는 이 DB 에 **암호문**으로만 들어간다(perf_credentials).
+-- 암호화 마스터 키(APP_ENCRYPTION_KEY)는 DB 에 저장하지 않는다.
+-- =====================================================================
+
+\set ON_ERROR_STOP on
+
+SELECT 'CREATE DATABASE performance_db ENCODING ''UTF8'' TEMPLATE template0'
+WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'performance_db')
+\gexec
+
+SELECT 'CREATE ROLE performance_app LOGIN PASSWORD ' || quote_literal(:'app_password')
+WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'performance_app')
+\gexec
+
+SELECT 'ALTER ROLE performance_app WITH LOGIN PASSWORD ' || quote_literal(:'app_password')
+\gexec
+
+GRANT CONNECT ON DATABASE performance_db TO performance_app;
+
+\connect performance_db
+
+CREATE OR REPLACE FUNCTION perf_set_updated_at() RETURNS trigger AS $$
+BEGIN
+ NEW.updated_at := now();
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+-- ════════════════════════════════════════════════════════════
+-- 1) 쇼핑몰 기본 설정 — 사용 여부 / 매출 집계 여부 / 표시 순서
+-- 어댑터(코드)가 쇼핑몰의 "종류"를 정의하고, 이 표는 운영 설정만 담는다.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_marketplaces (
+ code TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ include_in_sales BOOLEAN NOT NULL DEFAULT TRUE,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+DROP TRIGGER IF EXISTS trg_perf_marketplaces_updated ON perf_marketplaces;
+CREATE TRIGGER trg_perf_marketplaces_updated
+ BEFORE UPDATE ON perf_marketplaces
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+INSERT INTO perf_marketplaces (code, name, sort_order) VALUES
+ ('cafe24', '카페24', 10),
+ ('naver', '네이버 스마트스토어', 20),
+ ('coupang', '쿠팡', 30),
+ ('ohouse', '오늘의집', 40),
+ ('gmarket', 'G마켓', 50),
+ ('kakao', '카카오', 60),
+ ('gsshop', 'GS샵', 70),
+ ('elevenst', '11번가', 80),
+ ('lotteon', '롯데ON', 90),
+ ('toss', '토스쇼핑', 100)
+ON CONFLICT (code) DO NOTHING;
+
+-- ════════════════════════════════════════════════════════════
+-- 2) 수수료율 이력 — 적용 시작일(effective_from)부터 다음 변경 전까지 그 요율.
+-- 과거 실적은 그 날짜에 유효했던 요율로 계산한다(요율을 바꿔도 과거가 안 바뀜).
+-- rule_type 은 향후 상품별/카테고리별/정액 수수료 확장용(현재 'marketplace' 만).
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_commission_rates (
+ id BIGSERIAL PRIMARY KEY,
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ rule_type TEXT NOT NULL DEFAULT 'marketplace'
+ CHECK (rule_type IN ('marketplace')),
+ rate_percent NUMERIC(7,3) NOT NULL CHECK (rate_percent >= 0 AND rate_percent <= 100),
+ effective_from DATE NOT NULL,
+ memo TEXT NOT NULL DEFAULT '',
+ created_by TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (marketplace_code, rule_type, effective_from)
+);
+CREATE INDEX IF NOT EXISTS idx_perf_rates_code_from
+ ON perf_commission_rates (marketplace_code, effective_from DESC);
+
+-- ════════════════════════════════════════════════════════════
+-- 3) 쇼핑몰 API 인증정보 — 항목 하나 = 행 하나, 값은 AES-256-GCM 암호문.
+-- encrypted_value 형식: "v{키버전}:{base64url(nonce + 암호문 + tag)}"
+-- key_version 은 마스터 키 교체(rotation) 때 재암호화 대상을 찾는 데 쓴다.
+-- access/refresh token 도 여기에 같은 방식으로 저장한다.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_credentials (
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ credential_key TEXT NOT NULL,
+ encrypted_value TEXT NOT NULL,
+ key_version INTEGER NOT NULL,
+ updated_by TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (marketplace_code, credential_key)
+);
+DROP TRIGGER IF EXISTS trg_perf_credentials_updated ON perf_credentials;
+CREATE TRIGGER trg_perf_credentials_updated
+ BEFORE UPDATE ON perf_credentials
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+-- ════════════════════════════════════════════════════════════
+-- 4) 연결 상태 — 연결 테스트/동기화 결과. last_error 는 비밀값을 가린 문구만.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_connection_status (
+ marketplace_code TEXT PRIMARY KEY REFERENCES perf_marketplaces(code),
+ status TEXT NOT NULL DEFAULT 'unknown'
+ CHECK (status IN ('ok', 'not_configured', 'auth_failed', 'token_expired',
+ 'api_error', 'not_implemented', 'unknown')),
+ last_test_at TIMESTAMPTZ,
+ last_test_ok BOOLEAN,
+ last_sync_at TIMESTAMPTZ,
+ last_success_sync_at TIMESTAMPTZ,
+ last_error TEXT NOT NULL DEFAULT '',
+ last_error_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+DROP TRIGGER IF EXISTS trg_perf_status_updated ON perf_connection_status;
+CREATE TRIGGER trg_perf_status_updated
+ BEFORE UPDATE ON perf_connection_status
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+-- ════════════════════════════════════════════════════════════
+-- 5) 매출 사건 — 결제(+), 취소(-), 반품(-). 금액은 원 단위 정수(BIGINT).
+-- sales_date = 집계 기준일. 결제는 결제일, 취소·반품은 발생일
+-- (지난 실적이 나중에 바뀌지 않게). order_date/payment_date 는 원래 날짜를
+-- 따로 보관해 기준을 바꿀 수 있게 한다.
+-- 중복 방지: UNIQUE(쇼핑몰, 사건 종류, 외부 사건 ID) — 같은 사건은 덮어쓴다.
+-- raw_data 는 비밀값을 가린 원본. is_sample = 테스트(모의) 데이터.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_sales_events (
+ id BIGSERIAL PRIMARY KEY,
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ event_type TEXT NOT NULL CHECK (event_type IN ('SALE', 'CANCEL', 'RETURN', 'ADJUST')),
+ external_event_id TEXT NOT NULL,
+ external_order_id TEXT NOT NULL,
+ external_line_id TEXT NOT NULL DEFAULT '',
+ order_date DATE,
+ payment_date DATE,
+ event_date DATE NOT NULL,
+ sales_date DATE NOT NULL,
+ product_name TEXT NOT NULL DEFAULT '',
+ option_name TEXT NOT NULL DEFAULT '',
+ quantity INTEGER NOT NULL DEFAULT 0,
+ amount BIGINT NOT NULL,
+ discount_amount BIGINT NOT NULL DEFAULT 0,
+ order_status TEXT NOT NULL DEFAULT '',
+ raw_data JSONB,
+ is_sample BOOLEAN NOT NULL DEFAULT FALSE,
+ synced_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (marketplace_code, event_type, external_event_id)
+);
+CREATE INDEX IF NOT EXISTS idx_perf_events_date_code ON perf_sales_events (sales_date, marketplace_code);
+CREATE INDEX IF NOT EXISTS idx_perf_events_order ON perf_sales_events (marketplace_code, external_order_id);
+CREATE INDEX IF NOT EXISTS idx_perf_events_sample ON perf_sales_events (is_sample) WHERE is_sample;
+DROP TRIGGER IF EXISTS trg_perf_events_updated ON perf_sales_events;
+CREATE TRIGGER trg_perf_events_updated
+ BEFORE UPDATE ON perf_sales_events
+ FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
+
+-- ════════════════════════════════════════════════════════════
+-- 6) 동기화 실행 기록 — 같은 쇼핑몰은 동시에 하나만(running 부분 유니크 인덱스).
+-- 웹/스케줄러 어디서 돌려도 중복 실행이 막힌다.
+-- ════════════════════════════════════════════════════════════
+CREATE TABLE IF NOT EXISTS perf_sync_runs (
+ id BIGSERIAL PRIMARY KEY,
+ marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code),
+ trigger TEXT NOT NULL DEFAULT 'manual' CHECK (trigger IN ('manual', 'schedule')),
+ range_from DATE,
+ range_to DATE,
+ status TEXT NOT NULL DEFAULT 'running'
+ CHECK (status IN ('running', 'success', 'failed')),
+ fetched_count INTEGER NOT NULL DEFAULT 0,
+ upserted_count INTEGER NOT NULL DEFAULT 0,
+ error TEXT NOT NULL DEFAULT '',
+ started_by TEXT NOT NULL DEFAULT '',
+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ finished_at TIMESTAMPTZ
+);
+CREATE UNIQUE INDEX IF NOT EXISTS uq_perf_sync_running
+ ON perf_sync_runs (marketplace_code) WHERE status = 'running';
+CREATE INDEX IF NOT EXISTS idx_perf_sync_runs_code ON perf_sync_runs (marketplace_code, started_at DESC);
+
+-- ════════════════════════════════════════════════════════════
+-- 권한 — 앱 계정은 DML 만
+-- ════════════════════════════════════════════════════════════
+GRANT USAGE ON SCHEMA public TO performance_app;
+GRANT SELECT, INSERT, UPDATE, DELETE ON
+ perf_marketplaces, perf_commission_rates, perf_credentials,
+ perf_connection_status, perf_sales_events, perf_sync_runs
+ TO performance_app;
+GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO performance_app;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO performance_app;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public
+ GRANT USAGE, SELECT ON SEQUENCES TO performance_app;
From 6e175d0bac3f9e30a87409d42803c05da1a6869c Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 16:16:07 +0900
Subject: [PATCH 02/30] =?UTF-8?q?fix(performance):=20=EB=A7=A4=EC=B6=9C=20?=
=?UTF-8?q?=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8=20=EA=B2=B0=EA=B3=BC=20?=
=?UTF-8?q?=E2=80=94=20=EC=9D=B8=EC=A6=9D=EC=A0=95=EB=B3=B4=20=EB=AF=B8?=
=?UTF-8?q?=EC=84=A4=EC=A0=95=20=EC=87=BC=ED=95=91=EB=AA=B0=EC=9D=80=20?=
=?UTF-8?q?=EC=8B=A4=ED=8C=A8(=EB=B9=A8=EA=B0=95)=EA=B0=80=20=EC=95=84?=
=?UTF-8?q?=EB=8B=8C=20=ED=9A=8C=EC=83=89=20=ED=95=9C=20=EC=A4=84=EB=A1=9C?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
실패는 인증 실패·API 오류처럼 손봐야 하는 것만 표시. 미설정/연동 준비 중은 이름만 모아 표시.
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/templates/performance/index.html | 2 +-
app/modules/performance/templates/performance/settings.html | 2 +-
app/static/performance.js | 6 +++++-
3 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index c6a0b21..ef87ca1 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -235,4 +235,4 @@
} | 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 39f2a7d..2cdec23 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -118,4 +118,4 @@
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/static/performance.js b/app/static/performance.js
index aea815b..e61f20d 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -127,13 +127,16 @@
syncBtn.textContent = "업데이트 중…";
try {
const res = await api("POST", "/performance/api/sync", {});
- const ok = [], bad = [], pending = [], busy = [];
+ // 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
+ // 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
+ const ok = [], bad = [], pending = [], unset = [], busy = [];
let changed = 0;
(res.results || []).forEach(function (r) {
const name = (data.names || {})[r.code] || r.code;
if (r.skipped) busy.push(name);
else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; }
else if (r.status === "not_implemented") pending.push(name);
+ else if (r.status === "not_configured") unset.push(name);
else bad.push(name + "(" + (r.label || r.status) + (r.message ? ": " + r.message : "") + ")");
});
const parts = [];
@@ -141,6 +144,7 @@
if (bad.length) parts.push("실패 " + esc(bad.join(", ")));
if (busy.length) parts.push("이미 진행 중 " + esc(busy.join(", ")));
if (pending.length) parts.push('연동 준비 중: ' + esc(pending.join(", ")) + "");
+ if (unset.length) parts.push('인증정보 미설정: ' + esc(unset.join(", ")) + "");
resultBox.innerHTML = parts.join(" · ") || "업데이트할 쇼핑몰이 없습니다.";
resultBox.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
resultBox.hidden = false;
From 04a1fddd95664acb51169bb22018e1d4991dd88d Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 16:25:25 +0900
Subject: [PATCH 03/30] =?UTF-8?q?feat(performance):=20=EC=B9=B4=ED=8E=9824?=
=?UTF-8?q?=20=EC=A3=BC=EB=AC=B8=20=EB=A7=A4=EC=B6=9C=20=EC=88=98=EC=A7=91?=
=?UTF-8?q?=20=EC=97=B0=EB=8F=99=20+=20=EA=B3=BC=EA=B1=B0=20=EB=A7=A4?=
=?UTF-8?q?=EC=B6=9C=20=EA=B0=80=EC=A0=B8=EC=98=A4=EA=B8=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
카페24 (Admin API GET /admin/orders, 문서 2026-09-01 기준)
- 결제(SALE): date_type=pay_date, embed=items — 결제된 주문의 품목 결제금액(할인 반영·배송비 제외), 결제일
- 취소(CANCEL): cancel_complete_date, 품목 C40~C43 만 음수(입금전취소 C47~C49 제외)
- 반품(RETURN): return_complete_date, 품목 R40~R43 음수, 부분 반품은 claim_quantity 비율
- 자체몰 주문만(market_id=self) — 카페24로 연동된 다른 마켓 주문은 이중 집계 방지로 제외
- 60일 단위 분할(한 호출 3개월 미만), limit 1000 페이지 넘김, 개인정보 미저장(raw 는 금액·상태만)
- 기존 app/integrations/cafe24 토큰·클라이언트 재사용, 연결 테스트는 주문 권한까지 확인
- DEFAULT_SCOPES 에 mall.read_order 추가(읽기만) — 카페24 상품관리 → 시스템에서 재연결 필요
과거 매출 가져오기(설정, 관리자): 기간 지정 수집(최대 366일), 일반 사용자는 403
Co-Authored-By: Claude Opus 5.5
---
app/integrations/cafe24/config.py | 5 +-
app/modules/performance/adapters/cafe24.py | 243 ++++++++++++++++--
app/modules/performance/router.py | 19 +-
.../templates/performance/index.html | 2 +-
.../templates/performance/settings.html | 15 +-
.../performance/tests/test_performance.py | 85 ++++++
app/static/performance.js | 40 +++
docs/CAFE24_MODULE.md | 11 +-
docs/PERFORMANCE_MODULE.md | 26 +-
9 files changed, 414 insertions(+), 32 deletions(-)
diff --git a/app/integrations/cafe24/config.py b/app/integrations/cafe24/config.py
index efa98fb..ad80757 100644
--- a/app/integrations/cafe24/config.py
+++ b/app/integrations/cafe24/config.py
@@ -33,7 +33,10 @@ STORE_SCOPES: tuple[str, ...] = ("mall.read_store", "mall.write_store")
# 실제로 요청하는 scope 묶음. 개발자센터 앱에 등록된 권한과 어긋나면 인증이
# 거부되므로, 여기에 추가할 때는 앱 권한도 함께 확인해야 한다.
# 쓰지 않는 권한은 요청하지 않는다 — 토큰이 유출돼도 피해 범위를 좁히기 위함.
-DEFAULT_SCOPES: tuple[str, ...] = PRODUCT_SCOPES
+# 주문은 읽기만(실적 모듈의 매출 수집) — 앱에 쓰기 권한이 있어도 요청하지 않는다.
+# 이 목록을 바꾸면 카페24 상품관리 → 시스템에서 한 번 다시 연결해야 새 권한이 토큰에 붙는다
+# (기존 토큰은 예전 권한 그대로 계속 동작).
+DEFAULT_SCOPES: tuple[str, ...] = PRODUCT_SCOPES + ("mall.read_order",)
DEFAULT_API_VERSION = "2026-03-01"
diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py
index d931d8e..85cc105 100644
--- a/app/modules/performance/adapters/cafe24.py
+++ b/app/modules/performance/adapters/cafe24.py
@@ -1,49 +1,252 @@
"""카페24 — 공통 연동 계층(app/integrations/cafe24) 재사용.
카페24는 이미 OAuth 로 연결해 쓰고 있다(상품관리). 실적 설정에서 인증정보를 따로
-받지 않고, 같은 토큰 저장소(cafe24_db)의 연결 상태를 그대로 보여 준다.
-주문 수집(다음 단계)에는 카페24 앱 권한에 mall.read_order 추가 + 재연결이 필요하다
-(app/integrations/cafe24/config.py 의 ORDER_SCOPES).
+받지 않고, 같은 토큰 저장소(cafe24_db)와 클라이언트(재시도·429·토큰 자동 갱신)를 쓴다.
+주문 읽기 권한(mall.read_order)이 필요하다 — config.DEFAULT_SCOPES 에 포함, 권한 추가 후
+카페24 상품관리 → 시스템에서 한 번 다시 연결해야 한다.
+
+수집 규칙 (Admin API GET /admin/orders, 문서 버전 2026-09-01 확인)
+ - 결제(SALE): date_type=pay_date(결제일), embed=items. 결제된(paid=T) 주문의 품목마다
+ 품목 결제금액(payment_amount — 할인 반영, 배송비 제외)을 매출로. 사건 날짜 = 결제일.
+ - 취소(CANCEL): date_type=cancel_complete_date. 품목 상태 C40~C43(취소완료)만,
+ 결제 때와 같은 품목 금액을 음수로. 입금전취소(C47~C49)는 매출이 아니었으므로 제외.
+ - 반품(RETURN): date_type=return_complete_date. 품목 상태 R40~R43(반품완료)만 음수로.
+ 부분 반품(0 < claim_quantity < quantity)은 수량 비율로 나눈다.
+ - 교환(E**)은 매출 변화 없음으로 보고 1단계에서는 반영하지 않는다.
+ - 자체몰 주문만(market_id 가 self/빈값). 카페24 로 들어온 다른 마켓(스마트스토어·쿠팡 등)
+ 주문은 해당 쇼핑몰 어댑터와 이중 집계되지 않게 제외한다. 네이버페이 결제는 자체몰 주문이라 포함.
+ - 한 호출 검색기간 3개월 미만 → 60일씩 나눠 요청. limit 최대 1000, offset 최대 15000.
+ - 개인정보(구매자 이름·주소·연락처·계좌)는 저장하지 않는다 — raw 에는 금액·상태 필드만.
"""
from __future__ import annotations
-from .base import AdapterContext, AuthFailed, MarketplaceAdapter, NotConfigured, TokenExpired
+from datetime import date, timedelta
+from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
+from typing import Any, Iterable
+
+from .base import (
+ AdapterContext,
+ ApiError,
+ AuthFailed,
+ MarketplaceAdapter,
+ NotConfigured,
+ SaleEvent,
+ TokenExpired,
+)
+
+ORDER_SCOPE = "mall.read_order"
+PAGE_LIMIT = 1000
+MAX_OFFSET = 15000
+CHUNK_DAYS = 60
+CANCEL_DONE = {"C40", "C41", "C42", "C43"}
+RETURN_DONE = {"R40", "R41", "R42", "R43"}
+SELF_MARKETS = {"", "self", None}
+
+
+def _won(value: Any) -> int:
+ """카페24 금액 문자열("29000.00") → 원 단위 정수."""
+ try:
+ return int(Decimal(str(value or "0")).quantize(Decimal(1), rounding=ROUND_HALF_UP))
+ except (InvalidOperation, ValueError):
+ return 0
+
+
+def _day(value: Any) -> date | None:
+ """"2018-07-04T11:21:35+09:00" / "2017-07-10 15:55:51" → date (카페24 는 KST 로 준다)."""
+ s = str(value or "").strip()
+ if len(s) < 10:
+ return None
+ try:
+ return date.fromisoformat(s[:10])
+ except ValueError:
+ return None
+
+
+def item_amount(item: dict[str, Any]) -> int:
+ """품목 결제금액. payment_amount 가 없으면 (판매가+옵션가)×수량 − 품목 할인으로 계산."""
+ if item.get("payment_amount") not in (None, ""):
+ return _won(item["payment_amount"])
+ qty = int(item.get("quantity") or 0)
+ gross = (_won(item.get("product_price")) + _won(item.get("option_price"))) * qty
+ discounts = (_won(item.get("additional_discount_price")) + _won(item.get("coupon_discount_price"))
+ + _won(item.get("app_item_discount_amount")))
+ return max(0, gross - discounts)
+
+
+def _raw(order: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
+ """저장용 원본 — 금액·상태만(개인정보 제외)."""
+ keys = ("order_item_code", "order_status", "status_code", "product_no", "product_code", "variant_code",
+ "product_price", "option_price", "quantity", "claim_quantity", "additional_discount_price",
+ "coupon_discount_price", "app_item_discount_amount", "payment_amount", "claim_code")
+ return {
+ "order_id": order.get("order_id"), "market_id": order.get("market_id"),
+ "order_place_id": order.get("order_place_id"), "paid": order.get("paid"),
+ **{k: item.get(k) for k in keys},
+ }
class Cafe24Adapter(MarketplaceAdapter):
code = "cafe24"
name = "카페24"
auth_type = "shared"
- docs_url = "https://developers.cafe24.com/docs/api/admin/"
- note = "카페24 상품관리에서 연결한 OAuth 토큰을 함께 씁니다(여기서 따로 입력하지 않음)."
+ implemented = True
+ docs_url = "https://apidocs.cafe24.com/docs/admin/get-orders"
+ note = ("카페24 상품관리에서 연결한 OAuth 토큰을 함께 씁니다(여기서 따로 입력하지 않음). "
+ "주문 읽기 권한이 필요해 권한 추가 후 한 번 다시 연결해야 합니다.")
+ # ── 연결 ──────────────────────────────────────────────
def is_configured(self, ctx: AdapterContext) -> bool:
return True
+ def _repo(self, ctx: AdapterContext):
+ return getattr(ctx.app_state, "cafe24_store", None) if ctx.app_state is not None else None
+
+ def shared_status(self, ctx: AdapterContext) -> dict:
+ from app.integrations.cafe24.config import load_config # 지연 import
+ from app.integrations.cafe24.tokens import TokenService # 지연 import
+
+ repo = self._repo(ctx)
+ config = load_config()
+ if repo is None:
+ return {"connected": False, "missing": config.missing or ["CAFE24_DB_URL"], "needs_reauth": False}
+ return TokenService(repo, config).status()
+
def authenticate(self, ctx: AdapterContext) -> None:
st = self.shared_status(ctx)
if not st.get("connected"):
if st.get("missing"):
raise NotConfigured("카페24 연동 환경변수가 설정되지 않았습니다.")
- if st.get("needs_reauth") and st.get("reason", "").startswith("refresh"):
+ if st.get("needs_reauth") and str(st.get("reason", "")).startswith("refresh"):
raise TokenExpired("카페24 연결이 만료되었습니다. 카페24 상품관리 → 시스템에서 재연결하세요.")
raise AuthFailed("카페24에 연결되어 있지 않습니다. 카페24 상품관리 → 시스템에서 연결하세요.")
+ if ORDER_SCOPE not in str(st.get("scopes") or ""):
+ raise AuthFailed("카페24 토큰에 주문 읽기 권한(mall.read_order)이 없습니다. "
+ "카페24 상품관리 → 시스템에서 다시 연결하세요.")
- def shared_status(self, ctx: AdapterContext) -> dict:
- from app.integrations.cafe24.config import load_config # 지연 import
- from app.integrations.cafe24.tokens import TokenService # 지연 import
+ def _client(self, ctx: AdapterContext):
+ from app.integrations.cafe24 import build_cafe24_api # 지연 import
- repo = getattr(ctx.app_state, "cafe24_store", None) if ctx.app_state is not None else None
- config = load_config()
- if repo is None:
- return {"connected": False, "missing": config.missing or ["CAFE24_DB_URL"], "needs_reauth": False}
- return TokenService(repo, config).status()
+ return build_cafe24_api(self._repo(ctx)).client
+
+ def _get(self, ctx: AdapterContext, params: dict[str, Any]) -> dict[str, Any]:
+ from app.integrations.cafe24.errors import ( # 지연 import
+ Cafe24ApiError,
+ Cafe24AuthError,
+ Cafe24ConfigError,
+ Cafe24RateLimitError,
+ )
+
+ try:
+ return self._client(ctx).get("/admin/orders", params=params)
+ except Cafe24ConfigError as exc:
+ raise NotConfigured(str(exc)) from None
+ except Cafe24AuthError as exc:
+ raise AuthFailed(str(exc)) from None
+ except Cafe24RateLimitError as exc:
+ raise ApiError(f"카페24 호출 제한(429): {exc}") from None
+ except Cafe24ApiError as exc:
+ status = getattr(exc, "status", None)
+ if status == 403:
+ raise AuthFailed(f"카페24 권한 오류(403): {exc}. 주문 권한 추가 후 재연결하세요.") from None
+ raise ApiError(f"카페24 API 오류({status}): {exc}") from None
def test_connection(self, ctx: AdapterContext) -> str:
+ from app.timezone import today_kst # noqa: WPS433
+
self.authenticate(ctx)
- st = self.shared_status(ctx)
- scopes = st.get("scopes") or ""
- if "mall.read_order" not in scopes:
- return "카페24 연결 정상. 주문 수집에는 주문 읽기 권한(mall.read_order) 추가가 필요합니다."
- return "카페24 연결 정상."
+ today = today_kst()
+ self._get(ctx, {"start_date": today.isoformat(), "end_date": today.isoformat(),
+ "date_type": "pay_date", "limit": 1})
+ return "카페24 연결 정상(주문 조회 권한 확인)."
+
+ # ── 수집 ──────────────────────────────────────────────
+ def _orders(self, ctx: AdapterContext, start: date, end: date, date_type: str) -> Iterable[dict[str, Any]]:
+ """기간을 60일씩 나눠 페이지를 넘기며 주문(+items)을 모두 가져온다."""
+ s = start
+ while s <= end:
+ e = min(end, s + timedelta(days=CHUNK_DAYS - 1))
+ offset = 0
+ while True:
+ if offset > MAX_OFFSET:
+ raise ApiError(f"카페24 조회 건수가 너무 많습니다({s}~{e}). 기간을 줄여 다시 시도하세요.")
+ data = self._get(ctx, {"start_date": s.isoformat(), "end_date": e.isoformat(),
+ "date_type": date_type, "embed": "items",
+ "limit": PAGE_LIMIT, "offset": offset})
+ orders = data.get("orders") or []
+ yield from orders
+ if len(orders) < PAGE_LIMIT:
+ break
+ offset += PAGE_LIMIT
+ s = e + timedelta(days=1)
+
+ def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
+ for o in self._orders(ctx, start, end, "pay_date"):
+ yield {"kind": "paid", "order": o}
+
+ def fetch_refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
+ for o in self._orders(ctx, start, end, "cancel_complete_date"):
+ yield {"kind": "cancel", "order": o}
+ for o in self._orders(ctx, start, end, "return_complete_date"):
+ yield {"kind": "return", "order": o}
+
+ @staticmethod
+ def _is_self_order(order: dict[str, Any]) -> bool:
+ return order.get("market_id") in SELF_MARKETS
+
+ def normalize_order(self, raw: dict[str, Any]) -> list[SaleEvent]:
+ order = raw.get("order") or {}
+ if not self._is_self_order(order) or order.get("paid") != "T":
+ return []
+ pay_day = _day(order.get("payment_date"))
+ if pay_day is None:
+ return []
+ order_id = str(order.get("order_id") or "")
+ events = []
+ for item in order.get("items") or []:
+ code = str(item.get("order_item_code") or "")
+ if not code:
+ continue
+ events.append(SaleEvent(
+ event_type="SALE", external_event_id=f"{code}-S", external_order_id=order_id,
+ external_line_id=code, order_date=_day(order.get("order_date")), payment_date=pay_day,
+ event_date=pay_day, amount=item_amount(item), product_name=str(item.get("product_name") or ""),
+ option_name=str(item.get("option_value") or "") if isinstance(item.get("option_value"), str) else "",
+ quantity=int(item.get("quantity") or 0), order_status=str(item.get("order_status") or ""),
+ raw=_raw(order, item),
+ ))
+ return events
+
+ def normalize_refund(self, raw: dict[str, Any]) -> list[SaleEvent]:
+ order = raw.get("order") or {}
+ if not self._is_self_order(order):
+ return []
+ kind = raw.get("kind")
+ done, ev_type, suffix = (CANCEL_DONE, "CANCEL", "C") if kind == "cancel" else (RETURN_DONE, "RETURN", "R")
+ order_id = str(order.get("order_id") or "")
+ events = []
+ for item in order.get("items") or []:
+ code = str(item.get("order_item_code") or "")
+ status = str(item.get("order_status") or "")
+ if not code or status not in done:
+ continue
+ if kind == "cancel":
+ day = _day(item.get("cancel_date")) or _day(order.get("cancel_date"))
+ else:
+ day = _day(item.get("return_confirmed_date")) or _day(item.get("refund_date"))
+ if day is None:
+ continue
+ amount = item_amount(item)
+ qty = int(item.get("quantity") or 0)
+ claim = int(item.get("claim_quantity") or 0)
+ if kind == "return" and 0 < claim < qty:
+ amount = int((Decimal(amount) * claim / qty).quantize(Decimal(1), rounding=ROUND_HALF_UP))
+ qty = claim
+ events.append(SaleEvent(
+ event_type=ev_type, external_event_id=f"{code}-{suffix}", external_order_id=order_id,
+ external_line_id=code, order_date=_day(order.get("order_date")),
+ payment_date=_day(order.get("payment_date")), event_date=day, amount=-amount,
+ product_name=str(item.get("product_name") or ""), quantity=-qty, order_status=status,
+ raw=_raw(order, item),
+ ))
+ return events
diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py
index d5f7ae1..479905d 100644
--- a/app/modules/performance/router.py
+++ b/app/modules/performance/router.py
@@ -36,6 +36,7 @@ from .adapters.registry import all_adapters, get_adapter
router = APIRouter(prefix="/performance", tags=["performance"])
MAX_EVENT_DAYS = 31
+MAX_BACKFILL_DAYS = 366
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
@@ -127,10 +128,26 @@ 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 로 기간을 지정한 수집(과거 매출 가져오기)은 관리자만."""
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))]
- results = sync.sync_all(codes=codes or None, user=user["email"])
+ start = _parse_date(payload.get("from"), field="시작일")
+ end = _parse_date(payload.get("to"), field="종료일")
+ 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:
+ raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_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 ef87ca1..1ba74ca 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -235,4 +235,4 @@
} | 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 2cdec23..3dc985b 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -102,6 +102,19 @@
+
+
과거 매출 가져오기
+
[매출 업데이트]는 최근 며칠만 가져옵니다. 처음 연동했거나 빠진 기간이 있으면 기간을 지정해 한 번에
+ 가져오세요(연동된 쇼핑몰만, 최대 366일). 같은 주문은 덮어써서 여러 번 해도 중복되지 않습니다.
+
+
+ ~
+
+
+
+
+
+
테스트 데이터
현재 {{ "{:,}".format(sample_count) }}건
@@ -118,4 +131,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 bf78aeb..21d494b 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -378,6 +378,91 @@ def test_not_implemented_and_mock():
assert event_row(a[0])["sales_date"] == a[0].payment_date
+# ════════════════════════════════════════════════════════════
+# 카페24 어댑터(가짜 API 응답)
+# ════════════════════════════════════════════════════════════
+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, 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}
+
+
+class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist=["Cafe24Adapter"]).Cafe24Adapter):
+ def __init__(self, pages):
+ self.pages = pages # date_type → [응답 orders 목록(페이지별)]
+ 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 test_cafe24_normalize():
+ from app.modules.performance.adapters.cafe24 import Cafe24Adapter, item_amount
+
+ 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개 반품
+ 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
+ # 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"]
+ 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)
+ # 주문 권한 없는 토큰 → 인증 실패(재연결 안내)
+ real = Cafe24Adapter()
+ real.shared_status = lambda ctx: {"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.authenticate(ctx)
+
+
def test_registry_and_event_validation():
codes = [a.code for a in all_adapters()]
assert len(codes) == len(set(codes)) == 10
diff --git a/app/static/performance.js b/app/static/performance.js
index e61f20d..2be3082 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -470,6 +470,46 @@
} finally { btn.disabled = false; btn.textContent = label; }
}
+ // ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
+ const backfill = document.getElementById("perf-backfill");
+ if (backfill) backfill.addEventListener("click", async function () {
+ const from = document.getElementById("perf-backfill-from").value;
+ const to = document.getElementById("perf-backfill-to").value;
+ const box = document.getElementById("perf-backfill-result");
+ if (!from || !to) return;
+ if (!(await confirmMsg(from + " ~ " + to + " 매출을 연동된 쇼핑몰에서 가져옵니다. 기간이 길면 몇 분 걸릴 수 있습니다."))) return;
+ const names = {};
+ root.querySelectorAll("tr[data-code]").forEach(function (tr) { names[tr.dataset.code] = tr.dataset.name; });
+ backfill.disabled = true;
+ backfill.textContent = "가져오는 중…";
+ box.hidden = true;
+ try {
+ const res = await api("POST", "/performance/api/sync", { from: from, to: to });
+ const ok = [], bad = [], rest = [];
+ (res.results || []).forEach(function (r) {
+ const name = names[r.code] || r.code;
+ if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
+ else if (r.skipped) rest.push(name + "(이미 진행 중)");
+ else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name);
+ else bad.push(name + "(" + (r.label || r.status) + ": " + (r.message || "") + ")");
+ });
+ box.innerHTML = [
+ ok.length ? "반영 " + esc(ok.join(", ")) : "",
+ bad.length ? "실패 " + esc(bad.join(", ")) : "",
+ rest.length ? '건너뜀(미연동·미설정): ' + esc(rest.join(", ")) + "" : "",
+ ].filter(Boolean).join(" · ") || "가져올 쇼핑몰이 없습니다.";
+ box.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
+ box.hidden = false;
+ } catch (err) {
+ box.textContent = "가져오기 실패: " + err.message;
+ box.className = "perf-notice is-warn";
+ box.hidden = false;
+ } finally {
+ backfill.disabled = false;
+ backfill.textContent = "가져오기";
+ }
+ });
+
// ── 테스트 데이터 / 재암호화 ──
const gen = document.getElementById("perf-sample-gen");
if (gen) gen.addEventListener("click", async function () {
diff --git a/docs/CAFE24_MODULE.md b/docs/CAFE24_MODULE.md
index ce739d1..80731d3 100644
--- a/docs/CAFE24_MODULE.md
+++ b/docs/CAFE24_MODULE.md
@@ -306,10 +306,10 @@ code → access/refresh token 교환
cafe24_oauth_tokens 저장
```
-- scope 는 `app/integrations/cafe24/config.py` 의 `PRODUCT_SCOPES` =
- `mall.read_product`, `mall.write_product`.
- 주문관리 추가 시 `ORDER_SCOPES` 를 합쳐 넘기고, 카페24 개발자센터 앱에서도
- 권한을 추가한 뒤 **재인증**하면 된다.
+- scope 는 `app/integrations/cafe24/config.py` 의 `DEFAULT_SCOPES` =
+ `mall.read_product`, `mall.write_product`, `mall.read_order`(실적 모듈 매출 수집, 읽기만).
+ 목록을 바꾸면 카페24 개발자센터 앱에도 그 권한이 있어야 하고(없으면 인증 거부),
+ **재인증**해야 새 권한이 토큰에 붙는다. 재인증 전 기존 토큰은 예전 권한 그대로 계속 동작한다.
- access token 은 만료 2분 전부터 자동 갱신된다. 갱신은 토큰 행을
`SELECT ... FOR UPDATE` 로 잠근 채 수행 — web 컨테이너와 worker 컨테이너가
동시에 refresh 해서 한쪽 토큰이 무효화되는 것을 막는다(카페24는 refresh
@@ -535,7 +535,8 @@ cafe24_oauth_tokens 저장
1. 로그인 → 앱 생성
2. Redirect URI 를 `.env` 의 `CAFE24_REDIRECT_URI` 와 **정확히 동일하게** 등록
(운영: `https://dbx.no1king.freeddns.org/cafe24/oauth/callback`)
-3. 권한(Scope)에 `mall.read_product`, `mall.write_product` 체크
+3. 권한(Scope)에 상품(Product) 읽기+쓰기, 주문(Order) 읽기 이상 체크
+ (`mall.read_product`, `mall.write_product`, `mall.read_order` — 주문은 실적 모듈이 매출 수집에 사용)
4. 발급된 Client ID / Client Secret 을 `.env` 에 기입
### 5-2. DB 초기화 (superuser 로 1회)
diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md
index e1421cc..9758bd2 100644
--- a/docs/PERFORMANCE_MODULE.md
+++ b/docs/PERFORMANCE_MODULE.md
@@ -29,9 +29,27 @@
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
-**현재(1단계)**: 10개 어댑터 모두 입력칸만 정의, 수집은 `NotImplementedYet`. 카페24는 `auth_type="shared"` — 기존
-`app/integrations/cafe24` OAuth 토큰(cafe24_db)을 재사용해 연결 상태만 확인한다(주문 수집 시 앱 권한에
-`mall.read_order` 추가 + 재연결 필요). 쇼핑몰별 입력칸은 **연동 단계에서 공식 API 문서로 확정**한다.
+**연동 현황**: 카페24 = **구현됨**, 나머지 9개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
+**연동 단계에서 공식 API 문서로 확정**한다.
+
+### 카페24 (`adapters/cafe24.py`, 구현됨)
+
+`auth_type="shared"` — 기존 `app/integrations/cafe24` OAuth 토큰(cafe24_db)과 클라이언트(재시도·429·토큰 자동 갱신)를
+재사용한다. 토큰에 `mall.read_order` 가 있어야 한다(`DEFAULT_SCOPES` 포함, 권한 추가 후 카페24 상품관리 → 시스템에서 재연결).
+Admin API `GET /admin/orders`(문서 버전 2026-09-01 확인: 검색기간 한 호출 3개월 미만, limit ≤ 1000, offset ≤ 15000).
+
+| 사건 | 조회 | 대상 | 금액·날짜 |
+|---|---|---|---|
+| SALE | `date_type=pay_date`, `embed=items` | `paid=T` 주문의 모든 품목 | +품목 결제금액(`payment_amount`, 할인 반영·배송비 제외), 결제일 |
+| CANCEL | `date_type=cancel_complete_date` | 품목 상태 C40~C43(취소완료). 입금전취소 C47~C49 제외 | −같은 품목 금액, 품목 `cancel_date` |
+| RETURN | `date_type=return_complete_date` | 품목 상태 R40~R43(반품완료) | −품목 금액(부분 반품은 `claim_quantity/quantity` 비율), `return_confirmed_date` |
+
+- 사건 ID = `{order_item_code}-S|C|R` (중복 방지). 교환(E**)은 1단계에서 반영 안 함.
+- **자체몰 주문만**(`market_id` = self/빈값). 카페24 로 연동돼 들어온 다른 마켓 주문(스마트스토어·쿠팡 등)은 해당 쇼핑몰
+ 어댑터와 이중 집계되지 않게 제외. 네이버페이 결제(`order_place_id=NCHECKOUT`)는 자체몰 주문이라 포함.
+- 기간은 60일씩 나눠 요청, 1000건 단위 페이지. 개인정보(구매자 이름·주소·연락처·계좌)는 저장하지 않고 raw 에는 금액·상태만.
+- **실데이터로 확인할 것**: 품목 `payment_amount` 가 적립금·예치금 사용분을 어떻게 반영하는지, 부분 취소/반품 시 품목이
+ 분리되는지(`claim_quantity` 해석). 카페24 관리자 화면 매출과 한 주 정도 대조 후 필요하면 규칙 조정.
### 연동 단계 체크리스트(쇼핑몰마다)
@@ -92,6 +110,8 @@
- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·향후 cron/worker 공용. 기본 기간: 오늘 포함 최근
`PERFORMANCE_SYNC_DAYS`(기본 7)일.
+- **과거 매출 가져오기**(설정 화면, 관리자): `POST /api/sync {from, to}` — 기간 지정 수집(최대 366일, 미래는 오늘까지).
+ 처음 연동했거나 빠진 기간을 채울 때. 같은 사건은 덮어써서 여러 번 해도 중복 없음. 일반 사용자가 기간을 주면 403.
- 같은 쇼핑몰 동시 실행 금지: `perf_sync_runs` 의 `status='running'` 부분 유니크 인덱스(30분 넘은 running 은 정리).
- 쇼핑몰 하나 실패 → 그 쇼핑몰만 상태 오류(`perf_connection_status`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고
상단에 오류 쇼핑몰만 표시.
From 27ee92c0a69c084ee209ae478a19673c607345d1 Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 16:38:44 +0900
Subject: [PATCH 04/30] =?UTF-8?q?fix(performance):=20=EC=B9=B4=ED=8E=9824?=
=?UTF-8?q?=20=EB=A7=A4=EC=B6=9C=EC=9D=84=20=EC=B9=B4=ED=8E=9824=20"?=
=?UTF-8?q?=EC=9D=BC=EB=B3=84=20=EB=A7=A4=EC=B6=9C=EB=82=B4=EC=97=AD"=20?=
=?UTF-8?q?=EA=B8=B0=EC=A4=80=EC=9C=BC=EB=A1=9C(=EA=B2=B0=EC=A0=9C?=
=?UTF-8?q?=ED=95=A9=EA=B3=84=C2=B7=ED=99=98=EB=B6=88=ED=95=A9=EA=B3=84)?=
=?UTF-8?q?=20+=20=EB=A7=A4=EC=B6=9C=20=EB=8C=80=EC=A1=B0=20=EB=8F=84?=
=?UTF-8?q?=EA=B5=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
원인: 품목 결제금액(배송비 제외)을 매출로, 취소·반품 완료일의 품목 금액을 환불로 잡아
카페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
---
app/modules/performance/adapters/base.py | 4 +
app/modules/performance/adapters/cafe24.py | 284 +++++++++++-------
app/modules/performance/db.py | 55 ++--
app/modules/performance/router.py | 10 +
app/modules/performance/sync.py | 22 +-
.../templates/performance/index.html | 2 +-
.../templates/performance/settings.html | 13 +-
.../performance/tests/test_performance.py | 154 ++++++----
app/static/performance.js | 54 ++++
docs/PERFORMANCE_MODULE.md | 28 +-
10 files changed, 421 insertions(+), 205 deletions(-)
diff --git a/app/modules/performance/adapters/base.py b/app/modules/performance/adapters/base.py
index 15e2396..a7e6328 100644
--- a/app/modules/performance/adapters/base.py
+++ b/app/modules/performance/adapters/base.py
@@ -144,6 +144,10 @@ class MarketplaceAdapter(ABC):
auth_type: str = "api_key" # api_key / oauth / shared(공통 연동 계층 재사용)
docs_url: str = ""
implemented: bool = False # 실제 수집(fetch)이 구현됐는가
+ # True 면 동기화 때 그 기간(sales_date)의 이 쇼핑몰 실데이터를 지우고 새로 넣는다(한 트랜잭션).
+ # 쇼핑몰 API 가 "기간 안 결제·환불"을 빠짐없이 돌려줄 때만 켠다 — 규칙이 바뀌거나
+ # 주문이 사라져도 예전 행이 남지 않는다. False 면 같은 사건 ID 만 덮어쓴다(upsert).
+ replace_range: bool = False
note: str = "" # 설정 화면 안내 문구
# ── 설정 ──────────────────────────────────────────────
diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py
index 85cc105..7db0708 100644
--- a/app/modules/performance/adapters/cafe24.py
+++ b/app/modules/performance/adapters/cafe24.py
@@ -5,18 +5,21 @@
주문 읽기 권한(mall.read_order)이 필요하다 — config.DEFAULT_SCOPES 에 포함, 권한 추가 후
카페24 상품관리 → 시스템에서 한 번 다시 연결해야 한다.
-수집 규칙 (Admin API GET /admin/orders, 문서 버전 2026-09-01 확인)
- - 결제(SALE): date_type=pay_date(결제일), embed=items. 결제된(paid=T) 주문의 품목마다
- 품목 결제금액(payment_amount — 할인 반영, 배송비 제외)을 매출로. 사건 날짜 = 결제일.
- - 취소(CANCEL): date_type=cancel_complete_date. 품목 상태 C40~C43(취소완료)만,
- 결제 때와 같은 품목 금액을 음수로. 입금전취소(C47~C49)는 매출이 아니었으므로 제외.
- - 반품(RETURN): date_type=return_complete_date. 품목 상태 R40~R43(반품완료)만 음수로.
- 부분 반품(0 < claim_quantity < quantity)은 수량 비율로 나눈다.
- - 교환(E**)은 매출 변화 없음으로 보고 1단계에서는 반영하지 않는다.
- - 자체몰 주문만(market_id 가 self/빈값). 카페24 로 들어온 다른 마켓(스마트스토어·쿠팡 등)
- 주문은 해당 쇼핑몰 어댑터와 이중 집계되지 않게 제외한다. 네이버페이 결제는 자체몰 주문이라 포함.
- - 한 호출 검색기간 3개월 미만 → 60일씩 나눠 요청. limit 최대 1000, offset 최대 15000.
+카페24 관리자 "일별 매출내역"과 같은 기준으로 센다(Admin API 문서 2026-09-01 확인).
+ - 결제합계(SALE, +): GET /admin/orders date_type=pay_date(결제일), 결제된(paid=T) 주문마다
+ 상품구매금액 + 배송비 − 할인 − 쿠폰 (주문의 initial_order_amount — 결제 당시 금액)
+ 환불은 따로 빼므로 취소 후 금액(actual_order_amount)이 아니라 결제 당시 금액을 쓴다.
+ - 환불합계(CANCEL/RETURN, −): GET /admin/refunds date_type=refund_date(환불완료일),
+ 실제 환불액(actual_refund_amount). 환불코드가 R 로 시작하면 반품, 그 밖은 취소.
+ - 수집 기간을 통째로 다시 받는다(replace_range) — 결제·환불 모두 기간 안 날짜로 조회되므로
+ 그 기간의 카페24 실데이터를 지우고 새로 넣는다. 규칙이 바뀌거나 주문이 사라져도 이중 집계 없음.
+ - 자체몰 주문만(market_id 가 self/빈값). 카페24 로 연동돼 들어온 다른 마켓(스마트스토어·쿠팡 등)
+ 주문은 해당 쇼핑몰 어댑터와 이중 집계되지 않게 제외(환불도 원 주문의 market_id 로 판단).
+ 네이버페이 결제(order_place_id=NCHECKOUT)는 자체몰 주문이라 포함.
+ - 한 호출 검색기간 3개월 미만 → 60일씩 나눠 요청. orders limit ≤ 1000, refunds limit ≤ 500, offset ≤ 15000.
- 개인정보(구매자 이름·주소·연락처·계좌)는 저장하지 않는다 — raw 에는 금액·상태 필드만.
+ - 할인 항목 구성·마켓 주문 포함 여부는 `reconcile()`(설정 화면 "카페24 매출 대조")로 카페24 화면과
+ 대조해 확정한다.
"""
from __future__ import annotations
@@ -36,13 +39,20 @@ from .base import (
)
ORDER_SCOPE = "mall.read_order"
-PAGE_LIMIT = 1000
+ORDER_LIMIT = 1000
+REFUND_LIMIT = 500
+LOOKUP_BATCH = 100
MAX_OFFSET = 15000
CHUNK_DAYS = 60
-CANCEL_DONE = {"C40", "C41", "C42", "C43"}
-RETURN_DONE = {"R40", "R41", "R42", "R43"}
SELF_MARKETS = {"", "self", None}
+# 결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰 (initial_order_amount 의 필드)
+DISCOUNT_FIELDS = ("membership_discount_amount", "set_product_discount_amount", "app_discount_amount",
+ "market_other_discount_amount", "shipping_fee_discount_amount")
+COUPON_FIELDS = ("coupon_discount_price", "coupon_shipping_fee_amount")
+AMOUNT_FIELDS = ("order_price_amount", "shipping_fee", *DISCOUNT_FIELDS, *COUPON_FIELDS,
+ "points_spent_amount", "credits_spent_amount", "payment_amount")
+
def _won(value: Any) -> int:
"""카페24 금액 문자열("29000.00") → 원 단위 정수."""
@@ -63,27 +73,29 @@ def _day(value: Any) -> date | None:
return None
-def item_amount(item: dict[str, Any]) -> int:
- """품목 결제금액. payment_amount 가 없으면 (판매가+옵션가)×수량 − 품목 할인으로 계산."""
- if item.get("payment_amount") not in (None, ""):
- return _won(item["payment_amount"])
- qty = int(item.get("quantity") or 0)
- gross = (_won(item.get("product_price")) + _won(item.get("option_price"))) * qty
- discounts = (_won(item.get("additional_discount_price")) + _won(item.get("coupon_discount_price"))
- + _won(item.get("app_item_discount_amount")))
- return max(0, gross - discounts)
+def order_amounts(order: dict[str, Any]) -> dict[str, int]:
+ """결제 당시 금액(initial_order_amount, 없으면 actual_order_amount) 항목별 원 단위."""
+ a = order.get("initial_order_amount") or order.get("actual_order_amount") or {}
+ return {k: _won(a.get(k)) for k in AMOUNT_FIELDS}
-def _raw(order: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
- """저장용 원본 — 금액·상태만(개인정보 제외)."""
- keys = ("order_item_code", "order_status", "status_code", "product_no", "product_code", "variant_code",
- "product_price", "option_price", "quantity", "claim_quantity", "additional_discount_price",
- "coupon_discount_price", "app_item_discount_amount", "payment_amount", "claim_code")
- return {
- "order_id": order.get("order_id"), "market_id": order.get("market_id"),
- "order_place_id": order.get("order_place_id"), "paid": order.get("paid"),
- **{k: item.get(k) for k in keys},
- }
+def order_total(order: dict[str, Any]) -> int:
+ """결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰."""
+ a = order_amounts(order)
+ return (a["order_price_amount"] + a["shipping_fee"]
+ - sum(a[k] for k in DISCOUNT_FIELDS) - sum(a[k] for k in COUPON_FIELDS))
+
+
+def is_self_market(market_id: Any) -> bool:
+ return market_id in SELF_MARKETS
+
+
+def _chunks(start: date, end: date) -> Iterable[tuple[date, date]]:
+ s = start
+ while s <= end:
+ e = min(end, s + timedelta(days=CHUNK_DAYS - 1))
+ yield s, e
+ s = e + timedelta(days=1)
class Cafe24Adapter(MarketplaceAdapter):
@@ -91,6 +103,7 @@ class Cafe24Adapter(MarketplaceAdapter):
name = "카페24"
auth_type = "shared"
implemented = True
+ replace_range = True
docs_url = "https://apidocs.cafe24.com/docs/admin/get-orders"
note = ("카페24 상품관리에서 연결한 OAuth 토큰을 함께 씁니다(여기서 따로 입력하지 않음). "
"주문 읽기 권한이 필요해 권한 추가 후 한 번 다시 연결해야 합니다.")
@@ -129,7 +142,7 @@ class Cafe24Adapter(MarketplaceAdapter):
return build_cafe24_api(self._repo(ctx)).client
- def _get(self, ctx: AdapterContext, params: dict[str, Any]) -> dict[str, Any]:
+ def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
from app.integrations.cafe24.errors import ( # 지연 import
Cafe24ApiError,
Cafe24AuthError,
@@ -138,7 +151,7 @@ class Cafe24Adapter(MarketplaceAdapter):
)
try:
- return self._client(ctx).get("/admin/orders", params=params)
+ return self._client(ctx).get(path, params=params)
except Cafe24ConfigError as exc:
raise NotConfigured(str(exc)) from None
except Cafe24AuthError as exc:
@@ -155,98 +168,137 @@ class Cafe24Adapter(MarketplaceAdapter):
from app.timezone import today_kst # noqa: WPS433
self.authenticate(ctx)
- today = today_kst()
- self._get(ctx, {"start_date": today.isoformat(), "end_date": today.isoformat(),
- "date_type": "pay_date", "limit": 1})
+ today = today_kst().isoformat()
+ self._get(ctx, "/admin/orders", {"start_date": today, "end_date": today, "date_type": "pay_date", "limit": 1})
return "카페24 연결 정상(주문 조회 권한 확인)."
- # ── 수집 ──────────────────────────────────────────────
- def _orders(self, ctx: AdapterContext, start: date, end: date, date_type: str) -> Iterable[dict[str, Any]]:
- """기간을 60일씩 나눠 페이지를 넘기며 주문(+items)을 모두 가져온다."""
- s = start
- while s <= end:
- e = min(end, s + timedelta(days=CHUNK_DAYS - 1))
- offset = 0
- while True:
- if offset > MAX_OFFSET:
- raise ApiError(f"카페24 조회 건수가 너무 많습니다({s}~{e}). 기간을 줄여 다시 시도하세요.")
- data = self._get(ctx, {"start_date": s.isoformat(), "end_date": e.isoformat(),
- "date_type": date_type, "embed": "items",
- "limit": PAGE_LIMIT, "offset": offset})
- orders = data.get("orders") or []
- yield from orders
- if len(orders) < PAGE_LIMIT:
- break
- offset += PAGE_LIMIT
- s = e + timedelta(days=1)
+ # ── 조회 ──────────────────────────────────────────────
+ def _paged(self, ctx: AdapterContext, path: str, key: str, params: dict[str, Any],
+ limit: int) -> Iterable[dict[str, Any]]:
+ offset = 0
+ while True:
+ if offset > MAX_OFFSET:
+ raise ApiError(f"카페24 조회 건수가 너무 많습니다({params.get('start_date')}~{params.get('end_date')}). "
+ "기간을 줄여 다시 시도하세요.")
+ rows = self._get(ctx, path, {**params, "limit": limit, "offset": offset}).get(key) or []
+ yield from rows
+ if len(rows) < limit:
+ return
+ offset += limit
+ def paid_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
+ for s, e in _chunks(start, end):
+ yield from self._paged(ctx, "/admin/orders", "orders",
+ {"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]]:
+ 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)
+
+ def market_ids(self, ctx: AdapterContext, refunds: list[dict[str, Any]]) -> dict[str, Any]:
+ """환불의 원 주문 market_id — 주문일 60일 구간·100건씩 묶어 조회."""
+ pairs = sorted({(_day(r.get("order_date")) or date.min, str(r.get("order_id") or ""))
+ for r in refunds if r.get("order_id")})
+ out: dict[str, Any] = {}
+ i = 0
+ while i < len(pairs):
+ first = pairs[i][0]
+ group = [p for p in pairs[i:i + LOOKUP_BATCH] if (p[0] - first).days < CHUNK_DAYS]
+ ids = [oid for _, oid in group]
+ if first != date.min:
+ params = {"order_id": ",".join(ids), "start_date": first.isoformat(),
+ "end_date": group[-1][0].isoformat(), "date_type": "order_date", "limit": LOOKUP_BATCH}
+ for o in self._get(ctx, "/admin/orders", params).get("orders") or []:
+ out[str(o.get("order_id"))] = o.get("market_id")
+ i += len(group)
+ return out
+
+ # ── 수집(어댑터 공통 흐름) ──────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
- for o in self._orders(ctx, start, end, "pay_date"):
- yield {"kind": "paid", "order": o}
+ yield from self.paid_orders(ctx, start, end)
def fetch_refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
- for o in self._orders(ctx, start, end, "cancel_complete_date"):
- yield {"kind": "cancel", "order": o}
- for o in self._orders(ctx, start, end, "return_complete_date"):
- yield {"kind": "return", "order": o}
+ rows = [r for r in self.refunds(ctx, start, end) if str(r.get("status") or "T") == "T"]
+ markets = self.market_ids(ctx, rows)
+ for r in rows:
+ yield {**r, "_market_id": markets.get(str(r.get("order_id")), "self")}
- @staticmethod
- def _is_self_order(order: dict[str, Any]) -> bool:
- return order.get("market_id") in SELF_MARKETS
-
- def normalize_order(self, raw: dict[str, Any]) -> list[SaleEvent]:
- order = raw.get("order") or {}
- if not self._is_self_order(order) or order.get("paid") != "T":
+ def normalize_order(self, order: dict[str, Any]) -> list[SaleEvent]:
+ if not is_self_market(order.get("market_id")) or order.get("paid") != "T":
return []
pay_day = _day(order.get("payment_date"))
if pay_day is None:
return []
- order_id = str(order.get("order_id") or "")
- events = []
- for item in order.get("items") or []:
- code = str(item.get("order_item_code") or "")
- if not code:
- continue
- events.append(SaleEvent(
- event_type="SALE", external_event_id=f"{code}-S", external_order_id=order_id,
- external_line_id=code, order_date=_day(order.get("order_date")), payment_date=pay_day,
- event_date=pay_day, amount=item_amount(item), product_name=str(item.get("product_name") or ""),
- option_name=str(item.get("option_value") or "") if isinstance(item.get("option_value"), str) else "",
- quantity=int(item.get("quantity") or 0), order_status=str(item.get("order_status") or ""),
- raw=_raw(order, item),
- ))
- return events
+ items = order.get("items") or []
+ names = [str(i.get("product_name") or "") for i in items if i.get("product_name")]
+ name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
+ oid = str(order.get("order_id") or "")
+ return [SaleEvent(
+ event_type="SALE", external_event_id=f"{oid}-PAY", external_order_id=oid,
+ order_date=_day(order.get("order_date")), payment_date=pay_day, event_date=pay_day,
+ amount=max(0, order_total(order)), product_name=name,
+ quantity=sum(int(i.get("quantity") or 0) for i in items), order_status="결제완료",
+ discount_amount=sum(order_amounts(order)[k] for k in DISCOUNT_FIELDS + COUPON_FIELDS),
+ raw={"order_id": oid, "market_id": order.get("market_id"), "order_place_id": order.get("order_place_id"),
+ "items": len(items), **{f"initial_{k}": v for k, v in order_amounts(order).items()}},
+ )]
- def normalize_refund(self, raw: dict[str, Any]) -> list[SaleEvent]:
- order = raw.get("order") or {}
- if not self._is_self_order(order):
+ def normalize_refund(self, refund: dict[str, Any]) -> list[SaleEvent]:
+ if not is_self_market(refund.get("_market_id")):
return []
- kind = raw.get("kind")
- done, ev_type, suffix = (CANCEL_DONE, "CANCEL", "C") if kind == "cancel" else (RETURN_DONE, "RETURN", "R")
- order_id = str(order.get("order_id") or "")
- events = []
- for item in order.get("items") or []:
- code = str(item.get("order_item_code") or "")
- status = str(item.get("order_status") or "")
- if not code or status not in done:
+ day = _day(refund.get("refund_date"))
+ code = str(refund.get("refund_code") or "")
+ if day is None or not code:
+ return []
+ amount = _won(refund.get("actual_refund_amount"))
+ return [SaleEvent(
+ event_type="RETURN" if code.upper().startswith("R") else "CANCEL",
+ external_event_id=code, external_order_id=str(refund.get("order_id") or ""),
+ external_line_id=",".join(refund.get("order_item_code") or []),
+ order_date=_day(refund.get("order_date")), event_date=day, amount=-amount,
+ quantity=-int(refund.get("quantity") or 0), order_status="환불완료",
+ raw={"refund_code": code, "order_id": refund.get("order_id"), "status": refund.get("status"),
+ "actual_refund_amount": refund.get("actual_refund_amount"),
+ "used_points": refund.get("used_points"), "used_credits": refund.get("used_credits"),
+ "quantity": refund.get("quantity"), "order_item_code": refund.get("order_item_code")},
+ )]
+
+ # ── 대조(설정 화면 "카페24 매출 대조") ─────────────────
+ def reconcile(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
+ """그날 결제 주문·환불을 항목별로 합산 — 카페24 일별 매출내역과 비교해 규칙을 확정하는 용도.
+
+ 자체몰/다른 마켓을 나눠 합산한다. 개인정보는 담지 않는다.
+ """
+ self.authenticate(ctx)
+
+ def empty() -> dict[str, int]:
+ return {"orders": 0, "items": 0, "lines": 0, **{k: 0 for k in AMOUNT_FIELDS}, "total": 0}
+
+ groups = {"self": empty(), "market": empty()}
+ unpaid = 0
+ for o in self.paid_orders(ctx, day, day):
+ if o.get("paid") != "T":
+ unpaid += 1
continue
- if kind == "cancel":
- day = _day(item.get("cancel_date")) or _day(order.get("cancel_date"))
- else:
- day = _day(item.get("return_confirmed_date")) or _day(item.get("refund_date"))
- if day is None:
- continue
- amount = item_amount(item)
- qty = int(item.get("quantity") or 0)
- claim = int(item.get("claim_quantity") or 0)
- if kind == "return" and 0 < claim < qty:
- amount = int((Decimal(amount) * claim / qty).quantize(Decimal(1), rounding=ROUND_HALF_UP))
- qty = claim
- events.append(SaleEvent(
- event_type=ev_type, external_event_id=f"{code}-{suffix}", external_order_id=order_id,
- external_line_id=code, order_date=_day(order.get("order_date")),
- payment_date=_day(order.get("payment_date")), event_date=day, amount=-amount,
- product_name=str(item.get("product_name") or ""), quantity=-qty, order_status=status,
- raw=_raw(order, item),
- ))
- return events
+ g = groups["self" if is_self_market(o.get("market_id")) else "market"]
+ g["orders"] += 1
+ g["items"] += sum(int(i.get("quantity") or 0) for i in o.get("items") or [])
+ g["lines"] += len(o.get("items") or [])
+ for k, v in order_amounts(o).items():
+ g[k] += v
+ g["total"] += order_total(o)
+ rows = [r for r in self.refunds(ctx, day, day) if str(r.get("status") or "T") == "T"]
+ markets = self.market_ids(ctx, rows)
+ refunds = {"self": {"count": 0, "actual_refund_amount": 0, "used_points": 0, "used_credits": 0},
+ "market": {"count": 0, "actual_refund_amount": 0, "used_points": 0, "used_credits": 0}}
+ for r in rows:
+ g = refunds["self" if is_self_market(markets.get(str(r.get("order_id")), "self")) else "market"]
+ g["count"] += 1
+ for k in ("actual_refund_amount", "used_points", "used_credits"):
+ g[k] += _won(r.get(k))
+ return {"date": day.isoformat(), "orders": groups, "refunds": refunds, "unpaid_orders": unpaid,
+ "formula": "결제합계 = 상품구매금액 + 배송비 − 할인(" + ", ".join(DISCOUNT_FIELDS) +
+ ") − 쿠폰(" + ", ".join(COUPON_FIELDS) + ")"}
diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py
index 4d7956a..5c00b60 100644
--- a/app/modules/performance/db.py
+++ b/app/modules/performance/db.py
@@ -215,7 +215,43 @@ class PerformanceDBStore:
# ════════════════════════════════════════════════════════════
def upsert_events(self, code: str, events: Iterable[dict[str, Any]], *, is_sample: bool = False) -> int:
"""같은 (쇼핑몰, 사건 종류, 외부 사건 ID)는 덮어쓴다 — 여러 번 동기화해도 중복 없음."""
- sql = """
+ rows = self._event_rows(code, events, is_sample)
+ if not rows:
+ return 0
+ with self._pool.connection() as conn:
+ with conn.transaction():
+ with conn.cursor() as cur:
+ cur.executemany(self._UPSERT_SQL, rows)
+ return len(rows)
+
+ def replace_events(self, code: str, start: date, end: date, events: Iterable[dict[str, Any]]) -> int:
+ """기간(sales_date) 안 이 쇼핑몰 실데이터(is_sample 아님)를 지우고 새로 넣는다 — 한 트랜잭션.
+ 테스트 데이터는 건드리지 않는다. 실패하면 롤백되어 예전 데이터가 그대로 남는다."""
+ rows = self._event_rows(code, events, False)
+ with self._pool.connection() as conn:
+ with conn.transaction():
+ conn.execute(
+ "DELETE FROM perf_sales_events WHERE marketplace_code = %s AND is_sample = FALSE "
+ "AND sales_date BETWEEN %s AND %s",
+ (code, start, end),
+ )
+ if rows:
+ with conn.cursor() as cur:
+ cur.executemany(self._UPSERT_SQL, rows)
+ return len(rows)
+
+ @staticmethod
+ def _event_rows(code: str, events: Iterable[dict[str, Any]], is_sample: bool) -> list[tuple]:
+ return [
+ (code, e["event_type"], e["external_event_id"], e["external_order_id"], e.get("external_line_id", ""),
+ e.get("order_date"), e.get("payment_date"), e["event_date"], e["sales_date"],
+ e.get("product_name", ""), e.get("option_name", ""), int(e.get("quantity") or 0),
+ int(e["amount"]), int(e.get("discount_amount") or 0), e.get("order_status", ""),
+ Jsonb(e.get("raw") or {}), is_sample)
+ for e in events
+ ]
+
+ _UPSERT_SQL = """
INSERT INTO perf_sales_events
(marketplace_code, event_type, external_event_id, external_order_id, external_line_id,
order_date, payment_date, event_date, sales_date, product_name, option_name, quantity,
@@ -229,22 +265,7 @@ class PerformanceDBStore:
quantity = EXCLUDED.quantity, amount = EXCLUDED.amount,
discount_amount = EXCLUDED.discount_amount, order_status = EXCLUDED.order_status,
raw_data = EXCLUDED.raw_data, is_sample = EXCLUDED.is_sample, synced_at = now()
- """
- rows = [
- (code, e["event_type"], e["external_event_id"], e["external_order_id"], e.get("external_line_id", ""),
- e.get("order_date"), e.get("payment_date"), e["event_date"], e["sales_date"],
- e.get("product_name", ""), e.get("option_name", ""), int(e.get("quantity") or 0),
- int(e["amount"]), int(e.get("discount_amount") or 0), e.get("order_status", ""),
- Jsonb(e.get("raw") or {}), is_sample)
- for e in events
- ]
- if not rows:
- return 0
- with self._pool.connection() as conn:
- with conn.transaction():
- with conn.cursor() as cur:
- cur.executemany(sql, rows)
- return len(rows)
+ """
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
if not codes:
diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py
index 479905d..bfdf077 100644
--- a/app/modules/performance/router.py
+++ b/app/modules/performance/router.py
@@ -270,6 +270,16 @@ def api_test_connection(request: Request, code: str, payload: dict[str, Any] = B
return JSONResponse(result)
+@router.get("/api/marketplaces/{code}/reconcile")
+def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date")) -> JSONResponse:
+ """쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
+ store, user = common.require_store(request, admin=True)
+ _code_or_404(store, code)
+ day = _parse_date(date_)
+ _, sync = common.services(request, store)
+ return JSONResponse(sync.reconcile(code, day, 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)
diff --git a/app/modules/performance/sync.py b/app/modules/performance/sync.py
index da95b1c..0551445 100644
--- a/app/modules/performance/sync.py
+++ b/app/modules/performance/sync.py
@@ -107,7 +107,13 @@ class SyncService:
ctx = self._ctx(adapter, user=user)
fetched, events = adapter.collect(ctx, start, end)
known = ctx.credentials.known_secrets()
- upserted = self._store.upsert_events(code, (event_row(ev, known) for ev in events))
+ rows = [event_row(ev, known) for ev in events]
+ if adapter.replace_range:
+ # 그 기간을 통째로 다시 받은 쇼핑몰 — 기간 안 예전 행을 지우고 새로 넣는다(한 트랜잭션).
+ rows = [r for r in rows if start <= r["sales_date"] <= end]
+ upserted = self._store.replace_events(code, start, end, rows)
+ else:
+ upserted = self._store.upsert_events(code, rows)
self._store.finish_run(run_id, ok=True, fetched=fetched, upserted=upserted)
self._store.record_sync(code, status="ok", ok=True)
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
@@ -127,6 +133,20 @@ class SyncService:
targets = [a.code for a in all_adapters() if a.code in enabled and (not codes or a.code in codes)]
return [self.sync_marketplace(c, start, end, trigger=trigger, user=user) for c in targets]
+ # ── 쇼핑몰 화면과 대조 ────────────────────────────────
+ def reconcile(self, code: str, day: date, *, user: str = "") -> dict[str, Any]:
+ """어댑터가 지원하면(reconcile) 그날 원천 금액을 항목별로 합산해 돌려준다. DB 는 바꾸지 않는다."""
+ adapter = get_adapter(code)
+ if adapter is None or not hasattr(adapter, "reconcile"):
+ return {"ok": False, "message": "이 쇼핑몰은 대조 기능을 지원하지 않습니다."}
+ ctx = None
+ try:
+ ctx = self._ctx(adapter, user=user)
+ return {"ok": True, **adapter.reconcile(ctx, day)}
+ except Exception as exc: # noqa: BLE001
+ status, message = self._failure(exc, ctx)
+ return {"ok": False, "status": status, "label": STATUS_LABELS.get(status, status), "message": message}
+
# ── 테스트(모의) 데이터 ────────────────────────────────
def generate_samples(self, start: date, end: date, codes: list[str]) -> int:
from .adapters import mock # noqa: WPS433
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index 1ba74ca..c1f3341 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -235,4 +235,4 @@
} | 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 3dc985b..572675e 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -115,6 +115,17 @@
+
+
카페24 매출 대조
+
카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
+ 바로 합산하며(저장하지 않음), 자체몰과 다른 마켓 연동 주문을 나눠 보여 줍니다.
+
+
+
+
+
+
+
테스트 데이터
현재 {{ "{:,}".format(sample_count) }}건
@@ -131,4 +142,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 21d494b..1365cae 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -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():
diff --git a/app/static/performance.js b/app/static/performance.js
index 2be3082..6922482 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -470,6 +470,60 @@
} finally { btn.disabled = false; btn.textContent = label; }
}
+ // ── 카페24 매출 대조 — 카페24 "일별 매출내역" 열 순서대로 ──
+ const recon = document.getElementById("perf-recon");
+ if (recon) recon.addEventListener("click", async function () {
+ const day = document.getElementById("perf-recon-date").value;
+ const out = document.getElementById("perf-recon-result");
+ if (!day) return;
+ recon.disabled = true;
+ out.innerHTML = '
카페24에서 불러오는 중…
';
+ try {
+ const r = await api("GET", "/performance/api/marketplaces/cafe24/reconcile?date=" + encodeURIComponent(day));
+ if (!r.ok) { out.innerHTML = '
한 줄 = market_id × 주문경로. market_id "self"는 PC 전용이 아니라 자체몰 전체이며, 그 안에 PC쇼핑몰·모바일웹 경로가 섞여 있습니다. ' +
+ 'PC/모바일 주문은 카페24가 주문마다 주는 모바일 주문 여부(order_from_mobile) 기준입니다.
'
: "") +
((r.by_payment || []).length
? '
결제수단별 (카페24 열)
' +
From a19c1f4cab6491b7374dad1a8cf38550df437755 Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 17:21:08 +0900
Subject: [PATCH 10/30] =?UTF-8?q?feat(performance):=20=EB=A7=A4=EC=B6=9C?=
=?UTF-8?q?=20=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 "
" : "") +
From 1d12ac878b96e8664d529dbebea8d5dfbf212322 Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 17:59:24 +0900
Subject: [PATCH 14/30] =?UTF-8?q?fix(performance):=20=EC=B9=B4=ED=8E=9824?=
=?UTF-8?q?=20=ED=99=98=EB=B6=88=ED=95=A9=EA=B3=84=EB=A5=BC=20=EC=9D=BC?=
=?UTF-8?q?=EB=B3=84=20=EB=A7=A4=EC=B6=9C=EB=82=B4=EC=97=AD=EA=B3=BC=20?=
=?UTF-8?q?=EA=B0=99=EA=B2=8C=20=E2=80=94=20=EC=A0=81=EB=A6=BD=EA=B8=88=20?=
=?UTF-8?q?=ED=99=98=EB=B6=88=20+=20=EB=84=A4=EC=9D=B4=EB=B2=84=ED=8E=98?=
=?UTF-8?q?=EC=9D=B4=20=EC=B7=A8=EC=86=8C?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
실데이터 대조 결과 카페24 일별 매출 환불합계 =
환불 목록(실제 환불액 + 적립금·예치금 환불)
+ 환불 목록에 없는 취소·반품(네이버페이 취소 등, 품목 취소일 기준)
9/26: 178,220 + 1,080 + 96,500 = 275,800, 9/27: 145,000 + 55,800 = 200,800 일치.
- normalize_refund 금액에 적립금·예치금 환불 포함(refund_total)
- unrefunded_claims: orders date_type=cancel_date|return_complete_date 의 C40~43/R40~43
품목 중 앞뒤 60일 환불 목록에 없는 주문 → CANCEL/RETURN 사건(c24:{품목코드}-CL)
- 대조 화면 환불합계를 적용 규칙으로 표시 + "적용 규칙" 후보
- 테스트 추가
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/cafe24.py | 101 ++++++++++++++++--
.../templates/performance/index.html | 2 +-
.../templates/performance/settings.html | 2 +-
.../performance/tests/test_performance.py | 46 +++++++-
app/static/performance.js | 15 +--
docs/PERFORMANCE_MODULE.md | 13 ++-
6 files changed, 157 insertions(+), 22 deletions(-)
diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py
index b768ac7..e8acc3a 100644
--- a/app/modules/performance/adapters/cafe24.py
+++ b/app/modules/performance/adapters/cafe24.py
@@ -55,6 +55,10 @@ CLAIM_DATE_TYPES = (("cancel_complete_date", "취소완료"), ("cancel_date", "
("return_complete_date", "반품완료"), ("exchange_complete_date", "교환완료"))
CLAIM_DONE = frozenset({"C40", "C41", "C42", "C43", "R40", "R41", "R42", "R43", "E40"})
UNPAID_CANCEL = frozenset({"C47", "C48", "C49"})
+# 환불 목록(/admin/refunds)에 없는 취소·반품(네이버페이 등) — 카페24 일별 매출 환불합계에는 들어간다(실데이터 확인)
+NO_RECORD_DATE_TYPES = ("cancel_date", "return_complete_date")
+NO_RECORD_DONE = frozenset({"C40", "C41", "C42", "C43", "R40", "R41", "R42", "R43"})
+REFUND_LOOKAROUND_DAYS = 60
# 카페24 자체몰 주문 채널 — market_id 는 외부 마켓만이 아니라 주문 채널·간편결제도 담는다
# (실데이터 확인 2026-09-30: mobile=모바일웹, NCHECKOUT=네이버페이, KAKAOPAY=톡체크아웃).
@@ -141,6 +145,11 @@ def order_total(order: dict[str, Any]) -> int:
- sum(a[k] for k in DISCOUNT_FIELDS) - sum(a[k] for k in COUPON_FIELDS))
+def refund_total(refund: dict[str, Any]) -> int:
+ """환불합계 = 실제 환불액 + 적립금·예치금 환불."""
+ return _won(refund.get("actual_refund_amount")) + _won(refund.get("used_points")) + _won(refund.get("used_credits"))
+
+
def order_total_now(order: dict[str, Any]) -> int:
"""취소·반품 반영 후 현재 결제합계(actual_order_amount). 없으면 결제 당시 금액."""
a = order.get("actual_order_amount") or order.get("initial_order_amount") or {}
@@ -314,6 +323,49 @@ class Cafe24Adapter(MarketplaceAdapter):
seen.add(oid)
return {"items": items, "errors": errors, "full_cancel_shipping": full_cancel_shipping}
+ def unrefunded_claims(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
+ """환불 목록에 기록이 없는 취소·반품 완료 품목(네이버페이 취소 등). 날짜 = 품목 취소일(반품은 반품완료일).
+ 금액 = 판매가(+옵션)×수량 − 품목 할인·쿠폰. 앞뒤 60일 환불 목록(완료일·접수일)에 그 주문이 있으면 제외해
+ 환불 목록 쪽과 두 번 빼지 않는다."""
+ from app.timezone import today_kst # noqa: WPS433
+
+ found: dict[str, dict[str, Any]] = {}
+ for date_type in NO_RECORD_DATE_TYPES:
+ for s, e in _chunks(start, end):
+ for o in self._paged(ctx, "/admin/orders", "orders",
+ {"start_date": s.isoformat(), "end_date": e.isoformat(),
+ "date_type": date_type, "embed": "items"}, ORDER_LIMIT):
+ oid = str(o.get("order_id") or "")
+ for i in o.get("items") or []:
+ status = str(i.get("order_status") or "")
+ if status not in NO_RECORD_DONE:
+ continue
+ keys = (("cancel_date", "refund_date", "return_confirmed_date") if status[:1] == "C"
+ else ("return_confirmed_date", "refund_date", "cancel_date"))
+ day = next((d for d in (_day(i.get(k)) for k in keys) if d), None)
+ if day is None or not (start <= day <= end):
+ continue
+ key = str(i.get("order_item_code") or f"{oid}-{i.get('item_no')}")
+ qty = int(i.get("quantity") or 0)
+ amount = ((_won(i.get("product_price")) + _won(i.get("option_price"))) * qty
+ - _won(i.get("additional_discount_price")) - _won(i.get("coupon_discount_price"))
+ - _won(i.get("app_item_discount_amount")))
+ found[key] = {
+ "order_id": oid, "item_code": key, "status": status, "day": day,
+ "market_id": o.get("market_id"), "place_id": o.get("order_place_id"),
+ "place_name": o.get("order_place_name"), "order_date": _day(o.get("order_date")),
+ "quantity": qty, "amount": max(0, amount),
+ "product_name": str(i.get("product_name") or "")[:40],
+ "naver_pay_claim_status": str(i.get("naver_pay_claim_status") or ""),
+ }
+ if not found:
+ return []
+ lo = start - timedelta(days=REFUND_LOOKAROUND_DAYS)
+ hi = max(end, min(end + timedelta(days=REFUND_LOOKAROUND_DAYS), today_kst()))
+ refunded = {str(r.get("order_id") or "") for dt in ("refund_date", "accepted_refund_date")
+ for r in self.refunds(ctx, lo, hi, dt)}
+ return [c for c in found.values() if c["order_id"] not in refunded]
+
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건씩 묶어 조회.
못 찾으면 자체몰."""
@@ -343,6 +395,8 @@ class Cafe24Adapter(MarketplaceAdapter):
for r in rows:
mid, place, _name = markets.get(str(r.get("order_id")), ("self", None, None))
yield {**r, "_market_id": mid, "_order_place_id": place}
+ for c in self.unrefunded_claims(ctx, start, end):
+ yield {**c, "_kind": "claim"}
def normalize_order(self, order: dict[str, Any]) -> list[SaleEvent]:
"""결제 주문 → SALE. 자체몰은 카페24 열, 마켓 연동 주문은 해당 쇼핑몰 열(MARKET_MAP)."""
@@ -368,12 +422,15 @@ class Cafe24Adapter(MarketplaceAdapter):
)]
def normalize_refund(self, refund: dict[str, Any]) -> list[SaleEvent]:
- """환불 → CANCEL/RETURN(−). 원 주문의 market_id 로 결제와 같은 쇼핑몰 열에 넣는다."""
+ """환불 → CANCEL/RETURN(−). 원 주문의 market_id 로 결제와 같은 쇼핑몰 열에 넣는다.
+ 금액 = 실제 환불액 + 적립금·예치금 환불(카페24 일별 매출 환불합계와 같음, 실데이터 확인)."""
+ if refund.get("_kind") == "claim":
+ return self.normalize_claim(refund)
day = _day(refund.get("refund_date"))
code = str(refund.get("refund_code") or "")
if day is None or not code:
return []
- amount = _won(refund.get("actual_refund_amount"))
+ amount = refund_total(refund)
return [SaleEvent(
marketplace_code=target_code(refund.get("_market_id"), refund.get("_order_place_id")),
event_type="RETURN" if code.upper().startswith("R") else "CANCEL",
@@ -387,6 +444,23 @@ class Cafe24Adapter(MarketplaceAdapter):
"quantity": refund.get("quantity"), "order_item_code": refund.get("order_item_code")},
)]
+ def normalize_claim(self, c: dict[str, Any]) -> list[SaleEvent]:
+ """환불 목록에 없는 취소·반품 품목(네이버페이 등) → CANCEL/RETURN(−), 취소일(반품완료일)."""
+ if not c.get("amount") or c.get("day") is None:
+ return []
+ is_return = str(c.get("status"))[:1] == "R"
+ return [SaleEvent(
+ marketplace_code=target_code(c.get("market_id"), c.get("place_id")),
+ event_type="RETURN" if is_return else "CANCEL",
+ external_event_id=f"{EVENT_PREFIX}{c['item_code']}-CL", external_order_id=str(c.get("order_id") or ""),
+ external_line_id=str(c["item_code"]), order_date=c.get("order_date"), event_date=c["day"],
+ amount=-int(c["amount"]), quantity=-int(c.get("quantity") or 0), product_name=c.get("product_name") or "",
+ order_status="반품완료" if is_return else "취소완료",
+ raw={"order_id": c.get("order_id"), "item_code": c["item_code"], "status": c.get("status"),
+ "market_id": c.get("market_id"), "naver_pay_claim_status": c.get("naver_pay_claim_status"),
+ "no_refund_record": True},
+ )]
+
# ── 대조(설정 화면 "카페24 매출 대조") ─────────────────
def reconcile(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
"""그날 결제 주문·환불을 항목별로 합산 — 카페24 일별 매출내역과 비교해 규칙을 확정하는 용도.
@@ -465,8 +539,8 @@ class Cafe24Adapter(MarketplaceAdapter):
}
rows = [r for r in self.refunds(ctx, day, day) if str(r.get("status") or "T") == "T"]
markets = self.market_ids(ctx, rows)
- refunds = {"self": {"count": 0, "actual_refund_amount": 0, "used_points": 0, "used_credits": 0},
- "market": {"count": 0, "actual_refund_amount": 0, "used_points": 0, "used_credits": 0}}
+ refunds = {k: {"count": 0, "actual_refund_amount": 0, "used_points": 0, "used_credits": 0,
+ "no_record_count": 0, "no_record": 0, "total": 0} for k in ("self", "market")}
for r in rows:
mid, place, place_name = markets.get(str(r.get("order_id")), ("self", None, None))
ch = channel(mid, place, place_name)
@@ -474,8 +548,18 @@ class Cafe24Adapter(MarketplaceAdapter):
g["count"] += 1
for k in ("actual_refund_amount", "used_points", "used_credits"):
g[k] += _won(r.get(k))
+ g["total"] += refund_total(r)
ch["refund_count"] += 1
- ch["refund_amount"] += _won(r.get("actual_refund_amount"))
+ ch["refund_amount"] += refund_total(r)
+ no_record = self.unrefunded_claims(ctx, day, day)
+ for c in no_record:
+ ch = channel(c["market_id"], c["place_id"], c["place_name"])
+ g = refunds["self" if ch["target"] == "cafe24" else "market"]
+ g["no_record_count"] += 1
+ g["no_record"] += c["amount"]
+ g["total"] += c["amount"]
+ ch["refund_count"] += 1
+ ch["refund_amount"] += c["amount"]
channels_out = sorted(({**v, "names": sorted(v["names"])} for v in by_channel.values()),
key=lambda v: v["total"], reverse=True)
@@ -555,7 +639,9 @@ class Cafe24Adapter(MarketplaceAdapter):
claimed = csum(lambda c: True)
# 카페24 "환불합계" 후보 — 화면 값과 같은 줄을 찾는다(화면에서 값을 입력하면 강조)
candidates = [
- {"key": "completed", "label": "환불완료일 · 실제 환불액 (현재 적용)", "amount": comp["actual_refund_amount"]},
+ {"key": "applied", "label": "적용 규칙 · 환불 목록(실제 + 적립금·예치금) + 환불 목록 없는 취소·반품(네이버페이 등)",
+ "amount": refunds["self"]["total"] + refunds["market"]["total"]},
+ {"key": "completed", "label": "환불완료일 · 실제 환불액 (이전 규칙)", "amount": comp["actual_refund_amount"]},
{"key": "completed_pts", "label": "환불완료일 · 실제 환불액 + 적립금·예치금", "amount": comp["with_points"]},
{"key": "pay_date", "label": "결제일 기준 · 그날 결제 주문의 환불(오늘까지) · 실제 환불액",
"amount": by_pay["actual_refund_amount"]},
@@ -578,6 +664,9 @@ class Cafe24Adapter(MarketplaceAdapter):
"by_channel": channels_out, "refund_basis": refund_basis,
"refund_list": sorted(refund_list.values(), key=lambda r: r["refund_code"]),
"claims": claims, "refund_candidates": candidates,
+ "no_record_claims": [{**c, "day": c["day"].isoformat(),
+ "order_date": c["order_date"].isoformat() if c["order_date"] else None}
+ for c in no_record],
"reduced_orders": sorted(reduced.values(), key=lambda r: r["diff"] - r["refunded"], reverse=True),
"by_payment": sorted(by_payment.values(), key=lambda v: v["total"], reverse=True),
"formula": "결제합계 = 상품구매금액 + 배송비 − 할인(" + ", ".join(DISCOUNT_FIELDS) +
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index f20d3e5..b66215f 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -239,4 +239,4 @@
} | 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 7144ec3..5664b04 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 d7a38a9..915eeb9 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -425,7 +425,7 @@ class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist
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]}
- if params.get("date_type", "").endswith("_complete_date"):
+ if params.get("date_type", "").endswith("_complete_date") or params.get("date_type") == "cancel_date":
return {"orders": self.claims.get(params["date_type"], []) if idx == 0 else []}
return {"orders": self.orders_pages[idx] if idx < len(self.orders_pages) else []}
@@ -549,6 +549,50 @@ def test_cafe24_normalize_matches_daily_report():
assert calls[1]["offset"] == 1000 and all(c["limit"] == 1000 and c["date_type"] == "pay_date" for c in calls)
+def test_cafe24_refund_total_includes_points_and_naverpay_cancels():
+ """카페24 일별 매출 환불합계 = 환불 목록(실제 + 적립금·예치금) + 환불 목록에 없는 취소·반품(네이버페이 등).
+ 실데이터: 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800, 9/27 = 145,000 + 네이버페이 55,800."""
+ import app.timezone as _tz
+ from app.modules.performance.adapters.base import AdapterContext
+
+ ctx = AdapterContext(code="cafe24", credentials=None)
+ item = lambda code, st, price, qty=1, day="2026-09-26 15:00:00", **kw: {
+ "order_item_code": code, "order_status": st, "quantity": qty, "product_price": f"{price}.00",
+ "option_price": "0.00", "product_name": "상품", "cancel_date": day, **kw}
+ refund = {**_c24_refund("C20260926-01", "O1", 63_720), "used_points": "1080.00",
+ "refund_date": "2026-09-26T20:25:08+09:00"}
+ fake = _FakeCafe24([[]], [[refund]], claims={
+ "cancel_date": [
+ {**_c24_order("O1"), "items": [item("O1-01", "C40", 64_800)]}, # 환불 목록 있음 → 제외
+ {**_c24_order("NP1", market="NCHECKOUT"), "items": [item("NP1-01", "C40", 55_800),
+ item("NP1-02", "N40", 9_000)]}, # 정상 품목 제외
+ {**_c24_order("NP2", market="NCHECKOUT"), "items": [item("NP2-01", "C40", 20_000, 2,
+ coupon_discount_price="1000.00")]},
+ {**_c24_order("NP3", market="NCHECKOUT"), "items": [item("NP3-01", "C40", 5_000, day="2026-09-27 01:00:00")]},
+ {**_c24_order("NP4", market="NCHECKOUT"), "items": [item("NP4-01", "C00", 5_000)]}, # 취소신청만 → 제외
+ ],
+ "return_complete_date": [{**_c24_order("NP1", market="NCHECKOUT"), "items": [item("NP1-01", "C40", 55_800)]}],
+ })
+ orig, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
+ try:
+ _, events = fake.collect(ctx, date(2026, 9, 26), date(2026, 9, 26))
+ rec = fake.reconcile(ctx, date(2026, 9, 26))
+ finally:
+ _tz.today_kst = orig
+ by = {e.external_event_id: e for e in events if e.event_type != "SALE"}
+ assert by["c24:C20260926-01"].amount == -(63_720 + 1_080) # 적립금 환불 포함
+ assert by["c24:NP1-01-CL"].amount == -55_800 and by["c24:NP1-01-CL"].event_type == "CANCEL"
+ assert by["c24:NP1-01-CL"].event_date == date(2026, 9, 26) and by["c24:NP1-01-CL"].marketplace_code == "cafe24"
+ assert by["c24:NP2-01-CL"].amount == -(40_000 - 1_000) # 판매가×수량 − 품목 쿠폰
+ assert set(by) == {"c24:C20260926-01", "c24:NP1-01-CL", "c24:NP2-01-CL"} # 다른 날·신청·환불 기록 있는 주문 제외
+ rs = rec["refunds"]["self"]
+ assert rs["no_record_count"] == 2 and rs["no_record"] == 55_800 + 39_000
+ assert rs["total"] == 63_720 + 1_080 + 55_800 + 39_000
+ cand = {c["key"]: c["amount"] for c in rec["refund_candidates"]}
+ assert cand["applied"] == rs["total"]
+ assert {c["item_code"] for c in rec["no_record_claims"]} == {"NP1-01", "NP2-01"}
+
+
def test_cafe24_scope_and_replace_range():
import app.modules.performance.sync as syncmod
from app.modules.performance.adapters.base import AdapterContext
diff --git a/app/static/performance.js b/app/static/performance.js
index e023872..ecf11f6 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -509,11 +509,14 @@
[" 참고: 실결제금액", s.payment_amount, m.payment_amount, "sub"],
[" 참고: 적립금 사용", s.points_spent_amount, m.points_spent_amount, "sub"],
[" 참고: 예치금 사용", s.credits_spent_amount, m.credits_spent_amount, "sub"],
- ["환불 건수", rs.count, rm.count, "cnt"],
- ["환불합계(실제 환불액)", rs.actual_refund_amount, rm.actual_refund_amount, "key"],
- [" 참고: 환불 적립금", rs.used_points, rm.used_points, "sub"],
- [" 참고: 환불 예치금", rs.used_credits, rm.used_credits, "sub"],
- ["순매출(결제합계 − 환불합계)", s.total - rs.actual_refund_amount, m.total - rm.actual_refund_amount, "key"],
+ ["환불 건수(환불 목록)", rs.count, rm.count, "cnt"],
+ [" · 실제 환불액", rs.actual_refund_amount, rm.actual_refund_amount, "sub"],
+ [" · 적립금 환불", rs.used_points, rm.used_points, "sub"],
+ [" · 예치금 환불", rs.used_credits, rm.used_credits, "sub"],
+ ["환불 목록 없는 취소·반품 품목 수(네이버페이 등)", rs.no_record_count, rm.no_record_count, "cnt"],
+ [" · 취소·반품 금액", rs.no_record, rm.no_record, "sub"],
+ ["환불합계", rs.total, rm.total, "key"],
+ ["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key"],
]);
out.innerHTML = '
' + esc(r.date) +
"
카페24 열(자체몰 채널)
다른 쇼핑몰 열(외부 마켓)
" +
@@ -534,7 +537,7 @@
return '
환불 기준 비교 — 카페24 화면의 그날 "환불합계"와 같은 칸을 찾아 주세요
' +
'
기준
건수
실제 환불액
' +
"
적립금·예치금 환불
합계(포함)
" +
- row("환불완료일 기준 · 완료 현재 적용", b.completed, "perf-row-week") +
+ row("환불완료일 기준 · 완료 적용(합계 포함 칸)", b.completed, "perf-row-week") +
row("환불접수일 기준 · 전체 상태", b.accepted_all) +
(b.by_pay_date ? row("결제일 기준 · 그날 결제한 주문의 환불(오늘까지" +
(b.by_pay_date.refund_dates.length ? ", 환불일 " + esc(b.by_pay_date.refund_dates.join(", ")) : "") + ")", b.by_pay_date) : "") +
diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md
index 30f832a..db2e070 100644
--- a/docs/PERFORMANCE_MODULE.md
+++ b/docs/PERFORMANCE_MODULE.md
@@ -43,7 +43,8 @@
| 사건 | 조회 | 금액·날짜 |
|---|---|---|
| SALE(결제합계) | `GET /admin/orders` `date_type=pay_date`, `embed=items`, `paid=T` | +(상품구매금액 + 배송비 − 할인 − 쿠폰), `initial_order_amount`(결제 당시 금액 — 환불을 따로 빼므로 취소 후 금액 X), 결제일. 주문 1건 = 사건 1건(`{order_id}-PAY`) |
-| CANCEL / RETURN(환불합계) | `GET /admin/refunds` `date_type=refund_date`, `status=T` | −실제 환불액(`actual_refund_amount`), 환불완료일. 환불코드 R… = 반품, 그 밖 = 취소. 사건 ID = 환불코드 |
+| CANCEL / RETURN(환불합계) | `GET /admin/refunds` `date_type=refund_date`, `status=T` | −(실제 환불액 + 적립금·예치금 환불), 환불완료일. 환불코드 R… = 반품, 그 밖 = 취소. 사건 ID = 환불코드 |
+| CANCEL / RETURN(환불 목록 없는 취소·반품) | `GET /admin/orders` `date_type=cancel_date|return_complete_date`, `embed=items` — 품목 상태 C40~43/R40~43 이고 앞뒤 60일 환불 목록(완료일·접수일)에 그 주문이 없을 때 | −(판매가+옵션)×수량 − 품목 할인·쿠폰, 품목 취소일(반품은 반품완료일). 네이버페이 취소가 여기 해당 (네이버가 환불해 카페24 환불 목록에 없음). 사건 ID = `c24:{품목코드}-CL` (`unrefunded_claims`) |
- 할인 = 회원·세트상품·앱·마켓 기타·배송비 할인, 쿠폰 = 상품쿠폰 + 배송비쿠폰(`DISCOUNT_FIELDS`/`COUPON_FIELDS`).
- **기간 교체(`replace_range=True`)**: 결제·환불 모두 기간 안 날짜로 조회되므로 동기화 때 그 기간의 카페24 실데이터를 지우고
@@ -129,12 +130,10 @@
- **대시보드 [매출 업데이트]** = 지금 보고 있는 기간(오늘까지)을 `POST /api/sync {from, to}` 로 다시 가져온다
("이번달"이면 1일~오늘). 모듈 권한자는 92일까지, 더 긴 기간(올해 등, 최대 366일)은 관리자만.
- **과거 매출 가져오기**(설정 화면, 관리자): 같은 API 로 임의 기간(최대 366일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
-- 카페24 **환불 기준**은 현재 환불완료일(refund_date)·실제 환불액. 대조 도구의 "환불 기준 비교"(완료일 vs 접수일, 적립금·예치금
- 포함 여부)로 카페24 "환불합계"와 같은 기준을 확인한 뒤 확정한다(9/23~27 순매출이 카페24보다 크게 나온 원인 조사 중).
- 9/26 은 결제합계가 카페24와 같고(3,568,265) 환불만 97,580 모자라며, 완료일·접수일·적립금 포함 어느 기준으로도 맞지 않았다
- → 환불 API 에 안 잡히는 환불이 있다고 보고, 대조 도구에 **환불합계 후보**(카페24 값 입력 시 일치 줄 강조)·**환불 건별**·
- **그날 취소/반품/교환 완료 품목**(`GET /admin/orders` `date_type=cancel_complete_date|return_complete_date|exchange_complete_date`,
- `embed=items`, 품목별 판매가·결제금액·환불 기록 유무, `claim_items()`)을 추가해 빠진 건을 찾는다.
+- 카페24 **환불합계 규칙(확정, 2026-09-29 실데이터)**: 카페24 "일별 매출내역" 환불합계 = 환불 목록의 (실제 환불액 + 적립금·예치금 환불)
+ + 환불 목록에 없는 취소·반품(네이버페이 등, 취소일 기준). 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800,
+ 9/27 = 145,000 + 네이버페이 55,800 = 200,800 으로 일치. 대조 도구에 환불합계 후보(값 입력 시 일치 줄 강조)·환불 건별·
+ 취소/반품 완료 품목·그날 결제 주문 중 줄어든 주문 표가 있어 규칙이 어긋나면 이것으로 다시 찾는다.
- 같은 쇼핑몰 동시 실행 금지: `perf_sync_runs` 의 `status='running'` 부분 유니크 인덱스(30분 넘은 running 은 정리).
- 쇼핑몰 하나 실패 → 그 쇼핑몰만 상태 오류(`perf_connection_status`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고
상단에 오류 쇼핑몰만 표시.
From 614332a1e6895e35c1038c388348a6331ef1cefb Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 21:36:32 +0900
Subject: [PATCH 15/30] =?UTF-8?q?feat(performance):=20=EC=B9=B4=ED=8E=9824?=
=?UTF-8?q?=20=EC=9D=BC=EB=B3=84=20=EB=A7=A4=EC=B6=9C=EB=82=B4=EC=97=AD=20?=
=?UTF-8?q?=EB=B6=99=EC=97=AC=EB=84=A3=EA=B8=B0=EB=A1=9C=20=EB=82=A0?=
=?UTF-8?q?=EC=A7=9C=EB=B3=84=20=ED=95=9C=20=EB=B2=88=EC=97=90=20=EB=B9=84?=
=?UTF-8?q?=EA=B5=90?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
카페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
---
app/modules/performance/db.py | 19 ++++
app/modules/performance/router.py | 18 +++
app/modules/performance/sync.py | 33 ++++++
.../templates/performance/index.html | 4 +-
.../templates/performance/settings.html | 16 ++-
.../performance/tests/test_performance.py | 42 +++++++
app/static/performance.css | 5 +
app/static/performance.js | 104 ++++++++++++++++++
docs/PERFORMANCE_MODULE.md | 4 +
9 files changed, 241 insertions(+), 4 deletions(-)
diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py
index 1a4180c..5ae6763 100644
--- a/app/modules/performance/db.py
+++ b/app/modules/performance/db.py
@@ -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:
diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py
index 83f5bb6..e7e408c 100644
--- a/app/modules/performance/router.py
+++ b/app/modules/performance/router.py
@@ -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)
diff --git a/app/modules/performance/sync.py b/app/modules/performance/sync.py
index e53e2c7..b0c1792 100644
--- a/app/modules/performance/sync.py
+++ b/app/modules/performance/sync.py
@@ -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
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index b66215f..4e803cd 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}
@@ -239,4 +239,4 @@
} | 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 5664b04..cd9c2e9 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -125,6 +125,18 @@
대조
+
+
일별 한 번에 비교
+
카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다.
+ [API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과
+ 규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.
+
+
+
+ 비교
+
+
@@ -143,4 +155,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 915eeb9..d8f7a8a 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -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
diff --git a/app/static/performance.css b/app/static/performance.css
index d30ba31..2bf3cfb 100644
--- a/app/static/performance.css
+++ b/app/static/performance.css
@@ -210,3 +210,8 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
}
.perf-table tr.perf-row-match > *{background:#e7f6ec;font-weight:600}
+.perf-paste { width: 100%; min-height: 96px; font-family: ui-monospace, Consolas, monospace; font-size: 12px; white-space: pre; resize: vertical; box-sizing: border-box; }
+.perf-table tr.perf-row-diff > * { background: #fff7f5; }
+.perf-diff-bad { color: var(--perf-down); font-weight: 600; }
+.perf-diff-ok { color: #0f8a3a; }
+.perf-link { background: none; border: 0; padding: 0; color: inherit; font: inherit; text-decoration: underline dotted; cursor: pointer; }
diff --git a/app/static/performance.js b/app/static/performance.js
index ecf11f6..13e1d8a 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -663,6 +663,110 @@
} finally { recon.disabled = false; }
});
+ // ── 일별 한 번에 비교 — 카페24 일별 매출내역 붙여넣기 ↔ 저장값 ↔ 지금 API 값 ──
+ // 붙여넣은 한 줄: "2026-09-29(화) 주문수 품목수 … 결제합계 환불합계 순매출" — 뒤의 세 숫자와 첫 숫자(주문수)만 쓴다.
+ function parseDaily(text) {
+ const out = {};
+ String(text || "").split(/\r?\n/).forEach(function (line) {
+ const m = line.match(/(\d{4})[-./](\d{2})[-./](\d{2})/);
+ if (!m) return;
+ const nums = (line.slice(m.index + m[0].length).match(/-?\d[\d,]*/g) || [])
+ .map(function (x) { return parseInt(x.replace(/,/g, ""), 10); });
+ if (nums.length < 3) return;
+ const n = nums.length;
+ out[m[1] + "-" + m[2] + "-" + m[3]] = { orders: n >= 13 ? nums[0] : null, paid: nums[n - 3], refund: nums[n - 2], net: nums[n - 1] };
+ });
+ return out;
+ }
+ const dailyBtn = document.getElementById("perf-daily-check");
+ if (dailyBtn) dailyBtn.addEventListener("click", async function () {
+ const out = document.getElementById("perf-daily-result");
+ const shop = parseDaily(document.getElementById("perf-daily-paste").value);
+ const dates = Object.keys(shop).sort();
+ if (!dates.length) { out.innerHTML = '
저장 ' + esc(String(x.synced_at).slice(5, 16).replace("T", " ")) + "
" : "") + "
";
+ }).join("");
+ const head = '
날짜
주문수 카페24 / 저장' + (lv ? " / API" : "") + "
" +
+ "
결제합계(카페24)
저장값 차이
" + (lv ? "
API 차이
" : "") +
+ "
환불합계(카페24)
저장값 차이
" + (lv ? "
API 차이
" : "") + '
판정
';
+ const foot = '
합계
' + won(sum.cp) + '
' +
+ diff(sum.dp, sum.cp) + "
" + (lv ? '
' + diff(sum.lp, sum.cp) + "
" : "") + '
' + won(sum.cr) +
+ '
' + diff(sum.dr, sum.cr) + "
" + (lv ? '
' + diff(sum.lr, sum.cr) + "
" : "") + "
";
+ const summary = bad
+ ? "저장값이 다른 날 " + bad + "일" + (lv ? " — 다시 가져오면 해결 " + stale + "일, 규칙 차이 " + rule + "일" : " — [API 값도 계산]을 켜고 다시 비교하면 원인을 나눠 볼 수 있습니다")
+ : "모든 날짜가 일치합니다.";
+ out.innerHTML = '
' + esc(summary) +
+ (r.live_error ? " API 계산 실패: " + esc(r.live_error) : "") + "
" +
+ (stale ? '
' + esc(from + " ~ " + to) + " 카페24 다시 가져오기
" : "") +
+ '
' + head + "" + body + "" + foot + "
" +
+ '
차이 = 우리 값 − 카페24 값. 저장값은 카페24 열과 카페24 경유 다른 마켓 열을 합친 금액(카페24 화면과 같은 범위)입니다.
';
+ } catch (err) {
+ out.innerHTML = '
' + esc(err.message) + "
";
+ } finally { dailyBtn.disabled = false; }
+ });
+ const dailyOut = document.getElementById("perf-daily-result");
+ if (dailyOut) dailyOut.addEventListener("click", async function (e) {
+ const dayBtn = e.target.closest("[data-recon-day]");
+ if (dayBtn && recon) {
+ document.getElementById("perf-recon-date").value = dayBtn.dataset.reconDay;
+ recon.click();
+ recon.scrollIntoView({ behavior: "smooth", block: "center" });
+ return;
+ }
+ const rs = e.target.closest("#perf-daily-resync");
+ if (!rs) return;
+ if (!(await confirmMsg(rs.dataset.from + " ~ " + rs.dataset.to + " 카페24 매출을 지금 규칙으로 다시 가져옵니다."))) return;
+ rs.disabled = true;
+ rs.textContent = "가져오는 중…";
+ try {
+ const res = await api("POST", "/performance/api/sync", { from: rs.dataset.from, to: rs.dataset.to, codes: ["cafe24"] });
+ const r0 = (res.results || [])[0];
+ if (r0 && !r0.ok) throw new Error((r0.label || r0.status) + ": " + (r0.message || ""));
+ dailyBtn.click();
+ } catch (err) {
+ alertMsg("다시 가져오기 실패: " + err.message);
+ rs.disabled = false;
+ }
+ });
+
// ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
const backfill = document.getElementById("perf-backfill");
if (backfill) backfill.addEventListener("click", async function () {
diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md
index db2e070..0da9a2b 100644
--- a/docs/PERFORMANCE_MODULE.md
+++ b/docs/PERFORMANCE_MODULE.md
@@ -67,6 +67,10 @@
- **카페24 매출 대조**(설정 화면, `GET /api/marketplaces/cafe24/reconcile?date=`): 그날 결제 주문·환불을 카페24 화면 열 순서대로
(주문수·품목수·상품구매금액·배송비·할인·쿠폰·결제합계·환불합계·순매출) 자체몰/다른 마켓으로 나눠 합산. 저장하지 않음.
카페24 화면과 다른 줄이 있으면 할인 항목 구성·마켓 포함 여부를 이 결과로 조정한다.
+- **일별 한 번에 비교**(같은 카드, `GET /api/marketplaces/{code}/daily-check?from=&to=&live=1`, 최대 62일): 카페24 일별
+ 매출내역 표를 붙여 넣으면(날짜 + 뒤 세 숫자 = 결제합계·환불합계·순매출, 첫 숫자 = 주문수) 날짜마다 저장값(`c24:` 사건 전체,
+ 다른 마켓 열 포함)과 지금 API·현재 규칙으로 다시 계산한 값(`adapter.collect`, 저장 안 함)을 비교한다.
+ 저장값만 틀림 → 예전 규칙으로 받은 것([다시 가져오기] 버튼), API 값도 틀림 → 규칙 차이(결제/환불) → 날짜 클릭으로 그날 대조.
### 연동 단계 체크리스트(쇼핑몰마다)
From 6f43f8066abd50a34e56e4c37028e197eb4db229 Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 21:43:50 +0900
Subject: [PATCH 16/30] =?UTF-8?q?fix(performance):=20=EC=B9=B4=ED=8E=9824?=
=?UTF-8?q?=20=EA=B2=B0=EC=A0=9C=ED=95=A9=EA=B3=84=EC=97=90=EC=84=9C=20?=
=?UTF-8?q?=ED=92=88=EB=AA=A9=20=EC=83=81=ED=92=88=EC=B6=94=EA=B0=80?=
=?UTF-8?q?=ED=95=A0=EC=9D=B8=20=EB=B9=BC=EA=B8=B0=20+=20=EB=8C=80?=
=?UTF-8?q?=EC=A1=B0=20=ED=91=9C=EC=97=90=20=EC=B9=B4=ED=8E=9824=20?=
=?UTF-8?q?=EC=97=B4=EB=B3=84=20=EC=B0=A8=EC=9D=B4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
일별 비교 결과 결제합계가 틀린 날은 모두 카페24 상품구매금액이 100원 단위가
아닌 날이고, 차이만큼 더하면 정확히 100원 단위가 된다(9/23 1,860,738+62,
9/22 2,620,740+260, 9/12 7,889,287+13 …). 카페24 화면의 상품구매금액은
품목 상품추가할인(items[].additional_discount_price, 문서: 상품추가할인액)을
뺀 값인데, initial_order_amount 에는 이 할인이 없어 우리가 그만큼 많았다.
- order_total: 판매가 합계 − 품목 상품추가할인 + 배송비 − 할인 − 쿠폰
- order_total_now: 취소·반품 품목의 추가할인은 제외
- 대조 표: 상품구매금액을 추가할인 뺀 값으로 + 판매가 합계·추가할인 세부 줄
- 일별 비교에서 날짜를 눌러 연 대조 표에 붙여넣은 카페24 열과 열별 차이 표시
- 테스트 추가
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/cafe24.py | 27 ++++++++----
.../performance/tests/test_performance.py | 17 ++++++++
app/static/performance.js | 42 ++++++++++++-------
docs/PERFORMANCE_MODULE.md | 4 ++
4 files changed, 68 insertions(+), 22 deletions(-)
diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py
index e8acc3a..85ef0ad 100644
--- a/app/modules/performance/adapters/cafe24.py
+++ b/app/modules/performance/adapters/cafe24.py
@@ -8,6 +8,8 @@
카페24 관리자 "일별 매출내역"과 같은 기준으로 센다(Admin API 문서 2026-09-01 확인).
- 결제합계(SALE, +): GET /admin/orders date_type=pay_date(결제일), 결제된(paid=T) 주문마다
상품구매금액 + 배송비 − 할인 − 쿠폰 (주문의 initial_order_amount — 결제 당시 금액)
+ 카페24 화면의 상품구매금액은 품목의 상품추가할인(items[].additional_discount_price)을 뺀 값이다 —
+ initial_order_amount 에는 이 할인이 없어 품목에서 더해 뺀다(실데이터: 상품구매금액이 100원 단위가 아닌 날만 차이).
환불은 따로 빼므로 취소 후 금액(actual_order_amount)이 아니라 결제 당시 금액을 쓴다.
- 환불합계(CANCEL/RETURN, −): GET /admin/refunds date_type=refund_date(환불완료일),
실제 환불액(actual_refund_amount). 환불코드가 R 로 시작하면 반품, 그 밖은 취소.
@@ -132,16 +134,23 @@ def _day(value: Any) -> date | None:
return None
+def item_additional_discount(order: dict[str, Any], *, active_only: bool = False) -> int:
+ """품목 상품추가할인 합계(items[].additional_discount_price, 품목 줄 금액). 주문 금액(initial/actual)에는 없다.
+ active_only 면 취소·반품된 품목은 빼고(현재 금액 계산용)."""
+ return sum(_won(i.get("additional_discount_price")) for i in order.get("items") or []
+ if not (active_only and str(i.get("order_status") or "")[:1] in ("C", "R")))
+
+
def order_amounts(order: dict[str, Any]) -> dict[str, int]:
- """결제 당시 금액(initial_order_amount, 없으면 actual_order_amount) 항목별 원 단위."""
+ """결제 당시 금액(initial_order_amount, 없으면 actual_order_amount) 항목별 원 단위 + 품목 상품추가할인."""
a = order.get("initial_order_amount") or order.get("actual_order_amount") or {}
- return {k: _won(a.get(k)) for k in AMOUNT_FIELDS}
+ return {**{k: _won(a.get(k)) for k in AMOUNT_FIELDS}, "additional_discount_price": item_additional_discount(order)}
def order_total(order: dict[str, Any]) -> int:
- """결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰."""
+ """결제합계 = 상품구매금액(− 품목 상품추가할인) + 배송비 − 할인 − 쿠폰."""
a = order_amounts(order)
- return (a["order_price_amount"] + a["shipping_fee"]
+ return (a["order_price_amount"] - a["additional_discount_price"] + a["shipping_fee"]
- sum(a[k] for k in DISCOUNT_FIELDS) - sum(a[k] for k in COUPON_FIELDS))
@@ -154,7 +163,7 @@ def order_total_now(order: dict[str, Any]) -> int:
"""취소·반품 반영 후 현재 결제합계(actual_order_amount). 없으면 결제 당시 금액."""
a = order.get("actual_order_amount") or order.get("initial_order_amount") or {}
w = {k: _won(a.get(k)) for k in AMOUNT_FIELDS}
- return (w["order_price_amount"] + w["shipping_fee"]
+ return (w["order_price_amount"] - item_additional_discount(order, active_only=True) + w["shipping_fee"]
- sum(w[k] for k in DISCOUNT_FIELDS) - sum(w[k] for k in COUPON_FIELDS))
@@ -416,7 +425,8 @@ class Cafe24Adapter(MarketplaceAdapter):
order_date=_day(order.get("order_date")), payment_date=pay_day, event_date=pay_day,
amount=max(0, order_total(order)), product_name=name,
quantity=sum(int(i.get("quantity") or 0) for i in items), order_status="결제완료",
- discount_amount=sum(order_amounts(order)[k] for k in DISCOUNT_FIELDS + COUPON_FIELDS),
+ discount_amount=sum(order_amounts(order)[k]
+ for k in ("additional_discount_price", *DISCOUNT_FIELDS, *COUPON_FIELDS)),
raw={"order_id": oid, "market_id": order.get("market_id"), "order_place_id": order.get("order_place_id"),
"items": len(items), **{f"initial_{k}": v for k, v in order_amounts(order).items()}},
)]
@@ -471,7 +481,8 @@ class Cafe24Adapter(MarketplaceAdapter):
self.authenticate(ctx)
def empty() -> dict[str, int]:
- return {"orders": 0, "items": 0, "lines": 0, **{k: 0 for k in AMOUNT_FIELDS}, "total": 0}
+ return {"orders": 0, "items": 0, "lines": 0, **{k: 0 for k in AMOUNT_FIELDS},
+ "additional_discount_price": 0, "total": 0}
def channel(mid: Any, place: Any, place_name: Any = None) -> dict[str, Any]:
"""(market_id, 주문경로) 한 쌍 = 한 줄. self 안에도 PC쇼핑몰·모바일웹 경로가 섞여 있어 나눠 본다."""
@@ -669,5 +680,5 @@ class Cafe24Adapter(MarketplaceAdapter):
for c in no_record],
"reduced_orders": sorted(reduced.values(), key=lambda r: r["diff"] - r["refunded"], reverse=True),
"by_payment": sorted(by_payment.values(), key=lambda v: v["total"], reverse=True),
- "formula": "결제합계 = 상품구매금액 + 배송비 − 할인(" + ", ".join(DISCOUNT_FIELDS) +
+ "formula": "결제합계 = 상품구매금액(− 품목 상품추가할인) + 배송비 − 할인(" + ", ".join(DISCOUNT_FIELDS) +
") − 쿠폰(" + ", ".join(COUPON_FIELDS) + ")"}
diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py
index d8f7a8a..f989bd1 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -650,6 +650,23 @@ def test_cafe24_scope_and_replace_range():
("naver", "direct-naver-1"), ("cafe24", "sample")}, got
+def test_cafe24_item_additional_discount():
+ """카페24 상품구매금액 = 판매가 합계 − 품목 상품추가할인(additional_discount_price). 주문 금액에는 없다.
+ 실데이터: 9/23 카페24 상품구매금액 1,860,738 — 판매가 합계 1,860,800 과 62원 차이."""
+ from app.modules.performance.adapters.cafe24 import order_total, order_total_now
+
+ o = _c24_order("A") # 50,000 + 3,000 − 1,000 − 5,000
+ o["items"][0]["additional_discount_price"] = "38.00"
+ o["items"][1]["additional_discount_price"] = "24.00"
+ assert order_total(o) == 47_000 - 62
+ ev = _FakeCafe24([]).normalize_order(o)[0]
+ assert ev.amount == 46_938 and ev.discount_amount == 62 + 1_000 + 5_000
+ # 현재 금액: 취소된 품목의 추가할인은 빼지 않는다
+ o["actual_order_amount"] = dict(o["initial_order_amount"])
+ o["items"][1]["order_status"] = "C40"
+ assert order_total_now(o) == 47_000 - 38
+
+
def test_daily_check_db_vs_live():
"""일별 비교: 저장값(카페24 경유 다른 마켓 열 포함) + 지금 API 값(저장 안 함)."""
import app.modules.performance.sync as syncmod
diff --git a/app/static/performance.js b/app/static/performance.js
index 13e1d8a..811c1bc 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -474,6 +474,7 @@
}
// ── 카페24 매출 대조 — 카페24 "일별 매출내역" 열 순서대로 ──
+ let lastShop = {}; // 일별 비교에 붙여넣은 카페24 값(날짜 → 열) — 대조 표에 차이 열로 표시
const recon = document.getElementById("perf-recon");
if (recon) recon.addEventListener("click", async function () {
const day = document.getElementById("perf-recon-date").value;
@@ -497,34 +498,46 @@
coupon_discount_price: "상품쿠폰", coupon_shipping_fee_amount: "배송비쿠폰",
};
const sum = function (g, keys) { return keys.reduce(function (a, k) { return a + (g[k] || 0); }, 0); };
+ // x[4] = 붙여넣은 카페24 일별 매출내역 열 번호(일별 비교에서 이 날짜를 눌렀을 때 차이 표시)
const rows = [
- ["주문수", s.orders, m.orders, "cnt"], ["품목수(수량 합계)", s.items, m.items, "cnt"], ["품목수(품목 줄 수)", s.lines, m.lines, "cnt"],
- ["상품구매금액", s.order_price_amount, m.order_price_amount], ["배송비", s.shipping_fee, m.shipping_fee],
- ["할인 합계", sum(s, disc), sum(m, disc)],
+ ["주문수", s.orders, m.orders, "cnt", 0], ["품목수(수량 합계)", s.items, m.items, "cnt", 1], ["품목수(품목 줄 수)", s.lines, m.lines, "cnt", 1],
+ ["상품구매금액(− 상품추가할인)", s.order_price_amount - s.additional_discount_price, m.order_price_amount - m.additional_discount_price, "", 2],
+ [" · 판매가 합계", s.order_price_amount, m.order_price_amount, "sub"],
+ [" · 상품추가할인(품목)", s.additional_discount_price, m.additional_discount_price, "sub"],
+ ["배송비", s.shipping_fee, m.shipping_fee, "", 3],
+ ["할인 합계", sum(s, disc), sum(m, disc), "", 4],
].concat(disc.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; }))
- .concat([["쿠폰 합계", sum(s, coup), sum(m, coup)]])
+ .concat([["쿠폰 합계", sum(s, coup), sum(m, coup), "", 5]])
.concat(coup.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; }))
.concat([
- ["결제합계(계산)", s.total, m.total, "key"],
- [" 참고: 실결제금액", s.payment_amount, m.payment_amount, "sub"],
- [" 참고: 적립금 사용", s.points_spent_amount, m.points_spent_amount, "sub"],
- [" 참고: 예치금 사용", s.credits_spent_amount, m.credits_spent_amount, "sub"],
+ ["결제합계(계산)", s.total, m.total, "key", 10],
+ [" 참고: 실결제금액", s.payment_amount, m.payment_amount, "sub", 6],
+ [" 참고: 적립금 사용", s.points_spent_amount, m.points_spent_amount, "sub", 7],
+ [" 참고: 예치금 사용", s.credits_spent_amount, m.credits_spent_amount, "sub", 8],
["환불 건수(환불 목록)", rs.count, rm.count, "cnt"],
[" · 실제 환불액", rs.actual_refund_amount, rm.actual_refund_amount, "sub"],
[" · 적립금 환불", rs.used_points, rm.used_points, "sub"],
[" · 예치금 환불", rs.used_credits, rm.used_credits, "sub"],
["환불 목록 없는 취소·반품 품목 수(네이버페이 등)", rs.no_record_count, rm.no_record_count, "cnt"],
[" · 취소·반품 금액", rs.no_record, rm.no_record, "sub"],
- ["환불합계", rs.total, rm.total, "key"],
- ["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key"],
+ ["환불합계", rs.total, rm.total, "key", 11],
+ ["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key", 12],
]);
+ const shopCols = (lastShop[r.date] || {}).cols || null;
out.innerHTML = '
" +
From b52b182d471cd2ef7239c3fb8d663caea99d12f5 Mon Sep 17 00:00:00 2001
From: king
Date: Tue, 29 Sep 2026 23:59:06 +0900
Subject: [PATCH 23/30] =?UTF-8?q?fix(performance):=20=EC=B9=B4=ED=8E=9824?=
=?UTF-8?q?=20=EB=A7=88=EC=BC=93=20=ED=86=B5=ED=95=A9=EA=B4=80=EB=A6=AC=20?=
=?UTF-8?q?=EB=AF=B8=EC=82=AC=EC=9A=A9=20=E2=80=94=20MARKET=5FMAP=20?=
=?UTF-8?q?=EB=B9=84=EC=9A=B0=EA=B8=B0,=20"=EC=B9=B4=ED=8E=9824=20?=
=?UTF-8?q?=EA=B2=BD=EC=9C=A0"=20=ED=91=9C=EC=8B=9C=20=EC=A0=9C=EA=B1=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
이 쇼핑몰은 카페24 마켓 통합관리로 들어오는 매출이 없다(사용자 확인). 설정 화면에
네이버·쿠팡 등 9개 쇼핑몰이 "카페24 경유"로 표시돼 카페24 수집분이 그 열로 가는
것처럼 보였다.
- MARKET_MAP = {} — 카페24로 들어온 주문은 market_id 와 관계없이 카페24 열
(경로 기능은 남겨 두고, 쓰게 되면 매핑만 넣으면 됨)
- 경로 시험은 테스트용 매핑 주입(_with_markets)으로 유지 + 기본값 비어 있음 테스트
- 문서·대조 안내 문구 갱신
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/cafe24.py | 19 +++---------
.../templates/performance/index.html | 2 +-
.../templates/performance/settings.html | 2 +-
.../performance/tests/test_performance.py | 31 +++++++++++++++++++
app/static/performance.js | 2 +-
docs/PERFORMANCE_MODULE.md | 2 ++
6 files changed, 41 insertions(+), 17 deletions(-)
diff --git a/app/modules/performance/adapters/cafe24.py b/app/modules/performance/adapters/cafe24.py
index 4cedf98..cc1af94 100644
--- a/app/modules/performance/adapters/cafe24.py
+++ b/app/modules/performance/adapters/cafe24.py
@@ -19,6 +19,7 @@
그 기간의 카페24 실데이터를 지우고 새로 넣는다. 규칙이 바뀌거나 주문이 사라져도 이중 집계 없음.
- 자체몰 주문(market_id 가 self/빈값)은 카페24 열. 카페24 마켓 통합관리로 들어온 다른 마켓 주문
(스마트스토어·쿠팡 등)은 MARKET_MAP 으로 해당 쇼핑몰 열에 넣는다(환불도 원 주문으로 판단).
+ 현재 이 쇼핑몰은 마켓 통합관리를 쓰지 않아 MARKET_MAP 이 비어 있다 — 모두 카페24 열.
MARKET_MAP 에 없는 마켓은 카페24 열 — 전체 합계는 항상 카페24 일별 매출내역과 같다.
네이버페이 결제(order_place_id=NCHECKOUT)는 자체몰 주문이라 카페24 열.
카페24 가 만든 사건은 모두 외부 사건 ID 앞에 "c24:" — 다시 받을 때 이것만 골라 교체하므로
@@ -75,20 +76,10 @@ SELF_CHANNELS: dict[str, str] = {
}
# 카페24 마켓 통합관리가 가져온 외부 마켓 주문의 market_id(또는 order_place_id) → 우리 쇼핑몰 열.
-# 여기에도 SELF_CHANNELS 에도 없는 채널은 "알 수 없는 채널"로 카페24 열에 남긴다 — 전체 합계는 항상
-# 카페24 화면과 같다. 결제수단(네이버페이·카카오페이)과 헷갈릴 수 있는 일반 이름(naver, kakao)은 넣지 않는다.
-# 실제 값은 설정 → "카페24 매출 대조"의 주문 채널별 표로 확인해 보탠다.
-MARKET_MAP: dict[str, str] = {
- "shopn": "naver", "smartstore": "naver", "storefarm": "naver",
- "coupang": "coupang",
- "sk11st": "elevenst", "11st": "elevenst", "elevenst": "elevenst",
- "gmarket": "gmarket",
- "lotteon": "lotteon",
- "gsshop": "gsshop",
- "kakaotalkstore": "kakao", "talkstore": "kakao", "kakaostyle": "kakao",
- "ohouse": "ohouse", "todayhouse": "ohouse", "bucketplace": "ohouse",
- "tossshopping": "toss",
-}
+# 이 쇼핑몰은 카페24 마켓 통합관리를 쓰지 않는다(2026-09 사용자 확인) — 비워 두어 카페24로 들어온 주문은 모두
+# 카페24 열. 나중에 쓰게 되면 대조 화면 "주문 채널별" 표의 market_id 로 확인해 예: {"shopn": "naver"} 처럼 넣는다
+# (그 쇼핑몰을 직접 연동한다면 넣지 않는다 — 같은 주문을 두 번 받게 됨). 결제수단과 헷갈리는 이름(naver, kakao) 금지.
+MARKET_MAP: dict[str, str] = {}
def _key(value: Any) -> str:
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index acad170..ac3c821 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -239,4 +239,4 @@
} | 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 06da1de..df7fc22 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -155,4 +155,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 bd9389b..1116f9d 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -405,6 +405,26 @@ def test_not_implemented_and_mock():
# ════════════════════════════════════════════════════════════
# 카페24 어댑터(가짜 API 응답) — 카페24 "일별 매출내역" 기준
# ════════════════════════════════════════════════════════════
+# 마켓 통합관리 경로 시험용 매핑 — 실제 MARKET_MAP 은 비어 있다(이 쇼핑몰은 마켓 통합관리 미사용)
+TEST_MARKET_MAP = {"shopn": "naver", "sk11st": "elevenst", "coupang": "coupang"}
+
+
+def _with_markets(fn):
+ import functools
+
+ @functools.wraps(fn)
+ def run():
+ from app.modules.performance.adapters import cafe24 as c24
+ saved = dict(c24.MARKET_MAP)
+ c24.MARKET_MAP.update(TEST_MARKET_MAP)
+ try:
+ fn()
+ finally:
+ c24.MARKET_MAP.clear()
+ c24.MARKET_MAP.update(saved)
+ return run
+
+
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",
@@ -447,6 +467,7 @@ class _FakeCafe24(__import__("app.modules.performance.adapters.cafe24", fromlist
return {"orders": self.orders_pages[idx] if idx < len(self.orders_pages) else []}
+@_with_markets
def test_cafe24_normalize_matches_daily_report():
from app.modules.performance.adapters.base import AdapterContext
from app.modules.performance.adapters.cafe24 import order_total, target_code
@@ -620,6 +641,7 @@ def test_cafe24_refund_total_includes_points_and_naverpay_cancels():
assert {c["item_code"] for c in rec["no_record_claims"]} == {"NP1-01", "NP2-01", "NP5-02"}
+@_with_markets
def test_cafe24_scope_and_replace_range():
import app.modules.performance.sync as syncmod
from app.modules.performance.adapters.base import AdapterContext
@@ -697,6 +719,7 @@ def test_cafe24_paid_total_matches_daily_report():
assert odd["B"]["items_gross"] == 10_000 and odd["B"]["order_price_amount"] == 10_050
+@_with_markets
def test_daily_check_db_vs_live():
"""일별 비교: 저장값(카페24 경유 다른 마켓 열 포함) + 지금 API 값(저장 안 함)."""
import app.modules.performance.sync as syncmod
@@ -723,6 +746,14 @@ def test_daily_check_db_vs_live():
assert len(st.events) == 4 # 저장값은 바뀌지 않음
+def test_cafe24_market_map_empty_by_default():
+ """마켓 통합관리 미사용 — 카페24로 들어온 주문은 market_id 가 무엇이든 카페24 열."""
+ from app.modules.performance.adapters.cafe24 import MARKET_MAP, target_code
+
+ assert MARKET_MAP == {}
+ assert target_code("shopn") == target_code("coupang", "coupang") == target_code("NCHECKOUT") == "cafe24"
+
+
def test_registry_and_event_validation():
codes = [a.code for a in all_adapters()]
assert len(codes) == len(set(codes)) == 10
diff --git a/app/static/performance.js b/app/static/performance.js
index 7bc5037..14fbeb3 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -796,7 +796,7 @@
(stale ? '
' + esc(from + " ~ " + to) + " 카페24 다시 가져오기
" : "") +
'
' + head + "" + body + "" + foot + "
" +
- '
차이 = 우리 값 − 카페24 값. 저장값은 카페24 열과 카페24 경유 다른 마켓 열을 합친 금액(카페24 화면과 같은 범위)입니다.
';
+ '
차이 = 우리 값 − 카페24 값. 저장값은 카페24 수집분 전체(카페24 화면과 같은 범위)입니다.
';
} catch (err) {
out.innerHTML = '
' + esc(err.message) + "
";
} finally { dailyBtn.disabled = false; }
diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md
index 281a0ee..7815cac 100644
--- a/docs/PERFORMANCE_MODULE.md
+++ b/docs/PERFORMANCE_MODULE.md
@@ -54,6 +54,8 @@
`mobile`=모바일웹, `NCHECKOUT`=네이버페이, `KAKAOPAY`=톡체크아웃). 이들은 `SELF_CHANNELS` 로 카페24 열.
대조 도구의 "주문 채널별" 표가 채널마다 자체몰 채널 / 외부 마켓 / 알 수 없는 채널(→ 카페24 열)을 보여 준다.
`MARKET_MAP` 에는 결제수단과 헷갈릴 수 있는 일반 이름(naver, kakao)을 넣지 않는다.
+- **현재 `MARKET_MAP` 은 비어 있다** — 이 쇼핑몰은 카페24 마켓 통합관리를 쓰지 않는다(2026-09 사용자 확인). 카페24로 들어온
+ 주문은 모두 카페24 열이고 설정 화면의 "카페24 경유" 표시도 나오지 않는다. 아래는 나중에 마켓 통합관리를 쓸 때의 동작.
- **마켓 연동 주문은 해당 쇼핑몰 열로**: 자체몰 채널은 카페24 열. 카페24 마켓 통합관리가 가져온
다른 마켓 주문은 `MARKET_MAP`(market_id 또는 order_place_id → 우리 쇼핑몰 코드)으로 네이버·쿠팡·11번가 등 열에 넣는다
(`SaleEvent.marketplace_code`). 연결표에 없는 마켓은 카페24 열 — **전체 합계는 항상 카페24 일별 매출내역과 같다**
From dd6a849fbd4af1fbe7265c18d7b78f53051e3868 Mon Sep 17 00:00:00 2001
From: king
Date: Wed, 30 Sep 2026 00:14:06 +0900
Subject: [PATCH 24/30] =?UTF-8?q?feat(performance):=20=EC=BF=A0=ED=8C=A1?=
=?UTF-8?q?=20=EC=97=B0=EA=B2=B0=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=E2=80=94?=
=?UTF-8?q?=20HMAC(CEA)=20=EC=84=9C=EB=AA=85=EC=9C=BC=EB=A1=9C=20=EB=B0=9C?=
=?UTF-8?q?=EC=A3=BC=EC=84=9C=20=EC=8B=A4=EC=A0=9C=20=EC=A1=B0=ED=9A=8C?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
쿠팡 OPEN API 키를 입력했지만 연결 테스트가 "다음 단계에서 구현"만 돌려줘
키가 이 서버에서 통하는지 알 수 없었다. 키는 판매자당 1개이고 사방넷용
(연동업체 선택)으로 발급한 키는 이 서버 IP 에서 막힐 수 있어 먼저 확인이 필요.
- CEA HMAC-SHA256 서명(signed-date + METHOD + path + query, 공식 예제 방식),
쿠팡 예시와 같은 쿼리 인코딩(+ → %2B, : 유지)
- test_connection: 오늘 결제완료 발주서(v5 ordersheets) 1건 조회
- 401/403 → 인증 실패 + "연동업체 키면 자체개발로 바꾸고 이 서버 IP 허용" 안내
- 매출 수집은 아직 — 맞출 WING 화면을 정한 뒤 구현(주석에 API 조사 결과)
- 테스트: 서명 형식·쿼리 인코딩·403 메시지·비밀값 미노출
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/coupang.py | 92 ++++++++++++++++++-
.../performance/tests/test_performance.py | 49 ++++++++++
2 files changed, 139 insertions(+), 2 deletions(-)
diff --git a/app/modules/performance/adapters/coupang.py b/app/modules/performance/adapters/coupang.py
index b6725e2..825b39d 100644
--- a/app/modules/performance/adapters/coupang.py
+++ b/app/modules/performance/adapters/coupang.py
@@ -1,12 +1,57 @@
"""쿠팡 — 쿠팡 윙(마켓플레이스) Open API.
인증: Vendor ID + Access Key + Secret Key 로 요청마다 HMAC 서명(CEA 헤더).
+ signed-date = UTC "yyMMddTHHmmssZ", message = signed-date + METHOD + path + query(물음표 없이, 보내는 그대로)
+ Authorization: CEA algorithm=HmacSHA256, access-key=…, signed-date=…, signature=hex(HMAC-SHA256(secret, message))
+ (공식 문서 developers.coupangcorp.com → 시작하기 → HMAC Signature 생성 / Python Example, 2026-09-30 확인)
+
+OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
+ · 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
+ · 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
+연결 테스트는 오늘 결제완료 발주서 1건을 실제로 조회해 키·IP 가 통하는지 확인한다.
+
+매출 수집(fetch_orders)은 아직 — 어느 WING 화면과 맞출지 정한 뒤 구현한다.
+ · 발주서 목록(v5 ordersheets, 주문일 기준, 상태별 조회) + 반품/취소 요청(v6 returnRequests, 접수일 기준, 금액 없음)
+ · 매출내역(v1 revenue-history)은 매출인식일(구매확정 또는 배송완료+7일) 기준이라 결제일 기준 일별 매출과 다르다.
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 필요 시 별도 연계.
"""
from __future__ import annotations
-from .base import CredentialField, MarketplaceAdapter
+import hashlib
+import hmac
+import time
+from typing import Any
+from urllib.parse import quote, urlencode
+
+from .base import (
+ AdapterContext,
+ ApiError,
+ AuthFailed,
+ CredentialField,
+ MarketplaceAdapter,
+ NotConfigured,
+)
+
+HOST = "https://api-gateway.coupang.com"
+
+
+def signed_date(now: float | None = None) -> str:
+ return time.strftime("%y%m%dT%H%M%SZ", time.gmtime(now))
+
+
+def authorization(method: str, path: str, query: str, access_key: str, secret_key: str,
+ *, now: float | None = None) -> str:
+ """쿠팡 CEA HMAC 헤더. query 는 실제로 보내는 문자열 그대로(물음표 제외)."""
+ dt = signed_date(now)
+ sig = hmac.new(secret_key.encode("utf-8"), f"{dt}{method}{path}{query}".encode("utf-8"),
+ hashlib.sha256).hexdigest()
+ return f"CEA algorithm=HmacSHA256, access-key={access_key}, signed-date={dt}, signature={sig}"
+
+
+def build_query(params: dict[str, Any]) -> str:
+ """쿠팡 예시와 같은 인코딩 — '+' 는 %2B, ':' 는 그대로(2026-09-30%2B09:00)."""
+ return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
class CoupangAdapter(MarketplaceAdapter):
@@ -14,7 +59,9 @@ class CoupangAdapter(MarketplaceAdapter):
name = "쿠팡"
auth_type = "api_key"
docs_url = "https://developers.coupangcorp.com/"
- note = "쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다."
+ note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
+ "'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
+ "이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
def credential_fields(self) -> list[CredentialField]:
return [
@@ -22,3 +69,44 @@ class CoupangAdapter(MarketplaceAdapter):
CredentialField("access_key", "Access Key", secret=True),
CredentialField("secret_key", "Secret Key", secret=True),
]
+
+ # ── 호출 ──────────────────────────────────────────────
+ def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
+ import httpx # 지연 import
+
+ access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
+ if not (access and secret):
+ raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
+ query = build_query(params)
+ headers = {"Authorization": authorization("GET", path, query, access, secret),
+ "Content-Type": "application/json;charset=UTF-8"}
+ try:
+ res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
+ except httpx.HTTPError as exc:
+ raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
+ try:
+ body = res.json()
+ except ValueError:
+ body = {}
+ msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()
+ if res.status_code in (401, 403):
+ raise AuthFailed(
+ f"쿠팡 인증 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
+ "발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
+ "넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
+ if res.status_code >= 400:
+ raise ApiError(f"쿠팡 API 오류({res.status_code}): {msg}")
+ return body
+
+ def test_connection(self, ctx: AdapterContext) -> str:
+ from app.timezone import today_kst # noqa: WPS433
+
+ self.authenticate(ctx)
+ vendor = ctx.credentials.get("vendor_id").strip()
+ today = today_kst().isoformat()
+ body = self._get(ctx, f"/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets",
+ {"createdAtFrom": f"{today}+09:00", "createdAtTo": f"{today}+09:00",
+ "status": "ACCEPT", "maxPerPage": 1})
+ n = len(body.get("data") or [])
+ return (f"쿠팡 연결 정상(발주서 조회 권한 확인, 오늘 결제완료 {'있음' if n else '없음'}). "
+ "매출 수집은 다음 단계에서 구현됩니다.")
diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py
index 1116f9d..fce4c7c 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -754,6 +754,55 @@ def test_cafe24_market_map_empty_by_default():
assert target_code("shopn") == target_code("coupang", "coupang") == target_code("NCHECKOUT") == "cafe24"
+def test_coupang_hmac_and_connection_errors():
+ """쿠팡 CEA HMAC 서명(공식 예제 방식) + 연결 테스트 오류 구분. 비밀값은 메시지에 없다."""
+ import hashlib
+ import hmac as _hmac
+
+ import httpx
+
+ from app.modules.performance.adapters import coupang as cp
+ from app.modules.performance.adapters.base import AdapterContext
+
+ q = cp.build_query({"createdAtFrom": "2026-09-30+09:00", "status": "ACCEPT", "maxPerPage": 1})
+ assert q == "createdAtFrom=2026-09-30%2B09:00&status=ACCEPT&maxPerPage=1"
+ now = 1_790_000_000 # 2026-09-21 14:13:20 UTC
+ h = cp.authorization("GET", "/p", q, "AK", "SK", now=now)
+ dt = "260921T141320Z"
+ sig = _hmac.new(b"SK", f"{dt}GET/p{q}".encode(), hashlib.sha256).hexdigest()
+ assert h == f"CEA algorithm=HmacSHA256, access-key=AK, signed-date={dt}, signature={sig}"
+
+ class Creds(dict):
+ def get(self, k, default=""):
+ return dict.get(self, k, default)
+
+ def has(self, k):
+ return bool(dict.get(self, k))
+
+ ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK-1", secret_key="SK-SECRET"))
+ seen = {}
+
+ def fake_get(url, headers=None, timeout=None, status=200, body=None):
+ seen["url"], seen["auth"] = url, headers["Authorization"]
+ return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
+
+ orig = httpx.get
+ try:
+ httpx.get = fake_get
+ msg = cp.CoupangAdapter().test_connection(ctx)
+ assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"]
+ assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"]
+ httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
+ try:
+ cp.CoupangAdapter().test_connection(ctx)
+ except AuthFailed as exc:
+ assert "403" in exc.message and "자체개발" in exc.message and "SK-SECRET" not in exc.message
+ else:
+ raise AssertionError("403 이면 인증 실패여야 합니다")
+ finally:
+ httpx.get = orig
+
+
def test_registry_and_event_validation():
codes = [a.code for a in all_adapters()]
assert len(codes) == len(set(codes)) == 10
From c93ab2fbd8ecfba5109c2b90df9da904aac94d5f Mon Sep 17 00:00:00 2001
From: king
Date: Wed, 30 Sep 2026 00:31:57 +0900
Subject: [PATCH 25/30] =?UTF-8?q?feat(performance):=2011=EB=B2=88=EA=B0=80?=
=?UTF-8?q?=20=EC=97=B0=EA=B2=B0=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=E2=80=94?=
=?UTF-8?q?=20openapikey=20=EB=A1=9C=20=EA=B2=B0=EC=A0=9C=EC=99=84?=
=?UTF-8?q?=EB=A3=8C=20=EC=A3=BC=EB=AC=B8=20=EC=8B=A4=EC=A0=9C=20=EC=A1=B0?=
=?UTF-8?q?=ED=9A=8C?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
11번가 셀러 API 키 입력·IP 등록을 마쳤는데 연결 테스트가 "다음 단계에서
구현"만 돌려줘 이 서버에서 통하는지 알 수 없었다.
- test_connection: GET /rest/ordservices/complete/{오늘0000}/{오늘2359},
헤더 openapikey (공식 이용방법 문서). 셀러 API 는 등록 IP 에서만 호출됨
- XML 응답(euc-kr 선언) 직접 디코딩 후 파싱, result_code 오류·401/403 구분,
연결 실패 시 등록 IP 확인 안내
- 기존 테스트가 실제 11번가를 부르지 않게 httpx 대체 + 11번가 테스트 추가
- 매출 수집은 아직(맞출 셀러오피스 화면 정한 뒤)
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/elevenst.py | 78 ++++++++++++++++++-
.../performance/tests/test_performance.py | 54 ++++++++++++-
2 files changed, 128 insertions(+), 4 deletions(-)
diff --git a/app/modules/performance/adapters/elevenst.py b/app/modules/performance/adapters/elevenst.py
index 2eb8b3b..f1eea47 100644
--- a/app/modules/performance/adapters/elevenst.py
+++ b/app/modules/performance/adapters/elevenst.py
@@ -1,11 +1,54 @@
"""11번가 — 11번가 셀러 오픈API.
-인증: 셀러오피스에서 발급한 Open API Key 를 요청 헤더(openapikey)에 넣는다.
+인증: 셀러오피스(openapi.11st.co.kr → 서비스등록·확인)에서 발급한 Open API Key 를 요청 헤더 `openapikey` 에 넣는다.
+셀러 API 는 등록한 IP 에서만 호출된다("Seller API 정보 수정"에서 서버 IP 등록, 셀링툴(사방넷 등)과 함께 쓸 수 있음).
+(공식 이용방법 openapi.11st.co.kr → OpenApiOperationGuide SERVICE_METHOD, 2026-09-30 확인)
+
+연결 테스트는 결제완료(발주확인할) 주문 목록을 오늘 하루로 조회한다 — GET /rest/ordservices/complete/{시작}/{끝}
+(yyyyMMddHHmm). 엔드포인트 상세 문서는 로그인 뒤에만 보여 널리 쓰이는 경로를 쓰고, 실제 호출 결과로 확인한다.
+응답은 XML. 매출 수집(fetch_orders)은 맞출 셀러오피스 화면을 정한 뒤 구현한다.
"""
from __future__ import annotations
-from .base import CredentialField, MarketplaceAdapter
+import re
+import xml.etree.ElementTree as ET
+from typing import Any
+
+from .base import AdapterContext, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
+
+HOST = "https://api.11st.co.kr"
+
+
+def _xml_text(content: bytes) -> str:
+ """11번가 XML 은 euc-kr 선언이 많다 — 파이썬 XML 파서가 다바이트 인코딩 선언을 못 읽어 직접 풀고 선언을 뗀다."""
+ head = content[:200].decode("ascii", "ignore")
+ m = re.search(r"encoding=[\"']([\w-]+)", head)
+ enc = (m.group(1) if m else "utf-8").lower()
+ try:
+ text = content.decode("cp949" if enc in ("euc-kr", "euckr", "ks_c_5601-1987") else enc)
+ except (LookupError, UnicodeDecodeError):
+ text = content.decode("utf-8", "replace")
+ return re.sub(r"^\s*<\?xml[^>]*\?>", "", text)
+
+
+def xml_result(content: bytes) -> tuple[str, str, int]:
+ """(결과코드, 결과문구, 주문 수). 네임스페이스와 무관하게 태그 끝 이름으로 찾는다."""
+ try:
+ root = ET.fromstring(_xml_text(content))
+ except ET.ParseError:
+ return "", "", 0
+ code = text = ""
+ orders = 0
+ for el in root.iter():
+ tag = el.tag.rsplit("}", 1)[-1].lower()
+ if tag in ("result_code", "resultcode") and not code:
+ code = (el.text or "").strip()
+ elif tag in ("result_text", "resulttext", "result_message", "message") and not text:
+ text = (el.text or "").strip()
+ elif tag == "order":
+ orders += 1
+ return code, text, orders
class ElevenstAdapter(MarketplaceAdapter):
@@ -13,9 +56,38 @@ class ElevenstAdapter(MarketplaceAdapter):
name = "11번가"
auth_type = "api_key"
docs_url = "https://openapi.11st.co.kr/"
- note = "11번가 셀러오피스 → 오픈API 에서 발급한 키를 입력합니다."
+ note = ("11번가 셀러오피스 → 오픈API 에서 발급한 키를 입력합니다. 셀러 API 는 등록한 IP 에서만 호출되므로 "
+ "'Seller API 정보 수정 → IP 직접 입력'에 이 서버의 외부 IP 를 넣어야 합니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("api_key", "Open API Key", secret=True),
]
+
+ def _get(self, ctx: AdapterContext, path: str) -> bytes:
+ import httpx # 지연 import
+
+ headers = {"openapikey": ctx.credentials.get("api_key").strip(), "Accept": "application/xml"}
+ try:
+ res = httpx.get(f"{HOST}{path}", headers=headers, timeout=ctx.timeout_sec)
+ except httpx.HTTPError as exc:
+ raise ApiError(f"11번가 API 연결 실패: {type(exc).__name__} — 등록한 IP 가 이 서버 IP 인지 확인하세요.") from None
+ code, text, _ = xml_result(res.content)
+ detail = text or res.text[:200].strip()
+ if res.status_code in (401, 403):
+ raise AuthFailed(f"11번가 인증 거부({res.status_code}): {detail}. 키와 등록 IP(이 서버 외부 IP)를 확인하세요.")
+ if res.status_code >= 400:
+ raise ApiError(f"11번가 API 오류({res.status_code}): {detail}")
+ if code and code not in ("0", "200", "00"):
+ raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
+ return res.content
+
+ def test_connection(self, ctx: AdapterContext) -> str:
+ from app.timezone import today_kst # noqa: WPS433
+
+ self.authenticate(ctx)
+ d = today_kst().strftime("%Y%m%d")
+ body = self._get(ctx, f"/rest/ordservices/complete/{d}0000/{d}2359")
+ _, _, orders = xml_result(body)
+ return (f"11번가 연결 정상(주문 조회 권한 확인, 오늘 결제완료 {orders}건). "
+ "매출 수집은 다음 단계에서 구현됩니다.")
diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py
index fce4c7c..ec5ce5b 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -13,6 +13,7 @@ from decimal import Decimal
from app.modules.performance import calc
from app.modules.performance.adapters import mock
from app.modules.performance.adapters.base import (
+ ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
@@ -387,7 +388,12 @@ def test_not_implemented_and_mock():
creds.save(next(a for a in all_adapters() if a.code == "elevenst"), {"api_key": "k-123456"})
r = svc.sync_marketplace("elevenst", date(2026, 9, 29), date(2026, 9, 29))
assert r["status"] == "not_implemented" and "k-123456" not in r["message"]
- t = svc.test_connection("elevenst", values={"api_key": "typed-only"})
+ import httpx
+ orig_get, httpx.get = httpx.get, (lambda url, headers=None, timeout=None: httpx.Response(200, content=b""))
+ try:
+ t = svc.test_connection("elevenst", values={"api_key": "typed-only"})
+ finally:
+ httpx.get = orig_get
assert t["unsaved"] and "test" not in st.status.get("elevenst", {}) # 저장 안 한 값 시험은 상태 기록 안 함
a = mock.generate("naver", date(2026, 9, 1), date(2026, 9, 30))
b = mock.generate("naver", date(2026, 9, 1), date(2026, 9, 30))
@@ -803,6 +809,52 @@ def test_coupang_hmac_and_connection_errors():
httpx.get = orig
+def test_elevenst_connection():
+ """11번가: openapikey 헤더 + 결제완료 주문 조회(XML). 오류 코드·403 구분, 키는 메시지에 없음."""
+ import httpx
+
+ from app.modules.performance.adapters import elevenst as ev
+ from app.modules.performance.adapters.base import AdapterContext
+
+ class Creds(dict):
+ def get(self, k, default=""):
+ return dict.get(self, k, default)
+
+ def has(self, k):
+ return bool(dict.get(self, k))
+
+ ctx = AdapterContext(code="elevenst", credentials=Creds(api_key="KEY-11ST-SECRET"))
+ seen = {}
+ ok_xml = ('12'
+ '').encode("euc-kr")
+
+ def fake(status, content):
+ def get(url, headers=None, timeout=None):
+ seen["url"], seen["key"] = url, headers["openapikey"]
+ return httpx.Response(status, content=content)
+ return get
+
+ orig = httpx.get
+ try:
+ httpx.get = fake(200, ok_xml)
+ msg = ev.ElevenstAdapter().test_connection(ctx)
+ assert "연결 정상" in msg and "2건" in msg and seen["key"] == "KEY-11ST-SECRET"
+ assert "/rest/ordservices/complete/" in seen["url"]
+ err = '-1허용되지 않은 IP'
+ for status, body, kind in ((200, err.encode(), ApiError), (403, b"Forbidden", AuthFailed)):
+ httpx.get = fake(status, body)
+ try:
+ ev.ElevenstAdapter().test_connection(ctx)
+ except kind as exc:
+ assert "KEY-11ST-SECRET" not in exc.message
+ assert status == 403 or "허용되지 않은 IP" in exc.message
+ else:
+ raise AssertionError("오류여야 합니다")
+ finally:
+ httpx.get = orig
+
+
def test_registry_and_event_validation():
codes = [a.code for a in all_adapters()]
assert len(codes) == len(set(codes)) == 10
From 6376092bb7927e4f6eb721c0902ba29209b205dc Mon Sep 17 00:00:00 2001
From: king
Date: Wed, 30 Sep 2026 00:40:40 +0900
Subject: [PATCH 26/30] =?UTF-8?q?fix(performance):=2011=EB=B2=88=EA=B0=80?=
=?UTF-8?q?=20=EC=97=B0=EA=B2=B0=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=E2=80=94?=
=?UTF-8?q?=20XML=20=EC=95=84=EB=8B=8C=20=EC=9D=91=EB=8B=B5=EC=9D=80=20?=
=?UTF-8?q?=EC=8B=A4=ED=8C=A8,=20=EC=84=B1=EA=B3=B5=20=EC=95=8C=EB=A6=BC?=
=?UTF-8?q?=EC=9D=80=20=EC=B4=88=EB=A1=9D=20=EC=B2=B4=ED=81=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 11번가가 200 으로 웹페이지(IP 차단 안내 등)나 XML 아닌 응답을 주면 "0건 정상"으로
오판할 수 있어 실패로 처리
- 공용 알림 창 erpAlert(msg, { tone: "ok" }) — 경고 삼각형 대신 초록 체크.
기존 호출은 그대로. 실적 연결 테스트 성공 알림에 적용
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/elevenst.py | 8 ++++++--
.../performance/templates/performance/index.html | 2 +-
.../performance/templates/performance/settings.html | 2 +-
app/modules/performance/tests/test_performance.py | 5 +++--
app/static/erp-dialog.css | 5 +++++
app/static/erp-dialog.js | 13 +++++++++++--
app/static/performance.js | 4 ++--
app/templates/erp_base.html | 4 ++--
8 files changed, 31 insertions(+), 12 deletions(-)
diff --git a/app/modules/performance/adapters/elevenst.py b/app/modules/performance/adapters/elevenst.py
index f1eea47..43bb46d 100644
--- a/app/modules/performance/adapters/elevenst.py
+++ b/app/modules/performance/adapters/elevenst.py
@@ -33,11 +33,13 @@ def _xml_text(content: bytes) -> str:
def xml_result(content: bytes) -> tuple[str, str, int]:
- """(결과코드, 결과문구, 주문 수). 네임스페이스와 무관하게 태그 끝 이름으로 찾는다."""
+ """(결과코드, 결과문구, 주문 수). 네임스페이스와 무관하게 태그 끝 이름으로 찾는다. XML 이 아니면 코드 "not-xml"."""
try:
root = ET.fromstring(_xml_text(content))
except ET.ParseError:
- return "", "", 0
+ return "not-xml", "", 0
+ if root.tag.rsplit("}", 1)[-1].lower() == "html": # 오류 안내 웹페이지(IP 차단 등)
+ return "not-xml", "", 0
code = text = ""
orders = 0
for el in root.iter():
@@ -78,6 +80,8 @@ class ElevenstAdapter(MarketplaceAdapter):
raise AuthFailed(f"11번가 인증 거부({res.status_code}): {detail}. 키와 등록 IP(이 서버 외부 IP)를 확인하세요.")
if res.status_code >= 400:
raise ApiError(f"11번가 API 오류({res.status_code}): {detail}")
+ if code == "not-xml":
+ raise ApiError(f"11번가가 예상하지 못한 응답을 돌려줬습니다(XML 아님): {res.text[:120].strip()}")
if code and code not in ("0", "200", "00"):
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
return res.content
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index ac3c821..0fc29ca 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -239,4 +239,4 @@
} | 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 df7fc22..71a95e3 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -155,4 +155,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 ec5ce5b..618f950 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -842,13 +842,14 @@ def test_elevenst_connection():
assert "연결 정상" in msg and "2건" in msg and seen["key"] == "KEY-11ST-SECRET"
assert "/rest/ordservices/complete/" in seen["url"]
err = '-1허용되지 않은 IP'
- for status, body, kind in ((200, err.encode(), ApiError), (403, b"Forbidden", AuthFailed)):
+ for status, body, kind in ((200, err.encode(), ApiError), (403, b"Forbidden", AuthFailed),
+ (200, b"IP not allowed", ApiError)):
httpx.get = fake(status, body)
try:
ev.ElevenstAdapter().test_connection(ctx)
except kind as exc:
assert "KEY-11ST-SECRET" not in exc.message
- assert status == 403 or "허용되지 않은 IP" in exc.message
+ assert status == 403 or "허용되지 않은 IP" in exc.message or "XML 아님" in exc.message
else:
raise AssertionError("오류여야 합니다")
finally:
diff --git a/app/static/erp-dialog.css b/app/static/erp-dialog.css
index 8c3debb..5bdfb42 100644
--- a/app/static/erp-dialog.css
+++ b/app/static/erp-dialog.css
@@ -54,6 +54,11 @@
color: var(--color-callout-red, #c22b10);
}
+/* 성공 알림(erpAlert(msg, { tone: "ok" })) — 초록 체크 */
+.erp-dialog-icon.is-ok {
+ color: #0f8a3a;
+}
+
/* 확인(질문)용은 붉은 경고색 대신 차분한 검정으로 */
.erp-dialog-ask .erp-dialog-icon {
color: var(--color-rich-black, #0a0a0a);
diff --git a/app/static/erp-dialog.js b/app/static/erp-dialog.js
index 57ef137..bebf855 100644
--- a/app/static/erp-dialog.js
+++ b/app/static/erp-dialog.js
@@ -8,6 +8,7 @@
erpConfirm("지울까요?").then(function (ok) { if (ok) ... });
erpAlert("실패했습니다.").then(...)
erpPrompt("주소를 입력하세요", "https://").then(function (v) { if (v) ... }); // 취소면 null
+ erpAlert("저장했습니다.", { tone: "ok" }) // 성공 알림 — 경고 삼각형 대신 초록 체크
창 제목은 기본 "No.1 King ERP 프로그램". 화면마다 바꾸려면 그 화면 스크립트에서
window.ERP_DIALOG_TITLE = "..." 를 두거나, 한 번만 options.title 로 넘긴다.
@@ -31,6 +32,14 @@
'' +
"";
+ // 성공(tone: "ok") — 원 안의 체크.
+ var ICON_OK =
+ '";
+
function titleOf(options) {
return options.title || window.ERP_DIALOG_TITLE || TITLE;
}
@@ -54,8 +63,8 @@
body.className = "erp-dialog-body";
var icon = document.createElement("span");
- icon.className = "erp-dialog-icon";
- icon.innerHTML = ICON;
+ icon.className = "erp-dialog-icon" + (options.tone === "ok" ? " is-ok" : "");
+ icon.innerHTML = options.tone === "ok" ? ICON_OK : ICON;
var text = document.createElement("p");
text.className = "erp-dialog-message";
diff --git a/app/static/performance.js b/app/static/performance.js
index 14fbeb3..94fcfc4 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -31,7 +31,7 @@
if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만";
return s + fmt(a);
}
- function alertMsg(msg) { return window.erpAlert ? window.erpAlert(msg) : Promise.resolve(window.alert(msg)); }
+ function alertMsg(msg, opts) { return window.erpAlert ? window.erpAlert(msg, opts) : Promise.resolve(window.alert(msg)); }
function confirmMsg(msg) { return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg)); }
async function api(method, url, body) {
@@ -466,7 +466,7 @@
btn.textContent = "확인 중…";
try {
const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", {});
- await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message);
+ await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined);
location.reload();
} catch (err) {
alertMsg(err.message);
diff --git a/app/templates/erp_base.html b/app/templates/erp_base.html
index 6c4ce15..e657643 100644
--- a/app/templates/erp_base.html
+++ b/app/templates/erp_base.html
@@ -7,7 +7,7 @@
-
+
{% block head_extra %}{% endblock %}
@@ -177,7 +177,7 @@
{# 공용 확인/경고 창. defer 를 쓰지 않는다 — 아래 {% block scripts %} 의
인라인 스크립트가 곧바로 erpConfirm/erpAlert 을 쓸 수 있어야 한다. #}
-
+
{% block scripts %}{% endblock %}
From 1952e4f0b117529bec7ee4a9e3252ef1b354e2c9 Mon Sep 17 00:00:00 2001
From: king
Date: Wed, 30 Sep 2026 00:47:55 +0900
Subject: [PATCH 27/30] =?UTF-8?q?feat(performance):=2011=EB=B2=88=EA=B0=80?=
=?UTF-8?q?=20=EC=9B=90=EB=B3=B8=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20=ED=99=95?=
=?UTF-8?q?=EC=9D=B8=20=EB=8F=84=EA=B5=AC=20=E2=80=94=20=ED=9B=84=EB=B3=B4?=
=?UTF-8?q?=20=EC=A1=B0=ED=9A=8C=20=EC=A3=BC=EC=86=8C=EB=B3=84=20=EB=8F=99?=
=?UTF-8?q?=EC=9E=91=C2=B7=ED=95=AD=EB=AA=A9=20=ED=95=A9=EA=B3=84?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
11번가 셀러 API 의 주문·클레임 상세 문서는 로그인 뒤에만 있어 조회 주소와
금액 항목 이름을 공개 자료로 확정할 수 없다. 추측으로 매출 수집을 짜지 않고
실데이터로 확정하기 위해:
- ElevenstAdapter.reconcile(day): 결제완료·발송대상·배송중·배송완료·취소신청·
취소완료·반품신청·반품완료·정산 후보 주소를 그날로 호출 → 동작 여부(404 등 오류),
건수, 항목별 채워진 줄·숫자 합계·예시 값. 개인정보 항목은 이름만(값 숨김)
- 설정 화면 "11번가 원본 데이터 확인" 카드
- 테스트 추가
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/elevenst.py | 79 ++++++++++++++++++-
.../templates/performance/index.html | 2 +-
.../templates/performance/settings.html | 14 +++-
.../performance/tests/test_performance.py | 20 +++++
app/static/performance.js | 33 ++++++++
5 files changed, 145 insertions(+), 3 deletions(-)
diff --git a/app/modules/performance/adapters/elevenst.py b/app/modules/performance/adapters/elevenst.py
index 43bb46d..7416777 100644
--- a/app/modules/performance/adapters/elevenst.py
+++ b/app/modules/performance/adapters/elevenst.py
@@ -13,9 +13,10 @@ from __future__ import annotations
import re
import xml.etree.ElementTree as ET
+from datetime import date
from typing import Any
-from .base import AdapterContext, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
+from .base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
HOST = "https://api.11st.co.kr"
@@ -53,6 +54,62 @@ def xml_result(content: bytes) -> tuple[str, str, int]:
return code, text, orders
+# 원본 데이터 확인용 후보 주소 — {s}/{e} = yyyyMMddHHmm, {d} = yyyyMMdd. 문서 미확인 경로가 섞여 있어
+# 404 등 실패도 그대로 보여 준다(어느 주소가 살아 있는지 확인하는 것이 목적).
+PROBE_PATHS: tuple[tuple[str, str, str], ...] = (
+ ("complete", "결제완료(발주확인 전)", "/rest/ordservices/complete/{s}/{e}"),
+ ("packaging", "발송처리 대상(발주확인 후)", "/rest/ordservices/packaging/{s}/{e}"),
+ ("shipping", "배송중", "/rest/ordservices/shipping/{s}/{e}"),
+ ("completed", "배송완료", "/rest/ordservices/completed/{s}/{e}"),
+ ("cancelorders", "취소신청", "/rest/claimservice/cancelorders/{s}/{e}"),
+ ("canceledorders", "취소완료", "/rest/claimservice/canceledorders/{s}/{e}"),
+ ("returnorders", "반품신청", "/rest/claimservice/returnorders/{s}/{e}"),
+ ("returnedorders", "반품완료", "/rest/claimservice/returnedorders/{s}/{e}"),
+ ("settlement", "정산 내역", "/rest/settlement/settlementList/{d}/{d}"),
+)
+
+# 개인정보로 보이는 항목 — 값은 보이지 않고 이름만(이름·연락처·주소·우편번호·아이디·메일·메모)
+PERSONAL = re.compile(r"(nm|name|tel|tlphn|phone|hp|addr|zip|mail|id|memo|msg|pcc|clearance|birth)$|rcvr|ordnm|buyer",
+ re.IGNORECASE)
+NUMBER = re.compile(r"^-?\d+(\.\d+)?$")
+SAFE = re.compile(r"^(prd|opt|slct|dlvEtprs|dlvMthd|clm|reason|stl|sel)", re.IGNORECASE) # 상품·옵션·클레임 사유 등은 보임
+
+
+def xml_records(content: bytes) -> list[dict[str, str]]:
+ """응답에서 주문(또는 클레임·정산) 한 줄씩 — 자식이 모두 글자 항목인 요소를 한 줄로 본다(태그 끝 이름 → 값)."""
+ try:
+ root = ET.fromstring(_xml_text(content))
+ except ET.ParseError:
+ return []
+ out: list[dict[str, str]] = []
+ for el in root.iter():
+ kids = list(el)
+ if len(kids) >= 3 and all(len(k) == 0 for k in kids):
+ out.append({k.tag.rsplit("}", 1)[-1]: (k.text or "").strip() for k in kids})
+ return out
+
+
+def field_summary(records: list[dict[str, str]]) -> list[dict[str, Any]]:
+ """항목별: 채워진 줄 수, 숫자면 합계, 개인정보 아니면 예시 값 하나."""
+ names: dict[str, dict[str, Any]] = {}
+ for r in records:
+ for k, v in r.items():
+ f = names.setdefault(k, {"name": k, "filled": 0, "numeric": True, "sum": 0.0, "sample": "",
+ "personal": bool(PERSONAL.search(k)) and not SAFE.match(k)})
+ if not v:
+ continue
+ f["filled"] += 1
+ if NUMBER.match(v) and f["numeric"]:
+ f["sum"] += float(v)
+ else:
+ f["numeric"] = False
+ if not f["sample"] and not f["personal"]:
+ f["sample"] = v[:40]
+ for f in names.values():
+ f["sum"] = int(round(f["sum"])) if f["numeric"] and f["filled"] else None
+ return list(names.values())
+
+
class ElevenstAdapter(MarketplaceAdapter):
code = "elevenst"
name = "11번가"
@@ -86,6 +143,26 @@ class ElevenstAdapter(MarketplaceAdapter):
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
return res.content
+ # ── 원본 데이터 확인(설정 화면 "11번가 원본 데이터 확인") ─────────
+ def reconcile(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
+ """후보 조회 주소마다 그날(00:00~23:59) 실제로 불러 동작 여부·주문 수·항목별 합계를 돌려준다.
+ 셀러 API 상세 문서가 로그인 뒤에만 있어, 어느 주소·항목이 셀러오피스 화면 매출과 맞는지 실데이터로 확정하는 용도.
+ 개인정보 항목(이름·연락처·주소·아이디 등)은 값 없이 이름만."""
+ self.authenticate(ctx)
+ d = day.strftime("%Y%m%d")
+ out = []
+ for key, label, tmpl in PROBE_PATHS:
+ path = tmpl.format(s=f"{d}0000", e=f"{d}2359", d=d)
+ row: dict[str, Any] = {"key": key, "label": label, "path": path.split("/" + d)[0] + "/…"}
+ try:
+ body = self._get(ctx, path)
+ except AdapterError as exc:
+ out.append({**row, "ok": False, "error": exc.message[:200]})
+ continue
+ records = xml_records(body)
+ out.append({**row, "ok": True, "count": len(records), "fields": field_summary(records)})
+ return {"date": day.isoformat(), "probes": out}
+
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index 0fc29ca..eb8094b 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -239,4 +239,4 @@
} | 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 71a95e3..98537f4 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -116,6 +116,18 @@
+
+
11번가 원본 데이터 확인
+
11번가 셀러 API 의 주문·클레임 조회 주소를 그날(00:00~23:59)로 실제 불러, 어느 주소가 동작하는지와
+ 받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
+ 매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.
+
+
+ 불러오기
+
+
+
+
카페24 매출 대조
카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
@@ -155,4 +167,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 618f950..4989d20 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -852,6 +852,26 @@ def test_elevenst_connection():
assert status == 403 or "허용되지 않은 IP" in exc.message or "XML 아님" in exc.message
else:
raise AssertionError("오류여야 합니다")
+ # 원본 데이터 확인: 살아 있는 주소는 항목 합계, 없는 주소(404)는 실패로. 개인정보 값은 숨김
+ rows = ("" + "".join(
+ f"{n}{a}홍길동상품{n}"
+ f"2026-09-29 10:00:00" for n, a in ((1, 10000), (2, 5500))) +
+ "").encode()
+
+ def route(url, headers=None, timeout=None):
+ if "/ordservices/complete/" in url:
+ return httpx.Response(200, content=rows)
+ if "/ordservices/" in url:
+ return httpx.Response(200, content=b"")
+ return httpx.Response(404, content=b"not found")
+ httpx.get = route
+ rec = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 29))
+ by = {p["key"]: p for p in rec["probes"]}
+ assert by["complete"]["ok"] and by["complete"]["count"] == 2 and by["shipping"]["count"] == 0
+ assert not by["canceledorders"]["ok"] and "404" in by["canceledorders"]["error"]
+ f = {x["name"]: x for x in by["complete"]["fields"]}
+ assert f["ordPayAmt"]["sum"] == 15_500 and f["rcvrNm"]["personal"] and f["rcvrNm"]["sample"] == ""
+ assert f["prdNm"]["sample"] == "상품1" and "홍길동" not in repr(rec)
finally:
httpx.get = orig
diff --git a/app/static/performance.js b/app/static/performance.js
index 94fcfc4..841c81a 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -826,6 +826,39 @@
}
});
+ // ── 11번가 원본 데이터 확인 — 후보 조회 주소별 동작 여부·항목 합계 ──
+ const probe = document.getElementById("perf-probe");
+ if (probe) probe.addEventListener("click", async function () {
+ const day = document.getElementById("perf-probe-date").value;
+ const out = document.getElementById("perf-probe-result");
+ if (!day) return;
+ probe.disabled = true;
+ out.innerHTML = '
";
+ } finally { probe.disabled = false; }
+ });
+
// ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
const backfill = document.getElementById("perf-backfill");
if (backfill) backfill.addEventListener("click", async function () {
From 7d96f2e738c120a54a2cf0c317e4e5879c01a55a Mon Sep 17 00:00:00 2001
From: king
Date: Wed, 30 Sep 2026 01:14:32 +0900
Subject: [PATCH 28/30] =?UTF-8?q?fix(performance):=2011=EB=B2=88=EA=B0=80?=
=?UTF-8?q?=20=EC=9B=90=EB=B3=B8=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20=ED=99=95?=
=?UTF-8?q?=EC=9D=B8=20=E2=80=94=20"=ED=95=B4=EB=8B=B9=20=EA=B1=B4=20?=
=?UTF-8?q?=EC=97=86=EC=9D=8C"=EC=9D=80=200=EA=B1=B4,=20=EA=B8=B0=EA=B0=84?=
=?UTF-8?q?=20=EC=A1=B0=ED=9A=8C=C2=B7=EA=B5=AC=EB=A7=A4=ED=99=95=EC=A0=95?=
=?UTF-8?q?=20=ED=9B=84=EB=B3=B4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
9/9 확인 결과: 취소·반품 주소는 코드 -1 "해당 건이 없습니다"(= 0건)인데 실패로
표시했고, 주문 목록 4개는 지금 그 상태인 주문만 주는 듯해 이미 구매확정된
9/9 주문이 어디에도 없었다. 정산 내역은 정산확정일 기준일 가능성이 있다.
- 결과 문구가 "해당 건이 없습니다" 류면 오류가 아니라 0건
- 기간 조회(최대 31일, 7일씩 나눠 호출) — 매출일부터 정산확정일까지 넓게 확인
- 구매확정 목록 후보 주소 추가
- 테스트 갱신
Co-Authored-By: Claude Opus 5.5
---
app/modules/performance/adapters/elevenst.py | 47 ++++++++++++-------
app/modules/performance/router.py | 4 +-
app/modules/performance/sync.py | 4 +-
.../templates/performance/index.html | 2 +-
.../templates/performance/settings.html | 9 ++--
.../performance/tests/test_performance.py | 10 +++-
app/static/performance.js | 6 ++-
7 files changed, 55 insertions(+), 27 deletions(-)
diff --git a/app/modules/performance/adapters/elevenst.py b/app/modules/performance/adapters/elevenst.py
index 7416777..c3cabf9 100644
--- a/app/modules/performance/adapters/elevenst.py
+++ b/app/modules/performance/adapters/elevenst.py
@@ -13,7 +13,7 @@ from __future__ import annotations
import re
import xml.etree.ElementTree as ET
-from datetime import date
+from datetime import date, timedelta
from typing import Any
from .base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
@@ -65,8 +65,12 @@ PROBE_PATHS: tuple[tuple[str, str, str], ...] = (
("canceledorders", "취소완료", "/rest/claimservice/canceledorders/{s}/{e}"),
("returnorders", "반품신청", "/rest/claimservice/returnorders/{s}/{e}"),
("returnedorders", "반품완료", "/rest/claimservice/returnedorders/{s}/{e}"),
- ("settlement", "정산 내역", "/rest/settlement/settlementList/{d}/{d}"),
+ ("purchaseconfirm", "구매확정(후보)", "/rest/ordservices/purchaseconfirm/{s}/{e}"),
+ ("settlement", "정산 내역", "/rest/settlement/settlementList/{ds}/{de}"),
)
+NO_DATA = re.compile(r"해당\s*건이\s*없|조회된?\s*(내역|건|데이터)이?\s*없") # 코드 -1 이어도 "0건"
+PROBE_CHUNK_DAYS = 7
+PROBE_MAX_DAYS = 31
# 개인정보로 보이는 항목 — 값은 보이지 않고 이름만(이름·연락처·주소·우편번호·아이디·메일·메모)
PERSONAL = re.compile(r"(nm|name|tel|tlphn|phone|hp|addr|zip|mail|id|memo|msg|pcc|clearance|birth)$|rcvr|ordnm|buyer",
@@ -139,29 +143,40 @@ class ElevenstAdapter(MarketplaceAdapter):
raise ApiError(f"11번가 API 오류({res.status_code}): {detail}")
if code == "not-xml":
raise ApiError(f"11번가가 예상하지 못한 응답을 돌려줬습니다(XML 아님): {res.text[:120].strip()}")
- if code and code not in ("0", "200", "00"):
+ if code and code not in ("0", "200", "00") and not NO_DATA.search(text):
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
return res.content
# ── 원본 데이터 확인(설정 화면 "11번가 원본 데이터 확인") ─────────
- def reconcile(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
- """후보 조회 주소마다 그날(00:00~23:59) 실제로 불러 동작 여부·주문 수·항목별 합계를 돌려준다.
+ def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
+ """후보 조회 주소마다 기간(day~to, 최대 31일, 7일씩 나눠)을 실제로 불러 동작 여부·줄 수·항목별 합계를 돌려준다.
셀러 API 상세 문서가 로그인 뒤에만 있어, 어느 주소·항목이 셀러오피스 화면 매출과 맞는지 실데이터로 확정하는 용도.
개인정보 항목(이름·연락처·주소·아이디 등)은 값 없이 이름만."""
self.authenticate(ctx)
- d = day.strftime("%Y%m%d")
+ to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
+ chunks = []
+ s = day
+ while s <= to:
+ e = min(to, s + timedelta(days=PROBE_CHUNK_DAYS - 1))
+ chunks.append((s, e))
+ s = e + timedelta(days=1)
out = []
for key, label, tmpl in PROBE_PATHS:
- path = tmpl.format(s=f"{d}0000", e=f"{d}2359", d=d)
- row: dict[str, Any] = {"key": key, "label": label, "path": path.split("/" + d)[0] + "/…"}
- try:
- body = self._get(ctx, path)
- except AdapterError as exc:
- out.append({**row, "ok": False, "error": exc.message[:200]})
- continue
- records = xml_records(body)
- out.append({**row, "ok": True, "count": len(records), "fields": field_summary(records)})
- return {"date": day.isoformat(), "probes": out}
+ row: dict[str, Any] = {"key": key, "label": label, "path": tmpl.split("/{")[0] + "/…"}
+ records: list[dict[str, str]] = []
+ error = ""
+ for s, e in chunks:
+ ds, de = s.strftime("%Y%m%d"), e.strftime("%Y%m%d")
+ try:
+ records += xml_records(self._get(ctx, tmpl.format(s=f"{ds}0000", e=f"{de}2359", ds=ds, de=de)))
+ except AdapterError as exc:
+ error = exc.message[:200]
+ break
+ if error:
+ out.append({**row, "ok": False, "error": error})
+ else:
+ out.append({**row, "ok": True, "count": len(records), "fields": field_summary(records)})
+ return {"date": day.isoformat(), "to": to.isoformat(), "probes": out}
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py
index e7e408c..cbec390 100644
--- a/app/modules/performance/router.py
+++ b/app/modules/performance/router.py
@@ -279,13 +279,13 @@ def api_test_connection(request: Request, code: str, payload: dict[str, Any] = B
@router.get("/api/marketplaces/{code}/reconcile")
-def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date")) -> JSONResponse:
+def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse:
"""쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
store, user = common.require_store(request, admin=True)
_code_or_404(store, code)
day = _parse_date(date_)
_, sync = common.services(request, store)
- return JSONResponse(sync.reconcile(code, day, user=user["email"]))
+ return JSONResponse(sync.reconcile(code, day, to=_parse_date(to, field="종료일"), user=user["email"]))
@router.get("/api/marketplaces/{code}/daily-check")
diff --git a/app/modules/performance/sync.py b/app/modules/performance/sync.py
index b0c1792..12f01d8 100644
--- a/app/modules/performance/sync.py
+++ b/app/modules/performance/sync.py
@@ -139,7 +139,7 @@ class SyncService:
return [self.sync_marketplace(c, start, end, trigger=trigger, user=user) for c in targets]
# ── 쇼핑몰 화면과 대조 ────────────────────────────────
- def reconcile(self, code: str, day: date, *, user: str = "") -> dict[str, Any]:
+ def reconcile(self, code: str, day: date, *, to: date | None = None, user: str = "") -> dict[str, Any]:
"""어댑터가 지원하면(reconcile) 그날 원천 금액을 항목별로 합산해 돌려준다. DB 는 바꾸지 않는다."""
adapter = get_adapter(code)
if adapter is None or not hasattr(adapter, "reconcile"):
@@ -147,7 +147,7 @@ class SyncService:
ctx = None
try:
ctx = self._ctx(adapter, user=user)
- return {"ok": True, **adapter.reconcile(ctx, day)}
+ return {"ok": True, **(adapter.reconcile(ctx, day, to=to) if to else adapter.reconcile(ctx, day))}
except Exception as exc: # noqa: BLE001
status, message = self._failure(exc, ctx)
return {"ok": False, "status": status, "label": STATUS_LABELS.get(status, status), "message": message}
diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html
index eb8094b..d5bc6c3 100644
--- a/app/modules/performance/templates/performance/index.html
+++ b/app/modules/performance/templates/performance/index.html
@@ -239,4 +239,4 @@
} | 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 98537f4..3c3f8fd 100644
--- a/app/modules/performance/templates/performance/settings.html
+++ b/app/modules/performance/templates/performance/settings.html
@@ -118,11 +118,14 @@
11번가 원본 데이터 확인
-
11번가 셀러 API 의 주문·클레임 조회 주소를 그날(00:00~23:59)로 실제 불러, 어느 주소가 동작하는지와
- 받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
+
11번가 셀러 API 의 주문·클레임·정산 조회 주소를 기간(최대 31일)으로 실제 불러, 어느 주소가 동작하는지와
+ 받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 주문 목록은 지금 그 상태인 주문만, 정산은 정산일 기준일 수 있어
+ 매출이 있던 날부터 넉넉히(예: 3주) 잡아 주세요. 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.
+ ~
+
불러오기
@@ -167,4 +170,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 4989d20..c0a7820 100644
--- a/app/modules/performance/tests/test_performance.py
+++ b/app/modules/performance/tests/test_performance.py
@@ -861,14 +861,22 @@ def test_elevenst_connection():
def route(url, headers=None, timeout=None):
if "/ordservices/complete/" in url:
return httpx.Response(200, content=rows)
+ if "/ordservices/purchaseconfirm/" in url:
+ return httpx.Response(404, content=b"not found")
if "/ordservices/" in url:
return httpx.Response(200, content=b"")
+ if "/claimservice/" in url:
+ return httpx.Response(200, content="-1"
+ "해당 건이 없습니다.".encode())
return httpx.Response(404, content=b"not found")
httpx.get = route
rec = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 29))
+ wide = ev.ElevenstAdapter().reconcile(ctx, date(2026, 9, 1), to=date(2026, 9, 20)) # 7일씩 3번
+ assert wide["to"] == "2026-09-20" and {p["key"]: p.get("count") for p in wide["probes"]}["complete"] == 6
by = {p["key"]: p for p in rec["probes"]}
assert by["complete"]["ok"] and by["complete"]["count"] == 2 and by["shipping"]["count"] == 0
- assert not by["canceledorders"]["ok"] and "404" in by["canceledorders"]["error"]
+ assert not by["purchaseconfirm"]["ok"] and "404" in by["purchaseconfirm"]["error"]
+ assert by["canceledorders"]["ok"] and by["canceledorders"]["count"] == 0 # 코드 -1 "해당 건이 없습니다" = 0건
f = {x["name"]: x for x in by["complete"]["fields"]}
assert f["ordPayAmt"]["sum"] == 15_500 and f["rcvrNm"]["personal"] and f["rcvrNm"]["sample"] == ""
assert f["prdNm"]["sample"] == "상품1" and "홍길동" not in repr(rec)
diff --git a/app/static/performance.js b/app/static/performance.js
index 841c81a..7dcc954 100644
--- a/app/static/performance.js
+++ b/app/static/performance.js
@@ -833,9 +833,11 @@
const out = document.getElementById("perf-probe-result");
if (!day) return;
probe.disabled = true;
- out.innerHTML = '