Compare commits
54 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 91bdc12e78 | |||
| 81b1204693 | |||
| ae2e3eb943 | |||
| da63b93302 | |||
| a2d2382d71 | |||
| 8b3e6dffc5 | |||
| 898dc1153c | |||
| b765fb8fb8 | |||
| 7c283312b4 | |||
| f4fadec0a4 | |||
| 74f59c0a94 | |||
| e56c5685ca | |||
| 67cd73b963 | |||
| 3203ff87a4 | |||
| e398e9d906 | |||
| 077c92fa32 | |||
| e845f47043 | |||
| a5f90a0343 | |||
| 21019ac5f1 | |||
| 7a9f55c804 | |||
| ac2615805b | |||
| 220fb6e7d1 | |||
| 7de93e78d7 | |||
| 86ee50b2e6 | |||
| f037ea7de0 | |||
| 40d94e2892 | |||
| 7d96f2e738 | |||
| 1952e4f0b1 | |||
| 6376092bb7 | |||
| c93ab2fbd8 | |||
| dd6a849fbd | |||
| b52b182d47 | |||
| 1129db9e21 | |||
| bfa55bf367 | |||
| 643ff25f27 | |||
| 2f86445077 | |||
| 398e5181fd | |||
| 20d19792dd | |||
| 6f43f8066a | |||
| 614332a1e6 | |||
| 1d12ac878b | |||
| b3ee219858 | |||
| 1eca66838b | |||
| 370834b58b | |||
| a19c1f4cab | |||
| fb7c29833e | |||
| ef12a34600 | |||
| f63f82d642 | |||
| 19396f1745 | |||
| 4cb37688ed | |||
| 27ee92c0a6 | |||
| 04a1fddd95 | |||
| 6e175d0bac | |||
| aa669553db |
@@ -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
|
||||
|
||||
@@ -36,7 +36,9 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
|
||||
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
|
||||
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1상자=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1상자 묶음 기준 Package ID > Tracking ID > Order ID, 같은 상자 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
|
||||
- 카페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/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`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 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`.
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ from .errors import (
|
||||
Cafe24AuthError,
|
||||
Cafe24ConfigError,
|
||||
Cafe24Error,
|
||||
Cafe24FtpConflict,
|
||||
Cafe24FtpError,
|
||||
Cafe24RateLimitError,
|
||||
)
|
||||
@@ -80,6 +81,7 @@ __all__ = [
|
||||
"Cafe24RateLimitError",
|
||||
"Cafe24ApiError",
|
||||
"Cafe24FtpError",
|
||||
"Cafe24FtpConflict",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -164,6 +164,10 @@ class Cafe24Client:
|
||||
method = method.upper()
|
||||
forced_refresh = False
|
||||
last_error: Exception | None = None
|
||||
# 쓰기 요청이 카페24에 도달했을 수도 있는 시도가 있었나(5xx 응답·응답 전 끊김).
|
||||
# 최종 오류에 실어 호출부가 "반영 여부 모름"을 구분하게 한다(errors.Cafe24ApiError).
|
||||
writes = method in ("PUT", "POST", "DELETE", "PATCH")
|
||||
maybe_applied = False
|
||||
|
||||
for attempt in range(self._max_retries + 1):
|
||||
self._pace()
|
||||
@@ -224,7 +228,9 @@ class Cafe24Client:
|
||||
time.sleep(wait)
|
||||
continue
|
||||
|
||||
error = Cafe24ApiError(message, status=status, endpoint=endpoint)
|
||||
if writes and status >= 500:
|
||||
maybe_applied = True
|
||||
error = Cafe24ApiError(message, status=status, endpoint=endpoint, maybe_applied=maybe_applied)
|
||||
if error.retryable and attempt < self._max_retries:
|
||||
last_error = error
|
||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||
@@ -241,7 +247,11 @@ class Cafe24Client:
|
||||
http_status=status, result="ERROR", error_message=message,
|
||||
duration_ms=elapsed,
|
||||
)
|
||||
last_error = Cafe24ApiError(message, status=0, endpoint=endpoint)
|
||||
# 연결조차 안 된 경우만 "도달하지 않음"이 확실하다. 그 밖(읽기 타임아웃,
|
||||
# 응답 도중 끊김)은 카페24가 요청을 처리했을 수 있다.
|
||||
if writes and not isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
|
||||
maybe_applied = True
|
||||
last_error = Cafe24ApiError(message, status=0, endpoint=endpoint, maybe_applied=maybe_applied)
|
||||
if attempt < self._max_retries:
|
||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||
continue
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -7,15 +7,28 @@ Admin API(OAuth)로는 스킨 파일을 다루지 못한다(`config.py` 상단
|
||||
|
||||
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
||||
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
||||
|
||||
쓰기는 원본에 직접 STOR 하지 않는다 (write_text_file)
|
||||
직접 STOR 는 전송 도중 끊기면 원본이 **앞부분만 남은 채** 잘린다(스킨 템플릿이면
|
||||
모든 상품 페이지가 깨진다). 그래서
|
||||
1) 같은 폴더의 임시 파일에 올리고 (원본은 아직 그대로)
|
||||
2) 다시 받아 바이트 단위로 검증하고
|
||||
3) 교체 직전 원본을 다시 읽어 편집 시작 값과 같은지 확인하고(충돌 방지)
|
||||
4) RNFR/RNTO 로 이름을 바꿔 교체한다
|
||||
서버가 "이미 있는 이름으로 바꾸기"를 거부하면 원본을 옆 이름으로 비킨 뒤 교체하고,
|
||||
실패하면 원본을 제자리로 되돌린다. 이름 바꾸기 자체를 지원하지 않으면 **중단**한다
|
||||
(직접 STOR 로 물러서지 않는다).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ftplib
|
||||
import io
|
||||
import posixpath
|
||||
import uuid
|
||||
|
||||
from .config import Cafe24FtpConfig
|
||||
from .errors import Cafe24FtpError
|
||||
from .errors import Cafe24FtpConflict, Cafe24FtpError
|
||||
|
||||
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
||||
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
||||
@@ -35,37 +48,135 @@ def _connect(config: Cafe24FtpConfig) -> ftplib.FTP:
|
||||
raise Cafe24FtpError(f"FTP 연결/로그인에 실패했습니다: {exc}") from exc
|
||||
|
||||
|
||||
def _close(ftp: ftplib.FTP) -> None:
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
||||
ftp.close()
|
||||
|
||||
|
||||
def _retr(ftp: ftplib.FTP, path: str) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
ftp.retrbinary(f"RETR {path}", buf.write)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _delete_quiet(ftp: ftplib.FTP, path: str) -> None:
|
||||
try:
|
||||
ftp.delete(path)
|
||||
except ftplib.all_errors:
|
||||
pass # 임시 파일 정리 실패는 무시(이름에 cf24tmp 가 붙어 있어 구분된다)
|
||||
|
||||
|
||||
def read_text_file(config: Cafe24FtpConfig, path: str) -> str:
|
||||
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
||||
ftp = _connect(config)
|
||||
try:
|
||||
buf = io.BytesIO()
|
||||
try:
|
||||
ftp.retrbinary(f"RETR {path}", buf.write)
|
||||
raw = _retr(ftp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
||||
try:
|
||||
return buf.getvalue().decode("utf-8")
|
||||
return raw.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
||||
finally:
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
||||
ftp.close()
|
||||
_close(ftp)
|
||||
|
||||
|
||||
def write_text_file(config: Cafe24FtpConfig, path: str, content: str) -> None:
|
||||
"""디자인 보관함의 파일 1개를 통째로 덮어쓴다."""
|
||||
def temp_names(path: str, tag: str) -> tuple[str, str]:
|
||||
"""(임시 업로드 이름, 원본을 잠시 비킬 이름) — 같은 폴더, 원본 이름 + 표식."""
|
||||
folder, name = posixpath.split(path)
|
||||
return (posixpath.join(folder, f"{name}.cf24tmp-{tag}"),
|
||||
posixpath.join(folder, f"{name}.cf24old-{tag}"))
|
||||
|
||||
|
||||
def write_text_file(
|
||||
config: Cafe24FtpConfig, path: str, content: str, *, expected_current: str | None = None
|
||||
) -> None:
|
||||
"""디자인 보관함의 파일 1개를 안전하게 교체한다(모듈 설명 참고).
|
||||
|
||||
expected_current: 편집 시작(또는 백업) 때 읽은 원본. 주면 교체 직전 원본을 다시
|
||||
읽어 다르면 Cafe24FtpConflict 로 멈춘다(원본 그대로).
|
||||
실패 시 Cafe24FtpError — maybe_applied=True 면 원본이 이미 바뀌었을 수 있다.
|
||||
"""
|
||||
data = content.encode("utf-8")
|
||||
tmp, aside = temp_names(path, uuid.uuid4().hex[:10])
|
||||
ftp = _connect(config)
|
||||
try:
|
||||
buf = io.BytesIO(content.encode("utf-8"))
|
||||
# 1) 임시 파일에 올린다 — 원본은 아직 그대로다.
|
||||
try:
|
||||
ftp.storbinary(f"STOR {path}", buf)
|
||||
ftp.storbinary(f"STOR {tmp}", io.BytesIO(data))
|
||||
except ftplib.all_errors as exc:
|
||||
raise Cafe24FtpError(f"파일을 쓰지 못했습니다({path}): {exc}") from exc
|
||||
finally:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"임시 파일을 올리지 못했습니다 — 원본은 그대로입니다({path}): {exc}") from exc
|
||||
|
||||
# 2) 검증 — 다시 받아 바이트 단위로 비교한다(전송이 잘렸으면 여기서 잡힌다).
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
||||
ftp.close()
|
||||
uploaded = _retr(ftp, tmp)
|
||||
except ftplib.all_errors as exc:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"올린 임시 파일을 확인하지 못했습니다 — 원본은 그대로입니다: {exc}") from exc
|
||||
if uploaded != data:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(
|
||||
f"올린 임시 파일이 보낸 내용과 다릅니다({len(uploaded)}/{len(data)}바이트) — 원본은 그대로입니다."
|
||||
)
|
||||
|
||||
# 3) 충돌 확인 — 교체 직전의 원본이 편집 시작 값 그대로인가.
|
||||
if expected_current is not None:
|
||||
try:
|
||||
now = _retr(ftp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"교체 직전 원본을 다시 읽지 못했습니다 — 원본은 그대로입니다: {exc}") from exc
|
||||
if now != expected_current.encode("utf-8"):
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpConflict(
|
||||
"적용하는 사이 FTP 파일이 바뀌었습니다 — 원본은 그대로입니다. 새로고침해 확인한 뒤 다시 적용하세요."
|
||||
)
|
||||
|
||||
# 4) 교체 — 이름 바꾸기. 덮어쓰기를 거부하는 서버면 원본을 비킨 뒤 교체한다.
|
||||
moved_aside = False
|
||||
try:
|
||||
ftp.rename(tmp, path)
|
||||
except ftplib.all_errors as first:
|
||||
try:
|
||||
ftp.rename(path, aside)
|
||||
except ftplib.all_errors as exc:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(
|
||||
"이 FTP 서버가 파일 이름 바꾸기(rename)를 지원하지 않아 중단했습니다 — 원본은 그대로입니다. "
|
||||
f"({first} / {exc})"
|
||||
) from exc
|
||||
try:
|
||||
ftp.rename(tmp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
try:
|
||||
ftp.rename(aside, path)
|
||||
except ftplib.all_errors as exc2:
|
||||
raise Cafe24FtpError(
|
||||
f"교체에 실패했고 원본 되돌리기도 실패했습니다. FTP 에서 {aside} 를 {path} 로 "
|
||||
f"직접 되돌리세요: {exc} / {exc2}",
|
||||
maybe_applied=True,
|
||||
) from exc2
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"교체에 실패해 원본을 되돌렸습니다: {exc}") from exc
|
||||
moved_aside = True
|
||||
|
||||
# 5) 확인 — 교체 뒤 원본 경로가 새 내용인가.
|
||||
try:
|
||||
final = _retr(ftp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
raise Cafe24FtpError(
|
||||
f"교체 뒤 확인 조회에 실패했습니다 — 적용됐을 수 있으니 파일을 다시 열어 확인하세요: {exc}",
|
||||
maybe_applied=True,
|
||||
) from exc
|
||||
if final != data:
|
||||
raise Cafe24FtpError(
|
||||
"교체 뒤 파일 내용이 보낸 것과 다릅니다 — 파일을 다시 열어 확인하세요.", maybe_applied=True
|
||||
)
|
||||
if moved_aside:
|
||||
_delete_quiet(ftp, aside)
|
||||
finally:
|
||||
_close(ftp)
|
||||
|
||||
@@ -32,16 +32,35 @@ class Cafe24RateLimitError(Cafe24Error):
|
||||
|
||||
|
||||
class Cafe24FtpError(Cafe24Error):
|
||||
"""디자인 보관함 FTP 연결/전송 실패 (product-swiper.js 편집 등)."""
|
||||
"""디자인 보관함 FTP 연결/전송 실패 (product-swiper.js 편집 등).
|
||||
|
||||
maybe_applied: 원본 경로가 이미 새 내용으로 바뀌었을 수 있다(교체 뒤 확인 단계 실패).
|
||||
False 면 원본은 그대로다(임시 파일 단계에서 멈춤).
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, maybe_applied: bool = False):
|
||||
super().__init__(message)
|
||||
self.maybe_applied = maybe_applied
|
||||
|
||||
|
||||
class Cafe24FtpConflict(Cafe24FtpError):
|
||||
"""교체 직전 다시 읽은 원본이 편집 시작 때와 다르다 — 남의 수정을 덮지 않고 멈춘다."""
|
||||
|
||||
|
||||
class Cafe24ApiError(Cafe24Error):
|
||||
"""그 외 API 오류(4xx/5xx). status 로 재시도 가능 여부를 판단한다."""
|
||||
"""그 외 API 오류(4xx/5xx). status 로 재시도 가능 여부를 판단한다.
|
||||
|
||||
def __init__(self, message: str, *, status: int = 0, endpoint: str = ""):
|
||||
maybe_applied: 쓰기 요청(PUT/POST/DELETE)이 카페24에 **도달했을 수도** 있는가.
|
||||
응답을 받기 전에 끊겼거나(읽기 타임아웃 등) 5xx 를 받은 시도가 한 번이라도
|
||||
있으면 True — 반영됐는지 모르므로 호출부는 재적용하지 말고 "확인 필요"로 둔다.
|
||||
연결 자체가 안 된 경우(ConnectError)와 4xx 는 반영되지 않은 것이 확실하다.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, status: int = 0, endpoint: str = "", maybe_applied: bool = False):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.endpoint = endpoint
|
||||
self.maybe_applied = maybe_applied
|
||||
|
||||
@property
|
||||
def retryable(self) -> bool:
|
||||
|
||||
@@ -22,6 +22,7 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from .client import Cafe24Client
|
||||
from .errors import Cafe24Error
|
||||
|
||||
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
||||
PAGE_LIMIT = 100
|
||||
@@ -476,26 +477,55 @@ def wait_for_variants(
|
||||
return latest
|
||||
|
||||
|
||||
VARIANT_CHUNK = 100 # 카페24 문서상 PUT variants 1회 최대 건수
|
||||
|
||||
# update_variants 행별 결과 상태
|
||||
VARIANT_OK = "ok" # 카페24가 받아들임
|
||||
VARIANT_FAILED = "failed" # 거절 — 반영되지 않음이 확실
|
||||
VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을 못 받음 — 반영 여부 모름
|
||||
|
||||
|
||||
def update_variants(
|
||||
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
|
||||
) -> list[dict[str, Any]]:
|
||||
"""여러 품목 부분 수정. 100건씩 나눠 보낸다(문서상 1회 100건 제한)."""
|
||||
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
|
||||
|
||||
[{"variant_code": "...", "status": "ok"|"failed"|"unknown",
|
||||
"error": "", "variant": {카페24 응답의 그 품목 — 없으면 {}}}]
|
||||
|
||||
100건씩 나눠 보낸다(문서상 1회 100건 제한). 한 묶음이 실패해도 멈추지 않고 다음
|
||||
묶음을 보낸다 — 앞 묶음이 이미 반영됐는데 전체를 실패로 알리면 화면과 카페24가
|
||||
어긋나고, 사용자가 반영된 행까지 다시 보내게 된다. 호출부는 ok 인 행만 반영됨으로
|
||||
기록한다.
|
||||
"""
|
||||
no = int(product_no)
|
||||
out: list[dict[str, Any]] = []
|
||||
for start in range(0, len(requests), 100):
|
||||
chunk = requests[start : start + 100]
|
||||
for start in range(0, len(requests), VARIANT_CHUNK):
|
||||
chunk = requests[start : start + VARIANT_CHUNK]
|
||||
if not chunk:
|
||||
continue
|
||||
payload = client.put(
|
||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
||||
)
|
||||
try:
|
||||
payload = client.put(
|
||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
||||
)
|
||||
except Cafe24Error as exc:
|
||||
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
|
||||
for row in chunk:
|
||||
out.append({"variant_code": str(row.get("variant_code") or ""), "status": status,
|
||||
"error": str(exc), "variant": {}})
|
||||
continue
|
||||
result = payload.get("variants") if isinstance(payload, dict) else None
|
||||
returned: list[dict[str, Any]] = []
|
||||
if isinstance(result, list):
|
||||
out.extend(result)
|
||||
returned = [r for r in result if isinstance(r, dict)]
|
||||
elif isinstance(result, dict):
|
||||
out.append(result)
|
||||
elif isinstance(payload.get("variant"), dict):
|
||||
out.append(payload["variant"])
|
||||
returned = [result]
|
||||
elif isinstance(payload, dict) and isinstance(payload.get("variant"), dict):
|
||||
returned = [payload["variant"]]
|
||||
by_code = {str(r.get("variant_code") or ""): r for r in returned}
|
||||
for row in chunk:
|
||||
code = str(row.get("variant_code") or "")
|
||||
out.append({"variant_code": code, "status": VARIANT_OK, "error": "", "variant": by_code.get(code, {})})
|
||||
return out
|
||||
|
||||
|
||||
|
||||
+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"])
|
||||
|
||||
+503
-96
@@ -14,10 +14,12 @@ API 로그에는 토큰/시크릿을 넣지 않는다.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterator
|
||||
|
||||
from psycopg import errors as pg_errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
@@ -97,6 +99,315 @@ class Cafe24Store:
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 마이그레이션 005(쓰기 안전장치) 적용 여부
|
||||
# 쓰기 경로는 잠금·시도 기록 없이 카페24에 쓰지 않는다 — 적용 전이면 거부한다.
|
||||
# 읽기 경로는 005 가 없어도 동작하게 둔다(배포 순서가 어긋나도 화면은 열린다).
|
||||
# ════════════════════════════════════════════════════════════
|
||||
_schema_ok = False
|
||||
|
||||
def write_schema_ready(self) -> bool:
|
||||
if self._schema_ok:
|
||||
return True
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT to_regclass('public.cafe24_write_locks') IS NOT NULL
|
||||
AND to_regclass('public.cafe24_write_attempts') IS NOT NULL
|
||||
AND EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'cafe24_product_schedules'
|
||||
AND column_name = 'lease_token')
|
||||
AND EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'cafe24_product_revisions'
|
||||
AND column_name = 'source') AS ok
|
||||
"""
|
||||
).fetchone()
|
||||
self._schema_ok = bool(row and row.get("ok"))
|
||||
return self._schema_ok
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 쓰기 잠금 (lease) — 웹 여러 프로세스 + 예약 worker 가 공유한다.
|
||||
# 같은 lock_key 는 한 번에 하나만 잡는다. 만료(expires_at)가 지나면 다른 쪽이
|
||||
# 가져갈 수 있다(잡은 프로세스가 죽어도 영구히 막히지 않는다). 원격 쓰기 직전
|
||||
# renew_lock 으로 "아직 내 잠금인가"를 확인한다(펜싱) — 아니면 쓰지 않는다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def acquire_lock(self, key: str, *, owner: str, purpose: str, ttl_seconds: int) -> str | None:
|
||||
"""잠금을 잡으면 token, 남이 잡고 있으면 None."""
|
||||
token = uuid.uuid4().hex
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cafe24_write_locks (lock_key, owner, token, purpose, acquired_at, expires_at)
|
||||
VALUES (%s, %s, %s, %s, now(), now() + %s * interval '1 second')
|
||||
ON CONFLICT (lock_key) DO UPDATE SET
|
||||
owner = EXCLUDED.owner, token = EXCLUDED.token, purpose = EXCLUDED.purpose,
|
||||
acquired_at = now(), expires_at = EXCLUDED.expires_at
|
||||
WHERE cafe24_write_locks.expires_at < now()
|
||||
RETURNING token
|
||||
""",
|
||||
(key, (owner or "")[:200], token, (purpose or "")[:200], max(1, int(ttl_seconds))),
|
||||
).fetchone()
|
||||
return str(row["token"]) if row else None
|
||||
|
||||
def renew_lock(self, key: str, token: str, *, ttl_seconds: int) -> bool:
|
||||
"""아직 내 잠금이고 만료 전이면 연장하고 True. 이미 넘어갔으면 False."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_write_locks
|
||||
SET expires_at = now() + %s * interval '1 second'
|
||||
WHERE lock_key = %s AND token = %s AND expires_at > now()
|
||||
RETURNING lock_key
|
||||
""",
|
||||
(max(1, int(ttl_seconds)), key, token),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def release_lock(self, key: str, token: str) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"DELETE FROM cafe24_write_locks WHERE lock_key = %s AND token = %s",
|
||||
(key, token),
|
||||
)
|
||||
|
||||
def lock_holder(self, key: str) -> dict[str, Any]:
|
||||
"""지금 잠금을 잡고 있는 쪽(안내 문구용). 없거나 만료됐으면 {}."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT owner, purpose, acquired_at, expires_at FROM cafe24_write_locks
|
||||
WHERE lock_key = %s AND expires_at > now()
|
||||
""",
|
||||
(key,),
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 쓰기 시도 기록 (cafe24_write_attempts) — 운영용 가변 표.
|
||||
# 원격 PUT 직전에 STARTED 로 남기고, 결과에 따라 상태를 바꾼다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
_ATTEMPT_FIELDS: tuple[str, ...] = (
|
||||
"product_no", "mall_id", "shop_no", "origin", "schedule_id", "actor",
|
||||
"backup_revision_id", "observed_digest", "base_digest", "target_digest",
|
||||
"target_html", "target_revision_id", "set_display", "set_selling", "memo",
|
||||
)
|
||||
|
||||
def start_attempt(self, **fields: Any) -> int:
|
||||
cols = [k for k in self._ATTEMPT_FIELDS if k in fields]
|
||||
values = [fields[k] for k in cols]
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"""
|
||||
INSERT INTO cafe24_write_attempts ({", ".join(cols)}, status)
|
||||
VALUES ({", ".join(["%s"] * len(cols))}, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(*values, store.ATTEMPT_STARTED),
|
||||
).fetchone()
|
||||
return int(row["id"]) if row else 0
|
||||
|
||||
def update_attempt(
|
||||
self,
|
||||
attempt_id: int,
|
||||
*,
|
||||
status: str | None = None,
|
||||
error: str | None = None,
|
||||
remote_updated_at: str | None = None,
|
||||
remote_ok: bool = False,
|
||||
resolved_by: str | None = None,
|
||||
only_from: tuple[str, ...] | None = None,
|
||||
) -> bool:
|
||||
"""상태 전이. only_from 을 주면 그 상태에서만 바꾼다(늦게 도착한 갱신 무시)."""
|
||||
sets: list[str] = []
|
||||
args: list[Any] = []
|
||||
if status is not None:
|
||||
sets.append("status = %s")
|
||||
args.append(status)
|
||||
if error is not None:
|
||||
sets.append("error = %s")
|
||||
args.append((error or "")[:1000])
|
||||
if remote_updated_at is not None:
|
||||
sets.append("remote_updated_at = %s")
|
||||
args.append(str(remote_updated_at or ""))
|
||||
if remote_ok:
|
||||
sets.append("remote_at = COALESCE(remote_at, now())")
|
||||
if resolved_by is not None:
|
||||
sets.append("resolved_by = %s")
|
||||
args.append(resolved_by[:200])
|
||||
if not sets:
|
||||
return False
|
||||
where = "id = %s"
|
||||
args.append(int(attempt_id))
|
||||
if only_from:
|
||||
where += " AND status = ANY(%s)"
|
||||
args.append(list(only_from))
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"UPDATE cafe24_write_attempts SET {', '.join(sets)} WHERE {where} RETURNING id",
|
||||
args,
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def record_attempt_revision(
|
||||
self,
|
||||
attempt_id: int,
|
||||
*,
|
||||
revision_type: str,
|
||||
memo: str,
|
||||
created_by: str,
|
||||
source: str = "",
|
||||
source_revision_id: int | None = None,
|
||||
) -> int:
|
||||
"""원격 반영된 시도의 버전(MANUAL/SCHEDULED/ROLLBACK)을 남기고 RECORDED 로 바꾼다.
|
||||
|
||||
한 트랜잭션에서 한다 — 시도 행을 잠그고, 이미 기록돼 있으면 그 버전 id 를 돌려준다
|
||||
(기록 복구가 두 번 돌아도 버전이 둘 생기지 않는다). 내용은 시도에 보관한
|
||||
target_html(없으면 target_revision_id 의 내용)이다. 기록 뒤 target_html 은 비운다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
att = conn.execute(
|
||||
"""
|
||||
SELECT a.*, COALESCE(NULLIF(a.target_html, ''), t.html_content, '') AS body
|
||||
FROM cafe24_write_attempts a
|
||||
LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id
|
||||
WHERE a.id = %s
|
||||
FOR UPDATE OF a
|
||||
""",
|
||||
(int(attempt_id),),
|
||||
).fetchone()
|
||||
if att is None:
|
||||
return 0
|
||||
if att.get("applied_revision_id"):
|
||||
return int(att["applied_revision_id"])
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cafe24_product_revisions
|
||||
(product_no, html_content, revision_type, memo, created_by,
|
||||
mall_id, shop_no, source, source_revision_id)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
int(att["product_no"]), att["body"] or "",
|
||||
store.normalize_revision_type(revision_type), (memo or "")[:500],
|
||||
created_by or "", att.get("mall_id") or "", int(att.get("shop_no") or 1),
|
||||
source or "", source_revision_id,
|
||||
),
|
||||
).fetchone()
|
||||
revision_id = int(row["id"])
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_write_attempts
|
||||
SET status = %s, applied_revision_id = %s, target_html = '',
|
||||
remote_at = COALESCE(remote_at, now())
|
||||
WHERE id = %s
|
||||
""",
|
||||
(store.ATTEMPT_RECORDED, revision_id, int(attempt_id)),
|
||||
)
|
||||
return revision_id
|
||||
|
||||
def get_attempt(self, attempt_id: int) -> dict[str, Any]:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM cafe24_write_attempts WHERE id = %s", (int(attempt_id),)
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
def latest_attempt_for_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT * FROM cafe24_write_attempts WHERE schedule_id = %s
|
||||
ORDER BY created_at DESC, id DESC LIMIT 1
|
||||
""",
|
||||
(int(schedule_id),),
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
def open_attempts(self, product_no: int, *, since: datetime) -> list[dict[str, Any]]:
|
||||
"""결과 확정이 필요한 시도(STARTED/REMOTE_OK/UNKNOWN), 유예시간 안, 오래된 순.
|
||||
|
||||
005 적용 전이면 빈 목록(읽기 경로는 막지 않는다)."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, origin, schedule_id, actor, status, target_digest,
|
||||
target_revision_id, backup_revision_id, set_display, set_selling,
|
||||
error, created_at, remote_at, memo
|
||||
FROM cafe24_write_attempts
|
||||
WHERE product_no = %s AND status = ANY(%s) AND created_at >= %s
|
||||
ORDER BY created_at ASC, id ASC
|
||||
""",
|
||||
(int(product_no), list(store.ATTEMPT_OPEN), since),
|
||||
).fetchall()
|
||||
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||
return []
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def attempts_needing_record(self, *, since: datetime, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""원격 반영됐는데 버전 기록이 안 된 시도(REMOTE_OK) — worker 가 기록을 채운다."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, origin, schedule_id, actor, memo, target_revision_id, target_digest
|
||||
FROM cafe24_write_attempts
|
||||
WHERE status = %s AND created_at >= %s
|
||||
ORDER BY created_at ASC, id ASC LIMIT %s
|
||||
""",
|
||||
(store.ATTEMPT_REMOTE_OK, since, max(1, int(limit))),
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def write_lineage(self, product_no: int, *, since: datetime, limit: int = 30) -> list[dict[str, Any]]:
|
||||
"""원격 반영이 **확인된** 상세설명 쓰기(REMOTE_OK/RECORDED), 최신 순.
|
||||
|
||||
읽기 지연 판정의 유일한 근거다. 충돌로 거절된 적용의 백업, 예약 초안, 실패·결과
|
||||
모름 시도는 들어오지 않는다. 첫 행에만 html_content(마지막으로 쓴 HTML)를 채운다.
|
||||
created_at 은 원격 반영 시각(remote_at)이다. 005 적용 전이면 빈 목록.
|
||||
"""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, origin, actor, status, schedule_id, observed_digest, base_digest,
|
||||
target_digest, remote_updated_at, remote_at, applied_revision_id,
|
||||
target_revision_id
|
||||
FROM cafe24_write_attempts
|
||||
WHERE product_no = %s AND status = ANY(%s) AND target_digest <> ''
|
||||
AND remote_at >= %s
|
||||
ORDER BY remote_at DESC, id DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(int(product_no), list(store.ATTEMPT_CONFIRMED), since, max(1, int(limit))),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return []
|
||||
top = conn.execute(
|
||||
"""
|
||||
SELECT COALESCE(NULLIF(a.target_html, ''), r.html_content, t.html_content, '') AS body
|
||||
FROM cafe24_write_attempts a
|
||||
LEFT JOIN cafe24_product_revisions r ON r.id = a.applied_revision_id
|
||||
LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(rows[0]["id"],),
|
||||
).fetchone()
|
||||
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||
return []
|
||||
out: list[dict[str, Any]] = []
|
||||
for index, row in enumerate(rows):
|
||||
item = dict(row)
|
||||
at = item.get("remote_at")
|
||||
if isinstance(at, datetime) and at.tzinfo is None:
|
||||
at = at.replace(tzinfo=KST)
|
||||
item["created_at"] = at
|
||||
item["created_by"] = item.get("actor") or ""
|
||||
item["html_content"] = (top or {}).get("body", "") if index == 0 else ""
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# OAuth 토큰 — app/integrations/cafe24/tokens.py 가 요구하는 3개 메서드
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -281,31 +592,38 @@ class Cafe24Store:
|
||||
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
||||
# 스냅샷 JSON 모양:
|
||||
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
||||
# "options": {"data": {...GET/PUT options 응답...}, "written_at": ISO},
|
||||
# "variants": {"data": {variant_code: {...}}, "written_at": ISO}}
|
||||
# "options": {"data": {...GET/PUT options 응답..., "_before_signature", "_recent_values"},
|
||||
# "written_at": ISO},
|
||||
# "variants": {"data": {variant_code: {필드..., "_at", "_deleted"?}}, "written_at": ISO}}
|
||||
# 섹션별로 따로 갱신한다(가격만 바꿨는데 옵션 스냅샷이 사라지면 안 된다).
|
||||
def save_write_snapshot(self, product_no: int, section: str, data: Any) -> None:
|
||||
# 품목은 코드별·필드별로 병합한다(store.merge_variant_snapshot). 품목 전체 초기화
|
||||
# (옵션 삭제·재생성)는 replace=True 로 명시한다 — {} 를 넘기는 것은 "변경 없음"이다.
|
||||
def save_write_snapshot(self, product_no: int, section: str, data: Any, *, replace: bool = False) -> None:
|
||||
from psycopg.types.json import Jsonb # noqa: WPS433
|
||||
|
||||
no = int(product_no)
|
||||
if no <= 0 or section not in ("product", "options", "variants"):
|
||||
return
|
||||
now_iso = datetime.now(KST).isoformat(timespec="seconds")
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
# 행이 없으면 먼저 만든다 — FOR UPDATE 가 잠글 행이 있어야 동시 저장이
|
||||
# 서로의 병합 결과를 덮지 않는다.
|
||||
conn.execute(
|
||||
"INSERT INTO cafe24_products (product_no) VALUES (%s) ON CONFLICT (product_no) DO NOTHING",
|
||||
(no,),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
||||
(no,),
|
||||
).fetchone()
|
||||
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
||||
if section == "variants" and isinstance(data, dict):
|
||||
# 품목은 코드별로 누적 병합 — 일부만 바꿔도 이전에 바꾼 것을 잃지 않게.
|
||||
merged = dict((current.get("variants") or {}).get("data") or {})
|
||||
merged.update(data)
|
||||
data = merged
|
||||
current[section] = {
|
||||
"data": data,
|
||||
"written_at": datetime.now(KST).isoformat(timespec="seconds"),
|
||||
}
|
||||
if section == "variants":
|
||||
previous = (current.get("variants") or {}).get("data") or {}
|
||||
data = store.merge_variant_snapshot(
|
||||
previous, data if isinstance(data, dict) else {}, at=now_iso, replace=replace
|
||||
)
|
||||
current[section] = {"data": data, "written_at": now_iso}
|
||||
product = data if section == "product" and isinstance(data, dict) else {}
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -345,51 +663,14 @@ class Cafe24Store:
|
||||
return {}
|
||||
return dict(row["last_write_snapshot"])
|
||||
|
||||
# ── 읽기 지연 판정용 revision 조회 ──
|
||||
def latest_write_revision(self, product_no: int, *, since: datetime) -> dict[str, Any] | None:
|
||||
"""유예시간 안의 가장 최근 '쓰기' revision(MANUAL/SCHEDULED/ROLLBACK) — HTML 포함."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, revision_type, html_content, memo, created_by, created_at
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s
|
||||
AND revision_type = ANY(%s)
|
||||
AND created_at >= %s
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(int(product_no), list(store.WRITE_REVISION_TYPES), since),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
out = dict(row)
|
||||
at = out.get("created_at")
|
||||
if isinstance(at, datetime) and at.tzinfo is None:
|
||||
out["created_at"] = at.replace(tzinfo=KST)
|
||||
return out
|
||||
|
||||
def revision_digests(self, product_no: int, *, since: datetime) -> set[str]:
|
||||
"""유예시간 안의 revision 들의 내용 해시(store.content_digest 와 같은 md5 hex).
|
||||
|
||||
내용을 통째로 옮기지 않고 DB 에서 해시만 계산한다(상세페이지는 수 MB 일 수 있다).
|
||||
md5 를 쓰는 이유: 모든 PostgreSQL 버전에 있고, 여기서는 충돌 저항이 아니라
|
||||
"같은 내용인가"만 필요하다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT md5(html_content) AS digest
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s AND created_at >= %s
|
||||
""",
|
||||
(int(product_no), since),
|
||||
).fetchall()
|
||||
return {str(r["digest"]) for r in rows if r.get("digest")}
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
||||
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
||||
# 읽기 지연 판정은 이 표가 아니라 cafe24_write_attempts(확인된 쓰기)를 본다 —
|
||||
# 여기에는 충돌로 거절된 적용의 백업·예약 초안처럼 카페24에 올라간 적 없는 값도
|
||||
# 들어 있기 때문이다(write_lineage 참고).
|
||||
# 메타데이터(마이그레이션 005): mall_id·shop_no(복원 시 일치 검사), source
|
||||
# (BACKUP 이 카페24 관측값인지, 지연 중이라 마지막 확인된 쓰기인지), source_revision_id.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def add_revision(
|
||||
self,
|
||||
@@ -399,13 +680,18 @@ class Cafe24Store:
|
||||
revision_type: str,
|
||||
memo: str = "",
|
||||
created_by: str = "",
|
||||
mall_id: str = "",
|
||||
shop_no: int = 1,
|
||||
source: str = "",
|
||||
source_revision_id: int | None = None,
|
||||
) -> int:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cafe24_product_revisions
|
||||
(product_no, html_content, revision_type, memo, created_by)
|
||||
VALUES (%s,%s,%s,%s,%s)
|
||||
(product_no, html_content, revision_type, memo, created_by,
|
||||
mall_id, shop_no, source, source_revision_id)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
@@ -414,24 +700,33 @@ class Cafe24Store:
|
||||
store.normalize_revision_type(revision_type),
|
||||
(memo or "")[:500],
|
||||
created_by or "",
|
||||
mall_id or "",
|
||||
int(shop_no or 1),
|
||||
source or "",
|
||||
source_revision_id,
|
||||
),
|
||||
).fetchone()
|
||||
return int(row["id"]) if row else 0
|
||||
|
||||
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
||||
length(html_content) AS html_length
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(int(product_no), max(1, min(int(limit), 200))),
|
||||
).fetchall()
|
||||
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다.
|
||||
|
||||
005 적용 전이면 출처(source) 없이 돌려준다(읽기 경로는 막지 않는다)."""
|
||||
sql = """
|
||||
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
||||
length(html_content) AS html_length{extra}
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT %s
|
||||
"""
|
||||
args = (int(product_no), max(1, min(int(limit), 200)))
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(sql.format(extra=", source, source_revision_id, mall_id"), args).fetchall()
|
||||
except pg_errors.UndefinedColumn:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(sql.format(extra=""), args).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
||||
@@ -568,18 +863,24 @@ class Cafe24Store:
|
||||
)
|
||||
return True
|
||||
|
||||
@contextmanager
|
||||
def claim_due_schedule(self, *, now: datetime) -> Iterator[dict[str, Any] | None]:
|
||||
"""실행할 예약 1건을 잡아 PROCESSING 으로 바꾼다(worker 전용).
|
||||
# ── 예약 실행 lease (마이그레이션 005) ──
|
||||
# PROCESSING 은 lease_expires_at 까지만 유효하다. worker 가 죽으면 만료 후
|
||||
# claim_expired_schedules 로 다른(또는 재기동한) worker 가 가져가 시도 기록을 보고
|
||||
# 성공/재시도/확인 필요로 나눈다(worker.recover_expired). 모든 상태 변경은
|
||||
# lease_token 이 맞을 때만 한다 — 만료 뒤 늦게 끝난 worker 가 결과를 덮지 않게.
|
||||
def claim_due_schedule(self, *, now: datetime, owner: str, ttl_seconds: int) -> dict[str, Any] | None:
|
||||
"""실행할 예약 1건을 잡아 PROCESSING + lease 로 바꾼다(worker 전용).
|
||||
|
||||
`FOR UPDATE SKIP LOCKED` 로 잠그므로 worker 가 여러 개 떠 있어도 같은 예약을
|
||||
두 번 실행하지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
||||
두 번 잡지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
||||
반환 행의 lease_token 으로 renew/finish 한다.
|
||||
"""
|
||||
token = uuid.uuid4().hex
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT * FROM cafe24_product_schedules
|
||||
SELECT id FROM cafe24_product_schedules
|
||||
WHERE status = 'PENDING'
|
||||
AND scheduled_at <= %s
|
||||
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
||||
@@ -589,48 +890,154 @@ class Cafe24Store:
|
||||
""",
|
||||
(now, now),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = 'PROCESSING', started_at = now(), last_error = ''
|
||||
WHERE id = %s
|
||||
""",
|
||||
(row["id"],),
|
||||
if row is None:
|
||||
return None
|
||||
claimed = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = 'PROCESSING', started_at = now(), last_error = '',
|
||||
lease_owner = %s, lease_token = %s,
|
||||
lease_expires_at = now() + %s * interval '1 second'
|
||||
WHERE id = %s
|
||||
RETURNING *
|
||||
""",
|
||||
((owner or "")[:200], token, max(1, int(ttl_seconds)), row["id"]),
|
||||
).fetchone()
|
||||
return dict(claimed) if claimed else None
|
||||
|
||||
def claim_expired_schedules(
|
||||
self, *, owner: str, ttl_seconds: int, legacy_minutes: int, limit: int = 20
|
||||
) -> list[dict[str, Any]]:
|
||||
"""lease 가 만료된 PROCESSING 예약을 이 worker 에게 다시 lease 한다(복구 전용).
|
||||
|
||||
lease 컬럼이 비어 있는 옛 행(005 이전에 PROCESSING 이 된 것)은 started_at 이
|
||||
legacy_minutes 보다 오래됐으면 만료로 본다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
rows = conn.execute(
|
||||
"""
|
||||
WITH picked AS (
|
||||
SELECT id FROM cafe24_product_schedules
|
||||
WHERE status = 'PROCESSING'
|
||||
AND (lease_expires_at < now()
|
||||
OR (lease_expires_at IS NULL
|
||||
AND COALESCE(started_at, updated_at)
|
||||
< now() - %s * interval '1 minute'))
|
||||
ORDER BY id
|
||||
LIMIT %s
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
yield dict(row) if row is not None else None
|
||||
UPDATE cafe24_product_schedules s
|
||||
SET lease_owner = %s,
|
||||
lease_token = md5(random()::text || clock_timestamp()::text || s.id::text),
|
||||
lease_expires_at = now() + %s * interval '1 second'
|
||||
FROM picked
|
||||
WHERE s.id = picked.id
|
||||
RETURNING s.*
|
||||
""",
|
||||
(max(1, int(legacy_minutes)), max(1, int(limit)), (owner or "")[:200],
|
||||
max(1, int(ttl_seconds))),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def renew_schedule_lease(self, schedule_id: int, token: str, *, ttl_seconds: int) -> bool:
|
||||
"""아직 내 lease 면 연장하고 True. 만료돼 넘어갔으면 False — 카페24에 쓰지 않는다."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET lease_expires_at = now() + %s * interval '1 second'
|
||||
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||
AND lease_expires_at > now()
|
||||
RETURNING id
|
||||
""",
|
||||
(max(1, int(ttl_seconds)), int(schedule_id), token),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def finish_schedule(
|
||||
self,
|
||||
schedule_id: int,
|
||||
*,
|
||||
token: str,
|
||||
status: str,
|
||||
error: str = "",
|
||||
next_retry_at: datetime | None = None,
|
||||
retry_count: int | None = None,
|
||||
) -> None:
|
||||
"""예약 종료 처리. 재시도로 되돌릴 때는 status='PENDING' + next_retry_at."""
|
||||
) -> bool:
|
||||
"""예약 종료 처리(lease 가 내 것일 때만). 재시도로 되돌릴 때는 status='PENDING' + next_retry_at.
|
||||
|
||||
반환: 반영했으면 True. lease 를 잃었으면 False(다른 worker 가 복구 중 — 덮지 않는다).
|
||||
"""
|
||||
normalized = store.normalize_schedule_status(status)
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = %s,
|
||||
last_error = %s,
|
||||
next_retry_at = %s,
|
||||
retry_count = COALESCE(%s, retry_count),
|
||||
lease_owner = '', lease_token = '', lease_expires_at = NULL,
|
||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
||||
THEN now() ELSE completed_at END
|
||||
WHERE id = %s
|
||||
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
store.normalize_schedule_status(status),
|
||||
(error or "")[:1000],
|
||||
next_retry_at,
|
||||
retry_count,
|
||||
store.normalize_schedule_status(status),
|
||||
int(schedule_id),
|
||||
),
|
||||
)
|
||||
(normalized, (error or "")[:1000], next_retry_at, retry_count, normalized,
|
||||
int(schedule_id), token),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def get_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM cafe24_product_schedules WHERE id = %s", (int(schedule_id),)
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
def review_schedule(
|
||||
self, schedule_id: int, *, status: str, note: str, actor: str, action: str
|
||||
) -> dict[str, Any]:
|
||||
"""확인 필요(NEEDS_REVIEW) 예약을 사람이 확정한다 — SUCCESS / FAILED / PENDING(다시 실행).
|
||||
|
||||
SUCCESS 가 아니면 그 예약의 열린 쓰기 시도(STARTED/UNKNOWN)를 ABANDONED 로 닫는다
|
||||
(반영 안 됨으로 확정 / 재실행으로 대체). SUCCESS 면 호출부가 버전 기록을 채운다.
|
||||
반환: 바뀐 예약 행. NEEDS_REVIEW 가 아니었으면 {}.
|
||||
"""
|
||||
normalized = store.normalize_schedule_status(status)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = %s, last_error = %s,
|
||||
next_retry_at = CASE WHEN %s = 'PENDING' THEN now() ELSE NULL END,
|
||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED') THEN now() ELSE NULL END
|
||||
WHERE id = %s AND status = 'NEEDS_REVIEW'
|
||||
RETURNING *
|
||||
""",
|
||||
(normalized, (note or "")[:1000], normalized, normalized, int(schedule_id)),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return {}
|
||||
if normalized != store.STATUS_SUCCESS:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_write_attempts
|
||||
SET status = %s, resolved_by = %s
|
||||
WHERE schedule_id = %s AND status = ANY(%s)
|
||||
""",
|
||||
(store.ATTEMPT_ABANDONED, (actor or "")[:200], int(schedule_id),
|
||||
[store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN]),
|
||||
)
|
||||
self._insert_audit(
|
||||
conn, actor=actor, action=f"schedule_review:{action}",
|
||||
product_no=row["product_no"], schedule_id=row["id"], result="SUCCESS",
|
||||
detail=note,
|
||||
)
|
||||
return self._serialize(row)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일)
|
||||
|
||||
@@ -13,8 +13,11 @@
|
||||
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
||||
|
||||
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
||||
FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
||||
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부) → FTP 에 쓴다
|
||||
파일별 DB 잠금(writes.write_lock, 'design:{file_key}')
|
||||
→ FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
||||
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부)
|
||||
→ 임시 파일 업로드·검증 → 교체 직전 원본 재확인 → 이름 바꾸기로 교체
|
||||
(design_ftp.write_text_file — 원본에 직접 STOR 하지 않는다)
|
||||
→ MANUAL 버전 + 감사로그
|
||||
|
||||
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
||||
@@ -24,12 +27,14 @@ FastAPI 스레드풀에서 돌게 둔다(다른 cafe24 라우트와 동일한
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Form, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
|
||||
from app.integrations.cafe24 import (
|
||||
DESIGN_FILE_SPECS,
|
||||
Cafe24FtpConflict,
|
||||
Cafe24FtpError,
|
||||
design_file_label,
|
||||
design_file_path,
|
||||
@@ -38,7 +43,7 @@ from app.integrations.cafe24 import (
|
||||
load_ftp_config,
|
||||
)
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard
|
||||
from .routes_products import _no_store
|
||||
|
||||
@@ -128,74 +133,76 @@ def design_file_apply(
|
||||
st, user = checked
|
||||
actor = str(user.get("email") or "")
|
||||
back = f"/cafe24/design/{file_key}"
|
||||
action = f"apply_design:{file_key}"
|
||||
|
||||
def go(*, msg: str = "", err: str = "") -> RedirectResponse:
|
||||
key, text = ("err", err) if err else ("msg", msg)
|
||||
return RedirectResponse(url=f"{back}?{key}={quote(text, safe='')}", status_code=303)
|
||||
|
||||
path = design_file_path(file_key)
|
||||
ftp_config = _ftp_config()
|
||||
if not ftp_config.configured:
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=" + "FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing),
|
||||
status_code=303,
|
||||
)
|
||||
return go(err="FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing))
|
||||
|
||||
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
||||
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
||||
submitted = content.replace("\r\n", "\n")
|
||||
if not submitted.strip():
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=" + "내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.",
|
||||
status_code=303,
|
||||
)
|
||||
return go(err="내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.")
|
||||
|
||||
# 같은 파일을 두 사람이 동시에 적용하지 못하게 파일별 DB 잠금 안에서 한다.
|
||||
try:
|
||||
current = design_ftp.read_text_file(ftp_config, path)
|
||||
except Cafe24FtpError as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", result="FAIL",
|
||||
detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
return RedirectResponse(url=f"{back}?err=현재 파일을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
||||
with writes.write_lock(st, writes.design_lock_key(file_key), actor=actor, purpose=f"{file_key} 적용"):
|
||||
try:
|
||||
current = design_ftp.read_text_file(ftp_config, path)
|
||||
except Cafe24FtpError as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
return go(err=f"현재 파일을 읽지 못해 중단했습니다: {exc}")
|
||||
|
||||
backup_id = st.add_design_revision(
|
||||
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업", created_by=actor,
|
||||
)
|
||||
backup_id = st.add_design_revision(
|
||||
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업", created_by=actor,
|
||||
)
|
||||
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
||||
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨",
|
||||
)
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
||||
status_code=303,
|
||||
)
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
||||
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨")
|
||||
return go(err="편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.")
|
||||
|
||||
if submitted == current:
|
||||
return RedirectResponse(url=f"{back}?msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
||||
if submitted == current:
|
||||
return go(msg="변경된 내용이 없어 적용하지 않았습니다.")
|
||||
|
||||
try:
|
||||
design_ftp.write_text_file(ftp_config, path, submitted)
|
||||
except Cafe24FtpError as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
||||
result="FAIL", detail=str(exc),
|
||||
)
|
||||
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
||||
status_code=303,
|
||||
)
|
||||
try:
|
||||
# 임시 파일 업로드 → 검증 → 교체 직전 원본 재확인(current 와 같아야) → 이름 바꾸기.
|
||||
design_ftp.write_text_file(ftp_config, path, submitted, expected_current=current)
|
||||
except Cafe24FtpConflict as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||
result="FAIL", detail=f"충돌 — 교체 직전 파일이 변경됨: {exc}")
|
||||
return go(err=f"{exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||
except Cafe24FtpError as exc:
|
||||
maybe = bool(getattr(exc, "maybe_applied", False))
|
||||
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||
result="UNKNOWN" if maybe else "FAIL", detail=str(exc))
|
||||
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
||||
return go(err=f"적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||
|
||||
revision_id = st.add_design_revision(
|
||||
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
||||
memo=memo, created_by=actor,
|
||||
)
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", revision_id=revision_id, result="SUCCESS",
|
||||
detail=f"{len(submitted)}자 적용 (백업 {backup_id})",
|
||||
# 파일은 이미 바뀌었다 — 여기서의 기록 실패는 "적용 실패"가 아니다.
|
||||
record_note = ""
|
||||
try:
|
||||
revision_id = st.add_design_revision(
|
||||
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
||||
memo=memo, created_by=actor,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("디자인 파일(%s) 적용 후 버전 기록 실패", file_key)
|
||||
revision_id = None
|
||||
record_note = " ※ 파일은 적용됐지만 버전 기록 저장에 실패했습니다 — 다시 적용하지 마세요."
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
return go(err=str(exc))
|
||||
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action=action, revision_id=revision_id, result="SUCCESS",
|
||||
detail=f"{len(submitted)}자 적용 (백업 {backup_id}, 임시 파일 교체 방식)" + (" / 버전 기록 실패" if record_note else ""),
|
||||
)
|
||||
logger.info("디자인 파일 적용(%s) (%s)", file_key, actor)
|
||||
return RedirectResponse(
|
||||
url=f"{back}?msg=적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.",
|
||||
status_code=303,
|
||||
)
|
||||
return go(msg=f"적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{record_note}")
|
||||
|
||||
@@ -9,15 +9,20 @@
|
||||
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
||||
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
||||
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
||||
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매
|
||||
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매 (행별 결과)
|
||||
|
||||
공통 규칙
|
||||
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
||||
- 쓰기는 상품별 DB 잠금(writes.write_lock) 안에서 한다 — 같은 상품을 웹 여러
|
||||
프로세스·예약 worker 가 동시에 쓰지 않게. 못 잡으면 409.
|
||||
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
||||
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
||||
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
||||
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
||||
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
||||
PUT 이 성공한 뒤의 기록 실패는 쓰기 실패로 알리지 않는다(재전송을 부르지 않게).
|
||||
- 품목은 **품목코드**(안정 식별자)로 짝짓는다. 옵션값 이름을 바꾼 직후 GET 품목이
|
||||
예전 이름을 돌려줘도 스냅샷의 품목코드별 표기로 바로잡는다(store.apply_variant_patch).
|
||||
- 모든 쓰기는 감사로그(`cafe24_audit_logs`)에 남긴다.
|
||||
"""
|
||||
|
||||
@@ -31,9 +36,9 @@ from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import read_lag_grace_minutes, require_store
|
||||
from .routes_products import load_product, remember_write
|
||||
from .routes_products import load_product, locked_json, remember_write
|
||||
|
||||
logger = logging.getLogger("cafe24.product_info")
|
||||
|
||||
@@ -110,39 +115,40 @@ def product_basic(
|
||||
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
with locked_json(st, product_no, actor=actor, purpose="상품명·가격 변경"):
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
|
||||
changes: dict[str, str] = {}
|
||||
before: dict[str, str] = {}
|
||||
for key, value in want.items():
|
||||
old = str(current.get(key) or "")
|
||||
same = old == value if key == "product_name" else store.price_equal(old, value)
|
||||
if not same:
|
||||
changes[key] = value
|
||||
before[key] = old
|
||||
if not changes:
|
||||
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
||||
changes: dict[str, str] = {}
|
||||
before: dict[str, str] = {}
|
||||
for key, value in want.items():
|
||||
old = str(current.get(key) or "")
|
||||
same = old == value if key == "product_name" else store.price_equal(old, value)
|
||||
if not same:
|
||||
changes[key] = value
|
||||
before[key] = old
|
||||
if not changes:
|
||||
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
||||
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, **changes)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"{changes} 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, **changes)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"{changes} 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
||||
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
|
||||
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
|
||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
||||
result="SUCCESS", detail=detail)
|
||||
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||
result="SUCCESS", detail=detail)
|
||||
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
||||
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
||||
|
||||
@@ -169,30 +175,31 @@ def product_image(
|
||||
data = _read_image(file)
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
before = str(current.get("detail_image") or "")
|
||||
with locked_json(st, product_no, actor=actor, purpose="대표 이미지 교체"):
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
before = str(current.get("detail_image") or "")
|
||||
|
||||
try:
|
||||
images = products.set_main_image(
|
||||
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
||||
)
|
||||
if not images.get("detail_image"):
|
||||
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="FAIL", detail=f"등록 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
try:
|
||||
images = products.set_main_image(
|
||||
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
||||
)
|
||||
if not images.get("detail_image"):
|
||||
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="FAIL", detail=f"등록 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||
remember_write(st, product_no, merged)
|
||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
||||
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||
remember_write(st, product_no, merged)
|
||||
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
||||
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
||||
return {"ok": True, "product": _scalar_view(merged)}
|
||||
|
||||
@@ -208,6 +215,8 @@ def _variant_view(v: dict[str, Any]) -> dict[str, Any]:
|
||||
{"name": str(o.get("name") or ""), "value": str(o.get("value") or "")}
|
||||
for o in opts if isinstance(o, dict)
|
||||
],
|
||||
# 첫 옵션의 옵션값 번호(value_no) — 화면이 이름보다 먼저 이것으로 옵션값과 짝짓는다.
|
||||
"value_no": v.get("value_no"),
|
||||
"custom_variant_code": str(v.get("custom_variant_code") or ""),
|
||||
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
||||
"display": products._flag(v.get("display")), # noqa: SLF001
|
||||
@@ -238,6 +247,7 @@ def _options_view(option: dict[str, Any]) -> dict[str, Any]:
|
||||
"option_link_image": str(v.get("option_link_image") or ""),
|
||||
"option_color": str(v.get("option_color") or ""),
|
||||
"value_no": v.get("value_no"),
|
||||
"pending": bool(v.get("pending")),
|
||||
}
|
||||
for v in values if isinstance(v, dict)
|
||||
],
|
||||
@@ -252,43 +262,125 @@ def _options_view(option: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _apply_variant_snapshot(st: Any, product_no: int, variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""GET 품목 목록에 유예시간 안의 우리 쓰기(스냅샷)를 덮어씌운다.
|
||||
def _snapshot_sections(st: Any, product_no: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""(옵션 섹션, 품목 섹션) — 각각 {"data":…, "written_at":…} 또는 {}."""
|
||||
snap = st.get_write_snapshot(product_no) or {}
|
||||
return snap.get("options") or {}, snap.get("variants") or {}
|
||||
|
||||
삭제한 품목(`{"_deleted": true}`)은 카페24 GET 이 한동안 계속 돌려주므로 걸러낸다.
|
||||
"""
|
||||
section = (st.get_write_snapshot(product_no) or {}).get("variants") or {}
|
||||
|
||||
def _within(written_at: object) -> bool:
|
||||
return store.within_grace(written_at, grace_minutes=read_lag_grace_minutes())
|
||||
|
||||
|
||||
def _patch_variants(section: dict[str, Any], variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""GET 품목 목록에 품목코드별 쓰기 기록을 덮어씌운다(삭제한 품목은 뺀다)."""
|
||||
data = section.get("data") or {}
|
||||
if not data or not store.within_grace(section.get("written_at"), grace_minutes=read_lag_grace_minutes()):
|
||||
return variants
|
||||
if not isinstance(data, dict) or not data:
|
||||
return list(variants)
|
||||
out = []
|
||||
for v in variants:
|
||||
code = str(v.get("variant_code") or "")
|
||||
patch = data.get(code)
|
||||
if isinstance(patch, dict) and patch.get("_deleted"):
|
||||
continue
|
||||
out.append({**v, **patch} if isinstance(patch, dict) else v)
|
||||
patched = store.apply_variant_patch(
|
||||
v, data.get(str(v.get("variant_code") or "")),
|
||||
section_written_at=section.get("written_at"), grace_minutes=read_lag_grace_minutes(),
|
||||
)
|
||||
if patched is not None:
|
||||
out.append(patched)
|
||||
return out
|
||||
|
||||
|
||||
def _apply_options_snapshot(st: Any, product_no: int, option: dict[str, Any]) -> dict[str, Any]:
|
||||
"""GET 옵션이 우리 마지막 쓰기와 다르고 유예시간 안이면 스냅샷(우리 쓰기)을 쓴다."""
|
||||
section = (st.get_write_snapshot(product_no) or {}).get("options") or {}
|
||||
data = section.get("data")
|
||||
if not isinstance(data, dict) or not store.within_grace(
|
||||
section.get("written_at"), grace_minutes=read_lag_grace_minutes()
|
||||
):
|
||||
return option
|
||||
return data
|
||||
def _annotate(option: dict[str, Any], variants: list[dict[str, Any]], recent: list[str]) -> tuple[dict, list]:
|
||||
"""옵션 1개 상품: 품목에 첫 옵션값 번호(value_no)를, 품목이 아직 안 보이는 최근 추가
|
||||
옵션값에 pending 표시를 붙인다(화면이 "품목 없는 옵션값"으로 오해하지 않게)."""
|
||||
groups = option.get("options") if isinstance(option.get("options"), list) else []
|
||||
if len(groups) != 1 or not isinstance(groups[0], dict):
|
||||
return option, variants
|
||||
values = [v for v in (groups[0].get("option_value") or []) if isinstance(v, dict)]
|
||||
by_text = {str(v.get("option_text") or ""): v.get("value_no") for v in values}
|
||||
used: set[str] = set()
|
||||
out_variants = []
|
||||
for v in variants:
|
||||
opts = v.get("options") if isinstance(v.get("options"), list) else []
|
||||
first = str(opts[0].get("value") or "") if opts and isinstance(opts[0], dict) else ""
|
||||
used.add(first)
|
||||
out_variants.append({**v, "value_no": by_text.get(first)} if first in by_text else v)
|
||||
recent_set = set(recent or [])
|
||||
new_values = [
|
||||
{**v, "pending": True} if str(v.get("option_text") or "") in recent_set
|
||||
and str(v.get("option_text") or "") not in used else v
|
||||
for v in values
|
||||
]
|
||||
return {**option, "options": [{**groups[0], "option_value": new_values}]}, out_variants
|
||||
|
||||
|
||||
def _load_options_and_variants(st: Any, api: Any, product_no: int) -> dict[str, Any]:
|
||||
option = _apply_options_snapshot(st, product_no, products.get_options(api.client, product_no))
|
||||
view = _options_view(option)
|
||||
raw_option = products.get_options(api.client, product_no)
|
||||
osec, vsec = _snapshot_sections(st, product_no)
|
||||
option, _stale = store.overlay_options(
|
||||
raw_option, snapshot=osec.get("data"), written_at=osec.get("written_at"),
|
||||
grace_minutes=read_lag_grace_minutes(),
|
||||
)
|
||||
raw_variants: list[dict[str, Any]] = []
|
||||
variants: list[dict[str, Any]] = []
|
||||
if view["has_option"]:
|
||||
variants = _apply_variant_snapshot(st, product_no, products.list_variants(api.client, product_no))
|
||||
return {"option": view, "variants": [_variant_view(v) for v in variants], "raw_options": option}
|
||||
if products._flag(option.get("has_option"), default=False): # noqa: SLF001
|
||||
raw_variants = products.list_variants(api.client, product_no)
|
||||
variants = _patch_variants(vsec, raw_variants)
|
||||
recent = _recent_values(osec)
|
||||
shown_option, shown_variants = _annotate(option, variants, recent)
|
||||
return {
|
||||
"option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"raw_option": raw_option,
|
||||
"effective_option": option,
|
||||
"raw_variants": raw_variants,
|
||||
"effective_variants": variants,
|
||||
"options_section": osec,
|
||||
"variants_section": vsec,
|
||||
}
|
||||
|
||||
|
||||
def _recent_values(osec: dict[str, Any]) -> list[str]:
|
||||
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
||||
if not data or not _within(osec.get("written_at")):
|
||||
return []
|
||||
return [str(v) for v in (data.get("_recent_values") or [])]
|
||||
|
||||
|
||||
def _prior_signatures(osec: dict[str, Any]) -> list[str]:
|
||||
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
||||
if not data or not _within(osec.get("written_at")):
|
||||
return []
|
||||
return [str(s) for s in (data.get("_before_signatures") or []) if isinstance(s, str)]
|
||||
|
||||
|
||||
def _unique(items: list[Any]) -> list[Any]:
|
||||
out: list[Any] = []
|
||||
for item in items:
|
||||
if item not in out:
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _options_snapshot(
|
||||
written: dict[str, Any], *, befores: list[dict[str, Any]], osec: dict[str, Any], recent: list[str]
|
||||
) -> dict[str, Any]:
|
||||
"""옵션 스냅샷 = 카페24 응답 + 쓰기 직전 모양들의 서명 + 최근 추가한 옵션값."""
|
||||
signatures = _unique(_prior_signatures(osec) + [store.options_signature(b) for b in befores if b])
|
||||
texts = {
|
||||
str(v.get("option_text") or "")
|
||||
for o in (written.get("options") or []) if isinstance(o, dict)
|
||||
for v in (o.get("option_value") or []) if isinstance(v, dict)
|
||||
}
|
||||
keep = [t for t in _unique(_recent_values(osec) + list(recent)) if t in texts]
|
||||
return {**written, "_before_signatures": signatures, "_recent_values": keep}
|
||||
|
||||
|
||||
def _save_snapshot_safe(st: Any, product_no: int, section: str, data: Any, **kw: Any) -> str:
|
||||
try:
|
||||
st.save_write_snapshot(product_no, section, data, **kw)
|
||||
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
|
||||
logger.exception("상품 %s %s 스냅샷 저장 실패", product_no, section)
|
||||
return f"{type(exc).__name__}: {exc}"
|
||||
return ""
|
||||
|
||||
|
||||
@product_info_router.get("/products/{product_no}/options")
|
||||
@@ -322,29 +414,40 @@ def options_create(
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
existing = products.get_options(api.client, product_no)
|
||||
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
||||
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
||||
created = products.create_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="create_options", product_no=product_no,
|
||||
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
with locked_json(st, product_no, actor=actor, purpose="옵션 생성"):
|
||||
try:
|
||||
existing = products.get_options(api.client, product_no)
|
||||
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
||||
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
||||
created = products.create_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no,
|
||||
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
st.save_write_snapshot(product_no, "options", created)
|
||||
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
||||
st.log_audit(actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
||||
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
||||
osec, _vsec = _snapshot_sections(st, product_no)
|
||||
record_error = _save_snapshot_safe(
|
||||
st, product_no, "options",
|
||||
_options_snapshot(created, befores=[existing], osec=osec, recent=values),
|
||||
)
|
||||
# 새 옵션의 품목은 새 품목코드다 — 이전 품목 기록은 모두 버린다(전체 초기화).
|
||||
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
||||
# 카페24가 자동 생성한 품목(코드 부여)을 바로 돌려준다 — 읽기 지연이 있어 짧게 재시도.
|
||||
# 화면은 이 코드로 자체코드·추가금액을 이어서 PUT 한다. 다 안 보이면 pending 으로 표시.
|
||||
variants = products.wait_for_variants(api.client, product_no, len(values))
|
||||
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
||||
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
||||
logger.info("카페24 상품 %s 옵션 생성 (%s)", product_no, actor)
|
||||
# 카페24가 자동 생성한 품목(코드 부여)을 바로 돌려준다 — 읽기 지연이 있어 짧게 재시도.
|
||||
# 화면은 이 코드로 자체코드·추가금액을 이어서 PUT 한다.
|
||||
variants = products.wait_for_variants(api.client, product_no, len(values))
|
||||
if len(variants) < len(values):
|
||||
logger.warning("카페24 상품 %s 옵션 생성 후 품목 %s/%s 건만 조회됨", product_no, len(variants), len(values))
|
||||
return {"ok": True, "option": _options_view(created), "variants": [_variant_view(v) for v in variants]}
|
||||
shown_option, shown_variants = _annotate(created, variants, values)
|
||||
return {"ok": True, "option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"missing_variants": max(0, len(values) - len(variants)),
|
||||
"record_warning": record_error}
|
||||
|
||||
|
||||
@product_info_router.put("/products/{product_no}/options")
|
||||
@@ -358,6 +461,8 @@ def options_update(
|
||||
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
||||
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
||||
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
||||
이름을 바꾸면 품목코드별로 새 표기를 스냅샷에 남긴다(GET 품목이 예전 이름을
|
||||
돌려주는 동안에도 품목이 옵션값과 제대로 짝지어 보이게).
|
||||
"""
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
@@ -366,64 +471,99 @@ def options_update(
|
||||
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
loaded = _load_options_and_variants(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not loaded["option"]["has_option"]:
|
||||
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
||||
original = loaded["option"]["options"]
|
||||
try:
|
||||
body = store.build_update_options_request(
|
||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
||||
allow_append=True,
|
||||
with locked_json(st, product_no, actor=actor, purpose="옵션 수정"):
|
||||
try:
|
||||
loaded = _load_options_and_variants(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not loaded["option"]["has_option"]:
|
||||
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
||||
original = loaded["option"]["options"]
|
||||
try:
|
||||
body = store.build_update_options_request(
|
||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
||||
allow_append=True,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if loaded["option"]["option_preset_code"]:
|
||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
||||
# 뒤에 덧붙인 옵션값 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
||||
added_texts = [
|
||||
v["option_text"]
|
||||
for o, n in zip(body["original_options"], body["options"])
|
||||
for v in n["option_value"][len(o["option_value"]):]
|
||||
]
|
||||
added = len(added_texts)
|
||||
|
||||
try:
|
||||
updated = products.update_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
# ── 여기부터는 카페24에 반영된 뒤 — 기록 실패는 경고로만 알린다 ──
|
||||
record_error = _save_snapshot_safe(
|
||||
st, product_no, "options",
|
||||
_options_snapshot(updated, befores=[loaded["raw_option"], loaded["effective_option"]],
|
||||
osec=loaded["options_section"], recent=added_texts),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if loaded["option"]["option_preset_code"]:
|
||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
||||
# 뒤에 덧붙인 옵션값 수 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
||||
added = sum(
|
||||
max(0, len(n["option_value"]) - len(o["option_value"]))
|
||||
for o, n in zip(body["original_options"], body["options"])
|
||||
)
|
||||
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
||||
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||
for o, n in zip(original, body["options"]):
|
||||
for ov, nv in zip(o["option_value"], n["option_value"]):
|
||||
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
||||
raw_labels = {str(v.get("variant_code") or ""): v.get("options") for v in loaded["raw_variants"]}
|
||||
previous = (loaded["variants_section"].get("data") or {}) if _within(
|
||||
loaded["variants_section"].get("written_at")) else {}
|
||||
label_patch: dict[str, Any] = {}
|
||||
renamed_variants: list[dict[str, Any]] = []
|
||||
for v in loaded["effective_variants"]:
|
||||
code = str(v.get("variant_code") or "")
|
||||
current = store.labels_as_json(v.get("options"))
|
||||
new = [
|
||||
dict(zip(("name", "value"), rename.get((o["name"], o["value"]), (o["name"], o["value"]))))
|
||||
for o in current
|
||||
]
|
||||
renamed_variants.append({**v, "options": new})
|
||||
if new != current and code:
|
||||
prior = previous.get(code) if isinstance(previous.get(code), dict) else {}
|
||||
history = [
|
||||
[{"name": a, "value": b} for a, b in labels]
|
||||
for labels in store.label_history(prior.get("_options_before"))
|
||||
]
|
||||
befores = _unique(history + [current, store.labels_as_json(raw_labels.get(code))])
|
||||
label_patch[code] = {"options": new, "_options_before": [b for b in befores if b != new]}
|
||||
if label_patch:
|
||||
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", label_patch)
|
||||
summary = "; ".join(
|
||||
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
||||
for o in body["options"]
|
||||
) + (f" (+{added} 추가)" if added else "")
|
||||
|
||||
try:
|
||||
updated = products.update_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
st.save_write_snapshot(product_no, "options", updated)
|
||||
summary = "; ".join(
|
||||
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
||||
for o in body["options"]
|
||||
) + (f" (+{added} 추가)" if added else "")
|
||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
||||
result="SUCCESS", detail=summary[:900])
|
||||
fresh: list[dict[str, Any]] | None = None
|
||||
if added:
|
||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
||||
# 늦게 나타나는 품목은 pending 으로 표시된다(_annotate).
|
||||
_osec, vsec = _snapshot_sections(st, product_no)
|
||||
fresh = _patch_variants(
|
||||
vsec, products.wait_for_variants(api.client, product_no, len(loaded["raw_variants"]) + added)
|
||||
)
|
||||
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||
result="SUCCESS", detail=summary[:900])
|
||||
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
||||
|
||||
shown_option, shown_variants = _annotate(
|
||||
updated, fresh if fresh is not None else renamed_variants, added_texts
|
||||
)
|
||||
out: dict[str, Any] = {"ok": True, "option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"record_warning": record_error}
|
||||
if added:
|
||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
||||
fresh = products.wait_for_variants(api.client, product_no, len(loaded["variants"]) + added)
|
||||
fresh = _apply_variant_snapshot(st, product_no, fresh)
|
||||
return {"ok": True, "option": _options_view(updated), "variants": [_variant_view(v) for v in fresh],
|
||||
"added": added}
|
||||
|
||||
# 품목의 옵션값 표기는 이름을 바꾼 만큼 달라진다 — 응답값으로 다시 맞춘다.
|
||||
variants = loaded["variants"]
|
||||
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||
for o, n in zip(original, body["options"]):
|
||||
for ov, nv in zip(o["option_value"], n["option_value"]):
|
||||
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
||||
for v in variants:
|
||||
v["options"] = [
|
||||
dict(zip(("name", "value"), rename.get((opt["name"], opt["value"]), (opt["name"], opt["value"]))))
|
||||
for opt in v["options"]
|
||||
]
|
||||
return {"ok": True, "option": _options_view(updated), "variants": variants}
|
||||
out["added"] = added
|
||||
return out
|
||||
|
||||
|
||||
@product_info_router.delete("/products/{product_no}/options")
|
||||
@@ -432,22 +572,29 @@ def options_delete(request: Request, product_no: int) -> dict[str, Any]:
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
before = products.get_options(api.client, product_no)
|
||||
products.delete_options(api.client, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
names = ", ".join(
|
||||
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
||||
)
|
||||
st.save_write_snapshot(product_no, "options", {"has_option": "F", "options": []})
|
||||
st.save_write_snapshot(product_no, "variants", {})
|
||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
||||
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
||||
with locked_json(st, product_no, actor=actor, purpose="옵션 삭제"):
|
||||
try:
|
||||
before = products.get_options(api.client, product_no)
|
||||
products.delete_options(api.client, product_no)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
names = ", ".join(
|
||||
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
||||
)
|
||||
osec, _vsec = _snapshot_sections(st, product_no)
|
||||
record_error = _save_snapshot_safe(
|
||||
st, product_no, "options",
|
||||
_options_snapshot({"has_option": "F", "options": []}, befores=[before], osec=osec, recent=[]),
|
||||
)
|
||||
# 품목 전체 초기화 — 빈 dict 병합(=변경 없음)이 아니라 명시적 replace.
|
||||
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
||||
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
||||
logger.info("카페24 상품 %s 옵션 삭제 (%s)", product_no, actor)
|
||||
return {"ok": True, "option": _options_view({"has_option": "F"}), "variants": []}
|
||||
return {"ok": True, "option": _options_view({"has_option": "F"}), "variants": [],
|
||||
"record_warning": record_error}
|
||||
|
||||
|
||||
@product_info_router.post("/products/{product_no}/options/image")
|
||||
@@ -464,13 +611,13 @@ def option_image_upload(
|
||||
try:
|
||||
path = products.upload_image_bytes(api.client, data)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not path:
|
||||
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="SUCCESS", detail=path)
|
||||
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="SUCCESS", detail=path)
|
||||
return {"ok": True, "path": path}
|
||||
|
||||
|
||||
@@ -483,18 +630,20 @@ def variant_delete(request: Request, product_no: int, variant_code: str) -> dict
|
||||
if not store.VARIANT_CODE_RE.match(code):
|
||||
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
products.delete_variant(api.client, product_no, code)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="FAIL", detail=f"{code}: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 스냅샷에 삭제 표식을 남겨 걸러낸다.
|
||||
st.save_write_snapshot(product_no, "variants", {code: {"_deleted": True}})
|
||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="SUCCESS", detail=code)
|
||||
with locked_json(st, product_no, actor=actor, purpose="품목 삭제"):
|
||||
try:
|
||||
products.delete_variant(api.client, product_no, code)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="FAIL", detail=f"{code}: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 삭제 표식을 남겨 걸러낸다.
|
||||
# 표식은 이후 늦게 도착한 수정이 있어도 유지된다(store.merge_variant_snapshot).
|
||||
record_error = _save_snapshot_safe(st, product_no, "variants", {code: {"_deleted": True}})
|
||||
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="SUCCESS", detail=code)
|
||||
logger.info("카페24 상품 %s 품목 %s 삭제 (%s)", product_no, code, actor)
|
||||
return {"ok": True, "variant_code": code}
|
||||
return {"ok": True, "variant_code": code, "record_warning": record_error}
|
||||
|
||||
|
||||
@product_info_router.put("/products/{product_no}/variants")
|
||||
@@ -503,7 +652,13 @@ def variants_update(
|
||||
product_no: int,
|
||||
payload: dict[str, Any] = Body(default_factory=dict),
|
||||
) -> dict[str, Any]:
|
||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다."""
|
||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다 — **행별 결과**.
|
||||
|
||||
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
||||
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||
"""
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
rows = payload.get("rows")
|
||||
@@ -517,31 +672,51 @@ def variants_update(
|
||||
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
with locked_json(st, product_no, actor=actor, purpose="품목 수정"):
|
||||
results = products.update_variants(api.client, product_no, requests)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_variants", product_no=product_no,
|
||||
result="FAIL", detail=f"{len(requests)}건 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 품목 수정 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
# 우리가 보낸 값이 곧 현재값이다(카페24가 받아들였으므로). 응답에 담긴 값이 있으면
|
||||
# 그것을 우선한다.
|
||||
by_code: dict[str, dict[str, Any]] = {}
|
||||
for r in requests:
|
||||
by_code[r["variant_code"]] = {k: v for k, v in r.items() if k != "variant_code"}
|
||||
for r in results:
|
||||
code = str(r.get("variant_code") or "")
|
||||
if code in by_code:
|
||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
||||
if key in r and r[key] is not None:
|
||||
by_code[code][key] = r[key]
|
||||
st.save_write_snapshot(product_no, "variants", by_code)
|
||||
# 카페24가 받아들인 행만 현재값으로 기록한다. 응답에 담긴 값이 있으면 그것을 우선한다.
|
||||
sent = {r["variant_code"]: {k: v for k, v in r.items() if k != "variant_code"} for r in requests}
|
||||
by_code: dict[str, dict[str, Any]] = {}
|
||||
failed: dict[str, str] = {}
|
||||
unknown: dict[str, str] = {}
|
||||
for result in results:
|
||||
code = result["variant_code"]
|
||||
if result["status"] == products.VARIANT_OK:
|
||||
patch = dict(sent.get(code) or {})
|
||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
||||
value = (result.get("variant") or {}).get(key)
|
||||
if value is not None:
|
||||
patch[key] = value
|
||||
by_code[code] = patch
|
||||
elif result["status"] == products.VARIANT_UNKNOWN:
|
||||
unknown[code] = result["error"]
|
||||
else:
|
||||
failed[code] = result["error"]
|
||||
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
|
||||
|
||||
detail = "; ".join(
|
||||
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
|
||||
)
|
||||
st.log_audit(actor=actor, action="update_variants", product_no=product_no,
|
||||
result="SUCCESS", detail=detail[:900])
|
||||
logger.info("카페24 상품 %s 품목 %s건 수정 (%s)", product_no, len(by_code), actor)
|
||||
return {"ok": True, "updated": {code: _variant_view({"variant_code": code, **patch})
|
||||
for code, patch in by_code.items()}}
|
||||
if failed or unknown:
|
||||
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
||||
first = next(iter({**failed, **unknown}.values()), "")
|
||||
detail += f" / 오류: {first}"
|
||||
result_label = "SUCCESS" if not (failed or unknown) else ("PARTIAL" if by_code else "FAIL")
|
||||
writes.audit_safe(st, actor=actor, action="update_variants", product_no=product_no,
|
||||
result=result_label, detail=detail[:900])
|
||||
if not by_code:
|
||||
first = next(iter({**failed, **unknown}.values()), "알 수 없는 오류")
|
||||
note = " (일부는 반영됐을 수 있습니다 — 다시 불러와 확인하세요)" if unknown else ""
|
||||
logger.warning("카페24 상품 %s 품목 수정 실패: %s", product_no, first)
|
||||
raise HTTPException(status_code=502, detail=f"{first}{note}")
|
||||
logger.info("카페24 상품 %s 품목 %s건 수정 (%s, 실패 %s, 모름 %s)",
|
||||
product_no, len(by_code), actor, len(failed), len(unknown))
|
||||
return {
|
||||
"ok": not (failed or unknown),
|
||||
"partial": bool(failed or unknown),
|
||||
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
|
||||
"failed": failed,
|
||||
"unknown": unknown,
|
||||
"record_warning": record_error,
|
||||
}
|
||||
|
||||
@@ -50,10 +50,11 @@ PC/모바일은 구분하지 않는다 — 적용 시 `description` 만 쓰고
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
from typing import Any, Iterator
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
@@ -61,7 +62,7 @@ from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard, read_lag_grace_minutes, require_store
|
||||
|
||||
logger = logging.getLogger("cafe24.products")
|
||||
@@ -121,6 +122,16 @@ def _short_dt(value: Any) -> str:
|
||||
return text.replace("T", " ")[:16]
|
||||
|
||||
|
||||
def _iso(value: Any) -> str:
|
||||
"""datetime 이면 KST ISO, 아니면 문자열 그대로."""
|
||||
if hasattr(value, "astimezone"):
|
||||
from app.timezone import KST # noqa: WPS433
|
||||
|
||||
aware = value if value.tzinfo else value.replace(tzinfo=KST)
|
||||
return aware.astimezone(KST).isoformat(timespec="seconds")
|
||||
return str(value or "")
|
||||
|
||||
|
||||
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
||||
normalized = products.normalize_product(raw)
|
||||
@@ -187,30 +198,34 @@ def load_product(st: Any, api: Any, product_no: int) -> tuple[dict[str, Any], bo
|
||||
|
||||
|
||||
def resolve_description(
|
||||
st: Any, product_no: int, cafe24_html: str
|
||||
st: Any, product_no: int, cafe24_html: str, *, fetched_updated: object = None
|
||||
) -> tuple[str, str, dict[str, Any] | None]:
|
||||
"""(유효 HTML, 상태, 마지막 쓰기 revision). 상태는 store.SYNC_*."""
|
||||
grace = read_lag_grace_minutes()
|
||||
since = now_kst() - timedelta(minutes=grace)
|
||||
last_write = st.latest_write_revision(product_no, since=since)
|
||||
if not last_write:
|
||||
return cafe24_html, store.SYNC_NONE, None
|
||||
digests = st.revision_digests(product_no, since=since)
|
||||
effective, state = store.resolve_description(
|
||||
cafe24_html, last_write=last_write, known_digests=digests, grace_minutes=grace
|
||||
)
|
||||
return effective, state, last_write
|
||||
"""(유효 HTML, 상태, 마지막 확인된 쓰기). 상태는 store.SYNC_*.
|
||||
|
||||
근거는 원격 반영이 확인된 쓰기(cafe24_write_attempts)뿐이다 — writes.resolve_effective.
|
||||
"""
|
||||
return writes.resolve_effective(st, product_no, cafe24_html, fetched_updated=fetched_updated)
|
||||
|
||||
|
||||
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다."""
|
||||
info = products.normalize_product(updated) if updated else {}
|
||||
if info.get("product_no"):
|
||||
st.upsert_products([info])
|
||||
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다.
|
||||
|
||||
카페24에는 이미 반영된 뒤라 기록 실패로 예외를 내지 않는다(로그만 — writes 참고).
|
||||
"""
|
||||
info, _error = writes.remember_product_write(st, product_no, updated)
|
||||
return info
|
||||
|
||||
|
||||
@contextmanager
|
||||
def locked_json(st: Any, product_no: int, *, actor: str, purpose: str) -> Iterator[Any]:
|
||||
"""JSON API 용 상품 쓰기 잠금 — 못 잡으면 409, 스키마가 없으면 503."""
|
||||
try:
|
||||
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose=purpose) as lock:
|
||||
yield lock
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
|
||||
|
||||
|
||||
def _info(product: dict[str, Any]) -> dict[str, Any]:
|
||||
"""편집기·정보 패널 공용 상품 요약."""
|
||||
info = products.normalize_product(product) if product else {}
|
||||
@@ -245,11 +260,27 @@ def _editor_ctx(st: Any, product_no: int) -> dict[str, Any]:
|
||||
product, scalar_stale = load_product(st, api, product_no)
|
||||
desc = products.descriptions_from_product(product)
|
||||
st.upsert_products([products.normalize_product(product)])
|
||||
html_effective, sync_state, last_write = resolve_description(st, product_no, desc.description)
|
||||
html_effective, sync_state, last_write = resolve_description(
|
||||
st, product_no, desc.description, fetched_updated=product.get("updated_date")
|
||||
)
|
||||
except Cafe24Error as exc:
|
||||
error = str(exc)
|
||||
logger.warning("카페24 상품 %s 조회 실패: %s", product_no, exc)
|
||||
|
||||
# 반영 여부를 모르는 이전 시도 — 편집기 위에 확정 버튼과 함께 보여준다.
|
||||
# (REMOTE_OK 는 반영이 확인된 것이라 여기 올리지 않는다 — 기록은 자동 복구된다.)
|
||||
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||
open_attempts = [
|
||||
{**a, "label": writes.describe_attempt(a),
|
||||
"status_label": "결과 모름" if a.get("status") == store.ATTEMPT_UNKNOWN else "중단됨"}
|
||||
for a in st.open_attempts(product_no, since=since)
|
||||
if a.get("status") in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN)
|
||||
]
|
||||
revisions = [
|
||||
{**r, "type_label": store.REVISION_LABELS.get(str(r.get("revision_type") or ""), "")}
|
||||
for r in st.list_revisions(product_no, limit=20)
|
||||
]
|
||||
|
||||
return {
|
||||
"product_no": product_no,
|
||||
# 고객이 보는 상세페이지 주소 (CAFE24_SHOP_URL, 없으면 카페24 기본 도메인)
|
||||
@@ -268,9 +299,10 @@ def _editor_ctx(st: Any, product_no: int) -> dict[str, Any]:
|
||||
"sync_pending": sync_state == store.SYNC_PENDING,
|
||||
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
||||
"scalar_stale": scalar_stale,
|
||||
"last_write_at": _short_dt(last_write.get("created_at").isoformat() if last_write and last_write.get("created_at") else ""),
|
||||
"last_write_at": _short_dt(_iso(last_write.get("created_at")) if last_write else ""),
|
||||
"last_write_by": (last_write or {}).get("created_by") or "",
|
||||
"revisions": st.list_revisions(product_no, limit=20),
|
||||
"revisions": revisions,
|
||||
"open_attempts": open_attempts,
|
||||
"editor_error": error,
|
||||
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
||||
}
|
||||
@@ -384,33 +416,34 @@ def product_rename(
|
||||
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
||||
with locked_json(st, product_no, actor=actor, purpose="상품명 변경"):
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
||||
|
||||
before = str(current.get("product_name") or "")
|
||||
if before == name:
|
||||
return {"ok": True, "product_name": before, "changed": False}
|
||||
before = str(current.get("product_name") or "")
|
||||
if before == name:
|
||||
return {"ok": True, "product_name": before, "changed": False}
|
||||
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, product_name=name)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, product_name=name)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
info = remember_write(st, product_no, updated)
|
||||
info = remember_write(st, product_no, updated)
|
||||
after = str(info.get("product_name") or name)
|
||||
st.log_audit(
|
||||
actor=actor, action="rename_product", product_no=product_no,
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action="rename_product", product_no=product_no,
|
||||
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
||||
)
|
||||
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
||||
@@ -442,31 +475,32 @@ def product_status(
|
||||
want = bool(payload.get("value"))
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, **{field: want})
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
result="FAIL", detail=f"{want} 설정 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s %s 변경 실패: %s", product_no, field, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
# 응답이 상품 dict 면 그것이 곧 현재 상태다. 모양이 다르면(방어) 다시 조회한다.
|
||||
if "display" not in updated or "selling" not in updated:
|
||||
with locked_json(st, product_no, actor=actor, purpose="진열/판매 변경"):
|
||||
try:
|
||||
updated, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
||||
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
||||
updated = {}
|
||||
updated = products.update_product(api.client, product_no, **{field: want})
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
result="FAIL", detail=f"{want} 설정 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s %s 변경 실패: %s", product_no, field, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
info = remember_write(st, product_no, updated)
|
||||
# 응답이 상품 dict 면 그것이 곧 현재 상태다. 모양이 다르면(방어) 다시 조회한다.
|
||||
if "display" not in updated or "selling" not in updated:
|
||||
try:
|
||||
updated, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
||||
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
||||
updated = {}
|
||||
|
||||
info = remember_write(st, product_no, updated)
|
||||
state = {
|
||||
"display": bool(info.get("display", want if field == "display" else True)),
|
||||
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
||||
}
|
||||
st.log_audit(
|
||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
||||
)
|
||||
logger.info("카페24 상품 %s %s=%s (%s)", product_no, field, want, actor)
|
||||
@@ -479,6 +513,95 @@ def product_redirect(request: Request, product_no: int):
|
||||
return RedirectResponse(url=f"/cafe24/?selected={product_no}", status_code=303)
|
||||
|
||||
|
||||
def _back_url(product_no: int, list_query: str) -> str:
|
||||
"""적용 후 돌아갈 주소 — 검색·필터를 유지한 채 같은 상품이 선택된 화면."""
|
||||
base = f"/cafe24/?{list_query}" if list_query else f"/cafe24/?selected={product_no}"
|
||||
return base if f"selected={product_no}" in base else f"{base}&selected={product_no}"
|
||||
|
||||
|
||||
def _with_msg(back: str, *, msg: str = "", err: str = "") -> str:
|
||||
"""안내 문구를 쿼리에 붙인다. 문구 안의 &·#·% 가 주소를 깨지 않게 인코딩한다."""
|
||||
key, text = ("err", err) if err else ("msg", msg)
|
||||
return f"{back}&{key}={quote(text, safe='')}"
|
||||
|
||||
|
||||
def _run_description_write(
|
||||
st: Any,
|
||||
user: dict[str, Any],
|
||||
product_no: int,
|
||||
*,
|
||||
html: str,
|
||||
base_fingerprint: str,
|
||||
memo: str,
|
||||
list_query: str,
|
||||
origin: str,
|
||||
action: str,
|
||||
target_revision_id: int | None = None,
|
||||
) -> RedirectResponse:
|
||||
"""즉시 적용·버전 복원 공용 — writes.write_product 를 잠금 안에서 부르고 결과를 안내한다."""
|
||||
actor = str(user.get("email") or "")
|
||||
back = _back_url(product_no, list_query)
|
||||
verb = "복원" if origin == store.ORIGIN_ROLLBACK else "적용"
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
with writes.write_lock(
|
||||
st, writes.product_lock_key(product_no), actor=actor, purpose=f"상세설명 {verb}"
|
||||
) as lock:
|
||||
outcome = writes.write_product(
|
||||
st, api, product_no,
|
||||
lock=lock, origin=origin, actor=actor, html=html,
|
||||
base_fingerprint=base_fingerprint, target_revision_id=target_revision_id,
|
||||
memo=memo, skip_if_same=True,
|
||||
)
|
||||
except (writes.WriteSetupError, writes.WriteBusy, writes.WriteBlocked, writes.WriteConflict) as exc:
|
||||
detail = "충돌 — 편집 중 카페24 값이 변경됨" if isinstance(exc, writes.WriteConflict) else str(exc)
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=exc.backup_id or None, result="FAIL", detail=detail)
|
||||
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||
except writes.RemoteWriteUnknown as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=exc.backup_id or None, result="UNKNOWN",
|
||||
detail=f"시도 #{exc.attempt_id} 반영 여부 모름: {exc}")
|
||||
logger.warning("카페24 상품 %s %s 결과 모름(시도 #%s): %s", product_no, verb, exc.attempt_id, exc)
|
||||
return RedirectResponse(url=_with_msg(back, err=(
|
||||
f"카페24 응답을 받지 못해 {verb} 여부를 알 수 없습니다({exc}). 다시 {verb}하지 말고 "
|
||||
f"쇼핑몰에서 확인한 뒤 편집기 위 안내에서 결과를 확정하세요. "
|
||||
f"(직전 내용은 버전 {exc.backup_id} 로 보관됨)")), status_code=303)
|
||||
except writes.RemoteWriteFailed as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=exc.backup_id or None, result="FAIL", detail=str(exc))
|
||||
logger.warning("카페24 상품 %s %s 실패: %s", product_no, verb, exc)
|
||||
return RedirectResponse(url=_with_msg(back, err=(
|
||||
f"{verb}에 실패했습니다: {exc} (직전 내용은 버전 {exc.backup_id} 로 보관됨)")), status_code=303)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
return RedirectResponse(url=_with_msg(back, err=f"카페24 현재값을 읽지 못해 중단했습니다: {exc}"),
|
||||
status_code=303)
|
||||
|
||||
if not outcome.changed:
|
||||
return RedirectResponse(url=_with_msg(back, msg=f"변경된 내용이 없어 {verb}하지 않았습니다."), status_code=303)
|
||||
|
||||
detail = (
|
||||
f"{len(html)}자 {verb} (백업 {outcome.backup_id}, 시도 #{outcome.attempt_id}, 모바일 PC와 동일 유지, "
|
||||
f"카페24 재조회 {'확인' if outcome.confirmed else '지연 — 마지막 적용값 표시'})"
|
||||
)
|
||||
if target_revision_id:
|
||||
detail += f" / 원본 버전 {target_revision_id}"
|
||||
if outcome.record_error:
|
||||
detail += f" / 기록 실패(자동 복구 예정): {outcome.record_error}"
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=outcome.revision_id or None, result="SUCCESS", detail=detail)
|
||||
logger.info("카페24 상품 %s 상세설명 %s (%s, 재조회 확인=%s)", product_no, verb, actor, outcome.confirmed)
|
||||
note = "" if outcome.confirmed else " 카페24 관리자 API 반영은 잠시 늦을 수 있어 방금 적용한 내용을 표시합니다."
|
||||
if outcome.record_error:
|
||||
note += " ※ 카페24에는 반영됐지만 버전 기록 저장에 실패했습니다 — 자동으로 복구하니 다시 적용하지 마세요."
|
||||
return RedirectResponse(
|
||||
url=_with_msg(back, msg=f"카페24에 {verb}했습니다. 직전 내용은 버전 {outcome.backup_id} 로 보관됩니다.{note}"),
|
||||
status_code=303,
|
||||
)
|
||||
|
||||
|
||||
@products_router.post("/products/{product_no}/apply")
|
||||
def product_apply(
|
||||
request: Request,
|
||||
@@ -490,125 +613,165 @@ def product_apply(
|
||||
):
|
||||
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
||||
|
||||
순서를 지키는 것이 이 함수의 핵심이다.
|
||||
1) 카페24에서 **현재** HTML 을 다시 읽는다(로컬 값을 현재값으로 믿지 않는다)
|
||||
2) 읽기 지연을 판정해 **유효 현재값**을 정한다(예전 값을 돌려주는 중이면
|
||||
우리 마지막 쓰기가 현재값이다)
|
||||
3) 그 값으로 BACKUP 버전을 남긴다 ← 유일한 복구 수단
|
||||
4) 편집 시작 시점의 지문과 비교해 충돌이면 거부한다
|
||||
5) 쓰고, 스냅샷·MANUAL 버전·감사로그를 남긴다
|
||||
순서(writes.write_product): 상품 잠금 → 카페24 현재값 재조회(로컬 값을 현재값으로
|
||||
믿지 않는다) → 결과 모르는 이전 시도 확인 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||
← 유일한 복구 수단 → 지문 대조(충돌 거부) → 시도 기록 → PUT → 버전·스냅샷 기록.
|
||||
|
||||
PC/모바일을 구분하지 않는다 — 두 필드에 같은 HTML 을 쓴다. 분리 사용 상품의
|
||||
모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
||||
PC/모바일을 구분하지 않는다 — description 만 쓰고 separated_mobile_description="F".
|
||||
분리 사용 상품의 모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
||||
"""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
|
||||
actor = str(user.get("email") or "")
|
||||
# 적용 후에는 검색·필터를 유지한 채 같은 상품이 선택된 화면으로 돌아온다.
|
||||
base = f"/cafe24/?{list_query}" if list_query else f"/cafe24/?selected={product_no}"
|
||||
back = base if f"selected={product_no}" in base else f"{base}&selected={product_no}"
|
||||
|
||||
# 화면에서 보던 그대로(정리된 소스)를 카페24에 반영한다. 한글 이미지 경로는
|
||||
# 원래의 퍼센트 인코딩으로 되돌린다.
|
||||
submitted = store.format_html(store.encode_html_urls(html or ""))
|
||||
if not submitted.strip():
|
||||
return RedirectResponse(
|
||||
url=f"{back}&err=내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요.",
|
||||
url=_with_msg(_back_url(product_no, list_query),
|
||||
err="내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요."),
|
||||
status_code=303,
|
||||
)
|
||||
return _run_description_write(
|
||||
st, user, product_no,
|
||||
html=submitted, base_fingerprint=base_fingerprint, memo=memo, list_query=list_query,
|
||||
origin=store.ORIGIN_MANUAL, action="apply_description",
|
||||
)
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 버전 이력 — 원문 확인 · 선택 복원
|
||||
# 자동 복원(예약 종료 후 되돌리기)은 쓰지 않는다. 사람이 버전을 골라 누를 때만
|
||||
# 정상 쓰기 경로(잠금·백업·지문 대조·시도 기록)로 한 번 적용하고 ROLLBACK 을 남긴다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _revision_for(st: Any, product_no: int, revision_id: int) -> dict[str, Any]:
|
||||
"""이 쇼핑몰·이 상품의 버전만 돌려준다. 아니면 404(다른 상품 버전을 주소로 못 끌어온다)."""
|
||||
from app.integrations.cafe24 import load_config # noqa: WPS433
|
||||
|
||||
revision = st.get_revision(revision_id)
|
||||
if not revision or int(revision.get("product_no") or 0) != int(product_no):
|
||||
raise HTTPException(status_code=404, detail="이 상품의 버전을 찾을 수 없습니다.")
|
||||
mall = load_config().mall_id
|
||||
rev_mall = str(revision.get("mall_id") or "")
|
||||
# mall_id 가 빈 행은 005 이전 기록이다 — cafe24_db 는 쇼핑몰 1개 전용이라 같은 쇼핑몰로 본다.
|
||||
if rev_mall and mall and rev_mall != mall:
|
||||
raise HTTPException(status_code=404, detail="다른 쇼핑몰의 버전입니다.")
|
||||
if int(revision.get("shop_no") or 1) != 1:
|
||||
raise HTTPException(status_code=404, detail="다른 멀티쇼핑몰(shop_no)의 버전입니다.")
|
||||
return revision
|
||||
|
||||
|
||||
@products_router.get("/products/{product_no}/revisions/{revision_id}")
|
||||
def revision_detail(request: Request, product_no: int, revision_id: int) -> dict[str, Any]:
|
||||
"""버전 원문(JSON). 화면은 textContent 로만 넣는다(HTML 로 해석하지 않는다)."""
|
||||
st, _user = require_store(request)
|
||||
revision = _revision_for(st, product_no, revision_id)
|
||||
body = str(revision.get("html_content") or "")
|
||||
rtype = str(revision.get("revision_type") or "")
|
||||
return {
|
||||
"ok": True,
|
||||
"revision": {
|
||||
"id": revision.get("id"),
|
||||
"product_no": revision.get("product_no"),
|
||||
"revision_type": rtype,
|
||||
"type_label": store.REVISION_LABELS.get(rtype, rtype),
|
||||
"source": revision.get("source") or "",
|
||||
"created_at": revision.get("created_at") or "",
|
||||
"created_by": revision.get("created_by") or "",
|
||||
"memo": revision.get("memo") or "",
|
||||
"length": len(body),
|
||||
# 편집기와 같은 표시(이미지 경로의 %EC… 를 한글로). 복원은 저장된 원문 그대로 쓴다.
|
||||
"html": store.decode_html_urls(body),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@products_router.post("/products/{product_no}/revisions/{revision_id}/restore")
|
||||
def revision_restore(
|
||||
request: Request,
|
||||
product_no: int,
|
||||
revision_id: int,
|
||||
base_fingerprint: str = Form(""),
|
||||
memo: str = Form(""),
|
||||
list_query: str = Form(""),
|
||||
):
|
||||
"""고른 버전을 카페24에 다시 적용한다(ROLLBACK). 즉시 적용과 같은 경로·같은 보호."""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
back = _back_url(product_no, list_query)
|
||||
try:
|
||||
current = products.fetch_descriptions(api.client, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
return RedirectResponse(url=f"{back}&err=카페24 현재값을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
||||
|
||||
# 읽기 지연 판정 — 카페24가 아직 예전 값을 돌려주면 우리 마지막 쓰기가 현재값이다.
|
||||
effective, sync_state, _ = resolve_description(st, product_no, current.description)
|
||||
pending = sync_state == store.SYNC_PENDING
|
||||
|
||||
backup_id = st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=effective,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업" + (" (카페24 읽기 지연 — 마지막 적용값 기준)" if pending else ""),
|
||||
created_by=actor,
|
||||
)
|
||||
# 모바일 내용이 PC 와 달랐다면 그것도 따로 남긴다. 아래에서 모바일을 PC 와 같게
|
||||
# 덮어쓰므로, 백업하지 않으면 그 내용을 되찾을 방법이 없다.
|
||||
if current.mobile_description and current.mobile_description != current.description:
|
||||
st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=current.mobile_description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업 (모바일 — PC와 달랐던 내용)",
|
||||
created_by=actor,
|
||||
)
|
||||
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(effective):
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
revision_id=backup_id, result="FAIL", detail="충돌 — 편집 중 카페24 값이 변경됨",
|
||||
)
|
||||
revision = _revision_for(st, product_no, revision_id)
|
||||
except HTTPException as exc:
|
||||
return RedirectResponse(url=_with_msg(back, err=str(exc.detail)), status_code=303)
|
||||
body = str(revision.get("html_content") or "")
|
||||
if not body.strip():
|
||||
return RedirectResponse(url=_with_msg(back, err="내용이 빈 버전은 복원할 수 없습니다."), status_code=303)
|
||||
if not base_fingerprint:
|
||||
# 편집기가 본 현재값 없이 복원하면 그 사이 바뀐 내용을 모르고 덮는다.
|
||||
return RedirectResponse(
|
||||
url=f"{back}&err=편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
||||
status_code=303,
|
||||
url=_with_msg(back, err="편집기를 새로고침한 뒤 버전 이력에서 다시 복원하세요."), status_code=303
|
||||
)
|
||||
note = f"버전 {revision_id} 복원" + (f" — {memo.strip()}" if memo.strip() else "")
|
||||
return _run_description_write(
|
||||
st, user, product_no,
|
||||
html=body, base_fingerprint=base_fingerprint, memo=note, list_query=list_query,
|
||||
origin=store.ORIGIN_ROLLBACK, action="restore_revision", target_revision_id=int(revision_id),
|
||||
)
|
||||
|
||||
if submitted == effective:
|
||||
return RedirectResponse(url=f"{back}&msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 반영 여부를 모르는 시도 — 사람이 쇼핑몰을 확인하고 확정한다
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@products_router.post("/products/{product_no}/attempts/{attempt_id}/resolve")
|
||||
def attempt_resolve(
|
||||
request: Request,
|
||||
product_no: int,
|
||||
attempt_id: int,
|
||||
result: str = Form(""),
|
||||
list_query: str = Form(""),
|
||||
):
|
||||
"""applied = 반영됨(그 내용을 마지막 쓰기로 기록) / not_applied = 반영 안 됨(닫기).
|
||||
|
||||
예약에서 난 시도면 그 예약도 함께 완료/실패로 바꾼다. 다시 적용하는 것은 사람이
|
||||
편집기에서 한다(자동 재적용 없음).
|
||||
"""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
actor = str(user.get("email") or "")
|
||||
back = _back_url(product_no, list_query)
|
||||
if result not in ("applied", "not_applied"):
|
||||
return RedirectResponse(url=_with_msg(back, err="확정할 결과를 고르세요."), status_code=303)
|
||||
open_states = (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN)
|
||||
try:
|
||||
# mobile_description 은 보내지 않는다 — update_descriptions 가
|
||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제하고
|
||||
# 카페24가 모바일 값을 자동으로 맞춰준다(모바일도 항상 PC와 같다).
|
||||
updated = products.update_descriptions(api.client, product_no, description=submitted)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
revision_id=backup_id, result="FAIL", detail=str(exc),
|
||||
)
|
||||
logger.warning("카페24 상품 %s 적용 실패: %s", product_no, exc)
|
||||
return RedirectResponse(
|
||||
url=f"{back}&err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
||||
status_code=303,
|
||||
)
|
||||
|
||||
# PUT 응답은 쓰기 직후의 실제 값 — 스냅샷으로 남긴다(상품명·가격·updated_date 등).
|
||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
||||
|
||||
# MANUAL revision 을 **먼저** 남긴다. 이것이 "마지막 쓰기" 기준이 되어, 카페24 GET 이
|
||||
# 한동안 예전 값을 돌려줘도 편집기는 방금 적용한 내용을 보여준다.
|
||||
revision_id = st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=submitted,
|
||||
revision_type=store.REVISION_MANUAL,
|
||||
memo=memo,
|
||||
created_by=actor,
|
||||
)
|
||||
|
||||
# 카페24 관리자 API 는 쓰기 직후 몇 초간 이전 값을 돌려줄 때가 있다(쇼핑몰
|
||||
# 화면에는 바로 반영됨). 여기서 짧게 확인만 한다 — 확인이 안 돼도 화면은 위
|
||||
# MANUAL revision 을 기준으로 그리므로 문제없다.
|
||||
confirmed = products.wait_for_description(api.client, product_no, submitted)
|
||||
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
revision_id=revision_id, result="SUCCESS",
|
||||
detail=(
|
||||
f"{len(submitted)}자 적용 (백업 {backup_id}, 모바일 PC와 동일 유지, "
|
||||
f"카페24 재조회 {'확인' if confirmed else '지연 — 마지막 적용값 표시'})"
|
||||
),
|
||||
)
|
||||
logger.info("카페24 상품 %s 상세설명 적용 (%s, 재조회 확인=%s)", product_no, actor, confirmed)
|
||||
note = "" if confirmed else " 카페24 관리자 API 반영은 잠시 늦을 수 있어 방금 적용한 내용을 표시합니다."
|
||||
return RedirectResponse(
|
||||
url=f"{back}&msg=카페24에 적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{note}",
|
||||
status_code=303,
|
||||
)
|
||||
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="적용 결과 확정"):
|
||||
attempt = st.get_attempt(attempt_id)
|
||||
if (not attempt or int(attempt.get("product_no") or 0) != int(product_no)
|
||||
or attempt.get("status") not in open_states):
|
||||
return RedirectResponse(url=_with_msg(back, err="이미 확정됐거나 없는 시도입니다."), status_code=303)
|
||||
schedule_id = attempt.get("schedule_id")
|
||||
if result == "applied":
|
||||
st.update_attempt(attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by=actor, only_from=open_states)
|
||||
revision_id = writes.record_attempt(st, attempt)
|
||||
if schedule_id:
|
||||
st.review_schedule(int(schedule_id), status=store.STATUS_SUCCESS,
|
||||
note=f"{actor} 가 반영됨으로 확정", actor=actor, action="applied")
|
||||
text = f"시도 #{attempt_id} 를 반영됨으로 확정했습니다(버전 {revision_id})."
|
||||
else:
|
||||
st.update_attempt(attempt_id, status=store.ATTEMPT_ABANDONED, resolved_by=actor,
|
||||
only_from=open_states)
|
||||
if schedule_id:
|
||||
st.review_schedule(int(schedule_id), status=store.STATUS_FAILED,
|
||||
note=f"{actor} 가 반영 안 됨으로 확정", actor=actor, action="not_applied")
|
||||
text = f"시도 #{attempt_id} 를 반영 안 됨으로 확정했습니다. 필요하면 다시 적용하세요."
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||
writes.audit_safe(st, actor=actor, action=f"resolve_attempt:{result}", product_no=product_no,
|
||||
result="SUCCESS", detail=f"시도 #{attempt_id}")
|
||||
return RedirectResponse(url=_with_msg(back, msg=text), status_code=303)
|
||||
|
||||
@@ -22,9 +22,9 @@ import logging
|
||||
from fastapi import APIRouter, Form, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard
|
||||
from .routes_products import _no_store
|
||||
|
||||
@@ -55,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
||||
set_selling=row.get("set_selling"),
|
||||
),
|
||||
"editable": store.is_editable(row.get("status") or ""),
|
||||
"needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -65,6 +66,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
||||
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
||||
"rows": rows,
|
||||
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
|
||||
"review": sum(1 for r in rows if r["needs_review"]),
|
||||
"flash": request.query_params.get("msg", ""),
|
||||
"flash_error": request.query_params.get("err", ""),
|
||||
}
|
||||
@@ -114,6 +116,12 @@ def schedule_create(
|
||||
except ValueError as exc:
|
||||
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
||||
|
||||
# 예약은 worker 가 잠금·시도 기록(마이그레이션 005)으로 실행한다 — 없으면 등록도 받지 않는다.
|
||||
try:
|
||||
writes.require_schema(st)
|
||||
except writes.WriteSetupError as exc:
|
||||
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
||||
|
||||
revision_id: int | None = None
|
||||
if want_html:
|
||||
body = store.format_html(store.encode_html_urls(html or ""))
|
||||
@@ -127,6 +135,7 @@ def schedule_create(
|
||||
revision_type=store.REVISION_DRAFT,
|
||||
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
||||
created_by=actor,
|
||||
mall_id=load_config().mall_id,
|
||||
)
|
||||
|
||||
schedule_id = st.create_schedule(
|
||||
@@ -187,3 +196,51 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
|
||||
"display": normalized["display"],
|
||||
"selling": normalized["selling"],
|
||||
}
|
||||
|
||||
|
||||
# 확인 필요(NEEDS_REVIEW) 예약의 사람 확정 — 반영 여부를 모르는 채로 worker 가 멈춘 것.
|
||||
# applied = 쇼핑몰에 반영돼 있음(완료 + 버전 기록) / rerun = 다시 실행 / close = 실패로 종료.
|
||||
_REVIEW_ACTIONS = {
|
||||
"applied": (store.STATUS_SUCCESS, "반영됨으로 확정"),
|
||||
"rerun": (store.STATUS_PENDING, "다시 실행"),
|
||||
"close": (store.STATUS_FAILED, "실패로 종료"),
|
||||
}
|
||||
|
||||
|
||||
@schedules_router.post("/schedules/{schedule_id}/review")
|
||||
def schedule_review(request: Request, schedule_id: int, action: str = Form("")):
|
||||
"""확인 필요 예약을 확정한다. 자동으로 다시 실행하지 않는다 — 사람이 쇼핑몰을 보고 고른다."""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
actor = str(user.get("email") or "")
|
||||
if action not in _REVIEW_ACTIONS:
|
||||
return RedirectResponse(url="/cafe24/schedules?err=확정할 동작을 고르세요.", status_code=303)
|
||||
status, label = _REVIEW_ACTIONS[action]
|
||||
row = st.get_schedule(schedule_id)
|
||||
if not row or row.get("status") != store.STATUS_NEEDS_REVIEW:
|
||||
return RedirectResponse(
|
||||
url=f"/cafe24/schedules?err=예약 #{schedule_id} 은 확인 필요 상태가 아닙니다.", status_code=303
|
||||
)
|
||||
product_no = int(row.get("product_no") or 0)
|
||||
try:
|
||||
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="예약 결과 확정"):
|
||||
attempt = st.latest_attempt_for_schedule(schedule_id)
|
||||
open_attempt = attempt if attempt.get("status") in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN) else {}
|
||||
if action == "applied":
|
||||
if not open_attempt:
|
||||
return RedirectResponse(
|
||||
url=f"/cafe24/schedules?err=예약 #{schedule_id} 에는 확정할 적용 시도가 없습니다 — "
|
||||
"다시 실행하거나 실패로 종료하세요.",
|
||||
status_code=303,
|
||||
)
|
||||
st.update_attempt(int(open_attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by=actor,
|
||||
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||
writes.record_attempt(st, open_attempt)
|
||||
st.review_schedule(schedule_id, status=status, note=f"{actor} — {label}", actor=actor, action=action)
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
return RedirectResponse(url=f"/cafe24/schedules?err={exc}", status_code=303)
|
||||
logger.info("카페24 예약 #%s 확인 필요 → %s (%s)", schedule_id, label, actor)
|
||||
return RedirectResponse(url=f"/cafe24/schedules?msg=예약 #{schedule_id} — {label}", status_code=303)
|
||||
|
||||
+228
-2
@@ -6,6 +6,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import quote
|
||||
@@ -44,6 +45,9 @@ STATUS_PROCESSING = "PROCESSING"
|
||||
STATUS_SUCCESS = "SUCCESS"
|
||||
STATUS_FAILED = "FAILED"
|
||||
STATUS_CANCELLED = "CANCELLED"
|
||||
# 원격 반영 여부를 모른다(네트워크 끊김·worker 중단) — 사람이 카페24를 보고 확정한다.
|
||||
# 자동으로 PENDING 에 돌려 재적용하지 않는다(마이그레이션 005).
|
||||
STATUS_NEEDS_REVIEW = "NEEDS_REVIEW"
|
||||
|
||||
SCHEDULE_STATUSES: tuple[str, ...] = (
|
||||
STATUS_PENDING,
|
||||
@@ -51,6 +55,7 @@ SCHEDULE_STATUSES: tuple[str, ...] = (
|
||||
STATUS_SUCCESS,
|
||||
STATUS_FAILED,
|
||||
STATUS_CANCELLED,
|
||||
STATUS_NEEDS_REVIEW,
|
||||
)
|
||||
|
||||
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
||||
@@ -59,8 +64,36 @@ SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
||||
STATUS_SUCCESS: "완료",
|
||||
STATUS_FAILED: "실패",
|
||||
STATUS_CANCELLED: "취소",
|
||||
STATUS_NEEDS_REVIEW: "확인 필요",
|
||||
}
|
||||
|
||||
# ── 쓰기 시도 상태 (cafe24_write_attempts.status, 마이그레이션 005) ──
|
||||
ATTEMPT_STARTED = "STARTED" # PUT 직전 기록. 이대로 남으면 결과를 모른다.
|
||||
ATTEMPT_REMOTE_OK = "REMOTE_OK" # 카페24 반영 성공, 로컬 버전 기록 전(기록 복구 필요)
|
||||
ATTEMPT_RECORDED = "RECORDED" # 반영 성공 + 버전 기록 완료
|
||||
ATTEMPT_REMOTE_FAILED = "REMOTE_FAILED" # 카페24가 거절 — 반영되지 않은 것이 확실
|
||||
ATTEMPT_UNKNOWN = "UNKNOWN" # 반영 여부 모름 → 사람 확인
|
||||
ATTEMPT_ABANDONED = "ABANDONED" # 사람이 "반영 안 됨"으로 확정 / 재실행으로 대체
|
||||
# 원격 반영이 확인된 시도 — 읽기 지연 판정의 근거는 이것뿐이다.
|
||||
ATTEMPT_CONFIRMED: tuple[str, ...] = (ATTEMPT_REMOTE_OK, ATTEMPT_RECORDED)
|
||||
# 결과 확정이 필요한 시도 — 이것이 남아 있으면 같은 상품 상세설명을 다시 쓰지 않는다.
|
||||
ATTEMPT_OPEN: tuple[str, ...] = (ATTEMPT_STARTED, ATTEMPT_REMOTE_OK, ATTEMPT_UNKNOWN)
|
||||
|
||||
ORIGIN_MANUAL = "MANUAL"
|
||||
ORIGIN_SCHEDULED = "SCHEDULED"
|
||||
ORIGIN_ROLLBACK = "ROLLBACK"
|
||||
# 시도 출처 → 성공 시 남길 버전 종류
|
||||
ORIGIN_REVISION_TYPE: dict[str, str] = {
|
||||
ORIGIN_MANUAL: "MANUAL",
|
||||
ORIGIN_SCHEDULED: "SCHEDULED",
|
||||
ORIGIN_ROLLBACK: "ROLLBACK",
|
||||
}
|
||||
|
||||
# ── BACKUP 출처 (cafe24_product_revisions.source) ──
|
||||
SOURCE_OBSERVED = "OBSERVED" # 카페24 GET 으로 읽은 값 그대로
|
||||
SOURCE_LAST_WRITE = "LAST_WRITE" # 카페24가 읽기 지연 중 — 우리 마지막(확인된) 쓰기를 현재값으로 봄
|
||||
SOURCE_REVISION = "REVISION" # ROLLBACK — 과거 버전을 그대로 다시 올림
|
||||
|
||||
# 사용자가 손댈 수 있는 상태 — PROCESSING/SUCCESS 는 임의 변경 금지
|
||||
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
||||
|
||||
@@ -509,11 +542,20 @@ def resolve_description(
|
||||
known_digests: set[str] | frozenset[str],
|
||||
grace_minutes: int,
|
||||
now: datetime | None = None,
|
||||
fetched_updated: object = None,
|
||||
) -> tuple[str, str]:
|
||||
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
||||
|
||||
last_write: 최근 쓰기 revision — {"html_content", "created_at"}.
|
||||
known_digests: 유예시간 안의 revision 들의 내용 해시(`content_digest()` 결과) 집합.
|
||||
last_write: **원격 반영이 확인된** 마지막 쓰기 — {"html_content", "created_at",
|
||||
"remote_updated_at"(선택: 그 PUT 응답의 updated_date)}.
|
||||
known_digests: 확인된 쓰기들이 **덮어쓴 값**(쓰기 직전 관측값·기준값)과 쓴 값의
|
||||
내용 해시(`content_digest()`) 집합. 충돌로 거절된 적용의 백업, 예약 초안처럼
|
||||
카페24에 올라간 적 없는 값은 넣지 않는다 — 넣으면 관리자에서 직접 고친 값이
|
||||
우연히 그와 같을 때 "읽기 지연"으로 오판해 그 수정을 덮어쓴다.
|
||||
fetched_updated: 이번 GET 의 updated_date. 마지막 쓰기의 PUT 응답 updated_date 보다
|
||||
**뒤**라면 GET 은 우리 쓰기 이후의 레코드다 — 지연이 아니므로 카페24 값을 믿는다
|
||||
(관리자가 우리 적용 뒤 예전 값으로 되돌린 경우를 구분한다). 같거나 판단할 수
|
||||
없으면 내용 해시로 판정한다.
|
||||
"""
|
||||
if not last_write:
|
||||
return cafe24_html, SYNC_NONE
|
||||
@@ -523,11 +565,29 @@ def resolve_description(
|
||||
last_html = str(last_write.get("html_content") or "")
|
||||
if cafe24_html == last_html:
|
||||
return cafe24_html, SYNC_SYNCED
|
||||
fetched_at = _as_aware(fetched_updated)
|
||||
written_at = _as_aware(last_write.get("remote_updated_at"))
|
||||
if fetched_at is not None and written_at is not None and fetched_at > written_at:
|
||||
return cafe24_html, SYNC_EXTERNAL
|
||||
if content_digest(cafe24_html) in known_digests:
|
||||
return last_html, SYNC_PENDING
|
||||
return cafe24_html, SYNC_EXTERNAL
|
||||
|
||||
|
||||
def lineage_digests(lineage: list[dict]) -> set[str]:
|
||||
"""확인된 쓰기 목록 → 읽기 지연 판정에 쓸 내용 해시 집합.
|
||||
|
||||
각 쓰기의 직전 관측값(observed)·기준값(base)·쓴 값(target). 빈 해시는 뺀다.
|
||||
"""
|
||||
out: set[str] = set()
|
||||
for item in lineage or []:
|
||||
for key in ("observed_digest", "base_digest", "target_digest"):
|
||||
value = str(item.get(key) or "")
|
||||
if value:
|
||||
out.add(value)
|
||||
return out
|
||||
|
||||
|
||||
def content_digest(html: str) -> str:
|
||||
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
||||
|
||||
@@ -598,6 +658,172 @@ def overlay_recent_write(
|
||||
return merged, True
|
||||
|
||||
|
||||
# ── 품목 스냅샷: 코드별 · 필드별 병합 ──
|
||||
# 스냅샷 모양: {variant_code: {필드: 값, ..., "_at": ISO, "_deleted": bool,
|
||||
# "options": [{name,value}...], "_options_before": [...]}}
|
||||
def merge_variant_snapshot(current: dict | None, patch: dict | None, *, at: str, replace: bool = False) -> dict:
|
||||
"""품목 스냅샷 병합.
|
||||
|
||||
- 같은 품목의 이전 필드는 유지하고 새로 쓴 필드만 덮는다. (예전에는 품목 단위로
|
||||
통째로 바꿔서, 자체코드를 고친 뒤 진열만 바꾸면 자체코드 기록이 사라졌다.)
|
||||
- replace=True 는 전체 초기화(옵션 삭제·재생성) — 이전 품목 기록을 모두 버린다.
|
||||
빈 patch({}) 를 "초기화" 로 해석하지 않는다(병합에서 {} 는 아무것도 안 바꾼다).
|
||||
- 삭제 표식(_deleted)은 한 번 붙으면 유지한다. 삭제 뒤에 늦게 도착한 수정이
|
||||
그 품목을 되살리지 않게 한다.
|
||||
- 품목마다 기록 시각(_at)을 남겨 유예시간을 품목별로 판정한다.
|
||||
"""
|
||||
base: dict = {} if replace else {
|
||||
str(code): dict(fields) for code, fields in (current or {}).items() if isinstance(fields, dict)
|
||||
}
|
||||
for code, fields in (patch or {}).items():
|
||||
if not isinstance(fields, dict):
|
||||
continue
|
||||
code = str(code)
|
||||
entry = base.get(code, {})
|
||||
if entry.get("_deleted") and not fields.get("_deleted"):
|
||||
continue # 삭제된 품목에 대한 늦은 수정 — 되살리지 않는다
|
||||
if fields.get("_deleted"):
|
||||
base[code] = {"_deleted": True, "_at": at}
|
||||
continue
|
||||
entry.update(fields)
|
||||
entry["_at"] = at
|
||||
base[code] = entry
|
||||
return base
|
||||
|
||||
|
||||
def _labels(options: object) -> list[tuple[str, str]]:
|
||||
if not isinstance(options, list):
|
||||
return []
|
||||
return [
|
||||
(str(o.get("name") or ""), str(o.get("value") or ""))
|
||||
for o in options if isinstance(o, dict)
|
||||
]
|
||||
|
||||
|
||||
def apply_variant_patch(
|
||||
variant: dict,
|
||||
patch: dict | None,
|
||||
*,
|
||||
section_written_at: object,
|
||||
grace_minutes: int,
|
||||
now: datetime | None = None,
|
||||
) -> dict | None:
|
||||
"""GET 품목 1건에 우리 쓰기 기록을 덮어씌운다. 삭제한 품목이면 None.
|
||||
|
||||
옵션 표기(options)는 **품목코드**(안정 식별자)로 짝지은 기록이다. 옵션값 이름을
|
||||
바꾼 직후 GET 품목이 아직 예전 이름을 돌려주면(읽기 지연) 이름으로는 짝이 안 맞아
|
||||
정상 품목이 "품목 없는 옵션값"으로 보였다. 그래서
|
||||
- GET 표기가 쓰기 직전 표기들(_options_before) 중 하나 → 지연 → 우리가 쓴 표기로
|
||||
- GET 표기 == 우리가 쓴 표기 → 이미 따라잡음
|
||||
- 둘 다 아님 → 관리자에서 다시 고침 → GET 을 믿는다
|
||||
_options_before 는 유예시간 안에 연달아 바꾼 이전 표기를 모두 담은 목록이다
|
||||
(A→B→C 직후 GET 이 A 를 돌려줘도 지연으로 본다).
|
||||
"""
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
return variant
|
||||
at = patch.get("_at") or section_written_at
|
||||
if not within_grace(at, grace_minutes=grace_minutes, now=now):
|
||||
return variant
|
||||
if patch.get("_deleted"):
|
||||
return None
|
||||
out = dict(variant)
|
||||
for key, value in patch.items():
|
||||
if key.startswith("_") or key == "options":
|
||||
continue
|
||||
out[key] = value
|
||||
if "options" in patch:
|
||||
current = _labels(variant.get("options"))
|
||||
wanted = _labels(patch.get("options"))
|
||||
befores = label_history(patch.get("_options_before"))
|
||||
if current != wanted and (patch.get("_options_before") is None or current in befores):
|
||||
out["options"] = [{"name": n, "value": v} for n, v in wanted]
|
||||
return out
|
||||
|
||||
|
||||
def label_history(raw: object) -> list[list[tuple[str, str]]]:
|
||||
"""_options_before → 표기 목록의 목록. 옛 모양(표기 하나 = dict 목록)도 받는다."""
|
||||
if not isinstance(raw, list) or not raw:
|
||||
return []
|
||||
if all(isinstance(item, dict) for item in raw):
|
||||
return [_labels(raw)]
|
||||
return [_labels(item) for item in raw if isinstance(item, list)]
|
||||
|
||||
|
||||
def labels_as_json(options: object) -> list[dict]:
|
||||
"""표기(options) → 스냅샷 저장 모양 [{name, value}]."""
|
||||
return [{"name": n, "value": v} for n, v in _labels(options)]
|
||||
|
||||
|
||||
# ── 옵션 스냅샷: 쓰기 직전 모양과 비교해 지연/외부 변경을 가린다 ──
|
||||
def options_signature(option: object) -> str:
|
||||
"""옵션 dict 의 비교용 서명 — 옵션 사용 여부, 옵션명·표시방식, 옵션값 이름·이미지."""
|
||||
if not isinstance(option, dict):
|
||||
return ""
|
||||
raw = option.get("has_option")
|
||||
has = raw is True or str(raw or "").strip().upper() in ("T", "TRUE", "1", "Y")
|
||||
groups = []
|
||||
if has:
|
||||
for o in option.get("options") or []:
|
||||
if not isinstance(o, dict):
|
||||
continue
|
||||
values = [
|
||||
[str(v.get("option_text") or ""), str(v.get("option_image_file") or ""),
|
||||
str(v.get("option_link_image") or "")]
|
||||
for v in (o.get("option_value") or []) if isinstance(v, dict)
|
||||
]
|
||||
groups.append([str(o.get("option_name") or ""), str(o.get("option_display_type") or ""), values])
|
||||
return json.dumps([has, groups], ensure_ascii=False, sort_keys=True)
|
||||
|
||||
|
||||
def overlay_options(
|
||||
fetched: dict,
|
||||
*,
|
||||
snapshot: dict | None,
|
||||
written_at: object,
|
||||
grace_minutes: int,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[dict, bool]:
|
||||
"""(보여줄 옵션 dict, 지연 여부). 스냅샷에 `_before_signatures`(쓰기 직전 모양들의
|
||||
서명 — 유예시간 안에 연달아 바꾼 이전 모양 포함)가 있으면 GET 이 그중 하나일 때만
|
||||
지연으로 본다 — 관리자에서 다시 고친 옵션을 유예시간 동안 덮지 않게.
|
||||
서명 목록이 없는 옛 스냅샷은 예전처럼 유예시간 안이면 스냅샷을 쓴다."""
|
||||
if not isinstance(snapshot, dict) or not snapshot:
|
||||
return fetched, False
|
||||
if not within_grace(written_at, grace_minutes=grace_minutes, now=now):
|
||||
return fetched, False
|
||||
got = options_signature(fetched)
|
||||
if got == options_signature(snapshot):
|
||||
return fetched, False
|
||||
befores = snapshot.get("_before_signatures")
|
||||
if isinstance(befores, list) and got not in befores:
|
||||
return fetched, False
|
||||
return snapshot, True
|
||||
|
||||
|
||||
# ── 예약 worker 가 lease 만료된 PROCESSING 을 복구할 때의 판정 ──
|
||||
RECOVER_SUCCESS = "SUCCESS" # 이미 반영·기록됨
|
||||
RECOVER_RECORD = "RECORD" # 반영됨 — 버전 기록만 채우고 SUCCESS
|
||||
RECOVER_RETRY = "RETRY" # 반영 안 됨이 확실 — 재시도 예산 안에서 다시 대기
|
||||
RECOVER_FAIL = "FAIL" # 반영 안 됨 + 재시도 예산 소진
|
||||
RECOVER_REVIEW = "REVIEW" # 반영 여부 모름 — NEEDS_REVIEW (자동 재적용 금지)
|
||||
|
||||
|
||||
def recovery_decision(attempt: dict | None, retry_count: object) -> tuple[str, str]:
|
||||
"""(판정, 사람이 읽을 사유). attempt 는 그 예약의 가장 최근 쓰기 시도(없으면 None)."""
|
||||
if not attempt:
|
||||
note = "worker 가 카페24에 쓰기 전에 중단되었습니다"
|
||||
return (RECOVER_RETRY if can_retry(retry_count) else RECOVER_FAIL), note
|
||||
status = str(attempt.get("status") or "")
|
||||
if status == ATTEMPT_RECORDED:
|
||||
return RECOVER_SUCCESS, "카페24 반영·기록이 끝난 뒤 중단되었습니다"
|
||||
if status == ATTEMPT_REMOTE_OK:
|
||||
return RECOVER_RECORD, "카페24에는 반영됐고 로컬 기록 전에 중단되었습니다"
|
||||
if status in (ATTEMPT_REMOTE_FAILED, ATTEMPT_ABANDONED):
|
||||
note = "카페24가 요청을 반영하지 않았습니다"
|
||||
return (RECOVER_RETRY if can_retry(retry_count) else RECOVER_FAIL), note
|
||||
return RECOVER_REVIEW, "카페24에 쓰는 도중 중단되어 반영 여부를 알 수 없습니다 — 쇼핑몰에서 확인하세요"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 기본 정보(상품명·가격) 입력 검증 — 오른쪽 정보 패널
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -14,6 +14,33 @@
|
||||
{# 읽기 지연 배너 — 카페24 관리자 API 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
||||
적용한 내용(MANUAL/SCHEDULED revision)을 편집기에 보여준다. 쇼핑몰 화면에는 이미
|
||||
반영돼 있다(실물 관찰). 지문도 이 값으로 만들어 다음 적용이 충돌로 오판되지 않는다. #}
|
||||
{# 반영 여부를 모르는 이전 적용 — 네트워크가 끊겼거나 처리 도중 멈춘 것. 확정 전에는 이 상품
|
||||
상세설명을 다시 쓰지 않는다(재적용 금지). 쇼핑몰을 보고 사람이 결과를 고른다.
|
||||
카페24 값이 그 적용 내용과 같아지면 다음 적용 때 자동으로 "반영됨"이 된다. #}
|
||||
{% for att in open_attempts or [] %}
|
||||
<div class="cf24-flash cf24-flash-err cf24-attempt" data-attempt-id="{{ att.id }}">
|
||||
<strong>적용 결과 확인 필요</strong> — {{ att.label }} · {{ att.status_label }}{% if att.error %} ({{ att.error }}){% endif %}.
|
||||
쇼핑몰 상세페이지를 열어 이 적용이 반영됐는지 확인한 뒤 고르세요. 확정하기 전에는 이 상품 상세설명을 다시 적용할 수 없습니다.
|
||||
<span class="cf24-attempt-actions">
|
||||
<form method="post" action="/cafe24/products/{{ product_no }}/attempts/{{ att.id }}/resolve" style="display:inline;"
|
||||
data-erp-confirm="쇼핑몰에서 이 적용 내용이 보이는 것을 확인했나요? 반영됨으로 기록합니다.">
|
||||
<input type="hidden" name="result" value="applied" />
|
||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline cf24-btn-inline">반영됨</button>
|
||||
</form>
|
||||
<form method="post" action="/cafe24/products/{{ product_no }}/attempts/{{ att.id }}/resolve" style="display:inline;"
|
||||
data-erp-confirm="이 적용이 쇼핑몰에 반영되지 않은 것을 확인했나요? 반영 안 됨으로 닫습니다(다시 적용은 직접 하세요).">
|
||||
<input type="hidden" name="result" value="not_applied" />
|
||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline cf24-btn-inline">반영 안 됨</button>
|
||||
</form>
|
||||
</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
{# 적용·예약이 오류로 돌아왔을 때 브라우저에 남겨 둔 편집본을 여기서 되살린다(products.html JS). #}
|
||||
<div id="cf24-draft-slot"></div>
|
||||
|
||||
{% if sync_pending %}
|
||||
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
||||
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
||||
@@ -199,28 +226,40 @@
|
||||
</form>
|
||||
</details>
|
||||
|
||||
<details class="cf24-details">
|
||||
<details class="cf24-details" id="cf24-history">
|
||||
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
||||
{% if revisions %}
|
||||
<div class="cf24-scroll">
|
||||
<table class="erp-table cf24-compact">
|
||||
<thead>
|
||||
<tr><th>시각</th><th>유형</th><th>길이</th><th>작업자</th><th>메모</th></tr>
|
||||
<tr><th>시각</th><th>유형</th><th>길이</th><th>작업자</th><th>메모</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for rev in revisions %}
|
||||
<tr>
|
||||
<td class="cf24-nowrap">{{ rev.created_at }}</td>
|
||||
<td class="cf24-nowrap"><code>{{ rev.revision_type }}</code></td>
|
||||
<td class="cf24-nowrap" title="{{ rev.type_label }}">
|
||||
<code>{{ rev.revision_type }}</code>
|
||||
{% if rev.source == 'LAST_WRITE' %}<span class="cf24-muted" title="카페24가 읽기 지연 중이라 마지막으로 확인된 적용값을 백업했습니다">지연</span>{% endif %}
|
||||
</td>
|
||||
<td class="cf24-nowrap">{{ rev.html_length }}자</td>
|
||||
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
||||
<td>{{ rev.memo or '' }}</td>
|
||||
<td class="cf24-nowrap">
|
||||
{% if rev.html_length %}
|
||||
<button type="button" class="erp-btn erp-btn-outline cf24-btn-inline" data-rev-view="{{ rev.id }}">원문</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="cf24-muted">버전 선택 복원은 Phase 6 에서 붙습니다. 내용은 모두 보관됩니다.</p>
|
||||
<p class="cf24-muted">
|
||||
「원문」에서 그 버전의 소스를 확인·복사하고, 필요하면 「이 버전으로 복원」으로 카페24에 다시 적용합니다.
|
||||
복원도 적용과 같은 순서(현재값 재조회 → 직전 내용 자동 백업 → 편집 중 변경 확인)를 거치며 이력에
|
||||
<code>ROLLBACK</code> 으로 남습니다. 자동 복원(예약 종료 후 되돌리기)은 쓰지 않습니다.
|
||||
</p>
|
||||
{% else %}
|
||||
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
||||
{% endif %}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<div class="erp-card cf24-card">
|
||||
<div class="cf24-card-head">
|
||||
<h3>예약 목록</h3>
|
||||
<span class="cf24-muted">대기 {{ pending }}건 · 최근 200건</span>
|
||||
<span class="cf24-muted">대기 {{ pending }}건{% if review %} · <strong class="cf24-err">확인 필요 {{ review }}건</strong>{% endif %} · 최근 200건</span>
|
||||
</div>
|
||||
|
||||
<p class="cf24-note">
|
||||
@@ -22,6 +22,11 @@
|
||||
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
||||
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
||||
</p>
|
||||
<p class="cf24-note">
|
||||
<strong>확인 필요</strong> — 카페24에 쓰는 도중 응답이 끊겼거나 worker 가 멈춰 반영 여부를 알 수 없는 예약입니다.
|
||||
자동으로 다시 실행하지 않습니다. 쇼핑몰에서 상세페이지·진열/판매를 확인한 뒤
|
||||
「반영됨」(완료로 기록) · 「다시 실행」 · 「실패로 종료」 중 하나를 고르세요.
|
||||
</p>
|
||||
|
||||
{% if rows %}
|
||||
<div class="cf24-scroll">
|
||||
@@ -53,12 +58,13 @@
|
||||
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
|
||||
{% elif r.status == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
|
||||
{% elif r.status == 'PENDING' %}<span class="cf24-warn">{{ r.status_label }}</span>
|
||||
{% elif r.status == 'NEEDS_REVIEW' %}<span class="erp-badge cf24-badge-off">{{ r.status_label }}</span>
|
||||
{% else %}<span class="cf24-muted">{{ r.status_label }}</span>{% endif %}
|
||||
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{{ r.memo or '' }}
|
||||
{% if r.last_error %}<div class="cf24-err">{{ r.last_error }}</div>{% endif %}
|
||||
{% if r.last_error %}<div class="{{ 'cf24-muted' if r.status == 'SUCCESS' else 'cf24-err' }}">{{ r.last_error }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
||||
<td class="cf24-nowrap">
|
||||
@@ -67,6 +73,22 @@
|
||||
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
||||
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
||||
</form>
|
||||
{% elif r.needs_review %}
|
||||
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||
data-erp-confirm="쇼핑몰에서 반영된 것을 확인했나요? 예약 #{{ r.id }} 을 완료로 기록합니다.">
|
||||
<input type="hidden" name="action" value="applied" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">반영됨</button>
|
||||
</form>
|
||||
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||
data-erp-confirm="예약 #{{ r.id }} 을 다시 실행합니다. 이미 반영돼 있었다면 같은 내용을 한 번 더 적용합니다. 계속할까요?">
|
||||
<input type="hidden" name="action" value="rerun" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">다시 실행</button>
|
||||
</form>
|
||||
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||
data-erp-confirm="예약 #{{ r.id }} 을 실패로 종료할까요?">
|
||||
<input type="hidden" name="action" value="close" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">실패로 종료</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
"""카페24 모듈 단위 테스트용 대역 — 메모리 저장소 · 가짜 카페24 · 가짜 FTP.
|
||||
|
||||
실제 DB 의 동작(잠금 만료, SKIP LOCKED, JSONB 병합 등)은 이 대역으로 증명되지 않는다.
|
||||
그 부분은 test_cafe24_db.py(격리된 로컬 PostgreSQL)가 검증한다. 여기서는 쓰기 순서와
|
||||
분기(백업·충돌·결과 분류·복구 판정)를 빠르게 확인한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import ftplib
|
||||
import itertools
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.integrations.cafe24.errors import Cafe24ApiError
|
||||
from app.modules.cafe24 import store
|
||||
from app.timezone import KST, now_kst
|
||||
|
||||
|
||||
class MemoryStore:
|
||||
"""Cafe24Store 가 writes/worker/라우터에 주는 메서드를 메모리로 흉내낸다."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._ids = itertools.count(1)
|
||||
self.revisions: dict[int, dict[str, Any]] = {}
|
||||
self.attempts: dict[int, dict[str, Any]] = {}
|
||||
self.locks: dict[str, dict[str, Any]] = {}
|
||||
self.schedules: dict[int, dict[str, Any]] = {}
|
||||
self.snapshots: dict[int, dict[str, Any]] = {}
|
||||
self.audits: list[dict[str, Any]] = []
|
||||
self.products: dict[int, dict[str, Any]] = {}
|
||||
self.fail_on: set[str] = set() # 이 메서드 이름이 들어 있으면 예외(기록 실패 재현)
|
||||
self.schema_ok = True
|
||||
|
||||
def _maybe_fail(self, name: str) -> None:
|
||||
if name in self.fail_on:
|
||||
raise RuntimeError(f"DB 장애({name})")
|
||||
|
||||
# ── 스키마 ──
|
||||
def write_schema_ready(self) -> bool:
|
||||
return self.schema_ok
|
||||
|
||||
# ── 잠금 ──
|
||||
def acquire_lock(self, key, *, owner, purpose, ttl_seconds):
|
||||
now = now_kst()
|
||||
held = self.locks.get(key)
|
||||
if held and held["expires_at"] > now:
|
||||
return None
|
||||
token = uuid.uuid4().hex
|
||||
self.locks[key] = {"owner": owner, "purpose": purpose, "token": token,
|
||||
"expires_at": now + timedelta(seconds=ttl_seconds)}
|
||||
return token
|
||||
|
||||
def renew_lock(self, key, token, *, ttl_seconds):
|
||||
held = self.locks.get(key)
|
||||
if not held or held["token"] != token or held["expires_at"] <= now_kst():
|
||||
return False
|
||||
held["expires_at"] = now_kst() + timedelta(seconds=ttl_seconds)
|
||||
return True
|
||||
|
||||
def release_lock(self, key, token):
|
||||
if self.locks.get(key, {}).get("token") == token:
|
||||
del self.locks[key]
|
||||
|
||||
def lock_holder(self, key):
|
||||
held = self.locks.get(key)
|
||||
return dict(held) if held and held["expires_at"] > now_kst() else {}
|
||||
|
||||
def expire_lock(self, key):
|
||||
if key in self.locks:
|
||||
self.locks[key]["expires_at"] = now_kst() - timedelta(seconds=1)
|
||||
|
||||
# ── 버전 ──
|
||||
def add_revision(self, *, product_no, html_content, revision_type, memo="", created_by="",
|
||||
mall_id="", shop_no=1, source="", source_revision_id=None):
|
||||
self._maybe_fail("add_revision")
|
||||
rid = next(self._ids)
|
||||
self.revisions[rid] = {
|
||||
"id": rid, "product_no": int(product_no), "html_content": html_content or "",
|
||||
"revision_type": store.normalize_revision_type(revision_type), "memo": memo,
|
||||
"created_by": created_by, "mall_id": mall_id, "shop_no": shop_no, "source": source,
|
||||
"source_revision_id": source_revision_id, "created_at": now_kst().isoformat(),
|
||||
}
|
||||
return rid
|
||||
|
||||
def get_revision(self, revision_id):
|
||||
return dict(self.revisions.get(int(revision_id), {}))
|
||||
|
||||
def list_revisions(self, product_no, *, limit=20):
|
||||
rows = [dict(r, html_length=len(r["html_content"])) for r in self.revisions.values()
|
||||
if r["product_no"] == int(product_no)]
|
||||
return sorted(rows, key=lambda r: -r["id"])[:limit]
|
||||
|
||||
def of_type(self, revision_type):
|
||||
return [r for r in self.revisions.values() if r["revision_type"] == revision_type]
|
||||
|
||||
# ── 쓰기 시도 ──
|
||||
def start_attempt(self, **fields):
|
||||
self._maybe_fail("start_attempt")
|
||||
aid = next(self._ids)
|
||||
row = {"id": aid, "status": store.ATTEMPT_STARTED, "error": "", "remote_updated_at": "",
|
||||
"remote_at": None, "resolved_by": "", "applied_revision_id": None,
|
||||
"created_at": now_kst(), "target_html": "", "target_revision_id": None,
|
||||
"observed_digest": "", "base_digest": "", "target_digest": "", "schedule_id": None,
|
||||
"set_display": None, "set_selling": None, "memo": "", "actor": "", "origin": "MANUAL"}
|
||||
row.update(fields)
|
||||
self.attempts[aid] = row
|
||||
return aid
|
||||
|
||||
def update_attempt(self, attempt_id, *, status=None, error=None, remote_updated_at=None,
|
||||
remote_ok=False, resolved_by=None, only_from=None):
|
||||
self._maybe_fail("update_attempt")
|
||||
row = self.attempts.get(int(attempt_id))
|
||||
if not row or (only_from and row["status"] not in only_from):
|
||||
return False
|
||||
if status is not None:
|
||||
row["status"] = status
|
||||
if error is not None:
|
||||
row["error"] = error
|
||||
if remote_updated_at is not None:
|
||||
row["remote_updated_at"] = remote_updated_at
|
||||
if remote_ok and row["remote_at"] is None:
|
||||
row["remote_at"] = now_kst()
|
||||
if resolved_by is not None:
|
||||
row["resolved_by"] = resolved_by
|
||||
return True
|
||||
|
||||
def record_attempt_revision(self, attempt_id, *, revision_type, memo, created_by, source="",
|
||||
source_revision_id=None):
|
||||
self._maybe_fail("record_attempt_revision")
|
||||
row = self.attempts[int(attempt_id)]
|
||||
if row.get("applied_revision_id"):
|
||||
return row["applied_revision_id"]
|
||||
body = row.get("target_html") or self.revisions.get(row.get("target_revision_id") or 0, {}).get("html_content", "")
|
||||
rid = self.add_revision(product_no=row["product_no"], html_content=body, revision_type=revision_type,
|
||||
memo=memo, created_by=created_by, mall_id=row.get("mall_id", ""),
|
||||
source=source, source_revision_id=source_revision_id)
|
||||
row.update(status=store.ATTEMPT_RECORDED, applied_revision_id=rid, target_html="")
|
||||
if row["remote_at"] is None:
|
||||
row["remote_at"] = now_kst()
|
||||
return rid
|
||||
|
||||
def get_attempt(self, attempt_id):
|
||||
return dict(self.attempts.get(int(attempt_id), {}))
|
||||
|
||||
def latest_attempt_for_schedule(self, schedule_id):
|
||||
rows = [a for a in self.attempts.values() if a.get("schedule_id") == int(schedule_id)]
|
||||
return dict(max(rows, key=lambda a: a["id"])) if rows else {}
|
||||
|
||||
def open_attempts(self, product_no, *, since):
|
||||
return [dict(a) for a in sorted(self.attempts.values(), key=lambda a: a["id"])
|
||||
if a["product_no"] == int(product_no) and a["status"] in store.ATTEMPT_OPEN
|
||||
and a["created_at"] >= since]
|
||||
|
||||
def attempts_needing_record(self, *, since, limit=20):
|
||||
return [dict(a) for a in self.attempts.values()
|
||||
if a["status"] == store.ATTEMPT_REMOTE_OK and a["created_at"] >= since][:limit]
|
||||
|
||||
def write_lineage(self, product_no, *, since, limit=30):
|
||||
rows = [a for a in self.attempts.values()
|
||||
if a["product_no"] == int(product_no) and a["status"] in store.ATTEMPT_CONFIRMED
|
||||
and a["target_digest"] and a["remote_at"] and a["remote_at"] >= since]
|
||||
rows.sort(key=lambda a: (a["remote_at"], a["id"]), reverse=True)
|
||||
out = []
|
||||
for i, a in enumerate(rows[:limit]):
|
||||
body = ""
|
||||
if i == 0:
|
||||
body = (a.get("target_html")
|
||||
or self.revisions.get(a.get("applied_revision_id") or 0, {}).get("html_content")
|
||||
or self.revisions.get(a.get("target_revision_id") or 0, {}).get("html_content") or "")
|
||||
out.append({**a, "created_at": a["remote_at"], "created_by": a.get("actor", ""), "html_content": body})
|
||||
return out
|
||||
|
||||
# ── 상품 캐시 · 스냅샷 ──
|
||||
def upsert_products(self, rows):
|
||||
self._maybe_fail("upsert_products")
|
||||
for r in rows:
|
||||
self.products[int(r["product_no"])] = dict(r)
|
||||
return len(rows)
|
||||
|
||||
def save_write_snapshot(self, product_no, section, data, *, replace=False):
|
||||
self._maybe_fail("save_write_snapshot")
|
||||
at = now_kst().isoformat(timespec="seconds")
|
||||
current = self.snapshots.setdefault(int(product_no), {})
|
||||
if section == "variants":
|
||||
previous = (current.get("variants") or {}).get("data") or {}
|
||||
data = store.merge_variant_snapshot(previous, data, at=at, replace=replace)
|
||||
current[section] = {"data": data, "written_at": at}
|
||||
|
||||
def get_write_snapshot(self, product_no):
|
||||
return dict(self.snapshots.get(int(product_no), {}))
|
||||
|
||||
# ── 예약 ──
|
||||
def add_schedule(self, **fields):
|
||||
sid = next(self._ids)
|
||||
row = {"id": sid, "product_no": 131, "revision_id": None, "set_display": None, "set_selling": None,
|
||||
"status": store.STATUS_PENDING, "retry_count": 0, "next_retry_at": None, "last_error": "",
|
||||
"scheduled_at": now_kst() - timedelta(minutes=1), "lease_token": "", "lease_owner": "",
|
||||
"lease_expires_at": None, "started_at": None}
|
||||
row.update(fields)
|
||||
self.schedules[sid] = row
|
||||
return sid
|
||||
|
||||
def claim_due_schedule(self, *, now, owner, ttl_seconds):
|
||||
due = [s for s in sorted(self.schedules.values(), key=lambda s: (s["scheduled_at"], s["id"]))
|
||||
if s["status"] == store.STATUS_PENDING and s["scheduled_at"] <= now
|
||||
and (s["next_retry_at"] is None or s["next_retry_at"] <= now)]
|
||||
if not due:
|
||||
return None
|
||||
row = due[0]
|
||||
row.update(status=store.STATUS_PROCESSING, lease_owner=owner, lease_token=uuid.uuid4().hex,
|
||||
lease_expires_at=now_kst() + timedelta(seconds=ttl_seconds), started_at=now_kst(),
|
||||
last_error="")
|
||||
return dict(row)
|
||||
|
||||
def claim_expired_schedules(self, *, owner, ttl_seconds, legacy_minutes, limit=20):
|
||||
out = []
|
||||
for row in self.schedules.values():
|
||||
if row["status"] != store.STATUS_PROCESSING:
|
||||
continue
|
||||
expired = row["lease_expires_at"] is not None and row["lease_expires_at"] < now_kst()
|
||||
legacy = row["lease_expires_at"] is None and (row["started_at"] or now_kst()) < now_kst() - timedelta(minutes=legacy_minutes)
|
||||
if expired or legacy:
|
||||
row.update(lease_owner=owner, lease_token=uuid.uuid4().hex,
|
||||
lease_expires_at=now_kst() + timedelta(seconds=ttl_seconds))
|
||||
out.append(dict(row))
|
||||
return out[:limit]
|
||||
|
||||
def renew_schedule_lease(self, schedule_id, token, *, ttl_seconds):
|
||||
row = self.schedules.get(int(schedule_id))
|
||||
if (not row or row["status"] != store.STATUS_PROCESSING or row["lease_token"] != token
|
||||
or row["lease_expires_at"] <= now_kst()):
|
||||
return False
|
||||
row["lease_expires_at"] = now_kst() + timedelta(seconds=ttl_seconds)
|
||||
return True
|
||||
|
||||
def finish_schedule(self, schedule_id, *, token, status, error="", next_retry_at=None, retry_count=None):
|
||||
self._maybe_fail("finish_schedule")
|
||||
row = self.schedules.get(int(schedule_id))
|
||||
if not row or row["status"] != store.STATUS_PROCESSING or row["lease_token"] != token:
|
||||
return False
|
||||
row.update(status=store.normalize_schedule_status(status), last_error=error, next_retry_at=next_retry_at,
|
||||
lease_token="", lease_owner="", lease_expires_at=None)
|
||||
if retry_count is not None:
|
||||
row["retry_count"] = retry_count
|
||||
return True
|
||||
|
||||
def expire_schedule_lease(self, schedule_id):
|
||||
self.schedules[int(schedule_id)]["lease_expires_at"] = now_kst() - timedelta(seconds=1)
|
||||
|
||||
def get_schedule(self, schedule_id):
|
||||
return dict(self.schedules.get(int(schedule_id), {}))
|
||||
|
||||
def review_schedule(self, schedule_id, *, status, note, actor, action):
|
||||
row = self.schedules.get(int(schedule_id))
|
||||
if not row or row["status"] != store.STATUS_NEEDS_REVIEW:
|
||||
return {}
|
||||
row.update(status=status, last_error=note,
|
||||
next_retry_at=now_kst() if status == store.STATUS_PENDING else None)
|
||||
if status != store.STATUS_SUCCESS:
|
||||
for a in self.attempts.values():
|
||||
if a.get("schedule_id") == int(schedule_id) and a["status"] in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN):
|
||||
a.update(status=store.ATTEMPT_ABANDONED, resolved_by=actor)
|
||||
return dict(row)
|
||||
|
||||
# ── 감사 ──
|
||||
def log_audit(self, **fields):
|
||||
self._maybe_fail("log_audit")
|
||||
self.audits.append(fields)
|
||||
|
||||
def log_api_call(self, **_fields):
|
||||
pass
|
||||
|
||||
|
||||
class FakeConfig:
|
||||
mall_id = "testmall"
|
||||
shop_base = "https://testmall.cafe24.com"
|
||||
|
||||
def product_url(self, no):
|
||||
return f"https://testmall.cafe24.com/product/detail.html?product_no={no}"
|
||||
|
||||
|
||||
class FakeCafe24:
|
||||
"""카페24 상품 API 대역 — 상세설명·진열/판매·updated_date 를 들고 있고,
|
||||
읽기 지연(lag)·PUT 실패·응답 유실을 흉내낸다."""
|
||||
|
||||
def __init__(self, description: str = "<p>A</p>", *, product_no: int = 131):
|
||||
self.product_no = product_no
|
||||
self.state = {"product_no": product_no, "product_name": "상품", "product_code": "P000000B",
|
||||
"description": description, "mobile_description": description,
|
||||
"separated_mobile_description": "F", "display": "T", "selling": "T",
|
||||
"updated_date": "2026-09-30T10:00:00+09:00"}
|
||||
self.stale: dict | None = None # 설정하면 GET 이 이 값을 돌려준다(읽기 지연)
|
||||
self.put_error: Exception | None = None
|
||||
self.put_error_after_apply = False # True 면 반영한 뒤 오류(응답 유실)
|
||||
self.calls: list[tuple] = []
|
||||
self._clock = 0
|
||||
self.option: dict = {"has_option": "F", "options": []}
|
||||
self.variants: list = []
|
||||
self.stale_option: dict | None = None # 설정하면 GET options 가 이 값을 돌려준다
|
||||
self.stale_variants: list | None = None # 설정하면 GET variants 가 이 값을 돌려준다
|
||||
self.hidden_variants = 0 # 새로 생긴 품목이 GET 에 늦게 나타나는 횟수
|
||||
self.fail_variant_chunk = 0 # n번째 PUT variants 묶음을 실패시킨다
|
||||
self.variant_error: Exception | None = None
|
||||
self._variant_puts = 0
|
||||
self._code_seq = 0
|
||||
|
||||
def external_edit(self, description: str) -> None:
|
||||
"""카페24 관리자에서 사람이 직접 고친 것."""
|
||||
self._tick()
|
||||
self.state.update(description=description, mobile_description=description)
|
||||
|
||||
def _tick(self) -> None:
|
||||
self._clock += 1
|
||||
self.state["updated_date"] = (datetime(2026, 9, 30, 10, 0, tzinfo=KST)
|
||||
+ timedelta(minutes=self._clock)).isoformat()
|
||||
|
||||
# Cafe24Client 흉내 — products.* 래퍼가 부르는 get/put
|
||||
def get(self, path, **kw):
|
||||
self.calls.append(("GET", path))
|
||||
if path == f"/admin/products/{self.product_no}":
|
||||
return {"product": dict(self.stale if self.stale is not None else self.state)}
|
||||
out = self._options_call("GET", path, None)
|
||||
return copy.deepcopy(out) if out is not None else {}
|
||||
|
||||
# ── 옵션 / 품목 ── (상태는 __init__ 에서 만든다)
|
||||
|
||||
def _new_code(self) -> str:
|
||||
self._code_seq += 1
|
||||
return f"P000000B{self._code_seq:04X}"
|
||||
|
||||
def _options_call(self, method, path, json):
|
||||
no = self.product_no
|
||||
req = (json or {}).get("request") or {}
|
||||
if path == f"/admin/products/{no}/options":
|
||||
if method == "GET":
|
||||
return {"option": self.stale_option if self.stale_option is not None else self.option}
|
||||
if method == "POST":
|
||||
opt = req["options"][0]
|
||||
values = [{"option_text": v["option_text"], "value_no": i + 1} for i, v in enumerate(opt["option_value"])]
|
||||
self.option = {"has_option": "T", "option_type": "T", "option_list_type": "S",
|
||||
"options": [{"option_name": opt["option_name"], "option_code": "O1",
|
||||
"option_display_type": opt.get("option_display_type", "S"),
|
||||
"option_value": values}]}
|
||||
self.variants = [{"variant_code": self._new_code(), "options": [{"name": opt["option_name"], "value": v["option_text"]}],
|
||||
"custom_variant_code": "", "additional_amount": "0.00", "display": "T", "selling": "T"}
|
||||
for v in values]
|
||||
return {"option": self.option}
|
||||
if method == "PUT":
|
||||
new = req["options"]
|
||||
for gi, group in enumerate(new):
|
||||
cur = self.option["options"][gi]
|
||||
old_name = cur["option_name"]
|
||||
old_values = [v["option_text"] for v in cur["option_value"]]
|
||||
cur["option_name"] = group["option_name"]
|
||||
vals = []
|
||||
for vi, v in enumerate(group["option_value"]):
|
||||
vals.append({"option_text": v["option_text"], "value_no": vi + 1,
|
||||
"option_image_file": v.get("option_image_file", "")})
|
||||
if vi < len(old_values):
|
||||
for var in self.variants:
|
||||
for o in var["options"]:
|
||||
if o["name"] == old_name and o["value"] == old_values[vi]:
|
||||
o["value"] = v["option_text"]
|
||||
else:
|
||||
self.variants.append({"variant_code": self._new_code(),
|
||||
"options": [{"name": group["option_name"], "value": v["option_text"]}],
|
||||
"custom_variant_code": "", "additional_amount": "0.00",
|
||||
"display": "T", "selling": "T", "_new": True})
|
||||
for var in self.variants:
|
||||
for o in var["options"]:
|
||||
if o["name"] == old_name:
|
||||
o["name"] = group["option_name"]
|
||||
cur["option_value"] = vals
|
||||
return {"option": self.option}
|
||||
if method == "DELETE":
|
||||
self.option = {"has_option": "F", "options": []}
|
||||
self.variants = []
|
||||
return {"option": {"product_no": no}}
|
||||
if path == f"/admin/products/{no}/variants":
|
||||
if method == "GET":
|
||||
if self.stale_variants is not None:
|
||||
return {"variants": [dict(v) for v in self.stale_variants]}
|
||||
shown = [dict(v) for v in self.variants]
|
||||
if self.hidden_variants > 0:
|
||||
self.hidden_variants -= 1
|
||||
shown = [v for v in shown if not v.get("_new")]
|
||||
return {"variants": shown}
|
||||
if method == "PUT":
|
||||
self._variant_puts += 1
|
||||
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
|
||||
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
|
||||
out = []
|
||||
for r in (json or {}).get("requests") or []:
|
||||
for var in self.variants:
|
||||
if var["variant_code"] == r["variant_code"]:
|
||||
var.update({k: v for k, v in r.items() if k != "variant_code"})
|
||||
out.append(dict(var))
|
||||
return {"variants": out}
|
||||
if path.startswith(f"/admin/products/{no}/variants/") and method == "DELETE":
|
||||
code = path.rsplit("/", 1)[1]
|
||||
self.variants = [v for v in self.variants if v["variant_code"] != code]
|
||||
return {"variant": {"variant_code": code}}
|
||||
return None
|
||||
|
||||
def post(self, path, *, json=None, **kw):
|
||||
self.calls.append(("POST", path, json))
|
||||
out = self._options_call("POST", path, json)
|
||||
return copy.deepcopy(out) if out is not None else {}
|
||||
|
||||
def delete(self, path, **kw):
|
||||
self.calls.append(("DELETE", path))
|
||||
out = self._options_call("DELETE", path, None)
|
||||
return out if out is not None else {}
|
||||
|
||||
def put(self, path, *, json=None, **kw):
|
||||
self.calls.append(("PUT", path, json))
|
||||
if path != f"/admin/products/{self.product_no}":
|
||||
out = self._options_call("PUT", path, json)
|
||||
return copy.deepcopy(out) if out is not None else {}
|
||||
if self.put_error is not None and not self.put_error_after_apply:
|
||||
raise self.put_error
|
||||
req = (json or {}).get("request", {})
|
||||
self._tick()
|
||||
for key in ("description", "display", "selling", "product_name", "separated_mobile_description"):
|
||||
if key in req:
|
||||
self.state[key] = req[key]
|
||||
if "description" in req:
|
||||
self.state["mobile_description"] = req["description"]
|
||||
if self.put_error is not None:
|
||||
raise self.put_error
|
||||
return {"product": dict(self.state)}
|
||||
|
||||
def puts(self):
|
||||
return [c for c in self.calls if c[0] == "PUT"]
|
||||
|
||||
|
||||
class FakeApi:
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
self.config = FakeConfig()
|
||||
|
||||
|
||||
def network_error(maybe_applied: bool = True) -> Cafe24ApiError:
|
||||
return Cafe24ApiError("네트워크 오류 (ReadTimeout)", status=0, maybe_applied=maybe_applied)
|
||||
|
||||
|
||||
class FakeFTP:
|
||||
"""ftplib.FTP 대역 — RETR/STOR/RNFR·RNTO/DELE 를 메모리 파일로. 실패를 주입할 수 있다."""
|
||||
|
||||
files: dict[str, bytes] = {}
|
||||
rename_mode = "overwrite" # overwrite | no_overwrite | unsupported
|
||||
truncate_store = False # STOR 가 앞부분만 쓰고 끝난 것처럼
|
||||
on_before_rename = None # 교체 직전 끼어들기(남이 원본을 바꿈 등)
|
||||
log: list[tuple] = []
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def connect(self, host, port, timeout=None):
|
||||
FakeFTP.log.append(("connect",))
|
||||
|
||||
def login(self, user, password):
|
||||
pass
|
||||
|
||||
def set_pasv(self, value):
|
||||
pass
|
||||
|
||||
def retrbinary(self, cmd, callback):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
if path not in self.files:
|
||||
raise ftplib.error_perm("550 No such file")
|
||||
callback(self.files[path])
|
||||
|
||||
def storbinary(self, cmd, fp):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
data = fp.read()
|
||||
FakeFTP.log.append(("STOR", path))
|
||||
self.files[path] = data[: len(data) // 2] if FakeFTP.truncate_store else data
|
||||
|
||||
def rename(self, src, dst):
|
||||
FakeFTP.log.append(("RENAME", src, dst))
|
||||
if FakeFTP.on_before_rename is not None:
|
||||
hook, FakeFTP.on_before_rename = FakeFTP.on_before_rename, None
|
||||
hook(self.files)
|
||||
if FakeFTP.rename_mode == "unsupported":
|
||||
raise ftplib.error_perm("502 RNFR not implemented")
|
||||
if src not in self.files:
|
||||
raise ftplib.error_perm("550 No such file")
|
||||
if dst in self.files and FakeFTP.rename_mode == "no_overwrite":
|
||||
raise ftplib.error_perm("553 File exists")
|
||||
self.files[dst] = self.files.pop(src)
|
||||
|
||||
def delete(self, path):
|
||||
FakeFTP.log.append(("DELE", path))
|
||||
self.files.pop(path, None)
|
||||
|
||||
def quit(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def reset(cls, files):
|
||||
cls.files = dict(files)
|
||||
cls.rename_mode = "overwrite"
|
||||
cls.truncate_store = False
|
||||
cls.on_before_rename = None
|
||||
cls.log = []
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patched_ftp():
|
||||
saved = ftplib.FTP
|
||||
ftplib.FTP = FakeFTP
|
||||
try:
|
||||
yield FakeFTP
|
||||
finally:
|
||||
ftplib.FTP = saved
|
||||
@@ -8,6 +8,7 @@ DB/네트워크 없이 검증한다(가짜 저장소 + refresh 함수 주입).
|
||||
from __future__ import annotations
|
||||
|
||||
import ftplib
|
||||
import logging
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from datetime import timedelta
|
||||
@@ -15,7 +16,8 @@ from datetime import timedelta
|
||||
from app.integrations.cafe24 import config as cfgmod
|
||||
from app.integrations.cafe24 import crypto, oauth, products, tokens
|
||||
from app.integrations.cafe24.errors import Cafe24ApiError, Cafe24AuthError, Cafe24ConfigError
|
||||
from app.modules.cafe24 import store, worker
|
||||
from app.modules.cafe24 import store, worker, writes
|
||||
from app.modules.cafe24.tests import fakes
|
||||
from app.timezone import now_kst
|
||||
|
||||
SECRET = "unit-test-secret"
|
||||
@@ -25,6 +27,8 @@ SECRET = "unit-test-secret"
|
||||
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
||||
# 기다릴 필요는 없다.
|
||||
products.time.sleep = lambda *_a, **_k: None
|
||||
# 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히.
|
||||
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
||||
|
||||
_TEST_ENV = {
|
||||
"CAFE24_MALL_ID": "testmall",
|
||||
@@ -711,203 +715,303 @@ def test_design_file_path_env_override():
|
||||
os.environ["CAFE24_PC_DETAIL_FTP_PATH"] = saved
|
||||
|
||||
|
||||
class _FakeFTP:
|
||||
"""ftplib.FTP 대역 — 실제 소켓 없이 RETR/STOR 명령만 흉내낸다."""
|
||||
|
||||
files: dict[str, bytes] = {}
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def connect(self, host, port, timeout=None):
|
||||
self.calls.append(("connect", host, port))
|
||||
|
||||
def login(self, user, password):
|
||||
self.calls.append(("login", user, password))
|
||||
|
||||
def set_pasv(self, value):
|
||||
pass
|
||||
|
||||
def retrbinary(self, cmd, callback):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
if path not in self.files:
|
||||
raise ftplib.error_perm("550 No such file")
|
||||
callback(self.files[path])
|
||||
|
||||
def storbinary(self, cmd, fp):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
self.files[path] = fp.read()
|
||||
|
||||
def quit(self):
|
||||
self.calls.append(("quit",))
|
||||
_FTP_CFG = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||
_SWIPER = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
||||
|
||||
|
||||
def test_design_ftp_read_and_write_roundtrip():
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
|
||||
path = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
||||
_FakeFTP.files = {path: "old".encode("utf-8")}
|
||||
saved = ftplib.FTP
|
||||
ftplib.FTP = _FakeFTP
|
||||
try:
|
||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||
content = design_ftp.read_text_file(cfg, path)
|
||||
assert content == "old"
|
||||
|
||||
design_ftp.write_text_file(cfg, path, "new content")
|
||||
assert design_ftp.read_text_file(cfg, path) == "new content"
|
||||
finally:
|
||||
ftplib.FTP = saved
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: "old".encode("utf-8")})
|
||||
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "old"
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "new content", expected_current="old")
|
||||
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "new content"
|
||||
# 원본에 직접 STOR 하지 않는다 — 임시 파일에 올린 뒤 이름 바꾸기로 교체
|
||||
stors = [e for e in ftp.log if e[0] == "STOR"]
|
||||
assert stors and all(".cf24tmp-" in e[1] for e in stors), ftp.log
|
||||
assert any(e[0] == "RENAME" and e[2] == _SWIPER for e in ftp.log)
|
||||
# 임시 파일이 남지 않는다
|
||||
assert set(ftp.files) == {_SWIPER}
|
||||
|
||||
|
||||
def test_design_ftp_missing_file_raises_cafe24_error():
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||
|
||||
_FakeFTP.files = {}
|
||||
saved = ftplib.FTP
|
||||
ftplib.FTP = _FakeFTP
|
||||
try:
|
||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({})
|
||||
try:
|
||||
design_ftp.read_text_file(cfg, "/missing.js")
|
||||
design_ftp.read_text_file(_FTP_CFG, "/missing.js")
|
||||
raise AssertionError("Cafe24FtpError 가 났어야 한다")
|
||||
except Cafe24FtpError:
|
||||
pass
|
||||
finally:
|
||||
ftplib.FTP = saved
|
||||
|
||||
|
||||
def test_design_ftp_truncated_upload_keeps_original():
|
||||
"""[04] 전송이 잘려도 원본은 그대로 — 임시 파일 검증에서 멈춘다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"ORIGINAL"})
|
||||
ftp.truncate_store = True
|
||||
try:
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "NEW CONTENT 1234", expected_current="ORIGINAL")
|
||||
raise AssertionError("잘린 업로드를 성공으로 처리했다")
|
||||
except Cafe24FtpError as exc:
|
||||
assert exc.maybe_applied is False
|
||||
assert ftp.files == {_SWIPER: b"ORIGINAL"} # 원본 그대로 + 임시 파일 정리
|
||||
|
||||
|
||||
def test_design_ftp_rename_unsupported_aborts_without_direct_stor():
|
||||
"""[04] 이름 바꾸기를 지원하지 않으면 중단 — 원본에 직접 쓰지 않는다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"ORIGINAL"})
|
||||
ftp.rename_mode = "unsupported"
|
||||
try:
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "NEW", expected_current="ORIGINAL")
|
||||
raise AssertionError("rename 미지원인데 진행했다")
|
||||
except Cafe24FtpError as exc:
|
||||
assert "rename" in str(exc)
|
||||
assert ftp.files == {_SWIPER: b"ORIGINAL"}
|
||||
assert not any(e == ("STOR", _SWIPER) for e in ftp.log)
|
||||
|
||||
|
||||
def test_design_ftp_no_overwrite_rename_swaps_safely():
|
||||
"""덮어쓰기 rename 을 거부하는 서버 — 원본을 비킨 뒤 교체하고 비킨 파일은 지운다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"ORIGINAL"})
|
||||
ftp.rename_mode = "no_overwrite"
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "NEW", expected_current="ORIGINAL")
|
||||
assert ftp.files == {_SWIPER: b"NEW"}
|
||||
|
||||
|
||||
def test_design_ftp_conflict_right_before_replace():
|
||||
"""[04] 교체 직전 원본이 바뀌어 있으면(남이 수정) 덮지 않고 멈춘다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpConflict
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"SOMEONE ELSE"})
|
||||
try:
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "MINE", expected_current="ORIGINAL")
|
||||
raise AssertionError("충돌을 못 잡았다")
|
||||
except Cafe24FtpConflict:
|
||||
pass
|
||||
assert ftp.files == {_SWIPER: b"SOMEONE ELSE"}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 예약 worker — 성공/재시도/최종실패
|
||||
# 예약 worker — 성공/재시도/최종실패/확인 필요/중단 복구 (메모리 저장소 대역)
|
||||
# 실제 DB 의 lease·SKIP LOCKED 는 test_cafe24_db.py 에서 검증한다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class _FakeStore:
|
||||
"""worker 가 쓰는 저장소 메서드만 흉내낸다."""
|
||||
|
||||
def __init__(self, rows):
|
||||
self.rows = list(rows)
|
||||
self.revisions = {}
|
||||
self.added = []
|
||||
self.finished = []
|
||||
self.audits = []
|
||||
|
||||
@contextmanager
|
||||
def claim_due_schedule(self, *, now):
|
||||
yield self.rows.pop(0) if self.rows else None
|
||||
|
||||
def get_revision(self, revision_id):
|
||||
return self.revisions.get(int(revision_id), {})
|
||||
|
||||
def add_revision(self, **fields):
|
||||
self.added.append(fields)
|
||||
return 900 + len(self.added)
|
||||
|
||||
def save_write_snapshot(self, product_no, section, data):
|
||||
self.snapshots = getattr(self, "snapshots", [])
|
||||
self.snapshots.append((product_no, section, data))
|
||||
|
||||
def finish_schedule(self, schedule_id, *, status, error="", next_retry_at=None, retry_count=None):
|
||||
self.finished.append(
|
||||
{"id": schedule_id, "status": status, "error": error,
|
||||
"next_retry_at": next_retry_at, "retry_count": retry_count}
|
||||
)
|
||||
|
||||
def log_audit(self, **fields):
|
||||
self.audits.append(fields)
|
||||
|
||||
|
||||
class _FakeApi:
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
|
||||
class _WorkerClient(_FakeClient):
|
||||
"""PUT 을 실패시킬 수 있는 클라이언트."""
|
||||
|
||||
def __init__(self, payload=None, fail_put=None):
|
||||
super().__init__(payload)
|
||||
self.fail_put = fail_put
|
||||
|
||||
def put(self, path, *, params=None, json=None, product_no=None):
|
||||
if self.fail_put:
|
||||
raise self.fail_put
|
||||
return super().put(path, params=params, json=json, product_no=product_no)
|
||||
|
||||
|
||||
def _schedule_row(**overrides):
|
||||
row = {
|
||||
"id": 7, "product_no": 131, "revision_id": 55,
|
||||
"set_display": True, "set_selling": None, "retry_count": 0,
|
||||
}
|
||||
row.update(overrides)
|
||||
return row
|
||||
def _worker_env(description="<p>A</p>", **schedule):
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24(description)
|
||||
api = fakes.FakeApi(cafe)
|
||||
rid = st.add_revision(product_no=131, html_content="<p>예약 내용</p>", revision_type="DRAFT")
|
||||
fields = {"revision_id": rid, "set_display": True}
|
||||
fields.update(schedule)
|
||||
sid = st.add_schedule(**fields)
|
||||
return st, cafe, api, sid, rid
|
||||
|
||||
|
||||
def test_worker_applies_html_and_flags():
|
||||
st = _FakeStore([_schedule_row()])
|
||||
st.revisions[55] = {"html_content": "<p>예약 내용</p>"}
|
||||
client = _WorkerClient({"product": _PRODUCT})
|
||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
||||
st, cafe, api, sid, _rid = _worker_env()
|
||||
assert worker.process_once(st, api) == 1
|
||||
|
||||
# 쓰기 직전 현재값을 읽어 BACKUP 을 남겼는가
|
||||
assert any(r["revision_type"] == store.REVISION_BACKUP for r in st.added)
|
||||
backups = st.of_type(store.REVISION_BACKUP)
|
||||
assert backups and backups[0]["html_content"] == "<p>A</p>"
|
||||
assert backups[0]["source"] == store.SOURCE_OBSERVED
|
||||
# HTML 과 진열 상태를 한 번의 PUT 으로 보냈는가
|
||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
||||
assert put["json"]["request"]["description"] == "<p>예약 내용</p>"
|
||||
put = cafe.puts()[0]
|
||||
assert put[2]["request"]["description"] == "<p>예약 내용</p>"
|
||||
# mobile_description 은 보내지 않는다 — separated_mobile_description="F" 로
|
||||
# "PC 상세설명과 동일"을 강제한다(직접 보내면 "직접 등록"으로 바뀌어버린다).
|
||||
assert "mobile_description" not in put["json"]["request"]
|
||||
assert put["json"]["request"]["separated_mobile_description"] == "F"
|
||||
assert put["json"]["request"]["display"] == "T"
|
||||
assert "selling" not in put["json"]["request"] # 변경 없음이면 보내지 않는다
|
||||
assert st.finished == [
|
||||
{"id": 7, "status": store.STATUS_SUCCESS, "error": "",
|
||||
"next_retry_at": None, "retry_count": None}
|
||||
]
|
||||
assert "mobile_description" not in put[2]["request"]
|
||||
assert put[2]["request"]["separated_mobile_description"] == "F"
|
||||
assert put[2]["request"]["display"] == "T"
|
||||
assert "selling" not in put[2]["request"] # 변경 없음이면 보내지 않는다
|
||||
row = st.schedules[sid]
|
||||
assert row["status"] == store.STATUS_SUCCESS and row["last_error"] == ""
|
||||
assert row["lease_token"] == "" # 끝나면 lease 를 비운다
|
||||
assert len(st.of_type(store.REVISION_SCHEDULED)) == 1
|
||||
assert list(st.attempts.values())[0]["status"] == store.ATTEMPT_RECORDED
|
||||
assert st.locks == {} # 상품 잠금 해제
|
||||
|
||||
|
||||
def test_worker_flags_only_skips_backup():
|
||||
"""HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽거나 백업하지 않는다."""
|
||||
st = _FakeStore([_schedule_row(revision_id=None, set_selling=False)])
|
||||
client = _WorkerClient({"product": _PRODUCT})
|
||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
||||
assert st.added == [] # 백업 없음
|
||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
||||
assert "description" not in put["json"]["request"]
|
||||
assert put["json"]["request"] == {"display": "T", "selling": "F"}
|
||||
st, cafe, api, sid, _ = _worker_env(revision_id=None, set_selling=False)
|
||||
before = len(st.revisions)
|
||||
assert worker.process_once(st, api) == 1
|
||||
assert len(st.revisions) == before # 백업·SCHEDULED 버전 없음
|
||||
put = cafe.puts()[0]
|
||||
assert put[2]["request"] == {"display": "T", "selling": "F"}
|
||||
assert st.schedules[sid]["status"] == store.STATUS_SUCCESS
|
||||
|
||||
|
||||
def test_worker_retries_then_fails():
|
||||
"""실패는 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED 로 확정한다."""
|
||||
boom = Cafe24ApiError("서버 오류", status=500)
|
||||
|
||||
st = _FakeStore([_schedule_row(retry_count=0)])
|
||||
st.revisions[55] = {"html_content": "<p>x</p>"}
|
||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
||||
first = st.finished[0]
|
||||
"""거절(반영 안 됨이 확실)은 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
cafe.put_error = Cafe24ApiError("잘못된 요청", status=422)
|
||||
worker.process_once(st, api)
|
||||
first = st.schedules[sid]
|
||||
assert first["status"] == store.STATUS_PENDING # 다시 대기로
|
||||
assert first["retry_count"] == 1
|
||||
assert first["next_retry_at"] is not None
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_REMOTE_FAILED
|
||||
|
||||
st2 = _FakeStore([_schedule_row(retry_count=store.MAX_RETRY)])
|
||||
st2.revisions[55] = {"html_content": "<p>x</p>"}
|
||||
worker.process_once(st2, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
||||
assert st2.finished[0]["status"] == store.STATUS_FAILED
|
||||
st2, cafe2, api2, sid2, _ = _worker_env(retry_count=store.MAX_RETRY)
|
||||
cafe2.put_error = Cafe24ApiError("서버 오류", status=400)
|
||||
worker.process_once(st2, api2)
|
||||
assert st2.schedules[sid2]["status"] == store.STATUS_FAILED
|
||||
assert any(a["result"] == "FAIL" for a in st2.audits)
|
||||
|
||||
|
||||
def test_worker_missing_revision_is_failure_not_crash():
|
||||
st = _FakeStore([_schedule_row(revision_id=999, retry_count=store.MAX_RETRY)])
|
||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT})))
|
||||
assert st.finished[0]["status"] == store.STATUS_FAILED
|
||||
assert "999" in st.finished[0]["error"]
|
||||
st, _cafe, api, sid, _ = _worker_env(revision_id=999, retry_count=store.MAX_RETRY)
|
||||
worker.process_once(st, api)
|
||||
assert st.schedules[sid]["status"] == store.STATUS_FAILED
|
||||
assert "999" in st.schedules[sid]["last_error"]
|
||||
|
||||
|
||||
def test_worker_stops_when_nothing_due():
|
||||
st = _FakeStore([])
|
||||
assert worker.process_once(st, _FakeApi(_WorkerClient())) == 0
|
||||
st = fakes.MemoryStore()
|
||||
assert worker.process_once(st, fakes.FakeApi(fakes.FakeCafe24())) == 0
|
||||
|
||||
|
||||
def test_worker_unknown_result_needs_review_not_retry():
|
||||
"""[05][07] 응답 유실(반영 여부 모름) — 재시도로 한 번 더 쓰지 않고 확인 필요로 둔다."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
cafe.put_error = fakes.network_error(maybe_applied=True)
|
||||
cafe.put_error_after_apply = True
|
||||
worker.process_once(st, api)
|
||||
assert st.schedules[sid]["status"] == store.STATUS_NEEDS_REVIEW
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_UNKNOWN
|
||||
worker.process_once(st, api)
|
||||
assert len(cafe.puts()) == 1 # 다시 쓰지 않았다
|
||||
|
||||
|
||||
def test_worker_remote_ok_but_record_failure_is_success_not_failed():
|
||||
"""[07] PUT 성공 뒤 로컬 버전 기록 실패 → FAILED 가 아니라 SUCCESS + 기록 복구 메모, 재적용 없음."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
st.fail_on.add("record_attempt_revision")
|
||||
worker.process_once(st, api)
|
||||
row = st.schedules[sid]
|
||||
assert row["status"] == store.STATUS_SUCCESS, row
|
||||
assert "기록" in row["last_error"]
|
||||
attempt = list(st.attempts.values())[-1]
|
||||
assert attempt["status"] == store.ATTEMPT_REMOTE_OK # 반영됨, 기록 복구 대기
|
||||
# 다음 주기: 기록 복구만 하고 다시 PUT 하지 않는다
|
||||
st.fail_on.clear()
|
||||
worker.process_once(st, api)
|
||||
assert len(cafe.puts()) == 1
|
||||
assert attempt["status"] == store.ATTEMPT_RECORDED
|
||||
assert len(st.of_type(store.REVISION_SCHEDULED)) == 1
|
||||
|
||||
|
||||
def test_worker_busy_product_defers_without_burning_retry():
|
||||
"""[02] 같은 상품을 다른 작업이 쓰는 중이면 쓰지 않고 잠시 뒤로 미룬다(재시도 횟수 그대로)."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
st.acquire_lock("product:131", owner="king|web:1", purpose="상세설명 적용", ttl_seconds=60)
|
||||
worker.process_once(st, api)
|
||||
row = st.schedules[sid]
|
||||
assert row["status"] == store.STATUS_PENDING and row["retry_count"] == 0
|
||||
assert row["next_retry_at"] is not None
|
||||
assert cafe.puts() == []
|
||||
|
||||
|
||||
def test_worker_backup_uses_confirmed_last_write_during_lag():
|
||||
"""[06] 예약 직전 카페24가 읽기 지연으로 옛 HTML 을 돌려줘도, 백업은 마지막 확인된 적용값."""
|
||||
st, cafe, api, sid, _ = _worker_env(description="<p>OLD</p>")
|
||||
# 방금 웹에서 NEW 를 적용(확인된 쓰기) — 카페24 GET 은 아직 OLD
|
||||
with writes.write_lock(st, "product:131", actor="king", purpose="t") as lock:
|
||||
writes.write_product(st, api, 131, lock=lock, origin=store.ORIGIN_MANUAL, actor="king",
|
||||
html="<p>NEW</p>", wait_confirm=False)
|
||||
cafe.stale = {**cafe.state, "description": "<p>OLD</p>", "mobile_description": "<p>OLD</p>",
|
||||
"updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
worker.process_once(st, api)
|
||||
backups = [r for r in st.of_type(store.REVISION_BACKUP) if "예약" in r["memo"]]
|
||||
assert backups and backups[-1]["html_content"] == "<p>NEW</p>", backups
|
||||
assert backups[-1]["source"] == store.SOURCE_LAST_WRITE
|
||||
|
||||
|
||||
def test_worker_recovers_expired_processing_by_attempt_state():
|
||||
"""[05] lease 만료 PROCESSING — 시도 기록으로 판정(무조건 PENDING 금지)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
rid = st.add_revision(product_no=131, html_content="<p>예약</p>", revision_type="DRAFT")
|
||||
|
||||
def processing(**fields):
|
||||
sid = st.add_schedule(revision_id=rid, status=store.STATUS_PROCESSING,
|
||||
lease_token="dead", started_at=now_kst(), **fields)
|
||||
st.expire_schedule_lease(sid)
|
||||
return sid
|
||||
|
||||
# (1) 원격 쓰기 전에 죽음 → 재시도 대기
|
||||
s1 = processing()
|
||||
# (2) 반영·기록까지 끝난 뒤 죽음 → 완료
|
||||
s2 = processing()
|
||||
st.start_attempt(product_no=131, schedule_id=s2, origin="SCHEDULED", target_digest="x",
|
||||
target_revision_id=rid)
|
||||
st.attempts[max(st.attempts)]["status"] = store.ATTEMPT_RECORDED
|
||||
# (3) 반영됐고 기록 전에 죽음 → 기록 채우고 완료(재적용 없음)
|
||||
s3 = processing()
|
||||
a3 = st.start_attempt(product_no=131, schedule_id=s3, origin="SCHEDULED",
|
||||
target_digest=store.content_digest("<p>예약</p>"), target_revision_id=rid)
|
||||
st.attempts[a3]["status"] = store.ATTEMPT_REMOTE_OK
|
||||
# (4) PUT 도중 죽음, 카페24 값은 예약 결과와 다름 → 확인 필요
|
||||
s4 = processing()
|
||||
st.start_attempt(product_no=131, schedule_id=s4, origin="SCHEDULED",
|
||||
target_digest=store.content_digest("<p>예약</p>"), target_revision_id=rid)
|
||||
# (5) 레거시(lease 없음) PROCESSING, 40분 전 → 만료로 보고 재시도 대기
|
||||
s5 = st.add_schedule(revision_id=rid, status=store.STATUS_PROCESSING, lease_token="",
|
||||
started_at=now_kst() - timedelta(minutes=40))
|
||||
|
||||
worker.recover(st, api)
|
||||
assert st.schedules[s1]["status"] == store.STATUS_PENDING and st.schedules[s1]["retry_count"] == 1
|
||||
assert st.schedules[s2]["status"] == store.STATUS_SUCCESS
|
||||
assert st.schedules[s3]["status"] == store.STATUS_SUCCESS
|
||||
assert st.attempts[a3]["status"] == store.ATTEMPT_RECORDED
|
||||
assert st.schedules[s4]["status"] == store.STATUS_NEEDS_REVIEW
|
||||
assert st.schedules[s5]["status"] == store.STATUS_PENDING
|
||||
assert cafe.puts() == [] # 복구는 쓰지 않는다
|
||||
|
||||
|
||||
def test_worker_recover_verifies_remote_value():
|
||||
"""[05] 결과 모름 시도라도 카페24 현재값이 예약 결과와 같으면 반영됨으로 확정."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>예약</p>") # 이미 반영돼 있다
|
||||
api = fakes.FakeApi(cafe)
|
||||
rid = st.add_revision(product_no=131, html_content="<p>예약</p>", revision_type="DRAFT")
|
||||
sid = st.add_schedule(revision_id=rid, status=store.STATUS_PROCESSING, lease_token="dead",
|
||||
started_at=now_kst())
|
||||
st.expire_schedule_lease(sid)
|
||||
aid = st.start_attempt(product_no=131, schedule_id=sid, origin="SCHEDULED",
|
||||
target_digest=store.content_digest("<p>예약</p>"), target_revision_id=rid)
|
||||
worker.recover(st, api)
|
||||
assert st.schedules[sid]["status"] == store.STATUS_SUCCESS
|
||||
assert st.attempts[aid]["status"] == store.ATTEMPT_RECORDED
|
||||
|
||||
|
||||
def test_worker_late_finish_after_lease_loss_does_not_overwrite():
|
||||
"""[05] lease 를 잃은 worker 의 늦은 결과는 반영되지 않는다(token 불일치)."""
|
||||
st, _cafe, _api, sid, _ = _worker_env()
|
||||
row = st.claim_due_schedule(now=now_kst(), owner="w1", ttl_seconds=60)
|
||||
st.expire_schedule_lease(sid)
|
||||
st.claim_expired_schedules(owner="w2", ttl_seconds=60, legacy_minutes=30)
|
||||
assert st.finish_schedule(sid, token=row["lease_token"], status=store.STATUS_FAILED) is False
|
||||
assert st.schedules[sid]["status"] == store.STATUS_PROCESSING
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 카페24 읽기 지연 보정 — 마지막 쓰기가 권위
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -1185,7 +1289,8 @@ def test_upload_images_and_variants_wrappers():
|
||||
assert products.list_variants(client, 7) == [{"variant_code": "P000000R000A"}]
|
||||
assert products.get_options(client, 7)["has_option"] == "T"
|
||||
assert products.update_variants(client, 7, [{"variant_code": "P000000R000A", "display": "F"}]) == [
|
||||
{"variant_code": "P000000R000A", "display": "F"}
|
||||
{"variant_code": "P000000R000A", "status": "ok", "error": "",
|
||||
"variant": {"variant_code": "P000000R000A", "display": "F"}}
|
||||
]
|
||||
sent = [c for c in client.calls if c[0] == "PUT"][-1]
|
||||
assert sent[2]["requests"][0]["variant_code"] == "P000000R000A"
|
||||
@@ -1221,6 +1326,404 @@ def test_set_main_image_uses_product_images_endpoint():
|
||||
assert products.set_main_image(client, 13, b"") == {}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 쓰기 공통 처리(writes.write_product) — [01][02][06][07] 회귀
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _apply(st, api, html, *, fp=None, origin=store.ORIGIN_MANUAL, actor="king", **kw):
|
||||
with writes.write_lock(st, "product:131", actor=actor, purpose="t", wait_seconds=0) as lock:
|
||||
return writes.write_product(st, api, 131, lock=lock, origin=origin, actor=actor, html=html,
|
||||
base_fingerprint=fp, wait_confirm=False, **kw)
|
||||
|
||||
|
||||
def _editor_view(st, cafe):
|
||||
"""편집기가 보여줄 유효 현재값과 지문(routes_products._editor_ctx 와 같은 판정)."""
|
||||
product = cafe.get(f"/admin/products/{cafe.product_no}")["product"]
|
||||
effective, state, _ = writes.resolve_effective(st, 131, product["description"],
|
||||
fetched_updated=product.get("updated_date"))
|
||||
return effective, state, store.fingerprint(effective)
|
||||
|
||||
|
||||
def test_01_rejected_conflict_backup_does_not_mask_external_edit():
|
||||
"""[01] 충돌로 거절된 적용의 BACKUP(=외부 값 X)이 읽기 지연 근거가 되면 X 를 덮어쓴다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>W1</p>") # 우리 쓰기(확인됨)
|
||||
_eff, _state, stale_fp = _editor_view(st, cafe) # 사용자 1: W1 을 보고 편집 시작
|
||||
cafe.external_edit("<p>X</p>") # 관리자에서 직접 X 로 고침
|
||||
|
||||
try:
|
||||
_apply(st, api, "<p>Y</p>", fp=stale_fp) # 사용자 1 적용 → 충돌로 거절(BACKUP X 가 남는다)
|
||||
raise AssertionError("충돌을 못 잡았다")
|
||||
except writes.WriteConflict:
|
||||
pass
|
||||
assert any(r["html_content"] == "<p>X</p>" for r in st.of_type(store.REVISION_BACKUP))
|
||||
|
||||
effective, state, fp = _editor_view(st, cafe)
|
||||
assert (effective, state) == ("<p>X</p>", store.SYNC_EXTERNAL), (effective, state)
|
||||
try:
|
||||
_apply(st, api, "<p>Y</p>", fp=stale_fp) # 같은 옛 지문으로 다시 → 여전히 충돌
|
||||
raise AssertionError("외부 수정 X 를 덮어썼다")
|
||||
except writes.WriteConflict:
|
||||
pass
|
||||
assert cafe.state["description"] == "<p>X</p>"
|
||||
_apply(st, api, "<p>Y</p>", fp=fp) # 새로 본 X 기준이면 적용된다
|
||||
assert cafe.state["description"] == "<p>Y</p>"
|
||||
|
||||
|
||||
def test_01_draft_value_is_not_treated_as_known():
|
||||
"""[01] 예약 초안(DRAFT)은 카페24에 올라간 적이 없다 — 관리자가 그 값으로 고쳐도 외부 변경."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>W1</p>")
|
||||
st.add_revision(product_no=131, html_content="<p>D</p>", revision_type="DRAFT")
|
||||
cafe.external_edit("<p>D</p>")
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>D</p>", store.SYNC_EXTERNAL)
|
||||
|
||||
|
||||
def test_01_read_lag_still_shows_last_confirmed_write():
|
||||
"""읽기 지연 보정은 유지 — GET 이 쓰기 직전 값(A)을 돌려주면 마지막 확인된 쓰기를 보여준다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>B</p>")
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>B</p>", store.SYNC_PENDING)
|
||||
_apply(st, api, "<p>C</p>") # A→B→C 직후 GET 이 A 여도 지연
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>C</p>", store.SYNC_PENDING)
|
||||
|
||||
|
||||
def test_01_revert_after_our_write_detected_by_updated_date():
|
||||
"""[01] 관리자가 우리 적용 뒤 예전 값(A)으로 되돌림 — updated_date 가 더 뒤라 외부 변경."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>B</p>")
|
||||
cafe.external_edit("<p>A</p>")
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>A</p>", store.SYNC_EXTERNAL)
|
||||
|
||||
|
||||
def test_01_failed_write_is_not_lineage():
|
||||
"""[01] 카페24가 거절한 쓰기는 "마지막 쓰기"가 아니다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
cafe.put_error = Cafe24ApiError("거절", status=422)
|
||||
try:
|
||||
_apply(st, api, "<p>B</p>")
|
||||
raise AssertionError("실패를 삼켰다")
|
||||
except writes.RemoteWriteFailed:
|
||||
pass
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_REMOTE_FAILED
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>A</p>", store.SYNC_NONE)
|
||||
assert st.of_type(store.REVISION_MANUAL) == []
|
||||
|
||||
|
||||
def test_02_second_writer_is_serialized_and_detects_conflict():
|
||||
"""[02] 같은 편집 기준(A)으로 두 사람이 동시에 적용 — 잠금으로 순서가 생기고 뒤 사람은 충돌."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
fp_a = store.fingerprint("<p>A</p>")
|
||||
with writes.write_lock(st, "product:131", actor="alice", purpose="t", wait_seconds=0):
|
||||
try: # 앞 사람이 쓰는 동안 뒤 사람은 잠금을 못 잡는다
|
||||
with writes.write_lock(st, "product:131", actor="bob", purpose="t", wait_seconds=0):
|
||||
raise AssertionError("잠금이 겹쳤다")
|
||||
except writes.WriteBusy as exc:
|
||||
assert "alice" in str(exc)
|
||||
_apply(st, api, "<p>ALICE</p>", fp=fp_a, actor="alice")
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
try: # GET 이 지연으로 A 를 돌려줘도, 마지막 확인된 쓰기(ALICE)가 기준이라 충돌
|
||||
_apply(st, api, "<p>BOB</p>", fp=fp_a, actor="bob")
|
||||
raise AssertionError("둘 다 성공했다")
|
||||
except writes.WriteConflict:
|
||||
pass
|
||||
assert cafe.state["description"] == "<p>ALICE</p>"
|
||||
|
||||
|
||||
def test_02_expired_lock_cannot_write_fencing():
|
||||
"""[02] 잠금이 만료돼 남에게 넘어간 뒤에는 PUT 하지 않는다(펜싱)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
with writes.write_lock(st, "product:131", actor="slow", purpose="t", wait_seconds=0) as lock:
|
||||
st.expire_lock("product:131")
|
||||
with writes.write_lock(st, "product:131", actor="other", purpose="t", wait_seconds=0):
|
||||
pass # 만료 뒤 다른 요청이 가져갔다가 풀었다
|
||||
try:
|
||||
writes.write_product(st, api, 131, lock=lock, origin="MANUAL", actor="slow",
|
||||
html="<p>S</p>", wait_confirm=False)
|
||||
raise AssertionError("만료된 잠금으로 썼다")
|
||||
except writes.WriteBusy:
|
||||
pass
|
||||
assert cafe.puts() == []
|
||||
|
||||
|
||||
def test_02_schema_missing_refuses_to_write():
|
||||
st = fakes.MemoryStore()
|
||||
st.schema_ok = False
|
||||
try:
|
||||
with writes.write_lock(st, "product:131", actor="k", purpose="t"):
|
||||
raise AssertionError("스키마 없이 잠금을 줬다")
|
||||
except writes.WriteSetupError as exc:
|
||||
assert "005" in str(exc)
|
||||
|
||||
|
||||
def test_06_manual_backup_marks_source():
|
||||
"""[06] BACKUP 메타데이터 — 관측값(OBSERVED) / 지연 중 마지막 확인된 쓰기(LAST_WRITE)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
first = _apply(st, api, "<p>B</p>")
|
||||
b1 = st.revisions[first.backup_id]
|
||||
assert (b1["html_content"], b1["source"]) == ("<p>A</p>", store.SOURCE_OBSERVED)
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
second = _apply(st, api, "<p>C</p>")
|
||||
b2 = st.revisions[second.backup_id]
|
||||
assert (b2["html_content"], b2["source"]) == ("<p>B</p>", store.SOURCE_LAST_WRITE)
|
||||
assert b2["source_revision_id"] == first.revision_id
|
||||
|
||||
|
||||
def test_07_manual_record_failure_is_not_apply_failure():
|
||||
"""[07] PUT 성공 뒤 버전 기록 실패 — 예외 없이 record_error, 시도는 REMOTE_OK(기록 복구 대기)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
st.fail_on.add("record_attempt_revision")
|
||||
out = _apply(st, api, "<p>B</p>")
|
||||
assert out.record_error and not out.revision_id
|
||||
attempt = st.attempts[out.attempt_id]
|
||||
assert attempt["status"] == store.ATTEMPT_REMOTE_OK and attempt["target_html"] == "<p>B</p>"
|
||||
# 기록이 없어도 확인된 쓰기로 본다 — 지연 중에도 B 를 보여준다
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>B</p>", store.SYNC_PENDING)
|
||||
# 다음 쓰기 때 기록을 채운다(다시 PUT 하지 않음)
|
||||
st.fail_on.clear()
|
||||
puts = len(cafe.puts())
|
||||
cafe.stale = None
|
||||
_apply(st, api, "<p>C</p>")
|
||||
assert attempt["status"] == store.ATTEMPT_RECORDED and attempt["target_html"] == ""
|
||||
assert len(cafe.puts()) == puts + 1 # C 쓰기 한 번뿐
|
||||
|
||||
|
||||
def test_07_unknown_result_blocks_rewrite_until_verified():
|
||||
"""[07] 응답 유실 — UNKNOWN. 확정 전에는 같은 상품 상세설명을 다시 쓰지 않는다.
|
||||
카페24 값이 그 시도의 결과와 같아지면(=반영됨) 자동으로 확정한다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
cafe.put_error = fakes.network_error(maybe_applied=True)
|
||||
try:
|
||||
_apply(st, api, "<p>B</p>")
|
||||
raise AssertionError("결과 모름을 성공/실패로 판정했다")
|
||||
except writes.RemoteWriteUnknown as exc:
|
||||
aid = exc.attempt_id
|
||||
assert st.attempts[aid]["status"] == store.ATTEMPT_UNKNOWN
|
||||
cafe.put_error = None
|
||||
try:
|
||||
_apply(st, api, "<p>C</p>")
|
||||
raise AssertionError("결과 모름 시도가 있는데 또 썼다")
|
||||
except writes.WriteBlocked:
|
||||
pass
|
||||
cafe.state.update(description="<p>B</p>") # 확인해 보니 반영돼 있었다
|
||||
_apply(st, api, "<p>C</p>")
|
||||
assert st.attempts[aid]["status"] == store.ATTEMPT_RECORDED
|
||||
assert [r["html_content"] for r in st.of_type(store.REVISION_MANUAL)] == ["<p>B</p>", "<p>C</p>"]
|
||||
|
||||
|
||||
def test_07_connect_error_is_definite_failure():
|
||||
"""연결조차 안 된 오류는 반영 안 됨이 확실 — UNKNOWN 이 아니라 REMOTE_FAILED."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
cafe.put_error = fakes.network_error(maybe_applied=False)
|
||||
try:
|
||||
_apply(st, fakes.FakeApi(cafe), "<p>B</p>")
|
||||
except writes.RemoteWriteFailed:
|
||||
pass
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_REMOTE_FAILED
|
||||
|
||||
|
||||
def test_rollback_records_rollback_revision():
|
||||
"""[13] 선택 복원은 정상 경로로 한 번 적용하고 ROLLBACK(원본 버전 표시)을 남긴다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
first = _apply(st, api, "<p>B</p>")
|
||||
backup = first.backup_id # A
|
||||
out = _apply(st, api, st.revisions[backup]["html_content"], fp=store.fingerprint("<p>B</p>"),
|
||||
origin=store.ORIGIN_ROLLBACK, target_revision_id=backup, memo=f"버전 {backup} 복원")
|
||||
assert cafe.state["description"] == "<p>A</p>"
|
||||
rb = st.revisions[out.revision_id]
|
||||
assert rb["revision_type"] == "ROLLBACK" and rb["source_revision_id"] == backup
|
||||
assert rb["html_content"] == "<p>A</p>"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 스냅샷 병합 · 품목 표기 · 옵션 모양 — [10][11]
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_11_variant_snapshot_field_merge():
|
||||
at = now_kst().isoformat()
|
||||
a = store.merge_variant_snapshot({}, {"V1": {"custom_variant_code": "C1"}}, at=at)
|
||||
b = store.merge_variant_snapshot(a, {"V1": {"display": "F"}}, at=at)
|
||||
assert b["V1"]["custom_variant_code"] == "C1" and b["V1"]["display"] == "F"
|
||||
|
||||
|
||||
def test_11_empty_patch_is_not_reset_but_replace_is():
|
||||
at = now_kst().isoformat()
|
||||
a = store.merge_variant_snapshot({}, {"V1": {"display": "F"}}, at=at)
|
||||
assert store.merge_variant_snapshot(a, {}, at=at) == a
|
||||
assert store.merge_variant_snapshot(a, {}, at=at, replace=True) == {}
|
||||
|
||||
|
||||
def test_11_deleted_variant_is_not_resurrected():
|
||||
at = now_kst().isoformat()
|
||||
a = store.merge_variant_snapshot({}, {"V1": {"_deleted": True}}, at=at)
|
||||
b = store.merge_variant_snapshot(a, {"V1": {"display": "T", "custom_variant_code": "X"}}, at=at)
|
||||
assert b["V1"].get("_deleted") is True and "custom_variant_code" not in b["V1"]
|
||||
v = store.apply_variant_patch({"variant_code": "V1"}, b["V1"], section_written_at=at, grace_minutes=60)
|
||||
assert v is None
|
||||
|
||||
|
||||
def test_11_per_code_grace():
|
||||
old = (now_kst() - timedelta(hours=10)).isoformat()
|
||||
patch = {"display": "F", "_at": old}
|
||||
v = store.apply_variant_patch({"variant_code": "V1", "display": "T"}, patch,
|
||||
section_written_at=now_kst().isoformat(), grace_minutes=60)
|
||||
assert v["display"] == "T" # 그 품목 기록은 유예시간이 지났다
|
||||
|
||||
|
||||
def test_10_lagging_variant_labels_matched_by_code():
|
||||
"""[10] 옵션값 이름 변경 직후 GET 품목이 옛 이름 — 품목코드 기록으로 새 이름을 보여준다."""
|
||||
at = now_kst().isoformat()
|
||||
patch = {"options": [{"name": "색상", "value": "Jet"}], "_options_before": [[{"name": "색상", "value": "Black"}]],
|
||||
"_at": at}
|
||||
lag = store.apply_variant_patch({"variant_code": "V1", "options": [{"name": "색상", "value": "Black"}]},
|
||||
patch, section_written_at=at, grace_minutes=60)
|
||||
assert lag["options"] == [{"name": "색상", "value": "Jet"}]
|
||||
ext = store.apply_variant_patch({"variant_code": "V1", "options": [{"name": "색상", "value": "Onyx"}]},
|
||||
patch, section_written_at=at, grace_minutes=60)
|
||||
assert ext["options"] == [{"name": "색상", "value": "Onyx"}] # 관리자에서 다시 고친 이름은 믿는다
|
||||
|
||||
|
||||
def test_10_options_overlay_respects_external_change():
|
||||
at = now_kst().isoformat()
|
||||
before = {"has_option": "T", "options": [{"option_name": "색상", "option_value": [{"option_text": "Black"}]}]}
|
||||
ours = {"has_option": "T", "options": [{"option_name": "색상", "option_value": [{"option_text": "Jet"}]}]}
|
||||
other = {"has_option": "T", "options": [{"option_name": "색상", "option_value": [{"option_text": "Onyx"}]}]}
|
||||
snap = {**ours, "_before_signatures": [store.options_signature(before)]}
|
||||
assert store.overlay_options(before, snapshot=snap, written_at=at, grace_minutes=60) == (snap, True)
|
||||
assert store.overlay_options(other, snapshot=snap, written_at=at, grace_minutes=60) == (other, False)
|
||||
assert store.overlay_options(ours, snapshot=snap, written_at=at, grace_minutes=60) == (ours, False)
|
||||
|
||||
|
||||
def test_05_recovery_decision_table():
|
||||
rd = store.recovery_decision
|
||||
assert rd(None, 0)[0] == store.RECOVER_RETRY
|
||||
assert rd(None, store.MAX_RETRY)[0] == store.RECOVER_FAIL
|
||||
assert rd({"status": "RECORDED"}, 0)[0] == store.RECOVER_SUCCESS
|
||||
assert rd({"status": "REMOTE_OK"}, 0)[0] == store.RECOVER_RECORD
|
||||
assert rd({"status": "REMOTE_FAILED"}, 0)[0] == store.RECOVER_RETRY
|
||||
assert rd({"status": "STARTED"}, 0)[0] == store.RECOVER_REVIEW
|
||||
assert rd({"status": "UNKNOWN"}, 99)[0] == store.RECOVER_REVIEW # 예산과 무관하게 사람 확인
|
||||
|
||||
|
||||
def test_resolve_description_updated_date_rule():
|
||||
lw = {"html_content": "B", "created_at": now_kst(), "remote_updated_at": "2026-09-30T10:05:00+09:00"}
|
||||
digests = {store.content_digest("A")}
|
||||
newer = store.resolve_description("A", last_write=lw, known_digests=digests, grace_minutes=60,
|
||||
fetched_updated="2026-09-30T10:06:00+09:00")
|
||||
same = store.resolve_description("A", last_write=lw, known_digests=digests, grace_minutes=60,
|
||||
fetched_updated="2026-09-30T10:05:00+09:00")
|
||||
older = store.resolve_description("A", last_write=lw, known_digests=digests, grace_minutes=60,
|
||||
fetched_updated="2026-09-30T10:00:00+09:00")
|
||||
assert newer == ("A", store.SYNC_EXTERNAL)
|
||||
assert same == ("B", store.SYNC_PENDING) and older == ("B", store.SYNC_PENDING)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 품목 일괄 수정 행별 결과 — [09]
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class _ChunkClient:
|
||||
def __init__(self, fail_chunk: int, error):
|
||||
self.fail_chunk = fail_chunk
|
||||
self.error = error
|
||||
self.n = 0
|
||||
|
||||
def put(self, path, *, json=None, **kw):
|
||||
self.n += 1
|
||||
if self.n == self.fail_chunk:
|
||||
raise self.error
|
||||
return {"variants": [{"variant_code": r["variant_code"], "display": r.get("display")} for r in json["requests"]]}
|
||||
|
||||
|
||||
def _codes(n):
|
||||
return [{"variant_code": f"P0000000{i:04d}", "display": "F"} for i in range(n)]
|
||||
|
||||
|
||||
def test_09_partial_chunk_failure_reports_per_row():
|
||||
rows = products.update_variants(_ChunkClient(2, Cafe24ApiError("거절", status=422)), 7, _codes(150))
|
||||
assert [r["status"] for r in rows[:100]] == ["ok"] * 100
|
||||
assert [r["status"] for r in rows[100:]] == ["failed"] * 50
|
||||
assert rows[0]["variant"]["display"] == "F" and rows[120]["error"] == "거절"
|
||||
|
||||
|
||||
def test_09_first_chunk_failure_still_sends_second():
|
||||
client = _ChunkClient(1, fakes.network_error(maybe_applied=True))
|
||||
rows = products.update_variants(client, 7, _codes(150))
|
||||
assert client.n == 2
|
||||
assert {r["status"] for r in rows[:100]} == {"unknown"}
|
||||
assert {r["status"] for r in rows[100:]} == {"ok"}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 전송 계층 — 쓰기 요청이 카페24에 닿았을 수 있는가(maybe_applied)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _client_with(handler):
|
||||
import httpx
|
||||
|
||||
from app.integrations.cafe24 import client as client_mod
|
||||
|
||||
class _Tokens:
|
||||
def get_access_token(self):
|
||||
return "AT"
|
||||
|
||||
def force_expire(self):
|
||||
pass
|
||||
|
||||
real = httpx.Client
|
||||
transport = httpx.MockTransport(handler)
|
||||
client_mod.httpx.Client = lambda **kw: real(transport=transport, **kw)
|
||||
client_mod.time.sleep = lambda *_a, **_k: None
|
||||
return client_mod.Cafe24Client(_config(), _Tokens(), min_interval=0), (client_mod, real)
|
||||
|
||||
|
||||
def _restore(saved):
|
||||
client_mod, real = saved
|
||||
client_mod.httpx.Client = real
|
||||
|
||||
|
||||
def test_client_maybe_applied_classification():
|
||||
import httpx
|
||||
|
||||
cases = [
|
||||
("PUT", lambda req: (_ for _ in ()).throw(httpx.ReadTimeout("t", request=req)), True),
|
||||
("PUT", lambda req: (_ for _ in ()).throw(httpx.ConnectError("c", request=req)), False),
|
||||
("PUT", lambda req: httpx.Response(500, json={"error": {"message": "서버"}}), True),
|
||||
("PUT", lambda req: httpx.Response(422, json={"error": {"message": "검증"}}), False),
|
||||
("GET", lambda req: (_ for _ in ()).throw(httpx.ReadTimeout("t", request=req)), False),
|
||||
]
|
||||
for method, handler, expected in cases:
|
||||
client, saved = _client_with(handler)
|
||||
try:
|
||||
client.request(method, "/admin/products/1", json={"request": {}} if method == "PUT" else None)
|
||||
raise AssertionError("오류가 나야 한다")
|
||||
except Cafe24ApiError as exc:
|
||||
assert exc.maybe_applied is expected, (method, expected, str(exc))
|
||||
finally:
|
||||
_restore(saved)
|
||||
|
||||
|
||||
def _run_all():
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
for fn in fns:
|
||||
|
||||
+223
-119
@@ -8,14 +8,28 @@
|
||||
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
||||
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
||||
|
||||
한 번에 한 건씩 처리한다
|
||||
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잠그고 PROCESSING 으로
|
||||
바꾼다. worker 가 실수로 두 개 떠도 같은 예약이 두 번 적용되지 않는다.
|
||||
한 번에 한 건씩, lease 로 잡는다 (마이그레이션 005)
|
||||
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잡아 PROCESSING + lease
|
||||
(만료 시각·token)로 바꾼다. worker 가 여럿이어도 같은 예약을 두 번 잡지 않는다.
|
||||
카페24에 쓰기 직전 lease 를 연장해 "아직 내 것인가"를 확인하고(펜싱), 결과는
|
||||
token 이 맞을 때만 남긴다 — 만료 뒤 늦게 끝난 worker 가 남의 결과를 덮지 않는다.
|
||||
|
||||
적용 순서는 화면 편집과 같다
|
||||
카페24 현재값 재조회 → BACKUP revision → PUT → SUCCESS + 감사로그
|
||||
실패하면 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시 시도하고,
|
||||
소진되면 FAILED 로 확정한다. 되돌리기는 쓰지 않는다.
|
||||
적용 순서는 화면 편집과 같다 (writes.write_product 공용)
|
||||
상품 잠금 → 카페24 현재값 재조회 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||
→ 시도 기록 → PUT → 버전(SCHEDULED)·스냅샷 기록
|
||||
예약 직전 백업도 읽기 지연을 보정한 값이다(카페24가 아직 옛 HTML 을 돌려줘도
|
||||
그것을 "직전 내용"으로 남기지 않는다). 백업의 source 로 관측값/확인된 적용값을 구분한다.
|
||||
|
||||
결과 분류
|
||||
카페24가 거절 → 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시, 소진되면 FAILED
|
||||
반영 여부 모름 → NEEDS_REVIEW (자동 재적용 금지 — 사람이 쇼핑몰을 보고 확정)
|
||||
반영 성공·기록 실패 → SUCCESS + "기록 복구 필요" 메모. 기록은 다음 주기에 채운다(재적용 없음)
|
||||
같은 상품을 다른 작업이 쓰는 중 → 재시도 횟수를 쓰지 않고 잠시 뒤 다시
|
||||
|
||||
중단 복구 (recover)
|
||||
lease 가 만료된 PROCESSING 은 그 예약의 마지막 쓰기 시도를 보고 판정한다
|
||||
(store.recovery_decision). 무조건 PENDING 으로 돌리지 않는다 — 카페24에 이미 반영됐을
|
||||
수 있기 때문이다. 카페24 현재값이 예약 결과와 같으면 반영된 것으로 확정한다.
|
||||
|
||||
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
||||
"""
|
||||
@@ -25,6 +39,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
from datetime import timedelta
|
||||
@@ -33,141 +48,230 @@ from typing import Any
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import read_lag_grace_minutes
|
||||
|
||||
logger = logging.getLogger("cafe24.worker")
|
||||
|
||||
ACTOR = "SCHEDULER"
|
||||
DEFAULT_LEASE_SEC = 600 # 한 건 처리(현재값 조회 + PUT + 확인)에 넉넉한 시간
|
||||
LEGACY_PROCESSING_MIN = 30 # lease 컬럼이 없는 옛 PROCESSING 을 만료로 볼 시간
|
||||
BUSY_RETRY_SECONDS = 30 # 같은 상품을 다른 작업이 쓰는 중일 때 다시 볼 간격
|
||||
SETUP_RETRY_SECONDS = 300 # 마이그레이션 미적용 등 설정 문제일 때 다시 볼 간격
|
||||
|
||||
|
||||
def _apply(store_db: Any, api: Any, row: dict[str, Any]) -> str:
|
||||
"""예약 1건 적용. 성공 시 사람이 읽을 요약 문자열."""
|
||||
def lease_seconds() -> int:
|
||||
try:
|
||||
value = int(str(os.getenv("CAFE24_SCHEDULE_LEASE_SEC") or "").strip())
|
||||
except ValueError:
|
||||
return DEFAULT_LEASE_SEC
|
||||
return max(60, value)
|
||||
|
||||
|
||||
def worker_owner() -> str:
|
||||
return f"{ACTOR}|{socket.gethostname()}:{os.getpid()}"
|
||||
|
||||
|
||||
def _summary(row: dict[str, Any]) -> str:
|
||||
return store.describe_schedule_action(
|
||||
has_html=bool(row.get("revision_id")),
|
||||
set_display=row.get("set_display"),
|
||||
set_selling=row.get("set_selling"),
|
||||
)
|
||||
|
||||
|
||||
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
|
||||
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
|
||||
retry_count = int(row.get("retry_count") or 0)
|
||||
schedule_id = int(row["id"])
|
||||
if store.can_retry(retry_count):
|
||||
wait = store.retry_backoff_seconds(retry_count)
|
||||
st.finish_schedule(
|
||||
schedule_id, token=token, status=store.STATUS_PENDING, error=error,
|
||||
next_retry_at=now_kst() + timedelta(seconds=wait), retry_count=retry_count + 1,
|
||||
)
|
||||
logger.warning("예약 #%s 상품 %s 실패 — %s초 후 재시도 (%s/%s): %s",
|
||||
schedule_id, row.get("product_no"), wait, retry_count + 1, store.MAX_RETRY, error)
|
||||
return store.STATUS_PENDING
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_FAILED, error=error)
|
||||
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=row.get("product_no"),
|
||||
schedule_id=schedule_id, result="FAIL", detail=error)
|
||||
logger.error("예약 #%s 상품 %s 최종 실패: %s", schedule_id, row.get("product_no"), error)
|
||||
return store.STATUS_FAILED
|
||||
|
||||
|
||||
def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
||||
"""lease 로 잡은 예약 1건 실행. 반환: 남긴 상태(또는 'LEASE_LOST')."""
|
||||
schedule_id = int(row["id"])
|
||||
product_no = int(row["product_no"])
|
||||
token = str(row.get("lease_token") or "")
|
||||
lease = lease_seconds()
|
||||
revision_id = row.get("revision_id")
|
||||
set_display = row.get("set_display")
|
||||
set_selling = row.get("set_selling")
|
||||
|
||||
html: str | None = None
|
||||
if revision_id:
|
||||
revision = store_db.get_revision(int(revision_id))
|
||||
if not revision:
|
||||
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
||||
html = revision.get("html_content") or ""
|
||||
if not html.strip():
|
||||
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||
def fence() -> bool:
|
||||
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
||||
|
||||
# 상세설명을 바꿀 때는 쓰기 직전 현재값을 읽어 백업한다(로컬 값을 믿지 않는다).
|
||||
backup_id = 0
|
||||
if html is not None:
|
||||
current = products.fetch_descriptions(api.client, product_no)
|
||||
backup_id = store_db.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=current.description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업",
|
||||
created_by=ACTOR,
|
||||
)
|
||||
if current.mobile_description and current.mobile_description != current.description:
|
||||
store_db.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=current.mobile_description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업 (모바일)",
|
||||
created_by=ACTOR,
|
||||
try:
|
||||
html: str | None = None
|
||||
if revision_id:
|
||||
revision = st.get_revision(int(revision_id))
|
||||
if not revision:
|
||||
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
||||
html = str(revision.get("html_content") or "")
|
||||
if not html.strip():
|
||||
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||
with writes.write_lock(
|
||||
st, writes.product_lock_key(product_no), actor=ACTOR,
|
||||
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
||||
) as lock:
|
||||
outcome = writes.write_product(
|
||||
st, api, product_no,
|
||||
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
||||
set_display=set_display, set_selling=set_selling,
|
||||
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
|
||||
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
|
||||
)
|
||||
except writes.WriteSetupError as exc:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
||||
next_retry_at=now_kst() + timedelta(seconds=SETUP_RETRY_SECONDS))
|
||||
logger.error("예약 #%s 실행 보류 — %s", schedule_id, exc)
|
||||
return store.STATUS_PENDING
|
||||
except writes.WriteBusy as exc:
|
||||
# 다른 작업이 같은 상품을 쓰는 중이거나 lease 를 잃었다. 재시도 횟수를 쓰지 않는다.
|
||||
# (lease 를 잃었으면 finish 는 token 이 안 맞아 아무것도 바꾸지 않는다.)
|
||||
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
||||
next_retry_at=now_kst() + timedelta(seconds=BUSY_RETRY_SECONDS))
|
||||
logger.info("예약 #%s 상품 %s 보류(%s): %s", schedule_id, product_no, "재대기" if done else "lease 잃음", exc)
|
||||
return store.STATUS_PENDING if done else "LEASE_LOST"
|
||||
except (writes.WriteBlocked, writes.RemoteWriteUnknown) as exc:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=str(exc))
|
||||
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||
schedule_id=schedule_id, result="UNKNOWN", detail=str(exc))
|
||||
logger.error("예약 #%s 상품 %s 확인 필요: %s", schedule_id, product_no, exc)
|
||||
return store.STATUS_NEEDS_REVIEW
|
||||
except (writes.RemoteWriteFailed, Cafe24Error) as exc:
|
||||
return _retry_or_fail(st, row, token, str(exc))
|
||||
except Exception as exc: # noqa: BLE001 — 카페24에 쓰기 전의 사고(원격 이후는 write_product 가 삼킨다)
|
||||
logger.exception("예약 #%s 처리 중 예상치 못한 오류(카페24 쓰기 전)", schedule_id)
|
||||
return _retry_or_fail(st, row, token, f"{type(exc).__name__}: {exc}")
|
||||
|
||||
# PC/모바일은 구분하지 않는다 — mobile_description 은 보내지 않고
|
||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제한다.
|
||||
# (mobile_description 을 직접 보내면 카페24가 그 설정을 "직접 등록"으로 바꿔버린다.)
|
||||
updated = products.update_product(
|
||||
api.client,
|
||||
product_no,
|
||||
description=html,
|
||||
separated_mobile_description="F" if html is not None else None,
|
||||
display=set_display,
|
||||
selling=set_selling,
|
||||
note = ""
|
||||
if outcome.record_error:
|
||||
note = f"카페24 반영 성공 · 로컬 기록 실패(자동 복구 예정, 재적용 안 함): {outcome.record_error}"
|
||||
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||
if not done:
|
||||
# 반영은 됐다. 결과를 못 남겼어도 lease 만료 후 recover 가 시도 기록(REMOTE_OK/RECORDED)을
|
||||
# 보고 SUCCESS 로 확정한다 — 다시 적용하지 않는다.
|
||||
logger.warning("예약 #%s 적용됨 — 결과 기록 실패(lease 잃음). 복구 단계가 확정합니다.", schedule_id)
|
||||
summary = _summary(row)
|
||||
writes.audit_safe(
|
||||
st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
|
||||
schedule_id=schedule_id, result="SUCCESS",
|
||||
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
|
||||
+ (f" / {note}" if note else ""),
|
||||
)
|
||||
# PUT 응답은 쓰기 직후의 실제 값이다 — 스냅샷으로 남겨 화면이 GET 의 읽기 지연에
|
||||
# 흔들리지 않게 한다(routes_products._load_product 가 덮어씌운다).
|
||||
if isinstance(updated, dict) and updated.get("product_no"):
|
||||
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||
return store.STATUS_SUCCESS
|
||||
|
||||
|
||||
def _verify_attempt(st: Any, api: Any, attempt: dict[str, Any]) -> bool:
|
||||
"""카페24 현재값이 그 시도의 결과와 같은가(같으면 반영된 것으로 확정해도 된다)."""
|
||||
try:
|
||||
product = products.get_product(api.client, int(attempt["product_no"]))
|
||||
except Cafe24Error as exc:
|
||||
logger.warning("시도 #%s 확인용 조회 실패: %s", attempt.get("id"), exc)
|
||||
return False
|
||||
return writes.attempt_matches_remote(attempt, product)
|
||||
|
||||
|
||||
def recover_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
||||
"""lease 만료 PROCESSING 1건 복구 판정 — 반환: 남긴 상태."""
|
||||
schedule_id = int(row["id"])
|
||||
token = str(row.get("lease_token") or "")
|
||||
attempt = st.latest_attempt_for_schedule(schedule_id) or None
|
||||
decision, note = store.recovery_decision(attempt, row.get("retry_count"))
|
||||
note = f"중단 복구: {note}"
|
||||
|
||||
if decision == store.RECOVER_REVIEW and attempt:
|
||||
try:
|
||||
store_db.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
||||
except Exception: # noqa: BLE001 — 스냅샷 실패가 예약 결과를 바꾸면 안 된다.
|
||||
logger.exception("예약 #%s 상품 %s 스냅샷 저장 실패", schedule_id, product_no)
|
||||
if html is not None:
|
||||
# 화면 편집(apply)과 동일 — 카페24 관리자 API 의 쓰기 직후 읽기 지연을
|
||||
# 여기서 짧게 흡수한다(쇼핑몰에는 바로 반영되지만 관리자 조회만 뒤쳐질 때가 있다).
|
||||
# 확인이 안 돼도 실패가 아니다 — 화면은 마지막 쓰기(SCHEDULED revision)를 기준으로
|
||||
# 그린다. 여기서 SCHEDULED revision 을 남겨야 그 기준이 생긴다.
|
||||
products.wait_for_description(api.client, product_no, html)
|
||||
store_db.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=html,
|
||||
revision_type=store.REVISION_SCHEDULED,
|
||||
memo=f"예약 #{schedule_id} 적용",
|
||||
created_by=ACTOR,
|
||||
)
|
||||
with writes.write_lock(st, writes.product_lock_key(int(row["product_no"])), actor=ACTOR,
|
||||
purpose=f"예약 #{schedule_id} 복구 확인", wait_seconds=0):
|
||||
if _verify_attempt(st, api, attempt):
|
||||
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by="auto:카페24 값이 예약 결과와 같음",
|
||||
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||
decision, note = store.RECOVER_RECORD, "중단 복구: 카페24 현재값이 예약 결과와 같아 반영됨으로 확정"
|
||||
except writes.WriteBusy:
|
||||
pass # 다음 주기에 다시 — 판정은 REVIEW 로 남긴다
|
||||
if decision == store.RECOVER_RECORD and attempt:
|
||||
try:
|
||||
writes.record_attempt(st, attempt)
|
||||
except Exception as exc: # noqa: BLE001 — 반영은 됐다. 기록은 다음 주기에.
|
||||
logger.exception("예약 #%s 복구 중 버전 기록 실패", schedule_id)
|
||||
note += f" (버전 기록 실패 — 자동 재시도: {type(exc).__name__})"
|
||||
decision = store.RECOVER_SUCCESS
|
||||
|
||||
summary = store.describe_schedule_action(
|
||||
has_html=html is not None, set_display=set_display, set_selling=set_selling
|
||||
if decision == store.RECOVER_SUCCESS:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||
status = store.STATUS_SUCCESS
|
||||
elif decision == store.RECOVER_REVIEW:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=note)
|
||||
status = store.STATUS_NEEDS_REVIEW
|
||||
else:
|
||||
status = _retry_or_fail(st, row, token, note)
|
||||
writes.audit_safe(st, actor=ACTOR, action="schedule_recover", product_no=row.get("product_no"),
|
||||
schedule_id=schedule_id, result=status, detail=note)
|
||||
logger.warning("예약 #%s 중단 복구 → %s (%s)", schedule_id, status, note)
|
||||
return status
|
||||
|
||||
|
||||
def record_pending_attempts(st: Any) -> int:
|
||||
"""카페24에 반영됐는데 버전 기록이 빠진 시도(REMOTE_OK)의 기록을 채운다."""
|
||||
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||
done = 0
|
||||
for attempt in st.attempts_needing_record(since=since):
|
||||
try:
|
||||
with writes.write_lock(st, writes.product_lock_key(int(attempt["product_no"])), actor=ACTOR,
|
||||
purpose="기록 복구", wait_seconds=0):
|
||||
writes.record_attempt(st, attempt)
|
||||
done += 1
|
||||
except writes.WriteBusy:
|
||||
continue
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
|
||||
return done
|
||||
|
||||
|
||||
def recover(st: Any, api: Any) -> int:
|
||||
"""중단 복구 — 기록 복구 + lease 만료 PROCESSING 판정. 처리 건수."""
|
||||
count = record_pending_attempts(st)
|
||||
rows = st.claim_expired_schedules(
|
||||
owner=worker_owner(), ttl_seconds=lease_seconds(), legacy_minutes=LEGACY_PROCESSING_MIN
|
||||
)
|
||||
store_db.log_audit(
|
||||
actor=ACTOR,
|
||||
action="schedule_apply",
|
||||
product_no=product_no,
|
||||
revision_id=int(revision_id) if revision_id else None,
|
||||
schedule_id=schedule_id,
|
||||
result="SUCCESS",
|
||||
detail=summary + (f" (백업 {backup_id})" if backup_id else ""),
|
||||
)
|
||||
return summary
|
||||
for row in rows:
|
||||
try:
|
||||
recover_one(st, api, row)
|
||||
except Exception: # noqa: BLE001 — 한 건 때문에 나머지를 멈추지 않는다(lease 만료 후 다시)
|
||||
logger.exception("예약 #%s 복구 중 오류", row.get("id"))
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def process_once(store_db: Any, api: Any) -> int:
|
||||
"""실행할 예약을 모두 처리한다. 처리한 건수를 돌려준다."""
|
||||
def process_once(st: Any, api: Any) -> int:
|
||||
"""중단 복구 후, 실행할 예약을 모두 처리한다. 처리한(잡은) 예약 건수를 돌려준다."""
|
||||
try:
|
||||
recover(st, api)
|
||||
except Exception: # noqa: BLE001 — 복구 실패가 새 예약 실행을 막지 않게
|
||||
logger.exception("중단 복구 단계 오류 — 다음 주기에 다시 시도")
|
||||
handled = 0
|
||||
while True:
|
||||
with store_db.claim_due_schedule(now=now_kst()) as row:
|
||||
if row is None:
|
||||
return handled
|
||||
# 잠금은 여기서 이미 풀렸다. 상태가 PROCESSING 이라 다른 worker 가 집지 않는다.
|
||||
schedule_id = int(row["id"])
|
||||
product_no = int(row["product_no"])
|
||||
try:
|
||||
summary = _apply(store_db, api, row)
|
||||
except Cafe24Error as exc:
|
||||
retry_count = int(row.get("retry_count") or 0)
|
||||
if store.can_retry(retry_count):
|
||||
wait = store.retry_backoff_seconds(retry_count)
|
||||
store_db.finish_schedule(
|
||||
schedule_id,
|
||||
status=store.STATUS_PENDING,
|
||||
error=str(exc),
|
||||
next_retry_at=now_kst() + timedelta(seconds=wait),
|
||||
retry_count=retry_count + 1,
|
||||
)
|
||||
logger.warning(
|
||||
"예약 #%s 상품 %s 실패 — %s초 후 재시도 (%s/%s): %s",
|
||||
schedule_id, product_no, wait, retry_count + 1, store.MAX_RETRY, exc,
|
||||
)
|
||||
else:
|
||||
store_db.finish_schedule(
|
||||
schedule_id, status=store.STATUS_FAILED, error=str(exc)
|
||||
)
|
||||
store_db.log_audit(
|
||||
actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||
schedule_id=schedule_id, result="FAIL", detail=str(exc),
|
||||
)
|
||||
logger.error("예약 #%s 상품 %s 최종 실패: %s", schedule_id, product_no, exc)
|
||||
except Exception as exc: # noqa: BLE001 — 한 건의 사고가 worker 를 죽이면 안 된다.
|
||||
store_db.finish_schedule(
|
||||
schedule_id, status=store.STATUS_FAILED, error=f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
logger.exception("예약 #%s 처리 중 예상치 못한 오류", schedule_id)
|
||||
else:
|
||||
store_db.finish_schedule(schedule_id, status=store.STATUS_SUCCESS)
|
||||
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||
row = st.claim_due_schedule(now=now_kst(), owner=worker_owner(), ttl_seconds=lease_seconds())
|
||||
if row is None:
|
||||
return handled
|
||||
run_one(st, api, row)
|
||||
handled += 1
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,531 @@
|
||||
"""카페24 쓰기 공통 처리 — 잠금 · 유효 현재값 판정 · 백업 · 시도 기록 · 결과 분류.
|
||||
|
||||
상세설명(과 예약의 진열/판매)을 카페24에 쓰는 모든 경로 — 즉시 적용, 버전 복원,
|
||||
예약 worker — 가 `write_product` 한 곳을 지난다. 경로마다 판정이 달라 생기던 문제
|
||||
(예약 직전 백업이 지연된 옛 HTML 을 담는 등)를 막기 위해서다.
|
||||
|
||||
순서 (docs/CAFE24_MODULE.md 3-2, 3-5)
|
||||
상품 잠금(DB lease) → 카페24 현재값 GET → 결과 모르는 이전 시도 확인
|
||||
→ 유효 현재값(읽기 지연 보정) → BACKUP → 지문 대조(충돌 거부)
|
||||
→ 잠금 펜싱 → 시도 기록(STARTED) → PUT
|
||||
→ 원격 결과 분류(REMOTE_OK / REMOTE_FAILED / UNKNOWN)
|
||||
→ 스냅샷 · 버전(MANUAL/SCHEDULED/ROLLBACK) 기록(RECORDED)
|
||||
|
||||
원칙
|
||||
- 읽기 지연 판정의 근거는 **원격 반영이 확인된 쓰기**(cafe24_write_attempts 의
|
||||
REMOTE_OK/RECORDED)뿐이다. 충돌로 거절된 적용의 백업·예약 초안은 넣지 않는다.
|
||||
- PUT 이 성공한 뒤의 실패(스냅샷·버전 기록)는 "적용 실패"가 아니다. 결과에
|
||||
record_error 로 알리고, 시도 기록(REMOTE_OK)에 남은 내용으로 나중에 복구한다.
|
||||
재적용하지 않는다.
|
||||
- 반영 여부를 모르는 시도(STARTED/UNKNOWN)가 남아 있으면 같은 상품 상세설명을
|
||||
다시 쓰지 않는다(WriteBlocked). 카페24 값이 그 시도의 내용과 같으면 자동 확정.
|
||||
- 잠금은 웹 여러 프로세스 + worker 가 공유하는 DB 표(cafe24_write_locks)다.
|
||||
카페24 관리자 화면에서 사람이 동시에 고치는 것은 막을 수 없다 — 그것은 지문
|
||||
대조(편집 시작 시점 값과 비교)로만 잡는다.
|
||||
|
||||
카페24 호출은 `app.integrations.cafe24` 만 쓴다(httpx 직접 호출 금지).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import timedelta
|
||||
from typing import Any, Callable, Iterator
|
||||
|
||||
from app.integrations.cafe24 import Cafe24Error, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from .common import read_lag_grace_minutes
|
||||
|
||||
logger = logging.getLogger("cafe24.writes")
|
||||
|
||||
DEFAULT_LOCK_TTL_SEC = 300 # 이미지 업로드(최대 120초 × 재시도)도 담을 만큼
|
||||
DEFAULT_LOCK_WAIT_SEC = 3.0 # 웹 요청은 짧게만 기다린다 — 오래 걸리면 "수정 중" 안내
|
||||
|
||||
|
||||
def _env_number(name: str, default: float) -> float:
|
||||
try:
|
||||
value = float(str(os.getenv(name) or "").strip())
|
||||
except ValueError:
|
||||
return default
|
||||
return value if value >= 0 else default
|
||||
|
||||
|
||||
def lock_ttl_seconds() -> int:
|
||||
return max(30, int(_env_number("CAFE24_WRITE_LOCK_TTL_SEC", DEFAULT_LOCK_TTL_SEC)))
|
||||
|
||||
|
||||
def lock_wait_seconds() -> float:
|
||||
return min(30.0, _env_number("CAFE24_WRITE_LOCK_WAIT_SEC", DEFAULT_LOCK_WAIT_SEC))
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 예외 — http_status 는 JSON API 가 그대로 쓴다
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class WriteError(Exception):
|
||||
http_status = 500
|
||||
|
||||
def __init__(self, message: str, *, backup_id: int = 0, attempt_id: int = 0):
|
||||
super().__init__(message)
|
||||
self.backup_id = backup_id
|
||||
self.attempt_id = attempt_id
|
||||
|
||||
|
||||
class WriteSetupError(WriteError):
|
||||
"""마이그레이션 005 미적용 등 — 안전장치 없이 쓰지 않는다."""
|
||||
|
||||
http_status = 503
|
||||
|
||||
|
||||
class WriteBusy(WriteError):
|
||||
"""다른 요청(또는 예약 실행)이 같은 대상을 쓰는 중이거나, 잠금을 잃었다."""
|
||||
|
||||
http_status = 409
|
||||
|
||||
|
||||
class WriteConflict(WriteError):
|
||||
"""편집 시작 뒤 카페24 값이 바뀌었다(지문 불일치)."""
|
||||
|
||||
http_status = 409
|
||||
|
||||
|
||||
class WriteBlocked(WriteError):
|
||||
"""반영 여부를 모르는 이전 시도가 남아 있다 — 사람이 확정하기 전에는 쓰지 않는다."""
|
||||
|
||||
http_status = 409
|
||||
|
||||
def __init__(self, message: str, *, attempts: list[dict[str, Any]] | None = None, **kw: Any):
|
||||
super().__init__(message, **kw)
|
||||
self.attempts = attempts or []
|
||||
|
||||
|
||||
class RemoteWriteFailed(WriteError):
|
||||
"""카페24가 거절 — 반영되지 않은 것이 확실하다."""
|
||||
|
||||
http_status = 502
|
||||
|
||||
|
||||
class RemoteWriteUnknown(WriteError):
|
||||
"""요청이 도달했을 수 있으나 응답을 못 받았다 — 반영 여부를 모른다. 재적용 금지."""
|
||||
|
||||
http_status = 502
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 잠금
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def product_lock_key(product_no: int) -> str:
|
||||
return f"product:{int(product_no)}"
|
||||
|
||||
|
||||
def design_lock_key(file_key: str) -> str:
|
||||
return f"design:{file_key}"
|
||||
|
||||
|
||||
def lock_owner(actor: str) -> str:
|
||||
"""잠금 소유자 표기 — '사람|호스트:pid'. 안내 문구에는 '|' 앞(사람)만 쓴다."""
|
||||
return f"{actor or '-'}|{socket.gethostname()}:{os.getpid()}"
|
||||
|
||||
|
||||
def require_schema(st: Any) -> None:
|
||||
try:
|
||||
ok = st.write_schema_ready()
|
||||
except Exception as exc: # noqa: BLE001 — DB 접속 실패도 "쓰지 않음"으로
|
||||
raise WriteSetupError(f"cafe24_db 상태를 확인하지 못해 카페24에 쓰지 않았습니다: {type(exc).__name__}") from exc
|
||||
if not ok:
|
||||
raise WriteSetupError(
|
||||
"cafe24_db 마이그레이션 005(쓰기 안전장치)가 적용되지 않아 카페24에 쓰지 않았습니다. "
|
||||
"관리자에게 scripts/sql/cafe24_db_005_write_safety.sql 적용을 요청하세요."
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WriteLock:
|
||||
st: Any
|
||||
key: str
|
||||
token: str
|
||||
ttl: int
|
||||
|
||||
def still_mine(self) -> bool:
|
||||
"""아직 내 잠금이면 연장하고 True(펜싱). 만료돼 넘어갔으면 False."""
|
||||
try:
|
||||
return bool(self.st.renew_lock(self.key, self.token, ttl_seconds=self.ttl))
|
||||
except Exception: # noqa: BLE001 — 확인할 수 없으면 쓰지 않는다
|
||||
logger.exception("잠금 연장 실패 %s", self.key)
|
||||
return False
|
||||
|
||||
|
||||
@contextmanager
|
||||
def write_lock(
|
||||
st: Any,
|
||||
key: str,
|
||||
*,
|
||||
actor: str,
|
||||
purpose: str,
|
||||
wait_seconds: float | None = None,
|
||||
ttl_seconds: int | None = None,
|
||||
) -> Iterator[WriteLock]:
|
||||
"""DB 잠금을 잡은 채 작업한다. 못 잡으면 WriteBusy, 스키마가 없으면 WriteSetupError."""
|
||||
require_schema(st)
|
||||
ttl = int(ttl_seconds or lock_ttl_seconds())
|
||||
wait = lock_wait_seconds() if wait_seconds is None else max(0.0, float(wait_seconds))
|
||||
deadline = time.monotonic() + wait
|
||||
while True:
|
||||
token = st.acquire_lock(key, owner=lock_owner(actor), purpose=purpose, ttl_seconds=ttl)
|
||||
if token:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise WriteBusy(_busy_message(st, key))
|
||||
time.sleep(0.25)
|
||||
lock = WriteLock(st=st, key=key, token=token, ttl=ttl)
|
||||
try:
|
||||
yield lock
|
||||
finally:
|
||||
try:
|
||||
st.release_lock(key, token)
|
||||
except Exception: # noqa: BLE001 — 못 풀어도 만료되면 풀린다
|
||||
logger.exception("잠금 해제 실패 %s (만료 후 자동 해제)", key)
|
||||
|
||||
|
||||
def _busy_message(st: Any, key: str) -> str:
|
||||
try:
|
||||
holder = st.lock_holder(key) or {}
|
||||
except Exception: # noqa: BLE001
|
||||
holder = {}
|
||||
who = str(holder.get("owner") or "").split("|", 1)[0]
|
||||
what = str(holder.get("purpose") or "")
|
||||
detail = " · ".join(p for p in (what, who) if p and p != "-")
|
||||
return "다른 작업이 같은 대상을 수정하고 있습니다" + (f"({detail})" if detail else "") + ". 잠시 후 다시 시도하세요."
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 유효 현재값 — 읽기 지연 보정 (확인된 쓰기만 근거)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def resolve_effective(
|
||||
st: Any, product_no: int, cafe24_html: str, *, fetched_updated: object = None
|
||||
) -> tuple[str, str, dict[str, Any] | None]:
|
||||
"""(유효 HTML, 상태 store.SYNC_*, 마지막 확인된 쓰기)."""
|
||||
grace = read_lag_grace_minutes()
|
||||
since = now_kst() - timedelta(minutes=grace)
|
||||
lineage = st.write_lineage(product_no, since=since)
|
||||
if not lineage:
|
||||
return cafe24_html, store.SYNC_NONE, None
|
||||
last = lineage[0]
|
||||
effective, state = store.resolve_description(
|
||||
cafe24_html,
|
||||
last_write=last,
|
||||
known_digests=store.lineage_digests(lineage),
|
||||
grace_minutes=grace,
|
||||
fetched_updated=fetched_updated,
|
||||
)
|
||||
return effective, state, last
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 기록 — PUT 성공 뒤의 로컬 저장(실패해도 "적용 실패"가 아니다)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def remember_product_write(st: Any, product_no: int, updated: dict[str, Any]) -> tuple[dict[str, Any], str]:
|
||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. (정규화된 상품 행, 기록 오류 문자열)."""
|
||||
info = products.normalize_product(updated) if updated else {}
|
||||
if not info.get("product_no"):
|
||||
return info, ""
|
||||
try:
|
||||
st.upsert_products([info])
|
||||
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
||||
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
|
||||
logger.exception("상품 %s 쓰기 스냅샷 저장 실패", product_no)
|
||||
return info, f"{type(exc).__name__}: {exc}"
|
||||
return info, ""
|
||||
|
||||
|
||||
def audit_safe(st: Any, **fields: Any) -> None:
|
||||
"""감사로그 — 실패해도 호출부 결과를 바꾸지 않는다(이미 카페24에 반영된 뒤일 수 있다)."""
|
||||
try:
|
||||
st.log_audit(**fields)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("감사로그 기록 실패: %s", fields.get("action"))
|
||||
|
||||
|
||||
def record_attempt(st: Any, attempt: dict[str, Any]) -> int:
|
||||
"""원격 반영된 시도의 버전을 남기고 RECORDED 로 바꾼다(이미 있으면 그 id). 멱등.
|
||||
|
||||
진열/판매만 바꾼 시도(상세설명 없음)는 버전을 만들지 않고 상태만 RECORDED 로 둔다.
|
||||
"""
|
||||
if not attempt.get("target_digest") and not attempt.get("target_revision_id"):
|
||||
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_RECORDED, remote_ok=True)
|
||||
return 0
|
||||
origin = str(attempt.get("origin") or store.ORIGIN_MANUAL)
|
||||
revision_type = store.ORIGIN_REVISION_TYPE.get(origin, "MANUAL")
|
||||
source = store.SOURCE_REVISION if origin == store.ORIGIN_ROLLBACK else ""
|
||||
source_revision = attempt.get("target_revision_id") if origin != store.ORIGIN_MANUAL else None
|
||||
return int(st.record_attempt_revision(
|
||||
int(attempt["id"]),
|
||||
revision_type=revision_type,
|
||||
memo=str(attempt.get("memo") or ""),
|
||||
created_by=str(attempt.get("actor") or ""),
|
||||
source=source,
|
||||
source_revision_id=int(source_revision) if source_revision else None,
|
||||
))
|
||||
|
||||
|
||||
def _flags_match(product: dict[str, Any], attempt: dict[str, Any]) -> bool:
|
||||
for key in ("set_display", "set_selling"):
|
||||
want = attempt.get(key)
|
||||
if want is None:
|
||||
continue
|
||||
field_name = key.replace("set_", "")
|
||||
if products._flag(product.get(field_name)) != bool(want): # noqa: SLF001 — 같은 규칙
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def attempt_matches_remote(attempt: dict[str, Any], product: dict[str, Any]) -> bool:
|
||||
"""카페24 현재값이 그 시도가 쓰려던 결과와 같은가(같으면 결과를 "반영됨"으로 확정해도 된다)."""
|
||||
if not product:
|
||||
return False
|
||||
digest = str(attempt.get("target_digest") or "")
|
||||
if digest and store.content_digest(str(product.get("description") or "")) != digest:
|
||||
return False
|
||||
if not digest and attempt.get("set_display") is None and attempt.get("set_selling") is None:
|
||||
return False
|
||||
return _flags_match(product, attempt)
|
||||
|
||||
|
||||
def settle_open_attempts(
|
||||
st: Any, product_no: int, *, product: dict[str, Any], actor: str = "SYSTEM"
|
||||
) -> list[dict[str, Any]]:
|
||||
"""열린 시도를 정리하고 **아직 결과를 모르는 것**만 돌려준다. 잠금 안에서 부른다.
|
||||
|
||||
REMOTE_OK → 버전 기록을 채운다(기록 복구)
|
||||
STARTED / UNKNOWN → 카페24 현재값이 그 시도의 결과와 같으면 반영됨으로 확정
|
||||
(예약이 "확인 필요"였다면 완료로 바꾼다). 다르면 남긴다.
|
||||
"""
|
||||
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||
unresolved: list[dict[str, Any]] = []
|
||||
for attempt in st.open_attempts(product_no, since=since):
|
||||
status = attempt.get("status")
|
||||
if status == store.ATTEMPT_REMOTE_OK:
|
||||
try:
|
||||
record_attempt(st, attempt)
|
||||
except Exception: # noqa: BLE001 — 원격은 반영됨. 다음 기회에 다시.
|
||||
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
|
||||
continue
|
||||
if attempt_matches_remote(attempt, product):
|
||||
st.update_attempt(
|
||||
int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by="auto:카페24 값이 요청 결과와 같음",
|
||||
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN),
|
||||
)
|
||||
try:
|
||||
record_attempt(st, attempt)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("시도 #%s 기록 실패(자동 확정 후)", attempt.get("id"))
|
||||
if attempt.get("schedule_id"):
|
||||
st.review_schedule(
|
||||
int(attempt["schedule_id"]), status=store.STATUS_SUCCESS,
|
||||
note="자동 확인: 카페24 현재값이 예약 내용과 같습니다", actor=actor, action="auto_verify",
|
||||
)
|
||||
continue
|
||||
unresolved.append(attempt)
|
||||
return unresolved
|
||||
|
||||
|
||||
def describe_attempt(attempt: dict[str, Any]) -> str:
|
||||
origin = {store.ORIGIN_MANUAL: "즉시 적용", store.ORIGIN_SCHEDULED: "예약", store.ORIGIN_ROLLBACK: "복원"}.get(
|
||||
str(attempt.get("origin") or ""), "적용")
|
||||
when = str(attempt.get("created_at") or "").replace("T", " ")[:16]
|
||||
who = str(attempt.get("actor") or "")
|
||||
sched = f" · 예약 #{attempt['schedule_id']}" if attempt.get("schedule_id") else ""
|
||||
return f"시도 #{attempt.get('id')} ({origin}{sched}, {when}{', ' + who if who else ''})"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 본 처리
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@dataclass
|
||||
class WriteOutcome:
|
||||
attempt_id: int = 0
|
||||
backup_id: int = 0
|
||||
revision_id: int = 0
|
||||
changed: bool = True # False = 바뀐 것이 없어 PUT 하지 않음
|
||||
pending: bool = False # 백업이 "마지막 확인된 쓰기" 기준이었나(카페24 읽기 지연)
|
||||
recorded: bool = False # 버전 기록까지 끝났나
|
||||
record_error: str = "" # PUT 성공 뒤 로컬 기록 실패 사유(재적용 금지 — 자동 복구)
|
||||
confirmed: bool = False # PUT 뒤 GET 이 새 값을 돌려줬나
|
||||
updated: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def write_product(
|
||||
st: Any,
|
||||
api: Any,
|
||||
product_no: int,
|
||||
*,
|
||||
lock: WriteLock,
|
||||
origin: str,
|
||||
actor: str,
|
||||
html: str | None,
|
||||
base_fingerprint: str | None = None,
|
||||
set_display: bool | None = None,
|
||||
set_selling: bool | None = None,
|
||||
schedule_id: int | None = None,
|
||||
target_revision_id: int | None = None,
|
||||
memo: str = "",
|
||||
skip_if_same: bool = False,
|
||||
extra_fence: Callable[[], bool] | None = None,
|
||||
wait_confirm: bool = True,
|
||||
) -> WriteOutcome:
|
||||
"""상세설명(html)·진열/판매를 카페24에 쓴다. 잠금(lock)을 잡은 채 부른다.
|
||||
|
||||
예외(아무것도 쓰지 않음): Cafe24Error(현재값 조회 실패), WriteBlocked, WriteConflict,
|
||||
WriteBusy(펜싱 실패) / RemoteWriteFailed(거절) / RemoteWriteUnknown(반영 여부 모름).
|
||||
PUT 성공 뒤의 로컬 기록 실패는 예외가 아니라 WriteOutcome.record_error 로 알린다.
|
||||
"""
|
||||
mall_id = str(getattr(api.config, "mall_id", "") or "")
|
||||
shop_no = 1
|
||||
out = WriteOutcome()
|
||||
current_html: str | None = None
|
||||
effective: str | None = None
|
||||
|
||||
if html is not None:
|
||||
product = products.get_product(api.client, product_no)
|
||||
if not product:
|
||||
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
|
||||
desc = products.descriptions_from_product(product)
|
||||
current_html = desc.description
|
||||
|
||||
unresolved = [a for a in settle_open_attempts(st, product_no, product=product, actor=actor)
|
||||
if a.get("target_digest")]
|
||||
if unresolved:
|
||||
names = ", ".join(describe_attempt(a) for a in unresolved[:3])
|
||||
raise WriteBlocked(
|
||||
f"이전 적용의 반영 여부를 아직 확인하지 못했습니다: {names}. "
|
||||
"쇼핑몰에서 확인한 뒤 편집기 위 안내에서 결과를 확정하고 다시 시도하세요.",
|
||||
attempts=unresolved,
|
||||
)
|
||||
|
||||
effective, state, last = resolve_effective(
|
||||
st, product_no, current_html, fetched_updated=product.get("updated_date")
|
||||
)
|
||||
out.pending = state == store.SYNC_PENDING
|
||||
label = {store.ORIGIN_SCHEDULED: f"예약 #{schedule_id} 적용 직전 자동 백업",
|
||||
store.ORIGIN_ROLLBACK: "복원 직전 자동 백업"}.get(origin, "적용 직전 자동 백업")
|
||||
out.backup_id = st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=effective,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=label + (" (카페24 읽기 지연 — 마지막으로 확인된 적용값 기준)" if out.pending else ""),
|
||||
created_by=actor,
|
||||
mall_id=mall_id,
|
||||
shop_no=shop_no,
|
||||
source=store.SOURCE_LAST_WRITE if out.pending else store.SOURCE_OBSERVED,
|
||||
source_revision_id=(last or {}).get("applied_revision_id") if out.pending else None,
|
||||
)
|
||||
# 모바일이 PC 와 달랐다면 그것도 남긴다 — 아래 쓰기로 모바일이 PC 와 같아진다.
|
||||
if desc.mobile_description and desc.mobile_description != desc.description:
|
||||
st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=desc.mobile_description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=label + " (모바일 — PC와 달랐던 내용)",
|
||||
created_by=actor,
|
||||
mall_id=mall_id,
|
||||
shop_no=shop_no,
|
||||
source=store.SOURCE_OBSERVED,
|
||||
)
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(effective):
|
||||
raise WriteConflict(
|
||||
"편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
||||
backup_id=out.backup_id,
|
||||
)
|
||||
if skip_if_same and html == effective and set_display is None and set_selling is None:
|
||||
out.changed = False
|
||||
return out
|
||||
|
||||
# 펜싱 — 잠금이 만료돼 남에게 넘어갔으면 쓰지 않는다.
|
||||
if not lock.still_mine() or (extra_fence is not None and not extra_fence()):
|
||||
raise WriteBusy("작업 시간이 길어져 잠금이 만료되었습니다. 카페24에 쓰지 않았습니다 — 다시 시도하세요.",
|
||||
backup_id=out.backup_id)
|
||||
|
||||
out.attempt_id = st.start_attempt(
|
||||
product_no=int(product_no),
|
||||
mall_id=mall_id,
|
||||
shop_no=shop_no,
|
||||
origin=origin,
|
||||
schedule_id=schedule_id,
|
||||
actor=actor,
|
||||
backup_revision_id=out.backup_id or None,
|
||||
observed_digest=store.content_digest(current_html) if current_html is not None else "",
|
||||
base_digest=store.content_digest(effective) if effective is not None else "",
|
||||
target_digest=store.content_digest(html) if html is not None else "",
|
||||
# 예약·복원은 내용이 버전(target_revision_id)에 있다 — 즉시 적용만 시도에 보관한다.
|
||||
target_html=html if (html is not None and not target_revision_id) else "",
|
||||
target_revision_id=target_revision_id,
|
||||
set_display=set_display,
|
||||
set_selling=set_selling,
|
||||
memo=(memo or "")[:500],
|
||||
)
|
||||
|
||||
try:
|
||||
updated = products.update_product(
|
||||
api.client,
|
||||
product_no,
|
||||
description=html,
|
||||
# PC/모바일 구분 안 함 — mobile_description 은 보내지 않고 "PC 와 동일"을 강제.
|
||||
separated_mobile_description="F" if html is not None else None,
|
||||
display=set_display,
|
||||
selling=set_selling,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 — 분류해서 다시 던진다
|
||||
known = isinstance(exc, Cafe24Error)
|
||||
unknown = (not known) or bool(getattr(exc, "maybe_applied", False))
|
||||
message = str(exc) if known else f"{type(exc).__name__}: {exc}"
|
||||
try:
|
||||
st.update_attempt(
|
||||
out.attempt_id,
|
||||
status=store.ATTEMPT_UNKNOWN if unknown else store.ATTEMPT_REMOTE_FAILED,
|
||||
error=message,
|
||||
only_from=(store.ATTEMPT_STARTED,),
|
||||
)
|
||||
except Exception: # noqa: BLE001 — 기록 실패 시 STARTED 로 남는다(= 결과 모름, 안전 쪽)
|
||||
logger.exception("시도 #%s 결과 기록 실패", out.attempt_id)
|
||||
kind = RemoteWriteUnknown if unknown else RemoteWriteFailed
|
||||
raise kind(message, backup_id=out.backup_id, attempt_id=out.attempt_id) from exc
|
||||
|
||||
# ── 여기부터는 카페24에 반영된 뒤다. 무엇이 실패해도 "적용 실패"가 아니다. ──
|
||||
out.updated = updated if isinstance(updated, dict) else {}
|
||||
errors: list[str] = []
|
||||
try:
|
||||
st.update_attempt(
|
||||
out.attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
remote_updated_at=str(out.updated.get("updated_date") or ""),
|
||||
only_from=(store.ATTEMPT_STARTED,),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("시도 #%s REMOTE_OK 기록 실패", out.attempt_id)
|
||||
errors.append(f"시도 상태: {type(exc).__name__}")
|
||||
if out.updated.get("product_no"):
|
||||
_, snap_error = remember_product_write(st, product_no, out.updated)
|
||||
if snap_error:
|
||||
errors.append(f"스냅샷: {snap_error}")
|
||||
try:
|
||||
out.revision_id = record_attempt(st, {
|
||||
"id": out.attempt_id, "origin": origin, "actor": actor, "memo": memo,
|
||||
"target_revision_id": target_revision_id,
|
||||
"target_digest": store.content_digest(html) if html is not None else "",
|
||||
})
|
||||
out.recorded = True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("시도 #%s 버전 기록 실패", out.attempt_id)
|
||||
errors.append(f"버전 기록: {type(exc).__name__}: {exc}")
|
||||
out.record_error = "; ".join(errors)
|
||||
|
||||
if html is not None and wait_confirm:
|
||||
# 카페24 관리자 API 의 쓰기 직후 읽기 지연을 짧게 흡수(확인 실패는 실패가 아니다).
|
||||
out.confirmed = products.wait_for_description(api.client, product_no, html)
|
||||
return out
|
||||
@@ -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,253 @@
|
||||
"""① 쇼핑몰 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)
|
||||
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
|
||||
}
|
||||
|
||||
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"
|
||||
|
||||
|
||||
class Cancelled(AdapterError):
|
||||
"""사용자가 매출 업데이트를 취소함 — 어댑터가 ctx.progress.check() 에서 받는다. 연결 오류가 아니다."""
|
||||
status = "cancelled"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 설정 입력칸 · 공통 매출 사건
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@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: ...
|
||||
|
||||
|
||||
class Progress:
|
||||
"""수집 진행 알림(매출 업데이트 창의 진행 막대용). 기본은 아무것도 하지 않는다 — sync 가 진행 상황을 모으는
|
||||
객체(jobs.ShopProgress)로 바꿔 넣는다.
|
||||
|
||||
어댑터: 조회를 시작하기 전에 plan(전체 단계 수, 단위) → 단계 하나(하루·조회 구간)를 끝낼 때마다
|
||||
step(items=그 단계에서 받은 건수). 하다가 할 일이 늘면 add(늘어난 단계 수).
|
||||
API 를 부르기 직전마다 check() — 사용자가 [업데이트 취소]를 눌렀으면 Cancelled 를 던져 거기서 멈춘다."""
|
||||
|
||||
def plan(self, total: int, unit: str = "단계") -> None:
|
||||
return None
|
||||
|
||||
def add(self, n: int) -> None:
|
||||
return None
|
||||
|
||||
def step(self, n: int = 1, *, items: int = 0) -> None:
|
||||
return None
|
||||
|
||||
def check(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdapterContext:
|
||||
code: str
|
||||
credentials: CredentialAccessor
|
||||
app_state: Any = None # 공통 연동 계층 재사용(예: 카페24 토큰 저장소)
|
||||
timeout_sec: float = 20.0
|
||||
progress: Progress = field(default_factory=Progress)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 어댑터
|
||||
# ════════════════════════════════════════════════════════════
|
||||
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,770 @@
|
||||
"""카페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')}). "
|
||||
"기간을 줄여 다시 시도하세요.")
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
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):
|
||||
n = 0
|
||||
for o in self._paged(ctx, "/admin/orders", "orders",
|
||||
{"start_date": s.isoformat(), "end_date": e.isoformat(),
|
||||
"date_type": "pay_date", "embed": "items"}, ORDER_LIMIT):
|
||||
n += 1
|
||||
yield o
|
||||
ctx.progress.step(items=n)
|
||||
|
||||
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):
|
||||
n = 0
|
||||
for r in self._paged(ctx, "/admin/refunds", "refunds",
|
||||
{"start_date": s.isoformat(), "end_date": e.isoformat(),
|
||||
"date_type": date_type}, REFUND_LIMIT):
|
||||
n += 1
|
||||
yield r
|
||||
ctx.progress.step(items=n)
|
||||
|
||||
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):
|
||||
scanned = 0
|
||||
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):
|
||||
scanned += 1
|
||||
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")),
|
||||
}
|
||||
ctx.progress.step(items=scanned)
|
||||
if not found:
|
||||
return []
|
||||
lo = start - timedelta(days=REFUND_LOOKAROUND_DAYS)
|
||||
hi = max(end, min(end + timedelta(days=REFUND_LOOKAROUND_DAYS), today_kst()))
|
||||
ctx.progress.add(2 * len(list(_chunks(lo, hi)))) # 환불 목록 대조(완료일·접수일) — 찾은 게 있을 때만
|
||||
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]]:
|
||||
# 진행 막대: 60일 구간마다 결제 주문 1 + 환불 1 + 환불 없는 취소·반품(취소일·반품완료일) 2
|
||||
c = len(list(_chunks(start, end)))
|
||||
ctx.progress.plan(c * (2 + len(NO_RECORD_DATE_TYPES)), "구간")
|
||||
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,329 @@
|
||||
"""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
|
||||
|
||||
|
||||
def _n_chunks(lo: date, hi: date) -> int:
|
||||
return max(0, ((hi - lo).days + PROBE_CHUNK_DAYS) // PROBE_CHUNK_DAYS)
|
||||
|
||||
|
||||
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")
|
||||
rows = xml_records(self._get(ctx, tmpl.format(s=f"{ds}0000", e=f"{de}2359", ds=ds, de=de)))
|
||||
ctx.progress.step(items=len(rows))
|
||||
yield from rows
|
||||
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))
|
||||
hi = max(end, min(end + timedelta(days=LOOKAHEAD_DAYS), today))
|
||||
# 진행 막대: 7일 구간마다 한 번 — 정산 내역 + 주문 상태 목록 4개
|
||||
ctx.progress.plan(_n_chunks(start, settle_hi) + len(ORDER_PATHS) * _n_chunks(start, hi), "구간")
|
||||
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)
|
||||
|
||||
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
|
||||
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
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,308 @@
|
||||
"""GS샵 — GSSHOP 제휴 API(협력사 API V3, partners.gsshop.com → 제휴 API → 개발가이드).
|
||||
|
||||
인증(개발가이드 2026-09-30 확인): 요청 헤더
|
||||
supCd = 협력사코드
|
||||
token = AES256( Sysdate("yyyyMMddHHmmss") + 협력사코드 ) 예: "20181017174913" + "1036018"
|
||||
AES256 암복호화 키는 partners.gsshop.com/api/apiMain 에 로그인하면 보인다.
|
||||
암호화 모드(CBC/ECB, IV)와 키를 바이트로 쓰는 법은 문서에 없다 → 키 변형(글자 그대로 / 16진수 풀기 / 앞 32자,
|
||||
key_variants) × 모드(CBC·IV=키 앞 16바이트 → ECB → CBC·IV=0) 순서로 시도하고 통과한 조합을 기억한다. 출력은 base64.
|
||||
(포털 "운영 KEY" 는 16진수처럼 보이는 글자 — 32자면 글자 그대로 AES256, 64자면 16진수로 풀어 32바이트일 수 있다.)
|
||||
token 이 틀리면 HTTP 200 + {"result":"fail","message":"키 인증 중 오류…","code":"401 UNAUTHORIZED"}.
|
||||
주소: 운영 https://withgs-api.gsshop.com (개발가이드의 예시 주소 atwithgs-api 는 테스트용 — 두 곳 모두 응답 확인).
|
||||
|
||||
매출(Settlement API 1.0): GET /api/v2/settlement/out/sales/period?supCode=&fromDate=&toDate=&pageIdx=&rowsPerPage=
|
||||
— 매출인식일(YYYYMMDD) 기준, 한 번에 10일까지, 쪽당 최대 1만 건. 응답 {data:[…], hasMorePage, totalCount, …}.
|
||||
배송비는 /api/v2/settlement/out/sales/shippingFee/period(같은 조건).
|
||||
응답 줄 항목(2026-09-30 실데이터 9/3 — 개발가이드 예시에는 없음): saleAwareDt(매출인식일), ordNo·ordItemNo·orgOrdNo,
|
||||
ordType(SALE …), prdCd·prdNm, chrQty(수량), salePrice(할인 전 판매가 — 줄 합계), dcTotAmt(할인 합계),
|
||||
custChrAmt(고객 결제금액 = salePrice − dcTotAmt), supGiveAmt(협력사 지급액, 수수료 차감), sup*DcAmt(협력사 부담 할인).
|
||||
9/3: salePrice 211,100 − dcTotAmt 19,528 = custChrAmt 191,572, supGiveAmt 179,435, 배송비 내역 7,000.
|
||||
**주문일 기준 조회 API 는 없다**(V3 문서에 주문 조회 없음) — 협력사 포털 주문 통계(총주문금액, 주문일)와는 기준이 달라
|
||||
날짜별로 똑같이 맞출 수 없다.
|
||||
|
||||
매출 규칙 — 협력사 포털 주문 통계의 금액 = **supGiveAmt(협력사 지급액)**(2026-09-30, 9월 실데이터로 확인):
|
||||
미라미라클 6호세트 포털 176,715 ÷ 9 = 19,635 = API 줄 supGiveAmt 19,635(판매가 23,100·고객 결제 20,330),
|
||||
7호세트 39,015 = 45,900 × 85%, 주부체험 세트 8,910 = 9,900 × 90% — 상품마다 GS 수수료율이 달라 판매가 × 요율로는 못 맞춘다.
|
||||
9/1~9/29: 지급액 4,972,689 / 포털 순주문 4,823,074(차이는 주문일 ↔ 매출인식일 기준 차이·취소분).
|
||||
- 매출 내역 한 줄 = 사건 하나(`gs:{ordNo}-{ordItemNo}-{ordType}-{saleAwareDt}`), 날짜 = 매출인식일.
|
||||
- 금액 = supGiveAmt, 배송비 제외. 이미 GS 수수료를 뺀 금액이라 **실적 설정의 GS샵 수수료율은 0%** 로 둔다.
|
||||
ordType 이 SALE 이 아니면(취소·반품 등) 음수로(RETURN). 할인 = dcTotAmt. 기간을 통째로 다시 받는다(replace_range).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
AdapterError,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
CredentialField,
|
||||
MarketplaceAdapter,
|
||||
NotConfigured,
|
||||
SaleEvent,
|
||||
)
|
||||
from .elevenst import field_summary
|
||||
|
||||
HOST = "https://withgs-api.gsshop.com"
|
||||
SALES_PATH = "/api/v2/settlement/out/sales/period"
|
||||
SHIPPING_PATH = "/api/v2/settlement/out/sales/shippingFee/period"
|
||||
DAILY_SALES_PATH = "/api/v2/settlement/out/sales"
|
||||
CHUNK_DAYS = 10 # 기간 조회는 시작일부터 10일 이내
|
||||
ROWS_PER_PAGE = 10000
|
||||
MAX_PAGES = 50
|
||||
PROBE_MAX_DAYS = 31
|
||||
TOKEN_MODES = ("cbc-keyiv", "ecb", "cbc-zeroiv")
|
||||
MODE_LABEL = {"cbc-keyiv": "AES/CBC(IV=키 앞 16바이트)", "ecb": "AES/ECB", "cbc-zeroiv": "AES/CBC(IV=0)"}
|
||||
|
||||
|
||||
KEY_LABEL = {"text": "키 글자 그대로", "hex": "키 16진수 풀기", "first32": "키 앞 32자"}
|
||||
|
||||
|
||||
def key_variants(aes_key: str) -> list[tuple[str, bytes]]:
|
||||
"""AES 키로 쓸 수 있는 바이트 후보(시도 순서). 하나도 없으면 길이 오류."""
|
||||
raw = aes_key.strip().encode("utf-8")
|
||||
out: list[tuple[str, bytes]] = []
|
||||
if len(raw) in (16, 24, 32):
|
||||
out.append(("text", raw))
|
||||
txt = aes_key.strip()
|
||||
if len(txt) in (32, 48, 64) and all(c in "0123456789abcdefABCDEF" for c in txt):
|
||||
out.append(("hex", bytes.fromhex(txt)))
|
||||
if len(raw) > 32:
|
||||
out.append(("first32", raw[:32]))
|
||||
if not out:
|
||||
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(raw)}자). 제휴 API 메인 화면의 운영 KEY 를 "
|
||||
"[복사] 버튼으로 복사해 그대로 붙여 넣으세요.")
|
||||
return out
|
||||
|
||||
|
||||
def make_token(aes_key: str | bytes, sup_cd: str, now: datetime, mode: str) -> str:
|
||||
"""token = base64(AES(yyyyMMddHHmmss + 협력사코드)), PKCS7(=PKCS5) 패딩. aes_key 가 글자면 그대로 바이트로."""
|
||||
from cryptography.hazmat.primitives import padding # 지연 import
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
|
||||
key = aes_key if isinstance(aes_key, bytes) else aes_key.encode("utf-8")
|
||||
if len(key) not in (16, 24, 32):
|
||||
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(key)}바이트 — 16·24·32 중 하나여야 함). "
|
||||
"제휴 API 메인 화면의 키를 그대로 붙여 넣으세요.")
|
||||
plain = (now.strftime("%Y%m%d%H%M%S") + sup_cd).encode("utf-8")
|
||||
padder = padding.PKCS7(128).padder()
|
||||
data = padder.update(plain) + padder.finalize()
|
||||
if mode == "ecb":
|
||||
cipher = Cipher(algorithms.AES(key), modes.ECB())
|
||||
elif mode == "cbc-zeroiv":
|
||||
cipher = Cipher(algorithms.AES(key), modes.CBC(b"\0" * 16))
|
||||
else:
|
||||
cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]))
|
||||
enc = cipher.encryptor()
|
||||
return base64.b64encode(enc.update(data) + enc.finalize()).decode("ascii")
|
||||
|
||||
|
||||
def _rows(body: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
data = body.get("data")
|
||||
return [r for r in data if isinstance(r, dict)] if isinstance(data, list) else []
|
||||
|
||||
|
||||
def _strs(row: dict[str, Any]) -> dict[str, str]:
|
||||
"""원본 확인용 — 값은 모두 글자로(중첩은 JSON 글자 그대로 짧게)."""
|
||||
return {str(k): ("" if v is None else str(v)) for k, v in row.items()}
|
||||
|
||||
|
||||
EVENT_PREFIX = "gs:"
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
try:
|
||||
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def _yyyymmdd(value: Any) -> date | None:
|
||||
s = "".join(ch for ch in str(value or "") if ch.isdigit())[: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 GsshopAdapter(MarketplaceAdapter):
|
||||
code = "gsshop"
|
||||
name = "GS샵"
|
||||
auth_type = "api_key"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
docs_url = "https://partners.gsshop.com/api/apiDevGuide"
|
||||
note = ("GS SHOP 협력사 포털(partners.gsshop.com) → 제휴 API 메인 화면의 협력사코드와 "
|
||||
"운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._mode: dict[str, tuple[str, str]] = {} # 협력사코드 → 통과한 (키 변형, 암호화 모드)
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
|
||||
return [
|
||||
CredentialField("vendor_code", "협력사코드(supCd)", help="예: 1036018"),
|
||||
CredentialField("api_key", "운영 KEY(AES256 암복호화 키)", secret=True,
|
||||
help="제휴 API 메인 화면의 운영 KEY — [복사] 버튼으로 복사해 붙여 넣기"),
|
||||
]
|
||||
|
||||
# ── 호출 ──────────────────────────────────────────────
|
||||
def _creds(self, ctx: AdapterContext) -> tuple[str, str]:
|
||||
sup = ctx.credentials.get("vendor_code").strip()
|
||||
key = ctx.credentials.get("api_key").strip()
|
||||
if not sup or not key:
|
||||
raise NotConfigured("협력사코드와 AES256 키를 입력하세요.")
|
||||
return sup, key
|
||||
|
||||
def _call(self, ctx: AdapterContext, path: str, params: dict[str, Any], how: tuple[str, str]) -> dict[str, Any]:
|
||||
import httpx # 지연 import
|
||||
|
||||
from app.timezone import now_kst # noqa: WPS433
|
||||
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
sup, key = self._creds(ctx)
|
||||
key_bytes = dict(key_variants(key))[how[0]]
|
||||
headers = {"supCd": sup, "token": make_token(key_bytes, sup, now_kst(), how[1]), "Accept": "application/json"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}", params={"supCode": sup, **params}, headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"GS샵 API 연결 실패: {type(exc).__name__}") from None
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
raise ApiError(f"GS샵이 예상하지 못한 응답을 돌려줬습니다({res.status_code}): {res.text[:150].strip()}") from None
|
||||
if not isinstance(body, dict):
|
||||
body = {"data": body}
|
||||
code = str(body.get("code") or "")
|
||||
msg = str(body.get("message") or "")[:200]
|
||||
if res.status_code in (401, 403) or (str(body.get("result")) == "fail" and ("401" in code or "403" in code)):
|
||||
raise AuthFailed(f"GS샵 인증 거부({code or res.status_code}): {msg}")
|
||||
if res.status_code >= 400 or str(body.get("result")) == "fail":
|
||||
raise ApiError(f"GS샵 API 오류({code or res.status_code}): {msg or res.text[:150].strip()}")
|
||||
return body
|
||||
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""토큰 만드는 법(키 변형 × 암호화 모드)을 모르면 순서대로 시도 — 통과한 조합을 기억한다."""
|
||||
sup, key = self._creds(ctx)
|
||||
known = self._mode.get(sup)
|
||||
if known:
|
||||
return self._call(ctx, path, params, known)
|
||||
tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES]
|
||||
last: AuthFailed | None = None
|
||||
for how in tries:
|
||||
try:
|
||||
body = self._call(ctx, path, params, how)
|
||||
except AuthFailed as exc:
|
||||
last = exc
|
||||
continue
|
||||
self._mode[sup] = how
|
||||
return body
|
||||
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. "
|
||||
"협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.")
|
||||
|
||||
def _pages(self, ctx: AdapterContext, path: str, lo: date, hi: date) -> list[dict[str, Any]]:
|
||||
"""[lo, hi] 를 10일씩 나눠 쪽을 넘겨 모두 받는다."""
|
||||
out: list[dict[str, Any]] = []
|
||||
s = lo
|
||||
while s <= hi:
|
||||
e = min(hi, s + timedelta(days=CHUNK_DAYS - 1))
|
||||
for page in range(1, MAX_PAGES + 1):
|
||||
body = self._get(ctx, path, {"fromDate": s.strftime("%Y%m%d"), "toDate": e.strftime("%Y%m%d"),
|
||||
"pageIdx": page, "rowsPerPage": ROWS_PER_PAGE})
|
||||
rows = _rows(body)
|
||||
out.extend(rows)
|
||||
if not body.get("hasMorePage") or not rows:
|
||||
break
|
||||
ctx.progress.step(items=len(out))
|
||||
s = e + timedelta(days=1)
|
||||
return out
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
"""매출인식일이 [start, end] 인 매출 내역 줄. 같은 사건 ID 가 두 번 나오면 뒤에 번호를 붙여 둘 다 남긴다."""
|
||||
ctx.progress.plan(max(1, ((end - start).days + CHUNK_DAYS) // CHUNK_DAYS), "구간")
|
||||
seen: dict[str, int] = {}
|
||||
for r in self._pages(ctx, SALES_PATH, start, end):
|
||||
day = _yyyymmdd(r.get("saleAwareDt"))
|
||||
if day is None or not (start <= day <= end):
|
||||
continue
|
||||
base = f"{r.get('ordNo')}-{r.get('ordItemNo')}-{r.get('ordType') or 'SALE'}-{day.strftime('%Y%m%d')}"
|
||||
n = seen.get(base, 0)
|
||||
seen[base] = n + 1
|
||||
yield {**r, "_day": day, "_id": base if n == 0 else f"{base}-{n + 1}"}
|
||||
|
||||
def normalize_order(self, r: dict[str, Any]) -> list[SaleEvent]:
|
||||
"""매출 내역 한 줄 → SALE(ordType=SALE) 또는 RETURN(그 밖, 음수). 금액 = supGiveAmt(협력사 지급액 — 포털 주문 통계 금액)."""
|
||||
oid, day = str(r.get("ordNo") or ""), r.get("_day")
|
||||
if not oid or day is None:
|
||||
return []
|
||||
kind = str(r.get("ordType") or "SALE").upper()
|
||||
amount = abs(_won(r.get("supGiveAmt")))
|
||||
is_sale = kind == "SALE"
|
||||
return [SaleEvent(
|
||||
event_type="SALE" if is_sale else "RETURN", external_event_id=f"{EVENT_PREFIX}{r['_id']}",
|
||||
external_order_id=oid, external_line_id=str(r.get("ordItemNo") or ""), event_date=day,
|
||||
payment_date=day if is_sale else None, amount=amount if is_sale else -amount,
|
||||
product_name=str(r.get("prdNm") or "")[:200], quantity=abs(_won(r.get("chrQty"))),
|
||||
discount_amount=abs(_won(r.get("dcTotAmt"))), order_status=kind[:50],
|
||||
raw={"salePrice": _won(r.get("salePrice")), "custChrAmt": _won(r.get("custChrAmt")),
|
||||
"orgOrdNo": str(r.get("orgOrdNo") or ""), "prdCd": str(r.get("prdCd") or "")},
|
||||
)]
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
self.authenticate(ctx)
|
||||
sup, _ = self._creds(ctx)
|
||||
self._mode.pop(sup, None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다
|
||||
day = today_kst() - timedelta(days=1)
|
||||
body = self._get(ctx, DAILY_SALES_PATH, {"stdDate": day.strftime("%Y%m%d"), "pageIdx": 1, "rowsPerPage": 10})
|
||||
total = body.get("totalCount")
|
||||
return (f"GS샵 연결 정상(매출 내역 조회 확인, 어제 매출 {total if total is not None else len(_rows(body))}건, "
|
||||
f"토큰 {self._how_label(sup)}).")
|
||||
|
||||
def _how_label(self, sup: str) -> str:
|
||||
v, m = self._mode.get(sup, ("", ""))
|
||||
return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}"
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||
"""매출 내역·배송비 내역을 기간(최대 31일, 10일씩)으로 실제 불러 항목별 합계를 돌려준다(저장 안 함).
|
||||
응답 항목 이름이 개발가이드에 없어 협력사 포털 매출 화면과 맞는 항목을 실데이터로 확정하는 용도."""
|
||||
self.authenticate(ctx)
|
||||
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||
probes = []
|
||||
got: dict[str, list[dict[str, Any]]] = {}
|
||||
for key, label, path in (("sales", "매출 내역(매출인식일 기준)", SALES_PATH),
|
||||
("shipping", "배송비 내역(매출인식일 기준)", SHIPPING_PATH)):
|
||||
row: dict[str, Any] = {"key": key, "label": label, "path": path}
|
||||
try:
|
||||
rows = self._pages(ctx, path, day, to)
|
||||
except AdapterError as exc:
|
||||
probes.append({**row, "ok": False, "error": exc.message[:300]})
|
||||
continue
|
||||
got[key] = rows
|
||||
probes.append({**row, "ok": True, "count": len(rows), "fields": field_summary([_strs(r) for r in rows])})
|
||||
# 날짜별 현재 규칙 매출(supGiveAmt, SALE 아닌 줄은 음수) — 협력사 포털 매출 화면과 나란히 비교
|
||||
days = []
|
||||
d = day
|
||||
while d <= to:
|
||||
sales = [r for r in got.get("sales", []) if _yyyymmdd(r.get("saleAwareDt")) == d]
|
||||
ret = [r for r in sales if str(r.get("ordType") or "SALE").upper() != "SALE"]
|
||||
amt = sum(abs(_won(r.get("supGiveAmt"))) for r in sales if r not in ret) - sum(abs(_won(r.get("supGiveAmt"))) for r in ret)
|
||||
days.append({"date": d.isoformat(), "orders": len({str(r.get("ordNo")) for r in sales if r not in ret}),
|
||||
"amount": amt, "claimed": sum(abs(_won(r.get("supGiveAmt"))) for r in ret),
|
||||
"ship": sum(_won(r.get("salePrice")) for r in got.get("shipping", [])
|
||||
if _yyyymmdd(r.get("saleAwareDt")) == d)})
|
||||
d += timedelta(days=1)
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||
"day_cols": {"claimed": "그중 취소·반품(음수로 반영)", "ship": "배송비(참고, 매출 제외)"},
|
||||
"rule": "매출인식일 기준 매출 내역 supGiveAmt(협력사 지급액 = 포털 주문 통계 금액) 합, SALE 이 아닌 줄은 빼기, "
|
||||
"배송비 제외. 주문 통계는 주문일 기준이라 날마다 같지는 않고 기간이 길수록 가까워진다"}
|
||||
@@ -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,414 @@
|
||||
"""네이버 스마트스토어 — 네이버 커머스API.
|
||||
|
||||
인증(공식 방식): 애플리케이션 ID + 시크릿으로 전자서명 → OAuth2 client_credentials 토큰.
|
||||
client_secret_sign = base64( bcrypt.hashpw("{client_id}_{timestamp(ms)}", client_secret) )
|
||||
POST https://api.commerce.naver.com/external/v1/oauth2/token
|
||||
(client_id, timestamp, client_secret_sign, grant_type=client_credentials, type=SELF | SELLER+account_id)
|
||||
토큰은 약 3시간 — 암호화 저장(access_token·access_token_expires_at)해 두고 만료 5분 전에 새로 받는다.
|
||||
커머스API센터 애플리케이션에 **API 호출 IP(이 서버 외부 IP)** 를 등록해야 호출된다.
|
||||
|
||||
매출 수집 — 스마트스토어센터 **판매분석 "판매금액(총)"** 과 같은 기준(2026-09-30 사용자 확인: 9/1 매출 4,455,600원.
|
||||
판매금액은 할인(판매자·네이버 부담) 뒤 금액, 배송비 332,486원은 별도, 환불 346,340원은 환불일에 따로 빠져 판매금액(순)):
|
||||
- 조건형 상품 주문 상세 조회 GET /v1/pay-order/seller/product-orders
|
||||
?from=…&to=…&rangeType=PAYED_DATETIME&pageSize=&page= — 결제일 기준, 한 번에 24시간까지(하루씩 부른다),
|
||||
from 부터 180일 안의 주문만. 응답에 주문·상품주문 상세가 바로 들어 있다(네이버 안내: 소량·조회용 권장 API).
|
||||
- SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(order.paymentDate).
|
||||
금액 = 상품주문들의 결제금액(productOrder.totalPaymentAmount) 합 — 배송비 제외.
|
||||
- 결제 뒤 취소·반품된 상품주문도 결제일 매출에 그대로 둔다(판매금액(총)). 입금대기·미입금 취소만 뺀다.
|
||||
그래서 지난 날짜 매출이 나중에 줄지 않는다. 환불(판매금액(순))은 아직 따로 만들지 않는다.
|
||||
- 구매자 이름·연락처·주소는 저장하지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .base import (
|
||||
AdapterContext,
|
||||
AdapterError,
|
||||
ApiError,
|
||||
AuthFailed,
|
||||
CredentialField,
|
||||
MarketplaceAdapter,
|
||||
NotConfigured,
|
||||
SaleEvent,
|
||||
TokenExpired,
|
||||
)
|
||||
|
||||
HOST = "https://api.commerce.naver.com/external"
|
||||
TOKEN_PATH = "/v1/oauth2/token"
|
||||
ORDERS_PATH = "/v1/pay-order/seller/product-orders"
|
||||
EVENT_PREFIX = "naver:"
|
||||
PAGE_SIZE = 100
|
||||
MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지
|
||||
TOKEN_MARGIN_SEC = 300 # 만료 5분 전이면 새로 받는다
|
||||
CALL_INTERVAL_SEC = 0.35 # 초당 호출 제한(넘으면 429) — 호출 사이 간격
|
||||
RETRY_429 = 3
|
||||
PROBE_MAX_DAYS = 31
|
||||
|
||||
# 매출에서 빼는 상품주문 상태 — 결제되지 않은 것만(입금대기·미입금 취소). 결제 뒤 취소·반품된 것은 판매분석
|
||||
# "판매금액(총)"처럼 결제일 매출에 그대로 둔다(환불은 판매분석에서도 환불일에 따로 빠진다).
|
||||
EXCLUDED_STATUS = frozenset({"PAYMENT_WAITING", "CANCELED_BY_NOPAYMENT"})
|
||||
CLAIMED_STATUS = frozenset({"CANCELED", "RETURNED"}) # 결제 뒤 취소·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌
|
||||
STATUS_KO = {
|
||||
"PAYMENT_WAITING": "입금대기", "PAYED": "결제완료", "DELIVERING": "배송중", "DELIVERED": "배송완료",
|
||||
"PURCHASE_DECIDED": "구매확정", "EXCHANGED": "교환", "CANCELED": "취소", "RETURNED": "반품",
|
||||
"CANCELED_BY_NOPAYMENT": "미입금취소",
|
||||
}
|
||||
|
||||
# 원본 데이터 확인 — 개인정보로 보이는 항목은 값 없이 이름만. 금액·상태·날짜·상품명 등은 보인다.
|
||||
PERSONAL = re.compile(r"orderer|receiver|shippingAddress|takingAddress|returnAddress|pickupAddress|collectAddress|"
|
||||
r"name$|tel|phone|address|zip|mail|memo|customsClearance|buyer|recipient", re.IGNORECASE)
|
||||
SAFE = re.compile(r"(productName|productOption|optionCode|productClass|productId|deliveryCompany|reason|Status|Type|"
|
||||
r"Date|Amount|Price|Fee|Quantity|Count|Id)$")
|
||||
NUMBER = re.compile(r"^-?\d+(\.\d+)?$")
|
||||
|
||||
|
||||
def _won(value: Any) -> int:
|
||||
try:
|
||||
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def _day(value: Any) -> date | None:
|
||||
""""2026-09-29T10:11:12.0+09:00" → date(2026, 9, 29). 네이버 날짜는 한국 시간(+09:00)으로 온다."""
|
||||
s = str(value or "")
|
||||
m = re.match(r"(\d{4})-(\d{2})-(\d{2})", s)
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def sign(client_id: str, client_secret: str, timestamp_ms: int) -> str:
|
||||
"""커머스API 전자서명 — bcrypt(비밀번호 = "{client_id}_{timestamp}", 솔트 = 애플리케이션 시크릿) 을 base64."""
|
||||
import bcrypt # 지연 import
|
||||
|
||||
try:
|
||||
hashed = bcrypt.hashpw(f"{client_id}_{timestamp_ms}".encode("utf-8"), client_secret.encode("utf-8"))
|
||||
except ValueError:
|
||||
raise AuthFailed("애플리케이션 시크릿 형식이 올바르지 않습니다. 커머스API센터의 시크릿을 그대로 붙여 넣으세요.") from None
|
||||
return base64.standard_b64encode(hashed).decode("ascii")
|
||||
|
||||
|
||||
def product_order_items(body: Any) -> list[dict[str, Any]]:
|
||||
"""조건형 조회 응답에서 상품주문 하나씩 {"order": {...}, "productOrder": {...}, ...} 로 꺼낸다.
|
||||
응답 모양(data.contents[].content / data 목록 / 바로 목록)이 달라도 받아들인다."""
|
||||
data = body.get("data", body) if isinstance(body, dict) else body
|
||||
if isinstance(data, dict):
|
||||
data = data.get("contents") or data.get("productOrders") or data.get("items") or []
|
||||
out = []
|
||||
for it in data if isinstance(data, list) else []:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
c = it.get("content") if isinstance(it.get("content"), dict) else it
|
||||
if isinstance(c.get("productOrder"), dict):
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
|
||||
def has_next(body: Any, page: int, got: int) -> bool:
|
||||
data = body.get("data") if isinstance(body, dict) else None
|
||||
pg = data.get("pagination") if isinstance(data, dict) else None
|
||||
if isinstance(pg, dict):
|
||||
if "hasNext" in pg:
|
||||
return bool(pg["hasNext"])
|
||||
total = pg.get("totalPages") or pg.get("totalPage")
|
||||
if total:
|
||||
return page < int(total)
|
||||
return got >= PAGE_SIZE
|
||||
|
||||
|
||||
def flatten(obj: Any, prefix: str = "") -> dict[str, str]:
|
||||
"""중첩 사전 → {"productOrder.totalPaymentAmount": "12000", …}. 목록은 건너뛴다(개수만)."""
|
||||
out: dict[str, str] = {}
|
||||
if isinstance(obj, dict):
|
||||
for k, v in obj.items():
|
||||
key = f"{prefix}.{k}" if prefix else str(k)
|
||||
if isinstance(v, dict):
|
||||
out.update(flatten(v, key))
|
||||
elif isinstance(v, list):
|
||||
out[key + "[]"] = str(len(v))
|
||||
elif v is not None:
|
||||
out[key] = str(v)
|
||||
return out
|
||||
|
||||
|
||||
def is_personal(key: str) -> bool:
|
||||
last = key.rsplit(".", 1)[-1]
|
||||
if "Address." in key or key.split(".")[0] in ("orderer",):
|
||||
return True
|
||||
return bool(PERSONAL.search(key)) and not SAFE.search(last)
|
||||
|
||||
|
||||
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": is_personal(k)})
|
||||
if 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 sorted(names.values(), key=lambda f: f["name"])
|
||||
|
||||
|
||||
def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
|
||||
"""상품주문 → 주문 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
|
||||
금액 = totalPaymentAmount 합(할인 뒤 상품 결제금액, 배송비 제외) = 판매분석 "판매금액(총)".
|
||||
배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
|
||||
orders: dict[str, dict[str, Any]] = {}
|
||||
for c in items:
|
||||
po, od = c.get("productOrder") or {}, c.get("order") or {}
|
||||
oid = str(od.get("orderId") or po.get("orderId") or "")
|
||||
day = _day(od.get("paymentDate") or po.get("paymentDate"))
|
||||
status = str(po.get("productOrderStatus") or "")
|
||||
if not oid or day is None or not (start <= day <= end) or status in EXCLUDED_STATUS:
|
||||
continue
|
||||
o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
|
||||
"discount": 0, "names": [], "opt": "", "statuses": [],
|
||||
"order_day": _day(od.get("orderDate"))})
|
||||
paid = _won(po.get("totalPaymentAmount"))
|
||||
o["amount"] += paid
|
||||
if status in CLAIMED_STATUS:
|
||||
o["claimed"] += paid
|
||||
o["ship"] += _won(po.get("deliveryFeeAmount")) - _won(po.get("deliveryDiscountAmount"))
|
||||
o["qty"] += _won(po.get("quantity"))
|
||||
o["discount"] += _won(po.get("productDiscountAmount"))
|
||||
name = str(po.get("productName") or "")
|
||||
if name and name not in o["names"]:
|
||||
o["names"].append(name)
|
||||
o["opt"] = o["opt"] or str(po.get("productOption") or "")
|
||||
if status and status not in o["statuses"]:
|
||||
o["statuses"].append(status)
|
||||
return orders
|
||||
|
||||
|
||||
class NaverAdapter(MarketplaceAdapter):
|
||||
code = "naver"
|
||||
name = "네이버 스마트스토어"
|
||||
auth_type = "oauth"
|
||||
implemented = True
|
||||
replace_range = True
|
||||
event_prefix = EVENT_PREFIX
|
||||
docs_url = "https://apicenter.commerce.naver.com/"
|
||||
note = ("커머스API센터에서 발급한 애플리케이션 ID/시크릿을 입력합니다. 애플리케이션의 API 호출 IP 에 "
|
||||
"이 서버의 외부 IP 를 등록해야 호출됩니다.")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last_call = 0.0
|
||||
|
||||
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="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"),
|
||||
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
||||
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
||||
]
|
||||
|
||||
# ── 인증 ──────────────────────────────────────────────
|
||||
def _token(self, ctx: AdapterContext, *, force: bool = False) -> str:
|
||||
"""저장된 토큰이 5분 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장."""
|
||||
if not force:
|
||||
tok = ctx.credentials.get("access_token")
|
||||
try:
|
||||
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
|
||||
except ValueError:
|
||||
exp = 0.0
|
||||
if tok and exp - time.time() > TOKEN_MARGIN_SEC:
|
||||
return tok
|
||||
return self._issue_token(ctx)
|
||||
|
||||
def _issue_token(self, ctx: AdapterContext) -> str:
|
||||
import httpx # 지연 import
|
||||
|
||||
client_id = ctx.credentials.get("client_id").strip()
|
||||
client_secret = ctx.credentials.get("client_secret").strip()
|
||||
if not client_id or not client_secret:
|
||||
raise NotConfigured("애플리케이션 ID와 시크릿을 입력하세요.")
|
||||
ts = int(time.time() * 1000)
|
||||
form = {"client_id": client_id, "timestamp": str(ts), "grant_type": "client_credentials",
|
||||
"client_secret_sign": sign(client_id, client_secret, ts), "type": "SELF"}
|
||||
account_id = ctx.credentials.get("account_id").strip()
|
||||
if account_id:
|
||||
form.update(type="SELLER", account_id=account_id)
|
||||
try:
|
||||
res = httpx.post(f"{HOST}{TOKEN_PATH}", data=form, timeout=ctx.timeout_sec,
|
||||
headers={"Accept": "application/json"})
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"네이버 커머스API 연결 실패: {type(exc).__name__}") from None
|
||||
body = self._json(res)
|
||||
if res.status_code >= 400 or not body.get("access_token"):
|
||||
msg = self._err_text(body, res)
|
||||
if res.status_code in (400, 401, 403):
|
||||
raise AuthFailed(f"네이버 토큰 발급 실패({res.status_code}): {msg}. 애플리케이션 ID·시크릿과 "
|
||||
"API 호출 IP(이 서버 외부 IP) 등록을 확인하세요.")
|
||||
raise ApiError(f"네이버 토큰 발급 오류({res.status_code}): {msg}")
|
||||
tok = str(body["access_token"])
|
||||
expires_in = _won(body.get("expires_in")) or 3 * 3600
|
||||
ctx.credentials.set("access_token", tok)
|
||||
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
|
||||
return tok
|
||||
|
||||
def authenticate(self, ctx: AdapterContext) -> None:
|
||||
super().authenticate(ctx)
|
||||
self._token(ctx)
|
||||
|
||||
def refresh_token(self, ctx: AdapterContext) -> None:
|
||||
self._token(ctx, force=True)
|
||||
|
||||
# ── 호출 ──────────────────────────────────────────────
|
||||
@staticmethod
|
||||
def _json(res: Any) -> dict[str, Any]:
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
return {}
|
||||
return body if isinstance(body, dict) else {"data": body}
|
||||
|
||||
@staticmethod
|
||||
def _err_text(body: dict[str, Any], res: Any) -> str:
|
||||
parts = [str(body.get(k)) for k in ("code", "message", "error", "error_description") if body.get(k)]
|
||||
inv = body.get("invalidInputs")
|
||||
if isinstance(inv, list) and inv:
|
||||
parts.append("; ".join(str(i.get("message") or i) if isinstance(i, dict) else str(i) for i in inv[:3]))
|
||||
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
|
||||
|
||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더."""
|
||||
import httpx # 지연 import
|
||||
|
||||
retried_auth = False
|
||||
for attempt in range(RETRY_429 + 1):
|
||||
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||
wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call)
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
headers = {"Authorization": f"Bearer {self._token(ctx)}", "Accept": "application/json"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"네이버 커머스API 연결 실패: {type(exc).__name__}") from None
|
||||
finally:
|
||||
self._last_call = time.monotonic()
|
||||
if res.status_code == 429 and attempt < RETRY_429:
|
||||
time.sleep(1.0 * (2 ** attempt))
|
||||
continue
|
||||
if res.status_code == 401 and not retried_auth:
|
||||
retried_auth = True
|
||||
self._token(ctx, force=True)
|
||||
continue
|
||||
body = self._json(res)
|
||||
if res.status_code == 401:
|
||||
raise TokenExpired(f"네이버 인증 만료·거부(401): {self._err_text(body, res)}")
|
||||
if res.status_code == 403:
|
||||
raise AuthFailed(f"네이버 권한 거부(403): {self._err_text(body, res)}. 애플리케이션의 API 권한(주문)과 "
|
||||
"API 호출 IP 등록을 확인하세요.")
|
||||
if res.status_code >= 400:
|
||||
raise ApiError(f"네이버 API 오류({res.status_code}): {self._err_text(body, res)}")
|
||||
return body
|
||||
raise ApiError("네이버 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
|
||||
def _day_items(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
|
||||
"""결제일이 d(한국 시간 0시~23:59:59.999)인 상품주문 전체 — 모든 상태."""
|
||||
params: dict[str, Any] = {
|
||||
"from": f"{d.isoformat()}T00:00:00.000+09:00", "to": f"{d.isoformat()}T23:59:59.999+09:00",
|
||||
"rangeType": "PAYED_DATETIME", "pageSize": PAGE_SIZE,
|
||||
}
|
||||
out: list[dict[str, Any]] = []
|
||||
for page in range(1, MAX_PAGES + 1):
|
||||
body = self._get(ctx, ORDERS_PATH, {**params, "page": page})
|
||||
items = product_order_items(body)
|
||||
out.extend(items)
|
||||
if not items or not has_next(body, page, len(items)):
|
||||
break
|
||||
return out
|
||||
|
||||
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
|
||||
d = start
|
||||
while d <= end:
|
||||
rows = self._day_items(ctx, d)
|
||||
ctx.progress.step(items=len(rows))
|
||||
yield from rows
|
||||
d += timedelta(days=1)
|
||||
|
||||
# ── 수집 ──────────────────────────────────────────────
|
||||
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||
yield from group_orders(self._items(ctx, start, end), start, end).values()
|
||||
|
||||
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
|
||||
oid, day = str(o.get("orderId") 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 ""
|
||||
statuses = [STATUS_KO.get(s, s) for s in o.get("statuses") or []]
|
||||
return [SaleEvent(
|
||||
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}", external_order_id=oid,
|
||||
order_date=o.get("order_day"), 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="/".join(statuses)[:50],
|
||||
)]
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
from app.timezone import today_kst # noqa: WPS433
|
||||
|
||||
# 입력한 새 값으로 시험할 수 있으니 저장된 토큰을 쓰지 않고 항상 새로 받는다.
|
||||
super().authenticate(ctx)
|
||||
self._token(ctx, force=True)
|
||||
items = self._day_items(ctx, today_kst())
|
||||
return f"네이버 커머스API 연결 정상(토큰 발급·주문 조회 확인, 오늘 결제 상품주문 {len(items)}건)."
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||
"""결제일 기준 기간(최대 31일)의 상품주문을 실제로 불러 항목별 합계·상태별 합계·날짜별 현재 규칙 매출을 돌려준다.
|
||||
스마트스토어센터 화면 매출과 어느 항목이 맞는지 실데이터로 확정하는 용도. 개인정보 항목은 값 없이 이름만."""
|
||||
self.authenticate(ctx)
|
||||
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||
try:
|
||||
items = list(self._items(ctx, day, to))
|
||||
except AdapterError as exc:
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
|
||||
{"key": "payed", "label": "결제일 기준 상품주문", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]}
|
||||
by_status: dict[str, list[dict[str, Any]]] = {}
|
||||
for c in items:
|
||||
by_status.setdefault(str((c.get("productOrder") or {}).get("productOrderStatus") or "?"), []).append(c)
|
||||
probes = [{"key": "payed", "label": "결제일 기준 상품주문(전체 상태)", "path": ORDERS_PATH + " (PAYED_DATETIME)",
|
||||
"ok": True, "count": len(items), "fields": field_summary([flatten(c) for c in items])}]
|
||||
for st, rows in sorted(by_status.items()):
|
||||
probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})"
|
||||
+ (" — 매출 제외(미결제)" if st in EXCLUDED_STATUS else
|
||||
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "productOrderStatus",
|
||||
"ok": True, "count": len(rows),
|
||||
"fields": [f for f in field_summary([flatten(c) for c in rows])
|
||||
if f["sum"] is not None and f["name"].startswith("productOrder.")]})
|
||||
days = []
|
||||
orders = group_orders(items, day, to)
|
||||
d = day
|
||||
while d <= to:
|
||||
day_orders = [o for o in orders.values() if o["_day"] == d]
|
||||
days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sum(o["amount"] for o in day_orders),
|
||||
"claimed": sum(o["claimed"] for o in day_orders), "ship": sum(o["ship"] for o in day_orders)})
|
||||
d += timedelta(days=1)
|
||||
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||
"rule": "결제일 기준 상품주문 totalPaymentAmount 합(할인 뒤, 배송비 제외, 결제 뒤 취소·반품분 포함, "
|
||||
"미입금 제외) = 판매분석 '판매금액(총)'. 취소·반품분·배송비는 참고"}
|
||||
@@ -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,201 @@
|
||||
"""매출 업데이트 진행 상황 — 백그라운드 수집 작업(쇼핑몰별 진행 막대)을 메모리에 둔다.
|
||||
|
||||
- [매출 업데이트]·[과거 매출 가져오기]는 수집을 백그라운드 스레드로 돌리고 작업 번호를 바로 돌려준다.
|
||||
화면은 GET /performance/api/sync/jobs/{id} 를 0.8초마다 불러 쇼핑몰별·전체 진행 막대를 그린다.
|
||||
- 어댑터가 ctx.progress.plan()/step() 으로 알린 단계를 ShopProgress 가 모은다(쇼핑몰마다 단위가 다르다 —
|
||||
네이버 "일", 11번가·카페24 "구간").
|
||||
- 웹 프로세스 하나(uvicorn 단일 워커) 기준 — 워커를 여러 개로 늘리면 진행 상황을 DB 로 옮겨야 한다.
|
||||
서버를 다시 켜면 진행 중 작업 정보는 사라진다(수집 결과는 DB 에 이미 저장된 만큼 남음).
|
||||
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
|
||||
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
|
||||
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from .adapters.base import Cancelled, Progress
|
||||
|
||||
MAX_JOBS = 20
|
||||
_LOCK = threading.Lock()
|
||||
_JOBS: dict[str, "SyncJob"] = {}
|
||||
|
||||
# 끝났지만 막대에서 빼는 쇼핑몰(수집할 수 없어 바로 끝난 것) — 전체 진행률 계산에서 제외
|
||||
PASSIVE_STATUS = frozenset({"not_implemented", "not_configured"})
|
||||
|
||||
|
||||
class ShopProgress(Progress):
|
||||
"""쇼핑몰 하나의 진행 상황. state: waiting → running → saving → done | error | skipped | cancelled."""
|
||||
|
||||
def __init__(self, code: str, name: str, *, active: bool = True, job: "SyncJob | None" = None) -> None:
|
||||
self.code, self.name, self.active, self.job = code, name, active, job
|
||||
self.state = "waiting"
|
||||
self.done = self.total = self.items = self.upserted = 0
|
||||
self.unit = "단계"
|
||||
self.status = self.label = self.message = ""
|
||||
self.started_at = self.finished_at = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# ── 어댑터가 부르는 쪽(Progress) ──
|
||||
def plan(self, total: int, unit: str = "단계") -> None:
|
||||
with self._lock:
|
||||
self.total, self.unit, self.done = max(0, int(total)), unit or "단계", 0
|
||||
|
||||
def add(self, n: int) -> None:
|
||||
with self._lock:
|
||||
self.total += max(0, int(n))
|
||||
|
||||
def check(self) -> None:
|
||||
if self.cancel_requested and self.state == "running":
|
||||
raise Cancelled("사용자가 업데이트를 취소했습니다.")
|
||||
|
||||
@property
|
||||
def cancel_requested(self) -> bool:
|
||||
return bool(self.job is not None and self.job.cancel_requested)
|
||||
|
||||
def step(self, n: int = 1, *, items: int = 0) -> None:
|
||||
self.check()
|
||||
with self._lock:
|
||||
self.done += max(0, int(n))
|
||||
self.items += max(0, int(items))
|
||||
if self.total and self.done > self.total: # 계획보다 많이 돌면 전체를 늘려 100% 를 넘지 않게
|
||||
self.total = self.done
|
||||
|
||||
# ── sync 가 부르는 쪽 ──
|
||||
def start(self) -> None:
|
||||
with self._lock:
|
||||
self.state, self.started_at = "running", time.time()
|
||||
|
||||
def saving(self) -> None:
|
||||
with self._lock:
|
||||
self.state = "saving"
|
||||
|
||||
def finish(self, *, upserted: int, message: str = "") -> None:
|
||||
with self._lock:
|
||||
self.state, self.upserted, self.message, self.status = "done", int(upserted), message, "ok"
|
||||
if self.total:
|
||||
self.done = self.total
|
||||
self.finished_at = time.time()
|
||||
|
||||
def fail(self, *, status: str, label: str, message: str) -> None:
|
||||
with self._lock:
|
||||
self.state, self.status, self.label, self.message = "error", status, label, message
|
||||
if status in PASSIVE_STATUS:
|
||||
self.active = False
|
||||
self.finished_at = time.time()
|
||||
|
||||
def cancelled(self) -> None:
|
||||
with self._lock:
|
||||
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
|
||||
self.finished_at = time.time()
|
||||
|
||||
def skip(self, message: str) -> None:
|
||||
with self._lock:
|
||||
self.state, self.status, self.message = "skipped", "running", message
|
||||
self.finished_at = time.time()
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return self.state in ("done", "error", "skipped", "cancelled")
|
||||
|
||||
def fraction(self) -> float:
|
||||
if self.finished:
|
||||
return 1.0
|
||||
if self.state == "saving":
|
||||
return 0.98
|
||||
if self.state == "running" and self.total:
|
||||
return min(0.97, self.done / self.total)
|
||||
return 0.0
|
||||
|
||||
def snapshot(self) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
return {
|
||||
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
|
||||
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
|
||||
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
|
||||
"fraction": round(self.fraction(), 4),
|
||||
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
|
||||
}
|
||||
|
||||
|
||||
class SyncJob:
|
||||
def __init__(self, *, user: str, start: date | None, end: date | None) -> None:
|
||||
self.id = uuid.uuid4().hex[:12]
|
||||
self.user, self.start, self.end = user, start, end
|
||||
self.created_at = time.time()
|
||||
self.finished_at = 0.0
|
||||
self.shops: list[ShopProgress] = []
|
||||
self.error = ""
|
||||
self.last_update_at: str | None = None
|
||||
self.cancel_requested = False
|
||||
self.cancelled_by = ""
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def set_targets(self, targets: list[tuple[str, str, bool]], start: date, end: date) -> dict[str, ShopProgress]:
|
||||
with self._lock:
|
||||
self.start, self.end = start, end
|
||||
self.shops = [ShopProgress(code, name, active=active, job=self) for code, name, active in targets]
|
||||
return {s.code: s for s in self.shops}
|
||||
|
||||
def cancel(self, user: str = "") -> None:
|
||||
"""[업데이트 취소] — 돌고 있는 쇼핑몰은 다음 API 호출 직전에, 기다리는 쇼핑몰은 차례가 오면 멈춘다."""
|
||||
with self._lock:
|
||||
if not self.finished_at and not self.cancel_requested:
|
||||
self.cancel_requested, self.cancelled_by = True, user
|
||||
|
||||
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
|
||||
with self._lock:
|
||||
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return bool(self.finished_at)
|
||||
|
||||
def snapshot(self) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
shops = [s.snapshot() for s in self.shops]
|
||||
active = [s for s in shops if s["active"]]
|
||||
return {
|
||||
"id": self.id, "finished": self.finished, "error": self.error, "user": self.user,
|
||||
"cancel_requested": self.cancel_requested,
|
||||
"from": self.start.isoformat() if self.start else None, "to": self.end.isoformat() if self.end else None,
|
||||
"elapsed": round((self.finished_at or time.time()) - self.created_at, 1),
|
||||
"last_update_at": self.last_update_at, "shops": shops,
|
||||
"overall": {
|
||||
"shops": len(active),
|
||||
"finished": sum(1 for s in active if s["state"] in ("done", "error", "skipped", "cancelled")),
|
||||
"fraction": round(sum(s["fraction"] for s in active) / len(active), 4) if active else
|
||||
(1.0 if self.finished else 0.0),
|
||||
"items": sum(s["items"] for s in shops), "upserted": sum(s["upserted"] for s in shops),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def create_job(*, user: str, start: date | None, end: date | None) -> SyncJob:
|
||||
job = SyncJob(user=user, start=start, end=end)
|
||||
with _LOCK:
|
||||
_JOBS[job.id] = job
|
||||
if len(_JOBS) > MAX_JOBS: # 오래된 끝난 작업부터 정리
|
||||
for jid, j in sorted(_JOBS.items(), key=lambda kv: kv[1].created_at):
|
||||
if len(_JOBS) <= MAX_JOBS:
|
||||
break
|
||||
if j.finished:
|
||||
del _JOBS[jid]
|
||||
return job
|
||||
|
||||
|
||||
def get_job(job_id: str) -> SyncJob | None:
|
||||
with _LOCK:
|
||||
return _JOBS.get(job_id)
|
||||
|
||||
|
||||
def running_job() -> SyncJob | None:
|
||||
"""지금 돌고 있는 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
|
||||
with _LOCK:
|
||||
live = [j for j in _JOBS.values() if not j.finished]
|
||||
return max(live, key=lambda j: j.created_at) if live else None
|
||||
@@ -0,0 +1,411 @@
|
||||
"""실적 모듈 라우터 (prefix=/performance).
|
||||
|
||||
화면
|
||||
GET /performance/ 대시보드(모듈 권한)
|
||||
GET /performance/settings 실적 설정(관리자)
|
||||
JSON API — 모듈 권한
|
||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
|
||||
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
|
||||
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
||||
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
||||
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}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
|
||||
if payload.get("background"):
|
||||
return JSONResponse(_start_background_sync(store, sync, start=start, end=end, codes=codes or None,
|
||||
user=user["email"]))
|
||||
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()})
|
||||
|
||||
|
||||
def _start_background_sync(store: Any, sync: Any, *, start: date | None, end: date | None,
|
||||
codes: list[str] | None, user: str) -> dict[str, Any]:
|
||||
"""수집을 스레드로 돌리고 작업 번호를 바로 돌려준다. 이미 돌고 있는 업데이트가 있으면 새로 시작하지 않고
|
||||
그 작업을 보여 준다(같은 쇼핑몰 동시 실행은 어차피 막혀 있다)."""
|
||||
import logging # noqa: WPS433
|
||||
import threading # noqa: WPS433
|
||||
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
live = jobs.running_job()
|
||||
if live is not None:
|
||||
return {"job": live.snapshot(), "joined": True}
|
||||
job = jobs.create_job(user=user, start=start, end=end)
|
||||
|
||||
def run() -> None:
|
||||
error = ""
|
||||
try:
|
||||
sync.sync_all(start=start, end=end, codes=codes, user=user, job=job)
|
||||
except Exception as exc: # noqa: BLE001 — 스레드 밖으로 새지 않게, 화면에는 "오류"로
|
||||
logging.getLogger("performance.sync").exception("background sync failed")
|
||||
error = f"업데이트 중 오류: {type(exc).__name__}"
|
||||
last = None
|
||||
try:
|
||||
last = store.last_update_at()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
job.finish(error=error, last_update_at=last)
|
||||
|
||||
threading.Thread(target=run, name=f"perf-sync-{job.id}", daemon=True).start()
|
||||
return {"job": job.snapshot(), "joined": False}
|
||||
|
||||
|
||||
@router.get("/api/sync/jobs/{job_id}")
|
||||
def api_sync_job(request: Request, job_id: str) -> JSONResponse:
|
||||
common.require_store(request)
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
job = jobs.get_job(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
|
||||
return JSONResponse({"job": job.snapshot()})
|
||||
|
||||
|
||||
@router.post("/api/sync/jobs/{job_id}/cancel")
|
||||
def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
|
||||
"""[업데이트 취소] — 시작한 사람 또는 관리자. 돌고 있는 쇼핑몰은 다음 API 호출 직전에 멈추고(저장 전이면 DB 그대로),
|
||||
기다리는 쇼핑몰은 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 그대로 남는다."""
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
_, user = common.require_store(request)
|
||||
job = jobs.get_job(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
|
||||
if job.user and job.user != user["email"] and not is_admin(user):
|
||||
raise HTTPException(status_code=403, detail="업데이트를 시작한 사람이나 관리자만 취소할 수 있습니다.")
|
||||
job.cancel(user["email"])
|
||||
return JSONResponse({"job": job.snapshot()})
|
||||
|
||||
|
||||
@router.get("/api/sync/current")
|
||||
def api_sync_current(request: Request) -> JSONResponse:
|
||||
common.require_store(request)
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
job = jobs.running_job()
|
||||
return JSONResponse({"job": job.snapshot() if job else None})
|
||||
|
||||
|
||||
@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,235 @@
|
||||
"""① 수집 서비스 — 쇼핑몰 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, Cancelled, 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 = "", progress: Any = None) -> dict[str, Any]:
|
||||
"""progress: jobs.ShopProgress(매출 업데이트 창 진행 막대) — 없으면 알리지 않는다."""
|
||||
adapter = get_adapter(code)
|
||||
result: dict[str, Any] = {"code": code, "ok": False, "skipped": False, "fetched": 0, "upserted": 0}
|
||||
if adapter is None:
|
||||
if progress is not None:
|
||||
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
|
||||
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
||||
if progress is not None and progress.cancel_requested: # [업데이트 취소] 뒤 차례가 온 쇼핑몰
|
||||
progress.cancelled()
|
||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
||||
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
|
||||
if run_id is None:
|
||||
if progress is not None:
|
||||
progress.skip("이미 다른 업데이트가 진행 중입니다.")
|
||||
return {**result, "skipped": True, "status": "running", "message": "이미 업데이트 중입니다."}
|
||||
if progress is not None:
|
||||
progress.start()
|
||||
ctx = None
|
||||
try:
|
||||
ctx = self._ctx(adapter, user=user)
|
||||
if progress is not None:
|
||||
ctx.progress = progress
|
||||
fetched, events = adapter.collect(ctx, start, end)
|
||||
if progress is not None:
|
||||
progress.saving()
|
||||
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)
|
||||
if progress is not None:
|
||||
progress.finish(upserted=upserted, message=f"{upserted}건 반영")
|
||||
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
|
||||
"message": f"{upserted}건 반영"}
|
||||
except Cancelled:
|
||||
# 수집 중 취소 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
|
||||
self._store.finish_run(run_id, ok=False, error="업데이트 취소")
|
||||
if progress is not None:
|
||||
progress.cancelled()
|
||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
||||
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)
|
||||
if progress is not None:
|
||||
progress.fail(status=status, label=STATUS_LABELS.get(status, status), message=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 = "", job: Any = None) -> list[dict[str, Any]]:
|
||||
"""job: jobs.SyncJob — 주면 쇼핑몰마다 진행 상황(ShopProgress)을 채운다(매출 업데이트 창)."""
|
||||
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 for a in all_adapters() if a.code in enabled and (not codes or a.code in codes)]
|
||||
progress: dict[str, Any] = {}
|
||||
if job is not None:
|
||||
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
|
||||
# 쇼핑몰이 전체 진행률을 부풀리거나, 아직 차례가 안 와서 진행률을 낮추지 않게.
|
||||
def ready(a: MarketplaceAdapter) -> bool:
|
||||
if not a.implemented:
|
||||
return False
|
||||
try:
|
||||
return a.is_configured(self._ctx(a, user=user))
|
||||
except Exception: # noqa: BLE001 — 확인이 안 되면 일단 막대로(실제 결과는 수집 때 나온다)
|
||||
return True
|
||||
|
||||
progress = job.set_targets([(a.code, a.name, ready(a)) for a in targets], start, end)
|
||||
return [self.sync_marketplace(a.code, start, end, trigger=trigger, user=user, progress=progress.get(a.code))
|
||||
for a 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=20260930g" />{% 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=20260930zb" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,180 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% 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">쇼핑몰 원본 데이터 확인</h2></div>
|
||||
<p class="perf-muted">쇼핑몰 API 를 기간(최대 31일)으로 실제 불러, 받은 항목·금액 합계를 보여 줍니다(저장하지 않음).
|
||||
쇼핑몰 관리자 화면에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다.
|
||||
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
|
||||
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
||||
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.</p>
|
||||
<div class="perf-sample-form">
|
||||
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
||||
<option value="naver">네이버 스마트스토어</option>
|
||||
<option value="elevenst">11번가</option>
|
||||
<option value="gsshop">GS샵</option>
|
||||
</select>
|
||||
<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">불러오기</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=20260930zb" defer></script>{% endblock %}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,151 @@
|
||||
"""프로젝트 관리 — 현재 접근 권한의 공통 기준(서버).
|
||||
|
||||
라우터·마감 알림이 같은 규칙을 쓰도록 한 곳에 모은다. 모든 판단은 "지금" 기준이다 —
|
||||
예전에 멤버였거나 담당자·멘션·협업자로 기록돼 있어도, 지금 권한이 없으면 보이지도
|
||||
바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다).
|
||||
|
||||
프로젝트
|
||||
관리(=보기·작업 CRUD) : 관리자(is_admin) · 프로젝트 owner · 배정 멤버. 모두 `project` 모듈 권한이 있어야 한다.
|
||||
|
||||
작업
|
||||
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(삭제는 추가로 생성자 규칙)
|
||||
READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음
|
||||
→ 그 작업의 상세·하위 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
|
||||
연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용.
|
||||
None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Iterable
|
||||
|
||||
from . import store
|
||||
|
||||
FULL = "full"
|
||||
READ = "read"
|
||||
|
||||
UserLookup = Callable[[str], "dict[str, Any] | None"]
|
||||
|
||||
|
||||
def default_user_lookup(email: str) -> dict[str, Any] | None:
|
||||
"""등록 사용자 레코드(app.main.user_store). 지연 import — 테스트는 lookup 을 직접 넘긴다."""
|
||||
from app.main import user_store # noqa: WPS433
|
||||
|
||||
return user_store.get(store.norm_str(email, lower=True))
|
||||
|
||||
|
||||
def _is_admin(user: dict[str, Any] | None) -> bool:
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
return is_admin(user)
|
||||
|
||||
|
||||
def can_use_module(user: dict[str, Any] | None) -> bool:
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
return bool(user) and has_module(user, "project")
|
||||
|
||||
|
||||
def email_of(user: dict[str, Any] | None) -> str:
|
||||
return store.norm_str((user or {}).get("email", ""), lower=True)
|
||||
|
||||
|
||||
def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool:
|
||||
"""프로젝트 관리(=보기·작업 CRUD) — 관리자 또는 owner/멤버. 모듈 권한이 없으면 False."""
|
||||
if not can_use_module(user):
|
||||
return False
|
||||
if _is_admin(user):
|
||||
return True
|
||||
try:
|
||||
pid = int(project_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return bool(st.is_member(project_id=pid, user_email=email_of(user)))
|
||||
|
||||
|
||||
def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
|
||||
"""관리할 수 있는 프로젝트 id 집합. 관리자는 None(=전체)."""
|
||||
if _is_admin(user):
|
||||
return None
|
||||
if not can_use_module(user):
|
||||
return set()
|
||||
return {
|
||||
int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user))
|
||||
}
|
||||
|
||||
|
||||
def task_access(st: Any, user: dict[str, Any] | None, task: dict[str, Any] | None) -> str | None:
|
||||
"""작업 하나에 대한 지금 권한: FULL / READ / None."""
|
||||
if not task or not can_use_module(user):
|
||||
return None
|
||||
if can_manage_project(st, user, task.get("project_id")):
|
||||
return FULL
|
||||
for pid in link_scope(st, [int(task["id"])]).get(int(task["id"]), set()):
|
||||
if can_manage_project(st, user, pid):
|
||||
return READ
|
||||
return None
|
||||
|
||||
|
||||
def link_scope(st: Any, task_ids: Iterable[int]) -> dict[int, set[int]]:
|
||||
"""작업 id → 이 작업 또는 상위 작업이 연결된 프로젝트 id 들. 연결 표가 없으면 빈 값."""
|
||||
ids = [int(i) for i in task_ids]
|
||||
if not ids:
|
||||
return {}
|
||||
try:
|
||||
return st.task_link_scope(task_ids=ids)
|
||||
except Exception: # noqa: BLE001 - 003 미적용(연결 기능 없음) → 연결로 보이는 작업 없음
|
||||
return {}
|
||||
|
||||
|
||||
def filter_visible_tasks(st: Any, user: dict[str, Any], tasks: list[dict[str, Any]],
|
||||
*, key: str = "id") -> list[dict[str, Any]]:
|
||||
"""목록에서 지금 볼 수 있는(FULL 또는 READ) 작업만 남긴다 — 내 작업·수신함·알림 공용."""
|
||||
allowed = visible_project_ids(st, user)
|
||||
if allowed is None:
|
||||
return list(tasks)
|
||||
ids = [int(t[key]) for t in tasks if t.get(key) is not None]
|
||||
scope = link_scope(st, ids)
|
||||
out = []
|
||||
for t in tasks:
|
||||
tid = t.get(key)
|
||||
pid = t.get("project_id")
|
||||
if pid is not None and int(pid) in allowed:
|
||||
out.append(t)
|
||||
elif tid is not None and scope.get(int(tid), set()) & allowed:
|
||||
out.append(t)
|
||||
return out
|
||||
|
||||
|
||||
def email_task_access(st: Any, email: str, task: dict[str, Any],
|
||||
lookup: UserLookup | None = None) -> str | None:
|
||||
"""이메일(알림·멘션 대상)이 지금 이 작업을 볼 수 있는지. 등록 안 된 사람·모듈 권한 없는 사람은 None."""
|
||||
rec = (lookup or default_user_lookup)(email)
|
||||
if not rec:
|
||||
return None
|
||||
rec = {**rec, "email": rec.get("email") or email}
|
||||
return task_access(st, rec, task)
|
||||
|
||||
|
||||
def filter_recipients(st: Any, task: dict[str, Any], emails: Iterable[str],
|
||||
lookup: UserLookup | None = None) -> list[str]:
|
||||
"""알림·메일·멘션 대상 중 지금 이 작업을 볼 수 있는 사람만(순서 유지, 중복 제거)."""
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for e in emails:
|
||||
em = store.norm_str(e, lower=True)
|
||||
if not em or em in seen:
|
||||
continue
|
||||
seen.add(em)
|
||||
if email_task_access(st, em, task, lookup) is not None:
|
||||
out.append(em)
|
||||
return out
|
||||
|
||||
|
||||
def can_assign(st: Any, email: str, project_id: Any, lookup: UserLookup | None = None) -> bool:
|
||||
"""담당자·소유자 후보 — 등록된 사용자이고 project 모듈 권한이 있으며, 그 프로젝트를
|
||||
관리할 수 있어야 한다(관리자 포함). 권한 없는 사람에게 작업 정보가 담긴 알림이 가지 않게."""
|
||||
rec = (lookup or default_user_lookup)(email)
|
||||
if not rec:
|
||||
return False
|
||||
rec = {**rec, "email": rec.get("email") or email}
|
||||
return can_manage_project(st, rec, project_id)
|
||||
+137
-5
@@ -100,6 +100,7 @@ class ProjectStore:
|
||||
ic = store.validate_project_icon(icon)
|
||||
sd = store.validate_date(start_date)
|
||||
dd = store.validate_date(due_date)
|
||||
store.validate_date_range(sd, dd)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
if parent_id is not None:
|
||||
@@ -158,15 +159,26 @@ class ProjectStore:
|
||||
}
|
||||
sets: list[str] = []
|
||||
params: list[Any] = []
|
||||
clean: dict[str, Any] = {}
|
||||
for key, fn in allowed.items():
|
||||
if key in fields:
|
||||
clean[key] = fn(fields[key])
|
||||
sets.append(f"{key} = %s")
|
||||
params.append(fn(fields[key]))
|
||||
params.append(clean[key])
|
||||
if not sets:
|
||||
existing = self.get_project(project_id=project_id)
|
||||
if existing is None:
|
||||
raise KeyError(project_id)
|
||||
return existing
|
||||
if "start_date" in clean or "due_date" in clean:
|
||||
# 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다.
|
||||
existing = self.get_project(project_id=project_id)
|
||||
if existing is None:
|
||||
raise KeyError(project_id)
|
||||
store.validate_date_range(
|
||||
clean["start_date"] if "start_date" in clean else existing.get("start_date"),
|
||||
clean["due_date"] if "due_date" in clean else existing.get("due_date"),
|
||||
)
|
||||
params.append(project_id)
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
@@ -605,7 +617,9 @@ class ProjectStore:
|
||||
dd = store.validate_date(due_date)
|
||||
sti = store.validate_time(start_time)
|
||||
dti = store.validate_time(due_time)
|
||||
store.validate_date_range(sd, dd, sti, dti)
|
||||
assignee = store.norm_str(assignee_email, lower=True)
|
||||
done_at = None
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
if parent_task_id is not None:
|
||||
@@ -636,6 +650,13 @@ class ProjectStore:
|
||||
# 세션이 없어 해당 없음).
|
||||
if not assignee and stage_id is not None:
|
||||
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id)
|
||||
# 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력).
|
||||
if stage_id is not None:
|
||||
done_row = conn.execute(
|
||||
"SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)
|
||||
).fetchone()
|
||||
if done_row and done_row["is_done_stage"]:
|
||||
done_at = now_kst()
|
||||
nxt = conn.execute(
|
||||
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
|
||||
"WHERE project_id = %s",
|
||||
@@ -646,21 +667,26 @@ class ProjectStore:
|
||||
INSERT INTO tasks
|
||||
(project_id, stage_id, parent_task_id, title, description,
|
||||
assignee_email, assignee_name, priority, start_date, due_date,
|
||||
start_time, due_time, sort_order, created_by)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
start_time, due_time, sort_order, created_by, completed_at)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
RETURNING *
|
||||
""",
|
||||
(
|
||||
project_id, stage_id, parent_task_id, ttl, store.norm_str(description),
|
||||
assignee, store.norm_str(assignee_name), pr, sd, dd,
|
||||
sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True),
|
||||
sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), done_at,
|
||||
),
|
||||
).fetchone()
|
||||
if assignee:
|
||||
self._log(conn, project_id=project_id, task_id=row["id"],
|
||||
actor=created_by, action=store.ACTION_ASSIGNED,
|
||||
detail=f"{ttl} → {assignee}")
|
||||
return self.get_task(task_id=row["id"])
|
||||
if done_at is not None:
|
||||
self._log(conn, project_id=project_id, task_id=row["id"],
|
||||
actor=created_by, action=store.ACTION_COMPLETED, detail=ttl)
|
||||
out = self.get_task(task_id=row["id"])
|
||||
out["_newly_completed"] = done_at is not None
|
||||
return out
|
||||
|
||||
def move_subtask(
|
||||
self, *, task_id: int, parent_task_id: int, actor: str = ""
|
||||
@@ -806,6 +832,15 @@ class ProjectStore:
|
||||
if not sets:
|
||||
return {**prev, "_newly_assigned": None, "_newly_completed": False}
|
||||
|
||||
# 날짜 범위 — 한쪽만 바꾸거나 지워도 기존 값과 합친 최종 상태로 검사.
|
||||
if any(k in fields for k in ("start_date", "due_date", "start_time", "due_time")):
|
||||
def final(key: str, fn: Any) -> Any:
|
||||
return fn(fields[key]) if key in fields else prev.get(key)
|
||||
store.validate_date_range(
|
||||
final("start_date", store.validate_date), final("due_date", store.validate_date),
|
||||
final("start_time", store.validate_time), final("due_time", store.validate_time),
|
||||
)
|
||||
|
||||
params.append(task_id)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
@@ -1217,6 +1252,51 @@ class ProjectStore:
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
def add_comment_with_attachments(
|
||||
self, *, task_id: int, author_email: str, author_name: str, body: str,
|
||||
files: list[dict[str, Any]], parent_id: int | None = None,
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""댓글과 첨부를 한 트랜잭션에 — 둘 중 하나라도 실패하면 아무것도 남지 않는다
|
||||
(첨부 없이 빈 댓글만 남던 문제). files = [{filename, stored_name, content_type, size_bytes}].
|
||||
본문이 비어도 되지만 첨부가 한 개 이상 있어야 한다."""
|
||||
text = store.norm_str(body)
|
||||
if not files and not text:
|
||||
raise ValueError("댓글 내용이 비었습니다.")
|
||||
author = store.norm_str(author_email, lower=True)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
root = None
|
||||
if parent_id:
|
||||
p = conn.execute(
|
||||
"SELECT id, task_id, parent_id FROM task_comments WHERE id = %s", (parent_id,)
|
||||
).fetchone()
|
||||
if not p or int(p["task_id"]) != int(task_id):
|
||||
raise ValueError("답글을 달 댓글을 찾을 수 없습니다.")
|
||||
root = int(p["parent_id"] or p["id"])
|
||||
if root is not None:
|
||||
row = conn.execute(
|
||||
"INSERT INTO task_comments (task_id, author_email, author_name, body, parent_id) "
|
||||
"VALUES (%s,%s,%s,%s,%s) RETURNING *",
|
||||
(task_id, author, store.norm_str(author_name), text, root),
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"INSERT INTO task_comments (task_id, author_email, author_name, body) "
|
||||
"VALUES (%s,%s,%s,%s) RETURNING *",
|
||||
(task_id, author, store.norm_str(author_name), text),
|
||||
).fetchone()
|
||||
atts = []
|
||||
for f in files:
|
||||
atts.append(conn.execute(
|
||||
"INSERT INTO task_attachments "
|
||||
"(task_id, filename, stored_name, content_type, size_bytes, uploaded_by, comment_id) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING *",
|
||||
(task_id, store.norm_str(f["filename"]), f["stored_name"],
|
||||
store.norm_str(f.get("content_type") or "application/octet-stream"),
|
||||
int(f["size_bytes"]), author, row["id"]),
|
||||
).fetchone())
|
||||
return self._serialize(row), [self._serialize(a) for a in atts]
|
||||
|
||||
def update_comment(
|
||||
self, *, comment_id: int, requester: str, is_admin: bool, body: str
|
||||
) -> dict[str, Any]:
|
||||
@@ -1655,6 +1735,58 @@ class ProjectStore:
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def add_reminder_notification(
|
||||
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
|
||||
project_id: int | None, title: str, body: str,
|
||||
) -> bool:
|
||||
"""마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True,
|
||||
이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서
|
||||
다시 시도된다(예전엔 기록만 남아 영영 안 갔다). 동시에 두 번 돌아도 UNIQUE 로 한 번만."""
|
||||
rcpt = store.norm_str(recipient_email, lower=True)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"INSERT INTO task_reminders (task_id, kind, due_date, recipient_email) "
|
||||
"VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING RETURNING id",
|
||||
(task_id, kind, due_date, rcpt),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
conn.execute(
|
||||
"INSERT INTO project_notifications "
|
||||
"(recipient_email, actor_email, project_id, task_id, type, title, body) "
|
||||
"VALUES (%s,'',%s,%s,%s,%s,%s)",
|
||||
(rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)),
|
||||
)
|
||||
return True
|
||||
|
||||
def task_link_scope(self, *, task_ids: list[int]) -> dict[int, set[int]]:
|
||||
"""작업 id → 이 작업 또는 그 상위 작업들이 연결(멀티호밍)된 프로젝트 id 집합.
|
||||
연결된 프로젝트 멤버가 그 작업(과 하위 작업)을 읽기 전용으로 볼 수 있는지 판단한다."""
|
||||
ids = sorted({int(i) for i in task_ids})
|
||||
if not ids:
|
||||
return {}
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
WITH RECURSIVE chain AS (
|
||||
SELECT id AS task_id, id AS anc_id, parent_task_id, 0 AS depth
|
||||
FROM tasks WHERE id = ANY(%s)
|
||||
UNION ALL
|
||||
SELECT c.task_id, t.id, t.parent_task_id, c.depth + 1
|
||||
FROM chain c JOIN tasks t ON t.id = c.parent_task_id
|
||||
WHERE c.depth < 20
|
||||
)
|
||||
SELECT c.task_id, l.project_id
|
||||
FROM chain c JOIN task_project_links l ON l.task_id = c.anc_id
|
||||
""",
|
||||
(ids,),
|
||||
).fetchall()
|
||||
out: dict[int, set[int]] = {}
|
||||
for r in rows:
|
||||
out.setdefault(int(r["task_id"]), set()).add(int(r["project_id"]))
|
||||
return out
|
||||
|
||||
def record_reminder(
|
||||
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
|
||||
) -> bool:
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
· due_today — 오늘 마감
|
||||
· overdue — 마감이 지남(최근 7일 이내 마감분만 — 첫 적용 때 오래된 업무가
|
||||
한꺼번에 쏟아지지 않게, 연휴로 며칠 건너뛰어도 놓치지 않게)
|
||||
수신자는 담당자. 담당자가 없으면 팔로워 전원.
|
||||
수신자는 담당자. 담당자가 없으면 팔로워 전원. 단, 지금 그 작업을 볼 수 있는 사람만.
|
||||
|
||||
중복 방지: task_reminders(업무, 종류, 마감일, 수신자) UNIQUE — 같은 알림은 한 번만
|
||||
간다(재기동·여러 번 실행해도 안전). 마감일을 바꾸면 새 마감일 기준으로 다시 알린다.
|
||||
발송 기록과 수신함 알림은 한 트랜잭션이라, 알림 생성이 실패하면 다음 실행에 다시 시도된다.
|
||||
|
||||
실행 방식: 웹 프로세스 안의 데몬 스레드(start_reminder_thread). 5분마다 깨어나
|
||||
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
|
||||
@@ -33,7 +34,7 @@ from typing import Any
|
||||
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from . import access, store
|
||||
|
||||
logger = logging.getLogger("project.reminders")
|
||||
|
||||
@@ -87,8 +88,18 @@ def _title_for(kind: str, task: dict[str, Any], today: date) -> str:
|
||||
return f"마감 지남({(today - due).days}일): {task['title']}"
|
||||
|
||||
|
||||
def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]:
|
||||
"""한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다."""
|
||||
def run_due_reminders(
|
||||
st: Any, *, today: date | None = None, lookup: access.UserLookup | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다.
|
||||
|
||||
- 수신자는 지금 그 작업을 볼 수 있는 사람만(access.filter_recipients) — 멤버에서 빠진 담당자·
|
||||
협업자, 모듈 권한이 없어진 직원에게는 수신함 알림도 메일도 가지 않는다.
|
||||
- 발송 기록(task_reminders)과 수신함 알림은 한 트랜잭션(add_reminder_notification) — 알림 생성이
|
||||
실패하면 기록도 되돌려져 다음 실행에서 다시 시도된다. 같은 알림은 UNIQUE 로 한 번만(동시 실행 포함).
|
||||
- 보장 범위: 수신함 알림까지. 메일(PROJECT_REMINDER_EMAIL)은 알림이 새로 만들어진 것만 요약해 한 번
|
||||
보내며, 메일 발송 실패는 재시도하지 않는다(수신함 알림은 이미 남아 있다).
|
||||
"""
|
||||
today = today or now_kst().date()
|
||||
start = today - timedelta(days=OVERDUE_WINDOW_DAYS)
|
||||
end = next_workday(today)
|
||||
@@ -101,22 +112,25 @@ def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]:
|
||||
if kind is None:
|
||||
continue
|
||||
assignee = store.norm_str(t.get("assignee_email"), lower=True)
|
||||
recipients = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
|
||||
wanted = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
|
||||
try:
|
||||
recipients = access.filter_recipients(st, t, wanted, lookup)
|
||||
except Exception: # noqa: BLE001 - 권한 확인이 안 되면 이번엔 보내지 않는다(다음 실행에 재시도)
|
||||
logger.warning("마감 알림 수신자 확인 실패: task=%s", t["id"])
|
||||
continue
|
||||
for rcpt in recipients:
|
||||
if not st.record_reminder(
|
||||
task_id=t["id"], kind=kind, due_date=t["due_date"][:10], recipient_email=rcpt,
|
||||
):
|
||||
continue # 이미 보냄
|
||||
title = _title_for(kind, t, today)
|
||||
try:
|
||||
st.add_notification(
|
||||
recipient_email=rcpt, actor_email="", project_id=t["project_id"],
|
||||
task_id=t["id"], type=kind, title=title,
|
||||
created = st.add_reminder_notification(
|
||||
task_id=t["id"], kind=kind, due_date=t["due_date"][:10], recipient_email=rcpt,
|
||||
project_id=t["project_id"], title=title,
|
||||
body=f"{t.get('project_name') or ''} · 마감 {t['due_date'][:10]}",
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("마감 알림 생성 실패: task=%s", t["id"])
|
||||
except Exception: # noqa: BLE001 - 기록도 되돌려졌으니 다음 실행에서 다시 시도
|
||||
logger.warning("마감 알림 생성 실패(다음 실행에 재시도): task=%s", t["id"])
|
||||
continue
|
||||
if not created:
|
||||
continue # 이미 보냄
|
||||
counts[kind] += 1
|
||||
digest.setdefault(rcpt, []).append((title, t))
|
||||
|
||||
|
||||
+486
-172
File diff suppressed because it is too large
Load Diff
@@ -313,6 +313,30 @@ def validate_date(d: Any) -> str | None:
|
||||
return v[:10]
|
||||
|
||||
|
||||
DATE_RANGE_ERROR = "시작일이 마감일보다 늦을 수 없습니다."
|
||||
TIME_RANGE_ERROR = "같은 날이면 시작 시각이 마감 시각보다 늦을 수 없습니다."
|
||||
|
||||
|
||||
def validate_date_range(
|
||||
start_date: Any, due_date: Any, start_time: Any = None, due_time: Any = None
|
||||
) -> None:
|
||||
"""최종 상태(부분 수정이면 기존 값 + 바꾼 값)의 날짜 범위 검사 — 프로젝트·작업 공용.
|
||||
|
||||
둘 다 있으면 start_date <= due_date. 같은 날이고 두 시각이 모두 있으면 start_time <= due_time.
|
||||
한쪽이 비어 있는 입력은 허용. 값 형식 오류는 validate_date/validate_time 이 먼저 낸다.
|
||||
"""
|
||||
sd = validate_date(start_date)
|
||||
dd = validate_date(due_date)
|
||||
if sd and dd:
|
||||
if sd > dd:
|
||||
raise ValueError(DATE_RANGE_ERROR)
|
||||
if sd == dd:
|
||||
st = validate_time(start_time)
|
||||
dt = validate_time(due_time)
|
||||
if st and dt and st > dt:
|
||||
raise ValueError(TIME_RANGE_ERROR)
|
||||
|
||||
|
||||
def validate_time(t: Any) -> str | None:
|
||||
"""'HH:MM' 형식만 통과(초는 버림). 빈값/None 은 None(=종일)."""
|
||||
v = norm_str(t)
|
||||
@@ -334,11 +358,14 @@ def validate_time(t: Any) -> str | None:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스
|
||||
GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적
|
||||
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색만(글자는 항상 진한 색).
|
||||
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄).
|
||||
# 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다.
|
||||
# 빈 문자열 = 색 없음(흰 배경, GOAL_NO_COLOR).
|
||||
GOAL_AREA_COLORS: tuple[str, ...] = (
|
||||
"#fbe1d5", "#d9f2d0", "#d4d4d4", "#f0cdec",
|
||||
"#dbe8fb", "#fff2c2", "#e3dcfb", "#d3f0ee",
|
||||
"#fcd9d9", "#fde4c8", "#fbe1d5", "#fff2c2", "#eef5c8", "#d9f2d0", "#c9ecd9", "#d3f0ee",
|
||||
"#cfeaf7", "#dbe8fb", "#e3dcfb", "#f0cdec", "#fcdcec", "#eadcd0", "#d4d4d4", "#eef0f2",
|
||||
)
|
||||
GOAL_NO_COLOR = ""
|
||||
# 새 연도를 만들 때 이전 연도가 없으면 이 영역으로 시작한다(이전 연도가 있으면 그 구조를 복사).
|
||||
DEFAULT_GOAL_AREAS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
||||
("상품", "#fbe1d5", ("",)),
|
||||
@@ -401,7 +428,10 @@ def validate_goal_row_label(label: Any) -> str:
|
||||
|
||||
|
||||
def validate_goal_color(color: Any) -> str:
|
||||
"""영역 색 — 16색 중 하나, 빈값/"none" 은 색 없음(""), 목록 밖은 첫 색."""
|
||||
v = norm_str(color).lower()
|
||||
if v in ("", "none"):
|
||||
return GOAL_NO_COLOR
|
||||
return v if v in GOAL_AREA_COLORS else GOAL_AREA_COLORS[0]
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -66,8 +66,9 @@
|
||||
data-admin="{{ 'true' if is_admin else 'false' }}">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="pj-goal-c1"></th>
|
||||
<th class="pj-goal-c2"></th>
|
||||
{# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(localStorage pj_goal_col_w) #}
|
||||
<th class="pj-goal-c1"><span class="pj-goal-colresize" data-col="c1" title="끌어서 너비 조절"></span></th>
|
||||
<th class="pj-goal-c2"><span class="pj-goal-colresize" data-col="c2" title="끌어서 너비 조절"></span></th>
|
||||
<th class="pj-goal-year-col">연간</th>
|
||||
{% for mo in months %}<th class="{% if mo == this_month %}is-now{% endif %}">{{ mo }}월</th>{% endfor %}
|
||||
</tr>
|
||||
@@ -106,7 +107,7 @@
|
||||
|
||||
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #}
|
||||
{% for area in board.areas %}
|
||||
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color }}">
|
||||
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
||||
{% for row in area.rows %}
|
||||
<tr data-row-id="{{ row.id }}">
|
||||
{% if loop.first %}
|
||||
@@ -168,5 +169,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20260930a" defer></script>
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -119,7 +119,9 @@
|
||||
<tr><td>작업·섹션·프로젝트 삭제</td><td><b>만든 사람만</b> 지울 수 있습니다(최고 관리자는 예외).</td></tr>
|
||||
<tr><td>댓글 고치기·지우기</td><td>댓글을 쓴 사람(또는 관리자)만.</td></tr>
|
||||
<tr><td>새 프로젝트, 프로젝트 수정·순서 바꾸기</td><td>관리자 (<span class="pjh-ui">+</span> · <span class="pjh-ui">✎</span> · <span class="pjh-ui">⣿</span> 버튼이 관리자에게만 보입니다)</td></tr>
|
||||
<tr><td>멤버 배정·제외</td><td>관리자</td></tr>
|
||||
<tr><td>멤버 배정·제외, 프로젝트 소유자 바꾸기</td><td>관리자</td></tr>
|
||||
<tr><td>다른 프로젝트에서 연결돼 온 작업</td><td>원래 프로젝트 멤버가 아니면 <b>읽기만</b> — 내용·댓글·첨부는 보이지만 고치거나 댓글을 달 수 없습니다(연결된 보드 안에서 섹션 옮기기는 됩니다).</td></tr>
|
||||
<tr><td>멤버에서 빠졌을 때</td><td>그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고, 예전 링크로도 열리지 않습니다. 새 알림도 오지 않습니다.</td></tr>
|
||||
<tr><td>휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트</td><td>관리자</td></tr>
|
||||
<tr><td>목표 보기</td><td>누구나 · <b>목표 입력·연도 추가·업무 영역 편집</b>은 관리자</td></tr>
|
||||
</table>
|
||||
@@ -263,7 +265,7 @@
|
||||
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 작업의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 작업을 엽니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>작업을 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
|
||||
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 하위 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 작업을 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
|
||||
</table>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 하위 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
||||
@@ -301,7 +303,8 @@
|
||||
</ol>
|
||||
<p>작업은 하나라서 어느 보드에서 고쳐도 모두 같이 바뀝니다.</p>
|
||||
<h3>댓글</h3>
|
||||
<p>작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다.</p>
|
||||
<p>작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <span class="pjh-ui">댓글</span> 표시가 붙습니다.</p>
|
||||
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 9. 작업 창의 하위 작업 -->
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -104,5 +104,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20260930a" defer></script>
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20260930a" defer></script>
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -265,6 +265,11 @@
|
||||
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
|
||||
</button>
|
||||
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="작업 제목"></textarea>
|
||||
<!-- 다른 프로젝트에서 연결돼 온 작업을 원 소속 권한 없이 열었을 때 — 보기만 된다(서버도 변경 거절). -->
|
||||
<div class="pj-readonly-note" id="pj-t-readonly" hidden>
|
||||
<span class="material-symbols-outlined">visibility</span>
|
||||
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 작업이라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
|
||||
</div>
|
||||
|
||||
<div class="pj-modal-body">
|
||||
<div class="pj-modal-col-main">
|
||||
@@ -491,5 +496,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20260930a" defer></script>
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20260930a" defer></script>
|
||||
<script src="/static/project.js?v=20260930g" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -59,29 +59,86 @@
|
||||
|
||||
var state = { option: null, variants: [], displayTypes: {}, orphans: [], imageBase: "" };
|
||||
|
||||
// 모달은 페이지에 하나라 여러 상품이 같은 body 를 쓴다. 이 상품으로 연 "회차"(modal.gen)가
|
||||
// 바뀌었거나(닫힘·다른 상품) 더 나중에 보낸 조회가 있으면, 늦게 도착한 응답은 버린다.
|
||||
// (A 상품 응답이 B 상품 창에 그려지거나, 먼저 보낸 조회가 나중 조회를 덮는 것을 막는다.)
|
||||
var myGen = -1;
|
||||
var loadSeq = 0;
|
||||
function alive() { return modal.isOpen() && modal.gen === myGen; }
|
||||
|
||||
openBtn.addEventListener("click", function () {
|
||||
var nameEl = document.getElementById("cf24-name-text");
|
||||
modal.open((nameEl ? nameEl.textContent : "") + " (상품번호 " + no + ")");
|
||||
myGen = modal.gen;
|
||||
load();
|
||||
});
|
||||
|
||||
function load() {
|
||||
var seq = ++loadSeq;
|
||||
var gen = myGen;
|
||||
body.innerHTML = '<p class="cf24-muted">카페24에서 불러오는 중…</p>';
|
||||
return apiJson("GET", "/cafe24/products/" + no + "/options")
|
||||
.then(function (data) {
|
||||
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||
state.option = data.option;
|
||||
state.variants = data.variants || [];
|
||||
state.displayTypes = data.display_types || {};
|
||||
state.imageBase = data.image_base || "";
|
||||
render();
|
||||
return true;
|
||||
})
|
||||
.catch(function (err) {
|
||||
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||
body.innerHTML = '<p class="cf24-err">옵션을 불러오지 못했습니다: ' + esc(err.message) +
|
||||
'</p><button type="button" class="erp-btn erp-btn-outline" id="cf24-opt-retry">다시 시도</button>';
|
||||
body.querySelector("#cf24-opt-retry").addEventListener("click", load);
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
// 다시 불러오되, 아직 카페24에 저장되지 못한 품목 입력(자체코드·추가금액·진열/판매)은 옵션값
|
||||
// 이름으로 짝지어 되살린다. 품목코드가 늦게 나타나거나 일부 행 저장이 실패했을 때 입력을
|
||||
// 잃지 않게 한다(실패 뒤 자동으로 새로 읽어 입력을 지우던 문제).
|
||||
function reloadKeeping(keep, errors) {
|
||||
return load().then(function (ok) {
|
||||
if (!ok) return 0;
|
||||
var tbody = body.querySelector("#cf24-u-body");
|
||||
if (!tbody) return 0;
|
||||
var restored = 0;
|
||||
Array.prototype.forEach.call(tbody.children, function (tr) {
|
||||
var nameEl = tr.querySelector('[name="option_text"]');
|
||||
var k = nameEl && keep[norm(nameEl.value)];
|
||||
if (!k) return;
|
||||
var changed = false;
|
||||
[["custom_variant_code", k.custom], ["additional_amount", k.amount]].forEach(function (pair) {
|
||||
var el = tr.querySelector('[name="' + pair[0] + '"]');
|
||||
if (el && pair[1] != null && el.value !== pair[1]) {
|
||||
el.value = pair[1];
|
||||
el.dispatchEvent(new Event("input"));
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
["display", "selling"].forEach(function (flag) {
|
||||
var btn = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]');
|
||||
if (btn && k[flag] != null && btn.dataset.on !== k[flag]) { paintToggle(btn, k[flag] === "1", false); changed = true; }
|
||||
});
|
||||
var why = errors && errors[norm(nameEl.value)];
|
||||
if (why) { tr.classList.add("is-error"); tr.title = "저장 실패: " + why; }
|
||||
if (changed || why) restored++;
|
||||
});
|
||||
return restored;
|
||||
});
|
||||
}
|
||||
|
||||
function rowValues(tr) {
|
||||
return {
|
||||
custom: tr.querySelector('[name="custom_variant_code"]').value,
|
||||
amount: tr.querySelector('[name="additional_amount"]').value,
|
||||
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]').dataset.on,
|
||||
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]').dataset.on
|
||||
};
|
||||
}
|
||||
|
||||
/* ── 공통 조각 ── */
|
||||
function typeSelect(current, name) {
|
||||
var out = '<select name="' + name + '">';
|
||||
@@ -236,25 +293,34 @@
|
||||
통합 목록 — 옵션값 1 : 품목 1
|
||||
═══════════════════════════════════════════════════════════ */
|
||||
// 행 = 품목 목록 순서. index 는 options 응답 안 위치(옵션 PUT 짝맞춤용).
|
||||
// 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
||||
// 품목과 옵션값은 **옵션값 번호(value_no)** 로 먼저 짝짓고, 없을 때만 이름으로 짝짓는다.
|
||||
// (옵션값 이름을 바꾼 직후 카페24 품목 조회가 예전 이름을 돌려줘도 정상 품목이 숨지 않게.
|
||||
// 서버가 품목코드별 쓰기 기록으로 표기를 바로잡고 value_no 를 붙여 준다.)
|
||||
// 방금 추가해 품목이 아직 안 보이는 옵션값(pending)은 "품목 생성 대기" 행으로 그린다.
|
||||
// 그 밖에 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
||||
function unifiedRows() {
|
||||
var opt = state.option;
|
||||
state.orphans = [];
|
||||
if (!opt || !opt.has_option) return [];
|
||||
var group = opt.options[0];
|
||||
var byText = {};
|
||||
group.option_value.forEach(function (v, vi) { byText[v.option_text] = { index: vi, value: v, variant: null }; });
|
||||
var entries = group.option_value.map(function (v, vi) { return { index: vi, value: v, variant: null }; });
|
||||
var byNo = {}, byText = {};
|
||||
entries.forEach(function (r) {
|
||||
if (r.value.value_no != null && r.value.value_no !== "") byNo[String(r.value.value_no)] = r;
|
||||
if (!byText[r.value.option_text]) byText[r.value.option_text] = r;
|
||||
});
|
||||
var rows = [];
|
||||
state.variants.forEach(function (variant) {
|
||||
if (!variant.options.length) return;
|
||||
var r = byText[variant.options[0].value];
|
||||
var r = (variant.value_no != null && byNo[String(variant.value_no)]) || byText[variant.options[0].value];
|
||||
if (!r || r.variant) return;
|
||||
r.variant = variant;
|
||||
rows.push(r);
|
||||
});
|
||||
group.option_value.forEach(function (v) {
|
||||
var r = byText[v.option_text];
|
||||
if (rows.indexOf(r) < 0) state.orphans.push(r);
|
||||
entries.forEach(function (r) {
|
||||
if (r.variant) return;
|
||||
if (r.value.pending) { r.await = true; rows.push(r); }
|
||||
else state.orphans.push(r);
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
@@ -266,8 +332,10 @@
|
||||
var thumbSrc = [v.option_image_file, v.option_link_image,
|
||||
state.option && state.option.has_option ? variantImageFor(state.option.options[0].option_name, v.option_text) : ""];
|
||||
var code = variant ? variant.variant_code : "";
|
||||
var awaiting = !!r.await && !code;
|
||||
// data-index: options 응답 안 위치(옵션 PUT 짝맞춤용, 새 행은 빈 값) / data-pos: 처음 그린 순서(순서 변경 판정용)
|
||||
return '<tr class="cf24-u-row' + (isNewRow ? " is-new" : "") + '" data-index="' + (isNewRow ? "" : r.index) + '" data-pos="' + (position == null ? "" : position) + '" data-code="' + esc(code) + '">' +
|
||||
// data-await: 옵션값은 카페24에 있으나 품목코드가 아직 조회되지 않음 — 입력은 받고, 저장 때 코드를 다시 찾는다.
|
||||
return '<tr class="cf24-u-row' + (isNewRow ? " is-new" : "") + (awaiting ? " is-await" : "") + '" data-index="' + (isNewRow ? "" : r.index) + '" data-pos="' + (position == null ? "" : position) + '" data-code="' + esc(code) + '"' + (awaiting ? ' data-await="1"' : "") + '>' +
|
||||
'<td class="cf24-u-drag">' + (canDrag ? '<span class="cf24-drag-handle" draggable="true" title="드래그하여 순서 변경">⋮⋮</span>' : "") + "</td>" +
|
||||
'<td class="cf24-u-thumb"><span class="cf24-opt-thumb-slot">' + thumbHtml(thumbSrc, v.option_image_file ? "옵션 버튼 이미지" : v.option_link_image ? "옵션 연결 이미지" : "품목 이미지") + "</span>" +
|
||||
'<input type="hidden" name="option_image_file" value="' + esc(v.option_image_file || "") + '" />' +
|
||||
@@ -276,12 +344,14 @@
|
||||
'<td class="cf24-u-name"><input type="text" name="option_text" value="' + esc(v.option_text) + '" placeholder="옵션값 이름" /></td>' +
|
||||
'<td class="cf24-v-syscode">' + (code
|
||||
? '<button type="button" class="cf24-v-copy" data-copy-text="' + esc(code) + '" title="클릭하면 품목코드를 복사합니다">' + esc(code) + "</button>"
|
||||
: '<span class="cf24-muted">저장 시 부여</span>') + "</td>" +
|
||||
: awaiting
|
||||
? '<span class="cf24-muted" title="카페24가 품목을 만드는 중이거나 조회가 늦습니다. 입력해 두면 저장할 때 코드를 다시 찾아 반영합니다.">품목 생성 대기</span>'
|
||||
: '<span class="cf24-muted">저장 시 부여</span>') + "</td>" +
|
||||
'<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(variant ? variant.custom_variant_code : "") + '" /></td>' +
|
||||
'<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(variant ? variant.additional_amount : "0")) + '" /></td>' +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("display", variant ? !!variant.display : true) + "</td>" +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : true) + "</td>" +
|
||||
'<td class="cf24-u-del"><button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button></td>' +
|
||||
'<td class="cf24-u-del">' + (awaiting ? "" : '<button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button>') + "</td>" +
|
||||
"</tr>";
|
||||
}
|
||||
|
||||
|
||||
@@ -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,267 @@
|
||||
/* ════════════════════════════════════════════════════
|
||||
실적(쇼핑몰 통합 매출) — 정보 밀도 높은 관리자 대시보드.
|
||||
기존 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; }
|
||||
|
||||
/* ── 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대(runSyncWithProgress) ── */
|
||||
.perf-prog-card { width: min(640px, 100%); }
|
||||
.perf-prog-row {
|
||||
display: grid; grid-template-columns: 150px 1fr 44px; align-items: center; column-gap: 10px; row-gap: 3px;
|
||||
padding: 9px 0; border-bottom: 1px solid var(--perf-line);
|
||||
}
|
||||
.perf-prog-name { font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.perf-prog-bar { height: 10px; border-radius: 999px; background: #eef0f3; overflow: hidden; }
|
||||
.perf-prog-bar > span {
|
||||
display: block; height: 100%; border-radius: inherit; background: var(--perf-sat);
|
||||
transition: width .5s ease;
|
||||
}
|
||||
.perf-prog-pct { font-size: 12px; text-align: right; font-variant-numeric: tabular-nums; color: var(--color-midtone-gray); }
|
||||
.perf-prog-text { grid-column: 2 / -1; font-size: 12px; color: var(--color-midtone-gray); overflow-wrap: anywhere; }
|
||||
.perf-prog-row.is-done .perf-prog-bar > span { background: var(--perf-up); }
|
||||
.perf-prog-row.is-error .perf-prog-bar > span { background: var(--perf-down); }
|
||||
.perf-prog-row.is-error .perf-prog-text { color: var(--perf-down); }
|
||||
.perf-prog-row.is-skip .perf-prog-bar > span { background: #b8bec7; }
|
||||
/* 진행 중인 막대에 흐르는 빗금 — 멈춘 게 아니라는 표시 */
|
||||
.perf-prog-row:not(.is-done):not(.is-error):not(.is-skip) .perf-prog-bar > span {
|
||||
background-image: linear-gradient(45deg, rgba(255,255,255,.22) 25%, transparent 25%, transparent 50%,
|
||||
rgba(255,255,255,.22) 50%, rgba(255,255,255,.22) 75%, transparent 75%, transparent);
|
||||
background-size: 16px 16px; animation: perf-prog-flow 1s linear infinite;
|
||||
}
|
||||
@keyframes perf-prog-flow { from { background-position: 0 0; } to { background-position: 16px 0; } }
|
||||
.perf-prog-row.is-total { border-bottom: none; border-top: 2px solid var(--perf-line); margin-top: 4px; padding-top: 12px; }
|
||||
.perf-prog-row.is-total .perf-prog-name { font-weight: 700; }
|
||||
.perf-prog-row.is-total .perf-prog-bar { height: 14px; }
|
||||
.perf-prog-row.is-total .perf-prog-pct { font-weight: 700; color: inherit; }
|
||||
@media (max-width: 560px) { .perf-prog-row { grid-template-columns: 1fr 44px; } .perf-prog-name { grid-column: 1 / -1; } .perf-prog-text { grid-column: 1 / -1; } }
|
||||
|
||||
/* [업데이트 취소] — 창 아래 왼쪽, 빨간 글자. 끝나면 숨김 */
|
||||
.perf-prog-cancel { margin-right: auto; color: var(--perf-down); border-color: currentColor; }
|
||||
.perf-prog-cancel[hidden] { display: none; }
|
||||
.perf-prog-cancel:disabled { opacity: .6; cursor: default; }
|
||||
File diff suppressed because it is too large
Load Diff
+97
-20
@@ -2010,37 +2010,53 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
||||
border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px;
|
||||
color: var(--pj-ink); background: #fff; border: 1px solid #dfe2e6; border-radius: 10px;
|
||||
}
|
||||
/* 칸 너비는 여백·테두리 포함(border-box) — 안 그러면 padding 만큼 넓어진다 */
|
||||
.pj-goal-table th, .pj-goal-table td {
|
||||
box-sizing: border-box;
|
||||
border-right: 1px solid #e6e8eb; border-bottom: 1px solid #e6e8eb; padding: 0; vertical-align: top;
|
||||
}
|
||||
.pj-goal-table tr > :last-child { border-right: none; }
|
||||
.pj-goal-table thead th {
|
||||
position: sticky; top: 0; z-index: 3; background: #f7f8f9; height: 32px; padding: 0 10px;
|
||||
font-weight: 700; text-align: left; vertical-align: middle; white-space: nowrap;
|
||||
font-weight: 700; text-align: center; vertical-align: middle; white-space: nowrap;
|
||||
}
|
||||
.pj-goal-table thead th:not(.pj-goal-c1):not(.pj-goal-c2) { width: 150px; min-width: 150px; }
|
||||
.pj-goal-table thead th.pj-goal-year-col { width: 210px; min-width: 210px; }
|
||||
.pj-goal-table thead th { width: 85px; min-width: 85px; max-width: 85px; } /* 1~12월 */
|
||||
.pj-goal-table thead th.pj-goal-year-col { width: 90px; min-width: 90px; max-width: 90px; }
|
||||
.pj-goal-table thead th.is-now { color: var(--pj-accent-dark); box-shadow: inset 0 -2px 0 var(--pj-accent); }
|
||||
/* 왼쪽 고정 두 칸(구분·항목) — 너비는 머리 칸 오른쪽 끝을 끌어 조절(initGoals, localStorage
|
||||
pj_goal_col_w). --goal-c1-w 가 c2 의 left 도 같이 정한다. */
|
||||
.pj-goal-table { --goal-c1-w: 72px; --goal-c2-w: 72px; }
|
||||
.pj-goal-c1, .pj-goal-c2 {
|
||||
position: sticky; z-index: 2; width: 72px; min-width: 72px; max-width: 72px;
|
||||
background: #fff; text-align: left; font-weight: 700;
|
||||
position: sticky; z-index: 2; background: #fff; text-align: center; font-weight: 700;
|
||||
}
|
||||
.pj-goal-c1 { left: 0; }
|
||||
.pj-goal-c2 { left: 72px; font-weight: 600; color: #3b4048; }
|
||||
.pj-goal-table thead .pj-goal-c1, .pj-goal-table thead .pj-goal-c2 { z-index: 4; }
|
||||
.pj-goal-table tbody th { padding: 7px 8px; }
|
||||
.pj-goal-c1 { left: 0; width: var(--goal-c1-w); min-width: var(--goal-c1-w); max-width: var(--goal-c1-w); }
|
||||
.pj-goal-c2 {
|
||||
left: var(--goal-c1-w); width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w);
|
||||
font-weight: 600; color: #3b4048;
|
||||
}
|
||||
.pj-goal-table thead th.pj-goal-c1 { z-index: 4; width: var(--goal-c1-w); min-width: var(--goal-c1-w); max-width: var(--goal-c1-w); }
|
||||
.pj-goal-table thead th.pj-goal-c2 { z-index: 4; width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w); }
|
||||
.pj-goal-colresize {
|
||||
position: absolute; top: 0; right: -4px; bottom: 0; width: 8px; z-index: 5; cursor: col-resize;
|
||||
}
|
||||
.pj-goal-colresize::after {
|
||||
content: ""; position: absolute; top: 6px; bottom: 6px; left: 3px; width: 2px; border-radius: 2px; background: transparent;
|
||||
}
|
||||
.pj-goal-colresize:hover::after, .pj-goal-colresize.is-dragging::after { background: var(--pj-accent); }
|
||||
html.pj-goal-resizing, html.pj-goal-resizing * { cursor: col-resize !important; user-select: none !important; }
|
||||
.pj-goal-table tbody th { padding: 7px 8px; vertical-align: middle; } /* 왼쪽 이름은 세로 가운데 */
|
||||
|
||||
/* 숫자 지표 */
|
||||
.pj-goal-kpi td { height: 32px; vertical-align: middle; }
|
||||
.pj-goal-kpi td.is-now { background: #faf9ff; }
|
||||
input.pj-goal-num, span.pj-goal-num {
|
||||
display: block; width: 100%; box-sizing: border-box; height: 32px; padding: 0 10px; border: none;
|
||||
display: block; width: 100%; box-sizing: border-box; height: 32px; padding: 0 6px; border: none;
|
||||
background: transparent; font: inherit; font-variant-numeric: tabular-nums; text-align: right; line-height: 32px;
|
||||
}
|
||||
input.pj-goal-num:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: #fff; }
|
||||
.pj-goal-sum { padding: 0 10px !important; text-align: right; font-weight: 700; background: #fafafb;
|
||||
.pj-goal-sum { padding: 0 6px !important; text-align: right; font-weight: 700; background: #fafafb;
|
||||
font-variant-numeric: tabular-nums; }
|
||||
.pj-goal-rate { padding: 0 10px !important; text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.pj-goal-rate { padding: 0 6px !important; text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.pj-goal-rate.is-good { color: #1f8a4c; }
|
||||
.pj-goal-rate.is-low { color: #c2410c; }
|
||||
.pj-goal-kpi tr:last-child > * { border-bottom: 2px solid #d5d9de; }
|
||||
@@ -2050,19 +2066,27 @@ input.pj-goal-num:focus { outline: 2px solid var(--pj-accent); outline-offset: -
|
||||
.pj-goal-area > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
|
||||
.pj-goal-area-name { font-size: 13px; font-weight: 800 !important; }
|
||||
.pj-goal-area-text, .pj-goal-row-text { display: block; word-break: keep-all; overflow-wrap: anywhere; }
|
||||
.pj-goal-tools { display: flex; flex-wrap: wrap; gap: 0; margin-top: 4px; opacity: 0; transition: opacity .12s; }
|
||||
/* 관리자 도구(✎ 색 ↑ ↓ + ×) — 이름 칸 아래에 떠 있는 작은 막대. 자리를 차지하지 않아야
|
||||
이름이 세로 가운데에 온다. 칸 안에 붙어 있어 마우스를 막대로 옮겨도 사라지지 않는다. */
|
||||
.pj-goal-area-name:hover, .pj-goal-row-label:hover, .pj-goal-area-name:focus-within, .pj-goal-row-label:focus-within { z-index: 6; }
|
||||
.pj-goal-tools {
|
||||
position: absolute; top: calc(100% - 6px); left: 50%; transform: translateX(-50%); z-index: 7;
|
||||
display: flex; flex-wrap: nowrap; gap: 1px; padding: 3px; background: #ffe3c7; border: 1px solid #f6c69a;
|
||||
border-radius: 10px; box-shadow: 0 4px 12px rgba(16, 24, 40, .14); /* 파스텔 주황 */
|
||||
opacity: 0; pointer-events: none; transition: opacity .12s;
|
||||
}
|
||||
.pj-goal-area-name:hover .pj-goal-tools, .pj-goal-row-label:hover .pj-goal-tools,
|
||||
.pj-goal-tools:focus-within { opacity: 1; }
|
||||
.pj-goal-tools .pj-icon-btn { width: 20px; height: 20px; font-size: 13px; }
|
||||
.pj-goal-tools .pj-icon-btn .material-symbols-outlined { font-size: 15px; }
|
||||
.pj-goal-tools .pj-icon-btn:hover { background: rgba(255, 255, 255, .7); }
|
||||
.pj-goal-tools:focus-within { opacity: 1; pointer-events: auto; }
|
||||
.pj-goal-tools .pj-icon-btn { width: 30px; height: 30px; font-size: 20px; color: #8a4b14; border-radius: 7px; }
|
||||
.pj-goal-tools .pj-icon-btn .material-symbols-outlined { font-size: 22px; }
|
||||
.pj-goal-tools .pj-icon-btn:hover { background: #ffc98f; color: #5c2e06; }
|
||||
textarea.pj-goal-text {
|
||||
display: block; width: 100%; box-sizing: border-box; min-height: 46px; padding: 7px 9px; border: none;
|
||||
display: block; width: 100%; box-sizing: border-box; min-height: 46px; padding: 6px; border: none;
|
||||
background: transparent; font: inherit; line-height: 1.5; color: inherit; resize: none; overflow: hidden;
|
||||
}
|
||||
textarea.pj-goal-text:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: rgba(255, 255, 255, .75); }
|
||||
textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); }
|
||||
.pj-goal-text-ro { min-height: 46px; padding: 7px 9px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.pj-goal-text-ro { min-height: 46px; padding: 6px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.pj-goal-area td.is-now { box-shadow: inset 2px 0 0 rgba(123, 104, 238, .35), inset -2px 0 0 rgba(123, 104, 238, .35); }
|
||||
.pj-goal-texttd.pj-goal-year-col { font-weight: 600; }
|
||||
|
||||
@@ -2073,10 +2097,63 @@ textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); }
|
||||
|
||||
/* 영역 색 고르기 팝업(body 에 붙음) */
|
||||
.pj-goal-colorpop {
|
||||
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(4, 26px); gap: 6px;
|
||||
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
|
||||
padding: 10px; background: #fff; border: 1px solid var(--pj-border); border-radius: 10px;
|
||||
box-shadow: 0 8px 24px rgba(16, 24, 40, .16);
|
||||
}
|
||||
.pj-goal-swatch { width: 26px; height: 26px; border-radius: 6px; border: 1px solid rgba(0, 0, 0, .12); cursor: pointer; padding: 0; }
|
||||
.pj-goal-swatch:hover { transform: scale(1.08); }
|
||||
.pj-goal-swatch.is-on { outline: 2px solid var(--pj-accent); outline-offset: 1px; }
|
||||
/* 맨 위 "색 없음" — 한 줄 전체, 흰 칸에 빨간 사선 */
|
||||
.pj-goal-swatch-none {
|
||||
grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; height: 28px; padding: 0 8px;
|
||||
border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; color: var(--pj-ink);
|
||||
font-size: 12.5px; cursor: pointer;
|
||||
}
|
||||
.pj-goal-swatch-none:hover { background: #f6f7f8; }
|
||||
.pj-goal-swatch-none.is-on { outline: 2px solid var(--pj-accent); outline-offset: 1px; }
|
||||
.pj-goal-swatch-x {
|
||||
width: 16px; height: 16px; border: 1px solid rgba(0, 0, 0, .2); border-radius: 4px; background:
|
||||
linear-gradient(to top right, transparent calc(50% - 1px), #e5484d calc(50% - 1px), #e5484d calc(50% + 1px), transparent calc(50% + 1px));
|
||||
}
|
||||
|
||||
/* ════════════════════════════════════════════════════════════
|
||||
권한·저장 안전장치(2026-09-30)
|
||||
════════════════════════════════════════════════════════════ */
|
||||
/* 읽기 전용 안내줄 — 다른 프로젝트에서 연결돼 온 작업(원 소속 권한 없음) */
|
||||
.pj-readonly-note {
|
||||
display: flex; align-items: center; gap: 6px; margin: 4px 0 8px; padding: 7px 10px;
|
||||
border-radius: 8px; background: #f1f5fb; color: #34507a; font-size: 12.5px; line-height: 1.4;
|
||||
}
|
||||
.pj-readonly-note[hidden] { display: none; }
|
||||
.pj-readonly-note .material-symbols-outlined { font-size: 17px; }
|
||||
.pj-modal.is-readonly .pj-t-title-input { cursor: default; }
|
||||
.pj-modal.is-readonly .pj-desc-editor { background: #fafbfc; }
|
||||
.pj-subtask-row.is-readonly .pj-subtask-check,
|
||||
.pj-subtask-row.is-readonly .pj-subtask-due,
|
||||
.pj-subtask-row.is-readonly .pj-subtask-av { cursor: default; opacity: .7; }
|
||||
/* 이 프로젝트 권한을 잃었을 때 화면 위 안내 */
|
||||
.pj-access-lost {
|
||||
margin: 0 0 10px; padding: 10px 14px; border-radius: 8px; background: #fdecea; color: #a1261b;
|
||||
font-size: 13px; font-weight: 600;
|
||||
}
|
||||
.pj-access-lost a { color: inherit; text-decoration: underline; margin-left: 6px; }
|
||||
/* 저장 실패 — 눌러서 다시 시도 */
|
||||
.pj-autosave-state.is-retry { cursor: pointer; text-decoration: underline dotted; }
|
||||
/* 작업 창 댓글의 첨부(파일만 있는 댓글도 보이게) */
|
||||
.pj-comment-atts { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
|
||||
.pj-comment-att { display: inline-flex; align-items: center; gap: 5px; text-decoration: none; color: var(--pj-ink); }
|
||||
.pj-comment-att-file {
|
||||
padding: 4px 8px; border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; font-size: 12.5px;
|
||||
}
|
||||
.pj-comment-att-file:hover { background: #f6f7f8; }
|
||||
.pj-comment-att-img img {
|
||||
display: block; max-width: 160px; max-height: 120px; border-radius: 6px; border: 1px solid var(--pj-border);
|
||||
object-fit: cover;
|
||||
}
|
||||
/* 첨부 파일 목록에서 댓글에 붙은 파일 표시 */
|
||||
.pj-attach-from-comment {
|
||||
margin-left: 6px; padding: 0 6px; border-radius: 999px; background: #eef0f2; color: #525860; font-size: 11px;
|
||||
}
|
||||
/* 댓글 대화창 — 보낼 수 없었던 파일(빈 파일·20MB 초과) */
|
||||
.pj-chat-pending-chip.is-failed { border-color: #e5484d; background: #fdecea; color: #a1261b; }
|
||||
|
||||
+693
-146
File diff suppressed because it is too large
Load Diff
@@ -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,249 @@
|
||||
# 실적(쇼핑몰 통합 매출) 모듈
|
||||
|
||||
> `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·11번가·네이버 스마트스토어·GS샵 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `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` — 기간을 통째로 다시 받아 취소·반품된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 → 지난 날짜
|
||||
금액이 나중에 줄 수 있음). 구매자 이름·아이디·연락처는 저장하지 않는다.
|
||||
|
||||
### 네이버 스마트스토어 (`adapters/naver.py`, 구현됨)
|
||||
|
||||
- 인증: 커머스API센터 애플리케이션 ID·시크릿 → 전자서명 `client_secret_sign = base64(bcrypt.hashpw("{client_id}_{timestamp ms}",
|
||||
client_secret))` → `POST https://api.commerce.naver.com/external/v1/oauth2/token`(form: client_id·timestamp·client_secret_sign·
|
||||
grant_type=client_credentials·type=SELF, 판매자 ID 입력 시 type=SELLER+account_id). 토큰(약 3시간)은 `access_token`·
|
||||
`access_token_expires_at`(internal, 암호화)으로 저장해 만료 5분 전까지 재사용, 401 이면 한 번 새로 받아 다시 호출.
|
||||
[연결 테스트]는 입력값으로 시험하므로 항상 새 토큰. **애플리케이션의 API 호출 IP 에 운영 서버 외부 IP 등록 필요.**
|
||||
의존성 `bcrypt`(requirements.txt).
|
||||
- 수집: 조건형 상품 주문 상세 조회 `GET /v1/pay-order/seller/product-orders?from=&to=&rangeType=PAYED_DATETIME&pageSize=100&page=`
|
||||
— 한 번에 **24시간까지**(하루씩 0시~23:59:59.999 +09:00), from 부터 180일 안 주문만(네이버 안내, GitHub discussions #1875·#2380).
|
||||
응답 모양은 `data.contents[].content.{order, productOrder, …}` 로 보고 목록·`content` 유무가 달라도 받는다(`product_order_items`),
|
||||
다음 쪽은 `pagination.hasNext`(없으면 100건 꽉 차면). 호출 간격 0.35초, 429 는 1·2·4초 쉬고 다시.
|
||||
- **매출 규칙 = 스마트스토어센터 판매분석 "판매금액(총)"**(2026-09-30 사용자 확인): 판매분석 9/1 매출 4,455,600원 = 판매금액(총) —
|
||||
할인(판매자·네이버 부담) 뒤 금액, **배송비(332,486원)는 별도**, 결제 뒤 취소·반품도 결제일에 포함하고 환불(346,340원)은 **환불일**에
|
||||
따로 빼서 판매금액(순) 4,109,260원(예: 9/1 결제 0원인 상품에 환불 5건 75,040원). 주방세제 2.3L 16,640 = 17,900 − 네이버 부담 1,260.
|
||||
처음 규칙(취소·반품 빼고 배송비 더함)은 4,245,300원으로 달랐다.
|
||||
- SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(`order.paymentDate`), 금액 = 상품주문 `totalPaymentAmount` 합(배송비 제외),
|
||||
할인 = `productDiscountAmount` 합. 결제 뒤 취소·반품(`CANCELED`·`RETURNED`)도 포함, 입금대기·미입금 취소만 뺀다
|
||||
→ 지난 날짜 매출이 나중에 줄지 않는다. `replace_range`.
|
||||
- 환불(판매금액(순))은 아직 사건으로 만들지 않는다 — 필요하면 클레임 완료일 기준 CANCEL/RETURN 을 추가.
|
||||
- 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택): 결제일 기준 상품주문 전체의 항목별 합계, 상태별 합계, 날짜별
|
||||
매출·그중 결제 뒤 취소/반품(참고)·배송비(참고). 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만.
|
||||
|
||||
### GS샵 (`adapters/gsshop.py`, 구현됨)
|
||||
|
||||
- 문서: 협력사 포털 → 제휴 API → 개발가이드(`partners.gsshop.com/api/apiDevGuide`, 본문은 `/docs/withgs-api-docs.html` Redoc).
|
||||
- 인증: 헤더 `supCd`(협력사코드) + `token` = base64(AES256(`yyyyMMddHHmmss` + 협력사코드)), 키는 제휴 API 메인 화면(로그인 후).
|
||||
키 = 포털 제휴 API 메인의 **운영 KEY**(개발 KEY 아님). 문서에 암호화 모드·키를 바이트로 쓰는 법이 없어 키 변형(글자 그대로 /
|
||||
16진수 풀기 / 앞 32자, `key_variants`) × 모드(CBC·IV=키 앞 16 → ECB → CBC·IV=0) 순서로 시도하고 통과한 조합을 기억.
|
||||
토큰이 틀리면 **HTTP 200** + `{"result":"fail","code":"401 UNAUTHORIZED"}`. 운영 주소 `withgs-api.gsshop.com`(문서 예시
|
||||
`atwithgs-api` 는 테스트용 — 두 곳 모두 응답). 입력칸 키는 처음 만든 `vendor_code`·`api_key` 그대로(라벨만 협력사코드·AES256 키).
|
||||
- 매출: `GET /api/v2/settlement/out/sales/period?supCode&fromDate&toDate&pageIdx&rowsPerPage` — **매출인식일** 기준, 한 번에 10일,
|
||||
쪽당 1만 건, `{data, hasMorePage, totalCount}`. 배송비는 `/shippingFee/period`. 응답 줄 항목 이름이 문서 예시에 없어
|
||||
("property1") 실데이터로 확인(2026-09-30, 9/3): `saleAwareDt`·`ordNo`·`ordItemNo`·`ordType`(SALE…)·`prdNm`·`chrQty`·
|
||||
`salePrice`(할인 전, 줄 합계)·`dcTotAmt`·`custChrAmt`(= salePrice − dcTotAmt, 고객 결제금액)·`supGiveAmt`(협력사 지급액).
|
||||
9/3: 211,100 − 19,528 = 191,572, 지급 179,435, 배송비 내역 7,000.
|
||||
- **주문일 기준 조회 API 는 없다** — 협력사 포털 주문 통계(총주문금액·주문일, 할인 후 금액: 45,900 × 85% = 39,015)와는 날짜 기준이
|
||||
달라 날마다 똑같이 맞지 않는다(매출인식일 = 정산 기준).
|
||||
- **매출 규칙**: 매출 내역 한 줄 = 사건(`gs:{ordNo}-{ordItemNo}-{ordType}-{saleAwareDt}`), 날짜 = 매출인식일,
|
||||
금액 = **`supGiveAmt`(협력사 지급액)** = 협력사 포털 주문 통계의 금액(2026-09-30 확인: 6호세트 포털 176,715 ÷ 9 = 19,635 = API
|
||||
supGiveAmt 19,635 — 판매가 23,100·고객 결제 20,330. 7호세트 45,900 × 85%, 주부체험 9,900 × 90% — 상품마다 GS 수수료율이 다름).
|
||||
9/1~9/29 지급액 4,972,689 vs 포털 순주문 4,823,074 — 남는 차이는 주문일 ↔ 매출인식일·취소분. 이미 GS 수수료를 뺀 금액이라
|
||||
**GS샵 수수료율은 0%**. 배송비 제외, `ordType` 이 SALE 이 아니면 RETURN 음수. `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일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
|
||||
- **진행 창**(두 버튼 공통, `runSyncWithProgress`): `POST /api/sync {…, background: true}` → 수집을 스레드로 돌리고 작업 번호를
|
||||
바로 돌려줌 → 화면이 `GET /api/sync/jobs/{id}` 를 0.8초마다 불러 **쇼핑몰별 막대 + 전체 막대**를 그린다(`jobs.py`, 메모리 보관 —
|
||||
uvicorn 단일 워커 기준, 서버 재시작 시 진행 정보만 사라짐). 어댑터가 `ctx.progress.plan(전체, 단위)`/`step(items=)`/`add(n)` 로
|
||||
알린다 — 네이버 = 일, 11번가 = 7일 구간(정산 + 주문 상태 4개), 카페24 = 60일 구간(결제·환불·환불 없는 취소 2종, 대조 필요 시 +).
|
||||
상태: 대기 → 수집 중 n/전체 · 받은 자료 → 저장 중 → 완료 n건 반영 | 실패 | 건너뜀. 수집이 없거나 인증정보가 없는 쇼핑몰은
|
||||
막대에서 빼고 "건너뜀" 한 줄(전체 진행률에 안 넣음). 전체 = 막대 쇼핑몰 진행률 평균. 이미 돌고 있는 업데이트가 있으면 새로 시작하지
|
||||
않고 그 진행 상황을 보여 준다(`GET /api/sync/current`). 창을 닫아도 수집은 계속된다.
|
||||
- **[업데이트 취소]**(진행 창 왼쪽 아래, 시작한 사람·관리자, `POST /api/sync/jobs/{id}/cancel`): 돌고 있는 쇼핑몰은 다음 API 호출
|
||||
직전(`ctx.progress.check()` → `Cancelled`)에 멈추고 **저장하지 않는다**(저장은 수집이 끝난 뒤 한 트랜잭션이라 기존 매출 그대로),
|
||||
차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 남고, 저장 중이던 쇼핑몰은 그 저장을 끝낸다.
|
||||
취소된 실행은 `perf_sync_runs` 에 failed + "업데이트 취소", 연결 상태(`perf_connection_status`)는 바꾸지 않는다.
|
||||
- 카페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/네트워크 없이 검증한다.
|
||||
+79
-7
@@ -33,11 +33,13 @@
|
||||
| 연결 env | `PROJECT_DB_URL` (미설정 시 "설정 필요" 안내, 앱은 죽지 않음) |
|
||||
| 진입 권한 | 권한키 `project` (관리자 페이지 토글로 직원별 부여, admin 자동) |
|
||||
| 멤버 배정 후보 | `project` 권한 보유 등록 사용자 자동 목록 (`GET /project/api/assignable-users`) |
|
||||
| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. |
|
||||
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`) |
|
||||
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다 |
|
||||
| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다 |
|
||||
| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일 |
|
||||
| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. 다른 사람을 owner 로 지정해 만드는 건 관리자만(비관리자가 `owner_email` 을 남으로 보내면 403) |
|
||||
| 소유자 변경 | **관리자만**(2026-09-30). owner 는 멤버에서 빠져도 관리 권한이 남으므로, 일반 멤버가 스스로를 owner 로 바꿔 권한 회수를 피할 수 없게 `PUT /api/projects/{id}` 의 `owner_email` 변경은 비관리자 403(같은 값은 무시). 새 owner 는 `project` 권한이 있는 등록 사용자여야 한다(아니면 400) |
|
||||
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`). 작업 API 는 `_require_task(write=True)` = 원 소속 프로젝트 권한(FULL) |
|
||||
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다. 연결된(멀티호밍) 작업은 연결된 프로젝트 멤버에게 **읽기 전용**(6-10) |
|
||||
| 지금 권한 기준 | 모든 판단은 **지금** 권한(`app/modules/project/access.py`) — 멤버에서 빠진 사람은 예전 담당자·멘션·협업자 기록이 있어도 내 작업·수신함·알림·검색·상세·공유 링크·댓글·첨부에서 그 작업이 보이지 않고, 새 알림·메일도 받지 않는다(기록은 이력으로 남김) |
|
||||
| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다. 새 담당자는 그 프로젝트를 볼 수 있는 사람만(400). 날짜 범위(시작 ≤ 마감, 같은 날이면 시작 시각 ≤ 마감 시각)는 부분 수정도 기존 값과 합친 최종 상태로 검사(400) |
|
||||
| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일. **그리고 지금 그 프로젝트 권한이 있어야 한다**(멤버에서 빠진 생성자는 403, DB·휴지통 변화 없음) |
|
||||
| 멤버 배정 | 여전히 관리자(`is_admin`) 전용. 비관리자가 "새 프로젝트" 모달을 열면 멤버 선택란은 안내 문구만 뜨고 시도하지 않는다(불필요한 403 방지) |
|
||||
| 메일 알림 | `app/mail.py` (stdlib smtplib). 작업 배정/완료 시 관리자에게 발송 |
|
||||
|
||||
@@ -487,11 +489,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
(`initGoalSide`, localStorage `pj_goal_open`, 목표 화면에선 항상 펼침). 연도 목록은 `router._goal_years_nav`
|
||||
(`goal_years` 최근 연도 먼저 + **올해는 항상**, 013 미적용이면 올해만) — 사이드바를 그리는 모든 화면 컨텍스트에 `goal_years`.
|
||||
- 연도를 누르면 `/project/goals/{연도}`(`goals.html`) — 스프레드시트 같은 한 표. 머리 줄(연간·1~12월)과 왼쪽 두 칸은 고정,
|
||||
이번 달 열 강조.
|
||||
이번 달 열 강조. 월 칸 너비 85px·연간 90px(여백 포함, `box-sizing: border-box`), 머리·왼쪽 이름 가운데 정렬(왼쪽 이름은 세로도 가운데 — 관리자 도구는 칸 아래에 떠 있는 막대라 자리를 차지하지 않음). 왼쪽 이름 두 칸(구분·항목)은 머리 칸 오른쪽 끝을 끌어 너비 조절(48~320px, 더블클릭 = 72px) — 브라우저별 localStorage `pj_goal_col_w`, CSS 변수 `--goal-c1-w`·`--goal-c2-w`.
|
||||
- **숫자 지표** `goal_metrics`(year·metric `sales|roas`·kind `target|actual`·month 1~12·value NUMERIC(18,2)) —
|
||||
매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, 연간은 실적이 있는 달의 목표 합계 대비)는
|
||||
화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`.
|
||||
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 8색·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
|
||||
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 연한 16색 + 색 없음(빈 값 = 흰 배경)·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
|
||||
못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경.
|
||||
- 권한: 조회는 `project` 권한자 전원, **입력·구조 변경은 관리자만**(`_require_admin`, 화면도 관리자에게만 입력칸·도구).
|
||||
- 연도 추가(`POST /api/goals/years {year}`)는 가장 가까운 이전 연도(없으면 다음 연도)의 영역·줄 구조를 글 없이 복사,
|
||||
@@ -507,6 +509,76 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
영역 색은 팝업(body 에 붙임)에서 바로 바뀜. 목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지).
|
||||
- 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기.
|
||||
|
||||
## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음)
|
||||
|
||||
**권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙)
|
||||
- 프로젝트 관리 = 관리자 · owner · 배정 멤버, 모두 `project` 모듈 권한이 있어야 한다(`can_manage_project`).
|
||||
- 작업 권한 `task_access`: **FULL** = 원 소속 프로젝트 관리 가능 / **READ** = 원 소속 권한은 없지만 이 작업(또는 상위 작업)이
|
||||
연결된 프로젝트를 관리 가능(`task_link_scope`, 재귀 CTE) / 없음. 라우터 `_require_task(write=)` 가 FULL/READ 를 검사.
|
||||
- READ 로 되는 것: 작업 상세(`access:"read"`)·하위 작업 목록·댓글 목록·첨부 목록/다운로드/미리보기·공유 링크(연결된 프로젝트
|
||||
화면으로 이동). 안 되는 것: 제목·설명·담당자·완료·섹션(원 소속)·댓글/답글/반응·첨부 추가/삭제·협업자·삭제·하위 작업 변경.
|
||||
이미 연결된 작업을 연결된 프로젝트 안에서 섹션 이동(`POST /links`)은 예전처럼 허용, 새 연결은 양쪽 권한. 상세의 `links` 는
|
||||
내가 볼 수 있는 프로젝트만(다른 연결 프로젝트 이름도 숨김), `followers` 는 READ 면 null. 원 소속의 다른 작업·멤버는 계속 403.
|
||||
- 목록·배지·알림: 내 작업(`_my_visible_tasks`/`_my_open_count`)·수신함 태그(`_safe_mentions`)·알림(`_visible_notifications`)을
|
||||
지금 권한으로 거른다(FULL 또는 READ). 기존 기록은 지우지 않는다.
|
||||
- 알림·메일·멘션 수신자: `filter_recipients` — 지금 그 작업을 볼 수 있는 등록 사용자만(담당자·협업자여도 권한을 잃었으면 제외).
|
||||
@태그는 볼 수 없는 사람(비멤버·권한 회수·미등록 이메일)을 기록·알림·자동 협업자 등록 없이 건너뛰고 응답 `mention_skipped` 로
|
||||
알려 준다(payload 에 이메일을 직접 넣어도 같음). 멘션이 권한을 만들지 않는다. 태그 후보 `GET /api/all-users?task_id=`.
|
||||
- 새 담당자는 그 프로젝트를 볼 수 있는 사람만(`_check_assignee`, 400). 비우거나 예전 값 유지는 허용.
|
||||
- 댓글 수정·삭제도 지금 원 소속 권한이 있어야 한다(작성자라도 멤버에서 빠지면 403). 첨부는 본인 댓글에만 붙일 수 있다.
|
||||
|
||||
**저장·동기화**
|
||||
- 작업 창 세대(`taskGen`): 창을 열 때마다 +1. 상세·하위 작업·연결·첨부·댓글·담당자 후보·저장 결과는 요청 때 세대를 잡고, 돌아왔을
|
||||
때 다르면 반영하지 않는다(A→B, A→B→A). 하위 작업·연결 블록도 자체 `ctxSeq` 로 늦은 응답을 버리고, 추가·연결은 누른 순간의
|
||||
작업 id 로 보낸다. 설명 이미지 업로드는 시작한 작업·세대가 바뀌었으면 설명에 넣지 않는다(파일은 원래 작업 첨부로 남음).
|
||||
- 자동 저장(`saveField`)은 성공/실패를 돌려준다. 실패한 칸은 `failedFields` 에 남고 "저장 실패 · 다시 시도"(눌러 재시도).
|
||||
닫기·Esc·다른 작업 열기(`openTaskModal` → `settleBeforeLeave`)는 이미지 업로드·만들기·저장 큐가 끝나길 기다리고 실패한 칸을
|
||||
한 번 더 보낸 뒤, 그래도 실패하면 "버리고 넘어가기 / 계속 편집"을 묻는다. 버리기를 고를 때만 초안을 버린다(`discardTaskEdits`).
|
||||
저장 성공 뒤 화면 다시 그리기 오류는 저장 실패로 표시하지 않는다. 미저장(실패·대기·업로드 중)일 때만 페이지 이탈 경고.
|
||||
- 읽기 전용 작업 창: 제목·설명·담당자·섹션·우선순위·마감일 잠금, 완료·삭제·댓글 입력·첨부 추가·서식 도구·하위 작업 추가·
|
||||
연결 추가/해제 숨김, 안내줄 `#pj-t-readonly`. 댓글 대화창도 `GET /comments` 의 `access` 로 입력칸을 숨긴다.
|
||||
- 실시간 동기화(`initLiveRefresh`): `observed`(서버에서 본 버전)와 `applied`(화면에 반영 성공한 버전)를 나눈다. 반영이
|
||||
성공해야 applied 를 올리고, 실패하면 다음 주기(8→16→32→60초)에 같은 버전을 다시 받는다. 동기화 중엔 겹쳐 돌지 않고, 늦게 온
|
||||
응답은 버린다(`syncSeq`). 프로젝트 화면은 `GET /api/projects/{id}/snapshot?scope=all` — 화면이 들고 있는 범위(볼 수 있는 모든
|
||||
최상위 프로젝트의 작업·섹션·프로젝트 목록)를 통째로 바꿔 끼운다(다른 프로젝트의 생성·삭제·섹션 변경·권한 회수 반영, 멀티호밍은
|
||||
`context_project_id` 별 한 행). 이 프로젝트 권한을 잃으면(403) 작업을 비우고 창을 닫고 안내줄 `.pj-access-lost`.
|
||||
- 날짜: 업무 기준 "오늘" = 한국시간(`kstTodayIso`, UTC+9 고정) — 대시보드 지연 수·마감 색·오늘/내일·내 작업 필터가 브라우저
|
||||
시간대와 무관하게 서버(`today_kst`)·마감 알림과 같다.
|
||||
|
||||
**댓글 파일** — 파일이 있는 댓글은 `POST /api/tasks/{id}/comments/files`(multipart: `files[]`·`body`·`parent_id`·`mentions`(JSON)·
|
||||
`client_token`) 한 요청으로, 댓글+첨부를 한 트랜잭션(`add_comment_with_attachments`)에 만든다. 빈 파일·20MB 초과가 하나라도
|
||||
있으면 아무것도 만들지 않고 400 `detail.failed=[{index,name,reason}]` → 화면은 그 파일만 빨갛게 표시하고 입력·파일을 유지.
|
||||
DB 실패면 방금 쓴 파일도 지운다. 글 댓글(`POST /comments`)은 본문 필수 — 예전 `has_attachment` 플래그는 받지 않는다.
|
||||
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리, 단일 워커 기준).
|
||||
작업 창 댓글 목록도 댓글별 첨부(이미지 미리보기·파일명 다운로드, 이스케이프)를 보여 주고, 첨부 파일 목록엔 "댓글" 표시.
|
||||
|
||||
**마감 알림** — `add_reminder_notification`: 발송 기록(`task_reminders`)과 수신함 알림을 한 트랜잭션에. 알림 생성이 실패하면
|
||||
기록도 되돌려져 다음 실행에서 다시 시도, 동시 실행도 UNIQUE 로 한 번만. 수신자는 지금 볼 수 있는 사람만. 보장 범위는 수신함
|
||||
알림까지 — 메일(`PROJECT_REMINDER_EMAIL`)은 새로 만든 알림만 요약해 보내고 메일 실패는 재시도하지 않는다.
|
||||
|
||||
**완료 섹션에 바로 만든 작업** — `create_task` 가 완료 섹션이면 `completed_at`·완료 이력(1건)을 넣고, 라우터가 완료 섹션 이동과
|
||||
같은 완료 알림(`_notify_completed`)을 보낸다. 섹션 없는 하위 작업·수동 완료/취소는 그대로.
|
||||
|
||||
**테스트** — `tests/test_project_module.py`(로컬 테스트용 PostgreSQL + FastAPI TestClient, `PROJECT_TEST_DB_URL` 가
|
||||
localhost 일 때만), `tests/js/project_ui.test.js`(jsdom, `python tests/js/render_project.py` 후 실행, `PJ_TEST_TZ` 로 해외 시간대).
|
||||
프런트 테스트 훅은 `window.__PJ_TEST__` 가 있을 때만 열린다.
|
||||
|
||||
**기존 데이터 점검(조회만 — 운영 교정은 따로 승인 후)**
|
||||
```sql
|
||||
-- 시작일 > 마감일(프로젝트·작업), 같은 날 시각 역전
|
||||
SELECT id, name, start_date, due_date FROM projects WHERE start_date > due_date;
|
||||
SELECT id, project_id, title, start_date, due_date, start_time, due_time FROM tasks
|
||||
WHERE start_date > due_date OR (start_date = due_date AND start_time > due_time);
|
||||
-- 본문도 첨부도 없는 빈 댓글(예전 파일 업로드 실패 흔적)
|
||||
SELECT c.id, c.task_id, c.author_email, c.created_at FROM task_comments c
|
||||
WHERE btrim(c.body) = '' AND NOT EXISTS (SELECT 1 FROM task_attachments a WHERE a.comment_id = c.id);
|
||||
-- 완료 섹션에 있는데 미완료인 작업(예전 완료 섹션 직접 생성)
|
||||
SELECT t.id, t.title FROM tasks t JOIN project_stages s ON s.id = t.stage_id
|
||||
WHERE s.is_done_stage AND t.completed_at IS NULL;
|
||||
```
|
||||
교정안: 날짜 역전은 담당자와 확인해 한쪽을 고치고, 빈 댓글은 작성자 확인 후 삭제, 완료 섹션 미완료는 완료로 표시하거나 섹션을 옮긴다.
|
||||
권한을 잃은 사람의 담당자·멘션·협업자 기록은 지우지 않아도 된다(화면·알림은 이미 지금 권한으로 거른다).
|
||||
|
||||
## 7. 추후 단계
|
||||
|
||||
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩,
|
||||
|
||||
@@ -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`.
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ pdfplumber>=0.11
|
||||
pillow>=10.0
|
||||
# 카페24 OAuth 토큰 암호화 저장(Fernet) — app/integrations/cafe24/crypto.py
|
||||
cryptography>=42.0
|
||||
# 네이버 커머스API 토큰 전자서명(client_secret_sign) — app/modules/performance/adapters/naver.py
|
||||
bcrypt>=4.1
|
||||
google-api-python-client>=2.100
|
||||
google-auth>=2.30
|
||||
# refresh token 발급 스크립트(scripts/google_sheets_authorize.py) 전용
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
-- =====================================================================
|
||||
-- cafe24_db 005 — 쓰기 안전장치
|
||||
-- 1) 상품·디자인 파일별 쓰기 잠금(lease) cafe24_write_locks
|
||||
-- 2) 카페24 쓰기 시도 기록(원격 결과·기록 단계) cafe24_write_attempts
|
||||
-- 3) 버전(revision)의 쇼핑몰·출처 메타데이터 cafe24_product_revisions
|
||||
-- 4) 예약 실행 lease + "확인 필요" 상태 cafe24_product_schedules
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent): 여러 번 실행해도 안전. 데이터 DROP/TRUNCATE/DELETE 없음.
|
||||
-- (예약 상태 CHECK 제약만 새 값 목록으로 교체한다 — 데이터는 그대로다.)
|
||||
--
|
||||
-- ⚠️ 운영 적용은 사용자 승인 + 백업 확인 후. 코드 배포 **전에** 적용한다
|
||||
-- (새 코드는 이 표가 없으면 카페24 쓰기를 거부한다 — 잠금 없이 쓰지 않기 위해).
|
||||
--
|
||||
-- 실행:
|
||||
-- docker exec -i postgres-db psql -U postgres -d cafe24_db \
|
||||
-- < scripts/sql/cafe24_db_005_write_safety.sql
|
||||
--
|
||||
-- 배경 (docs/CAFE24_MODULE.md 3-5):
|
||||
-- - 같은 상품을 두 사람(또는 웹 + 예약 worker)이 동시에 적용하면 둘 다 성공하고
|
||||
-- 나중 것이 앞의 것을 조용히 덮었다 → 상품별 DB 잠금(만료시각이 있는 lease).
|
||||
-- 프로세스가 죽어도 만료되면 다른 요청이 가져간다.
|
||||
-- - 읽기 지연 판정이 "우리가 아는 값" 목록에 충돌로 거절된 적용의 백업·초안까지
|
||||
-- 넣어, 관리자에서 직접 고친 값을 지연으로 오판했다 → 원격 쓰기가 **성공한**
|
||||
-- 시도만 판정 근거로 쓴다(이 표의 status).
|
||||
-- - 원격 쓰기는 성공했는데 로컬 기록이 실패하면 FAILED 로 보이고 재적용됐다
|
||||
-- → 원격 결과와 기록 단계를 나눠 남긴다.
|
||||
-- - worker 가 PROCESSING 중에 죽으면 영구히 남았다 → lease 만료 후 시도 기록을
|
||||
-- 보고 성공/재시도/확인 필요로 나눈다(무조건 PENDING 으로 돌리지 않는다).
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
|
||||
-- ── updated_at 트리거 함수 (init 에 있지만 단독 실행 대비) ──
|
||||
CREATE OR REPLACE FUNCTION cafe24_set_updated_at() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at := now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 1) 쓰기 잠금 — lock_key 예: 'product:131', 'design:pc_detail'
|
||||
-- 잡기: INSERT … ON CONFLICT DO UPDATE … WHERE expires_at < now()
|
||||
-- 풀기: DELETE … WHERE lock_key = ? AND token = ?
|
||||
-- 원격 쓰기 직전 token 으로 연장(펜싱) — 만료돼 남에게 넘어갔으면 쓰지 않는다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS cafe24_write_locks (
|
||||
lock_key TEXT PRIMARY KEY,
|
||||
owner TEXT NOT NULL DEFAULT '',
|
||||
token TEXT NOT NULL,
|
||||
purpose TEXT NOT NULL DEFAULT '',
|
||||
acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 2) 쓰기 시도 기록 (상세설명·진열/판매를 카페24에 PUT 하는 작업)
|
||||
-- status
|
||||
-- STARTED PUT 직전에 남김. 이 상태로 남아 있으면 결과를 모른다.
|
||||
-- REMOTE_OK 카페24 PUT 성공. 로컬 버전 기록은 아직(기록 복구 필요).
|
||||
-- RECORDED PUT 성공 + 버전(MANUAL/SCHEDULED/ROLLBACK) 기록 완료.
|
||||
-- REMOTE_FAILED 카페24가 거절(요청이 반영되지 않음이 확실).
|
||||
-- UNKNOWN 네트워크 끊김·5xx 등으로 반영 여부를 모름 → 사람 확인.
|
||||
-- ABANDONED 사람이 "반영 안 됨"으로 확정했거나 재실행으로 대체됨.
|
||||
-- target_html 은 기록(RECORDED) 전까지만 보관한다(기록 복구용). 기록 후 비운다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS cafe24_write_attempts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
product_no BIGINT NOT NULL,
|
||||
mall_id TEXT NOT NULL DEFAULT '',
|
||||
shop_no INTEGER NOT NULL DEFAULT 1,
|
||||
origin TEXT NOT NULL DEFAULT 'MANUAL',
|
||||
schedule_id BIGINT,
|
||||
actor TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'STARTED',
|
||||
backup_revision_id BIGINT,
|
||||
observed_digest TEXT NOT NULL DEFAULT '',
|
||||
base_digest TEXT NOT NULL DEFAULT '',
|
||||
target_digest TEXT NOT NULL DEFAULT '',
|
||||
target_html TEXT NOT NULL DEFAULT '',
|
||||
target_revision_id BIGINT,
|
||||
applied_revision_id BIGINT,
|
||||
set_display BOOLEAN,
|
||||
set_selling BOOLEAN,
|
||||
memo TEXT NOT NULL DEFAULT '',
|
||||
remote_updated_at TEXT NOT NULL DEFAULT '',
|
||||
error TEXT NOT NULL DEFAULT '',
|
||||
resolved_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
remote_at TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chk_cafe24_attempt_status CHECK (
|
||||
status IN ('STARTED','REMOTE_OK','RECORDED','REMOTE_FAILED','UNKNOWN','ABANDONED')
|
||||
),
|
||||
CONSTRAINT chk_cafe24_attempt_origin CHECK (
|
||||
origin IN ('MANUAL','SCHEDULED','ROLLBACK')
|
||||
)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_attempts_product
|
||||
ON cafe24_write_attempts (product_no, created_at DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_attempts_schedule
|
||||
ON cafe24_write_attempts (schedule_id) WHERE schedule_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_attempts_open
|
||||
ON cafe24_write_attempts (product_no, created_at DESC)
|
||||
WHERE status IN ('STARTED','REMOTE_OK','UNKNOWN');
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_cafe24_write_attempts_updated ON cafe24_write_attempts;
|
||||
CREATE TRIGGER trg_cafe24_write_attempts_updated
|
||||
BEFORE UPDATE ON cafe24_write_attempts
|
||||
FOR EACH ROW EXECUTE FUNCTION cafe24_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 3) 버전 메타데이터 (append-only 는 그대로 — INSERT 시점에만 채운다)
|
||||
-- mall_id / shop_no 어느 쇼핑몰의 버전인가(복원 시 일치 검사). 기존 행은 ''/1
|
||||
-- source BACKUP 의 출처
|
||||
-- OBSERVED 카페24 GET 으로 읽은 값
|
||||
-- LAST_WRITE 카페24가 읽기 지연 중이라 우리 마지막 쓰기(확인된
|
||||
-- 적용값)를 현재값으로 본 것
|
||||
-- ROLLBACK 은 'REVISION'(source_revision_id = 복원한 버전)
|
||||
-- source_revision_id LAST_WRITE 백업이 근거로 삼은 버전 / ROLLBACK 원본 버전
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
ALTER TABLE cafe24_product_revisions
|
||||
ADD COLUMN IF NOT EXISTS mall_id TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS shop_no INTEGER NOT NULL DEFAULT 1,
|
||||
ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS source_revision_id BIGINT;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 4) 예약 lease + 상태 NEEDS_REVIEW(확인 필요)
|
||||
-- PROCESSING 은 lease_expires_at 까지만 유효하다. 만료되면 worker 가 시도 기록을 보고
|
||||
-- 기록 완료/원격 성공 → SUCCESS, 원격 거절 → 재시도 규칙, 원격 전 중단 → 재시도 규칙,
|
||||
-- 결과 모름 → NEEDS_REVIEW (사람이 카페24를 보고 확정)
|
||||
-- lease 컬럼이 비어 있는 옛 PROCESSING 행은 started_at 기준으로 만료를 판정한다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
ADD COLUMN IF NOT EXISTS lease_owner TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS lease_token TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMPTZ;
|
||||
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
DROP CONSTRAINT IF EXISTS chk_cafe24_schedule_status;
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
ADD CONSTRAINT chk_cafe24_schedule_status CHECK (
|
||||
status IN ('PENDING','PROCESSING','SUCCESS','FAILED','CANCELLED','NEEDS_REVIEW')
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_schedules_processing
|
||||
ON cafe24_product_schedules (lease_expires_at)
|
||||
WHERE status = 'PROCESSING';
|
||||
|
||||
-- ── 권한 (cafe24_app: CRUD only) ──
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON cafe24_write_locks, cafe24_write_attempts TO cafe24_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO cafe24_app;
|
||||
|
||||
SELECT 'cafe24_db 005 applied' AS status;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,425 @@
|
||||
// 프로젝트 관리 화면(project/project.html + static/project.js) UI 회귀 테스트 — jsdom.
|
||||
// 서버 응답은 가짜(fetch 대체)로, 지연·실패·순서 역전을 직접 만든다. 실제 브라우저 레이아웃·입력기는 아니다.
|
||||
//
|
||||
// python tests/js/render_project.py # 템플릿 렌더 → tests/js/.out/project_render.html
|
||||
// npm install jsdom # (최초 1회)
|
||||
// TZ=America/Los_Angeles node tests/js/project_ui.test.js # 해외 시간대 브라우저 흉내
|
||||
//
|
||||
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
|
||||
// Git Bash 는 윈도우 프로그램에 TZ 를 넘기지 않아 PJ_TEST_TZ 로도 받는다(날짜 객체를 만들기 전에 설정).
|
||||
if (process.env.PJ_TEST_TZ) process.env.TZ = process.env.PJ_TEST_TZ;
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 90000);
|
||||
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
function deferred() {
|
||||
let resolve, reject;
|
||||
const p = new Promise(function (a, b) { resolve = a; reject = b; });
|
||||
return { promise: p, resolve: resolve, reject: reject };
|
||||
}
|
||||
|
||||
function makeEnv() {
|
||||
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
|
||||
const w = dom.window, d = w.document;
|
||||
w.__PJ_TEST__ = true;
|
||||
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
|
||||
w.URL.createObjectURL = function () { return "blob:x"; };
|
||||
w.URL.revokeObjectURL = function () {};
|
||||
w.Image = function () { const self = this; Object.defineProperty(self, "src", { set: function () { setTimeout(function () { if (self.onerror) self.onerror(); }, 0); } }); };
|
||||
w.console.error = function () {};
|
||||
let confirmAnswer = false;
|
||||
w.erpConfirm = function () { env.confirms++; return Promise.resolve(confirmAnswer); };
|
||||
w.erpAlert = function (m) { env.alerts.push(m); };
|
||||
w.alert = function (m) { env.alerts.push(m); };
|
||||
// 8초 이상 타이머(실시간 새로고침)는 붙잡아 두고 테스트가 직접 돌린다.
|
||||
const realSetTimeout = w.setTimeout.bind(w);
|
||||
const slow = [];
|
||||
w.setTimeout = function (fn, ms) {
|
||||
if (ms >= 8000) { slow.push({ fn: fn, ms: ms }); return 999000 + slow.length; }
|
||||
return realSetTimeout(fn, ms);
|
||||
};
|
||||
const env = {
|
||||
w: w, d: d, calls: [], routes: [], slow: slow, confirms: 0, alerts: [],
|
||||
setConfirm: function (v) { confirmAnswer = v; },
|
||||
route: function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); },
|
||||
runSlow: async function () { const t = slow.shift(); if (t) { t.fn(); await settle(); } return t; },
|
||||
};
|
||||
w.fetch = async function (url, opts) {
|
||||
const method = (opts && opts.method) || "GET";
|
||||
let body = opts && opts.body;
|
||||
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
|
||||
env.calls.push({ method: method, url: String(url), body: body });
|
||||
if (process.env.PJ_TEST_TRACE && method === "PUT") console.log(" TRACE PUT", url, new Error().stack.split("\n").slice(2, 7).join(" | "));
|
||||
for (const r of env.routes) {
|
||||
if (r.method === method && r.re.test(String(url))) {
|
||||
const out = await r.fn(String(url), body);
|
||||
if (out === "NETWORK") throw new TypeError("Failed to fetch");
|
||||
const status = out.status || 200;
|
||||
return { ok: status < 400, status: status, statusText: "x", json: async function () { return out.body; } };
|
||||
}
|
||||
}
|
||||
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; } };
|
||||
};
|
||||
return env;
|
||||
}
|
||||
|
||||
function settle(n) {
|
||||
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 30)) return r(); setImmediate(spin); })(); });
|
||||
}
|
||||
|
||||
function detail(id, title, extra) {
|
||||
return Object.assign({ id: id, title: title, project_id: 1, stage_id: 11, description: "", priority: "normal",
|
||||
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null }, extra || {});
|
||||
}
|
||||
|
||||
function baseRoutes(env) {
|
||||
env.route("GET", /\/project\/api\/tasks\/\d+\/attachments/, function () { return { body: { attachments: [] } }; });
|
||||
env.route("GET", /\/project\/api\/tasks\/\d+\/comments/, function () { return { body: { comments: [], events: [], features: {} } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/\d+\/members/, function () { return { body: { members: [{ user_email: "me@test.local" }] } }; });
|
||||
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [] } }; });
|
||||
env.route("GET", /\/project\/api\/all-users/, function () { return { body: { users: [] } }; });
|
||||
env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: "v1" } }; });
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return { body: { task: detail(101, "작업 A") } }; });
|
||||
env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B") } }; });
|
||||
}
|
||||
|
||||
async function boot(env) {
|
||||
// jsdom 이 문서를 다 읽고 DOMContentLoaded 를 보낸 뒤에 넣는다 — 먼저 넣으면 초기화가 두 번 돈다.
|
||||
if (env.d.readyState === "loading") {
|
||||
await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
|
||||
}
|
||||
// jsdom 의 <select>·일부 입력은 내부 Proxy 라 value 를 재정의(enhance*)하면 쓰기가 막힌다(실제 브라우저는
|
||||
// 문제없음, 기존 코드 그대로). 테스트에서는 버튼 보강을 건너뛰고 원래 입력칸으로 시험한다.
|
||||
env.d.querySelectorAll("select").forEach(function (s) { s.dataset.pjEnhanced = "1"; });
|
||||
env.d.querySelectorAll("input[type=date]").forEach(function (i) { i.dataset.pjDate = "1"; });
|
||||
env.w.eval(JS);
|
||||
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
|
||||
await settle();
|
||||
return env.w.__pjProject;
|
||||
}
|
||||
|
||||
function taskOf(P, id) { return P.state().tasks.find(function (t) { return t.id === id && t.context_project_id === 1; }); }
|
||||
function subsText(d) { // 하위 작업 제목은 입력칸 값이다
|
||||
return Array.from(d.querySelectorAll("#pj-subtask-list .pj-subtask-title")).map(function (i) { return i.value; }).join("|") ||
|
||||
d.getElementById("pj-subtask-list").textContent;
|
||||
}
|
||||
function wait(ms) { return new Promise(function (r) { setTimeout(r, ms); }); } // 창 닫기 애니메이션(0.32초) 대기
|
||||
function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
|
||||
(async function () {
|
||||
// ── [05] 한국시간 기준 오늘 ─────────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); await boot(env);
|
||||
const H = env.w.__pjHelpers;
|
||||
const kst = function (y, m, d, hh, mm) { return Date.UTC(y, m - 1, d, hh - 9, mm); };
|
||||
check("[05] KST 00:00 → 그날", H.kstTodayIso(kst(2026, 9, 30, 0, 0)) === "2026-09-30");
|
||||
check("[05] KST 08:59(UTC 전날) → 그날", H.kstTodayIso(kst(2026, 9, 30, 8, 59)) === "2026-09-30");
|
||||
check("[05] KST 09:00 → 그날", H.kstTodayIso(kst(2026, 9, 30, 9, 0)) === "2026-09-30");
|
||||
check("[05] KST 23:59 → 그날", H.kstTodayIso(kst(2026, 9, 30, 23, 59)) === "2026-09-30");
|
||||
const realNow = env.w.Date.now;
|
||||
env.w.Date.now = function () { return kst(2026, 9, 30, 8, 30); };
|
||||
const y = H.dueInfo("2026-09-29", false), t = H.dueInfo("2026-09-30", false);
|
||||
check("[05] 해외 시간대(" + (process.env.TZ || "기본") + ")·한국 오전에도 전날 마감=지남", y.cls === "is-overdue" && y.text === "어제", y);
|
||||
check("[05] 오늘 마감은 지남이 아님", t.cls === "is-soon" && t.text === "오늘", t);
|
||||
env.w.Date.now = realNow;
|
||||
}
|
||||
|
||||
// ── [09] A→B 전환 중 늦은 A 응답이 B 를 덮지 않는다 ───────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dA = deferred();
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return dA.promise; });
|
||||
env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B", { subtasks: [{ id: 902, title: "B-sub", project_id: 1 }] }) } }; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await P.openTaskModal(taskOf(P, 102));
|
||||
await settle();
|
||||
dA.resolve({ body: { task: detail(101, "작업 A", { subtasks: [{ id: 901, title: "A-sub", project_id: 1 }] }) } });
|
||||
await settle();
|
||||
check("[09] 늦은 A 상세가 B 의 하위 작업 목록을 덮지 않음", subsText(d).includes("B-sub") && !subsText(d).includes("A-sub"), subsText(d));
|
||||
env.route("POST", /\/project\/api\/projects\/1\/tasks$/, function (u, b) { return { status: 201, body: { task: detail(903, b.title, { parent_task_id: b.parent_task_id }) } }; });
|
||||
d.getElementById("pj-subtask-input").value = "새 하위";
|
||||
d.getElementById("pj-subtask-add").click();
|
||||
await settle();
|
||||
const post = env.calls.filter(function (c) { return c.method === "POST" && /projects\/1\/tasks$/.test(c.url); }).pop();
|
||||
check("[09] B 화면에서 추가한 하위 작업은 B 에 붙음", post && post.body.parent_task_id === 102, post && post.body);
|
||||
}
|
||||
// A→B→A — 같은 작업을 다시 열어도 이전 요청은 버린다
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dOld = deferred(); let n = 0;
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () {
|
||||
n++;
|
||||
if (n === 1) return dOld.promise;
|
||||
return { body: { task: detail(101, "작업 A", { subtasks: [{ id: 911, title: "A-new", project_id: 1 }] }) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await P.openTaskModal(taskOf(P, 102));
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await settle();
|
||||
dOld.resolve({ body: { task: detail(101, "작업 A", { subtasks: [{ id: 910, title: "A-old", project_id: 1 }] }) } });
|
||||
await settle();
|
||||
check("[09] A→B→A 에서 첫 A 의 늦은 응답은 버림", subsText(d).includes("A-new") && !subsText(d).includes("A-old"), subsText(d));
|
||||
}
|
||||
// 이미지 업로드 중 A→B 전환 — 업로드가 끝나 A 설명에 들어가고 저장된 뒤에 B 가 열린다
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const up = deferred();
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/attachments$/, function () { return up.promise; });
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) { return { body: { task: Object.assign(detail(101, "작업 A"), b) } }; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await settle();
|
||||
const box = d.getElementById("pj-t-desc");
|
||||
const file = new env.w.File(["x"], "a.png", { type: "image/png" });
|
||||
const ev = new env.w.Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(ev, "clipboardData", { value: { items: [{ type: "image/png", getAsFile: function () { return file; } }], getData: function () { return ""; } } });
|
||||
box.dispatchEvent(ev);
|
||||
await settle();
|
||||
const switching = P.openTaskModal(taskOf(P, 102));
|
||||
await settle();
|
||||
check("[09] 업로드 중에는 B 로 넘어가지 않고 기다림", d.getElementById("pj-t-id").value === "101");
|
||||
up.resolve({ status: 201, body: { attachment: { id: 55 } } });
|
||||
await switching; await settle();
|
||||
const put = env.calls.filter(function (c) { return c.method === "PUT" && /tasks\/101$/.test(c.url) && c.body.description; }).pop();
|
||||
check("[09] 업로드된 이미지는 A 설명에 넣어 A 에 저장", !!put && put.body.description.includes("/attachments/55/inline"), put && put.body);
|
||||
check("[09] 그 다음 B 가 열리고 B 설명엔 이미지 없음", d.getElementById("pj-t-id").value === "102" && !box.innerHTML.includes("/attachments/55/"));
|
||||
}
|
||||
|
||||
// ── [10] 저장 실패 후 닫기 — 유실 없이 재시도/버리기 선택 ─────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let putStatus = 500; const puts = [];
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) {
|
||||
puts.push(b);
|
||||
return putStatus >= 400 ? { status: putStatus, body: { detail: "서버 오류" } } : { body: { task: Object.assign(detail(101, "작업 A"), b) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const ta = d.getElementById("pj-t-title");
|
||||
ta.value = "작업 A2"; ta.dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
check("[10] 실패한 칸 기록 + '저장 실패 · 다시 시도' 표시", P.state().failed.includes("title") && d.getElementById("pj-autosave-state").textContent.includes("저장 실패"), P.state().failed);
|
||||
check("[10] 저장 안 된 상태면 페이지 이탈 경고 대상", P.state().unsaved === true);
|
||||
env.setConfirm(false); // 계속 편집
|
||||
await P.attemptClose(); await settle();
|
||||
check("[10] 닫기 때 재시도해도 실패 → 묻고, '계속 편집'이면 창·입력 유지", !modal.hidden && titleVal(d) === "작업 A2" && env.confirms === 1);
|
||||
putStatus = 200;
|
||||
await P.attemptClose(); await settle(); await wait(400);
|
||||
check("[10] 다시 닫기 → 재시도 성공 후 닫힘", modal.hidden && puts[puts.length - 1].title === "작업 A2", { hidden: modal.hidden, last: puts[puts.length - 1] });
|
||||
check("[10] 저장된 상태에서는 이탈 경고 없음", P.state().unsaved === false);
|
||||
}
|
||||
{
|
||||
// 403·지연 + Escape + 버리기, A 실패가 B 상태를 오염시키지 않음
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dPut = deferred();
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function () { return dPut.promise; });
|
||||
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
d.getElementById("pj-t-priority").value = "high";
|
||||
d.getElementById("pj-t-priority").dispatchEvent(new env.w.Event("change")); await settle();
|
||||
d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[10] 저장 중 Esc → 저장이 끝날 때까지 창 유지", !modal.hidden);
|
||||
env.setConfirm(true); // 버리고 넘어가기
|
||||
const opening = P.openTaskModal(taskOf(P, 102)); await settle();
|
||||
dPut.resolve({ status: 403, body: { detail: "권한 없음" } });
|
||||
await opening; await settle();
|
||||
check("[10] 403 실패 → 버리기 선택 후 B 열림", d.getElementById("pj-t-id").value === "102" && !modal.hidden);
|
||||
check("[10] A 의 실패가 B 상태를 오염시키지 않음", P.state().failed.length === 0 && d.getElementById("pj-autosave-state").textContent === "", P.state().failed);
|
||||
}
|
||||
{
|
||||
// 네트워크 단절 → 계속 편집, 복구 후 표시줄 클릭으로 재시도
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let net = false; const puts = [];
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) { puts.push(b); return net ? { body: { task: Object.assign(detail(101, "작업 A"), b) } } : "NETWORK"; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
d.getElementById("pj-t-due").value = "2026-10-10";
|
||||
d.getElementById("pj-t-due").dispatchEvent(new env.w.Event("change")); await settle();
|
||||
check("[10] 네트워크 오류 → 마감일 칸 실패로 남음", P.state().failed.includes("due"));
|
||||
net = true;
|
||||
const stEl = d.getElementById("pj-autosave-state");
|
||||
const stBefore = stEl.dataset.state;
|
||||
stEl.click(); await settle();
|
||||
check("[10] '다시 시도' → 같은 값으로 재전송 성공", P.state().failed.length === 0 && puts[puts.length - 1].due_date === "2026-10-10",
|
||||
{ stBefore: stBefore, failed: P.state().failed, puts: puts });
|
||||
}
|
||||
|
||||
// ── [16] 한글 조합 Enter ─────────────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dPost = deferred();
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/comments$/, function () { return dPost.promise; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const inp = d.getElementById("pj-comment-input");
|
||||
inp.value = "안녕하세요";
|
||||
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true }));
|
||||
const ev229 = new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });
|
||||
Object.defineProperty(ev229, "keyCode", { value: 229 });
|
||||
inp.dispatchEvent(ev229);
|
||||
await settle();
|
||||
const posts = function () { return env.calls.filter(function (c) { return c.method === "POST" && /101\/comments$/.test(c.url); }); };
|
||||
check("[16] 조합 중 Enter(isComposing·229)는 댓글 전송 안 함", posts().length === 0);
|
||||
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
await settle();
|
||||
check("[16] 조합이 끝난 Enter 연타 → 한 번만 전송", posts().length === 1 && posts()[0].body.client_token, posts().length);
|
||||
dPost.resolve({ status: 201, body: { comment: { id: 1, body: "안녕하세요" }, mention_skipped: [] } }); await settle();
|
||||
const sub = d.getElementById("pj-subtask-input");
|
||||
await settle(); sub.value = "하위";
|
||||
sub.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true })); await settle();
|
||||
check("[16] 하위 작업 칸도 조합 중 Enter 는 추가 안 함", !env.calls.some(function (c) { return c.method === "POST" && /projects\/1\/tasks$/.test(c.url); }));
|
||||
const cm = d.getElementById("pj-cm-input");
|
||||
env.w.__pjChat.open(101); await settle();
|
||||
cm.value = "채팅";
|
||||
cm.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true })); await settle();
|
||||
check("[16] 댓글 대화창도 조합 중 Enter 는 전송 안 함", posts().length === 1);
|
||||
}
|
||||
|
||||
// ── [03] 파일 댓글 — 실패 파일 표시·유지, 성공 시 비움 ───────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let mode = "fail";
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/comments\/files$/, function () {
|
||||
if (mode === "fail") return { status: 400, body: { detail: { message: "보낼 수 없는 파일이 있어 댓글을 등록하지 않았습니다.", failed: [{ index: "1", name: "b.png", reason: "빈 파일" }] } } };
|
||||
if (mode === "net") return "NETWORK";
|
||||
return { status: 201, body: { comment: { id: 5, body: "" }, attachments: [], mention_skipped: [] } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
env.w.__pjChat.open(101); await settle();
|
||||
const cm = d.getElementById("pj-cm-input");
|
||||
function pasteImg(name, content) {
|
||||
const f = new env.w.File(content, name, { type: "image/png" });
|
||||
const ev = new env.w.Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(ev, "clipboardData", { value: { items: [{ type: "image/png", getAsFile: function () { return f; } }], getData: function () { return ""; } } });
|
||||
cm.dispatchEvent(ev);
|
||||
}
|
||||
pasteImg("a.png", ["aaa"]); pasteImg("b.png", []);
|
||||
await settle();
|
||||
d.getElementById("pj-cm-send").click(); await settle();
|
||||
const chips = function () { return Array.from(d.querySelectorAll("#pj-cm-pending .pj-chat-pending-chip")); };
|
||||
check("[03] 서버가 거절한 파일만 빨간 표시, 두 파일 모두 남음", chips().length === 2 && chips()[1].classList.contains("is-failed") && !chips()[0].classList.contains("is-failed"));
|
||||
const sent = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); });
|
||||
check("[03] 파일은 본문과 한 요청으로(빈 댓글을 먼저 만들지 않음)", sent.length === 1 && !env.calls.some(function (c) { return c.method === "POST" && /101\/comments$/.test(c.url); }));
|
||||
mode = "net";
|
||||
d.getElementById("pj-cm-send").click(); await settle();
|
||||
check("[03] 네트워크 오류 → 파일·입력 유지", chips().length === 2);
|
||||
const tok1 = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); }).pop().body.get("client_token");
|
||||
mode = "ok";
|
||||
d.getElementById("pj-cm-send").click(); await settle();
|
||||
const tok2 = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); }).pop().body.get("client_token");
|
||||
check("[03] 응답을 못 받은 재전송은 같은 client_token(서버가 한 번만 만듦)", tok1 && tok1 === tok2);
|
||||
check("[03] 성공하면 대기 파일 비움", chips().length === 0);
|
||||
}
|
||||
|
||||
// ── [14] 작업 창 댓글에 파일 표시 ─────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/tasks\/101\/comments/, function () {
|
||||
return { body: { comments: [{ id: 7, body: "", author_email: "me@test.local", created_at: "2026-09-30T10:00" },
|
||||
{ id: 8, body: "답글", parent_id: 7, author_email: "me@test.local", created_at: "2026-09-30T10:01" }],
|
||||
events: [], features: { replies: true } } };
|
||||
});
|
||||
env.route("GET", /\/project\/api\/tasks\/101\/attachments/, function () {
|
||||
return { body: { attachments: [{ id: 70, comment_id: 7, filename: "<b>x</b>.pdf", content_type: "application/pdf", size_bytes: 10 },
|
||||
{ id: 71, comment_id: 8, filename: "r.png", content_type: "image/png", size_bytes: 10 },
|
||||
{ id: 72, comment_id: null, filename: "plain.txt", content_type: "text/plain", size_bytes: 10 }] } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const list = d.getElementById("pj-comment-list");
|
||||
check("[14] 파일만 있는 댓글에 파일 표시", list.querySelector('a[href="/project/api/attachments/70/download"]') !== null);
|
||||
check("[14] 파일명은 이스케이프(태그로 해석 안 됨)", !list.querySelector(".pj-comment-atts b") && list.textContent.includes("<b>x</b>.pdf"));
|
||||
check("[14] 답글의 파일은 답글에", !!list.querySelector(".pj-comment-item.is-reply img[src='/project/api/attachments/71/inline']"));
|
||||
check("[14] 댓글 아닌 첨부는 댓글에 안 섞임", !list.innerHTML.includes("attachments/72/"));
|
||||
check("[14] 첨부 목록에 '댓글' 표시", d.getElementById("pj-attach-list").textContent.includes("댓글"));
|
||||
}
|
||||
|
||||
// ── [12] 연결된 작업은 읽기 전용 ─────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/tasks\/301$/, function () {
|
||||
return { body: { task: detail(301, "연결된 작업", { project_id: 3, project_name: "비밀", access: "read", followers: null, subtasks: [{ id: 3011, title: "읽기 하위", project_id: 3 }] }) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
const linked = P.state().tasks.find(function (t) { return t.id === 301; });
|
||||
await P.openTaskModal(linked); await settle();
|
||||
check("[12] 제목·담당자 편집 불가", d.getElementById("pj-t-title").readOnly && d.getElementById("pj-t-assignee").disabled);
|
||||
check("[12] 읽기 전용 안내 표시", !d.getElementById("pj-t-readonly").hidden);
|
||||
check("[12] 댓글 입력·완료·삭제 숨김", d.getElementById("pj-comment-dock").hidden && d.getElementById("pj-toggle-complete").hidden && d.getElementById("pj-delete-task").hidden);
|
||||
check("[12] 하위 작업 추가 칸 숨김, 목록은 보임", d.querySelector(".pj-subtask-form").hidden && subsText(d).includes("읽기 하위"));
|
||||
d.getElementById("pj-t-title").value = "바꿈";
|
||||
d.getElementById("pj-t-title").dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
const puts12 = env.calls.filter(function (c) { return c.method === "PUT"; });
|
||||
check("[12] 읽기 전용이면 저장 요청을 보내지 않음(뒤늦은 403 없음)", puts12.length === 0, puts12);
|
||||
}
|
||||
|
||||
// ── [13][01] 실시간 동기화 — 실패 후 같은 버전 재시도, 전체 범위 반영, 권한 회수 ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let ver = "v1", snapMode = "fail";
|
||||
const dSnap = deferred();
|
||||
env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: ver } }; });
|
||||
env.route("GET", /\/snapshot\?scope=all/, function () {
|
||||
if (snapMode === "fail") return { status: 500, body: { detail: "잠시 오류" } };
|
||||
if (snapMode === "slow") return dSnap.promise;
|
||||
if (snapMode === "gone") return { status: 403, body: { detail: "권한 없음" } };
|
||||
return { body: { scope: "all", project: { id: 1, name: "P1" },
|
||||
projects: [{ id: 1, name: "P1", color: "#4573d2", status: "active" }],
|
||||
tasks: [{ id: 101, title: "작업 A(새 제목)", project_id: 1, context_project_id: 1, stage_id: 11, stage_name: "할 일" },
|
||||
{ id: 150, title: "다른 사람이 만든 작업", project_id: 1, context_project_id: 1, stage_id: 13, stage_name: "검토" }],
|
||||
stages_by_project: { "1": [{ id: 11, project_id: 1, name: "할 일" }, { id: 13, project_id: 1, name: "검토" }] },
|
||||
stages: [{ id: 11, project_id: 1, name: "할 일" }, { id: 13, project_id: 1, name: "검토" }],
|
||||
members: [{ user_email: "me@test.local" }] } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
const st = function () { return env.w.pjLiveRefreshState(); };
|
||||
const poll = function () { return env.w.__pjLivePoll(); };
|
||||
const nextDelay = function () { const t = env.slow.filter(function (s) { return s.fn === env.w.__pjLivePoll; }).pop(); return t && t.ms; };
|
||||
check("[13] 처음 본 버전 = 반영된 버전", st().observed === "v1" && st().applied === "v1");
|
||||
ver = "v2";
|
||||
await poll(); await settle();
|
||||
check("[13] 스냅샷 실패 → 반영 버전은 그대로(v1), 실패 1", st().observed === "v2" && st().applied === "v1" && st().failures === 1, st());
|
||||
check("[13] 실패 뒤 다음 확인은 늘어난 간격(16초)", nextDelay() === 16000, nextDelay());
|
||||
snapMode = "ok";
|
||||
await poll(); await settle();
|
||||
check("[13] 같은 버전 다음 요청 성공 → v2 반영", st().applied === "v2" && st().failures === 0, st());
|
||||
const s = P.state();
|
||||
check("[01] 다른 프로젝트(P2) 작업·사이드바 항목 제거(권한 회수)", !s.tasks.some(function (t) { return t.project_id === 2; }) && !s.projectsMeta.some(function (p) { return p.id === 2; }));
|
||||
check("[01] 새 작업·새 섹션 반영", s.tasks.some(function (t) { return t.id === 150; }) && s.boardStages.includes("검토"));
|
||||
check("[01] 제목 변경 반영", s.tasks.find(function (t) { return t.id === 101; }).title === "작업 A(새 제목)");
|
||||
// 동기화 중 버전이 또 바뀌면 끝난 뒤 한 번 더
|
||||
snapMode = "slow"; ver = "v3";
|
||||
const firstPoll = poll();
|
||||
await settle();
|
||||
ver = "v4";
|
||||
const snapsBefore = env.calls.filter(function (c) { return /snapshot/.test(c.url); }).length;
|
||||
await poll(); // 동기화가 도는 중에 또 확인 — 겹쳐 받지 않는다
|
||||
const snapsDuring = env.calls.filter(function (c) { return /snapshot/.test(c.url); }).length;
|
||||
dSnap.resolve({ body: { tasks: [], projects: [{ id: 1, name: "P1", status: "active" }], stages_by_project: {}, stages: [], members: [] } });
|
||||
await firstPoll; await settle();
|
||||
check("[13] 동기화 중 새 버전(v4) — 겹쳐 돌지 않고 반영 버전은 v3", st().applied === "v3" && st().observed === "v4" && snapsDuring === snapsBefore, { st: st(), snapsBefore: snapsBefore, snapsDuring: snapsDuring });
|
||||
snapMode = "ok";
|
||||
await poll(); await settle();
|
||||
check("[13] 다음 주기에 v4 반영", st().applied === "v4", st());
|
||||
snapMode = "gone"; ver = "v5";
|
||||
await poll(); await settle();
|
||||
check("[01][02] 이 프로젝트 권한 회수 → 작업 비우고 안내", !!d.querySelector(".pj-access-lost") && P.state().tasks.length === 0);
|
||||
}
|
||||
|
||||
clearTimeout(WATCHDOG);
|
||||
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})().catch(function (e) { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,71 @@
|
||||
"""project/project.html 을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_project.py # → tests/js/.out/project_render.html
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
import jinja2
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_actions %}{% endblock %}"
|
||||
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
|
||||
|
||||
ME = "me@test.local"
|
||||
STAGES = {
|
||||
1: [{"id": 11, "project_id": 1, "name": "할 일", "is_done_stage": False, "sort_order": 0, "color": None,
|
||||
"created_by": ME, "default_assignee_email": ""},
|
||||
{"id": 12, "project_id": 1, "name": "완료", "is_done_stage": True, "sort_order": 1, "color": None,
|
||||
"created_by": ME, "default_assignee_email": ""}],
|
||||
2: [{"id": 21, "project_id": 2, "name": "할 일", "is_done_stage": False, "sort_order": 0, "color": None,
|
||||
"created_by": ME, "default_assignee_email": ""}],
|
||||
}
|
||||
|
||||
|
||||
def task(tid: int, title: str, pid: int, stage: int, *, ctx: int | None = None, linked: bool = False) -> dict:
|
||||
return {"id": tid, "title": title, "project_id": pid, "context_project_id": ctx or pid, "is_linked": linked,
|
||||
"stage_id": stage, "home_stage_id": stage, "stage_name": "할 일", "is_done_stage": False,
|
||||
"description": "", "assignee_email": "", "assignee_name": "", "priority": "normal",
|
||||
"start_date": None, "due_date": None, "completed_at": None, "created_by": ME,
|
||||
"parent_task_id": None, "comment_count": 0, "subtask_count": 0, "subtask_done": 0,
|
||||
"project_name": {1: "P1", 2: "P2", 3: "비밀"}[pid], "project_color": "#4573d2", "sort_order": tid}
|
||||
|
||||
|
||||
TASKS = [task(101, "작업 A", 1, 11), task(102, "작업 B", 1, 11), task(103, "작업 C", 2, 21),
|
||||
task(301, "연결된 작업", 3, 99, ctx=1, linked=True)]
|
||||
PROJECTS = [{"id": 1, "name": "P1", "color": "#4573d2", "icon": "", "start_date": None, "due_date": None,
|
||||
"created_by": ME, "description": "", "status": "active"},
|
||||
{"id": 2, "name": "P2", "color": "#f06a6a", "icon": "", "start_date": None, "due_date": None,
|
||||
"created_by": ME, "description": "", "status": "active"}]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||
]))
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
html = env.get_template("project/project.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=False, can_manage=True,
|
||||
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
|
||||
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
|
||||
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
|
||||
avatars={}, priority_labels={"low": "낮음", "normal": "보통", "high": "높음"},
|
||||
color_palette=["#4573d2"], project_icons=["folder"], stage_color_palette=["#c7c4c4"],
|
||||
today="2026-09-30", holidays={}, year=2026, month=9, prev_y=2026, prev_m=8, next_y=2026, next_m=10,
|
||||
weekdays=["일", "월", "화", "수", "목", "금", "토"], weeks=[], goal_years=[2026],
|
||||
my_open_total=0, mention_unread=0,
|
||||
)
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
path = os.path.join(OUT_DIR, "project_render.html")
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,633 @@
|
||||
"""카페24 모듈 — 실제 PostgreSQL 잠금·lease·JSONB 병합 + FastAPI 라우트 통합 테스트.
|
||||
|
||||
운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 카페24 API·FTP 는 가짜
|
||||
(app/modules/cafe24/tests/fakes.py)이며 실제 쇼핑몰·디자인 파일은 건드리지 않는다.
|
||||
|
||||
# 1) 로컬 테스트 DB 에 스키마 적용(최초 1회)
|
||||
# psql -v app_password=... -f scripts/sql/cafe24_db_init.sql
|
||||
# psql -d cafe24_db -f scripts/sql/cafe24_db_002_… 003 … 004 … 005_write_safety.sql
|
||||
# 2) 실행
|
||||
CAFE24_TEST_DB_URL=postgresql://postgres@localhost:55432/cafe24_db python tests/test_cafe24_db.py
|
||||
|
||||
CAFE24_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호).
|
||||
테스트마다 새 상품번호를 쓰고 기존 행을 지우지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import threading
|
||||
import types
|
||||
from datetime import timedelta
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
DSN = os.getenv("CAFE24_TEST_DB_URL", "")
|
||||
_host = urlparse(DSN).hostname if DSN else None
|
||||
ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1")
|
||||
|
||||
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
||||
|
||||
if ENABLED:
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
USERS = {
|
||||
"king@test.local": {"email": "king@test.local", "role": "admin", "modules": {"cafe24": True}},
|
||||
"amy@test.local": {"email": "amy@test.local", "role": "user", "modules": {"cafe24": True}},
|
||||
"nope@test.local": {"email": "nope@test.local", "role": "user", "modules": {}},
|
||||
}
|
||||
fake_main = types.ModuleType("app.main")
|
||||
fake_main.get_current_user_record = lambda request: USERS.get(request.headers.get("x-test-user", ""))
|
||||
fake_main.build_erp_nav = lambda user, active="": []
|
||||
|
||||
def _render(request, name, ctx, status_code=200):
|
||||
keep = {k: ctx.get(k) for k in ("sync_state", "fingerprint", "html_pc", "editor_error", "open_attempts",
|
||||
"revisions", "reason", "flash", "flash_error", "rows")}
|
||||
return HTMLResponse(name + "\n" + json.dumps(keep, ensure_ascii=False, default=str), status_code=status_code)
|
||||
|
||||
fake_main.render_template = _render
|
||||
sys.modules["app.main"] = fake_main
|
||||
os.environ.update({
|
||||
"CAFE24_MALL_ID": "testmall", "CAFE24_CLIENT_ID": "cid", "CAFE24_CLIENT_SECRET": "cs",
|
||||
"CAFE24_REDIRECT_URI": "http://localhost/cb", "CAFE24_TOKEN_SECRET": "unit-test-secret",
|
||||
"CAFE24_WRITE_LOCK_WAIT_SEC": "3",
|
||||
})
|
||||
os.environ.pop("CAFE24_READ_LAG_GRACE_MIN", None)
|
||||
|
||||
from fastapi import FastAPI # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from app.integrations.cafe24 import products # noqa: E402
|
||||
from app.modules.cafe24 import ( # noqa: E402
|
||||
routes_design_files, routes_product_info, routes_products, routes_schedules, store, worker, writes,
|
||||
)
|
||||
from app.modules.cafe24.db import Cafe24Store # noqa: E402
|
||||
from app.modules.cafe24.router import router as cafe24_router # noqa: E402
|
||||
from app.modules.cafe24.tests import fakes # noqa: E402
|
||||
from app.timezone import now_kst # noqa: E402
|
||||
|
||||
products.time.sleep = lambda *_a, **_k: None
|
||||
ST = Cafe24Store(DSN)
|
||||
ST2 = Cafe24Store(DSN) # 두 번째 "프로세스"(별도 연결 풀)
|
||||
|
||||
class _Multi:
|
||||
"""상품번호별 FakeCafe24 로 요청을 나눠 준다(모르는 상품은 빈 응답)."""
|
||||
|
||||
def __init__(self):
|
||||
self.by_no: dict[int, fakes.FakeCafe24] = {}
|
||||
|
||||
def _pick(self, path):
|
||||
parts = path.split("/")
|
||||
try:
|
||||
return self.by_no.get(int(parts[3]))
|
||||
except (IndexError, ValueError):
|
||||
return None
|
||||
|
||||
def __getattr__(self, method):
|
||||
if method not in ("get", "put", "post", "delete"):
|
||||
raise AttributeError(method)
|
||||
|
||||
def call(path, **kw):
|
||||
target = self._pick(path)
|
||||
return getattr(target, method)(path, **kw) if target else {}
|
||||
|
||||
return call
|
||||
|
||||
MULTI = _Multi()
|
||||
for _mod in (routes_products, routes_product_info, routes_schedules):
|
||||
_mod.build_cafe24_api = lambda st, **kw: fakes.FakeApi(MULTI)
|
||||
|
||||
APP = FastAPI()
|
||||
APP.include_router(cafe24_router)
|
||||
APP.state.cafe24_store = ST
|
||||
CLIENT = TestClient(APP)
|
||||
|
||||
_BASE = random.randint(100_000, 900_000) * 10
|
||||
|
||||
|
||||
def _new_product(description="<p>A</p>") -> tuple[int, "fakes.FakeCafe24"]:
|
||||
global _BASE
|
||||
_BASE += 1
|
||||
cafe = fakes.FakeCafe24(description, product_no=_BASE)
|
||||
MULTI.by_no[_BASE] = cafe
|
||||
return _BASE, cafe
|
||||
|
||||
|
||||
def req(method, url, who="king@test.local", **kw):
|
||||
return CLIENT.request(method, url, headers={"x-test-user": who}, follow_redirects=False, **kw)
|
||||
|
||||
|
||||
def q(sql, *args):
|
||||
with ST._pool.connection() as conn: # noqa: SLF001 — 테스트 확인용
|
||||
cur = conn.execute(sql, args)
|
||||
return cur.fetchall() if cur.description else []
|
||||
|
||||
|
||||
def _location(resp) -> dict:
|
||||
loc = resp.headers.get("location", "")
|
||||
return {k: v[0] for k, v in parse_qs(urlparse(loc).query).items()}
|
||||
|
||||
|
||||
def _pane(no):
|
||||
resp = req("GET", f"/cafe24/products/{no}/pane")
|
||||
assert resp.status_code == 200, resp.text
|
||||
return json.loads(resp.text.split("\n", 1)[1])
|
||||
|
||||
|
||||
def _apply(no, html, fp, who="king@test.local", memo=""):
|
||||
return req("POST", f"/cafe24/products/{no}/apply",
|
||||
data={"html": html, "base_fingerprint": fp, "memo": memo}, who=who)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# DB — 잠금(lease)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_lock_exclusive_across_pools_and_expiry_fencing():
|
||||
key = f"test:lock:{_BASE}:{random.random()}"
|
||||
t1 = ST.acquire_lock(key, owner="a|h:1", purpose="p", ttl_seconds=60)
|
||||
assert t1
|
||||
assert ST2.acquire_lock(key, owner="b|h:2", purpose="p", ttl_seconds=60) is None
|
||||
assert ST2.lock_holder(key)["owner"].startswith("a|")
|
||||
assert ST.renew_lock(key, t1, ttl_seconds=60)
|
||||
q("UPDATE cafe24_write_locks SET expires_at = now() - interval '1 second' WHERE lock_key = %s", key)
|
||||
t2 = ST2.acquire_lock(key, owner="b|h:2", purpose="p", ttl_seconds=60)
|
||||
assert t2 and t2 != t1
|
||||
assert ST.renew_lock(key, t1, ttl_seconds=60) is False # 펜싱: 넘어간 잠금은 연장 불가
|
||||
ST.release_lock(key, t1) # 남의 잠금은 못 푼다
|
||||
assert ST2.lock_holder(key)["owner"].startswith("b|")
|
||||
ST2.release_lock(key, t2)
|
||||
assert ST.lock_holder(key) == {}
|
||||
|
||||
|
||||
def test_lock_race_only_one_winner():
|
||||
key = f"test:race:{_BASE}:{random.random()}"
|
||||
tokens, barrier = [], threading.Barrier(8)
|
||||
|
||||
def grab(s):
|
||||
barrier.wait()
|
||||
tokens.append(s.acquire_lock(key, owner="x", purpose="p", ttl_seconds=30))
|
||||
|
||||
threads = [threading.Thread(target=grab, args=(ST if i % 2 else ST2,)) for i in range(8)]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
assert sum(1 for t in tokens if t) == 1, tokens
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# DB — 예약 lease
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _schedule(no, **kw):
|
||||
fields = dict(product_no=no, scheduled_at=now_kst() - timedelta(minutes=1), revision_id=None,
|
||||
set_display=True, set_selling=None)
|
||||
fields.update(kw)
|
||||
return ST.create_schedule(**fields)
|
||||
|
||||
|
||||
def test_schedule_claim_is_exclusive_between_workers():
|
||||
no, _ = _new_product()
|
||||
ids = {_schedule(no) for _ in range(6)}
|
||||
got, barrier = [], threading.Barrier(2)
|
||||
|
||||
def run(s, name):
|
||||
barrier.wait()
|
||||
while True:
|
||||
row = s.claim_due_schedule(now=now_kst(), owner=name, ttl_seconds=60)
|
||||
if row is None:
|
||||
return
|
||||
got.append(row["id"])
|
||||
|
||||
threads = [threading.Thread(target=run, args=(ST, "w1")), threading.Thread(target=run, args=(ST2, "w2"))]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
mine = [i for i in got if i in ids]
|
||||
assert sorted(mine) == sorted(ids) and len(mine) == len(set(mine)), got
|
||||
|
||||
|
||||
def test_schedule_lease_expiry_and_stale_finish():
|
||||
no, _ = _new_product()
|
||||
sid = _schedule(no, scheduled_at=now_kst() - timedelta(days=3650)) # 가장 먼저 잡히게
|
||||
row = ST.claim_due_schedule(now=now_kst(), owner="w1", ttl_seconds=60)
|
||||
assert row["id"] == sid and row["lease_token"]
|
||||
assert ST.renew_schedule_lease(sid, row["lease_token"], ttl_seconds=60)
|
||||
q("UPDATE cafe24_product_schedules SET lease_expires_at = now() - interval '1 second' WHERE id = %s", sid)
|
||||
taken = [r for r in ST2.claim_expired_schedules(owner="w2", ttl_seconds=60, legacy_minutes=30) if r["id"] == sid]
|
||||
assert taken and taken[0]["lease_token"] != row["lease_token"]
|
||||
assert ST.renew_schedule_lease(sid, row["lease_token"], ttl_seconds=60) is False
|
||||
assert ST.finish_schedule(sid, token=row["lease_token"], status="FAILED") is False # 늦은 결과 무시
|
||||
assert ST2.finish_schedule(sid, token=taken[0]["lease_token"], status="SUCCESS") is True
|
||||
assert q("SELECT status, lease_token FROM cafe24_product_schedules WHERE id = %s", sid)[0] == \
|
||||
{"status": "SUCCESS", "lease_token": ""}
|
||||
|
||||
|
||||
def test_legacy_processing_row_is_recovered():
|
||||
"""005 이전에 PROCESSING 이 된 행(lease 없음)도 오래됐으면 복구 대상."""
|
||||
no, _ = _new_product()
|
||||
sid = _schedule(no)
|
||||
q("UPDATE cafe24_product_schedules SET status='PROCESSING', started_at = now() - interval '40 minutes' "
|
||||
"WHERE id = %s RETURNING id", sid)
|
||||
rows = [r for r in ST.claim_expired_schedules(owner="w", ttl_seconds=60, legacy_minutes=30) if r["id"] == sid]
|
||||
assert rows and rows[0]["lease_token"]
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# DB — 시도 기록 · 확인된 쓰기 · 스냅샷
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_record_attempt_revision_is_idempotent_under_race():
|
||||
no, _ = _new_product()
|
||||
aid = ST.start_attempt(product_no=no, origin="MANUAL", actor="k", target_html="<p>X</p>",
|
||||
target_digest=store.content_digest("<p>X</p>"))
|
||||
ST.update_attempt(aid, status="REMOTE_OK", remote_ok=True)
|
||||
out, barrier = [], threading.Barrier(2)
|
||||
|
||||
def rec(s):
|
||||
barrier.wait()
|
||||
out.append(s.record_attempt_revision(aid, revision_type="MANUAL", memo="", created_by="k"))
|
||||
|
||||
threads = [threading.Thread(target=rec, args=(s,)) for s in (ST, ST2)]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
assert len(set(out)) == 1
|
||||
assert q("SELECT count(*) AS n FROM cafe24_product_revisions WHERE product_no = %s AND revision_type='MANUAL'",
|
||||
no)[0]["n"] == 1
|
||||
assert q("SELECT status, target_html FROM cafe24_write_attempts WHERE id = %s", aid)[0] == \
|
||||
{"status": "RECORDED", "target_html": ""}
|
||||
|
||||
|
||||
def test_write_lineage_only_confirmed():
|
||||
no, _ = _new_product()
|
||||
since = now_kst() - timedelta(hours=1)
|
||||
for status, html in (("REMOTE_FAILED", "F"), ("UNKNOWN", "U"), ("STARTED", "S"), ("RECORDED", "OK1"), ("REMOTE_OK", "OK2")):
|
||||
aid = ST.start_attempt(product_no=no, origin="MANUAL", target_html=html,
|
||||
target_digest=store.content_digest(html), observed_digest=store.content_digest("OBS-" + html))
|
||||
if status != "STARTED":
|
||||
ST.update_attempt(aid, status=status, remote_ok=status in ("RECORDED", "REMOTE_OK"))
|
||||
ST.add_revision(product_no=no, html_content="CONFLICT-BACKUP", revision_type="BACKUP")
|
||||
lineage = ST.write_lineage(no, since=since)
|
||||
assert [store.content_digest(x) for x in ("OK2", "OK1")] == [a["target_digest"] for a in lineage]
|
||||
assert lineage[0]["html_content"] == "OK2"
|
||||
digests = store.lineage_digests(lineage)
|
||||
assert store.content_digest("CONFLICT-BACKUP") not in digests
|
||||
assert store.content_digest("F") not in digests and store.content_digest("U") not in digests
|
||||
|
||||
|
||||
def test_snapshot_jsonb_field_merge_replace_and_deleted():
|
||||
no, _ = _new_product()
|
||||
ST.save_write_snapshot(no, "variants", {"V1": {"custom_variant_code": "C1"}, "V2": {"display": "F"}})
|
||||
ST.save_write_snapshot(no, "variants", {"V1": {"display": "F"}})
|
||||
data = ST.get_write_snapshot(no)["variants"]["data"]
|
||||
assert data["V1"]["custom_variant_code"] == "C1" and data["V1"]["display"] == "F" and "V2" in data
|
||||
ST.save_write_snapshot(no, "variants", {"V2": {"_deleted": True}})
|
||||
ST.save_write_snapshot(no, "variants", {"V2": {"display": "T"}})
|
||||
assert ST.get_write_snapshot(no)["variants"]["data"]["V2"].get("_deleted") is True
|
||||
ST.save_write_snapshot(no, "variants", {})
|
||||
assert "V1" in ST.get_write_snapshot(no)["variants"]["data"]
|
||||
ST.save_write_snapshot(no, "variants", {}, replace=True)
|
||||
assert ST.get_write_snapshot(no)["variants"]["data"] == {}
|
||||
|
||||
|
||||
def test_snapshot_concurrent_saves_both_persist():
|
||||
no, _ = _new_product()
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
def save(s, code):
|
||||
barrier.wait()
|
||||
s.save_write_snapshot(no, "variants", {code: {"display": "F"}})
|
||||
|
||||
threads = [threading.Thread(target=save, args=(ST, "VA")), threading.Thread(target=save, args=(ST2, "VB"))]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
assert set(ST.get_write_snapshot(no)["variants"]["data"]) == {"VA", "VB"}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 라우트 — [01] 충돌 백업이 외부 수정을 가리지 않는다 / 권한
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_route_permission_required():
|
||||
no, _ = _new_product()
|
||||
assert req("POST", f"/cafe24/products/{no}/apply", who="nope@test.local",
|
||||
data={"html": "x"}).status_code == 403
|
||||
assert req("GET", f"/cafe24/products/{no}/revisions/1", who="nope@test.local").status_code == 403
|
||||
|
||||
|
||||
def test_route_01_conflict_then_external_edit_not_overwritten():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
p0 = _pane(no)
|
||||
assert _location(_apply(no, "<p>W1</p>", p0["fingerprint"])).get("msg")
|
||||
stale_fp = _pane(no)["fingerprint"]
|
||||
cafe.external_edit("<p>X</p>")
|
||||
assert "변경" in _location(_apply(no, "<p>Y</p>", stale_fp)).get("err", "")
|
||||
pane = _pane(no)
|
||||
assert pane["sync_state"] == store.SYNC_EXTERNAL and "<p>X</p>" in pane["html_pc"]
|
||||
assert "변경" in _location(_apply(no, "<p>Y</p>", stale_fp)).get("err", "")
|
||||
assert cafe.state["description"] == "<p>X</p>"
|
||||
|
||||
|
||||
def test_route_02_concurrent_applies_one_wins():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
import time as _time
|
||||
|
||||
real_put = cafe.put
|
||||
|
||||
def slow_put(path, **kw):
|
||||
_time.sleep(0.4)
|
||||
return real_put(path, **kw)
|
||||
|
||||
cafe.put = slow_put
|
||||
results, barrier = [], threading.Barrier(2)
|
||||
|
||||
def go(text, who):
|
||||
barrier.wait()
|
||||
results.append(_location(_apply(no, text, fp, who=who)))
|
||||
|
||||
threads = [threading.Thread(target=go, args=("<p>AMY</p>", "amy@test.local")),
|
||||
threading.Thread(target=go, args=("<p>KING</p>", "king@test.local"))]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
ok = [r for r in results if r.get("msg")]
|
||||
err = [r for r in results if r.get("err")]
|
||||
assert len(ok) == 1 and len(err) == 1, results
|
||||
desc_puts = [c for c in cafe.calls if c[0] == "PUT" and "description" in (c[2] or {}).get("request", {})]
|
||||
assert len(desc_puts) == 1
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 라우트 — [13] 버전 원문 · 선택 복원 · [07] 결과 확정
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_route_13_revision_detail_scoped_and_restore():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
other, _ = _new_product("<p>O</p>")
|
||||
_apply(no, "<p>B<script>x</script></p>", _pane(no)["fingerprint"])
|
||||
backup = next(r for r in _pane(no)["revisions"] if r["revision_type"] == "BACKUP")
|
||||
detail = req("GET", f"/cafe24/products/{no}/revisions/{backup['id']}").json()["revision"]
|
||||
assert detail["html"] == "<p>A</p>" and detail["type_label"]
|
||||
assert req("GET", f"/cafe24/products/{other}/revisions/{backup['id']}").status_code == 404
|
||||
foreign = ST.add_revision(product_no=no, html_content="<p>F</p>", revision_type="MANUAL", mall_id="othermall")
|
||||
assert req("GET", f"/cafe24/products/{no}/revisions/{foreign}").status_code == 404
|
||||
shop2 = ST.add_revision(product_no=no, html_content="<p>S</p>", revision_type="MANUAL", shop_no=2)
|
||||
assert req("GET", f"/cafe24/products/{no}/revisions/{shop2}").status_code == 404
|
||||
# 복원 — 지문 없이는 거부, 옛 지문이면 충돌, 현재 지문이면 ROLLBACK
|
||||
assert _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore", data={})).get("err")
|
||||
assert "변경" in _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore",
|
||||
data={"base_fingerprint": store.fingerprint("<p>A</p>")})).get("err", "")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
loc = _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore",
|
||||
data={"base_fingerprint": fp, "memo": "되돌림"}))
|
||||
assert "복원" in loc.get("msg", ""), loc
|
||||
assert cafe.state["description"] == "<p>A</p>"
|
||||
rb = q("SELECT revision_type, source, source_revision_id, memo FROM cafe24_product_revisions "
|
||||
"WHERE product_no = %s ORDER BY id DESC LIMIT 1", no)[0]
|
||||
assert rb["revision_type"] == "ROLLBACK" and rb["source_revision_id"] == backup["id"] and "되돌림" in rb["memo"]
|
||||
# 다른 상품 버전을 이 상품 주소로 복원 시도 → 거부
|
||||
assert _location(req("POST", f"/cafe24/products/{other}/revisions/{backup['id']}/restore",
|
||||
data={"base_fingerprint": fp})).get("err")
|
||||
|
||||
|
||||
def test_route_07_unknown_attempt_blocks_until_resolved():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
cafe.put_error = fakes.network_error(maybe_applied=True)
|
||||
assert "알 수 없습니다" in _location(_apply(no, "<p>B</p>", fp)).get("err", "")
|
||||
cafe.put_error = None
|
||||
pane = _pane(no)
|
||||
assert len(pane["open_attempts"]) == 1
|
||||
assert "확인하지 못했습니다" in _location(_apply(no, "<p>C</p>", pane["fingerprint"])).get("err", "")
|
||||
aid = pane["open_attempts"][0]["id"]
|
||||
loc = _location(req("POST", f"/cafe24/products/{no}/attempts/{aid}/resolve", data={"result": "not_applied"}))
|
||||
assert loc.get("msg"), loc
|
||||
assert _pane(no)["open_attempts"] == []
|
||||
assert _location(_apply(no, "<p>C</p>", _pane(no)["fingerprint"])).get("msg")
|
||||
assert cafe.state["description"] == "<p>C</p>"
|
||||
|
||||
|
||||
def test_route_07_record_failure_reported_as_success():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
real = ST.record_attempt_revision
|
||||
|
||||
def boom(*a, **kw):
|
||||
raise RuntimeError("DB 장애")
|
||||
|
||||
ST.record_attempt_revision = boom
|
||||
try:
|
||||
loc = _location(_apply(no, "<p>B</p>", fp))
|
||||
finally:
|
||||
ST.record_attempt_revision = real
|
||||
assert "다시 적용하지 마세요" in loc.get("msg", ""), loc
|
||||
status = q("SELECT status FROM cafe24_write_attempts WHERE product_no = %s ORDER BY id DESC LIMIT 1", no)
|
||||
assert status[0]["status"] == "REMOTE_OK"
|
||||
# worker 의 기록 복구가 채운다(다시 PUT 하지 않음)
|
||||
worker.record_pending_attempts(ST)
|
||||
assert q("SELECT status FROM cafe24_write_attempts WHERE product_no = %s ORDER BY id DESC LIMIT 1",
|
||||
no)[0]["status"] == "RECORDED"
|
||||
assert len([c for c in cafe.calls if c[0] == "PUT"]) == 1
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 라우트 — [09] 행별 결과 · [10] 품목 표기 · [11] 삭제 품목
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _create_options(no, values):
|
||||
resp = req("POST", f"/cafe24/products/{no}/options", json={"option_name": "구성", "values": values})
|
||||
assert resp.status_code == 200, resp.text
|
||||
return resp.json()
|
||||
|
||||
|
||||
def test_route_09_variants_partial_success():
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, [f"v{i}" for i in range(150)])
|
||||
rows = [{"variant_code": v["variant_code"], "custom_variant_code": f"C{i}"}
|
||||
for i, v in enumerate(created["variants"])]
|
||||
cafe.fail_variant_chunk = 2
|
||||
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": rows})
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert body["partial"] and len(body["updated"]) == 100 and len(body["failed"]) == 50
|
||||
snap = ST.get_write_snapshot(no)["variants"]["data"]
|
||||
assert len([c for c in snap if c in body["updated"]]) == 100
|
||||
assert not any(c in snap for c in body["failed"])
|
||||
audit = q("SELECT result FROM cafe24_audit_logs WHERE product_no = %s AND action='update_variants' "
|
||||
"ORDER BY id DESC LIMIT 1", no)[0]
|
||||
assert audit["result"] == "PARTIAL"
|
||||
cafe.fail_variant_chunk = 0
|
||||
cafe._variant_puts = 0
|
||||
cafe.fail_variant_chunk = 1
|
||||
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": rows[:5]})
|
||||
assert resp.status_code == 502
|
||||
|
||||
|
||||
def test_route_10_rename_with_lagging_variants_keeps_rows():
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, ["Black", "Red"])
|
||||
before_variants = [dict(v, options=[dict(o) for o in v["options"]]) for v in cafe.variants]
|
||||
before_option = json.loads(json.dumps(cafe.option))
|
||||
resp = req("PUT", f"/cafe24/products/{no}/options", json={"options": [{
|
||||
"option_name": "구성", "option_value": [{"option_text": "Jet"}, {"option_text": "Crimson"}]}]})
|
||||
assert resp.status_code == 200, resp.text
|
||||
# 카페24 GET 이 아직 옛 옵션·옛 품목 표기를 돌려준다(읽기 지연)
|
||||
cafe.stale_option = before_option
|
||||
cafe.stale_variants = before_variants
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
texts = [v["option_text"] for v in got["option"]["options"][0]["option_value"]]
|
||||
labels = sorted(v["options"][0]["value"] for v in got["variants"])
|
||||
assert texts == ["Jet", "Crimson"] and labels == ["Crimson", "Jet"], (texts, labels)
|
||||
assert all(v["value_no"] for v in got["variants"]) # 옵션값 번호로 짝지을 수 있다
|
||||
# 관리자에서 다시 Onyx 로 고침 — 그 값은 믿는다
|
||||
cafe.stale_option = None
|
||||
cafe.stale_variants = None
|
||||
cafe.option["options"][0]["option_value"][0]["option_text"] = "Onyx"
|
||||
cafe.variants[0]["options"][0]["value"] = "Onyx"
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][0]["option_text"] == "Onyx"
|
||||
assert "Onyx" in [v["options"][0]["value"] for v in got["variants"]]
|
||||
assert created["variants"]
|
||||
|
||||
|
||||
def test_route_08_appended_value_pending_until_variant_appears():
|
||||
no, cafe = _new_product()
|
||||
_create_options(no, ["A"])
|
||||
cafe.hidden_variants = 99 # 새 품목이 한동안 안 보인다
|
||||
resp = req("PUT", f"/cafe24/products/{no}/options", json={"options": [{
|
||||
"option_name": "구성", "option_value": [{"option_text": "A"}, {"option_text": "B"}]}]}).json()
|
||||
values = resp["option"]["options"][0]["option_value"]
|
||||
assert values[1]["option_text"] == "B" and values[1]["pending"] is True
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][1]["pending"] is True
|
||||
cafe.hidden_variants = 0
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][1]["pending"] is False
|
||||
assert len(got["variants"]) == 2
|
||||
|
||||
|
||||
def test_route_11_deleted_variant_stays_hidden():
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, ["A", "B"])
|
||||
code = created["variants"][0]["variant_code"]
|
||||
stale = [dict(v) for v in cafe.variants]
|
||||
assert req("DELETE", f"/cafe24/products/{no}/variants/{code}").status_code == 200
|
||||
ST.save_write_snapshot(no, "variants", {code: {"display": "T"}}) # 늦게 도착한 수정
|
||||
cafe.stale_variants = stale
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert code not in [v["variant_code"] for v in got["variants"]]
|
||||
|
||||
|
||||
def test_route_lock_busy_returns_409():
|
||||
no, _ = _new_product()
|
||||
token = ST2.acquire_lock(f"product:{no}", owner="amy|h:1", purpose="상세설명 적용", ttl_seconds=60)
|
||||
os.environ["CAFE24_WRITE_LOCK_WAIT_SEC"] = "0"
|
||||
try:
|
||||
resp = req("POST", f"/cafe24/products/{no}/basic", json={"price": "1000"})
|
||||
assert resp.status_code == 409 and "amy" in resp.json()["detail"], resp.text
|
||||
finally:
|
||||
os.environ["CAFE24_WRITE_LOCK_WAIT_SEC"] = "3"
|
||||
ST2.release_lock(f"product:{no}", token)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# worker — 실제 DB
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _draft(no, html):
|
||||
return ST.add_revision(product_no=no, html_content=html, revision_type="DRAFT", mall_id="testmall")
|
||||
|
||||
|
||||
def test_worker_real_db_success_and_needs_review():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
sid = _schedule(no, revision_id=_draft(no, "<p>S</p>"), scheduled_at=now_kst() - timedelta(days=3000))
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
row = ST.get_schedule(sid)
|
||||
assert row["status"] == "SUCCESS" and cafe.state["description"] == "<p>S</p>", row
|
||||
assert q("SELECT count(*) AS n FROM cafe24_product_revisions WHERE product_no=%s AND revision_type='SCHEDULED'",
|
||||
no)[0]["n"] == 1
|
||||
|
||||
no2, cafe2 = _new_product("<p>A</p>")
|
||||
cafe2.put_error = fakes.network_error(maybe_applied=True)
|
||||
cafe2.put_error_after_apply = True
|
||||
sid2 = _schedule(no2, revision_id=_draft(no2, "<p>S2</p>"), scheduled_at=now_kst() - timedelta(days=3000))
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
assert ST.get_schedule(sid2)["status"] == "NEEDS_REVIEW"
|
||||
# 사람이 쇼핑몰을 보고 "반영됨" 확정
|
||||
resp = req("POST", f"/cafe24/schedules/{sid2}/review", data={"action": "applied"})
|
||||
assert _location(resp).get("msg"), resp.headers
|
||||
assert ST.get_schedule(sid2)["status"] == "SUCCESS"
|
||||
assert q("SELECT status FROM cafe24_write_attempts WHERE schedule_id=%s", sid2)[0]["status"] == "RECORDED"
|
||||
|
||||
|
||||
def test_worker_real_db_recovers_crash_after_remote_ok():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
rid = _draft(no, "<p>R</p>")
|
||||
sid = _schedule(no, revision_id=rid, scheduled_at=now_kst() - timedelta(days=3000))
|
||||
row = ST.claim_due_schedule(now=now_kst(), owner="dead", ttl_seconds=60)
|
||||
assert row["id"] == sid
|
||||
aid = ST.start_attempt(product_no=no, schedule_id=sid, origin="SCHEDULED", target_revision_id=rid,
|
||||
target_digest=store.content_digest("<p>R</p>"))
|
||||
ST.update_attempt(aid, status="REMOTE_OK", remote_ok=True) # 반영 직후 죽음
|
||||
q("UPDATE cafe24_product_schedules SET lease_expires_at = now() - interval '1 second' WHERE id=%s RETURNING id", sid)
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
assert ST.get_schedule(sid)["status"] == "SUCCESS"
|
||||
assert q("SELECT status FROM cafe24_write_attempts WHERE id=%s", aid)[0]["status"] == "RECORDED"
|
||||
assert [c for c in cafe.calls if c[0] == "PUT"] == [] # 재적용 없음
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 디자인 파일 — [04] 잠금 + 임시 파일 교체
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_design_apply_route_temp_replace_and_conflict():
|
||||
os.environ.update({"CAFE24_FTP_USER": "u", "CAFE24_FTP_PASSWORD": "p", "CAFE24_FTP_HOST": "h"})
|
||||
path = routes_design_files.design_file_path("swiper")
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({path: b"OLD"})
|
||||
fp = store.fingerprint("OLD")
|
||||
loc = _location(req("POST", "/cafe24/design/swiper/apply", data={"content": "NEW", "base_fingerprint": fp}))
|
||||
assert loc.get("msg"), loc
|
||||
assert ftp.files == {path: b"NEW"}
|
||||
# 교체 직전 남이 바꿈 → 충돌, 원본(남의 값) 그대로
|
||||
ftp.on_before_rename = None
|
||||
fp = store.fingerprint("NEW")
|
||||
|
||||
real_retr = fakes.FakeFTP.retrbinary
|
||||
calls = {"n": 0}
|
||||
|
||||
def sneaky(self, cmd, cb):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 3: # 1: 현재값 조회, 2: 임시 파일 검증, 3: 교체 직전 재확인
|
||||
self.files[path] = b"THEIRS"
|
||||
return real_retr(self, cmd, cb)
|
||||
|
||||
fakes.FakeFTP.retrbinary = sneaky
|
||||
try:
|
||||
loc = _location(req("POST", "/cafe24/design/swiper/apply", data={"content": "MINE", "base_fingerprint": fp}))
|
||||
finally:
|
||||
fakes.FakeFTP.retrbinary = real_retr
|
||||
assert "바뀌었습니다" in loc.get("err", ""), loc
|
||||
assert ftp.files == {path: b"THEIRS"}
|
||||
|
||||
|
||||
def _run_all() -> None:
|
||||
if not ENABLED:
|
||||
print("SKIP — CAFE24_TEST_DB_URL(localhost) 이 없어 건너뜁니다.")
|
||||
return
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
try:
|
||||
fn()
|
||||
print("PASS", fn.__name__)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failed += 1
|
||||
import traceback
|
||||
|
||||
print("FAIL", fn.__name__, "→", repr(exc))
|
||||
traceback.print_exc()
|
||||
print(f"\n{len(fns) - failed}/{len(fns)} passed.")
|
||||
ST.close()
|
||||
ST2.close()
|
||||
if failed:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_run_all()
|
||||
@@ -0,0 +1,471 @@
|
||||
"""프로젝트 관리 모듈 — 권한·저장·댓글 첨부·알림 회귀 테스트 (실제 PostgreSQL + FastAPI TestClient).
|
||||
|
||||
운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 가상의 사용자·프로젝트만 만든다.
|
||||
|
||||
# 1) 로컬 테스트 DB 에 스키마 적용(최초 1회): project_db_init.sql + project_db_0*.sql
|
||||
# 2) 실행
|
||||
PROJECT_TEST_DB_URL=postgresql://postgres@localhost:55432/project_db \
|
||||
python tests/test_project_module.py
|
||||
|
||||
PROJECT_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호).
|
||||
메일은 app.mail.send_email 을 가짜로 바꿔 기록만 한다(실제 발송 없음).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import types
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from urllib.parse import urlparse
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
|
||||
_host = urlparse(DSN).hostname if DSN else None
|
||||
ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1")
|
||||
|
||||
# ── app.main 대역(전체 앱을 띄우지 않고 프로젝트 라우터만 시험) ──────────────
|
||||
class _Users:
|
||||
def __init__(self) -> None:
|
||||
self.d: dict[str, dict] = {}
|
||||
|
||||
def add(self, email: str, *, role: str = "user", project: bool = True, super_: bool = False) -> str:
|
||||
email = email.lower()
|
||||
self.d[email] = {"email": email, "name": email.split("@")[0], "role": role,
|
||||
"modules": {"project": project}, "is_super_admin": super_}
|
||||
return email
|
||||
|
||||
def get(self, email: str):
|
||||
return self.d.get((email or "").lower())
|
||||
|
||||
def list_all(self):
|
||||
return list(self.d.values())
|
||||
|
||||
|
||||
USERS = _Users()
|
||||
SENT_MAIL: list[dict] = []
|
||||
|
||||
if ENABLED:
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
fake_main = types.ModuleType("app.main")
|
||||
fake_main.user_store = USERS
|
||||
|
||||
def _current(request):
|
||||
return USERS.get(request.headers.get("x-test-user", ""))
|
||||
|
||||
fake_main.get_current_user_record = _current
|
||||
fake_main.build_erp_nav = lambda user, active="": []
|
||||
fake_main.render_template = lambda request, name, ctx, status_code=200: HTMLResponse(
|
||||
f"{name}|{ctx.get('reason', '')}", status_code=status_code)
|
||||
sys.modules["app.main"] = fake_main
|
||||
for k in list(os.environ):
|
||||
if k.startswith("SMTP_") or k == "PROJECT_NOTIFY_EMAIL":
|
||||
os.environ.pop(k)
|
||||
import app.mail as _mail # noqa: E402
|
||||
|
||||
_mail.send_email = lambda **kw: SENT_MAIL.append(kw)
|
||||
|
||||
from fastapi import FastAPI # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from app.modules.project import reminders # noqa: E402
|
||||
from app.modules.project import router as project_api_router # noqa: E402 - 패키지가 APIRouter 를 내보낸다
|
||||
from app.modules.project.db import ProjectStore # noqa: E402
|
||||
from app.timezone import today_kst # noqa: E402
|
||||
|
||||
ST = ProjectStore(DSN)
|
||||
DATA_DIR = tempfile.mkdtemp(prefix="pj-test-")
|
||||
APP = FastAPI()
|
||||
APP.include_router(project_api_router)
|
||||
APP.state.project_store = ST
|
||||
APP.state.data_dir = DATA_DIR
|
||||
CLIENT = TestClient(APP)
|
||||
|
||||
RUN = uuid.uuid4().hex[:6]
|
||||
ADMIN = USERS.add(f"admin-{RUN}@test.local", role="admin")
|
||||
SUPER = USERS.add("king@dbxcorp.co.kr", role="admin", super_=True)
|
||||
ALICE = USERS.add(f"alice-{RUN}@test.local")
|
||||
BOB = USERS.add(f"bob-{RUN}@test.local")
|
||||
CAROL = USERS.add(f"carol-{RUN}@test.local")
|
||||
DAVE = USERS.add(f"dave-{RUN}@test.local") # 프로젝트 권한은 있으나 어디에도 멤버 아님
|
||||
EVE = USERS.add(f"eve-{RUN}@test.local", project=False) # 프로젝트 모듈 권한 없음
|
||||
|
||||
|
||||
def req(method: str, url: str, who: str, **kw):
|
||||
return CLIENT.request(method, url, headers={"x-test-user": who}, **kw)
|
||||
|
||||
|
||||
def _project(name: str, owner: str, members: tuple[str, ...] = ()) -> dict:
|
||||
p = ST.create_project(name=f"{name}-{uuid.uuid4().hex[:4]}", owner_email=owner, created_by=owner)
|
||||
for m in members:
|
||||
ST.add_member(project_id=p["id"], user_email=m)
|
||||
return p
|
||||
|
||||
|
||||
def _stage(pid: int, name: str = "할 일", done: bool = False, by: str = "") -> dict:
|
||||
return ST.add_stage(project_id=pid, name=name, is_done_stage=done, created_by=by)
|
||||
|
||||
|
||||
def _count(sql: str, *args) -> int:
|
||||
with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 전용 확인 쿼리
|
||||
return int(conn.execute(sql, args).fetchone()["n"])
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [07] 소유자 변경은 관리자만
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_owner_change_admin_only():
|
||||
p = _project("P-owner", ADMIN, (BOB,))
|
||||
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": BOB})
|
||||
assert r.status_code == 403, r.text
|
||||
assert ST.get_project(project_id=p["id"])["owner_email"] == ADMIN
|
||||
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": CAROL, "name": "x"})
|
||||
assert r.status_code == 403 and ST.get_project(project_id=p["id"])["name"] != "x"
|
||||
# 같은 값을 같이 보내는 건(화면 저장) 통과
|
||||
assert req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": ADMIN, "name": "ok"}).status_code == 200
|
||||
# 관리자: 모듈 권한 없는 사람은 소유자 불가, 정상 사용자는 가능
|
||||
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": EVE}).status_code == 400
|
||||
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": CAROL}).status_code == 200
|
||||
assert ST.get_project(project_id=p["id"])["owner_email"] == CAROL
|
||||
# 소유자에서 빠지면(관리자가 다시 바꿈) 멤버가 아닌 CAROL 은 관리 권한을 잃는다
|
||||
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": ADMIN}).status_code == 200
|
||||
assert req("GET", f"/project/api/projects/{p['id']}/snapshot", CAROL).status_code == 403
|
||||
# 생성: 비관리자가 남을 소유자로 지정 → 거절, 본인·미지정 → 본인이 소유자
|
||||
assert req("POST", "/project/api/projects", BOB, json={"name": "n1", "owner_email": CAROL}).status_code == 403
|
||||
r = req("POST", "/project/api/projects", BOB, json={"name": "n2"})
|
||||
assert r.status_code == 201 and r.json()["project"]["owner_email"] == BOB
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [06] 삭제 — 생성자 규칙 + 지금 권한
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_delete_requires_current_access():
|
||||
p = _project("P-del", ADMIN, (ALICE, BOB))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
t = req("POST", f"/project/api/projects/{p['id']}/tasks", ALICE, json={"title": "alice task", "stage_id": s["id"]}).json()["task"]
|
||||
ST.add_comment(task_id=t["id"], author_email=ALICE, author_name="a", body="hi")
|
||||
trash_before = _count("SELECT COUNT(*) AS n FROM project_trash")
|
||||
# 현재 멤버인 타인 → 생성자 규칙으로 거절
|
||||
assert req("DELETE", f"/project/api/tasks/{t['id']}", BOB).status_code == 403
|
||||
# 멤버에서 빠진 생성자 → 거절, 행·댓글·휴지통 변화 없음
|
||||
ST.remove_member(project_id=p["id"], user_email=ALICE)
|
||||
assert req("DELETE", f"/project/api/tasks/{t['id']}", ALICE).status_code == 403
|
||||
assert ST.get_task(task_id=t["id"]) is not None
|
||||
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id = %s", t["id"]) == 1
|
||||
assert _count("SELECT COUNT(*) AS n FROM project_trash") == trash_before
|
||||
# 다시 멤버가 된 생성자 → 삭제(휴지통)
|
||||
ST.add_member(project_id=p["id"], user_email=ALICE)
|
||||
r = req("DELETE", f"/project/api/tasks/{t['id']}", ALICE)
|
||||
assert r.status_code == 200 and ST.get_task(task_id=t["id"]) is None
|
||||
# 프로젝트 삭제: 만든 사람이어도 지금 권한이 없으면 거절, 슈퍼관리자는 예외
|
||||
p2 = _project("P-del2", ALICE)
|
||||
ST.update_project(project_id=p2["id"], fields={"owner_email": ADMIN}) # 관리자가 소유자를 바꿈
|
||||
assert req("DELETE", f"/project/api/projects/{p2['id']}", ALICE).status_code == 403
|
||||
assert ST.get_project(project_id=p2["id"]) is not None
|
||||
assert req("DELETE", f"/project/api/projects/{p2['id']}", SUPER).status_code == 200
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [02] 권한 회수 후 조회·변경·알림
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_revoked_member_loses_everything():
|
||||
p = _project("P-rev", ADMIN, (ALICE, BOB))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
t = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB,
|
||||
json={"title": "shared", "stage_id": s["id"], "assignee_email": ALICE,
|
||||
"description": f'<span class="pj-mention" data-email="{ALICE}">@a</span>'}).json()["task"]
|
||||
c = req("POST", f"/project/api/tasks/{t['id']}/comments", ALICE, json={"body": "mine"}).json()["comment"]
|
||||
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"])
|
||||
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"])
|
||||
assert any(n["task_id"] == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"])
|
||||
|
||||
ST.remove_member(project_id=p["id"], user_email=ALICE)
|
||||
assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"])
|
||||
assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"])
|
||||
assert not any(n.get("task_id") == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"])
|
||||
for m, u, body in (("GET", f"/project/api/tasks/{t['id']}", None),
|
||||
("GET", f"/project/api/tasks/{t['id']}/comments", None),
|
||||
("GET", f"/project/api/tasks/{t['id']}/attachments", None),
|
||||
("PUT", f"/project/api/tasks/{t['id']}", {"title": "x"}),
|
||||
("PUT", f"/project/api/comments/{c['id']}", {"body": "edited"}),
|
||||
("DELETE", f"/project/api/comments/{c['id']}", None),
|
||||
("POST", f"/project/api/tasks/{t['id']}/followers", {})):
|
||||
r = req(m, u, ALICE, json=body) if body is not None else req(m, u, ALICE)
|
||||
assert r.status_code == 403, (m, u, r.status_code)
|
||||
assert ST.get_comment(comment_id=c["id"])["body"] == "mine"
|
||||
assert req("GET", f"/project/t/{t['id']}", ALICE, follow_redirects=False).status_code == 403 # 옛 공유 링크
|
||||
# 완료 알림은 권한 잃은 담당자에게 가지 않는다(담당자 기록은 남음)
|
||||
before = _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"])
|
||||
assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"completed": True}).status_code == 200
|
||||
assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"]) == before
|
||||
assert ST.get_task(task_id=t["id"])["assignee_email"] == ALICE
|
||||
# 권한 없는 사람을 새 담당자로 지정할 수 없다
|
||||
assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"assignee_email": DAVE}).status_code == 400
|
||||
# 관리자·owner·멤버는 그대로
|
||||
assert req("GET", f"/project/api/tasks/{t['id']}", ADMIN).status_code == 200
|
||||
assert req("GET", f"/project/api/tasks/{t['id']}", BOB).status_code == 200
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [08] 비멤버 @태그
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_mentions_only_for_people_who_can_see():
|
||||
p = _project("P-men", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
desc = "".join(f'<span class="pj-mention" data-email="{e}">@x</span>' for e in (DAVE, EVE, "ghost@nowhere.test"))
|
||||
r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "m", "stage_id": s["id"], "description": desc})
|
||||
t = r.json()["task"]
|
||||
assert set(r.json()["mention_skipped"]) == {DAVE, EVE, "ghost@nowhere.test"}
|
||||
assert _count("SELECT COUNT(*) AS n FROM task_mentions WHERE task_id=%s", t["id"]) == 0
|
||||
r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@dave hi", "mentions": [DAVE]})
|
||||
assert r.status_code == 201 and r.json()["mention_skipped"] == [DAVE]
|
||||
assert not req("GET", "/project/api/mentions", DAVE).json()["tasks"] or \
|
||||
all(x["id"] != t["id"] for x in req("GET", "/project/api/mentions", DAVE).json()["tasks"])
|
||||
# 멘션이 접근 권한을 만들지 않는다
|
||||
assert req("GET", f"/project/api/tasks/{t['id']}", DAVE).status_code == 403
|
||||
# 연결된 프로젝트 멤버는 태그 가능(읽기 권한)
|
||||
p2 = _project("P-men2", ADMIN, (BOB, CAROL))
|
||||
s2 = _stage(p2["id"], by=ADMIN)
|
||||
assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": p2["id"], "stage_id": s2["id"]}).status_code == 201
|
||||
r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@carol", "mentions": [CAROL]})
|
||||
assert r.json()["mention_skipped"] == []
|
||||
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", CAROL).json()["tasks"])
|
||||
# 태그 후보 API 도 같은 기준
|
||||
cands = {u["email"] for u in req("GET", f"/project/api/all-users?task_id={t['id']}", BOB).json()["users"]}
|
||||
assert CAROL in cands and BOB in cands and DAVE not in cands and EVE not in cands
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [12] 연결된 프로젝트 — 읽기 전용
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_linked_task_is_read_only():
|
||||
home = _project("P-home", ADMIN, (BOB,))
|
||||
other = _project("P-link", ADMIN, (BOB, CAROL))
|
||||
secret = _project("P-secret", ADMIN, (BOB,))
|
||||
hs, os_ = _stage(home["id"], by=ADMIN), _stage(other["id"], by=ADMIN)
|
||||
os2 = _stage(other["id"], name="진행", by=ADMIN)
|
||||
ss = _stage(secret["id"], by=ADMIN)
|
||||
t = ST.create_task(project_id=home["id"], title="linked", stage_id=hs["id"], created_by=BOB)
|
||||
sib = ST.create_task(project_id=home["id"], title="sibling", stage_id=hs["id"], created_by=BOB)
|
||||
sub = ST.create_task(project_id=home["id"], title="child", parent_task_id=t["id"], created_by=BOB)
|
||||
for pid, sid in ((other["id"], os_["id"]), (secret["id"], ss["id"])):
|
||||
assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": pid, "stage_id": sid}).status_code == 201
|
||||
r = req("GET", f"/project/api/tasks/{t['id']}", CAROL)
|
||||
assert r.status_code == 200 and r.json()["task"]["access"] == "read"
|
||||
assert [ln["project_id"] for ln in r.json()["task"]["links"]] == [other["id"]] # 비밀 프로젝트는 숨김
|
||||
assert r.json()["task"]["followers"] is None
|
||||
assert req("GET", f"/project/api/tasks/{sub['id']}", CAROL).json()["task"]["access"] == "read" # 하위 작업도 읽기
|
||||
assert req("GET", f"/project/api/tasks/{sib['id']}", CAROL).status_code == 403 # 원 소속의 다른 작업은 안 보임
|
||||
assert req("GET", f"/project/api/projects/{home['id']}/members", CAROL).status_code == 403
|
||||
assert req("GET", f"/project/api/tasks/{t['id']}/comments", CAROL).status_code == 200
|
||||
for m, u, body in (("PUT", f"/project/api/tasks/{t['id']}", {"title": "hack"}),
|
||||
("POST", f"/project/api/tasks/{t['id']}/comments", {"body": "hi"}),
|
||||
("DELETE", f"/project/api/tasks/{t['id']}", None)):
|
||||
r = req(m, u, CAROL, json=body) if body is not None else req(m, u, CAROL)
|
||||
assert r.status_code == 403, (m, u, r.status_code)
|
||||
assert ST.get_task(task_id=t["id"])["title"] == "linked"
|
||||
# 연결된 프로젝트 안의 섹션 이동은 예전처럼 허용
|
||||
assert req("POST", f"/project/api/tasks/{t['id']}/links", CAROL, json={"project_id": other["id"], "stage_id": os2["id"]}).status_code == 201
|
||||
# 공유 링크 — 연결된 프로젝트 화면으로
|
||||
r = req("GET", f"/project/t/{t['id']}", CAROL, follow_redirects=False)
|
||||
assert r.status_code == 303 and r.headers["location"] == f"/project/p/{other['id']}?task={t['id']}"
|
||||
# 전체 스냅샷에서 연결 행은 연결된 프로젝트 맥락으로 한 번씩(원 소속 행은 CAROL 에게 없음)
|
||||
snap = req("GET", f"/project/api/projects/{other['id']}/snapshot?scope=all", CAROL).json()
|
||||
rows = [x for x in snap["tasks"] if x["id"] == t["id"]]
|
||||
assert [(x["context_project_id"], x["is_linked"]) for x in rows] == [(other["id"], True)]
|
||||
# 연결 해제 후엔 볼 수 없다
|
||||
assert req("DELETE", f"/project/api/tasks/{t['id']}/links/{other['id']}", BOB).status_code == 200
|
||||
assert req("GET", f"/project/api/tasks/{t['id']}", CAROL).status_code == 403
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [03] 파일 댓글 — 원자적 등록·재전송 중복 방지
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_file_comment_atomic_and_idempotent():
|
||||
p = _project("P-file", ADMIN, (BOB, CAROL))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
t = ST.create_task(project_id=p["id"], title="files", stage_id=s["id"], created_by=BOB)
|
||||
url = f"/project/api/tasks/{t['id']}/comments/files"
|
||||
n0 = _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"])
|
||||
# JSON 경로: 예전 has_attachment 플래그로 빈 댓글을 만들 수 없다
|
||||
assert req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "", "has_attachment": True}).status_code == 400
|
||||
# 한 파일이라도 문제면(빈 파일) 아무것도 만들지 않고 어느 파일인지 알려 준다
|
||||
r = req("POST", url, BOB, files=[("files", ("ok.txt", b"hello", "text/plain")), ("files", ("empty.txt", b"", "text/plain"))])
|
||||
assert r.status_code == 400 and [f["name"] for f in r.json()["detail"]["failed"]] == ["empty.txt"]
|
||||
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0
|
||||
assert not os.path.isdir(os.path.join(DATA_DIR, "project", str(t["id"]))) or \
|
||||
not os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))
|
||||
# 정상: 본문 없이 파일 두 개, 같은 토큰으로 두 번 보내도 한 번만
|
||||
files = [("files", ("a.png", b"\x89PNG....", "image/png")), ("files", ("b.pdf", b"%PDF-1", "application/pdf"))]
|
||||
r1 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files)
|
||||
r2 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files)
|
||||
assert r1.status_code == 201 and r2.status_code == 201
|
||||
assert r1.json()["comment"]["id"] == r2.json()["comment"]["id"] and r2.json().get("duplicate")
|
||||
cid = r1.json()["comment"]["id"]
|
||||
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1
|
||||
assert _count("SELECT COUNT(*) AS n FROM task_attachments WHERE comment_id=%s", cid) == 2
|
||||
# DB 저장 실패 → 방금 쓴 파일도 지우고 댓글 없음
|
||||
orig = ST.add_comment_with_attachments
|
||||
ST.add_comment_with_attachments = lambda **kw: (_ for _ in ()).throw(RuntimeError("db down"))
|
||||
try:
|
||||
before_files = set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"]))))
|
||||
try:
|
||||
req("POST", url, BOB, files=[("files", ("c.txt", b"data", "text/plain"))])
|
||||
except RuntimeError:
|
||||
pass # TestClient 가 서버 예외를 그대로 올린다(운영에선 500)
|
||||
assert set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))) == before_files
|
||||
finally:
|
||||
ST.add_comment_with_attachments = orig
|
||||
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1
|
||||
# 남의 댓글에 파일을 붙일 수 없다
|
||||
r = req("POST", f"/project/api/tasks/{t['id']}/attachments", CAROL,
|
||||
data={"comment_id": str(cid)}, files={"file": ("x.txt", b"x", "text/plain")})
|
||||
assert r.status_code == 403
|
||||
# 동시에 같은 토큰 두 개 → 댓글 하나
|
||||
out = []
|
||||
ths = [threading.Thread(target=lambda: out.append(req("POST", url, BOB, data={"client_token": "tok-par"},
|
||||
files=[("files", ("p.txt", b"p", "text/plain"))]).json()))
|
||||
for _ in range(2)]
|
||||
[th.start() for th in ths]
|
||||
[th.join() for th in ths]
|
||||
assert len({o["comment"]["id"] for o in out}) == 1
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [04] 날짜 범위
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_date_range_validation():
|
||||
p = _project("P-date", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
base = f"/project/api/projects/{p['id']}/tasks"
|
||||
assert req("POST", base, BOB, json={"title": "bad", "stage_id": s["id"], "start_date": "2026-10-05", "due_date": "2026-10-01"}).status_code == 400
|
||||
t = req("POST", base, BOB, json={"title": "ok", "stage_id": s["id"], "start_date": "2026-10-01", "due_date": "2026-10-05"}).json()["task"]
|
||||
u = f"/project/api/tasks/{t['id']}"
|
||||
assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 400 # 한쪽만 바꿔도 최종 상태 검사
|
||||
assert ST.get_task(task_id=t["id"])["due_date"] == "2026-10-05"
|
||||
assert req("PUT", u, BOB, json={"start_date": None}).status_code == 200 # null 로 지우기
|
||||
assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 200 # 시작일 없으면 허용
|
||||
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "18:00", "due_time": "09:00"}).status_code == 400
|
||||
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "00:00", "due_time": "23:59"}).status_code == 200
|
||||
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "09:00", "due_time": "09:00"}).status_code == 200
|
||||
# 프로젝트도 같은 규칙(부분 수정 포함)
|
||||
pu = f"/project/api/projects/{p['id']}"
|
||||
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
|
||||
assert req("PUT", pu, BOB, json={"due_date": "2026-10-01"}).status_code == 200
|
||||
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01"}).status_code == 400
|
||||
assert req("POST", "/project/api/projects", BOB, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [11] 완료 섹션에 바로 만든 작업
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_create_in_done_stage_completes():
|
||||
p = _project("P-done", ADMIN, (ALICE, BOB))
|
||||
todo, done = _stage(p["id"], by=ADMIN), _stage(p["id"], name="완료", done=True, by=ADMIN)
|
||||
SENT_MAIL.clear()
|
||||
r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "done now", "stage_id": done["id"], "assignee_email": ALICE})
|
||||
t = r.json()["task"]
|
||||
assert t["completed_at"] and "_newly_completed" not in t
|
||||
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id=%s AND action='completed'", t["id"]) == 1
|
||||
assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='completed' AND recipient_email=%s", t["id"], ALICE) == 1
|
||||
# 일반 섹션 생성 → 미완료, 완료 섹션으로 이동 → 완료(이력 1건 더), 이탈 → 미완료
|
||||
t2 = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "later", "stage_id": todo["id"]}).json()["task"]
|
||||
assert not t2["completed_at"]
|
||||
assert req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": done["id"]}).json()["task"]["completed_at"]
|
||||
assert not req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": todo["id"]}).json()["task"]["completed_at"]
|
||||
# 섹션 없는 하위 작업: 수동 완료/취소
|
||||
sub = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "sub", "parent_task_id": t2["id"]}).json()["task"]
|
||||
assert sub["stage_id"] is None and not sub["completed_at"]
|
||||
assert req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": True}).json()["task"]["completed_at"]
|
||||
assert not req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": False}).json()["task"]["completed_at"]
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [15] 마감 알림 — 원자적·재시도·중복 방지·권한
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_due_reminders_atomic_and_access():
|
||||
p = _project("P-rem", ADMIN, (ALICE, BOB))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
today = today_kst()
|
||||
t_ok = ST.create_task(project_id=p["id"], title=f"rem-ok-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
|
||||
t_gone = ST.create_task(project_id=p["id"], title=f"rem-gone-{RUN}", stage_id=s["id"], assignee_email=ALICE, due_date=today.isoformat(), created_by=BOB)
|
||||
t_fail = ST.create_task(project_id=p["id"], title=f"FAILME-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
|
||||
ST.remove_member(project_id=p["id"], user_email=ALICE)
|
||||
q = "SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='due_today'"
|
||||
qr = "SELECT COUNT(*) AS n FROM task_reminders WHERE task_id=%s"
|
||||
with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 DB 에서만: 알림 생성 실패 흉내
|
||||
conn.execute(f"ALTER TABLE project_notifications ADD CONSTRAINT test_fail_{RUN} CHECK (title NOT LIKE '%%FAILME-{RUN}%%')")
|
||||
try:
|
||||
reminders.run_due_reminders(ST, today=today, lookup=USERS.get)
|
||||
assert _count(q, t_ok["id"]) == 1 and _count(q, t_gone["id"]) == 0
|
||||
assert _count(q, t_fail["id"]) == 0 and _count(qr, t_fail["id"]) == 0 # 실패 → 기록도 되돌려짐
|
||||
finally:
|
||||
with ST._pool.connection() as conn: # noqa: SLF001
|
||||
conn.execute(f"ALTER TABLE project_notifications DROP CONSTRAINT test_fail_{RUN}")
|
||||
reminders.run_due_reminders(ST, today=today, lookup=USERS.get) # 재실행: 실패분만 생성
|
||||
assert _count(q, t_fail["id"]) == 1 and _count(q, t_ok["id"]) == 1
|
||||
# 동시 실행에도 중복 없음
|
||||
t_par = ST.create_task(project_id=p["id"], title=f"rem-par-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
|
||||
ths = [threading.Thread(target=reminders.run_due_reminders, args=(ST,), kwargs={"today": today, "lookup": USERS.get}) for _ in range(4)]
|
||||
[th.start() for th in ths]
|
||||
[th.join() for th in ths]
|
||||
assert _count(q, t_par["id"]) == 1
|
||||
assert _count(q, t_gone["id"]) == 0 and _count(qr, t_gone["id"]) == 0
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [01] 전체 범위 스냅샷 — 다른 프로젝트의 생성·삭제·섹션 변경·권한 회수
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_snapshot_all_scope():
|
||||
a = _project("P-sa", ADMIN, (BOB,))
|
||||
b = _project("P-sb", ADMIN, (BOB,))
|
||||
sa, sb = _stage(a["id"], by=ADMIN), _stage(b["id"], by=ADMIN)
|
||||
tb = ST.create_task(project_id=b["id"], title="in b", stage_id=sb["id"], created_by=BOB)
|
||||
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
|
||||
assert {a["id"], b["id"]} <= {x["id"] for x in snap["projects"]}
|
||||
assert any(x["id"] == tb["id"] for x in snap["tasks"]) and str(b["id"]) in snap["stages_by_project"]
|
||||
sb2 = _stage(b["id"], name="new", by=ADMIN)
|
||||
ST.delete_task(task_id=tb["id"], deleted_by=BOB)
|
||||
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
|
||||
assert not any(x["id"] == tb["id"] for x in snap["tasks"])
|
||||
assert sb2["id"] in [s["id"] for s in snap["stages_by_project"][str(b["id"])]]
|
||||
ST.remove_member(project_id=b["id"], user_email=BOB)
|
||||
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
|
||||
assert b["id"] not in {x["id"] for x in snap["projects"]} and str(b["id"]) not in snap["stages_by_project"]
|
||||
ST.remove_member(project_id=a["id"], user_email=BOB)
|
||||
assert req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).status_code == 403
|
||||
_ = sa
|
||||
|
||||
|
||||
def test_store_date_range_unit():
|
||||
from app.modules.project import store
|
||||
store.validate_date_range(None, "2026-01-01")
|
||||
store.validate_date_range("2026-01-01", None, "10:00", None)
|
||||
store.validate_date_range("2026-01-01", "2026-01-01", "23:59", None)
|
||||
for args in (("2026-01-02", "2026-01-01"), ("2026-01-01", "2026-01-01", "10:01", "10:00")):
|
||||
try:
|
||||
store.validate_date_range(*args)
|
||||
except ValueError:
|
||||
continue
|
||||
raise AssertionError(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
sys.exit(0)
|
||||
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")
|
||||
ST.close()
|
||||
_ = io, timedelta
|
||||
Reference in New Issue
Block a user