Merge branch 'feat/performance' into feat/project — 서버가 feat/project 로 실적 모듈까지 함께 돌도록
This commit is contained in:
@@ -146,3 +146,20 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# 읽기 전용 역할 itemcode_ro 를 먼저 생성하고(아래 DSN), 낱개+세트 UNION 검색 SQL 사용:
|
||||
# ITEMCODE_DB_URL=postgresql://itemcode_ro:replace-me@postgres-db:5432/itemcode_db
|
||||
# ITEMCODE_SEARCH_SQL=SELECT item_code AS code, name AS name, '낱개' AS type FROM single_items WHERE item_code ILIKE %(q)s OR name ILIKE %(q)s UNION ALL SELECT item_code AS code, name AS name, '세트' AS type FROM set_items WHERE item_code ILIKE %(q)s OR name ILIKE %(q)s ORDER BY code ASC LIMIT %(limit)s
|
||||
|
||||
# ─── 실적(쇼핑몰 통합 매출) — app/modules/performance ───
|
||||
# performance_db 전용. 미설정 시 모듈이 "설정 필요" 안내만 표시.
|
||||
# 초기화: scripts/sql/performance_db_init.sql (docs/DATABASES.md 참고)
|
||||
# PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/performance_db
|
||||
#
|
||||
# 쇼핑몰 API 인증정보(ID·Key·Secret·Token)는 여기에 넣지 않는다 —
|
||||
# 실적 → 설정 화면에서 입력하면 아래 마스터 키로 AES-256-GCM 암호화해 DB 에 저장한다.
|
||||
# 마스터 키는 DB 에 저장되지 않으며, 잃어버리면 저장된 인증정보를 복구할 수 없다(별도 안전 보관).
|
||||
# 생성: openssl rand -hex 32 (64자 hex, 또는 32바이트 base64)
|
||||
# APP_ENCRYPTION_KEY=
|
||||
# APP_ENCRYPTION_KEY_VERSION=1
|
||||
# 키 교체(rotation) 시: 새 키를 APP_ENCRYPTION_KEY 에, 버전을 올리고(예: 2),
|
||||
# 예전 키는 APP_ENCRYPTION_KEY_V1= 로 남긴 뒤 설정 화면 [현재 키로 다시 암호화] → 완료 후 V1 삭제.
|
||||
# APP_ENCRYPTION_KEY_V1=
|
||||
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
||||
# PERFORMANCE_SYNC_DAYS=7
|
||||
|
||||
@@ -38,6 +38,8 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
|
||||
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력. 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지(`POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A` — NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨), 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매)을 수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다. 그래서 "마지막 쓰기가 권위": 상세설명은 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 쓰고(`store.resolve_description`), 스칼라(상품명·가격·이미지·진열/판매)는 PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌운다(`store.overlay_recent_write`). 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분). 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다. 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
|
||||
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 iframe 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md`
|
||||
|
||||
- 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면·API 는 `is_admin`. 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `docs/PERFORMANCE_MODULE.md`
|
||||
|
||||
상세는 `docs/PROJECT_OVERVIEW.md`.
|
||||
|
||||
---
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
+19
@@ -24,6 +24,8 @@ from .modules.expense import CategoryStore, build_expense_store
|
||||
from .modules.expense import router as expense_router
|
||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||
from .modules.malaysia import router as malaysia_router
|
||||
from .modules.performance import build_performance_store
|
||||
from .modules.performance import router as performance_router
|
||||
from .modules.project import build_project_store
|
||||
from .modules.project import router as project_router
|
||||
from .modules.vacation import build_vacation_store
|
||||
@@ -49,6 +51,7 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"dispatch": "말레이시아 배송",
|
||||
"project": "프로젝트 관리",
|
||||
"cafe24": "카페24 상품관리",
|
||||
"performance": "실적",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
@@ -136,6 +139,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "dispatch" / "templates",
|
||||
BASE_DIR / "modules" / "project" / "templates",
|
||||
BASE_DIR / "modules" / "cafe24" / "templates",
|
||||
BASE_DIR / "modules" / "performance" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -195,6 +199,9 @@ app.state.project_store = build_project_store(dsn=env("PROJECT_DB_URL") or None)
|
||||
# 카페24 상품관리: CAFE24_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||
# 카페24 API 호출/토큰은 app/integrations/cafe24 공통 계층(CAFE24_* 환경변수).
|
||||
app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
|
||||
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
||||
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
||||
|
||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||
app.include_router(expense_router)
|
||||
@@ -204,6 +211,7 @@ app.include_router(malaysia_router)
|
||||
app.include_router(dispatch_router)
|
||||
app.include_router(project_router)
|
||||
app.include_router(cafe24_router)
|
||||
app.include_router(performance_router)
|
||||
|
||||
|
||||
def public_url_for(request: Request, route_name: str) -> str:
|
||||
@@ -386,6 +394,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
{
|
||||
"key": "performance",
|
||||
"title": "실적",
|
||||
"subtitle": "Sales Performance",
|
||||
"description": "여러 쇼핑몰의 매출을 일자·쇼핑몰별로 한 화면에서 보고 수수료 차감 매출을 계산합니다.",
|
||||
"url": "/performance/",
|
||||
"health_url": "/performance/health",
|
||||
"status": "ready",
|
||||
"category": "관리",
|
||||
},
|
||||
]
|
||||
allowed = allowed_modules(user_rec)
|
||||
for item in items:
|
||||
@@ -406,6 +424,7 @@ def _icon_svg(name: str) -> str:
|
||||
"dispatch": '<rect x="1" y="3" width="15" height="13"/><path d="M16 8h4l3 3v5h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/>',
|
||||
"project": '<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="8" y1="13" x2="13" y2="13"/><line x1="8" y1="16" x2="11" y2="16"/>',
|
||||
"cafe24": '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9h10"/><path d="M7 13h7"/><path d="M7 17h4"/>',
|
||||
"performance": '<path d="M3 3v18h18"/><rect x="7" y="12" width="3" height="6"/><rect x="12" y="8" width="3" height="10"/><rect x="17" y="5" width="3" height="13"/>',
|
||||
"modules": '<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>',
|
||||
}
|
||||
body = paths.get(name, paths["modules"])
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""실적(쇼핑몰 통합 매출) 모듈.
|
||||
|
||||
네 영역을 분리해 둔다(쇼핑몰 하나를 추가할 때 어댑터 파일 하나만 늘어나게).
|
||||
① 쇼핑몰 API 수집 adapters/ (쇼핑몰별 어댑터) + sync.py (공통 동기화 서비스)
|
||||
② 인증정보·보안 security/ (AES-256-GCM, 비밀값 가리기) + credentials.py
|
||||
③ 매출 계산/저장 calc.py (기간·수수료·집계) + db.py (performance_db)
|
||||
④ 대시보드/UI dashboard.py (화면 데이터 조립) + router.py + templates/performance/
|
||||
|
||||
데이터 저장은 performance_db 전용이다. PERFORMANCE_DB_URL 미설정 시
|
||||
build_performance_store 는 None 을 반환하고 라우터가 "설정 필요" 안내를 보여 준다(앱은 죽지 않음).
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .router import router
|
||||
|
||||
__all__ = ["router", "build_performance_store"]
|
||||
|
||||
|
||||
def build_performance_store(*, dsn: str | None) -> Any:
|
||||
if not dsn:
|
||||
return None
|
||||
from .db import PerformanceDBStore # 지연 import (개발 환경 deps 없을 수 있음)
|
||||
|
||||
return PerformanceDBStore(dsn)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""① 쇼핑몰 API 수집 — 쇼핑몰별 어댑터(공통 인터페이스는 base.py, 목록은 registry.py)."""
|
||||
|
||||
from .registry import all_adapters, get_adapter
|
||||
|
||||
__all__ = ["all_adapters", "get_adapter"]
|
||||
@@ -0,0 +1,225 @@
|
||||
"""① 쇼핑몰 API 수집 — 공통 인터페이스.
|
||||
|
||||
쇼핑몰 하나 = 어댑터 파일 하나. 새 쇼핑몰은 `MarketplaceAdapter` 를 상속한 파일을
|
||||
만들고 `registry.py` 에 한 줄 추가하면 설정 화면·동기화·대시보드에 자동으로 붙는다.
|
||||
|
||||
흐름: 쇼핑몰 원본 → 어댑터(fetch_* → normalize_*) → 공통 SaleEvent → sync 서비스가 DB 저장
|
||||
|
||||
어댑터가 지켜야 할 것:
|
||||
- 인증정보는 `ctx.credentials.get(key)` 로만 꺼낸다(복호화는 서버 안에서만).
|
||||
- 새 토큰은 `ctx.credentials.set(key, value)` 로 저장한다(자동 암호화).
|
||||
- 오류는 아래 AdapterError 계열로 던진다. 메시지에 비밀값을 넣지 않는다
|
||||
(sync 서비스가 한 번 더 가리지만, 애초에 넣지 않는 것이 원칙).
|
||||
- 금액은 원 단위 정수(int). 결제는 +, 취소/반품은 − 로 만든다.
|
||||
- 날짜 기준을 섞지 않는다: order_date / payment_date / event_date 를 각각 채운다.
|
||||
집계 기준일(sales_date)은 sync 서비스가 정한다(결제=결제일, 취소·반품=발생일).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from typing import Any, Iterable, Protocol
|
||||
|
||||
# 연결 상태 코드 → 화면 표시. DB CHECK 제약과 같은 목록.
|
||||
STATUS_LABELS: dict[str, str] = {
|
||||
"ok": "정상 연결",
|
||||
"not_configured": "인증정보 미설정",
|
||||
"auth_failed": "인증 실패",
|
||||
"token_expired": "Token 만료",
|
||||
"api_error": "API 오류",
|
||||
"not_implemented": "연동 준비 중",
|
||||
"unknown": "확인 전",
|
||||
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
|
||||
}
|
||||
|
||||
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 오류 — status 가 곧 연결 상태 코드
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class AdapterError(Exception):
|
||||
status = "api_error"
|
||||
|
||||
def __init__(self, message: str = "") -> None:
|
||||
super().__init__(message or STATUS_LABELS.get(self.status, "오류"))
|
||||
self.message = message or STATUS_LABELS.get(self.status, "오류")
|
||||
|
||||
|
||||
class NotConfigured(AdapterError):
|
||||
status = "not_configured"
|
||||
|
||||
|
||||
class AuthFailed(AdapterError):
|
||||
status = "auth_failed"
|
||||
|
||||
|
||||
class TokenExpired(AdapterError):
|
||||
status = "token_expired"
|
||||
|
||||
|
||||
class ApiError(AdapterError):
|
||||
status = "api_error"
|
||||
|
||||
|
||||
class NotImplementedYet(AdapterError):
|
||||
status = "not_implemented"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 설정 입력칸 · 공통 매출 사건
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@dataclass(frozen=True)
|
||||
class CredentialField:
|
||||
"""설정 화면 입력칸 하나. secret=True 면 저장 후 값을 화면으로 다시 보내지 않는다.
|
||||
|
||||
internal=True 는 화면에 안 보이는 내부 값(access/refresh token 등) — 어댑터가 직접 저장.
|
||||
"""
|
||||
|
||||
key: str
|
||||
label: str
|
||||
secret: bool = False
|
||||
required: bool = True
|
||||
help: str = ""
|
||||
placeholder: str = ""
|
||||
internal: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaleEvent:
|
||||
"""쇼핑몰 원본을 공통 형식으로 바꾼 매출 사건 하나(주문 라인 단위 권장)."""
|
||||
|
||||
event_type: str # SALE / CANCEL / RETURN / ADJUST
|
||||
external_event_id: str # 쇼핑몰 안에서 이 사건을 유일하게 가리키는 값(중복 방지 키)
|
||||
external_order_id: str
|
||||
event_date: date # 사건 발생일(결제=결제일, 취소=취소일, 반품=반품완료일)
|
||||
amount: int # 원 단위 정수. 결제 +, 취소/반품 −
|
||||
external_line_id: str = ""
|
||||
order_date: date | None = None
|
||||
payment_date: date | None = None
|
||||
product_name: str = ""
|
||||
option_name: str = ""
|
||||
quantity: int = 0
|
||||
discount_amount: int = 0
|
||||
order_status: str = ""
|
||||
raw: dict[str, Any] = field(default_factory=dict)
|
||||
# 어느 쇼핑몰 열로 집계할지 — None 이면 이 어댑터의 쇼핑몰. 다른 쇼핑몰 주문을 대신 받아 오는
|
||||
# 연동(예: 카페24 마켓 통합관리가 가져온 스마트스토어 주문)은 해당 쇼핑몰 코드를 넣는다.
|
||||
marketplace_code: str | None = None
|
||||
|
||||
def validate(self) -> None:
|
||||
if self.event_type not in EVENT_TYPES:
|
||||
raise ValueError(f"알 수 없는 사건 종류: {self.event_type}")
|
||||
if not self.external_event_id or not self.external_order_id:
|
||||
raise ValueError("external_event_id / external_order_id 가 필요합니다.")
|
||||
if not isinstance(self.amount, int) or isinstance(self.amount, bool):
|
||||
raise ValueError("amount 는 원 단위 정수여야 합니다.")
|
||||
if self.event_type == "SALE" and self.amount < 0:
|
||||
raise ValueError("결제(SALE) 금액은 음수일 수 없습니다.")
|
||||
if self.event_type in ("CANCEL", "RETURN") and self.amount > 0:
|
||||
raise ValueError("취소/반품 금액은 음수(또는 0)여야 합니다.")
|
||||
|
||||
|
||||
class CredentialAccessor(Protocol):
|
||||
def get(self, key: str) -> str: ...
|
||||
|
||||
def set(self, key: str, value: str) -> None: ...
|
||||
|
||||
def has(self, key: str) -> bool: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdapterContext:
|
||||
code: str
|
||||
credentials: CredentialAccessor
|
||||
app_state: Any = None # 공통 연동 계층 재사용(예: 카페24 토큰 저장소)
|
||||
timeout_sec: float = 20.0
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 어댑터
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class MarketplaceAdapter(ABC):
|
||||
code: str = ""
|
||||
name: str = ""
|
||||
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
|
||||
# replace_range 일 때 이 어댑터가 만든 사건을 가려내는 외부 사건 ID 접두어. 다른 쇼핑몰 열로 보낸
|
||||
# 사건(marketplace_code 지정)도 이 접두어로 찾아 함께 교체한다 — 그 쇼핑몰의 직접 연동분은 건드리지 않음.
|
||||
event_prefix: str = ""
|
||||
note: str = "" # 설정 화면 안내 문구
|
||||
|
||||
# ── 설정 ──────────────────────────────────────────────
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return []
|
||||
|
||||
def visible_fields(self) -> list[CredentialField]:
|
||||
return [f for f in self.credential_fields() if not f.internal]
|
||||
|
||||
@property
|
||||
def uses_shared_integration(self) -> bool:
|
||||
return self.auth_type == "shared"
|
||||
|
||||
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||
"""저장 전 검사. 값 자체를 오류 문구에 넣지 않는다."""
|
||||
errors: list[str] = []
|
||||
for f in self.visible_fields():
|
||||
v = (values.get(f.key) or "").strip()
|
||||
if f.required and not v:
|
||||
errors.append(f"{f.label} 을(를) 입력하세요.")
|
||||
elif v and len(v) > 2000:
|
||||
errors.append(f"{f.label} 값이 너무 깁니다.")
|
||||
return errors
|
||||
|
||||
def is_configured(self, ctx: AdapterContext) -> bool:
|
||||
return all(ctx.credentials.has(f.key) for f in self.visible_fields() if f.required)
|
||||
|
||||
# ── 인증 ──────────────────────────────────────────────
|
||||
def authenticate(self, ctx: AdapterContext) -> None:
|
||||
"""API 호출 전 준비(토큰 발급 등). 기본은 할 일 없음."""
|
||||
if not self.is_configured(ctx):
|
||||
raise NotConfigured("필수 인증정보가 입력되지 않았습니다.")
|
||||
|
||||
def refresh_token(self, ctx: AdapterContext) -> None:
|
||||
"""OAuth 쇼핑몰: refresh token 으로 access token 재발급 후 ctx.credentials.set(...)."""
|
||||
return None
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
"""성공 시 사람이 읽을 짧은 문구 반환. 실패는 AdapterError."""
|
||||
self.authenticate(ctx)
|
||||
raise NotImplementedYet(f"{self.name} API 연동은 다음 단계에서 구현됩니다.")
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
raise NotImplementedYet(f"{self.name} 주문 수집은 다음 단계에서 구현됩니다.")
|
||||
|
||||
def fetch_refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
return []
|
||||
|
||||
def normalize_order(self, raw: dict[str, Any]) -> list[SaleEvent]:
|
||||
raise NotImplementedYet(f"{self.name} 주문 변환은 다음 단계에서 구현됩니다.")
|
||||
|
||||
def normalize_refund(self, raw: dict[str, Any]) -> list[SaleEvent]:
|
||||
return []
|
||||
|
||||
def collect(self, ctx: AdapterContext, start: date, end: date) -> tuple[int, list[SaleEvent]]:
|
||||
"""기간의 주문·취소/반품을 받아 공통 사건으로 변환. (원본 건수, 사건 목록)."""
|
||||
self.authenticate(ctx)
|
||||
fetched = 0
|
||||
events: list[SaleEvent] = []
|
||||
for raw in self.fetch_orders(ctx, start, end):
|
||||
fetched += 1
|
||||
events.extend(self.normalize_order(raw))
|
||||
for raw in self.fetch_refunds(ctx, start, end):
|
||||
fetched += 1
|
||||
events.extend(self.normalize_refund(raw))
|
||||
for ev in events:
|
||||
ev.validate()
|
||||
return fetched, events
|
||||
@@ -0,0 +1,754 @@
|
||||
"""카페24 — 공통 연동 계층(app/integrations/cafe24) 재사용.
|
||||
|
||||
카페24는 이미 OAuth 로 연결해 쓰고 있다(상품관리). 실적 설정에서 인증정보를 따로
|
||||
받지 않고, 같은 토큰 저장소(cafe24_db)와 클라이언트(재시도·429·토큰 자동 갱신)를 쓴다.
|
||||
주문 읽기 권한(mall.read_order)이 필요하다 — config.DEFAULT_SCOPES 에 포함, 권한 추가 후
|
||||
카페24 상품관리 → 시스템에서 한 번 다시 연결해야 한다.
|
||||
|
||||
카페24 관리자 "일별 매출내역"과 같은 기준으로 센다(Admin API 문서 2026-09-01 확인).
|
||||
- 결제합계(SALE, +): GET /admin/orders date_type=pay_date(결제일), 결제된(paid=T) 주문마다
|
||||
실결제금액 + 적립금 + 예치금 + 네이버포인트 = 고객이 실제로 낸 금액
|
||||
(initial_order_amount 의 payment_amount·points_spent_amount·credits_spent_amount + 주문의 naver_point)
|
||||
"상품구매금액 + 배송비 − 할인 − 쿠폰"은 할인 필드에 안 잡히는 차이(수십~수만 원)가 생겨 쓰지 않는다
|
||||
(2026-09-23 실데이터: 카페24 1,874,738 = 1,713,128 + 10,110 + 151,500, 상품식은 1,874,800).
|
||||
네 값이 모두 0인 주문도 0원(카페24와 같음).
|
||||
환불은 따로 빼므로 취소 후 금액(actual_order_amount)이 아니라 결제 당시 금액을 쓴다.
|
||||
- 환불합계(CANCEL/RETURN, −): GET /admin/refunds date_type=refund_date(환불완료일),
|
||||
실제 환불액(actual_refund_amount). 환불코드가 R 로 시작하면 반품, 그 밖은 취소.
|
||||
- 수집 기간을 통째로 다시 받는다(replace_range) — 결제·환불 모두 기간 안 날짜로 조회되므로
|
||||
그 기간의 카페24 실데이터를 지우고 새로 넣는다. 규칙이 바뀌거나 주문이 사라져도 이중 집계 없음.
|
||||
- 자체몰 주문(market_id 가 self/빈값)은 카페24 열. 카페24 마켓 통합관리로 들어온 다른 마켓 주문
|
||||
(스마트스토어·쿠팡 등)은 MARKET_MAP 으로 해당 쇼핑몰 열에 넣는다(환불도 원 주문으로 판단).
|
||||
현재 이 쇼핑몰은 마켓 통합관리를 쓰지 않아 MARKET_MAP 이 비어 있다 — 모두 카페24 열.
|
||||
MARKET_MAP 에 없는 마켓은 카페24 열 — 전체 합계는 항상 카페24 일별 매출내역과 같다.
|
||||
네이버페이 결제(order_place_id=NCHECKOUT)는 자체몰 주문이라 카페24 열.
|
||||
카페24 가 만든 사건은 모두 외부 사건 ID 앞에 "c24:" — 다시 받을 때 이것만 골라 교체하므로
|
||||
해당 쇼핑몰을 나중에 직접 연동해도 그 데이터는 건드리지 않는다(단, 같은 주문을 양쪽에서 받지 않게
|
||||
직접 연동을 켜는 쇼핑몰은 MARKET_MAP 에서 빼야 한다).
|
||||
- 한 호출 검색기간 3개월 미만 → 60일씩 나눠 요청. orders limit ≤ 1000, refunds limit ≤ 500, offset ≤ 15000.
|
||||
- 개인정보(구매자 이름·주소·연락처·계좌)는 저장하지 않는다 — raw 에는 금액·상태 필드만.
|
||||
- 할인 항목 구성·마켓 주문 포함 여부는 `reconcile()`(설정 화면 "카페24 매출 대조")로 카페24 화면과
|
||||
대조해 확정한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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"
|
||||
ORDER_LIMIT = 1000
|
||||
REFUND_LIMIT = 500
|
||||
LOOKUP_BATCH = 100
|
||||
MAX_OFFSET = 15000
|
||||
CHUNK_DAYS = 60
|
||||
EVENT_PREFIX = "c24:"
|
||||
|
||||
# 매출 대조 전용 — 클레임 완료 주문 조회 날짜 유형과 "완료" 상태(입금전취소 C47~49 는 결제 전이라 제외)
|
||||
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"})
|
||||
NO_RECORD_CHANNEL = "ncheckout" # 네이버페이만 — 톡체크아웃·자체몰의 환불 기록 없는 취소는 카페24 환불합계에 없다
|
||||
REFUND_LOOKAROUND_DAYS = 60
|
||||
|
||||
# 카페24 자체몰 주문 채널 — market_id 는 외부 마켓만이 아니라 주문 채널·간편결제도 담는다
|
||||
# (실데이터 확인 2026-09-30: mobile=모바일웹, NCHECKOUT=네이버페이, KAKAOPAY=톡체크아웃).
|
||||
# 이 주문들은 카페24 자체몰 매출이다. 비교는 소문자로.
|
||||
SELF_CHANNELS: dict[str, str] = {
|
||||
# self 는 PC 전용이 아니다 — 주문경로(order_place_name)가 "PC쇼핑몰"·"모바일웹"으로 나뉘어 섞여 있다(실데이터 확인).
|
||||
"": "자체몰", "self": "자체몰", "cafe24": "자체몰", "mobile": "모바일웹", "mobile_d": "모바일앱",
|
||||
"ncheckout": "네이버페이", "kakaopay": "톡체크아웃",
|
||||
}
|
||||
|
||||
# 카페24 마켓 통합관리가 가져온 외부 마켓 주문의 market_id(또는 order_place_id) → 우리 쇼핑몰 열.
|
||||
# 이 쇼핑몰은 카페24 마켓 통합관리를 쓰지 않는다(2026-09 사용자 확인) — 비워 두어 카페24로 들어온 주문은 모두
|
||||
# 카페24 열. 나중에 쓰게 되면 대조 화면 "주문 채널별" 표의 market_id 로 확인해 예: {"shopn": "naver"} 처럼 넣는다
|
||||
# (그 쇼핑몰을 직접 연동한다면 넣지 않는다 — 같은 주문을 두 번 받게 됨). 결제수단과 헷갈리는 이름(naver, kakao) 금지.
|
||||
MARKET_MAP: dict[str, str] = {}
|
||||
|
||||
|
||||
def _key(value: Any) -> str:
|
||||
return str(value or "").strip().lower()
|
||||
|
||||
|
||||
def channel_kind(market_id: Any, order_place_id: Any = None) -> str:
|
||||
"""self(자체몰 채널) / market(외부 마켓, 해당 쇼핑몰 열) / unknown(모르는 채널 → 카페24 열)."""
|
||||
if market_id is None or _key(market_id) in SELF_CHANNELS:
|
||||
return "self"
|
||||
if _key(market_id) in MARKET_MAP or _key(order_place_id) in MARKET_MAP:
|
||||
return "market"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def target_code(market_id: Any, order_place_id: Any = None) -> str:
|
||||
"""이 주문을 집계할 쇼핑몰 열. 자체몰 채널·모르는 채널은 카페24."""
|
||||
if channel_kind(market_id, order_place_id) != "market":
|
||||
return "cafe24"
|
||||
return MARKET_MAP.get(_key(market_id)) or MARKET_MAP[_key(order_place_id)]
|
||||
|
||||
# 참고식(상품구매금액 + 배송비 − 할인 − 쿠폰)의 필드 — 결제합계는 PAID_FIELDS + naver_point 로 센다
|
||||
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")
|
||||
PAID_FIELDS = ("payment_amount", "points_spent_amount", "credits_spent_amount")
|
||||
|
||||
|
||||
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 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}, "naver_point": _won(order.get("naver_point"))}
|
||||
|
||||
|
||||
def goods_total(w: dict[str, int]) -> int:
|
||||
"""참고식: 상품구매금액 + 배송비 − 할인 − 쿠폰."""
|
||||
return (w["order_price_amount"] + w["shipping_fee"]
|
||||
- sum(w[k] for k in DISCOUNT_FIELDS) - sum(w[k] for k in COUPON_FIELDS))
|
||||
|
||||
|
||||
def _paid_total(w: dict[str, int]) -> int:
|
||||
"""결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트. 넷 다 0인 주문은 카페24도 0원으로 센다
|
||||
(9/25 가상계좌·휴대폰 9,900 주문 — 상품식으로 넣으면 그만큼 많아짐)."""
|
||||
return sum(w[k] for k in PAID_FIELDS) + w["naver_point"]
|
||||
|
||||
|
||||
def order_total(order: dict[str, Any]) -> int:
|
||||
"""결제합계(결제 당시) — 카페24 일별 매출내역 결제합계와 같은 기준."""
|
||||
return _paid_total(order_amounts(order))
|
||||
|
||||
|
||||
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 {}
|
||||
return _paid_total({**{k: _won(a.get(k)) for k in AMOUNT_FIELDS}, "naver_point": _won(order.get("naver_point"))})
|
||||
|
||||
|
||||
def is_self_market(market_id: Any) -> bool:
|
||||
"""카페24 자체몰 채널(PC·모바일·네이버페이·톡체크아웃 등)인가."""
|
||||
return channel_kind(market_id) == "self"
|
||||
|
||||
|
||||
# 대조 진단 — 이름에 이 말이 들어간 숫자 필드만 합산(계좌·연락처 같은 개인정보 숫자는 이름이 달라 제외)
|
||||
DIAG_WORDS = ("price", "amount", "discount", "point", "fee", "credit", "mileage", "sale", "benefit", "incentive", "coupon")
|
||||
|
||||
|
||||
def _num(value: Any) -> Decimal | None:
|
||||
if isinstance(value, bool) or value is None:
|
||||
return None
|
||||
try:
|
||||
d = Decimal(str(value).strip())
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
return d if d.is_finite() else None
|
||||
|
||||
|
||||
def money_fields(obj: Any) -> dict[str, int]:
|
||||
"""dict 의 금액성 숫자 필드(이름에 DIAG_WORDS) → 원 단위. 중첩은 한 단계까지 "부모.자식"."""
|
||||
out: dict[str, int] = {}
|
||||
if not isinstance(obj, dict):
|
||||
return out
|
||||
for k, v in obj.items():
|
||||
if isinstance(v, dict):
|
||||
for k2, v2 in money_fields(v).items():
|
||||
out[f"{k}.{k2}"] = v2
|
||||
continue
|
||||
if not any(w in str(k).lower() for w in DIAG_WORDS):
|
||||
continue
|
||||
n = _num(v)
|
||||
if n is not None:
|
||||
out[str(k)] = int(n.quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
return out
|
||||
|
||||
|
||||
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):
|
||||
code = "cafe24"
|
||||
name = "카페24"
|
||||
auth_type = "shared"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
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 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 _client(self, ctx: AdapterContext):
|
||||
from app.integrations.cafe24 import build_cafe24_api # 지연 import
|
||||
|
||||
return build_cafe24_api(self._repo(ctx)).client
|
||||
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
from app.integrations.cafe24.errors import ( # 지연 import
|
||||
Cafe24ApiError,
|
||||
Cafe24AuthError,
|
||||
Cafe24ConfigError,
|
||||
Cafe24RateLimitError,
|
||||
)
|
||||
|
||||
try:
|
||||
return self._client(ctx).get(path, 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)
|
||||
today = today_kst().isoformat()
|
||||
self._get(ctx, "/admin/orders", {"start_date": today, "end_date": today, "date_type": "pay_date", "limit": 1})
|
||||
return "카페24 연결 정상(주문 조회 권한 확인)."
|
||||
|
||||
# ── 조회 ──────────────────────────────────────────────
|
||||
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,
|
||||
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": date_type}, REFUND_LIMIT)
|
||||
|
||||
def claim_items(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
|
||||
"""그날 취소완료·반품완료·교환완료된 주문의 클레임 품목(대조 전용). 환불 API 에 안 잡히는 건
|
||||
(네이버페이 취소 등)을 찾기 위한 것. 조회 실패는 errors 에 담고 계속한다. 개인정보 제외."""
|
||||
items: list[dict[str, Any]] = []
|
||||
errors: list[str] = []
|
||||
seen: set[str] = set()
|
||||
full_cancel_shipping = 0
|
||||
for date_type, label in CLAIM_DATE_TYPES:
|
||||
try:
|
||||
orders = list(self._paged(ctx, "/admin/orders", "orders",
|
||||
{"start_date": day.isoformat(), "end_date": day.isoformat(),
|
||||
"date_type": date_type, "embed": "items"}, ORDER_LIMIT))
|
||||
except ApiError as exc:
|
||||
errors.append(f"{label}: {exc}")
|
||||
continue
|
||||
for o in orders:
|
||||
oid = str(o.get("order_id") or "")
|
||||
its = o.get("items") or []
|
||||
claimed = [i for i in its if str(i.get("order_status") or "")[:1] in ("C", "R", "E")
|
||||
and str(i.get("order_status") or "") not in UNPAID_CANCEL]
|
||||
if claimed and len(claimed) == len(its) and oid not in seen and \
|
||||
all(str(i.get("order_status") or "") in CLAIM_DONE and str(i.get("order_status"))[:1] == "C" for i in its):
|
||||
full_cancel_shipping += order_amounts(o)["shipping_fee"]
|
||||
for i in claimed:
|
||||
key = str(i.get("order_item_code") or f"{oid}-{i.get('item_no')}")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
status = str(i.get("order_status") or "")
|
||||
qty = int(i.get("quantity") or 0)
|
||||
items.append({
|
||||
"via": label, "order_id": oid, "item_code": key,
|
||||
"channel": str(o.get("order_place_name") or o.get("market_id") or ""),
|
||||
"paid": o.get("paid") == "T", "pay_date": str(o.get("payment_date") or "")[:10],
|
||||
"status": status, "status_text": str(i.get("status_text") or ""),
|
||||
"done": status in CLAIM_DONE,
|
||||
"claim_code": str(i.get("claim_code") or ""),
|
||||
"product_name": str(i.get("product_name") or "")[:40], "quantity": qty,
|
||||
"product_amount": (_won(i.get("product_price")) + _won(i.get("option_price"))) * qty,
|
||||
"payment_amount": _won(i.get("payment_amount")),
|
||||
"coupon": _won(i.get("coupon_discount_price")),
|
||||
"naver_pay_claim_status": str(i.get("naver_pay_claim_status") or ""),
|
||||
"cancel_date": str(i.get("cancel_date") or "")[:16],
|
||||
"refund_date": str(i.get("refund_date") or "")[:16],
|
||||
"return_confirmed_date": str(i.get("return_confirmed_date") or "")[:16],
|
||||
})
|
||||
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일 환불 목록(완료일·접수일)에 그 주문이 있으면
|
||||
제외해 환불 목록 쪽과 두 번 빼지 않는다.
|
||||
카페24 일별 매출 환불합계와 대조한 결과(2026-09): 네이버페이만 센다 — 톡체크아웃(KAKAOPAY)·자체몰의
|
||||
환불 기록 없는 취소는 넣지 않는다(9/16 톡체크아웃 취소 9,900 제외, 9/4 네이버페이 전체취소 배송비 3,500 포함)."""
|
||||
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):
|
||||
if NO_RECORD_CHANNEL not in (_key(o.get("market_id")), _key(o.get("order_place_id"))):
|
||||
continue
|
||||
oid = str(o.get("order_id") or "")
|
||||
its = o.get("items") or []
|
||||
claimed: list[tuple[date, str, dict[str, Any]]] = []
|
||||
for i in its:
|
||||
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 not None:
|
||||
claimed.append((day, str(i.get("order_item_code") or f"{oid}-{i.get('item_no')}"), i))
|
||||
if not claimed:
|
||||
continue
|
||||
all_claimed = len(claimed) == len(its)
|
||||
w = order_amounts(o)
|
||||
ship = max(0, w["shipping_fee"] - w["coupon_shipping_fee_amount"] - w["shipping_fee_discount_amount"])
|
||||
last = max((d, k) for d, k, _ in claimed)
|
||||
for day, key, i in claimed:
|
||||
if not (start <= day <= end):
|
||||
continue
|
||||
status = str(i.get("order_status") or "")
|
||||
qty = int(i.get("quantity") or 0)
|
||||
amount = max(0, (_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")))
|
||||
ship_refund = ship if all_claimed and (day, key) == last else 0
|
||||
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": amount + ship_refund, "shipping_refund": ship_refund,
|
||||
"product_name": str(i.get("product_name") or "")[:40],
|
||||
"naver_pay_claim_status": str(i.get("naver_pay_claim_status") or ""),
|
||||
# 대조용 — 주문 전체가 취소·반품됐는지, 그 주문 배송비
|
||||
"order_all_claimed": all_claimed, "order_shipping_fee": w["shipping_fee"],
|
||||
"item_payment_amount": _won(i.get("payment_amount")),
|
||||
"coupon": _won(i.get("coupon_discount_price")),
|
||||
}
|
||||
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건씩 묶어 조회.
|
||||
못 찾으면 자체몰."""
|
||||
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"), o.get("order_place_id"), o.get("order_place_name"))
|
||||
i += len(group)
|
||||
return out
|
||||
|
||||
# ── 수집(어댑터 공통 흐름) ──────────────────────────────
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
yield from self.paid_orders(ctx, start, end)
|
||||
|
||||
def fetch_refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
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:
|
||||
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)."""
|
||||
if order.get("paid") != "T":
|
||||
return []
|
||||
pay_day = _day(order.get("payment_date"))
|
||||
if pay_day is None:
|
||||
return []
|
||||
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 "")
|
||||
target = target_code(order.get("market_id"), order.get("order_place_id"))
|
||||
return [SaleEvent(
|
||||
marketplace_code=target,
|
||||
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{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, refund: dict[str, Any]) -> list[SaleEvent]:
|
||||
"""환불 → 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 = 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",
|
||||
external_event_id=f"{EVENT_PREFIX}{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")},
|
||||
)]
|
||||
|
||||
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 일별 매출내역과 비교해 규칙을 확정하는 용도.
|
||||
|
||||
groups["self"] = 카페24 열(자체몰 채널 + 알 수 없는 채널), groups["market"] = 다른 쇼핑몰 열로 가는
|
||||
외부 마켓 주문. by_channel = 주문 채널(market_id)별 내역. 개인정보는 담지 않는다.
|
||||
"""
|
||||
self.authenticate(ctx)
|
||||
|
||||
def empty() -> dict[str, int]:
|
||||
return {"orders": 0, "items": 0, "lines": 0, **{k: 0 for k in AMOUNT_FIELDS},
|
||||
"naver_point": 0, "goods_total": 0, "total": 0}
|
||||
|
||||
def channel(mid: Any, place: Any, place_name: Any = None) -> dict[str, Any]:
|
||||
"""(market_id, 주문경로) 한 쌍 = 한 줄. self 안에도 PC쇼핑몰·모바일웹 경로가 섞여 있어 나눠 본다."""
|
||||
mkey = "" if mid is None else str(mid)
|
||||
pname = str(place_name or place or "")
|
||||
kind = channel_kind(mid, place)
|
||||
return by_channel.setdefault((mkey, pname), {
|
||||
"market_id": mkey or "(없음)", "place": pname, "place_id": str(place or ""),
|
||||
"label": SELF_CHANNELS.get(_key(mid), ""), "names": set(),
|
||||
"kind": kind, "target": target_code(mid, place),
|
||||
"orders": 0, "total": 0, "refund_count": 0, "refund_amount": 0,
|
||||
# 기기 — 주문의 order_from_mobile(T=모바일에서 주문). PC 채널(self)에도 모바일 주문이 섞여 있다.
|
||||
"pc_orders": 0, "pc_total": 0, "mobile_orders": 0, "mobile_total": 0,
|
||||
})
|
||||
|
||||
groups = {"self": empty(), "market": empty()}
|
||||
by_channel: dict[str, dict[str, Any]] = {}
|
||||
by_payment: dict[str, dict[str, Any]] = {} # 결제수단 조합별(카페24 열 주문만)
|
||||
unpaid = 0
|
||||
paid_self: dict[str, int] = {} # 그날 결제된 카페24 열 주문 → (결제 당시 − 현재) 금액
|
||||
reduced: dict[str, dict[str, Any]] = {} # 그중 금액이 줄어든 주문(취소·반품) — 환불 기록과 대조
|
||||
# 진단 — 어떤 원본 필드가 카페24 화면 열과 맞는지 찾는 용도(결제 주문 전체, 개인정보 제외)
|
||||
diag = {"order": {}, "initial": {}, "actual": {}, "item": {}}
|
||||
odd: list[dict[str, Any]] = [] # 판매가×수량 합이 주문 상품금액과 다르거나 100원 단위가 아닌 주문
|
||||
for o in self.paid_orders(ctx, day, day):
|
||||
if o.get("paid") != "T":
|
||||
unpaid += 1
|
||||
continue
|
||||
for part, src in (("order", {k: v for k, v in o.items() if not isinstance(v, (dict, list))}),
|
||||
("initial", o.get("initial_order_amount")), ("actual", o.get("actual_order_amount"))):
|
||||
for k, v in money_fields(src).items():
|
||||
diag[part][k] = diag[part].get(k, 0) + v
|
||||
its = o.get("items") or []
|
||||
for i in its:
|
||||
for k, v in money_fields(i).items():
|
||||
diag["item"][k] = diag["item"].get(k, 0) + v
|
||||
gross = sum((_won(i.get("product_price")) + _won(i.get("option_price"))) * int(i.get("quantity") or 0) for i in its)
|
||||
opa = order_amounts(o)["order_price_amount"]
|
||||
if (gross != opa or opa % 100) and len(odd) < 60:
|
||||
odd.append({"order_id": str(o.get("order_id") or ""),
|
||||
"channel": str(o.get("order_place_name") or o.get("market_id") or ""),
|
||||
"order_price_amount": opa, "items_gross": gross, "total": order_total(o),
|
||||
"items": [{"code": str(i.get("order_item_code") or ""), "status": str(i.get("order_status") or ""),
|
||||
"quantity": int(i.get("quantity") or 0),
|
||||
"fields": {k: v for k, v in money_fields(i).items() if v}} for i in its]})
|
||||
ch = channel(o.get("market_id"), o.get("order_place_id"), o.get("order_place_name"))
|
||||
total = order_total(o)
|
||||
ch["orders"] += 1
|
||||
ch["total"] += total
|
||||
dev = "mobile" if str(o.get("order_from_mobile") or "").upper() == "T" else "pc"
|
||||
ch[f"{dev}_orders"] += 1
|
||||
ch[f"{dev}_total"] += total
|
||||
if ch["target"] == "cafe24":
|
||||
names = [str(n) for n in (o.get("payment_method_name") or o.get("payment_method") or []) if n]
|
||||
pkey = " + ".join(names) or "(없음)"
|
||||
pm = by_payment.setdefault(pkey, {"method": pkey, "orders": 0, "total": 0})
|
||||
pm["orders"] += 1
|
||||
pm["total"] += total
|
||||
for n in (o.get("order_place_name"), o.get("order_place_id")):
|
||||
if n:
|
||||
ch["names"].add(str(n))
|
||||
g = groups["self" if ch["target"] == "cafe24" 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["goods_total"] += goods_total(order_amounts(o))
|
||||
g["total"] += order_total(o)
|
||||
if ch["target"] == "cafe24":
|
||||
oid_ = str(o.get("order_id") or "")
|
||||
paid_self[oid_] = order_total(o) - order_total_now(o)
|
||||
if paid_self[oid_] > 0:
|
||||
reduced[oid_] = {
|
||||
"order_id": oid_, "channel": str(o.get("order_place_name") or o.get("market_id") or ""),
|
||||
"payment": " + ".join(str(n) for n in (o.get("payment_method_name") or []) if n),
|
||||
"initial": order_total(o), "now": order_total_now(o), "diff": paid_self[oid_],
|
||||
"statuses": sorted({f"{i.get('order_status') or ''} {i.get('status_text') or ''}".strip()
|
||||
for i in o.get("items") or []}),
|
||||
"naver_pay": sorted({str(i.get("naver_pay_claim_status")) for i in o.get("items") or []
|
||||
if i.get("naver_pay_claim_status")}),
|
||||
"claim_dates": sorted({str(i.get(k))[:10] for i in o.get("items") or []
|
||||
for k in ("cancel_date", "refund_date", "return_confirmed_date")
|
||||
if i.get(k)}),
|
||||
"refunded": 0, "refund_dates": [],
|
||||
}
|
||||
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 = {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)
|
||||
g = refunds["self" if ch["target"] == "cafe24" else "market"]
|
||||
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"] += 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)
|
||||
|
||||
# 환불 기준 비교 — 카페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})
|
||||
],
|
||||
}
|
||||
|
||||
# 환불 건별 목록(완료일 기준 + 접수일 기준, 환불코드로 합침) — 개인정보(이메일·계좌) 제외
|
||||
extra = markets | self.market_ids(ctx, [a for a in accepted if str(a.get("order_id")) not in markets])
|
||||
refund_list: dict[str, dict[str, Any]] = {}
|
||||
for basis, items in (("completed", rows), ("accepted", accepted)):
|
||||
for x in items:
|
||||
code = str(x.get("refund_code") or "")
|
||||
mid, place, place_name = extra.get(str(x.get("order_id")), ("self", None, None))
|
||||
e = refund_list.setdefault(code, {
|
||||
"refund_code": code, "order_id": str(x.get("order_id") or ""),
|
||||
"channel": str(place_name or mid or ""), "status": str(x.get("status") or ""),
|
||||
"accepted_date": str(x.get("accepted_refund_date") or "")[:16].replace("T", " "),
|
||||
"refund_date": str(x.get("refund_date") or "")[:16].replace("T", " "),
|
||||
"quantity": int(x.get("quantity") or 0),
|
||||
"actual_refund_amount": _won(x.get("actual_refund_amount")),
|
||||
"used_points": _won(x.get("used_points")), "used_credits": _won(x.get("used_credits")),
|
||||
"cancel_fee_amount": _won(x.get("cancel_fee_amount")),
|
||||
"methods": [str(m) for m in (x.get("refund_methods") or []) if m],
|
||||
"in_completed": False, "in_accepted": False,
|
||||
})
|
||||
e["in_" + basis] = True
|
||||
|
||||
claims = self.claim_items(ctx, day)
|
||||
refunded_orders = {r["order_id"] for r in refund_list.values()}
|
||||
for c in claims["items"]:
|
||||
c["has_refund"] = c["order_id"] in refunded_orders
|
||||
|
||||
def csum(pred) -> dict[str, int]:
|
||||
sel = [c for c in claims["items"] if c["done"] and pred(c)]
|
||||
return {"count": len(sel), "payment_amount": sum(c["payment_amount"] for c in sel),
|
||||
"product_amount": sum(c["product_amount"] for c in sel)}
|
||||
|
||||
# 결제일 기준 — 그날 결제된 주문이 그 뒤(오늘까지) 환불된 금액. 카페24 일별 매출이 환불을 원 주문 결제일에
|
||||
# 빼는지 확인하는 용도(최근일만 맞고 지난 날일수록 차이가 커지는 현상).
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
later = [x for x in self.refunds(ctx, day, max(day, today_kst()))
|
||||
if str(x.get("order_id") or "") in paid_self and str(x.get("status") or "T") == "T"]
|
||||
by_pay = rsum(later)
|
||||
by_pay["amount_diff"] = sum(v for v in paid_self.values() if v > 0)
|
||||
by_pay["refund_dates"] = sorted({str(x.get("refund_date") or "")[:10] for x in later})
|
||||
refund_basis["by_pay_date"] = by_pay
|
||||
for x in later:
|
||||
r_ = reduced.get(str(x.get("order_id") or ""))
|
||||
if r_ is not None:
|
||||
r_["refunded"] += _won(x.get("actual_refund_amount")) + _won(x.get("used_points")) + _won(x.get("used_credits"))
|
||||
r_["refund_dates"] = sorted({*r_["refund_dates"], str(x.get("refund_date") or "")[:10]})
|
||||
|
||||
comp = refund_basis["completed"]
|
||||
no_refund = csum(lambda c: not c["has_refund"])
|
||||
claimed = csum(lambda c: True)
|
||||
# 카페24 "환불합계" 후보 — 화면 값과 같은 줄을 찾는다(화면에서 값을 입력하면 강조)
|
||||
candidates = [
|
||||
{"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"]},
|
||||
{"key": "pay_date_pts", "label": "결제일 기준 · 그날 결제 주문의 환불(오늘까지) · 실제 + 적립금·예치금",
|
||||
"amount": by_pay["with_points"]},
|
||||
{"key": "pay_date_diff", "label": "결제일 기준 · 그날 결제 주문의 (결제 당시 금액 − 현재 금액)",
|
||||
"amount": by_pay["amount_diff"]},
|
||||
{"key": "accepted", "label": "환불접수일(전체 상태) · 실제 환불액", "amount": refund_basis["accepted_all"]["actual_refund_amount"]},
|
||||
{"key": "accepted_pts", "label": "환불접수일(전체 상태) · 실제 + 적립금·예치금", "amount": refund_basis["accepted_all"]["with_points"]},
|
||||
{"key": "claim_pay", "label": "취소·반품·교환 완료 품목 · 품목 결제금액", "amount": claimed["payment_amount"]},
|
||||
{"key": "claim_prod", "label": "취소·반품·교환 완료 품목 · 판매가(+옵션)×수량", "amount": claimed["product_amount"]},
|
||||
{"key": "claim_pay_ship", "label": "완료 품목 결제금액 + 전체취소 주문 배송비",
|
||||
"amount": claimed["payment_amount"] + claims["full_cancel_shipping"]},
|
||||
{"key": "completed_plus_noref", "label": "환불완료 실제 환불액 + 환불 기록 없는 완료 품목 결제금액",
|
||||
"amount": comp["actual_refund_amount"] + no_refund["payment_amount"]},
|
||||
{"key": "completed_pts_plus_noref", "label": "환불완료 (실제+적립금) + 환불 기록 없는 완료 품목 결제금액",
|
||||
"amount": comp["with_points"] + no_refund["payment_amount"]},
|
||||
]
|
||||
return {"date": day.isoformat(), "orders": groups, "refunds": refunds, "unpaid_orders": unpaid,
|
||||
"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),
|
||||
"diag": {part: dict(sorted(v.items())) for part, v in diag.items()}, "odd_orders": odd,
|
||||
"formula": "결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트(결제 당시). 참고식 = 상품구매금액 + 배송비 − 할인("
|
||||
+ ", ".join(DISCOUNT_FIELDS) + ") − 쿠폰(" + ", ".join(COUPON_FIELDS) + ")"}
|
||||
@@ -0,0 +1,112 @@
|
||||
"""쿠팡 — 쿠팡 윙(마켓플레이스) 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
|
||||
|
||||
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):
|
||||
code = "coupang"
|
||||
name = "쿠팡"
|
||||
auth_type = "api_key"
|
||||
docs_url = "https://developers.coupangcorp.com/"
|
||||
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
|
||||
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
|
||||
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("vendor_id", "Vendor ID(업체코드)", placeholder="A00012345"),
|
||||
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 '없음'}). "
|
||||
"매출 수집은 다음 단계에서 구현됩니다.")
|
||||
@@ -0,0 +1,320 @@
|
||||
"""11번가 — 11번가 셀러 오픈API.
|
||||
|
||||
인증: 셀러오피스(openapi.11st.co.kr → 서비스등록·확인)에서 발급한 Open API Key 를 요청 헤더 `openapikey` 에 넣는다.
|
||||
셀러 API 는 등록한 IP 에서만 호출된다("Seller API 정보 수정"에서 서버 IP 등록, 셀링툴(사방넷 등)과 함께 쓸 수 있음).
|
||||
(공식 이용방법 openapi.11st.co.kr → OpenApiOperationGuide SERVICE_METHOD, 2026-09-30 확인)
|
||||
응답은 XML(euc-kr). 없는 주소는 500 + resultCode -997 "등록된 API 정보가 존재하지 않습니다", 건이 없으면 -1 "해당 건이 없습니다".
|
||||
|
||||
매출(2026-09-30 실데이터·셀러오피스 "판매 상세내역"으로 확정):
|
||||
- SALE = 주문 하나(`11st:{ordNo}`), 날짜 = 결제일.
|
||||
- 정산된 주문: 정산 내역(/rest/settlement/settlementList/{yyyyMMdd}/{yyyyMMdd}, 정산확정일 stlDy 기준)의
|
||||
판매금액합계(selPrcAmt) 합 — 판매 상세내역과 같고 배송비(도서산간 등)가 별도 줄로 들어 있다.
|
||||
예: 9/10 주문 = 83,800 + 배송비 줄 3,000 = 86,800 (주문 목록의 dlvCst 는 0 이라 주문 목록만으로는 모자람).
|
||||
- 정산 전 주문: 주문 상태 목록 4개(결제완료·발송대기·배송중·배송완료 — 지금 그 상태인 주문만, 배송완료에 구매확정 주문도
|
||||
남음)의 ordAmt(판매금액, 11번가 부담 쿠폰 전) + 배송비(dlvCst 최댓값 한 번). 정산되면 다음 업데이트 때 정산 값으로 바뀐다.
|
||||
- ordAmt − ordPayAmt = 11번가 부담 할인(= 정산 cupnAmt/tmallApplyDscAmt). 수수료는 판매금액 기준(34,900 × 13% = 4,537).
|
||||
- 취소·반품된 주문은 목록에서 빠진다 → 기간을 통째로 다시 받아(replace_range) 매출에서 빠진다(취소 사건을 따로 만들지 않음).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import date, timedelta
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
AdapterError,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
CredentialField,
|
||||
MarketplaceAdapter,
|
||||
SaleEvent,
|
||||
)
|
||||
|
||||
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]:
|
||||
"""(결과코드, 결과문구, 주문 수). 네임스페이스와 무관하게 태그 끝 이름으로 찾는다. XML 이 아니면 코드 "not-xml"."""
|
||||
try:
|
||||
root = ET.fromstring(_xml_text(content))
|
||||
except ET.ParseError:
|
||||
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():
|
||||
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
|
||||
|
||||
|
||||
# 원본 데이터 확인용 후보 주소 — {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}"),
|
||||
("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",
|
||||
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())
|
||||
|
||||
|
||||
# 매출 수집 — 주문 상태 목록 4개(지금 그 상태인 주문만 준다). 배송완료 목록에는 구매확정된 주문도 남는다(실데이터 확인).
|
||||
# 취소·반품된 주문은 이 목록들에서 빠진다 → 기간을 통째로 다시 받아(replace_range) 매출에서 자연히 빠지게 한다.
|
||||
ORDER_PATHS = ("/rest/ordservices/complete/{s}/{e}", "/rest/ordservices/packaging/{s}/{e}",
|
||||
"/rest/ordservices/shipping/{s}/{e}", "/rest/ordservices/completed/{s}/{e}")
|
||||
ORDER_STATUS = {"complete": "결제완료", "packaging": "발송대기", "shipping": "배송중", "completed": "배송완료"}
|
||||
# 목록의 날짜 조건이 주문일인지 상태 변경일(배송완료일 등)인지 문서로 확인 못 해, 기간 뒤로 넉넉히 더 불러
|
||||
# 주문일로 거른다(나중에 배송완료된 주문도 빠지지 않게).
|
||||
LOOKAHEAD_DAYS = 30
|
||||
SETTLE_LOOKAHEAD_DAYS = 45 # 결제 → 정산확정(구매확정)까지 보통 1~3주
|
||||
SETTLEMENT_PATH = "/rest/settlement/settlementList/{ds}/{de}"
|
||||
EVENT_PREFIX = "11st:"
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
try:
|
||||
return int(round(float(str(value or "0").replace(",", ""))))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def _day(value: Any) -> date | None:
|
||||
""""2026-09-09 15:13:16" / "2026/09/09" / "20260909" → date."""
|
||||
s = re.sub(r"[^0-9]", "", str(value or ""))[:8]
|
||||
if len(s) < 8:
|
||||
return None
|
||||
try:
|
||||
return date(int(s[:4]), int(s[4:6]), int(s[6:8]))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class ElevenstAdapter(MarketplaceAdapter):
|
||||
code = "elevenst"
|
||||
name = "11번가"
|
||||
auth_type = "api_key"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
docs_url = "https://openapi.11st.co.kr/"
|
||||
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 _pages(self, ctx: AdapterContext, tmpl: str, lo: date, hi: date) -> Iterable[dict[str, str]]:
|
||||
"""[lo, hi] 를 7일씩 나눠 한 주소를 부른다."""
|
||||
s = lo
|
||||
while s <= hi:
|
||||
e = min(hi, s + timedelta(days=PROBE_CHUNK_DAYS - 1))
|
||||
ds, de = s.strftime("%Y%m%d"), e.strftime("%Y%m%d")
|
||||
yield from xml_records(self._get(ctx, tmpl.format(s=f"{ds}0000", e=f"{de}2359", ds=ds, de=de)))
|
||||
s = e + timedelta(days=1)
|
||||
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
"""결제일이 [start, end] 인 주문을 주문 단위로 합쳐 돌려준다.
|
||||
1) 정산 내역 — 정산확정일 기준이라 [start, end+45일(오늘까지)] 를 불러 결제일(ordStlEndDt)로 거른다.
|
||||
판매금액합계(selPrcAmt)는 셀러오피스 "판매 상세내역"과 같고 배송비 줄(도서산간 등)도 따로 들어 있다.
|
||||
2) 아직 정산 전인 주문 — 주문 상태 목록 4개([start, end+30일]) 의 ordAmt + 배송비(dlvCst 최댓값 한 번).
|
||||
같은 주문이 정산에 있으면 정산 값을 쓴다(정산되면 다음 업데이트 때 정산 값으로 바뀜)."""
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
today = today_kst()
|
||||
orders: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def acc(oid: str, src: str, day: date) -> dict[str, Any]:
|
||||
return orders.setdefault(oid, {"ordNo": oid, "_src": src, "_day": day, "amount": 0, "qty": 0,
|
||||
"discount": 0, "ship": 0, "names": [], "opt": "", "raw": {}})
|
||||
|
||||
settle_hi = max(end, min(end + timedelta(days=SETTLE_LOOKAHEAD_DAYS), today))
|
||||
for r in self._pages(ctx, SETTLEMENT_PATH, start, settle_hi):
|
||||
oid, day = str(r.get("ordNo") or ""), _day(r.get("ordStlEndDt"))
|
||||
if not oid or day is None or not (start <= day <= end):
|
||||
continue
|
||||
o = acc(oid, "settlement", day)
|
||||
o["amount"] += _won(r.get("selPrcAmt"))
|
||||
o["qty"] += _won(r.get("ordQty"))
|
||||
o["discount"] += _won(r.get("cupnAmt"))
|
||||
if r.get("prdNm") and r["prdNm"] not in o["names"]:
|
||||
o["names"].append(r["prdNm"])
|
||||
o["opt"] = o["opt"] or str(r.get("slctPrdOptNm") or "")
|
||||
for k in ("stlAmt", "selFee", "deductAmt", "bmStlDlvCst"):
|
||||
o["raw"][k] = o["raw"].get(k, 0) + _won(r.get(k))
|
||||
o["raw"]["stlDy"] = r.get("stlDy")
|
||||
settled = set(orders)
|
||||
|
||||
hi = max(end, min(end + timedelta(days=LOOKAHEAD_DAYS), today))
|
||||
seen: set[str] = set()
|
||||
for tmpl in ORDER_PATHS:
|
||||
status = ORDER_STATUS[tmpl.split("/")[3]]
|
||||
for r in self._pages(ctx, tmpl, start, hi):
|
||||
oid = str(r.get("ordNo") or "")
|
||||
key = f"{oid}-{r.get('ordPrdSeq')}"
|
||||
day = _day(r.get("ordStlEndDt") or r.get("ordDt"))
|
||||
if not oid or oid in settled or key in seen or day is None or not (start <= day <= end):
|
||||
continue
|
||||
seen.add(key)
|
||||
o = acc(oid, status, day)
|
||||
o["amount"] += _won(r.get("ordAmt"))
|
||||
o["ship"] = max(o["ship"], _won(r.get("dlvCst")))
|
||||
o["qty"] += _won(r.get("ordQty"))
|
||||
o["discount"] += max(0, _won(r.get("ordAmt")) - _won(r.get("ordPayAmt")))
|
||||
if r.get("prdNm") and r["prdNm"] not in o["names"]:
|
||||
o["names"].append(r["prdNm"])
|
||||
o["opt"] = o["opt"] or str(r.get("slctPrdOptNm") or "")
|
||||
o["raw"]["ordDt"] = r.get("ordDt")
|
||||
for o in orders.values():
|
||||
o["amount"] += o.pop("ship")
|
||||
yield o
|
||||
|
||||
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
|
||||
"""주문 하나 → SALE(결제일). 금액 = 정산 판매금액합계(정산 전이면 ordAmt + 배송비) — 11번가 부담 쿠폰 전 금액.
|
||||
수수료가 판매금액 기준이라(34,900 × 13% = 4,537, 정산 실데이터) 판매자 매출은 할인 전 금액으로 본다."""
|
||||
oid, day = str(o.get("ordNo") or ""), o.get("_day")
|
||||
if not oid or day is None:
|
||||
return []
|
||||
names = o.get("names") or []
|
||||
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
|
||||
return [SaleEvent(
|
||||
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}", external_order_id=oid,
|
||||
payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)),
|
||||
product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0),
|
||||
discount_amount=max(0, int(o.get("discount") or 0)),
|
||||
order_status="정산확정" if o.get("_src") == "settlement" else str(o.get("_src") or ""),
|
||||
raw={"source": o.get("_src"), **(o.get("raw") or {})},
|
||||
)]
|
||||
|
||||
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 == "not-xml":
|
||||
raise ApiError(f"11번가가 예상하지 못한 응답을 돌려줬습니다(XML 아님): {res.text[:120].strip()}")
|
||||
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, to: date | None = None) -> dict[str, Any]:
|
||||
"""후보 조회 주소마다 기간(day~to, 최대 31일, 7일씩 나눠)을 실제로 불러 동작 여부·줄 수·항목별 합계를 돌려준다.
|
||||
셀러 API 상세 문서가 로그인 뒤에만 있어, 어느 주소·항목이 셀러오피스 화면 매출과 맞는지 실데이터로 확정하는 용도.
|
||||
개인정보 항목(이름·연락처·주소·아이디 등)은 값 없이 이름만."""
|
||||
self.authenticate(ctx)
|
||||
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:
|
||||
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
|
||||
|
||||
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}건)."
|
||||
@@ -0,0 +1,23 @@
|
||||
"""G마켓 — ESM(ESM Plus / ESM Trading API).
|
||||
|
||||
인증: ESM 마스터 ID + 판매자 ID + 발급 Secret Key 로 JWT 서명(연동 단계에서 확정).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
|
||||
|
||||
class GmarketAdapter(MarketplaceAdapter):
|
||||
code = "gmarket"
|
||||
name = "G마켓"
|
||||
auth_type = "api_key"
|
||||
docs_url = "https://etapi.gmarket.com/"
|
||||
note = "ESM Plus 에서 발급한 API 인증정보를 입력합니다."
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("master_id", "ESM 마스터 ID"),
|
||||
CredentialField("seller_id", "G마켓 판매자 ID"),
|
||||
CredentialField("secret_key", "Secret Key", secret=True),
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""GS샵 — 협력사 API.
|
||||
|
||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
|
||||
|
||||
class GsshopAdapter(MarketplaceAdapter):
|
||||
code = "gsshop"
|
||||
name = "GS샵"
|
||||
auth_type = "api_key"
|
||||
note = "입력 항목은 연동 단계에서 GS샵 협력사 API 문서로 확정합니다."
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("vendor_code", "협력사 코드"),
|
||||
CredentialField("api_key", "API Key", secret=True),
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""카카오 — 카카오쇼핑(톡스토어) 판매자 API.
|
||||
|
||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
|
||||
|
||||
class KakaoAdapter(MarketplaceAdapter):
|
||||
code = "kakao"
|
||||
name = "카카오"
|
||||
auth_type = "api_key"
|
||||
note = "입력 항목은 연동 단계에서 카카오쇼핑 판매자 API 문서로 확정합니다."
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("seller_id", "판매자(채널) ID"),
|
||||
CredentialField("api_key", "API Key", secret=True),
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""롯데ON — 롯데ON 판매자 API.
|
||||
|
||||
인증: 거래처번호 + 발급 API Key(연동 단계에서 확정).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
|
||||
|
||||
class LotteonAdapter(MarketplaceAdapter):
|
||||
code = "lotteon"
|
||||
name = "롯데ON"
|
||||
auth_type = "api_key"
|
||||
note = "롯데ON 스토어센터에서 발급한 API 인증정보를 입력합니다."
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("trade_no", "거래처번호"),
|
||||
CredentialField("api_key", "API Key", secret=True),
|
||||
]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""테스트(모의) 매출 데이터 — 실제 API 연동 전 화면 확인용.
|
||||
|
||||
같은 (쇼핑몰, 날짜)면 항상 같은 값이 나온다(재현 가능). 결제뿐 아니라 전체 취소·
|
||||
부분 반품도 섞어 넣어 음수 반영과 합계를 확인할 수 있게 한다.
|
||||
DB 에는 is_sample=TRUE 로 들어가며 설정 화면에서 한 번에 지울 수 있다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from datetime import date, timedelta
|
||||
|
||||
from .base import SaleEvent
|
||||
|
||||
# 쇼핑몰별 하루 평균 주문 건수(모의값) — 화면에 차이가 보이도록만 다르게 둔다.
|
||||
_DAILY_ORDERS = {
|
||||
"cafe24": 9, "naver": 14, "coupang": 18, "ohouse": 4, "gmarket": 6,
|
||||
"kakao": 3, "gsshop": 2, "elevenst": 4, "lotteon": 2, "toss": 1,
|
||||
}
|
||||
_PRODUCTS = (
|
||||
("스테인리스 냄비 20cm", 39_000), ("프라이팬 28cm", 45_900), ("밀폐용기 5종 세트", 29_800),
|
||||
("도마 대형", 19_900), ("칼 블록 세트", 89_000), ("주방 가위", 12_900),
|
||||
("냄비 받침", 8_900), ("전골 냄비", 59_000),
|
||||
)
|
||||
|
||||
|
||||
def generate(code: str, start: date, end: date) -> list[SaleEvent]:
|
||||
events: list[SaleEvent] = []
|
||||
base = _DAILY_ORDERS.get(code, 3)
|
||||
d = start
|
||||
while d <= end:
|
||||
rng = random.Random(f"perf-sample:{code}:{d.isoformat()}")
|
||||
weekend = d.weekday() >= 5
|
||||
n = max(0, int(rng.gauss(base * (0.7 if weekend else 1.0), base * 0.35)))
|
||||
for i in range(n):
|
||||
name, price = rng.choice(_PRODUCTS)
|
||||
qty = 1 if rng.random() < 0.8 else rng.randint(2, 3)
|
||||
discount = rng.choice((0, 0, 0, 1000, 2000, 3000))
|
||||
amount = max(0, price * qty - discount)
|
||||
order_id = f"SAMPLE-{code}-{d:%Y%m%d}-{i:03d}"
|
||||
events.append(SaleEvent(
|
||||
event_type="SALE", external_event_id=f"{order_id}-S", external_order_id=order_id,
|
||||
external_line_id="1", order_date=d, payment_date=d, event_date=d, amount=amount,
|
||||
product_name=name, quantity=qty, discount_amount=discount, order_status="결제완료",
|
||||
raw={"sample": True},
|
||||
))
|
||||
roll = rng.random()
|
||||
if roll < 0.05: # 전체 취소(당일~2일 뒤)
|
||||
cd = min(end, d + timedelta(days=rng.randint(0, 2)))
|
||||
events.append(SaleEvent(
|
||||
event_type="CANCEL", external_event_id=f"{order_id}-C", external_order_id=order_id,
|
||||
external_line_id="1", order_date=d, payment_date=d, event_date=cd, amount=-amount,
|
||||
product_name=name, quantity=-qty, order_status="취소완료", raw={"sample": True},
|
||||
))
|
||||
elif roll < 0.08 and qty > 1: # 부분 반품(1개, 3~7일 뒤)
|
||||
rd = min(end, d + timedelta(days=rng.randint(3, 7)))
|
||||
events.append(SaleEvent(
|
||||
event_type="RETURN", external_event_id=f"{order_id}-R", external_order_id=order_id,
|
||||
external_line_id="1", order_date=d, payment_date=d, event_date=rd, amount=-price,
|
||||
product_name=name, quantity=-1, order_status="반품완료", raw={"sample": True},
|
||||
))
|
||||
d += timedelta(days=1)
|
||||
return events
|
||||
@@ -0,0 +1,27 @@
|
||||
"""네이버 스마트스토어 — 네이버 커머스API.
|
||||
|
||||
인증: 애플리케이션 ID + 시크릿으로 전자서명(bcrypt) → OAuth2 client_credentials 토큰.
|
||||
토큰은 발급받아 암호화 저장하고 만료 시 재발급한다(다음 단계에서 구현).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
|
||||
|
||||
class NaverAdapter(MarketplaceAdapter):
|
||||
code = "naver"
|
||||
name = "네이버 스마트스토어"
|
||||
auth_type = "oauth"
|
||||
docs_url = "https://apicenter.commerce.naver.com/"
|
||||
note = "커머스API센터에서 발급한 애플리케이션 ID/시크릿을 입력합니다."
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("client_id", "애플리케이션 ID(Client ID)"),
|
||||
CredentialField("client_secret", "애플리케이션 시크릿(Client Secret)", secret=True),
|
||||
CredentialField("account_id", "판매자 ID", required=False,
|
||||
help="판매자 계정 지정이 필요한 경우에만 입력"),
|
||||
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
||||
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
"""오늘의집 — 파트너(판매자) API.
|
||||
|
||||
인증 방식·필드는 연동 단계에서 오늘의집 파트너 API 문서로 확정한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
|
||||
|
||||
class OhouseAdapter(MarketplaceAdapter):
|
||||
code = "ohouse"
|
||||
name = "오늘의집"
|
||||
auth_type = "api_key"
|
||||
note = "입력 항목은 연동 단계에서 오늘의집 파트너 API 문서로 확정합니다."
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("seller_id", "판매자 ID"),
|
||||
CredentialField("api_key", "API Key", secret=True),
|
||||
CredentialField("api_secret", "API Secret", secret=True, required=False),
|
||||
]
|
||||
@@ -0,0 +1,41 @@
|
||||
"""쇼핑몰 어댑터 목록 — 새 쇼핑몰은 여기 한 줄 + 어댑터 파일 하나.
|
||||
|
||||
DB(perf_marketplaces)에 행이 없으면 설정 화면에서 쓸 수 없으므로, 새 쇼핑몰을
|
||||
추가할 때는 scripts/sql 의 seed(INSERT … ON CONFLICT DO NOTHING)에도 한 줄 넣는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import MarketplaceAdapter
|
||||
from .cafe24 import Cafe24Adapter
|
||||
from .coupang import CoupangAdapter
|
||||
from .elevenst import ElevenstAdapter
|
||||
from .gmarket import GmarketAdapter
|
||||
from .gsshop import GsshopAdapter
|
||||
from .kakao import KakaoAdapter
|
||||
from .lotteon import LotteonAdapter
|
||||
from .naver import NaverAdapter
|
||||
from .ohouse import OhouseAdapter
|
||||
from .toss import TossAdapter
|
||||
|
||||
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
||||
Cafe24Adapter(),
|
||||
NaverAdapter(),
|
||||
CoupangAdapter(),
|
||||
OhouseAdapter(),
|
||||
GmarketAdapter(),
|
||||
KakaoAdapter(),
|
||||
GsshopAdapter(),
|
||||
ElevenstAdapter(),
|
||||
LotteonAdapter(),
|
||||
TossAdapter(),
|
||||
)
|
||||
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
||||
|
||||
|
||||
def all_adapters() -> tuple[MarketplaceAdapter, ...]:
|
||||
return _ADAPTERS
|
||||
|
||||
|
||||
def get_adapter(code: str) -> MarketplaceAdapter | None:
|
||||
return _BY_CODE.get(code)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""토스쇼핑 — 판매자 API.
|
||||
|
||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import CredentialField, MarketplaceAdapter
|
||||
|
||||
|
||||
class TossAdapter(MarketplaceAdapter):
|
||||
code = "toss"
|
||||
name = "토스쇼핑"
|
||||
auth_type = "api_key"
|
||||
note = "입력 항목은 연동 단계에서 토스쇼핑 판매자 API 문서로 확정합니다."
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("seller_id", "판매자 ID"),
|
||||
CredentialField("api_key", "API Key", secret=True),
|
||||
CredentialField("api_secret", "API Secret", secret=True, required=False),
|
||||
]
|
||||
@@ -0,0 +1,306 @@
|
||||
"""③ 매출 계산 — 기간/주 계산, 수수료·반올림, 표·KPI 집계. DB·HTTP 와 무관한 순수 함수.
|
||||
|
||||
금액 규칙
|
||||
- 모든 금액은 원 단위 정수(int). 부동소수점을 쓰지 않는다(수수료율만 Decimal).
|
||||
- 수수료 = round_half_up(해당 일 쇼핑몰 매출 합계 × 그날 유효한 수수료율 / 100).
|
||||
반올림은 `commission()` 한 곳에서만 한다. 취소/반품(음수)도 같은 규칙(0 에서 먼 쪽).
|
||||
- 수수료 차감 매출 = 총매출 − 수수료.
|
||||
- 수수료율은 이력(적용 시작일)으로 관리한다. 어떤 날의 요율 = 그날 이전(포함) 가장 최근
|
||||
적용 시작일의 요율. 첫 요율보다 이전 날짜는 0%.
|
||||
|
||||
주 = 월요일 ~ 일요일.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Iterable, Mapping, Sequence
|
||||
|
||||
WEEKDAYS_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
PERIOD_KINDS = ("day", "week", "month", "year", "custom")
|
||||
MAX_CUSTOM_DAYS = 366
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 금액
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def commission(amount: int, rate_percent: Decimal) -> int:
|
||||
"""수수료(원). 반올림 기준은 이 함수 한 곳 — ROUND_HALF_UP(0.5 는 0 에서 먼 쪽)."""
|
||||
if not amount or not rate_percent:
|
||||
return 0
|
||||
value = Decimal(int(amount)) * Decimal(rate_percent) / Decimal(100)
|
||||
return int(value.quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Money:
|
||||
gross: int = 0
|
||||
commission: int = 0
|
||||
|
||||
@property
|
||||
def net(self) -> int:
|
||||
return self.gross - self.commission
|
||||
|
||||
def add(self, other: "Money") -> "Money":
|
||||
self.gross += other.gross
|
||||
self.commission += other.commission
|
||||
return self
|
||||
|
||||
def as_dict(self) -> dict[str, int]:
|
||||
return {"gross": self.gross, "commission": self.commission, "net": self.net}
|
||||
|
||||
|
||||
def total(items: Iterable[Money]) -> Money:
|
||||
out = Money()
|
||||
for m in items:
|
||||
out.add(m)
|
||||
return out
|
||||
|
||||
|
||||
RateTable = Mapping[str, Sequence[tuple[date, Decimal]]] # 쇼핑몰 → [(적용 시작일, 요율%)] 오름차순
|
||||
|
||||
|
||||
def rate_on(rates: RateTable, code: str, d: date) -> Decimal:
|
||||
current = Decimal(0)
|
||||
for eff, rate in rates.get(code, ()):
|
||||
if eff <= d:
|
||||
current = Decimal(rate)
|
||||
else:
|
||||
break
|
||||
return current
|
||||
|
||||
|
||||
def build_cells(daily_amounts: Mapping[tuple[date, str], int], rates: RateTable) -> dict[tuple[date, str], Money]:
|
||||
"""(날짜, 쇼핑몰) → 그날 매출 합계로 Money 를 만든다(수수료는 그날 요율)."""
|
||||
return {
|
||||
(d, code): Money(gross=int(amt), commission=commission(int(amt), rate_on(rates, code, d)))
|
||||
for (d, code), amt in daily_amounts.items()
|
||||
}
|
||||
|
||||
|
||||
def pct_change(current: int, previous: int) -> float | None:
|
||||
"""증감률(%). 비교 대상이 0 이하이면 의미 없는 값 대신 None."""
|
||||
if previous <= 0:
|
||||
return None
|
||||
return round((current - previous) / previous * 100, 1)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 기간
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def week_start(d: date) -> date:
|
||||
return d - timedelta(days=d.weekday())
|
||||
|
||||
|
||||
def month_end(d: date) -> date:
|
||||
return d.replace(day=calendar.monthrange(d.year, d.month)[1])
|
||||
|
||||
|
||||
def _add_months(d: date, n: int) -> date:
|
||||
y, m = divmod(d.month - 1 + n, 12)
|
||||
year, month = d.year + y, m + 1
|
||||
return date(year, month, min(d.day, calendar.monthrange(year, month)[1]))
|
||||
|
||||
|
||||
def fmt_md(d: date) -> str:
|
||||
return f"{d.month}/{d.day}"
|
||||
|
||||
|
||||
def day_label(d: date) -> str:
|
||||
"""일자별 표 날짜 — mm/dd(요일), 예: 09/01(화)."""
|
||||
return f"{d.month:02d}/{d.day:02d}({WEEKDAYS_KO[d.weekday()]})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Period:
|
||||
kind: str
|
||||
anchor: date
|
||||
start: date
|
||||
end: date
|
||||
label: str
|
||||
prev_anchor: date
|
||||
next_anchor: date
|
||||
prev_label: str
|
||||
next_label: str
|
||||
|
||||
@property
|
||||
def days(self) -> int:
|
||||
return (self.end - self.start).days + 1
|
||||
|
||||
def compare_range(self, today: date) -> tuple[date, date, str]:
|
||||
"""직전 같은 길이 기간. 진행 중인 기간이면 같은 경과일수까지만(공정한 비교)."""
|
||||
length = self.days
|
||||
prev_start = self.start - timedelta(days=length)
|
||||
if self.kind == "month":
|
||||
prev_start = _add_months(self.start, -1)
|
||||
elif self.kind == "year":
|
||||
prev_start = self.start.replace(year=self.start.year - 1)
|
||||
in_progress = self.start <= today < self.end
|
||||
if in_progress:
|
||||
elapsed = (today - self.start).days
|
||||
prev_end = prev_start + timedelta(days=elapsed)
|
||||
if self.kind == "month":
|
||||
prev_end = min(prev_end, month_end(prev_start))
|
||||
note = "같은 기간"
|
||||
else:
|
||||
if self.kind == "month":
|
||||
prev_end = month_end(prev_start)
|
||||
elif self.kind == "year":
|
||||
prev_end = prev_start.replace(month=12, day=31)
|
||||
else:
|
||||
prev_end = self.start - timedelta(days=1)
|
||||
note = ""
|
||||
unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간")
|
||||
return prev_start, prev_end, f"{unit} {note}".strip()
|
||||
|
||||
|
||||
def resolve_period(
|
||||
kind: str,
|
||||
anchor: date,
|
||||
*,
|
||||
custom_from: date | None = None,
|
||||
custom_to: date | None = None,
|
||||
) -> Period:
|
||||
kind = kind if kind in PERIOD_KINDS else "week"
|
||||
if kind == "day":
|
||||
return Period(kind, anchor, anchor, anchor,
|
||||
f"{anchor.year}년 {anchor.month}월 {anchor.day}일 ({WEEKDAYS_KO[anchor.weekday()]})",
|
||||
anchor - timedelta(days=1), anchor + timedelta(days=1), "전일", "다음날")
|
||||
if kind == "week":
|
||||
s = week_start(anchor)
|
||||
e = s + timedelta(days=6)
|
||||
label = (f"{s.year}년 {s.month}월 {s.day}일 ~ "
|
||||
+ (f"{e.year}년 " if e.year != s.year else "") + f"{e.month}월 {e.day}일")
|
||||
return Period(kind, anchor, s, e, label, s - timedelta(days=7), s + timedelta(days=7), "이전주", "다음주")
|
||||
if kind == "month":
|
||||
s = anchor.replace(day=1)
|
||||
return Period(kind, anchor, s, month_end(s), f"{s.year}년 {s.month}월",
|
||||
_add_months(s, -1), _add_months(s, 1), "이전달", "다음달")
|
||||
if kind == "year":
|
||||
s = date(anchor.year, 1, 1)
|
||||
return Period(kind, anchor, s, date(anchor.year, 12, 31), f"{anchor.year}년",
|
||||
date(anchor.year - 1, 1, 1), date(anchor.year + 1, 1, 1), "이전해", "다음해")
|
||||
# custom
|
||||
s = custom_from or anchor
|
||||
e = custom_to or s
|
||||
if e < s:
|
||||
s, e = e, s
|
||||
if (e - s).days + 1 > MAX_CUSTOM_DAYS:
|
||||
e = s + timedelta(days=MAX_CUSTOM_DAYS - 1)
|
||||
length = (e - s).days + 1
|
||||
return Period("custom", s, s, e, f"{s.isoformat()} ~ {e.isoformat()}",
|
||||
s - timedelta(days=length), e + timedelta(days=1), "이전", "다음")
|
||||
|
||||
|
||||
def daterange(start: date, end: date) -> Iterable[date]:
|
||||
d = start
|
||||
while d <= end:
|
||||
yield d
|
||||
d += timedelta(days=1)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 집계
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def sum_range(cells: Mapping[tuple[date, str], Money], codes: Sequence[str], start: date, end: date) -> Money:
|
||||
wanted = set(codes)
|
||||
out = Money()
|
||||
for (d, code), m in cells.items():
|
||||
if code in wanted and start <= d <= end:
|
||||
out.add(m)
|
||||
return out
|
||||
|
||||
|
||||
def by_code(cells: Mapping[tuple[date, str], Money], codes: Sequence[str], start: date, end: date) -> dict[str, Money]:
|
||||
out = {c: Money() for c in codes}
|
||||
for (d, code), m in cells.items():
|
||||
if code in out and start <= d <= end:
|
||||
out[code].add(m)
|
||||
return out
|
||||
|
||||
|
||||
def _row(kind: str, label: str, per_code: dict[str, Money], **extra) -> dict:
|
||||
return {
|
||||
"kind": kind,
|
||||
"label": label,
|
||||
"cells": {c: m.as_dict() for c, m in per_code.items()},
|
||||
"total": total(per_code.values()).as_dict(),
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def main_table(period: Period, codes: Sequence[str], cells: Mapping[tuple[date, str], Money],
|
||||
*, today: date, holidays: Mapping[str, str] | None = None) -> list[dict]:
|
||||
"""일자 × 쇼핑몰 표. 일 행 + 주간합계(일요일 뒤 / 기간 끝) + 기간 합계.
|
||||
|
||||
연간 보기는 일 대신 월 행(1~12월)으로 줄인다.
|
||||
"""
|
||||
holidays = holidays or {}
|
||||
rows: list[dict] = []
|
||||
if period.kind == "year":
|
||||
for m in range(1, 13):
|
||||
s = date(period.start.year, m, 1)
|
||||
e = month_end(s)
|
||||
rows.append(_row("month", f"{m}월", by_code(cells, codes, s, e), future=s > today,
|
||||
**{"from": s.isoformat(), "to": e.isoformat()}))
|
||||
rows.append(_row("total", "연간 합계", by_code(cells, codes, period.start, period.end)))
|
||||
return rows
|
||||
|
||||
week_codes: dict[str, Money] = {c: Money() for c in codes}
|
||||
for d in daterange(period.start, period.end):
|
||||
per_code = {c: cells.get((d, c), Money()) for c in codes}
|
||||
iso = d.isoformat()
|
||||
rows.append(_row("day", day_label(d), per_code, date=iso, weekday=d.weekday(),
|
||||
holiday=holidays.get(iso, ""), future=d > today, today=d == today,
|
||||
**{"from": iso, "to": iso}))
|
||||
for c in codes:
|
||||
week_codes[c].add(per_code[c])
|
||||
if period.days > 1 and (d.weekday() == 6 or d == period.end):
|
||||
ws = max(week_start(d), period.start)
|
||||
label = "주간합계" if period.kind == "week" else f"주간합계 ({fmt_md(ws)}~{fmt_md(d)})"
|
||||
rows.append(_row("week", label, week_codes, **{"from": ws.isoformat(), "to": d.isoformat()}))
|
||||
week_codes = {c: Money() for c in codes}
|
||||
if period.kind != "week" and period.days > 1:
|
||||
rows.append(_row("total", "기간 합계", by_code(cells, codes, period.start, period.end)))
|
||||
return rows
|
||||
|
||||
|
||||
def month_summary(year: int, month: int, codes: Sequence[str], cells: Mapping[tuple[date, str], Money]) -> dict:
|
||||
s = date(year, month, 1)
|
||||
per = by_code(cells, codes, s, month_end(s))
|
||||
tot = total(per.values())
|
||||
rows = []
|
||||
for c in codes:
|
||||
m = per[c]
|
||||
share = round(m.gross / tot.gross * 100, 1) if tot.gross > 0 else None
|
||||
rows.append({"code": c, **m.as_dict(), "share": share})
|
||||
rows.sort(key=lambda r: r["gross"], reverse=True)
|
||||
return {"label": f"{year}년 {month}월", "rows": rows,
|
||||
"total": {**tot.as_dict(), "share": 100.0 if tot.gross > 0 else None}}
|
||||
|
||||
|
||||
def year_months(year: int, codes: Sequence[str], cells: Mapping[tuple[date, str], Money], *, today: date) -> dict:
|
||||
rows = []
|
||||
for m in range(1, 13):
|
||||
s = date(year, m, 1)
|
||||
future = s > today
|
||||
money = sum_range(cells, codes, s, month_end(s))
|
||||
rows.append({"month": m, "label": f"{m}월", "future": future,
|
||||
**({"gross": None, "commission": None, "net": None} if future else money.as_dict())})
|
||||
tot = sum_range(cells, codes, date(year, 1, 1), date(year, 12, 31))
|
||||
return {"year": year, "rows": rows, "total": tot.as_dict()}
|
||||
|
||||
|
||||
def daily_series(period: Period, codes: Sequence[str], cells: Mapping[tuple[date, str], Money]) -> list[dict]:
|
||||
"""일별 추이 그래프용. 연간은 월별."""
|
||||
if period.kind == "year":
|
||||
out = []
|
||||
for m in range(1, 13):
|
||||
s = date(period.start.year, m, 1)
|
||||
out.append({"label": f"{m}월", **sum_range(cells, codes, s, month_end(s)).as_dict()})
|
||||
return out
|
||||
return [{"label": fmt_md(d), "date": d.isoformat(), **sum_range(cells, codes, d, d).as_dict()}
|
||||
for d in daterange(period.start, period.end)]
|
||||
@@ -0,0 +1,126 @@
|
||||
"""실적 모듈 공용 가드/서비스 생성 — router.py 가 쓴다(순환 import 방지로 분리).
|
||||
|
||||
권한(프론트에서 메뉴를 숨기는 것과 별개로 **서버에서** 항상 검사):
|
||||
- 실적 대시보드/매출 업데이트/상세 조회 : 모듈 권한 `performance` (admin 은 자동)
|
||||
- 실적 설정(수수료·API 인증정보·연결 테스트·테스트 데이터) : 관리자(is_admin)만
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
|
||||
MODULE_KEY = "performance"
|
||||
MODULE_NAME = "실적"
|
||||
|
||||
CONFIG_HELP = (
|
||||
"실적 모듈이 아직 설정되지 않았습니다. "
|
||||
"scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 "
|
||||
"PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
|
||||
)
|
||||
|
||||
|
||||
def get_store(request: Request) -> Any:
|
||||
return getattr(request.app.state, "performance_store", None)
|
||||
|
||||
|
||||
def key_ring():
|
||||
"""마스터 키 — 호출할 때마다 환경변수에서 읽는다(DB 에는 없다)."""
|
||||
from .security.crypto import KeyRing # noqa: WPS433
|
||||
|
||||
return KeyRing.from_env()
|
||||
|
||||
|
||||
def key_status() -> dict[str, Any]:
|
||||
"""설정 화면용 — 키가 설정됐는지/버전만. 키 값은 절대 넣지 않는다."""
|
||||
from .security.crypto import CryptoConfigError # noqa: WPS433
|
||||
|
||||
try:
|
||||
ring = key_ring()
|
||||
except CryptoConfigError as exc:
|
||||
return {"ok": False, "message": str(exc), "current_version": None, "versions": []}
|
||||
return {"ok": True, "message": "", "current_version": ring.current_version, "versions": ring.versions}
|
||||
|
||||
|
||||
def services(request: Request, store: Any):
|
||||
"""(CredentialService, SyncService)."""
|
||||
from .credentials import CredentialService # noqa: WPS433
|
||||
from .sync import SyncService # noqa: WPS433
|
||||
|
||||
creds = CredentialService(store, key_ring)
|
||||
return creds, SyncService(store, creds, app_state=request.app.state)
|
||||
|
||||
|
||||
def require_user(request: Request) -> dict[str, Any]:
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||
if not has_module(user, MODULE_KEY):
|
||||
raise HTTPException(status_code=403, detail=f"{MODULE_NAME} 모듈 권한이 없습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def require_admin(request: Request) -> dict[str, Any]:
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = require_user(request)
|
||||
if not is_admin(user):
|
||||
raise HTTPException(status_code=403, detail="실적 설정은 관리자만 변경할 수 있습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[str, Any]]:
|
||||
user = require_admin(request) if admin else require_user(request)
|
||||
st = get_store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail=CONFIG_HELP)
|
||||
return st, user
|
||||
|
||||
|
||||
def guard(request: Request, *, admin: bool = False):
|
||||
"""페이지 진입부. tuple(store, user) 이 아니면 그대로 응답으로 돌려준다."""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
|
||||
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
|
||||
return render_template(request, "denied.html",
|
||||
{"reason": reason, "user": user, "is_admin": is_admin(user)}, status_code=403)
|
||||
st = get_store(request)
|
||||
if st is None:
|
||||
return render_config_needed(request, user)
|
||||
return st, user
|
||||
|
||||
|
||||
def render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
return render_template(
|
||||
request, "denied.html",
|
||||
{"reason": CONFIG_HELP, "user": user, "is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active=MODULE_KEY)},
|
||||
status_code=503,
|
||||
)
|
||||
|
||||
|
||||
def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "실적") -> dict[str, Any]:
|
||||
from app.main import build_erp_nav # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
return {
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active=MODULE_KEY),
|
||||
"active_tab": active_tab,
|
||||
"page_title": page_title,
|
||||
"page_subtitle": "쇼핑몰 통합 매출",
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
"""② 쇼핑몰 API 인증정보 — 저장(암호화) / 화면용 요약 / 어댑터용 복호화 접근자 / 재암호화.
|
||||
|
||||
흐름: 설정 화면 입력 → 이 서비스(암호화) → perf_credentials(암호문)
|
||||
어댑터 → CredentialAccessor.get() → 서버 안에서만 복호화
|
||||
|
||||
화면으로 돌려주는 값
|
||||
- secret 항목: 값 있음/없음(has_value)만. 원문·일부·길이 모두 보내지 않는다.
|
||||
- 일반 항목(Vendor ID 등): 확인용으로 원문을 보여 준다(이것도 DB 에는 암호문).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from .adapters.base import MarketplaceAdapter
|
||||
from .security.crypto import KeyRing, decrypt, encrypt, needs_reencrypt
|
||||
|
||||
|
||||
def aad_for(code: str, key: str) -> str:
|
||||
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터."""
|
||||
return f"perf:{code}:{key}"
|
||||
|
||||
|
||||
class CredentialAccessor:
|
||||
"""어댑터 전용 — 서버 안에서만 복호화. 값은 처음 꺼낼 때 한 번 복호화해 둔다."""
|
||||
|
||||
def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *,
|
||||
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "") -> None:
|
||||
self._store = store
|
||||
self._code = code
|
||||
self._ring_loader = ring_loader
|
||||
self._rows = store.credential_rows(code) if store is not None else {}
|
||||
self._cache: dict[str, str] = {}
|
||||
self._overrides = {k: v for k, v in (overrides or {}).items() if v}
|
||||
self._persist = persist
|
||||
self._user = user
|
||||
|
||||
def has(self, key: str) -> bool:
|
||||
return bool(self._overrides.get(key)) or key in self._rows
|
||||
|
||||
def get(self, key: str) -> str:
|
||||
if key in self._overrides:
|
||||
return self._overrides[key]
|
||||
if key in self._cache:
|
||||
return self._cache[key]
|
||||
row = self._rows.get(key)
|
||||
if not row:
|
||||
return ""
|
||||
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key), ring=self._ring_loader())
|
||||
self._cache[key] = value
|
||||
return value
|
||||
|
||||
def set(self, key: str, value: str) -> None:
|
||||
"""어댑터가 새로 받은 토큰 등을 저장. 테스트(persist=False)면 메모리에만."""
|
||||
self._cache[key] = value
|
||||
if not self._persist or self._store is None:
|
||||
return
|
||||
ring = self._ring_loader()
|
||||
self._store.upsert_credential(
|
||||
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key), ring=ring),
|
||||
key_version=ring.current_version, user=self._user or "system",
|
||||
)
|
||||
self._rows[key] = {"encrypted_value": "", "key_version": ring.current_version}
|
||||
|
||||
def known_secrets(self) -> list[str]:
|
||||
"""가리기(redact)용 — 지금까지 꺼낸 원문들."""
|
||||
return [v for v in list(self._cache.values()) + list(self._overrides.values()) if v]
|
||||
|
||||
|
||||
class CredentialService:
|
||||
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing]) -> None:
|
||||
self._store = store
|
||||
self._ring_loader = ring_loader
|
||||
|
||||
def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True,
|
||||
user: str = "") -> CredentialAccessor:
|
||||
return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides,
|
||||
persist=persist, user=user)
|
||||
|
||||
# ── 화면용 요약(비밀 원문 없음) ─────────────────────────
|
||||
def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]:
|
||||
rows = self._store.credential_rows(adapter.code)
|
||||
fields = []
|
||||
decrypt_error = ""
|
||||
for f in adapter.visible_fields():
|
||||
row = rows.get(f.key)
|
||||
item: dict[str, Any] = {
|
||||
"key": f.key, "label": f.label, "secret": f.secret, "required": f.required,
|
||||
"help": f.help, "placeholder": f.placeholder, "has_value": row is not None,
|
||||
"updated_at": row["updated_at"].isoformat(timespec="seconds") if row and row.get("updated_at") else "",
|
||||
}
|
||||
if row is not None and not f.secret:
|
||||
try:
|
||||
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key),
|
||||
ring=self._ring_loader())
|
||||
except Exception as exc: # noqa: BLE001 — 키 없음/손상: 값 없이 안내만
|
||||
item["value"] = ""
|
||||
decrypt_error = str(exc) if "환경변수" in str(exc) else "저장된 값을 복호화하지 못했습니다."
|
||||
fields.append(item)
|
||||
return {"fields": fields, "decrypt_error": decrypt_error,
|
||||
"configured": all(x["has_value"] for x in fields if x["required"])}
|
||||
|
||||
def configured_codes(self, adapters: list[MarketplaceAdapter]) -> dict[str, bool]:
|
||||
keys = self._store.credential_keys_by_code()
|
||||
out = {}
|
||||
for a in adapters:
|
||||
if a.uses_shared_integration:
|
||||
out[a.code] = True
|
||||
continue
|
||||
have = keys.get(a.code, set())
|
||||
required = [f.key for f in a.visible_fields() if f.required]
|
||||
out[a.code] = bool(required) and all(k in have for k in required)
|
||||
return out
|
||||
|
||||
# ── 저장 ────────────────────────────────────────────────
|
||||
def merged_values(self, adapter: MarketplaceAdapter, values: dict[str, str]) -> dict[str, str]:
|
||||
"""검사용 — 새 입력 + (빈 칸은) 기존 값 존재 여부. 비밀 원문은 꺼내지 않고 표식만."""
|
||||
rows = self._store.credential_rows(adapter.code)
|
||||
merged = {}
|
||||
for f in adapter.visible_fields():
|
||||
v = (values.get(f.key) or "").strip()
|
||||
merged[f.key] = v if v else ("__stored__" if f.key in rows else "")
|
||||
return merged
|
||||
|
||||
def save(self, adapter: MarketplaceAdapter, values: dict[str, str], *, clear: list[str] | None = None,
|
||||
user: str = "") -> list[str]:
|
||||
"""빈 칸 = 기존 값 유지. clear 에 든 항목은 삭제. 저장한 항목 키 목록 반환."""
|
||||
allowed = {f.key for f in adapter.visible_fields()}
|
||||
ring = self._ring_loader()
|
||||
saved = []
|
||||
for key, raw in values.items():
|
||||
if key not in allowed:
|
||||
continue
|
||||
v = (raw or "").strip()
|
||||
if not v:
|
||||
continue
|
||||
self._store.upsert_credential(
|
||||
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key), ring=ring),
|
||||
key_version=ring.current_version, user=user,
|
||||
)
|
||||
saved.append(key)
|
||||
for key in clear or []:
|
||||
if key in allowed and key not in saved:
|
||||
self._store.delete_credential(adapter.code, key)
|
||||
return saved
|
||||
|
||||
# ── 마스터 키 교체 후 재암호화 ─────────────────────────
|
||||
def reencrypt_all(self) -> dict[str, int]:
|
||||
"""예전 키 버전으로 된 암호문을 현재 키로 다시 암호화. (재암호화 수, 실패 수)."""
|
||||
ring = self._ring_loader()
|
||||
done = failed = 0
|
||||
for row in self._store.all_credential_rows():
|
||||
token = row["encrypted_value"]
|
||||
if not needs_reencrypt(token, ring):
|
||||
continue
|
||||
code, key = row["marketplace_code"], row["credential_key"]
|
||||
try:
|
||||
plain = decrypt(token, aad=aad_for(code, key), ring=ring)
|
||||
except Exception: # noqa: BLE001
|
||||
failed += 1
|
||||
continue
|
||||
self._store.upsert_credential(
|
||||
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key), ring=ring),
|
||||
key_version=ring.current_version, user="rekey",
|
||||
)
|
||||
done += 1
|
||||
return {"reencrypted": done, "failed": failed}
|
||||
|
||||
def key_versions_in_use(self) -> dict[int, int]:
|
||||
counts: dict[int, int] = {}
|
||||
for row in self._store.all_credential_rows():
|
||||
v = int(row["key_version"])
|
||||
counts[v] = counts.get(v, 0) + 1
|
||||
return counts
|
||||
@@ -0,0 +1,201 @@
|
||||
"""④ 대시보드/설정 화면 데이터 조립 — 저장소 조회 + calc 계산 결과를 템플릿 컨텍스트로.
|
||||
|
||||
HTTP 와 무관하다(store 만 주입). 라우터는 파라미터 파싱·권한만 하고 여기로 넘긴다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
from . import calc
|
||||
from .adapters.base import STATUS_LABELS
|
||||
from .adapters.registry import all_adapters, get_adapter
|
||||
|
||||
|
||||
def _sales_marketplaces(store: Any) -> list[dict[str, Any]]:
|
||||
"""대시보드 열 = 사용 ON + 매출 집계 ON 인 쇼핑몰(설정 순서)."""
|
||||
known = {a.code for a in all_adapters()}
|
||||
return [m for m in store.list_marketplaces() if m["enabled"] and m["include_in_sales"] and m["code"] in known]
|
||||
|
||||
|
||||
def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None,
|
||||
configured: bool) -> str:
|
||||
if not marketplace.get("enabled"):
|
||||
return "disabled"
|
||||
adapter = get_adapter(marketplace["code"])
|
||||
if adapter is not None and not adapter.uses_shared_integration and not configured:
|
||||
return "not_configured"
|
||||
return (status_row or {}).get("status") or "unknown"
|
||||
|
||||
|
||||
def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
custom_from: date | None = None, custom_to: date | None = None,
|
||||
selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None,
|
||||
configured: Mapping[str, bool] | None = None) -> dict[str, Any]:
|
||||
markets = _sales_marketplaces(store)
|
||||
all_codes = [m["code"] for m in markets]
|
||||
codes = [c for c in all_codes if c in set(selected)] or all_codes
|
||||
names = {m["code"]: m["name"] for m in markets}
|
||||
short = {c: _short_name(names[c]) for c in all_codes}
|
||||
|
||||
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
|
||||
cmp_start, cmp_end, cmp_label = period.compare_range(today)
|
||||
# 월·연 누적의 기준일 — 선택 기간이 오늘을 포함하면 오늘(이번주가 다음 달로 걸쳐도
|
||||
# "이번달"), 지난 기간이면 기간 끝, 앞으로의 기간이면 기간 시작.
|
||||
if period.end < today:
|
||||
ref = period.end
|
||||
elif period.start <= today:
|
||||
ref = today
|
||||
else:
|
||||
ref = period.start
|
||||
month_period = calc.resolve_period("month", ref)
|
||||
year_period = calc.resolve_period("year", ref)
|
||||
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
|
||||
y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today)
|
||||
|
||||
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
||||
q_end = max(period.end, year_period.end)
|
||||
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
|
||||
|
||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
|
||||
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
|
||||
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
|
||||
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
|
||||
has_prev = prev.gross != 0 or prev.commission != 0
|
||||
|
||||
period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
||||
"custom": "선택 기간"}[period.kind]
|
||||
kpis = [
|
||||
{"key": "gross", "label": f"{period_word} 총매출", "value": cur.gross, "primary": True,
|
||||
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label},
|
||||
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
|
||||
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
|
||||
{"key": "commission", "label": f"{period_word} 수수료", "value": cur.commission,
|
||||
"delta": calc.pct_change(cur.commission, prev.commission) if has_prev else None, "cmp": cmp_label,
|
||||
"invert": True},
|
||||
{"key": "mtd", "label": f"{month_period.label} 누적 매출", "value": mtd.gross,
|
||||
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label},
|
||||
{"key": "ytd", "label": f"{year_period.label} 누적 매출", "value": ytd.gross,
|
||||
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label},
|
||||
]
|
||||
|
||||
share = calc.by_code(cells, codes, period.start, period.end)
|
||||
statuses = store.statuses()
|
||||
configured = configured or {}
|
||||
problems = []
|
||||
for m in markets:
|
||||
if m["code"] not in codes:
|
||||
continue
|
||||
st = display_status(m, statuses.get(m["code"]), configured.get(m["code"], False))
|
||||
if st in ("auth_failed", "token_expired", "api_error"):
|
||||
problems.append({"code": m["code"], "name": m["name"], "label": STATUS_LABELS[st],
|
||||
"error": (statuses.get(m["code"]) or {}).get("last_error", "")})
|
||||
|
||||
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
|
||||
|
||||
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if kind == "custom":
|
||||
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}{m_qs}"
|
||||
return f"?period={kind}&d={anchor_d.isoformat()}{m_qs}"
|
||||
|
||||
if period.kind == "custom":
|
||||
length = timedelta(days=period.days)
|
||||
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
||||
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
||||
else:
|
||||
prev_url = url(period.kind, period.prev_anchor)
|
||||
next_url = url(period.kind, period.next_anchor)
|
||||
nav = {
|
||||
"prev": prev_url, "next": next_url,
|
||||
"quick": [
|
||||
{"key": "day", "label": "오늘", "url": url("day", today),
|
||||
"active": period.kind == "day" and period.start == today},
|
||||
{"key": "week", "label": "이번주", "url": url("week", today),
|
||||
"active": period.kind == "week" and period.start <= today <= period.end},
|
||||
{"key": "month", "label": "이번달", "url": url("month", today),
|
||||
"active": period.kind == "month" and period.start <= today <= period.end},
|
||||
{"key": "year", "label": "올해", "url": url("year", today),
|
||||
"active": period.kind == "year" and period.start <= today <= period.end},
|
||||
],
|
||||
"m_qs": m_qs,
|
||||
}
|
||||
|
||||
return {
|
||||
"nav": nav,
|
||||
"period": period,
|
||||
"period_kind": period.kind,
|
||||
"today": today.isoformat(),
|
||||
"codes": codes,
|
||||
"all_codes": all_codes,
|
||||
"names": names,
|
||||
"short_names": short,
|
||||
"selected_all": len(codes) == len(all_codes),
|
||||
"kpis": kpis,
|
||||
"table": calc.main_table(period, codes, cells, today=today, holidays=holidays),
|
||||
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells),
|
||||
"year": calc.year_months(year_period.start.year, codes, cells, today=today),
|
||||
"chart_daily": calc.daily_series(period, codes, cells),
|
||||
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
|
||||
"problems": problems,
|
||||
"last_update_at": store.last_update_at(),
|
||||
"running": store.running_codes(),
|
||||
"no_marketplaces": not all_codes,
|
||||
}
|
||||
|
||||
|
||||
def _short_name(name: str) -> str:
|
||||
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스"}.get(name, name)
|
||||
|
||||
|
||||
def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapping[str, Any],
|
||||
key_versions_in_use: Mapping[int, int], sample_count: int) -> dict[str, Any]:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
from .adapters.cafe24 import MARKET_MAP # noqa: WPS433
|
||||
|
||||
statuses = store.statuses()
|
||||
rates = store.rate_table()
|
||||
today = today_kst()
|
||||
via_cafe24 = set(MARKET_MAP.values()) # 카페24 마켓 통합관리 경유로 매출이 들어오는 쇼핑몰
|
||||
rows = []
|
||||
by_code = {m["code"]: m for m in store.list_marketplaces()}
|
||||
for adapter in all_adapters():
|
||||
m = by_code.get(adapter.code)
|
||||
if m is None:
|
||||
continue
|
||||
st_row = statuses.get(adapter.code) or {}
|
||||
st = display_status(m, st_row, configured.get(adapter.code, False))
|
||||
cur_rate = calc.rate_on(rates, adapter.code, today)
|
||||
has_rate = bool(rates.get(adapter.code))
|
||||
rows.append({
|
||||
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
|
||||
"include_in_sales": m["include_in_sales"],
|
||||
"rate": _fmt_rate(cur_rate) if has_rate else "",
|
||||
"rate_history": len(rates.get(adapter.code, ())),
|
||||
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
|
||||
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
|
||||
"configured": configured.get(adapter.code, False),
|
||||
"via_cafe24": adapter.code in via_cafe24,
|
||||
"status": st, "status_label": STATUS_LABELS.get(st, st),
|
||||
"last_test_at": st_row.get("last_test_at"), "last_test_ok": st_row.get("last_test_ok"),
|
||||
"last_sync_at": st_row.get("last_sync_at"), "last_success_sync_at": st_row.get("last_success_sync_at"),
|
||||
"last_error": st_row.get("last_error") or "", "last_error_at": st_row.get("last_error_at"),
|
||||
})
|
||||
stale = {v: n for v, n in key_versions_in_use.items() if key_info.get("current_version") and v != key_info["current_version"]}
|
||||
return {"rows": rows, "key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
|
||||
"stale_key_rows": sum(stale.values()), "sample_count": sample_count,
|
||||
"default_sample_from": today.replace(month=1, day=1).isoformat(),
|
||||
"default_sample_to": today.isoformat()}
|
||||
|
||||
|
||||
def _fmt_rate(rate: Decimal) -> str:
|
||||
s = f"{Decimal(rate):f}"
|
||||
if "." in s:
|
||||
s = s.rstrip("0").rstrip(".")
|
||||
return s
|
||||
@@ -0,0 +1,385 @@
|
||||
"""performance_db PostgreSQL 저장소.
|
||||
|
||||
- 드라이버: psycopg 3 (`psycopg[binary,pool]`) — 다른 모듈과 동일 패턴.
|
||||
- 연결 정보: 환경변수 `PERFORMANCE_DB_URL`
|
||||
(예: postgresql://performance_app:<pwd>@postgres-db:5432/performance_db)
|
||||
- 스키마는 앱이 만들지 않는다. `scripts/sql/performance_db_init.sql` 을 superuser 가 사전 적용.
|
||||
- 연결 풀은 lazy open — 부팅 시 DB 가 잠시 끊겨도 컨테이너가 죽지 않게.
|
||||
|
||||
이 저장소는 인증정보를 **암호문 그대로만** 읽고 쓴다. 암·복호화는 credentials.py 의 몫.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Iterable
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from app.timezone import to_kst_iso
|
||||
|
||||
# running 상태로 이 시간 넘게 남은 동기화는 죽은 것으로 보고 정리한다(서버 재시작 등).
|
||||
STALE_RUN_AFTER = timedelta(minutes=30)
|
||||
|
||||
|
||||
def _iso(v: Any) -> Any:
|
||||
if isinstance(v, datetime):
|
||||
return to_kst_iso(v)
|
||||
if isinstance(v, date):
|
||||
return v.isoformat()
|
||||
return v
|
||||
|
||||
|
||||
class PerformanceDBStore:
|
||||
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5):
|
||||
self._pool = ConnectionPool(
|
||||
conninfo=dsn,
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
kwargs={"row_factory": dict_row, "autocommit": True},
|
||||
open=False,
|
||||
)
|
||||
self._pool.open(wait=False)
|
||||
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 쇼핑몰 기본 설정
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def list_marketplaces(self) -> list[dict[str, Any]]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT * FROM perf_marketplaces ORDER BY sort_order, code").fetchall()
|
||||
return [{k: _iso(v) for k, v in r.items()} for r in rows]
|
||||
|
||||
def update_marketplace(self, code: str, *, enabled: bool | None = None,
|
||||
include_in_sales: bool | None = None) -> dict[str, Any] | None:
|
||||
sets, params = [], []
|
||||
if enabled is not None:
|
||||
sets.append("enabled = %s")
|
||||
params.append(bool(enabled))
|
||||
if include_in_sales is not None:
|
||||
sets.append("include_in_sales = %s")
|
||||
params.append(bool(include_in_sales))
|
||||
if not sets:
|
||||
return None
|
||||
params.append(code)
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
|
||||
).fetchone()
|
||||
return {k: _iso(v) for k, v in row.items()} if row else None
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 수수료율 이력
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def rate_table(self) -> dict[str, list[tuple[date, Decimal]]]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT marketplace_code, effective_from, rate_percent FROM perf_commission_rates "
|
||||
"WHERE rule_type = 'marketplace' ORDER BY marketplace_code, effective_from"
|
||||
).fetchall()
|
||||
out: dict[str, list[tuple[date, Decimal]]] = {}
|
||||
for r in rows:
|
||||
out.setdefault(r["marketplace_code"], []).append((r["effective_from"], Decimal(r["rate_percent"])))
|
||||
return out
|
||||
|
||||
def list_rates(self, code: str) -> list[dict[str, Any]]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, rate_percent, effective_from, memo, created_by, created_at "
|
||||
"FROM perf_commission_rates WHERE marketplace_code = %s AND rule_type = 'marketplace' "
|
||||
"ORDER BY effective_from DESC",
|
||||
(code,),
|
||||
).fetchall()
|
||||
return [{k: (str(v) if isinstance(v, Decimal) else _iso(v)) for k, v in r.items()} for r in rows]
|
||||
|
||||
def set_rate(self, code: str, *, rate_percent: Decimal, effective_from: date,
|
||||
memo: str = "", user: str = "") -> None:
|
||||
"""같은 적용 시작일이면 덮어쓴다(오타 수정), 다르면 이력으로 추가."""
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO perf_commission_rates
|
||||
(marketplace_code, rule_type, rate_percent, effective_from, memo, created_by)
|
||||
VALUES (%s, 'marketplace', %s, %s, %s, %s)
|
||||
ON CONFLICT (marketplace_code, rule_type, effective_from) DO UPDATE
|
||||
SET rate_percent = EXCLUDED.rate_percent, memo = EXCLUDED.memo,
|
||||
created_by = EXCLUDED.created_by, created_at = now()
|
||||
""",
|
||||
(code, rate_percent, effective_from, memo, user),
|
||||
)
|
||||
|
||||
def delete_rate(self, code: str, rate_id: int) -> bool:
|
||||
with self._pool.connection() as conn:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM perf_commission_rates WHERE id = %s AND marketplace_code = %s", (rate_id, code)
|
||||
)
|
||||
return cur.rowcount > 0
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 인증정보(암호문)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT credential_key, encrypted_value, key_version, updated_at, updated_by "
|
||||
"FROM perf_credentials WHERE marketplace_code = %s",
|
||||
(code,),
|
||||
).fetchall()
|
||||
return {r["credential_key"]: r for r in rows}
|
||||
|
||||
def credential_keys_by_code(self) -> dict[str, set[str]]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT marketplace_code, credential_key FROM perf_credentials").fetchall()
|
||||
out: dict[str, set[str]] = {}
|
||||
for r in rows:
|
||||
out.setdefault(r["marketplace_code"], set()).add(r["credential_key"])
|
||||
return out
|
||||
|
||||
def upsert_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int,
|
||||
user: str = "") -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO perf_credentials (marketplace_code, credential_key, encrypted_value, key_version, updated_by)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (marketplace_code, credential_key) DO UPDATE
|
||||
SET encrypted_value = EXCLUDED.encrypted_value, key_version = EXCLUDED.key_version,
|
||||
updated_by = EXCLUDED.updated_by
|
||||
""",
|
||||
(code, key, encrypted_value, key_version, user),
|
||||
)
|
||||
|
||||
def delete_credential(self, code: str, key: str) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"DELETE FROM perf_credentials WHERE marketplace_code = %s AND credential_key = %s", (code, key)
|
||||
)
|
||||
|
||||
def all_credential_rows(self) -> list[dict[str, Any]]:
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute(
|
||||
"SELECT marketplace_code, credential_key, encrypted_value, key_version FROM perf_credentials"
|
||||
).fetchall()
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 연결 상태
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def statuses(self) -> dict[str, dict[str, Any]]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT * FROM perf_connection_status").fetchall()
|
||||
return {r["marketplace_code"]: {k: _iso(v) for k, v in r.items()} for r in rows}
|
||||
|
||||
def record_test(self, code: str, *, status: str, ok: bool, error: str = "") -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO perf_connection_status (marketplace_code, status, last_test_at, last_test_ok,
|
||||
last_error, last_error_at)
|
||||
VALUES (%s, %s, now(), %s, %s, CASE WHEN %s = '' THEN NULL ELSE now() END)
|
||||
ON CONFLICT (marketplace_code) DO UPDATE
|
||||
SET status = EXCLUDED.status, last_test_at = now(), last_test_ok = EXCLUDED.last_test_ok,
|
||||
last_error = CASE WHEN EXCLUDED.last_error = '' THEN perf_connection_status.last_error
|
||||
ELSE EXCLUDED.last_error END,
|
||||
last_error_at = CASE WHEN EXCLUDED.last_error = '' THEN perf_connection_status.last_error_at
|
||||
ELSE now() END
|
||||
""",
|
||||
(code, status, ok, error, error),
|
||||
)
|
||||
|
||||
def record_sync(self, code: str, *, status: str, ok: bool, error: str = "") -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO perf_connection_status (marketplace_code, status, last_sync_at,
|
||||
last_success_sync_at, last_error, last_error_at)
|
||||
VALUES (%s, %s, now(), CASE WHEN %s THEN now() END, %s, CASE WHEN %s = '' THEN NULL ELSE now() END)
|
||||
ON CONFLICT (marketplace_code) DO UPDATE
|
||||
SET status = EXCLUDED.status, last_sync_at = now(),
|
||||
last_success_sync_at = CASE WHEN %s THEN now()
|
||||
ELSE perf_connection_status.last_success_sync_at END,
|
||||
last_error = CASE WHEN EXCLUDED.last_error = '' THEN perf_connection_status.last_error
|
||||
ELSE EXCLUDED.last_error END,
|
||||
last_error_at = CASE WHEN EXCLUDED.last_error = '' THEN perf_connection_status.last_error_at
|
||||
ELSE now() END
|
||||
""",
|
||||
(code, status, ok, error, error, ok),
|
||||
)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 매출 사건
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def upsert_events(self, code: str, events: Iterable[dict[str, Any]], *, is_sample: bool = False) -> int:
|
||||
"""같은 (쇼핑몰, 사건 종류, 외부 사건 ID)는 덮어쓴다 — 여러 번 동기화해도 중복 없음."""
|
||||
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]],
|
||||
*, id_prefix: str = "") -> int:
|
||||
"""기간(sales_date) 안 이 어댑터가 만든 실데이터(is_sample 아님)를 지우고 새로 넣는다 — 한 트랜잭션.
|
||||
|
||||
지우는 대상: 이 쇼핑몰(code)의 행 + (id_prefix 가 있으면) 다른 쇼핑몰 열로 보냈던 이 어댑터의 행
|
||||
(external_event_id 가 id_prefix 로 시작). 다른 쇼핑몰의 직접 연동분·테스트 데이터는 건드리지 않는다.
|
||||
실패하면 롤백되어 예전 데이터가 그대로 남는다."""
|
||||
rows = self._event_rows(code, events, False)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
if id_prefix:
|
||||
conn.execute(
|
||||
"DELETE FROM perf_sales_events WHERE is_sample = FALSE AND sales_date BETWEEN %s AND %s "
|
||||
"AND (marketplace_code = %s OR left(external_event_id, %s) = %s)",
|
||||
(start, end, code, len(id_prefix), id_prefix),
|
||||
)
|
||||
else:
|
||||
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]:
|
||||
"""행마다 집계할 쇼핑몰 = 사건의 marketplace_code(다른 쇼핑몰 대신 받은 주문), 없으면 code."""
|
||||
return [
|
||||
(e.get("marketplace_code") or 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,
|
||||
amount, discount_amount, order_status, raw_data, is_sample, synced_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, now())
|
||||
ON CONFLICT (marketplace_code, event_type, external_event_id) DO UPDATE
|
||||
SET external_order_id = EXCLUDED.external_order_id, external_line_id = EXCLUDED.external_line_id,
|
||||
order_date = EXCLUDED.order_date, payment_date = EXCLUDED.payment_date,
|
||||
event_date = EXCLUDED.event_date, sales_date = EXCLUDED.sales_date,
|
||||
product_name = EXCLUDED.product_name, option_name = EXCLUDED.option_name,
|
||||
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()
|
||||
"""
|
||||
|
||||
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
|
||||
if not codes:
|
||||
return {}
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT sales_date, marketplace_code, SUM(amount)::BIGINT AS amount "
|
||||
"FROM perf_sales_events WHERE sales_date BETWEEN %s AND %s AND marketplace_code = ANY(%s) "
|
||||
"GROUP BY sales_date, marketplace_code",
|
||||
(start, end, codes),
|
||||
).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:
|
||||
rows = conn.execute(
|
||||
"SELECT id, event_type, external_order_id, external_line_id, order_date, payment_date, "
|
||||
" event_date, sales_date, product_name, option_name, quantity, amount, "
|
||||
" discount_amount, order_status, is_sample "
|
||||
"FROM perf_sales_events WHERE marketplace_code = %s AND sales_date BETWEEN %s AND %s "
|
||||
"ORDER BY sales_date, external_order_id, event_type LIMIT %s",
|
||||
(code, start, end, limit),
|
||||
).fetchall()
|
||||
return [{k: _iso(v) for k, v in r.items()} for r in rows]
|
||||
|
||||
def sample_count(self) -> int:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("SELECT COUNT(*) AS n FROM perf_sales_events WHERE is_sample").fetchone()
|
||||
return int(row["n"] or 0)
|
||||
|
||||
def delete_sample_events(self) -> int:
|
||||
"""테스트 데이터만(is_sample) 지운다 — 조건이 있는 삭제."""
|
||||
with self._pool.connection() as conn:
|
||||
cur = conn.execute("DELETE FROM perf_sales_events WHERE is_sample = TRUE")
|
||||
return cur.rowcount
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 동기화 실행(중복 실행 방지)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def start_run(self, code: str, *, trigger: str, range_from: date, range_to: date, user: str) -> int | None:
|
||||
"""running 행을 만든다. 이미 돌고 있으면 None(부분 유니크 인덱스로 막힘)."""
|
||||
import psycopg # noqa: WPS433
|
||||
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE perf_sync_runs SET status = 'failed', finished_at = now(), "
|
||||
"error = '중단됨(시간 초과로 정리)' "
|
||||
"WHERE marketplace_code = %s AND status = 'running' AND started_at < now() - %s",
|
||||
(code, STALE_RUN_AFTER),
|
||||
)
|
||||
try:
|
||||
row = conn.execute(
|
||||
"INSERT INTO perf_sync_runs (marketplace_code, trigger, range_from, range_to, started_by) "
|
||||
"VALUES (%s, %s, %s, %s, %s) RETURNING id",
|
||||
(code, trigger, range_from, range_to, user),
|
||||
).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
return None
|
||||
return int(row["id"])
|
||||
|
||||
def finish_run(self, run_id: int, *, ok: bool, fetched: int = 0, upserted: int = 0, error: str = "") -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE perf_sync_runs SET status = %s, fetched_count = %s, upserted_count = %s, "
|
||||
"error = %s, finished_at = now() WHERE id = %s",
|
||||
("success" if ok else "failed", fetched, upserted, error, run_id),
|
||||
)
|
||||
|
||||
def last_update_at(self) -> str | None:
|
||||
"""대시보드 "마지막 업데이트" — 성공한 동기화 중 가장 최근."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT MAX(finished_at) AS t FROM perf_sync_runs WHERE status = 'success'"
|
||||
).fetchone()
|
||||
return _iso(row["t"]) if row and row["t"] else None
|
||||
|
||||
def running_codes(self) -> list[str]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT marketplace_code FROM perf_sync_runs WHERE status = 'running' "
|
||||
"AND started_at >= now() - %s",
|
||||
(STALE_RUN_AFTER,),
|
||||
).fetchall()
|
||||
return [r["marketplace_code"] for r in rows]
|
||||
@@ -0,0 +1,334 @@
|
||||
"""실적 모듈 라우터 (prefix=/performance).
|
||||
|
||||
화면
|
||||
GET /performance/ 대시보드(모듈 권한)
|
||||
GET /performance/settings 실적 설정(관리자)
|
||||
JSON API — 모듈 권한
|
||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
||||
JSON API — 관리자
|
||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
|
||||
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 테스트 데이터 생성/삭제
|
||||
POST /performance/api/rekey 마스터 키 교체 후 재암호화
|
||||
|
||||
핸들러는 동기 DB 라 `def` 로 둔다(FastAPI 가 스레드풀에서 실행).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, HTTPException, Query, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
from . import common
|
||||
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 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
|
||||
|
||||
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(str(value)[:10])
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail=f"{field} 형식이 올바르지 않습니다(YYYY-MM-DD).") from None
|
||||
|
||||
|
||||
def _holidays() -> dict[str, str]:
|
||||
try:
|
||||
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433 — 공휴일 표 공유(읽기 전용)
|
||||
|
||||
return dict(KR_HOLIDAYS)
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
def _code_or_404(store: Any, code: str):
|
||||
adapter = get_adapter(code)
|
||||
if adapter is None or code not in {m["code"] for m in store.list_marketplaces()}:
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
|
||||
return adapter
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(request: Request) -> JSONResponse:
|
||||
st = common.get_store(request)
|
||||
return JSONResponse({"ok": st is not None, "module": "performance",
|
||||
"encryption_key": common.key_status()["ok"]})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 화면
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def dashboard_page(
|
||||
request: Request,
|
||||
period: str = "week",
|
||||
d: str | None = None,
|
||||
from_: str | None = Query(None, alias="from"),
|
||||
to: str | None = None,
|
||||
m: list[str] = Query(default=[]),
|
||||
metric: str = "gross",
|
||||
):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
|
||||
g = common.guard(request)
|
||||
if not isinstance(g, tuple):
|
||||
return g
|
||||
store, user = g
|
||||
from .dashboard import build_dashboard # noqa: WPS433
|
||||
|
||||
today = today_kst()
|
||||
anchor = _parse_date(d) or today
|
||||
creds, _ = common.services(request, store)
|
||||
ctx = build_dashboard(
|
||||
store, kind=period, anchor=anchor, today=today,
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), selected=m,
|
||||
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
|
||||
)
|
||||
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross"
|
||||
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings_page(request: Request):
|
||||
from app.main import render_template # noqa: WPS433
|
||||
|
||||
g = common.guard(request, admin=True)
|
||||
if not isinstance(g, tuple):
|
||||
return g
|
||||
store, user = g
|
||||
from .dashboard import build_settings # noqa: WPS433
|
||||
|
||||
creds, _ = common.services(request, store)
|
||||
ctx = build_settings(
|
||||
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
|
||||
key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(),
|
||||
)
|
||||
return render_template(request, "performance/settings.html",
|
||||
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 모듈 권한
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@router.post("/api/sync")
|
||||
def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""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))]
|
||||
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
|
||||
|
||||
end = end or today_kst()
|
||||
start = start or end
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
if end > today_kst():
|
||||
end = today_kst()
|
||||
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()})
|
||||
|
||||
|
||||
@router.get("/api/events")
|
||||
def api_events(request: Request, code: str, from_: str = Query(..., alias="from"), to: str | None = None) -> JSONResponse:
|
||||
store, _ = common.require_store(request)
|
||||
_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_EVENT_DAYS:
|
||||
raise HTTPException(status_code=400, detail=f"상세 조회는 {MAX_EVENT_DAYS}일 이내만 가능합니다.")
|
||||
rows = store.list_events(code, start, end)
|
||||
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 관리자(설정)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@router.put("/api/marketplaces/{code}")
|
||||
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
_code_or_404(store, code)
|
||||
row = store.update_marketplace(
|
||||
code,
|
||||
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
||||
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
||||
)
|
||||
return JSONResponse({"marketplace": row})
|
||||
|
||||
|
||||
@router.post("/api/marketplaces/{code}/rates")
|
||||
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
store, user = common.require_store(request, admin=True)
|
||||
_code_or_404(store, code)
|
||||
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
||||
try:
|
||||
rate = Decimal(raw)
|
||||
except InvalidOperation:
|
||||
raise HTTPException(status_code=400, detail="수수료율은 숫자로 입력하세요(예: 5, 10.8, 15.35).") from None
|
||||
if not rate.is_finite() or rate < 0 or rate > 100:
|
||||
raise HTTPException(status_code=400, detail="수수료율은 0 ~ 100 사이여야 합니다.")
|
||||
if rate != rate.quantize(Decimal("0.001")):
|
||||
raise HTTPException(status_code=400, detail="수수료율은 소수점 셋째 자리까지 입력할 수 있습니다.")
|
||||
effective_from = _parse_date(payload.get("effective_from"), field="적용 시작일")
|
||||
if effective_from is None:
|
||||
raise HTTPException(status_code=400, detail="적용 시작일을 입력하세요.")
|
||||
store.set_rate(code, rate_percent=rate, effective_from=effective_from,
|
||||
memo=str(payload.get("memo") or "")[:200], user=user["email"])
|
||||
return JSONResponse({"rates": store.list_rates(code)})
|
||||
|
||||
|
||||
@router.get("/api/marketplaces/{code}/rates")
|
||||
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
_code_or_404(store, code)
|
||||
return JSONResponse({"rates": store.list_rates(code)})
|
||||
|
||||
|
||||
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
|
||||
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
_code_or_404(store, code)
|
||||
if not store.delete_rate(code, rate_id):
|
||||
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
||||
return JSONResponse({"rates": store.list_rates(code)})
|
||||
|
||||
|
||||
@router.get("/api/marketplaces/{code}/credentials")
|
||||
def api_get_credentials(request: Request, code: str) -> JSONResponse:
|
||||
"""입력칸 정의 + 저장 여부만. secret 항목의 원문은 보내지 않는다."""
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
adapter = _code_or_404(store, code)
|
||||
creds, _ = common.services(request, store)
|
||||
info = creds.describe(adapter)
|
||||
return JSONResponse({"code": code, "name": adapter.name, "shared": adapter.uses_shared_integration,
|
||||
"note": adapter.note, "docs_url": adapter.docs_url,
|
||||
"key": common.key_status(), **info})
|
||||
|
||||
|
||||
def _clean_values(adapter, payload: dict[str, Any]) -> dict[str, str]:
|
||||
allowed = {f.key for f in adapter.visible_fields()}
|
||||
values = payload.get("values") or {}
|
||||
if not isinstance(values, dict):
|
||||
raise HTTPException(status_code=400, detail="values 형식이 올바르지 않습니다.")
|
||||
return {k: str(v) for k, v in values.items() if k in allowed and v is not None}
|
||||
|
||||
|
||||
@router.put("/api/marketplaces/{code}/credentials")
|
||||
def api_save_credentials(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
store, user = common.require_store(request, admin=True)
|
||||
adapter = _code_or_404(store, code)
|
||||
if adapter.uses_shared_integration:
|
||||
raise HTTPException(status_code=400, detail=f"{adapter.name}은(는) 공통 연동을 사용해 여기서 입력하지 않습니다.")
|
||||
if not common.key_status()["ok"]:
|
||||
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
||||
creds, _ = common.services(request, store)
|
||||
values = _clean_values(adapter, payload)
|
||||
clear = [str(k) for k in (payload.get("clear") or [])]
|
||||
merged = creds.merged_values(adapter, values)
|
||||
for k in clear:
|
||||
if k in merged and not values.get(k):
|
||||
merged[k] = ""
|
||||
errors = adapter.validate_credentials(merged)
|
||||
if errors:
|
||||
raise HTTPException(status_code=400, detail=" ".join(errors))
|
||||
saved = creds.save(adapter, values, clear=clear, user=user["email"])
|
||||
return JSONResponse({"saved": saved, **creds.describe(adapter)})
|
||||
|
||||
|
||||
@router.post("/api/marketplaces/{code}/test")
|
||||
def api_test_connection(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용)."""
|
||||
store, user = common.require_store(request, admin=True)
|
||||
adapter = _code_or_404(store, code)
|
||||
_, sync = common.services(request, store)
|
||||
values = {k: v for k, v in _clean_values(adapter, payload).items() if v.strip()}
|
||||
result = sync.test_connection(code, values=values or None, user=user["email"])
|
||||
return JSONResponse(result)
|
||||
|
||||
|
||||
@router.get("/api/marketplaces/{code}/reconcile")
|
||||
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, to=_parse_date(to, field="종료일"), 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)
|
||||
action = payload.get("action")
|
||||
if action == "delete":
|
||||
return JSONResponse({"deleted": store.delete_sample_events(), "sample_count": store.sample_count()})
|
||||
if action != "generate":
|
||||
raise HTTPException(status_code=400, detail="action 은 generate 또는 delete 입니다.")
|
||||
today = today_kst()
|
||||
start = _parse_date(payload.get("from")) or today.replace(month=1, day=1)
|
||||
end = _parse_date(payload.get("to")) or today
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
if (end - start).days > 400:
|
||||
raise HTTPException(status_code=400, detail="테스트 데이터는 한 번에 400일까지 만들 수 있습니다.")
|
||||
codes = [m["code"] for m in store.list_marketplaces() if m["enabled"]]
|
||||
_, sync = common.services(request, store)
|
||||
n = sync.generate_samples(start, end, codes)
|
||||
return JSONResponse({"generated": n, "sample_count": store.sample_count()})
|
||||
|
||||
|
||||
@router.post("/api/rekey")
|
||||
def api_rekey(request: Request) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
if not common.key_status()["ok"]:
|
||||
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
||||
creds, _ = common.services(request, store)
|
||||
return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()})
|
||||
@@ -0,0 +1 @@
|
||||
"""② API 인증정보 보안 — 암호화(crypto) · 비밀값 가리기(redact)."""
|
||||
@@ -0,0 +1,161 @@
|
||||
"""쇼핑몰 인증정보 암호화 — AES-256-GCM(인증 암호화) + 키 버전.
|
||||
|
||||
- 라이브러리: `cryptography` 의 AESGCM (직접 만든 알고리즘 없음).
|
||||
- 해시가 아니라 **복호화 가능한** 암호화다 — API Secret/Token 은 나중에 원문이 필요하다.
|
||||
- 마스터 키는 DB 에 두지 않는다. 환경변수(.env)에서만 읽는다.
|
||||
|
||||
APP_ENCRYPTION_KEY 현재 키(32바이트). `openssl rand -hex 32` 의 64자 hex
|
||||
또는 32바이트 base64/base64url 둘 다 받는다.
|
||||
APP_ENCRYPTION_KEY_VERSION 현재 키의 버전 번호(기본 1).
|
||||
APP_ENCRYPTION_KEY_V{n} 키 교체 중 남겨 두는 예전 키(버전 n). 재암호화가
|
||||
끝나면 지운다.
|
||||
|
||||
암호문 형식: ``v{버전}:{base64url(nonce 12바이트 + 암호문 + tag 16바이트)}``
|
||||
|
||||
AAD(추가 인증 데이터)로 "어느 쇼핑몰의 어느 항목"인지를 묶는다
|
||||
(예: ``perf:coupang:secret_key``). DB 에서 암호문을 다른 행/칸으로 옮겨 붙이면
|
||||
복호화가 실패한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Mapping
|
||||
|
||||
KEY_ENV = "APP_ENCRYPTION_KEY"
|
||||
VERSION_ENV = "APP_ENCRYPTION_KEY_VERSION"
|
||||
_OLD_KEY_RE = re.compile(r"^APP_ENCRYPTION_KEY_V(\d+)$")
|
||||
_TOKEN_RE = re.compile(r"^v(\d+):([A-Za-z0-9_\-]+={0,2})$")
|
||||
_NONCE_LEN = 12
|
||||
|
||||
|
||||
class CryptoConfigError(RuntimeError):
|
||||
"""마스터 키가 없거나 형식이 틀림 — 설정 문제."""
|
||||
|
||||
|
||||
class DecryptError(RuntimeError):
|
||||
"""복호화 실패(키 버전 없음/키 바뀜/손상/다른 칸의 암호문). 원문·키는 메시지에 넣지 않는다."""
|
||||
|
||||
|
||||
def _parse_key(raw: str, *, name: str) -> bytes:
|
||||
value = (raw or "").strip()
|
||||
if not value:
|
||||
raise CryptoConfigError(f"{name} 가 비어 있습니다.")
|
||||
if re.fullmatch(r"[0-9a-fA-F]{64}", value):
|
||||
return bytes.fromhex(value)
|
||||
try:
|
||||
padded = value + "=" * (-len(value) % 4)
|
||||
decoded = base64.urlsafe_b64decode(padded.replace("+", "-").replace("/", "_"))
|
||||
except (binascii.Error, ValueError):
|
||||
decoded = b""
|
||||
if len(decoded) == 32:
|
||||
return decoded
|
||||
raise CryptoConfigError(
|
||||
f"{name} 형식이 올바르지 않습니다. 32바이트 키가 필요합니다 "
|
||||
"(`openssl rand -hex 32` 로 만든 64자 hex 권장)."
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KeyRing:
|
||||
"""현재 키 + (교체 중이면) 예전 키들. 키 값은 repr 에 나오지 않는다."""
|
||||
|
||||
current_version: int
|
||||
_keys: Mapping[int, bytes] = field(repr=False)
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, environ: Mapping[str, str] | None = None) -> "KeyRing":
|
||||
env = os.environ if environ is None else environ
|
||||
raw_current = (env.get(KEY_ENV) or "").strip()
|
||||
if not raw_current:
|
||||
raise CryptoConfigError(
|
||||
f"{KEY_ENV} 환경변수가 설정되지 않았습니다. "
|
||||
"`openssl rand -hex 32` 로 값을 만들어 .env 에 넣고 컨테이너를 재기동하세요."
|
||||
)
|
||||
try:
|
||||
version = int((env.get(VERSION_ENV) or "1").strip())
|
||||
except ValueError:
|
||||
raise CryptoConfigError(f"{VERSION_ENV} 는 1 이상의 정수여야 합니다.") from None
|
||||
if version < 1:
|
||||
raise CryptoConfigError(f"{VERSION_ENV} 는 1 이상의 정수여야 합니다.")
|
||||
keys: dict[int, bytes] = {}
|
||||
for name, raw in env.items():
|
||||
m = _OLD_KEY_RE.match(name)
|
||||
if m and (raw or "").strip():
|
||||
keys[int(m.group(1))] = _parse_key(raw, name=name)
|
||||
keys[version] = _parse_key(raw_current, name=KEY_ENV)
|
||||
return cls(current_version=version, _keys=keys)
|
||||
|
||||
@property
|
||||
def versions(self) -> list[int]:
|
||||
return sorted(self._keys)
|
||||
|
||||
def key(self, version: int) -> bytes:
|
||||
try:
|
||||
return self._keys[version]
|
||||
except KeyError:
|
||||
raise DecryptError(
|
||||
f"암호화 키 버전 v{version} 이 서버에 없습니다. "
|
||||
f"{KEY_ENV}_V{version} 환경변수를 확인하세요."
|
||||
) from None
|
||||
|
||||
|
||||
def _aesgcm(key: bytes):
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM # 지연 import
|
||||
|
||||
return AESGCM(key)
|
||||
|
||||
|
||||
def encrypt(plaintext: str, *, aad: str, ring: KeyRing) -> str:
|
||||
"""평문 → ``v{버전}:{...}``. 항상 현재 키로 암호화한다."""
|
||||
if plaintext is None:
|
||||
raise ValueError("암호화할 값이 없습니다.")
|
||||
nonce = os.urandom(_NONCE_LEN)
|
||||
ct = _aesgcm(ring.key(ring.current_version)).encrypt(
|
||||
nonce, plaintext.encode("utf-8"), aad.encode("utf-8")
|
||||
)
|
||||
body = base64.urlsafe_b64encode(nonce + ct).decode("ascii")
|
||||
return f"v{ring.current_version}:{body}"
|
||||
|
||||
|
||||
def key_version_of(token: str) -> int:
|
||||
m = _TOKEN_RE.match(token or "")
|
||||
if not m:
|
||||
raise DecryptError("암호문 형식이 올바르지 않습니다.")
|
||||
return int(m.group(1))
|
||||
|
||||
|
||||
def decrypt(token: str, *, aad: str, ring: KeyRing) -> str:
|
||||
"""``v{버전}:{...}`` → 평문. 실패 원인은 알려 주되 값은 절대 담지 않는다."""
|
||||
m = _TOKEN_RE.match(token or "")
|
||||
if not m:
|
||||
raise DecryptError("암호문 형식이 올바르지 않습니다.")
|
||||
version = int(m.group(1))
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(m.group(2))
|
||||
except (binascii.Error, ValueError):
|
||||
raise DecryptError("암호문이 손상되었습니다.") from None
|
||||
if len(raw) <= _NONCE_LEN:
|
||||
raise DecryptError("암호문이 손상되었습니다.")
|
||||
from cryptography.exceptions import InvalidTag # 지연 import
|
||||
|
||||
try:
|
||||
pt = _aesgcm(ring.key(version)).decrypt(raw[:_NONCE_LEN], raw[_NONCE_LEN:], aad.encode("utf-8"))
|
||||
except InvalidTag:
|
||||
raise DecryptError(
|
||||
"복호화하지 못했습니다. 마스터 키가 바뀌었거나 값이 손상되었습니다. "
|
||||
"인증정보를 다시 입력해야 할 수 있습니다."
|
||||
) from None
|
||||
return pt.decode("utf-8")
|
||||
|
||||
|
||||
def needs_reencrypt(token: str, ring: KeyRing) -> bool:
|
||||
"""현재 키 버전이 아닌 암호문인가(키 교체 후 재암호화 대상)."""
|
||||
try:
|
||||
return key_version_of(token) != ring.current_version
|
||||
except DecryptError:
|
||||
return False
|
||||
@@ -0,0 +1,95 @@
|
||||
"""비밀값 가리기 — 오류 메시지·로그·원본 데이터(raw_data)에 인증정보가 남지 않게.
|
||||
|
||||
원칙은 "애초에 남기지 않는다"이고, 이 모듈은 그래도 섞여 들어올 수 있는 값을
|
||||
걸러내는 마지막 방어선이다.
|
||||
|
||||
- `redact_text(text, known_secrets)`: 문자열 안의 비밀값을 가린다.
|
||||
· 알고 있는 실제 비밀값(저장된 인증정보 원문)은 어디에 있든 통째로 치환
|
||||
· "Authorization: ...", "Bearer ...", "Basic ...", 쿠키
|
||||
· key=value / "key": "value" 형태에서 key 가 비밀 이름(password, secret, token …)인 값
|
||||
· 길이 제한(기본 300자)
|
||||
- `redact_mapping(obj)`: dict/list 를 깊이 복사하며 비밀 이름 키의 값을 가린다.
|
||||
- `mask(value)`: 꼭 보여야 할 때 앞 4자 + **** + 뒤 4자(짧으면 전부 가림).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Iterable
|
||||
|
||||
MASK = "****"
|
||||
|
||||
# 이름만 보고 비밀로 판단하는 키(대소문자 무시, 부분 일치).
|
||||
_SENSITIVE_NAME = re.compile(
|
||||
r"(pass(word|wd)?|pwd|secret|token|api[_\-]?key|access[_\-]?key|private[_\-]?key|"
|
||||
r"authorization|auth[_\-]?header|cookie|session|signature|credential|client[_\-]?secret|"
|
||||
r"refresh|bearer|x[_\-]?api)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# 헤더 이름 뒤의 "인증 방식 + 값" 한 덩어리(예: Bearer xxx, CEA algorithm=…, signature=…).
|
||||
_AUTH_HEADER = re.compile(
|
||||
r"(?i)\b(authorization|proxy-authorization)[\"']?\s*[:=]\s*[\"']?"
|
||||
r"(?:(?:bearer|basic|digest|cea|hmac\S*)\s+)?[^\s\"',;}\]]+"
|
||||
)
|
||||
_BEARER = re.compile(r"(?i)\b(bearer|basic|cea)\s+[A-Za-z0-9._~+/=\-]{6,}")
|
||||
_COOKIE = re.compile(r"(?i)\b(set-cookie|cookie)\s*[:=]\s*[^\r\n]+")
|
||||
_KV = re.compile(
|
||||
r"""(?ix)
|
||||
(["']?) # 여는 따옴표(선택)
|
||||
([A-Za-z0-9_\-\.]*? # 키 이름
|
||||
(?:pass(?:word|wd)?|pwd|secret|token|api[_\-]?key|access[_\-]?key|
|
||||
private[_\-]?key|signature|credential|client[_\-]?secret|refresh)
|
||||
[A-Za-z0-9_\-\.]*)
|
||||
\1\s*[:=]\s*
|
||||
(["']?)([^"'&\s,;}\]]+)\3
|
||||
"""
|
||||
)
|
||||
|
||||
DEFAULT_MAX_LEN = 300
|
||||
|
||||
|
||||
def is_sensitive_name(name: str) -> bool:
|
||||
return bool(_SENSITIVE_NAME.search(name or ""))
|
||||
|
||||
|
||||
def mask(value: str | None) -> str:
|
||||
v = value or ""
|
||||
if len(v) < 12:
|
||||
return MASK
|
||||
return f"{v[:4]}{MASK}{v[-4:]}"
|
||||
|
||||
|
||||
def redact_text(
|
||||
text: Any,
|
||||
known_secrets: Iterable[str] = (),
|
||||
*,
|
||||
max_len: int = DEFAULT_MAX_LEN,
|
||||
) -> str:
|
||||
s = "" if text is None else str(text)
|
||||
for secret in sorted({x for x in known_secrets if x and len(x) >= 4}, key=len, reverse=True):
|
||||
s = s.replace(secret, MASK)
|
||||
s = _AUTH_HEADER.sub(lambda m: f"{m.group(1)}: {MASK}", s)
|
||||
s = _COOKIE.sub(lambda m: f"{m.group(1)}: {MASK}", s)
|
||||
s = _BEARER.sub(lambda m: f"{m.group(1)} {MASK}", s)
|
||||
s = _KV.sub(lambda m: f"{m.group(1)}{m.group(2)}{m.group(1)}={MASK}", s)
|
||||
if max_len and len(s) > max_len:
|
||||
s = s[:max_len] + "…"
|
||||
return s
|
||||
|
||||
|
||||
def redact_mapping(obj: Any, known_secrets: Iterable[str] = ()) -> Any:
|
||||
secrets = tuple(known_secrets)
|
||||
if isinstance(obj, dict):
|
||||
out: dict[str, Any] = {}
|
||||
for k, v in obj.items():
|
||||
if is_sensitive_name(str(k)):
|
||||
out[k] = MASK
|
||||
else:
|
||||
out[k] = redact_mapping(v, secrets)
|
||||
return out
|
||||
if isinstance(obj, (list, tuple)):
|
||||
return [redact_mapping(v, secrets) for v in obj]
|
||||
if isinstance(obj, str):
|
||||
return redact_text(obj, secrets, max_len=0) if secrets else obj
|
||||
return obj
|
||||
@@ -0,0 +1,196 @@
|
||||
"""① 수집 서비스 — 쇼핑몰 API → 어댑터 → 공통 사건 → DB. 화면(버튼)과 분리된 공통 로직.
|
||||
|
||||
- 버튼(매출 업데이트)·연결 테스트·향후 cron/worker 모두 이 서비스를 부른다.
|
||||
- 같은 쇼핑몰은 동시에 한 번만(perf_sync_runs 의 running 부분 유니크 인덱스).
|
||||
- 쇼핑몰 하나가 실패해도 나머지는 계속한다. 실패한 쇼핑몰만 상태가 오류로 바뀐다.
|
||||
- 오류 문구·원본 데이터는 비밀값을 가린 뒤에만 저장/로그한다.
|
||||
|
||||
매출 기준일(sales_date) — 한 곳에서만 정한다(`sales_date_for`):
|
||||
결제(SALE) = 결제일(payment_date, 없으면 event_date)
|
||||
취소/반품 = 발생일(event_date) — 지난 실적이 나중에 바뀌지 않게
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import asdict
|
||||
from datetime import date, timedelta
|
||||
from typing import Any, Iterable
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError, MarketplaceAdapter, SaleEvent
|
||||
from .adapters.registry import all_adapters, get_adapter
|
||||
from .credentials import CredentialService
|
||||
from .security.crypto import CryptoConfigError, DecryptError
|
||||
from .security.redact import redact_mapping, redact_text
|
||||
|
||||
logger = logging.getLogger("performance.sync")
|
||||
|
||||
DEFAULT_SYNC_DAYS = 7
|
||||
|
||||
|
||||
def sync_days() -> int:
|
||||
try:
|
||||
return max(1, min(90, int(os.getenv("PERFORMANCE_SYNC_DAYS", str(DEFAULT_SYNC_DAYS)))))
|
||||
except ValueError:
|
||||
return DEFAULT_SYNC_DAYS
|
||||
|
||||
|
||||
def sales_date_for(ev: SaleEvent) -> date:
|
||||
if ev.event_type == "SALE":
|
||||
return ev.payment_date or ev.event_date
|
||||
return ev.event_date
|
||||
|
||||
|
||||
def event_row(ev: SaleEvent, known_secrets: Iterable[str] = ()) -> dict[str, Any]:
|
||||
row = asdict(ev)
|
||||
row["sales_date"] = sales_date_for(ev)
|
||||
row["raw"] = redact_mapping(ev.raw or {}, known_secrets)
|
||||
return row
|
||||
|
||||
|
||||
class SyncService:
|
||||
def __init__(self, store: Any, creds: CredentialService, *, app_state: Any = None) -> None:
|
||||
self._store = store
|
||||
self._creds = creds
|
||||
self._app_state = app_state
|
||||
|
||||
def _ctx(self, adapter: MarketplaceAdapter, *, overrides: dict[str, str] | None = None,
|
||||
persist: bool = True, user: str = "") -> AdapterContext:
|
||||
acc = self._creds.accessor(adapter.code, overrides=overrides, persist=persist, user=user)
|
||||
return AdapterContext(code=adapter.code, credentials=acc, app_state=self._app_state)
|
||||
|
||||
@staticmethod
|
||||
def _failure(exc: Exception, ctx: AdapterContext | None) -> tuple[str, str]:
|
||||
known = ctx.credentials.known_secrets() if ctx is not None else []
|
||||
if isinstance(exc, AdapterError):
|
||||
return exc.status, redact_text(exc.message, known)
|
||||
if isinstance(exc, (DecryptError, CryptoConfigError)):
|
||||
return "not_configured", redact_text(str(exc), known)
|
||||
return "api_error", redact_text(f"예상하지 못한 오류: {type(exc).__name__}: {exc}", known)
|
||||
|
||||
# ── 연결 테스트 ─────────────────────────────────────────
|
||||
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> dict[str, Any]:
|
||||
"""values 를 주면 저장하지 않은 새 입력값으로 시험(저장된 상태는 바꾸지 않음)."""
|
||||
adapter = get_adapter(code)
|
||||
if adapter is None:
|
||||
return {"ok": False, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
||||
unsaved = bool(values)
|
||||
ctx = None
|
||||
try:
|
||||
ctx = self._ctx(adapter, overrides=values, persist=not unsaved, user=user)
|
||||
message = adapter.test_connection(ctx)
|
||||
status, ok = "ok", True
|
||||
except Exception as exc: # noqa: BLE001 — 어떤 오류든 상태로 바꿔 화면에 보여 준다
|
||||
status, message = self._failure(exc, ctx)
|
||||
ok = False
|
||||
logger.info("performance test %s: %s %s", code, status, message)
|
||||
if not unsaved:
|
||||
self._store.record_test(code, status=status, ok=ok, error="" if ok else message)
|
||||
return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status),
|
||||
"message": message, "unsaved": unsaved}
|
||||
|
||||
# ── 동기화 ──────────────────────────────────────────────
|
||||
def sync_marketplace(self, code: str, start: date, end: date, *, trigger: str = "manual",
|
||||
user: str = "") -> dict[str, Any]:
|
||||
adapter = get_adapter(code)
|
||||
result: dict[str, Any] = {"code": code, "ok": False, "skipped": False, "fetched": 0, "upserted": 0}
|
||||
if adapter is None:
|
||||
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
||||
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
|
||||
if run_id is None:
|
||||
return {**result, "skipped": True, "status": "running", "message": "이미 업데이트 중입니다."}
|
||||
ctx = None
|
||||
try:
|
||||
ctx = self._ctx(adapter, user=user)
|
||||
fetched, events = adapter.collect(ctx, start, end)
|
||||
known = ctx.credentials.known_secrets()
|
||||
rows = [event_row(ev, known) for ev in events]
|
||||
# 다른 쇼핑몰 열로 보낸 사건 — 등록된 쇼핑몰이 아니면 이 쇼핑몰 열에 둔다(합계가 빠지지 않게).
|
||||
registered = {m["code"] for m in self._store.list_marketplaces()}
|
||||
for r in rows:
|
||||
if r.get("marketplace_code") not in registered:
|
||||
r["marketplace_code"] = code
|
||||
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, id_prefix=adapter.event_prefix)
|
||||
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,
|
||||
"message": f"{upserted}건 반영"}
|
||||
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
|
||||
status, message = self._failure(exc, ctx)
|
||||
logger.warning("performance sync %s failed: %s %s", code, status, message)
|
||||
self._store.finish_run(run_id, ok=False, error=message)
|
||||
self._store.record_sync(code, status=status, ok=False, error=message)
|
||||
return {**result, "status": status, "label": STATUS_LABELS.get(status, status), "message": message}
|
||||
|
||||
def sync_all(self, *, start: date | None = None, end: date | None = None, codes: list[str] | None = None,
|
||||
trigger: str = "manual", user: str = "") -> list[dict[str, Any]]:
|
||||
end = end or today_kst()
|
||||
start = start or (end - timedelta(days=sync_days() - 1))
|
||||
enabled = {m["code"] for m in self._store.list_marketplaces() if m["enabled"]}
|
||||
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, *, to: date | None = None, 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, 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}
|
||||
|
||||
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
|
||||
|
||||
n = 0
|
||||
for code in codes:
|
||||
n += self._store.upsert_events(code, (event_row(ev) for ev in mock.generate(code, start, end)),
|
||||
is_sample=True)
|
||||
return n
|
||||
@@ -0,0 +1,7 @@
|
||||
{# 실적 모듈 탭 — 설정 탭은 관리자에게만(서버도 관리자만 허용). #}
|
||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
||||
{% if is_admin %}
|
||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">설정</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
@@ -0,0 +1,242 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930e" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
|
||||
{%- macro m3(m) -%}
|
||||
<span class="v v-gross">{{ won(m.gross) }}</span><span class="v v-commission">{{ won(m.commission) }}</span><span class="v v-net">{{ won(m.net) }}</span>
|
||||
{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
<section class="perf" id="perf-dash" data-metric="{{ metric }}">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<!-- ── 기간 · 필터 · 업데이트 ── -->
|
||||
<div class="perf-toolbar">
|
||||
<div class="perf-quick" role="group" aria-label="기간 선택">
|
||||
{% for q in nav.quick %}
|
||||
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
|
||||
{% endfor %}
|
||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||
</div>
|
||||
|
||||
<div class="perf-nav">
|
||||
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
|
||||
<span class="perf-nav-label">{{ period.label }}</span>
|
||||
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
|
||||
</div>
|
||||
|
||||
<form class="perf-custom" id="perf-custom" method="get" action="/performance/"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||
<input type="hidden" name="period" value="custom" />
|
||||
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
|
||||
{% for c in codes %}{% if not selected_all %}<input type="hidden" name="m" value="{{ c }}" />{% endif %}{% endfor %}
|
||||
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||
</form>
|
||||
|
||||
<details class="perf-filter" id="perf-filter">
|
||||
<summary class="erp-btn erp-btn-outline">쇼핑몰: {% if selected_all %}전체{% else %}{{ codes | length }}곳{% endif %}</summary>
|
||||
<form class="perf-filter-pop" method="get" action="/performance/">
|
||||
<input type="hidden" name="period" value="{{ period_kind }}" />
|
||||
{% if period_kind == 'custom' %}
|
||||
<input type="hidden" name="from" value="{{ period.start.isoformat() }}" />
|
||||
<input type="hidden" name="to" value="{{ period.end.isoformat() }}" />
|
||||
{% else %}
|
||||
<input type="hidden" name="d" value="{{ period.anchor.isoformat() }}" />
|
||||
{% endif %}
|
||||
{% for c in all_codes %}
|
||||
<label class="perf-check"><input type="checkbox" name="m" value="{{ c }}"{% if c in codes %} checked{% endif %} /> {{ names[c] }}</label>
|
||||
{% endfor %}
|
||||
<div class="perf-filter-act">
|
||||
<button type="button" class="erp-btn erp-btn-ghost" data-perf-check-all>전체</button>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">적용</button>
|
||||
</div>
|
||||
</form>
|
||||
</details>
|
||||
|
||||
<div class="perf-update">
|
||||
<span class="perf-muted" id="perf-last-update">마지막 업데이트
|
||||
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="perf-sync-btn"{% if running %} disabled{% endif %}
|
||||
title="지금 보고 있는 기간({{ period.label }}, 오늘까지)의 매출을 쇼핑몰에서 다시 가져옵니다">
|
||||
{% if running %}업데이트 중…{% else %}매출 업데이트{% endif %}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if no_marketplaces %}
|
||||
<div class="perf-notice">매출에 포함된 쇼핑몰이 없습니다. {% if is_admin %}<a href="/performance/settings">실적 설정</a>에서 쇼핑몰 사용을 켜세요.{% endif %}</div>
|
||||
{% endif %}
|
||||
|
||||
{% if problems %}
|
||||
<div class="perf-notice is-warn" id="perf-problems">
|
||||
<b>연결 오류</b>
|
||||
{% for p in problems %}<span class="perf-problem" title="{{ p.error }}">{{ p.name }} · {{ p.label }}</span>{% endfor %}
|
||||
<span class="perf-muted">— 해당 쇼핑몰은 마지막 정상 수집분까지만 반영됩니다. 나머지는 정상입니다.</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
||||
|
||||
<!-- ── KPI ── -->
|
||||
<div class="perf-kpis">
|
||||
{% for k in kpis %}
|
||||
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
||||
<div class="perf-kpi-label">{{ k.label }}</div>
|
||||
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
|
||||
<div class="perf-kpi-delta">
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- ── 일자 × 쇼핑몰 ── -->
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
|
||||
<div class="perf-metric" role="group" aria-label="표시 기준">
|
||||
<button type="button" class="perf-seg" data-metric="gross">총매출</button>
|
||||
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
|
||||
<button type="button" class="perf-seg" data-metric="net">수수료 차감 매출</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="erp-table-wrap perf-table-wrap">
|
||||
<table class="perf-table perf-main">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
{% for c in codes %}<th title="{{ names[c] }}">{{ short_names[c] }}</th>{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in table %}
|
||||
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row"{% if r.holiday %} title="{{ r.holiday }}"{% endif %}>
|
||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||
</th>
|
||||
{% for c in codes %}
|
||||
{% set m = r.cells[c] %}
|
||||
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
|
||||
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}</td>
|
||||
{% endfor %}
|
||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── 그래프 ── -->
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 매출 추이</h2>
|
||||
<span class="perf-muted perf-metric-name"></span></div>
|
||||
<div class="perf-chart" id="perf-chart-daily"></div>
|
||||
</div>
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">쇼핑몰별 비중</h2>
|
||||
<span class="perf-muted">{{ period.label }}</span></div>
|
||||
<div class="perf-chart" id="perf-chart-share"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── 월 누적 · 연간 누적 ── -->
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 쇼핑몰별 누적 실적</h2></div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table">
|
||||
<thead><tr><th class="perf-th-label">쇼핑몰</th><th>총매출</th><th>수수료</th><th>수수료 차감 매출</th><th>매출 비중</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in month.rows %}
|
||||
<tr>
|
||||
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
|
||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||
<td class="perf-num">{{ won(r.commission) }}</td>
|
||||
<td class="perf-num">{{ won(r.net) }}</td>
|
||||
<td class="perf-num perf-share">
|
||||
{% if r.share is not none %}<span class="perf-bar" style="--w: {{ [r.share, 0] | max }}%"></span>{{ "%.1f" | format(r.share) }}%{% else %}<span class="perf-zero">–</span>{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="perf-row-total">
|
||||
<th class="perf-td-label" scope="row">합계</th>
|
||||
<td class="perf-num">{{ won(month.total.gross) }}</td>
|
||||
<td class="perf-num">{{ won(month.total.commission) }}</td>
|
||||
<td class="perf-num">{{ won(month.total.net) }}</td>
|
||||
<td class="perf-num">{% if month.total.share is not none %}100%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
|
||||
<div class="perf-year-sum">
|
||||
<div><span>총매출</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
|
||||
<div><span>수수료</span><b>₩{{ "{:,}".format(year.total.commission) }}</b></div>
|
||||
<div><span>수수료 차감 매출</span><b>₩{{ "{:,}".format(year.total.net) }}</b></div>
|
||||
</div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-year">
|
||||
<thead><tr><th class="perf-th-label">월</th><th>총매출</th><th>수수료</th><th>수수료 차감 매출</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in year.rows %}
|
||||
<tr class="{% if r.future %}is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row">{{ r.label }}</th>
|
||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||
<td class="perf-num">{{ won(r.commission) }}</td>
|
||||
<td class="perf-num">{{ won(r.net) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="perf-row-total">
|
||||
<th class="perf-td-label" scope="row">합계</th>
|
||||
<td class="perf-num">{{ won(year.total.gross) }}</td>
|
||||
<td class="perf-num">{{ won(year.total.commission) }}</td>
|
||||
<td class="perf-num">{{ won(year.total.net) }}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="perf-foot perf-muted">
|
||||
매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며
|
||||
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<script type="application/json" id="perf-data">{{ {
|
||||
"names": names,
|
||||
"codes": codes,
|
||||
"daily": chart_daily,
|
||||
"share": chart_share,
|
||||
"period_kind": period_kind,
|
||||
"period_start": period.start.isoformat(),
|
||||
"period_end": period.end.isoformat(),
|
||||
"today": today
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,173 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930e" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
<section class="perf perf-settings" id="perf-settings">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
{% if not key_info.ok %}
|
||||
<div class="perf-notice is-warn">
|
||||
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
|
||||
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">쇼핑몰 설정</h2>
|
||||
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
|
||||
</div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-set-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">쇼핑몰</th>
|
||||
<th>사용</th>
|
||||
<th>매출 집계</th>
|
||||
<th>수수료율</th>
|
||||
<th>API 설정</th>
|
||||
<th>연결 상태</th>
|
||||
<th>마지막 동기화</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in rows %}
|
||||
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
|
||||
<th class="perf-td-label" scope="row">{{ r.name }}</th>
|
||||
<td class="perf-center">
|
||||
<label class="perf-switch" title="사용 여부">
|
||||
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
|
||||
</label>
|
||||
</td>
|
||||
<td class="perf-center">
|
||||
<label class="perf-switch" title="매출 집계에 포함">
|
||||
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
||||
</label>
|
||||
</td>
|
||||
<td class="perf-rate-cell">
|
||||
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
|
||||
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
|
||||
</td>
|
||||
<td>
|
||||
{% if r.shared %}<span class="perf-pill">공통 연동</span>
|
||||
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
||||
{% else %}<span class="perf-pill">미설정</span>{% endif %}
|
||||
{% if r.via_cafe24 %}<span class="perf-pill is-ok" title="카페24 마켓 통합관리로 들어온 이 쇼핑몰 주문을 카페24 수집 때 함께 반영합니다">카페24 경유</span>{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
<span class="perf-status st-{{ r.status }}"
|
||||
title="마지막 연결 테스트: {{ when(r.last_test_at) }}{% if r.last_error %} 최근 오류({{ when(r.last_error_at) }}): {{ r.last_error }}{% endif %}">
|
||||
<i></i>{{ r.status_label }}</span>
|
||||
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
||||
<td class="perf-nowrap">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="perf-foot perf-muted">
|
||||
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
||||
상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
||||
<dl class="perf-dl">
|
||||
<dt>마스터 키</dt>
|
||||
<dd>{% if key_info.ok %}<span class="perf-pill is-ok">설정됨 · 현재 v{{ key_info.current_version }}</span>
|
||||
{% set olds = key_info.versions | reject('equalto', key_info.current_version) | list %}
|
||||
{% if olds %}<span class="perf-muted">(예전 키 v{{ olds | join(', v') }} 보관 중)</span>{% endif %}
|
||||
{% else %}<span class="perf-pill is-bad">미설정</span>{% endif %}</dd>
|
||||
<dt>저장된 항목</dt>
|
||||
<dd>{% for v, n in key_versions_in_use.items() %}v{{ v }}: {{ n }}개{% if not loop.last %}, {% endif %}{% else %}<span class="perf-muted">없음</span>{% endfor %}</dd>
|
||||
</dl>
|
||||
{% if stale_key_rows %}
|
||||
<p class="perf-notice is-warn">예전 키로 암호화된 항목이 {{ stale_key_rows }}개 있습니다.
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-rekey">현재 키로 다시 암호화</button></p>
|
||||
{% endif %}
|
||||
<p class="perf-foot perf-muted">
|
||||
API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
|
||||
서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">과거 매출 가져오기</h2></div>
|
||||
<p class="perf-muted">[매출 업데이트]는 최근 며칠만 가져옵니다. 처음 연동했거나 빠진 기간이 있으면 기간을 지정해 한 번에
|
||||
가져오세요(연동된 쇼핑몰만, 최대 366일). 같은 주문은 덮어써서 여러 번 해도 중복되지 않습니다.</p>
|
||||
<div class="perf-sample-form">
|
||||
<input class="erp-input perf-date" type="date" id="perf-backfill-from" value="{{ default_sample_from }}" />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" id="perf-backfill-to" value="{{ default_sample_to }}" />
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="perf-backfill">가져오기</button>
|
||||
</div>
|
||||
<div class="perf-notice" id="perf-backfill-result" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card perf-card-wide">
|
||||
<div class="perf-card-head"><h2 class="perf-h">11번가 원본 데이터 확인</h2></div>
|
||||
<p class="perf-muted">11번가 셀러 API 의 주문·클레임·정산 조회 주소를 기간(최대 31일)으로 실제 불러, 어느 주소가 동작하는지와
|
||||
받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 주문 목록은 지금 그 상태인 주문만, 정산은 정산일 기준일 수 있어
|
||||
매출이 있던 날부터 넉넉히(예: 3주) 잡아 주세요. 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
|
||||
매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.</p>
|
||||
<div class="perf-sample-form">
|
||||
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" id="perf-probe-to" value="{{ default_sample_to }}" />
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe" data-code="elevenst">불러오기</button>
|
||||
</div>
|
||||
<div id="perf-probe-result"></div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card perf-card-wide">
|
||||
<div class="perf-card-head"><h2 class="perf-h">카페24 매출 대조</h2></div>
|
||||
<p class="perf-muted">카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
|
||||
바로 합산하며(저장하지 않음), 자체몰과 다른 마켓 연동 주문을 나눠 보여 줍니다.</p>
|
||||
<div class="perf-sample-form">
|
||||
<input class="erp-input perf-date" type="date" id="perf-recon-date" value="{{ default_sample_to }}" />
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-recon">대조</button>
|
||||
</div>
|
||||
<div id="perf-recon-result"></div>
|
||||
|
||||
<h3 class="perf-h" style="margin:18px 0 6px">일별 한 번에 비교</h3>
|
||||
<p class="perf-muted">카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다.
|
||||
[API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과
|
||||
규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.</p>
|
||||
<textarea class="erp-input perf-paste" id="perf-daily-paste" rows="5"
|
||||
placeholder="2026-09-29(화) 47 116 2,475,300 … 2,477,800 158,000 2,319,800"></textarea>
|
||||
<div class="perf-sample-form" style="margin-top:6px">
|
||||
<label class="perf-muted"><input type="checkbox" id="perf-daily-live" /> API 값도 계산(느림)</label>
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-daily-check">비교</button>
|
||||
</div>
|
||||
<div id="perf-daily-result"></div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">테스트 데이터</h2>
|
||||
<span class="perf-muted">현재 {{ "{:,}".format(sample_count) }}건</span></div>
|
||||
<p class="perf-muted">실제 API 연동 전 화면 확인용 모의 매출입니다(사용 중인 쇼핑몰 대상). 실제 데이터와 구분되어 한 번에 지울 수 있습니다.</p>
|
||||
<div class="perf-sample-form">
|
||||
<input class="erp-input perf-date" type="date" id="perf-sample-from" value="{{ default_sample_from }}" />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" id="perf-sample-to" value="{{ default_sample_to }}" />
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-sample-gen">생성</button>
|
||||
<button type="button" class="erp-btn erp-btn-danger" id="perf-sample-del"{% if not sample_count %} disabled{% endif %}>모두 삭제</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,977 @@
|
||||
"""실적 모듈 테스트 — 암호화·가리기·계산·인증정보·동기화. DB/네트워크 없이 가짜 저장소로.
|
||||
|
||||
python -m app.modules.performance.tests.test_performance
|
||||
또는 pytest 로 실행 가능.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import date, timedelta
|
||||
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,
|
||||
SaleEvent,
|
||||
)
|
||||
from app.modules.performance.adapters.registry import all_adapters
|
||||
from app.modules.performance.credentials import CredentialService, aad_for
|
||||
from app.modules.performance.security import crypto
|
||||
from app.modules.performance.security.redact import MASK, mask, redact_mapping, redact_text
|
||||
from app.modules.performance.sync import SyncService, event_row, sales_date_for
|
||||
|
||||
KEY1 = "11" * 32
|
||||
KEY2 = "22" * 32
|
||||
|
||||
|
||||
def ring(version: int = 1, **old: str) -> crypto.KeyRing:
|
||||
env = {"APP_ENCRYPTION_KEY": KEY1 if version == 1 else KEY2, "APP_ENCRYPTION_KEY_VERSION": str(version)}
|
||||
env.update(old)
|
||||
return crypto.KeyRing.from_env(env)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 암호화
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_crypto_roundtrip_and_format():
|
||||
r = ring()
|
||||
token = crypto.encrypt("my-secret-value", aad="perf:coupang:secret_key", ring=r)
|
||||
assert token.startswith("v1:")
|
||||
assert "my-secret-value" not in token
|
||||
assert crypto.decrypt(token, aad="perf:coupang:secret_key", ring=r) == "my-secret-value"
|
||||
# 같은 평문도 매번 다른 암호문(nonce)
|
||||
assert token != crypto.encrypt("my-secret-value", aad="perf:coupang:secret_key", ring=r)
|
||||
|
||||
|
||||
def test_crypto_rejects_wrong_aad_tamper_and_key():
|
||||
r = ring()
|
||||
token = crypto.encrypt("abc", aad="perf:coupang:secret_key", ring=r)
|
||||
for bad in (lambda: crypto.decrypt(token, aad="perf:naver:client_secret", ring=r),
|
||||
lambda: crypto.decrypt(token[:-2] + ("A" if token[-2] != "A" else "B") + token[-1], aad="perf:coupang:secret_key", ring=r),
|
||||
lambda: crypto.decrypt(token, aad="perf:coupang:secret_key",
|
||||
ring=crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY2}))):
|
||||
try:
|
||||
bad()
|
||||
except crypto.DecryptError as exc:
|
||||
assert "abc" not in str(exc)
|
||||
else:
|
||||
raise AssertionError("복호화가 실패해야 합니다")
|
||||
|
||||
|
||||
def test_crypto_missing_or_bad_key():
|
||||
for env in ({}, {"APP_ENCRYPTION_KEY": "short"}, {"APP_ENCRYPTION_KEY": KEY1, "APP_ENCRYPTION_KEY_VERSION": "0"}):
|
||||
try:
|
||||
crypto.KeyRing.from_env(env)
|
||||
except crypto.CryptoConfigError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(f"설정 오류여야 합니다: {list(env)}")
|
||||
# base64 32바이트 키도 받는다
|
||||
import base64
|
||||
b64 = base64.urlsafe_b64encode(bytes(range(32))).decode()
|
||||
assert crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": b64}).current_version == 1
|
||||
assert "11" * 4 not in repr(ring()) # 키 값이 repr 에 나오지 않음
|
||||
|
||||
|
||||
def test_crypto_rotation():
|
||||
old = ring(1)
|
||||
token = crypto.encrypt("rotate-me", aad="a", ring=old)
|
||||
new = ring(2, APP_ENCRYPTION_KEY_V1=KEY1)
|
||||
assert new.versions == [1, 2]
|
||||
assert crypto.needs_reencrypt(token, new)
|
||||
assert crypto.decrypt(token, aad="a", ring=new) == "rotate-me"
|
||||
token2 = crypto.encrypt("rotate-me", aad="a", ring=new)
|
||||
assert token2.startswith("v2:") and not crypto.needs_reencrypt(token2, new)
|
||||
try:
|
||||
crypto.decrypt(token, aad="a", ring=ring(2)) # 예전 키를 안 남기면 실패
|
||||
except crypto.DecryptError as exc:
|
||||
assert "v1" in str(exc)
|
||||
else:
|
||||
raise AssertionError("예전 키 없이는 복호화 실패해야 합니다")
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 가리기
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_redact():
|
||||
secret = "SK-live-9f8e7d6c5b4a"
|
||||
msg = f"401 Unauthorized secret={secret} Authorization: Bearer abcdef123456 token=zzz999 other=ok"
|
||||
out = redact_text(msg, [secret])
|
||||
assert secret not in out and "abcdef123456" not in out and "zzz999" not in out
|
||||
assert "other=ok" in out and MASK in out
|
||||
assert "Cookie" not in redact_text("Cookie: sid=abc; x=1").replace(f"Cookie: {MASK}", "")
|
||||
j = redact_text('{"access_token": "tok-123456", "vendor": "A001"}')
|
||||
assert "tok-123456" not in j and "A001" in j
|
||||
data = redact_mapping({"order": "1", "headers": {"Authorization": "x", "X-Api-Key": "y"}, "items": [{"password": "p"}]})
|
||||
assert data["order"] == "1" and data["headers"]["Authorization"] == MASK
|
||||
assert data["headers"]["X-Api-Key"] == MASK and data["items"][0]["password"] == MASK
|
||||
assert mask("ABCDEFGHIJKL1234") == "ABCD****1234" and mask("short") == MASK
|
||||
assert len(redact_text("x" * 1000)) <= 301
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 계산
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_commission_rounding():
|
||||
assert calc.commission(1_000_000, Decimal("10")) == 100_000
|
||||
assert calc.commission(12_345, Decimal("10.8")) == 1_333 # 1333.26 → 1333
|
||||
assert calc.commission(15, Decimal("10")) == 2 # 1.5 → 2 (half up)
|
||||
assert calc.commission(-15, Decimal("10")) == -2 # 취소도 같은 규칙
|
||||
assert calc.commission(100_000, Decimal("15.35")) == 15_350
|
||||
assert calc.commission(0, Decimal("10")) == 0 and calc.commission(1000, Decimal("0")) == 0
|
||||
m = calc.Money(gross=1_000_000, commission=100_000)
|
||||
assert m.net == 900_000
|
||||
|
||||
|
||||
def test_rate_history():
|
||||
rates = {"coupang": [(date(2026, 1, 1), Decimal("8")), (date(2026, 7, 1), Decimal("10"))]}
|
||||
assert calc.rate_on(rates, "coupang", date(2025, 12, 31)) == 0
|
||||
assert calc.rate_on(rates, "coupang", date(2026, 6, 30)) == 8
|
||||
assert calc.rate_on(rates, "coupang", date(2026, 7, 1)) == 10
|
||||
assert calc.rate_on(rates, "naver", date(2026, 7, 1)) == 0
|
||||
cells = calc.build_cells({(date(2026, 6, 30), "coupang"): 100_000, (date(2026, 7, 1), "coupang"): 100_000}, rates)
|
||||
assert cells[(date(2026, 6, 30), "coupang")].commission == 8_000
|
||||
assert cells[(date(2026, 7, 1), "coupang")].commission == 10_000
|
||||
|
||||
|
||||
def test_periods():
|
||||
wed = date(2026, 9, 30)
|
||||
p = calc.resolve_period("week", wed)
|
||||
assert (p.start, p.end) == (date(2026, 9, 28), date(2026, 10, 4)) # 월~일
|
||||
assert p.start.weekday() == 0 and p.end.weekday() == 6 and p.days == 7
|
||||
assert p.prev_anchor == date(2026, 9, 21)
|
||||
m = calc.resolve_period("month", date(2026, 2, 15))
|
||||
assert (m.start, m.end) == (date(2026, 2, 1), date(2026, 2, 28))
|
||||
y = calc.resolve_period("year", wed)
|
||||
assert (y.start, y.end) == (date(2026, 1, 1), date(2026, 12, 31))
|
||||
c = calc.resolve_period("custom", wed, custom_from=date(2026, 9, 29), custom_to=date(2026, 9, 1))
|
||||
assert (c.start, c.end) == (date(2026, 9, 1), date(2026, 9, 29))
|
||||
# 진행 중인 주 — 전주 같은 요일까지만 비교
|
||||
s, e, label = p.compare_range(today=wed)
|
||||
assert (s, e) == (date(2026, 9, 21), date(2026, 9, 23)) and label.startswith("전주")
|
||||
# 지난 주 — 전주 전체
|
||||
s, e, _ = calc.resolve_period("week", date(2026, 9, 20)).compare_range(today=wed)
|
||||
assert (s, e) == (date(2026, 9, 7), date(2026, 9, 13))
|
||||
# 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
|
||||
s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31))
|
||||
assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28))
|
||||
assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None
|
||||
|
||||
|
||||
def _cells_for(days, codes, amount=10_000):
|
||||
return calc.build_cells({(d, c): amount for d in days for c in codes}, {"a": [(date(2000, 1, 1), Decimal("10"))]})
|
||||
|
||||
|
||||
def test_main_table_week():
|
||||
p = calc.resolve_period("week", date(2026, 9, 30))
|
||||
days = list(calc.daterange(p.start, p.end))
|
||||
cells = _cells_for(days, ["a", "b"])
|
||||
rows = calc.main_table(p, ["a", "b"], cells, today=date(2026, 9, 30), holidays={"2026-10-03": "개천절"})
|
||||
assert [r["kind"] for r in rows] == ["day"] * 7 + ["week"]
|
||||
assert rows[0]["label"] == "09/28(월)" and rows[6]["label"] == "10/04(일)"
|
||||
assert rows[5]["holiday"] == "개천절" and rows[2]["today"] and rows[3]["future"]
|
||||
week = rows[-1]
|
||||
assert week["cells"]["a"] == {"gross": 70_000, "commission": 7_000, "net": 63_000}
|
||||
assert week["cells"]["b"]["commission"] == 0 # 요율 없는 쇼핑몰 = 0%
|
||||
assert week["total"]["gross"] == 140_000
|
||||
assert rows[0]["total"]["gross"] == 20_000
|
||||
|
||||
|
||||
def test_main_table_month_and_year():
|
||||
p = calc.resolve_period("month", date(2026, 9, 10))
|
||||
cells = _cells_for(list(calc.daterange(p.start, p.end)), ["a"])
|
||||
rows = calc.main_table(p, ["a"], cells, today=date(2026, 9, 30))
|
||||
weeks = [r for r in rows if r["kind"] == "week"]
|
||||
assert rows[-1]["kind"] == "total" and rows[-1]["total"]["gross"] == 300_000
|
||||
assert sum(w["total"]["gross"] for w in weeks) == 300_000
|
||||
assert weeks[0]["from"] == "2026-09-01" and weeks[0]["to"] == "2026-09-06" # 첫 주는 월 시작부터
|
||||
y = calc.resolve_period("year", date(2026, 9, 10))
|
||||
yrows = calc.main_table(y, ["a"], cells, today=date(2026, 9, 30))
|
||||
assert len(yrows) == 13 and yrows[8]["total"]["gross"] == 300_000 and yrows[9]["future"]
|
||||
ym = calc.year_months(2026, ["a"], cells, today=date(2026, 9, 30))
|
||||
assert ym["rows"][9]["gross"] is None and ym["rows"][8]["gross"] == 300_000 and ym["total"]["gross"] == 300_000
|
||||
ms = calc.month_summary(2026, 9, ["a"], cells)
|
||||
assert ms["rows"][0]["share"] == 100.0 and ms["total"]["net"] == 270_000
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 가짜 저장소 + 인증정보
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class FakeStore:
|
||||
def __init__(self):
|
||||
self.creds: dict[tuple[str, str], dict] = {}
|
||||
self.events: dict[tuple[str, str, str], dict] = {}
|
||||
self.status: dict[str, dict] = {}
|
||||
self.running: set[str] = set()
|
||||
self.markets = [{"code": a.code, "name": a.name, "enabled": True, "include_in_sales": True} for a in all_adapters()]
|
||||
|
||||
def credential_rows(self, code):
|
||||
return {k: {**v, "updated_at": None} for (c, k), v in self.creds.items() if c == code}
|
||||
|
||||
def credential_keys_by_code(self):
|
||||
out = {}
|
||||
for c, k in self.creds:
|
||||
out.setdefault(c, set()).add(k)
|
||||
return out
|
||||
|
||||
def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""):
|
||||
self.creds[(code, key)] = {"encrypted_value": encrypted_value, "key_version": key_version}
|
||||
|
||||
def delete_credential(self, code, key):
|
||||
self.creds.pop((code, key), None)
|
||||
|
||||
def all_credential_rows(self):
|
||||
return [{"marketplace_code": c, "credential_key": k, **v} for (c, k), v in self.creds.items()]
|
||||
|
||||
def list_marketplaces(self):
|
||||
return self.markets
|
||||
|
||||
def start_run(self, code, **_):
|
||||
if code in self.running:
|
||||
return None
|
||||
self.running.add(code)
|
||||
return len(self.running)
|
||||
|
||||
def finish_run(self, run_id, **_):
|
||||
self.running.clear()
|
||||
|
||||
def record_sync(self, code, *, status, ok, error=""):
|
||||
self.status[code] = {"status": status, "ok": ok, "error": error}
|
||||
|
||||
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, *, id_prefix=""):
|
||||
def mine(k, v):
|
||||
return k[0] == code or (id_prefix and k[2].startswith(id_prefix))
|
||||
self.events = {k: v for k, v in self.events.items()
|
||||
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:
|
||||
target = e.get("marketplace_code") or code
|
||||
self.events[(target, e["event_type"], e["external_event_id"])] = {**e, "is_sample": is_sample}
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def _coupang():
|
||||
return next(a for a in all_adapters() if a.code == "coupang")
|
||||
|
||||
|
||||
def test_credentials_encrypted_and_never_returned():
|
||||
st = FakeStore()
|
||||
svc = CredentialService(st, lambda: ring())
|
||||
ad = _coupang()
|
||||
saved = svc.save(ad, {"vendor_id": "A00012345", "access_key": "AK-plain-111", "secret_key": "SK-plain-222",
|
||||
"unknown": "x"}, user="t@x")
|
||||
assert sorted(saved) == ["access_key", "secret_key", "vendor_id"]
|
||||
for (code, key), row in st.creds.items():
|
||||
assert "plain" not in row["encrypted_value"] and "A00012345" not in row["encrypted_value"]
|
||||
assert row["encrypted_value"].startswith("v1:") and row["key_version"] == 1
|
||||
info = svc.describe(ad)
|
||||
as_text = repr(info)
|
||||
assert "AK-plain-111" not in as_text and "SK-plain-222" not in as_text
|
||||
by_key = {f["key"]: f for f in info["fields"]}
|
||||
assert by_key["secret_key"]["has_value"] and "value" not in by_key["secret_key"]
|
||||
assert by_key["vendor_id"]["value"] == "A00012345" and info["configured"]
|
||||
# 빈 칸 = 유지, 다른 쇼핑몰 칸으로 옮긴 암호문은 풀리지 않음(AAD)
|
||||
svc.save(ad, {"secret_key": "", "access_key": "AK-new"})
|
||||
acc = svc.accessor("coupang")
|
||||
assert acc.get("secret_key") == "SK-plain-222" and acc.get("access_key") == "AK-new"
|
||||
moved = st.creds[("coupang", "secret_key")]["encrypted_value"]
|
||||
try:
|
||||
crypto.decrypt(moved, aad=aad_for("naver", "client_secret"), ring=ring())
|
||||
except crypto.DecryptError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("다른 칸의 암호문은 복호화되면 안 됩니다")
|
||||
# 재암호화(키 교체)
|
||||
svc2 = CredentialService(st, lambda: ring(2, APP_ENCRYPTION_KEY_V1=KEY1))
|
||||
assert svc2.reencrypt_all() == {"reencrypted": 3, "failed": 0}
|
||||
assert all(r["key_version"] == 2 for r in st.creds.values())
|
||||
assert svc2.accessor("coupang").get("secret_key") == "SK-plain-222"
|
||||
assert svc2.configured_codes(list(all_adapters()))["coupang"] is True
|
||||
assert svc2.configured_codes(list(all_adapters()))["naver"] is False
|
||||
assert svc2.configured_codes(list(all_adapters()))["cafe24"] is True # 공통 연동
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 동기화
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class _Leaky(MarketplaceAdapter):
|
||||
code, name = "coupang", "쿠팡"
|
||||
|
||||
def credential_fields(self):
|
||||
return [CredentialField("secret_key", "Secret", secret=True)]
|
||||
|
||||
def collect(self, ctx, start, end):
|
||||
secret = ctx.credentials.get("secret_key")
|
||||
raise AuthFailed(f"401 invalid signature for key {secret} Authorization: CEA abcdefg123")
|
||||
|
||||
|
||||
class _Good(MarketplaceAdapter):
|
||||
code, name = "naver", "네이버"
|
||||
|
||||
def collect(self, ctx, start, end):
|
||||
d = date(2026, 9, 29)
|
||||
return 1, [
|
||||
SaleEvent("SALE", "o1-S", "o1", d, 10_000, payment_date=d - timedelta(days=1), raw={"token": "t"}),
|
||||
SaleEvent("CANCEL", "o1-C", "o1", d, -10_000),
|
||||
]
|
||||
|
||||
|
||||
def test_sync_isolation_redaction_and_dedupe():
|
||||
import app.modules.performance.sync as syncmod
|
||||
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(_coupang(), {"vendor_id": "V", "access_key": "AK", "secret_key": "SUPER-SECRET-KEY-123"})
|
||||
leaky, good = _Leaky(), _Good()
|
||||
orig = syncmod.get_adapter
|
||||
syncmod.get_adapter = lambda c: {"coupang": leaky, "naver": good}.get(c)
|
||||
try:
|
||||
svc = SyncService(st, creds)
|
||||
r1 = svc.sync_marketplace("coupang", date(2026, 9, 23), date(2026, 9, 29))
|
||||
r2 = svc.sync_marketplace("naver", date(2026, 9, 23), date(2026, 9, 29))
|
||||
svc.sync_marketplace("naver", date(2026, 9, 23), date(2026, 9, 29)) # 두 번 = 중복 없음
|
||||
finally:
|
||||
syncmod.get_adapter = orig
|
||||
assert not r1["ok"] and r1["status"] == "auth_failed"
|
||||
assert "SUPER-SECRET-KEY-123" not in r1["message"] and "abcdefg123" not in r1["message"]
|
||||
assert "SUPER-SECRET-KEY-123" not in st.status["coupang"]["error"]
|
||||
assert r2["ok"] and r2["upserted"] == 2 and st.status["naver"]["status"] == "ok"
|
||||
assert len([k for k in st.events if k[0] == "naver"]) == 2
|
||||
sale = st.events[("naver", "SALE", "o1-S")]
|
||||
assert sale["sales_date"] == date(2026, 9, 28) # 결제일 기준
|
||||
assert st.events[("naver", "CANCEL", "o1-C")]["sales_date"] == date(2026, 9, 29) # 발생일 기준
|
||||
assert sale["raw"]["token"] == MASK
|
||||
# 이미 도는 중이면 건너뜀
|
||||
st.running.add("naver")
|
||||
syncmod.get_adapter = lambda c: good
|
||||
try:
|
||||
r3 = SyncService(st, creds).sync_marketplace("naver", date(2026, 9, 29), date(2026, 9, 29))
|
||||
finally:
|
||||
syncmod.get_adapter = orig
|
||||
assert r3["skipped"]
|
||||
|
||||
|
||||
def test_not_implemented_and_mock():
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
svc = SyncService(st, creds)
|
||||
gm = next(a for a in all_adapters() if a.code == "gmarket")
|
||||
r = svc.sync_marketplace("gmarket", date(2026, 9, 29), date(2026, 9, 29))
|
||||
assert r["status"] == "not_configured" # 키 미입력
|
||||
secret = next(f.key for f in gm.visible_fields() if f.secret)
|
||||
creds.save(gm, {f.key: ("k-123456" if f.key == secret else "v") for f in gm.visible_fields()})
|
||||
r = svc.sync_marketplace("gmarket", date(2026, 9, 29), date(2026, 9, 29))
|
||||
assert r["status"] == "not_implemented" and "k-123456" not in r["message"]
|
||||
import httpx
|
||||
orig_get, httpx.get = httpx.get, (lambda url, headers=None, timeout=None: httpx.Response(200, content=b"<orders/>"))
|
||||
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))
|
||||
assert [e.amount for e in a] == [e.amount for e in b] and a
|
||||
for e in a:
|
||||
e.validate()
|
||||
assert (e.amount < 0) == (e.event_type in ("CANCEL", "RETURN"))
|
||||
assert any(e.event_type == "CANCEL" for e in a)
|
||||
n = svc.generate_samples(date(2026, 9, 1), date(2026, 9, 30), ["naver"])
|
||||
assert n == len(a) and all(v["is_sample"] for v in st.events.values())
|
||||
assert sales_date_for(a[0]) == a[0].payment_date
|
||||
assert event_row(a[0])["sales_date"] == a[0].payment_date
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 카페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",
|
||||
"payment_amount": f"{price + ship - coupon - member}.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", "payment_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_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, orders_pages, refunds_pages=(), lookup=None, claims=None):
|
||||
self.orders_pages = orders_pages # 결제일 조회 페이지들
|
||||
self.claims = claims or {} # date_type(취소/반품/교환 완료일) → 주문 목록
|
||||
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, 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]}
|
||||
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 []}
|
||||
|
||||
|
||||
@_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
|
||||
|
||||
ctx = AdapterContext(code="cafe24", credentials=None)
|
||||
fake = _FakeCafe24(
|
||||
[[_c24_order("A", order_from_mobile="T", payment_method_name=["신용카드"]), _c24_order("B", market="shopn"),
|
||||
_c24_order("C", paid="F"), _c24_order("D", market="auction", payment_method_name=["신용카드"]),
|
||||
_c24_order("E", market="NCHECKOUT", payment_method_name=["네이버페이"]),
|
||||
_c24_order("F", market="KAKAOPAY", payment_method_name=["카카오페이", "적립금"]),
|
||||
_c24_order("G", market="mobile", order_from_mobile="T", payment_method_name=["무통장입금"])]],
|
||||
[[_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}
|
||||
# 결제합계 = 상품구매금액 + 배송비 − 할인 − 쿠폰 (결제 당시 금액), 사건 ID 는 c24: 접두어
|
||||
sale = by[("SALE", "c24:A-PAY")]
|
||||
assert sale.amount == 50_000 + 3_000 - 1_000 - 5_000 == 47_000 and sale.marketplace_code == "cafe24"
|
||||
assert sale.event_date == date(2026, 9, 29) and sale.quantity == 2 and sale.product_name == "상품1 외 1건"
|
||||
# 마켓 연동 주문은 해당 쇼핑몰 열로, 연결표에 없는 마켓(옥션)은 카페24 열, 미결제는 제외
|
||||
assert by[("SALE", "c24:B-PAY")].marketplace_code == "naver"
|
||||
assert by[("SALE", "c24:D-PAY")].marketplace_code == "cafe24"
|
||||
# 네이버페이·톡체크아웃·모바일웹은 카페24 자체몰 주문(실데이터 확인) — 네이버/카카오 열로 가면 안 된다
|
||||
for oid in ("E", "F", "G"):
|
||||
assert by[("SALE", f"c24:{oid}-PAY")].marketplace_code == "cafe24", oid
|
||||
assert ("SALE", "c24:C-PAY") not in by
|
||||
# 환불: 환불완료일, 실제 환불액, R→반품 / 그 밖→취소, 원 주문의 마켓 열로, 미완료 환불 제외
|
||||
assert by[("CANCEL", "c24:C20260929-01")].amount == -12_610
|
||||
assert by[("CANCEL", "c24:C20260929-01")].marketplace_code == "cafe24"
|
||||
assert by[("RETURN", "c24:R20260929-02")].amount == -20_000
|
||||
assert by[("CANCEL", "c24:C20260929-03")].marketplace_code == "naver"
|
||||
assert ("CANCEL", "c24:C20260929-04") not in by
|
||||
assert by[("CANCEL", "c24:C20260929-01")].event_date == date(2026, 9, 29)
|
||||
for e in events:
|
||||
assert "buyer_name" not in str(e.raw) and "1234567890" not in str(e.raw) # 개인정보 미저장
|
||||
assert order_total({"naver_point": "151500.00", # 9/23 화면값
|
||||
"initial_order_amount": {"order_price_amount": "1860800.00", "shipping_fee": "35000.00",
|
||||
"coupon_discount_price": "21000.00", "payment_amount": "1713128.00",
|
||||
"points_spent_amount": "10110.00"}}) == 1_874_738
|
||||
assert target_code("self") == "cafe24" and target_code("SK11ST") == "elevenst"
|
||||
assert target_code("unknown", "coupang") == "coupang" and target_code("unknown") == "cafe24"
|
||||
assert target_code("NCHECKOUT", "NCHECKOUT") == "cafe24" and target_code("KAKAOPAY") == "cafe24"
|
||||
assert target_code("naver") == "cafe24" and target_code("kakao") == "cafe24" # 결제수단과 헷갈리는 일반 이름 X
|
||||
# 대조: 카페24 열(자체몰 채널+모르는 채널)/다른 쇼핑몰 열 + 주문 채널별
|
||||
import app.timezone as _tz
|
||||
_orig_today, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
|
||||
try:
|
||||
rec = fake.reconcile(ctx, date(2026, 9, 29))
|
||||
finally:
|
||||
_tz.today_kst = _orig_today
|
||||
assert rec["orders"]["self"]["orders"] == 5 and rec["orders"]["self"]["total"] == 5 * 47_000 # A,D,E,F,G
|
||||
assert rec["orders"]["market"]["orders"] == 1 and rec["unpaid_orders"] == 1 # B(스마트스토어)
|
||||
assert rec["refunds"]["self"]["actual_refund_amount"] == 32_610 and rec["refunds"]["market"]["count"] == 1
|
||||
ch = {b["market_id"]: b for b in rec["by_channel"]}
|
||||
assert ch["shopn"]["kind"] == "market" and ch["shopn"]["target"] == "naver" and ch["shopn"]["refund_amount"] == 9_000
|
||||
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}
|
||||
assert {c["key"] for c in rec["refund_candidates"]} >= {"completed", "completed_pts", "claim_pay"}
|
||||
# 결제일 기준: 그날 결제된 카페24 열 주문(A,D,E,F,G)의 환불만 — X(결제 없음)·M(스마트스토어)·미완료 제외
|
||||
bp = rec["refund_basis"]["by_pay_date"]
|
||||
assert bp["count"] == 1 and bp["actual_refund_amount"] == 12_610
|
||||
assert bp["amount_diff"] == 5 * 47_000 # 결제 당시 − 현재(가짜 현재 상품금액 0)
|
||||
red = {x["order_id"]: x for x in rec["reduced_orders"]}
|
||||
assert set(red) == {"A", "D", "E", "F", "G"} and red["A"]["refunded"] == 12_610 and red["D"]["refunded"] == 0
|
||||
assert rec["reduced_orders"][-1]["order_id"] == "A" # 환불 기록으로 설명 안 되는 금액이 큰 순
|
||||
assert {r["refund_code"] for r in rec["refund_list"]} == {"C20260929-01", "R20260929-02", "C20260929-03", "C20260929-04"}
|
||||
assert "1234567890" not in str(rec["refund_list"]) # 환불 계좌 미노출
|
||||
# 클레임 완료 품목: 환불 API 에 없는 취소(네이버페이 등)를 찾는다. 입금전취소·미완료는 합계 제외
|
||||
item = lambda code, st, pay, price=10_000, qty=1: {"order_item_code": code, "order_status": st, "quantity": qty,
|
||||
"product_price": f"{price}.00", "option_price": "0.00",
|
||||
"payment_amount": f"{pay}.00", "product_name": "상품"}
|
||||
fake4 = _FakeCafe24([[]], [[_c24_refund("C1", "A", 9_000)]], claims={
|
||||
"cancel_complete_date": [
|
||||
{**_c24_order("A"), "items": [item("A-01", "C40", 9_000)]},
|
||||
{**_c24_order("N"), "market_id": "NCHECKOUT", "items": [item("N-01", "C40", 19_800, 20_000), item("N-02", "C40", 5_000, 5_000)]},
|
||||
{**_c24_order("U"), "items": [item("U-01", "C48", 7_000)]},
|
||||
{**_c24_order("P"), "items": [item("P-01", "C34", 3_000), item("P-02", "N40", 4_000)]}],
|
||||
"return_complete_date": [{**_c24_order("N"), "items": [item("N-01", "C40", 19_800, 20_000)]},
|
||||
{**_c24_order("R"), "items": [item("R-01", "R40", 12_000, 6_000, 2)]}],
|
||||
})
|
||||
rec4 = fake4.reconcile(ctx, date(2026, 9, 29))
|
||||
cl = {c["item_code"]: c for c in rec4["claims"]["items"]}
|
||||
assert set(cl) == {"A-01", "N-01", "N-02", "P-01", "R-01"} # 입금전취소(U)·정상 품목 제외, 중복 제거
|
||||
assert cl["A-01"]["has_refund"] and not cl["N-01"]["has_refund"] and not cl["P-01"]["done"]
|
||||
assert cl["R-01"]["product_amount"] == 12_000
|
||||
assert rec4["claims"]["full_cancel_shipping"] == 3_000 * 2 # A, N 전체취소(배송비 3,000씩)
|
||||
cand = {c["key"]: c["amount"] for c in rec4["refund_candidates"]}
|
||||
assert cand["claim_pay"] == 9_000 + 19_800 + 5_000 + 12_000
|
||||
assert cand["completed_plus_noref"] == 9_000 + 19_800 + 5_000 + 12_000
|
||||
# 기기: 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
|
||||
# self 는 PC 전용이 아니다 — 주문경로(PC쇼핑몰/모바일웹)별로 한 줄씩(실데이터 확인)
|
||||
fake3 = _FakeCafe24([[_c24_order("P1", order_place_name="PC쇼핑몰"), _c24_order("P2", order_place_name="PC쇼핑몰"),
|
||||
_c24_order("M1", order_place_name="모바일웹", order_from_mobile="T")]])
|
||||
rows3 = {(b["market_id"], b["place"]): b for b in fake3.reconcile(ctx, date(2026, 9, 29))["by_channel"]}
|
||||
assert rows3[("self", "PC쇼핑몰")]["orders"] == 2 and rows3[("self", "모바일웹")]["mobile_orders"] == 1
|
||||
assert rows3[("self", "PC쇼핑몰")]["label"] == "자체몰"
|
||||
# 결제수단별(카페24 열만 — 외부 마켓 B 제외)
|
||||
pay = {p["method"]: p for p in rec["by_payment"]}
|
||||
assert pay["신용카드"]["orders"] == 2 and pay["신용카드"]["total"] == 94_000
|
||||
assert pay["카카오페이 + 적립금"]["orders"] == 1 and "네이버페이" in pay and "무통장입금" in pay
|
||||
assert sum(p["orders"] for p in rec["by_payment"]) == 5
|
||||
# 60일 단위 분할 + 페이지 넘김(1000건이면 다음 페이지)
|
||||
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 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_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)]}, # 취소신청만 → 제외
|
||||
# 전체취소 두 품목 — 배송비(3,000)는 마지막 품목(NP5-02)에 한 번만. 앞 품목은 전날 취소(기간 밖)
|
||||
{**_c24_order("NP5", market="NCHECKOUT"), "items": [item("NP5-01", "C40", 7_000, day="2026-09-25 10:00:00"),
|
||||
item("NP5-02", "C40", 8_000)]},
|
||||
{**_c24_order("KP1", market="KAKAOPAY"), "items": [item("KP1-01", "C40", 9_900)]}, # 톡체크아웃 → 제외
|
||||
{**_c24_order("S1"), "items": [item("S1-01", "R40", 9_900)]}, # 자체몰 → 제외
|
||||
],
|
||||
"return_complete_date": [{**_c24_order("NP1", market="NCHECKOUT"),
|
||||
"items": [item("NP1-01", "C40", 55_800), item("NP1-02", "N40", 9_000)]}],
|
||||
})
|
||||
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 + 3_000) # 판매가×수량 − 품목 쿠폰 + 전체취소 배송비
|
||||
assert by["c24:NP5-02-CL"].amount == -(8_000 + 3_000) # 배송비는 마지막 품목에 한 번
|
||||
# 다른 날·신청·환불 기록 있는 주문·톡체크아웃·자체몰 제외
|
||||
assert set(by) == {"c24:C20260926-01", "c24:NP1-01-CL", "c24:NP2-01-CL", "c24:NP5-02-CL"}
|
||||
rs = rec["refunds"]["self"]
|
||||
assert rs["no_record_count"] == 3 and rs["no_record"] == 55_800 + 42_000 + 11_000
|
||||
assert rs["total"] == 63_720 + 1_080 + 55_800 + 42_000 + 11_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", "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
|
||||
from app.modules.performance.adapters.cafe24 import Cafe24Adapter
|
||||
|
||||
ctx = AdapterContext(code="cafe24", credentials=None)
|
||||
real = Cafe24Adapter()
|
||||
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 c: {"connected": True, "scopes": "mall.read_product,mall.read_order"}
|
||||
real.authenticate(ctx)
|
||||
|
||||
def ev(eid, day, **kw):
|
||||
return {"event_type": "SALE", "external_event_id": eid, "external_order_id": "o",
|
||||
"event_date": day, "sales_date": day, "amount": 1, **kw}
|
||||
|
||||
# 기간 교체: 기간 안 카페24 행(예전 품목 단위)·카페24 경유 네이버 행은 지우고,
|
||||
# 네이버 직접 연동분·테스트 데이터·기간 밖은 남긴다
|
||||
st = FakeStore()
|
||||
d, out = date(2026, 9, 29), date(2026, 9, 1)
|
||||
st.upsert_events("cafe24", [ev("old-item-S", d), ev("outside", out)])
|
||||
st.upsert_events("naver", [ev("c24:OLD-PAY", d), ev("direct-naver-1", d)])
|
||||
st.upsert_events("cafe24", [ev("sample", d)], is_sample=True)
|
||||
fake = _FakeCafe24([[_c24_order("A"), _c24_order("B", market="shopn")]])
|
||||
orig = syncmod.get_adapter
|
||||
syncmod.get_adapter = lambda c: fake
|
||||
try:
|
||||
r = SyncService(st, CredentialService(st, lambda: ring())).sync_marketplace("cafe24", d, d)
|
||||
finally:
|
||||
syncmod.get_adapter = orig
|
||||
got = {(k[0], k[2]) for k in st.events}
|
||||
assert r["ok"], r
|
||||
assert got == {("cafe24", "c24:A-PAY"), ("naver", "c24:B-PAY"), ("cafe24", "outside"),
|
||||
("naver", "direct-naver-1"), ("cafe24", "sample")}, got
|
||||
|
||||
|
||||
def test_cafe24_paid_total_matches_daily_report():
|
||||
"""카페24 결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트(결제 당시). 상품식과 다를 수 있다.
|
||||
실데이터 9/23: 1,713,128 + 10,110 + 0 + 151,500 = 1,874,738 (상품식 1,874,800)."""
|
||||
from app.modules.performance.adapters.cafe24 import order_total, order_total_now
|
||||
|
||||
o = _c24_order("A", naver_point="3000.00") # 상품식 50,000 + 3,000 − 1,000 − 5,000 = 47,000
|
||||
o["initial_order_amount"].update(payment_amount="42938.00", points_spent_amount="1000.00")
|
||||
assert order_total(o) == 42_938 + 1_000 + 3_000 == 46_938
|
||||
ev = _FakeCafe24([]).normalize_order(o)[0]
|
||||
assert ev.amount == 46_938 and ev.discount_amount == 1_000 + 5_000
|
||||
o["actual_order_amount"] = {**o["initial_order_amount"], "payment_amount": "20000.00"}
|
||||
assert order_total_now(o) == 20_000 + 1_000 + 3_000
|
||||
z = _c24_order("Z")
|
||||
z["initial_order_amount"]["payment_amount"] = "0.00"
|
||||
assert order_total(z) == 0 # 결제 필드가 모두 0이면 카페24도 0원
|
||||
# 대조 진단: 원본 금액 필드 합계 + 이상 주문(개인정보 숫자 필드는 제외)
|
||||
import app.timezone as _tz
|
||||
from app.modules.performance.adapters.base import AdapterContext
|
||||
from app.modules.performance.adapters.cafe24 import money_fields
|
||||
|
||||
got = money_fields({"bank_account_no": "1234567890", "order_price_amount": "100.50", "x": {"coupon_discount_price": 3}})
|
||||
assert got == {"order_price_amount": 101, "x.coupon_discount_price": 3}
|
||||
o2 = _c24_order("B", price=10_050)
|
||||
o2["items"] = [{"order_item_code": "B-01", "product_price": "10000.00", "option_price": "0", "quantity": 1,
|
||||
"order_status": "N40"}]
|
||||
orig, _tz.today_kst = _tz.today_kst, (lambda: date(2026, 9, 29))
|
||||
try:
|
||||
rec = _FakeCafe24([[o, o2]]).reconcile(AdapterContext(code="cafe24", credentials=None), date(2026, 9, 29))
|
||||
finally:
|
||||
_tz.today_kst = orig
|
||||
assert rec["diag"]["order"]["naver_point"] == 3_000
|
||||
assert rec["diag"]["initial"]["order_price_amount"] == 60_050 and "bank_account_no" not in rec["diag"]["order"]
|
||||
odd = {x["order_id"]: x for x in rec["odd_orders"]}
|
||||
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
|
||||
|
||||
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_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_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_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 = ('<?xml version="1.0" encoding="euc-kr"?><ns2:orders xmlns:ns2="http://skt.tmall.business.openapi.spring.service.'
|
||||
'client.domain/"><ns2:order><ordNo>1</ordNo></ns2:order><ns2:order><ordNo>2</ordNo></ns2:order>'
|
||||
'</ns2:orders>').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 = '<ns2:orders xmlns:ns2="x"><ns2:result_code>-1</ns2:result_code><ns2:result_text>허용되지 않은 IP</ns2:result_text></ns2:orders>'
|
||||
for status, body, kind in ((200, err.encode(), ApiError), (403, b"Forbidden", AuthFailed),
|
||||
(200, b"<html><body>IP not allowed</body></html>", 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 or "XML 아님" in exc.message
|
||||
else:
|
||||
raise AssertionError("오류여야 합니다")
|
||||
# 원본 데이터 확인: 살아 있는 주소는 항목 합계, 없는 주소(404)는 실패로. 개인정보 값은 숨김
|
||||
rows = ("<ns2:orders xmlns:ns2='x'>" + "".join(
|
||||
f"<ns2:order><ordNo>{n}</ordNo><ordPayAmt>{a}</ordPayAmt><rcvrNm>홍길동</rcvrNm><prdNm>상품{n}</prdNm>"
|
||||
f"<ordStlEndDt>2026-09-29 10:00:00</ordStlEndDt></ns2:order>" for n, a in ((1, 10000), (2, 5500))) +
|
||||
"</ns2:orders>").encode()
|
||||
|
||||
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"<html>not found</html>")
|
||||
if "/ordservices/" in url:
|
||||
return httpx.Response(200, content=b"<ns2:orders xmlns:ns2='x'/>")
|
||||
if "/claimservice/" in url:
|
||||
return httpx.Response(200, content="<ns2:orders xmlns:ns2='x'><ns2:result_code>-1</ns2:result_code>"
|
||||
"<ns2:result_text>해당 건이 없습니다.</ns2:result_text></ns2:orders>".encode())
|
||||
return httpx.Response(404, content=b"<html>not found</html>")
|
||||
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["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)
|
||||
finally:
|
||||
httpx.get = orig
|
||||
|
||||
|
||||
def test_elevenst_collect_sales():
|
||||
"""11번가 매출 = 주문 단위, 결제일 기준.
|
||||
정산된 주문은 정산 내역의 판매금액합계(selPrcAmt) 합 — 셀러오피스 "판매 상세내역"과 같다(배송비 줄 포함).
|
||||
정산 전 주문은 주문 상태 목록의 ordAmt + 배송비. 실데이터: 9/9 = 34,900, 9/10 = 83,800 + 배송비 3,000 = 86,800
|
||||
(주문 목록의 dlvCst 는 0 이라 정산 값을 써야 맞음)."""
|
||||
import httpx
|
||||
|
||||
import app.modules.performance.sync as syncmod # noqa: F401
|
||||
import app.timezone as _tz
|
||||
|
||||
def line(no, seq, day, amt, pay, ship=0, qty=1):
|
||||
return (f"<ns2:order><ordNo>{no}</ordNo><ordPrdSeq>{seq}</ordPrdSeq><ordDt>{day} 15:13:16</ordDt>"
|
||||
f"<ordAmt>{amt}</ordAmt><ordPayAmt>{pay}</ordPayAmt><dlvCst>{ship}</dlvCst><ordQty>{qty}</ordQty>"
|
||||
f"<prdNm>밀폐용기</prdNm><rcvrNm>홍길동</rcvrNm><memNo>18550503</memNo></ns2:order>")
|
||||
|
||||
def stl(no, pay_day, amt, qty, cupn=0):
|
||||
return (f"<ns2:settlement><ordNo>{no}</ordNo><ordPrdSeq>1</ordPrdSeq><memNm>홍길동</memNm>"
|
||||
f"<ordStlEndDt>{pay_day}</ordStlEndDt><stlDy>2026/09/19</stlDy><prdNm>밀폐용기</prdNm><ordQty>{qty}</ordQty>"
|
||||
f"<selPrcAmt>{amt}</selPrcAmt><stlAmt>{amt - 100}</stlAmt><cupnAmt>{cupn}</cupnAmt></ns2:settlement>")
|
||||
settlement = ("<ns2:settlements xmlns:ns2='x'>" + stl("20260909099415322", "2026/09/09", 34900, 1) +
|
||||
stl("20260910099718265", "2026/09/10", 3000, 0) + stl("20260910099718265", "2026/09/10", 83800, 2, 11060) +
|
||||
stl("20260801000000009", "2026/08/01", 9999, 1) + "</ns2:settlements>").encode()
|
||||
completed = ("<ns2:orders xmlns:ns2='x'>" + line("20260909099415322", 1, "2026-09-09", 34900, 34900) +
|
||||
line("20260910099718265", 1, "2026-09-10", 83800, 72740, qty=2) +
|
||||
line("20260801000000001", 1, "2026-08-01", 5000, 5000) + "</ns2:orders>").encode()
|
||||
packaging = ("<ns2:orders xmlns:ns2='x'>" + line("20260911000000002", 1, "2026-09-11", 20000, 20000, ship=3000) +
|
||||
line("20260911000000002", 2, "2026-09-11", 5000, 5000, ship=3000) +
|
||||
line("20260911000000002", 2, "2026-09-11", 5000, 5000, ship=3000) + "</ns2:orders>").encode()
|
||||
empty = "<ns2:orders xmlns:ns2='x'><ns2:result_code>-1</ns2:result_code><ns2:result_text>해당 건이 없습니다.</ns2:result_text></ns2:orders>".encode()
|
||||
calls = []
|
||||
|
||||
def route(url, headers=None, timeout=None):
|
||||
calls.append(url)
|
||||
if "/settlement/" in url:
|
||||
return httpx.Response(200, content=settlement if "/20260916/" in url else empty)
|
||||
if "/ordservices/completed/" in url:
|
||||
return httpx.Response(200, content=completed)
|
||||
if "/ordservices/packaging/" in url:
|
||||
return httpx.Response(200, content=packaging)
|
||||
return httpx.Response(200, content=empty)
|
||||
|
||||
st = FakeStore()
|
||||
creds = CredentialService(st, lambda: ring())
|
||||
creds.save(next(a for a in all_adapters() if a.code == "elevenst"), {"api_key": "KEY-11ST"})
|
||||
orig, orig_today = httpx.get, _tz.today_kst
|
||||
httpx.get, _tz.today_kst = route, (lambda: date(2026, 9, 30))
|
||||
try:
|
||||
r = SyncService(st, creds).sync_marketplace("elevenst", date(2026, 9, 9), date(2026, 9, 11))
|
||||
finally:
|
||||
httpx.get, _tz.today_kst = orig, orig_today
|
||||
assert r["ok"], r
|
||||
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "elevenst"}
|
||||
assert set(ev_) == {"11st:20260909099415322", "11st:20260910099718265", "11st:20260911000000002"} # 8/1 제외
|
||||
assert ev_["11st:20260909099415322"]["amount"] == 34_900 and ev_["11st:20260909099415322"]["sales_date"] == date(2026, 9, 9)
|
||||
assert ev_["11st:20260910099718265"]["amount"] == 86_800 # 정산 값(배송비 줄 포함)
|
||||
assert ev_["11st:20260910099718265"]["discount_amount"] == 11_060 and ev_["11st:20260910099718265"]["quantity"] == 2
|
||||
assert ev_["11st:20260910099718265"]["order_status"] == "정산확정"
|
||||
assert ev_["11st:20260911000000002"]["amount"] == 25_000 + 3_000 # 정산 전: ordAmt + 배송비 한 번, 중복 줄 1번
|
||||
assert ev_["11st:20260911000000002"]["order_status"] == "발송대기"
|
||||
assert "홍길동" not in repr(st.events) and "18550503" not in repr(st.events) # 구매자 정보 미저장
|
||||
assert any("/20260930" in u for u in calls) and not any("/20261001" in u for u in calls) # 오늘까지만 더 불러옴
|
||||
|
||||
|
||||
def test_registry_and_event_validation():
|
||||
codes = [a.code for a in all_adapters()]
|
||||
assert len(codes) == len(set(codes)) == 10
|
||||
for a in all_adapters():
|
||||
keys = [f.key for f in a.credential_fields()]
|
||||
assert len(keys) == len(set(keys)), a.code
|
||||
assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
|
||||
for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
|
||||
SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
|
||||
try:
|
||||
bad.validate()
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(f"검증 실패해야 함: {bad.event_type} {bad.amount}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
||||
n = 0
|
||||
for name, fn in sorted(globals().items()):
|
||||
if name.startswith("test_") and callable(fn):
|
||||
fn()
|
||||
n += 1
|
||||
print("ok", name)
|
||||
print(f"{n} tests passed")
|
||||
@@ -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);
|
||||
|
||||
@@ -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 @@
|
||||
'<circle cx="12" cy="17.1" r="1.05" fill="currentColor"/>' +
|
||||
"</svg>";
|
||||
|
||||
// 성공(tone: "ok") — 원 안의 체크.
|
||||
var ICON_OK =
|
||||
'<svg width="32" height="32" viewBox="0 0 24 24" fill="none" aria-hidden="true">' +
|
||||
'<circle cx="12" cy="12" r="9.2" stroke="currentColor" stroke-width="1.6"/>' +
|
||||
'<path d="m7.6 12.3 3 3 5.8-6.2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"' +
|
||||
' stroke-linejoin="round"/>' +
|
||||
"</svg>";
|
||||
|
||||
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";
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
/* ════════════════════════════════════════════════════
|
||||
실적(쇼핑몰 통합 매출) — 정보 밀도 높은 관리자 대시보드.
|
||||
기존 ERP 토큰(erp.css :root) 위에서만 쓴다. 색은 증감·상태·주말에만.
|
||||
════════════════════════════════════════════════════ */
|
||||
/* 색 변수 — 창(.perf-modal)은 document.body 에 붙어 .perf 밖이라 같이 정의한다 */
|
||||
.perf, .perf-modal {
|
||||
--perf-line: var(--color-subtle-ash);
|
||||
--perf-soft: #fafafa;
|
||||
--perf-up: #0f8a3a;
|
||||
--perf-down: var(--color-callout-red);
|
||||
--perf-sat: #1d4ed8;
|
||||
--perf-sun: var(--color-callout-red);
|
||||
}
|
||||
.perf {
|
||||
display: flex; flex-direction: column; gap: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
/* 공통 .erp-page 는 width:100% + padding 이라 부모보다 48px 넓어져 오른쪽이 잘린다.
|
||||
전역 규칙은 다른 모듈에 영향이 있어, 실적 화면이 들어 있을 때만 border-box 로 맞춘다. */
|
||||
.erp-page:has(> .perf) { box-sizing: border-box; }
|
||||
.perf, .perf > * { min-width: 0; }
|
||||
.perf-muted { color: var(--color-midtone-gray); font-size: 12px; }
|
||||
.perf-nowrap { white-space: nowrap; }
|
||||
.perf-center { text-align: center; }
|
||||
|
||||
/* 탭 */
|
||||
.perf-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--perf-line); }
|
||||
.perf-tab {
|
||||
padding: 8px 14px; font-size: 13px; font-weight: 500; color: var(--color-midtone-gray);
|
||||
border-bottom: 2px solid transparent; margin-bottom: -1px;
|
||||
}
|
||||
.perf-tab:hover { color: var(--color-rich-black); }
|
||||
.perf-tab.is-active { color: var(--color-rich-black); border-bottom-color: var(--color-rich-black); }
|
||||
|
||||
/* 도구 막대 */
|
||||
.perf-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
|
||||
.perf-quick, .perf-metric { display: inline-flex; border: 1px solid var(--perf-line); border-radius: 10px; padding: 2px; background: #fff; }
|
||||
.perf-seg {
|
||||
border: 0; background: transparent; font: inherit; font-size: 12px; font-weight: 500;
|
||||
padding: 5px 11px; border-radius: 8px; cursor: pointer; color: var(--color-rich-black); white-space: nowrap;
|
||||
}
|
||||
.perf-seg:hover { background: var(--color-ghost-gray); }
|
||||
.perf-seg.is-active { background: var(--color-deep-black); color: #fff; }
|
||||
a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited { color: #fff; }
|
||||
.perf-nav { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.perf-nav-btn {
|
||||
font-size: 12px; padding: 5px 9px; border: 1px solid var(--perf-line); border-radius: 8px; background: #fff;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.perf-nav-btn:hover { background: var(--color-ghost-gray); }
|
||||
.perf-nav-label { font-weight: 600; font-size: 14px; min-width: 200px; text-align: center; }
|
||||
.perf-custom { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.perf-custom[hidden] { display: none; }
|
||||
/* 공통 .erp-input 의 min-width:240px 를 날짜칸에서만 푼다 */
|
||||
.perf .erp-input.perf-date { width: 150px; min-width: 0; flex: 0 0 auto; padding: 5px 8px !important; font-size: 12px !important; }
|
||||
.perf-modal .erp-input.perf-date { width: 150px; min-width: 0; }
|
||||
.perf-filter { position: relative; }
|
||||
.perf-filter > summary { list-style: none; cursor: pointer; }
|
||||
.perf-filter > summary::-webkit-details-marker { display: none; }
|
||||
.perf-filter-pop {
|
||||
position: absolute; z-index: 20; top: calc(100% + 6px); left: 0; min-width: 220px;
|
||||
background: #fff; border: 1px solid var(--perf-line); border-radius: 12px; padding: 10px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, .1); display: flex; flex-direction: column; gap: 4px;
|
||||
}
|
||||
.perf-check { display: flex; align-items: center; gap: 6px; font-size: 13px; padding: 3px 2px; cursor: pointer; }
|
||||
.perf-filter-act { display: flex; justify-content: space-between; margin-top: 6px; }
|
||||
.perf-update { margin-left: auto; display: inline-flex; align-items: center; gap: 10px; }
|
||||
.perf-update b { color: var(--color-rich-black); font-weight: 600; }
|
||||
|
||||
/* 알림 */
|
||||
.perf-notice {
|
||||
font-size: 12.5px; padding: 8px 12px; border-radius: 10px; background: var(--perf-soft);
|
||||
border: 1px solid var(--perf-line); display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center;
|
||||
}
|
||||
.perf-notice[hidden] { display: none; }
|
||||
.perf-notice.is-warn { background: #fff7f5; border-color: #f3d2ca; }
|
||||
.perf-notice.is-ok { background: #f3fbf5; border-color: #cdeccf; }
|
||||
.perf-problem { padding: 1px 8px; border-radius: 999px; background: #fbe9e6; color: var(--perf-down); font-weight: 500; }
|
||||
|
||||
/* KPI */
|
||||
.perf-kpis { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px; }
|
||||
.perf-kpi { border: 1px solid var(--perf-line); border-radius: 12px; padding: 12px 14px; background: #fff; min-width: 0; }
|
||||
.perf-kpi.is-primary { border-color: #cfcfcf; box-shadow: inset 3px 0 0 var(--color-deep-black); }
|
||||
.perf-kpi-label { font-size: 12px; color: var(--color-midtone-gray); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.perf-kpi-value { font-size: 22px; font-weight: 600; letter-spacing: -.5px; margin: 2px 0; white-space: nowrap; }
|
||||
.perf-kpi.is-primary .perf-kpi-value { font-size: 24px; }
|
||||
.perf-kpi-delta { font-size: 12px; display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
|
||||
.perf-delta { font-weight: 600; }
|
||||
.perf-delta.is-up { color: var(--perf-up); }
|
||||
.perf-delta.is-down { color: var(--perf-down); }
|
||||
.perf-delta.is-flat { color: var(--color-midtone-gray); }
|
||||
|
||||
/* 카드 */
|
||||
.perf-card { padding: 12px 14px; }
|
||||
.perf-card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; }
|
||||
.perf-h { margin: 0; font-size: 14px; font-weight: 600; }
|
||||
.perf-grid2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.perf-grid2 > .perf-card-wide { grid-column: 1 / -1; } /* 표가 넓은 카드(매출 대조)는 한 줄 전체 */
|
||||
.perf-foot { margin: 8px 0 0; line-height: 1.5; }
|
||||
|
||||
/* 표 */
|
||||
.perf-table-wrap { overflow-x: auto; }
|
||||
.perf-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
||||
.perf-table th, .perf-table td { padding: 6px 8px; border-bottom: 1px solid #efefef; white-space: nowrap; }
|
||||
.perf-table thead th {
|
||||
font-size: 12px; font-weight: 500; color: var(--color-midtone-gray); text-align: right;
|
||||
background: var(--perf-soft); border-bottom: 1px solid var(--perf-line); position: sticky; top: 0;
|
||||
}
|
||||
.perf-table thead th.perf-th-label { text-align: left; }
|
||||
.perf-td-label { text-align: left; font-weight: 500; }
|
||||
.perf-num { text-align: right; }
|
||||
.perf-zero { color: #c9c9c9; }
|
||||
.perf-na::before { content: ""; }
|
||||
.perf-th-total, .perf-td-total { background: #f6f6f6; font-weight: 600; }
|
||||
/* 날짜 열 너비 고정(210px) — 공휴일 이름이 날짜 오른쪽에 붙는다 */
|
||||
.perf-main thead th.perf-th-label, .perf-main .perf-td-label { width: 210px; min-width: 210px; max-width: 210px; box-sizing: border-box; overflow: hidden; text-overflow: ellipsis; }
|
||||
.perf-row-day.is-sat .perf-td-label { color: var(--perf-sat); }
|
||||
.perf-row-day.is-sun .perf-td-label { color: var(--perf-sun); }
|
||||
.perf-row-day.is-today .perf-td-label::after { content: "오늘"; margin-left: 6px; font-size: 10px; padding: 0 5px; border-radius: 999px; background: var(--color-deep-black); color: #fff; vertical-align: 1px; }
|
||||
.perf-row-day.is-future td, .perf-row-month.is-future td, .perf-year tr.is-future td { color: #c9c9c9; }
|
||||
.perf-hol { display: inline; margin-left: 6px; font-size: 11px; font-weight: 400; }
|
||||
.perf-row-week th, .perf-row-week td { background: #f3f3f3; font-weight: 600; border-bottom: 1px solid var(--perf-line); }
|
||||
.perf-row-week .perf-td-total { background: #e9e9e9; }
|
||||
.perf-row-total th, .perf-row-total td { background: var(--color-deep-black); color: #fff; font-weight: 600; border-bottom: 0; }
|
||||
.perf-row-total .perf-zero { color: #777; }
|
||||
td.is-link { cursor: pointer; }
|
||||
td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
|
||||
/* 표시 기준 전환 — 한 칸에 3값, data-metric 으로 하나만 보인다 */
|
||||
.perf .v { display: none; }
|
||||
.perf[data-metric="gross"] .v-gross,
|
||||
.perf[data-metric="commission"] .v-commission,
|
||||
.perf[data-metric="net"] .v-net { display: inline; }
|
||||
|
||||
/* 비중 막대 */
|
||||
.perf-share { position: relative; min-width: 110px; }
|
||||
.perf-bar { position: absolute; left: 8px; bottom: 3px; height: 3px; width: calc((100% - 16px) * var(--w) / 100); background: #d4d4d4; border-radius: 2px; }
|
||||
|
||||
/* 연간 요약 */
|
||||
.perf-year-sum { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 8px; }
|
||||
.perf-year-sum div { background: var(--perf-soft); border: 1px solid #efefef; border-radius: 10px; padding: 8px 10px; }
|
||||
.perf-year-sum span { display: block; font-size: 11.5px; color: var(--color-midtone-gray); }
|
||||
.perf-year-sum b { font-size: 16px; font-weight: 600; }
|
||||
|
||||
/* 그래프(SVG, performance.js 가 그림) */
|
||||
.perf-chart { min-height: 220px; }
|
||||
.perf-chart svg { display: block; width: 100%; height: auto; }
|
||||
.perf-chart text { font-size: 10.5px; fill: var(--color-midtone-gray); font-family: var(--font-geist); }
|
||||
.perf-chart .bar { fill: #1f1f1f; }
|
||||
.perf-chart .bar.is-neg { fill: var(--perf-down); }
|
||||
.perf-chart .bar:hover { fill: #555; }
|
||||
.perf-chart .grid { stroke: #efefef; }
|
||||
.perf-chart .axis { stroke: #d4d4d4; }
|
||||
.perf-chart-empty { color: var(--color-midtone-gray); font-size: 12px; padding: 80px 0; text-align: center; }
|
||||
|
||||
/* 상세(Drill-down) 창 */
|
||||
.perf-modal { position: fixed; inset: 0; z-index: 1000; background: rgba(0, 0, 0, .35); display: flex; align-items: center; justify-content: center; padding: 20px; }
|
||||
.perf-modal-card { background: #fff; border-radius: 14px; width: min(1100px, 100%); max-height: 88vh; display: flex; flex-direction: column; box-shadow: 0 20px 60px rgba(0, 0, 0, .25); }
|
||||
.perf-modal-card.is-narrow { width: min(560px, 100%); }
|
||||
.perf-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--perf-line); }
|
||||
.perf-modal-head h3 { margin: 0; font-size: 15px; font-weight: 600; }
|
||||
.perf-modal-body { padding: 12px 16px; overflow: auto; }
|
||||
.perf-modal-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--perf-line); flex-wrap: wrap; align-items: center; }
|
||||
.perf-modal-x { border: 0; background: none; font-size: 20px; cursor: pointer; color: var(--color-midtone-gray); }
|
||||
.perf-ev-cancel td { color: var(--perf-down); }
|
||||
|
||||
/* 설정 */
|
||||
.perf-set-table td, .perf-set-table th { vertical-align: middle; }
|
||||
.perf-set-table thead th { text-align: left; }
|
||||
.perf-set-table thead th:nth-child(2), .perf-set-table thead th:nth-child(3) { text-align: center; }
|
||||
.perf-set-table thead th:nth-child(4) { text-align: right; padding-right: 60px; }
|
||||
.perf-rate-cell { white-space: nowrap; }
|
||||
.perf-rate { display: inline-block; min-width: 56px; text-align: right; font-weight: 600; margin-right: 4px; }
|
||||
.perf-pill { display: inline-block; font-size: 11.5px; padding: 1px 8px; border-radius: 999px; background: var(--color-ghost-gray); color: var(--color-midtone-gray); white-space: nowrap; }
|
||||
.perf-pill.is-ok { background: #e6f8e9; color: #0f8a3a; }
|
||||
.perf-pill.is-bad { background: #fbe9e6; color: var(--perf-down); }
|
||||
.perf-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; white-space: nowrap; }
|
||||
.perf-status i { width: 8px; height: 8px; border-radius: 50%; background: #bdbdbd; display: inline-block; }
|
||||
.perf-status.st-ok i { background: #10b33a; }
|
||||
.perf-status.st-auth_failed i, .perf-status.st-token_expired i, .perf-status.st-api_error i { background: var(--perf-down); }
|
||||
.perf-status.st-not_configured i { background: #e0a526; }
|
||||
.perf-status.st-disabled { color: var(--color-midtone-gray); }
|
||||
.perf-err { font-size: 11px; color: var(--perf-down); max-width: 260px; white-space: normal; line-height: 1.35; margin-top: 2px; }
|
||||
.perf-switch { position: relative; display: inline-block; width: 34px; height: 20px; cursor: pointer; }
|
||||
.perf-switch input { opacity: 0; width: 0; height: 0; position: absolute; }
|
||||
.perf-switch span { position: absolute; inset: 0; background: #d4d4d4; border-radius: 999px; transition: background .15s; }
|
||||
.perf-switch span::after { content: ""; position: absolute; left: 3px; top: 3px; width: 14px; height: 14px; background: #fff; border-radius: 50%; transition: transform .15s; }
|
||||
.perf-switch input:checked + span { background: var(--color-deep-black); }
|
||||
.perf-switch input:checked + span::after { transform: translateX(14px); }
|
||||
.perf-switch input:focus-visible + span { outline: 2px solid #93c5fd; outline-offset: 2px; }
|
||||
.perf-dl { display: grid; grid-template-columns: 90px 1fr; gap: 6px 10px; margin: 0; font-size: 13px; }
|
||||
.perf-dl dt { color: var(--color-midtone-gray); }
|
||||
.perf-dl dd { margin: 0; }
|
||||
.perf-sample-form { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
|
||||
.perf-form { display: flex; flex-direction: column; gap: 12px; }
|
||||
.perf-form-row { display: flex; flex-direction: column; gap: 4px; }
|
||||
.perf-form-row > label { font-size: 12px; font-weight: 500; }
|
||||
.perf-form-row .erp-input { width: 100%; box-sizing: border-box; }
|
||||
.perf-form-help { font-size: 11.5px; color: var(--color-midtone-gray); }
|
||||
.perf-secret-state { font-size: 11.5px; color: #0f8a3a; }
|
||||
.perf-secret-state.is-empty { color: var(--color-midtone-gray); }
|
||||
.perf-inline { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.perf-test-result { font-size: 12.5px; margin-right: auto; }
|
||||
.perf-test-result.is-ok { color: #0f8a3a; }
|
||||
.perf-test-result.is-bad { color: var(--perf-down); }
|
||||
|
||||
@media (max-width: 1280px) {
|
||||
.perf-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 980px) {
|
||||
.perf-grid2 { grid-template-columns: 1fr; }
|
||||
.perf-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.perf-update { margin-left: 0; }
|
||||
}
|
||||
|
||||
.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; }
|
||||
|
||||
/* 주문 내역 창 — 열 제목은 가운데·굵게·150%, 창을 스크롤해도 위에 고정 */
|
||||
.perf-ev-wrap { overflow: visible; }
|
||||
.perf-ev-table thead th, .perf-ev-table thead th.perf-th-label {
|
||||
text-align: center; font-weight: 700; font-size: 18px; color: var(--color-deep-black, #111);
|
||||
position: sticky; top: -12px; z-index: 2;
|
||||
}
|
||||
.perf-ev-table thead th { background: var(--perf-soft, #fafafa); box-shadow: 0 1px 0 var(--perf-line, #e5e5e5); }
|
||||
/* 취소 행 — 행 전체를 기울임 + 취소선 + 회색 */
|
||||
.perf-ev-table tr.is-cancel td { font-style: italic; text-decoration: line-through; color: #9a9a9a; }
|
||||
@@ -0,0 +1,943 @@
|
||||
/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작.
|
||||
*
|
||||
* 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(/performance/api/…)로만.
|
||||
* 인증정보 창은 저장된 비밀값을 받지 않는다(서버가 "저장됨" 여부만 준다).
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// ── 공통 ─────────────────────────────────────────────
|
||||
function el(tag, attrs, html) {
|
||||
const n = document.createElement(tag);
|
||||
Object.keys(attrs || {}).forEach(function (k) {
|
||||
if (k === "class") n.className = attrs[k];
|
||||
else if (k === "text") n.textContent = attrs[k];
|
||||
else n.setAttribute(k, attrs[k]);
|
||||
});
|
||||
if (html != null) n.innerHTML = html;
|
||||
return n;
|
||||
}
|
||||
function esc(s) {
|
||||
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
||||
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
||||
});
|
||||
}
|
||||
function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
|
||||
function won(n) { return n ? fmt(n) : '<span class="perf-zero">–</span>'; }
|
||||
// 축 눈금용 짧은 금액(1.2억 / 350만)
|
||||
function short(n) {
|
||||
const a = Math.abs(n), s = n < 0 ? "-" : "";
|
||||
if (a >= 100000000) return s + (a / 100000000).toFixed(a >= 1000000000 ? 0 : 1).replace(/\.0$/, "") + "억";
|
||||
if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만";
|
||||
return s + fmt(a);
|
||||
}
|
||||
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) {
|
||||
const res = await fetch(url, {
|
||||
method: method,
|
||||
credentials: "same-origin",
|
||||
headers: body ? { "Content-Type": "application/json" } : {},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
let data = null;
|
||||
try { data = await res.json(); } catch (_) { data = null; }
|
||||
if (!res.ok) {
|
||||
const detail = data && data.detail;
|
||||
throw new Error(typeof detail === "string" ? detail : "요청 실패 (" + res.status + ")");
|
||||
}
|
||||
return data || {};
|
||||
}
|
||||
|
||||
// 간단한 창. 반환: { card, body, foot, close }
|
||||
function openModal(title, opts) {
|
||||
opts = opts || {};
|
||||
const back = el("div", { class: "perf-modal" });
|
||||
const card = el("div", { class: "perf-modal-card" + (opts.narrow ? " is-narrow" : ""), role: "dialog", "aria-modal": "true" });
|
||||
const head = el("div", { class: "perf-modal-head" });
|
||||
head.appendChild(el("h3", { text: title }));
|
||||
const x = el("button", { type: "button", class: "perf-modal-x", "aria-label": "닫기" }, "×");
|
||||
head.appendChild(x);
|
||||
const body = el("div", { class: "perf-modal-body" });
|
||||
const foot = el("div", { class: "perf-modal-foot" });
|
||||
card.appendChild(head); card.appendChild(body); card.appendChild(foot);
|
||||
back.appendChild(card);
|
||||
document.body.appendChild(back);
|
||||
function onKey(e) { if (e.key === "Escape") close(); }
|
||||
function close() {
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
back.remove();
|
||||
if (opts.onClose) opts.onClose();
|
||||
}
|
||||
x.addEventListener("click", close);
|
||||
back.addEventListener("mousedown", function (e) { if (e.target === back) close(); });
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
return { card: card, body: body, foot: foot, close: close };
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════
|
||||
// 대시보드
|
||||
// ════════════════════════════════════════════════════
|
||||
function initDashboard(root) {
|
||||
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
|
||||
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
|
||||
const KEY = "perf_metric";
|
||||
|
||||
// 표시 기준 전환 — 서버가 세 값을 다 그려 두었고 CSS 가 하나만 보인다.
|
||||
function setMetric(m) {
|
||||
if (!METRIC_NAMES[m]) m = "gross";
|
||||
root.dataset.metric = m;
|
||||
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
|
||||
b.classList.toggle("is-active", b.dataset.metric === m);
|
||||
});
|
||||
try { localStorage.setItem(KEY, m); } catch (_) {}
|
||||
drawDaily(m);
|
||||
drawShare(m);
|
||||
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
|
||||
}
|
||||
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
|
||||
b.addEventListener("click", function () { setMetric(b.dataset.metric); });
|
||||
});
|
||||
|
||||
// 직접선택 / 쇼핑몰 필터
|
||||
const customBtn = document.getElementById("perf-custom-btn");
|
||||
const customForm = document.getElementById("perf-custom");
|
||||
if (customBtn && customForm) customBtn.addEventListener("click", function () {
|
||||
customForm.hidden = !customForm.hidden;
|
||||
if (!customForm.hidden) customForm.querySelector("input[type=date]").focus();
|
||||
});
|
||||
const checkAll = root.querySelector("[data-perf-check-all]");
|
||||
if (checkAll) checkAll.addEventListener("click", function () {
|
||||
const boxes = root.querySelectorAll(".perf-filter-pop input[type=checkbox]");
|
||||
const allOn = Array.prototype.every.call(boxes, function (b) { return b.checked; });
|
||||
boxes.forEach(function (b) { b.checked = !allOn; });
|
||||
});
|
||||
document.addEventListener("click", function (e) {
|
||||
const f = document.getElementById("perf-filter");
|
||||
if (f && f.open && !f.contains(e.target)) f.open = false;
|
||||
});
|
||||
|
||||
// 매출 업데이트 — 서버가 쇼핑몰별로 따로 수집(한 곳 실패해도 나머지 반영)
|
||||
const syncBtn = document.getElementById("perf-sync-btn");
|
||||
const resultBox = document.getElementById("perf-sync-result");
|
||||
if (syncBtn) syncBtn.addEventListener("click", async function () {
|
||||
syncBtn.disabled = true;
|
||||
const label = syncBtn.textContent;
|
||||
syncBtn.textContent = "업데이트 중…";
|
||||
try {
|
||||
// 지금 보고 있는 기간(오늘까지)을 가져온다 — "이번달"이면 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 = [];
|
||||
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 = [];
|
||||
if (ok.length) parts.push("<b>반영</b> " + esc(ok.join(", ")));
|
||||
if (bad.length) parts.push("<b>실패</b> " + esc(bad.join(", ")));
|
||||
if (busy.length) parts.push("<b>이미 진행 중</b> " + esc(busy.join(", ")));
|
||||
if (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
|
||||
if (unset.length) parts.push('<span class="perf-muted">인증정보 미설정: ' + esc(unset.join(", ")) + "</span>");
|
||||
resultBox.innerHTML = parts.join(" · ") || "업데이트할 쇼핑몰이 없습니다.";
|
||||
resultBox.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
|
||||
resultBox.hidden = false;
|
||||
if (res.last_update_at) {
|
||||
const lu = document.querySelector("#perf-last-update b");
|
||||
if (lu) lu.textContent = res.last_update_at.slice(0, 16).replace("T", " ");
|
||||
}
|
||||
if (changed > 0) setTimeout(function () { location.reload(); }, 1200);
|
||||
} catch (err) {
|
||||
resultBox.textContent = "업데이트 실패: " + err.message;
|
||||
resultBox.className = "perf-notice is-warn";
|
||||
resultBox.hidden = false;
|
||||
} finally {
|
||||
syncBtn.disabled = false;
|
||||
syncBtn.textContent = label === "업데이트 중…" ? "매출 업데이트" : label;
|
||||
}
|
||||
});
|
||||
|
||||
// 금액 클릭 → 주문 상세
|
||||
root.addEventListener("click", function (e) {
|
||||
const td = e.target.closest("td.is-link");
|
||||
if (!td) return;
|
||||
openEvents(td.dataset.code, td.dataset.from, td.dataset.to);
|
||||
});
|
||||
async function openEvents(code, from, to) {
|
||||
const name = (data.names || {})[code] || code;
|
||||
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
|
||||
const m = openModal(title);
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
try {
|
||||
const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) +
|
||||
"&from=" + encodeURIComponent(from) + "&to=" + encodeURIComponent(to));
|
||||
const rows = res.rows || [];
|
||||
if (!rows.length) { m.body.innerHTML = '<p class="perf-muted">내역이 없습니다.</p>'; return; }
|
||||
const KIND = { SALE: "결제", CANCEL: "취소", RETURN: "반품", ADJUST: "조정" };
|
||||
let sum = 0, sales = 0, minus = 0;
|
||||
const body = rows.map(function (r) {
|
||||
sum += r.amount;
|
||||
if (r.amount >= 0) sales += r.amount; else minus += r.amount;
|
||||
return '<tr class="' + (r.event_type === "CANCEL" ? "is-cancel" : r.amount < 0 ? "perf-ev-cancel" : "") + '">' +
|
||||
"<td>" + esc(r.sales_date) + "</td><td>" + esc(KIND[r.event_type] || r.event_type) +
|
||||
(r.is_sample ? ' <span class="perf-pill">테스트</span>' : "") + "</td>" +
|
||||
"<td>" + esc(r.external_order_id) + "</td>" +
|
||||
"<td>" + esc(r.product_name) + (r.option_name ? " <span class='perf-muted'>" + esc(r.option_name) + "</span>" : "") + "</td>" +
|
||||
'<td class="perf-num">' + esc(r.quantity) + "</td>" +
|
||||
'<td class="perf-num">' + fmt(r.amount) + "</td>" +
|
||||
"<td>" + esc(r.order_date || "") + "</td><td>" + esc(r.payment_date || "") + "</td>" +
|
||||
"<td>" + esc(r.order_status) + "</td></tr>";
|
||||
}).join("");
|
||||
m.body.innerHTML =
|
||||
'<div class="perf-ev-wrap"><table class="perf-table perf-ev-table"><thead><tr>' +
|
||||
'<th class="perf-th-label">매출일</th><th class="perf-th-label">구분</th><th class="perf-th-label">주문번호</th>' +
|
||||
'<th class="perf-th-label">상품명</th><th>수량</th><th>금액</th><th class="perf-th-label">주문일</th>' +
|
||||
'<th class="perf-th-label">결제일</th><th class="perf-th-label">상태</th></tr></thead><tbody>' + body +
|
||||
'</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" colspan="5">결제 ' + fmt(sales) +
|
||||
" / 취소·반품 " + fmt(minus) + '</th><td class="perf-num">' + fmt(sum) + '</td><td colspan="3"></td></tr></tfoot></table></div>' +
|
||||
(res.truncated ? '<p class="perf-muted">처음 500건만 표시합니다.</p>' : "") +
|
||||
'<p class="perf-muted">수수료는 일·쇼핑몰 단위로 계산되어 주문별로는 표시하지 않습니다.</p>';
|
||||
} catch (err) {
|
||||
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
}
|
||||
}
|
||||
|
||||
// ── 그래프(SVG) ──
|
||||
function svg(w, h, inner) {
|
||||
return '<svg viewBox="0 0 ' + w + " " + h + '" preserveAspectRatio="none" role="img">' + inner + "</svg>";
|
||||
}
|
||||
function niceMax(v) {
|
||||
if (v <= 0) return 1;
|
||||
const p = Math.pow(10, Math.floor(Math.log10(v)));
|
||||
const n = v / p;
|
||||
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p;
|
||||
}
|
||||
function drawDaily(metric) {
|
||||
const box = document.getElementById("perf-chart-daily");
|
||||
if (!box) return;
|
||||
const pts = data.daily || [];
|
||||
const vals = pts.map(function (p) { return p[metric] || 0; });
|
||||
if (!pts.length || vals.every(function (v) { return !v; })) {
|
||||
box.innerHTML = '<div class="perf-chart-empty">기간 내 매출이 없습니다.</div>';
|
||||
return;
|
||||
}
|
||||
const W = 640, H = 230, L = 48, R = 8, T = 10, B = 26;
|
||||
const maxV = niceMax(Math.max.apply(null, vals.concat([0])));
|
||||
const minV = Math.min.apply(null, vals.concat([0])) < 0 ? -niceMax(-Math.min.apply(null, vals)) : 0;
|
||||
const y = function (v) { return T + (H - T - B) * (maxV - v) / (maxV - minV); };
|
||||
const bw = (W - L - R) / pts.length;
|
||||
let g = "";
|
||||
for (let i = 0; i <= 4; i++) {
|
||||
const v = minV + (maxV - minV) * i / 4;
|
||||
g += '<line class="grid" x1="' + L + '" x2="' + (W - R) + '" y1="' + y(v) + '" y2="' + y(v) + '"/>' +
|
||||
'<text x="' + (L - 6) + '" y="' + (y(v) + 3.5) + '" text-anchor="end">' + short(Math.round(v)) + "</text>";
|
||||
}
|
||||
const every = Math.ceil(pts.length / 16);
|
||||
pts.forEach(function (p, i) {
|
||||
const v = vals[i];
|
||||
const x = L + i * bw + bw * 0.15, w = Math.max(1, bw * 0.7);
|
||||
const y0 = y(0), y1 = y(v);
|
||||
g += '<rect class="bar' + (v < 0 ? " is-neg" : "") + '" x="' + x + '" y="' + Math.min(y0, y1) +
|
||||
'" width="' + w + '" height="' + Math.max(0.5, Math.abs(y1 - y0)) + '"><title>' + esc(p.label) + " " + fmt(v) + "원</title></rect>";
|
||||
if (i % every === 0) g += '<text x="' + (L + i * bw + bw / 2) + '" y="' + (H - 8) + '" text-anchor="middle">' + esc(p.label) + "</text>";
|
||||
});
|
||||
g += '<line class="axis" x1="' + L + '" x2="' + (W - R) + '" y1="' + y(0) + '" y2="' + y(0) + '"/>';
|
||||
box.innerHTML = svg(W, H, g);
|
||||
}
|
||||
function drawShare(metric) {
|
||||
const box = document.getElementById("perf-chart-share");
|
||||
if (!box) return;
|
||||
const rows = (data.share || []).slice().sort(function (a, b) { return (b[metric] || 0) - (a[metric] || 0); });
|
||||
const total = rows.reduce(function (s, r) { return s + Math.max(0, r[metric] || 0); }, 0);
|
||||
if (!rows.length || total <= 0) { box.innerHTML = '<div class="perf-chart-empty">기간 내 매출이 없습니다.</div>'; return; }
|
||||
const W = 640, rowH = 22, L = 120, R = 150, H = rows.length * rowH + 6;
|
||||
const maxV = Math.max.apply(null, rows.map(function (r) { return Math.max(0, r[metric] || 0); })) || 1;
|
||||
let g = "";
|
||||
rows.forEach(function (r, i) {
|
||||
const v = r[metric] || 0, y = 4 + i * rowH;
|
||||
const w = Math.max(0, (W - L - R) * Math.max(0, v) / maxV);
|
||||
const pct = total > 0 ? (Math.max(0, v) / total * 100).toFixed(1) : "0.0";
|
||||
g += '<text x="' + (L - 8) + '" y="' + (y + 14) + '" text-anchor="end">' + esc(r.name) + "</text>" +
|
||||
'<rect class="bar" x="' + L + '" y="' + (y + 4) + '" width="' + w + '" height="13"><title>' + esc(r.name) + " " + fmt(v) + "원</title></rect>" +
|
||||
'<text x="' + (L + w + 6) + '" y="' + (y + 14) + '">' + fmt(v) + " (" + pct + "%)</text>";
|
||||
});
|
||||
box.innerHTML = svg(W, H, g);
|
||||
}
|
||||
|
||||
let saved = null;
|
||||
try { saved = localStorage.getItem(KEY); } catch (_) {}
|
||||
setMetric(saved || root.dataset.metric || "gross");
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════
|
||||
// 설정
|
||||
// ════════════════════════════════════════════════════
|
||||
function initSettings(root) {
|
||||
// 사용 / 매출 집계 토글 — 바로 저장, 실패하면 되돌림
|
||||
root.querySelectorAll(".perf-switch input").forEach(function (box) {
|
||||
box.addEventListener("change", async function () {
|
||||
const tr = box.closest("tr");
|
||||
const payload = {};
|
||||
payload[box.dataset.field] = box.checked;
|
||||
box.disabled = true;
|
||||
try {
|
||||
await api("PUT", "/performance/api/marketplaces/" + tr.dataset.code, payload);
|
||||
} catch (err) {
|
||||
box.checked = !box.checked;
|
||||
alertMsg("저장 실패: " + err.message);
|
||||
} finally { box.disabled = false; }
|
||||
});
|
||||
});
|
||||
|
||||
root.addEventListener("click", function (e) {
|
||||
const btn = e.target.closest("button[data-act]");
|
||||
if (!btn) return;
|
||||
const tr = btn.closest("tr");
|
||||
const code = tr.dataset.code, name = tr.dataset.name;
|
||||
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
|
||||
else if (btn.dataset.act === "creds") openCreds(code, name);
|
||||
else if (btn.dataset.act === "test") runTest(code, name, btn);
|
||||
});
|
||||
|
||||
function today() {
|
||||
const d = new Date();
|
||||
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
|
||||
}
|
||||
|
||||
// ── 수수료율 ──
|
||||
async function openRate(code, name, hasHistory) {
|
||||
const m = openModal(name + " 수수료율", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
|
||||
m.body.innerHTML =
|
||||
'<form class="perf-form" id="perf-rate-form">' +
|
||||
'<div class="perf-form-row"><label for="perf-rate-in">수수료율(%)</label>' +
|
||||
'<input class="erp-input" id="perf-rate-in" inputmode="decimal" placeholder="예: 5, 10.8, 15.35" required /></div>' +
|
||||
'<div class="perf-form-row"><label for="perf-rate-from">적용 시작일</label>' +
|
||||
'<div class="perf-inline"><input class="erp-input perf-date" type="date" id="perf-rate-from" value="' + today() + '" />' +
|
||||
'<label class="perf-check"><input type="checkbox" id="perf-rate-all"' + (hasHistory ? "" : " checked") + " /> 처음부터(과거 전체)</label></div>" +
|
||||
'<div class="perf-form-help">이 날짜부터 새 요율로 계산하고, 그 전 실적은 예전 요율을 유지합니다.</div></div>' +
|
||||
'<div class="perf-form-row"><label for="perf-rate-memo">메모</label><input class="erp-input" id="perf-rate-memo" maxlength="200" /></div>' +
|
||||
"</form>" +
|
||||
'<h4 class="perf-h" style="margin:14px 0 6px">변경 이력</h4><div id="perf-rate-hist" class="perf-muted">불러오는 중…</div>';
|
||||
const save = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "저장");
|
||||
m.foot.appendChild(save);
|
||||
const from = m.body.querySelector("#perf-rate-from"), all = m.body.querySelector("#perf-rate-all");
|
||||
function syncAll() { from.disabled = all.checked; }
|
||||
all.addEventListener("change", syncAll); syncAll();
|
||||
|
||||
function renderHist(rates) {
|
||||
const box = m.body.querySelector("#perf-rate-hist");
|
||||
if (!rates.length) { box.textContent = "이력이 없습니다(현재 0%)."; return; }
|
||||
box.innerHTML = '<table class="perf-table"><thead><tr><th class="perf-th-label">적용 시작일</th><th>요율</th>' +
|
||||
'<th class="perf-th-label">메모</th><th class="perf-th-label">변경자</th><th></th></tr></thead><tbody>' +
|
||||
rates.map(function (r) {
|
||||
const eff = r.effective_from === "2000-01-01" ? "처음부터" : r.effective_from;
|
||||
return "<tr><td>" + esc(eff) + '</td><td class="perf-num">' + esc(String(r.rate_percent).replace(/\.?0+$/, "")) +
|
||||
"%</td><td>" + esc(r.memo) + "</td><td>" + esc((r.created_by || "").split("@")[0]) +
|
||||
'</td><td><button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-del="' + r.id + '">삭제</button></td></tr>';
|
||||
}).join("") + "</tbody></table>";
|
||||
}
|
||||
try { renderHist((await api("GET", "/performance/api/marketplaces/" + code + "/rates")).rates || []); }
|
||||
catch (err) { m.body.querySelector("#perf-rate-hist").textContent = err.message; }
|
||||
|
||||
m.body.addEventListener("click", async function (e) {
|
||||
const b = e.target.closest("button[data-del]");
|
||||
if (!b) return;
|
||||
if (!(await confirmMsg("이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다."))) return;
|
||||
try {
|
||||
renderHist((await api("DELETE", "/performance/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []);
|
||||
m.changed = true;
|
||||
} catch (err) { alertMsg(err.message); }
|
||||
});
|
||||
async function submit() {
|
||||
const rate = m.body.querySelector("#perf-rate-in").value.trim();
|
||||
if (!rate) { m.body.querySelector("#perf-rate-in").focus(); return; }
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/marketplaces/" + code + "/rates", {
|
||||
rate_percent: rate, effective_from: all.checked ? "2000-01-01" : from.value,
|
||||
memo: m.body.querySelector("#perf-rate-memo").value,
|
||||
});
|
||||
renderHist(res.rates || []);
|
||||
m.changed = true;
|
||||
m.body.querySelector("#perf-rate-in").value = "";
|
||||
} catch (err) { alertMsg(err.message); }
|
||||
}
|
||||
save.addEventListener("click", submit);
|
||||
m.body.querySelector("#perf-rate-form").addEventListener("submit", function (e) { e.preventDefault(); submit(); });
|
||||
m.body.querySelector("#perf-rate-in").focus();
|
||||
}
|
||||
|
||||
// ── API 인증정보 ──
|
||||
async function openCreds(code, name) {
|
||||
const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
let info;
|
||||
try { info = await api("GET", "/performance/api/marketplaces/" + code + "/credentials"); }
|
||||
catch (err) { m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>"; return; }
|
||||
|
||||
const result = el("span", { class: "perf-test-result" });
|
||||
m.foot.appendChild(result);
|
||||
const testBtn = el("button", { type: "button", class: "erp-btn erp-btn-outline" }, "연결 테스트");
|
||||
m.foot.appendChild(testBtn);
|
||||
|
||||
let html = "";
|
||||
if (info.note) html += '<p class="perf-muted">' + esc(info.note) + "</p>";
|
||||
if (info.docs_url) html += '<p class="perf-muted">API 문서: <a href="' + esc(info.docs_url) + '" target="_blank" rel="noopener noreferrer">' + esc(info.docs_url) + "</a></p>";
|
||||
if (info.shared) {
|
||||
m.body.innerHTML = html + '<p class="perf-notice">이 쇼핑몰은 기존 공통 연동을 사용합니다. 연결 테스트로 상태만 확인할 수 있습니다.</p>';
|
||||
} else {
|
||||
if (!info.key || !info.key.ok) html += '<p class="perf-notice is-warn">' + esc((info.key && info.key.message) || "암호화 키가 없습니다.") + "</p>";
|
||||
if (info.decrypt_error) html += '<p class="perf-notice is-warn">' + esc(info.decrypt_error) + "</p>";
|
||||
html += '<form class="perf-form" id="perf-cred-form" autocomplete="off">' + info.fields.map(function (f) {
|
||||
const id = "perf-cred-" + f.key;
|
||||
let state = "";
|
||||
if (f.secret) {
|
||||
state = f.has_value
|
||||
? '<span class="perf-secret-state">현재 값: •••••••• (저장됨' + (f.updated_at ? ", " + esc(f.updated_at.slice(0, 16).replace("T", " ")) : "") + ")</span>"
|
||||
: '<span class="perf-secret-state is-empty">저장된 값 없음</span>';
|
||||
}
|
||||
return '<div class="perf-form-row"><label for="' + id + '">' + esc(f.label) + (f.required ? " *" : "") + "</label>" + state +
|
||||
'<input class="erp-input" id="' + id + '" data-key="' + esc(f.key) + '" ' +
|
||||
(f.secret ? 'type="password" autocomplete="new-password" placeholder="' + (f.has_value ? "변경할 때만 새 값 입력" : "입력") + '"'
|
||||
: 'type="text" value="' + esc(f.value || "") + '" placeholder="' + esc(f.placeholder || "") + '"') + " />" +
|
||||
(f.help ? '<div class="perf-form-help">' + esc(f.help) + "</div>" : "") +
|
||||
(f.secret && f.has_value && !f.required ? '<label class="perf-check"><input type="checkbox" data-clear="' + esc(f.key) + '" /> 저장된 값 지우기</label>' : "") +
|
||||
"</div>";
|
||||
}).join("") + "</form>" +
|
||||
'<p class="perf-foot perf-muted">[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 칸은 저장된 값 사용). ' +
|
||||
"[저장]은 연결 테스트 결과와 관계없이 저장합니다 — 쇼핑몰의 일시 장애로 테스트가 실패할 수 있기 때문입니다. " +
|
||||
"저장 후 자동으로 한 번 더 연결 테스트를 합니다.</p>";
|
||||
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, res.ok ? { tone: "ok" } : undefined);
|
||||
location.reload();
|
||||
} catch (err) {
|
||||
alertMsg(err.message);
|
||||
} finally { btn.disabled = false; btn.textContent = label; }
|
||||
}
|
||||
|
||||
// ── 카페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;
|
||||
const out = document.getElementById("perf-recon-result");
|
||||
if (!day) return;
|
||||
recon.disabled = true;
|
||||
out.innerHTML = '<p class="perf-muted">카페24에서 불러오는 중…</p>';
|
||||
try {
|
||||
const r = await api("GET", "/performance/api/marketplaces/cafe24/reconcile?date=" + encodeURIComponent(day));
|
||||
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; return; }
|
||||
const s = r.orders.self, m = r.orders.market, rs = r.refunds.self, rm = r.refunds.market;
|
||||
const dev = function (n, amt) { return n ? fmt(n) + '건 <span class="perf-muted">' + won(amt) + "</span>" : won(0); };
|
||||
const MARKET_NAMES = {};
|
||||
root.querySelectorAll("tr[data-code]").forEach(function (tr) { MARKET_NAMES[tr.dataset.code] = tr.dataset.name; });
|
||||
const disc = ["membership_discount_amount", "set_product_discount_amount", "app_discount_amount",
|
||||
"market_other_discount_amount", "shipping_fee_discount_amount"];
|
||||
const coup = ["coupon_discount_price", "coupon_shipping_fee_amount"];
|
||||
const LABEL = {
|
||||
membership_discount_amount: "회원할인", set_product_discount_amount: "세트상품할인", app_discount_amount: "앱할인",
|
||||
market_other_discount_amount: "마켓 기타할인", shipping_fee_discount_amount: "배송비할인",
|
||||
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", 0], ["품목수(수량 합계)", s.items, m.items, "cnt", 1], ["품목수(품목 줄 수)", s.lines, m.lines, "cnt", 1],
|
||||
["상품구매금액", s.order_price_amount, m.order_price_amount, "", 2],
|
||||
["배송비", 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), "", 5]])
|
||||
.concat(coup.map(function (k) { return [" · " + LABEL[k], s[k], m[k], "sub"]; }))
|
||||
.concat([
|
||||
[" 참고식: 상품구매금액 + 배송비 − 할인 − 쿠폰", s.goods_total, m.goods_total, "sub"],
|
||||
["실결제금액", s.payment_amount, m.payment_amount, "", 6],
|
||||
["적립금 사용", s.points_spent_amount, m.points_spent_amount, "", 7],
|
||||
["예치금 사용", s.credits_spent_amount, m.credits_spent_amount, "", 8],
|
||||
["네이버포인트", s.naver_point, m.naver_point, "", 9],
|
||||
["결제합계(실결제 + 적립금 + 예치금 + 네이버포인트)", s.total, m.total, "key", 10],
|
||||
["환불 건수(환불 목록)", 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", 11],
|
||||
["순매출(결제합계 − 환불합계)", s.total - rs.total, m.total - rm.total, "key", 12],
|
||||
]);
|
||||
const shopCols = (lastShop[r.date] || {}).cols || null;
|
||||
out.innerHTML = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">' + esc(r.date) +
|
||||
"</th><th>카페24 열(자체몰 채널)</th><th>다른 쇼핑몰 열(외부 마켓)</th>" +
|
||||
(shopCols ? "<th>합계</th><th>카페24 화면</th><th>차이</th>" : "") + "</tr></thead><tbody>" +
|
||||
rows.map(function (x) {
|
||||
const cls = x[3] === "key" ? ' class="perf-row-week"' : "";
|
||||
const f = function (v) { return x[3] === "cnt" ? fmt(v) : won(v); };
|
||||
let cmp = "";
|
||||
if (shopCols) {
|
||||
const both = (x[1] || 0) + (x[2] || 0), c = x[4] == null ? null : shopCols[x[4]];
|
||||
cmp = '<td class="perf-num">' + f(both) + '</td><td class="perf-num">' + (c == null ? "" : f(c)) + '</td><td class="perf-num">' +
|
||||
(c == null ? "" : both === c ? '<span class="perf-diff-ok">✓</span>' : '<span class="perf-diff-bad">' + (both > c ? "+" : "") + fmt(both - c) + "</span>") + "</td>";
|
||||
}
|
||||
return "<tr" + cls + '><th class="perf-td-label' + (x[3] === "sub" ? " perf-muted" : "") + '">' + esc(x[0]) +
|
||||
'</th><td class="perf-num">' + f(x[1]) + '</td><td class="perf-num">' + f(x[2]) + "</td>" + cmp + "</tr>";
|
||||
}).join("") + "</tbody></table>" +
|
||||
(r.refund_basis
|
||||
? (function () {
|
||||
const b = r.refund_basis;
|
||||
const row = function (label, x, cls) {
|
||||
return "<tr" + (cls ? ' class="' + cls + '"' : "") + '><th class="perf-td-label">' + label + '</th><td class="perf-num">' +
|
||||
fmt(x.count) + '</td><td class="perf-num">' + won(x.actual_refund_amount) + '</td><td class="perf-num">' +
|
||||
won(x.used_points + x.used_credits) + '</td><td class="perf-num">' + won(x.with_points) + "</td></tr>";
|
||||
};
|
||||
return '<h4 class="perf-h" style="margin:14px 0 6px">환불 기준 비교 — 카페24 화면의 그날 "환불합계"와 같은 칸을 찾아 주세요</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">기준</th><th>건수</th><th>실제 환불액</th>' +
|
||||
"<th>적립금·예치금 환불</th><th>합계(포함)</th></tr></thead><tbody>" +
|
||||
row("환불완료일 기준 · 완료 <span class='perf-pill is-ok'>적용(합계 포함 칸)</span>", b.completed, "perf-row-week") +
|
||||
row("환불접수일 기준 · 전체 상태", b.accepted_all) +
|
||||
(b.by_pay_date ? row("결제일 기준 · 그날 결제한 주문의 환불(오늘까지" +
|
||||
(b.by_pay_date.refund_dates.length ? ", 환불일 " + esc(b.by_pay_date.refund_dates.join(", ")) : "") + ")", b.by_pay_date) : "") +
|
||||
(b.accepted_by_status || []).map(function (s) {
|
||||
return row(" · 접수일 기준 " + esc(s.label), s);
|
||||
}).join("") + "</tbody></table>";
|
||||
})()
|
||||
: "") +
|
||||
((r.refund_candidates || []).length
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">환불합계 후보 — 카페24 화면 값을 넣으면 같은 줄을 표시합니다</h4>' +
|
||||
'<div class="perf-row-inline" style="margin-bottom:6px"><input class="erp-input perf-date" type="text" inputmode="numeric" ' +
|
||||
'id="perf-recon-target" placeholder="카페24 환불합계" /></div>' +
|
||||
'<table class="perf-table" id="perf-recon-cands"><thead><tr><th class="perf-th-label">후보</th><th>금액</th><th>차이</th></tr></thead><tbody>' +
|
||||
r.refund_candidates.map(function (c) {
|
||||
return '<tr data-amount="' + c.amount + '"><td class="perf-td-label">' + esc(c.label) + '</td><td class="perf-num">' +
|
||||
won(c.amount) + '</td><td class="perf-num perf-cand-diff">–</td></tr>';
|
||||
}).join("") + "</tbody></table>"
|
||||
: "") +
|
||||
((r.refund_list || []).length
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 건별 (환불 API)</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">환불코드</th><th class="perf-th-label">주문번호</th>' +
|
||||
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">접수일</th><th class="perf-th-label">완료일</th>' +
|
||||
"<th>수량</th><th>실제 환불액</th><th>적립금·예치금</th><th class=\"perf-th-label\">환불수단</th></tr></thead><tbody>" +
|
||||
r.refund_list.map(function (x) {
|
||||
const st = { T: "환불완료", F: "환불전", M: "환불보류" }[x.status] || x.status;
|
||||
return '<tr><td class="perf-td-label">' + esc(x.refund_code) + "</td><td>" + esc(x.order_id) + "</td><td>" + esc(x.channel || "–") +
|
||||
"</td><td>" + esc(st) + "</td><td>" + esc(x.accepted_date || "–") + "</td><td>" + esc(x.refund_date || "–") +
|
||||
'</td><td class="perf-num">' + fmt(x.quantity) + '</td><td class="perf-num">' + won(x.actual_refund_amount) +
|
||||
'</td><td class="perf-num">' + won(x.used_points + x.used_credits) + "</td><td>" + esc((x.methods || []).join(", ") || "–") + "</td></tr>";
|
||||
}).join("") + "</tbody></table>"
|
||||
: "") +
|
||||
((r.no_record_claims || []).length
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">환불 목록에 없는 네이버페이 취소·반품 (환불합계에 넣은 건 — 주문 전체취소면 배송비 포함)</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">품목</th>' +
|
||||
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">반영일</th><th class="perf-th-label">상품</th>' +
|
||||
"<th>수량</th><th>뺀 금액</th><th>품목 결제금액</th><th>쿠폰</th><th class=\"perf-th-label\">주문 전체취소</th><th>주문 배송비</th></tr></thead><tbody>" +
|
||||
r.no_record_claims.map(function (c) {
|
||||
return '<tr><td class="perf-td-label">' + esc(c.order_id) + "</td><td>" + esc(c.item_code) + "</td><td>" + esc(c.place_name || c.market_id || "–") +
|
||||
"</td><td>" + esc(c.status + (c.naver_pay_claim_status ? " / 네이버페이 " + c.naver_pay_claim_status : "")) + "</td><td>" + esc(c.day) +
|
||||
"</td><td>" + esc(c.product_name) + '</td><td class="perf-num">' + fmt(c.quantity) + '</td><td class="perf-num">' + won(c.amount) +
|
||||
(c.shipping_refund ? ' <span class="perf-muted">(배송비 ' + fmt(c.shipping_refund) + ")</span>" : "") +
|
||||
'</td><td class="perf-num">' + won(c.item_payment_amount) + '</td><td class="perf-num">' + won(c.coupon) + "</td><td>" +
|
||||
(c.order_all_claimed ? "<b>예</b>" : "아니오") + '</td><td class="perf-num">' + won(c.order_shipping_fee) + "</td></tr>";
|
||||
}).join("") + "</tbody></table>"
|
||||
: "") +
|
||||
((r.reduced_orders || []).length
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">그날 결제한 주문 중 금액이 줄어든 주문 (취소·반품) — "환불 기록 없음"이 환불 API 에 안 잡힌 건</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">채널</th>' +
|
||||
'<th class="perf-th-label">결제수단</th><th class="perf-th-label">품목 상태</th><th class="perf-th-label">취소·환불일</th>' +
|
||||
"<th>결제 당시</th><th>현재</th><th>줄어든 금액</th><th>환불 기록</th></tr></thead><tbody>" +
|
||||
r.reduced_orders.map(function (x) {
|
||||
const miss = x.diff - x.refunded;
|
||||
return "<tr" + (miss > 0 ? ' class="perf-row-match"' : "") + '><td class="perf-td-label">' + esc(x.order_id) + "</td><td>" +
|
||||
esc(x.channel || "–") + "</td><td>" + esc(x.payment || "–") + "</td><td>" +
|
||||
esc(x.statuses.join(", ") + (x.naver_pay.length ? " / 네이버페이 " + x.naver_pay.join(",") : "")) + "</td><td>" +
|
||||
esc(x.claim_dates.join(", ") || "–") + '</td><td class="perf-num">' + won(x.initial) + '</td><td class="perf-num">' +
|
||||
won(x.now) + '</td><td class="perf-num">' + won(x.diff) + '</td><td class="perf-num">' +
|
||||
(x.refunded ? won(x.refunded) + ' <span class="perf-muted">' + esc(x.refund_dates.join(", ")) + "</span>" : "<b>없음</b>") + "</td></tr>";
|
||||
}).join("") + "</tbody></table>"
|
||||
: "") +
|
||||
(r.claims
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">그날 취소·반품·교환 완료 품목 (주문 API)</h4>' +
|
||||
((r.claims.errors || []).length ? '<p class="perf-notice is-warn">' + esc(r.claims.errors.join(" / ")) + "</p>" : "") +
|
||||
((r.claims.items || []).length
|
||||
? '<table class="perf-table"><thead><tr><th class="perf-th-label">조회</th><th class="perf-th-label">주문번호</th>' +
|
||||
'<th class="perf-th-label">채널</th><th class="perf-th-label">상태</th><th class="perf-th-label">클레임</th><th class="perf-th-label">상품</th>' +
|
||||
"<th>수량</th><th>판매가×수량</th><th>품목 결제금액</th><th>쿠폰</th><th class=\"perf-th-label\">환불 기록</th></tr></thead><tbody>" +
|
||||
r.claims.items.map(function (c) {
|
||||
return "<tr" + (c.done ? "" : ' class="perf-muted"') + '><td class="perf-td-label">' + esc(c.via) + "</td><td>" + esc(c.order_id) +
|
||||
"</td><td>" + esc(c.channel || "–") + "</td><td>" + esc(c.status + (c.status_text ? " " + c.status_text : "")) +
|
||||
"</td><td>" + esc(c.claim_code || "–") + "</td><td>" + esc(c.product_name) + '</td><td class="perf-num">' + fmt(c.quantity) +
|
||||
'</td><td class="perf-num">' + won(c.product_amount) + '</td><td class="perf-num">' + won(c.payment_amount) +
|
||||
'</td><td class="perf-num">' + won(c.coupon) + "</td><td>" + (c.has_refund ? "있음" : '<b>없음</b>') + "</td></tr>";
|
||||
}).join("") + "</tbody></table>" +
|
||||
'<p class="perf-foot perf-muted">전체취소 주문 배송비 ' + won(r.claims.full_cancel_shipping) +
|
||||
'. 흐린 줄은 아직 완료되지 않은 클레임(후보 합계에서 제외).</p>'
|
||||
: '<p class="perf-muted">없음</p>')
|
||||
: "") +
|
||||
((r.by_channel || []).length
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">주문 채널별</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">market_id</th><th class="perf-th-label">주문경로</th>' +
|
||||
'<th class="perf-th-label">구분</th><th class="perf-th-label">반영 열</th><th>주문수</th><th>결제합계</th>' +
|
||||
"<th>PC 주문</th><th>모바일 주문</th><th>환불</th><th>순매출</th></tr></thead><tbody>" +
|
||||
r.by_channel.map(function (b) {
|
||||
const col = MARKET_NAMES[b.target] || b.target;
|
||||
const kind = b.kind === "self" ? "자체몰 채널" + (b.label ? "(" + b.label + ")" : "")
|
||||
: b.kind === "market" ? "외부 마켓" : '<span class="perf-err" style="display:inline">알 수 없는 채널</span>';
|
||||
return '<tr><td class="perf-td-label">' + esc(b.market_id) + "</td><td>" + esc(b.place || "–") +
|
||||
(b.place_id && b.place_id !== b.place ? ' <span class="perf-muted">' + esc(b.place_id) + "</span>" : "") +
|
||||
"</td><td>" + (b.kind === "unknown" ? kind : esc(kind)) + "</td><td>" + esc(col) +
|
||||
'</td><td class="perf-num">' + fmt(b.orders) + '</td><td class="perf-num">' + won(b.total) +
|
||||
'</td><td class="perf-num">' + dev(b.pc_orders, b.pc_total) + '</td><td class="perf-num">' + dev(b.mobile_orders, b.mobile_total) +
|
||||
'</td><td class="perf-num">' + won(-b.refund_amount) + '</td><td class="perf-num">' + won(b.total - b.refund_amount) + "</td></tr>";
|
||||
}).join("") + "</tbody>" +
|
||||
// 카페24 열(자체몰) 기기 합계
|
||||
(function () {
|
||||
const own = r.by_channel.filter(function (b) { return b.target === "cafe24"; });
|
||||
const t = own.reduce(function (a, b) {
|
||||
a.o += b.orders; a.t += b.total; a.po += b.pc_orders; a.pt += b.pc_total; a.mo += b.mobile_orders; a.mt += b.mobile_total;
|
||||
a.ra += b.refund_amount; return a;
|
||||
}, { o: 0, t: 0, po: 0, pt: 0, mo: 0, mt: 0, ra: 0 });
|
||||
return '<tfoot><tr class="perf-row-week"><th class="perf-td-label" colspan="4">카페24 열(자체몰) 합계</th><td class="perf-num">' +
|
||||
fmt(t.o) + '</td><td class="perf-num">' + won(t.t) + '</td><td class="perf-num">' + dev(t.po, t.pt) +
|
||||
'</td><td class="perf-num">' + dev(t.mo, t.mt) + '</td><td class="perf-num">' + won(-t.ra) +
|
||||
'</td><td class="perf-num">' + won(t.t - t.ra) + "</td></tr></tfoot>";
|
||||
})() + "</table>" +
|
||||
'<p class="perf-foot perf-muted">한 줄 = market_id × 주문경로. market_id "self"는 PC 전용이 아니라 자체몰 전체이며, 그 안에 PC쇼핑몰·모바일웹 경로가 섞여 있습니다. ' +
|
||||
'PC/모바일 주문은 카페24가 주문마다 주는 모바일 주문 여부(order_from_mobile) 기준입니다.</p>'
|
||||
: "") +
|
||||
((r.by_payment || []).length
|
||||
? '<h4 class="perf-h" style="margin:14px 0 6px">결제수단별 (카페24 열)</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">결제수단</th><th>주문수</th><th>결제합계</th><th>비중</th></tr></thead><tbody>' +
|
||||
(function () {
|
||||
const tot = r.by_payment.reduce(function (a, p) { return a + p.total; }, 0);
|
||||
return r.by_payment.map(function (p) {
|
||||
return '<tr><td class="perf-td-label">' + esc(p.method) + '</td><td class="perf-num">' + fmt(p.orders) +
|
||||
'</td><td class="perf-num">' + won(p.total) + '</td><td class="perf-num">' +
|
||||
(tot > 0 ? (p.total / tot * 100).toFixed(1) + "%" : "–") + "</td></tr>";
|
||||
}).join("");
|
||||
})() + "</tbody></table>"
|
||||
: "") +
|
||||
(r.diag
|
||||
? (function () {
|
||||
// 판매가 합계 − 카페24 상품구매금액 = 찾는 금액(예: 9/23 → 62). 같은 값인 필드를 강조.
|
||||
const gap = shopCols ? (s.order_price_amount + m.order_price_amount) - shopCols[2] : null;
|
||||
const PART = { initial: "주문 금액(결제 당시 initial_order_amount)", actual: "주문 금액(현재 actual_order_amount)",
|
||||
item: "품목(items) 합계", order: "주문 최상위 필드" };
|
||||
const cells = ["initial", "actual", "item", "order"].map(function (p) {
|
||||
const f = r.diag[p] || {};
|
||||
const keys = Object.keys(f).filter(function (k) { return f[k]; });
|
||||
return '<div><h5 class="perf-h" style="margin:6px 0">' + esc(PART[p]) + "</h5>" +
|
||||
(keys.length ? '<table class="perf-table"><tbody>' + keys.map(function (k) {
|
||||
return "<tr" + (gap && f[k] === gap ? ' class="perf-row-match"' : "") + '><td class="perf-td-label">' + esc(k) +
|
||||
'</td><td class="perf-num">' + fmt(f[k]) + "</td></tr>";
|
||||
}).join("") + "</tbody></table>" : '<p class="perf-muted">0 아닌 값 없음</p>') + "</div>";
|
||||
}).join("");
|
||||
const odd = (r.odd_orders || []).map(function (o) {
|
||||
return '<tr><td class="perf-td-label">' + esc(o.order_id) + "</td><td>" + esc(o.channel || "–") + '</td><td class="perf-num">' +
|
||||
fmt(o.items_gross) + '</td><td class="perf-num">' + fmt(o.order_price_amount) + '</td><td class="perf-num">' + fmt(o.total) +
|
||||
'</td><td style="white-space:normal;font-size:11.5px">' + o.items.map(function (i) {
|
||||
return esc(i.code + " " + i.status + " ×" + i.quantity + " — " +
|
||||
Object.keys(i.fields).map(function (k) { return k + "=" + fmt(i.fields[k]); }).join(", "));
|
||||
}).join("<br>") + "</td></tr>";
|
||||
}).join("");
|
||||
return '<h4 class="perf-h" style="margin:14px 0 6px">원본 금액 필드 합계 (진단 — 그날 결제 주문 전체)' +
|
||||
(gap ? ' · 판매가 합계 − 카페24 상품구매금액 = <b>' + fmt(gap) + "</b> (같은 값 강조)" : "") + "</h4>" +
|
||||
'<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:10px">' + cells + "</div>" +
|
||||
(odd ? '<h4 class="perf-h" style="margin:14px 0 6px">상품금액이 100원 단위가 아니거나 판매가×수량 합과 다른 주문</h4>' +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">주문번호</th><th class="perf-th-label">채널</th><th>판매가×수량</th>' +
|
||||
'<th>주문 상품금액</th><th>결제합계(계산)</th><th class="perf-th-label">품목 금액 필드(0 제외)</th></tr></thead><tbody>' + odd + "</tbody></table>" : "");
|
||||
})()
|
||||
: "") +
|
||||
'<p class="perf-foot perf-muted">' + esc(r.formula) + ". 미결제 주문 " + fmt(r.unpaid_orders) +
|
||||
"건 제외. \"알 수 없는 채널\"은 카페24 열에 넣습니다 — 외부 마켓이면 어느 쇼핑몰인지 알려 주세요.</p>";
|
||||
const target = document.getElementById("perf-recon-target");
|
||||
if (target) target.addEventListener("input", function () {
|
||||
const v = parseInt(target.value.replace(/[^0-9-]/g, ""), 10);
|
||||
out.querySelectorAll("#perf-recon-cands tr[data-amount]").forEach(function (tr) {
|
||||
const a = parseInt(tr.dataset.amount, 10);
|
||||
const d = tr.querySelector(".perf-cand-diff");
|
||||
if (isNaN(v)) { d.textContent = "–"; tr.classList.remove("perf-row-match"); return; }
|
||||
d.textContent = a === v ? "일치" : fmt(a - v);
|
||||
tr.classList.toggle("perf-row-match", a === v);
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
} 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],
|
||||
cols: n >= 13 ? nums.slice(n - 13) : null };
|
||||
});
|
||||
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 = lastShop = parseDaily(document.getElementById("perf-daily-paste").value);
|
||||
const dates = Object.keys(shop).sort();
|
||||
if (!dates.length) { out.innerHTML = '<p class="perf-notice is-warn">날짜가 있는 줄을 찾지 못했습니다. 카페24 일별 매출내역 표를 복사해 붙여 넣으세요.</p>'; return; }
|
||||
const live = document.getElementById("perf-daily-live").checked;
|
||||
dailyBtn.disabled = true;
|
||||
out.innerHTML = '<p class="perf-muted">' + (live ? "저장값과 카페24 API 값을 계산하는 중… (기간이 길면 1~2분)" : "저장값을 불러오는 중…") + "</p>";
|
||||
try {
|
||||
const from = dates[0], to = dates[dates.length - 1];
|
||||
const r = await api("GET", "/performance/api/marketplaces/cafe24/daily-check?from=" + from + "&to=" + to + (live ? "&live=1" : ""));
|
||||
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc(r.message) + "</p>"; return; }
|
||||
const byDate = function (rows) { const o = {}; (rows || []).forEach(function (x) { o[x.date] = x; }); return o; };
|
||||
const db = byDate(r.db), lv = r.live ? byDate(r.live) : null;
|
||||
const zero = { paid: 0, refund: 0, orders: 0 };
|
||||
const diff = function (ours, theirs) {
|
||||
const d = ours - theirs;
|
||||
return d === 0 ? '<span class="perf-diff-ok">✓</span>' : '<span class="perf-diff-bad">' + (d > 0 ? "+" : "") + fmt(d) + "</span>";
|
||||
};
|
||||
const todayIso = today();
|
||||
let bad = 0, stale = 0, rule = 0;
|
||||
const sum = { cp: 0, cr: 0, dp: 0, dr: 0, lp: 0, lr: 0 };
|
||||
const body = dates.slice().reverse().map(function (d) {
|
||||
const c = shop[d], x = db[d] || zero, l = lv ? (lv[d] || zero) : null;
|
||||
sum.cp += c.paid; sum.cr += c.refund; sum.dp += x.paid; sum.dr += x.refund;
|
||||
if (l) { sum.lp += l.paid; sum.lr += l.refund; }
|
||||
const dbOk = x.paid === c.paid && x.refund === c.refund;
|
||||
const liveOk = l && l.paid === c.paid && l.refund === c.refund;
|
||||
let verdict;
|
||||
if (dbOk) verdict = '<span class="perf-pill is-ok">일치</span>';
|
||||
else if (l && liveOk) { verdict = '<span class="perf-pill">다시 가져오면 해결</span>'; stale++; }
|
||||
else if (l) {
|
||||
const what = [l.paid !== c.paid ? "결제" : "", l.refund !== c.refund ? "환불" : ""].filter(Boolean).join("·");
|
||||
verdict = '<span class="perf-pill is-bad">규칙 차이(' + what + ")</span>"; rule++;
|
||||
} else verdict = '<span class="perf-pill is-bad">차이</span>';
|
||||
if (!dbOk) bad++;
|
||||
const wd = "일월화수목금토"[new Date(d + "T00:00:00").getDay()];
|
||||
return "<tr" + (dbOk ? "" : ' class="perf-row-diff"') + '><td class="perf-td-label"><button type="button" class="perf-link" data-recon-day="' + d + '">' +
|
||||
esc(d) + "(" + wd + ")</button>" + (d === todayIso ? ' <span class="perf-muted">오늘·집계 중</span>' : "") + "</td>" +
|
||||
'<td class="perf-num">' + (c.orders == null ? "–" : fmt(c.orders)) + ' <span class="perf-muted">/ ' + fmt(x.orders) + (l ? " / " + fmt(l.orders) : "") + "</span></td>" +
|
||||
'<td class="perf-num">' + won(c.paid) + '</td><td class="perf-num">' + diff(x.paid, c.paid) + "</td>" + (l ? '<td class="perf-num">' + diff(l.paid, c.paid) + "</td>" : "") +
|
||||
'<td class="perf-num">' + won(c.refund) + '</td><td class="perf-num">' + diff(x.refund, c.refund) + "</td>" + (l ? '<td class="perf-num">' + diff(l.refund, c.refund) + "</td>" : "") +
|
||||
"<td>" + verdict + (x.synced_at ? '<div class="perf-muted" style="font-size:11px">저장 ' + esc(String(x.synced_at).slice(5, 16).replace("T", " ")) + "</div>" : "") + "</td></tr>";
|
||||
}).join("");
|
||||
const head = '<tr><th class="perf-th-label">날짜</th><th>주문수 <span class="perf-muted">카페24 / 저장' + (lv ? " / API" : "") + "</span></th>" +
|
||||
"<th>결제합계(카페24)</th><th>저장값 차이</th>" + (lv ? "<th>API 차이</th>" : "") +
|
||||
"<th>환불합계(카페24)</th><th>저장값 차이</th>" + (lv ? "<th>API 차이</th>" : "") + '<th class="perf-th-label">판정</th></tr>';
|
||||
const foot = '<tr class="perf-row-week"><th class="perf-td-label">합계</th><td></td><td class="perf-num">' + won(sum.cp) + '</td><td class="perf-num">' +
|
||||
diff(sum.dp, sum.cp) + "</td>" + (lv ? '<td class="perf-num">' + diff(sum.lp, sum.cp) + "</td>" : "") + '<td class="perf-num">' + won(sum.cr) +
|
||||
'</td><td class="perf-num">' + diff(sum.dr, sum.cr) + "</td>" + (lv ? '<td class="perf-num">' + diff(sum.lr, sum.cr) + "</td>" : "") + "<td></td></tr>";
|
||||
const summary = bad
|
||||
? "저장값이 다른 날 " + bad + "일" + (lv ? " — 다시 가져오면 해결 " + stale + "일, 규칙 차이 " + rule + "일" : " — [API 값도 계산]을 켜고 다시 비교하면 원인을 나눠 볼 수 있습니다")
|
||||
: "모든 날짜가 일치합니다.";
|
||||
out.innerHTML = '<p class="perf-notice ' + (bad ? "is-warn" : "is-ok") + '" style="margin-top:8px">' + esc(summary) +
|
||||
(r.live_error ? "<br>API 계산 실패: " + esc(r.live_error) : "") + "</p>" +
|
||||
(stale ? '<div class="perf-sample-form"><button type="button" class="erp-btn erp-btn-primary" id="perf-daily-resync" data-from="' + from +
|
||||
'" data-to="' + to + '">' + esc(from + " ~ " + to) + " 카페24 다시 가져오기</button></div>" : "") +
|
||||
'<table class="perf-table" style="margin-top:8px"><thead>' + head + "</thead><tbody>" + body + "</tbody><tfoot>" + foot + "</tfoot></table>" +
|
||||
'<p class="perf-foot perf-muted">차이 = 우리 값 − 카페24 값. 저장값은 카페24 수집분 전체(카페24 화면과 같은 범위)입니다.</p>';
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
} 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;
|
||||
}
|
||||
});
|
||||
|
||||
// ── 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 = '<p class="perf-muted">11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)</p>';
|
||||
try {
|
||||
const to = document.getElementById("perf-probe-to").value || day;
|
||||
const r = await api("GET", "/performance/api/marketplaces/" + probe.dataset.code + "/reconcile?date=" + encodeURIComponent(day) +
|
||||
"&to=" + encodeURIComponent(to));
|
||||
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; return; }
|
||||
const summary = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">조회</th>' +
|
||||
'<th class="perf-th-label">주소</th><th class="perf-th-label">결과</th><th>건수</th></tr></thead><tbody>' +
|
||||
r.probes.map(function (p) {
|
||||
return '<tr><td class="perf-td-label">' + esc(p.label) + '</td><td class="perf-muted">' + esc(p.path) + "</td><td>" +
|
||||
(p.ok ? '<span class="perf-pill is-ok">동작</span>' : '<span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(p.error) + "</span>") +
|
||||
'</td><td class="perf-num">' + (p.ok ? fmt(p.count) : "") + "</td></tr>";
|
||||
}).join("") + "</tbody></table>";
|
||||
const details = r.probes.filter(function (p) { return p.ok && p.count; }).map(function (p) {
|
||||
return '<h4 class="perf-h" style="margin:14px 0 6px">' + esc(p.label) + " — " + fmt(p.count) + "줄</h4>" +
|
||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">항목</th><th>채워진 줄</th><th>숫자 합계</th>' +
|
||||
'<th class="perf-th-label">예시 값</th></tr></thead><tbody>' +
|
||||
p.fields.map(function (f) {
|
||||
return '<tr><td class="perf-td-label">' + esc(f.name) + '</td><td class="perf-num">' + fmt(f.filled) + '</td><td class="perf-num">' +
|
||||
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
|
||||
}).join("") + "</tbody></table>";
|
||||
}).join("");
|
||||
out.innerHTML = summary + (details || '<p class="perf-muted" style="margin-top:8px">그날 조회된 주문이 없습니다. 셀러오피스에서 매출이 있던 날로 다시 해 보세요.</p>');
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
} finally { probe.disabled = false; }
|
||||
});
|
||||
|
||||
// ── 과거 매출 가져오기(기간 지정 수집, 관리자) ──
|
||||
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 ? "<b>반영</b> " + esc(ok.join(", ")) : "",
|
||||
bad.length ? "<b>실패</b> " + esc(bad.join(", ")) : "",
|
||||
rest.length ? '<span class="perf-muted">건너뜀(미연동·미설정): ' + esc(rest.join(", ")) + "</span>" : "",
|
||||
].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 () {
|
||||
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);
|
||||
});
|
||||
})();
|
||||
@@ -32,6 +32,7 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
"dispatch",
|
||||
"project",
|
||||
"cafe24",
|
||||
"performance",
|
||||
"expense_approver",
|
||||
"vacation_approver",
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<link rel="stylesheet" href="/static/erp.css?v=20260615b" />
|
||||
<link rel="stylesheet" href="/static/erp-shell.css?v=20260615b" />
|
||||
<link rel="stylesheet" href="/static/erp-attach-viewer.css" />
|
||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260928a" />
|
||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260930a" />
|
||||
{% block head_extra %}{% endblock %}
|
||||
</head>
|
||||
<body class="erp-body erp-app-body">
|
||||
@@ -177,7 +177,7 @@
|
||||
|
||||
{# 공용 확인/경고 창. defer 를 쓰지 않는다 — 아래 {% block scripts %} 의
|
||||
인라인 스크립트가 곧바로 erpConfirm/erpAlert 을 쓸 수 있어야 한다. #}
|
||||
<script src="/static/erp-dialog.js?v=20260928a"></script>
|
||||
<script src="/static/erp-dialog.js?v=20260930a"></script>
|
||||
<script src="/static/erp-attach-viewer.js" defer></script>
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
|
||||
@@ -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. <https://developers.cafe24.com> 로그인 → 앱 생성
|
||||
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회)
|
||||
|
||||
@@ -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:<APP_PWD>@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 하지 않음.
|
||||
|
||||
---
|
||||
|
||||
## 백업 / 복구 (안전 절차)
|
||||
|
||||
### 백업
|
||||
|
||||
@@ -120,6 +120,10 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
|
||||
| `VACATION_DB_URL` | 휴가 관리 DB DSN (예: `postgresql://vacation_app:<pwd>@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:<pwd>@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) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
# 실적(쇼핑몰 통합 매출) 모듈
|
||||
|
||||
> `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`(연동 준비 중).
|
||||
|
||||
**연동 현황**: 카페24 = **구현됨**, 나머지 9개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||
**연동 단계에서 공식 API 문서로 확정**한다.
|
||||
|
||||
### 카페24 (`adapters/cafe24.py`, 구현됨)
|
||||
|
||||
`auth_type="shared"` — 기존 `app/integrations/cafe24` OAuth 토큰(cafe24_db)과 클라이언트(재시도·429·토큰 자동 갱신)를
|
||||
재사용한다. 토큰에 `mall.read_order` 가 있어야 한다(`DEFAULT_SCOPES` 포함, 권한 추가 후 카페24 상품관리 → 시스템에서 재연결).
|
||||
|
||||
**카페24 관리자 "일별 매출내역"과 같은 기준**으로 센다(처음의 품목 결제금액 방식은 배송비가 빠지고 환불 날짜 기준이 달라
|
||||
화면과 맞지 않아 교체).
|
||||
|
||||
| 사건 | 조회 | 금액·날짜 |
|
||||
|---|---|---|
|
||||
| SALE(결제합계) | `GET /admin/orders` `date_type=pay_date`, `embed=items`, `paid=T` | +(실결제금액 + 적립금 + 예치금 + 네이버포인트), `initial_order_amount` + 주문 `naver_point`(결제 당시 금액 — 환불을 따로 빼므로 취소 후 금액 X), 결제일. 주문 1건 = 사건 1건(`{order_id}-PAY`) |
|
||||
| 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 실데이터를 지우고
|
||||
새로 넣는다(한 트랜잭션, 테스트 데이터 제외). 규칙이 바뀌어도 예전 행이 남지 않는다 → 규칙을 고친 뒤에는 같은 기간을
|
||||
[과거 매출 가져오기]로 다시 받으면 된다.
|
||||
- **주의 — `market_id` 는 외부 마켓만이 아니라 자체몰 주문 채널·간편결제도 담는다**(실데이터 확인 2026-09-30:
|
||||
`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 일별 매출내역과 같다**
|
||||
(9/28 대조로 자체몰+마켓 합계가 모든 줄에서 일치 확인). 환불은 원 주문을 100건씩 조회해 같은 열로. 네이버페이는 자체몰.
|
||||
- 카페24 가 만든 사건 ID 는 모두 `c24:` 접두어(`event_prefix`) — 다시 받을 때 카페24 열 + 다른 열의 `c24:` 행만 교체해
|
||||
그 쇼핑몰의 **직접 연동분은 건드리지 않는다**. 어떤 쇼핑몰을 직접 API 로 연동하면 같은 주문을 두 번 받지 않도록 그 마켓을
|
||||
`MARKET_MAP` 에서 빼야 한다. 설정 화면 API 설정 칸의 "카페24 경유" 표시 = 카페24 수집 때 함께 반영되는 쇼핑몰.
|
||||
- 실제 market_id 값은 "카페24 매출 대조"의 마켓별 표(market_id / 주문경로 / 반영 열)로 확인하고, "(연결표 없음)"으로 나오는
|
||||
마켓이 우리 쇼핑몰이면 `MARKET_MAP` 에 추가한다.
|
||||
- 60일 단위 분할(한 호출 3개월 미만), orders limit 1000 / refunds limit 500 페이지. 개인정보는 저장하지 않는다.
|
||||
- **카페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 값도 틀림 → 규칙 차이(결제/환불) → 날짜 클릭으로 그날 대조.
|
||||
날짜를 눌러 연 대조 표에는 붙여넣은 카페24 열(주문수·품목수·상품구매금액·배송비·할인·쿠폰·실결제·적립금·예치금·결제·환불·순매출)과
|
||||
열별 차이가 같이 나온다.
|
||||
- **결제합계 = 실결제금액 + 적립금 + 예치금 + 네이버포인트**(initial_order_amount 의 payment_amount·points_spent_amount·
|
||||
credits_spent_amount + 주문의 naver_point). "상품구매금액 + 배송비 − 할인 − 쿠폰"은 할인 필드에 안 잡히는 차이가 있어 쓰지 않음
|
||||
(2026-09-23: 카페24 1,874,738 = 1,713,128 + 10,110 + 151,500, 상품식 1,874,800). 네 값이 모두 0인 주문도 0원
|
||||
(9/25 가상계좌·휴대폰 9,900 — 카페24도 0원).
|
||||
- **환불 목록 없는 취소는 네이버페이(NCHECKOUT)만** 환불합계에 넣는다. 주문 전체가 취소·반품되면 배송비(− 배송비 할인·쿠폰)도
|
||||
그 주문의 마지막 클레임 품목에 한 번 더한다. 톡체크아웃·자체몰의 환불 기록 없는 취소는 카페24 환불합계에 없음
|
||||
(9/4: 98,700 + 네이버페이 19,900 + 배송비 3,500 = 122,100 / 9/16: 톡체크아웃 취소 9,900 제외 → 201,100).
|
||||
|
||||
### 11번가 (`adapters/elevenst.py`, 구현됨)
|
||||
|
||||
- 인증: 셀러오피스 Open API Key → 헤더 `openapikey`. **셀러 API 는 등록 IP 에서만** 호출된다(Seller API 정보 수정 →
|
||||
IP 직접 입력에 운영 서버 외부 IP, 셀링툴 사방넷과 함께 사용 가능). 응답은 XML(euc-kr 선언 → 직접 디코딩).
|
||||
- 없는 주소 = 500 + `-997 등록된 API 정보가 존재하지 않습니다`, 건 없음 = `-1 해당 건이 없습니다`(0건으로 처리).
|
||||
- 상세 문서가 로그인 뒤에만 있어 설정 화면 **"11번가 원본 데이터 확인"**(`reconcile(day, to)`, 후보 주소별 동작·항목 합계,
|
||||
개인정보 값 숨김)으로 실데이터를 보고 확정했다(2026-09-30).
|
||||
- 주문 상태 목록 4개(`/rest/ordservices/complete|packaging|shipping|completed/{yyyyMMddHHmm}/{…}`)는 **지금 그 상태인 주문만**
|
||||
준다. 배송완료 목록에 구매확정 주문도 남는다. 취소·반품된 주문은 목록에서 빠지고 `/rest/claimservice/canceledorders|…` 에 있다.
|
||||
- SALE = **주문 하나**(`11st:{ordNo}`), 날짜 = 결제일.
|
||||
- **정산된 주문**: 정산 내역(`/rest/settlement/settlementList/{yyyyMMdd}/{yyyyMMdd}`, 정산확정일 `stlDy` 기준 → 기간 뒤 45일
|
||||
(오늘까지)을 더 불러 결제일 `ordStlEndDt` 로 거름)의 **판매금액합계 `selPrcAmt` 합**. 셀러오피스 "판매 상세내역"과 같고
|
||||
배송비(도서산간 등)가 별도 줄로 들어 있다 — 9/10 주문 83,800 + 배송비 줄 3,000 = 86,800(주문 목록 `dlvCst` 는 0).
|
||||
- **정산 전 주문**: 주문 상태 목록의 `ordAmt`(판매금액, 11번가 부담 쿠폰 전) + 배송비(`dlvCst` 최댓값 한 번). 기간 뒤 30일을 더
|
||||
불러 주문일로 거른다. 정산되면 다음 업데이트 때 정산 값으로 바뀐다.
|
||||
- `ordAmt − ordPayAmt` = 정산 `cupnAmt` = 11번가 부담 할인(`discount_amount`). 수수료는 판매금액 기준(34,900 × 13% = 4,537).
|
||||
- `replace_range` — 기간을 통째로 다시 받아 취소·반품된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 → 지난 날짜
|
||||
금액이 나중에 줄 수 있음). 구매자 이름·아이디·연락처는 저장하지 않는다.
|
||||
|
||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||
|
||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 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)일.
|
||||
- **대시보드 [매출 업데이트]** = 지금 보고 있는 기간(오늘까지)을 `POST /api/sync {from, to}` 로 다시 가져온다
|
||||
("이번달"이면 1일~오늘). 모듈 권한자는 92일까지, 더 긴 기간(올해 등, 최대 366일)은 관리자만.
|
||||
- **과거 매출 가져오기**(설정 화면, 관리자): 같은 API 로 임의 기간(최대 366일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
|
||||
- 카페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`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고
|
||||
상단에 오류 쇼핑몰만 표시.
|
||||
- 중복 방지: `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/네트워크 없이 검증한다.
|
||||
@@ -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/<name>/
|
||||
| `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`.
|
||||
|
||||
|
||||
@@ -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:<APP_PWD>@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;
|
||||
Reference in New Issue
Block a user