Compare commits
229 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ea7817752d | |||
| 67001f0a6e | |||
| c30ef72c6e | |||
| 581e0cf325 | |||
| e6b2812624 | |||
| 30fd2c5470 | |||
| 2df86983da | |||
| 90332bcb59 | |||
| 1c42ed5dd3 | |||
| 779cc79a87 | |||
| 1ba494dab8 | |||
| ef38140673 | |||
| 099271fdb2 | |||
| e6d38f342f | |||
| f8245b4499 | |||
| 9a8aea6435 | |||
| eab6b836d2 | |||
| deb5bfb9a1 | |||
| 4d3b747ab7 | |||
| 5471cbc32b | |||
| 4c94bf1293 | |||
| f36f7d3ad4 | |||
| 5bd0a5c406 | |||
| c317d7bb5d | |||
| 941b35a7a6 | |||
| ecc6405299 | |||
| 028831694a | |||
| 542e7fb7d1 | |||
| ac0f48bfce | |||
| 68bf43ea2f | |||
| cf7c44ce49 | |||
| db3b7d500d | |||
| d5fd617425 | |||
| bed3d4fc89 | |||
| 822c955bb6 | |||
| 20a79f5719 | |||
| b4edc16785 | |||
| 66db501170 | |||
| ac01a33c47 | |||
| 513aece27e | |||
| 1d3573a44a | |||
| 410d4fe05c | |||
| c15a746ae4 | |||
| da46abd678 | |||
| d38d00b4d2 | |||
| 8201fde606 | |||
| 70bf263a80 | |||
| 5a2c6ba2ad | |||
| 6ebf705e27 | |||
| 22490664d6 | |||
| 0c6dacb824 | |||
| 6345b69816 | |||
| 3882836fd5 | |||
| 59add598fa | |||
| ca2821464f | |||
| 24950c94ce | |||
| 454b3cc700 | |||
| dd1bc310dc | |||
| 53bead6691 | |||
| 36283ae265 | |||
| 89d204b2fe | |||
| 724b590868 | |||
| e130bbe577 | |||
| bc62e53270 | |||
| 6fd01314d5 | |||
| 1bdcd59287 | |||
| b7c0f28ad2 | |||
| 4320766abd | |||
| e934dd6abf | |||
| 18ac8f0761 | |||
| b5be26089d | |||
| 3a9a94f97b | |||
| c69bc0e9f3 | |||
| 833dbb5fdf | |||
| 2aa6b6efae | |||
| 1759e00213 | |||
| fa6e7066ae | |||
| 7cdca852bd | |||
| ee09e8bfd1 | |||
| ae6b6ec603 | |||
| 89ad338024 | |||
| c07a3466a0 | |||
| 5d054e59b6 | |||
| 061f18d081 | |||
| ee9c04147a | |||
| 6a1c437635 | |||
| 8045d06362 | |||
| 85e91ca882 | |||
| 11e9803965 | |||
| 90fb06c48c | |||
| ac3b90f2be | |||
| a664c4a9fc | |||
| 64aabdfbda | |||
| 98fda9923e | |||
| 53c7c85caf | |||
| c380b5e411 | |||
| 84113d1fd7 | |||
| 4715de9b5b | |||
| d7d4f61bfb | |||
| 69e594ac54 | |||
| f69219919d | |||
| 972c94d86c | |||
| f4606bddc6 | |||
| 06af036f86 | |||
| 8f46d6c13a | |||
| 701f43a1f8 | |||
| 9eea1a073a | |||
| 5278d568de | |||
| 21fc78adb9 | |||
| 4bdab1de3d | |||
| f90884e028 | |||
| 6959941128 | |||
| 18dd9531ad | |||
| 28d56fc3c5 | |||
| b8d944b3ef | |||
| a0722f26ca | |||
| 261267a523 | |||
| da27c9990a | |||
| 50153139fc | |||
| c4fb7761ad | |||
| fb7b25ba2c | |||
| e9be17faab | |||
| 133df472d1 | |||
| 569b33ece4 | |||
| 452e8a9093 | |||
| 1cfcec2bef | |||
| 2d638804d1 | |||
| b6dc82c0b3 | |||
| 2a01d97dd0 | |||
| fc3a2d0b9b | |||
| c766af691a | |||
| b7c24c07e7 | |||
| fbb6c648a5 | |||
| 8b664fc216 | |||
| 5f10f9ce45 | |||
| 46dc038e26 | |||
| c0b742af8a | |||
| 80c9904771 | |||
| 8885bbce6b | |||
| e9618d93d6 | |||
| cbf59d9bf0 | |||
| c9d5e6e017 | |||
| 15e84ba5bc | |||
| 3045944200 | |||
| e1f50e0ca5 | |||
| 9528f735b8 | |||
| 7417e661e0 | |||
| 38d0a87d6b | |||
| cd3577b299 | |||
| 9194487217 | |||
| e958743e65 | |||
| 85cf0a28b1 | |||
| 39dcda66b4 | |||
| f09b8fa2f9 | |||
| df36a5a917 | |||
| d18e801e08 | |||
| b576dd1a38 | |||
| bd0c47e6fc | |||
| 75c0370e54 | |||
| a2a39671b9 | |||
| 2a1a3e7bd9 | |||
| 5bf8c9c160 | |||
| 86622cc4dd | |||
| ed7da57066 | |||
| e2fc14a584 | |||
| d89875db7e | |||
| 321bf11f65 | |||
| 3e4c6dfad3 | |||
| d3c1ca12e9 | |||
| 090e508bf3 | |||
| 193da56edf | |||
| cd0a509215 | |||
| 7647e4b20f | |||
| 2c8542339d | |||
| b32f2ac3a3 | |||
| e726f986db | |||
| 36a6866b96 | |||
| db39d3b383 | |||
| dc2008c5b3 | |||
| 494d84f7c2 | |||
| 44f6ca4ef7 | |||
| 7f9c7a24d3 | |||
| 22af196d56 | |||
| 20232baf06 | |||
| 035cb83d6f | |||
| 114af59b26 | |||
| 6a38fdb06a | |||
| d387048ebf | |||
| 71516713c5 | |||
| d21670f6af | |||
| 2434bce35e | |||
| f02742497a | |||
| 968892d811 | |||
| a3a9444c3b | |||
| e1006c63de | |||
| 21981eb946 | |||
| ac4f2653af | |||
| 51727e419a | |||
| b791f7be68 | |||
| 334b83c973 | |||
| 6ea4a2e0f9 | |||
| ec5d7e2efe | |||
| 737191c170 | |||
| f199eda322 | |||
| 9161e0901f | |||
| 5460c7f676 | |||
| 2a9f6f5628 | |||
| 58dbb7ef3e | |||
| 75b82024de | |||
| 4af1ad8848 | |||
| 164153dc9c | |||
| ac0672bc11 | |||
| 24dd3acd09 | |||
| 4efe7cef58 | |||
| 2dab20f718 | |||
| be298777af | |||
| 45a671940b | |||
| 601971d43d | |||
| c9bce7c976 | |||
| 614747ffca | |||
| 931cc0d1d9 | |||
| b6b4f8c360 | |||
| ff81d80cf9 | |||
| 01000757f3 | |||
| d75dec2a50 | |||
| a45f78217c | |||
| d3761183c3 | |||
| 5d07770ce2 | |||
| 91bdc12e78 |
@@ -43,6 +43,12 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json
|
# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json
|
||||||
# 또는 파일 대신 JSON 본문을 통째로 (한 줄):
|
# 또는 파일 대신 JSON 본문을 통째로 (한 줄):
|
||||||
# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...}
|
# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...}
|
||||||
|
#
|
||||||
|
# 주간 회의록 "회의록 보드"(주차마다 빈 Google 슬라이드) — 위 Google 인증을 같이 쓴다.
|
||||||
|
# OAuth 토큰은 Drive·Slides 권한까지 필요: scripts/google_sheets_authorize.py 로 다시 발급(시트 권한도 함께 들어감)
|
||||||
|
# Cloud Console 에서 Google Drive API·Google Slides API 사용 설정. 서비스 계정이면 공유 드라이브 콘텐츠 관리자로 추가.
|
||||||
|
# GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN=replace-me # 비우면 GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN 사용
|
||||||
|
# MEETING_BOARD_FOLDER_ID=0AGF3CIEboPQiUk9PVA # 보드를 만들 공유 드라이브(폴더) ID — 비우면 이 기본값
|
||||||
|
|
||||||
# ─── 휴가 관리 모듈 (vacation_db) ───
|
# ─── 휴가 관리 모듈 (vacation_db) ───
|
||||||
# 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음).
|
# 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음).
|
||||||
@@ -163,3 +169,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# APP_ENCRYPTION_KEY_V1=
|
# APP_ENCRYPTION_KEY_V1=
|
||||||
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
||||||
# PERFORMANCE_SYNC_DAYS=7
|
# PERFORMANCE_SYNC_DAYS=7
|
||||||
|
# 매출 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 매일 09:00~19:00 정각·30분마다 오늘 포함 최근 10일.
|
||||||
|
# PERFORMANCE_AUTO_SYNC=false # 끄기
|
||||||
|
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
|
||||||
|
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||||
|
|
||||||
|
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
||||||
|
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
||||||
|
# ASSET_DB_URL=postgresql://asset_app:replace-me@postgres-db:5432/asset_db
|
||||||
|
|||||||
@@ -16,3 +16,6 @@ PUBLIC_BASE_URL=http://localhost:8080
|
|||||||
|
|
||||||
CS_ORDER_URL=https://cs.example.com
|
CS_ORDER_URL=https://cs.example.com
|
||||||
CUSTOMER_ORDER_LIST_URL=https://orders.example.com
|
CUSTOMER_ORDER_LIST_URL=https://orders.example.com
|
||||||
|
|
||||||
|
# 자산관리 개발용 DB (사용자가 직접 생성). 운영 DB 접속정보를 사용하지 마세요.
|
||||||
|
# ASSET_DB_URL=postgresql://asset_app:replace-me@host.docker.internal:5432/asset_db
|
||||||
|
|||||||
@@ -24,3 +24,9 @@ __pycache__/
|
|||||||
# dispatch 라벨 PDF 샘플(실제 고객 PII — 커밋 금지)
|
# dispatch 라벨 PDF 샘플(실제 고객 PII — 커밋 금지)
|
||||||
docs/samples/
|
docs/samples/
|
||||||
tests/js/.out/
|
tests/js/.out/
|
||||||
|
|
||||||
|
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
|
||||||
|
KING-DESKTOP.XML
|
||||||
|
|
||||||
|
# Excel 가 파일을 열 때 만드는 잠금 파일
|
||||||
|
~$*
|
||||||
|
|||||||
@@ -36,10 +36,15 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
|
|||||||
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
|
- 말레이시아 창고 재고관리 (`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`
|
- 말레이시아 배송 (`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) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
|
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 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)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성/삭제·사용자 배정은 `is_admin` 만, 배정 멤버(또는 owner)는 서브프로젝트/업무/단계 CRUD. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 권한은 등급(수퍼관리자 > Admin > Pro user > User, 2026-10-12)과 멤버십 기준 — 표는 `docs/PROJECT_MODULE.md` 6-14, 공통 판단 `access.py`(관리자도 멤버가 아니면 프로젝트가 안 보임, 예외는 수퍼관리자). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
||||||
|
|
||||||
상세는 `docs/PROJECT_OVERVIEW.md`.
|
상세는 `docs/PROJECT_OVERVIEW.md`.
|
||||||
|
|
||||||
|
- 자산관리 (`app/modules/asset/`, `asset_db`) — 사무집기·전산장비 등록/배정/반납/상태·구매/보증·이력.
|
||||||
|
HWiNFO XML 분석·사양 조회·이전 보고서와 원본 보존. 권한키 `asset`, 환경변수 `ASSET_DB_URL`.
|
||||||
|
사진 등록/갤러리·모니터 자산 조회/등록/연결·수퍼 관리자 삭제(이력/원본 보존). 기존 설치는 마이그레이션 `asset_db_002_photos_monitors.sql` 필요.
|
||||||
|
DB 미설정 시 저장 비활성, XML 분석 미리보기 가능. DB 생성은 사용자가 서버 명령으로 직접 진행. 상세 `docs/ASSET_MODULE.md`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 개발 원칙
|
## 개발 원칙
|
||||||
@@ -47,7 +52,7 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
|
|||||||
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
|
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
|
||||||
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
|
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
|
||||||
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
|
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
|
||||||
- 신규 DB가 필요하면 **승인 요청 후** 생성하며, DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`).
|
- 신규 DB가 필요하면 **서버에서 실행할 명령을 제공하고 생성은 사용자가 직접 진행한다** (사용자 지시: 2026-10-06). DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`). 대상 서버·현재 DB·백업 상태와 생성 후 스키마·앱 계정 권한·연결 확인 명령을 함께 제공한다. 기존 DB 삭제·덮어쓰기 등 위험 명령은 아래의 별도 승인 원칙을 그대로 따른다.
|
||||||
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
|
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ from .errors import (
|
|||||||
Cafe24AuthError,
|
Cafe24AuthError,
|
||||||
Cafe24ConfigError,
|
Cafe24ConfigError,
|
||||||
Cafe24Error,
|
Cafe24Error,
|
||||||
|
Cafe24FtpConflict,
|
||||||
Cafe24FtpError,
|
Cafe24FtpError,
|
||||||
Cafe24RateLimitError,
|
Cafe24RateLimitError,
|
||||||
)
|
)
|
||||||
@@ -80,6 +81,7 @@ __all__ = [
|
|||||||
"Cafe24RateLimitError",
|
"Cafe24RateLimitError",
|
||||||
"Cafe24ApiError",
|
"Cafe24ApiError",
|
||||||
"Cafe24FtpError",
|
"Cafe24FtpError",
|
||||||
|
"Cafe24FtpConflict",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -164,6 +164,10 @@ class Cafe24Client:
|
|||||||
method = method.upper()
|
method = method.upper()
|
||||||
forced_refresh = False
|
forced_refresh = False
|
||||||
last_error: Exception | None = None
|
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):
|
for attempt in range(self._max_retries + 1):
|
||||||
self._pace()
|
self._pace()
|
||||||
@@ -224,7 +228,9 @@ class Cafe24Client:
|
|||||||
time.sleep(wait)
|
time.sleep(wait)
|
||||||
continue
|
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:
|
if error.retryable and attempt < self._max_retries:
|
||||||
last_error = error
|
last_error = error
|
||||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||||
@@ -241,7 +247,11 @@ class Cafe24Client:
|
|||||||
http_status=status, result="ERROR", error_message=message,
|
http_status=status, result="ERROR", error_message=message,
|
||||||
duration_ms=elapsed,
|
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:
|
if attempt < self._max_retries:
|
||||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -7,15 +7,28 @@ Admin API(OAuth)로는 스킨 파일을 다루지 못한다(`config.py` 상단
|
|||||||
|
|
||||||
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
||||||
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
||||||
|
|
||||||
|
쓰기는 원본에 직접 STOR 하지 않는다 (write_text_file)
|
||||||
|
직접 STOR 는 전송 도중 끊기면 원본이 **앞부분만 남은 채** 잘린다(스킨 템플릿이면
|
||||||
|
모든 상품 페이지가 깨진다). 그래서
|
||||||
|
1) 같은 폴더의 임시 파일에 올리고 (원본은 아직 그대로)
|
||||||
|
2) 다시 받아 바이트 단위로 검증하고
|
||||||
|
3) 교체 직전 원본을 다시 읽어 편집 시작 값과 같은지 확인하고(충돌 방지)
|
||||||
|
4) RNFR/RNTO 로 이름을 바꿔 교체한다
|
||||||
|
서버가 "이미 있는 이름으로 바꾸기"를 거부하면 원본을 옆 이름으로 비킨 뒤 교체하고,
|
||||||
|
실패하면 원본을 제자리로 되돌린다. 이름 바꾸기 자체를 지원하지 않으면 **중단**한다
|
||||||
|
(직접 STOR 로 물러서지 않는다).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ftplib
|
import ftplib
|
||||||
import io
|
import io
|
||||||
|
import posixpath
|
||||||
|
import uuid
|
||||||
|
|
||||||
from .config import Cafe24FtpConfig
|
from .config import Cafe24FtpConfig
|
||||||
from .errors import Cafe24FtpError
|
from .errors import Cafe24FtpConflict, Cafe24FtpError
|
||||||
|
|
||||||
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
||||||
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
||||||
@@ -35,37 +48,135 @@ def _connect(config: Cafe24FtpConfig) -> ftplib.FTP:
|
|||||||
raise Cafe24FtpError(f"FTP 연결/로그인에 실패했습니다: {exc}") from exc
|
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:
|
def read_text_file(config: Cafe24FtpConfig, path: str) -> str:
|
||||||
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
||||||
ftp = _connect(config)
|
ftp = _connect(config)
|
||||||
try:
|
try:
|
||||||
buf = io.BytesIO()
|
|
||||||
try:
|
try:
|
||||||
ftp.retrbinary(f"RETR {path}", buf.write)
|
raw = _retr(ftp, path)
|
||||||
except ftplib.all_errors as exc:
|
except ftplib.all_errors as exc:
|
||||||
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
||||||
try:
|
try:
|
||||||
return buf.getvalue().decode("utf-8")
|
return raw.decode("utf-8")
|
||||||
except UnicodeDecodeError as exc:
|
except UnicodeDecodeError as exc:
|
||||||
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
||||||
finally:
|
finally:
|
||||||
try:
|
_close(ftp)
|
||||||
ftp.quit()
|
|
||||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
|
||||||
ftp.close()
|
|
||||||
|
|
||||||
|
|
||||||
def write_text_file(config: Cafe24FtpConfig, path: str, content: str) -> None:
|
def temp_names(path: str, tag: str) -> tuple[str, str]:
|
||||||
"""디자인 보관함의 파일 1개를 통째로 덮어쓴다."""
|
"""(임시 업로드 이름, 원본을 잠시 비킬 이름) — 같은 폴더, 원본 이름 + 표식."""
|
||||||
|
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)
|
ftp = _connect(config)
|
||||||
try:
|
try:
|
||||||
buf = io.BytesIO(content.encode("utf-8"))
|
# 1) 임시 파일에 올린다 — 원본은 아직 그대로다.
|
||||||
try:
|
try:
|
||||||
ftp.storbinary(f"STOR {path}", buf)
|
ftp.storbinary(f"STOR {tmp}", io.BytesIO(data))
|
||||||
except ftplib.all_errors as exc:
|
except ftplib.all_errors as exc:
|
||||||
raise Cafe24FtpError(f"파일을 쓰지 못했습니다({path}): {exc}") from exc
|
_delete_quiet(ftp, tmp)
|
||||||
finally:
|
raise Cafe24FtpError(f"임시 파일을 올리지 못했습니다 — 원본은 그대로입니다({path}): {exc}") from exc
|
||||||
|
|
||||||
|
# 2) 검증 — 다시 받아 바이트 단위로 비교한다(전송이 잘렸으면 여기서 잡힌다).
|
||||||
try:
|
try:
|
||||||
ftp.quit()
|
uploaded = _retr(ftp, tmp)
|
||||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
except ftplib.all_errors as exc:
|
||||||
ftp.close()
|
_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):
|
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):
|
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)
|
super().__init__(message)
|
||||||
self.status = status
|
self.status = status
|
||||||
self.endpoint = endpoint
|
self.endpoint = endpoint
|
||||||
|
self.maybe_applied = maybe_applied
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def retryable(self) -> bool:
|
def retryable(self) -> bool:
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ from dataclasses import dataclass
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .client import Cafe24Client
|
from .client import Cafe24Client
|
||||||
|
from .errors import Cafe24Error
|
||||||
|
|
||||||
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
||||||
PAGE_LIMIT = 100
|
PAGE_LIMIT = 100
|
||||||
@@ -476,26 +477,55 @@ def wait_for_variants(
|
|||||||
return latest
|
return latest
|
||||||
|
|
||||||
|
|
||||||
|
VARIANT_CHUNK = 100 # 카페24 문서상 PUT variants 1회 최대 건수
|
||||||
|
|
||||||
|
# update_variants 행별 결과 상태
|
||||||
|
VARIANT_OK = "ok" # 카페24가 받아들임
|
||||||
|
VARIANT_FAILED = "failed" # 거절 — 반영되지 않음이 확실
|
||||||
|
VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을 못 받음 — 반영 여부 모름
|
||||||
|
|
||||||
|
|
||||||
def update_variants(
|
def update_variants(
|
||||||
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
|
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
|
||||||
) -> 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)
|
no = int(product_no)
|
||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
for start in range(0, len(requests), 100):
|
for start in range(0, len(requests), VARIANT_CHUNK):
|
||||||
chunk = requests[start : start + 100]
|
chunk = requests[start : start + VARIANT_CHUNK]
|
||||||
if not chunk:
|
if not chunk:
|
||||||
continue
|
continue
|
||||||
payload = client.put(
|
try:
|
||||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
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
|
result = payload.get("variants") if isinstance(payload, dict) else None
|
||||||
|
returned: list[dict[str, Any]] = []
|
||||||
if isinstance(result, list):
|
if isinstance(result, list):
|
||||||
out.extend(result)
|
returned = [r for r in result if isinstance(r, dict)]
|
||||||
elif isinstance(result, dict):
|
elif isinstance(result, dict):
|
||||||
out.append(result)
|
returned = [result]
|
||||||
elif isinstance(payload.get("variant"), dict):
|
elif isinstance(payload, dict) and isinstance(payload.get("variant"), dict):
|
||||||
out.append(payload["variant"])
|
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
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"""Google 슬라이드(회의록 보드) 공통 계층 — 공유 드라이브 폴더에 빈 슬라이드를 만들거나 찾는다.
|
||||||
|
|
||||||
|
인증은 google_sheets 와 같은 설정을 쓰되 권한 범위(scope)가 다르다(Drive + Slides).
|
||||||
|
설정된 쪽을 자동 선택(서비스 계정 우선).
|
||||||
|
|
||||||
|
1) 사용자 OAuth 리프레시 토큰
|
||||||
|
· `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` — 없으면 `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`
|
||||||
|
토큰은 Drive·Slides 권한까지 받아야 한다: `python scripts/google_sheets_authorize.py`(스프레드시트·Drive·Slides 한 번에)
|
||||||
|
· `GOOGLE_SHEETS_OAUTH_CLIENT_ID` / `..._SECRET`(없으면 로그인용 `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`)
|
||||||
|
2) 서비스 계정 JSON — `GOOGLE_SHEETS_CREDENTIALS` / `GOOGLE_SHEETS_CREDENTIALS_JSON`
|
||||||
|
서비스 계정 이메일을 대상 공유 드라이브의 **콘텐츠 관리자** 이상으로 추가해야 한다.
|
||||||
|
|
||||||
|
- 회의록 보드 폴더: `MEETING_BOARD_FOLDER_ID`(기본 = 회의록 보드 공유 드라이브).
|
||||||
|
- 같은 주차 보드를 다시 누르면 새로 만들지 않고 Drive 파일 appProperties(`dbxMeetingWeek` = 주차 시작일)로 찾는다
|
||||||
|
— 파일 이름을 바꿔도 같은 보드가 열린다. 휴지통에 버리면 다음에 새로 만든다.
|
||||||
|
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/presentations"]
|
||||||
|
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||||
|
DEFAULT_BOARD_FOLDER_ID = "0AGF3CIEboPQiUk9PVA"
|
||||||
|
PRESENTATION_MIME = "application/vnd.google-apps.presentation"
|
||||||
|
WEEK_KEY = "dbxMeetingWeek"
|
||||||
|
|
||||||
|
# googleapiclient 의 HTTP 클라이언트는 스레드 안전하지 않고, 같은 주차를 두 사람이 동시에 누르면
|
||||||
|
# 보드가 두 개 생길 수 있으므로 찾기·만들기는 한 번에 하나씩.
|
||||||
|
_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleSlidesError(RuntimeError):
|
||||||
|
"""화면에 보여도 되는 사유(비밀값 없음)."""
|
||||||
|
|
||||||
|
|
||||||
|
def board_folder_id() -> str:
|
||||||
|
return (os.getenv("MEETING_BOARD_FOLDER_ID") or "").strip() or DEFAULT_BOARD_FOLDER_ID
|
||||||
|
|
||||||
|
|
||||||
|
def board_url(file_id: str) -> str:
|
||||||
|
return f"https://docs.google.com/presentation/d/{file_id}/edit"
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleSlidesClient:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.enabled = False
|
||||||
|
self.reason = ""
|
||||||
|
self.auth_mode = ""
|
||||||
|
self._drive: Any = None
|
||||||
|
self._slides: Any = None
|
||||||
|
try:
|
||||||
|
from googleapiclient.discovery import build
|
||||||
|
except ImportError:
|
||||||
|
self.reason = "google-api-python-client 미설치"
|
||||||
|
return
|
||||||
|
creds = self._service_account_creds()
|
||||||
|
if creds is None:
|
||||||
|
creds = self._oauth_creds()
|
||||||
|
if creds is None:
|
||||||
|
if not self.reason:
|
||||||
|
self.reason = "Google 인증 미설정(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 또는 GOOGLE_SHEETS_* 설정 필요)"
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self._drive = build("drive", "v3", credentials=creds, cache_discovery=False)
|
||||||
|
self._slides = build("slides", "v1", credentials=creds, cache_discovery=False)
|
||||||
|
except Exception as exc: # noqa: BLE001 — 사유만(비밀값 미출력)
|
||||||
|
self.reason = f"Google 클라이언트 생성 실패: {type(exc).__name__}"
|
||||||
|
return
|
||||||
|
self.enabled = True
|
||||||
|
|
||||||
|
# ── 인증(google_sheets 와 같은 설정, 범위만 Drive·Slides) ──
|
||||||
|
def _service_account_creds(self) -> Any:
|
||||||
|
raw = (os.getenv("GOOGLE_SHEETS_CREDENTIALS_JSON") or "").strip()
|
||||||
|
path = (os.getenv("GOOGLE_SHEETS_CREDENTIALS") or "").strip()
|
||||||
|
if not raw and not path:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
info = json.loads(raw) if raw else json.loads(open(path, encoding="utf-8").read())
|
||||||
|
from google.oauth2.service_account import Credentials
|
||||||
|
|
||||||
|
creds = Credentials.from_service_account_info(info, scopes=SCOPES)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.reason = f"서비스 계정 인증 실패: {type(exc).__name__}"
|
||||||
|
return None
|
||||||
|
self.auth_mode = "service_account"
|
||||||
|
return creds
|
||||||
|
|
||||||
|
def _oauth_creds(self) -> Any:
|
||||||
|
token = (os.getenv("GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN") or os.getenv("GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN") or "").strip()
|
||||||
|
if not token:
|
||||||
|
return None
|
||||||
|
cid = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_ID") or os.getenv("GOOGLE_CLIENT_ID") or "").strip()
|
||||||
|
secret = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_SECRET") or os.getenv("GOOGLE_CLIENT_SECRET") or "").strip()
|
||||||
|
if not cid or not secret:
|
||||||
|
self.reason = "GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET 미설정"
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
from google.oauth2.credentials import Credentials
|
||||||
|
|
||||||
|
creds = Credentials(token=None, refresh_token=token, token_uri=TOKEN_URI,
|
||||||
|
client_id=cid, client_secret=secret, scopes=SCOPES)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
self.reason = f"OAuth 자격 생성 실패: {type(exc).__name__}"
|
||||||
|
return None
|
||||||
|
self.auth_mode = "oauth"
|
||||||
|
return creds
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────
|
||||||
|
def open_week_board(self, *, folder_id: str, week_key: str, title: str) -> dict[str, Any]:
|
||||||
|
"""그 주차 보드(빈 슬라이드)를 찾고, 없으면 폴더에 만든다 → {id, url, created}."""
|
||||||
|
if not self.enabled:
|
||||||
|
raise GoogleSlidesError(self.reason or "Google 슬라이드 연동이 꺼져 있습니다.")
|
||||||
|
with _LOCK:
|
||||||
|
try:
|
||||||
|
found = self._find(folder_id, week_key)
|
||||||
|
if found:
|
||||||
|
return {"id": found, "url": board_url(found), "created": False}
|
||||||
|
file_id = self._create_blank(folder_id, week_key, title)
|
||||||
|
except GoogleSlidesError:
|
||||||
|
raise
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
raise GoogleSlidesError(_friendly(exc)) from None
|
||||||
|
return {"id": file_id, "url": board_url(file_id), "created": True}
|
||||||
|
|
||||||
|
def _find(self, folder_id: str, week_key: str) -> str | None:
|
||||||
|
q = (f"'{folder_id}' in parents and trashed = false and mimeType = '{PRESENTATION_MIME}' "
|
||||||
|
f"and appProperties has {{ key='{WEEK_KEY}' and value='{week_key}' }}")
|
||||||
|
res = self._drive.files().list(
|
||||||
|
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
|
||||||
|
corpora="allDrives",
|
||||||
|
).execute()
|
||||||
|
files = res.get("files") or []
|
||||||
|
return files[0]["id"] if files else None
|
||||||
|
|
||||||
|
def _create_blank(self, folder_id: str, week_key: str, title: str) -> str:
|
||||||
|
meta = {"name": title, "mimeType": PRESENTATION_MIME, "parents": [folder_id],
|
||||||
|
"appProperties": {WEEK_KEY: week_key}}
|
||||||
|
file_id = self._drive.files().create(body=meta, fields="id", supportsAllDrives=True).execute()["id"]
|
||||||
|
# 새 프레젠테이션의 첫 장은 "제목·부제목" 틀(TITLE 레이아웃) — 틀 없는 빈 장(BLANK) 하나만 남긴다
|
||||||
|
pres = self._slides.presentations().get(presentationId=file_id, fields="slides.objectId").execute()
|
||||||
|
reqs: list[dict[str, Any]] = [{"createSlide": {"insertionIndex": 0, "slideLayoutReference": {"predefinedLayout": "BLANK"}}}]
|
||||||
|
reqs += [{"deleteObject": {"objectId": s["objectId"]}} for s in pres.get("slides") or []]
|
||||||
|
self._slides.presentations().batchUpdate(presentationId=file_id, body={"requests": reqs}).execute()
|
||||||
|
return file_id
|
||||||
|
|
||||||
|
|
||||||
|
def _friendly(exc: Exception) -> str:
|
||||||
|
"""Google API 오류 → 화면용 문구(비밀값·원문 응답 미포함)."""
|
||||||
|
status = getattr(getattr(exc, "resp", None), "status", None)
|
||||||
|
text = str(exc)
|
||||||
|
# 토큰 갱신 실패(RefreshError) — Google 이 준 OAuth 오류 코드(비밀값 아님)를 보여 원인을 바로 알 수 있게
|
||||||
|
m = re.search(r"\b(invalid_scope|invalid_grant|invalid_client|unauthorized_client|deleted_client|access_denied|invalid_request)\b", text)
|
||||||
|
code = m.group(1) if m else ""
|
||||||
|
if code in ("unauthorized_client", "invalid_client", "deleted_client"):
|
||||||
|
return (f"Google 토큰 갱신 실패({code}) — 토큰을 발급한 OAuth 클라이언트와 서버 .env 의 "
|
||||||
|
"GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET(없으면 GOOGLE_CLIENT_ID/SECRET)이 다릅니다.")
|
||||||
|
if "invalid_scope" in text or "insufficient" in text.lower() or "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text:
|
||||||
|
return "Google 권한(Drive·Slides)이 없는 토큰입니다. 토큰을 다시 발급해 주세요(scripts/google_sheets_authorize.py)."
|
||||||
|
if "invalid_grant" in text:
|
||||||
|
return "Google 토큰이 만료·폐기되었습니다. 토큰을 다시 발급해 주세요."
|
||||||
|
if status == 404:
|
||||||
|
return "회의록 보드 폴더를 찾을 수 없습니다(MEETING_BOARD_FOLDER_ID·공유 드라이브 접근 권한 확인)."
|
||||||
|
if status == 403:
|
||||||
|
return "Google Drive·Slides 접근이 거부되었습니다(API 사용 설정·공유 드라이브 권한 확인)."
|
||||||
|
return f"Google 슬라이드 처리 실패({type(exc).__name__}{f' {status}' if status else ''}{f' {code}' if code else ''})."
|
||||||
|
|
||||||
|
|
||||||
|
_CLIENT: GoogleSlidesClient | None = None
|
||||||
|
_CLIENT_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def get_client() -> GoogleSlidesClient:
|
||||||
|
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
|
||||||
|
global _CLIENT
|
||||||
|
with _CLIENT_LOCK:
|
||||||
|
if _CLIENT is None or not _CLIENT.enabled:
|
||||||
|
_CLIENT = GoogleSlidesClient()
|
||||||
|
return _CLIENT
|
||||||
+50
-4
@@ -15,6 +15,8 @@ from pydantic import BaseModel
|
|||||||
from starlette.middleware.sessions import SessionMiddleware
|
from starlette.middleware.sessions import SessionMiddleware
|
||||||
|
|
||||||
from .modules.cafe24 import build_cafe24_store
|
from .modules.cafe24 import build_cafe24_store
|
||||||
|
from .modules.asset import build_asset_store
|
||||||
|
from .modules.asset import router as asset_router
|
||||||
from .modules.cafe24 import router as cafe24_router
|
from .modules.cafe24 import router as cafe24_router
|
||||||
from .modules.cupang import build_cupang_store, build_itemcode_reader
|
from .modules.cupang import build_cupang_store, build_itemcode_reader
|
||||||
from .modules.cupang import router as cupang_router
|
from .modules.cupang import router as cupang_router
|
||||||
@@ -24,6 +26,8 @@ from .modules.expense import CategoryStore, build_expense_store
|
|||||||
from .modules.expense import router as expense_router
|
from .modules.expense import router as expense_router
|
||||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||||
from .modules.malaysia import router as malaysia_router
|
from .modules.malaysia import router as malaysia_router
|
||||||
|
from .modules.notice import build_notice_store
|
||||||
|
from .modules.notice import router as notice_router
|
||||||
from .modules.performance import build_performance_store
|
from .modules.performance import build_performance_store
|
||||||
from .modules.performance import router as performance_router
|
from .modules.performance import router as performance_router
|
||||||
from .modules.project import build_project_store
|
from .modules.project import build_project_store
|
||||||
@@ -33,6 +37,8 @@ from .modules.vacation import router as vacation_router
|
|||||||
from .store import (
|
from .store import (
|
||||||
APPROVER_KEYS,
|
APPROVER_KEYS,
|
||||||
MODULE_KEYS,
|
MODULE_KEYS,
|
||||||
|
ROLE_LABELS,
|
||||||
|
ROLES,
|
||||||
SUPER_ADMIN_EMAIL,
|
SUPER_ADMIN_EMAIL,
|
||||||
UserStore,
|
UserStore,
|
||||||
allowed_modules,
|
allowed_modules,
|
||||||
@@ -52,6 +58,7 @@ MODULE_LABELS: dict[str, str] = {
|
|||||||
"project": "프로젝트 관리",
|
"project": "프로젝트 관리",
|
||||||
"cafe24": "카페24 상품관리",
|
"cafe24": "카페24 상품관리",
|
||||||
"performance": "실적",
|
"performance": "실적",
|
||||||
|
"asset": "자산관리",
|
||||||
"expense_approver": "개인경비",
|
"expense_approver": "개인경비",
|
||||||
"vacation_approver": "휴가",
|
"vacation_approver": "휴가",
|
||||||
}
|
}
|
||||||
@@ -110,10 +117,14 @@ def build_google_oauth() -> OAuth:
|
|||||||
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
||||||
"""앱 시작 시 백그라운드 작업 시작.
|
"""앱 시작 시 백그라운드 작업 시작.
|
||||||
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
||||||
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py."""
|
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py.
|
||||||
|
- 실적 매출 자동 업데이트(09~19시 정각·30분, 최근 10일) 스레드.
|
||||||
|
PERFORMANCE_AUTO_SYNC=false 면 안 돈다. 상세는 app/modules/performance/auto_sync.py."""
|
||||||
|
from .modules.performance.auto_sync import start_auto_sync_thread # noqa: WPS433
|
||||||
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
||||||
|
|
||||||
start_reminder_thread(getattr(app_.state, "project_store", None))
|
start_reminder_thread(getattr(app_.state, "project_store", None))
|
||||||
|
start_auto_sync_thread(app_.state)
|
||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
@@ -140,6 +151,8 @@ _MODULE_TEMPLATE_DIRS = [
|
|||||||
BASE_DIR / "modules" / "project" / "templates",
|
BASE_DIR / "modules" / "project" / "templates",
|
||||||
BASE_DIR / "modules" / "cafe24" / "templates",
|
BASE_DIR / "modules" / "cafe24" / "templates",
|
||||||
BASE_DIR / "modules" / "performance" / "templates",
|
BASE_DIR / "modules" / "performance" / "templates",
|
||||||
|
BASE_DIR / "modules" / "asset" / "templates",
|
||||||
|
BASE_DIR / "modules" / "notice" / "templates",
|
||||||
]
|
]
|
||||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||||
templates.env.loader = ChoiceLoader(
|
templates.env.loader = ChoiceLoader(
|
||||||
@@ -202,6 +215,9 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
|
|||||||
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||||
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
||||||
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
||||||
|
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
|
||||||
|
# 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503).
|
||||||
|
app.state.notice_store = build_notice_store(app.state.project_store)
|
||||||
|
|
||||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||||
app.include_router(expense_router)
|
app.include_router(expense_router)
|
||||||
@@ -212,6 +228,8 @@ app.include_router(dispatch_router)
|
|||||||
app.include_router(project_router)
|
app.include_router(project_router)
|
||||||
app.include_router(cafe24_router)
|
app.include_router(cafe24_router)
|
||||||
app.include_router(performance_router)
|
app.include_router(performance_router)
|
||||||
|
app.include_router(asset_router)
|
||||||
|
app.include_router(notice_router)
|
||||||
|
|
||||||
|
|
||||||
def public_url_for(request: Request, route_name: str) -> str:
|
def public_url_for(request: Request, route_name: str) -> str:
|
||||||
@@ -376,7 +394,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"key": "project",
|
"key": "project",
|
||||||
"title": "프로젝트 관리",
|
"title": "Project",
|
||||||
"subtitle": "Projects",
|
"subtitle": "Projects",
|
||||||
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
|
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
|
||||||
"url": "/project/",
|
"url": "/project/",
|
||||||
@@ -405,6 +423,11 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
"category": "관리",
|
"category": "관리",
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
items.append({
|
||||||
|
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||||
|
"description": "사무집기·전산장비의 배정·반납·구매 이력과 HWiNFO 컴퓨터 사양을 관리합니다.",
|
||||||
|
"url": "/asset/", "health_url": "/asset/health", "status": "ready", "category": "관리",
|
||||||
|
})
|
||||||
allowed = allowed_modules(user_rec)
|
allowed = allowed_modules(user_rec)
|
||||||
for item in items:
|
for item in items:
|
||||||
item["allowed"] = item["key"] in allowed
|
item["allowed"] = item["key"] in allowed
|
||||||
@@ -414,6 +437,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
def _icon_svg(name: str) -> str:
|
def _icon_svg(name: str) -> str:
|
||||||
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
||||||
paths = {
|
paths = {
|
||||||
|
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
||||||
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
||||||
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
||||||
"vacation": '<path d="M8 2v4"/><path d="M16 2v4"/><rect x="3" y="6" width="18" height="15" rx="2"/><path d="M3 11h18"/>',
|
"vacation": '<path d="M8 2v4"/><path d="M16 2v4"/><rect x="3" y="6" width="18" height="15" rx="2"/><path d="M3 11h18"/>',
|
||||||
@@ -476,16 +500,36 @@ def build_erp_nav(
|
|||||||
return items
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _login_orbit_names(limit: int = 40) -> list[str]:
|
||||||
|
"""로그인 화면 왼쪽 패널 — King 주위를 도는 사용자 아이디(이메일 @ 앞, 첫 글자 대문자). 이메일·실명은 내보내지 않는다."""
|
||||||
|
names: set[str] = set()
|
||||||
|
try:
|
||||||
|
users = user_store.list_all()
|
||||||
|
except Exception: # noqa: BLE001 — 장식이라 실패해도 로그인 화면은 그대로
|
||||||
|
return []
|
||||||
|
for u in users:
|
||||||
|
email = str(u.get("email") or "").lower().strip()
|
||||||
|
local = email.split("@", 1)[0]
|
||||||
|
if not local or email == SUPER_ADMIN_EMAIL:
|
||||||
|
continue
|
||||||
|
names.add(local[:1].upper() + local[1:])
|
||||||
|
return sorted(names)[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def _render_login(request: Request) -> HTMLResponse:
|
||||||
|
return render_template(request, "login.html", {"orbit_names": _login_orbit_names()})
|
||||||
|
|
||||||
|
|
||||||
@app.get("/", response_class=HTMLResponse)
|
@app.get("/", response_class=HTMLResponse)
|
||||||
async def home(request: Request) -> HTMLResponse:
|
async def home(request: Request) -> HTMLResponse:
|
||||||
sess = get_session_user(request)
|
sess = get_session_user(request)
|
||||||
if not sess:
|
if not sess:
|
||||||
return render_template(request, "login.html")
|
return _render_login(request)
|
||||||
user_rec = user_store.get(sess["email"])
|
user_rec = user_store.get(sess["email"])
|
||||||
if user_rec is None:
|
if user_rec is None:
|
||||||
# 도메인은 통과했으나 저장소에 없음 — 세션 정리 후 재로그인
|
# 도메인은 통과했으나 저장소에 없음 — 세션 정리 후 재로그인
|
||||||
request.session.clear()
|
request.session.clear()
|
||||||
return render_template(request, "login.html")
|
return _render_login(request)
|
||||||
|
|
||||||
# 슈퍼 관리자 → 업무 모듈 선택 화면(main.html).
|
# 슈퍼 관리자 → 업무 모듈 선택 화면(main.html).
|
||||||
# 일반 사용자 → ERP 메인(좌측 메뉴 + 우측 콘텐츠).
|
# 일반 사용자 → ERP 메인(좌측 메뉴 + 우측 콘텐츠).
|
||||||
@@ -631,6 +675,8 @@ async def admin_page(request: Request) -> HTMLResponse:
|
|||||||
"module_keys": list(MODULE_KEYS),
|
"module_keys": list(MODULE_KEYS),
|
||||||
"module_labels": MODULE_LABELS,
|
"module_labels": MODULE_LABELS,
|
||||||
"approver_keys": list(APPROVER_KEYS),
|
"approver_keys": list(APPROVER_KEYS),
|
||||||
|
"roles": list(ROLES),
|
||||||
|
"role_labels": ROLE_LABELS,
|
||||||
"super_admin_email": SUPER_ADMIN_EMAIL,
|
"super_admin_email": SUPER_ADMIN_EMAIL,
|
||||||
"is_admin": True,
|
"is_admin": True,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Company asset management; PostgreSQL only, never creates databases at startup."""
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
|
||||||
|
def build_asset_store(*, dsn: str | None):
|
||||||
|
if not dsn:
|
||||||
|
return None
|
||||||
|
from .db import AssetStore
|
||||||
|
return AssetStore(dsn)
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
"""자산·보고서·이력을 함께 저장합니다. DB 생성은 사용자가 서버에서 SQL로 진행합니다."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
from .store import AssetConflict, transition
|
||||||
|
from .media import MAX_PHOTOS
|
||||||
|
from .monitors import compatible_monitor, monitor_devices
|
||||||
|
|
||||||
|
FIELDS = ("tag", "name", "category", "manufacturer", "model", "serial", "location", "department",
|
||||||
|
"purchased_on", "purchase_cost", "vendor", "warranty_until", "notes")
|
||||||
|
SORTS = {"updated": "a.updated_at DESC", "name": "a.name ASC", "tag": "a.tag ASC",
|
||||||
|
"cost": "a.purchase_cost DESC NULLS LAST", "warranty": "a.warranty_until ASC NULLS LAST"}
|
||||||
|
|
||||||
|
|
||||||
|
def serialize(row):
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return {k: (v.isoformat() if isinstance(v, (date, datetime)) else str(v) if isinstance(v, Decimal) else v)
|
||||||
|
for k, v in row.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def filters(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||||
|
conditions, params = ["a.deleted_at IS NULL"], []
|
||||||
|
if q:
|
||||||
|
# %와 _도 입력한 글자 그대로 검색합니다. 검색어는 SQL과 분리해서 전달합니다.
|
||||||
|
value = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||||
|
conditions.append("(concat_ws(' ',a.tag,a.name,a.model,a.serial,a.manufacturer,a.location,a.department,a.assignee_email) ILIKE %s)")
|
||||||
|
params.append(value)
|
||||||
|
for col, value in (("category", category), ("status", status), ("location", location), ("assignee_email", assignee)):
|
||||||
|
if value:
|
||||||
|
conditions.append(f"a.{col} = %s")
|
||||||
|
params.append(value)
|
||||||
|
if warranty:
|
||||||
|
conditions.append("a.warranty_until BETWEEN (now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date + 30 AND a.status <> 'retired'")
|
||||||
|
if group == "furniture":
|
||||||
|
conditions.append("a.category IN ('desk','chair','furniture')")
|
||||||
|
elif group == "computer":
|
||||||
|
conditions.append("a.category NOT IN ('desk','chair','furniture')")
|
||||||
|
return " AND ".join(conditions), params
|
||||||
|
|
||||||
|
|
||||||
|
class AssetStore:
|
||||||
|
def __init__(self, dsn):
|
||||||
|
self._pool = ConnectionPool(dsn, min_size=0, max_size=5, timeout=5, open=False,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True})
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self._pool.close()
|
||||||
|
|
||||||
|
def health(self):
|
||||||
|
with self._pool.connection(timeout=5) as conn:
|
||||||
|
conn.execute("SELECT id,deleted_at FROM assets LIMIT 1")
|
||||||
|
conn.execute("SELECT id FROM asset_photos LIMIT 0")
|
||||||
|
conn.execute("SELECT monitor_key FROM asset_monitor_links LIMIT 0")
|
||||||
|
|
||||||
|
def list_assets(self, *, page=1, page_size=25, sort="updated", **kwargs):
|
||||||
|
# 전체 개수와 목록을 같은 시점의 데이터로 읽어 페이지 숫자가 어긋나지 않게 합니다.
|
||||||
|
where, params = filters(**kwargs)
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
total = conn.execute(f"SELECT count(*) AS n FROM assets a WHERE {where}", params).fetchone()["n"]
|
||||||
|
rows = conn.execute(
|
||||||
|
f"SELECT a.*,r.parsed->'summary' AS specs,r.uploaded_at AS report_at FROM assets a "
|
||||||
|
"LEFT JOIN asset_reports r ON r.id=a.latest_report_id "
|
||||||
|
f"WHERE {where} ORDER BY {SORTS.get(sort, SORTS['updated'])},a.id LIMIT %s OFFSET %s",
|
||||||
|
[*params, page_size, (page - 1) * page_size]).fetchall()
|
||||||
|
return {"items": [serialize(r) for r in rows], "total": total, "page": page, "page_size": page_size}
|
||||||
|
|
||||||
|
def dashboard(self):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
totals = conn.execute("""SELECT count(*) AS total,
|
||||||
|
count(*) FILTER(WHERE status='available') AS available,
|
||||||
|
count(*) FILTER(WHERE status='in_use') AS in_use,
|
||||||
|
count(*) FILTER(WHERE status='maintenance') AS maintenance,
|
||||||
|
count(*) FILTER(WHERE status='lost') AS lost,
|
||||||
|
count(*) FILTER(WHERE status='retired') AS retired,
|
||||||
|
coalesce(sum(purchase_cost) FILTER(WHERE status<>'retired'),0) AS purchase_total,
|
||||||
|
count(*) FILTER(WHERE status<>'retired' AND warranty_until BETWEEN
|
||||||
|
(now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date+30) AS warranty_soon
|
||||||
|
FROM assets WHERE deleted_at IS NULL""").fetchone()
|
||||||
|
categories = conn.execute("SELECT category,count(*) AS count FROM assets WHERE deleted_at IS NULL GROUP BY category ORDER BY count(*) DESC,category").fetchall()
|
||||||
|
locations = conn.execute("SELECT DISTINCT location FROM assets WHERE location<>'' AND deleted_at IS NULL ORDER BY location").fetchall()
|
||||||
|
activity = conn.execute("SELECT e.*,a.tag,a.name FROM asset_events e JOIN assets a ON a.id=e.asset_id WHERE a.deleted_at IS NULL ORDER BY e.id DESC LIMIT 12").fetchall()
|
||||||
|
return {"totals": serialize(totals), "categories": categories, "locations": [r["location"] for r in locations],
|
||||||
|
"activity": [serialize(r) for r in activity]}
|
||||||
|
|
||||||
|
def detail(self, asset_id):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL", (asset_id,)).fetchone()
|
||||||
|
if not asset:
|
||||||
|
raise KeyError(asset_id)
|
||||||
|
reports = conn.execute("SELECT id,filename,sha256,uploaded_at,actor,parsed->'summary' AS summary,parsed->>'scan_time' AS scan_time FROM asset_reports WHERE asset_id=%s ORDER BY uploaded_at DESC,id DESC", (asset_id,)).fetchall()
|
||||||
|
report = conn.execute("SELECT id,filename,uploaded_at,parsed FROM asset_reports WHERE id=%s AND asset_id=%s", (asset["latest_report_id"], asset_id)).fetchone() if asset["latest_report_id"] else None
|
||||||
|
events = conn.execute("SELECT * FROM asset_events WHERE asset_id=%s ORDER BY id DESC LIMIT 200", (asset_id,)).fetchall()
|
||||||
|
photos = conn.execute("SELECT id,filename,width,height,uploaded_at,actor FROM asset_photos WHERE asset_id=%s ORDER BY uploaded_at DESC,id", (asset_id,)).fetchall()
|
||||||
|
monitors = self._monitor_matches(conn, asset_id, report["parsed"]) if report else []
|
||||||
|
return {"asset": serialize(asset), "report": serialize(report), "reports": [serialize(r) for r in reports],
|
||||||
|
"events": [serialize(r) for r in events], "photos": [serialize(r) for r in photos], "monitors": monitors}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _lock(conn, asset_id, version):
|
||||||
|
# 같은 자산을 동시에 변경할 때 먼저 저장한 사용자의 값을 보호합니다.
|
||||||
|
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (asset_id,)).fetchone()
|
||||||
|
if not asset or asset.get("deleted_at"):
|
||||||
|
raise KeyError(asset_id)
|
||||||
|
if asset["version"] != version:
|
||||||
|
raise AssetConflict("다른 사용자가 수정했습니다. 상세 화면을 새로 열고 다시 시도하세요.")
|
||||||
|
return asset
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _event(conn, asset_id, actor, kind, note, changes):
|
||||||
|
conn.execute("INSERT INTO asset_events(asset_id,actor,kind,note,changes) VALUES(%s,%s,%s,%s,%s)",
|
||||||
|
(asset_id, actor, kind, note, Jsonb(changes)))
|
||||||
|
|
||||||
|
def create(self, payload, actor, report=None):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
return self._create(conn, payload, actor, report)
|
||||||
|
|
||||||
|
def _create(self, conn, payload, actor, report=None):
|
||||||
|
# 모니터 등록도 같은 트랜잭션 안에서 자산 생성과 연결을 함께 처리합니다.
|
||||||
|
data = payload.model_dump()
|
||||||
|
asset_id = uuid.uuid4().hex
|
||||||
|
if not data["tag"]:
|
||||||
|
data["tag"] = "AST-" + str(conn.execute("SELECT nextval('asset_tag_seq') AS n").fetchone()["n"]).zfill(6)
|
||||||
|
conn.execute(f"INSERT INTO assets(id,{','.join(FIELDS)}) VALUES({','.join(['%s'] * (len(FIELDS) + 1))})",
|
||||||
|
[asset_id, *[data[k] for k in FIELDS]])
|
||||||
|
self._event(conn, asset_id, actor, "create", "자산 등록", {"after": serialize(data)})
|
||||||
|
if report:
|
||||||
|
if data["category"] != "computer":
|
||||||
|
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||||
|
self._save_report(conn, asset_id, actor, *report)
|
||||||
|
return asset_id
|
||||||
|
|
||||||
|
def update(self, asset_id, payload, actor):
|
||||||
|
data = payload.model_dump(exclude={"version"})
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
old = self._lock(conn, asset_id, payload.version)
|
||||||
|
if old["latest_report_id"] and data["category"] != "computer":
|
||||||
|
raise ValueError("사양 보고서가 연결된 자산은 컴퓨터 분류를 유지해야 합니다.")
|
||||||
|
if not data["tag"]:
|
||||||
|
data["tag"] = old["tag"]
|
||||||
|
changes = {k: {"before": serialize(old)[k], "after": serialize(data)[k]} for k in FIELDS if old[k] != data[k]}
|
||||||
|
if changes:
|
||||||
|
conn.execute(f"UPDATE assets SET {','.join(k+'=%s' for k in FIELDS)},version=version+1,updated_at=now() WHERE id=%s",
|
||||||
|
[*[data[k] for k in FIELDS], asset_id])
|
||||||
|
self._event(conn, asset_id, actor, "update", "자산 정보 수정", changes)
|
||||||
|
|
||||||
|
def action(self, asset_id, payload, actor):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
old = self._lock(conn, asset_id, payload.version)
|
||||||
|
status, assignee = transition(old, payload)
|
||||||
|
location = payload.location or old["location"]
|
||||||
|
conn.execute("UPDATE assets SET status=%s,assignee_email=%s,location=%s,version=version+1,updated_at=now() WHERE id=%s",
|
||||||
|
(status, assignee, location, asset_id))
|
||||||
|
changes = {k: {"before": old[k], "after": value} for k, value in
|
||||||
|
(("status", status), ("assignee_email", assignee), ("location", location)) if old[k] != value}
|
||||||
|
self._event(conn, asset_id, actor, payload.action, payload.note, changes)
|
||||||
|
|
||||||
|
def _save_report(self, conn, asset_id, actor, filename, raw, parsed):
|
||||||
|
# 원본과 분석 결과를 함께 저장하고 최신 보고서만 교체합니다. 이전 보고서는 남습니다.
|
||||||
|
existing = conn.execute("SELECT id FROM asset_reports WHERE asset_id=%s AND sha256=%s", (asset_id, parsed["sha256"])).fetchone()
|
||||||
|
if existing:
|
||||||
|
raise AssetConflict("이 자산에 동일한 보고서가 이미 등록되어 있습니다.")
|
||||||
|
report_id = uuid.uuid4().hex
|
||||||
|
conn.execute("INSERT INTO asset_reports(id,asset_id,filename,sha256,raw_xml,parsed,actor) VALUES(%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(report_id, asset_id, filename, parsed["sha256"], raw, Jsonb(parsed), actor))
|
||||||
|
conn.execute("UPDATE assets SET latest_report_id=%s,version=version+1,updated_at=now() WHERE id=%s", (report_id, asset_id))
|
||||||
|
self._event(conn, asset_id, actor, "report", filename, {"report_id": report_id, "summary": parsed["summary"]})
|
||||||
|
return report_id
|
||||||
|
|
||||||
|
def attach_report(self, asset_id, version, actor, filename, raw, parsed):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
asset = self._lock(conn, asset_id, version)
|
||||||
|
if asset["category"] != "computer":
|
||||||
|
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||||
|
return self._save_report(conn, asset_id, actor, filename, raw, parsed)
|
||||||
|
|
||||||
|
def report(self, asset_id, report_id, *, raw=False):
|
||||||
|
columns = "r.filename,r.raw_xml" if raw else "r.id,r.filename,r.parsed,r.uploaded_at"
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(f"SELECT {columns} FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise KeyError(report_id)
|
||||||
|
return serialize(row)
|
||||||
|
|
||||||
|
def delete(self, asset_id, version, actor, note):
|
||||||
|
# 수퍼 관리자 삭제도 이력과 원본은 보존하고 대장·다운로드에서 제외합니다.
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock(conn, asset_id, version)
|
||||||
|
self._event(conn, asset_id, actor, "delete", note, {})
|
||||||
|
conn.execute("UPDATE assets SET deleted_at=now(),deleted_by=%s,version=version+1,updated_at=now() WHERE id=%s", (actor, asset_id))
|
||||||
|
|
||||||
|
def add_photo(self, asset_id, version, actor, filename, image, mime, width, height):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock(conn, asset_id, version)
|
||||||
|
count = conn.execute("SELECT count(*) AS n FROM asset_photos WHERE asset_id=%s", (asset_id,)).fetchone()["n"]
|
||||||
|
if count >= MAX_PHOTOS:
|
||||||
|
raise ValueError(f"사진은 자산당 {MAX_PHOTOS}개까지 등록할 수 있습니다.")
|
||||||
|
photo_id = uuid.uuid4().hex
|
||||||
|
conn.execute("INSERT INTO asset_photos(id,asset_id,filename,image,mime,width,height,actor) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(photo_id, asset_id, filename, image, mime, width, height, actor))
|
||||||
|
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (asset_id,))
|
||||||
|
self._event(conn, asset_id, actor, "photo", filename, {"photo_id": photo_id})
|
||||||
|
return photo_id
|
||||||
|
|
||||||
|
def photo(self, asset_id, photo_id):
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT p.image,p.mime FROM asset_photos p JOIN assets a ON a.id=p.asset_id WHERE p.asset_id=%s AND p.id=%s AND a.deleted_at IS NULL", (asset_id, photo_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise KeyError(photo_id)
|
||||||
|
return row
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _monitor_matches(conn, computer_id, parsed):
|
||||||
|
result = []
|
||||||
|
for device in monitor_devices(parsed):
|
||||||
|
linked = conn.execute("SELECT a.* FROM asset_monitor_links l JOIN assets a ON a.id=l.monitor_asset_id WHERE l.computer_id=%s AND l.monitor_key=%s AND a.category='monitor' AND a.deleted_at IS NULL", (computer_id, device["key"])).fetchone()
|
||||||
|
matches = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND lower(btrim(serial))=%s ORDER BY id LIMIT 21", (device["serial"].casefold(),)).fetchall() if device["serial"] else []
|
||||||
|
compatible = [a for a in matches if compatible_monitor(a, device)]
|
||||||
|
asset = linked or (compatible[0] if len(compatible) == 1 else None)
|
||||||
|
candidates = matches if not asset else []
|
||||||
|
# candidate_by — 후보가 같은 시리얼(같은 실물일 가능성)인지, 참고용 같은 모델·이름인지.
|
||||||
|
# 같은 모델은 여러 대일 수 있으므로(듀얼 모니터 등) 새 등록을 막지 않는다(2026-10-07).
|
||||||
|
candidate_by = "serial" if candidates else ""
|
||||||
|
if not asset and not candidates:
|
||||||
|
candidates = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND (lower(btrim(model))=%s OR lower(btrim(name))=%s) ORDER BY id LIMIT 20", (device["model"].casefold(), device["name"].casefold())).fetchall()
|
||||||
|
candidate_by = "model" if candidates else ""
|
||||||
|
result.append({**device, "asset": serialize(asset), "candidates": [serialize(r) for r in candidates],
|
||||||
|
"candidate_by": candidate_by,
|
||||||
|
"match": "linked" if linked else "serial" if asset else "unconfirmed"})
|
||||||
|
return result
|
||||||
|
|
||||||
|
def report_monitors(self, asset_id, report_id):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||||
|
row = conn.execute("SELECT r.parsed FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise KeyError(report_id)
|
||||||
|
return self._monitor_matches(conn, asset_id, row["parsed"])
|
||||||
|
|
||||||
|
def register_monitor(self, computer_id, index, payload, actor):
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
computer = self._lock(conn, computer_id, payload.version)
|
||||||
|
if computer["category"] != "computer" or computer["latest_report_id"] != payload.report_id:
|
||||||
|
raise AssetConflict("최신 컴퓨터 보고서를 다시 열고 모니터를 등록하세요.")
|
||||||
|
row = conn.execute("SELECT parsed FROM asset_reports WHERE asset_id=%s AND id=%s", (computer_id, payload.report_id)).fetchone()
|
||||||
|
devices = monitor_devices(row["parsed"]) if row else []
|
||||||
|
if index < 0 or index >= len(devices):
|
||||||
|
raise KeyError(index)
|
||||||
|
device = devices[index]
|
||||||
|
# 서로 다른 컴퓨터에서 동일 시리얼을 동시에 등록하는 경우도 중복을 막습니다.
|
||||||
|
if device["serial"]:
|
||||||
|
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s,0))", ("asset-monitor:" + device["serial"].casefold(),))
|
||||||
|
if payload.asset_id:
|
||||||
|
target = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (payload.asset_id,)).fetchone()
|
||||||
|
if not target or target["category"] != "monitor":
|
||||||
|
raise ValueError("등록된 모니터 자산을 선택하세요.")
|
||||||
|
monitor_id = target["id"]
|
||||||
|
else:
|
||||||
|
match = self._monitor_matches(conn, computer_id, row["parsed"])[index]
|
||||||
|
# 같은 시리얼(같은 실물)만 막는다 — 같은 모델이지만 시리얼이 다른 모니터는 새 자산으로 등록된다.
|
||||||
|
if match["asset"] or match["candidate_by"] == "serial":
|
||||||
|
raise AssetConflict(f"같은 시리얼({device['serial']})의 모니터가 이미 등록되어 있습니다. 기존 자산에 연결하세요."
|
||||||
|
if device["serial"] else "이 모니터는 이미 자산에 연결되어 있습니다.")
|
||||||
|
# 보고서의 실제 시리얼을 유지해야 이후 보고서에서도 같은 장비를 찾습니다.
|
||||||
|
data = payload.asset.model_copy(update={"serial": device["serial"] or payload.asset.serial})
|
||||||
|
monitor_id = self._create(conn, data, actor)
|
||||||
|
conn.execute("INSERT INTO asset_monitor_links(computer_id,monitor_key,monitor_asset_id,actor) VALUES(%s,%s,%s,%s) ON CONFLICT(computer_id,monitor_key) DO UPDATE SET monitor_asset_id=EXCLUDED.monitor_asset_id,actor=EXCLUDED.actor,linked_at=now()",
|
||||||
|
(computer_id, device["key"], monitor_id, actor))
|
||||||
|
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (computer_id,))
|
||||||
|
self._event(conn, computer_id, actor, "monitor", "모니터 자산 연결", {"monitor_asset_id": monitor_id, "model": device["model"]})
|
||||||
|
return monitor_id
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""HWiNFO XML을 부품별로 읽습니다. 외부 파일이나 엔티티는 열지 않습니다."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from xml.etree.ElementTree import ParseError
|
||||||
|
|
||||||
|
from defusedxml.ElementTree import fromstring
|
||||||
|
from defusedxml.common import DefusedXmlException
|
||||||
|
|
||||||
|
MAX_REPORT_BYTES = 10 * 1024 * 1024
|
||||||
|
SECTION_LABELS = {
|
||||||
|
"SYSTEM": "시스템", "CPU": "프로세서", "MOBO": "메인보드 · BIOS",
|
||||||
|
"MEMORY": "메모리", "VIDEO": "그래픽", "MONITOR": "모니터",
|
||||||
|
"DRIVES": "저장장치", "NETWORK": "네트워크", "SOUND": "오디오",
|
||||||
|
"PORTS": "포트 · USB", "BUS": "버스 · 컨트롤러",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _text(node, tag):
|
||||||
|
return (node.findtext(tag) or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _props(node):
|
||||||
|
return [{"label": _text(p, "Entry"), "value": _text(p, "Description"),
|
||||||
|
"type": _text(p, "PropertyType")} for p in node.findall("Property")]
|
||||||
|
|
||||||
|
|
||||||
|
def _pick(nodes, *, types=(), labels=()):
|
||||||
|
# 언어와 무관한 PropertyType을 먼저 사용하고, 없을 때 한글/영문 항목명을 찾습니다.
|
||||||
|
properties = [p for n in nodes for p in n["properties"]]
|
||||||
|
for kind in types:
|
||||||
|
for p in properties:
|
||||||
|
if p["type"] == kind and p["value"]:
|
||||||
|
return p["value"]
|
||||||
|
for label in labels:
|
||||||
|
for p in properties:
|
||||||
|
if p["label"].casefold() == label.casefold() and p["value"]:
|
||||||
|
return p["value"]
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def parse_hwinfo(raw: bytes) -> dict:
|
||||||
|
if not raw or len(raw) > MAX_REPORT_BYTES:
|
||||||
|
raise ValueError("XML 보고서는 비어 있지 않은 10 MB 이하 파일이어야 합니다.")
|
||||||
|
try:
|
||||||
|
# HWiNFO의 DTD 선언은 허용하되 파일을 읽지 않습니다. 엔티티는 모두 차단합니다.
|
||||||
|
root = fromstring(raw, forbid_dtd=False, forbid_entities=True, forbid_external=True)
|
||||||
|
except (ParseError, DefusedXmlException, ValueError, LookupError) as exc:
|
||||||
|
raise ValueError("XML을 읽을 수 없습니다. HWiNFO XML 보고서인지 확인하세요.") from exc
|
||||||
|
if root.tag != "HWINFO" or len(root.findall("COMPUTER")) != 1:
|
||||||
|
raise ValueError("컴퓨터 한 대의 HWiNFO XML 보고서만 업로드할 수 있습니다.")
|
||||||
|
computer = root.find("COMPUTER")
|
||||||
|
sections = [{"key": "SYSTEM", "label": "시스템", "nodes": []}]
|
||||||
|
count = 0
|
||||||
|
|
||||||
|
def walk(node, path, result, depth=0):
|
||||||
|
nonlocal count
|
||||||
|
count += 1
|
||||||
|
if count > 30000 or depth > 64:
|
||||||
|
raise ValueError("보고서 구조가 너무 크거나 깊습니다.")
|
||||||
|
name = _text(node, "NodeName")
|
||||||
|
trail = path + ([name] if name else [])
|
||||||
|
props = _props(node)
|
||||||
|
if props:
|
||||||
|
result.append({"name": name or node.tag, "path": " › ".join(trail), "properties": props})
|
||||||
|
for child in node:
|
||||||
|
if child.tag in {"SubNodes", "SubNode"}:
|
||||||
|
walk(child, trail, result, depth + 1)
|
||||||
|
elif child.find("NodeName") is not None:
|
||||||
|
walk(child, trail, result, depth + 1)
|
||||||
|
|
||||||
|
sections[0]["nodes"] = [{"name": _text(computer, "NodeName") or "컴퓨터",
|
||||||
|
"path": "시스템", "properties": _props(computer)}]
|
||||||
|
subnodes = computer.find("SubNodes")
|
||||||
|
if subnodes is not None:
|
||||||
|
for node in subnodes:
|
||||||
|
group = {"key": node.tag, "label": SECTION_LABELS.get(node.tag, _text(node, "NodeName") or node.tag), "nodes": []}
|
||||||
|
walk(node, [], group["nodes"])
|
||||||
|
sections.append(group)
|
||||||
|
by_key = {s["key"]: s["nodes"] for s in sections}
|
||||||
|
get = lambda key, **kw: _pick(by_key.get(key, []), **kw)
|
||||||
|
summary = {
|
||||||
|
"computer_name": _text(computer, "NodeName") or get("SYSTEM", labels=("컴퓨터 이름", "Computer Name")),
|
||||||
|
"os": get("SYSTEM", labels=("운영 체제", "Operating System")),
|
||||||
|
"manufacturer": get("SYSTEM", labels=("컴퓨터 브랜드", "Computer Brand Name")),
|
||||||
|
"cpu": get("CPU", types=("CPU_NAME",), labels=("프로세서 이름", "Processor Name")),
|
||||||
|
"cores": get("CPU", labels=("프로세서 코어 수", "CPU 코어 수", "Number of CPU Cores", "Number of Processor Cores")),
|
||||||
|
"threads": get("CPU", labels=("논리 프로세서 수", "논리 CPU 수", "Number of Logical CPUs", "Number of Logical Processors")),
|
||||||
|
"motherboard": get("MOBO", types=("SYSTEM_MAINBOARD",)),
|
||||||
|
"bios": get("MOBO", labels=("BIOS 버전", "BIOS Version")),
|
||||||
|
"memory": get("MEMORY", labels=("총 메모리 크기", "Total Memory Size")),
|
||||||
|
"gpu": get("VIDEO", types=("GFXCARD_CHIPSET", "GFXCARD")),
|
||||||
|
"gpu_memory": get("VIDEO", labels=("그래픽 메모리", "Video Memory", "Video Memory Size")),
|
||||||
|
"serial": get("MOBO", labels=("제품 일련 번호", "Product Serial Number", "System Serial Number")),
|
||||||
|
}
|
||||||
|
if summary["serial"].casefold() in {"system serial number", "to be filled by o.e.m.", "default string", "none", "n/a"}:
|
||||||
|
summary["serial"] = ""
|
||||||
|
if not summary["memory"]:
|
||||||
|
mb = get("MEMORY", types=("SYSTEM_MEMORY",))
|
||||||
|
if re.fullmatch(r"\d+(\.\d+)?", mb):
|
||||||
|
summary["memory"] = f"{float(mb) / 1024:g} GiB"
|
||||||
|
devices = {}
|
||||||
|
for key, types, labels in [
|
||||||
|
("DRIVES", ("HDD",), ("드라이브 모델", "Drive Model")),
|
||||||
|
("MEMORY", (), ("모듈 부품 번호", "Module Part Number")),
|
||||||
|
("MONITOR", ("MONITOR",), ("모니터 이름", "Monitor Name")),
|
||||||
|
("NETWORK", ("NETCARD",), ("네트워크 카드", "Network Card")),
|
||||||
|
("VIDEO", ("GFXCARD_CHIPSET", "GFXCARD"), ("그래픽 프로세서", "Video Chipset")),
|
||||||
|
]:
|
||||||
|
devices[key] = []
|
||||||
|
for node in by_key.get(key, []):
|
||||||
|
model = _pick([node], types=types, labels=labels)
|
||||||
|
if model:
|
||||||
|
devices[key].append({"name": model, "node": node["name"], "properties": node["properties"]})
|
||||||
|
summary["drive_count"] = len(devices["DRIVES"])
|
||||||
|
summary["monitor_count"] = len(devices["MONITOR"])
|
||||||
|
if not summary["computer_name"] or not any(summary[k] for k in ("cpu", "motherboard", "memory", "gpu")):
|
||||||
|
raise ValueError("컴퓨터 이름과 하드웨어 사양이 포함된 HWiNFO 보고서가 필요합니다.")
|
||||||
|
scan_time = _text(computer, "ScanTime")
|
||||||
|
try:
|
||||||
|
scan_time = datetime.strptime(scan_time, "%d.%m.%Y %H:%M").isoformat(timespec="minutes")
|
||||||
|
except ValueError:
|
||||||
|
pass # 날짜 형식이 다르면 원래 보고서에 적힌 시각을 그대로 보존합니다.
|
||||||
|
warnings = [p["value"] for p in _props(computer) if p["label"] in ("가상 머신 경고", "Virtual Machine Warning") and p["value"]]
|
||||||
|
return {"summary": summary, "sections": sections, "devices": devices, "scan_time": scan_time,
|
||||||
|
"warnings": warnings, "sha256": hashlib.sha256(raw).hexdigest(),
|
||||||
|
"property_count": sum(len(n["properties"]) for s in sections for n in s["nodes"])}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""사진을 실제 이미지로 확인하고 위치 정보 등 메타데이터를 제거합니다."""
|
||||||
|
import io
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||||
|
|
||||||
|
MAX_PHOTO_BYTES = 8 * 1024 * 1024
|
||||||
|
MAX_STORED_BYTES = 5 * 1024 * 1024
|
||||||
|
MAX_PHOTOS = 10
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_photo(raw):
|
||||||
|
if not raw or len(raw) > MAX_PHOTO_BYTES:
|
||||||
|
raise ValueError("사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.")
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||||
|
with Image.open(io.BytesIO(raw)) as source:
|
||||||
|
if source.format not in {"JPEG", "PNG", "WEBP"}:
|
||||||
|
raise ValueError("JPG, PNG, WebP 사진만 등록할 수 있습니다.")
|
||||||
|
if source.width * source.height > 20_000_000:
|
||||||
|
raise ValueError("사진은 2천만 화소 이하로 등록하세요.")
|
||||||
|
source.load()
|
||||||
|
image = ImageOps.exif_transpose(source)
|
||||||
|
image.thumbnail((2400, 2400))
|
||||||
|
transparent = "A" in image.getbands() or "transparency" in image.info
|
||||||
|
mode = "RGBA" if transparent else "RGB"
|
||||||
|
# 새 캔버스에 복사해 EXIF, GPS, 촬영기기 정보를 저장하지 않습니다.
|
||||||
|
clean = Image.new(mode, image.size)
|
||||||
|
clean.paste(image.convert(mode))
|
||||||
|
output = io.BytesIO()
|
||||||
|
clean.save(output, format="PNG" if transparent else "JPEG", **({} if transparent else {"quality": 88}))
|
||||||
|
data = output.getvalue()
|
||||||
|
if len(data) > MAX_STORED_BYTES:
|
||||||
|
raise ValueError("사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.")
|
||||||
|
return data, "image/png" if transparent else "image/jpeg", clean.width, clean.height
|
||||||
|
except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||||
|
raise ValueError("사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.") from exc
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""이전 보고서에도 적용할 수 있도록 저장된 모니터 항목에서 식별 정보를 읽습니다."""
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
|
def usable_serial(value):
|
||||||
|
value = value.strip()
|
||||||
|
if value.casefold() in {"", "unknown", "n/a", "none", "not specified", "serial number", "알 수 없음"}:
|
||||||
|
return ""
|
||||||
|
if re.fullmatch(r"[0\s-]+", value):
|
||||||
|
return ""
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def compatible_monitor(asset, device):
|
||||||
|
"""다른 제조사나 다른 모델이 같은 시리얼을 쓰면 자동 연결하지 않습니다."""
|
||||||
|
def normalized(value):
|
||||||
|
return "".join(c for c in value.casefold() if c.isalnum())
|
||||||
|
brand = normalized(asset.get("manufacturer", ""))
|
||||||
|
reported_brand = normalized(device["manufacturer"])
|
||||||
|
if brand and reported_brand and brand != reported_brand:
|
||||||
|
return False
|
||||||
|
model = normalized(asset.get("model", ""))
|
||||||
|
if not model:
|
||||||
|
return True
|
||||||
|
return any(model == value or len(model) >= 4 and model in value
|
||||||
|
for value in (normalized(device["model"]), normalized(device["name"])))
|
||||||
|
|
||||||
|
|
||||||
|
def monitor_devices(parsed):
|
||||||
|
devices = []
|
||||||
|
for index, item in enumerate(parsed.get("devices", {}).get("MONITOR", [])):
|
||||||
|
props = item.get("properties", [])
|
||||||
|
def pick(*labels, kind=""):
|
||||||
|
return next((p["value"].strip() for p in props if p.get("label", "").casefold() in
|
||||||
|
{label.casefold() for label in labels} or kind and p.get("type") == kind), "")
|
||||||
|
name = item.get("name", "모니터")
|
||||||
|
model = pick("모니터 이름(제조업체)", "Monitor Name (Manuf)", "Monitor Name (Manufacturer)") or name
|
||||||
|
serial = usable_serial(pick("일련 번호", "Serial Number", "Monitor Serial Number"))
|
||||||
|
instance = pick("디바이스 인스턴스 ID", "Device Instance ID", kind="DeviceInstanceId")
|
||||||
|
# 시리얼이 없는 장치는 모델명만으로 동일 자산이라고 판단하지 않습니다.
|
||||||
|
identity = ("serial:" + serial.casefold() + ":" + model.casefold()) if serial else (
|
||||||
|
"instance:" + instance.casefold() if instance else f"report:{parsed.get('sha256', '')}:{index}")
|
||||||
|
devices.append({"index": index, "key": hashlib.sha256(identity.encode()).hexdigest(),
|
||||||
|
"name": name, "model": model[:200], "serial": serial[:200],
|
||||||
|
"manufacturer": name.split(" ", 1)[0][:150], "properties": props})
|
||||||
|
return devices
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
# 화면, 권한 검사, 파일 업로드를 담당합니다. 실제 저장은 db.py에서 처리합니다.
|
||||||
|
|
||||||
|
import io
|
||||||
|
import secrets
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from typing import Annotated
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
|
||||||
|
from fastapi.responses import RedirectResponse, Response
|
||||||
|
from openpyxl import Workbook
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from psycopg import Error as DBError
|
||||||
|
from psycopg.errors import UniqueViolation
|
||||||
|
from psycopg_pool import PoolTimeout
|
||||||
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
|
from .hwinfo import MAX_REPORT_BYTES, parse_hwinfo
|
||||||
|
from .store import ActionInput, AssetConflict, AssetInput, AssetUpdate, CATEGORIES, STATUSES
|
||||||
|
from .store import DeleteInput, MonitorInput
|
||||||
|
from .media import MAX_PHOTO_BYTES, prepare_photo
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/asset", tags=["asset"])
|
||||||
|
|
||||||
|
|
||||||
|
def _user(request: Request):
|
||||||
|
from app.main import get_current_user_record
|
||||||
|
from app.store import has_module
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(401, "로그인이 필요합니다.")
|
||||||
|
if not has_module(user, "asset"):
|
||||||
|
raise HTTPException(403, "자산관리 권한이 없습니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _write(request: Request, user=Depends(_user)):
|
||||||
|
expected = request.session.get("asset_csrf", "")
|
||||||
|
token = request.headers.get("x-asset-csrf", "")
|
||||||
|
if not expected or not secrets.compare_digest(expected, token):
|
||||||
|
raise HTTPException(403, "화면을 새로 열고 다시 시도하세요.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _super(user):
|
||||||
|
from app.store import SUPER_ADMIN_EMAIL
|
||||||
|
return user.get("email", "").lower() == SUPER_ADMIN_EMAIL
|
||||||
|
|
||||||
|
|
||||||
|
def _super_write(user=Depends(_write)):
|
||||||
|
if not _super(user):
|
||||||
|
raise HTTPException(403, "수퍼 관리자만 자산을 삭제할 수 있습니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _store(request):
|
||||||
|
store = getattr(request.app.state, "asset_store", None)
|
||||||
|
if store is None:
|
||||||
|
raise HTTPException(503, "자산관리 DB 설정이 필요합니다. 관리자에게 문의하세요.")
|
||||||
|
return store
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _errors():
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
except AssetConflict as exc:
|
||||||
|
raise HTTPException(409, str(exc)) from exc
|
||||||
|
except KeyError as exc:
|
||||||
|
raise HTTPException(404, "자산 또는 보고서를 찾을 수 없습니다.") from exc
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(422, str(exc)) from exc
|
||||||
|
except UniqueViolation as exc:
|
||||||
|
raise HTTPException(409, "이미 등록된 자산번호입니다. 다른 번호를 사용하세요.") from exc
|
||||||
|
except (DBError, PoolTimeout) as exc:
|
||||||
|
# DB 오류에 접속 비밀번호가 섞일 수 있어 원문 대신 일반 안내만 보여줍니다.
|
||||||
|
raise HTTPException(503, "자산관리 DB에 연결할 수 없습니다. 설정과 초기화를 확인하세요.") from exc
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/")
|
||||||
|
def index(request: Request):
|
||||||
|
from app.main import build_erp_nav, get_current_user_record, render_template
|
||||||
|
from app.store import has_module, is_admin
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if not user:
|
||||||
|
return RedirectResponse("/login", 303)
|
||||||
|
if not has_module(user, "asset"):
|
||||||
|
return render_template(request, "denied.html", {"reason": "자산관리 권한이 없습니다.", "user": user,
|
||||||
|
"is_admin": is_admin(user)}, status_code=403)
|
||||||
|
request.session.setdefault("asset_csrf", secrets.token_urlsafe(32))
|
||||||
|
return render_template(request, "asset/index.html", {
|
||||||
|
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="asset"),
|
||||||
|
"page_title": "자산관리", "page_subtitle": "사무집기부터 컴퓨터 사양까지, 회사 자산을 한곳에서",
|
||||||
|
"categories": CATEGORIES, "statuses": STATUSES, "csrf_token": request.session["asset_csrf"],
|
||||||
|
"configured": getattr(request.app.state, "asset_store", None) is not None,
|
||||||
|
"can_delete": _super(user),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def health(request: Request, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
_store(request).health()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/bootstrap")
|
||||||
|
def bootstrap(request: Request, user=Depends(_user)):
|
||||||
|
from app.main import user_store
|
||||||
|
with _errors():
|
||||||
|
data = _store(request).dashboard()
|
||||||
|
data["users"] = [{"email": u["email"], "name": u.get("name") or u["email"]} for u in user_store.list_all()]
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _query(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||||
|
if category and category not in CATEGORIES or status and status not in STATUSES:
|
||||||
|
raise HTTPException(422, "분류 또는 상태 필터가 올바르지 않습니다.")
|
||||||
|
if group not in {"", "computer", "furniture"}:
|
||||||
|
raise HTTPException(422, "자산 구분 필터가 올바르지 않습니다.")
|
||||||
|
return dict(q=q, category=category, status=status, location=location, assignee=assignee, warranty=warranty, group=group)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets")
|
||||||
|
def assets(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||||
|
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||||
|
page: int = Query(1, ge=1, le=100000), page_size: int = Query(25, ge=1, le=100),
|
||||||
|
sort: str = "updated", group: str = "", user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return _store(request).list_assets(page=page, page_size=page_size, sort=sort,
|
||||||
|
**_query(q, category, status, location, assignee, warranty, group))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/export")
|
||||||
|
def export(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||||
|
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||||
|
group: str = "", user=Depends(_user)):
|
||||||
|
from app.timezone import today_kst
|
||||||
|
with _errors():
|
||||||
|
data = _store(request).list_assets(page=1, page_size=10001, **_query(q, category, status, location, assignee, warranty, group))
|
||||||
|
if data["total"] > 10000:
|
||||||
|
raise HTTPException(422, "한 번에 10,000개까지 내보낼 수 있습니다. 필터를 좁혀주세요.")
|
||||||
|
book = Workbook()
|
||||||
|
sheet = book.active
|
||||||
|
sheet.title = "자산대장"
|
||||||
|
headers = ["자산번호", "자산명", "분류", "상태", "제조사", "모델", "시리얼", "위치", "부서", "사용자", "구매일", "구매금액(원)", "구매처", "보증종료", "메모", "CPU", "메모리", "GPU", "운영체제"]
|
||||||
|
sheet.append(headers)
|
||||||
|
for row in data["items"]:
|
||||||
|
specs = row.get("specs") or {}
|
||||||
|
values = [row["tag"], row["name"], CATEGORIES[row["category"]], STATUSES[row["status"]],
|
||||||
|
*[row[k] for k in ("manufacturer", "model", "serial", "location", "department", "assignee_email", "purchased_on")],
|
||||||
|
float(row["purchase_cost"]) if row["purchase_cost"] is not None else None,
|
||||||
|
row["vendor"], row["warranty_until"], row["notes"], *[specs.get(k, "") for k in ("cpu", "memory", "gpu", "os")]]
|
||||||
|
sheet.append(values)
|
||||||
|
# =로 시작하는 자산명도 엑셀 수식 대신 일반 글자로 저장합니다.
|
||||||
|
for cell in sheet[sheet.max_row]:
|
||||||
|
if isinstance(cell.value, str):
|
||||||
|
cell.data_type = "s"
|
||||||
|
sheet.freeze_panes = "C2"
|
||||||
|
sheet.auto_filter.ref = sheet.dimensions
|
||||||
|
from openpyxl.styles import Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
for cell in sheet[1]:
|
||||||
|
cell.font = Font(bold=True, color="FFFFFF")
|
||||||
|
cell.fill = PatternFill("solid", fgColor="171717")
|
||||||
|
for i in range(1, len(headers) + 1):
|
||||||
|
sheet.column_dimensions[get_column_letter(i)].width = 22 if i > 2 else 28
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
book.save(buffer)
|
||||||
|
return Response(buffer.getvalue(), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="assets-{today_kst().isoformat()}.xlsx"'})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets")
|
||||||
|
def create(request: Request, payload: AssetInput, user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
asset_id = _store(request).create(payload, user["email"])
|
||||||
|
return {"id": asset_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}")
|
||||||
|
def detail(request: Request, asset_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return _store(request).detail(asset_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/assets/{asset_id}")
|
||||||
|
def update(request: Request, asset_id: str, payload: AssetUpdate, user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
_store(request).update(asset_id, payload, user["email"])
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/assets/{asset_id}")
|
||||||
|
def delete(request: Request, asset_id: str, payload: DeleteInput, user=Depends(_super_write)):
|
||||||
|
with _errors():
|
||||||
|
_store(request).delete(asset_id, payload.version, user["email"], payload.note)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/photos")
|
||||||
|
async def add_photo(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||||
|
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||||
|
filename = (file.filename or "photo.jpg").replace("\\", "/").rsplit("/", 1)[-1]
|
||||||
|
try:
|
||||||
|
if len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||||
|
raise HTTPException(422, "사진 파일 이름을 확인하세요.")
|
||||||
|
raw = await file.read(MAX_PHOTO_BYTES + 1)
|
||||||
|
finally:
|
||||||
|
await file.close()
|
||||||
|
with _errors():
|
||||||
|
image, mime, width, height = await run_in_threadpool(prepare_photo, raw)
|
||||||
|
photo_id = await run_in_threadpool(_store(request).add_photo, asset_id, version, user["email"], filename, image, mime, width, height)
|
||||||
|
return {"id": photo_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/photos/{photo_id}")
|
||||||
|
def photo(request: Request, asset_id: str, photo_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
row = _store(request).photo(asset_id, photo_id)
|
||||||
|
return Response(bytes(row["image"]), media_type=row["mime"],
|
||||||
|
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/reports/{report_id}/monitors")
|
||||||
|
def report_monitors(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return {"items": _store(request).report_monitors(asset_id, report_id)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/monitors/{index}")
|
||||||
|
def register_monitor(request: Request, asset_id: str, index: int, payload: MonitorInput, user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
monitor_id = _store(request).register_monitor(asset_id, index, payload, user["email"])
|
||||||
|
return {"id": monitor_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/actions")
|
||||||
|
def action(request: Request, asset_id: str, payload: ActionInput, user=Depends(_write)):
|
||||||
|
from app.main import user_store
|
||||||
|
if payload.action == "checkout" and not user_store.get(payload.assignee_email.lower()):
|
||||||
|
raise HTTPException(422, "등록된 회사 사용자를 선택하세요.")
|
||||||
|
with _errors():
|
||||||
|
_store(request).action(asset_id, payload, user["email"])
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
async def _report_file(file):
|
||||||
|
filename = (file.filename or "report.xml").replace("\\", "/").rsplit("/", 1)[-1]
|
||||||
|
if not filename.lower().endswith(".xml") or len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||||
|
raise HTTPException(422, "이름이 200자 이하인 XML 보고서를 선택하세요.")
|
||||||
|
try:
|
||||||
|
raw = await file.read(MAX_REPORT_BYTES + 1)
|
||||||
|
finally:
|
||||||
|
await file.close()
|
||||||
|
with _errors():
|
||||||
|
parsed = await run_in_threadpool(parse_hwinfo, raw)
|
||||||
|
return filename, raw, parsed
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/reports/preview")
|
||||||
|
async def preview(file: Annotated[UploadFile, File()], user=Depends(_write)):
|
||||||
|
filename, raw, parsed = await _report_file(file)
|
||||||
|
return {"filename": filename, "summary": parsed["summary"], "scan_time": parsed["scan_time"],
|
||||||
|
"property_count": parsed["property_count"], "warnings": parsed["warnings"]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/reports/import")
|
||||||
|
async def import_report(request: Request, file: Annotated[UploadFile, File()], payload: Annotated[str, Form(max_length=20000)], user=Depends(_write)):
|
||||||
|
with _errors():
|
||||||
|
try:
|
||||||
|
data = AssetInput.model_validate_json(payload)
|
||||||
|
except ValidationError as exc:
|
||||||
|
raise HTTPException(422, "자산명·분류·구매일·금액을 확인하세요.") from exc
|
||||||
|
report = await _report_file(file)
|
||||||
|
with _errors():
|
||||||
|
asset_id = await run_in_threadpool(_store(request).create, data, user["email"], report)
|
||||||
|
return {"id": asset_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/assets/{asset_id}/reports")
|
||||||
|
async def attach(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||||
|
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||||
|
filename, raw, parsed = await _report_file(file)
|
||||||
|
with _errors():
|
||||||
|
report_id = await run_in_threadpool(_store(request).attach_report, asset_id, version, user["email"], filename, raw, parsed)
|
||||||
|
return {"id": report_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/reports/{report_id}")
|
||||||
|
def report_detail(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
return _store(request).report(asset_id, report_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/assets/{asset_id}/reports/{report_id}/download")
|
||||||
|
def download(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||||
|
with _errors():
|
||||||
|
row = _store(request).report(asset_id, report_id, raw=True)
|
||||||
|
return Response(bytes(row["raw_xml"]), media_type="application/octet-stream",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename=hwinfo.xml; filename*=UTF-8''{quote(row['filename'], safe='')}",
|
||||||
|
"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""Asset validation and lifecycle rules, shared by API and storage."""
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||||
|
|
||||||
|
CATEGORIES = {"computer": "컴퓨터", "monitor": "모니터", "mouse": "마우스", "keyboard": "키보드",
|
||||||
|
"camera": "카메라", "hub": "허브 · 네트워크", "lighting": "조명", "desk": "책상",
|
||||||
|
"chair": "의자", "furniture": "기타 사무집기", "equipment": "기타 전산장비"}
|
||||||
|
STATUSES = {"available": "사용 가능", "in_use": "사용 중", "maintenance": "수리 중", "lost": "분실", "retired": "폐기"}
|
||||||
|
|
||||||
|
|
||||||
|
class AssetInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
tag: str = Field(default="", max_length=64)
|
||||||
|
name: str = Field(min_length=1, max_length=200)
|
||||||
|
category: str
|
||||||
|
manufacturer: str = Field(default="", max_length=150)
|
||||||
|
model: str = Field(default="", max_length=200)
|
||||||
|
serial: str = Field(default="", max_length=200)
|
||||||
|
location: str = Field(default="", max_length=150)
|
||||||
|
department: str = Field(default="", max_length=100)
|
||||||
|
purchased_on: date | None = None
|
||||||
|
purchase_cost: Decimal | None = Field(default=None, ge=0, le=10**12, decimal_places=2)
|
||||||
|
vendor: str = Field(default="", max_length=200)
|
||||||
|
warranty_until: date | None = None
|
||||||
|
notes: str = Field(default="", max_length=10000)
|
||||||
|
|
||||||
|
@field_validator("category")
|
||||||
|
@classmethod
|
||||||
|
def valid_category(cls, value):
|
||||||
|
if value not in CATEGORIES:
|
||||||
|
raise ValueError("자산 분류가 올바르지 않습니다.")
|
||||||
|
return value
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def valid_dates(self):
|
||||||
|
if self.purchased_on and self.warranty_until and self.warranty_until < self.purchased_on:
|
||||||
|
raise ValueError("보증 종료일은 구매일 이후여야 합니다.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class AssetUpdate(AssetInput):
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
|
||||||
|
|
||||||
|
class DeleteInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
note: str = Field(min_length=1, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
class MonitorInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
report_id: str = Field(min_length=1, max_length=64)
|
||||||
|
asset: AssetInput | None = None
|
||||||
|
asset_id: str = Field(default="", max_length=64)
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def require_target(self):
|
||||||
|
if bool(self.asset) == bool(self.asset_id):
|
||||||
|
raise ValueError("등록할 정보 또는 연결할 모니터 자산 중 하나를 지정하세요.")
|
||||||
|
if self.asset and self.asset.category != "monitor":
|
||||||
|
raise ValueError("모니터 분류로 등록하세요.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class ActionInput(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||||
|
version: int = Field(ge=1)
|
||||||
|
action: str
|
||||||
|
assignee_email: str = Field(default="", max_length=254)
|
||||||
|
location: str = Field(default="", max_length=150)
|
||||||
|
note: str = Field(default="", max_length=2000)
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def require_reason(self):
|
||||||
|
if self.action in {"lost", "retired"} and not self.note:
|
||||||
|
raise ValueError("분실·폐기 사유를 입력하세요.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class AssetConflict(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def transition(asset, payload: ActionInput):
|
||||||
|
state = asset["status"]
|
||||||
|
if payload.action == "checkout":
|
||||||
|
if state != "available" or not payload.assignee_email:
|
||||||
|
raise ValueError("사용 가능한 자산을 선택하고 배정할 사용자를 지정하세요.")
|
||||||
|
return "in_use", payload.assignee_email.lower()
|
||||||
|
if payload.action == "checkin":
|
||||||
|
if state != "in_use":
|
||||||
|
raise ValueError("사용 중인 자산만 반납할 수 있습니다.")
|
||||||
|
return "available", ""
|
||||||
|
if payload.action == "maintenance" and state == "available":
|
||||||
|
return "maintenance", ""
|
||||||
|
if payload.action == "available" and state in {"maintenance", "lost", "retired"}:
|
||||||
|
return "available", ""
|
||||||
|
if payload.action == "lost" and state in {"available", "in_use", "maintenance"}:
|
||||||
|
return "lost", asset.get("assignee_email", "")
|
||||||
|
if payload.action == "retired" and state in {"available", "maintenance", "lost"}:
|
||||||
|
return "retired", ""
|
||||||
|
raise ValueError("현재 상태에서 처리할 수 없습니다. 배정된 자산은 먼저 반납하세요.")
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% set force_sidebar_collapsed = true %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/asset.css?v=20261006c">{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<div id="asset-app" class="am-workspace" data-csrf="{{ csrf_token }}" data-configured="{{ 'true' if configured else 'false' }}" data-can-delete="{{ 'true' if can_delete else 'false' }}">
|
||||||
|
<aside class="am-nav" aria-label="자산관리 탐색">
|
||||||
|
<div class="am-nav-brand"><span class="am-mark">A</span><div><strong>회사 자산</strong><small>ASSET MANAGEMENT</small></div></div>
|
||||||
|
<button class="am-nav-link is-active" data-view="all"><span>전체 자산</span><span id="am-nav-total" class="am-count">—</span></button>
|
||||||
|
<button class="am-nav-link" data-view="computer"><span>컴퓨터 · 전산장비</span></button>
|
||||||
|
<button class="am-nav-link" data-view="furniture"><span>사무실 · 집기</span></button>
|
||||||
|
<p class="am-nav-label">자산 상태</p>
|
||||||
|
{% for key,label in statuses.items() %}<button class="am-nav-link" data-state="{{ key }}"><span><i class="am-dot am-dot-{{ key }}"></i>{{ label }}</span><span class="am-count" id="am-count-{{ key }}">—</span></button>{% endfor %}
|
||||||
|
<p class="am-nav-label">확인할 항목</p>
|
||||||
|
<button class="am-nav-link" data-view="warranty"><span>보증 만료 예정</span><span class="am-count" id="am-count-warranty">—</span></button>
|
||||||
|
<div class="am-nav-foot"><strong>자산 한 개, 기록 하나</strong><p>개별 자산번호로 등록하고<br>배정부터 폐기까지 추적하세요.</p><button class="am-text-btn" id="am-help-open">사용 안내 ↗</button></div>
|
||||||
|
</aside>
|
||||||
|
<section class="am-main" aria-label="자산대장">
|
||||||
|
<div class="am-heading"><div><p class="am-eyebrow">COMPANY INVENTORY</p><h2>회사 자산 대장</h2><p>어떤 자산이, 어디에, 누구에게 있는지 확인하세요.</p></div><div class="am-heading-actions"><button class="erp-btn erp-btn-outline" id="am-import">↑ HWiNFO 보고서</button><button class="erp-btn erp-btn-primary" id="am-create" {% if not configured %}disabled{% endif %}>+ 자산 등록</button></div></div>
|
||||||
|
{% if not configured %}<div class="am-notice" role="status"><strong>자산관리 저장소 설정이 필요합니다.</strong><p>관리자가 자산관리 DB를 연결하면 등록·배정·반납을 사용할 수 있습니다. HWiNFO 보고서는 지금도 분석 결과를 미리 볼 수 있습니다.</p></div>{% endif %}
|
||||||
|
<div id="am-message" class="am-message" role="status" aria-live="polite" hidden></div>
|
||||||
|
<div class="am-kpis" aria-label="자산 현황">
|
||||||
|
<button data-kpi="all" class="am-kpi"><span>전체 자산</span><strong id="am-total">—</strong><small>회사에 등록된 자산</small></button>
|
||||||
|
<button data-kpi="in_use" class="am-kpi"><span><i class="am-dot am-dot-in_use"></i>사용 중</span><strong id="am-in_use">—</strong><small>직원에게 배정된 자산</small></button>
|
||||||
|
<button data-kpi="available" class="am-kpi"><span><i class="am-dot am-dot-available"></i>사용 가능</span><strong id="am-available">—</strong><small>새로 배정할 수 있는 자산</small></button>
|
||||||
|
<button data-kpi="maintenance" class="am-kpi"><span><i class="am-dot am-dot-maintenance"></i>수리 중</span><strong id="am-maintenance">—</strong><small>점검 · 수리 중인 자산</small></button>
|
||||||
|
<button data-kpi="warranty" class="am-kpi"><span>보증 만료 예정</span><strong id="am-warranty_soon">—</strong><small>오늘부터 30일 이내</small></button>
|
||||||
|
</div>
|
||||||
|
<div class="am-register">
|
||||||
|
<div class="am-register-head"><div><h3 id="am-list-title">전체 자산</h3><span id="am-result-count">자산을 불러오는 중</span></div><div><button class="am-text-btn" id="am-refresh" aria-label="자산 새로고침">↻ 새로고침</button><button class="erp-btn erp-btn-outline" id="am-export" {% if not configured %}disabled{% endif %}>엑셀 내보내기 ↓</button></div></div>
|
||||||
|
<form class="am-filters" id="am-filters" role="search">
|
||||||
|
<label class="am-search"><span aria-hidden="true">⌕</span><input id="am-query" type="search" maxlength="200" placeholder="자산명, 번호, 모델, 시리얼 검색" aria-label="자산 검색"></label>
|
||||||
|
<select id="am-category" aria-label="분류"><option value="">모든 분류</option>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||||
|
<select id="am-status" aria-label="상태"><option value="">모든 상태</option>{% for key,label in statuses.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||||
|
<select id="am-location" aria-label="위치"><option value="">모든 위치</option></select>
|
||||||
|
<select id="am-assignee" aria-label="배정 사용자"><option value="">모든 사용자</option></select>
|
||||||
|
<select id="am-sort" aria-label="정렬"><option value="updated">최근 변경순</option><option value="name">자산명순</option><option value="tag">자산번호순</option><option value="cost">구매금액순</option><option value="warranty">보증종료순</option></select>
|
||||||
|
<button type="button" class="am-text-btn" id="am-reset">초기화</button>
|
||||||
|
</form>
|
||||||
|
<div class="am-table-scroll"><table class="am-table"><thead><tr><th>자산</th><th>분류</th><th>상태</th><th>사용자 / 위치</th><th>구매금액</th><th>보증 종료</th><th>사양</th></tr></thead><tbody id="am-rows"><tr><td colspan="7" class="am-empty">{% if configured %}자산을 불러오는 중입니다.{% else %}등록된 자산이 여기에 표시됩니다.{% endif %}</td></tr></tbody></table></div>
|
||||||
|
<div class="am-pagination"><span id="am-page-info">—</span><div><button class="erp-btn erp-btn-outline" id="am-prev" disabled>← 이전</button><span id="am-page-number">1</span><button class="erp-btn erp-btn-outline" id="am-next" disabled>다음 →</button></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="am-bottom"><section class="am-panel"><div class="am-panel-head"><h3>자산 구성</h3><span>분류별 등록 수</span></div><div id="am-breakdown" class="am-breakdown"><p class="am-muted">등록된 자산이 없습니다.</p></div><div class="am-value"><span>보유 자산 구매금액 <small>폐기 제외 · 입력된 금액 기준</small></span><strong id="am-value">—</strong></div></section><section class="am-panel"><div class="am-panel-head"><h3>최근 활동</h3><span>등록 · 배정 · 반납 · 변경</span></div><div id="am-activity" class="am-activity"><p class="am-muted">활동 이력이 여기에 표시됩니다.</p></div></section></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<dialog id="am-detail" class="am-drawer" aria-labelledby="am-detail-title"><div class="am-dialog-head"><div><small id="am-detail-tag">자산 상세</small><h2 id="am-detail-title">자산 정보</h2></div><button type="button" class="am-close" data-close="am-detail" aria-label="자산 상세 닫기">×</button></div><div id="am-detail-content"></div></dialog>
|
||||||
|
<dialog id="am-editor" class="am-dialog" aria-labelledby="am-editor-title"><div class="am-dialog-head"><div><small>ASSET REGISTER</small><h2 id="am-editor-title">자산 등록</h2></div><button type="button" class="am-close" data-close="am-editor" aria-label="등록 창 닫기">×</button></div><form id="am-editor-form" class="am-form"><div class="am-form-grid">
|
||||||
|
<label>자산명 <span>*</span><input name="name" maxlength="200" required placeholder="예: 디자인팀 데스크톱"></label>
|
||||||
|
<label>자산번호<input name="tag" maxlength="64" placeholder="비워두면 자동 발급 (AST-000001)"></label>
|
||||||
|
<label>분류 <span>*</span><select name="category" required>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label>
|
||||||
|
<label>제조사<input name="manufacturer" maxlength="150" placeholder="예: Dell, 시디즈"></label>
|
||||||
|
<label>모델<input name="model" maxlength="200"></label><label>시리얼 번호<input name="serial" maxlength="200"></label>
|
||||||
|
<label>위치<input name="location" maxlength="150" list="am-locations" placeholder="예: 본사 3층 디자인팀"></label><label>부서<input name="department" maxlength="100"></label>
|
||||||
|
<label>구매일<input type="date" name="purchased_on"></label><label>구매금액 (원)<input type="number" name="purchase_cost" min="0" max="1000000000000" step="0.01" placeholder="미입력 가능"></label>
|
||||||
|
<label>구매처<input name="vendor" maxlength="200"></label><label>보증 종료일<input type="date" name="warranty_until"></label>
|
||||||
|
<label class="am-wide">메모<textarea name="notes" maxlength="10000" rows="3" placeholder="관리에 필요한 추가 정보를 입력하세요."></textarea></label>
|
||||||
|
</div><p class="am-form-hint">같은 모델도 자산번호를 각각 발급합니다. 사용자 배정은 등록 후 상세 화면에서 진행합니다.</p><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-editor">취소</button><button type="submit" class="erp-btn erp-btn-primary">자산 저장</button></div></form></dialog>
|
||||||
|
<dialog id="am-upload" class="am-dialog am-upload-dialog" aria-labelledby="am-upload-title"><div class="am-dialog-head"><div><small>HWiNFO XML IMPORT</small><h2 id="am-upload-title">컴퓨터 보고서 가져오기</h2></div><button type="button" class="am-close" data-close="am-upload" aria-label="업로드 창 닫기">×</button></div><form id="am-upload-form" class="am-form">
|
||||||
|
<p class="am-form-hint" id="am-upload-hint">HWiNFO에서 저장한 XML 보고서를 선택하세요. 사양을 분석한 뒤 자산으로 등록합니다.</p>
|
||||||
|
<label class="am-drop" id="am-drop"><span class="am-upload-icon">↑</span><strong>XML 보고서 선택</strong><span>파일을 여기에 놓거나 클릭하세요 · 최대 10 MB</span><input type="file" id="am-report-file" accept=".xml" aria-label="HWiNFO XML 보고서 선택" required></label>
|
||||||
|
<div id="am-report-preview" hidden></div>
|
||||||
|
<div id="am-import-fields" class="am-form-grid" hidden><label>자산명 <span>*</span><input id="am-import-name" maxlength="200" required></label><label>위치<input id="am-import-location" maxlength="150" list="am-locations" placeholder="예: 본사 3층"></label></div>
|
||||||
|
<div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><span id="am-upload-status" class="am-muted"></span><button type="button" class="erp-btn erp-btn-outline" data-close="am-upload">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-import-save" disabled>자산으로 등록</button></div>
|
||||||
|
</form></dialog>
|
||||||
|
<dialog id="am-action" class="am-dialog am-action-dialog" aria-labelledby="am-action-title"><div class="am-dialog-head"><div><small id="am-action-tag"></small><h2 id="am-action-title">자산 배정</h2></div><button type="button" class="am-close" data-close="am-action" aria-label="처리 창 닫기">×</button></div><form id="am-action-form" class="am-form"><p id="am-action-hint" class="am-form-hint"></p><label id="am-action-user-label">배정할 사용자 <span>*</span><select id="am-action-user"><option value="">사용자 선택</option></select></label><label>자산 위치<input id="am-action-location" list="am-locations" maxlength="150"></label><label>처리 메모<textarea id="am-action-note" maxlength="2000" rows="3" placeholder="배정 사유, 반납 상태, 수리 내용 등을 기록하세요."></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-action">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-action-save">처리하기</button></div></form></dialog>
|
||||||
|
<dialog id="am-help" class="am-dialog" aria-labelledby="am-help-title"><div class="am-dialog-head"><h2 id="am-help-title">자산관리 사용 안내</h2><button class="am-close" data-close="am-help" aria-label="사용 안내 닫기">×</button></div><div class="am-form am-help"><h3>01. 자산 등록</h3><p>책상·의자·마우스 등은 개별 자산으로 등록합니다. 자산번호를 비워두면 자동 발급합니다. 컴퓨터는 HWiNFO 보고서를 가져오면 이름과 주요 사양을 확인하고 등록할 수 있습니다.</p><h3>02. 배정과 반납</h3><p>사용 가능한 자산을 등록된 회사 사용자에게 배정합니다. 사용 중인 자산은 반납 후 수리·폐기할 수 있습니다. 위치·사유와 처리자가 이력에 남습니다. 분실 처리 시 기존 배정 사용자도 기록됩니다.</p><h3>03. 컴퓨터 사양</h3><p>HWiNFO → 보고서 저장 → XML 형식을 선택합니다. 핵심 사양, 부품별 상세와 보고서 전체 항목을 볼 수 있습니다. 재업로드할 때 컴퓨터 이름을 확인하세요. 이전 보고서와 원본 XML은 보존됩니다.</p><h3>04. 찾기와 내보내기</h3><p>검색·분류·상태·위치·사용자 필터를 조합합니다. 엑셀 내보내기는 현재 필터에 해당하는 자산 전체를 포함하며 최대 10,000개입니다. 보증 만료 예정은 오늘부터 30일 이내입니다.</p><p class="am-form-hint">보고서에는 시리얼·MAC 주소 등 회사 장비 정보가 포함될 수 있습니다. 자산관리 권한을 가진 사용자만 조회할 수 있습니다.</p></div></dialog>
|
||||||
|
<datalist id="am-locations"></datalist>
|
||||||
|
<dialog id="am-photo" class="am-dialog" aria-labelledby="am-photo-title"><div class="am-dialog-head"><h2 id="am-photo-title">자산 사진 등록</h2><button type="button" class="am-close" data-close="am-photo" aria-label="사진 등록 닫기">×</button></div><form id="am-photo-form" class="am-form"><p class="am-form-hint">JPG · PNG · WebP, 파일당 8 MB 이하 · 자산당 최대 10장. 촬영 위치 정보는 제거해 보관합니다.</p><label>사진 선택<input id="am-photo-file" type="file" accept="image/jpeg,image/png,image/webp" required></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-photo">취소</button><button type="submit" class="erp-btn erp-btn-primary">사진 저장</button></div></form></dialog>
|
||||||
|
<dialog id="am-delete" class="am-dialog" aria-labelledby="am-delete-title"><div class="am-dialog-head"><h2 id="am-delete-title">자산 삭제</h2><button type="button" class="am-close" data-close="am-delete" aria-label="삭제 창 닫기">×</button></div><form id="am-delete-form" class="am-form"><p class="am-warning" id="am-delete-hint"></p><p class="am-form-hint">자산대장과 현황에서 제외됩니다. 사진·보고서·처리 이력은 보존됩니다.</p><label>삭제할 자산번호 확인<input id="am-delete-confirm" required autocomplete="off"></label><label>삭제 사유<textarea id="am-delete-note" required maxlength="2000" rows="3"></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-delete">취소</button><button type="submit" class="erp-btn am-danger">자산 삭제</button></div></form></dialog>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261007a" defer></script>{% endblock %}
|
||||||
+503
-96
@@ -14,10 +14,12 @@ API 로그에는 토큰/시크릿을 넣지 않는다.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import uuid
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Any, Iterator
|
from typing import Any, Iterator
|
||||||
|
|
||||||
|
from psycopg import errors as pg_errors
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
from psycopg_pool import ConnectionPool
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
@@ -97,6 +99,315 @@ class Cafe24Store:
|
|||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self._pool.close()
|
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개 메서드
|
# OAuth 토큰 — app/integrations/cafe24/tokens.py 가 요구하는 3개 메서드
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -281,31 +592,38 @@ class Cafe24Store:
|
|||||||
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
||||||
# 스냅샷 JSON 모양:
|
# 스냅샷 JSON 모양:
|
||||||
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
||||||
# "options": {"data": {...GET/PUT options 응답...}, "written_at": ISO},
|
# "options": {"data": {...GET/PUT options 응답..., "_before_signature", "_recent_values"},
|
||||||
# "variants": {"data": {variant_code: {...}}, "written_at": ISO}}
|
# "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
|
from psycopg.types.json import Jsonb # noqa: WPS433
|
||||||
|
|
||||||
no = int(product_no)
|
no = int(product_no)
|
||||||
if no <= 0 or section not in ("product", "options", "variants"):
|
if no <= 0 or section not in ("product", "options", "variants"):
|
||||||
return
|
return
|
||||||
|
now_iso = datetime.now(KST).isoformat(timespec="seconds")
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
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(
|
row = conn.execute(
|
||||||
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
||||||
(no,),
|
(no,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
||||||
if section == "variants" and isinstance(data, dict):
|
if section == "variants":
|
||||||
# 품목은 코드별로 누적 병합 — 일부만 바꿔도 이전에 바꾼 것을 잃지 않게.
|
previous = (current.get("variants") or {}).get("data") or {}
|
||||||
merged = dict((current.get("variants") or {}).get("data") or {})
|
data = store.merge_variant_snapshot(
|
||||||
merged.update(data)
|
previous, data if isinstance(data, dict) else {}, at=now_iso, replace=replace
|
||||||
data = merged
|
)
|
||||||
current[section] = {
|
current[section] = {"data": data, "written_at": now_iso}
|
||||||
"data": data,
|
|
||||||
"written_at": datetime.now(KST).isoformat(timespec="seconds"),
|
|
||||||
}
|
|
||||||
product = data if section == "product" and isinstance(data, dict) else {}
|
product = data if section == "product" and isinstance(data, dict) else {}
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
@@ -345,51 +663,14 @@ class Cafe24Store:
|
|||||||
return {}
|
return {}
|
||||||
return dict(row["last_write_snapshot"])
|
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 하지 않는다)
|
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
||||||
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
||||||
|
# 읽기 지연 판정은 이 표가 아니라 cafe24_write_attempts(확인된 쓰기)를 본다 —
|
||||||
|
# 여기에는 충돌로 거절된 적용의 백업·예약 초안처럼 카페24에 올라간 적 없는 값도
|
||||||
|
# 들어 있기 때문이다(write_lineage 참고).
|
||||||
|
# 메타데이터(마이그레이션 005): mall_id·shop_no(복원 시 일치 검사), source
|
||||||
|
# (BACKUP 이 카페24 관측값인지, 지연 중이라 마지막 확인된 쓰기인지), source_revision_id.
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
def add_revision(
|
def add_revision(
|
||||||
self,
|
self,
|
||||||
@@ -399,13 +680,18 @@ class Cafe24Store:
|
|||||||
revision_type: str,
|
revision_type: str,
|
||||||
memo: str = "",
|
memo: str = "",
|
||||||
created_by: str = "",
|
created_by: str = "",
|
||||||
|
mall_id: str = "",
|
||||||
|
shop_no: int = 1,
|
||||||
|
source: str = "",
|
||||||
|
source_revision_id: int | None = None,
|
||||||
) -> int:
|
) -> int:
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO cafe24_product_revisions
|
INSERT INTO cafe24_product_revisions
|
||||||
(product_no, html_content, revision_type, memo, created_by)
|
(product_no, html_content, revision_type, memo, created_by,
|
||||||
VALUES (%s,%s,%s,%s,%s)
|
mall_id, shop_no, source, source_revision_id)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
@@ -414,24 +700,33 @@ class Cafe24Store:
|
|||||||
store.normalize_revision_type(revision_type),
|
store.normalize_revision_type(revision_type),
|
||||||
(memo or "")[:500],
|
(memo or "")[:500],
|
||||||
created_by or "",
|
created_by or "",
|
||||||
|
mall_id or "",
|
||||||
|
int(shop_no or 1),
|
||||||
|
source or "",
|
||||||
|
source_revision_id,
|
||||||
),
|
),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return int(row["id"]) if row else 0
|
return int(row["id"]) if row else 0
|
||||||
|
|
||||||
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다."""
|
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다.
|
||||||
with self._pool.connection() as conn:
|
|
||||||
rows = conn.execute(
|
005 적용 전이면 출처(source) 없이 돌려준다(읽기 경로는 막지 않는다)."""
|
||||||
"""
|
sql = """
|
||||||
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
||||||
length(html_content) AS html_length
|
length(html_content) AS html_length{extra}
|
||||||
FROM cafe24_product_revisions
|
FROM cafe24_product_revisions
|
||||||
WHERE product_no = %s
|
WHERE product_no = %s
|
||||||
ORDER BY created_at DESC, id DESC
|
ORDER BY created_at DESC, id DESC
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
""",
|
"""
|
||||||
(int(product_no), max(1, min(int(limit), 200))),
|
args = (int(product_no), max(1, min(int(limit), 200)))
|
||||||
).fetchall()
|
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]
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
||||||
@@ -568,18 +863,24 @@ class Cafe24Store:
|
|||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@contextmanager
|
# ── 예약 실행 lease (마이그레이션 005) ──
|
||||||
def claim_due_schedule(self, *, now: datetime) -> Iterator[dict[str, Any] | None]:
|
# PROCESSING 은 lease_expires_at 까지만 유효하다. worker 가 죽으면 만료 후
|
||||||
"""실행할 예약 1건을 잡아 PROCESSING 으로 바꾼다(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 가 여러 개 떠 있어도 같은 예약을
|
`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 self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
with conn.transaction():
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM cafe24_product_schedules
|
SELECT id FROM cafe24_product_schedules
|
||||||
WHERE status = 'PENDING'
|
WHERE status = 'PENDING'
|
||||||
AND scheduled_at <= %s
|
AND scheduled_at <= %s
|
||||||
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
||||||
@@ -589,48 +890,154 @@ class Cafe24Store:
|
|||||||
""",
|
""",
|
||||||
(now, now),
|
(now, now),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if row is not None:
|
if row is None:
|
||||||
conn.execute(
|
return None
|
||||||
"""
|
claimed = conn.execute(
|
||||||
UPDATE cafe24_product_schedules
|
"""
|
||||||
SET status = 'PROCESSING', started_at = now(), last_error = ''
|
UPDATE cafe24_product_schedules
|
||||||
WHERE id = %s
|
SET status = 'PROCESSING', started_at = now(), last_error = '',
|
||||||
""",
|
lease_owner = %s, lease_token = %s,
|
||||||
(row["id"],),
|
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(
|
def finish_schedule(
|
||||||
self,
|
self,
|
||||||
schedule_id: int,
|
schedule_id: int,
|
||||||
*,
|
*,
|
||||||
|
token: str,
|
||||||
status: str,
|
status: str,
|
||||||
error: str = "",
|
error: str = "",
|
||||||
next_retry_at: datetime | None = None,
|
next_retry_at: datetime | None = None,
|
||||||
retry_count: int | None = None,
|
retry_count: int | None = None,
|
||||||
) -> None:
|
) -> bool:
|
||||||
"""예약 종료 처리. 재시도로 되돌릴 때는 status='PENDING' + next_retry_at."""
|
"""예약 종료 처리(lease 가 내 것일 때만). 재시도로 되돌릴 때는 status='PENDING' + next_retry_at.
|
||||||
|
|
||||||
|
반환: 반영했으면 True. lease 를 잃었으면 False(다른 worker 가 복구 중 — 덮지 않는다).
|
||||||
|
"""
|
||||||
|
normalized = store.normalize_schedule_status(status)
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE cafe24_product_schedules
|
UPDATE cafe24_product_schedules
|
||||||
SET status = %s,
|
SET status = %s,
|
||||||
last_error = %s,
|
last_error = %s,
|
||||||
next_retry_at = %s,
|
next_retry_at = %s,
|
||||||
retry_count = COALESCE(%s, retry_count),
|
retry_count = COALESCE(%s, retry_count),
|
||||||
|
lease_owner = '', lease_token = '', lease_expires_at = NULL,
|
||||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
||||||
THEN now() ELSE completed_at END
|
THEN now() ELSE completed_at END
|
||||||
WHERE id = %s
|
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||||
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(normalized, (error or "")[:1000], next_retry_at, retry_count, normalized,
|
||||||
store.normalize_schedule_status(status),
|
int(schedule_id), token),
|
||||||
(error or "")[:1000],
|
).fetchone()
|
||||||
next_retry_at,
|
return row is not None
|
||||||
retry_count,
|
|
||||||
store.normalize_schedule_status(status),
|
def get_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||||
int(schedule_id),
|
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 (다른 모듈과 동일)
|
# 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일)
|
||||||
|
|||||||
@@ -13,8 +13,11 @@
|
|||||||
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
||||||
|
|
||||||
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
||||||
FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
파일별 DB 잠금(writes.write_lock, 'design:{file_key}')
|
||||||
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부) → FTP 에 쓴다
|
→ FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
||||||
|
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부)
|
||||||
|
→ 임시 파일 업로드·검증 → 교체 직전 원본 재확인 → 이름 바꾸기로 교체
|
||||||
|
(design_ftp.write_text_file — 원본에 직접 STOR 하지 않는다)
|
||||||
→ MANUAL 버전 + 감사로그
|
→ MANUAL 버전 + 감사로그
|
||||||
|
|
||||||
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
||||||
@@ -24,12 +27,14 @@ FastAPI 스레드풀에서 돌게 둔다(다른 cafe24 라우트와 동일한
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, HTTPException, Request
|
from fastapi import APIRouter, Form, HTTPException, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||||
|
|
||||||
from app.integrations.cafe24 import (
|
from app.integrations.cafe24 import (
|
||||||
DESIGN_FILE_SPECS,
|
DESIGN_FILE_SPECS,
|
||||||
|
Cafe24FtpConflict,
|
||||||
Cafe24FtpError,
|
Cafe24FtpError,
|
||||||
design_file_label,
|
design_file_label,
|
||||||
design_file_path,
|
design_file_path,
|
||||||
@@ -38,7 +43,7 @@ from app.integrations.cafe24 import (
|
|||||||
load_ftp_config,
|
load_ftp_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import base_ctx, guard
|
from .common import base_ctx, guard
|
||||||
from .routes_products import _no_store
|
from .routes_products import _no_store
|
||||||
|
|
||||||
@@ -128,74 +133,76 @@ def design_file_apply(
|
|||||||
st, user = checked
|
st, user = checked
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
back = f"/cafe24/design/{file_key}"
|
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)
|
path = design_file_path(file_key)
|
||||||
ftp_config = _ftp_config()
|
ftp_config = _ftp_config()
|
||||||
if not ftp_config.configured:
|
if not ftp_config.configured:
|
||||||
return RedirectResponse(
|
return go(err="FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing))
|
||||||
url=f"{back}?err=" + "FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing),
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
||||||
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
||||||
submitted = content.replace("\r\n", "\n")
|
submitted = content.replace("\r\n", "\n")
|
||||||
if not submitted.strip():
|
if not submitted.strip():
|
||||||
return RedirectResponse(
|
return go(err="내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.")
|
||||||
url=f"{back}?err=" + "내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
# 같은 파일을 두 사람이 동시에 적용하지 못하게 파일별 DB 잠금 안에서 한다.
|
||||||
try:
|
try:
|
||||||
current = design_ftp.read_text_file(ftp_config, path)
|
with writes.write_lock(st, writes.design_lock_key(file_key), actor=actor, purpose=f"{file_key} 적용"):
|
||||||
except Cafe24FtpError as exc:
|
try:
|
||||||
st.log_audit(
|
current = design_ftp.read_text_file(ftp_config, path)
|
||||||
actor=actor, action=f"apply_design:{file_key}", result="FAIL",
|
except Cafe24FtpError as exc:
|
||||||
detail=f"현재값 조회 실패: {exc}",
|
writes.audit_safe(st, actor=actor, action=action, result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||||
)
|
return go(err=f"현재 파일을 읽지 못해 중단했습니다: {exc}")
|
||||||
return RedirectResponse(url=f"{back}?err=현재 파일을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
|
||||||
|
|
||||||
backup_id = st.add_design_revision(
|
backup_id = st.add_design_revision(
|
||||||
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
||||||
memo="적용 직전 자동 백업", created_by=actor,
|
memo="적용 직전 자동 백업", created_by=actor,
|
||||||
)
|
)
|
||||||
|
|
||||||
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
||||||
st.log_audit(
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨")
|
||||||
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨",
|
return go(err="편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.")
|
||||||
)
|
|
||||||
return RedirectResponse(
|
|
||||||
url=f"{back}?err=편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
if submitted == current:
|
if submitted == current:
|
||||||
return RedirectResponse(url=f"{back}?msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
return go(msg="변경된 내용이 없어 적용하지 않았습니다.")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
design_ftp.write_text_file(ftp_config, path, submitted)
|
# 임시 파일 업로드 → 검증 → 교체 직전 원본 재확인(current 와 같아야) → 이름 바꾸기.
|
||||||
except Cafe24FtpError as exc:
|
design_ftp.write_text_file(ftp_config, path, submitted, expected_current=current)
|
||||||
st.log_audit(
|
except Cafe24FtpConflict as exc:
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
result="FAIL", detail=str(exc),
|
result="FAIL", detail=f"충돌 — 교체 직전 파일이 변경됨: {exc}")
|
||||||
)
|
return go(err=f"{exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||||
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
except Cafe24FtpError as exc:
|
||||||
return RedirectResponse(
|
maybe = bool(getattr(exc, "maybe_applied", False))
|
||||||
url=f"{back}?err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
status_code=303,
|
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,
|
record_note = ""
|
||||||
memo=memo, created_by=actor,
|
try:
|
||||||
)
|
revision_id = st.add_design_revision(
|
||||||
st.log_audit(
|
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=revision_id, result="SUCCESS",
|
memo=memo, created_by=actor,
|
||||||
detail=f"{len(submitted)}자 적용 (백업 {backup_id})",
|
)
|
||||||
|
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)
|
logger.info("디자인 파일 적용(%s) (%s)", file_key, actor)
|
||||||
return RedirectResponse(
|
return go(msg=f"적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{record_note}")
|
||||||
url=f"{back}?msg=적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -9,15 +9,20 @@
|
|||||||
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
||||||
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
||||||
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
||||||
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매
|
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매 (행별 결과)
|
||||||
|
|
||||||
공통 규칙
|
공통 규칙
|
||||||
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
||||||
|
- 쓰기는 상품별 DB 잠금(writes.write_lock) 안에서 한다 — 같은 상품을 웹 여러
|
||||||
|
프로세스·예약 worker 가 동시에 쓰지 않게. 못 잡으면 409.
|
||||||
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
||||||
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
||||||
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
||||||
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
||||||
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
||||||
|
PUT 이 성공한 뒤의 기록 실패는 쓰기 실패로 알리지 않는다(재전송을 부르지 않게).
|
||||||
|
- 품목은 **품목코드**(안정 식별자)로 짝짓는다. 옵션값 이름을 바꾼 직후 GET 품목이
|
||||||
|
예전 이름을 돌려줘도 스냅샷의 품목코드별 표기로 바로잡는다(store.apply_variant_patch).
|
||||||
- 모든 쓰기는 감사로그(`cafe24_audit_logs`)에 남긴다.
|
- 모든 쓰기는 감사로그(`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.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
from app.timezone import now_kst
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import read_lag_grace_minutes, require_store
|
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")
|
logger = logging.getLogger("cafe24.product_info")
|
||||||
|
|
||||||
@@ -110,39 +115,40 @@ def product_basic(
|
|||||||
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="상품명·가격 변경"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||||
if not current:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
if not current:
|
||||||
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
|
||||||
changes: dict[str, str] = {}
|
changes: dict[str, str] = {}
|
||||||
before: dict[str, str] = {}
|
before: dict[str, str] = {}
|
||||||
for key, value in want.items():
|
for key, value in want.items():
|
||||||
old = str(current.get(key) or "")
|
old = str(current.get(key) or "")
|
||||||
same = old == value if key == "product_name" else store.price_equal(old, value)
|
same = old == value if key == "product_name" else store.price_equal(old, value)
|
||||||
if not same:
|
if not same:
|
||||||
changes[key] = value
|
changes[key] = value
|
||||||
before[key] = old
|
before[key] = old
|
||||||
if not changes:
|
if not changes:
|
||||||
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
updated = products.update_product(api.client, product_no, **changes)
|
updated = products.update_product(api.client, product_no, **changes)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
result="FAIL", detail=f"{changes} 실패: {exc}")
|
result="FAIL", detail=f"{changes} 실패: {exc}")
|
||||||
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
||||||
raise _http_from_cafe24(exc) from 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}
|
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
|
||||||
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
|
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,
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
result="SUCCESS", detail=detail)
|
result="SUCCESS", detail=detail)
|
||||||
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
||||||
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
||||||
|
|
||||||
@@ -169,30 +175,31 @@ def product_image(
|
|||||||
data = _read_image(file)
|
data = _read_image(file)
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="대표 이미지 교체"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
raise _http_from_cafe24(exc) from exc
|
except Cafe24Error as exc:
|
||||||
if not current:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
if not current:
|
||||||
before = str(current.get("detail_image") or "")
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
before = str(current.get("detail_image") or "")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
images = products.set_main_image(
|
images = products.set_main_image(
|
||||||
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
||||||
)
|
)
|
||||||
if not images.get("detail_image"):
|
if not images.get("detail_image"):
|
||||||
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||||
result="FAIL", detail=f"등록 실패: {exc}")
|
result="FAIL", detail=f"등록 실패: {exc}")
|
||||||
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
||||||
raise _http_from_cafe24(exc) from exc
|
raise _http_from_cafe24(exc) from exc
|
||||||
|
|
||||||
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||||
remember_write(st, product_no, merged)
|
remember_write(st, product_no, merged)
|
||||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
||||||
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
||||||
return {"ok": True, "product": _scalar_view(merged)}
|
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 "")}
|
{"name": str(o.get("name") or ""), "value": str(o.get("value") or "")}
|
||||||
for o in opts if isinstance(o, dict)
|
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 ""),
|
"custom_variant_code": str(v.get("custom_variant_code") or ""),
|
||||||
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
||||||
"display": products._flag(v.get("display")), # noqa: SLF001
|
"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_link_image": str(v.get("option_link_image") or ""),
|
||||||
"option_color": str(v.get("option_color") or ""),
|
"option_color": str(v.get("option_color") or ""),
|
||||||
"value_no": v.get("value_no"),
|
"value_no": v.get("value_no"),
|
||||||
|
"pending": bool(v.get("pending")),
|
||||||
}
|
}
|
||||||
for v in values if isinstance(v, dict)
|
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]]:
|
def _snapshot_sections(st: Any, product_no: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||||
"""GET 품목 목록에 유예시간 안의 우리 쓰기(스냅샷)를 덮어씌운다.
|
"""(옵션 섹션, 품목 섹션) — 각각 {"data":…, "written_at":…} 또는 {}."""
|
||||||
|
snap = st.get_write_snapshot(product_no) or {}
|
||||||
|
return snap.get("options") or {}, snap.get("variants") or {}
|
||||||
|
|
||||||
삭제한 품목(`{"_deleted": true}`)은 카페24 GET 이 한동안 계속 돌려주므로 걸러낸다.
|
|
||||||
"""
|
def _within(written_at: object) -> bool:
|
||||||
section = (st.get_write_snapshot(product_no) or {}).get("variants") or {}
|
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 {}
|
data = section.get("data") or {}
|
||||||
if not data or not store.within_grace(section.get("written_at"), grace_minutes=read_lag_grace_minutes()):
|
if not isinstance(data, dict) or not data:
|
||||||
return variants
|
return list(variants)
|
||||||
out = []
|
out = []
|
||||||
for v in variants:
|
for v in variants:
|
||||||
code = str(v.get("variant_code") or "")
|
patched = store.apply_variant_patch(
|
||||||
patch = data.get(code)
|
v, data.get(str(v.get("variant_code") or "")),
|
||||||
if isinstance(patch, dict) and patch.get("_deleted"):
|
section_written_at=section.get("written_at"), grace_minutes=read_lag_grace_minutes(),
|
||||||
continue
|
)
|
||||||
out.append({**v, **patch} if isinstance(patch, dict) else v)
|
if patched is not None:
|
||||||
|
out.append(patched)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _apply_options_snapshot(st: Any, product_no: int, option: dict[str, Any]) -> dict[str, Any]:
|
def _annotate(option: dict[str, Any], variants: list[dict[str, Any]], recent: list[str]) -> tuple[dict, list]:
|
||||||
"""GET 옵션이 우리 마지막 쓰기와 다르고 유예시간 안이면 스냅샷(우리 쓰기)을 쓴다."""
|
"""옵션 1개 상품: 품목에 첫 옵션값 번호(value_no)를, 품목이 아직 안 보이는 최근 추가
|
||||||
section = (st.get_write_snapshot(product_no) or {}).get("options") or {}
|
옵션값에 pending 표시를 붙인다(화면이 "품목 없는 옵션값"으로 오해하지 않게)."""
|
||||||
data = section.get("data")
|
groups = option.get("options") if isinstance(option.get("options"), list) else []
|
||||||
if not isinstance(data, dict) or not store.within_grace(
|
if len(groups) != 1 or not isinstance(groups[0], dict):
|
||||||
section.get("written_at"), grace_minutes=read_lag_grace_minutes()
|
return option, variants
|
||||||
):
|
values = [v for v in (groups[0].get("option_value") or []) if isinstance(v, dict)]
|
||||||
return option
|
by_text = {str(v.get("option_text") or ""): v.get("value_no") for v in values}
|
||||||
return data
|
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]:
|
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))
|
raw_option = products.get_options(api.client, product_no)
|
||||||
view = _options_view(option)
|
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]] = []
|
variants: list[dict[str, Any]] = []
|
||||||
if view["has_option"]:
|
if products._flag(option.get("has_option"), default=False): # noqa: SLF001
|
||||||
variants = _apply_variant_snapshot(st, product_no, products.list_variants(api.client, product_no))
|
raw_variants = products.list_variants(api.client, product_no)
|
||||||
return {"option": view, "variants": [_variant_view(v) for v in variants], "raw_options": option}
|
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")
|
@product_info_router.get("/products/{product_no}/options")
|
||||||
@@ -322,29 +414,40 @@ def options_create(
|
|||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from 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)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 생성"):
|
||||||
existing = products.get_options(api.client, product_no)
|
try:
|
||||||
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
existing = products.get_options(api.client, product_no)
|
||||||
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
||||||
created = products.create_options(api.client, product_no, body)
|
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
||||||
except Cafe24Error as exc:
|
created = products.create_options(api.client, product_no, body)
|
||||||
st.log_audit(actor=actor, action="create_options", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
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)
|
osec, _vsec = _snapshot_sections(st, product_no)
|
||||||
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
record_error = _save_snapshot_safe(
|
||||||
st.log_audit(actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
st, product_no, "options",
|
||||||
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
_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)
|
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):
|
if len(variants) < len(values):
|
||||||
logger.warning("카페24 상품 %s 옵션 생성 후 품목 %s/%s 건만 조회됨", product_no, 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")
|
@product_info_router.put("/products/{product_no}/options")
|
||||||
@@ -358,6 +461,8 @@ def options_update(
|
|||||||
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
||||||
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
||||||
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
||||||
|
이름을 바꾸면 품목코드별로 새 표기를 스냅샷에 남긴다(GET 품목이 예전 이름을
|
||||||
|
돌려주는 동안에도 품목이 옵션값과 제대로 짝지어 보이게).
|
||||||
"""
|
"""
|
||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
@@ -366,64 +471,99 @@ def options_update(
|
|||||||
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 수정"):
|
||||||
loaded = _load_options_and_variants(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
loaded = _load_options_and_variants(st, api, product_no)
|
||||||
raise _http_from_cafe24(exc) from exc
|
except Cafe24Error as exc:
|
||||||
if not loaded["option"]["has_option"]:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
if not loaded["option"]["has_option"]:
|
||||||
original = loaded["option"]["options"]
|
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
||||||
try:
|
original = loaded["option"]["options"]
|
||||||
body = store.build_update_options_request(
|
try:
|
||||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
body = store.build_update_options_request(
|
||||||
allow_append=True,
|
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:
|
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||||
if loaded["option"]["option_preset_code"]:
|
for o, n in zip(original, body["options"]):
|
||||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
for ov, nv in zip(o["option_value"], n["option_value"]):
|
||||||
# 뒤에 덧붙인 옵션값 수 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
||||||
added = sum(
|
raw_labels = {str(v.get("variant_code") or ""): v.get("options") for v in loaded["raw_variants"]}
|
||||||
max(0, len(n["option_value"]) - len(o["option_value"]))
|
previous = (loaded["variants_section"].get("data") or {}) if _within(
|
||||||
for o, n in zip(body["original_options"], body["options"])
|
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:
|
fresh: list[dict[str, Any]] | None = None
|
||||||
updated = products.update_options(api.client, product_no, body)
|
if added:
|
||||||
except Cafe24Error as exc:
|
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
||||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
# 늦게 나타나는 품목은 pending 으로 표시된다(_annotate).
|
||||||
result="FAIL", detail=str(exc))
|
_osec, vsec = _snapshot_sections(st, product_no)
|
||||||
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
fresh = _patch_variants(
|
||||||
raise _http_from_cafe24(exc) from exc
|
vsec, products.wait_for_variants(api.client, product_no, len(loaded["raw_variants"]) + added)
|
||||||
|
)
|
||||||
st.save_write_snapshot(product_no, "options", updated)
|
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||||
summary = "; ".join(
|
result="SUCCESS", detail=summary[:900])
|
||||||
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])
|
|
||||||
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
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:
|
if added:
|
||||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
out["added"] = added
|
||||||
fresh = products.wait_for_variants(api.client, product_no, len(loaded["variants"]) + added)
|
return out
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.delete("/products/{product_no}/options")
|
@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)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 삭제"):
|
||||||
before = products.get_options(api.client, product_no)
|
try:
|
||||||
products.delete_options(api.client, product_no)
|
before = products.get_options(api.client, product_no)
|
||||||
except Cafe24Error as exc:
|
products.delete_options(api.client, product_no)
|
||||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=str(exc))
|
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=str(exc))
|
||||||
names = ", ".join(
|
raise _http_from_cafe24(exc) from exc
|
||||||
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
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", {})
|
osec, _vsec = _snapshot_sections(st, product_no)
|
||||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
record_error = _save_snapshot_safe(
|
||||||
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
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)
|
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")
|
@product_info_router.post("/products/{product_no}/options/image")
|
||||||
@@ -464,13 +611,13 @@ def option_image_upload(
|
|||||||
try:
|
try:
|
||||||
path = products.upload_image_bytes(api.client, data)
|
path = products.upload_image_bytes(api.client, data)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||||
result="FAIL", detail=str(exc))
|
result="FAIL", detail=str(exc))
|
||||||
raise _http_from_cafe24(exc) from exc
|
raise _http_from_cafe24(exc) from exc
|
||||||
if not path:
|
if not path:
|
||||||
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
||||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||||
result="SUCCESS", detail=path)
|
result="SUCCESS", detail=path)
|
||||||
return {"ok": True, "path": 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):
|
if not store.VARIANT_CODE_RE.match(code):
|
||||||
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="품목 삭제"):
|
||||||
products.delete_variant(api.client, product_no, code)
|
try:
|
||||||
except Cafe24Error as exc:
|
products.delete_variant(api.client, product_no, code)
|
||||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"{code}: {exc}")
|
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=f"{code}: {exc}")
|
||||||
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 스냅샷에 삭제 표식을 남겨 걸러낸다.
|
raise _http_from_cafe24(exc) from exc
|
||||||
st.save_write_snapshot(product_no, "variants", {code: {"_deleted": True}})
|
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 삭제 표식을 남겨 걸러낸다.
|
||||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
# 표식은 이후 늦게 도착한 수정이 있어도 유지된다(store.merge_variant_snapshot).
|
||||||
result="SUCCESS", detail=code)
|
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)
|
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")
|
@product_info_router.put("/products/{product_no}/variants")
|
||||||
@@ -503,7 +652,13 @@ def variants_update(
|
|||||||
product_no: int,
|
product_no: int,
|
||||||
payload: dict[str, Any] = Body(default_factory=dict),
|
payload: dict[str, Any] = Body(default_factory=dict),
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다."""
|
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다 — **행별 결과**.
|
||||||
|
|
||||||
|
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
||||||
|
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||||
|
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||||
|
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||||
|
"""
|
||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
rows = payload.get("rows")
|
rows = payload.get("rows")
|
||||||
@@ -517,31 +672,51 @@ def variants_update(
|
|||||||
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="품목 수정"):
|
||||||
results = products.update_variants(api.client, product_no, requests)
|
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가 받아들였으므로). 응답에 담긴 값이 있으면
|
# 카페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]] = {}
|
by_code: dict[str, dict[str, Any]] = {}
|
||||||
for r in requests:
|
failed: dict[str, str] = {}
|
||||||
by_code[r["variant_code"]] = {k: v for k, v in r.items() if k != "variant_code"}
|
unknown: dict[str, str] = {}
|
||||||
for r in results:
|
for result in results:
|
||||||
code = str(r.get("variant_code") or "")
|
code = result["variant_code"]
|
||||||
if code in by_code:
|
if result["status"] == products.VARIANT_OK:
|
||||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
patch = dict(sent.get(code) or {})
|
||||||
if key in r and r[key] is not None:
|
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
||||||
by_code[code][key] = r[key]
|
value = (result.get("variant") or {}).get(key)
|
||||||
st.save_write_snapshot(product_no, "variants", by_code)
|
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(
|
detail = "; ".join(
|
||||||
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
|
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,
|
if failed or unknown:
|
||||||
result="SUCCESS", detail=detail[:900])
|
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
||||||
logger.info("카페24 상품 %s 품목 %s건 수정 (%s)", product_no, len(by_code), actor)
|
first = next(iter({**failed, **unknown}.values()), "")
|
||||||
return {"ok": True, "updated": {code: _variant_view({"variant_code": code, **patch})
|
detail += f" / 오류: {first}"
|
||||||
for code, patch in by_code.items()}}
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from contextlib import contextmanager
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any
|
from typing import Any, Iterator
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import quote, urlencode
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
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.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
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
|
from .common import base_ctx, guard, read_lag_grace_minutes, require_store
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.products")
|
logger = logging.getLogger("cafe24.products")
|
||||||
@@ -121,6 +122,16 @@ def _short_dt(value: Any) -> str:
|
|||||||
return text.replace("T", " ")[:16]
|
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]:
|
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
||||||
normalized = products.normalize_product(raw)
|
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(
|
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]:
|
) -> tuple[str, str, dict[str, Any] | None]:
|
||||||
"""(유효 HTML, 상태, 마지막 쓰기 revision). 상태는 store.SYNC_*."""
|
"""(유효 HTML, 상태, 마지막 확인된 쓰기). 상태는 store.SYNC_*.
|
||||||
grace = read_lag_grace_minutes()
|
|
||||||
since = now_kst() - timedelta(minutes=grace)
|
근거는 원격 반영이 확인된 쓰기(cafe24_write_attempts)뿐이다 — writes.resolve_effective.
|
||||||
last_write = st.latest_write_revision(product_no, since=since)
|
"""
|
||||||
if not last_write:
|
return writes.resolve_effective(st, product_no, cafe24_html, fetched_updated=fetched_updated)
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다."""
|
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다.
|
||||||
info = products.normalize_product(updated) if updated else {}
|
|
||||||
if info.get("product_no"):
|
카페24에는 이미 반영된 뒤라 기록 실패로 예외를 내지 않는다(로그만 — writes 참고).
|
||||||
st.upsert_products([info])
|
"""
|
||||||
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
info, _error = writes.remember_product_write(st, product_no, updated)
|
||||||
return info
|
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]:
|
def _info(product: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""편집기·정보 패널 공용 상품 요약."""
|
"""편집기·정보 패널 공용 상품 요약."""
|
||||||
info = products.normalize_product(product) if product else {}
|
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)
|
product, scalar_stale = load_product(st, api, product_no)
|
||||||
desc = products.descriptions_from_product(product)
|
desc = products.descriptions_from_product(product)
|
||||||
st.upsert_products([products.normalize_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:
|
except Cafe24Error as exc:
|
||||||
error = str(exc)
|
error = str(exc)
|
||||||
logger.warning("카페24 상품 %s 조회 실패: %s", product_no, 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 {
|
return {
|
||||||
"product_no": product_no,
|
"product_no": product_no,
|
||||||
# 고객이 보는 상세페이지 주소 (CAFE24_SHOP_URL, 없으면 카페24 기본 도메인)
|
# 고객이 보는 상세페이지 주소 (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_pending": sync_state == store.SYNC_PENDING,
|
||||||
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
||||||
"scalar_stale": scalar_stale,
|
"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 "",
|
"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,
|
"editor_error": error,
|
||||||
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
||||||
}
|
}
|
||||||
@@ -384,33 +416,34 @@ def product_rename(
|
|||||||
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="상품명 변경"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
st.log_audit(
|
except Cafe24Error as exc:
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
writes.audit_safe(
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
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
|
)
|
||||||
|
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
||||||
|
|
||||||
before = str(current.get("product_name") or "")
|
before = str(current.get("product_name") or "")
|
||||||
if before == name:
|
if before == name:
|
||||||
return {"ok": True, "product_name": before, "changed": False}
|
return {"ok": True, "product_name": before, "changed": False}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
updated = products.update_product(api.client, product_no, product_name=name)
|
updated = products.update_product(api.client, product_no, product_name=name)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
st, actor=actor, action="rename_product", product_no=product_no,
|
||||||
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
||||||
)
|
)
|
||||||
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
||||||
raise HTTPException(status_code=502, detail=str(exc)) from 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)
|
after = str(info.get("product_name") or name)
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
st, actor=actor, action="rename_product", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
||||||
)
|
)
|
||||||
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
||||||
@@ -442,31 +475,32 @@ def product_status(
|
|||||||
want = bool(payload.get("value"))
|
want = bool(payload.get("value"))
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="진열/판매 변경"):
|
||||||
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:
|
|
||||||
try:
|
try:
|
||||||
updated, _ = load_product(st, api, product_no)
|
updated = products.update_product(api.client, product_no, **{field: want})
|
||||||
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
except Cafe24Error as exc:
|
||||||
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
writes.audit_safe(
|
||||||
updated = {}
|
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 = {
|
state = {
|
||||||
"display": bool(info.get("display", want if field == "display" else True)),
|
"display": bool(info.get("display", want if field == "display" else True)),
|
||||||
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
||||||
}
|
}
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
||||||
)
|
)
|
||||||
logger.info("카페24 상품 %s %s=%s (%s)", product_no, field, want, actor)
|
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)
|
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")
|
@products_router.post("/products/{product_no}/apply")
|
||||||
def product_apply(
|
def product_apply(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -490,125 +613,165 @@ def product_apply(
|
|||||||
):
|
):
|
||||||
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
||||||
|
|
||||||
순서를 지키는 것이 이 함수의 핵심이다.
|
순서(writes.write_product): 상품 잠금 → 카페24 현재값 재조회(로컬 값을 현재값으로
|
||||||
1) 카페24에서 **현재** HTML 을 다시 읽는다(로컬 값을 현재값으로 믿지 않는다)
|
믿지 않는다) → 결과 모르는 이전 시도 확인 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||||
2) 읽기 지연을 판정해 **유효 현재값**을 정한다(예전 값을 돌려주는 중이면
|
← 유일한 복구 수단 → 지문 대조(충돌 거부) → 시도 기록 → PUT → 버전·스냅샷 기록.
|
||||||
우리 마지막 쓰기가 현재값이다)
|
|
||||||
3) 그 값으로 BACKUP 버전을 남긴다 ← 유일한 복구 수단
|
|
||||||
4) 편집 시작 시점의 지문과 비교해 충돌이면 거부한다
|
|
||||||
5) 쓰고, 스냅샷·MANUAL 버전·감사로그를 남긴다
|
|
||||||
|
|
||||||
PC/모바일을 구분하지 않는다 — 두 필드에 같은 HTML 을 쓴다. 분리 사용 상품의
|
PC/모바일을 구분하지 않는다 — description 만 쓰고 separated_mobile_description="F".
|
||||||
모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
분리 사용 상품의 모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
||||||
"""
|
"""
|
||||||
checked = guard(request)
|
checked = guard(request)
|
||||||
if not isinstance(checked, tuple):
|
if not isinstance(checked, tuple):
|
||||||
return checked
|
return checked
|
||||||
st, user = 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에 반영한다. 한글 이미지 경로는
|
# 화면에서 보던 그대로(정리된 소스)를 카페24에 반영한다. 한글 이미지 경로는
|
||||||
# 원래의 퍼센트 인코딩으로 되돌린다.
|
# 원래의 퍼센트 인코딩으로 되돌린다.
|
||||||
submitted = store.format_html(store.encode_html_urls(html or ""))
|
submitted = store.format_html(store.encode_html_urls(html or ""))
|
||||||
if not submitted.strip():
|
if not submitted.strip():
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요.",
|
url=_with_msg(_back_url(product_no, list_query),
|
||||||
|
err="내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요."),
|
||||||
status_code=303,
|
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:
|
try:
|
||||||
current = products.fetch_descriptions(api.client, product_no)
|
revision = _revision_for(st, product_no, revision_id)
|
||||||
except Cafe24Error as exc:
|
except HTTPException as exc:
|
||||||
st.log_audit(
|
return RedirectResponse(url=_with_msg(back, err=str(exc.detail)), status_code=303)
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
body = str(revision.get("html_content") or "")
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
if not body.strip():
|
||||||
)
|
return RedirectResponse(url=_with_msg(back, err="내용이 빈 버전은 복원할 수 없습니다."), status_code=303)
|
||||||
return RedirectResponse(url=f"{back}&err=카페24 현재값을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
if not base_fingerprint:
|
||||||
|
# 편집기가 본 현재값 없이 복원하면 그 사이 바뀐 내용을 모르고 덮는다.
|
||||||
# 읽기 지연 판정 — 카페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 값이 변경됨",
|
|
||||||
)
|
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
url=_with_msg(back, err="편집기를 새로고침한 뒤 버전 이력에서 다시 복원하세요."), status_code=303
|
||||||
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:
|
try:
|
||||||
# mobile_description 은 보내지 않는다 — update_descriptions 가
|
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="적용 결과 확정"):
|
||||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제하고
|
attempt = st.get_attempt(attempt_id)
|
||||||
# 카페24가 모바일 값을 자동으로 맞춰준다(모바일도 항상 PC와 같다).
|
if (not attempt or int(attempt.get("product_no") or 0) != int(product_no)
|
||||||
updated = products.update_descriptions(api.client, product_no, description=submitted)
|
or attempt.get("status") not in open_states):
|
||||||
except Cafe24Error as exc:
|
return RedirectResponse(url=_with_msg(back, err="이미 확정됐거나 없는 시도입니다."), status_code=303)
|
||||||
st.log_audit(
|
schedule_id = attempt.get("schedule_id")
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
if result == "applied":
|
||||||
revision_id=backup_id, result="FAIL", detail=str(exc),
|
st.update_attempt(attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
)
|
resolved_by=actor, only_from=open_states)
|
||||||
logger.warning("카페24 상품 %s 적용 실패: %s", product_no, exc)
|
revision_id = writes.record_attempt(st, attempt)
|
||||||
return RedirectResponse(
|
if schedule_id:
|
||||||
url=f"{back}&err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
st.review_schedule(int(schedule_id), status=store.STATUS_SUCCESS,
|
||||||
status_code=303,
|
note=f"{actor} 가 반영됨으로 확정", actor=actor, action="applied")
|
||||||
)
|
text = f"시도 #{attempt_id} 를 반영됨으로 확정했습니다(버전 {revision_id})."
|
||||||
|
else:
|
||||||
# PUT 응답은 쓰기 직후의 실제 값 — 스냅샷으로 남긴다(상품명·가격·updated_date 등).
|
st.update_attempt(attempt_id, status=store.ATTEMPT_ABANDONED, resolved_by=actor,
|
||||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
only_from=open_states)
|
||||||
|
if schedule_id:
|
||||||
# MANUAL revision 을 **먼저** 남긴다. 이것이 "마지막 쓰기" 기준이 되어, 카페24 GET 이
|
st.review_schedule(int(schedule_id), status=store.STATUS_FAILED,
|
||||||
# 한동안 예전 값을 돌려줘도 편집기는 방금 적용한 내용을 보여준다.
|
note=f"{actor} 가 반영 안 됨으로 확정", actor=actor, action="not_applied")
|
||||||
revision_id = st.add_revision(
|
text = f"시도 #{attempt_id} 를 반영 안 됨으로 확정했습니다. 필요하면 다시 적용하세요."
|
||||||
product_no=product_no,
|
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||||
html_content=submitted,
|
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||||
revision_type=store.REVISION_MANUAL,
|
writes.audit_safe(st, actor=actor, action=f"resolve_attempt:{result}", product_no=product_no,
|
||||||
memo=memo,
|
result="SUCCESS", detail=f"시도 #{attempt_id}")
|
||||||
created_by=actor,
|
return RedirectResponse(url=_with_msg(back, msg=text), status_code=303)
|
||||||
)
|
|
||||||
|
|
||||||
# 카페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,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -22,9 +22,9 @@ import logging
|
|||||||
from fastapi import APIRouter, Form, Request
|
from fastapi import APIRouter, Form, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
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 .common import base_ctx, guard
|
||||||
from .routes_products import _no_store
|
from .routes_products import _no_store
|
||||||
|
|
||||||
@@ -55,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
|||||||
set_selling=row.get("set_selling"),
|
set_selling=row.get("set_selling"),
|
||||||
),
|
),
|
||||||
"editable": store.is_editable(row.get("status") or ""),
|
"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": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
||||||
"rows": rows,
|
"rows": rows,
|
||||||
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
|
"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": request.query_params.get("msg", ""),
|
||||||
"flash_error": request.query_params.get("err", ""),
|
"flash_error": request.query_params.get("err", ""),
|
||||||
}
|
}
|
||||||
@@ -114,6 +116,12 @@ def schedule_create(
|
|||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
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
|
revision_id: int | None = None
|
||||||
if want_html:
|
if want_html:
|
||||||
body = store.format_html(store.encode_html_urls(html or ""))
|
body = store.format_html(store.encode_html_urls(html or ""))
|
||||||
@@ -127,6 +135,7 @@ def schedule_create(
|
|||||||
revision_type=store.REVISION_DRAFT,
|
revision_type=store.REVISION_DRAFT,
|
||||||
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
||||||
created_by=actor,
|
created_by=actor,
|
||||||
|
mall_id=load_config().mall_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
schedule_id = st.create_schedule(
|
schedule_id = st.create_schedule(
|
||||||
@@ -187,3 +196,51 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
|
|||||||
"display": normalized["display"],
|
"display": normalized["display"],
|
||||||
"selling": normalized["selling"],
|
"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
|
from __future__ import annotations
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
@@ -44,6 +45,9 @@ STATUS_PROCESSING = "PROCESSING"
|
|||||||
STATUS_SUCCESS = "SUCCESS"
|
STATUS_SUCCESS = "SUCCESS"
|
||||||
STATUS_FAILED = "FAILED"
|
STATUS_FAILED = "FAILED"
|
||||||
STATUS_CANCELLED = "CANCELLED"
|
STATUS_CANCELLED = "CANCELLED"
|
||||||
|
# 원격 반영 여부를 모른다(네트워크 끊김·worker 중단) — 사람이 카페24를 보고 확정한다.
|
||||||
|
# 자동으로 PENDING 에 돌려 재적용하지 않는다(마이그레이션 005).
|
||||||
|
STATUS_NEEDS_REVIEW = "NEEDS_REVIEW"
|
||||||
|
|
||||||
SCHEDULE_STATUSES: tuple[str, ...] = (
|
SCHEDULE_STATUSES: tuple[str, ...] = (
|
||||||
STATUS_PENDING,
|
STATUS_PENDING,
|
||||||
@@ -51,6 +55,7 @@ SCHEDULE_STATUSES: tuple[str, ...] = (
|
|||||||
STATUS_SUCCESS,
|
STATUS_SUCCESS,
|
||||||
STATUS_FAILED,
|
STATUS_FAILED,
|
||||||
STATUS_CANCELLED,
|
STATUS_CANCELLED,
|
||||||
|
STATUS_NEEDS_REVIEW,
|
||||||
)
|
)
|
||||||
|
|
||||||
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
||||||
@@ -59,8 +64,36 @@ SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
|||||||
STATUS_SUCCESS: "완료",
|
STATUS_SUCCESS: "완료",
|
||||||
STATUS_FAILED: "실패",
|
STATUS_FAILED: "실패",
|
||||||
STATUS_CANCELLED: "취소",
|
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 는 임의 변경 금지
|
# 사용자가 손댈 수 있는 상태 — PROCESSING/SUCCESS 는 임의 변경 금지
|
||||||
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
||||||
|
|
||||||
@@ -509,11 +542,20 @@ def resolve_description(
|
|||||||
known_digests: set[str] | frozenset[str],
|
known_digests: set[str] | frozenset[str],
|
||||||
grace_minutes: int,
|
grace_minutes: int,
|
||||||
now: datetime | None = None,
|
now: datetime | None = None,
|
||||||
|
fetched_updated: object = None,
|
||||||
) -> tuple[str, str]:
|
) -> tuple[str, str]:
|
||||||
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
||||||
|
|
||||||
last_write: 최근 쓰기 revision — {"html_content", "created_at"}.
|
last_write: **원격 반영이 확인된** 마지막 쓰기 — {"html_content", "created_at",
|
||||||
known_digests: 유예시간 안의 revision 들의 내용 해시(`content_digest()` 결과) 집합.
|
"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:
|
if not last_write:
|
||||||
return cafe24_html, SYNC_NONE
|
return cafe24_html, SYNC_NONE
|
||||||
@@ -523,11 +565,29 @@ def resolve_description(
|
|||||||
last_html = str(last_write.get("html_content") or "")
|
last_html = str(last_write.get("html_content") or "")
|
||||||
if cafe24_html == last_html:
|
if cafe24_html == last_html:
|
||||||
return cafe24_html, SYNC_SYNCED
|
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:
|
if content_digest(cafe24_html) in known_digests:
|
||||||
return last_html, SYNC_PENDING
|
return last_html, SYNC_PENDING
|
||||||
return cafe24_html, SYNC_EXTERNAL
|
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:
|
def content_digest(html: str) -> str:
|
||||||
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
||||||
|
|
||||||
@@ -598,6 +658,172 @@ def overlay_recent_write(
|
|||||||
return merged, True
|
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 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
{# 읽기 지연 배너 — 카페24 관리자 API 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
||||||
적용한 내용(MANUAL/SCHEDULED revision)을 편집기에 보여준다. 쇼핑몰 화면에는 이미
|
적용한 내용(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 %}
|
{% if sync_pending %}
|
||||||
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
||||||
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
||||||
@@ -199,28 +226,40 @@
|
|||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details class="cf24-details">
|
<details class="cf24-details" id="cf24-history">
|
||||||
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
||||||
{% if revisions %}
|
{% if revisions %}
|
||||||
<div class="cf24-scroll">
|
<div class="cf24-scroll">
|
||||||
<table class="erp-table cf24-compact">
|
<table class="erp-table cf24-compact">
|
||||||
<thead>
|
<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>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for rev in revisions %}
|
{% for rev in revisions %}
|
||||||
<tr>
|
<tr>
|
||||||
<td class="cf24-nowrap">{{ rev.created_at }}</td>
|
<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.html_length }}자</td>
|
||||||
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
||||||
<td>{{ rev.memo 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>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<p class="cf24-muted">버전 선택 복원은 Phase 6 에서 붙습니다. 내용은 모두 보관됩니다.</p>
|
<p class="cf24-muted">
|
||||||
|
「원문」에서 그 버전의 소스를 확인·복사하고, 필요하면 「이 버전으로 복원」으로 카페24에 다시 적용합니다.
|
||||||
|
복원도 적용과 같은 순서(현재값 재조회 → 직전 내용 자동 백업 → 편집 중 변경 확인)를 거치며 이력에
|
||||||
|
<code>ROLLBACK</code> 으로 남습니다. 자동 복원(예약 종료 후 되돌리기)은 쓰지 않습니다.
|
||||||
|
</p>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
<div class="erp-card cf24-card">
|
<div class="erp-card cf24-card">
|
||||||
<div class="cf24-card-head">
|
<div class="cf24-card-head">
|
||||||
<h3>예약 목록</h3>
|
<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>
|
</div>
|
||||||
|
|
||||||
<p class="cf24-note">
|
<p class="cf24-note">
|
||||||
@@ -22,6 +22,11 @@
|
|||||||
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
||||||
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
||||||
</p>
|
</p>
|
||||||
|
<p class="cf24-note">
|
||||||
|
<strong>확인 필요</strong> — 카페24에 쓰는 도중 응답이 끊겼거나 worker 가 멈춰 반영 여부를 알 수 없는 예약입니다.
|
||||||
|
자동으로 다시 실행하지 않습니다. 쇼핑몰에서 상세페이지·진열/판매를 확인한 뒤
|
||||||
|
「반영됨」(완료로 기록) · 「다시 실행」 · 「실패로 종료」 중 하나를 고르세요.
|
||||||
|
</p>
|
||||||
|
|
||||||
{% if rows %}
|
{% if rows %}
|
||||||
<div class="cf24-scroll">
|
<div class="cf24-scroll">
|
||||||
@@ -53,12 +58,13 @@
|
|||||||
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
|
{% 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 == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
|
||||||
{% elif r.status == 'PENDING' %}<span class="cf24-warn">{{ 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 %}
|
{% else %}<span class="cf24-muted">{{ r.status_label }}</span>{% endif %}
|
||||||
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
{{ r.memo or '' }}
|
{{ 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>
|
||||||
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
||||||
<td class="cf24-nowrap">
|
<td class="cf24-nowrap">
|
||||||
@@ -67,6 +73,22 @@
|
|||||||
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
||||||
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
||||||
</form>
|
</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 %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</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
|
from __future__ import annotations
|
||||||
|
|
||||||
import ftplib
|
import ftplib
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import timedelta
|
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 config as cfgmod
|
||||||
from app.integrations.cafe24 import crypto, oauth, products, tokens
|
from app.integrations.cafe24 import crypto, oauth, products, tokens
|
||||||
from app.integrations.cafe24.errors import Cafe24ApiError, Cafe24AuthError, Cafe24ConfigError
|
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
|
from app.timezone import now_kst
|
||||||
|
|
||||||
SECRET = "unit-test-secret"
|
SECRET = "unit-test-secret"
|
||||||
@@ -25,6 +27,8 @@ SECRET = "unit-test-secret"
|
|||||||
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
||||||
# 기다릴 필요는 없다.
|
# 기다릴 필요는 없다.
|
||||||
products.time.sleep = lambda *_a, **_k: None
|
products.time.sleep = lambda *_a, **_k: None
|
||||||
|
# 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히.
|
||||||
|
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
||||||
|
|
||||||
_TEST_ENV = {
|
_TEST_ENV = {
|
||||||
"CAFE24_MALL_ID": "testmall",
|
"CAFE24_MALL_ID": "testmall",
|
||||||
@@ -711,203 +715,303 @@ def test_design_file_path_env_override():
|
|||||||
os.environ["CAFE24_PC_DETAIL_FTP_PATH"] = saved
|
os.environ["CAFE24_PC_DETAIL_FTP_PATH"] = saved
|
||||||
|
|
||||||
|
|
||||||
class _FakeFTP:
|
_FTP_CFG = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||||
"""ftplib.FTP 대역 — 실제 소켓 없이 RETR/STOR 명령만 흉내낸다."""
|
_SWIPER = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
||||||
|
|
||||||
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",))
|
|
||||||
|
|
||||||
|
|
||||||
def test_design_ftp_read_and_write_roundtrip():
|
def test_design_ftp_read_and_write_roundtrip():
|
||||||
from app.integrations.cafe24 import design_ftp
|
from app.integrations.cafe24 import design_ftp
|
||||||
|
|
||||||
path = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
with fakes.patched_ftp() as ftp:
|
||||||
_FakeFTP.files = {path: "old".encode("utf-8")}
|
ftp.reset({_SWIPER: "old".encode("utf-8")})
|
||||||
saved = ftplib.FTP
|
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "old"
|
||||||
ftplib.FTP = _FakeFTP
|
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "new content", expected_current="old")
|
||||||
try:
|
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "new content"
|
||||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
# 원본에 직접 STOR 하지 않는다 — 임시 파일에 올린 뒤 이름 바꾸기로 교체
|
||||||
content = design_ftp.read_text_file(cfg, path)
|
stors = [e for e in ftp.log if e[0] == "STOR"]
|
||||||
assert content == "old"
|
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)
|
||||||
design_ftp.write_text_file(cfg, path, "new content")
|
# 임시 파일이 남지 않는다
|
||||||
assert design_ftp.read_text_file(cfg, path) == "new content"
|
assert set(ftp.files) == {_SWIPER}
|
||||||
finally:
|
|
||||||
ftplib.FTP = saved
|
|
||||||
|
|
||||||
|
|
||||||
def test_design_ftp_missing_file_raises_cafe24_error():
|
def test_design_ftp_missing_file_raises_cafe24_error():
|
||||||
from app.integrations.cafe24 import design_ftp
|
from app.integrations.cafe24 import design_ftp
|
||||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||||
|
|
||||||
_FakeFTP.files = {}
|
with fakes.patched_ftp() as ftp:
|
||||||
saved = ftplib.FTP
|
ftp.reset({})
|
||||||
ftplib.FTP = _FakeFTP
|
|
||||||
try:
|
|
||||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
|
||||||
try:
|
try:
|
||||||
design_ftp.read_text_file(cfg, "/missing.js")
|
design_ftp.read_text_file(_FTP_CFG, "/missing.js")
|
||||||
raise AssertionError("Cafe24FtpError 가 났어야 한다")
|
raise AssertionError("Cafe24FtpError 가 났어야 한다")
|
||||||
except Cafe24FtpError:
|
except Cafe24FtpError:
|
||||||
pass
|
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:
|
def _worker_env(description="<p>A</p>", **schedule):
|
||||||
"""worker 가 쓰는 저장소 메서드만 흉내낸다."""
|
st = fakes.MemoryStore()
|
||||||
|
cafe = fakes.FakeCafe24(description)
|
||||||
def __init__(self, rows):
|
api = fakes.FakeApi(cafe)
|
||||||
self.rows = list(rows)
|
rid = st.add_revision(product_no=131, html_content="<p>예약 내용</p>", revision_type="DRAFT")
|
||||||
self.revisions = {}
|
fields = {"revision_id": rid, "set_display": True}
|
||||||
self.added = []
|
fields.update(schedule)
|
||||||
self.finished = []
|
sid = st.add_schedule(**fields)
|
||||||
self.audits = []
|
return st, cafe, api, sid, rid
|
||||||
|
|
||||||
@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 test_worker_applies_html_and_flags():
|
def test_worker_applies_html_and_flags():
|
||||||
st = _FakeStore([_schedule_row()])
|
st, cafe, api, sid, _rid = _worker_env()
|
||||||
st.revisions[55] = {"html_content": "<p>예약 내용</p>"}
|
assert worker.process_once(st, api) == 1
|
||||||
client = _WorkerClient({"product": _PRODUCT})
|
|
||||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
|
||||||
|
|
||||||
# 쓰기 직전 현재값을 읽어 BACKUP 을 남겼는가
|
# 쓰기 직전 현재값을 읽어 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 으로 보냈는가
|
# HTML 과 진열 상태를 한 번의 PUT 으로 보냈는가
|
||||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
put = cafe.puts()[0]
|
||||||
assert put["json"]["request"]["description"] == "<p>예약 내용</p>"
|
assert put[2]["request"]["description"] == "<p>예약 내용</p>"
|
||||||
# mobile_description 은 보내지 않는다 — separated_mobile_description="F" 로
|
# mobile_description 은 보내지 않는다 — separated_mobile_description="F" 로
|
||||||
# "PC 상세설명과 동일"을 강제한다(직접 보내면 "직접 등록"으로 바뀌어버린다).
|
# "PC 상세설명과 동일"을 강제한다(직접 보내면 "직접 등록"으로 바뀌어버린다).
|
||||||
assert "mobile_description" not in put["json"]["request"]
|
assert "mobile_description" not in put[2]["request"]
|
||||||
assert put["json"]["request"]["separated_mobile_description"] == "F"
|
assert put[2]["request"]["separated_mobile_description"] == "F"
|
||||||
assert put["json"]["request"]["display"] == "T"
|
assert put[2]["request"]["display"] == "T"
|
||||||
assert "selling" not in put["json"]["request"] # 변경 없음이면 보내지 않는다
|
assert "selling" not in put[2]["request"] # 변경 없음이면 보내지 않는다
|
||||||
assert st.finished == [
|
row = st.schedules[sid]
|
||||||
{"id": 7, "status": store.STATUS_SUCCESS, "error": "",
|
assert row["status"] == store.STATUS_SUCCESS and row["last_error"] == ""
|
||||||
"next_retry_at": None, "retry_count": None}
|
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():
|
def test_worker_flags_only_skips_backup():
|
||||||
"""HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽거나 백업하지 않는다."""
|
"""HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽거나 백업하지 않는다."""
|
||||||
st = _FakeStore([_schedule_row(revision_id=None, set_selling=False)])
|
st, cafe, api, sid, _ = _worker_env(revision_id=None, set_selling=False)
|
||||||
client = _WorkerClient({"product": _PRODUCT})
|
before = len(st.revisions)
|
||||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
assert worker.process_once(st, api) == 1
|
||||||
assert st.added == [] # 백업 없음
|
assert len(st.revisions) == before # 백업·SCHEDULED 버전 없음
|
||||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
put = cafe.puts()[0]
|
||||||
assert "description" not in put["json"]["request"]
|
assert put[2]["request"] == {"display": "T", "selling": "F"}
|
||||||
assert put["json"]["request"] == {"display": "T", "selling": "F"}
|
assert st.schedules[sid]["status"] == store.STATUS_SUCCESS
|
||||||
|
|
||||||
|
|
||||||
def test_worker_retries_then_fails():
|
def test_worker_retries_then_fails():
|
||||||
"""실패는 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED 로 확정한다."""
|
"""거절(반영 안 됨이 확실)은 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED."""
|
||||||
boom = Cafe24ApiError("서버 오류", status=500)
|
st, cafe, api, sid, _ = _worker_env()
|
||||||
|
cafe.put_error = Cafe24ApiError("잘못된 요청", status=422)
|
||||||
st = _FakeStore([_schedule_row(retry_count=0)])
|
worker.process_once(st, api)
|
||||||
st.revisions[55] = {"html_content": "<p>x</p>"}
|
first = st.schedules[sid]
|
||||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
|
||||||
first = st.finished[0]
|
|
||||||
assert first["status"] == store.STATUS_PENDING # 다시 대기로
|
assert first["status"] == store.STATUS_PENDING # 다시 대기로
|
||||||
assert first["retry_count"] == 1
|
assert first["retry_count"] == 1
|
||||||
assert first["next_retry_at"] is not None
|
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, cafe2, api2, sid2, _ = _worker_env(retry_count=store.MAX_RETRY)
|
||||||
st2.revisions[55] = {"html_content": "<p>x</p>"}
|
cafe2.put_error = Cafe24ApiError("서버 오류", status=400)
|
||||||
worker.process_once(st2, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
worker.process_once(st2, api2)
|
||||||
assert st2.finished[0]["status"] == store.STATUS_FAILED
|
assert st2.schedules[sid2]["status"] == store.STATUS_FAILED
|
||||||
assert any(a["result"] == "FAIL" for a in st2.audits)
|
assert any(a["result"] == "FAIL" for a in st2.audits)
|
||||||
|
|
||||||
|
|
||||||
def test_worker_missing_revision_is_failure_not_crash():
|
def test_worker_missing_revision_is_failure_not_crash():
|
||||||
st = _FakeStore([_schedule_row(revision_id=999, retry_count=store.MAX_RETRY)])
|
st, _cafe, api, sid, _ = _worker_env(revision_id=999, retry_count=store.MAX_RETRY)
|
||||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT})))
|
worker.process_once(st, api)
|
||||||
assert st.finished[0]["status"] == store.STATUS_FAILED
|
assert st.schedules[sid]["status"] == store.STATUS_FAILED
|
||||||
assert "999" in st.finished[0]["error"]
|
assert "999" in st.schedules[sid]["last_error"]
|
||||||
|
|
||||||
|
|
||||||
def test_worker_stops_when_nothing_due():
|
def test_worker_stops_when_nothing_due():
|
||||||
st = _FakeStore([])
|
st = fakes.MemoryStore()
|
||||||
assert worker.process_once(st, _FakeApi(_WorkerClient())) == 0
|
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 읽기 지연 보정 — 마지막 쓰기가 권위
|
# 카페24 읽기 지연 보정 — 마지막 쓰기가 권위
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -1185,7 +1289,8 @@ def test_upload_images_and_variants_wrappers():
|
|||||||
assert products.list_variants(client, 7) == [{"variant_code": "P000000R000A"}]
|
assert products.list_variants(client, 7) == [{"variant_code": "P000000R000A"}]
|
||||||
assert products.get_options(client, 7)["has_option"] == "T"
|
assert products.get_options(client, 7)["has_option"] == "T"
|
||||||
assert products.update_variants(client, 7, [{"variant_code": "P000000R000A", "display": "F"}]) == [
|
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]
|
sent = [c for c in client.calls if c[0] == "PUT"][-1]
|
||||||
assert sent[2]["requests"][0]["variant_code"] == "P000000R000A"
|
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"") == {}
|
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():
|
def _run_all():
|
||||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||||
for fn in fns:
|
for fn in fns:
|
||||||
|
|||||||
+223
-119
@@ -8,14 +8,28 @@
|
|||||||
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
||||||
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
||||||
|
|
||||||
한 번에 한 건씩 처리한다
|
한 번에 한 건씩, lease 로 잡는다 (마이그레이션 005)
|
||||||
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잠그고 PROCESSING 으로
|
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잡아 PROCESSING + lease
|
||||||
바꾼다. worker 가 실수로 두 개 떠도 같은 예약이 두 번 적용되지 않는다.
|
(만료 시각·token)로 바꾼다. worker 가 여럿이어도 같은 예약을 두 번 잡지 않는다.
|
||||||
|
카페24에 쓰기 직전 lease 를 연장해 "아직 내 것인가"를 확인하고(펜싱), 결과는
|
||||||
|
token 이 맞을 때만 남긴다 — 만료 뒤 늦게 끝난 worker 가 남의 결과를 덮지 않는다.
|
||||||
|
|
||||||
적용 순서는 화면 편집과 같다
|
적용 순서는 화면 편집과 같다 (writes.write_product 공용)
|
||||||
카페24 현재값 재조회 → BACKUP revision → PUT → SUCCESS + 감사로그
|
상품 잠금 → 카페24 현재값 재조회 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||||
실패하면 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시 시도하고,
|
→ 시도 기록 → PUT → 버전(SCHEDULED)·스냅샷 기록
|
||||||
소진되면 FAILED 로 확정한다. 되돌리기는 쓰지 않는다.
|
예약 직전 백업도 읽기 지연을 보정한 값이다(카페24가 아직 옛 HTML 을 돌려줘도
|
||||||
|
그것을 "직전 내용"으로 남기지 않는다). 백업의 source 로 관측값/확인된 적용값을 구분한다.
|
||||||
|
|
||||||
|
결과 분류
|
||||||
|
카페24가 거절 → 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시, 소진되면 FAILED
|
||||||
|
반영 여부 모름 → NEEDS_REVIEW (자동 재적용 금지 — 사람이 쇼핑몰을 보고 확정)
|
||||||
|
반영 성공·기록 실패 → SUCCESS + "기록 복구 필요" 메모. 기록은 다음 주기에 채운다(재적용 없음)
|
||||||
|
같은 상품을 다른 작업이 쓰는 중 → 재시도 횟수를 쓰지 않고 잠시 뒤 다시
|
||||||
|
|
||||||
|
중단 복구 (recover)
|
||||||
|
lease 가 만료된 PROCESSING 은 그 예약의 마지막 쓰기 시도를 보고 판정한다
|
||||||
|
(store.recovery_decision). 무조건 PENDING 으로 돌리지 않는다 — 카페24에 이미 반영됐을
|
||||||
|
수 있기 때문이다. 카페24 현재값이 예약 결과와 같으면 반영된 것으로 확정한다.
|
||||||
|
|
||||||
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
||||||
"""
|
"""
|
||||||
@@ -25,6 +39,7 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import socket
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
@@ -33,141 +48,230 @@ from typing import Any
|
|||||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
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")
|
logger = logging.getLogger("cafe24.worker")
|
||||||
|
|
||||||
ACTOR = "SCHEDULER"
|
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:
|
def lease_seconds() -> int:
|
||||||
"""예약 1건 적용. 성공 시 사람이 읽을 요약 문자열."""
|
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"])
|
schedule_id = int(row["id"])
|
||||||
product_no = int(row["product_no"])
|
product_no = int(row["product_no"])
|
||||||
|
token = str(row.get("lease_token") or "")
|
||||||
|
lease = lease_seconds()
|
||||||
revision_id = row.get("revision_id")
|
revision_id = row.get("revision_id")
|
||||||
set_display = row.get("set_display")
|
set_display = row.get("set_display")
|
||||||
set_selling = row.get("set_selling")
|
set_selling = row.get("set_selling")
|
||||||
|
|
||||||
html: str | None = None
|
def fence() -> bool:
|
||||||
if revision_id:
|
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
||||||
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} 의 내용이 비어 있습니다.")
|
|
||||||
|
|
||||||
# 상세설명을 바꿀 때는 쓰기 직전 현재값을 읽어 백업한다(로컬 값을 믿지 않는다).
|
try:
|
||||||
backup_id = 0
|
html: str | None = None
|
||||||
if html is not None:
|
if revision_id:
|
||||||
current = products.fetch_descriptions(api.client, product_no)
|
revision = st.get_revision(int(revision_id))
|
||||||
backup_id = store_db.add_revision(
|
if not revision:
|
||||||
product_no=product_no,
|
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
||||||
html_content=current.description,
|
html = str(revision.get("html_content") or "")
|
||||||
revision_type=store.REVISION_BACKUP,
|
if not html.strip():
|
||||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업",
|
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||||
created_by=ACTOR,
|
with writes.write_lock(
|
||||||
)
|
st, writes.product_lock_key(product_no), actor=ACTOR,
|
||||||
if current.mobile_description and current.mobile_description != current.description:
|
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
||||||
store_db.add_revision(
|
) as lock:
|
||||||
product_no=product_no,
|
outcome = writes.write_product(
|
||||||
html_content=current.mobile_description,
|
st, api, product_no,
|
||||||
revision_type=store.REVISION_BACKUP,
|
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
||||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업 (모바일)",
|
set_display=set_display, set_selling=set_selling,
|
||||||
created_by=ACTOR,
|
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 은 보내지 않고
|
note = ""
|
||||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제한다.
|
if outcome.record_error:
|
||||||
# (mobile_description 을 직접 보내면 카페24가 그 설정을 "직접 등록"으로 바꿔버린다.)
|
note = f"카페24 반영 성공 · 로컬 기록 실패(자동 복구 예정, 재적용 안 함): {outcome.record_error}"
|
||||||
updated = products.update_product(
|
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||||
api.client,
|
if not done:
|
||||||
product_no,
|
# 반영은 됐다. 결과를 못 남겼어도 lease 만료 후 recover 가 시도 기록(REMOTE_OK/RECORDED)을
|
||||||
description=html,
|
# 보고 SUCCESS 로 확정한다 — 다시 적용하지 않는다.
|
||||||
separated_mobile_description="F" if html is not None else None,
|
logger.warning("예약 #%s 적용됨 — 결과 기록 실패(lease 잃음). 복구 단계가 확정합니다.", schedule_id)
|
||||||
display=set_display,
|
summary = _summary(row)
|
||||||
selling=set_selling,
|
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 의 읽기 지연에
|
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||||
# 흔들리지 않게 한다(routes_products._load_product 가 덮어씌운다).
|
return store.STATUS_SUCCESS
|
||||||
if isinstance(updated, dict) and updated.get("product_no"):
|
|
||||||
|
|
||||||
|
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:
|
try:
|
||||||
store_db.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
with writes.write_lock(st, writes.product_lock_key(int(row["product_no"])), actor=ACTOR,
|
||||||
except Exception: # noqa: BLE001 — 스냅샷 실패가 예약 결과를 바꾸면 안 된다.
|
purpose=f"예약 #{schedule_id} 복구 확인", wait_seconds=0):
|
||||||
logger.exception("예약 #%s 상품 %s 스냅샷 저장 실패", schedule_id, product_no)
|
if _verify_attempt(st, api, attempt):
|
||||||
if html is not None:
|
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
# 화면 편집(apply)과 동일 — 카페24 관리자 API 의 쓰기 직후 읽기 지연을
|
resolved_by="auto:카페24 값이 예약 결과와 같음",
|
||||||
# 여기서 짧게 흡수한다(쇼핑몰에는 바로 반영되지만 관리자 조회만 뒤쳐질 때가 있다).
|
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||||
# 확인이 안 돼도 실패가 아니다 — 화면은 마지막 쓰기(SCHEDULED revision)를 기준으로
|
decision, note = store.RECOVER_RECORD, "중단 복구: 카페24 현재값이 예약 결과와 같아 반영됨으로 확정"
|
||||||
# 그린다. 여기서 SCHEDULED revision 을 남겨야 그 기준이 생긴다.
|
except writes.WriteBusy:
|
||||||
products.wait_for_description(api.client, product_no, html)
|
pass # 다음 주기에 다시 — 판정은 REVIEW 로 남긴다
|
||||||
store_db.add_revision(
|
if decision == store.RECOVER_RECORD and attempt:
|
||||||
product_no=product_no,
|
try:
|
||||||
html_content=html,
|
writes.record_attempt(st, attempt)
|
||||||
revision_type=store.REVISION_SCHEDULED,
|
except Exception as exc: # noqa: BLE001 — 반영은 됐다. 기록은 다음 주기에.
|
||||||
memo=f"예약 #{schedule_id} 적용",
|
logger.exception("예약 #%s 복구 중 버전 기록 실패", schedule_id)
|
||||||
created_by=ACTOR,
|
note += f" (버전 기록 실패 — 자동 재시도: {type(exc).__name__})"
|
||||||
)
|
decision = store.RECOVER_SUCCESS
|
||||||
|
|
||||||
summary = store.describe_schedule_action(
|
if decision == store.RECOVER_SUCCESS:
|
||||||
has_html=html is not None, set_display=set_display, set_selling=set_selling
|
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(
|
for row in rows:
|
||||||
actor=ACTOR,
|
try:
|
||||||
action="schedule_apply",
|
recover_one(st, api, row)
|
||||||
product_no=product_no,
|
except Exception: # noqa: BLE001 — 한 건 때문에 나머지를 멈추지 않는다(lease 만료 후 다시)
|
||||||
revision_id=int(revision_id) if revision_id else None,
|
logger.exception("예약 #%s 복구 중 오류", row.get("id"))
|
||||||
schedule_id=schedule_id,
|
count += 1
|
||||||
result="SUCCESS",
|
return count
|
||||||
detail=summary + (f" (백업 {backup_id})" if backup_id else ""),
|
|
||||||
)
|
|
||||||
return summary
|
|
||||||
|
|
||||||
|
|
||||||
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
|
handled = 0
|
||||||
while True:
|
while True:
|
||||||
with store_db.claim_due_schedule(now=now_kst()) as row:
|
row = st.claim_due_schedule(now=now_kst(), owner=worker_owner(), ttl_seconds=lease_seconds())
|
||||||
if row is None:
|
if row is None:
|
||||||
return handled
|
return handled
|
||||||
# 잠금은 여기서 이미 풀렸다. 상태가 PROCESSING 이라 다른 worker 가 집지 않는다.
|
run_one(st, api, row)
|
||||||
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)
|
|
||||||
handled += 1
|
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
|
||||||
@@ -36,10 +36,23 @@ class CupangDBStore:
|
|||||||
open=False,
|
open=False,
|
||||||
)
|
)
|
||||||
self._pool.open(wait=False)
|
self._pool.open(wait=False)
|
||||||
|
self._weight_col: bool | None = None # 마이그레이션 007(weight_g) 적용 여부 — 한 번 확인되면 기억
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self._pool.close()
|
self._pool.close()
|
||||||
|
|
||||||
|
def weight_enabled(self) -> bool:
|
||||||
|
"""cupang_products.weight_g(포장무게, 마이그레이션 007) 가 있는가. 있으면 기억(없으면 다음에 다시 확인)."""
|
||||||
|
if self._weight_col:
|
||||||
|
return True
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT 1 FROM information_schema.columns "
|
||||||
|
"WHERE table_name = 'cupang_products' AND column_name = 'weight_g'"
|
||||||
|
).fetchone()
|
||||||
|
self._weight_col = row is not None
|
||||||
|
return self._weight_col
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 입고센터 (cupang_centers)
|
# 입고센터 (cupang_centers)
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -300,32 +313,39 @@ class CupangDBStore:
|
|||||||
product_name: str,
|
product_name: str,
|
||||||
coupang_item_code: str | None = None,
|
coupang_item_code: str | None = None,
|
||||||
sort_order: int = 0,
|
sort_order: int = 0,
|
||||||
|
weight_g: int | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""제품 등록/수정.
|
"""제품 등록/수정.
|
||||||
|
|
||||||
coupang_item_code 가 None 이면 기존 값을 유지한다(빈 문자열은 지우기).
|
coupang_item_code 가 None 이면 기존 값을 유지한다(빈 문자열은 지우기).
|
||||||
|
weight_g(포장무게 g) 가 None 이면 기존 값을 유지한다(수기 추가에서 비워 두면 그대로). 007 미적용이면 무시.
|
||||||
"""
|
"""
|
||||||
code = (product_code or "").strip()
|
code = (product_code or "").strip()
|
||||||
name = (product_name or "").strip()
|
name = (product_name or "").strip()
|
||||||
cic = None if coupang_item_code is None else coupang_item_code.strip()
|
cic = None if coupang_item_code is None else coupang_item_code.strip()
|
||||||
if not code or not name:
|
if not code or not name:
|
||||||
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
||||||
|
weight = self.weight_enabled()
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO cupang_products
|
INSERT INTO cupang_products
|
||||||
(product_code, product_name, coupang_item_code, sort_order)
|
(product_code, product_name, coupang_item_code, sort_order"""
|
||||||
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s)
|
+ (", weight_g" if weight else "") + """)
|
||||||
|
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s"""
|
||||||
|
+ (", %(w)s" if weight else "") + """)
|
||||||
ON CONFLICT (product_code) DO UPDATE
|
ON CONFLICT (product_code) DO UPDATE
|
||||||
SET product_name = EXCLUDED.product_name,
|
SET product_name = EXCLUDED.product_name,
|
||||||
coupang_item_code = COALESCE(
|
coupang_item_code = COALESCE(
|
||||||
%(cic)s, cupang_products.coupang_item_code
|
%(cic)s, cupang_products.coupang_item_code
|
||||||
),
|
),"""
|
||||||
|
+ ("\n weight_g = COALESCE(%(w)s, cupang_products.weight_g)," if weight else "")
|
||||||
|
+ """
|
||||||
sort_order = EXCLUDED.sort_order,
|
sort_order = EXCLUDED.sort_order,
|
||||||
active = TRUE
|
active = TRUE
|
||||||
RETURNING *
|
RETURNING *
|
||||||
""",
|
""",
|
||||||
{"code": code, "name": name, "cic": cic, "sort": sort_order},
|
{"code": code, "name": name, "cic": cic, "sort": sort_order, "w": weight_g},
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return self._product_serialize(row)
|
return self._product_serialize(row)
|
||||||
|
|
||||||
@@ -345,8 +365,11 @@ class CupangDBStore:
|
|||||||
product_name: str,
|
product_name: str,
|
||||||
product_code: str,
|
product_code: str,
|
||||||
coupang_item_code: str = "",
|
coupang_item_code: str = "",
|
||||||
|
weight_g: Any = ...,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드).
|
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드/포장무게).
|
||||||
|
|
||||||
|
weight_g: 정수 g 또는 None(지움). 넘기지 않으면(...) 그대로 — 007 미적용이면 무시.
|
||||||
|
|
||||||
제품코드가 바뀌면 같은 코드로 연결돼 있던 상자 규칙(cupang_box_rules)의
|
제품코드가 바뀌면 같은 코드로 연결돼 있던 상자 규칙(cupang_box_rules)의
|
||||||
product_code 도 함께 옮긴다(출고 라인은 과거 기록이라 스냅샷 유지).
|
product_code 도 함께 옮긴다(출고 라인은 과거 기록이라 스냅샷 유지).
|
||||||
@@ -356,6 +379,7 @@ class CupangDBStore:
|
|||||||
cic = (coupang_item_code or "").strip()
|
cic = (coupang_item_code or "").strip()
|
||||||
if not name or not code:
|
if not name or not code:
|
||||||
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
raise ValueError("제품코드와 제품명 모두 필요합니다.")
|
||||||
|
set_weight = weight_g is not ... and self.weight_enabled() # 트랜잭션 밖에서 확인(연결을 겹쳐 잡지 않게)
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
with conn.transaction():
|
||||||
old = conn.execute(
|
old = conn.execute(
|
||||||
@@ -378,11 +402,12 @@ class CupangDBStore:
|
|||||||
UPDATE cupang_products
|
UPDATE cupang_products
|
||||||
SET product_name = %s,
|
SET product_name = %s,
|
||||||
product_code = %s,
|
product_code = %s,
|
||||||
coupang_item_code = %s
|
coupang_item_code = %s"""
|
||||||
|
+ (", weight_g = %s" if set_weight else "") + """
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
RETURNING *
|
RETURNING *
|
||||||
""",
|
""",
|
||||||
(name, code, cic, product_id),
|
(name, code, cic) + ((weight_g,) if set_weight else ()) + (product_id,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if code != old_code:
|
if code != old_code:
|
||||||
# 새 코드로 된 규칙이 이미 있으면 옮기지 않는다(중복 방지).
|
# 새 코드로 된 규칙이 이미 있으면 옮기지 않는다(중복 방지).
|
||||||
@@ -1081,6 +1106,8 @@ class CupangDBStore:
|
|||||||
out["active"] = bool(out.get("active", True))
|
out["active"] = bool(out.get("active", True))
|
||||||
out["sort_order"] = int(out.get("sort_order", 0))
|
out["sort_order"] = int(out.get("sort_order", 0))
|
||||||
out["coupang_item_code"] = (out.get("coupang_item_code") or "").strip()
|
out["coupang_item_code"] = (out.get("coupang_item_code") or "").strip()
|
||||||
|
w = out.get("weight_g") # 007 미적용이면 키 없음 → None
|
||||||
|
out["weight_g"] = int(w) if w is not None else None
|
||||||
for k in ("created_at", "updated_at"):
|
for k in ("created_at", "updated_at"):
|
||||||
v = out.get(k)
|
v = out.get(k)
|
||||||
if isinstance(v, datetime):
|
if isinstance(v, datetime):
|
||||||
|
|||||||
@@ -193,10 +193,17 @@ def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
|
|||||||
# ── 상자 목록(상자 번호별 내용물) ──────────────────────────────
|
# ── 상자 목록(상자 번호별 내용물) ──────────────────────────────
|
||||||
BOX_HEADERS = ["상자번호", "제품명", "제품코드", "수량"]
|
BOX_HEADERS = ["상자번호", "제품명", "제품코드", "수량"]
|
||||||
BOX_WIDTHS_PX = {1: 70, 2: 240, 3: 110, 4: 70}
|
BOX_WIDTHS_PX = {1: 70, 2: 240, 3: 110, 4: 70}
|
||||||
|
BOX_WEIGHT_HEADER = "무게(g)" # with_weight 일 때 5열 — 상자 무게 합계(상자번호처럼 상자 단위로 세로 병합)
|
||||||
|
BOX_WEIGHT_WIDTH_PX = 80
|
||||||
|
|
||||||
|
|
||||||
def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, Any]]) -> Any:
|
def build_box_list_workbook(
|
||||||
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일)."""
|
shipment: dict[str, Any], box_list: list[dict[str, Any]], *, with_weight: bool = False
|
||||||
|
) -> Any:
|
||||||
|
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일).
|
||||||
|
|
||||||
|
with_weight 면 5열 "무게(g)" — 상자마다 box["weight_g"](라우터 _attach_box_weights), 모르면 빈칸."""
|
||||||
|
headers = BOX_HEADERS + ([BOX_WEIGHT_HEADER] if with_weight else [])
|
||||||
from openpyxl import Workbook
|
from openpyxl import Workbook
|
||||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||||
from openpyxl.utils import get_column_letter
|
from openpyxl.utils import get_column_letter
|
||||||
@@ -215,10 +222,10 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
|
|||||||
|
|
||||||
ws.cell(row=1, column=1, value=f"{with_dow(ship_date)} {center} 상자 목록")
|
ws.cell(row=1, column=1, value=f"{with_dow(ship_date)} {center} 상자 목록")
|
||||||
ws.cell(row=1, column=1).font = Font(size=14, bold=True)
|
ws.cell(row=1, column=1).font = Font(size=14, bold=True)
|
||||||
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(BOX_HEADERS))
|
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
|
||||||
|
|
||||||
header_fill = PatternFill("solid", fgColor=HEADER_BG)
|
header_fill = PatternFill("solid", fgColor=HEADER_BG)
|
||||||
for idx, name in enumerate(BOX_HEADERS, start=1):
|
for idx, name in enumerate(headers, start=1):
|
||||||
cell = ws.cell(row=2, column=idx, value=name)
|
cell = ws.cell(row=2, column=idx, value=name)
|
||||||
cell.font = Font(bold=True)
|
cell.font = Font(bold=True)
|
||||||
cell.alignment = center_align
|
cell.alignment = center_align
|
||||||
@@ -235,18 +242,27 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
|
|||||||
ws.cell(row=row, column=3, value=it.get("product_code") or "")
|
ws.cell(row=row, column=3, value=it.get("product_code") or "")
|
||||||
ws.cell(row=row, column=4, value=int(it.get("quantity") or 0))
|
ws.cell(row=row, column=4, value=int(it.get("quantity") or 0))
|
||||||
row += 1
|
row += 1
|
||||||
# 한 상자에 여러 제품이면 상자번호 칸을 세로로 합친다.
|
if with_weight and contents:
|
||||||
|
w = entry.get("weight_g")
|
||||||
|
ws.cell(row=first, column=5, value=(int(w) if w is not None else None))
|
||||||
|
ws.cell(row=first, column=5).number_format = "#,##0"
|
||||||
|
# 한 상자에 여러 제품이면 상자번호(·무게) 칸을 세로로 합친다.
|
||||||
if row - first > 1:
|
if row - first > 1:
|
||||||
ws.merge_cells(start_row=first, start_column=1, end_row=row - 1, end_column=1)
|
ws.merge_cells(start_row=first, start_column=1, end_row=row - 1, end_column=1)
|
||||||
|
if with_weight:
|
||||||
|
ws.merge_cells(start_row=first, start_column=5, end_row=row - 1, end_column=5)
|
||||||
|
|
||||||
last = row - 1
|
last = row - 1
|
||||||
for r in range(3, last + 1):
|
for r in range(3, last + 1):
|
||||||
for col in range(1, len(BOX_HEADERS) + 1):
|
for col in range(1, len(headers) + 1):
|
||||||
cell = ws.cell(row=r, column=col)
|
cell = ws.cell(row=r, column=col)
|
||||||
cell.border = box
|
cell.border = box
|
||||||
cell.alignment = left_align if col == 2 else center_align
|
cell.alignment = left_align if col == 2 else center_align
|
||||||
|
|
||||||
for col, px in BOX_WIDTHS_PX.items():
|
widths = dict(BOX_WIDTHS_PX)
|
||||||
|
if with_weight:
|
||||||
|
widths[5] = BOX_WEIGHT_WIDTH_PX
|
||||||
|
for col, px in widths.items():
|
||||||
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
|
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
|
||||||
ws.row_dimensions[1].height = 24
|
ws.row_dimensions[1].height = 24
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import calendar as _calendar
|
import calendar as _calendar
|
||||||
import json
|
import json
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
from fractions import Fraction
|
from fractions import Fraction
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -22,7 +23,7 @@ from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request
|
|||||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||||
|
|
||||||
from .holidays import holiday_name, is_holiday
|
from .holidays import holiday_name, is_holiday
|
||||||
from .store import SHIP_METHODS
|
from .store import SHIP_METHODS, parse_weight_g
|
||||||
|
|
||||||
router = APIRouter(prefix="/cupang", tags=["cupang"])
|
router = APIRouter(prefix="/cupang", tags=["cupang"])
|
||||||
|
|
||||||
@@ -411,6 +412,19 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
]
|
]
|
||||||
calc = _compute_boxes(store, items)
|
calc = _compute_boxes(store, items)
|
||||||
total_qty = sum(it["quantity"] for it in items)
|
total_qty = sum(it["quantity"] for it in items)
|
||||||
|
box_list = _expand_box_list(ship, calc, items)
|
||||||
|
box_weight = _attach_box_weights(store, box_list)
|
||||||
|
# 상자 목록 합계 행 — 수량 합계와 무게 합계(kg, 소수 첫째 자리)
|
||||||
|
box_qty_total = sum(int(it.get("quantity") or 0) for b in box_list for it in (b.get("items") or []))
|
||||||
|
box_weight_total = None
|
||||||
|
box_weight_partial = False
|
||||||
|
if box_weight:
|
||||||
|
for b in box_list:
|
||||||
|
b["weight_kg"] = _g_to_kg(b.get("weight_g"))
|
||||||
|
if b.get("weight_g") is not None:
|
||||||
|
box_weight_total = (box_weight_total or 0) + int(b["weight_g"])
|
||||||
|
if b.get("weight_missing"):
|
||||||
|
box_weight_partial = True
|
||||||
|
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -424,7 +438,12 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
"shipment": ship,
|
"shipment": ship,
|
||||||
"items": items,
|
"items": items,
|
||||||
"calc": calc,
|
"calc": calc,
|
||||||
"box_list": _expand_box_list(ship, calc, items),
|
"box_list": box_list,
|
||||||
|
# 상자별 무게 합계(g) 칸 — 포장무게(마이그레이션 007) 가 있을 때만
|
||||||
|
"box_weight": box_weight,
|
||||||
|
"box_qty_total": box_qty_total,
|
||||||
|
"box_weight_total_kg": _g_to_kg(box_weight_total),
|
||||||
|
"box_weight_partial": box_weight_partial,
|
||||||
"total_qty": total_qty,
|
"total_qty": total_qty,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -432,7 +451,7 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
|
|
||||||
@router.get("/{shipment_id:int}/boxes.xlsx")
|
@router.get("/{shipment_id:int}/boxes.xlsx")
|
||||||
def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
||||||
"""상자 목록(상자번호·제품명·제품코드·수량) 엑셀 다운로드."""
|
"""상자 목록(상자번호·제품명·제품코드·수량·무게) 엑셀 다운로드."""
|
||||||
from io import BytesIO # noqa: WPS433
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
from fastapi.responses import StreamingResponse # noqa: WPS433
|
from fastapi.responses import StreamingResponse # noqa: WPS433
|
||||||
@@ -457,8 +476,9 @@ def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
|
|||||||
for ln in (ship.get("lines") or [])
|
for ln in (ship.get("lines") or [])
|
||||||
]
|
]
|
||||||
box_list = _expand_box_list(ship, _compute_boxes(store, items), items)
|
box_list = _expand_box_list(ship, _compute_boxes(store, items), items)
|
||||||
|
with_weight = _attach_box_weights(store, box_list)
|
||||||
|
|
||||||
wb = build_box_list_workbook(ship, box_list)
|
wb = build_box_list_workbook(ship, box_list, with_weight=with_weight)
|
||||||
buf = BytesIO()
|
buf = BytesIO()
|
||||||
wb.save(buf)
|
wb.save(buf)
|
||||||
buf.seek(0)
|
buf.seek(0)
|
||||||
@@ -1185,6 +1205,44 @@ def _compute_boxes(store: Any, raw_items: list[Any]) -> dict[str, Any]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _g_to_kg(grams: Any) -> str | None:
|
||||||
|
"""g → kg 표시 글자 — 소수 둘째 자리에서 반올림(사사오입)해 첫째 자리까지. 예: 1,250g → "1.3"."""
|
||||||
|
if grams is None:
|
||||||
|
return None
|
||||||
|
kg = (Decimal(int(grams)) / 1000).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
|
||||||
|
return f"{kg:,.1f}"
|
||||||
|
|
||||||
|
|
||||||
|
def _attach_box_weights(store: Any, box_list: list[dict[str, Any]]) -> bool:
|
||||||
|
"""상자마다 무게 합계(g) — 상자에 든 제품마다 수량 × 포장무게(설정(제품명)의 지금 값, cupang_products.weight_g).
|
||||||
|
|
||||||
|
상자에 넣는 값: weight_g = 아는 무게의 합(상자 안 제품 무게가 하나도 없으면 None),
|
||||||
|
weight_missing = 무게가 없는 제품코드 목록(일부만 없으면 합계는 그 제품을 뺀 값).
|
||||||
|
포장무게 칸(마이그레이션 007)이 없으면 아무것도 넣지 않고 False.
|
||||||
|
"""
|
||||||
|
if not store.weight_enabled():
|
||||||
|
return False
|
||||||
|
weights = {
|
||||||
|
str(p.get("product_code") or "").strip(): p.get("weight_g")
|
||||||
|
for p in store.list_products(include_inactive=True)
|
||||||
|
}
|
||||||
|
for box in box_list:
|
||||||
|
contents = box.get("items") or []
|
||||||
|
total, missing = 0, []
|
||||||
|
for it in contents:
|
||||||
|
code = str(it.get("product_code") or "").strip()
|
||||||
|
w = weights.get(code)
|
||||||
|
if w is None:
|
||||||
|
if code not in missing:
|
||||||
|
missing.append(code)
|
||||||
|
continue
|
||||||
|
total += int(w) * int(it.get("quantity") or 0)
|
||||||
|
known = any(weights.get(str(it.get("product_code") or "").strip()) is not None for it in contents)
|
||||||
|
box["weight_g"] = total if known else None
|
||||||
|
box["weight_missing"] = missing
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _expand_box_list(
|
def _expand_box_list(
|
||||||
shipment: dict[str, Any], calc: dict[str, Any], items: list[dict[str, Any]]
|
shipment: dict[str, Any], calc: dict[str, Any], items: list[dict[str, Any]]
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
@@ -1349,6 +1407,8 @@ def products_page(request: Request) -> HTMLResponse:
|
|||||||
"page_subtitle": "왼쪽 itemcode_db 목록에서 선택해 등록하면 폼 드롭다운에 노출됩니다.",
|
"page_subtitle": "왼쪽 itemcode_db 목록에서 선택해 등록하면 폼 드롭다운에 노출됩니다.",
|
||||||
"products": store.list_products(include_inactive=True),
|
"products": store.list_products(include_inactive=True),
|
||||||
"registered_codes": [p["product_code"] for p in store.list_products(include_inactive=True)],
|
"registered_codes": [p["product_code"] for p in store.list_products(include_inactive=True)],
|
||||||
|
# 포장무게(g) — 마이그레이션 007 적용 전이면 무게 칸을 숨긴다
|
||||||
|
"weight_enabled": store.weight_enabled(),
|
||||||
"search_enabled": bool(reader and reader.enabled),
|
"search_enabled": bool(reader and reader.enabled),
|
||||||
"search_reason": (reader.reason if reader else ""),
|
"search_reason": (reader.reason if reader else ""),
|
||||||
},
|
},
|
||||||
@@ -1412,6 +1472,7 @@ def product_upsert(
|
|||||||
product_code: str = Form(...),
|
product_code: str = Form(...),
|
||||||
product_name: str = Form(...),
|
product_name: str = Form(...),
|
||||||
coupang_item_code: str = Form(""),
|
coupang_item_code: str = Form(""),
|
||||||
|
weight_g: str = Form(""),
|
||||||
sort_order: int = Form(0),
|
sort_order: int = Form(0),
|
||||||
user: dict[str, Any] = Depends(_require_user),
|
user: dict[str, Any] = Depends(_require_user),
|
||||||
) -> RedirectResponse:
|
) -> RedirectResponse:
|
||||||
@@ -1422,9 +1483,10 @@ def product_upsert(
|
|||||||
store.upsert_product(
|
store.upsert_product(
|
||||||
product_code=product_code,
|
product_code=product_code,
|
||||||
product_name=product_name,
|
product_name=product_name,
|
||||||
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드를 유지한다.
|
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드·포장무게를 유지한다.
|
||||||
coupang_item_code=(coupang_item_code.strip() or None),
|
coupang_item_code=(coupang_item_code.strip() or None),
|
||||||
sort_order=sort_order,
|
sort_order=sort_order,
|
||||||
|
weight_g=parse_weight_g(weight_g),
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc))
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
@@ -1457,7 +1519,8 @@ def product_edit(
|
|||||||
payload: dict[str, Any] = Body(...),
|
payload: dict[str, Any] = Body(...),
|
||||||
user: dict[str, Any] = Depends(_require_user),
|
user: dict[str, Any] = Depends(_require_user),
|
||||||
) -> JSONResponse:
|
) -> JSONResponse:
|
||||||
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code}."""
|
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code, weight_g?}.
|
||||||
|
weight_g 키가 있으면 저장(빈 값 = 지움), 없으면 무게는 그대로."""
|
||||||
store = _store(request)
|
store = _store(request)
|
||||||
if store is None:
|
if store is None:
|
||||||
raise HTTPException(status_code=503, detail="cupang_db 미설정")
|
raise HTTPException(status_code=503, detail="cupang_db 미설정")
|
||||||
@@ -1467,6 +1530,7 @@ def product_edit(
|
|||||||
product_name=str(payload.get("product_name") or ""),
|
product_name=str(payload.get("product_name") or ""),
|
||||||
product_code=str(payload.get("product_code") or ""),
|
product_code=str(payload.get("product_code") or ""),
|
||||||
coupang_item_code=str(payload.get("coupang_item_code") or ""),
|
coupang_item_code=str(payload.get("coupang_item_code") or ""),
|
||||||
|
weight_g=(parse_weight_g(payload.get("weight_g")) if "weight_g" in payload else ...),
|
||||||
)
|
)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise HTTPException(status_code=404, detail="제품을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="제품을 찾을 수 없습니다.")
|
||||||
|
|||||||
@@ -94,3 +94,32 @@ def compute_boxes(quantity: int, units_per_box: int | None) -> dict[str, Any]:
|
|||||||
"remainder_units": qty % upb,
|
"remainder_units": qty % upb,
|
||||||
"required_boxes": math.ceil(qty / upb),
|
"required_boxes": math.ceil(qty / upb),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# 제품 포장무게(g) — cupang_products.weight_g (마이그레이션 007). 0 ~ 1,000,000g, 정수.
|
||||||
|
WEIGHT_MAX_G = 1_000_000
|
||||||
|
|
||||||
|
|
||||||
|
def parse_weight_g(value: Any) -> int | None:
|
||||||
|
"""포장무게 입력 → 그램 정수. 빈 값은 None(미입력).
|
||||||
|
|
||||||
|
"1,070" · " 1,070 " · "1070g" · "1070.0" 처럼 쉼표·공백·g 단위가 붙어도 읽는다.
|
||||||
|
숫자가 아니거나 음수·소수(0.5g 등)·범위 밖이면 ValueError.
|
||||||
|
"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
s = str(value).strip().replace(",", "").replace(" ", "")
|
||||||
|
if s.lower().endswith("g"):
|
||||||
|
s = s[:-1]
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
f = float(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"포장무게는 숫자(g)로 입력하세요: {value}")
|
||||||
|
if f != f or f < 0 or f != int(f):
|
||||||
|
raise ValueError(f"포장무게는 0 이상의 정수(g)로 입력하세요: {value}")
|
||||||
|
v = int(f)
|
||||||
|
if v > WEIGHT_MAX_G:
|
||||||
|
raise ValueError(f"포장무게가 너무 큽니다(최대 {WEIGHT_MAX_G:,}g): {value}")
|
||||||
|
return v
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
@@ -34,6 +34,12 @@
|
|||||||
<input class="erp-input" type="text" name="product_code" required placeholder="예: MS-1012" /></label>
|
<input class="erp-input" type="text" name="product_code" required placeholder="예: MS-1012" /></label>
|
||||||
<label class="erp-field"><span>쿠팡상품코드</span>
|
<label class="erp-field"><span>쿠팡상품코드</span>
|
||||||
<input class="erp-input" type="text" name="coupang_item_code" placeholder="예: 1234567890" /></label>
|
<input class="erp-input" type="text" name="coupang_item_code" placeholder="예: 1234567890" /></label>
|
||||||
|
{% if weight_enabled %}
|
||||||
|
{# 포장무게(g) — 쉼표·g 붙여도 됨(1,070). 비워 두면 같은 제품코드의 기존 무게 유지 #}
|
||||||
|
<label class="erp-field cpg-weight-field"><span>포장무게(g)</span>
|
||||||
|
<input class="erp-input" type="text" name="weight_g" inputmode="numeric" autocomplete="off"
|
||||||
|
pattern="\s*[0-9][0-9,]*\s*(g|G)?\s*" title="숫자(g)로 입력하세요. 예: 1,070" placeholder="예: 1,070" /></label>
|
||||||
|
{% endif %}
|
||||||
<button type="submit" class="erp-btn erp-btn-primary">추가</button>
|
<button type="submit" class="erp-btn erp-btn-primary">추가</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
@@ -60,6 +66,7 @@
|
|||||||
<th><button type="button" class="cpg-sort" data-sort-key="name">제품명<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
<th><button type="button" class="cpg-sort" data-sort-key="name">제품명<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||||
<th><button type="button" class="cpg-sort" data-sort-key="code">제품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
<th><button type="button" class="cpg-sort" data-sort-key="code">제품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||||
<th><button type="button" class="cpg-sort" data-sort-key="cpcode">쿠팡상품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
<th><button type="button" class="cpg-sort" data-sort-key="cpcode">쿠팡상품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
|
||||||
|
{% if weight_enabled %}<th class="cpg-weight-col"><button type="button" class="cpg-sort" data-sort-key="weight">포장무게<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>{% endif %}
|
||||||
<th>상태</th>
|
<th>상태</th>
|
||||||
<th>동작</th>
|
<th>동작</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -68,10 +75,12 @@
|
|||||||
{% for p in products %}
|
{% for p in products %}
|
||||||
<tr data-name="{{ p.product_name }}" data-code="{{ p.product_code }}"
|
<tr data-name="{{ p.product_name }}" data-code="{{ p.product_code }}"
|
||||||
data-cpcode="{{ p.coupang_item_code }}"
|
data-cpcode="{{ p.coupang_item_code }}"
|
||||||
|
data-weight="{{ p.weight_g if p.weight_g is not none else '' }}"
|
||||||
class="cpg-prod-row{% if not p.active %} is-inactive{% endif %}">
|
class="cpg-prod-row{% if not p.active %} is-inactive{% endif %}">
|
||||||
<td title="{{ p.product_name }}">{{ p.product_name }}</td>
|
<td title="{{ p.product_name }}">{{ p.product_name }}</td>
|
||||||
<td title="{{ p.product_code }}">{{ p.product_code }}</td>
|
<td title="{{ p.product_code }}">{{ p.product_code }}</td>
|
||||||
<td class="cpg-cpcode" title="{{ p.coupang_item_code }}">{% if p.coupang_item_code %}{{ p.coupang_item_code }}{% else %}<span class="erp-muted">—</span>{% endif %}</td>
|
<td class="cpg-cpcode" title="{{ p.coupang_item_code }}">{% if p.coupang_item_code %}{{ p.coupang_item_code }}{% else %}<span class="erp-muted">—</span>{% endif %}</td>
|
||||||
|
{% if weight_enabled %}<td class="cpg-weight-col">{% if p.weight_g is not none %}{{ "{:,}".format(p.weight_g) }}<span class="cpg-weight-unit">g</span>{% else %}<span class="erp-muted">—</span>{% endif %}</td>{% endif %}
|
||||||
<td>
|
<td>
|
||||||
<!-- 배지 자체가 토글 버튼: 클릭 → 활성/비활성 전환 -->
|
<!-- 배지 자체가 토글 버튼: 클릭 → 활성/비활성 전환 -->
|
||||||
<button type="button" class="erp-badge cpg-active-toggle
|
<button type="button" class="erp-badge cpg-active-toggle
|
||||||
@@ -92,7 +101,7 @@
|
|||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if not products %}
|
{% if not products %}
|
||||||
<tr class="cpg-no-sort"><td colspan="5" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
|
<tr class="cpg-no-sort"><td colspan="{{ 6 if weight_enabled else 5 }}" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -117,6 +126,10 @@
|
|||||||
rows.sort(function (a, b) {
|
rows.sort(function (a, b) {
|
||||||
var av = a.getAttribute("data-" + state.key) || "";
|
var av = a.getAttribute("data-" + state.key) || "";
|
||||||
var bv = b.getAttribute("data-" + state.key) || "";
|
var bv = b.getAttribute("data-" + state.key) || "";
|
||||||
|
if (state.key === "weight") { // 포장무게 — 숫자 크기순, 무게 없는 줄은 늘 맨 뒤
|
||||||
|
if (!av || !bv) return (av ? 0 : 1) - (bv ? 0 : 1);
|
||||||
|
return (Number(av) - Number(bv)) * state.dir;
|
||||||
|
}
|
||||||
return collator.compare(av, bv) * state.dir;
|
return collator.compare(av, bv) * state.dir;
|
||||||
});
|
});
|
||||||
rows.forEach(function (r) { tbody.appendChild(r); });
|
rows.forEach(function (r) { tbody.appendChild(r); });
|
||||||
@@ -150,6 +163,10 @@
|
|||||||
<input class="erp-input" type="text" id="cpg-edit-code" /></label>
|
<input class="erp-input" type="text" id="cpg-edit-code" /></label>
|
||||||
<label class="erp-field"><span>쿠팡상품코드</span>
|
<label class="erp-field"><span>쿠팡상품코드</span>
|
||||||
<input class="erp-input" type="text" id="cpg-edit-cpcode" placeholder="비우면 지워집니다" /></label>
|
<input class="erp-input" type="text" id="cpg-edit-cpcode" placeholder="비우면 지워집니다" /></label>
|
||||||
|
{% if weight_enabled %}
|
||||||
|
<label class="erp-field"><span>포장무게(g)</span>
|
||||||
|
<input class="erp-input" type="text" id="cpg-edit-weight" inputmode="numeric" autocomplete="off" placeholder="예: 1,070 (비우면 지워집니다)" /></label>
|
||||||
|
{% endif %}
|
||||||
<p class="erp-muted" id="cpg-edit-msg" style="margin:0;font-size:12px;"></p>
|
<p class="erp-muted" id="cpg-edit-msg" style="margin:0;font-size:12px;"></p>
|
||||||
<div class="cpg-dlg-actions erp-page-actions">
|
<div class="cpg-dlg-actions erp-page-actions">
|
||||||
<button type="button" class="erp-btn erp-btn-outline" data-edit-close>취소</button>
|
<button type="button" class="erp-btn erp-btn-outline" data-edit-close>취소</button>
|
||||||
@@ -167,6 +184,7 @@
|
|||||||
var elName = document.getElementById("cpg-edit-name");
|
var elName = document.getElementById("cpg-edit-name");
|
||||||
var elCode = document.getElementById("cpg-edit-code");
|
var elCode = document.getElementById("cpg-edit-code");
|
||||||
var elCp = document.getElementById("cpg-edit-cpcode");
|
var elCp = document.getElementById("cpg-edit-cpcode");
|
||||||
|
var elW = document.getElementById("cpg-edit-weight"); // 마이그레이션 007 전이면 없음
|
||||||
var elMsg = document.getElementById("cpg-edit-msg");
|
var elMsg = document.getElementById("cpg-edit-msg");
|
||||||
var saveBtn = document.getElementById("cpg-edit-save");
|
var saveBtn = document.getElementById("cpg-edit-save");
|
||||||
var editingId = null;
|
var editingId = null;
|
||||||
@@ -181,6 +199,10 @@
|
|||||||
elName.value = row.getAttribute("data-name") || "";
|
elName.value = row.getAttribute("data-name") || "";
|
||||||
elCode.value = row.getAttribute("data-code") || "";
|
elCode.value = row.getAttribute("data-code") || "";
|
||||||
elCp.value = row.getAttribute("data-cpcode") || "";
|
elCp.value = row.getAttribute("data-cpcode") || "";
|
||||||
|
if (elW) {
|
||||||
|
var w = row.getAttribute("data-weight") || "";
|
||||||
|
elW.value = w ? Number(w).toLocaleString("ko-KR") : "";
|
||||||
|
}
|
||||||
elMsg.textContent = "";
|
elMsg.textContent = "";
|
||||||
dlg.hidden = false;
|
dlg.hidden = false;
|
||||||
elName.focus();
|
elName.focus();
|
||||||
@@ -200,6 +222,12 @@
|
|||||||
product_code: (elCode.value || "").trim(),
|
product_code: (elCode.value || "").trim(),
|
||||||
coupang_item_code: (elCp.value || "").trim()
|
coupang_item_code: (elCp.value || "").trim()
|
||||||
};
|
};
|
||||||
|
if (elW) {
|
||||||
|
// 포장무게 — 쉼표·g 는 서버가 읽는다. 숫자가 아니면 여기서 먼저 막는다(빈 값 = 지움)
|
||||||
|
var wv = (elW.value || "").trim();
|
||||||
|
if (wv && !/^[0-9][0-9,]*\s*g?$/i.test(wv)) { elMsg.textContent = "포장무게는 숫자(g)로 입력하세요. 예: 1,070"; return; }
|
||||||
|
body.weight_g = wv;
|
||||||
|
}
|
||||||
if (!body.product_name || !body.product_code) {
|
if (!body.product_name || !body.product_code) {
|
||||||
elMsg.textContent = "제품명과 제품코드는 필수입니다."; return;
|
elMsg.textContent = "제품명과 제품코드는 필수입니다."; return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
||||||
@@ -73,16 +73,17 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cpg-sum-scroll">
|
<div class="cpg-sum-scroll cpg-boxno-scroll">
|
||||||
<table class="erp-table cpg-boxno-table">
|
<table class="erp-table cpg-boxno-table">
|
||||||
<colgroup>
|
<colgroup>
|
||||||
<col class="cpg-boxno-c-no" />
|
<col class="cpg-boxno-c-no" />
|
||||||
<col class="cpg-boxno-c-name" />
|
<col class="cpg-boxno-c-name" />
|
||||||
<col class="cpg-boxno-c-code" />
|
<col class="cpg-boxno-c-code" />
|
||||||
<col class="cpg-boxno-c-qty" />
|
<col class="cpg-boxno-c-qty" />
|
||||||
|
{% if box_weight %}<col class="cpg-boxno-c-weight" />{% endif %}
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th></tr>
|
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th>{% if box_weight %}<th title="상자에 든 제품의 수량 × 포장무게(설정(제품명)) 합계">무게</th>{% endif %}</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for b in box_list %}
|
{% for b in box_list %}
|
||||||
@@ -94,13 +95,40 @@
|
|||||||
<td title="{{ it.product_name }}">{{ it.product_name }}</td>
|
<td title="{{ it.product_name }}">{{ it.product_name }}</td>
|
||||||
<td class="cpg-boxno-code">{{ it.product_code }}</td>
|
<td class="cpg-boxno-code">{{ it.product_code }}</td>
|
||||||
<td class="cpg-calc-num">{{ it.quantity }}</td>
|
<td class="cpg-calc-num">{{ it.quantity }}</td>
|
||||||
|
{% if box_weight and loop.first %}
|
||||||
|
{# 상자 무게 합계 — 상자번호처럼 상자 단위로 한 칸. 무게 없는 제품이 있으면 표시 #}
|
||||||
|
{% set miss = b.weight_missing or [] %}
|
||||||
|
<td class="cpg-boxno-weight" rowspan="{{ b['items']|length }}"
|
||||||
|
{% if miss %}title="포장무게 미입력: {{ miss|join(', ') }}{% if b.weight_g is not none %} — 이 제품을 뺀 합계{% endif %} (설정(제품명)에서 입력)"{% endif %}>
|
||||||
|
{%- if b.weight_g is not none -%}
|
||||||
|
{{ b.weight_kg }}<span class="cpg-weight-unit">kg</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||||
|
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if not box_list %}
|
{% if not box_list %}
|
||||||
<tr><td colspan="4" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
<tr><td colspan="{{ 5 if box_weight else 4 }}" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
{% if box_list %}
|
||||||
|
{# 합계 행 — 수량 합계, 무게 합계(kg). 무게 없는 제품이 있으면 아는 무게만 더한 값 #}
|
||||||
|
<tfoot>
|
||||||
|
<tr class="cpg-boxno-total">
|
||||||
|
<td class="cpg-boxno-cell" colspan="3">합계</td>
|
||||||
|
<td class="cpg-calc-num">{{ "{:,}".format(box_qty_total) }}</td>
|
||||||
|
{% if box_weight %}
|
||||||
|
<td class="cpg-boxno-weight"
|
||||||
|
{% if box_weight_partial %}title="포장무게 미입력 제품이 있어 아는 무게만 더한 합계 (설정(제품명)에서 입력)"{% endif %}>
|
||||||
|
{%- if box_weight_total_kg is not none -%}
|
||||||
|
{{ box_weight_total_kg }}<span class="cpg-weight-unit">kg</span>{% if box_weight_partial %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||||
|
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
{% endif %}
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""긴급 공지 — ERP 전체 화면 가운데에 띄우는 공지(2026-10-12).
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/notice) — 만들기·고치기는 수퍼관리자만, 받기·[확인]은 로그인 사용자 누구나
|
||||||
|
- 저장소: `db.py` (project_db 마이그레이션 024 의 urgent_notice* 표 — 프로젝트 저장소의 연결 풀을 같이 쓴다)
|
||||||
|
- 검증: `store.py`
|
||||||
|
- 화면: 관리 `templates/notice/admin.html` + `static/erp-notice-admin.js`, 표시 `static/erp-notice.js`(erp_base.html 공용)
|
||||||
|
상세는 docs/NOTICE_MODULE.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_notice_store"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_notice_store(project_store: Any) -> Any:
|
||||||
|
"""프로젝트 저장소(PROJECT_DB_URL)가 있으면 그 연결 풀로 NoticeStore, 없으면 None(공지 API 는 503)."""
|
||||||
|
if project_store is None:
|
||||||
|
return None
|
||||||
|
from .db import NoticeStore # noqa: WPS433
|
||||||
|
|
||||||
|
return NoticeStore(project_store.pool)
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
"""긴급 공지 저장소 — project_db(마이그레이션 024)의 urgent_notice* 표. 연결 풀은 프로젝트 저장소와 같이 쓴다."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg import errors as psycopg_errors
|
||||||
|
|
||||||
|
from app.modules.project import store as pj_store
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(v: Any) -> str:
|
||||||
|
return v.astimezone(KST).isoformat(timespec="minutes") if isinstance(v, datetime) else ""
|
||||||
|
|
||||||
|
|
||||||
|
class NoticeStore:
|
||||||
|
def __init__(self, pool: Any) -> None:
|
||||||
|
self._pool = pool
|
||||||
|
|
||||||
|
def _conn(self) -> Any:
|
||||||
|
return self._pool.connection()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _run(fn: Any) -> Any:
|
||||||
|
try:
|
||||||
|
return fn()
|
||||||
|
except psycopg_errors.UndefinedTable:
|
||||||
|
raise store.NoticeMigrationNeeded()
|
||||||
|
|
||||||
|
# ── 읽기 ────────────────────────────────────────────────
|
||||||
|
@staticmethod
|
||||||
|
def _row(r: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"id": int(r["id"]), "title": r["title"], "body_html": r["body_html"],
|
||||||
|
"show_at": _iso(r["show_at"]), "to_all": bool(r["to_all"]),
|
||||||
|
"created_by": r["created_by"], "created_at": _iso(r["created_at"]),
|
||||||
|
"updated_by": r.get("updated_by") or "", "updated_at": _iso(r.get("updated_at")),
|
||||||
|
"cancelled_at": _iso(r.get("cancelled_at")), "cancelled_by": r.get("cancelled_by") or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_notices(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||||
|
"""관리 화면 — 최근 것부터. 받는 사람·확인한 사람 목록을 함께."""
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM urgent_notices ORDER BY show_at DESC, id DESC LIMIT %s",
|
||||||
|
(int(limit),)).fetchall()
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
targets: dict[int, list[str]] = {i: [] for i in ids}
|
||||||
|
acks: dict[int, dict[str, str]] = {i: {} for i in ids}
|
||||||
|
if ids:
|
||||||
|
for t in conn.execute("SELECT notice_id, user_email FROM urgent_notice_targets "
|
||||||
|
"WHERE notice_id = ANY(%s) ORDER BY user_email", (ids,)).fetchall():
|
||||||
|
targets[int(t["notice_id"])].append(t["user_email"])
|
||||||
|
for a in conn.execute("SELECT notice_id, user_email, acked_at FROM urgent_notice_acks "
|
||||||
|
"WHERE notice_id = ANY(%s) ORDER BY acked_at", (ids,)).fetchall():
|
||||||
|
acks[int(a["notice_id"])][a["user_email"]] = _iso(a["acked_at"])
|
||||||
|
return [{**self._row(r), "targets": targets[int(r["id"])], "acks": acks[int(r["id"])]} for r in rows]
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def pending_for(self, *, email: str, now: datetime | None = None) -> list[dict[str, Any]]:
|
||||||
|
"""이 사람이 지금 봐야 할 공지 — 취소 안 됨·띄울 시각이 지남·받는 사람(전체 또는 지정)·아직 [확인] 안 함. 오래된 것부터."""
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT n.* FROM urgent_notices n "
|
||||||
|
"WHERE n.cancelled_at IS NULL AND n.show_at <= %s "
|
||||||
|
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
|
||||||
|
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
|
||||||
|
" AND NOT EXISTS (SELECT 1 FROM urgent_notice_acks a WHERE a.notice_id = n.id AND a.user_email = %s) "
|
||||||
|
"ORDER BY n.show_at ASC, n.id ASC LIMIT 20",
|
||||||
|
(now or datetime.now(KST), em, em),
|
||||||
|
).fetchall()
|
||||||
|
return [self._row(r) for r in rows]
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def get_notice(self, *, notice_id: int) -> dict[str, Any] | None:
|
||||||
|
def run() -> dict[str, Any] | None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
r = conn.execute("SELECT * FROM urgent_notices WHERE id = %s", (notice_id,)).fetchone()
|
||||||
|
if r is None:
|
||||||
|
return None
|
||||||
|
t = [x["user_email"] for x in conn.execute(
|
||||||
|
"SELECT user_email FROM urgent_notice_targets WHERE notice_id = %s ORDER BY user_email",
|
||||||
|
(notice_id,)).fetchall()]
|
||||||
|
return {**self._row(r), "targets": t}
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def is_recipient(self, *, notice: dict[str, Any], email: str) -> bool:
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
return bool(notice["to_all"]) or em in notice.get("targets", [])
|
||||||
|
|
||||||
|
# ── 쓰기 ────────────────────────────────────────────────
|
||||||
|
def _link_images(self, conn: Any, notice_id: int, body: str, by: str) -> None:
|
||||||
|
"""본문에 든 이미지를 이 공지에 묶는다 — 내가 올린, 아직 어느 공지에도 안 묶인 이미지만(남의 공지 이미지 가로채기 방지)."""
|
||||||
|
ids = store.image_ids_in(body)
|
||||||
|
if ids:
|
||||||
|
conn.execute("UPDATE urgent_notice_images SET notice_id = %s "
|
||||||
|
"WHERE id = ANY(%s) AND notice_id IS NULL AND uploaded_by = %s", (notice_id, ids, by))
|
||||||
|
# 하루 넘게 어느 공지에도 안 묶인 이미지(올렸다가 저장 안 함)는 정리
|
||||||
|
conn.execute("DELETE FROM urgent_notice_images WHERE notice_id IS NULL AND created_at < now() - interval '1 day'")
|
||||||
|
|
||||||
|
def create_notice(self, *, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any, by: str) -> dict[str, Any]:
|
||||||
|
ttl = store.validate_title(title)
|
||||||
|
html = store.sanitize_body(body)
|
||||||
|
when = store.parse_show_at(show_at)
|
||||||
|
all_, emails = store.validate_targets(to_all, targets)
|
||||||
|
who = pj_store.norm_str(by, lower=True)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
nid = int(conn.execute(
|
||||||
|
"INSERT INTO urgent_notices (title, body_html, show_at, to_all, created_by, updated_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s) RETURNING id", (ttl, html, when, all_, who, who),
|
||||||
|
).fetchone()["id"])
|
||||||
|
for em in emails:
|
||||||
|
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING", (nid, em))
|
||||||
|
self._link_images(conn, nid, html, who)
|
||||||
|
return nid
|
||||||
|
return self.get_notice(notice_id=self._run(run)) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def update_notice(self, *, notice_id: int, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any,
|
||||||
|
by: str, reshow: bool = False) -> dict[str, Any]:
|
||||||
|
"""고치기 — 받는 사람·시각·내용 전부. reshow=True 면 이미 [확인]한 사람에게도 다시 띄운다(확인 기록 지움)."""
|
||||||
|
ttl = store.validate_title(title)
|
||||||
|
html = store.sanitize_body(body)
|
||||||
|
when = store.parse_show_at(show_at)
|
||||||
|
all_, emails = store.validate_targets(to_all, targets)
|
||||||
|
who = pj_store.norm_str(by, lower=True)
|
||||||
|
|
||||||
|
def run() -> None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute("UPDATE urgent_notices SET title=%s, body_html=%s, show_at=%s, to_all=%s, "
|
||||||
|
"updated_by=%s, updated_at=now() WHERE id=%s RETURNING id",
|
||||||
|
(ttl, html, when, all_, who, notice_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(notice_id)
|
||||||
|
conn.execute("DELETE FROM urgent_notice_targets WHERE notice_id = %s", (notice_id,))
|
||||||
|
for em in emails:
|
||||||
|
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING", (notice_id, em))
|
||||||
|
if reshow:
|
||||||
|
conn.execute("DELETE FROM urgent_notice_acks WHERE notice_id = %s", (notice_id,))
|
||||||
|
self._link_images(conn, notice_id, html, who)
|
||||||
|
self._run(run)
|
||||||
|
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def cancel_notice(self, *, notice_id: int, by: str, cancel: bool = True) -> dict[str, Any]:
|
||||||
|
"""취소(더 띄우지 않음) · 취소 되돌리기. 기록은 남는다."""
|
||||||
|
def run() -> None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE urgent_notices SET cancelled_at = CASE WHEN %s THEN now() ELSE NULL END, "
|
||||||
|
"cancelled_by = CASE WHEN %s THEN %s ELSE '' END, updated_at = now() WHERE id = %s RETURNING id",
|
||||||
|
(cancel, cancel, pj_store.norm_str(by, lower=True), notice_id),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(notice_id)
|
||||||
|
self._run(run)
|
||||||
|
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def ack(self, *, notice_id: int, email: str) -> bool:
|
||||||
|
"""[확인] — 처음이면 True(이미 확인했으면 False). 받는 사람·표시 시각 확인은 라우터가 먼저 한다."""
|
||||||
|
def run() -> bool:
|
||||||
|
with self._conn() as conn:
|
||||||
|
r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING RETURNING notice_id",
|
||||||
|
(notice_id, pj_store.norm_str(email, lower=True))).fetchone()
|
||||||
|
return r is not None
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
# ── 이미지 ──────────────────────────────────────────────
|
||||||
|
def add_image(self, *, data: bytes, filename: str, by: str) -> dict[str, Any]:
|
||||||
|
ctype = store.sniff_image(data)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
with self._conn() as conn:
|
||||||
|
return int(conn.execute(
|
||||||
|
"INSERT INTO urgent_notice_images (filename, content_type, size_bytes, data, uploaded_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(pj_store.norm_str(filename)[:200], ctype, len(data), data, pj_store.norm_str(by, lower=True)),
|
||||||
|
).fetchone()["id"])
|
||||||
|
iid = self._run(run)
|
||||||
|
return {"id": iid, "url": f"/notice/images/{iid}", "content_type": ctype}
|
||||||
|
|
||||||
|
def get_image(self, *, image_id: int) -> dict[str, Any] | None:
|
||||||
|
def run() -> dict[str, Any] | None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
r = conn.execute("SELECT id, notice_id, content_type, data, uploaded_by FROM urgent_notice_images "
|
||||||
|
"WHERE id = %s", (image_id,)).fetchone()
|
||||||
|
return dict(r) if r else None
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def enabled(self) -> bool:
|
||||||
|
try:
|
||||||
|
with self._conn() as conn:
|
||||||
|
return bool(conn.execute("SELECT to_regclass('public.urgent_notices') AS r").fetchone()["r"])
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return False
|
||||||
|
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
"""긴급 공지 라우터(/notice) — ERP 전체 화면 가운데 공지.
|
||||||
|
|
||||||
|
- 만들기·고치기·취소·이미지 올리기·확인 현황: 수퍼관리자(app.store.SUPER_ADMIN_EMAIL)만.
|
||||||
|
- 받기(GET /notice/api/pending)·[확인]: 로그인한 등록 사용자 누구나 — 모듈 권한과 무관(ERP 전체 공지).
|
||||||
|
- 저장: project_db 024(urgent_notice*). PROJECT_DB_URL 이 없거나 024 미적용이면 503(화면 스크립트는 조용히 멈춘다).
|
||||||
|
- 핸들러는 동기 DB 라 def(프로젝트 라우터와 같은 이유).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/notice", tags=["notice"])
|
||||||
|
|
||||||
|
_MIGRATION_MSG = "긴급 공지 기능이 아직 준비되지 않았습니다(project_db 마이그레이션 024 필요)."
|
||||||
|
|
||||||
|
|
||||||
|
def _user(request: Request) -> dict[str, Any]:
|
||||||
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _is_super(user: dict[str, Any]) -> bool:
|
||||||
|
from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433
|
||||||
|
|
||||||
|
return str(user.get("email") or "").strip().lower() == SUPER_ADMIN_EMAIL
|
||||||
|
|
||||||
|
|
||||||
|
def _super(request: Request) -> dict[str, Any]:
|
||||||
|
user = _user(request)
|
||||||
|
if not _is_super(user):
|
||||||
|
raise HTTPException(status_code=403, detail="긴급 공지는 수퍼관리자만 만들 수 있습니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _store(request: Request) -> Any:
|
||||||
|
st = getattr(request.app.state, "notice_store", None)
|
||||||
|
if st is None:
|
||||||
|
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _call(fn: Any, **kw: Any) -> Any:
|
||||||
|
try:
|
||||||
|
return fn(**kw)
|
||||||
|
except store.NoticeMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
except KeyError:
|
||||||
|
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
def _public(n: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""받는 사람 화면에 보내는 값 — 받는 사람 목록·확인 현황은 빼고."""
|
||||||
|
return {k: n[k] for k in ("id", "title", "body_html", "show_at", "created_by")}
|
||||||
|
|
||||||
|
|
||||||
|
# ── 화면 ─────────────────────────────────────────────────────
|
||||||
|
@router.get("/", response_class=HTMLResponse)
|
||||||
|
def notice_admin_page(request: Request) -> HTMLResponse:
|
||||||
|
"""긴급 공지 관리 — 수퍼관리자만. 목록(예약·표시 중·취소)·확인 현황·새 공지."""
|
||||||
|
from app.main import build_erp_nav, render_template, user_store # noqa: WPS433
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
user = _super(request)
|
||||||
|
st = getattr(request.app.state, "notice_store", None)
|
||||||
|
enabled = bool(st) and st.enabled()
|
||||||
|
# 받는 사람 후보 = 등록 사용자 전원 — 프로젝트 멤버 고르기와 같은 모양(아이콘 + 이름)으로 그린다(project.js memberPickHtml)
|
||||||
|
people = sorted(
|
||||||
|
({"email": u["email"], "id": u["email"].split("@")[0], "name": u.get("name") or u["email"].split("@")[0],
|
||||||
|
"avatar": u.get("picture") or ""} for u in user_store.list_all()),
|
||||||
|
key=lambda p: p["id"],
|
||||||
|
)
|
||||||
|
return render_template(request, "notice/admin.html", {
|
||||||
|
"user": user, "is_admin": is_admin(user),
|
||||||
|
"nav_items": build_erp_nav(user, active=""),
|
||||||
|
"page_title": "긴급 공지", "page_subtitle": "정한 시각에 받는 사람 화면 가운데에 띄웁니다([확인] 전까지)",
|
||||||
|
"enabled": enabled, "people": people,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# ── 받는 사람 ────────────────────────────────────────────────
|
||||||
|
@router.get("/api/pending")
|
||||||
|
def api_pending(request: Request) -> JSONResponse:
|
||||||
|
"""지금 내가 봐야 할 공지(띄울 시각이 지났고 아직 [확인] 안 한 것, 오래된 것부터)."""
|
||||||
|
user = _user(request)
|
||||||
|
st = _store(request)
|
||||||
|
rows = _call(st.pending_for, email=user["email"])
|
||||||
|
return JSONResponse({"notices": [_public(n) for n in rows]})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/{notice_id}/ack")
|
||||||
|
def api_ack(request: Request, notice_id: int) -> JSONResponse:
|
||||||
|
"""[확인] — 받는 사람이고 이미 띄워진(취소 안 된) 공지만. 여러 번 눌러도 한 번 기록."""
|
||||||
|
user = _user(request)
|
||||||
|
st = _store(request)
|
||||||
|
n = _call(st.get_notice, notice_id=notice_id)
|
||||||
|
if n is None or not st.is_recipient(notice=n, email=user["email"]):
|
||||||
|
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
|
||||||
|
_call(st.ack, notice_id=notice_id, email=user["email"])
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/images/{image_id}")
|
||||||
|
def notice_image(request: Request, image_id: int) -> Response:
|
||||||
|
"""공지 본문 이미지 — 수퍼관리자, 또는 그 공지를 받는 사람(띄울 시각이 지난 공지)만."""
|
||||||
|
from datetime import datetime # noqa: WPS433
|
||||||
|
|
||||||
|
from app.timezone import KST # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
st = _store(request)
|
||||||
|
img = _call(st.get_image, image_id=image_id)
|
||||||
|
if img is None:
|
||||||
|
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
|
||||||
|
if not _is_super(user):
|
||||||
|
n = _call(st.get_notice, notice_id=int(img["notice_id"])) if img["notice_id"] else None
|
||||||
|
if (n is None or n["cancelled_at"] or not st.is_recipient(notice=n, email=user["email"])
|
||||||
|
or datetime.fromisoformat(n["show_at"]) > datetime.now(KST)):
|
||||||
|
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
|
||||||
|
return Response(content=bytes(img["data"]), media_type=img["content_type"], headers={
|
||||||
|
"X-Content-Type-Options": "nosniff", "Cache-Control": "private, max-age=3600",
|
||||||
|
"Content-Security-Policy": "default-src 'none'; img-src 'self'; sandbox",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# ── 수퍼관리자 ───────────────────────────────────────────────
|
||||||
|
@router.get("/api/notices")
|
||||||
|
def api_list(request: Request) -> JSONResponse:
|
||||||
|
_super(request)
|
||||||
|
st = _store(request)
|
||||||
|
return JSONResponse({"notices": _call(st.list_notices)})
|
||||||
|
|
||||||
|
|
||||||
|
def _fields(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"title": payload.get("title"), "body": payload.get("body_html") or "",
|
||||||
|
"show_at": payload.get("show_at"), "to_all": payload.get("to_all", True),
|
||||||
|
"targets": payload.get("targets") or []}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/notices")
|
||||||
|
def api_create(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
n = _call(st.create_notice, **_fields(payload), by=user["email"])
|
||||||
|
return JSONResponse({"notice": n}, status_code=201)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/notices/{notice_id}")
|
||||||
|
def api_update(request: Request, notice_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""고치기 — reshow=true 면 이미 [확인]한 사람에게도 다시 띄운다."""
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
n = _call(st.update_notice, notice_id=notice_id, **_fields(payload), by=user["email"],
|
||||||
|
reshow=payload.get("reshow") is True)
|
||||||
|
return JSONResponse({"notice": n})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/notices/{notice_id}/cancel")
|
||||||
|
def api_cancel(request: Request, notice_id: int, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
|
"""취소(더 띄우지 않음) {cancel: true} · 되돌리기 {cancel: false}."""
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
n = _call(st.cancel_notice, notice_id=notice_id, by=user["email"], cancel=payload.get("cancel", True) is not False)
|
||||||
|
return JSONResponse({"notice": n})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/images")
|
||||||
|
def api_upload_image(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||||
|
"""본문 이미지 올리기 — 저장(공지 만들기·고치기) 때 본문에 든 것만 그 공지에 묶인다."""
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
data = file.file.read(store.IMAGE_MAX_BYTES + 1)
|
||||||
|
img = _call(st.add_image, data=data, filename=file.filename or "image", by=user["email"])
|
||||||
|
return JSONResponse({"image": img}, status_code=201)
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""긴급 공지 — 순수 검증(DB 없음). 저장은 db.py, 화면·권한은 router.py."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.modules.project import store as pj_store
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
TITLE_MAX = 200
|
||||||
|
BODY_MAX = 100_000 # 정리한 HTML 기준(이미지는 주소만 들어간다)
|
||||||
|
IMAGE_MAX_BYTES = 10 * 1024 * 1024
|
||||||
|
TARGETS_MAX = 500
|
||||||
|
|
||||||
|
# 이미지 형식은 올린 쪽이 정한 Content-Type 이 아니라 파일 앞 바이트로 정한다(svg·html 은 받지 않는다).
|
||||||
|
_MAGIC: tuple[tuple[bytes, str], ...] = (
|
||||||
|
(b"\x89PNG\r\n\x1a\n", "image/png"),
|
||||||
|
(b"\xff\xd8\xff", "image/jpeg"),
|
||||||
|
(b"GIF87a", "image/gif"),
|
||||||
|
(b"GIF89a", "image/gif"),
|
||||||
|
)
|
||||||
|
_IMG_SRC_OK = re.compile(r"^/notice/images/(\d+)$")
|
||||||
|
_IMG_TAG = re.compile(r"<img\b[^>]*>", re.IGNORECASE)
|
||||||
|
_SRC_ATTR = re.compile(r"""\bsrc\s*=\s*"([^"]*)\"""", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
class NoticeMigrationNeeded(Exception):
|
||||||
|
"""project_db 024 미적용."""
|
||||||
|
|
||||||
|
|
||||||
|
def validate_title(v: Any) -> str:
|
||||||
|
t = pj_store.norm_str(v)
|
||||||
|
if not t:
|
||||||
|
raise ValueError("공지 제목을 입력하세요.")
|
||||||
|
if len(t) > TITLE_MAX:
|
||||||
|
raise ValueError(f"제목은 {TITLE_MAX}자 이하로 입력하세요.")
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_body(html: Any) -> str:
|
||||||
|
"""작업 설명란과 같은 허용 목록으로 정리한 뒤, 이미지는 공지 이미지 주소(/notice/images/{id})만 남긴다
|
||||||
|
(외부 주소·data: 이미지는 뺀다 — 받는 사람 화면에서 다른 곳으로 요청이 나가지 않게)."""
|
||||||
|
out = pj_store.sanitize_description_html(str(html or ""))
|
||||||
|
|
||||||
|
def keep(m: re.Match[str]) -> str:
|
||||||
|
src = _SRC_ATTR.search(m.group(0))
|
||||||
|
return m.group(0) if src and _IMG_SRC_OK.match(src.group(1)) else ""
|
||||||
|
out = _IMG_TAG.sub(keep, out)
|
||||||
|
if len(out) > BODY_MAX:
|
||||||
|
raise ValueError("내용이 너무 깁니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def image_ids_in(html: str) -> list[int]:
|
||||||
|
"""본문에 들어 있는 공지 이미지 id(순서대로, 중복 없이)."""
|
||||||
|
ids: list[int] = []
|
||||||
|
for tag in _IMG_TAG.findall(html or ""):
|
||||||
|
src = _SRC_ATTR.search(tag)
|
||||||
|
m = _IMG_SRC_OK.match(src.group(1)) if src else None
|
||||||
|
if m and int(m.group(1)) not in ids:
|
||||||
|
ids.append(int(m.group(1)))
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def parse_show_at(v: Any, *, now: datetime | None = None) -> datetime:
|
||||||
|
"""띄울 시각 — 'YYYY-MM-DDTHH:MM'(화면 입력, 한국시간) 또는 시간대가 붙은 ISO. 비우면 지금."""
|
||||||
|
s = pj_store.norm_str(v)
|
||||||
|
if not s:
|
||||||
|
return now or datetime.now(KST)
|
||||||
|
try:
|
||||||
|
d = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError("띄울 시각이 올바르지 않습니다.")
|
||||||
|
if d.tzinfo is None:
|
||||||
|
d = d.replace(tzinfo=KST)
|
||||||
|
if not 2000 <= d.year <= 2100:
|
||||||
|
raise ValueError("띄울 시각이 올바르지 않습니다.")
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def validate_targets(to_all: Any, targets: Any) -> tuple[bool, list[str]]:
|
||||||
|
"""(전체 여부, 받는 사람 이메일). 전체가 아니면 한 명 이상."""
|
||||||
|
if to_all is True or to_all in ("1", "true", "on"):
|
||||||
|
return True, []
|
||||||
|
emails = pj_store.normalize_emails(targets if isinstance(targets, (list, tuple)) else [])
|
||||||
|
if not emails:
|
||||||
|
raise ValueError("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요.")
|
||||||
|
if len(emails) > TARGETS_MAX:
|
||||||
|
raise ValueError(f"받는 사람은 {TARGETS_MAX}명까지 고를 수 있습니다.")
|
||||||
|
return False, emails
|
||||||
|
|
||||||
|
|
||||||
|
def sniff_image(data: bytes) -> str:
|
||||||
|
"""파일 앞 바이트로 이미지 형식 — png·jpeg·gif·webp 만. 아니면 ValueError."""
|
||||||
|
if not data:
|
||||||
|
raise ValueError("빈 파일입니다.")
|
||||||
|
if len(data) > IMAGE_MAX_BYTES:
|
||||||
|
raise ValueError("이미지는 10MB 이하만 올릴 수 있습니다.")
|
||||||
|
for magic, ctype in _MAGIC:
|
||||||
|
if data.startswith(magic):
|
||||||
|
return ctype
|
||||||
|
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||||
|
return "image/webp"
|
||||||
|
raise ValueError("이미지(png·jpg·gif·webp)만 올릴 수 있습니다.")
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}
|
||||||
|
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||||
|
<link rel="stylesheet" href="/static/project.css?v=20261013i" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{% if not enabled %}
|
||||||
|
<div class="ntc-card">
|
||||||
|
<h2>긴급 공지 준비 필요</h2>
|
||||||
|
<p>project_db 마이그레이션 024(<code>scripts/sql/project_db_024_urgent_notices.sql</code>)를 적용하면 사용할 수 있습니다.</p>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="ntc-wrap" id="ntc-root">
|
||||||
|
<section class="ntc-card" aria-labelledby="ntc-form-title">
|
||||||
|
<h2 id="ntc-form-title">새 긴급 공지</h2>
|
||||||
|
<input type="hidden" id="ntc-id" value="" />
|
||||||
|
<label class="ntc-field">제목
|
||||||
|
<input type="text" id="ntc-title" maxlength="200" placeholder="예: 오늘 18시 서버 점검" autocomplete="off" />
|
||||||
|
</label>
|
||||||
|
{# 내용 — 작업 설명란과 같은 편집기(서식 도구 전체·이미지 붙여넣기/버튼·크기 조절·링크·체크리스트) #}
|
||||||
|
<div class="ntc-field pj-desc-block ntc-desc">
|
||||||
|
<div class="pj-desc-toolbar"><span>내용</span><span class="pj-muted-sm" id="ntc-hint"></span></div>
|
||||||
|
{% with fmtbar_id = "ntc-fmtbar", img_input_id = "ntc-img-input" %}{% include "project/_desc_fmtbar.html" %}{% endwith %}
|
||||||
|
<div class="pj-desc-wrap">
|
||||||
|
<div class="pj-desc-editor" id="ntc-body" contenteditable="true" role="textbox" aria-multiline="true" aria-label="공지 내용"
|
||||||
|
data-placeholder="공지 내용을 쓰세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{# 띄울 날짜 — 프로젝트와 같은 날짜 팝업(공휴일·오늘·지우기), 시각은 옆 칸. 둘 다 비우면 바로 #}
|
||||||
|
<div class="ntc-field">띄울 시각 <small class="ntc-sub">한국시간 · 날짜를 비우면 바로</small>
|
||||||
|
<div class="ntc-when">
|
||||||
|
<input type="date" id="ntc-date" />
|
||||||
|
<input type="time" id="ntc-time" class="ntc-time" step="300" aria-label="띄울 시각" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="ntc-field">받는 사람
|
||||||
|
<div class="ntc-targets">
|
||||||
|
<div class="ntc-to">
|
||||||
|
<label><input type="radio" name="ntc-to" value="all" checked /> 전체(로그인하는 모든 사람)</label>
|
||||||
|
<label><input type="radio" name="ntc-to" value="some" /> 고른 사람만</label>
|
||||||
|
</div>
|
||||||
|
{# 프로젝트 멤버 고르기와 같은 모양 — 아이콘 + 이름 + 체크 #}
|
||||||
|
<div class="pj-member-picker ntc-people" id="ntc-people" hidden></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label class="ntc-field ntc-inline" id="ntc-reshow-row" hidden>
|
||||||
|
<input type="checkbox" id="ntc-reshow" /> 이미 [확인]한 사람에게도 다시 띄우기
|
||||||
|
</label>
|
||||||
|
<div class="ntc-actions">
|
||||||
|
<button type="button" class="pj-btn" id="ntc-reset">새로 쓰기</button>
|
||||||
|
<button type="button" class="pj-btn" id="ntc-preview">미리 보기</button>
|
||||||
|
<button type="button" class="pj-btn pj-btn-primary" id="ntc-save">공지 만들기</button>
|
||||||
|
</div>
|
||||||
|
<p class="ntc-msg" id="ntc-msg" role="alert" hidden></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="ntc-card" aria-labelledby="ntc-list-title">
|
||||||
|
<h2 id="ntc-list-title">공지 목록</h2>
|
||||||
|
<div class="ntc-list" id="ntc-list">불러오는 중…</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||||
|
<script src="/static/project.js?v=20261013i" defer></script>
|
||||||
|
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립.
|
||||||
|
|
||||||
|
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
|
||||||
|
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
|
||||||
|
- 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계).
|
||||||
|
|
||||||
|
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
|
||||||
|
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
|
||||||
|
날짜 줄 아래 캠페인 줄(1열 빈 칸)과 맨 위 "전체" 합계 줄은 건너뛴다.
|
||||||
|
|
||||||
|
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
|
from typing import Any, Callable, Mapping, Sequence
|
||||||
|
|
||||||
|
from . import calc
|
||||||
|
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
||||||
|
|
||||||
|
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
|
||||||
|
CHANNELS: tuple[tuple[str, str], ...] = (
|
||||||
|
("google", "구글"),
|
||||||
|
("meta", "메타"),
|
||||||
|
("naver", "네이버"),
|
||||||
|
("coupang_wing", "쿠팡(윙)"),
|
||||||
|
("coupang_rocket", "쿠팡(로켓)"),
|
||||||
|
("ohouse", "오늘의집"),
|
||||||
|
("gmarket", "G마켓"),
|
||||||
|
("kakao", "카카오"),
|
||||||
|
("gsshop", "GS샵"),
|
||||||
|
("elevenst", "11번가"),
|
||||||
|
("lotteon", "롯데ON"),
|
||||||
|
("toss", "토스"),
|
||||||
|
("atomy", "애터미아자몰"),
|
||||||
|
)
|
||||||
|
CHANNEL_NAMES = dict(CHANNELS)
|
||||||
|
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
|
||||||
|
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 구글·메타는 자체몰(카페24)로 보내는 광고라 카페24 매출.
|
||||||
|
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES}
|
||||||
|
ROAS_SALES_CODE.update({"google": "cafe24", "meta": "cafe24", "coupang_wing": "coupang"})
|
||||||
|
|
||||||
|
|
||||||
|
def roas(sales: int, spend: int) -> int | None:
|
||||||
|
"""ROAS(%) = 매출 ÷ 광고비 × 100, 정수로 반올림. 광고비가 없으면 None."""
|
||||||
|
if not spend or spend <= 0:
|
||||||
|
return None
|
||||||
|
return int((Decimal(int(sales)) * 100 / Decimal(int(spend))).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def roas_basis(code: str) -> str:
|
||||||
|
"""머리글 말풍선 — ROAS 에 쓰는 매출."""
|
||||||
|
sales = ROAS_SALES_CODE[code]
|
||||||
|
return "카페24(자체몰)" if sales == "cafe24" else CHANNEL_NAMES.get(code, code)
|
||||||
|
|
||||||
|
ROCKET_DATE_COL = 0 # 1열 날짜
|
||||||
|
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
|
||||||
|
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
|
||||||
|
|
||||||
|
|
||||||
|
class AdMigrationNeeded(Exception):
|
||||||
|
"""광고비 표(마이그레이션 005: perf_ad_spend)가 아직 없음."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ParseResult:
|
||||||
|
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
|
||||||
|
errors: list[str] = field(default_factory=list)
|
||||||
|
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 파일 읽기
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _decode_csv(content: bytes) -> str:
|
||||||
|
for enc in ("utf-8-sig", "cp949"):
|
||||||
|
try:
|
||||||
|
return content.decode(enc)
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
continue
|
||||||
|
raise UploadError("CSV 글자 인코딩을 읽을 수 없습니다(UTF-8 또는 CP949 로 저장해 주세요).")
|
||||||
|
|
||||||
|
|
||||||
|
def read_rows(content: bytes, filename: str = "") -> list[tuple[Any, ...]]:
|
||||||
|
"""CSV 또는 엑셀(.xlsx) 첫 시트 → 줄 목록(값 그대로)."""
|
||||||
|
if not content:
|
||||||
|
raise UploadError("빈 파일입니다.")
|
||||||
|
if len(content) > MAX_FILE_BYTES:
|
||||||
|
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
||||||
|
is_xlsx = content[:2] == b"PK" or filename.lower().endswith(".xlsx")
|
||||||
|
if not is_xlsx:
|
||||||
|
return [tuple(r) for r in csv.reader(io.StringIO(_decode_csv(content)))]
|
||||||
|
try:
|
||||||
|
import openpyxl # noqa: WPS433
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||||
|
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
||||||
|
raise UploadError("파일을 읽을 수 없습니다. 쿠팡 광고 보고서 CSV 또는 엑셀(.xlsx) 파일을 올려 주세요.") from None
|
||||||
|
try:
|
||||||
|
return [tuple(r or ()) for r in wb.worksheets[0].iter_rows(values_only=True)]
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") -> ParseResult:
|
||||||
|
"""쿠팡(로켓) 광고 보고서 → (날짜, 청구금액(+부가가치세)). 잘못된 줄이 있으면 errors 에 담는다(저장은 라우터가 막음)."""
|
||||||
|
rows = read_rows(content, filename)
|
||||||
|
res = ParseResult()
|
||||||
|
seen: dict[date, int] = {}
|
||||||
|
for r, row in enumerate(rows, start=1):
|
||||||
|
raw_day = row[ROCKET_DATE_COL] if len(row) > ROCKET_DATE_COL else None
|
||||||
|
text = str(raw_day or "").strip()
|
||||||
|
if not text or text.replace(" ", "") in SKIP_LABELS:
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
day = parse_date(raw_day)
|
||||||
|
except ValueError:
|
||||||
|
if r == 1: # 머리글
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
res.errors.append(f"{r}행 1열: 날짜를 읽을 수 없습니다({text[:30]}).")
|
||||||
|
continue
|
||||||
|
if day is None:
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
raw_amt = row[ROCKET_AMOUNT_COL] if len(row) > ROCKET_AMOUNT_COL else None
|
||||||
|
try:
|
||||||
|
amt = parse_amount(raw_amt)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{r}행 19열: 금액이 숫자가 아닙니다({str(raw_amt)[:30]}).")
|
||||||
|
continue
|
||||||
|
if amt is None:
|
||||||
|
res.errors.append(f"{r}행 19열: {day.isoformat()} 청구금액이 비어 있습니다.")
|
||||||
|
elif abs(amt) > MAX_AMOUNT:
|
||||||
|
res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.")
|
||||||
|
elif day > today:
|
||||||
|
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||||
|
elif day in seen:
|
||||||
|
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
|
||||||
|
else:
|
||||||
|
seen[day] = r
|
||||||
|
res.entries.append((day, amt))
|
||||||
|
if len(res.entries) > MAX_DATA_ROWS:
|
||||||
|
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||||
|
if len(res.errors) > MAX_ERRORS:
|
||||||
|
break
|
||||||
|
if not res.entries and not res.errors:
|
||||||
|
raise UploadError("광고비 날짜 줄이 없습니다. 1열 날짜(예: 2026년 10월 01일), 19열 청구금액(+부가가치세) 양식인지 확인하세요.")
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
|
||||||
|
PARSERS: dict[str, Callable[..., ParseResult]] = {"coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
|
||||||
|
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
|
||||||
|
UPLOAD_HELP = {"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 화면 데이터
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||||
|
custom_from: date | None = None, custom_to: date | None = None,
|
||||||
|
holidays: Mapping[str, str] | None = None,
|
||||||
|
sales_codes: Sequence[str] = ()) -> dict[str, Any]:
|
||||||
|
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
|
||||||
|
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
|
||||||
|
codes = list(CHANNEL_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)
|
||||||
|
ref = period.end if period.end < today else today if period.start <= today else 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)
|
||||||
|
|
||||||
|
migration_needed = False
|
||||||
|
try:
|
||||||
|
amounts, sources = store.ad_amounts(q_start, q_end)
|
||||||
|
except AdMigrationNeeded:
|
||||||
|
amounts, sources, migration_needed = {}, {}, True
|
||||||
|
cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()}
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
|
||||||
|
total_codes = list(sales_codes)
|
||||||
|
need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes))
|
||||||
|
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
|
||||||
|
|
||||||
|
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
|
||||||
|
want = set(mcodes)
|
||||||
|
return sum(v for (d, c), v in sales.items() if c in want and s <= d <= e)
|
||||||
|
|
||||||
|
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
|
||||||
|
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
|
||||||
|
|
||||||
|
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": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
||||||
|
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
||||||
|
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
||||||
|
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
|
||||||
|
{"key": "mtd", "label": f"{month_period.label} 누적 광고비", "value": mtd.gross,
|
||||||
|
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label, "invert": True},
|
||||||
|
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
|
||||||
|
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||||
|
if k == "custom":
|
||||||
|
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
||||||
|
return f"?period={k}&d={anchor_d.isoformat()}"
|
||||||
|
|
||||||
|
if period.kind == "custom":
|
||||||
|
from datetime import timedelta # noqa: WPS433
|
||||||
|
|
||||||
|
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, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
||||||
|
nav = {"prev": prev_url, "next": next_url, "quick": [
|
||||||
|
{"label": "오늘", "url": url("day", today), "active": period.kind == "day" and period.start == today},
|
||||||
|
{"label": "이번주", "url": url("week", today), "active": period.kind == "week" and period.start <= today <= period.end},
|
||||||
|
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
|
||||||
|
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
|
||||||
|
]}
|
||||||
|
|
||||||
|
share = calc.by_code(cells, codes, period.start, period.end)
|
||||||
|
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
|
||||||
|
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||||
|
# 칸마다 ROAS — "광고비(ROAS%)" 로 보인다. 행 기간 = 그 날·주·월(합계 행은 선택 기간)
|
||||||
|
for row in table:
|
||||||
|
s = date.fromisoformat(row["from"]) if row.get("from") else period.start
|
||||||
|
e = date.fromisoformat(row["to"]) if row.get("to") else period.end
|
||||||
|
row["roas"] = {c: roas(sales_sum([ROAS_SALES_CODE[c]], s, e), row["cells"][c]["gross"]) for c in codes}
|
||||||
|
row["roas_total"] = roas(sales_sum(total_codes, s, e), row["total"]["gross"]) if total_codes else None
|
||||||
|
m_s, m_e = month_period.start, month_period.end
|
||||||
|
for r in month["rows"]:
|
||||||
|
r["roas"] = roas(sales_sum([ROAS_SALES_CODE[r["code"]]], m_s, m_e), r["gross"])
|
||||||
|
month["total"]["roas"] = roas(sales_sum(total_codes, m_s, m_e), month["total"]["gross"]) if total_codes else None
|
||||||
|
year = calc.year_months(year_period.start.year, codes, cells, today=today)
|
||||||
|
for i, r in enumerate(year["rows"], start=1):
|
||||||
|
s = date(year_period.start.year, i, 1)
|
||||||
|
r["roas"] = None if r.get("future") or not total_codes else roas(sales_sum(total_codes, s, calc.month_end(s)), r["gross"] or 0)
|
||||||
|
year["total"]["roas"] = roas(sales_sum(total_codes, year_period.start, year_period.end), year["total"]["gross"]) if total_codes else None
|
||||||
|
return {
|
||||||
|
"nav": nav,
|
||||||
|
"period": period,
|
||||||
|
"period_kind": period.kind,
|
||||||
|
"today": today.isoformat(),
|
||||||
|
"codes": codes,
|
||||||
|
"names": dict(CHANNEL_NAMES),
|
||||||
|
"kpis": kpis,
|
||||||
|
"table": table,
|
||||||
|
"month": month,
|
||||||
|
"year": year,
|
||||||
|
"roas_basis": {c: roas_basis(c) for c in codes},
|
||||||
|
"chart_daily": calc.daily_series(period, codes, cells),
|
||||||
|
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
|
||||||
|
# 업로드로 들어온 칸(표시용) — "날짜|채널"
|
||||||
|
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||||||
|
if s == "upload" and period.start <= d <= period.end),
|
||||||
|
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
|
||||||
|
"migration_needed": migration_needed,
|
||||||
|
}
|
||||||
@@ -33,6 +33,7 @@ STATUS_LABELS: dict[str, str] = {
|
|||||||
"unknown": "확인 전",
|
"unknown": "확인 전",
|
||||||
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
|
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
|
||||||
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
|
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
|
||||||
|
"manual": "수동 입력", # 화면 전용 — API 없이 수동 입력만 쓰는 쇼핑몰(manual_only)
|
||||||
}
|
}
|
||||||
|
|
||||||
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
|
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
|
||||||
@@ -175,6 +176,8 @@ class MarketplaceAdapter(ABC):
|
|||||||
auth_type: str = "api_key" # api_key / oauth / shared(공통 연동 계층 재사용)
|
auth_type: str = "api_key" # api_key / oauth / shared(공통 연동 계층 재사용)
|
||||||
docs_url: str = ""
|
docs_url: str = ""
|
||||||
implemented: bool = False # 실제 수집(fetch)이 구현됐는가
|
implemented: bool = False # 실제 수집(fetch)이 구현됐는가
|
||||||
|
# True 면 API 연동이 없는 수동 입력 전용 쇼핑몰 — 매출 업데이트에서 빠지고, 인증 설정·연결 테스트가 없다.
|
||||||
|
manual_only: bool = False
|
||||||
# True 면 동기화 때 그 기간(sales_date)의 이 쇼핑몰 실데이터를 지우고 새로 넣는다(한 트랜잭션).
|
# True 면 동기화 때 그 기간(sales_date)의 이 쇼핑몰 실데이터를 지우고 새로 넣는다(한 트랜잭션).
|
||||||
# 쇼핑몰 API 가 "기간 안 결제·환불"을 빠짐없이 돌려줄 때만 켠다 — 규칙이 바뀌거나
|
# 쇼핑몰 API 가 "기간 안 결제·환불"을 빠짐없이 돌려줄 때만 켠다 — 규칙이 바뀌거나
|
||||||
# 주문이 사라져도 예전 행이 남지 않는다. False 면 같은 사건 ID 만 덮어쓴다(upsert).
|
# 주문이 사라져도 예전 행이 남지 않는다. False 면 같은 사건 ID 만 덮어쓴다(upsert).
|
||||||
|
|||||||
@@ -8,12 +8,23 @@
|
|||||||
OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
|
OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
|
||||||
· 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
|
· 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
|
||||||
· 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
|
· 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
|
||||||
연결 테스트는 오늘 결제완료 발주서 1건을 실제로 조회해 키·IP 가 통하는지 확인한다.
|
|
||||||
|
|
||||||
매출 수집(fetch_orders)은 아직 — 어느 WING 화면과 맞출지 정한 뒤 구현한다.
|
매출 수집 — 맞출 화면: WING → 비즈니스 인사이트 → **판매분석**(판매자배송 + 로켓그로스, 날짜 선택) 의 "매출(원)"
|
||||||
· 발주서 목록(v5 ordersheets, 주문일 기준, 상태별 조회) + 반품/취소 요청(v6 returnRequests, 접수일 기준, 금액 없음)
|
(2026-10-12 사용자 지정). 판매분석 자체를 주는 Open API 는 없다(2026-10-12 developers.coupang.com API 목록 확인) —
|
||||||
· 매출내역(v1 revenue-history)은 매출인식일(구매확정 또는 배송완료+7일) 기준이라 결제일 기준 일별 매출과 다르다.
|
그래서 주문 API 두 개를 결제일(한국 시간)로 합친다:
|
||||||
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 필요 시 별도 연계.
|
- 판매자배송: 발주서 목록(일단위 페이징) GET /v2/providers/openapi/apis/api/v5/vendors/{vendorId}/ordersheets
|
||||||
|
?createdAtFrom=yyyy-mm-dd+09:00&createdAtTo=…&status=…&maxPerPage=50&nextToken=
|
||||||
|
— 주문일 기준·한 번에 31일까지·상태(ACCEPT·INSTRUCT·DEPARTURE·DELIVERING·FINAL_DELIVERY·NONE_TRACKING)마다 따로.
|
||||||
|
결제일(paidAt)로 다시 거른다(주문일 하루 앞부터 조회). 줄 금액 = orderPrice(판매가 × 수량, 쿠폰 할인 전).
|
||||||
|
완료된 반품·결제 전 취소된 발주서는 이 목록에 없다(쿠팡 안내).
|
||||||
|
- 로켓그로스: 주문 목록 GET /v2/providers/rg_open_api/apis/api/v1/vendors/{vendorId}/rg/orders
|
||||||
|
?paidDateFrom=yyyymmdd&paidDateTo=yyyymmdd&nextToken= — 결제일 기준·30일까지·분당 50회.
|
||||||
|
줄 금액 = unitSalesPrice × salesQuantity. 쿠팡 안내상 **출고된 주문만** 나온다(오늘 주문은 출고 뒤에 잡힐 수 있음).
|
||||||
|
- SALE = 주문 하나(판매자배송 `coupang:{orderId}`, 로켓그로스 `coupang:rg:{orderId}`), 날짜 = 결제일.
|
||||||
|
결제 뒤 취소된 줄(canceled·cancelCount)도 결제일 매출에 둔다(지난 날짜가 나중에 줄지 않게) — 금액은 참고로 따로.
|
||||||
|
판매분석 "매출" 의 정확한 정의(할인 전·후, 취소 포함 여부)는 공개 문서가 없어 **설정 → 쇼핑몰 원본 데이터 확인**
|
||||||
|
(reconcile)의 날짜별 후보 금액을 WING 숫자와 비교해 확정한다. 구매자 이름·연락처·주소는 저장·표시하지 않는다.
|
||||||
|
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 여기에 넣지 않는다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -21,19 +32,47 @@ from __future__ import annotations
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import time
|
import time
|
||||||
from typing import Any
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from typing import Any, Iterable
|
||||||
from urllib.parse import quote, urlencode
|
from urllib.parse import quote, urlencode
|
||||||
|
|
||||||
from .base import (
|
from .base import (
|
||||||
AdapterContext,
|
AdapterContext,
|
||||||
|
AdapterError,
|
||||||
ApiError,
|
ApiError,
|
||||||
AuthFailed,
|
AuthFailed,
|
||||||
CredentialField,
|
CredentialField,
|
||||||
MarketplaceAdapter,
|
MarketplaceAdapter,
|
||||||
NotConfigured,
|
NotConfigured,
|
||||||
|
SaleEvent,
|
||||||
)
|
)
|
||||||
|
from .naver import field_summary, flatten
|
||||||
|
|
||||||
HOST = "https://api-gateway.coupang.com"
|
HOST = "https://api-gateway.coupang.com"
|
||||||
|
ORDERS_PATH = "/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets"
|
||||||
|
RG_ORDERS_PATH = "/v2/providers/rg_open_api/apis/api/v1/vendors/{vendor}/rg/orders"
|
||||||
|
EVENT_PREFIX = "coupang:"
|
||||||
|
RG_PREFIX = "coupang:rg:"
|
||||||
|
STATUSES = ("ACCEPT", "INSTRUCT", "DEPARTURE", "DELIVERING", "FINAL_DELIVERY", "NONE_TRACKING")
|
||||||
|
STATUS_KO = {"ACCEPT": "결제완료", "INSTRUCT": "상품준비중", "DEPARTURE": "배송지시", "DELIVERING": "배송중",
|
||||||
|
"FINAL_DELIVERY": "배송완료", "NONE_TRACKING": "업체직송", "RG": "로켓그로스"}
|
||||||
|
ORDER_SPAN_DAYS = 31 # 발주서 목록 한 번에 조회할 수 있는 기간(시작·끝 포함)
|
||||||
|
RG_SPAN_DAYS = 30 # 로켓그로스 주문 목록 한 번에 조회할 수 있는 기간
|
||||||
|
PAGE_SIZE = 50
|
||||||
|
MAX_PAGES = 400 # 한 조회 2만 건 — 무한 반복 방지
|
||||||
|
CALL_INTERVAL_SEC = 0.25 # 발주서 목록 호출 간격
|
||||||
|
RG_CALL_INTERVAL_SEC = 1.25 # 로켓그로스 분당 50회 제한
|
||||||
|
RETRY_429 = 3
|
||||||
|
RETRY_TIMEOUT_1DAY = 2 # 하루 구간도 시간 초과면 잠깐 쉬고 다시 부르는 횟수
|
||||||
|
PROBE_MAX_DAYS = 31
|
||||||
|
KST_OFFSET = timedelta(hours=9)
|
||||||
|
|
||||||
|
|
||||||
|
class GatewayTimeout(ApiError):
|
||||||
|
"""쿠팡 서버가 시간 안에 답하지 못함(502·503·504·응답 시간 초과) — 조회 기간을 줄이면 대개 풀린다."""
|
||||||
|
# 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목)
|
||||||
|
PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"})
|
||||||
|
PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"})
|
||||||
|
|
||||||
|
|
||||||
def signed_date(now: float | None = None) -> str:
|
def signed_date(now: float | None = None) -> str:
|
||||||
@@ -54,14 +93,163 @@ def build_query(params: dict[str, Any]) -> str:
|
|||||||
return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
|
return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
|
||||||
|
|
||||||
|
|
||||||
|
def _won(value: Any) -> int:
|
||||||
|
"""금액 → 원 정수. 쿠팡 Money({"units": 15000, "nanos": 0})·숫자·문자열("27800") 모두."""
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return _won(value.get("units")) + int(round((_num(value.get("nanos")) or 0) / 1e9))
|
||||||
|
n = _num(value)
|
||||||
|
return int(round(n)) if n is not None else 0
|
||||||
|
|
||||||
|
|
||||||
|
def _num(value: Any) -> float | None:
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return float(str(value).replace(",", "").strip() or 0)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _kst_day(value: Any) -> date | None:
|
||||||
|
"""결제 시각 → 한국 날짜. ISO 문자열("2025-08-01T10:06:12+09:00", 시간대 없으면 한국 시간) 또는
|
||||||
|
밀리초 타임스탬프(1746093162000, 로켓그로스)."""
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
n = _num(value) if not isinstance(value, str) or value.strip().isdigit() else None
|
||||||
|
if n is not None:
|
||||||
|
secs = n / 1000 if n > 1e11 else n
|
||||||
|
return (datetime.fromtimestamp(secs, tz=timezone.utc) + KST_OFFSET).date()
|
||||||
|
s = str(value).strip().replace("Z", "+00:00")
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(s if "T" in s or " " in s else s[:10])
|
||||||
|
except ValueError:
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(s[:10])
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if dt.tzinfo is not None:
|
||||||
|
dt = (dt - dt.utcoffset()).replace(tzinfo=None) + KST_OFFSET # type: ignore[operator]
|
||||||
|
return dt.date()
|
||||||
|
|
||||||
|
|
||||||
|
def spans(start: date, end: date, days: int) -> list[tuple[date, date]]:
|
||||||
|
"""[start, end] 를 days 일(시작·끝 포함) 이하 구간으로 자른다."""
|
||||||
|
out, d = [], start
|
||||||
|
while d <= end:
|
||||||
|
e = min(end, d + timedelta(days=days - 1))
|
||||||
|
out.append((d, e))
|
||||||
|
d = e + timedelta(days=1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def safe_order(o: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""개인정보 항목을 뺀 발주서(원본 확인·저장용)."""
|
||||||
|
out = {k: v for k, v in o.items() if k not in PERSONAL_KEYS}
|
||||||
|
if isinstance(out.get("orderItems"), list):
|
||||||
|
out["orderItems"] = [{k: v for k, v in it.items() if k not in PERSONAL_ITEM_KEYS}
|
||||||
|
for it in out["orderItems"] if isinstance(it, dict)]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def line_records(o: dict[str, Any]) -> list[dict[str, str]]:
|
||||||
|
"""발주서 하나 → 줄(orderItems)마다 평평한 기록 하나 — 원본 확인 표의 항목별 합계용."""
|
||||||
|
base = flatten({k: v for k, v in safe_order(o).items() if k != "orderItems"})
|
||||||
|
items = safe_order(o).get("orderItems") or [{}]
|
||||||
|
return [{**base, **flatten(it, "orderItems")} for it in items]
|
||||||
|
|
||||||
|
|
||||||
|
def seller_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""판매자배송 발주서 → 결제일이 [start, end] 인 줄. 같은 발주서가 두 번 와도(상태 사이 이동) 한 번만."""
|
||||||
|
seen: set[tuple[str, str, str, str]] = set()
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for o in orders:
|
||||||
|
oid = str(o.get("orderId") or "")
|
||||||
|
day = _kst_day(o.get("paidAt") or o.get("orderedAt"))
|
||||||
|
if not oid or day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
box = str(o.get("shipmentBoxId") or "")
|
||||||
|
first = len(out)
|
||||||
|
for it in o.get("orderItems") or []:
|
||||||
|
if not isinstance(it, dict):
|
||||||
|
continue
|
||||||
|
key = (oid, box, str(it.get("vendorItemId") or ""), str(it.get("sequenceNo") or ""))
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
qty = _won(it.get("shippingCount"))
|
||||||
|
price = _won(it.get("orderPrice")) or _won(it.get("salesPrice")) * qty
|
||||||
|
cancel_qty = _won(it.get("cancelCount")) + _won(it.get("holdCountForCancel"))
|
||||||
|
canceled = bool(it.get("canceled")) or (qty > 0 and cancel_qty >= qty)
|
||||||
|
cancel_amt = price if canceled else (_won(it.get("salesPrice")) * min(cancel_qty, qty) if cancel_qty else 0)
|
||||||
|
out.append({
|
||||||
|
"orderId": oid, "_day": day, "order_day": _kst_day(o.get("orderedAt")), "status": str(o.get("status") or ""),
|
||||||
|
"amount": price, "discount": _won(it.get("discountPrice")), "canceled": cancel_amt, "qty": qty,
|
||||||
|
"name": str(it.get("sellerProductName") or it.get("vendorItemName") or ""),
|
||||||
|
"opt": str(it.get("sellerProductItemName") or ""), "ship": 0,
|
||||||
|
})
|
||||||
|
# 배송비는 발주서(묶음 배송)마다 한 번 — 그 발주서의 첫 새 줄에(참고용, 매출 제외). 같은 발주서가 또 오면 새 줄이 없어 안 더함
|
||||||
|
if len(out) > first:
|
||||||
|
out[first]["ship"] += _won(o.get("shippingPrice")) + _won(o.get("remotePrice"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def rg_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""로켓그로스 주문 → 결제일이 [start, end] 인 줄. 금액 = 단가 × 수량."""
|
||||||
|
seen: set[tuple[str, str, int]] = set()
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for o in orders:
|
||||||
|
oid = str(o.get("orderId") or "")
|
||||||
|
day = _kst_day(o.get("paidAt"))
|
||||||
|
if not oid or day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
for i, it in enumerate(o.get("orderItems") or []):
|
||||||
|
if not isinstance(it, dict):
|
||||||
|
continue
|
||||||
|
key = (oid, str(it.get("vendorItemId") or ""), i)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
qty = _won(it.get("salesQuantity"))
|
||||||
|
out.append({"orderId": oid, "_day": day, "order_day": day, "status": "RG",
|
||||||
|
"amount": _won(it.get("unitSalesPrice")) * qty, "discount": 0, "canceled": 0, "qty": qty,
|
||||||
|
"name": str(it.get("productName") or ""), "opt": "", "ship": 0})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def group_lines(lines: Iterable[dict[str, Any]], prefix: str) -> dict[str, dict[str, Any]]:
|
||||||
|
"""줄 → 주문 하나(외부 사건 ID 기준)."""
|
||||||
|
orders: dict[str, dict[str, Any]] = {}
|
||||||
|
for ln in lines:
|
||||||
|
eid = f"{prefix}{ln['orderId']}"
|
||||||
|
o = orders.setdefault(eid, {"event_id": eid, "orderId": ln["orderId"], "_day": ln["_day"],
|
||||||
|
"order_day": ln.get("order_day"), "amount": 0, "discount": 0, "canceled": 0,
|
||||||
|
"ship": 0, "qty": 0, "names": [], "opt": "", "statuses": []})
|
||||||
|
for k in ("amount", "discount", "canceled", "ship", "qty"):
|
||||||
|
o[k] += int(ln.get(k) or 0)
|
||||||
|
if ln["name"] and ln["name"] not in o["names"]:
|
||||||
|
o["names"].append(ln["name"])
|
||||||
|
o["opt"] = o["opt"] or ln.get("opt") or ""
|
||||||
|
if ln["status"] and ln["status"] not in o["statuses"]:
|
||||||
|
o["statuses"].append(ln["status"])
|
||||||
|
return orders
|
||||||
|
|
||||||
|
|
||||||
class CoupangAdapter(MarketplaceAdapter):
|
class CoupangAdapter(MarketplaceAdapter):
|
||||||
code = "coupang"
|
code = "coupang"
|
||||||
name = "쿠팡"
|
name = "쿠팡(윙)"
|
||||||
auth_type = "api_key"
|
auth_type = "api_key"
|
||||||
docs_url = "https://developers.coupangcorp.com/"
|
implemented = True
|
||||||
|
replace_range = True
|
||||||
|
event_prefix = EVENT_PREFIX
|
||||||
|
docs_url = "https://developers.coupang.com/"
|
||||||
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
|
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
|
||||||
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
|
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
|
||||||
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
|
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인). 매출은 판매자배송 + 로켓그로스 주문을 "
|
||||||
|
"결제일로 합칩니다(WING 비즈니스 인사이트 → 판매분석 '매출'과 비교).")
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._last_call = 0.0
|
||||||
|
self._last_rg_call = 0.0
|
||||||
|
|
||||||
def credential_fields(self) -> list[CredentialField]:
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
return [
|
return [
|
||||||
@@ -71,42 +259,253 @@ class CoupangAdapter(MarketplaceAdapter):
|
|||||||
]
|
]
|
||||||
|
|
||||||
# ── 호출 ──────────────────────────────────────────────
|
# ── 호출 ──────────────────────────────────────────────
|
||||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
def _vendor(self, ctx: AdapterContext) -> str:
|
||||||
|
v = ctx.credentials.get("vendor_id").strip()
|
||||||
|
if not v:
|
||||||
|
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||||
|
return v
|
||||||
|
|
||||||
|
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> dict[str, Any]:
|
||||||
|
"""GET — 호출 간격 유지(로켓그로스는 분당 50회), 429 는 잠깐 쉬고 다시."""
|
||||||
import httpx # 지연 import
|
import httpx # 지연 import
|
||||||
|
|
||||||
access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
|
access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
|
||||||
if not (access and secret):
|
if not (access and secret):
|
||||||
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||||
query = build_query(params)
|
query = build_query(params)
|
||||||
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
what = "로켓그로스 주문" if rg else "발주서"
|
||||||
"Content-Type": "application/json;charset=UTF-8"}
|
for attempt in range(RETRY_429 + 1):
|
||||||
try:
|
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||||
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
gap = RG_CALL_INTERVAL_SEC if rg else CALL_INTERVAL_SEC
|
||||||
except httpx.HTTPError as exc:
|
last = self._last_rg_call if rg else self._last_call
|
||||||
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
wait = gap - (time.monotonic() - last)
|
||||||
try:
|
if wait > 0:
|
||||||
body = res.json()
|
time.sleep(wait)
|
||||||
except ValueError:
|
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
||||||
body = {}
|
"Content-Type": "application/json;charset=UTF-8"}
|
||||||
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()
|
try:
|
||||||
if res.status_code in (401, 403):
|
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
||||||
raise AuthFailed(
|
except httpx.TimeoutException as exc:
|
||||||
f"쿠팡 인증 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
raise GatewayTimeout(f"쿠팡 {what} 응답 시간 초과: {type(exc).__name__}") from None
|
||||||
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
except httpx.HTTPError as exc:
|
||||||
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
||||||
if res.status_code >= 400:
|
finally:
|
||||||
raise ApiError(f"쿠팡 API 오류({res.status_code}): {msg}")
|
if rg:
|
||||||
return body
|
self._last_rg_call = time.monotonic()
|
||||||
|
else:
|
||||||
|
self._last_call = time.monotonic()
|
||||||
|
if res.status_code == 429 and attempt < RETRY_429:
|
||||||
|
time.sleep(2.0 * (2 ** attempt))
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
body = res.json()
|
||||||
|
except ValueError:
|
||||||
|
body = {}
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
body = {"data": body}
|
||||||
|
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()[:300]
|
||||||
|
if res.status_code in (401, 403):
|
||||||
|
raise AuthFailed(
|
||||||
|
f"쿠팡 {what} 조회 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
||||||
|
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
||||||
|
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
||||||
|
if res.status_code == 429:
|
||||||
|
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
if res.status_code in (502, 503, 504):
|
||||||
|
raise GatewayTimeout(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||||
|
if res.status_code >= 400:
|
||||||
|
raise ApiError(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||||
|
code = body.get("code")
|
||||||
|
if isinstance(code, int) and code >= 400:
|
||||||
|
raise ApiError(f"쿠팡 {what} API 오류({code}): {msg}")
|
||||||
|
return body
|
||||||
|
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
|
||||||
|
def _pages(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> list[dict[str, Any]]:
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token: str | None = None
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, path, {**params, "nextToken": token} if token else params, rg=rg)
|
||||||
|
rows = [r for r in (body.get("data") or []) if isinstance(r, dict)] if isinstance(body.get("data"), list) else []
|
||||||
|
out.extend(rows)
|
||||||
|
nxt = str(body.get("nextToken") or "").strip()
|
||||||
|
if not nxt or not rows or nxt == token:
|
||||||
|
break
|
||||||
|
token = nxt
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _seller_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가.
|
||||||
|
|
||||||
|
건수가 많은 상태(배송완료 등)는 31일을 한 번에 부르면 쿠팡 서버가 504(시간 초과)를 낸다 — 그러면 그 구간을
|
||||||
|
반으로 줄여 다시 부르고(하루까지), 줄인 크기는 같은 상태의 다음 구간에도 그대로 쓴다(매번 31일로 실패하지 않게)."""
|
||||||
|
path = ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
size_by_status = {st: ORDER_SPAN_DAYS for st in STATUSES}
|
||||||
|
for a, b in spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS):
|
||||||
|
for st in STATUSES:
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
d, tries = a, 0
|
||||||
|
while d <= b:
|
||||||
|
e = min(b, d + timedelta(days=size_by_status[st] - 1))
|
||||||
|
try:
|
||||||
|
part = self._pages(ctx, path, {"createdAtFrom": f"{d.isoformat()}+09:00",
|
||||||
|
"createdAtTo": f"{e.isoformat()}+09:00",
|
||||||
|
"status": st, "maxPerPage": PAGE_SIZE})
|
||||||
|
except GatewayTimeout as exc:
|
||||||
|
if size_by_status[st] > 1:
|
||||||
|
size_by_status[st] = max(1, size_by_status[st] // 2)
|
||||||
|
continue
|
||||||
|
tries += 1
|
||||||
|
if tries <= RETRY_TIMEOUT_1DAY:
|
||||||
|
time.sleep(3.0 * tries)
|
||||||
|
continue
|
||||||
|
raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루도 시간 초과, 상태 {st}] "
|
||||||
|
"— 잠시 뒤 다시 시도하세요.") from None
|
||||||
|
except ApiError as exc: # 긴 기간을 나눠 부를 때 어느 구간에서 막혔는지 알 수 있게
|
||||||
|
raise ApiError(f"{exc.message} [주문일 {d.isoformat()}~{e.isoformat()}, 상태 {st}]") from None
|
||||||
|
rows.extend(part)
|
||||||
|
d, tries = e + timedelta(days=1), 0
|
||||||
|
out.extend(rows)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _rg_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
path = RG_ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for a, b in spans(start, end, RG_SPAN_DAYS):
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
d, size, tries = a, RG_SPAN_DAYS, 0
|
||||||
|
while d <= b: # 시간 초과면 판매자배송과 같이 구간을 반으로(하루까지)
|
||||||
|
e = min(b, d + timedelta(days=size - 1))
|
||||||
|
try:
|
||||||
|
part = self._pages(ctx, path, {"paidDateFrom": d.strftime("%Y%m%d"),
|
||||||
|
"paidDateTo": e.strftime("%Y%m%d")}, rg=True)
|
||||||
|
except GatewayTimeout as exc:
|
||||||
|
if size > 1:
|
||||||
|
size = max(1, size // 2)
|
||||||
|
continue
|
||||||
|
tries += 1
|
||||||
|
if tries <= RETRY_TIMEOUT_1DAY:
|
||||||
|
time.sleep(3.0 * tries)
|
||||||
|
continue
|
||||||
|
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루도 시간 초과] "
|
||||||
|
"— 잠시 뒤 다시 시도하세요.") from None
|
||||||
|
except ApiError as exc:
|
||||||
|
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()}~{e.isoformat()}]") from None
|
||||||
|
rows.extend(part)
|
||||||
|
d, tries = e + timedelta(days=1), 0
|
||||||
|
out.extend(rows)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _plan(self, ctx: AdapterContext, start: date, end: date) -> None:
|
||||||
|
ctx.progress.plan(len(spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS)) * len(STATUSES)
|
||||||
|
+ len(spans(start, end, RG_SPAN_DAYS)), "조회")
|
||||||
|
|
||||||
|
# ── 수집 ──────────────────────────────────────────────
|
||||||
|
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
self._plan(ctx, start, end)
|
||||||
|
seller = seller_lines(self._seller_orders(ctx, start, end), start, end)
|
||||||
|
rg = rg_lines(self._rg_orders(ctx, start, end), start, end)
|
||||||
|
yield from group_lines(seller, EVENT_PREFIX).values()
|
||||||
|
yield from group_lines(rg, RG_PREFIX).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 []]
|
||||||
|
if o.get("canceled"):
|
||||||
|
statuses.append("취소 포함")
|
||||||
|
return [SaleEvent(
|
||||||
|
event_type="SALE", external_event_id=str(o["event_id"]), 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:
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
from app.timezone import today_kst # noqa: WPS433
|
from app.timezone import today_kst # noqa: WPS433
|
||||||
|
|
||||||
self.authenticate(ctx)
|
self.authenticate(ctx)
|
||||||
vendor = ctx.credentials.get("vendor_id").strip()
|
vendor = self._vendor(ctx)
|
||||||
today = today_kst().isoformat()
|
today = today_kst()
|
||||||
body = self._get(ctx, f"/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets",
|
body = self._get(ctx, ORDERS_PATH.format(vendor=vendor),
|
||||||
{"createdAtFrom": f"{today}+09:00", "createdAtTo": f"{today}+09:00",
|
{"createdAtFrom": f"{today.isoformat()}+09:00", "createdAtTo": f"{today.isoformat()}+09:00",
|
||||||
"status": "ACCEPT", "maxPerPage": 1})
|
"status": "ACCEPT", "maxPerPage": 1})
|
||||||
n = len(body.get("data") or [])
|
n = len(body.get("data") or [])
|
||||||
return (f"쿠팡 연결 정상(발주서 조회 권한 확인, 오늘 결제완료 {'있음' if n else '없음'}). "
|
rg = self._get(ctx, RG_ORDERS_PATH.format(vendor=vendor),
|
||||||
"매출 수집은 다음 단계에서 구현됩니다.")
|
{"paidDateFrom": today.strftime("%Y%m%d"), "paidDateTo": today.strftime("%Y%m%d")}, rg=True)
|
||||||
|
m = len(rg.get("data") or [])
|
||||||
|
return (f"쿠팡 연결 정상(판매자배송 발주서·로켓그로스 주문 조회 권한 확인 — 오늘 결제완료 발주서 {'있음' if n else '없음'}, "
|
||||||
|
f"로켓그로스 오늘 주문 {m}건{'+' if rg.get('nextToken') else ''}).")
|
||||||
|
|
||||||
|
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||||
|
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||||
|
"""결제일 기준 기간(최대 31일)의 판매자배송 발주서·로켓그로스 주문을 실제로 불러, 날짜별 후보 금액을 나란히 —
|
||||||
|
WING 판매분석 '매출(원)'과 같은 열을 찾아 규칙을 확정하는 용도. 저장하지 않고, 개인정보 항목은 빼고 보여 준다."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||||
|
self._plan(ctx, day, to)
|
||||||
|
probes: list[dict[str, Any]] = []
|
||||||
|
seller_raw: list[dict[str, Any]] = []
|
||||||
|
rg_raw: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
seller_raw = self._seller_orders(ctx, day, to)
|
||||||
|
probes.append({"key": "seller", "label": "판매자배송 발주서(주문일 하루 앞부터, 상태 6개)",
|
||||||
|
"path": ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(seller_raw),
|
||||||
|
"fields": field_summary([r for o in seller_raw for r in line_records(o)])})
|
||||||
|
except AdapterError as exc:
|
||||||
|
probes.append({"key": "seller", "label": "판매자배송 발주서", "path": ORDERS_PATH.format(vendor="{vendorId}"),
|
||||||
|
"ok": False, "error": exc.message[:300]})
|
||||||
|
try:
|
||||||
|
rg_raw = self._rg_orders(ctx, day, to)
|
||||||
|
probes.append({"key": "rg", "label": "로켓그로스 주문(결제일, 출고된 주문만)",
|
||||||
|
"path": RG_ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(rg_raw),
|
||||||
|
"fields": field_summary([{**flatten({k: v for k, v in o.items() if k != "orderItems"}),
|
||||||
|
**flatten(it, "orderItems")}
|
||||||
|
for o in rg_raw for it in (o.get("orderItems") or [{}])])})
|
||||||
|
except AdapterError as exc:
|
||||||
|
probes.append({"key": "rg", "label": "로켓그로스 주문", "path": RG_ORDERS_PATH.format(vendor="{vendorId}"),
|
||||||
|
"ok": False, "error": exc.message[:300]})
|
||||||
|
seller = seller_lines(seller_raw, day, to)
|
||||||
|
rg = rg_lines(rg_raw, day, to)
|
||||||
|
dates = [(day + timedelta(days=i)).isoformat() for i in range((to - day).days + 1)]
|
||||||
|
|
||||||
|
def per_day(lines: list[dict[str, Any]], fn: Any) -> dict[str, int]:
|
||||||
|
out = {d: 0 for d in dates}
|
||||||
|
for ln in lines:
|
||||||
|
out[ln["_day"].isoformat()] += int(fn(ln))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def count(lines: list[dict[str, Any]], d: str) -> int:
|
||||||
|
return len({ln["orderId"] for ln in lines if ln["_day"].isoformat() == d})
|
||||||
|
|
||||||
|
s_amt, s_net = per_day(seller, lambda x: x["amount"]), per_day(seller, lambda x: x["amount"] - x["discount"])
|
||||||
|
s_live = per_day(seller, lambda x: x["amount"] - x["canceled"])
|
||||||
|
s_qty, r_qty = per_day(seller, lambda x: x["qty"]), per_day(rg, lambda x: x["qty"])
|
||||||
|
s_cancel, s_ship = per_day(seller, lambda x: x["canceled"]), per_day(seller, lambda x: x["ship"])
|
||||||
|
r_amt = per_day(rg, lambda x: x["amount"])
|
||||||
|
ok = {p["key"]: p["ok"] for p in probes}
|
||||||
|
failed = {p["key"]: p.get("error", "") for p in probes if not p["ok"]}
|
||||||
|
cands = [
|
||||||
|
{"label": "① 현재 규칙: 판매자배송 판매가 + 로켓그로스", "days": {d: s_amt[d] + r_amt[d] for d in dates}},
|
||||||
|
{"label": "② 판매자배송 판매가(쿠폰 할인 전)", "days": s_amt, "error": failed.get("seller")},
|
||||||
|
{"label": "③ 판매자배송 할인 뒤(판매가 − 쿠폰·쿠팡 할인)", "days": s_net, "error": failed.get("seller")},
|
||||||
|
{"label": "④ 판매자배송 취소분 뺀 판매가", "days": s_live, "error": failed.get("seller")},
|
||||||
|
{"label": "⑤ 로켓그로스 단가 × 수량", "days": r_amt, "error": failed.get("rg")},
|
||||||
|
{"label": "판매량: 판매자배송 + 로켓그로스(개)", "days": {d: s_qty[d] + r_qty[d] for d in dates}},
|
||||||
|
]
|
||||||
|
if not all(ok.values()):
|
||||||
|
cands[0]["error"] = "일부 조회 실패 — 위 표 참고"
|
||||||
|
days = [{"date": d, "orders": count(seller, d) + count(rg, d), "amount": s_amt[d] + r_amt[d],
|
||||||
|
"claimed": s_cancel[d], "ship": s_ship[d]}
|
||||||
|
for d in dates]
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||||
|
"day_cols": {"amount": "매출(현재 규칙)", "claimed": "그중 판매자배송 취소분(참고)", "ship": "판매자배송 배송비(참고, 매출 제외)"},
|
||||||
|
"refund_candidates": cands, "candidates_title": "매출 후보 비교 — WING 판매분석 '매출(원)'·'판매량'과 같은 열을 알려 주세요",
|
||||||
|
"rule": "결제일(한국 시간) 기준 — 판매자배송 발주서 orderPrice(판매가 × 수량, 쿠폰 할인 전, 결제 뒤 취소분 포함) + "
|
||||||
|
"로켓그로스 unitSalesPrice × salesQuantity(출고된 주문만). 배송비 제외"}
|
||||||
|
|||||||
@@ -1,21 +1,366 @@
|
|||||||
"""카카오 — 카카오쇼핑(톡스토어) 판매자 API.
|
"""카카오 — 카카오쇼핑(톡스토어) Open API(shopping-developers.kakao.com, 2026-10-13 문서 확인).
|
||||||
|
|
||||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
인증(“API 공통 인증 헤더 구성”) — 모든 호출에 같은 헤더 3개, 주소 https://kapi.kakao.com
|
||||||
|
Authorization: KakaoAK {앱 어드민 키} 카카오디벨로퍼스 앱(연동 앱) → 앱 설정 → 앱 → 어드민 키
|
||||||
|
Target-Authorization: KakaoAK {판매자 API 인증키} 카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키
|
||||||
|
channel-ids: 101(톡스토어) / 1(선물하기) / "1,101"(둘 다)
|
||||||
|
두 헤더에 같은 앱의 키를 넣으면 {"code": -2, "msg": "invalid authorization or target-authorization header."},
|
||||||
|
판매자 인증키가 바뀌었거나 무효면 {"code": -401, "msg": "appKey(판매자인증키) is already deactivated"},
|
||||||
|
연동 앱과 판매자가 연결되지 않았으면 "대행사 매핑/권한 확인이 필요합니다."
|
||||||
|
Open API 는 카카오쇼핑 검토를 거쳐 허락된 앱만 쓸 수 있다(“카카오쇼핑 API 연동 검토 요청하기”).
|
||||||
|
|
||||||
|
매출 수집 — 네이버와 같은 기준(결제일, 할인 뒤 상품 금액, 배송비 제외, 결제 뒤 취소·반품분도 결제일 매출에 포함):
|
||||||
|
- 결제일시 기준 주문내역 조회 GET /v2/shopping/orders/paidAt?from=YYYY-MM-DD HH:mm:ss&to=…&size=100(&token=)
|
||||||
|
— 한 번에 24시간까지(하루씩 부른다), 쪽당 100건, 다음 쪽은 응답의 token(더 없으면 token 없음).
|
||||||
|
목록에는 금액이 없다(orderId·paymentId·orderStatus·paidAt …).
|
||||||
|
- 주문 하나씩 주문정보 조회 GET /v1/shopping/order?order_id= 로 orderProduct 금액을 받는다.
|
||||||
|
한 번 받은 주문은 목록의 modifiedAt 이 같으면 다시 부르지 않는다(프로세스 안 메모리 캐시).
|
||||||
|
- 카카오 주문(orderId)은 상품 한 줄이고 결제(paymentId)가 장바구니 하나 → SALE = 결제 하나(`kakao:{paymentId}`),
|
||||||
|
날짜 = 결제일(paidAt, 한국 시간), 금액 = 그 결제에 든 상품 줄 금액 합.
|
||||||
|
- 상품 줄 금액(line_amount) = (productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice
|
||||||
|
− adminDiscountPrice. 문서에 결제금액 항목이 따로 없어 이 식으로 만든다 — **판매자센터 매출 화면과 아직 대조 전**.
|
||||||
|
설정 화면 "쇼핑몰 원본 데이터 확인"에서 항목별 합계를 보고 맞는 식으로 확정한다.
|
||||||
|
- 미결제(주문 생성·결제 요청·입금 대기/확인·결제 실패·미입금 취소)만 뺀다.
|
||||||
|
- 구매자 이름·연락처·주소는 저장하지 않는다(원본 확인에서도 값 없이 이름만).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from .base import CredentialField, MarketplaceAdapter
|
import re
|
||||||
|
import time
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from .base import (
|
||||||
|
AdapterContext,
|
||||||
|
AdapterError,
|
||||||
|
ApiError,
|
||||||
|
AuthFailed,
|
||||||
|
CredentialField,
|
||||||
|
MarketplaceAdapter,
|
||||||
|
NotConfigured,
|
||||||
|
SaleEvent,
|
||||||
|
)
|
||||||
|
from .naver import field_summary, flatten
|
||||||
|
|
||||||
|
HOST = "https://kapi.kakao.com"
|
||||||
|
PAID_PATH = "/v2/shopping/orders/paidAt"
|
||||||
|
ORDER_PATH = "/v1/shopping/order"
|
||||||
|
EVENT_PREFIX = "kakao:"
|
||||||
|
DEFAULT_CHANNELS = "101" # 톡스토어
|
||||||
|
PAGE_SIZE = 100
|
||||||
|
MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지
|
||||||
|
CALL_INTERVAL_SEC = 0.1 # 호출 사이 간격(문서에 제한 없음 — 넉넉히)
|
||||||
|
RETRY_429 = 3
|
||||||
|
PROBE_MAX_DAYS = 31
|
||||||
|
CACHE_MAX = 20000
|
||||||
|
|
||||||
|
# 매출에서 빼는 상태 — 결제되지 않은 것만. 결제 뒤 취소·반품은 결제일 매출에 그대로(네이버 "판매금액(총)"과 같은 기준).
|
||||||
|
UNPAID_STATUS = frozenset({"Created", "PayRequest", "PayWaiting", "PayChecking", "PayFailed", "UnpaidCancelComplete"})
|
||||||
|
# 결제 뒤 취소·환불·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌
|
||||||
|
CLAIMED_STATUS = frozenset({
|
||||||
|
"PayCancelComplete", "RefundComplete", "ShippingCancelComplete", "ShippingRefundComplete",
|
||||||
|
"ReturnCancelComplete", "ReturnRefundComplete", "TicketCancelComplete", "TicketRefundComplete",
|
||||||
|
})
|
||||||
|
STATUS_KO = {
|
||||||
|
"Created": "주문 생성", "PayRequest": "결제 요청", "PayWaiting": "결제 대기", "PayChecking": "입금 확인 중",
|
||||||
|
"PayFailed": "결제 실패", "PayComplete": "결제 완료", "ShippingRequest": "배송 요청",
|
||||||
|
"PayCancelRequest": "결제 취소 예정", "PayCancelComplete": "결제 취소 완료", "RefundComplete": "환불 완료",
|
||||||
|
"UnpaidCancelComplete": "미입금 취소 완료", "ShippingWaiting": "배송 준비 중",
|
||||||
|
"ShippingCancelComplete": "결제 취소 완료", "ShippingProgress": "배송 중", "ShippingComplete": "배송 완료",
|
||||||
|
"ShippingRefundComplete": "환불 완료", "ExchangeShippingComplete": "교환 완료", "ReturnRequest": "반품 요청",
|
||||||
|
"ReturnCancelComplete": "반품 결제 취소 완료", "ReturnRefundComplete": "반품 환불 완료",
|
||||||
|
"TicketSendComplete": "발송 완료", "TicketCancelComplete": "결제 취소 완료", "TicketRefundComplete": "환불 완료",
|
||||||
|
"BuyDecision": "구매 결정",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
""""20251201201735" 또는 "2025-12-01 20:17:35" → date(2025, 12, 1). 카카오 날짜는 한국 시간."""
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def line_amount(op: dict[str, Any]) -> int:
|
||||||
|
"""상품 줄 금액 = (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오(관리자) 할인. 배송비 제외."""
|
||||||
|
qty = max(1, _won(op.get("quantity")))
|
||||||
|
gross = (_won(op.get("productPrice")) + _won(op.get("optionPrice"))) * qty
|
||||||
|
return max(0, gross - line_discount(op))
|
||||||
|
|
||||||
|
|
||||||
|
def line_discount(op: dict[str, Any]) -> int:
|
||||||
|
return sum(abs(_won(op.get(k))) for k in ("sellerDiscountPrice", "sellerCouponDiscountPrice", "adminDiscountPrice"))
|
||||||
|
|
||||||
|
|
||||||
|
# 구매자 개인정보 — 받자마자 값을 지운다(메모리 캐시·원본 확인 표 어디에도 남기지 않음, 항목 이름만 남김).
|
||||||
|
PERSONAL_OBJECTS = ("orderer", "orderDeliveryRequest", "orderTicketReceiver")
|
||||||
|
PERSONAL_KEY = re.compile(r"^(pickup|exchange)(Name|ZipCode|RoadZipCode|Address\d*|MobileNumber|PhoneNumber)$|reasonComment")
|
||||||
|
|
||||||
|
|
||||||
|
def strip_personal(det: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
out: dict[str, Any] = {}
|
||||||
|
for k, v in det.items():
|
||||||
|
if k in PERSONAL_OBJECTS and isinstance(v, dict):
|
||||||
|
out[k] = {kk: "" for kk in v}
|
||||||
|
elif isinstance(v, dict):
|
||||||
|
out[k] = {kk: ("" if PERSONAL_KEY.search(str(kk)) else vv) for kk, vv in v.items()}
|
||||||
|
else:
|
||||||
|
out[k] = v
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def order_detail(body: Any) -> dict[str, Any]:
|
||||||
|
"""주문정보 조회 응답에서 주문 하나(orderBase·orderProduct …)를 꺼낸다(개인정보 값은 지움).
|
||||||
|
감싼 모양(data/content)도 받아들인다."""
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
return {}
|
||||||
|
if isinstance(body.get("orderProduct"), dict) or isinstance(body.get("orderBase"), dict):
|
||||||
|
return strip_personal(body)
|
||||||
|
for k in ("data", "content", "contents"):
|
||||||
|
v = body.get(k)
|
||||||
|
if isinstance(v, list) and v and isinstance(v[0], dict):
|
||||||
|
v = v[0]
|
||||||
|
if isinstance(v, dict) and (isinstance(v.get("orderProduct"), dict) or isinstance(v.get("orderBase"), dict)):
|
||||||
|
return strip_personal(v)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def group_payments(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
|
||||||
|
"""주문(상품 줄) → 결제 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
|
||||||
|
items = {"row": 목록 줄, "detail": 주문정보}. 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
|
||||||
|
pays: dict[str, dict[str, Any]] = {}
|
||||||
|
for it in items:
|
||||||
|
row, det = it.get("row") or {}, it.get("detail") or {}
|
||||||
|
base, op = det.get("orderBase") or {}, det.get("orderProduct") or {}
|
||||||
|
status = str(row.get("orderStatus") or base.get("status") or "")
|
||||||
|
day = _day(row.get("paidAt") or base.get("paidAt"))
|
||||||
|
oid = str(row.get("orderId") or base.get("id") or det.get("id") or "")
|
||||||
|
pid = str(row.get("paymentId") or base.get("paymentId") or oid)
|
||||||
|
if not oid or day is None or not (start <= day <= end) or status in UNPAID_STATUS or not op:
|
||||||
|
continue
|
||||||
|
p = pays.setdefault(pid, {"paymentId": pid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
|
||||||
|
"discount": 0, "names": [], "opt": "", "statuses": [], "orders": [],
|
||||||
|
"order_day": _day(row.get("createdAt") or base.get("createdAt"))})
|
||||||
|
amt = line_amount(op)
|
||||||
|
p["amount"] += amt
|
||||||
|
if status in CLAIMED_STATUS:
|
||||||
|
p["claimed"] += amt
|
||||||
|
p["ship"] += _won(op.get("deliveryAmount")) + _won(op.get("areaAdditionalDeliveryAmount"))
|
||||||
|
p["qty"] += max(1, _won(op.get("quantity")))
|
||||||
|
p["discount"] += line_discount(op)
|
||||||
|
p["orders"].append(oid)
|
||||||
|
name = str(op.get("name") or "")
|
||||||
|
if name and name not in p["names"]:
|
||||||
|
p["names"].append(name)
|
||||||
|
p["opt"] = p["opt"] or str(op.get("optionContent") or "")
|
||||||
|
if status and status not in p["statuses"]:
|
||||||
|
p["statuses"].append(status)
|
||||||
|
return pays
|
||||||
|
|
||||||
|
|
||||||
|
def _err_text(body: dict[str, Any], res: Any) -> str:
|
||||||
|
parts = [str(body.get(k)) for k in ("code", "msg", "message") if body.get(k) not in (None, "")]
|
||||||
|
ex = body.get("extras")
|
||||||
|
if isinstance(ex, dict):
|
||||||
|
parts += [str(ex.get(k)) for k in ("error_code", "error_message") if ex.get(k) not in (None, "")]
|
||||||
|
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
|
||||||
|
|
||||||
|
|
||||||
class KakaoAdapter(MarketplaceAdapter):
|
class KakaoAdapter(MarketplaceAdapter):
|
||||||
code = "kakao"
|
code = "kakao"
|
||||||
name = "카카오"
|
name = "카카오"
|
||||||
auth_type = "api_key"
|
auth_type = "api_key"
|
||||||
note = "입력 항목은 연동 단계에서 카카오쇼핑 판매자 API 문서로 확정합니다."
|
implemented = True
|
||||||
|
replace_range = True
|
||||||
|
event_prefix = EVENT_PREFIX
|
||||||
|
docs_url = "https://shopping-developers.kakao.com/hc/ko/articles/4578909656975"
|
||||||
|
note = ("카카오쇼핑 Open API 는 카카오쇼핑 검토로 허락된 카카오디벨로퍼스 앱만 쓸 수 있습니다. "
|
||||||
|
"그 앱의 어드민 키와, 판매자센터(정보관리 → 판매채널 정보 → API 인증키)의 판매자 API 인증키를 입력합니다. "
|
||||||
|
"두 키는 서로 다른 앱의 키여야 합니다.")
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._last_call = 0.0
|
||||||
|
self._details: dict[str, tuple[str, dict[str, Any]]] = {} # orderId → (modifiedAt, 주문정보)
|
||||||
|
|
||||||
def credential_fields(self) -> list[CredentialField]:
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
# api_key 는 처음 만든 입력칸 이름 그대로 — 이미 저장한 판매자 인증키를 다시 넣지 않아도 되게.
|
||||||
return [
|
return [
|
||||||
CredentialField("seller_id", "판매자(채널) ID"),
|
CredentialField("admin_key", "앱 어드민 키(Authorization)", secret=True,
|
||||||
CredentialField("api_key", "API Key", secret=True),
|
help="카카오디벨로퍼스 → 내 애플리케이션(카카오쇼핑 API 허락된 앱) → 앱 설정 → 앱 → 어드민 키"),
|
||||||
|
CredentialField("api_key", "판매자 API 인증키(Target-Authorization)", secret=True,
|
||||||
|
help="카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키"),
|
||||||
|
CredentialField("channel_ids", "판매채널(channel-ids)", required=False, placeholder=DEFAULT_CHANNELS,
|
||||||
|
help="톡스토어 101(기본), 선물하기 1, 둘 다 1,101"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# ── 호출 ──────────────────────────────────────────────
|
||||||
|
def _headers(self, ctx: AdapterContext) -> dict[str, str]:
|
||||||
|
admin = ctx.credentials.get("admin_key").strip()
|
||||||
|
seller = ctx.credentials.get("api_key").strip()
|
||||||
|
if not admin or not seller:
|
||||||
|
raise NotConfigured("앱 어드민 키와 판매자 API 인증키를 입력하세요.")
|
||||||
|
channels = re.sub(r"\s+", "", ctx.credentials.get("channel_ids") or "") or DEFAULT_CHANNELS
|
||||||
|
return {"Authorization": f"KakaoAK {admin}", "Target-Authorization": f"KakaoAK {seller}",
|
||||||
|
"channel-ids": channels, "Accept": "application/json"}
|
||||||
|
|
||||||
|
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시. 키 오류는 AuthFailed(무엇을 확인할지 안내)."""
|
||||||
|
import httpx # 지연 import
|
||||||
|
|
||||||
|
headers = self._headers(ctx)
|
||||||
|
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)
|
||||||
|
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
|
||||||
|
try:
|
||||||
|
body = res.json()
|
||||||
|
except ValueError:
|
||||||
|
body = {}
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
body = {"contents": body}
|
||||||
|
code = _won(body.get("code")) if body.get("code") not in (None, "") else 0
|
||||||
|
text = _err_text(body, res)
|
||||||
|
if code == -2 or "target-authorization" in text.lower():
|
||||||
|
raise AuthFailed(f"카카오 인증 헤더 거부({text}). 앱 어드민 키와 판매자 API 인증키가 서로 다른 앱의 키인지, "
|
||||||
|
"어드민 키가 REST API 키가 아닌지 확인하세요.")
|
||||||
|
if code == -401 or "deactivated" in text:
|
||||||
|
raise AuthFailed(f"카카오 판매자 API 인증키 무효({text}). 판매자센터의 API 인증키를 다시 복사해 넣으세요.")
|
||||||
|
if "매핑" in text or "대행사" in text:
|
||||||
|
raise AuthFailed(f"카카오쇼핑 연동 앱과 판매자가 연결되지 않았습니다({text}). 판매자 연결(POST /v1/store/register)이 "
|
||||||
|
"끝났는지, 앱이 카카오쇼핑 API 허락을 받았는지 확인하세요.")
|
||||||
|
if res.status_code in (401, 403):
|
||||||
|
raise AuthFailed(f"카카오 권한 거부({res.status_code}): {text}. 앱이 카카오쇼핑 API 허락을 받았는지, "
|
||||||
|
"두 키가 맞는지 확인하세요.")
|
||||||
|
if res.status_code >= 400 or code < 0:
|
||||||
|
raise ApiError(f"카카오쇼핑 API 오류({res.status_code}): {text}")
|
||||||
|
return body
|
||||||
|
raise ApiError("카카오쇼핑 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
|
||||||
|
def _day_rows(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
|
||||||
|
"""결제일이 d(한국 시간 0시~23:59:59)인 주문 목록 — 모든 상태, 금액 없음."""
|
||||||
|
params: dict[str, Any] = {"from": f"{d.isoformat()} 00:00:00", "to": f"{d.isoformat()} 23:59:59",
|
||||||
|
"size": PAGE_SIZE}
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token = ""
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, PAID_PATH, {**params, **({"token": token} if token else {})})
|
||||||
|
rows = [r for r in body.get("contents") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
token = str(body.get("token") or "")
|
||||||
|
if not token or not rows:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _detail(self, ctx: AdapterContext, row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
oid = str(row.get("orderId") or "")
|
||||||
|
mod = str(row.get("modifiedAt") or "")
|
||||||
|
hit = self._details.get(oid)
|
||||||
|
if hit and hit[0] == mod and mod:
|
||||||
|
return hit[1]
|
||||||
|
det = order_detail(self._get(ctx, ORDER_PATH, {"order_id": oid}))
|
||||||
|
if det:
|
||||||
|
if len(self._details) >= CACHE_MAX:
|
||||||
|
self._details.clear()
|
||||||
|
self._details[oid] = (mod, det)
|
||||||
|
return det
|
||||||
|
|
||||||
|
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
"""하루씩 목록 → 결제된 주문만 주문정보까지 받아 {"row", "detail"}."""
|
||||||
|
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
|
||||||
|
d = start
|
||||||
|
while d <= end:
|
||||||
|
rows = self._day_rows(ctx, d)
|
||||||
|
got = []
|
||||||
|
for r in rows:
|
||||||
|
if not r.get("orderId") or str(r.get("orderStatus") or "") in UNPAID_STATUS:
|
||||||
|
got.append({"row": r, "detail": {}})
|
||||||
|
continue
|
||||||
|
got.append({"row": r, "detail": self._detail(ctx, r)})
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
yield from got
|
||||||
|
d += timedelta(days=1)
|
||||||
|
|
||||||
|
# ── 수집 ──────────────────────────────────────────────
|
||||||
|
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
yield from group_payments(self._items(ctx, start, end), start, end).values()
|
||||||
|
|
||||||
|
def normalize_order(self, p: dict[str, Any]) -> list[SaleEvent]:
|
||||||
|
pid, day = str(p.get("paymentId") or ""), p.get("_day")
|
||||||
|
if not pid or day is None:
|
||||||
|
return []
|
||||||
|
names = p.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 p.get("statuses") or []]
|
||||||
|
orders = p.get("orders") or []
|
||||||
|
return [SaleEvent(
|
||||||
|
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{pid}", external_order_id=pid,
|
||||||
|
external_line_id=",".join(orders)[:100], order_date=p.get("order_day"), payment_date=day, event_date=day,
|
||||||
|
amount=max(0, int(p.get("amount") or 0)), product_name=name[:200], option_name=str(p.get("opt") or "")[:200],
|
||||||
|
quantity=int(p.get("qty") or 0), discount_amount=max(0, int(p.get("discount") or 0)),
|
||||||
|
order_status="/".join(statuses)[:50],
|
||||||
|
)]
|
||||||
|
|
||||||
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
|
from app.timezone import today_kst # noqa: WPS433
|
||||||
|
|
||||||
|
self.authenticate(ctx)
|
||||||
|
rows = self._day_rows(ctx, today_kst())
|
||||||
|
return f"카카오쇼핑 API 연결 정상(결제일 기준 주문 조회 확인, 오늘 결제 주문 {len(rows)}건)."
|
||||||
|
|
||||||
|
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||||
|
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": "paid", "label": "결제일 기준 주문", "path": PAID_PATH, "ok": False, "error": exc.message[:300]}]}
|
||||||
|
flat = [{**flatten(it["row"], "list"), **flatten(it["detail"])} for it in items]
|
||||||
|
probes = [{"key": "paid", "label": "결제일 기준 주문 + 주문정보(전체 상태)", "path": f"{PAID_PATH} → {ORDER_PATH}",
|
||||||
|
"ok": True, "count": len(items), "fields": field_summary(flat)}]
|
||||||
|
by_status: dict[str, list[dict[str, str]]] = {}
|
||||||
|
for it, f in zip(items, flat):
|
||||||
|
by_status.setdefault(str(it["row"].get("orderStatus") or "?"), []).append(f)
|
||||||
|
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 UNPAID_STATUS else
|
||||||
|
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "orderStatus",
|
||||||
|
"ok": True, "count": len(rows),
|
||||||
|
"fields": [f for f in field_summary(rows)
|
||||||
|
if f["sum"] is not None and f["name"].startswith("orderProduct.")]})
|
||||||
|
pays = group_payments(items, day, to)
|
||||||
|
days = []
|
||||||
|
d = day
|
||||||
|
while d <= to:
|
||||||
|
day_pays = [p for p in pays.values() if p["_day"] == d]
|
||||||
|
days.append({"date": d.isoformat(), "orders": len(day_pays), "amount": sum(p["amount"] for p in day_pays),
|
||||||
|
"claimed": sum(p["claimed"] for p in day_pays), "ship": sum(p["ship"] for p in day_pays)})
|
||||||
|
d += timedelta(days=1)
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||||
|
"rule": "결제일 기준 주문의 (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오 할인 합(배송비 제외, "
|
||||||
|
"결제 뒤 취소·반품분 포함, 미결제 제외). 판매자센터 매출과 대조 전 — 표의 항목 합계로 확인"}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""수동 입력 전용 쇼핑몰 — API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 넣는다.
|
||||||
|
|
||||||
|
어댑터는 쇼핑몰의 "종류"만 알린다: 인증 항목이 없고(manual_only), 매출 업데이트(sync_all)에서 빠진다.
|
||||||
|
DB(perf_marketplaces)에는 manual_input = TRUE 로 넣는다(마이그레이션 003).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .base import MarketplaceAdapter
|
||||||
|
|
||||||
|
|
||||||
|
class ManualOnlyAdapter(MarketplaceAdapter):
|
||||||
|
auth_type = "manual"
|
||||||
|
manual_only = True
|
||||||
|
note = "API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 입력합니다."
|
||||||
|
|
||||||
|
|
||||||
|
class CoupangRocketAdapter(ManualOnlyAdapter):
|
||||||
|
code = "coupang_rocket"
|
||||||
|
name = "쿠팡(로켓)"
|
||||||
|
|
||||||
|
|
||||||
|
class AtomyAzmallAdapter(ManualOnlyAdapter):
|
||||||
|
code = "atomy"
|
||||||
|
name = "애터미아자몰"
|
||||||
@@ -202,7 +202,7 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic
|
|||||||
|
|
||||||
class NaverAdapter(MarketplaceAdapter):
|
class NaverAdapter(MarketplaceAdapter):
|
||||||
code = "naver"
|
code = "naver"
|
||||||
name = "네이버 스마트스토어"
|
name = "네이버"
|
||||||
auth_type = "oauth"
|
auth_type = "oauth"
|
||||||
implemented = True
|
implemented = True
|
||||||
replace_range = True
|
replace_range = True
|
||||||
|
|||||||
@@ -14,14 +14,17 @@ from .gmarket import GmarketAdapter
|
|||||||
from .gsshop import GsshopAdapter
|
from .gsshop import GsshopAdapter
|
||||||
from .kakao import KakaoAdapter
|
from .kakao import KakaoAdapter
|
||||||
from .lotteon import LotteonAdapter
|
from .lotteon import LotteonAdapter
|
||||||
|
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter
|
||||||
from .naver import NaverAdapter
|
from .naver import NaverAdapter
|
||||||
from .ohouse import OhouseAdapter
|
from .ohouse import OhouseAdapter
|
||||||
from .toss import TossAdapter
|
from .toss import TossAdapter
|
||||||
|
|
||||||
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
||||||
|
# 화면 순서와 같게(DB sort_order 도 같은 순서 — 마이그레이션 003)
|
||||||
Cafe24Adapter(),
|
Cafe24Adapter(),
|
||||||
NaverAdapter(),
|
NaverAdapter(),
|
||||||
CoupangAdapter(),
|
CoupangAdapter(), # 쿠팡(윙)
|
||||||
|
CoupangRocketAdapter(), # 쿠팡(로켓) — 수동 입력 전용
|
||||||
OhouseAdapter(),
|
OhouseAdapter(),
|
||||||
GmarketAdapter(),
|
GmarketAdapter(),
|
||||||
KakaoAdapter(),
|
KakaoAdapter(),
|
||||||
@@ -29,6 +32,7 @@ _ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
|||||||
ElevenstAdapter(),
|
ElevenstAdapter(),
|
||||||
LotteonAdapter(),
|
LotteonAdapter(),
|
||||||
TossAdapter(),
|
TossAdapter(),
|
||||||
|
AtomyAzmallAdapter(), # 애터미아자몰 — 수동 입력 전용
|
||||||
)
|
)
|
||||||
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
||||||
|
|
||||||
|
|||||||
@@ -1,22 +1,604 @@
|
|||||||
"""토스쇼핑 — 판매자 API.
|
"""토스쇼핑 — 토스쇼핑 API(shopping-fep).
|
||||||
|
|
||||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
문서: https://shopping-docs.toss.im/dev (전체 목록 llms.txt, 각 쪽 주소 뒤에 .md 를 붙이면 원문)
|
||||||
|
|
||||||
|
인증(공식 방식): 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > 자체 개발 → [키 발급](호출 IP 입력) →
|
||||||
|
Access Key·Secret Key. OAuth2 client_credentials 로 토큰을 받는다.
|
||||||
|
POST https://oauth2.cert.toss.im/token (form: grant_type=client_credentials, client_id=Access Key,
|
||||||
|
client_secret=Secret Key, scope=toss-shopping-fep:write)
|
||||||
|
응답 expires_in 은 약 1년 — 매번 새로 받으면 이용이 제한될 수 있어(문서 안내) 암호화 저장해 두고 재사용,
|
||||||
|
401 이면 한 번만 새로 받는다. **키 발급 때 넣은 IP(이 서버 외부 IP)에서만 호출된다.**
|
||||||
|
API 는 https://shopping-fep.toss.im, 헤더 Authorization: Bearer {token}. HTTP 200 + resultType FAIL 로 오류를 준다.
|
||||||
|
호출 제한: 셀러·API 별 읽기 초당 50회(넘으면 TOO_MANY_REQUEST).
|
||||||
|
|
||||||
|
매출 = 토스쇼핑 파트너스 "순 거래액" = 매출 − 환불(2026-10-01 사용자 지정, 9/6 화면: 매출 29,600 − 환불 11,900 = 17,700).
|
||||||
|
- 매출 SALE — 주문 내역 조회 GET /api/v3/shopping-fep/orders/v2?startDate=&endDate=&limit=50&nextCursor=
|
||||||
|
(한 번에 31일까지, 상태 생략 = 전체 상태, 커서 페이지). 줄 = 주문상품(orderProductId), 묶음 = 주문(orderId).
|
||||||
|
주문 하나 = 사건 하나(`toss:{orderId}`), 날짜 = 주문 시각(orderedAt, 한국 날짜 — 토스쇼핑은 주문 = 결제),
|
||||||
|
금액 = 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외. 할인(totalDiscountPrice = 토스쇼핑 할인 + 토스페이 할인)은
|
||||||
|
discount_amount 로만 보관. 결제 전(BEFORE_PAYMENT)만 빼고 결제 뒤 취소·반품도 주문일 매출에 둔다(화면 "매출"도 환불 전 금액).
|
||||||
|
- 환불 CANCEL/RETURN — 환불일에 뺀다. 주문상품 하나에 한 번(사건 ID `toss:R{orderProductId}`). `merge_refunds`:
|
||||||
|
① 클레임 목록 GET /api/v3/shopping-fep/claims(날짜 조건이 없어 전체를 넘긴다)의 환불 완료(isRefunded) CANCEL·RETURN —
|
||||||
|
날짜 = refundedDt(한국 날짜). 반품은 이것뿐(주문 내역엔 반품 완료 날짜가 없다).
|
||||||
|
② 클레임이 없는 결제취소 — 주문 내역의 canceledAt(한국 날짜). 결제완료 단계의 고객 취소는 클레임이 생기지 않는다(문서).
|
||||||
|
기간보다 CANCEL_LOOKBACK_DAYS(90)일 앞 주문까지 불러 다른 날 주문을 기간 안에 취소한 것도 잡는다.
|
||||||
|
금액 = 그 주문상품의 price(판매가 × 수량, 매출과 같은 기준), 주문 내역에 없으면(90일보다 오래된 주문) 클레임 order.price.
|
||||||
|
9/6 실데이터: 9/5 주문(276435356)을 9/6 취소 11,900 — 클레임(CANCEL/COMPLETED)·canceledAt 둘 다 9/6 = 화면 환불 11,900.
|
||||||
|
정산 건별(settlement-steps)의 REFUND 는 이 취소를 담지 않아(구매확정 전 취소는 정산에 안 올라옴) 쓰지 않는다.
|
||||||
|
- 설정 화면 "쇼핑몰 원본 데이터 확인"에 날짜별 매출·환불·순 거래액과 환불 출처별(정산·취소 시각·클레임) 비교.
|
||||||
|
- 구매자·수령인 이름·연락처·주소·요청사항은 저장하지 않는다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from .base import CredentialField, MarketplaceAdapter
|
import re
|
||||||
|
import time
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from .base import (
|
||||||
|
AdapterContext,
|
||||||
|
AdapterError,
|
||||||
|
ApiError,
|
||||||
|
AuthFailed,
|
||||||
|
CredentialField,
|
||||||
|
MarketplaceAdapter,
|
||||||
|
NotConfigured,
|
||||||
|
SaleEvent,
|
||||||
|
TokenExpired,
|
||||||
|
)
|
||||||
|
from .naver import field_summary, flatten
|
||||||
|
|
||||||
|
TOKEN_URL = "https://oauth2.cert.toss.im/token"
|
||||||
|
HOST = "https://shopping-fep.toss.im"
|
||||||
|
ORDERS_PATH = "/api/v3/shopping-fep/orders/v2"
|
||||||
|
SETTLEMENT_PATH = "/api/v3/shopping-fep/settlement-steps"
|
||||||
|
SETTLEMENT_SIZE = 100 # 문서 1~100
|
||||||
|
SCOPE = "toss-shopping-fep:write"
|
||||||
|
EVENT_PREFIX = "toss:"
|
||||||
|
PAGE_SIZE = 50 # 문서 최대 50
|
||||||
|
WINDOW_DAYS = 31 # 한 번에 31일까지
|
||||||
|
MAX_PAGES = 2000 # 한 구간 10만 건 — 무한 반복 방지
|
||||||
|
TOKEN_MARGIN_SEC = 3600 # 만료 1시간 전이면 새로 받는다(토큰은 약 1년)
|
||||||
|
CALL_INTERVAL_SEC = 0.1 # 읽기 초당 50회 제한 — 넉넉히
|
||||||
|
RETRY_429 = 3
|
||||||
|
PROBE_MAX_DAYS = 31
|
||||||
|
KST = timezone(timedelta(hours=9))
|
||||||
|
|
||||||
|
# 결제 전 주문만 매출에서 뺀다. 결제 뒤 취소·반품은 주문일 매출에 두고 원본 확인 표에 참고로 따로 보인다.
|
||||||
|
EXCLUDED_STATUS = frozenset({"BEFORE_PAYMENT"})
|
||||||
|
CLAIMED_STATUS = frozenset({"CANCELED_PAYMENT", "COMPLETED_RETURN"})
|
||||||
|
STATUS_KO = {
|
||||||
|
"BEFORE_PAYMENT": "결제전", "PAID": "결제완료", "PREPARING_PRODUCT": "상품준비중", "DELIVERING": "배송중",
|
||||||
|
"DELIVERED": "배송완료", "CONFIRMED_ORDER": "구매확정", "CLAIM_REQUESTED_CANCEL": "취소요청",
|
||||||
|
"CANCELED_PAYMENT": "결제취소", "CLAIM_REJECTED_CANCEL": "취소거절", "REQUESTED_EXCHANGE": "교환요청",
|
||||||
|
"ONGOING_EXCHANGE": "교환중", "COMPLETED_EXCHANGE": "교환완료", "CLAIM_REJECTED_EXCHANGE": "교환거절",
|
||||||
|
"REQUESTED_RETURN": "반품요청", "ONGOING_RETURN": "반품중", "COMPLETED_RETURN": "반품완료",
|
||||||
|
"CLAIM_REJECTED_RETURN": "반품거절", "CLAIM_COLLECTING": "수거중", "CLAIM_COLLECTED": "수거완료",
|
||||||
|
"CLAIM_DELIVERING": "재배송중",
|
||||||
|
}
|
||||||
|
# 원본 데이터 확인에서 값을 숨기는 항목(개인정보·자유 입력)
|
||||||
|
PERSONAL_KEYS = frozenset({
|
||||||
|
"ordererName", "ordererPhone", "ordererRealPhone", "receiverName", "receiverPhone", "receiverRealPhone",
|
||||||
|
"address", "detailAddress", "zipCode", "shippingNote", "shippingTrackingNumber",
|
||||||
|
# 클레임 목록(order.* · 수거 주소 · 요청 사유 자유 입력 · 첨부 사진)
|
||||||
|
"ordererPhoneNumber", "receiverPhoneNumber", "returnAddress", "requestReason", "requestDetailReason",
|
||||||
|
"requestImages[]",
|
||||||
|
})
|
||||||
|
CLAIMS_PATH = "/api/v3/shopping-fep/claims"
|
||||||
|
CLAIM_PAGE_SIZE = 100
|
||||||
|
CLAIM_MAX_PAGES = 100 # 클레임 목록은 날짜로 못 거른다(전체를 넘긴다) — 1만 건까지
|
||||||
|
CANCEL_LOOKBACK_DAYS = 90 # 환불 후보(주문 취소 시각): 이만큼 전 주문까지 본다
|
||||||
|
|
||||||
|
|
||||||
|
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 kst_day(value: Any) -> date | None:
|
||||||
|
"""주문 시각 → 한국 날짜. 시간대가 붙어 있으면(Z, +00:00 …) 한국 시간으로 바꾸고, 없으면 한국 시간으로 본다."""
|
||||||
|
s = str(value or "").strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
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
|
||||||
|
if dt.tzinfo is not None:
|
||||||
|
dt = dt.astimezone(KST)
|
||||||
|
return dt.date()
|
||||||
|
|
||||||
|
|
||||||
|
def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
|
||||||
|
"""주문상품 → 주문 하나로 합침(주문일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
|
||||||
|
금액 = price(판매가 × 수량) 합(할인 전, 배송비 제외). 할인·배송비·취소/반품분은 참고용으로 모은다.
|
||||||
|
배송비는 묶음(deliveryFeeGroupId)마다 한 번만 센다."""
|
||||||
|
orders: dict[str, dict[str, Any]] = {}
|
||||||
|
ship_groups: set[str] = set()
|
||||||
|
for it in items:
|
||||||
|
oid = str(it.get("orderId") or "")
|
||||||
|
day = kst_day(it.get("orderedAt"))
|
||||||
|
status = str(it.get("orderProductStatus") 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": []})
|
||||||
|
price = _won(it.get("price"))
|
||||||
|
o["amount"] += price
|
||||||
|
if status in CLAIMED_STATUS:
|
||||||
|
o["claimed"] += price
|
||||||
|
group = str(it.get("deliveryFeeGroupId") or f"{oid}-{it.get('orderProductId')}")
|
||||||
|
if group not in ship_groups:
|
||||||
|
ship_groups.add(group)
|
||||||
|
o["ship"] += _won(it.get("deliveryFee"))
|
||||||
|
o["qty"] += _won(it.get("quantity"))
|
||||||
|
o["discount"] += _won(it.get("totalDiscountPrice"))
|
||||||
|
name = str(it.get("productName") or "")
|
||||||
|
if name and name not in o["names"]:
|
||||||
|
o["names"].append(name)
|
||||||
|
o["opt"] = o["opt"] or str(it.get("optionName") or "")
|
||||||
|
if status and status not in o["statuses"]:
|
||||||
|
o["statuses"].append(status)
|
||||||
|
return orders
|
||||||
|
|
||||||
|
|
||||||
|
def refund_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""정산 건별 목록 → 환불(stepType REFUND) 상품 줄만, 환불일(transactionTs 한국 날짜)이 [start, end] 인 것.
|
||||||
|
금액은 양수로(사건에서 − 를 붙인다). 배송비 줄(orderProductId 없음)은 매출에 배송비를 넣지 않으므로 뺀다."""
|
||||||
|
out = []
|
||||||
|
for it in items:
|
||||||
|
if str(it.get("stepType") or "") != "REFUND" or not it.get("orderProductId") or not it.get("orderId"):
|
||||||
|
continue
|
||||||
|
day = kst_day(it.get("transactionTs"))
|
||||||
|
if day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
amount = abs(_won(it.get("orderProductPrice"))) or abs(_won(it.get("stockPrice"))) * max(1, _won(it.get("quantity")))
|
||||||
|
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it["orderProductId"]),
|
||||||
|
"_day": day, "_ts": str(it.get("transactionTs") or ""), "amount": amount,
|
||||||
|
"qty": _won(it.get("quantity")), "name": str(it.get("displayProductName") or ""),
|
||||||
|
"order_day": kst_day(it.get("originTransactionTs"))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""환불 후보 — 주문 내역의 취소 시각(canceledAt 한국 날짜)이 [start, end] 인 주문상품. 금액 = price(판매가 × 수량)."""
|
||||||
|
out = []
|
||||||
|
for it in items:
|
||||||
|
day = kst_day(it.get("canceledAt"))
|
||||||
|
if not it.get("orderId") or day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
status = str(it.get("orderProductStatus") or "")
|
||||||
|
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it.get("orderProductId") or ""), "_day": day,
|
||||||
|
"amount": _won(it.get("price")), "status": status, "note": STATUS_KO.get(status, status),
|
||||||
|
"order_day": kst_day(it.get("orderedAt"))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def claim_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""환불 후보 — 클레임 목록의 환불 완료(isRefunded, refundedDt 한국 날짜)가 [start, end] 인 것.
|
||||||
|
금액 = order.price(문서: "상품 가격" — 수량을 곱한 값인지 실데이터로 확인), 수량은 note 에."""
|
||||||
|
out = []
|
||||||
|
for it in items:
|
||||||
|
day = kst_day(it.get("refundedDt"))
|
||||||
|
order = it.get("order") if isinstance(it.get("order"), dict) else {}
|
||||||
|
product = it.get("product") if isinstance(it.get("product"), dict) else {}
|
||||||
|
if not it.get("isRefunded") or day is None or not (start <= day <= end) or not order.get("id"):
|
||||||
|
continue
|
||||||
|
out.append({"orderId": str(order["id"]), "orderProductId": str(order.get("orderProductId") or ""), "_day": day,
|
||||||
|
"amount": _won(order.get("price")), "note": f"{it.get('type') or '?'}/{it.get('status') or '?'} · "
|
||||||
|
f"수량 {_won(product.get('quantity'))}", "order_day": kst_day(order.get("createdDt"))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def merge_refunds(order_items: Iterable[dict[str, Any]], claims: Iterable[dict[str, Any]],
|
||||||
|
start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""환불 규칙 — 클레임 환불 완료(CANCEL·RETURN, refundedDt) + 클레임이 없는 결제취소(canceledAt), 주문상품마다 한 번.
|
||||||
|
금액은 주문 내역의 price(판매가 × 수량)를 우선(없으면 클레임 order.price). 날짜가 [start, end] 인 것만.
|
||||||
|
클레임이 있는 주문상품은 그 클레임 날짜만 쓴다(기간 밖이어도 취소 시각으로 다시 넣지 않음 — 날짜가 바뀌지 않게)."""
|
||||||
|
order_items = list(order_items)
|
||||||
|
by_op = {str(it.get("orderProductId")): it for it in order_items if it.get("orderProductId")}
|
||||||
|
out: dict[str, dict[str, Any]] = {}
|
||||||
|
claimed_ops: set[str] = set()
|
||||||
|
for c in claims:
|
||||||
|
order = c.get("order") if isinstance(c.get("order"), dict) else {}
|
||||||
|
product = c.get("product") if isinstance(c.get("product"), dict) else {}
|
||||||
|
kind = str(c.get("type") or "")
|
||||||
|
op = str(order.get("orderProductId") or "")
|
||||||
|
if not c.get("isRefunded") or kind not in ("CANCEL", "RETURN") or not order.get("id") or not op:
|
||||||
|
continue
|
||||||
|
claimed_ops.add(op)
|
||||||
|
day = kst_day(c.get("refundedDt"))
|
||||||
|
if day is None or not (start <= day <= end) or op in out:
|
||||||
|
continue
|
||||||
|
it = by_op.get(op) or {}
|
||||||
|
out[op] = {"orderId": str(order["id"]), "orderProductId": op, "_day": day, "type": kind,
|
||||||
|
"amount": _won(it["price"]) if "price" in it else _won(order.get("price")),
|
||||||
|
"qty": _won(it.get("quantity")) or _won(product.get("quantity")),
|
||||||
|
"name": str(it.get("productName") or product.get("name") or ""),
|
||||||
|
"order_day": kst_day(it.get("orderedAt") or order.get("createdDt"))}
|
||||||
|
for r in cancel_rows(order_items, start, end):
|
||||||
|
op = r["orderProductId"]
|
||||||
|
if not op or op in claimed_ops or op in out or r["status"] != "CANCELED_PAYMENT":
|
||||||
|
continue
|
||||||
|
it = by_op.get(op) or {}
|
||||||
|
out[op] = {"orderId": r["orderId"], "orderProductId": op, "_day": r["_day"], "type": "CANCEL",
|
||||||
|
"amount": r["amount"], "qty": _won(it.get("quantity")), "name": str(it.get("productName") or ""),
|
||||||
|
"order_day": kst_day(it.get("orderedAt"))}
|
||||||
|
return sorted(out.values(), key=lambda x: (x["_day"], x["orderId"], x["orderProductId"]))
|
||||||
|
|
||||||
|
|
||||||
|
def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""원본 확인 표 — 항목별 채워진 줄·숫자 합계·예시 값(개인정보·자유 입력 항목은 값·합계 숨김)."""
|
||||||
|
fields = field_summary([flatten(r) for r in rows])
|
||||||
|
for f in fields:
|
||||||
|
if f["name"].rsplit(".", 1)[-1] in PERSONAL_KEYS:
|
||||||
|
f["personal"], f["sample"], f["sum"] = True, "", None
|
||||||
|
return fields
|
||||||
|
|
||||||
|
|
||||||
class TossAdapter(MarketplaceAdapter):
|
class TossAdapter(MarketplaceAdapter):
|
||||||
code = "toss"
|
code = "toss"
|
||||||
name = "토스쇼핑"
|
name = "토스쇼핑"
|
||||||
auth_type = "api_key"
|
auth_type = "oauth"
|
||||||
note = "입력 항목은 연동 단계에서 토스쇼핑 판매자 API 문서로 확정합니다."
|
implemented = True
|
||||||
|
replace_range = True
|
||||||
|
event_prefix = EVENT_PREFIX
|
||||||
|
docs_url = "https://shopping-docs.toss.im/dev"
|
||||||
|
note = ("토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발에서 발급한 Access Key·Secret Key 를 입력합니다. "
|
||||||
|
"키 발급 때 이 서버의 외부 IP 를 등록해야 호출됩니다.")
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._last_call = 0.0
|
||||||
|
|
||||||
def credential_fields(self) -> list[CredentialField]:
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
# 키 이름(api_key·api_secret)은 처음 만든 입력칸 그대로 — 이미 저장한 값이 이어진다.
|
||||||
return [
|
return [
|
||||||
CredentialField("seller_id", "판매자 ID"),
|
CredentialField("api_key", "Access Key", secret=True,
|
||||||
CredentialField("api_key", "API Key", secret=True),
|
help="토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발의 Access Key"),
|
||||||
CredentialField("api_secret", "API Secret", secret=True, required=False),
|
CredentialField("api_secret", "Secret Key", secret=True,
|
||||||
|
help="같은 화면의 Secret Key"),
|
||||||
|
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:
|
||||||
|
"""저장된 토큰이 1시간 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장."""
|
||||||
|
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
|
||||||
|
|
||||||
|
access_key = ctx.credentials.get("api_key").strip()
|
||||||
|
secret_key = ctx.credentials.get("api_secret").strip()
|
||||||
|
if not access_key or not secret_key:
|
||||||
|
raise NotConfigured("Access Key 와 Secret Key 를 입력하세요.")
|
||||||
|
form = {"grant_type": "client_credentials", "client_id": access_key, "client_secret": secret_key,
|
||||||
|
"scope": SCOPE}
|
||||||
|
try:
|
||||||
|
res = httpx.post(TOKEN_URL, data=form, timeout=ctx.timeout_sec,
|
||||||
|
headers={"Accept": "application/json; charset=UTF-8"})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"토스 인증 서버 연결 실패: {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}. Access Key·Secret Key 와 "
|
||||||
|
"키 발급 때 등록한 IP(이 서버 외부 IP)를 확인하세요.")
|
||||||
|
raise ApiError(f"토스쇼핑 토큰 발급 오류({res.status_code}): {msg}")
|
||||||
|
tok = str(body["access_token"])
|
||||||
|
expires_in = _won(body.get("expires_in")) or 24 * 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:
|
||||||
|
err = body.get("error")
|
||||||
|
if isinstance(err, dict):
|
||||||
|
parts = [str(err.get(k)) for k in ("errorCode", "errorType", "reason", "message") if err.get(k)]
|
||||||
|
else:
|
||||||
|
parts = [str(body.get(k)) for k in ("error", "error_description", "code", "message") if body.get(k)]
|
||||||
|
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·TOO_MANY_REQUEST 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더.
|
||||||
|
성공이면 success 내용을 돌려준다(토스쇼핑은 HTTP 200 + resultType FAIL 로도 오류를 준다)."""
|
||||||
|
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()
|
||||||
|
body = self._json(res)
|
||||||
|
err = body.get("error") if isinstance(body.get("error"), dict) else {}
|
||||||
|
limited = res.status_code == 429 or "TOO_MANY" in str(err.get("errorCode") or err.get("errorType") or "")
|
||||||
|
if limited 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
|
||||||
|
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)}. 키 발급 때 등록한 IP"
|
||||||
|
"(이 서버 외부 IP)를 확인하세요.")
|
||||||
|
if limited:
|
||||||
|
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
if res.status_code >= 400:
|
||||||
|
raise ApiError(f"토스쇼핑 API 오류({res.status_code}): {self._err_text(body, res)}")
|
||||||
|
if body.get("resultType") == "FAIL":
|
||||||
|
raise ApiError(f"토스쇼핑 API 오류: {self._err_text(body, res)}")
|
||||||
|
success = body.get("success")
|
||||||
|
return success if isinstance(success, dict) else {}
|
||||||
|
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
|
||||||
|
def _window_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
||||||
|
"""조회 기간 [a, b](31일 이하)의 주문상품 전체 — 모든 상태, 커서로 끝까지."""
|
||||||
|
params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE}
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
cursor = None
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, ORDERS_PATH, {**params, **({"nextCursor": cursor} if cursor else {})})
|
||||||
|
rows = [r for r in body.get("results") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
cursor = body.get("nextCursor")
|
||||||
|
if not cursor or not rows:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _settlement_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
||||||
|
"""거래일 기준 [a, b](31일 이하)의 정산 건별 줄 전체(결제·환불·배송비), nextToken 으로 끝까지."""
|
||||||
|
params: dict[str, Any] = {"dateCondition": "TRANSACTION_DATE", "fromDate": a.isoformat(),
|
||||||
|
"toDate": b.isoformat(), "size": SETTLEMENT_SIZE}
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token = None
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, SETTLEMENT_PATH, {**params, **({"nextToken": token} if token else {})})
|
||||||
|
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
token = body.get("nextToken")
|
||||||
|
if not token or not rows:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
||||||
|
"""클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지."""
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token = None
|
||||||
|
for _ in range(CLAIM_MAX_PAGES):
|
||||||
|
body = self._get(ctx, CLAIMS_PATH, {"size": CLAIM_PAGE_SIZE, **({"nextToken": token} if token else {})})
|
||||||
|
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
token = body.get("nextToken")
|
||||||
|
if not token or not rows or body.get("hasNext") is False:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _windows(start: date, end: date) -> list[tuple[date, date]]:
|
||||||
|
windows = []
|
||||||
|
a = start
|
||||||
|
while a <= end:
|
||||||
|
b = min(end, a + timedelta(days=WINDOW_DAYS - 1))
|
||||||
|
windows.append((a, b))
|
||||||
|
a = b + timedelta(days=1)
|
||||||
|
return windows
|
||||||
|
|
||||||
|
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
"""주문 내역(매출) — 31일 구간마다 진행 막대 한 칸(plan 은 부르는 쪽이 주문 + 정산 구간 수로 정한다)."""
|
||||||
|
for a, b in self._windows(start, end):
|
||||||
|
rows = self._window_items(ctx, a, b)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
yield from rows
|
||||||
|
|
||||||
|
def _refund_items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
"""정산 건별(환불이 들어 있음) — 31일 구간마다 진행 막대 한 칸."""
|
||||||
|
for a, b in self._windows(start, end):
|
||||||
|
rows = self._settlement_items(ctx, a, b)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
yield from rows
|
||||||
|
|
||||||
|
def _lookback_items(self, ctx: AdapterContext, start: date) -> list[dict[str, Any]]:
|
||||||
|
"""기간 앞 CANCEL_LOOKBACK_DAYS 일의 주문상품 — 다른 날 주문을 기간 안에 취소한 것을 찾는 용도."""
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for a, b in self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)):
|
||||||
|
rows = self._window_items(ctx, a, b)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
out.extend(rows)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _plan(self, ctx: AdapterContext, start: date, end: date, extra: int = 0) -> None:
|
||||||
|
"""진행 막대: 기간 주문 구간 + 앞 90일 주문 구간 + 클레임 목록 1단계 (+ 원본 확인의 정산 구간)."""
|
||||||
|
back = len(self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)))
|
||||||
|
ctx.progress.plan(len(self._windows(start, end)) + back + 1 + extra, "단계")
|
||||||
|
|
||||||
|
def _claims_step(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
||||||
|
claims = self._claims(ctx)
|
||||||
|
ctx.progress.step(items=len(claims))
|
||||||
|
return claims
|
||||||
|
|
||||||
|
# ── 수집 ──────────────────────────────────────────────
|
||||||
|
def collect(self, ctx: AdapterContext, start: date, end: date) -> tuple[int, list[SaleEvent]]:
|
||||||
|
"""매출(주문일) + 환불(환불일, merge_refunds). 주문 내역은 환불 금액·취소 시각에도 쓰여 한 번만 부른다."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
self._plan(ctx, start, end)
|
||||||
|
items = list(self._items(ctx, start, end))
|
||||||
|
back = self._lookback_items(ctx, start)
|
||||||
|
claims = self._claims_step(ctx)
|
||||||
|
events: list[SaleEvent] = []
|
||||||
|
for o in group_orders(items, start, end).values():
|
||||||
|
events.extend(self.normalize_order(o))
|
||||||
|
for r in merge_refunds(back + items, claims, start, end):
|
||||||
|
events.extend(self.normalize_refund(r))
|
||||||
|
for ev in events:
|
||||||
|
ev.validate()
|
||||||
|
return len(items) + len(claims), events
|
||||||
|
|
||||||
|
def normalize_refund(self, r: dict[str, Any]) -> list[SaleEvent]:
|
||||||
|
oid, day = str(r.get("orderId") or ""), r.get("_day")
|
||||||
|
if not oid or day is None or not r.get("orderProductId"):
|
||||||
|
return []
|
||||||
|
kind = "RETURN" if r.get("type") == "RETURN" else "CANCEL"
|
||||||
|
return [SaleEvent(
|
||||||
|
event_type=kind, external_event_id=f"{EVENT_PREFIX}R{r['orderProductId']}", external_order_id=oid,
|
||||||
|
external_line_id=str(r["orderProductId"]), event_date=day, order_date=r.get("order_day"),
|
||||||
|
amount=-abs(int(r.get("amount") or 0)), product_name=str(r.get("name") or "")[:200],
|
||||||
|
quantity=int(r.get("qty") or 0), order_status="반품 환불" if kind == "RETURN" else "취소 환불",
|
||||||
|
)]
|
||||||
|
|
||||||
|
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=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)
|
||||||
|
today = today_kst()
|
||||||
|
body = self._get(ctx, ORDERS_PATH, {"startDate": today.isoformat(), "endDate": today.isoformat(), "limit": 1})
|
||||||
|
n = len(body.get("results") or [])
|
||||||
|
more = " 이상" if body.get("nextCursor") else ""
|
||||||
|
return f"토스쇼핑 API 연결 정상(토큰 발급·주문 조회 확인, 오늘 주문상품 {n}건{more})."
|
||||||
|
|
||||||
|
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||||
|
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||||
|
"""기간(최대 31일)을 실제로 불러 항목별 합계·상태별 합계와 날짜별 매출·환불·순 거래액(= 저장되는 값)을 돌려준다.
|
||||||
|
환불은 출처별(클레임 환불 완료·주문 취소 시각·정산 REFUND)로도 나란히 보여 파트너스 화면과 맞춰 볼 수 있게.
|
||||||
|
개인정보 항목은 값 없이 이름만. 저장하지 않는다."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||||
|
self._plan(ctx, day, to, extra=len(self._windows(day, to)))
|
||||||
|
try:
|
||||||
|
items = list(self._items(ctx, day, to))
|
||||||
|
back = self._lookback_items(ctx, day)
|
||||||
|
except AdapterError as exc:
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
|
||||||
|
{"key": "orders", "label": "주문 내역", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]}
|
||||||
|
by_status: dict[str, list[dict[str, Any]]] = {}
|
||||||
|
for it in items:
|
||||||
|
by_status.setdefault(str(it.get("orderProductStatus") or "?"), []).append(it)
|
||||||
|
probes = [{"key": "orders", "label": "주문 내역(전체 상태, 주문상품 단위)", "path": ORDERS_PATH,
|
||||||
|
"ok": True, "count": len(items), "fields": summary(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": "orderProductStatus", "ok": True, "count": len(rows),
|
||||||
|
"fields": [f for f in summary(rows) if f["sum"] is not None]})
|
||||||
|
claims_err = ""
|
||||||
|
try:
|
||||||
|
claims = self._claims_step(ctx)
|
||||||
|
probes.append({"key": "claims", "label": "클레임 목록(전체 — 날짜 조건 없음)", "path": CLAIMS_PATH, "ok": True,
|
||||||
|
"count": len(claims), "fields": summary(claims)})
|
||||||
|
except AdapterError as exc:
|
||||||
|
claims, claims_err = [], exc.message[:300]
|
||||||
|
probes.append({"key": "claims", "label": "클레임 목록", "path": CLAIMS_PATH, "ok": False, "error": claims_err})
|
||||||
|
settle_err = ""
|
||||||
|
try:
|
||||||
|
settle = list(self._refund_items(ctx, day, to))
|
||||||
|
probes.append({"key": "settlement", "label": "정산 건별(거래일 기준, 결제·환불·배송비 줄 전체 — 참고)",
|
||||||
|
"path": SETTLEMENT_PATH + " (TRANSACTION_DATE)", "ok": True, "count": len(settle),
|
||||||
|
"fields": summary(settle)})
|
||||||
|
except AdapterError as exc:
|
||||||
|
settle, settle_err = [], exc.message[:300]
|
||||||
|
probes.append({"key": "settlement", "label": "정산 건별(참고)", "path": SETTLEMENT_PATH, "ok": False,
|
||||||
|
"error": settle_err})
|
||||||
|
|
||||||
|
refunds = merge_refunds(back + items, claims, day, to) # 저장되는 환불(현재 규칙)
|
||||||
|
# ── 환불 출처별 — 파트너스 화면 "환불"과 맞춰 보는 용도 ──
|
||||||
|
candidates: list[dict[str, Any]] = [
|
||||||
|
{"key": "rule", "label": "적용 규칙(클레임 환불 + 클레임 없는 결제취소)", "rows": [
|
||||||
|
{**r, "note": "반품" if r["type"] == "RETURN" else "취소"}
|
||||||
|
for r in refunds], "error": claims_err},
|
||||||
|
{"key": "claims", "label": "클레임 환불 완료(refundedDt, 금액 order.price)", "rows": claim_rows(claims, day, to),
|
||||||
|
"error": claims_err},
|
||||||
|
{"key": "canceled", "label": f"주문 취소 시각(canceledAt, {CANCEL_LOOKBACK_DAYS}일 전 주문까지)",
|
||||||
|
"rows": cancel_rows(back + items, day, to), "error": ""},
|
||||||
|
{"key": "settlement", "label": "정산 REFUND 상품 줄(거래일) — 참고", "rows": [
|
||||||
|
{**r, "note": "정산 REFUND"} for r in refund_rows(settle, day, to)],
|
||||||
|
"error": settle_err},
|
||||||
|
]
|
||||||
|
for c in candidates:
|
||||||
|
c["days"] = {}
|
||||||
|
for r in c["rows"]:
|
||||||
|
k = r["_day"].isoformat()
|
||||||
|
c["days"][k] = c["days"].get(k, 0) + r["amount"]
|
||||||
|
c["rows"] = [{"date": r["_day"].isoformat(), "orderDate": r["order_day"].isoformat() if r.get("order_day") else "",
|
||||||
|
"orderId": r["orderId"], "orderProductId": r["orderProductId"],
|
||||||
|
"amount": r["amount"], "note": r.get("note") or ""}
|
||||||
|
for r in sorted(c["rows"], key=lambda x: (x["_day"], x["orderId"]))][:200]
|
||||||
|
|
||||||
|
days = []
|
||||||
|
orders = group_orders(items, day, to)
|
||||||
|
d = day
|
||||||
|
while d <= to:
|
||||||
|
day_orders = [o for o in orders.values() if o["_day"] == d]
|
||||||
|
sales = sum(o["amount"] for o in day_orders)
|
||||||
|
refund = sum(r["amount"] for r in refunds if r["_day"] == d)
|
||||||
|
days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sales, "claimed": refund,
|
||||||
|
"ship": sales - refund})
|
||||||
|
d += timedelta(days=1)
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||||
|
"refund_candidates": candidates,
|
||||||
|
"day_cols": {"amount": "매출(주문일)", "claimed": "환불(환불일)", "ship": "순 거래액(저장되는 매출)"},
|
||||||
|
"rule": "순 거래액 = 매출 − 환불. 매출 = 주문일(orderedAt) 기준 주문상품 price(판매가 × 수량) 합(할인 전, "
|
||||||
|
"배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외). 환불 = 클레임 환불 완료(취소·반품, refundedDt) + "
|
||||||
|
"클레임 없는 결제취소(canceledAt), 주문상품마다 한 번, 금액 = 그 주문상품 price. 환불일 기준"}
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
||||||
|
|
||||||
|
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
|
||||||
|
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||||
|
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
||||||
|
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
||||||
|
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
|
||||||
|
|
||||||
|
환경변수(.env)
|
||||||
|
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
|
||||||
|
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
|
||||||
|
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.timezone import now_kst
|
||||||
|
|
||||||
|
logger = logging.getLogger("performance.auto_sync")
|
||||||
|
|
||||||
|
AUTO_USER = "자동 업데이트"
|
||||||
|
DEFAULT_DAYS = 10
|
||||||
|
DEFAULT_HOURS = (9, 19)
|
||||||
|
SLOT_MINUTES = 30
|
||||||
|
|
||||||
|
_started = False
|
||||||
|
_start_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _env(name: str) -> str:
|
||||||
|
return (os.getenv(name, "") or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def enabled() -> bool:
|
||||||
|
return _env("PERFORMANCE_AUTO_SYNC").lower() not in ("0", "false", "no", "off")
|
||||||
|
|
||||||
|
|
||||||
|
def sync_days() -> int:
|
||||||
|
try:
|
||||||
|
return max(1, min(90, int(_env("PERFORMANCE_AUTO_SYNC_DAYS") or DEFAULT_DAYS)))
|
||||||
|
except ValueError:
|
||||||
|
return DEFAULT_DAYS
|
||||||
|
|
||||||
|
|
||||||
|
def hour_window() -> tuple[int, int]:
|
||||||
|
m = re.fullmatch(r"(\d{1,2})\s*-\s*(\d{1,2})", _env("PERFORMANCE_AUTO_SYNC_HOURS"))
|
||||||
|
if not m:
|
||||||
|
return DEFAULT_HOURS
|
||||||
|
first, last = int(m.group(1)), int(m.group(2))
|
||||||
|
if not (0 <= first <= last <= 23):
|
||||||
|
return DEFAULT_HOURS
|
||||||
|
return first, last
|
||||||
|
|
||||||
|
|
||||||
|
def is_slot(t: datetime, hours: tuple[int, int]) -> bool:
|
||||||
|
"""t(분 단위로 자른 시각)가 회차인가 — 정각·30분, first시 정각 ~ last시 정각."""
|
||||||
|
first, last = hours
|
||||||
|
if t.minute % SLOT_MINUTES:
|
||||||
|
return False
|
||||||
|
return first <= t.hour < last or (t.hour == last and t.minute == 0)
|
||||||
|
|
||||||
|
|
||||||
|
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
|
||||||
|
"""after 보다 뒤의 첫 회차 시각."""
|
||||||
|
t = after.replace(second=0, microsecond=0)
|
||||||
|
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
|
||||||
|
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
|
||||||
|
if is_slot(t, hours):
|
||||||
|
return t
|
||||||
|
t += timedelta(minutes=SLOT_MINUTES)
|
||||||
|
raise ValueError("회차를 찾을 수 없습니다")
|
||||||
|
|
||||||
|
|
||||||
|
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
|
||||||
|
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
|
||||||
|
from . import common, jobs # noqa: WPS433
|
||||||
|
from .credentials import CredentialService # noqa: WPS433
|
||||||
|
from .sync import SyncService # noqa: WPS433
|
||||||
|
|
||||||
|
if jobs.running_job() is not None:
|
||||||
|
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
|
||||||
|
start, end = today - timedelta(days=days - 1), today
|
||||||
|
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
|
||||||
|
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
|
||||||
|
error = ""
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
results = sync.sync_all(start=start, end=end, trigger="schedule", user=AUTO_USER, job=job)
|
||||||
|
except Exception as exc: # noqa: BLE001 — 스레드가 죽지 않게
|
||||||
|
logger.exception("auto 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)
|
||||||
|
ok = sum(1 for r in results if r.get("ok"))
|
||||||
|
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
|
||||||
|
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error}
|
||||||
|
|
||||||
|
|
||||||
|
def start_auto_sync_thread(app_state: Any) -> bool:
|
||||||
|
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
|
||||||
|
global _started # noqa: PLW0603
|
||||||
|
store = getattr(app_state, "performance_store", None)
|
||||||
|
if store is None or not enabled():
|
||||||
|
return False
|
||||||
|
with _start_lock:
|
||||||
|
if _started:
|
||||||
|
return False
|
||||||
|
_started = True
|
||||||
|
hours, days = hour_window(), sync_days()
|
||||||
|
|
||||||
|
def _loop() -> None:
|
||||||
|
due = next_slot(now_kst(), hours)
|
||||||
|
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
|
||||||
|
due.strftime("%m-%d %H:%M"))
|
||||||
|
while True:
|
||||||
|
wait = (due - now_kst()).total_seconds()
|
||||||
|
if wait > 0:
|
||||||
|
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
res = run_once(store, app_state, today=due.date(), days=days)
|
||||||
|
logger.info("매출 자동 업데이트 %s: %s", due.strftime("%H:%M"), res)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("매출 자동 업데이트 실패 — 다음 회차에 다시")
|
||||||
|
due = next_slot(max(now_kst(), due), hours)
|
||||||
|
|
||||||
|
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
|
||||||
|
return True
|
||||||
@@ -25,6 +25,8 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any]
|
|||||||
if not marketplace.get("enabled"):
|
if not marketplace.get("enabled"):
|
||||||
return "disabled"
|
return "disabled"
|
||||||
adapter = get_adapter(marketplace["code"])
|
adapter = get_adapter(marketplace["code"])
|
||||||
|
if adapter is not None and adapter.manual_only:
|
||||||
|
return "manual"
|
||||||
if adapter is not None and not adapter.uses_shared_integration and not configured:
|
if adapter is not None and not adapter.uses_shared_integration and not configured:
|
||||||
return "not_configured"
|
return "not_configured"
|
||||||
return (status_row or {}).get("status") or "unknown"
|
return (status_row or {}).get("status") or "unknown"
|
||||||
@@ -58,6 +60,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
||||||
q_end = max(period.end, year_period.end)
|
q_end = max(period.end, year_period.end)
|
||||||
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
|
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
|
||||||
|
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
|
||||||
|
manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes]
|
||||||
|
manual_amounts = getattr(store, "manual_amounts", None)
|
||||||
|
manual_cells = sorted(f"{d.isoformat()}|{c}" for d, c in
|
||||||
|
(manual_amounts(period.start, period.end, manual_codes) if manual_amounts and manual_codes else {}))
|
||||||
|
|
||||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||||
@@ -143,6 +150,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
"chart_daily": calc.daily_series(period, codes, cells),
|
"chart_daily": calc.daily_series(period, codes, cells),
|
||||||
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
|
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
|
||||||
"problems": problems,
|
"problems": problems,
|
||||||
|
"manual_codes": manual_codes,
|
||||||
|
"manual_cells": manual_cells,
|
||||||
|
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
|
||||||
|
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
|
||||||
"last_update_at": store.last_update_at(),
|
"last_update_at": store.last_update_at(),
|
||||||
"running": store.running_codes(),
|
"running": store.running_codes(),
|
||||||
"no_marketplaces": not all_codes,
|
"no_marketplaces": not all_codes,
|
||||||
@@ -175,10 +186,11 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
|
|||||||
has_rate = bool(rates.get(adapter.code))
|
has_rate = bool(rates.get(adapter.code))
|
||||||
rows.append({
|
rows.append({
|
||||||
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
|
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
|
||||||
"include_in_sales": m["include_in_sales"],
|
"include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")),
|
||||||
"rate": _fmt_rate(cur_rate) if has_rate else "",
|
"rate": _fmt_rate(cur_rate) if has_rate else "",
|
||||||
"rate_history": len(rates.get(adapter.code, ())),
|
"rate_history": len(rates.get(adapter.code, ())),
|
||||||
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
|
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
|
||||||
|
"manual_only": adapter.manual_only,
|
||||||
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
|
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
|
||||||
"configured": configured.get(adapter.code, False),
|
"configured": configured.get(adapter.code, False),
|
||||||
"via_cafe24": adapter.code in via_cafe24,
|
"via_cafe24": adapter.code in via_cafe24,
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from datetime import date, datetime, timedelta
|
|||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from psycopg import errors as pg_errors
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
from psycopg_pool import ConnectionPool
|
from psycopg_pool import ConnectionPool
|
||||||
@@ -25,6 +26,10 @@ from app.timezone import to_kst_iso
|
|||||||
STALE_RUN_AFTER = timedelta(minutes=30)
|
STALE_RUN_AFTER = timedelta(minutes=30)
|
||||||
|
|
||||||
|
|
||||||
|
class ManualMigrationNeeded(Exception):
|
||||||
|
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
|
||||||
|
|
||||||
|
|
||||||
def _iso(v: Any) -> Any:
|
def _iso(v: Any) -> Any:
|
||||||
if isinstance(v, datetime):
|
if isinstance(v, datetime):
|
||||||
return to_kst_iso(v)
|
return to_kst_iso(v)
|
||||||
@@ -56,8 +61,12 @@ class PerformanceDBStore:
|
|||||||
return [{k: _iso(v) for k, v in r.items()} for r in rows]
|
return [{k: _iso(v) for k, v in r.items()} for r in rows]
|
||||||
|
|
||||||
def update_marketplace(self, code: str, *, enabled: bool | None = None,
|
def update_marketplace(self, code: str, *, enabled: bool | None = None,
|
||||||
include_in_sales: bool | None = None) -> dict[str, Any] | None:
|
include_in_sales: bool | None = None,
|
||||||
|
manual_input: bool | None = None) -> dict[str, Any] | None:
|
||||||
sets, params = [], []
|
sets, params = [], []
|
||||||
|
if manual_input is not None:
|
||||||
|
sets.append("manual_input = %s")
|
||||||
|
params.append(bool(manual_input))
|
||||||
if enabled is not None:
|
if enabled is not None:
|
||||||
sets.append("enabled = %s")
|
sets.append("enabled = %s")
|
||||||
params.append(bool(enabled))
|
params.append(bool(enabled))
|
||||||
@@ -67,10 +76,13 @@ class PerformanceDBStore:
|
|||||||
if not sets:
|
if not sets:
|
||||||
return None
|
return None
|
||||||
params.append(code)
|
params.append(code)
|
||||||
with self._pool.connection() as conn:
|
try:
|
||||||
row = conn.execute(
|
with self._pool.connection() as conn:
|
||||||
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
|
row = conn.execute(
|
||||||
).fetchone()
|
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
|
||||||
|
).fetchone()
|
||||||
|
except pg_errors.UndefinedColumn:
|
||||||
|
raise ManualMigrationNeeded() from None
|
||||||
return {k: _iso(v) for k, v in row.items()} if row else None
|
return {k: _iso(v) for k, v in row.items()} if row else None
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -281,6 +293,8 @@ class PerformanceDBStore:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
|
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
|
||||||
|
"""날짜 × 쇼핑몰 총매출. 수동 입력이 켜진 쇼핑몰은 수동 값을 넣은 날 그 값이 API 수집값을 대신한다
|
||||||
|
(실적 화면·회의록 머리 카드가 같은 숫자를 보게 여기서 합친다)."""
|
||||||
if not codes:
|
if not codes:
|
||||||
return {}
|
return {}
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
@@ -290,7 +304,122 @@ class PerformanceDBStore:
|
|||||||
"GROUP BY sales_date, marketplace_code",
|
"GROUP BY sales_date, marketplace_code",
|
||||||
(start, end, codes),
|
(start, end, codes),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
|
out = {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
|
||||||
|
out.update(self.manual_amounts(start, end, codes))
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 수동 입력 매출(마이그레이션 002)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def manual_amounts(self, start: date, end: date, codes: list[str], *,
|
||||||
|
active_only: bool = True) -> dict[tuple[date, str], int]:
|
||||||
|
"""수동 입력 값. active_only = 그 쇼핑몰 수동 입력이 켜진 것만(집계에 쓰는 값). 002 미적용이면 비어 있음."""
|
||||||
|
if not codes:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT s.sales_date, s.marketplace_code, s.amount FROM perf_manual_sales s "
|
||||||
|
"JOIN perf_marketplaces m ON m.code = s.marketplace_code "
|
||||||
|
"WHERE s.sales_date BETWEEN %s AND %s AND s.marketplace_code = ANY(%s)"
|
||||||
|
+ (" AND m.manual_input" if active_only else ""),
|
||||||
|
(start, end, codes),
|
||||||
|
).fetchall()
|
||||||
|
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||||
|
return {}
|
||||||
|
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"]) for r in rows}
|
||||||
|
|
||||||
|
def api_amount(self, code: str, day: date) -> int:
|
||||||
|
"""그날 API 수집 합계(수동 값과 무관) — 수동 입력 칸에 참고로 보여 준다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT COALESCE(SUM(amount), 0)::BIGINT AS amount FROM perf_sales_events "
|
||||||
|
"WHERE marketplace_code = %s AND sales_date = %s", (code, day),
|
||||||
|
).fetchone()
|
||||||
|
return int(row["amount"] or 0)
|
||||||
|
|
||||||
|
def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "") -> None:
|
||||||
|
"""수동 값 저장(amount None = 지움 → 그날은 다시 API 값)."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if amount is None:
|
||||||
|
conn.execute("DELETE FROM perf_manual_sales WHERE marketplace_code = %s AND sales_date = %s",
|
||||||
|
(code, day))
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
|
||||||
|
(code, day, int(amount), user),
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise ManualMigrationNeeded() from None
|
||||||
|
|
||||||
|
def set_manual_sales_bulk(self, entries: list[tuple[str, date, int]], *, user: str = "") -> int:
|
||||||
|
"""엑셀 업로드 — (쇼핑몰, 날짜, 금액) 여러 개를 한 트랜잭션으로 저장(덮어씀). 하나라도 실패하면 모두 취소."""
|
||||||
|
if not entries:
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.executemany(
|
||||||
|
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
|
||||||
|
[(code, day, int(amount), user) for code, day, amount in entries],
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise ManualMigrationNeeded() from None
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 광고비(마이그레이션 005)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def ad_amounts(self, start: date, end: date) -> tuple[dict[tuple[date, str], int], dict[tuple[date, str], str]]:
|
||||||
|
"""(날짜, 채널) → 금액, (날짜, 채널) → 입력 방식(manual/upload/api). 005 미적용이면 AdMigrationNeeded."""
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT spend_date, channel_code, amount, source FROM perf_ad_spend "
|
||||||
|
"WHERE spend_date BETWEEN %s AND %s", (start, end),
|
||||||
|
).fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded() from None
|
||||||
|
return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows},
|
||||||
|
{(r["spend_date"], r["channel_code"]): r["source"] for r in rows})
|
||||||
|
|
||||||
|
def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "") -> None:
|
||||||
|
"""광고비 한 칸 저장(amount None = 지움)."""
|
||||||
|
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
|
||||||
|
|
||||||
|
def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual",
|
||||||
|
user: str = "") -> int:
|
||||||
|
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소."""
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
if not entries:
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
gone = [(code, d) for d, a in entries if a is None]
|
||||||
|
keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
|
||||||
|
if gone:
|
||||||
|
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s", gone)
|
||||||
|
if keep:
|
||||||
|
cur.executemany(
|
||||||
|
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by",
|
||||||
|
keep,
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded() from None
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
||||||
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
|
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
|
||||||
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
|
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
|
||||||
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
|
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
|
||||||
|
- 쇼핑몰별 [중지]: SyncJob.stop_shop(code) → 그 쇼핑몰만 같은 방식(다음 API 호출 직전, 저장 안 함)으로 멈추고 "중지됨",
|
||||||
|
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 저장 중이면 못 멈춘다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -39,8 +41,17 @@ class ShopProgress(Progress):
|
|||||||
self.unit = "단계"
|
self.unit = "단계"
|
||||||
self.status = self.label = self.message = ""
|
self.status = self.label = self.message = ""
|
||||||
self.started_at = self.finished_at = 0.0
|
self.started_at = self.finished_at = 0.0
|
||||||
|
self.stop_requested = False # 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def stop(self) -> bool:
|
||||||
|
"""[중지] — 대기·수집 중일 때만(저장 중·끝난 뒤엔 못 멈춤). 받아들였으면 True."""
|
||||||
|
with self._lock:
|
||||||
|
if self.state not in ("waiting", "running"):
|
||||||
|
return False
|
||||||
|
self.stop_requested = True
|
||||||
|
return True
|
||||||
|
|
||||||
# ── 어댑터가 부르는 쪽(Progress) ──
|
# ── 어댑터가 부르는 쪽(Progress) ──
|
||||||
def plan(self, total: int, unit: str = "단계") -> None:
|
def plan(self, total: int, unit: str = "단계") -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -52,11 +63,18 @@ class ShopProgress(Progress):
|
|||||||
|
|
||||||
def check(self) -> None:
|
def check(self) -> None:
|
||||||
if self.cancel_requested and self.state == "running":
|
if self.cancel_requested and self.state == "running":
|
||||||
raise Cancelled("사용자가 업데이트를 취소했습니다.")
|
raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else
|
||||||
|
"사용자가 업데이트를 취소했습니다.")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def cancel_requested(self) -> bool:
|
def cancel_requested(self) -> bool:
|
||||||
return bool(self.job is not None and self.job.cancel_requested)
|
"""멈춰야 하나 — 업데이트 전체 취소 또는 이 쇼핑몰만 중지."""
|
||||||
|
return self.stop_requested or bool(self.job is not None and self.job.cancel_requested)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def stopped_only(self) -> bool:
|
||||||
|
"""이 쇼핑몰만 중지(전체 취소가 아님) — 업데이트는 다음 쇼핑몰로 계속된다."""
|
||||||
|
return self.stop_requested and not (self.job is not None and self.job.cancel_requested)
|
||||||
|
|
||||||
def step(self, n: int = 1, *, items: int = 0) -> None:
|
def step(self, n: int = 1, *, items: int = 0) -> None:
|
||||||
self.check()
|
self.check()
|
||||||
@@ -91,7 +109,8 @@ class ShopProgress(Progress):
|
|||||||
|
|
||||||
def cancelled(self) -> None:
|
def cancelled(self) -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
|
self.state, self.status = "cancelled", "cancelled"
|
||||||
|
self.message = "중지됨" if self.stopped_only else "취소됨"
|
||||||
self.finished_at = time.time()
|
self.finished_at = time.time()
|
||||||
|
|
||||||
def skip(self, message: str) -> None:
|
def skip(self, message: str) -> None:
|
||||||
@@ -118,7 +137,7 @@ class ShopProgress(Progress):
|
|||||||
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
|
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
|
||||||
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
|
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
|
||||||
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
|
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
|
||||||
"fraction": round(self.fraction(), 4),
|
"stop_requested": self.stop_requested, "fraction": round(self.fraction(), 4),
|
||||||
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
|
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,6 +167,14 @@ class SyncJob:
|
|||||||
if not self.finished_at and not self.cancel_requested:
|
if not self.finished_at and not self.cancel_requested:
|
||||||
self.cancel_requested, self.cancelled_by = True, user
|
self.cancel_requested, self.cancelled_by = True, user
|
||||||
|
|
||||||
|
def stop_shop(self, code: str) -> bool:
|
||||||
|
"""쇼핑몰별 [중지] — 그 쇼핑몰만 멈추고 다음 쇼핑몰로. 끝난 작업·없는 쇼핑몰·저장 중·끝난 쇼핑몰은 False."""
|
||||||
|
with self._lock:
|
||||||
|
if self.finished_at:
|
||||||
|
return False
|
||||||
|
shop = next((s for s in self.shops if s.code == code), None)
|
||||||
|
return bool(shop is not None and shop.stop())
|
||||||
|
|
||||||
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
|
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
|
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
"""수동 입력 매출 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글(샘플: upload_sample.xlsx).
|
||||||
|
|
||||||
|
규칙
|
||||||
|
- 머리글(1행) 2열부터 = 쇼핑몰 이름. 설정의 이름·짧은 이름(네이버/토스)·코드 어느 것이든 되고 띄어쓰기·대소문자는 무시.
|
||||||
|
- 수동 입력이 켜진 쇼핑몰 열만 반영. 꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 준다.
|
||||||
|
- 값이 있는 칸만 반영(빈 칸은 그날 기존 값 그대로 — 지우지 않음). 0 은 값(0원)으로 저장.
|
||||||
|
- 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜는 안 됨.
|
||||||
|
- 금액: 원 단위 정수(쉼표·"원" 허용, 소수는 반올림).
|
||||||
|
- 잘못된 칸이 하나라도 있으면 아무것도 저장하지 않고 오류 목록을 돌려준다(일부만 들어가 헷갈리지 않게).
|
||||||
|
|
||||||
|
HTTP·DB 와 무관한 순수 함수 — 라우터가 파일 바이트와 쇼핑몰 목록을 넘긴다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
from typing import Any, Iterable, Mapping
|
||||||
|
|
||||||
|
MAX_FILE_BYTES = 5 * 1024 * 1024
|
||||||
|
MAX_DATA_ROWS = 2000
|
||||||
|
MAX_ERRORS = 30
|
||||||
|
MAX_AMOUNT = 10 ** 12 # 라우터 MAX_MANUAL_AMOUNT 와 같은 상한(원)
|
||||||
|
|
||||||
|
_EXCEL_EPOCH = date(1899, 12, 30)
|
||||||
|
_DATE_RE = re.compile(r"^(\d{4})\s*[-./년]\s*(\d{1,2})\s*[-./월]\s*(\d{1,2})")
|
||||||
|
_COMPACT_RE = re.compile(r"^(\d{4})(\d{2})(\d{2})(?!\d)")
|
||||||
|
|
||||||
|
|
||||||
|
class UploadError(ValueError):
|
||||||
|
"""파일 자체를 읽을 수 없음(형식·크기·머리글)."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ParseResult:
|
||||||
|
entries: list[tuple[str, date, int]] = field(default_factory=list) # (쇼핑몰 코드, 날짜, 금액)
|
||||||
|
errors: list[str] = field(default_factory=list)
|
||||||
|
ignored: list[str] = field(default_factory=list) # 건너뛴 열(머리글 + 이유)
|
||||||
|
columns: list[str] = field(default_factory=list) # 반영 대상 쇼핑몰 코드(열 순서)
|
||||||
|
|
||||||
|
|
||||||
|
def _norm(text: Any) -> str:
|
||||||
|
return re.sub(r"\s+", "", str(text or "")).lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _cell_ref(row: int, col: int) -> str:
|
||||||
|
letters = ""
|
||||||
|
n = col
|
||||||
|
while n:
|
||||||
|
n, r = divmod(n - 1, 26)
|
||||||
|
letters = chr(65 + r) + letters
|
||||||
|
return f"{letters}{row}"
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date(value: Any) -> date | None:
|
||||||
|
"""날짜 칸 → date. 읽을 수 없으면 ValueError, 빈 칸이면 None."""
|
||||||
|
if value is None or (isinstance(value, str) and not value.strip()):
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||||
|
n = int(value)
|
||||||
|
if 19000101 <= n <= 29991231: # 20261012
|
||||||
|
return parse_date(str(n))
|
||||||
|
if 20000 <= n <= 80000: # 엑셀 날짜 일련번호(서식 없는 날짜)
|
||||||
|
return _EXCEL_EPOCH + timedelta(days=n)
|
||||||
|
raise ValueError
|
||||||
|
text = str(value).strip()
|
||||||
|
m = _DATE_RE.match(text) or _COMPACT_RE.match(text)
|
||||||
|
if not m:
|
||||||
|
raise ValueError
|
||||||
|
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||||
|
|
||||||
|
|
||||||
|
def parse_amount(value: Any) -> int | None:
|
||||||
|
"""금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
raise ValueError
|
||||||
|
if isinstance(value, (int, float, Decimal)):
|
||||||
|
num = Decimal(str(value))
|
||||||
|
else:
|
||||||
|
text = re.sub(r"[,\s원₩]", "", str(value))
|
||||||
|
if text == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
num = Decimal(text)
|
||||||
|
except InvalidOperation:
|
||||||
|
raise ValueError from None
|
||||||
|
if not num.is_finite():
|
||||||
|
raise ValueError
|
||||||
|
return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
|
||||||
|
"""머리글로 쓸 수 있는 이름 → 쇼핑몰 코드. markets: code·name, extra_names: 코드별 다른 이름(어댑터 이름·짧은 이름)."""
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for m in markets:
|
||||||
|
code = str(m["code"])
|
||||||
|
for alias in (code, m.get("name"), *((extra_names or {}).get(code) or ())):
|
||||||
|
key = _norm(alias)
|
||||||
|
if key:
|
||||||
|
out.setdefault(key, code)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
|
||||||
|
extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult:
|
||||||
|
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
|
||||||
|
if not content:
|
||||||
|
raise UploadError("빈 파일입니다.")
|
||||||
|
if len(content) > MAX_FILE_BYTES:
|
||||||
|
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
||||||
|
try:
|
||||||
|
import openpyxl # noqa: WPS433
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||||
|
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
||||||
|
raise UploadError("엑셀(.xlsx) 파일을 읽을 수 없습니다. 샘플 파일 양식으로 저장해 올려 주세요.") from None
|
||||||
|
try:
|
||||||
|
ws = wb.worksheets[0]
|
||||||
|
rows = ws.iter_rows(values_only=True)
|
||||||
|
header = next(rows, None)
|
||||||
|
if not header or len(header) < 2:
|
||||||
|
raise UploadError("1행에 날짜와 쇼핑몰 이름 머리글이 없습니다.")
|
||||||
|
|
||||||
|
aliases = header_aliases(markets, extra_names)
|
||||||
|
by_code = {str(m["code"]): m for m in markets}
|
||||||
|
res = ParseResult()
|
||||||
|
col_code: dict[int, str] = {} # 열 번호(0부터) → 반영할 쇼핑몰 코드
|
||||||
|
for idx, title in enumerate(header[1:], start=1):
|
||||||
|
if title is None or not str(title).strip():
|
||||||
|
continue
|
||||||
|
label = str(title).strip()
|
||||||
|
code = aliases.get(_norm(label))
|
||||||
|
if code is None:
|
||||||
|
res.ignored.append(f"{label}(알 수 없는 쇼핑몰)")
|
||||||
|
elif not by_code[code].get("manual_input"):
|
||||||
|
res.ignored.append(f"{label}(수동 입력 꺼짐)")
|
||||||
|
elif code in col_code.values():
|
||||||
|
res.errors.append(f"{_cell_ref(1, idx + 1)} {label}: 같은 쇼핑몰 열이 두 번 있습니다.")
|
||||||
|
else:
|
||||||
|
col_code[idx] = code
|
||||||
|
res.columns.append(code)
|
||||||
|
if not col_code and not res.errors:
|
||||||
|
raise UploadError("반영할 쇼핑몰 열이 없습니다. 머리글을 수동 입력이 켜진 쇼핑몰 이름으로 적어 주세요."
|
||||||
|
+ (f" (건너뛴 열: {', '.join(res.ignored)})" if res.ignored else ""))
|
||||||
|
|
||||||
|
seen: dict[tuple[str, date], str] = {}
|
||||||
|
data_rows = 0
|
||||||
|
for r, row in enumerate(rows, start=2):
|
||||||
|
row = tuple(row or ())
|
||||||
|
cells = {i: (row[i] if i < len(row) else None) for i in col_code}
|
||||||
|
amounts: dict[int, int] = {}
|
||||||
|
for i, raw in cells.items():
|
||||||
|
try:
|
||||||
|
amt = parse_amount(raw)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
|
||||||
|
continue
|
||||||
|
if amt is None:
|
||||||
|
continue
|
||||||
|
if abs(amt) > MAX_AMOUNT:
|
||||||
|
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 너무 큽니다.")
|
||||||
|
continue
|
||||||
|
amounts[i] = amt
|
||||||
|
raw_day = row[0] if row else None
|
||||||
|
try:
|
||||||
|
day = parse_date(raw_day)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{_cell_ref(r, 1)}: 날짜를 읽을 수 없습니다({raw_day}).")
|
||||||
|
continue
|
||||||
|
if day is None:
|
||||||
|
if amounts:
|
||||||
|
res.errors.append(f"{r}행: 날짜가 비어 있습니다.")
|
||||||
|
continue
|
||||||
|
if not amounts:
|
||||||
|
continue
|
||||||
|
data_rows += 1
|
||||||
|
if data_rows > MAX_DATA_ROWS:
|
||||||
|
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||||
|
if day > today:
|
||||||
|
res.errors.append(f"{_cell_ref(r, 1)}: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||||
|
continue
|
||||||
|
for i, amt in amounts.items():
|
||||||
|
code = col_code[i]
|
||||||
|
where = _cell_ref(r, i + 1)
|
||||||
|
if (code, day) in seen:
|
||||||
|
res.errors.append(f"{where}: {by_code[code]['name']} {day.isoformat()} 이 {seen[(code, day)]} 와 겹칩니다.")
|
||||||
|
continue
|
||||||
|
seen[(code, day)] = where
|
||||||
|
res.entries.append((code, day, amt))
|
||||||
|
if len(res.errors) > MAX_ERRORS:
|
||||||
|
break
|
||||||
|
return res
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
화면
|
화면
|
||||||
GET /performance/ 대시보드(모듈 권한)
|
GET /performance/ 대시보드(모듈 권한)
|
||||||
|
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
||||||
GET /performance/settings 실적 설정(관리자)
|
GET /performance/settings 실적 설정(관리자)
|
||||||
JSON API — 모듈 권한
|
JSON API — 모듈 권한
|
||||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||||
@@ -10,8 +11,13 @@ JSON API — 모듈 권한
|
|||||||
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
||||||
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
||||||
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
||||||
|
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
|
||||||
|
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
|
||||||
|
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
|
||||||
|
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
|
||||||
|
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡(로켓) 광고 보고서 — 1열 날짜, 19열 청구금액)
|
||||||
JSON API — 관리자
|
JSON API — 관리자
|
||||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
|
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
|
||||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||||
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
||||||
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
||||||
@@ -28,10 +34,11 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from decimal import Decimal, InvalidOperation
|
from decimal import Decimal, InvalidOperation
|
||||||
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, HTTPException, Query, Request
|
from fastapi import APIRouter, Body, File, HTTPException, Query, Request, UploadFile
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||||
|
|
||||||
from app.timezone import today_kst
|
from app.timezone import today_kst
|
||||||
|
|
||||||
@@ -44,6 +51,12 @@ MAX_EVENT_DAYS = 31
|
|||||||
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
||||||
MAX_BACKFILL_DAYS = 366
|
MAX_BACKFILL_DAYS = 366
|
||||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||||
|
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
||||||
|
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
|
||||||
|
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
|
||||||
|
"먼저 적용해야 합니다.")
|
||||||
|
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
||||||
|
"먼저 적용해야 합니다.")
|
||||||
|
|
||||||
|
|
||||||
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
||||||
@@ -111,11 +124,39 @@ def dashboard_page(
|
|||||||
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/ads", response_class=HTMLResponse)
|
||||||
|
def ads_page(
|
||||||
|
request: Request,
|
||||||
|
period: str = "month",
|
||||||
|
d: str | None = None,
|
||||||
|
from_: str | None = Query(None, alias="from"),
|
||||||
|
to: str | None = None,
|
||||||
|
):
|
||||||
|
from app.main import render_template # noqa: WPS433
|
||||||
|
|
||||||
|
g = common.guard(request)
|
||||||
|
if not isinstance(g, tuple):
|
||||||
|
return g
|
||||||
|
store, user = g
|
||||||
|
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
||||||
|
from .dashboard import _sales_marketplaces # noqa: WPS433
|
||||||
|
|
||||||
|
today = today_kst()
|
||||||
|
ctx = build_ad_dashboard(
|
||||||
|
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||||
|
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||||
|
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
||||||
|
)
|
||||||
|
return render_template(request, "performance/ads.html",
|
||||||
|
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/settings", response_class=HTMLResponse)
|
@router.get("/settings", response_class=HTMLResponse)
|
||||||
def settings_page(request: Request):
|
def settings_page(request: Request):
|
||||||
from app.main import render_template # noqa: WPS433
|
from app.main import render_template # noqa: WPS433
|
||||||
|
|
||||||
g = common.guard(request, admin=True)
|
# 모듈 권한자 누구나 들어온다 — 일반 사용자는 수수료율만(쇼핑몰 표의 다른 칸·다른 카드는 템플릿이 관리자에게만 그린다).
|
||||||
|
g = common.guard(request)
|
||||||
if not isinstance(g, tuple):
|
if not isinstance(g, tuple):
|
||||||
return g
|
return g
|
||||||
store, user = g
|
store, user = g
|
||||||
@@ -227,6 +268,25 @@ def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
|
|||||||
return JSONResponse({"job": job.snapshot()})
|
return JSONResponse({"job": job.snapshot()})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/sync/jobs/{job_id}/shops/{code}/stop")
|
||||||
|
def api_sync_stop_shop(request: Request, job_id: str, code: str) -> JSONResponse:
|
||||||
|
"""쇼핑몰별 [중지] — 시작한 사람 또는 관리자. 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, 기존 매출 그대로)
|
||||||
|
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰은 차례가 오면 건너뛴다. 저장 중·끝난 쇼핑몰은 409."""
|
||||||
|
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="업데이트를 시작한 사람이나 관리자만 중지할 수 있습니다.")
|
||||||
|
if not job.stop_shop(code):
|
||||||
|
raise HTTPException(status_code=409, detail="이미 끝났거나 저장 중인 쇼핑몰은 중지할 수 없습니다.")
|
||||||
|
return JSONResponse({"job": job.snapshot()})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/sync/current")
|
@router.get("/api/sync/current")
|
||||||
def api_sync_current(request: Request) -> JSONResponse:
|
def api_sync_current(request: Request) -> JSONResponse:
|
||||||
common.require_store(request)
|
common.require_store(request)
|
||||||
@@ -250,24 +310,185 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
|
|||||||
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/manual-sales/{code}/{day}")
|
||||||
|
def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지. amount 가 비면 지움(그날은 다시 API 값)."""
|
||||||
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정)
|
||||||
|
_code_or_404(store, code)
|
||||||
|
d = _parse_date(day)
|
||||||
|
if d > today_kst():
|
||||||
|
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
||||||
|
m = next((x for x in store.list_marketplaces() if x["code"] == code), {})
|
||||||
|
if not m.get("manual_input"):
|
||||||
|
raise HTTPException(status_code=400, detail="이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).")
|
||||||
|
raw = payload.get("amount")
|
||||||
|
amount: int | None
|
||||||
|
if raw in (None, ""):
|
||||||
|
amount = None
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
||||||
|
if abs(amount) > MAX_MANUAL_AMOUNT:
|
||||||
|
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
||||||
|
try:
|
||||||
|
store.set_manual_sale(code, d, amount, user=user.get("email", ""))
|
||||||
|
except ManualMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||||
|
api_amount = store.api_amount(code, d)
|
||||||
|
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount,
|
||||||
|
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/manual-sales/sample.xlsx")
|
||||||
|
def api_manual_sample(request: Request) -> Any:
|
||||||
|
common.require_store(request)
|
||||||
|
if not MANUAL_SAMPLE_PATH.is_file():
|
||||||
|
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
|
||||||
|
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/manual-sales/upload")
|
||||||
|
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||||
|
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
|
||||||
|
from . import manual_upload # noqa: WPS433
|
||||||
|
from .dashboard import _short_name # noqa: WPS433
|
||||||
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request) # 날짜 칸 수동 입력과 같은 권한(모듈 권한자 누구나)
|
||||||
|
content = file.file.read(manual_upload.MAX_FILE_BYTES + 1)
|
||||||
|
known = {a.code: a for a in all_adapters()}
|
||||||
|
markets = [m for m in store.list_marketplaces() if m["code"] in known and m["enabled"]]
|
||||||
|
extra = {m["code"]: (known[m["code"]].name, _short_name(m["name"])) for m in markets}
|
||||||
|
try:
|
||||||
|
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
|
||||||
|
except manual_upload.UploadError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||||
|
names = {m["code"]: m["name"] for m in markets}
|
||||||
|
if res.errors:
|
||||||
|
return JSONResponse(status_code=400, content={
|
||||||
|
"detail": f"잘못된 칸이 {len(res.errors)}개{'+' if len(res.errors) > manual_upload.MAX_ERRORS else ''} 있어 "
|
||||||
|
"아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||||
|
"errors": res.errors[:manual_upload.MAX_ERRORS], "ignored": res.ignored})
|
||||||
|
try:
|
||||||
|
saved = store.set_manual_sales_bulk(res.entries, user=user.get("email", ""))
|
||||||
|
except ManualMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
for code, _, _ in res.entries:
|
||||||
|
counts[code] = counts.get(code, 0) + 1
|
||||||
|
days = sorted({d for _, d, _ in res.entries})
|
||||||
|
return JSONResponse({
|
||||||
|
"ok": True, "saved": saved,
|
||||||
|
"by_shop": [{"code": c, "name": names.get(c, c), "count": counts[c]} for c in res.columns if counts.get(c)],
|
||||||
|
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None,
|
||||||
|
"ignored": res.ignored,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# JSON API — 관리자(설정)
|
# JSON API — 광고비(모듈 권한자 누구나)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _ad_channel(channel: str) -> str:
|
||||||
|
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
||||||
|
|
||||||
|
if channel not in CHANNEL_NAMES:
|
||||||
|
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||||
|
return channel
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/ad-spend/{channel}/{day}")
|
||||||
|
def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request)
|
||||||
|
_ad_channel(channel)
|
||||||
|
d = _parse_date(day)
|
||||||
|
if d is None:
|
||||||
|
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
|
||||||
|
if d > today_kst():
|
||||||
|
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
||||||
|
raw = payload.get("amount")
|
||||||
|
amount: int | None
|
||||||
|
if raw in (None, ""):
|
||||||
|
amount = None
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
||||||
|
if abs(amount) > MAX_MANUAL_AMOUNT:
|
||||||
|
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
||||||
|
try:
|
||||||
|
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
|
||||||
|
except AdMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
|
||||||
|
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount,
|
||||||
|
"amount": amount or 0})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/ad-spend/upload")
|
||||||
|
def api_ad_spend_upload(request: Request, channel: str = Query(...), file: UploadFile = File(...)) -> JSONResponse:
|
||||||
|
"""광고비 파일 업로드 — 파일에 있는 날만 덮어쓴다. 잘못된 줄이 있으면 아무것도 저장하지 않는다."""
|
||||||
|
from . import ad_spend # noqa: WPS433
|
||||||
|
from .manual_upload import MAX_FILE_BYTES, UploadError # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request)
|
||||||
|
_ad_channel(channel)
|
||||||
|
parser = ad_spend.PARSERS.get(channel)
|
||||||
|
if parser is None:
|
||||||
|
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
|
||||||
|
content = file.file.read(MAX_FILE_BYTES + 1)
|
||||||
|
try:
|
||||||
|
res = parser(content, today=today_kst(), filename=file.filename or "")
|
||||||
|
except UploadError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||||
|
if res.errors:
|
||||||
|
return JSONResponse(status_code=400, content={
|
||||||
|
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||||
|
"errors": res.errors})
|
||||||
|
try:
|
||||||
|
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""))
|
||||||
|
except ad_spend.AdMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
|
||||||
|
days = sorted(d for d, _ in res.entries)
|
||||||
|
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
|
||||||
|
"total": sum(a for _, a in res.entries), "skipped": res.skipped,
|
||||||
|
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@router.put("/api/marketplaces/{code}")
|
@router.put("/api/marketplaces/{code}")
|
||||||
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
store, _ = common.require_store(request, admin=True)
|
store, _ = common.require_store(request, admin=True)
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
row = store.update_marketplace(
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||||
code,
|
|
||||||
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
adapter = get_adapter(code)
|
||||||
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
if adapter is not None and adapter.manual_only and payload.get("manual_input") is False:
|
||||||
)
|
raise HTTPException(status_code=400, detail="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
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,
|
||||||
|
manual_input=bool(payload["manual_input"]) if "manual_input" in payload else None,
|
||||||
|
)
|
||||||
|
except ManualMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||||
return JSONResponse({"marketplace": row})
|
return JSONResponse({"marketplace": row})
|
||||||
|
|
||||||
|
|
||||||
@router.post("/api/marketplaces/{code}/rates")
|
@router.post("/api/marketplaces/{code}/rates")
|
||||||
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
store, user = common.require_store(request, admin=True)
|
store, user = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
||||||
try:
|
try:
|
||||||
@@ -288,14 +509,14 @@ def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...
|
|||||||
|
|
||||||
@router.get("/api/marketplaces/{code}/rates")
|
@router.get("/api/marketplaces/{code}/rates")
|
||||||
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
||||||
store, _ = common.require_store(request, admin=True)
|
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
return JSONResponse({"rates": store.list_rates(code)})
|
return JSONResponse({"rates": store.list_rates(code)})
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
|
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
|
||||||
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
|
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
|
||||||
store, _ = common.require_store(request, admin=True)
|
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
if not store.delete_rate(code, rate_id):
|
if not store.delete_rate(code, rate_id):
|
||||||
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
||||||
|
|||||||
@@ -102,9 +102,9 @@ class SyncService:
|
|||||||
if progress is not None:
|
if progress is not None:
|
||||||
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
|
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
|
||||||
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
||||||
if progress is not None and progress.cancel_requested: # [업데이트 취소] 뒤 차례가 온 쇼핑몰
|
if progress is not None and progress.cancel_requested: # [업데이트 취소]·쇼핑몰 [중지] 뒤 차례가 온 쇼핑몰
|
||||||
progress.cancelled()
|
progress.cancelled()
|
||||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
return {**result, "cancelled": True, "status": "cancelled", "message": progress.message}
|
||||||
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
|
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
|
||||||
if run_id is None:
|
if run_id is None:
|
||||||
if progress is not None:
|
if progress is not None:
|
||||||
@@ -140,11 +140,13 @@ class SyncService:
|
|||||||
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
|
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
|
||||||
"message": f"{upserted}건 반영"}
|
"message": f"{upserted}건 반영"}
|
||||||
except Cancelled:
|
except Cancelled:
|
||||||
# 수집 중 취소 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
|
# 수집 중 취소·중지 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
|
||||||
self._store.finish_run(run_id, ok=False, error="업데이트 취소")
|
# 쇼핑몰 [중지]면 이 쇼핑몰만 멈추고 sync_all 이 다음 쇼핑몰로 넘어간다.
|
||||||
|
stopped = progress is not None and progress.stopped_only
|
||||||
|
self._store.finish_run(run_id, ok=False, error="쇼핑몰 중지" if stopped else "업데이트 취소")
|
||||||
if progress is not None:
|
if progress is not None:
|
||||||
progress.cancelled()
|
progress.cancelled()
|
||||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
return {**result, "cancelled": True, "status": "cancelled", "message": "중지됨" if stopped else "취소됨"}
|
||||||
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
|
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
|
||||||
status, message = self._failure(exc, ctx)
|
status, message = self._failure(exc, ctx)
|
||||||
logger.warning("performance sync %s failed: %s %s", code, status, message)
|
logger.warning("performance sync %s failed: %s %s", code, status, message)
|
||||||
@@ -160,7 +162,9 @@ class SyncService:
|
|||||||
end = end or today_kst()
|
end = end or today_kst()
|
||||||
start = start or (end - timedelta(days=sync_days() - 1))
|
start = start or (end - timedelta(days=sync_days() - 1))
|
||||||
enabled = {m["code"] for m in self._store.list_marketplaces() if m["enabled"]}
|
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)]
|
# 수동 입력 전용 쇼핑몰(manual_only)은 가져올 API 가 없어 매출 업데이트에서 뺀다
|
||||||
|
targets = [a for a in all_adapters()
|
||||||
|
if a.code in enabled and not a.manual_only and (not codes or a.code in codes)]
|
||||||
progress: dict[str, Any] = {}
|
progress: dict[str, Any] = {}
|
||||||
if job is not None:
|
if job is not None:
|
||||||
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
|
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
|
||||||
|
|||||||
@@ -1,7 +1,16 @@
|
|||||||
{# 실적 모듈 탭 — 설정 탭은 관리자에게만(서버도 관리자만 허용). #}
|
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||||
|
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||||
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
<div class="perf-tabs-main" role="tablist">
|
||||||
{% if is_admin %}
|
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/"
|
||||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">설정</a>
|
role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}">
|
||||||
{% endif %}
|
<span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a>
|
||||||
|
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
|
||||||
|
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||||
|
</div>
|
||||||
|
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
|
||||||
|
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014a" />{% endblock %}
|
||||||
|
|
||||||
|
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||||
|
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||||
|
|
||||||
|
{%- 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 -%}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
|
||||||
|
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
|
||||||
|
{% 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/ads"{% 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 />
|
||||||
|
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if migration_needed %}
|
||||||
|
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005
|
||||||
|
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- ── 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>
|
||||||
|
{% if k.key == 'ratio' %}
|
||||||
|
<div class="perf-kpi-value">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</div>
|
||||||
|
<div class="perf-kpi-delta"><span class="perf-muted">{{ k.note }}</span></div>
|
||||||
|
{% else %}
|
||||||
|
<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>
|
||||||
|
{% endif %}
|
||||||
|
</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>
|
||||||
|
{% if upload_channels %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn perf-ad-upload-btn" id="perf-ad-upload"
|
||||||
|
title="광고 보고서 파일로 일별 광고비를 한 번에 입력">파일 업로드</button>
|
||||||
|
{% endif %}
|
||||||
|
</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] }} — 날짜 칸을 눌러 광고비 입력. 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비)">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></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 v = r.cells[c].gross %}
|
||||||
|
{% if r.kind == 'day' and not r.future and not migration_needed %}
|
||||||
|
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
|
||||||
|
<td class="perf-num is-manual-cell{% if v and not up %} is-manual{% endif %}{% if up %} is-upload{% endif %}"
|
||||||
|
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}" tabindex="0"
|
||||||
|
title="{% if up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||||
|
{% else %}
|
||||||
|
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% if period_kind != 'year' %}
|
||||||
|
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||||
|
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(구글·메타는 카페24 자체몰 매출, 합계 열은 전체 매출).
|
||||||
|
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(윙)·쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.</p>
|
||||||
|
{% endif %}
|
||||||
|
</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></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>ROAS</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">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</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">{% if month.total.roas is not none %}{{ "{:,}".format(month.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</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>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="perf-table perf-year">
|
||||||
|
<thead><tr><th class="perf-th-label">월</th><th>광고비</th><th>ROAS</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">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% elif not r.future %}<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(year.total.gross) }}</td>
|
||||||
|
<td class="perf-num">{% if year.total.roas is not none %}{{ "{:,}".format(year.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="perf-foot perf-muted">
|
||||||
|
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 매출 ÷ 광고비 × 100(구글·메타 = 카페24 자체몰 매출).
|
||||||
|
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||||
|
구글·메타는 지금은 직접 입력합니다.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script type="application/json" id="perf-data">{{ {
|
||||||
|
"names": names,
|
||||||
|
"codes": codes,
|
||||||
|
"daily": chart_daily,
|
||||||
|
"share": chart_share,
|
||||||
|
"period_kind": period_kind,
|
||||||
|
"today": today,
|
||||||
|
"manual_api": "/performance/api/ad-spend/",
|
||||||
|
"manual_word": "광고비",
|
||||||
|
"empty_text": "기간 내 광고비가 없습니다.",
|
||||||
|
"upload_channels": upload_channels
|
||||||
|
} | tojson }}</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}<script src="/static/performance.js?v=20261014a" defer></script>{% endblock %}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014a" />{% endblock %}
|
||||||
|
|
||||||
{%- macro won(v) -%}
|
{%- macro won(v) -%}
|
||||||
{%- if v is none -%}<span class="perf-na"></span>
|
{%- if v is none -%}<span class="perf-na"></span>
|
||||||
@@ -107,6 +107,10 @@
|
|||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head">
|
<div class="perf-card-head">
|
||||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
|
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
|
||||||
|
{% if manual_upload_names %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload"
|
||||||
|
title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button>
|
||||||
|
{% endif %}
|
||||||
<div class="perf-metric" role="group" aria-label="표시 기준">
|
<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="gross">총매출</button>
|
||||||
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
|
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
|
||||||
@@ -118,7 +122,7 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
<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 %}
|
{% for c in codes %}<th title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}</th>{% endfor %}
|
||||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -130,8 +134,15 @@
|
|||||||
</th>
|
</th>
|
||||||
{% for c in codes %}
|
{% for c in codes %}
|
||||||
{% set m = r.cells[c] %}
|
{% set m = r.cells[c] %}
|
||||||
|
{% if r.kind == 'day' and c in manual_codes and not r.future %}
|
||||||
|
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
|
||||||
|
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}" data-manual-code="{{ c }}" data-date="{{ r.date }}"
|
||||||
|
data-manual-value="{{ m.gross if is_manual else '' }}" tabindex="0"
|
||||||
|
title="{% if is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력{% endif %}">{{ m3(m) }}</td>
|
||||||
|
{% else %}
|
||||||
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
|
<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>
|
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}</td>
|
||||||
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
|
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -139,6 +150,10 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
{% if manual_codes and period_kind != 'year' %}
|
||||||
|
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
|
||||||
|
비우고 저장하면 다시 API 수집값. 파란 숫자 = 수동 입력값. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ── 그래프 ── -->
|
<!-- ── 그래프 ── -->
|
||||||
@@ -235,8 +250,9 @@
|
|||||||
"period_kind": period_kind,
|
"period_kind": period_kind,
|
||||||
"period_start": period.start.isoformat(),
|
"period_start": period.start.isoformat(),
|
||||||
"period_end": period.end.isoformat(),
|
"period_end": period.end.isoformat(),
|
||||||
"today": today
|
"today": today,
|
||||||
|
"manual_upload_names": manual_upload_names
|
||||||
} | tojson }}</script>
|
} | tojson }}</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261014a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014a" />{% endblock %}
|
||||||
|
|
||||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||||
|
|
||||||
@@ -8,7 +8,8 @@
|
|||||||
<section class="perf perf-settings" id="perf-settings">
|
<section class="perf perf-settings" id="perf-settings">
|
||||||
{% include "performance/_tabs.html" %}
|
{% include "performance/_tabs.html" %}
|
||||||
|
|
||||||
{% if not key_info.ok %}
|
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
|
||||||
|
{% if is_admin and not key_info.ok %}
|
||||||
<div class="perf-notice is-warn">
|
<div class="perf-notice is-warn">
|
||||||
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
|
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
|
||||||
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
|
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
|
||||||
@@ -18,26 +19,33 @@
|
|||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head">
|
<div class="perf-card-head">
|
||||||
<h2 class="perf-h">쇼핑몰 설정</h2>
|
<h2 class="perf-h">쇼핑몰 설정</h2>
|
||||||
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
|
{% if is_admin %}
|
||||||
|
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
|
||||||
|
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있습니다.</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
<div class="erp-table-wrap">
|
<div class="erp-table-wrap">
|
||||||
<table class="perf-table perf-set-table">
|
<table class="perf-table perf-set-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="perf-th-label">쇼핑몰</th>
|
<th class="perf-th-label">쇼핑몰</th>
|
||||||
<th>사용</th>
|
{% if is_admin %}<th>사용</th>
|
||||||
<th>매출 집계</th>
|
<th>매출 집계</th>
|
||||||
|
<th>수동 입력</th>{% endif %}
|
||||||
<th>수수료율</th>
|
<th>수수료율</th>
|
||||||
<th>API 설정</th>
|
{% if is_admin %}<th>API 설정</th>
|
||||||
<th>연결 상태</th>
|
<th>연결 상태</th>{% endif %}
|
||||||
<th>마지막 동기화</th>
|
<th>마지막 동기화</th>
|
||||||
<th></th>
|
{% if is_admin %}<th></th>{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for r in rows %}
|
{% for r in rows %}
|
||||||
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
|
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
|
||||||
<th class="perf-td-label" scope="row">{{ r.name }}</th>
|
<th class="perf-td-label" scope="row">{{ r.name }}</th>
|
||||||
|
{% if is_admin %}
|
||||||
<td class="perf-center">
|
<td class="perf-center">
|
||||||
<label class="perf-switch" title="사용 여부">
|
<label class="perf-switch" title="사용 여부">
|
||||||
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
|
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
|
||||||
@@ -48,13 +56,21 @@
|
|||||||
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
||||||
</label>
|
</label>
|
||||||
</td>
|
</td>
|
||||||
|
<td class="perf-center">
|
||||||
|
<label class="perf-switch" title="{% if r.manual_only %}수동 입력 전용 쇼핑몰 — API 연동이 없어 늘 켜져 있습니다{% else %}수동 입력 사용 — 켜면 실적 일자별 표에서 날짜 칸에 매출을 직접 입력(입력한 날은 API 값 대신){% endif %}">
|
||||||
|
<input type="checkbox" data-field="manual_input"{% if r.manual_input or r.manual_only %} checked{% endif %}{% if r.manual_only %} disabled{% endif %} /><span></span>
|
||||||
|
</label>
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
<td class="perf-rate-cell">
|
<td class="perf-rate-cell">
|
||||||
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
<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"
|
<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>
|
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
|
||||||
</td>
|
</td>
|
||||||
|
{% if is_admin %}
|
||||||
<td>
|
<td>
|
||||||
{% if r.shared %}<span class="perf-pill">공통 연동</span>
|
{% if r.manual_only %}<span class="perf-pill">수동 입력 전용</span>
|
||||||
|
{% elif r.shared %}<span class="perf-pill">공통 연동</span>
|
||||||
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
||||||
{% else %}<span class="perf-pill">미설정</span>{% endif %}
|
{% else %}<span class="perf-pill">미설정</span>{% endif %}
|
||||||
{% if r.via_cafe24 %}<span class="perf-pill is-ok" title="카페24 마켓 통합관리로 들어온 이 쇼핑몰 주문을 카페24 수집 때 함께 반영합니다">카페24 경유</span>{% endif %}
|
{% if r.via_cafe24 %}<span class="perf-pill is-ok" title="카페24 마켓 통합관리로 들어온 이 쇼핑몰 주문을 카페24 수집 때 함께 반영합니다">카페24 경유</span>{% endif %}
|
||||||
@@ -65,11 +81,16 @@
|
|||||||
<i></i>{{ r.status_label }}</span>
|
<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 %}
|
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
|
{% endif %}
|
||||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
||||||
|
{% if is_admin %}
|
||||||
<td class="perf-nowrap">
|
<td class="perf-nowrap">
|
||||||
|
{% if not r.manual_only %}
|
||||||
<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="creds">설정</button>
|
||||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
||||||
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
|
{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -77,10 +98,11 @@
|
|||||||
</div>
|
</div>
|
||||||
<p class="perf-foot perf-muted">
|
<p class="perf-foot perf-muted">
|
||||||
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
||||||
상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
|
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{% if is_admin %}
|
||||||
<div class="perf-grid2">
|
<div class="perf-grid2">
|
||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
||||||
@@ -123,12 +145,16 @@
|
|||||||
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
|
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
|
||||||
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
||||||
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
||||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.</p>
|
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.<br>
|
||||||
|
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.<br>
|
||||||
|
· <b>쿠팡(윙)</b>: 판매자배송 발주서 + 로켓그로스 주문을 결제일로 모아 날짜별 매출 후보(할인 전·후, 취소분 뺀 값, 로켓그로스 따로)와 판매량 — WING 비즈니스 인사이트 → 판매분석에서 같은 날짜의 "매출(원)"·"판매량"과 비교해 주세요.</p>
|
||||||
<div class="perf-sample-form">
|
<div class="perf-sample-form">
|
||||||
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
||||||
<option value="naver">네이버 스마트스토어</option>
|
<option value="naver">네이버</option>
|
||||||
<option value="elevenst">11번가</option>
|
<option value="elevenst">11번가</option>
|
||||||
<option value="gsshop">GS샵</option>
|
<option value="gsshop">GS샵</option>
|
||||||
|
<option value="toss">토스쇼핑</option>
|
||||||
|
<option value="coupang">쿠팡(윙)</option>
|
||||||
</select>
|
</select>
|
||||||
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
||||||
<span class="perf-muted">~</span>
|
<span class="perf-muted">~</span>
|
||||||
@@ -174,7 +200,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{% endif %}
|
||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261014a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance import ad_spend as ads
|
||||||
|
from app.modules.performance.manual_upload import UploadError
|
||||||
|
|
||||||
|
TODAY = date(2026, 10, 13)
|
||||||
|
|
||||||
|
# 사용자 제공 양식(2026-10-13) 그대로 — 머리글, "전체" 합계 줄, 날짜 줄 + 그 아래 캠페인 줄
|
||||||
|
ROCKET_CSV = """날짜,배송유형,부가세 유형,생성자,담당자,광고 유형,광고 목표,캠페인 ID,캠페인명,청구가능 금액 유형,예산 유형,광고 예산,소진 광고비,소진 광고비 중 조정 금액,조정 후 소진 광고비,초과 소진 금액,청구 가능 광고비,부가가치세,청구금액(+부가가치세)
|
||||||
|
전체,RETAIL,,,,,,,,,,,2400506,0,2400506,2396813,2396813,239681,2636494
|
||||||
|
2026년 10월 01일,RETAIL,Taxable,,,,,,,,,,200404,0,200404,200000,200000,20000,220000
|
||||||
|
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200404,0,200404,200000,200000,,
|
||||||
|
2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,196997,0,196997,196997,196997,19700,216697
|
||||||
|
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,196997,0,196997,196997,196997,,
|
||||||
|
2026년 10월 12일,RETAIL,Taxable,,,,,,,,,,200210,0,200210,200210,200210,20021,220231
|
||||||
|
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200210,0,200210,200210,200210,,
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _xlsx(text: str) -> bytes:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
for line in text.strip().splitlines():
|
||||||
|
ws.append([int(v) if v.isdigit() else (v or None) for v in line.split(",")])
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("content,name", [
|
||||||
|
(ROCKET_CSV.encode("utf-8-sig"), "report.csv"),
|
||||||
|
(ROCKET_CSV.encode("cp949"), "report.csv"),
|
||||||
|
(_xlsx(ROCKET_CSV), "report.xlsx"),
|
||||||
|
])
|
||||||
|
def test_rocket_report_reads_date_and_col19(content, name):
|
||||||
|
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
|
||||||
|
assert not res.errors
|
||||||
|
assert res.entries == [(date(2026, 10, 1), 220000), (date(2026, 10, 6), 216697), (date(2026, 10, 12), 220231)]
|
||||||
|
assert res.skipped == 5 # 머리글 + 전체 + 캠페인 줄 3개
|
||||||
|
|
||||||
|
|
||||||
|
def test_rocket_report_errors_block_everything():
|
||||||
|
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,9\n" # 같은 날 두 번
|
||||||
|
bad += "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류
|
||||||
|
bad += "2026년 10월 07일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,\n" # 금액 빈 칸
|
||||||
|
bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜
|
||||||
|
res = ads.parse_coupang_rocket(bad.encode("utf-8"), today=TODAY)
|
||||||
|
joined = " / ".join(res.errors)
|
||||||
|
assert len(res.errors) == 4, res.errors
|
||||||
|
assert "겹칩니다" in joined and "날짜를 읽을 수 없습니다" in joined and "비어 있습니다" in joined and "앞으로의 날짜" in joined
|
||||||
|
|
||||||
|
|
||||||
|
def test_rocket_report_wrong_file():
|
||||||
|
with pytest.raises(UploadError):
|
||||||
|
ads.parse_coupang_rocket(b"", today=TODAY)
|
||||||
|
with pytest.raises(UploadError): # 날짜 줄이 하나도 없음
|
||||||
|
ads.parse_coupang_rocket("날짜,금액\n전체,3\n".encode("utf-8"), today=TODAY)
|
||||||
|
other = ads.parse_coupang_rocket("이름,금액\n홍길동,3\n".encode("utf-8"), today=TODAY) # 다른 양식 → 줄 오류
|
||||||
|
assert not other.entries and "날짜를 읽을 수 없습니다" in other.errors[0]
|
||||||
|
with pytest.raises(UploadError):
|
||||||
|
ads.parse_coupang_rocket(b"PK\x03\x04broken", today=TODAY, filename="x.xlsx")
|
||||||
|
|
||||||
|
|
||||||
|
class _Store:
|
||||||
|
def __init__(self, missing=False):
|
||||||
|
self.missing = missing
|
||||||
|
|
||||||
|
def ad_amounts(self, start, end):
|
||||||
|
if self.missing:
|
||||||
|
raise ads.AdMigrationNeeded()
|
||||||
|
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"),
|
||||||
|
(date(2026, 10, 2), "google"): (50000, "manual"),
|
||||||
|
(date(2026, 9, 1), "meta"): (100000, "manual")}
|
||||||
|
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||||
|
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
rows = {(date(2026, 10, 5), "cafe24"): 2_700_000, (date(2026, 10, 1), "coupang_rocket"): 550_000,
|
||||||
|
(date(2026, 10, 3), "coupang_rocket"): 110_000}
|
||||||
|
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_dashboard_month():
|
||||||
|
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||||
|
sales_codes=["cafe24"])
|
||||||
|
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||||
|
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
|
||||||
|
k = {x["key"]: x for x in ctx["kpis"]}
|
||||||
|
assert k["spend"]["value"] == 270000 and k["ratio"]["pct"] == 10.0 # 270,000 ÷ 2,700,000
|
||||||
|
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
|
||||||
|
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
|
||||||
|
assert [c["code"] for c in ctx["upload_channels"]] == ["coupang_wing", "coupang_rocket"]
|
||||||
|
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
|
||||||
|
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
|
||||||
|
assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000
|
||||||
|
# ROAS = 그 쇼핑몰 매출 ÷ 광고비 — 로켓 10/1: 550,000 ÷ 220,000 = 250%, 구글 10/2: 카페24 그날 매출 0 → 0%
|
||||||
|
assert day1["roas"]["coupang_rocket"] == 250 and day1["roas"]["google"] is None
|
||||||
|
day2 = next(r for r in ctx["table"] if r.get("date") == "2026-10-02")
|
||||||
|
assert day2["roas"]["google"] == 0
|
||||||
|
total = ctx["table"][-1]
|
||||||
|
assert total["roas"]["coupang_rocket"] == 300 and total["roas"]["google"] == 5400 # 660,000÷220,000 · 2,700,000÷50,000
|
||||||
|
assert total["roas_total"] == 1000 # 2,700,000 ÷ 270,000 (합계 = sales_codes)
|
||||||
|
m = {r["code"]: r for r in ctx["month"]["rows"]}
|
||||||
|
assert m["coupang_rocket"]["roas"] == 300 and m["naver"]["roas"] is None and ctx["month"]["total"]["roas"] == 1000
|
||||||
|
assert ctx["year"]["rows"][9]["roas"] == 1000 and ctx["year"]["rows"][10]["roas"] is None # 11월 = 앞으로
|
||||||
|
assert ctx["roas_basis"]["google"] == "카페24(자체몰)" and ctx["roas_basis"]["coupang_wing"] == "쿠팡(윙)"
|
||||||
|
assert ads.roas(1, 3) == 33 and ads.roas(1, 200) == 1 and ads.roas(5, 0) is None # 0.5% 반올림 → 1
|
||||||
|
assert ctx["nav"]["quick"][2]["active"] # 이번달
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_dashboard_year_and_missing_table():
|
||||||
|
ctx = ads.build_ad_dashboard(_Store(), kind="year", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||||
|
rows = {r["label"]: r for r in ctx["table"]}
|
||||||
|
assert rows["9월"]["total"]["gross"] == 100000 and rows["10월"]["total"]["gross"] == 270000
|
||||||
|
assert {x["key"]: x for x in ctx["kpis"]}["ratio"]["pct"] is None # 매출 없음
|
||||||
|
miss = ads.build_ad_dashboard(_Store(missing=True), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||||
|
assert miss["migration_needed"] and miss["kpis"][0]["value"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_spend_endpoints(monkeypatch):
|
||||||
|
"""라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400,
|
||||||
|
칸 저장(source=manual)·지우기, 모르는 채널 404, 앞으로의 날 400, 005 미적용 503."""
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self):
|
||||||
|
self.saved, self.missing = [], False
|
||||||
|
|
||||||
|
def set_ad_spend_bulk(self, code, entries, *, source="manual", user=""):
|
||||||
|
if self.missing:
|
||||||
|
raise ads.AdMigrationNeeded()
|
||||||
|
self.saved.extend((code, d, a, source) for d, a in entries)
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
def set_ad_spend(self, code, day, amount, *, source="manual", user=""):
|
||||||
|
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
|
||||||
|
|
||||||
|
store = Store()
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert r.json()["saved"] == 3 and r.json()["total"] == 220000 + 216697 + 220231 and r.json()["to"] == "2026-10-12"
|
||||||
|
assert store.saved[0] == ("coupang_rocket", date(2026, 10, 1), 220000, "upload")
|
||||||
|
store.saved.clear()
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=coupang_wing", files={"file": ("w.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||||
|
assert r.status_code == 200 and r.json()["name"] == "쿠팡(윙)" # 윙도 같은 양식
|
||||||
|
assert store.saved[0] == ("coupang_wing", date(2026, 10, 1), 220000, "upload") and len(store.saved) == 3
|
||||||
|
store.saved.clear()
|
||||||
|
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,9\n"
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", bad.encode("utf-8"))})
|
||||||
|
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=google", files={"file": ("r.csv", b"x")})
|
||||||
|
assert r.status_code == 400 and "양식" in r.json()["detail"]
|
||||||
|
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "33,000"}).json()["amount"] == 33000
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-11", json={"amount": ""}).status_code == 200
|
||||||
|
assert store.saved == [("meta", date(2026, 10, 12), 33000, "manual"), ("meta", date(2026, 10, 11), None, "manual")]
|
||||||
|
assert client.put("/performance/api/ad-spend/cafe24/2026-10-12", json={"amount": 1}).status_code == 404
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 400
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "abc"}).status_code == 400
|
||||||
|
store.missing = True
|
||||||
|
r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": 1})
|
||||||
|
assert r.status_code == 503 and "005" in r.json()["detail"]
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from app.modules.performance import auto_sync as au
|
||||||
|
|
||||||
|
KST = timezone(timedelta(hours=9))
|
||||||
|
H = (9, 19)
|
||||||
|
|
||||||
|
|
||||||
|
def _t(h, m, d=13):
|
||||||
|
return datetime(2026, 10, d, h, m, tzinfo=KST)
|
||||||
|
|
||||||
|
|
||||||
|
def test_slots_every_half_hour_9_to_19():
|
||||||
|
slots = [t for t in (_t(0, 0) + timedelta(minutes=30 * i) for i in range(48)) if au.is_slot(t, H)]
|
||||||
|
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
|
||||||
|
assert not au.is_slot(_t(19, 30), H) and not au.is_slot(_t(8, 30), H) and not au.is_slot(_t(10, 15), H)
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_slot():
|
||||||
|
assert au.next_slot(_t(8, 10), H) == _t(9, 0)
|
||||||
|
assert au.next_slot(_t(9, 0), H) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
|
||||||
|
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), H) == _t(9, 30)
|
||||||
|
assert au.next_slot(_t(18, 45), H) == _t(19, 0)
|
||||||
|
assert au.next_slot(_t(19, 0), H) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
|
||||||
|
assert au.next_slot(_t(23, 59), H) == _t(9, 0, d=14)
|
||||||
|
|
||||||
|
|
||||||
|
def test_env_parsing(monkeypatch):
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_DAYS", raising=False)
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
|
||||||
|
assert au.enabled() and au.sync_days() == 10 and au.hour_window() == (9, 19)
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_DAYS", "200")
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "20-8") # 잘못된 값 → 기본
|
||||||
|
assert not au.enabled() and au.sync_days() == 90 and au.hour_window() == (9, 19)
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20")
|
||||||
|
assert au.hour_window() == (8, 20)
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
||||||
|
from app.modules.performance import jobs
|
||||||
|
from app.modules.performance.sync import SyncService
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_sync_all(self, *, start, end, codes=None, trigger="manual", user="", job=None):
|
||||||
|
calls.append((start, end, trigger, user, job is not None))
|
||||||
|
return [{"code": "naver", "ok": True}, {"code": "toss", "ok": False, "skipped": False}]
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def last_update_at(self):
|
||||||
|
return "2026-10-13T09:00:05+09:00"
|
||||||
|
|
||||||
|
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
|
||||||
|
monkeypatch.setattr(jobs, "running_job", lambda: None)
|
||||||
|
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
|
||||||
|
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
|
||||||
|
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": ""}
|
||||||
|
|
||||||
|
monkeypatch.setattr(jobs, "running_job", lambda: object())
|
||||||
|
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
|
||||||
|
assert len(calls) == 1
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""쿠팡 발주서 — 504(시간 초과)면 조회 구간을 반으로 줄여 다시 부른다."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, ApiError
|
||||||
|
|
||||||
|
|
||||||
|
class Creds:
|
||||||
|
def get(self, key):
|
||||||
|
return {"vendor_id": "A001", "access_key": "ak", "secret_key": "sk"}[key]
|
||||||
|
|
||||||
|
def has(self, key):
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _ctx():
|
||||||
|
return AdapterContext(code="coupang", credentials=Creds())
|
||||||
|
|
||||||
|
|
||||||
|
def _days(params):
|
||||||
|
a = date.fromisoformat(params["createdAtFrom"][:10])
|
||||||
|
b = date.fromisoformat(params["createdAtTo"][:10])
|
||||||
|
return a, b
|
||||||
|
|
||||||
|
|
||||||
|
def test_seller_window_halves_on_timeout_and_remembers(monkeypatch):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||||
|
a, b = _days(params)
|
||||||
|
calls.append((params["status"], a, b))
|
||||||
|
if params["status"] == "FINAL_DELIVERY" and (b - a).days + 1 > 7:
|
||||||
|
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||||
|
return [{"orderId": f"{params['status']}-{a}-{b}"}]
|
||||||
|
|
||||||
|
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||||
|
ad = cp.CoupangAdapter()
|
||||||
|
start, end = date(2026, 1, 1), date(2026, 3, 31) # 주문일 2025-12-31 ~ 3-31 = 91일 → 31일 구간 3개
|
||||||
|
ad._seller_orders(_ctx(), start, end)
|
||||||
|
|
||||||
|
fd = [(a, b) for st, a, b in calls if st == "FINAL_DELIVERY"]
|
||||||
|
ok = [(a, b) for a, b in fd if (b - a).days + 1 <= 7]
|
||||||
|
# 성공한 구간이 빈틈·겹침 없이 전체 주문일을 덮는다
|
||||||
|
d = start - timedelta(days=1)
|
||||||
|
for a, b in ok:
|
||||||
|
assert a == d
|
||||||
|
d = b + timedelta(days=1)
|
||||||
|
assert d == end + timedelta(days=1)
|
||||||
|
# 31 → 15 → 7 로 줄인 뒤엔 다음 31일 구간도 처음부터 7일로(실패는 첫 구간의 두 번뿐)
|
||||||
|
assert len(fd) - len(ok) == 2
|
||||||
|
# 다른 상태는 31일 그대로
|
||||||
|
assert sum(1 for st, a, b in calls if st == "ACCEPT") == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_day_timeout_retries_then_fails(monkeypatch):
|
||||||
|
sleeps = []
|
||||||
|
monkeypatch.setattr(cp.time, "sleep", lambda s: sleeps.append(s))
|
||||||
|
|
||||||
|
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||||
|
if params["status"] == "FINAL_DELIVERY":
|
||||||
|
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||||
|
return []
|
||||||
|
|
||||||
|
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||||
|
with pytest.raises(ApiError) as ei:
|
||||||
|
cp.CoupangAdapter()._seller_orders(_ctx(), date(2026, 1, 5), date(2026, 1, 5))
|
||||||
|
assert "하루도 시간 초과" in ei.value.message and "FINAL_DELIVERY" in ei.value.message
|
||||||
|
assert sleeps == [3.0, 6.0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_rg_window_halves_on_timeout(monkeypatch):
|
||||||
|
got = []
|
||||||
|
|
||||||
|
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||||
|
a = date(int(params["paidDateFrom"][:4]), int(params["paidDateFrom"][4:6]), int(params["paidDateFrom"][6:]))
|
||||||
|
b = date(int(params["paidDateTo"][:4]), int(params["paidDateTo"][4:6]), int(params["paidDateTo"][6:]))
|
||||||
|
if (b - a).days + 1 > 10:
|
||||||
|
raise cp.GatewayTimeout("쿠팡 로켓그로스 주문 API 오류(504)")
|
||||||
|
got.append((a, b))
|
||||||
|
return [{"orderId": str(a)}]
|
||||||
|
|
||||||
|
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||||
|
cp.CoupangAdapter()._rg_orders(_ctx(), date(2026, 1, 1), date(2026, 1, 30))
|
||||||
|
assert got[0][0] == date(2026, 1, 1) and got[-1][1] == date(2026, 1, 30)
|
||||||
|
assert all((b - a).days + 1 <= 10 for a, b in got)
|
||||||
|
assert all(got[i + 1][0] == got[i][1] + timedelta(days=1) for i in range(len(got) - 1))
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
"""수동 입력 엑셀 업로드 — 머리글 매칭·값 있는 칸만·오류 시 전부 거절."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
from datetime import date, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance import manual_upload as mu
|
||||||
|
|
||||||
|
TODAY = date(2026, 10, 13)
|
||||||
|
MARKETS = [
|
||||||
|
{"code": "naver", "name": "네이버", "manual_input": False},
|
||||||
|
{"code": "coupang_rocket", "name": "쿠팡(로켓)", "manual_input": True},
|
||||||
|
{"code": "ohouse", "name": "오늘의집", "manual_input": True},
|
||||||
|
{"code": "toss", "name": "토스쇼핑", "manual_input": True},
|
||||||
|
{"code": "atomy", "name": "애터미아자몰", "manual_input": True},
|
||||||
|
]
|
||||||
|
EXTRA = {"toss": ("토스쇼핑", "토스")}
|
||||||
|
|
||||||
|
|
||||||
|
def _xlsx(rows):
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
for r in rows:
|
||||||
|
ws.append(list(r))
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(rows):
|
||||||
|
return mu.parse_workbook(_xlsx(rows), markets=MARKETS, today=TODAY, extra_names=EXTRA)
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_filled_cells_of_manual_shops():
|
||||||
|
res = _parse([
|
||||||
|
("날짜", "쿠팡(로켓)", " 오늘의 집 ", "네이버", "모르는몰", "토스", "애터미아자몰"),
|
||||||
|
(datetime(2026, 10, 12), 1_000, None, 999, 5, "12,300원", ""),
|
||||||
|
("2026.10.13(화)", None, 0, None, None, None, 4500.4),
|
||||||
|
(None, None, None, None, None, None, None), # 빈 줄
|
||||||
|
])
|
||||||
|
assert not res.errors
|
||||||
|
assert res.columns == ["coupang_rocket", "ohouse", "toss", "atomy"]
|
||||||
|
assert sorted(res.entries) == sorted([
|
||||||
|
("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 12), 12300),
|
||||||
|
("ohouse", date(2026, 10, 13), 0), ("atomy", date(2026, 10, 13), 4500)])
|
||||||
|
assert res.ignored == ["네이버(수동 입력 꺼짐)", "모르는몰(알 수 없는 쇼핑몰)"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("raw, expect", [
|
||||||
|
("2026-10-01", date(2026, 10, 1)), ("2026/10/1", date(2026, 10, 1)), ("20261001", date(2026, 10, 1)),
|
||||||
|
(20261001, date(2026, 10, 1)), (46296, date(2026, 10, 1)), ("2026년 10월 1일", date(2026, 10, 1)), (None, None),
|
||||||
|
])
|
||||||
|
def test_parse_date(raw, expect):
|
||||||
|
assert mu.parse_date(raw) == expect
|
||||||
|
|
||||||
|
|
||||||
|
def test_errors_reject_everything_with_cell_refs():
|
||||||
|
res = _parse([
|
||||||
|
("날짜", "쿠팡(로켓)", "오늘의집"),
|
||||||
|
("2026-10-10", "abc", 100),
|
||||||
|
("엉터리", 1, None),
|
||||||
|
("2026-10-14", 1, None), # 앞으로의 날짜
|
||||||
|
(None, 5, None), # 날짜 없음
|
||||||
|
("2026-10-11", 7, None),
|
||||||
|
("2026-10-11", 8, None), # 같은 날 두 번
|
||||||
|
])
|
||||||
|
joined = "\n".join(res.errors)
|
||||||
|
assert "B2" in joined and "A3" in joined and "A4" in joined and "5행" in joined and "B7" in joined
|
||||||
|
assert len(res.errors) == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_header_problems():
|
||||||
|
with pytest.raises(mu.UploadError):
|
||||||
|
_parse([("날짜", "네이버", "모르는몰"), ("2026-10-10", 1, 2)]) # 반영할 열 없음
|
||||||
|
with pytest.raises(mu.UploadError):
|
||||||
|
mu.parse_workbook(b"not an xlsx", markets=MARKETS, today=TODAY)
|
||||||
|
res = _parse([("날짜", "쿠팡(로켓)", "coupang_rocket"), ("2026-10-10", 1, 2)])
|
||||||
|
assert any("두 번" in e for e in res.errors)
|
||||||
|
|
||||||
|
|
||||||
|
def test_sample_file_headers_match_marketplaces():
|
||||||
|
"""모듈 폴더 샘플 파일 머리글 = 수동 입력 쇼핑몰 이름(시드 기준) — 업로드하면 전부 반영 대상이어야 한다."""
|
||||||
|
sample = Path(mu.__file__).resolve().parent / "upload_sample.xlsx"
|
||||||
|
seed = [{"code": c, "name": n, "manual_input": True} for c, n in (
|
||||||
|
("coupang_rocket", "쿠팡(로켓)"), ("ohouse", "오늘의집"), ("gmarket", "G마켓"), ("kakao", "카카오"),
|
||||||
|
("gsshop", "GS샵"), ("lotteon", "롯데ON"), ("atomy", "애터미아자몰"))]
|
||||||
|
wb = openpyxl.load_workbook(sample)
|
||||||
|
ws = wb.active
|
||||||
|
ws.append([date(2026, 10, 1)] + [1] * 7)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
res = mu.parse_workbook(buf.getvalue(), markets=seed, today=TODAY)
|
||||||
|
assert not res.errors and not res.ignored and len(res.entries) == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_endpoint_saves_or_rejects(monkeypatch):
|
||||||
|
"""라우터: 정상 파일은 한 번에 저장, 잘못된 칸이 있으면 400 + 칸 목록, 아무것도 저장 안 함. 샘플 받기."""
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router") # 패키지 속성 router 는 APIRouter
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
saved: list = []
|
||||||
|
|
||||||
|
def list_marketplaces(self):
|
||||||
|
return [{**m, "enabled": True} for m in MARKETS]
|
||||||
|
|
||||||
|
def set_manual_sales_bulk(self, entries, *, user=""):
|
||||||
|
self.saved.extend(entries)
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
store = Store()
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
ok = _xlsx([("날짜", "쿠팡(로켓)", "토스"), ("2026-10-12", 1000, None), ("2026-10-13", None, 2000)])
|
||||||
|
r = client.post("/performance/api/manual-sales/upload", files={"file": ("a.xlsx", ok)})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
body = r.json()
|
||||||
|
assert body["saved"] == 2 and body["from"] == "2026-10-12" and body["to"] == "2026-10-13"
|
||||||
|
assert [s["code"] for s in body["by_shop"]] == ["coupang_rocket", "toss"]
|
||||||
|
assert sorted(store.saved) == [("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 13), 2000)]
|
||||||
|
|
||||||
|
store.saved.clear()
|
||||||
|
bad = _xlsx([("날짜", "쿠팡(로켓)"), ("2026-10-12", 1000), ("2026-10-13", "x")])
|
||||||
|
r = client.post("/performance/api/manual-sales/upload", files={"file": ("b.xlsx", bad)})
|
||||||
|
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
|
||||||
|
|
||||||
|
r = client.get("/performance/api/manual-sales/sample.xlsx")
|
||||||
|
assert r.status_code == 200 and r.content[:2] == b"PK"
|
||||||
@@ -379,6 +379,279 @@ def test_sync_isolation_redaction_and_dedupe():
|
|||||||
assert r3["skipped"]
|
assert r3["skipped"]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _toss_item(order_id, op_id, ordered_at, price, *, status="PAID", qty=1, dc=0, ship=0, group=None, name="밀폐용기"):
|
||||||
|
"""토스쇼핑 주문 내역 조회 results[] 한 줄(주문상품) — 개인정보 항목 포함(저장 안 되는지 확인용)."""
|
||||||
|
return {"orderId": order_id, "orderProductId": op_id, "orderedAt": ordered_at, "orderProductStatus": status,
|
||||||
|
"productName": name, "optionName": "3개입", "quantity": qty, "price": price, "originPrice": price,
|
||||||
|
"totalDiscountPrice": dc, "tossShoppingDiscount": dc, "tossPayDiscount": 0, "tossPayPoint": 0,
|
||||||
|
"deliveryFee": ship, "deliveryFeeGroupId": group,
|
||||||
|
"ordererName": "홍길동", "ordererPhone": "010-1234-5678", "receiverName": "홍길동",
|
||||||
|
"receiverPhone": "010-1234-5678", "address": "서울시 어딘가", "detailAddress": "101호", "zipCode": "01234",
|
||||||
|
"shippingNote": "문 앞에 두세요 010-9999-8888"}
|
||||||
|
|
||||||
|
|
||||||
|
class _TossCreds(dict):
|
||||||
|
def get(self, k, default=""):
|
||||||
|
return dict.get(self, k, default)
|
||||||
|
|
||||||
|
def has(self, k):
|
||||||
|
return bool(dict.get(self, k))
|
||||||
|
|
||||||
|
def set(self, k, v):
|
||||||
|
self[k] = v
|
||||||
|
|
||||||
|
|
||||||
|
def test_toss_token_and_connection():
|
||||||
|
"""토스쇼핑: Access Key·Secret Key → OAuth2 토큰(form, scope 고정) → Bearer 로 주문 내역 조회.
|
||||||
|
HTTP 200 + resultType FAIL 도 오류, 401 이면 토큰 한 번 새로 받기. 키·토큰은 오류 문구에 없음."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, AdapterError
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="ACCESS-KEY-1", api_secret="SECRET-KEY-1"))
|
||||||
|
seen = {"posts": [], "gets": []}
|
||||||
|
|
||||||
|
def post(url, data=None, timeout=None, headers=None):
|
||||||
|
seen["posts"].append((url, dict(data)))
|
||||||
|
return httpx.Response(200, json={"access_token": f"TOKEN-{len(seen['posts'])}", "expires_in": 31535999,
|
||||||
|
"token_type": "Bearer", "scope": "toss-shopping-fep:write"})
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
seen["gets"].append((url, dict(params), headers["Authorization"]))
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {
|
||||||
|
"results": [_toss_item(1, 11, "2026-09-30T10:00:00", 12000)], "nextCursor": "c2"}})
|
||||||
|
|
||||||
|
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
|
||||||
|
try:
|
||||||
|
msg = ts.TossAdapter().test_connection(ctx)
|
||||||
|
assert "연결 정상" in msg and "1건 이상" in msg
|
||||||
|
url, form = seen["posts"][0]
|
||||||
|
assert url == "https://oauth2.cert.toss.im/token"
|
||||||
|
assert form == {"grant_type": "client_credentials", "client_id": "ACCESS-KEY-1",
|
||||||
|
"client_secret": "SECRET-KEY-1", "scope": "toss-shopping-fep:write"}
|
||||||
|
gurl, params, auth = seen["gets"][0]
|
||||||
|
assert gurl == "https://shopping-fep.toss.im/api/v3/shopping-fep/orders/v2" and auth == "Bearer TOKEN-1"
|
||||||
|
assert params["startDate"] == params["endDate"] and params["limit"] == 1
|
||||||
|
assert ctx.credentials["access_token"] == "TOKEN-1" and int(ctx.credentials["access_token_expires_at"]) > 0
|
||||||
|
# 저장된 토큰은 다시 쓴다(매번 발급하지 않음) — 401 이면 한 번만 새로 받는다
|
||||||
|
n_posts = len(seen["posts"])
|
||||||
|
statuses = iter([401, 200])
|
||||||
|
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||||
|
next(statuses), json={"resultType": "SUCCESS", "success": {"results": [], "nextCursor": None}})
|
||||||
|
assert ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1)) == []
|
||||||
|
assert len(seen["posts"]) == n_posts + 1 and ctx.credentials["access_token"] == f"TOKEN-{n_posts + 1}"
|
||||||
|
# HTTP 200 + resultType FAIL → API 오류
|
||||||
|
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||||
|
200, json={"resultType": "FAIL", "error": {"errorCode": "INVALID_DATE_RANGE", "reason": "조회 기간 초과"}})
|
||||||
|
try:
|
||||||
|
ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1))
|
||||||
|
except AdapterError as exc:
|
||||||
|
assert exc.status == "api_error" and "INVALID_DATE_RANGE" in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("API 오류여야 합니다")
|
||||||
|
# 토큰 발급 거부 → 인증 실패(키는 문구에 없음)
|
||||||
|
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(
|
||||||
|
401, json={"error": "invalid_client", "error_description": "client authentication failed"})
|
||||||
|
try:
|
||||||
|
ts.TossAdapter().test_connection(ctx)
|
||||||
|
except AuthFailed as exc:
|
||||||
|
assert "invalid_client" in exc.message and "SECRET-KEY-1" not in exc.message
|
||||||
|
assert "ACCESS-KEY-1" not in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("인증 실패여야 합니다")
|
||||||
|
# 주문 조회 403(IP 미등록 등) → 인증 실패 + IP 안내, 토큰은 문구에 없음
|
||||||
|
httpx.post = post
|
||||||
|
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||||
|
403, json={"resultType": "FAIL", "error": {"errorCode": "FORBIDDEN", "reason": "허용되지 않은 IP"}})
|
||||||
|
try:
|
||||||
|
ts.TossAdapter().test_connection(ctx)
|
||||||
|
except AuthFailed as exc:
|
||||||
|
assert "허용되지 않은 IP" in exc.message and "TOKEN-" not in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("권한 거부여야 합니다")
|
||||||
|
finally:
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
|
||||||
|
|
||||||
|
def _toss_step(step, order_id, op_id, ts, price, *, qty=1):
|
||||||
|
"""정산 건별 목록 items[] 한 줄 — op_id None = 배송비 줄."""
|
||||||
|
return {"orderId": order_id, "orderProductId": op_id, "transactionTs": ts, "originTransactionTs": "2026-08-31T16:00:00Z",
|
||||||
|
"stepType": step, "orderProductPrice": price, "stockPrice": price // max(1, qty), "quantity": qty,
|
||||||
|
"displayProductName": "밀폐용기", "orderProductStatus": "CANCELED_PAYMENT" if step == "REFUND" else "CONFIRMED_ORDER"}
|
||||||
|
|
||||||
|
|
||||||
|
def _toss_claim(cid, kind, status, order_id, op_id, price, *, refunded=None, created="2026-08-01T10:00:00", qty=1):
|
||||||
|
"""클레임 목록 items[] 한 줄 — refunded = 환불 완료 일시(없으면 미환불). 개인정보·자유 입력 항목 포함."""
|
||||||
|
return {"id": cid, "type": kind, "status": status, "isRefunded": bool(refunded), "refundedDt": refunded,
|
||||||
|
"requestReason": "단순 변심 010-5555-6666", "returnAddress": "서울시 반품동",
|
||||||
|
"order": {"id": order_id, "orderProductId": op_id, "price": price, "createdDt": created,
|
||||||
|
"ordererName": "홍길동", "ordererPhoneNumber": "010-1234-5678"},
|
||||||
|
"product": {"id": 3, "name": "밀폐용기", "quantity": qty}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_toss_collect_sales():
|
||||||
|
"""토스쇼핑 매출 = 파트너스 "순 거래액" = 매출 − 환불(9/6 화면: 29,600 − 11,900 = 17,700, 9/5 주문을 9/6 취소).
|
||||||
|
매출 = 주문 단위, 주문일(한국 날짜), 주문상품 price 합(할인 전·배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외).
|
||||||
|
환불 = 클레임 환불 완료(취소·반품, refundedDt) + 클레임 없는 결제취소(canceledAt), 주문상품마다 한 번, 금액 = 주문상품 price.
|
||||||
|
기간 앞 90일 주문까지 불러 다른 날 주문의 환불도 잡는다. 31일 구간 + 커서. 구매자 정보는 저장 안 함."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
|
||||||
|
def item(*a, canceled=None, **kw):
|
||||||
|
it = _toss_item(*a, **kw)
|
||||||
|
if canceled:
|
||||||
|
it["canceledAt"] = canceled
|
||||||
|
return it
|
||||||
|
|
||||||
|
pages = {
|
||||||
|
("2026-08-01", None): ([item(1, 11, "2026-08-31T23:30:00+09:00", 20000, qty=2, dc=1000, ship=3000, group=7),
|
||||||
|
item(1, 12, "2026-08-31T23:30:00+09:00", 5000, ship=3000, group=7, name="뚜껑")], "p2"),
|
||||||
|
("2026-08-01", "p2"): ([item(2, 21, "2026-08-31T16:00:00Z", 9900, status="CANCELED_PAYMENT", # 9/1 01:00 KST
|
||||||
|
canceled="2026-08-31T17:30:00Z"), # 9/1 02:30 — 클레임 없음
|
||||||
|
item(3, 31, "2026-08-31T09:00:00", 4000, status="BEFORE_PAYMENT")], None),
|
||||||
|
("2026-09-01", None): ([item(4, 41, "2026-09-01T10:00:00", 15000, status="COMPLETED_RETURN"),
|
||||||
|
item(6, 61, "2026-09-02T10:00:00", 5000, status="CANCELED_PAYMENT",
|
||||||
|
canceled="2026-09-02T11:00:00")], None), # 클레임 환불은 9/5(기간 밖) → 여기선 안 뺌
|
||||||
|
# 기간 앞 90일(5/3~7/31) 조회의 마지막 구간 — 7/15 주문을 8/10 에 취소(클레임 있음)
|
||||||
|
("2026-07-04", None): ([item(5, 51, "2026-07-15T10:00:00", 7000, qty=2, status="CANCELED_PAYMENT",
|
||||||
|
canceled="2026-08-10T09:00:00")], None),
|
||||||
|
}
|
||||||
|
claims = [
|
||||||
|
_toss_claim(1, "RETURN", "COMPLETED", 4, 41, 15000, refunded="2026-09-02T09:00:00"),
|
||||||
|
_toss_claim(2, "CANCEL", "COMPLETED", 5, 51, 3500, refunded="2026-08-10T09:05:00", qty=2), # 금액은 주문 price 7,000
|
||||||
|
_toss_claim(3, "CANCEL", "COMPLETED", 6, 61, 5000, refunded="2026-09-05T10:00:00"), # 기간 밖
|
||||||
|
_toss_claim(4, "CANCEL", "COMPLETED", 8, 81, 4400, refunded="2026-08-15T10:00:00"), # 90일보다 오래된 주문
|
||||||
|
_toss_claim(5, "EXCHANGE", "COMPLETED", 1, 11, 20000, refunded="2026-09-01T10:00:00"), # 교환 → 제외
|
||||||
|
_toss_claim(6, "CANCEL", "REQUESTED", 1, 12, 5000), # 미환불 → 제외
|
||||||
|
]
|
||||||
|
calls, ccalls = [], []
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
if url.endswith("/claims"):
|
||||||
|
ccalls.append(params.get("nextToken"))
|
||||||
|
page = claims[:3] if not params.get("nextToken") else claims[3:]
|
||||||
|
tok = None if params.get("nextToken") else "c2"
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": page, "nextToken": tok,
|
||||||
|
"hasNext": tok is not None}})
|
||||||
|
assert not url.endswith("/settlement-steps"), "수집은 정산 건별을 부르지 않는다"
|
||||||
|
calls.append((params["startDate"], params["endDate"], params.get("nextCursor")))
|
||||||
|
rows, cur = pages.get((params["startDate"], params.get("nextCursor")), ([], None))
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": cur}})
|
||||||
|
|
||||||
|
def post(url, data=None, timeout=None, headers=None):
|
||||||
|
return httpx.Response(200, json={"access_token": "TOKEN-T", "expires_in": 31535999})
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
|
||||||
|
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
|
||||||
|
try:
|
||||||
|
r = SyncService(st, creds).sync_marketplace("toss", date(2026, 8, 1), date(2026, 9, 2))
|
||||||
|
finally:
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
assert r["ok"], r
|
||||||
|
assert [c for c in calls if c[0] >= "2026-08-01"] == [
|
||||||
|
("2026-08-01", "2026-08-31", None), ("2026-08-01", "2026-08-31", "p2"), ("2026-09-01", "2026-09-02", None)]
|
||||||
|
assert [(a, b) for a, b, _ in calls if a < "2026-08-01"] == [
|
||||||
|
("2026-05-03", "2026-06-02"), ("2026-06-03", "2026-07-03"), ("2026-07-04", "2026-07-31")] # 앞 90일
|
||||||
|
assert ccalls == [None, "c2"] # 클레임 목록 끝까지
|
||||||
|
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "toss"}
|
||||||
|
refunds = {k: v for k, v in ev_.items() if k.startswith("toss:R")}
|
||||||
|
assert set(ev_) - set(refunds) == {"toss:1", "toss:2", "toss:4", "toss:6"} # 결제 전(3)만 제외
|
||||||
|
assert {k: (v["amount"], v["sales_date"], v["event_type"]) for k, v in refunds.items()} == {
|
||||||
|
"toss:R21": (-9900, date(2026, 9, 1), "CANCEL"), # 클레임 없는 결제취소 → canceledAt
|
||||||
|
"toss:R41": (-15000, date(2026, 9, 2), "RETURN"), # 반품 → 클레임 refundedDt
|
||||||
|
"toss:R51": (-7000, date(2026, 8, 10), "CANCEL"), # 앞 90일 주문 — 금액은 주문 price(판매가 × 수량)
|
||||||
|
"toss:R81": (-4400, date(2026, 8, 15), "CANCEL"), # 주문 내역에 없는 오래된 주문 → 클레임 order.price
|
||||||
|
} # R61: 클레임 환불(9/5)이 기간 밖 → canceledAt(9/2)으로 넣지 않음, 교환·미환불 클레임 제외
|
||||||
|
# 환불 사건에도 원래 주문일 — 대시보드 금액 클릭 상세의 "주문일" 열(9/6 화면: 9/5 주문을 9/6 취소)
|
||||||
|
assert {k: v["order_date"] for k, v in refunds.items()} == {
|
||||||
|
"toss:R21": date(2026, 9, 1), "toss:R41": date(2026, 9, 1), "toss:R51": date(2026, 7, 15),
|
||||||
|
"toss:R81": date(2026, 8, 1)}
|
||||||
|
net = {}
|
||||||
|
for v in ev_.values():
|
||||||
|
net[v["sales_date"]] = net.get(v["sales_date"], 0) + v["amount"]
|
||||||
|
assert net == {date(2026, 8, 10): -7000, date(2026, 8, 15): -4400, date(2026, 8, 31): 25000,
|
||||||
|
date(2026, 9, 1): 9900 + 15000 - 9900, date(2026, 9, 2): 5000 - 15000}
|
||||||
|
assert ev_["toss:1"]["amount"] == 25000 and ev_["toss:1"]["discount_amount"] == 1000 # 할인 전·배송비 제외
|
||||||
|
assert ev_["toss:1"]["quantity"] == 3 and ev_["toss:1"]["product_name"] == "밀폐용기 외 1건"
|
||||||
|
assert ev_["toss:1"]["sales_date"] == date(2026, 8, 31)
|
||||||
|
assert ev_["toss:2"]["amount"] == 9900 and ev_["toss:2"]["sales_date"] == date(2026, 9, 1) # UTC → 한국 날짜
|
||||||
|
assert ev_["toss:4"]["amount"] == 15000 and ev_["toss:4"]["order_status"] == "반품완료"
|
||||||
|
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
|
||||||
|
|
||||||
|
|
||||||
|
def test_toss_reconcile_hides_personal():
|
||||||
|
import time as _t
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T",
|
||||||
|
access_token_expires_at=str(int(_t.time()) + 99999)))
|
||||||
|
rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1),
|
||||||
|
_toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)]
|
||||||
|
steps = [_toss_step("REFUND", 2, 21, "2026-09-10T11:00:00", -9900), _toss_step("REFUND", 2, None, "2026-09-10T11:00:00", -3000)]
|
||||||
|
|
||||||
|
# 다른 날(8/20) 주문을 9/10 에 취소 — 기간 앞(90일) 주문 조회에서만 보인다
|
||||||
|
old = {**_toss_item(7, 71, "2026-08-20T10:00:00", 11900, status="CANCELED_PAYMENT"), "canceledAt": "2026-09-10T09:00:00"}
|
||||||
|
claims = [{"id": 1, "type": "RETURN", "status": "COMPLETED", "isRefunded": True, "refundedDt": "2026-09-10T12:00:00",
|
||||||
|
"requestReason": "단순 변심 010-5555-6666", "returnAddress": "서울시 반품동",
|
||||||
|
"order": {"id": 8, "orderProductId": 81, "price": 5000, "createdDt": "2026-08-25T10:00:00",
|
||||||
|
"ordererName": "홍길동", "ordererPhoneNumber": "010-1234-5678"},
|
||||||
|
"product": {"id": 3, "name": "밀폐용기", "quantity": 1}},
|
||||||
|
{"id": 2, "type": "CANCEL", "status": "REQUESTED", "isRefunded": False, "order": {"id": 9, "price": 777}}]
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
if url.endswith("/settlement-steps"):
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": steps, "nextToken": None}})
|
||||||
|
if url.endswith("/claims"):
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": claims, "nextToken": None,
|
||||||
|
"hasNext": False}})
|
||||||
|
found = rows if params["startDate"] >= "2026-09-09" else [old] if params["startDate"] <= "2026-08-20" <= params["endDate"] else []
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}})
|
||||||
|
|
||||||
|
orig = (httpx.get, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.get, ts.CALL_INTERVAL_SEC = get, 0
|
||||||
|
try:
|
||||||
|
rec = ts.TossAdapter().reconcile(ctx, date(2026, 9, 9), to=date(2026, 9, 10))
|
||||||
|
finally:
|
||||||
|
httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
allp = rec["probes"][0]
|
||||||
|
assert allp["ok"] and allp["count"] == 2
|
||||||
|
f = {x["name"]: x for x in allp["fields"]}
|
||||||
|
assert f["price"]["sum"] == 29900
|
||||||
|
for k in ("ordererName", "ordererPhone", "address", "zipCode", "shippingNote"):
|
||||||
|
assert f[k]["personal"] and f[k]["sample"] == "", k
|
||||||
|
assert not f["productName"]["personal"] and f["productName"]["sample"] == "밀폐용기"
|
||||||
|
assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec) and "010-9999-8888" not in repr(rec)
|
||||||
|
# 날짜별: 매출(주문일) · 환불(환불일, 적용 규칙) · 순 거래액 — 9/10 환불 = 반품 클레임 5,000 + 클레임 없는 결제취소 11,900
|
||||||
|
assert rec["days"] == [{"date": "2026-09-09", "orders": 2, "amount": 29900, "claimed": 0, "ship": 29900},
|
||||||
|
{"date": "2026-09-10", "orders": 0, "amount": 0, "claimed": 16900, "ship": -16900}]
|
||||||
|
assert rec["day_cols"]["ship"].startswith("순 거래액")
|
||||||
|
labels = [p["label"] for p in rec["probes"]]
|
||||||
|
assert any("결제 뒤 취소·반품(매출 포함)" in x for x in labels) and any("정산 건별" in x for x in labels)
|
||||||
|
# 환불 출처별 — 적용 규칙 · 클레임 · 취소 시각 · 정산(참고), 날짜별 합계 + 건별
|
||||||
|
cand = {c["key"]: c for c in rec["refund_candidates"]}
|
||||||
|
assert rec["refund_candidates"][0]["key"] == "rule" and cand["rule"]["days"] == {"2026-09-10": 16900}
|
||||||
|
assert sorted(x["orderId"] for x in cand["rule"]["rows"]) == ["7", "8"]
|
||||||
|
assert cand["settlement"]["days"] == {"2026-09-10": 9900}
|
||||||
|
assert cand["canceled"]["days"] == {"2026-09-10": 11900} and cand["canceled"]["rows"][0]["orderId"] == "7"
|
||||||
|
assert cand["canceled"]["rows"][0]["orderDate"] == "2026-08-20" # 주문일은 따로 열로(메모 X)
|
||||||
|
assert {x["orderId"]: x["orderDate"] for x in cand["rule"]["rows"]} == {"7": "2026-08-20", "8": "2026-08-25"}
|
||||||
|
assert cand["claims"]["days"] == {"2026-09-10": 5000} and len(cand["claims"]["rows"]) == 1 # 환불 안 된 클레임 제외
|
||||||
|
cf = {x["name"]: x for x in next(p for p in rec["probes"] if p["key"] == "claims")["fields"]}
|
||||||
|
assert cf["requestReason"]["personal"] and cf["returnAddress"]["personal"] and cf["order.ordererPhoneNumber"]["personal"]
|
||||||
|
assert "010-5555-6666" not in repr(rec) and "반품동" not in repr(rec)
|
||||||
|
|
||||||
|
|
||||||
def test_not_implemented_and_mock():
|
def test_not_implemented_and_mock():
|
||||||
st = FakeStore()
|
st = FakeStore()
|
||||||
creds = CredentialService(st, lambda: ring())
|
creds = CredentialService(st, lambda: ring())
|
||||||
@@ -791,15 +1064,18 @@ def test_coupang_hmac_and_connection_errors():
|
|||||||
seen = {}
|
seen = {}
|
||||||
|
|
||||||
def fake_get(url, headers=None, timeout=None, status=200, body=None):
|
def fake_get(url, headers=None, timeout=None, status=200, body=None):
|
||||||
|
seen.setdefault("urls", []).append(url)
|
||||||
seen["url"], seen["auth"] = url, headers["Authorization"]
|
seen["url"], seen["auth"] = url, headers["Authorization"]
|
||||||
return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
|
return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
|
||||||
|
|
||||||
orig = httpx.get
|
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||||
try:
|
try:
|
||||||
httpx.get = fake_get
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = fake_get, 0, 0
|
||||||
msg = cp.CoupangAdapter().test_connection(ctx)
|
msg = cp.CoupangAdapter().test_connection(ctx)
|
||||||
assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"]
|
first, rg = seen["urls"]
|
||||||
assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"]
|
assert "연결 정상" in msg and "로켓그로스" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in first
|
||||||
|
assert "%2B09:00" in first and "SK-SECRET" not in seen["auth"]
|
||||||
|
assert "/rg_open_api/apis/api/v1/vendors/A00012345/rg/orders?paidDateFrom=" in rg
|
||||||
httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
|
httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
|
||||||
try:
|
try:
|
||||||
cp.CoupangAdapter().test_connection(ctx)
|
cp.CoupangAdapter().test_connection(ctx)
|
||||||
@@ -808,7 +1084,158 @@ def test_coupang_hmac_and_connection_errors():
|
|||||||
else:
|
else:
|
||||||
raise AssertionError("403 이면 인증 실패여야 합니다")
|
raise AssertionError("403 이면 인증 실패여야 합니다")
|
||||||
finally:
|
finally:
|
||||||
httpx.get = orig
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||||
|
|
||||||
|
|
||||||
|
def _cp_sheet(order_id, box, paid, items, *, status="INSTRUCT", ship=3000):
|
||||||
|
def money(n):
|
||||||
|
return {"currencyCode": "KRW", "units": n, "nanos": 0}
|
||||||
|
|
||||||
|
return {"shipmentBoxId": box, "orderId": order_id, "orderedAt": paid, "paidAt": paid, "status": status,
|
||||||
|
"orderer": {"name": "홍길동", "safeNumber": "0502-1111-2222"},
|
||||||
|
"receiver": {"name": "홍길동", "addr1": "서울 비밀구 1", "receiverNumber": "+82-10-1234-5678"},
|
||||||
|
"parcelPrintMessage": "문 앞", "shippingPrice": money(ship), "remotePrice": money(0),
|
||||||
|
"orderItems": [{"sequenceNo": f"{i + 1:03d}", "vendorItemId": 100 + i, "vendorItemName": n,
|
||||||
|
"sellerProductName": n, "sellerProductItemName": "1개", "shippingCount": q,
|
||||||
|
"salesPrice": money(p), "orderPrice": money(p * q), "discountPrice": money(dc),
|
||||||
|
"cancelCount": cc, "holdCountForCancel": 0, "canceled": cc >= q,
|
||||||
|
"etcInfoValues": ["개인 메모"]}
|
||||||
|
for i, (n, p, q, dc, cc) in enumerate(items)]}
|
||||||
|
|
||||||
|
|
||||||
|
def _cp_rg(order_id, paid_ms, items):
|
||||||
|
return {"vendorId": "A00012345", "orderId": order_id, "paidAt": paid_ms,
|
||||||
|
"orderItems": [{"vendorItemId": 900 + i, "productName": n, "salesQuantity": q, "unitSalesPrice": str(p),
|
||||||
|
"currency": "KRW"} for i, (n, p, q) in enumerate(items)]}
|
||||||
|
|
||||||
|
|
||||||
|
def _cp_server(sheets_by_status, rg_pages):
|
||||||
|
"""가짜 쿠팡 — 발주서는 상태별 목록(2쪽까지), 로켓그로스는 nextToken 쪽 넘김. 호출 기록을 남긴다."""
|
||||||
|
import httpx
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def get(url, headers=None, timeout=None):
|
||||||
|
u = urlparse(url)
|
||||||
|
q = {k: v[0] for k, v in parse_qs(u.query).items()}
|
||||||
|
calls.append((u.path, q))
|
||||||
|
if u.path.endswith("/rg/orders"):
|
||||||
|
i = int(q.get("nextToken") or 0)
|
||||||
|
nxt = str(i + 1) if i + 1 < len(rg_pages) else ""
|
||||||
|
return httpx.Response(200, json={"code": 200, "message": "SUCCESS", "data": rg_pages[i], "nextToken": nxt})
|
||||||
|
rows = sheets_by_status.get(q["status"], [])
|
||||||
|
if q.get("nextToken") == "p2":
|
||||||
|
return httpx.Response(200, json={"code": 200, "data": rows[1:], "nextToken": ""})
|
||||||
|
return httpx.Response(200, json={"code": 200, "data": rows[:1], "nextToken": "p2" if len(rows) > 1 else ""})
|
||||||
|
|
||||||
|
return get, calls
|
||||||
|
|
||||||
|
|
||||||
|
KST_1012_0030_MS = 1791732600000 # 2026-10-12 00:30 KST = 10-11 15:30 UTC
|
||||||
|
|
||||||
|
|
||||||
|
def test_coupang_collect_sales():
|
||||||
|
"""쿠팡 매출 = 판매자배송 발주서 orderPrice(쿠폰 할인 전) + 로켓그로스 단가 × 수량, 결제일(한국 시간) 기준.
|
||||||
|
상태 6개 모두 조회·쪽 넘김, 결제일이 기간 밖이면 뺌, 결제 뒤 취소된 줄도 결제일 매출, 같은 발주서 두 번 와도 한 번.
|
||||||
|
구매자·수령자 정보는 저장하지 않는다."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
|
||||||
|
sheets = {
|
||||||
|
"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0), ("뚜껑", 3000, 1, 0, 0)]),
|
||||||
|
_cp_sheet(2, 21, "2026-10-12T23:59:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])], # 결제 뒤 취소
|
||||||
|
"FINAL_DELIVERY": [_cp_sheet(3, 31, "2026-10-11T23:50:00+09:00", [("밀폐용기", 12000, 1, 0, 0)]), # 전날 결제 — 뺌
|
||||||
|
_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)])], # 같은 발주서 다시
|
||||||
|
}
|
||||||
|
rg_pages = [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])], [_cp_rg(71, KST_1012_0030_MS + 3600_000, [("컵", 5000, 1)])]]
|
||||||
|
get, calls = _cp_server(sheets, rg_pages)
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "coupang"),
|
||||||
|
{"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-SECRET"})
|
||||||
|
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||||
|
try:
|
||||||
|
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||||
|
finally:
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||||
|
assert r["ok"], r
|
||||||
|
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "coupang"}
|
||||||
|
assert set(ev_) == {"coupang:1", "coupang:2", "coupang:rg:70", "coupang:rg:71"}, set(ev_)
|
||||||
|
assert ev_["coupang:1"]["amount"] == 24000 + 3000 and ev_["coupang:1"]["quantity"] == 3 # 배송비 제외, 중복 없음
|
||||||
|
assert ev_["coupang:1"]["discount_amount"] == 1000 and ev_["coupang:1"]["product_name"] == "밀폐용기 외 1건"
|
||||||
|
assert ev_["coupang:2"]["amount"] == 12000 and "취소" in ev_["coupang:2"]["order_status"]
|
||||||
|
assert ev_["coupang:rg:70"]["amount"] == 29700 and ev_["coupang:rg:70"]["sales_date"] == date(2026, 10, 12)
|
||||||
|
assert ev_["coupang:rg:71"]["amount"] == 5000 # 다음 쪽(nextToken)
|
||||||
|
assert {q["status"] for p, q in calls if p.endswith("/ordersheets")} == set(cp.STATUSES)
|
||||||
|
sheet_q = next(q for p, q in calls if p.endswith("/ordersheets"))
|
||||||
|
assert sheet_q["createdAtFrom"] == "2026-10-11+09:00" and sheet_q["createdAtTo"] == "2026-10-12+09:00" # 주문일 하루 앞부터
|
||||||
|
assert any(q.get("nextToken") == "p2" and q["status"] == "INSTRUCT" for p, q in calls if p.endswith("/ordersheets"))
|
||||||
|
rg_q = next(q for p, q in calls if p.endswith("/rg/orders"))
|
||||||
|
assert rg_q["paidDateFrom"] == "20261012" and rg_q["paidDateTo"] == "20261012"
|
||||||
|
assert "홍길동" not in repr(st.events) and "비밀구" not in repr(st.events) and "1234-5678" not in repr(st.events)
|
||||||
|
|
||||||
|
|
||||||
|
def test_coupang_spans_and_money():
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
|
||||||
|
assert cp.spans(date(2026, 1, 1), date(2026, 3, 5), 31) == [
|
||||||
|
(date(2026, 1, 1), date(2026, 1, 31)), (date(2026, 2, 1), date(2026, 3, 3)), (date(2026, 3, 4), date(2026, 3, 5))]
|
||||||
|
assert cp._won({"units": 15000, "nanos": 0}) == 15000 and cp._won("27,800") == 27800 and cp._won(None) == 0
|
||||||
|
assert cp._kst_day("2026-10-12T00:10:00+09:00") == date(2026, 10, 12)
|
||||||
|
assert cp._kst_day("2026-10-11T15:10:00Z") == date(2026, 10, 12) # UTC → 한국 날짜
|
||||||
|
assert cp._kst_day(KST_1012_0030_MS) == date(2026, 10, 12)
|
||||||
|
assert cp._kst_day("2026-10-12") == date(2026, 10, 12) and cp._kst_day("") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_coupang_reconcile_candidates_hide_personal():
|
||||||
|
"""원본 데이터 확인 — 날짜별 후보 금액(할인 전·후, 취소분 뺀 값, 로켓그로스)·판매량, 개인정보 항목은 아예 없음.
|
||||||
|
로켓그로스만 실패해도 판매자배송 결과는 보여 준다."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext
|
||||||
|
|
||||||
|
class Creds(dict):
|
||||||
|
def get(self, k, default=""):
|
||||||
|
return dict.get(self, k, default)
|
||||||
|
|
||||||
|
def has(self, k):
|
||||||
|
return bool(dict.get(self, k))
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK"))
|
||||||
|
sheets = {"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)]),
|
||||||
|
_cp_sheet(2, 21, "2026-10-13T10:00:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])]}
|
||||||
|
get, _calls = _cp_server(sheets, [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])]])
|
||||||
|
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||||
|
try:
|
||||||
|
rec = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12), to=date(2026, 10, 13))
|
||||||
|
cands = {c["label"][:1]: c for c in rec["refund_candidates"]}
|
||||||
|
assert cands["①"]["days"] == {"2026-10-12": 24000 + 29700, "2026-10-13": 12000}
|
||||||
|
assert cands["②"]["days"]["2026-10-12"] == 24000 and cands["③"]["days"]["2026-10-12"] == 23000
|
||||||
|
assert cands["④"]["days"]["2026-10-13"] == 0 and cands["⑤"]["days"]["2026-10-12"] == 29700
|
||||||
|
assert next(c for c in rec["refund_candidates"] if c["label"].startswith("판매량"))["days"]["2026-10-12"] == 5
|
||||||
|
assert rec["days"][0] == {"date": "2026-10-12", "orders": 2, "amount": 53700, "claimed": 0, "ship": 3000}
|
||||||
|
assert rec["days"][1]["claimed"] == 12000 and rec["candidates_title"]
|
||||||
|
names = {f["name"] for p in rec["probes"] if p["ok"] for f in p["fields"]}
|
||||||
|
assert "orderItems.orderPrice.units" in names and not any(n.startswith(("orderer", "receiver")) for n in names)
|
||||||
|
assert "홍길동" not in repr(rec) and "비밀구" not in repr(rec) and "개인 메모" not in repr(rec) and "문 앞" not in repr(rec)
|
||||||
|
|
||||||
|
def deny_rg(url, headers=None, timeout=None): # 로켓그로스만 거부(403)
|
||||||
|
if "/rg/orders" in url:
|
||||||
|
return httpx.Response(403, json={"message": "Access Denied"})
|
||||||
|
return get(url, headers, timeout)
|
||||||
|
|
||||||
|
httpx.get = deny_rg
|
||||||
|
rec2 = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12))
|
||||||
|
p = {x["key"]: x for x in rec2["probes"]}
|
||||||
|
assert p["seller"]["ok"] and not p["rg"]["ok"] and "403" in p["rg"]["error"]
|
||||||
|
assert rec2["refund_candidates"][0]["error"] and rec2["refund_candidates"][1]["days"]["2026-10-12"] == 24000
|
||||||
|
finally:
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||||
|
|
||||||
|
|
||||||
def test_elevenst_connection():
|
def test_elevenst_connection():
|
||||||
@@ -951,10 +1378,15 @@ def test_elevenst_collect_sales():
|
|||||||
|
|
||||||
def test_registry_and_event_validation():
|
def test_registry_and_event_validation():
|
||||||
codes = [a.code for a in all_adapters()]
|
codes = [a.code for a in all_adapters()]
|
||||||
assert len(codes) == len(set(codes)) == 10
|
assert len(codes) == len(set(codes)) == 12
|
||||||
|
assert codes == ["cafe24", "naver", "coupang", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||||
|
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
|
||||||
for a in all_adapters():
|
for a in all_adapters():
|
||||||
keys = [f.key for f in a.credential_fields()]
|
keys = [f.key for f in a.credential_fields()]
|
||||||
assert len(keys) == len(set(keys)), a.code
|
assert len(keys) == len(set(keys)), a.code
|
||||||
|
if a.manual_only: # 수동 입력 전용 — 인증 항목 없음
|
||||||
|
assert not keys and not a.implemented, a.code
|
||||||
|
continue
|
||||||
assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
|
assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
|
||||||
for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
|
for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
|
||||||
SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
|
SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
|
||||||
@@ -1340,6 +1772,158 @@ def test_gsshop_collect_sales():
|
|||||||
assert rec["days"][1]["amount"] == -17000 and rec["days"][1]["claimed"] == 17000
|
assert rec["days"][1]["amount"] == -17000 and rec["days"][1]["claimed"] == 17000
|
||||||
|
|
||||||
|
|
||||||
|
def _kakao_detail(oid, pid, paid, price, qty=1, opt=0, sdc=0, cdc=0, adc=0, ship=3000, status="ShippingProgress"):
|
||||||
|
return {"id": oid,
|
||||||
|
"orderBase": {"id": oid, "paymentId": pid, "status": status, "createdAt": paid, "paidAt": paid,
|
||||||
|
"modifiedAt": paid},
|
||||||
|
"orderer": {"phoneNumber": "010-1234-5678"},
|
||||||
|
"orderProduct": {"id": oid, "name": "미라클통", "optionContent": "3200ml", "quantity": qty,
|
||||||
|
"productPrice": price, "optionPrice": opt, "sellerDiscountPrice": sdc,
|
||||||
|
"sellerCouponDiscountPrice": cdc, "adminDiscountPrice": adc, "deliveryAmount": ship,
|
||||||
|
"areaAdditionalDeliveryAmount": 0},
|
||||||
|
"orderDeliveryRequest": {"receiverName": "홍길동", "receiverAddress1": "서울 반품동", "requirement": "문 앞"},
|
||||||
|
"orderClaimReturn": {"claimItemStatus": "RETURN_COMPLETE", "pickupName": "홍길동", "reasonComment": "변심"}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_kakao_connection_headers_and_errors():
|
||||||
|
"""카카오: kapi.kakao.com + Authorization(앱 어드민 키)·Target-Authorization(판매자 인증키)·channel-ids 헤더.
|
||||||
|
-2(두 키가 같은 앱)·-401(판매자 키 무효)·403 은 인증 실패, 키 값은 메시지에 없음."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import kakao as kk
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, NotConfigured
|
||||||
|
|
||||||
|
class Creds(dict):
|
||||||
|
def get(self, k, default=""):
|
||||||
|
return dict.get(self, k, default)
|
||||||
|
|
||||||
|
def has(self, k):
|
||||||
|
return bool(dict.get(self, k))
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="kakao", credentials=Creds(admin_key="ADMIN-SECRET", api_key="SELLER-SECRET"))
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
def ok(url, params=None, headers=None, timeout=None):
|
||||||
|
seen.update(url=url, params=params, headers=headers)
|
||||||
|
return httpx.Response(200, json={"contents": [{"orderId": 1, "paymentId": 9, "orderStatus": "PayComplete"}]})
|
||||||
|
|
||||||
|
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
|
||||||
|
kk.CALL_INTERVAL_SEC = 0
|
||||||
|
try:
|
||||||
|
httpx.get = ok
|
||||||
|
msg = kk.KakaoAdapter().test_connection(ctx)
|
||||||
|
assert "연결 정상" in msg and "1건" in msg
|
||||||
|
assert seen["url"] == "https://kapi.kakao.com/v2/shopping/orders/paidAt"
|
||||||
|
assert seen["headers"]["Authorization"] == "KakaoAK ADMIN-SECRET"
|
||||||
|
assert seen["headers"]["Target-Authorization"] == "KakaoAK SELLER-SECRET"
|
||||||
|
assert seen["headers"]["channel-ids"] == "101" # 기본 톡스토어
|
||||||
|
assert seen["params"]["from"].endswith(" 00:00:00") and seen["params"]["to"].endswith(" 23:59:59")
|
||||||
|
ctx2 = AdapterContext(code="kakao", credentials=Creds(admin_key="A", api_key="S", channel_ids=" 1, 101 "))
|
||||||
|
kk.KakaoAdapter().test_connection(ctx2)
|
||||||
|
assert seen["headers"]["channel-ids"] == "1,101"
|
||||||
|
for status, body, kind, word in (
|
||||||
|
(401, {"msg": "invalid authorization or target-authorization header.", "code": -2}, AuthFailed, "서로 다른 앱"),
|
||||||
|
(401, {"msg": "appKey(판매자인증키) is already deactivated", "code": -401}, AuthFailed, "판매자 API 인증키"),
|
||||||
|
(400, {"code": -800, "msg": "대행사 매핑/권한 확인이 필요합니다."}, AuthFailed, "연결되지 않았습니다"),
|
||||||
|
(403, {"code": -3, "msg": "forbidden"}, AuthFailed, "403"),
|
||||||
|
(500, {"code": -500, "msg": "internal"}, ApiError, "500")):
|
||||||
|
httpx.get = (lambda s, b: lambda url, params=None, headers=None, timeout=None: httpx.Response(s, json=b))(status, body)
|
||||||
|
try:
|
||||||
|
kk.KakaoAdapter().test_connection(ctx)
|
||||||
|
except kind as exc:
|
||||||
|
assert word in exc.message and "ADMIN-SECRET" not in exc.message and "SELLER-SECRET" not in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("오류여야 합니다")
|
||||||
|
finally:
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||||
|
try:
|
||||||
|
kk.KakaoAdapter().test_connection(AdapterContext(code="kakao", credentials=Creds(api_key="S")))
|
||||||
|
except NotConfigured:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("어드민 키 없으면 미설정")
|
||||||
|
|
||||||
|
|
||||||
|
def test_kakao_collect_sales():
|
||||||
|
"""카카오 매출 = 결제(paymentId) 하나, 결제일 기준, (상품가+옵션가)×수량 − 할인들, 배송비 제외.
|
||||||
|
목록(paidAt, token 으로 다음 쪽) → 주문정보(order_id). 미결제는 빼고 결제 뒤 취소는 포함. 개인정보 미저장."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import kakao as kk
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext
|
||||||
|
|
||||||
|
details = {
|
||||||
|
11: _kakao_detail(11, 900, "20261001101500", 10000, qty=2, opt=1000, sdc=500, cdc=1000, adc=500), # 22000-2000
|
||||||
|
12: _kakao_detail(12, 900, "20261001101500", 5000), # 같은 결제
|
||||||
|
13: _kakao_detail(13, 901, "20261001200000", 7000, status="PayCancelComplete"), # 결제 뒤 취소
|
||||||
|
15: _kakao_detail(15, 903, "20261002090000", 3000),
|
||||||
|
}
|
||||||
|
rows = {
|
||||||
|
"2026-10-01": [[{"orderId": 11, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
|
||||||
|
"modifiedAt": "20261001110000"},
|
||||||
|
{"orderId": 12, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
|
||||||
|
"modifiedAt": "20261001110000"}],
|
||||||
|
[{"orderId": 13, "paymentId": 901, "orderStatus": "PayCancelComplete", "paidAt": "20261001200000",
|
||||||
|
"modifiedAt": "20261001210000"},
|
||||||
|
{"orderId": 14, "paymentId": 902, "orderStatus": "PayWaiting", "paidAt": "",
|
||||||
|
"modifiedAt": "20261001210000"}]],
|
||||||
|
"2026-10-02": [[{"orderId": 15, "paymentId": 903, "orderStatus": "BuyDecision", "paidAt": "20261002090000",
|
||||||
|
"modifiedAt": "20261002090000"}]],
|
||||||
|
}
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
calls.append((url.rsplit("/", 1)[-1], dict(params)))
|
||||||
|
if url.endswith("/v1/shopping/order"):
|
||||||
|
return httpx.Response(200, json=details[int(params["order_id"])])
|
||||||
|
pages = rows.get(params["from"][:10], [[]])
|
||||||
|
i = int(params.get("token") or 0)
|
||||||
|
body = {"contents": pages[i]}
|
||||||
|
if i + 1 < len(pages):
|
||||||
|
body["token"] = str(i + 1)
|
||||||
|
return httpx.Response(200, json=body)
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "kakao"), {"admin_key": "ADMIN", "api_key": "SELLER"})
|
||||||
|
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
|
||||||
|
try:
|
||||||
|
r = SyncService(st, creds).sync_marketplace("kakao", date(2026, 10, 1), date(2026, 10, 2))
|
||||||
|
finally:
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||||
|
assert r["ok"], r
|
||||||
|
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "kakao"}
|
||||||
|
assert set(ev_) == {"kakao:900", "kakao:901", "kakao:903"} # 미결제 902 제외
|
||||||
|
a = ev_["kakao:900"]
|
||||||
|
assert a["amount"] == (10000 + 1000) * 2 - 2000 + 5000 and a["sales_date"] == date(2026, 10, 1)
|
||||||
|
assert a["discount_amount"] == 2000 and a["quantity"] == 3 and a["product_name"] == "미라클통"
|
||||||
|
assert ev_["kakao:901"]["amount"] == 7000 # 결제 뒤 취소도 결제일 매출(네이버와 같은 기준)
|
||||||
|
assert ev_["kakao:903"]["sales_date"] == date(2026, 10, 2)
|
||||||
|
assert not any(c[0] == "order" and c[1]["order_id"] == "14" for c in calls) # 미결제는 주문정보도 안 부름
|
||||||
|
assert [c[1].get("token") for c in calls if c[0] == "paidAt"] == [None, "1", None] # 다음 쪽 token
|
||||||
|
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
|
||||||
|
|
||||||
|
# 원본 데이터 확인 — 개인정보는 값 없이 이름만, 날짜별 현재 규칙 매출
|
||||||
|
ad = kk.KakaoAdapter()
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
|
||||||
|
try:
|
||||||
|
rec = ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1),
|
||||||
|
to=date(2026, 10, 2))
|
||||||
|
n = len(calls)
|
||||||
|
ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1))
|
||||||
|
assert not [c for c in calls[n:] if c[0] == "order"] # 수정일이 같으면 주문정보 캐시
|
||||||
|
finally:
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||||
|
assert rec["days"][0] == {"date": "2026-10-01", "orders": 2, "amount": 25000 + 7000, "claimed": 7000, "ship": 9000}
|
||||||
|
assert rec["days"][1]["amount"] == 3000
|
||||||
|
f = {x["name"]: x for x in rec["probes"][0]["fields"]}
|
||||||
|
assert f["orderProduct.productPrice"]["sum"] == 10000 + 5000 + 7000 + 3000
|
||||||
|
assert f["orderDeliveryRequest.receiverName"]["sample"] == "" and f["orderer.phoneNumber"]["sample"] == ""
|
||||||
|
assert "홍길동" not in repr(rec) and "반품동" not in repr(rec) and "010-1234-5678" not in repr(rec)
|
||||||
|
assert "변심" not in repr(rec) and "문 앞" not in repr(rec)
|
||||||
|
|
||||||
|
|
||||||
def test_sync_job_cancel():
|
def test_sync_job_cancel():
|
||||||
"""[업데이트 취소]: 수집 중인 쇼핑몰은 다음 API 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
|
"""[업데이트 취소]: 수집 중인 쇼핑몰은 다음 API 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
|
||||||
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""
|
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""
|
||||||
@@ -1385,6 +1969,83 @@ def test_sync_job_cancel():
|
|||||||
assert snapshot["cancel_requested"] and snapshot["overall"]["finished"] == 2 and snapshot["overall"]["fraction"] == 1.0
|
assert snapshot["cancel_requested"] and snapshot["overall"]["finished"] == 2 and snapshot["overall"]["fraction"] == 1.0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_job_stop_shop():
|
||||||
|
"""쇼핑몰별 [중지]: 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, "중지됨") 다음 쇼핑몰로 넘어간다.
|
||||||
|
차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 끝난 쇼핑몰·없는 쇼핑몰은 중지 못 함."""
|
||||||
|
import bcrypt
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance import jobs
|
||||||
|
from app.modules.performance.adapters import naver as nv
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
|
||||||
|
job = jobs.create_job(user="king@x", start=None, end=None)
|
||||||
|
naver_days = []
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
if "commerce.naver.com" in url:
|
||||||
|
naver_days.append(params["from"][:10])
|
||||||
|
if len(naver_days) == 1:
|
||||||
|
assert job.stop_shop("gsshop") # 차례가 안 온 GS샵을 미리 중지
|
||||||
|
if len(naver_days) == 2:
|
||||||
|
assert job.stop_shop("naver") # 둘째 날을 받는 도중 네이버 중지
|
||||||
|
rows = [_naver_item("A" + naver_days[-1], "P" + naver_days[-1], naver_days[-1], 10000)]
|
||||||
|
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"hasNext": False}}})
|
||||||
|
if url.endswith("/claims"):
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": [], "nextToken": None}})
|
||||||
|
found = [_toss_item(1, 11, "2026-09-09T10:00:00", 12000)] if params["startDate"] == "2026-09-09" else []
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}})
|
||||||
|
|
||||||
|
def post(url, data=None, timeout=None, headers=None):
|
||||||
|
return httpx.Response(200, json={"access_token": "T", "expires_in": 10799})
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
st.markets = [m for m in st.markets if m["code"] in ("naver", "gsshop", "toss")]
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "naver"),
|
||||||
|
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "gsshop"),
|
||||||
|
{"vendor_code": "1047142", "api_key": "0123456789abcdef0123456789ABCDEF"})
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
|
||||||
|
st.events[("naver", "SALE", "naver:OLD")] = {"amount": 5000, "is_sample": False, "sales_date": date(2026, 9, 10)}
|
||||||
|
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = post, get, 0, 0
|
||||||
|
try:
|
||||||
|
res = SyncService(st, creds).sync_all(start=date(2026, 9, 9), end=date(2026, 9, 12), user="king@x", job=job)
|
||||||
|
finally:
|
||||||
|
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
job.finish()
|
||||||
|
by = {r["code"]: r for r in res}
|
||||||
|
assert naver_days == ["2026-09-09", "2026-09-10"] # 중지 뒤 네이버는 더 부르지 않음
|
||||||
|
assert by["naver"]["cancelled"] and by["naver"]["message"] == "중지됨"
|
||||||
|
assert by["gsshop"]["cancelled"] and by["gsshop"]["message"] == "중지됨" # 미리 중지 → 차례에 건너뜀
|
||||||
|
assert by["toss"]["ok"] and by["toss"]["upserted"] == 1 # 다음 쇼핑몰은 계속
|
||||||
|
assert ("naver", "SALE", "naver:OLD") in st.events and not any(k[0] == "naver" and k[2] != "naver:OLD" for k in st.events)
|
||||||
|
assert ("toss", "SALE", "toss:1") in st.events
|
||||||
|
snap = job.snapshot()
|
||||||
|
shops = {s["code"]: s for s in snap["shops"]}
|
||||||
|
assert shops["naver"]["state"] == "cancelled" and shops["naver"]["message"] == "중지됨" and shops["naver"]["stop_requested"]
|
||||||
|
assert shops["toss"]["state"] == "done" and not snap["cancel_requested"]
|
||||||
|
assert "naver" not in st.status # 연결 상태 안 바뀜
|
||||||
|
assert not job.stop_shop("toss") and not job.stop_shop("nope") # 끝난 작업·없는 쇼핑몰
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_only_marketplaces_skip_sync_and_show_manual_status():
|
||||||
|
"""쿠팡(로켓)·애터미아자몰 = 수동 입력 전용 — 매출 업데이트 대상이 아니고 연결 상태는 "수동 입력"."""
|
||||||
|
from app.modules.performance.dashboard import display_status
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
res = SyncService(st, creds).sync_all(start=date(2026, 10, 1), end=date(2026, 10, 2),
|
||||||
|
codes=["coupang_rocket", "atomy"], user="king@x")
|
||||||
|
assert res == [] and not st.events and not st.status
|
||||||
|
for code in ("coupang_rocket", "atomy"):
|
||||||
|
assert display_status({"code": code, "enabled": True}, None, False) == "manual"
|
||||||
|
assert display_status({"code": "coupang_rocket", "enabled": False}, None, False) == "disabled"
|
||||||
|
assert display_status({"code": "ohouse", "enabled": True}, None, False) == "not_configured"
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
||||||
n = 0
|
n = 0
|
||||||
@@ -1394,3 +2055,112 @@ if __name__ == "__main__":
|
|||||||
n += 1
|
n += 1
|
||||||
print("ok", name)
|
print("ok", name)
|
||||||
print(f"{n} tests passed")
|
print(f"{n} tests passed")
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_sale_api_rules():
|
||||||
|
"""수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지, 숫자(쉼표 허용), 비우면 지움, 002 미적용이면 503.
|
||||||
|
켜고 끄기(PUT marketplaces)는 관리자 전용 그대로, manual_input 도 받는다."""
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
from app.modules.performance.db import ManualMigrationNeeded
|
||||||
|
|
||||||
|
router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
|
||||||
|
|
||||||
|
class St:
|
||||||
|
def __init__(self):
|
||||||
|
self.saved, self.updated, self.missing = [], [], False
|
||||||
|
|
||||||
|
def list_marketplaces(self):
|
||||||
|
return [{"code": "coupang", "manual_input": True}, {"code": "naver", "manual_input": False}]
|
||||||
|
|
||||||
|
def set_manual_sale(self, code, day, amount, *, user=""):
|
||||||
|
if self.missing:
|
||||||
|
raise ManualMigrationNeeded()
|
||||||
|
self.saved.append((code, day, amount, user))
|
||||||
|
|
||||||
|
def api_amount(self, code, day):
|
||||||
|
return 50000
|
||||||
|
|
||||||
|
def update_marketplace(self, code, **kw):
|
||||||
|
if self.missing and kw.get("manual_input") is not None:
|
||||||
|
raise ManualMigrationNeeded()
|
||||||
|
self.updated.append((code, kw))
|
||||||
|
return {"code": code}
|
||||||
|
|
||||||
|
st = St()
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
def fake_require(request, *, admin=False):
|
||||||
|
seen["admin"] = admin
|
||||||
|
return st, {"email": "me@test.local"}
|
||||||
|
|
||||||
|
def status_of(fn):
|
||||||
|
try:
|
||||||
|
fn()
|
||||||
|
except HTTPException as exc:
|
||||||
|
return exc.status_code, exc.detail
|
||||||
|
return 200, ""
|
||||||
|
|
||||||
|
orig = (common.require_store, router.today_kst)
|
||||||
|
common.require_store, router.today_kst = fake_require, (lambda: date(2026, 10, 12))
|
||||||
|
try:
|
||||||
|
r = router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "87,000"})
|
||||||
|
body = __import__("json").loads(r.body)
|
||||||
|
assert st.saved[-1] == ("coupang", date(2026, 10, 12), 87000, "me@test.local") and seen["admin"] is False
|
||||||
|
assert body["manual"] == 87000 and body["amount"] == 87000 and body["api_amount"] == 50000
|
||||||
|
body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-11", {"amount": ""}).body)
|
||||||
|
assert st.saved[-1][2] is None and body["manual"] is None and body["amount"] == 50000 # 지움 → API 값
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 400 # 앞날
|
||||||
|
code, msg = status_of(lambda: router.api_manual_sale(None, "naver", "2026-10-12", {"amount": 1}))
|
||||||
|
assert code == 400 and "수동 입력" in msg # 꺼진 쇼핑몰
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "abc"}))[0] == 400
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 10 ** 13}))[0] == 400
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "nope", "2026-10-12", {"amount": 1}))[0] == 404
|
||||||
|
router.api_update_marketplace(None, "coupang", {"manual_input": True})
|
||||||
|
assert seen["admin"] is True and st.updated[-1] == ("coupang", {"enabled": None, "include_in_sales": None, "manual_input": True})
|
||||||
|
st.missing = True
|
||||||
|
code, msg = status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 1}))
|
||||||
|
assert code == 503 and "002" in msg
|
||||||
|
assert status_of(lambda: router.api_update_marketplace(None, "coupang", {"manual_input": False}))[0] == 503
|
||||||
|
finally:
|
||||||
|
common.require_store, router.today_kst = orig
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_manual_cells_and_order():
|
||||||
|
"""대시보드 — 수동 입력 켠 쇼핑몰만 manual_codes, 값이 있는 칸만 manual_cells, 수동 값이 그날 금액(수수료도 그 값으로)."""
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from app.modules.performance.dashboard import build_dashboard
|
||||||
|
|
||||||
|
class St:
|
||||||
|
def list_marketplaces(self):
|
||||||
|
return [{"code": c, "name": c, "enabled": True, "include_in_sales": True, "manual_input": c == "coupang"}
|
||||||
|
for c in ("cafe24", "naver", "coupang", "toss")]
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
return {(date(2026, 10, 5), "coupang"): 87000} # 저장소가 이미 수동 값으로 바꿔 돌려준다
|
||||||
|
|
||||||
|
def manual_amounts(self, start, end, codes, *, active_only=True):
|
||||||
|
assert codes == ["coupang"]
|
||||||
|
return {(date(2026, 10, 5), "coupang"): 87000} if start <= date(2026, 10, 5) <= end else {}
|
||||||
|
|
||||||
|
def rate_table(self):
|
||||||
|
return {"coupang": [(date(2026, 1, 1), Decimal("10"))]}
|
||||||
|
|
||||||
|
def statuses(self):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def last_update_at(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def running_codes(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
ctx = build_dashboard(St(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||||
|
assert ctx["codes"] == ["cafe24", "naver", "coupang", "toss"]
|
||||||
|
assert ctx["manual_codes"] == ["coupang"] and ctx["manual_cells"] == ["2026-10-05|coupang"]
|
||||||
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
|
assert day5["cells"]["coupang"]["gross"] == 87000 and day5["cells"]["coupang"]["commission"] == 8700
|
||||||
|
|||||||
Binary file not shown.
@@ -5,12 +5,23 @@
|
|||||||
바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다).
|
바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다).
|
||||||
|
|
||||||
프로젝트
|
프로젝트
|
||||||
관리(=보기·작업 CRUD) : 관리자(is_admin) · 프로젝트 owner · 배정 멤버. 모두 `project` 모듈 권한이 있어야 한다.
|
관리(=보기·작업 CRUD) : 프로젝트 owner · 배정 멤버 · 슈퍼관리자. 모두 `project` 모듈 권한이 있어야 한다.
|
||||||
|
(2026-10-07 — 관리자(is_admin)도 멤버가 아닌 프로젝트는 보이지 않는다. 예외는 슈퍼관리자 한 명뿐.
|
||||||
|
멤버 배정은 Pro user 이상(2026-10-12) — 라우터의 _require_pro, 아래 등급 표.)
|
||||||
|
|
||||||
|
등급(2026-10-12, app.store.ROLES) — 수퍼관리자 > admin > pro > user
|
||||||
|
is_project_admin : 수퍼관리자·admin — 남이 만든 프로젝트·섹션도 삭제.
|
||||||
|
is_pro : 수퍼관리자·admin·pro — 새 프로젝트 만들기, 프로젝트 이름·색·아이콘·소유자 수정,
|
||||||
|
멤버 배정·제외(자기가 멤버인 프로젝트), 사이드바 순서, 남의 댓글 수정·삭제,
|
||||||
|
휴지통 보기·복구, 전체 보기, 대시보드 담당자별 합계, 전체 멤버 메뉴,
|
||||||
|
목표 표 입력·구조 변경·주차별 목표·연도 추가/삭제, 회의 완료·완료 해제·회의록 삭제.
|
||||||
|
user : 멤버인 프로젝트의 작업·섹션·서브프로젝트·작업 삭제, 회의록 작성(완료 전까지).
|
||||||
|
프로젝트 단위 권한은 등급과 상관없이 멤버(owner)여야 한다 — 위 is_pro 권한도 멤버인 프로젝트 안에서만.
|
||||||
|
|
||||||
작업
|
작업
|
||||||
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(삭제는 추가로 생성자 규칙)
|
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(작업 삭제는 멤버 누구나, 2026-10-12)
|
||||||
READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음
|
READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음
|
||||||
→ 그 작업의 상세·하위 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
|
→ 그 작업의 상세·세부 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
|
||||||
연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용.
|
연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용.
|
||||||
None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외
|
None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외
|
||||||
"""
|
"""
|
||||||
@@ -34,10 +45,34 @@ def default_user_lookup(email: str) -> dict[str, Any] | None:
|
|||||||
return user_store.get(store.norm_str(email, lower=True))
|
return user_store.get(store.norm_str(email, lower=True))
|
||||||
|
|
||||||
|
|
||||||
def _is_admin(user: dict[str, Any] | None) -> bool:
|
def _is_super(user: dict[str, Any] | None) -> bool:
|
||||||
from app.store import is_admin # noqa: WPS433
|
"""슈퍼관리자(app.store.SUPER_ADMIN_EMAIL) — 모든 프로젝트를 보는 유일한 예외."""
|
||||||
|
from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433
|
||||||
|
|
||||||
return is_admin(user)
|
return bool(user) and email_of(user) == SUPER_ADMIN_EMAIL
|
||||||
|
|
||||||
|
|
||||||
|
def role_of(user: dict[str, Any] | None) -> str:
|
||||||
|
"""등급 — 'super' · 'admin' · 'pro' · 'user'. 모르는 role 값은 user 로 본다."""
|
||||||
|
if _is_super(user):
|
||||||
|
return "super"
|
||||||
|
role = (user or {}).get("role")
|
||||||
|
return role if role in ("admin", "pro") else "user"
|
||||||
|
|
||||||
|
|
||||||
|
def is_project_admin(user: dict[str, Any] | None) -> bool:
|
||||||
|
"""수퍼관리자·admin — 만든 사람이 아니어도 프로젝트·섹션을 지운다."""
|
||||||
|
return role_of(user) in ("super", "admin")
|
||||||
|
|
||||||
|
|
||||||
|
def is_pro(user: dict[str, Any] | None) -> bool:
|
||||||
|
"""수퍼관리자·admin·pro — 프로젝트 관리·목표 입력 등 운영 권한(모듈 docstring 의 등급 표)."""
|
||||||
|
return role_of(user) in ("super", "admin", "pro")
|
||||||
|
|
||||||
|
|
||||||
|
def sees_all_projects(user: dict[str, Any] | None) -> bool:
|
||||||
|
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
|
||||||
|
return can_use_module(user) and _is_super(user)
|
||||||
|
|
||||||
|
|
||||||
def can_use_module(user: dict[str, Any] | None) -> bool:
|
def can_use_module(user: dict[str, Any] | None) -> bool:
|
||||||
@@ -51,10 +86,10 @@ def email_of(user: dict[str, Any] | None) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool:
|
def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool:
|
||||||
"""프로젝트 관리(=보기·작업 CRUD) — 관리자 또는 owner/멤버. 모듈 권한이 없으면 False."""
|
"""프로젝트 관리(=보기·작업 CRUD) — owner/멤버(관리자도 마찬가지), 슈퍼관리자는 전부. 모듈 권한이 없으면 False."""
|
||||||
if not can_use_module(user):
|
if not can_use_module(user):
|
||||||
return False
|
return False
|
||||||
if _is_admin(user):
|
if _is_super(user):
|
||||||
return True
|
return True
|
||||||
try:
|
try:
|
||||||
pid = int(project_id)
|
pid = int(project_id)
|
||||||
@@ -64,11 +99,11 @@ def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) ->
|
|||||||
|
|
||||||
|
|
||||||
def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
|
def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
|
||||||
"""관리할 수 있는 프로젝트 id 집합. 관리자는 None(=전체)."""
|
"""관리할 수 있는 프로젝트 id 집합. 슈퍼관리자는 None(=전체), 그 밖(관리자 포함)은 owner·멤버인 프로젝트만."""
|
||||||
if _is_admin(user):
|
|
||||||
return None
|
|
||||||
if not can_use_module(user):
|
if not can_use_module(user):
|
||||||
return set()
|
return set()
|
||||||
|
if _is_super(user):
|
||||||
|
return None
|
||||||
return {
|
return {
|
||||||
int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user))
|
int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user))
|
||||||
}
|
}
|
||||||
|
|||||||
+1935
-190
File diff suppressed because it is too large
Load Diff
+1524
-232
File diff suppressed because it is too large
Load Diff
+414
-10
@@ -6,7 +6,10 @@ DB 없이 단위 테스트 가능한 순수 함수만 둔다(malaysia.store 패
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from html import escape
|
||||||
from html.parser import HTMLParser
|
from html.parser import HTMLParser
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -37,7 +40,8 @@ ACTION_ASSIGNED = "assigned"
|
|||||||
ACTION_COMPLETED = "completed"
|
ACTION_COMPLETED = "completed"
|
||||||
ACTION_STAGE_CHANGED = "stage_changed"
|
ACTION_STAGE_CHANGED = "stage_changed"
|
||||||
ACTION_REOPENED = "reopened"
|
ACTION_REOPENED = "reopened"
|
||||||
ACTION_SUBTASK_MOVED = "subtask_moved" # 하위 업무를 다른 상위 업무로 옮김(보드 드래그)
|
ACTION_SUBTASK_MOVED = "subtask_moved" # 세부 업무를 다른 상위 업무로 옮김(보드 드래그)
|
||||||
|
ACTION_PROJECT_MOVED = "project_moved" # 업무를 다른 프로젝트로 옮김(왼쪽 프로젝트 목록으로 드래그)
|
||||||
|
|
||||||
# 프로젝트 색상 팔레트 — 32색(8칸 × 4줄). 앞 16색은 아사나 프로젝트 색(아사나 색상표
|
# 프로젝트 색상 팔레트 — 32색(8칸 × 4줄). 앞 16색은 아사나 프로젝트 색(아사나 색상표
|
||||||
# 순서 그대로), 뒤 16색은 같은 칸(열)에 대응하는 진한 색 — 3줄째 = 1줄째의 진한 색,
|
# 순서 그대로), 뒤 16색은 같은 칸(열)에 대응하는 진한 색 — 3줄째 = 1줄째의 진한 색,
|
||||||
@@ -128,6 +132,22 @@ PROJECT_ICONS: tuple[str, ...] = (
|
|||||||
"build", # 도구
|
"build", # 도구
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 아사나 아이콘(2026-10-08) — 아사나 프로젝트 아이콘과 같은 채워진 모양. 저장 값은 "asana:" + 이름,
|
||||||
|
# 글꼴은 이 33개만 담은 채워진 Material Symbols(static/vendor/material-symbols/material-symbols-asana.woff2).
|
||||||
|
# 이름을 늘리면 그 글꼴도 다시 받아야 한다(docs/PROJECT_MODULE.md 6-12).
|
||||||
|
ASANA_ICON_PREFIX = "asana:"
|
||||||
|
PROJECT_ASANA_ICONS: tuple[str, ...] = (
|
||||||
|
"format_list_bulleted", "view_kanban", "view_timeline", "calendar_month",
|
||||||
|
"rocket_launch", "group", "monitoring", "stars",
|
||||||
|
"bug_report", "lightbulb", "language", "settings",
|
||||||
|
"book_2", "desktop_windows", "check_circle", "adjust",
|
||||||
|
"code_blocks", "campaign", "forum", "work",
|
||||||
|
"article", "landscape", "extension", "id_card",
|
||||||
|
"conversion_path", "speed", "workspace_premium", "steps",
|
||||||
|
"shopping_basket", "map", "confirmation_number", "toll",
|
||||||
|
"web",
|
||||||
|
)
|
||||||
|
|
||||||
# 섹션(칸반 컬럼) 색상표 — 모든 편집창이 프로젝트 색상표(32색) 하나를 쓴다.
|
# 섹션(칸반 컬럼) 색상표 — 모든 편집창이 프로젝트 색상표(32색) 하나를 쓴다.
|
||||||
# 섹션에서는 첫 칸(연회색 #c7c4c4, 아사나의 "색 없음")을 고르면 색 없음(NULL, 기본 회색 머리).
|
# 섹션에서는 첫 칸(연회색 #c7c4c4, 아사나의 "색 없음")을 고르면 색 없음(NULL, 기본 회색 머리).
|
||||||
STAGE_COLOR_PALETTE: tuple[str, ...] = COLOR_PALETTE
|
STAGE_COLOR_PALETTE: tuple[str, ...] = COLOR_PALETTE
|
||||||
@@ -264,9 +284,9 @@ def validate_project_name(name: Any) -> str:
|
|||||||
def validate_task_title(title: Any) -> str:
|
def validate_task_title(title: Any) -> str:
|
||||||
v = norm_str(title)
|
v = norm_str(title)
|
||||||
if not v:
|
if not v:
|
||||||
raise ValueError("작업 제목은 필수입니다.")
|
raise ValueError("업무 제목은 필수입니다.")
|
||||||
if len(v) > 300:
|
if len(v) > 300:
|
||||||
raise ValueError("작업 제목이 너무 깁니다(300자 이내).")
|
raise ValueError("업무 제목이 너무 깁니다(300자 이내).")
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
@@ -285,8 +305,10 @@ def validate_color(color: Any) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def validate_project_icon(icon: Any) -> str | None:
|
def validate_project_icon(icon: Any) -> str | None:
|
||||||
"""프로젝트 아이콘 — PROJECT_ICONS 안의 이름만, 빈값/목록 밖은 None(첫 글자 표시)."""
|
"""프로젝트 아이콘 — PROJECT_ICONS 안의 이름 또는 "asana:" + PROJECT_ASANA_ICONS 이름만, 빈값/목록 밖은 None(첫 글자 표시)."""
|
||||||
v = norm_str(icon)
|
v = norm_str(icon)
|
||||||
|
if v.startswith(ASANA_ICON_PREFIX):
|
||||||
|
return v if v[len(ASANA_ICON_PREFIX):] in PROJECT_ASANA_ICONS else None
|
||||||
return v if v in PROJECT_ICONS else None
|
return v if v in PROJECT_ICONS else None
|
||||||
|
|
||||||
|
|
||||||
@@ -356,7 +378,7 @@ def validate_time(t: Any) -> str | None:
|
|||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
|
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스
|
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스(단위 %)
|
||||||
GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적
|
GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적
|
||||||
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄).
|
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄).
|
||||||
# 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다.
|
# 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다.
|
||||||
@@ -386,17 +408,86 @@ def validate_goal_year(y: Any) -> int:
|
|||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class GoalMigration014Needed(RuntimeError):
|
||||||
|
"""기간(분기) 글 칸·월 칸 병합은 마이그레이션 014(goal_cell_merges) 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class GoalMigration017Needed(RuntimeError):
|
||||||
|
"""2·4분기 글 칸(15·16)은 마이그레이션 017(분기) 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class GoalCellConflict(RuntimeError):
|
||||||
|
"""셀 이동 전에 다른 창에서 원본 또는 대상 내용이 바뀜."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingCellMigrationNeeded(RuntimeError):
|
||||||
|
"""회의록 셀 병합 메타데이터(019)가 아직 없다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingLocked(RuntimeError):
|
||||||
|
"""회의 완료(022)된 회의록은 고칠 수 없다(관리자가 완료 해제하면 다시)."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingMigration022Needed(RuntimeError):
|
||||||
|
"""회의 완료(잠금)는 마이그레이션 022 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingMigration027Needed(RuntimeError):
|
||||||
|
"""같은 항목 칸 안 줄 추가·항목 칸 나누기(goal_meeting_items.label_cont)는 마이그레이션 027 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingTaskMigrationNeeded(RuntimeError):
|
||||||
|
"""회의록 작업 등록 표(서버 저장)는 마이그레이션 025 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingParentTaskMigrationNeeded(RuntimeError):
|
||||||
|
"""작업 등록 표의 작업 칸(이미 있는 작업의 세부 작업으로)은 마이그레이션 026 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingMigration020Needed(RuntimeError):
|
||||||
|
"""새 주차(월요일이 아닌 시작일)·결과 글 칸·주차별 목표는 마이그레이션 020 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
GOAL_YEAR = 0 # 업무 영역 글 칸 — 연간
|
||||||
|
# 분기 글 칸(2026-10-01 상·하반기 → 1~4분기). 칸 번호는 예전 반기 칸을 그대로 이어 쓴다 — 데이터 옮기기 없이
|
||||||
|
# 예전 상반기 글(13)은 1분기, 하반기 글(14)은 3분기에 보인다. 2분기(15)·4분기(16)는 마이그레이션 017 뒤에 저장.
|
||||||
|
GOAL_QUARTER_COL: dict[int, int] = {1: 13, 2: 15, 3: 14, 4: 16}
|
||||||
|
GOAL_COL_QUARTER: dict[int, int] = {c: q for q, c in GOAL_QUARTER_COL.items()}
|
||||||
|
GOAL_Q_NEW: tuple[int, ...] = (15, 16) # 017 이 있어야 저장되는 분기 칸
|
||||||
|
GOAL_MAX_COL = 16
|
||||||
|
|
||||||
|
|
||||||
|
def goal_quarter_of(month: int) -> int:
|
||||||
|
"""1~3월 → 1분기, 4~6월 → 2분기, 7~9월 → 3분기, 10~12월 → 4분기."""
|
||||||
|
return (int(month) - 1) // 3 + 1
|
||||||
|
|
||||||
|
|
||||||
def validate_goal_month(m: Any, *, allow_year: bool = False) -> int:
|
def validate_goal_month(m: Any, *, allow_year: bool = False) -> int:
|
||||||
"""1~12월. allow_year 이면 0(연간)도 허용."""
|
"""1~12월. allow_year 이면 업무 영역 글 칸 — 0(연간)·13~16(분기 칸, GOAL_QUARTER_COL)도 허용."""
|
||||||
try:
|
try:
|
||||||
v = int(m)
|
v = int(m)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
raise ValueError("월이 올바르지 않습니다.")
|
raise ValueError("월이 올바르지 않습니다.")
|
||||||
if not ((0 if allow_year else 1) <= v <= 12):
|
if not ((0 if allow_year else 1) <= v <= (GOAL_MAX_COL if allow_year else 12)):
|
||||||
raise ValueError("월이 올바르지 않습니다.")
|
raise ValueError("월이 올바르지 않습니다.")
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def validate_goal_merge(start: Any, end: Any) -> tuple[int, int]:
|
||||||
|
"""월 칸 병합 범위(start~end 월, 2칸 이상) — 분기를 넘지 않는다."""
|
||||||
|
try:
|
||||||
|
s, e = int(start), int(end)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("병합할 월이 올바르지 않습니다.")
|
||||||
|
if s > e:
|
||||||
|
s, e = e, s
|
||||||
|
if not (1 <= s and e <= 12) or s == e:
|
||||||
|
raise ValueError("병합은 1~12월 안에서 2칸 이상 골라야 합니다.")
|
||||||
|
if goal_quarter_of(s) != goal_quarter_of(e):
|
||||||
|
raise ValueError("분기(1~3·4~6·7~9·10~12월)를 넘어 병합할 수 없습니다.")
|
||||||
|
return s, e
|
||||||
|
|
||||||
|
|
||||||
def validate_goal_value(v: Any) -> float | None:
|
def validate_goal_value(v: Any) -> float | None:
|
||||||
"""지표 숫자 — '1,234.5' 같은 쉼표·공백·% 는 떼고 읽는다. 빈값은 None(=지움)."""
|
"""지표 숫자 — '1,234.5' 같은 쉼표·공백·% 는 떼고 읽는다. 빈값은 None(=지움)."""
|
||||||
s = norm_str(v).replace(",", "").replace("%", "").replace(" ", "")
|
s = norm_str(v).replace(",", "").replace("%", "").replace(" ", "")
|
||||||
@@ -437,17 +528,309 @@ def validate_goal_color(color: Any) -> str:
|
|||||||
|
|
||||||
def validate_goal_text(body: Any) -> str:
|
def validate_goal_text(body: Any) -> str:
|
||||||
v = str(body or "").replace("\r\n", "\n").strip()
|
v = str(body or "").replace("\r\n", "\n").strip()
|
||||||
|
if v.startswith(GOAL_RICH_PREFIX):
|
||||||
|
runs = goal_text_runs(v, strict=True)
|
||||||
|
if not "".join(r["text"] for r in runs).strip():
|
||||||
|
return ""
|
||||||
|
return GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False, separators=(",", ":"))
|
||||||
if len(v) > GOAL_TEXT_MAX:
|
if len(v) > GOAL_TEXT_MAX:
|
||||||
raise ValueError(f"칸 하나에 {GOAL_TEXT_MAX}자까지 쓸 수 있습니다.")
|
raise ValueError(f"칸 하나에 {GOAL_TEXT_MAX}자까지 쓸 수 있습니다.")
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
# 기존 TEXT 칸에 버전이 있는 텍스트 조각을 저장한다. 예전 평문은 그대로 유지한다.
|
||||||
|
GOAL_RICH_PREFIX = "pj-rich:v1:"
|
||||||
|
|
||||||
|
|
||||||
|
def goal_text_runs(body: Any, *, strict: bool = False) -> list[dict[str, Any]]:
|
||||||
|
value = str(body or "")
|
||||||
|
if not value.startswith(GOAL_RICH_PREFIX):
|
||||||
|
return [{"text": value}]
|
||||||
|
try:
|
||||||
|
raw = json.loads(value[len(GOAL_RICH_PREFIX):])
|
||||||
|
if not isinstance(raw, list) or len(raw) > GOAL_TEXT_MAX:
|
||||||
|
raise ValueError("서식 데이터가 올바르지 않습니다.")
|
||||||
|
runs = []
|
||||||
|
for item in raw:
|
||||||
|
if not isinstance(item, dict) or not isinstance(item.get("text"), str):
|
||||||
|
raise ValueError("서식 데이터가 올바르지 않습니다.")
|
||||||
|
run: dict[str, Any] = {"text": item["text"]}
|
||||||
|
for key in ("bold", "italic", "underline"):
|
||||||
|
if isinstance(item.get(key), bool):
|
||||||
|
run[key] = item[key]
|
||||||
|
if re.fullmatch(r"#[0-9a-fA-F]{6}", str(item.get("color", ""))):
|
||||||
|
run["color"] = item["color"].lower()
|
||||||
|
size = item.get("size")
|
||||||
|
if isinstance(size, int) and not isinstance(size, bool) and 10 <= size <= 32:
|
||||||
|
run["size"] = size
|
||||||
|
if run["text"]:
|
||||||
|
runs.append(run)
|
||||||
|
if sum(len(r["text"]) for r in runs) > GOAL_TEXT_MAX:
|
||||||
|
raise ValueError(f"칸 하나에 {GOAL_TEXT_MAX}자까지 쓸 수 있습니다.")
|
||||||
|
return runs
|
||||||
|
except (ValueError, TypeError) as err:
|
||||||
|
if strict:
|
||||||
|
raise ValueError("칸의 서식 데이터가 올바르지 않습니다.") from err
|
||||||
|
return [{"text": value}]
|
||||||
|
|
||||||
|
|
||||||
|
def goal_text_plain(body: Any) -> str:
|
||||||
|
return "".join(r["text"] for r in goal_text_runs(body))
|
||||||
|
|
||||||
|
|
||||||
|
def goal_text_html(body: Any, *, include_size: bool = True) -> str:
|
||||||
|
"""허용한 글자 서식만 HTML로 만든다. 사용자 텍스트는 항상 escape한다.
|
||||||
|
월간 계획 요약에서는 include_size=False로 글자 크기만 화면 기본값을 사용한다."""
|
||||||
|
out = []
|
||||||
|
for run in goal_text_runs(body):
|
||||||
|
style = []
|
||||||
|
if "bold" in run:
|
||||||
|
style.append("font-weight:" + ("700" if run["bold"] else "400"))
|
||||||
|
if "italic" in run:
|
||||||
|
style.append("font-style:" + ("italic" if run["italic"] else "normal"))
|
||||||
|
if "underline" in run:
|
||||||
|
style.append("text-decoration:" + ("underline" if run["underline"] else "none"))
|
||||||
|
if "color" in run:
|
||||||
|
style.append("color:" + run["color"])
|
||||||
|
if include_size and "size" in run:
|
||||||
|
style.append(f'font-size:{run["size"]}px')
|
||||||
|
text = escape(run["text"])
|
||||||
|
out.append(f'<span style="{";".join(style)}">{text}</span>' if style else text)
|
||||||
|
return "".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def merge_goal_texts(bodies: list[str]) -> str:
|
||||||
|
values = [v for v in bodies if goal_text_plain(v).strip()]
|
||||||
|
if not any(v.startswith(GOAL_RICH_PREFIX) for v in values):
|
||||||
|
return validate_goal_text("\n".join(values))
|
||||||
|
runs = []
|
||||||
|
for value in values:
|
||||||
|
if runs:
|
||||||
|
runs.append({"text": "\n"})
|
||||||
|
runs.extend(goal_text_runs(value))
|
||||||
|
return validate_goal_text(GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False))
|
||||||
|
|
||||||
|
|
||||||
|
def validate_meeting_content(body: Any) -> str:
|
||||||
|
"""회의록 편집기와 같은 서식 조각 합치기로 이동 예상값을 비교한다."""
|
||||||
|
value = validate_goal_text(body)
|
||||||
|
if not value.startswith(GOAL_RICH_PREFIX):
|
||||||
|
return value
|
||||||
|
runs: list[dict[str, Any]] = []
|
||||||
|
keys = ("bold", "italic", "underline", "color", "size")
|
||||||
|
for run in goal_text_runs(value):
|
||||||
|
if runs and all(runs[-1].get(k) == run.get(k) for k in keys):
|
||||||
|
runs[-1]["text"] += run["text"]
|
||||||
|
else:
|
||||||
|
runs.append(dict(run))
|
||||||
|
if not any(len(run) > 1 for run in runs):
|
||||||
|
return validate_goal_text("".join(run["text"] for run in runs))
|
||||||
|
return GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
# ── 엑셀식 사각형 병합(마이그레이션 015) ──────────────────────────────
|
||||||
|
class GoalMigration015Needed(RuntimeError):
|
||||||
|
"""세로 병합·주간 회의록은 마이그레이션 015 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class GoalMigration016Needed(RuntimeError):
|
||||||
|
"""항목 칸(2열) 묶음(같은 항목 칸 안에 줄 추가)은 마이그레이션 016 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
# 업무 영역 글 칸의 화면 순서 — 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 · 7~9월 · 3분기 · 10~12월 · 4분기
|
||||||
|
GOAL_COL_ORDER: tuple[int, ...] = (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)
|
||||||
|
|
||||||
|
|
||||||
|
def goal_col_group(m: int) -> str:
|
||||||
|
"""병합 가능 묶음 — 가로 병합은 같은 묶음 안에서만(연간·분기 칸은 혼자, 월은 같은 분기끼리)."""
|
||||||
|
if m == GOAL_YEAR:
|
||||||
|
return "year"
|
||||||
|
if m in GOAL_COL_QUARTER:
|
||||||
|
return f"q{GOAL_COL_QUARTER[m]}"
|
||||||
|
return f"months{goal_quarter_of(m)}"
|
||||||
|
|
||||||
|
|
||||||
|
def validate_goal_rect_cols(col_from: Any, col_to: Any) -> tuple[int, int]:
|
||||||
|
"""병합할 칸 범위(화면 순서의 양 끝 칸 번호) → (시작 칸 번호, 가로 칸 수).
|
||||||
|
가로로 여러 칸이면 같은 분기의 월 칸끼리만 — 연간·분기 칸은 세로로만 합칠 수 있다."""
|
||||||
|
try:
|
||||||
|
a, b = int(col_from), int(col_to)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("병합할 칸이 올바르지 않습니다.")
|
||||||
|
if a not in GOAL_COL_ORDER or b not in GOAL_COL_ORDER:
|
||||||
|
raise ValueError("병합할 칸이 올바르지 않습니다.")
|
||||||
|
ia, ib = sorted((GOAL_COL_ORDER.index(a), GOAL_COL_ORDER.index(b)))
|
||||||
|
cols = GOAL_COL_ORDER[ia:ib + 1]
|
||||||
|
if len({goal_col_group(m) for m in cols}) > 1:
|
||||||
|
raise ValueError("연간·분기 칸은 세로로만, 월 칸은 같은 분기 안에서만 합칠 수 있습니다.")
|
||||||
|
return cols[0], len(cols)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 주간 회의록(마이그레이션 015) — 월 머리를 누르면 그 달 주차별 회의록 ──────────
|
||||||
|
MEETING_STATUS: dict[str, str] = {"": "", "done": "완료", "partial": "일부", "miss": "미달"}
|
||||||
|
MEETING_TEXT_MAX = 4000
|
||||||
|
MEETING_LABEL_MAX = 50
|
||||||
|
MEETING_AMOUNT_TEXT_MAX = 100 # 정량 목표·결과 글(021, 예: "20개")
|
||||||
|
# 첫 회의록(이전 주 회의록이 없을 때)의 구역별 줄 — 사용자 회의록 양식(2026-10). 목표 표의 업무 영역 이름과 같으면
|
||||||
|
# 그 줄들로, 없는 구역은 빈 줄 하나. 다음 주부터는 지난주 회의록 줄을 그대로 이어받는다.
|
||||||
|
MEETING_TEMPLATE: dict[str, tuple[str, ...]] = {
|
||||||
|
"상품": ("상품1", "상품2", "상품3", "상품4", "상품5"),
|
||||||
|
"마케팅": ("메타", "구글", "네이버", "기타.신규"),
|
||||||
|
"컨텐츠": ("내용1", "내용2", "내용3", "내용4", "내용5"),
|
||||||
|
"유통": ("신규 인플루언서", "콜라보", "쿠팡", "네이버", "gs", "토스", "애터미", "해외", "오프라인", "기타"),
|
||||||
|
}
|
||||||
|
# 유통 줄 이름 → 실적 모듈 쇼핑몰 코드(그 주 결과를 실적에서 자동으로). 첫 단어 기준, 소문자 비교.
|
||||||
|
MEETING_MARKET_GUESS: tuple[tuple[str, str], ...] = (
|
||||||
|
("쿠팡", "coupang"), ("네이버", "naver"), ("스마트스토어", "naver"), ("gs", "gsshop"), ("토스", "toss"),
|
||||||
|
("11번가", "elevenst"), ("카페24", "cafe24"), ("자사몰", "cafe24"), ("롯데", "lotteon"), ("지마켓", "gmarket"),
|
||||||
|
("g마켓", "gmarket"), ("카카오", "kakao"), ("오늘의집", "ohouse"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def guess_meeting_market(section: str, label: str) -> str:
|
||||||
|
"""유통 구역 줄 이름으로 실적 쇼핑몰 코드 추측(없으면 ""). 마케팅의 "네이버"(광고)는 연결하지 않는다."""
|
||||||
|
if norm_str(section) != "유통":
|
||||||
|
return ""
|
||||||
|
lb = norm_str(label).lower()
|
||||||
|
for word, code in MEETING_MARKET_GUESS:
|
||||||
|
if lb.startswith(word):
|
||||||
|
return code
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def week_monday(d: date) -> date:
|
||||||
|
return d - timedelta(days=d.weekday())
|
||||||
|
|
||||||
|
|
||||||
|
def month_last_day(year: int, month: int) -> date:
|
||||||
|
return date(year + (month == 12), month % 12 + 1, 1) - timedelta(days=1)
|
||||||
|
|
||||||
|
|
||||||
|
def month_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||||
|
"""그 달의 주차(시작일, 끝일) — 2026-10-07 사용자 기준. 주차는 늘 그 달 안(달을 넘지 않는다).
|
||||||
|
· 1일이 월~금이면 1주차 = 1일 ~ 그 주 일요일(월요일 시작이 아니어도 1주차)
|
||||||
|
· 1일이 토·일이면 1주차 = 1일 ~ 다음 주 일요일(토·일 + 다음 월~일)
|
||||||
|
· 그 뒤는 월~일. 말일이 월·화이면 그 하루·이틀은 앞 주차에 붙는다(마지막 주차 = 월~다음 주 월·화).
|
||||||
|
예: 2026년 10월(1일 목·31일 토) = 10/1~4 · 5~11 · 12~18 · 19~25 · 26~31.
|
||||||
|
월간 목표·누적은 늘 1일~말일."""
|
||||||
|
first = date(year, month, 1)
|
||||||
|
last = month_last_day(year, month)
|
||||||
|
wd = first.weekday()
|
||||||
|
end = first + timedelta(days=6 - wd + (7 if wd >= 5 else 0))
|
||||||
|
out = [(first, end)]
|
||||||
|
s = end + timedelta(days=1)
|
||||||
|
while s <= last:
|
||||||
|
out.append((s, min(s + timedelta(days=6), last)))
|
||||||
|
s += timedelta(days=7)
|
||||||
|
if len(out) > 1 and last.weekday() <= 1: # 말일이 월·화 — 앞 주차에 붙인다
|
||||||
|
out.pop()
|
||||||
|
out[-1] = (out[-1][0], last)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def week_period(d: date) -> tuple[date, date]:
|
||||||
|
"""그 날짜가 든 주차(시작일, 끝일)."""
|
||||||
|
return next(p for p in month_weeks(d.year, d.month) if p[0] <= d <= p[1])
|
||||||
|
|
||||||
|
|
||||||
|
def prev_week_period(start: date) -> tuple[date, date]:
|
||||||
|
"""바로 앞 주차(앞 달 마지막 주차일 수 있다) — 회의록의 "지난주"."""
|
||||||
|
return week_period(start - timedelta(days=1))
|
||||||
|
|
||||||
|
|
||||||
|
def week_number(start: date) -> int:
|
||||||
|
"""주차 시작일 → 그 달 몇 주차(1부터). 주차 시작일이 아니면 그 날짜가 든 주차."""
|
||||||
|
return next(i + 1 for i, (a, b) in enumerate(month_weeks(start.year, start.month)) if a <= start <= b)
|
||||||
|
|
||||||
|
|
||||||
|
def calendar_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||||
|
"""작은 달력용 — 그 달 날짜가 하나라도 든 줄(월요일 시작) 전부(1일이 든 줄부터 말일이 든 줄까지)."""
|
||||||
|
first, last = date(year, month, 1), month_last_day(year, month)
|
||||||
|
out, mon = [], week_monday(first)
|
||||||
|
while mon <= last:
|
||||||
|
out.append((mon, mon + timedelta(days=6)))
|
||||||
|
mon += timedelta(days=7)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def validate_week_start(v: Any) -> date:
|
||||||
|
"""회의록 시작일(날짜) — 020 부터 월요일이 아닐 수 있다. 주차 시작일인지는 validate_period_start."""
|
||||||
|
try:
|
||||||
|
d = date.fromisoformat(str(v).strip()[:10])
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError("주 시작일이 올바르지 않습니다.")
|
||||||
|
if not 2000 <= d.year <= 2100:
|
||||||
|
raise ValueError("주 시작일이 올바르지 않습니다.")
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def validate_period_start(v: Any) -> date:
|
||||||
|
"""주차 시작일만(month_weeks 의 시작일) — 새 회의록·주차별 목표."""
|
||||||
|
d = validate_week_start(v)
|
||||||
|
if week_period(d)[0] != d:
|
||||||
|
raise ValueError("주차 시작일이 아닙니다. 새로고침해 주세요.")
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def _korean_amount(s: str) -> float:
|
||||||
|
""""1억2천만"·"3천만"·"1.5억"·"120만"·"3천5백" → 숫자. 단위 없는 숫자는 그대로. 틀리면 ValueError."""
|
||||||
|
def small(t: str) -> float: # 만 아래 자리 — 천·백·십
|
||||||
|
val = 0.0
|
||||||
|
for unit, mul in (("천", 1_000), ("백", 100), ("십", 10)):
|
||||||
|
if unit in t:
|
||||||
|
a, t = t.split(unit, 1)
|
||||||
|
val += (float(a) if a else 1.0) * mul
|
||||||
|
return val + (float(t) if t else 0.0)
|
||||||
|
|
||||||
|
total, rest = 0.0, s
|
||||||
|
for unit, mul in (("억", 100_000_000), ("만", 10_000)):
|
||||||
|
if unit in rest:
|
||||||
|
a, rest = rest.split(unit, 1)
|
||||||
|
total += (small(a) if a else 1.0) * mul
|
||||||
|
return total + small(rest)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_meeting_amount(v: Any) -> int | None:
|
||||||
|
"""금액(원) — 쉼표·공백·"원" 은 떼고, "120만"·"1.5억"·"3천만"·"1억2천만" 도 읽는다. 빈값은 None(=지움)."""
|
||||||
|
s = norm_str(v).replace(",", "").replace(" ", "").rstrip("원")
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
f = _korean_amount(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"금액은 숫자로 입력하세요(예: 1,200,000 · 120만 · 1.5억 · 3천만): {v}")
|
||||||
|
if f != f or abs(f) >= 1e15:
|
||||||
|
raise ValueError(f"금액 범위를 벗어났습니다: {v}")
|
||||||
|
return int(round(f))
|
||||||
|
|
||||||
|
|
||||||
|
def validate_meeting_text(v: Any, *, limit: int = MEETING_TEXT_MAX, what: str = "내용") -> str:
|
||||||
|
s = str(v or "").replace("\r\n", "\n").strip()
|
||||||
|
if len(s) > limit:
|
||||||
|
raise ValueError(f"{what}은(는) {limit}자까지 쓸 수 있습니다.")
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def validate_meeting_status(v: Any) -> str:
|
||||||
|
s = norm_str(v)
|
||||||
|
if s not in MEETING_STATUS:
|
||||||
|
raise ValueError("평가 값이 올바르지 않습니다.")
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def sales_unit_multiplier(unit: str) -> int | None:
|
||||||
|
"""목표 표의 매출 단위 글자 → 원 배수("백만원" → 1,000,000). 모르는 단위면 None(원 환산 안 함)."""
|
||||||
|
u = norm_str(unit).replace(" ", "").rstrip("원") or ""
|
||||||
|
table = {"": 1, "천": 1_000, "만": 10_000, "십만": 100_000, "백만": 1_000_000, "천만": 10_000_000, "억": 100_000_000}
|
||||||
|
return table.get(u)
|
||||||
|
|
||||||
|
|
||||||
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
|
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
|
||||||
return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}"
|
return f"[DBX 프로젝트] 업무 배정: {project_name} · {task_title} → {assignee}"
|
||||||
|
|
||||||
|
|
||||||
def build_subject_completed(*, project_name: str, task_title: str) -> str:
|
def build_subject_completed(*, project_name: str, task_title: str) -> str:
|
||||||
return f"[DBX 프로젝트] 작업 완료: {project_name} · {task_title}"
|
return f"[DBX 프로젝트] 업무 완료: {project_name} · {task_title}"
|
||||||
|
|
||||||
|
|
||||||
def build_subject_project_done(*, project_name: str) -> str:
|
def build_subject_project_done(*, project_name: str) -> str:
|
||||||
@@ -515,6 +898,23 @@ _DESC_ALLOWED_CLASS: dict[str, str] = {"span": _MENTION_CLASS, "ul": "pj-checkli
|
|||||||
# 허용 태그 목록에 없어 태그는 이미 안 남지만, HTMLParser는 이 둘의 내용을
|
# 허용 태그 목록에 없어 태그는 이미 안 남지만, HTMLParser는 이 둘의 내용을
|
||||||
# 별도 데이터로 넘기므로 handle_data 에서 따로 걸러야 한다.
|
# 별도 데이터로 넘기므로 handle_data 에서 따로 걸러야 한다.
|
||||||
_DESC_RAW_TEXT_TAGS: frozenset[str] = frozenset({"script", "style"})
|
_DESC_RAW_TEXT_TAGS: frozenset[str] = frozenset({"script", "style"})
|
||||||
|
# 글자 색·크기(서식 도구, 2026-10-08) — 평범한 span 의 style 에서 이 둘만, 정해진 형식만 남긴다.
|
||||||
|
_DESC_STYLE_COLOR = re.compile(r"^(#[0-9a-f]{3}|#[0-9a-f]{6}|rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\))$", re.I)
|
||||||
|
DESC_FONT_SIZES: frozenset[str] = frozenset({"12px", "18px", "22px", "28px"})
|
||||||
|
|
||||||
|
|
||||||
|
def desc_inline_style(value: str) -> str:
|
||||||
|
"""span style → "color: …; font-size: …" 중 허용된 것만(나머지 선언·url()·expression 등은 버림)."""
|
||||||
|
kept: list[str] = []
|
||||||
|
for decl in (value or "").split(";"):
|
||||||
|
if ":" not in decl:
|
||||||
|
continue
|
||||||
|
prop, val = (x.strip().lower() for x in decl.split(":", 1))
|
||||||
|
if prop == "color" and _DESC_STYLE_COLOR.match(val) and not any(k.startswith("color:") for k in kept):
|
||||||
|
kept.append(f"color: {val}")
|
||||||
|
elif prop == "font-size" and val in DESC_FONT_SIZES and not any(k.startswith("font-size:") for k in kept):
|
||||||
|
kept.append(f"font-size: {val}")
|
||||||
|
return "; ".join(kept)
|
||||||
|
|
||||||
|
|
||||||
def _desc_escape_text(text: str) -> str:
|
def _desc_escape_text(text: str) -> str:
|
||||||
@@ -571,7 +971,7 @@ class _DescriptionSanitizer(HTMLParser):
|
|||||||
# span 은 멘션 칩일 때만 속성을 갖는다 — class 가 pj-mention 이 아니면
|
# span 은 멘션 칩일 때만 속성을 갖는다 — class 가 pj-mention 이 아니면
|
||||||
# data-email 까지 통째로 버린다(평범한 span 으로만 남는다).
|
# data-email 까지 통째로 버린다(평범한 span 으로만 남는다).
|
||||||
if tag == "span" and (dict(attrs).get("class") or "").strip() != _MENTION_CLASS:
|
if tag == "span" and (dict(attrs).get("class") or "").strip() != _MENTION_CLASS:
|
||||||
allowed = frozenset()
|
allowed = frozenset({"style"}) # 평범한 span — 글자 색·크기만(desc_inline_style)
|
||||||
kept: list[str] = []
|
kept: list[str] = []
|
||||||
for name, value in attrs:
|
for name, value in attrs:
|
||||||
if name not in allowed:
|
if name not in allowed:
|
||||||
@@ -587,6 +987,10 @@ class _DescriptionSanitizer(HTMLParser):
|
|||||||
continue
|
continue
|
||||||
if name == "data-checked" and value.strip() != "true":
|
if name == "data-checked" and value.strip() != "true":
|
||||||
continue
|
continue
|
||||||
|
if name == "style":
|
||||||
|
value = desc_inline_style(value)
|
||||||
|
if not value:
|
||||||
|
continue
|
||||||
kept.append(f'{name}="{_desc_escape_attr(value)}"')
|
kept.append(f'{name}="{_desc_escape_attr(value)}"')
|
||||||
attr_text = (" " + " ".join(kept)) if kept else ""
|
attr_text = (" " + " ".join(kept)) if kept else ""
|
||||||
self.out.append(f"<{tag}{attr_text}>")
|
self.out.append(f"<{tag}{attr_text}>")
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<div class="pj-goal-format" id="pj-goal-format" role="toolbar" aria-label="선택한 글자 서식" hidden>
|
||||||
|
<div class="pj-goal-format-group pj-goal-color-picker">
|
||||||
|
<button type="button" class="pj-goal-format-btn pj-goal-color-toggle" data-goal-format="color" aria-label="글자 색상" title="글자 색상" aria-expanded="false" aria-controls="pj-goal-color-grid" disabled><span class="pj-goal-color-letter" aria-hidden="true">가<span class="pj-goal-color-preview"></span></span><svg class="pj-goal-format-chevron" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><path d="m2 4 3 3 3-3"/></svg></button>
|
||||||
|
<div class="pj-goal-color-grid" id="pj-goal-color-grid" role="group" aria-label="글자 색상 선택" hidden>
|
||||||
|
{% for color in ('#000000', '#4B5563', '#9CA3AF', '#DC2626', '#EA580C', '#CA8A04', '#16A34A', '#0891B2', '#2563EB', '#7C3AED', '#DB2777', '#FFFFFF') %}
|
||||||
|
<button type="button" class="pj-goal-text-swatch" data-goal-color="{{ color }}" style="--swatch: {{ color }}" title="{{ color }}" aria-label="{{ color }}" aria-pressed="false" disabled></button>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="pj-goal-format-group" role="group" aria-label="글자 크기">
|
||||||
|
<button type="button" class="pj-goal-format-btn" data-goal-format="size-up" aria-label="글자 크기 2px 키우기" title="글자 크기 2px 키우기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 9V2M2 5l3-3 3 3"/></svg></button>
|
||||||
|
<button type="button" class="pj-goal-format-btn" data-goal-format="size-down" aria-label="글자 크기 2px 줄이기" title="글자 크기 2px 줄이기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 2v7M2 6l3 3 3-3"/></svg></button>
|
||||||
|
<output class="pj-goal-size-value" data-goal-format="size" aria-label="선택한 글자 크기">14px</output>
|
||||||
|
</div>
|
||||||
|
<div class="pj-goal-format-group" role="group" aria-label="글자 모양">
|
||||||
|
{% for key, label in (('bold', '굵게'), ('italic', '기울임'), ('underline', '밑줄')) %}
|
||||||
|
<button type="button" class="pj-goal-format-btn" data-goal-format="{{ key }}" aria-label="{{ label }}" title="{{ label }}" aria-pressed="false" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span></button>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<div class="pj-goal-format-group" role="group" aria-label="서식 초기화">
|
||||||
|
<button type="button" class="pj-goal-format-btn" data-goal-format="reset" aria-label="서식 초기화" title="서식 초기화" disabled><svg class="pj-goal-reset-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16 3 5 5a2 2 0 0 1 0 3L11 21H7l-4-4a2 2 0 0 1 0-3L13 3a2 2 0 0 1 3 0Z"/><path d="m8 9 7 7M11 21h10"/></svg></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{# 설명란 서식 도구(작업 창·긴급 공지 관리 공용). fmtbar_id·img_input_id 를 주면 그 id 로(기본 = 작업 창 id).
|
||||||
|
동작은 project.js createDescEditor — 버튼 data-cmd 를 그대로 쓴다. #}
|
||||||
|
{# 서식 도구 — 모든 버튼을 같은 아이콘 글꼴(Material Symbols)·같은 크기로 그려
|
||||||
|
한 줄에 딱 맞춰 선다(예전엔 글자·이모지가 섞여 높이가 들쭉날쭉했다). #}
|
||||||
|
<div class="pj-desc-fmtbar" id="{{ fmtbar_id or 'pj-desc-fmtbar' }}">
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="bold" title="굵게 (Ctrl+B)"><span class="material-symbols-outlined">format_bold</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
|
||||||
|
{# 글자 색·크기(2026-10-08) — 누르면 고르는 창(body 에 붙음). 저장 때 서버가 span 의 color·font-size 만 남긴다 #}
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="textColor" title="글자 색"><span class="material-symbols-outlined">format_color_text</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="textSize" title="글자 크기"><span class="material-symbols-outlined">format_size</span></button>
|
||||||
|
<span class="pj-desc-fmtsep"></span>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertCheckbox" title="체크박스 넣기"><span class="material-symbols-outlined">check_box</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="formatBlock" data-arg="blockquote" title="인용구"><span class="material-symbols-outlined">format_quote</span></button>
|
||||||
|
<span class="pj-desc-fmtsep"></span>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="createLink" title="링크 삽입"><span class="material-symbols-outlined">link</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="removeFormat" title="서식 지우기"><span class="material-symbols-outlined">format_clear</span></button>
|
||||||
|
<span class="pj-desc-fmtsep"></span>
|
||||||
|
<label class="pj-desc-fmtbtn" id="{{ (fmtbar_id ~ '-imgbtn') if fmtbar_id else 'pj-desc-imgbtn' }}" title="이미지 추가"><span class="material-symbols-outlined">image</span><input type="file" id="{{ img_input_id or 'pj-desc-img-input' }}" accept="image/*" hidden /></label>
|
||||||
|
</div>
|
||||||
@@ -34,3 +34,4 @@
|
|||||||
title="프로젝트 관리 도움말" aria-label="프로젝트 관리 도움말">
|
title="프로젝트 관리 도움말" aria-label="프로젝트 관리 도움말">
|
||||||
<span class="material-symbols-outlined">help</span>
|
<span class="material-symbols-outlined">help</span>
|
||||||
</a>
|
</a>
|
||||||
|
{% include "project/_options.html" %}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{# 오른쪽 회의록 전용 문서. 공통 메뉴를 다시 만들지 않고 회의록의 기존 편집 기능을 그대로 사용한다. #}
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="ko" class="pj-meeting-content">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>{{ page_title or '주간 회의록' }}</title>
|
||||||
|
<link rel="stylesheet" href="/static/erp.css?v=20260615b" />
|
||||||
|
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260930a" />
|
||||||
|
{% block head_extra %}{% endblock %}
|
||||||
|
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
|
||||||
|
<script>
|
||||||
|
try { document.documentElement.dataset.pjFont = localStorage.getItem('pj_font') || 'system'; } catch (_) {}
|
||||||
|
window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};
|
||||||
|
</script>
|
||||||
|
<script src="/static/project-meeting-panel.js?v=20261004a" defer></script>
|
||||||
|
</head>
|
||||||
|
<body class="erp-body">
|
||||||
|
<main class="erp-page">{% block content %}{% endblock %}</main>
|
||||||
|
<script src="/static/erp-dialog.js?v=20260930a"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -2,12 +2,12 @@
|
|||||||
project.js initMemberTasks() 가 배선. project/mytasks/inbox 공용. #}
|
project.js initMemberTasks() 가 배선. project/mytasks/inbox 공용. #}
|
||||||
<div class="pj-modal" id="pj-modal-member-tasks" hidden>
|
<div class="pj-modal" id="pj-modal-member-tasks" hidden>
|
||||||
<div class="pj-modal-card pj-mt-card">
|
<div class="pj-modal-card pj-mt-card">
|
||||||
<h3 id="pj-mt-title">작업</h3>
|
<h3 id="pj-mt-title">업무</h3>
|
||||||
<p class="pj-modal-hint">더블클릭하면 작업 편집 창이 열립니다.</p>
|
<p class="pj-modal-hint">더블클릭하면 업무 편집 창이 열립니다.</p>
|
||||||
<div class="pj-mt-head" id="pj-mt-head">
|
<div class="pj-mt-head" id="pj-mt-head">
|
||||||
<span class="pj-mt-h" data-sort="project">프로젝트<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="project">프로젝트<span class="pj-mt-sort-icon"></span></span>
|
||||||
<span class="pj-mt-h" data-sort="stage">섹션<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="stage">섹션<span class="pj-mt-sort-icon"></span></span>
|
||||||
<span class="pj-mt-h" data-sort="title">작업<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="title">업무<span class="pj-mt-sort-icon"></span></span>
|
||||||
<span class="pj-mt-h" data-sort="due">마감일<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="due">마감일<span class="pj-mt-sort-icon"></span></span>
|
||||||
</div>
|
</div>
|
||||||
<ul class="pj-mt-list" id="pj-mt-list"></ul>
|
<ul class="pj-mt-list" id="pj-mt-list"></ul>
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션">
|
||||||
|
<span class="material-symbols-outlined">settings</span>
|
||||||
|
</button>
|
||||||
|
<dialog class="pj-options-dialog" id="pj-options-dialog" aria-labelledby="pj-options-title">
|
||||||
|
<form id="pj-options-form">
|
||||||
|
<h2 id="pj-options-title">Project 옵션</h2>
|
||||||
|
<label for="pj-options-font">폰트</label>
|
||||||
|
<select id="pj-options-font" name="font">
|
||||||
|
<option value="system">기본 시스템 폰트</option>
|
||||||
|
<option value="pretendard">프리텐다드</option>
|
||||||
|
<option value="nanum-square">나눔 스퀘어</option>
|
||||||
|
<option value="nanum-square-neo">나눔 스퀘어 네오</option>
|
||||||
|
<option value="nanum-square-round">나눔 스퀘어 라운드</option>
|
||||||
|
</select>
|
||||||
|
<div class="pj-options-preview" id="pj-options-preview">프로젝트와 목표를 한눈에<br><b>Project · 업무 이름 · 가나다 123</b></div>
|
||||||
|
<p>이 브라우저의 모든 Project 화면에 적용됩니다.</p>
|
||||||
|
{% if user and user.is_super_admin %}<p class="pj-options-notice"><a class="pj-btn" href="/notice/"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">campaign</span> 긴급 공지 만들기·관리</a> <small>ERP 전체 화면 가운데에 띄우는 공지(수퍼관리자)</small></p>{% endif %}
|
||||||
|
<p class="pj-options-error" id="pj-options-error" role="alert" hidden></p>
|
||||||
|
<div class="pj-options-actions">
|
||||||
|
<button type="button" class="pj-btn" id="pj-options-cancel">취소</button>
|
||||||
|
<button type="submit" class="pj-btn pj-btn-primary" id="pj-options-save">저장</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
<script>
|
||||||
|
try {
|
||||||
|
var pf = localStorage.getItem("pj_font") || "system";
|
||||||
|
if (["system", "pretendard", "nanum-square", "nanum-square-neo", "nanum-square-round"].indexOf(pf) >= 0)
|
||||||
|
document.documentElement.dataset.pjFont = pf;
|
||||||
|
} catch (_) {}
|
||||||
|
</script>
|
||||||
|
<script src="/static/project-options.js?v=20261002g" defer></script>
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{# ── 프로젝트 모듈 좌측 사이드바 (공용) ──────────────────────────────
|
{# ── 프로젝트 모듈 좌측 사이드바 (공용) ──────────────────────────────
|
||||||
수신함·내 업무·휴지통·프로젝트 화면이 함께 쓴다 — 어느 화면이든 프로젝트
|
수신함·내 업무·휴지통·프로젝트 화면이 함께 쓴다 — 어느 화면이든 프로젝트
|
||||||
목록은 똑같다(관리자: 드래그 순서 변경·✎ 수정·× 삭제·우클릭 메뉴).
|
목록은 똑같다(Pro user 이상: 드래그 순서 변경·✎ 수정·× 삭제·우클릭 메뉴).
|
||||||
|
|
||||||
변수:
|
변수:
|
||||||
mention_unread 미확인 @태그 개수 (수신함 배지)
|
mention_unread 미확인 @태그 개수 (수신함 배지)
|
||||||
@@ -10,20 +10,24 @@
|
|||||||
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
|
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
|
||||||
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
|
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
|
||||||
goal_year_active 목표 화면에서 보고 있는 연도
|
goal_year_active 목표 화면에서 보고 있는 연도
|
||||||
is_admin 프로젝트 생성/수정/삭제 권한
|
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·전체 보기·휴지통·전체 멤버·연도 추가
|
||||||
|
pj_admin Admin 이상 — 남이 만든 프로젝트도 삭제(그 밖은 만든 사람만)
|
||||||
목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림),
|
목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림),
|
||||||
새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #}
|
새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #}
|
||||||
{# 날짜 팝업(openDatePopover)이 공휴일을 빨강으로 칠할 때 쓰는 표 — 이 사이드바는
|
{# 날짜 팝업(openDatePopover)이 공휴일을 빨강으로 칠할 때 쓰는 표 — 이 사이드바는
|
||||||
프로젝트 관리의 모든 화면에 들어가므로 여기서 한 번 넘긴다(main.py 의 Jinja 전역). #}
|
프로젝트 관리의 모든 화면에 들어가므로 여기서 한 번 넘긴다(main.py 의 Jinja 전역). #}
|
||||||
<script>window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
<script>window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||||
<aside class="pj-side" data-is-admin="{{ 'true' if is_admin else 'false' }}"
|
{# 모든 프로젝트 화면에서 같은 회의록 트리를 사용한다. #}
|
||||||
|
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
|
||||||
|
<script src="/static/project-goal-nav.js?v=20261004d" defer></script>
|
||||||
|
<aside class="pj-side" data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||||
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
|
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
|
||||||
data-me="{{ user.email }}">
|
data-me="{{ user.email }}">
|
||||||
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(하위 업무 포함).
|
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(세부 업무 포함).
|
||||||
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
|
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
|
||||||
<div class="pj-side-search">
|
<div class="pj-side-search">
|
||||||
<span class="material-symbols-outlined pj-side-search-ic">search</span>
|
<span class="material-symbols-outlined pj-side-search-ic">search</span>
|
||||||
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="작업 전체 검색" />
|
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="업무 전체 검색" />
|
||||||
<div class="pj-search-results" id="pj-search-results" hidden></div>
|
<div class="pj-search-results" id="pj-search-results" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
<!-- 아사나처럼 맨 위에 개인 메뉴(수신함 / 내 업무). 내 업무는 접었다 펴는
|
<!-- 아사나처럼 맨 위에 개인 메뉴(수신함 / 내 업무). 내 업무는 접었다 펴는
|
||||||
@@ -35,14 +39,25 @@
|
|||||||
<span class="pj-side-navbadge" id="pj-mention-badge"
|
<span class="pj-side-navbadge" id="pj-mention-badge"
|
||||||
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
||||||
</a>
|
</a>
|
||||||
|
{# 전체 보기(2026-10-08, Pro user 이상 — 멤버인 프로젝트 범위) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
|
||||||
|
화면을 ?scope=all 로 연다 — 볼 수 있는 모든 프로젝트의 작업. 프로젝트 화면에서는 project.js 가 새로고침 없이 바꾼다. #}
|
||||||
|
{% if pj_pro %}
|
||||||
|
{% set _all_pid = current_pid or ((nav_projects | rejectattr("status", "equalto", "completed") | list | first or {}).id or 0) %}
|
||||||
|
{% if _all_pid %}
|
||||||
|
<a class="pj-side-navlink" id="pj-side-allview" href="/project/p/{{ _all_pid }}?scope=all">
|
||||||
|
<span class="material-symbols-outlined pj-side-navic">apps</span>
|
||||||
|
<span class="pj-side-navtext">전체 보기</span>
|
||||||
|
</a>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
<a class="pj-side-navlink {% if side_active == 'mytasks' %}is-active{% endif %}" href="/project/">
|
<a class="pj-side-navlink {% if side_active == 'mytasks' %}is-active{% endif %}" href="/project/">
|
||||||
<span class="material-symbols-outlined pj-side-navic">checklist</span>
|
<span class="material-symbols-outlined pj-side-navic">checklist</span>
|
||||||
<span class="pj-side-navtext">내 작업</span>
|
<span class="pj-side-navtext">내 업무</span>
|
||||||
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
|
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
|
||||||
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
|
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
|
||||||
</a>
|
</a>
|
||||||
{# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #}
|
{# 휴지통 — Pro user 이상만 보이고(화면·복구 API 도 같음), 지운 업무를 3개월 보관. #}
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash">
|
<a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash">
|
||||||
<span class="material-symbols-outlined pj-side-navic">delete</span>
|
<span class="material-symbols-outlined pj-side-navic">delete</span>
|
||||||
<span class="pj-side-navtext">휴지통</span>
|
<span class="pj-side-navtext">휴지통</span>
|
||||||
@@ -50,7 +65,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
{# 목표 — 누르면 바로 아래에 연도가 펼쳐지고, 연도를 누르면 오른쪽에 그해 전체 목표
|
{# 목표 — 누르면 바로 아래에 연도가 펼쳐지고, 연도를 누르면 오른쪽에 그해 전체 목표
|
||||||
(/project/goals/{연도}). 펼침 상태는 localStorage(pj_goal_open), 목표 화면에서는 항상 펼침.
|
(/project/goals/{연도}). 펼침 상태는 localStorage(pj_goal_open), 목표 화면에서는 항상 펼침.
|
||||||
연도 추가는 관리자만(마이그레이션 013). #}
|
연도 추가는 Pro user 이상(마이그레이션 013). #}
|
||||||
{% set goal_open = side_active == 'goals' %}
|
{% set goal_open = side_active == 'goals' %}
|
||||||
<div class="pj-side-goal{% if goal_open %} is-open{% endif %}" id="pj-side-goal"
|
<div class="pj-side-goal{% if goal_open %} is-open{% endif %}" id="pj-side-goal"
|
||||||
data-force-open="{{ 'true' if goal_open else 'false' }}">
|
data-force-open="{{ 'true' if goal_open else 'false' }}">
|
||||||
@@ -62,10 +77,20 @@
|
|||||||
</button>
|
</button>
|
||||||
<div class="pj-side-goal-years" id="pj-side-goal-years"{% if not goal_open %} hidden{% endif %}>
|
<div class="pj-side-goal-years" id="pj-side-goal-years"{% if not goal_open %} hidden{% endif %}>
|
||||||
{% for y in (goal_years or []) %}
|
{% for y in (goal_years or []) %}
|
||||||
|
<div class="pj-side-goal-branch" data-goal-year="{{ y }}">
|
||||||
|
{# 화살표는 하위 월을 접고 펼치고, 연도 글자는 기존 목표 화면을 연다. #}
|
||||||
|
<div class="pj-side-goal-year-row">
|
||||||
|
<button type="button" class="pj-side-goal-year-toggle" aria-expanded="true"
|
||||||
|
aria-controls="pj-side-meeting-months-{{ y }}" aria-label="{{ y }}년 하위 월 접기" title="하위 월 접기">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">chevron_right</span>
|
||||||
|
</button>
|
||||||
<a class="pj-side-goal-year{% if side_active == 'goals' and y == goal_year_active %} is-active{% endif %}"
|
<a class="pj-side-goal-year{% if side_active == 'goals' and y == goal_year_active %} is-active{% endif %}"
|
||||||
href="/project/goals/{{ y }}">{{ y }}년</a>
|
href="/project/goals/{{ y }}">{{ y }}년</a>
|
||||||
|
</div>
|
||||||
|
<div class="pj-side-meeting-months" id="pj-side-meeting-months-{{ y }}" data-current-week="{{ week if goal_month is defined else '' }}"></div>
|
||||||
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<button type="button" class="pj-side-goal-add" id="pj-goal-year-add"
|
<button type="button" class="pj-side-goal-add" id="pj-goal-year-add"
|
||||||
data-next="{{ ((goal_years or [0]) | max) + 1 }}">+ 연도 추가</button>
|
data-next="{{ ((goal_years or [0]) | max) + 1 }}">+ 연도 추가</button>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -76,23 +101,23 @@
|
|||||||
<div class="pj-side-block pj-tree-block">
|
<div class="pj-side-block pj-tree-block">
|
||||||
<div class="pj-side-head">
|
<div class="pj-side-head">
|
||||||
<span>프로젝트</span>
|
<span>프로젝트</span>
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<button type="button" class="pj-icon-btn" id="pj-new-project-side" title="새 프로젝트">+</button>
|
<button type="button" class="pj-icon-btn" id="pj-new-project-side" title="새 프로젝트">+</button>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% macro nav_li(p) %}
|
{% macro nav_li(p) %}
|
||||||
<li class="pj-tree-li" data-id="{{ p.id }}"{% if is_admin %} draggable="true"{% endif %}
|
<li class="pj-tree-li" data-id="{{ p.id }}"{% if pj_pro %} draggable="true"{% endif %}
|
||||||
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
|
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
|
||||||
data-start="{{ p.start_date or '' }}" data-due="{{ p.due_date or '' }}"
|
data-start="{{ p.start_date or '' }}" data-due="{{ p.due_date or '' }}"
|
||||||
data-color="{{ p.color }}" data-status="{{ p.status or 'active' }}"
|
data-color="{{ p.color }}" data-status="{{ p.status or 'active' }}"
|
||||||
data-creator="{{ p.created_by or '' }}" data-icon="{{ p.icon or '' }}">
|
data-creator="{{ p.created_by or '' }}" data-icon="{{ p.icon or '' }}">
|
||||||
<div class="pj-tree-row {% if p.id == current_pid %}is-active{% endif %}">
|
<div class="pj-tree-row {% if p.id == current_pid %}is-active{% endif %}">
|
||||||
{% if is_admin %}<span class="pj-tree-handle" title="드래그로 순서 변경">⣿</span>{% endif %}
|
{% if pj_pro %}<span class="pj-tree-handle" title="드래그로 순서 변경">⣿</span>{% endif %}
|
||||||
<a class="pj-tree-link" href="/project/p/{{ p.id }}"{% if is_admin %} draggable="false"{% endif %}>
|
<a class="pj-tree-link" href="/project/p/{{ p.id }}"{% if pj_pro %} draggable="false"{% endif %}>
|
||||||
<span class="pj-tree-avatar{% if p.icon %} has-icon{% endif %}" style="background: {{ p.color }}">{% if p.icon %}<span class="material-symbols-outlined pj-proj-ic">{{ p.icon }}</span>{% else %}{{ p.name[0] | upper }}{% endif %}</span>
|
<span class="pj-tree-avatar{% if p.icon %} has-icon{% endif %}" style="background: {{ p.color }}">{% if p.icon %}{% set _a = p.icon.startswith("asana:") %}<span class="material-symbols-outlined pj-proj-ic{% if _a %} pj-ic-asana{% endif %}">{{ p.icon[6:] if _a else p.icon }}</span>{% else %}{{ p.name[0] | upper }}{% endif %}</span>
|
||||||
<span class="pj-tree-name">{{ p.name }}</span>
|
<span class="pj-tree-name">{{ p.name }}</span>
|
||||||
</a>
|
</a>
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<span class="pj-tree-acts">
|
<span class="pj-tree-acts">
|
||||||
<button type="button" class="pj-icon-btn pj-tree-edit" data-id="{{ p.id }}"
|
<button type="button" class="pj-icon-btn pj-tree-edit" data-id="{{ p.id }}"
|
||||||
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
|
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
|
||||||
@@ -121,11 +146,11 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 전체 멤버 — 등록된 전체 직원(프로젝트 권한 보유자). 관리자 전용
|
<!-- 전체 멤버 — 등록된 전체 직원(프로젝트 권한 보유자). Pro user 이상
|
||||||
(/api/all-users 도 관리자만). 아이콘 클릭 시 그 사람이 담당자인 업무를
|
(/api/all-users 는 @태그 후보로 누구나 부른다). 아이콘 클릭 시 그 사람이 담당자인 업무를
|
||||||
팝업으로 보여준다(프로젝트/세션/마감일). 수신함·내 업무·프로젝트 화면
|
팝업으로 보여준다(프로젝트/세션/마감일). 수신함·내 업무·프로젝트 화면
|
||||||
모두에서 보인다 — 팝업 마크업은 _member_tasks_modal.html. -->
|
모두에서 보인다 — 팝업 마크업은 _member_tasks_modal.html. -->
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<div class="pj-side-block">
|
<div class="pj-side-block">
|
||||||
<div class="pj-side-head"><span>전체 멤버</span></div>
|
<div class="pj-side-head"><span>전체 멤버</span></div>
|
||||||
<div class="pj-allmembers-grid" id="pj-allmembers-grid">불러오는 중…</div>
|
<div class="pj-allmembers-grid" id="pj-allmembers-grid">불러오는 중…</div>
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
{# ── 좌측 프로젝트 목록(project/_side.html)용 모달 (공용) ──────────────
|
{# ── 좌측 프로젝트 목록(project/_side.html)용 모달 (공용) ──────────────
|
||||||
"+" 새 프로젝트 / ✎ 프로젝트 수정 — 수신함·내 업무·휴지통·프로젝트 화면이
|
"+" 새 프로젝트 / ✎ 프로젝트 수정 — 수신함·내 업무·휴지통·프로젝트 화면이
|
||||||
모두 include 한다(동작은 project.js 의 initSideTree). 관리자만 쓰므로
|
모두 include 한다(동작은 project.js 의 initSideTree). Pro user 이상만 쓰므로
|
||||||
관리자에게만 그린다. 색상 원은 window.PJ_COLORS(color_palette, 32색),
|
그들에게만 그린다. 색상 원은 window.PJ_COLORS(color_palette, 32색),
|
||||||
아이콘은 window.PJ_ICONS(project_icons — Material Symbols 이름). #}
|
아이콘은 window.PJ_ICONS(project_icons — Material Symbols 이름). #}
|
||||||
<script>
|
<script>
|
||||||
window.PJ_COLORS = {{ color_palette | tojson }};
|
window.PJ_COLORS = {{ color_palette | tojson }};
|
||||||
window.PJ_ICONS = {{ (project_icons or []) | tojson }};
|
window.PJ_ICONS = {{ (project_icons or []) | tojson }};
|
||||||
|
window.PJ_ASANA_ICONS = {{ (project_asana_icons or []) | tojson }}; {# 아사나 아이콘 탭 — 값은 "asana:" + 이름 #}
|
||||||
</script>
|
</script>
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<!-- 새 프로젝트 모달 — 좌측 프로젝트 목록의 + 버튼 -->
|
<!-- 새 프로젝트 모달 — 좌측 프로젝트 목록의 + 버튼 -->
|
||||||
<div class="pj-modal" id="pj-modal-project" hidden>
|
<div class="pj-modal" id="pj-modal-project" hidden>
|
||||||
<div class="pj-modal-card">
|
<div class="pj-modal-card">
|
||||||
@@ -21,12 +22,13 @@
|
|||||||
<div class="pj-field-label">색상
|
<div class="pj-field-label">색상
|
||||||
<span class="pj-color-palette" id="pj-f-colors"></span>
|
<span class="pj-color-palette" id="pj-f-colors"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-field-label">아이콘
|
<div class="pj-field-label">아이콘<span class="pj-icon-tabs"></span>
|
||||||
<div class="pj-icon-palette" id="pj-f-icons"></div>
|
<div class="pj-icon-palette" id="pj-f-icons"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-field-label">멤버
|
<div class="pj-field-label">멤버
|
||||||
<div class="pj-member-picker" id="pj-f-members">불러오는 중…</div>
|
<div class="pj-member-picker" id="pj-f-members">불러오는 중…</div>
|
||||||
</div>
|
</div>
|
||||||
|
<p class="pj-modal-msg" id="pj-f-project-msg" role="status" hidden></p>
|
||||||
<div class="pj-modal-actions">
|
<div class="pj-modal-actions">
|
||||||
<button type="button" class="pj-btn" data-close>취소</button>
|
<button type="button" class="pj-btn" data-close>취소</button>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-project">만들기</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-project">만들기</button>
|
||||||
@@ -49,7 +51,7 @@
|
|||||||
<div class="pj-field-label">색상
|
<div class="pj-field-label">색상
|
||||||
<span class="pj-color-palette" id="pj-e-colors"></span>
|
<span class="pj-color-palette" id="pj-e-colors"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-field-label">아이콘
|
<div class="pj-field-label">아이콘<span class="pj-icon-tabs"></span>
|
||||||
<div class="pj-icon-palette" id="pj-e-icons"></div>
|
<div class="pj-icon-palette" id="pj-e-icons"></div>
|
||||||
</div>
|
</div>
|
||||||
<label class="pj-time-toggle">
|
<label class="pj-time-toggle">
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}
|
||||||
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
|
||||||
|
|
||||||
|
{%- macro won(v) -%}{% if v is not none %}{{ "{:,}".format(v) }}{% endif %}{%- endmacro -%}
|
||||||
|
{%- macro num(v) -%}{% if v is not none %}{% if v == v | int %}{{ "{:,}".format(v | int) }}{% else %}{{ "{:,.2f}".format(v) }}{% endif %}{% endif %}{%- endmacro -%}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{% set h = head if head is defined and head else {} %}
|
||||||
|
{% set unk = h.unknown or [] %}
|
||||||
|
{#- 머리 숫자 — 목표 표 매출 단위(예: 백만원)로, 원이거나 모르는 단위면 원. 정확한 원 금액은 말풍선 -#}
|
||||||
|
{%- macro unitv(v) -%}{% if h.unit_mult and h.unit_mult > 1 %}{{ "{:,.1f}".format(v / h.unit_mult).rstrip('0').rstrip('.') }}<small>{{ h.sales_unit }}</small>{% else %}{{ won(v) }}<small>원</small>{% endif %}{%- endmacro -%}
|
||||||
|
{%- macro unknown_val() -%}<span class="pj-meet-unknown" title="실적 조회 실패 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>{%- endmacro -%}
|
||||||
|
{# 주간 회의록 — 목표 표 월 머리를 누르면 열린다(/project/goals/{연도}/meetings/{월}?week=주차 시작일).
|
||||||
|
주차(store.month_weeks — 그 달 안, 1주차는 1일부터)마다 회의록 하나: 머리 영역 3칸(월 계획 + 숫자 한 줄 | 결정 사항·메모 | 작업 등록)
|
||||||
|
+ 구역(목표 표 업무 영역)별 줄 — 주요 업무·정량 목표 | 지난주: 전주 업무·결과(글)·전주 목표·결과(금액).
|
||||||
|
지난주 칸은 바로 앞 주차 회의록의 같은 줄(연결키). 월 누적 실적은 실적 모듈, 월 누적 목표는 목표 표 주차별 목표 합.
|
||||||
|
입력은 누구나(완료 전까지, 칸별 즉시 저장, project.js initGoalMeeting). DB: project_db 015·020. #}
|
||||||
|
<div class="pj-wrap pj-inbox-view pj-goal-view pj-meet-view" data-me="{{ (user.email if user else '') | lower }}">
|
||||||
|
<div class="pj-layout">
|
||||||
|
{% if not meeting_embedded %}{% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %}{% endif %}
|
||||||
|
|
||||||
|
<section class="pj-main">
|
||||||
|
{# 머리 — 왼쪽: 제목·이전/다음 달·인쇄·회의록 삭제·주차 탭(한 줄) + 영역 3칸(월 계획·숫자 | 결정 사항 | 작업 등록) / 오른쪽 위: 작은 달력 #}
|
||||||
|
<div class="pj-meet-headgrid">
|
||||||
|
<div class="pj-meet-headleft">
|
||||||
|
<div class="pj-meet-title">
|
||||||
|
{# 연간 목표로 — 눈에 잘 띄는 큰 버튼(예전 ← 화살표 대신) #}
|
||||||
|
<a class="pj-meet-goalbtn" href="/project/goals/{{ goal_year }}" title="{{ goal_year }}년 연간 목표로"><span class="material-symbols-outlined">flag</span><span>{{ goal_year }}년 목표</span></a>
|
||||||
|
<h2 class="pj-goal-title">{{ goal_year }}년 {{ goal_month }}월 주간 회의록</h2>
|
||||||
|
{% set pm = goal_month - 1 if goal_month > 1 else 12 %}{% set py = goal_year if goal_month > 1 else goal_year - 1 %}
|
||||||
|
{% set nm = goal_month + 1 if goal_month < 12 else 1 %}{% set ny = goal_year if goal_month < 12 else goal_year + 1 %}
|
||||||
|
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ py }}/meetings/{{ pm }}">‹ {{ pm }}월</a>
|
||||||
|
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ ny }}/meetings/{{ nm }}">{{ nm }}월 ›</a>
|
||||||
|
{% if meeting %}
|
||||||
|
{# 회의록은 프로젝트 권한이 있는 누구나 고친다. [회의 완료](Pro user 이상) = 수정 잠금, 완료 뒤 [완료 해제](Pro user 이상) — 마이그레이션 022 #}
|
||||||
|
<span class="pj-meet-title-acts">
|
||||||
|
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-print"><span class="material-symbols-outlined">print</span> 인쇄</button>
|
||||||
|
{% if pj_pro %}<button type="button" class="pj-btn pj-btn-sm pj-btn-danger" id="pj-meet-del">회의록 삭제</button>{% endif %}
|
||||||
|
{% if meeting.can_complete %}
|
||||||
|
{% if meeting.completed %}
|
||||||
|
<span class="pj-meet-done-badge" title="{{ meeting.completed_at }}{% if meeting.completed_by %} · {{ meeting.completed_by }}{% endif %} — 완료된 회의록은 고칠 수 없습니다"><span class="material-symbols-outlined">lock</span>회의 완료</span>
|
||||||
|
{% if pj_pro %}<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-reopen" title="다시 고칠 수 있게 엽니다">완료 해제</button>{% endif %}
|
||||||
|
{% elif pj_pro %}<button type="button" class="pj-btn pj-btn-sm pj-meet-complete-btn" id="pj-meet-complete" title="이 회의록을 더 고칠 수 없게 잠급니다(Pro user 이상)"><span class="material-symbols-outlined">task_alt</span>회의 완료</button>{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</span>
|
||||||
|
{% endif %}
|
||||||
|
{# 주차 탭 — 주차는 그 달 안(1일이 월~금이면 1일~일요일, 토·일이면 1일~다음 주 일요일, 말일이 월·화면 앞 주차에 붙음). 점 = 회의록 있음 #}
|
||||||
|
<nav class="pj-meet-weeks" aria-label="주차">
|
||||||
|
{% for w in weeks %}
|
||||||
|
<a class="pj-meet-week{% if w.start == week %} is-on{% endif %}{% if w.now %} is-now{% endif %}"
|
||||||
|
href="?week={{ w.start }}" title="{{ w.n }}주차 {{ w.label }}">
|
||||||
|
{# 날짜는 짧게 — 주차는 달을 넘지 않아 끝 월 생략(10/5~11) #}
|
||||||
|
{% set ws = w.start.split('-') %}{% set we = w.end.split('-') %}
|
||||||
|
<b>{{ w.n }}주차</b><span>{{ ws[1] | int }}/{{ ws[2] | int }}~{% if we[1] != ws[1] %}{{ we[1] | int }}/{% endif %}{{ we[2] | int }}</span>
|
||||||
|
{% if w.has %}<i class="pj-meet-dot" title="회의록 있음"></i>{% endif %}
|
||||||
|
{% if w.now %}<em>이번 주</em>{% endif %}
|
||||||
|
</a>
|
||||||
|
{% endfor %}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
{# ── 머리 영역 3칸(스크롤해도 보임 — 표만 아래 .pj-meet-pane 에서 스크롤) ──
|
||||||
|
① 월 계획 + 머리 줄 오른쪽에 숫자 4개를 작게 한 줄로 ② 결정 사항·메모 ③ 작업 빠른 등록 표(project.js initMeetQuickTasks) #}
|
||||||
|
<div class="pj-meet-board">
|
||||||
|
<section class="pj-meet-area pj-meet-plan">
|
||||||
|
<div class="pj-meet-plan-head">
|
||||||
|
<span class="pj-meet-plan-title"><span class="material-symbols-outlined">event_note</span>{{ goal_month }}월 계획</span>
|
||||||
|
{% if h %}
|
||||||
|
<div class="pj-meet-kpiline">
|
||||||
|
<span class="pj-meet-kpi" title="월 목표 매출(연간 목표 표){% if h.month_target_won is not none %} = {{ won(h.month_target_won) }}원{% endif %}">
|
||||||
|
<span class="pj-meet-kpi-label">월 목표</span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.sales_target is not none %}{{ num(h.sales_target) }}<small>{{ h.sales_unit }}</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
</span>
|
||||||
|
<span class="pj-meet-kpi" title="월 누적 목표 매출{% if h.cum_target_won is not none %} {{ won(h.cum_target_won) }}원{% endif %} — 연간 목표 표에서 입력한 주차별 매출 목표의 1주차~{{ week_n }}주차 합계{% if not h.week_targets_set %} — 목표 표에서 주차별 목표를 입력하세요{% endif %}">
|
||||||
|
<span class="pj-meet-kpi-label">누적 목표 <small>({{ week_n }}주차)</small></span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.cum_target_won is not none %}{{ unitv(h.cum_target_won) }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
</span>
|
||||||
|
<span class="pj-meet-kpi" title="월 누적 실적{% if h.mtd is not none %} {{ won(h.mtd) }}원{% endif %}(1일~{{ h.mtd_end[5:] | replace('-', '/') if h.mtd_end else '' }}){% if h.fresh_tip %} · {{ h.fresh_tip }}{% endif %}">
|
||||||
|
<span class="pj-meet-kpi-label">누적 실적 {% if h.mtd_end %}<small>({{ h.mtd_end[5:] | replace('-', '/') }})</small>{% endif %}</span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.mtd is not none %}{{ unitv(h.mtd) }}{% elif 'mtd' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
</span>
|
||||||
|
<span class="pj-meet-kpi" title="누적 목표 대비 달성{% if h.gap is not none %} {{ '+' if h.gap > 0 else '' }}{{ won(h.gap) }}원{% endif %} — 월 누적 실적 − 월 누적 목표 매출 (월 누적 실적 ÷ 월 누적 목표 매출)">
|
||||||
|
<span class="pj-meet-kpi-label">목표 대비</span>
|
||||||
|
{% if h.gap is not none %}<span class="pj-meet-kpi-val {{ 'is-good' if h.gap >= 0 else 'is-low' }}">{{ '+' if h.gap > 0 else '' }}{{ unitv(h.gap) }}{% if h.rate is not none %} <small class="pj-meet-kpi-rate">{{ h.rate }}%</small>{% endif %}</span>
|
||||||
|
{% elif 'mtd' in unk and h.cum_target_won is not none %}<span class="pj-meet-kpi-val">{{ unknown_val() }}</span>
|
||||||
|
{% else %}<span class="pj-meet-kpi-val"><span class="pj-muted">—</span></span>{% endif %}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-area-body">
|
||||||
|
{% if month_plan is none %}<p class="pj-meet-plan-empty">연간 목표 표가 없어 월 계획을 보여 줄 수 없습니다.</p>
|
||||||
|
{% elif month_plan %}
|
||||||
|
<div class="pj-meet-plan-grid">
|
||||||
|
{% for a in month_plan %}
|
||||||
|
<div class="pj-meet-plan-area" style="--goal-bg: {{ a.color or '#f4f5f7' }}">
|
||||||
|
<b class="pj-meet-plan-name">{{ a.name }}</b>
|
||||||
|
{% for it in a.lines %}
|
||||||
|
<div class="pj-meet-plan-item">{% if it.label %}<span class="pj-meet-plan-label">{{ it.label }}</span>{% endif %}<span class="pj-meet-plan-text">{{ it.text_html | safe }}</span>{% if it.range %}<em>{{ it.range }}</em>{% endif %}</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}<p class="pj-meet-plan-empty">목표 표에 {{ goal_month }}월 계획이 아직 없습니다.</p>{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section class="pj-meet-area pj-meet-notes">
|
||||||
|
<h3>결정사항 : 진행상황 수시 공유 및 완료 되어야 함</h3>
|
||||||
|
{% if meeting %}
|
||||||
|
{% if not meeting.completed %}<textarea id="pj-meet-notes" rows="4" placeholder="이번 회의에서 정한 것, 다음 주까지 확인할 것">{{ meeting.notes }}</textarea>
|
||||||
|
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
|
||||||
|
{% else %}<p class="pj-meet-plan-empty">이 주차 회의록을 만들면 적을 수 있습니다.</p>{% endif %}
|
||||||
|
</section>
|
||||||
|
{# 작업 등록 — 주차마다 한 표를 서버에(025, 모두가 같은 표 — project.js initMeetQuickTasks). 제목 = "N주차 작업 등록", 회의 완료면 읽기 전용 #}
|
||||||
|
{% set qw = weeks | selectattr("start", "equalto", week) | first %}
|
||||||
|
<section class="pj-meet-area pj-meet-quick" id="pj-meet-quick" data-week="{{ week }}"{% if qw and qw.now %} data-now="1"{% endif %}{% if meeting and meeting.completed %} data-locked="1"{% endif %}>
|
||||||
|
<h3>{% if week_n %}<span class="pj-meet-quick-week">{{ week_n }}주차</span> {% endif %}업무 등록
|
||||||
|
<button type="button" class="pj-btn pj-btn-sm pj-meet-quick-expand" data-quick="expand" title="넓은 창에서 업무·세부 업무 등록(같은 표)"><span class="material-symbols-outlined">open_in_full</span>크게 열기</button></h3>
|
||||||
|
<div class="pj-meet-area-body">
|
||||||
|
<table class="pj-meet-quick-table">
|
||||||
|
<thead><tr><th>제목</th><th>담당자</th><th>프로젝트</th><th>섹션</th><th title="고르면 그 업무의 세부 업무로 등록(비우면 섹션에 새 업무)">업무</th><th></th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
<button type="button" class="pj-meet-quick-add" data-quick="add">+ 줄 추가</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{# 작은 달력 — 월요일 시작 줄, 줄을 누르면 그 줄의 이 달 날짜가 든 주차 회의록(보고 있는 주차의 줄은 영역 표시). 점 = 회의록 있음. #}
|
||||||
|
<div class="pj-meet-cal" aria-label="{{ goal_month }}월 달력">
|
||||||
|
<div class="pj-meet-cal-head">{{ goal_year }}년 {{ goal_month }}월</div>
|
||||||
|
<div class="pj-meet-cal-wd"><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span><span class="is-sun">일</span></div>
|
||||||
|
{% for w in cal_weeks %}
|
||||||
|
<a class="pj-meet-cal-row{% if w.start == week %} is-on{% endif %}{% if not w.own %} is-other{% endif %}" href="{{ w.href }}"
|
||||||
|
title="{{ w.title }}{% if w.has %} · 회의록 있음{% endif %}">
|
||||||
|
{% for d in w.days %}<span class="pj-meet-cal-d{% if not d.in %} is-out{% endif %}{% if d.today %} is-today{% endif %}{% if d.wd == 5 %} is-sat{% endif %}{% if d.wd == 6 or d.hol %} is-sun{% endif %}"{% if d.hol %} title="{{ d.hol }}"{% endif %}>{{ d.d }}</span>{% endfor %}
|
||||||
|
{% if w.has %}<i class="pj-meet-cal-dot"></i>{% endif %}
|
||||||
|
</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if meeting and not meeting.completed %}{% include "project/_cell_format.html" %}{% endif %}
|
||||||
|
<div class="pj-view pj-meet-pane" id="pj-meet-pane" data-week="{{ week }}" data-year="{{ goal_year }}"
|
||||||
|
data-month="{{ goal_month }}" data-pro="{{ 'true' if pj_pro else 'false' }}"
|
||||||
|
data-edit="{{ 'true' if meeting and not meeting.completed else 'false' }}">
|
||||||
|
|
||||||
|
{% if not meetings_enabled %}
|
||||||
|
<div class="pj-empty">주간 회의록이 아직 준비되지 않았습니다(DB 마이그레이션 015 필요).</div>
|
||||||
|
{% elif not meeting %}
|
||||||
|
<div class="pj-empty pj-goal-empty">
|
||||||
|
<p>{{ week_n }}주차({{ week }} ~ {{ week_end }}) 회의록이 아직 없습니다.</p>
|
||||||
|
{% if true %}
|
||||||
|
<p class="pj-goal-empty-sub">만들면 앞선 회의록의 줄(구역·항목)을 이어받아, 지난주 업무·목표·결과를 나란히 리뷰할 수 있습니다.
|
||||||
|
처음이면 {{ goal_year }}년 목표 표의 업무 영역과 기본 양식 줄로 시작합니다.</p>
|
||||||
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-meet-create">{{ week_n }}주차 회의록 만들기</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
{% set edit = not meeting.completed %} {# 누구나 고친다 — 회의 완료(022)면 잠금 #}
|
||||||
|
{# 매출 자료 갱신 — 주차를 열면 실적 모듈 매출 업데이트(지난 주차 시작 ~ 이 주차 오늘)를 한 번 더 돌리고 숫자 칸만 다시 그린다
|
||||||
|
(project.js initMeetingSync, 같은 주는 10분에 한 번). 정상이면 아무것도 보이지 않는다(2026-10-01 요청 — 큰 상태 줄 없음).
|
||||||
|
실패·일부 실패면 이 작은 안내 + [다시 시도], 실적 권한이 없으면 부르지 않고 한 줄 설명. 마지막 갱신 성공 시각은 서버 기록(data-fresh). #}
|
||||||
|
{% if h.perf and sync_from %}<div id="pj-meet-sync" class="pj-meet-syncnote" hidden role="status" aria-live="polite"
|
||||||
|
data-from="{{ sync_from }}" data-to="{{ sync_to }}" data-can="{{ '1' if can_sync else '0' }}" data-fresh="{{ h.fresh_oldest }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">sync_problem</span><span class="pj-meet-sync-text"></span>
|
||||||
|
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-sync-btn" hidden>다시 시도</button>
|
||||||
|
</div>{% endif %}
|
||||||
|
{% if not h.perf %}<p class="pj-goal-note">실적 모듈이 연결되지 않아 실적·누적은 비어 있습니다.</p>
|
||||||
|
{% elif h.perf_state == 'error' %}<p class="pj-goal-note pj-meet-perf-warn">실적 모듈 쇼핑몰 목록을 읽지 못해 실적·누적을 <b>미확인</b>으로 표시합니다(0 원이 아님). 회의록 입력은 그대로 됩니다.</p>
|
||||||
|
{% elif h.perf_state == 'empty' %}<p class="pj-goal-note">실적 모듈에 매출 집계 쇼핑몰이 없어 실적·누적은 비어 있습니다.</p>
|
||||||
|
{% elif unk %}<p class="pj-goal-note pj-meet-perf-warn">일부 실적을 읽지 못했습니다 — <b>미확인</b> 칸은 0 원이 아니라 알 수 없는 값입니다.</p>{% endif %}
|
||||||
|
|
||||||
|
{# 참석자 — 전체 멤버에서 고른다(칩, [참석자] = 고르기 창). 저장은 이메일을 쉼표로 이어서, 예전 자유 입력 글자도 칩으로 #}
|
||||||
|
<div class="pj-meet-attend">
|
||||||
|
<span class="pj-meet-attend-label">참석자</span>
|
||||||
|
<div class="pj-meet-attend-chips" id="pj-meet-attend"{% if edit %} data-edit="1"{% endif %}>
|
||||||
|
{% for a in attendee_list %}<span class="pj-meet-chip" data-key="{{ a.key }}" data-name="{{ a.name }}" data-avatar="{{ a.avatar }}"{% if not a.email %} title="멤버가 아닌 글자(예전 입력)"{% endif %}>
|
||||||
|
{%- if a.avatar %}<img class="pj-avatar" src="{{ a.avatar }}" alt="" referrerpolicy="no-referrer">{% else %}<span class="pj-meet-chip-ini">{{ a.name[:1] }}</span>{% endif %}<span>{{ a.name }}</span>
|
||||||
|
{%- if edit %}<button type="button" class="pj-meet-chip-x" title="빼기" aria-label="{{ a.name }} 빼기">×</button>{% endif %}</span>{% endfor %}
|
||||||
|
{% if edit %}<button type="button" class="pj-meet-attend-add" id="pj-meet-attend-add"><span class="material-symbols-outlined">person_add</span>참석자</button>
|
||||||
|
{% elif not attendee_list %}<span class="pj-muted">—</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
{# 회의록 보드 — 그 주차의 빈 Google 슬라이드를 독립 창으로(없으면 공유 드라이브에 만든다, project.js initMeetBoard) #}
|
||||||
|
<button type="button" class="pj-btn pj-btn-sm pj-meet-board-btn" id="pj-meet-board"
|
||||||
|
title="이 주차의 Google 슬라이드 보드를 새 창으로 엽니다(처음이면 공유 드라이브에 빈 슬라이드를 만듭니다)">
|
||||||
|
<span class="material-symbols-outlined">co_present</span>회의록 보드</button>
|
||||||
|
{# 회의록 보드 링크 복사(2026-10-08) — 같은 주차 보드 주소(없으면 만든 뒤)를 클립보드로 #}
|
||||||
|
<button type="button" class="pj-icon-btn pj-meet-board-copy" id="pj-meet-board-copy"
|
||||||
|
title="회의록 보드 링크 복사" aria-label="회의록 보드 링크 복사"><span class="material-symbols-outlined">link</span></button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{# ── 구역별 줄 — 왼쪽: 이번주 / 오른쪽: 전주 리뷰(지난 회의록 같은 줄) ── #}
|
||||||
|
<table class="pj-meet-table" id="pj-meet-table" data-cell-merges="{{ 'true' if meeting.cell_merges else 'false' }}">
|
||||||
|
{# table-layout: fixed 는 첫 줄(묶음 머리, colspan)로 너비를 정하므로 열 너비는 colgroup 으로 #}
|
||||||
|
<colgroup>
|
||||||
|
{# is-this / is-prev — 순서 바꾸기(project.js initMeetOrder)가 이 묶음으로 열을 옮긴다 #}
|
||||||
|
<col class="pj-meet-w-sec" data-meet-col="section" /><col class="pj-meet-w-label" data-meet-col="label" /><col class="is-this" data-meet-col="content" /><col class="pj-meet-w-amt is-this" data-meet-col="target" />
|
||||||
|
<col class="is-prev" data-meet-col="prev_content" /><col class="is-prev" data-meet-col="prev_note" /><col class="pj-meet-w-amt is-prev" data-meet-col="prev_target" /><col class="pj-meet-w-amt is-prev" data-meet-col="result" />
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr class="pj-meet-group">
|
||||||
|
{# 이번주 ↔ 지난주 리뷰 순서 바꾸기 — 보는 사람마다 브라우저에 기억(localStorage pj_meet_order:{이메일}) #}
|
||||||
|
<th colspan="2" class="pj-meet-order-cell"><button type="button" class="pj-meet-order-btn" id="pj-meet-order"
|
||||||
|
title="이번주와 지난주 리뷰의 순서 바꾸기(내 화면에 기억)"><span class="material-symbols-outlined">swap_horiz</span>순서 바꾸기</button></th>
|
||||||
|
<th colspan="2" class="is-this">이번주 ({{ week[5:] | replace('-', '/') }} ~ {{ week_end[5:] | replace('-', '/') }})</th>
|
||||||
|
{# 지난주 = 바로 앞 주차 — 줄의 지난주 칸·결과도 그 주차 회의록의 같은 줄(연결키)만 #}
|
||||||
|
<th colspan="4" class="is-prev">지난주 리뷰 ({{ prev_week[5:] | replace('-', '/') }} ~ {{ prev_week_end[5:] | replace('-', '/') }}){% if not h.prev_exists %} <span class="pj-meet-noprev">— 이 주 회의록 없음</span>{% endif %}</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th class="pj-meet-c-sec">구분</th>
|
||||||
|
<th class="pj-meet-c-label">항목</th>
|
||||||
|
<th class="pj-meet-c-text">주요 업무</th>
|
||||||
|
<th class="pj-meet-c-amt">정량 목표</th>
|
||||||
|
<th class="pj-meet-c-text is-prev">전주 업무</th>
|
||||||
|
<th class="pj-meet-c-text is-prev">결과</th>
|
||||||
|
<th class="pj-meet-c-amt is-prev">전주 목표</th>
|
||||||
|
<th class="pj-meet-c-amt is-prev">결과</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
{% for sec in meeting.sections %}
|
||||||
|
<tbody class="pj-meet-sec" data-section="{{ sec.name }}" style="--goal-bg: {{ sec.color or '#fff' }}">
|
||||||
|
{% for it in sec.rows %}
|
||||||
|
{% set p = it.prev %}
|
||||||
|
<tr data-item="{{ it.id }}" data-section="{{ sec.name }}"{% if it.label_hidden %} data-label-cont="1"{% endif %} data-market="{{ it.marketplace_code }}" data-target-amount="{{ it.target_amount if it.target_amount is not none else '' }}"{% if p %} data-prev="{{ p.id }}" data-prev-target="{{ p.target_amount if p.target_amount is not none else '' }}"{% endif %}>
|
||||||
|
{% if loop.first %}
|
||||||
|
<th class="pj-meet-c-sec" rowspan="{{ sec.rows | length }}">{{ sec.name }}
|
||||||
|
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more pj-meet-sec-more" data-meet-act="sec-menu" title="구역 메뉴(위로·아래로) · 우클릭도 됩니다"><span class="material-symbols-outlined">more_horiz</span></button>
|
||||||
|
<button type="button" class="pj-meet-sec-add" data-meet-act="sec-add" title="{{ sec.name }} 구역 끝에 줄 추가">+</button>{% endif %}
|
||||||
|
</th>
|
||||||
|
{% endif %}
|
||||||
|
{# 항목 칸 — 같은 항목 칸 안에 이어 붙은 줄(027 label_cont)은 그리지 않고 묶음 첫 줄이 rowspan #}
|
||||||
|
{% if not it.label_hidden %}
|
||||||
|
<th class="pj-meet-c-label"{% if (it.label_span or 1) > 1 %} rowspan="{{ it.label_span }}"{% endif %}>
|
||||||
|
<span class="pj-meet-label-line">
|
||||||
|
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
|
||||||
|
</span>
|
||||||
|
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more" data-meet-act="menu" title="줄 메뉴"><span class="material-symbols-outlined">more_horiz</span></button>{% endif %}
|
||||||
|
</th>
|
||||||
|
{% endif %}
|
||||||
|
{% if not it.content_hidden %}
|
||||||
|
<td class="pj-meet-c-text" rowspan="{{ it.content_span or 1 }}" data-meet-item="{{ it.id }}">
|
||||||
|
{% if edit %}<div class="pj-meet-text pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="{{ it.label_shown if it.label_shown is defined else it.label }} 주요 업무" data-field="content" data-placeholder="주요 업무">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>
|
||||||
|
{% else %}<div class="pj-meet-ro">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>{% endif %}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
|
<td class="pj-meet-c-amt">
|
||||||
|
{# 숫자(원, 120만·1.5억도) 또는 글(예: 20개 — 021 target_text) #}
|
||||||
|
{% if edit %}<input type="text" class="pj-meet-amount" data-field="target_amount" autocomplete="off" value="{{ it.target_text or won(it.target_amount) }}" />
|
||||||
|
{% else %}{{ it.target_text or won(it.target_amount) }}{% endif %}
|
||||||
|
</td>
|
||||||
|
{% if p %}
|
||||||
|
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{% if p.content_html is defined %}{{ p.content_html | safe }}{% else %}{{ p.content }}{% endif %}</div></td>
|
||||||
|
{# 결과(글) — 지난 주차 줄의 result_note(020). 미적용이면 보기만 #}
|
||||||
|
<td class="pj-meet-c-text is-prev pj-meet-c-note">
|
||||||
|
{% if edit and meeting.result_notes %}<textarea class="pj-meet-rnote" rows="1" data-field="result_note" data-target="prev" aria-label="{{ it.label_shown if it.label_shown is defined else it.label }} 결과" placeholder="결과">{{ p.result_note or '' }}</textarea>
|
||||||
|
{% else %}<div class="pj-meet-ro">{{ p.result_note or '' }}</div>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="pj-meet-c-amt is-prev">{{ p.target_text or won(p.target_amount) }}</td>
|
||||||
|
<td class="pj-meet-c-amt is-prev pj-meet-c-result">
|
||||||
|
{% if edit %}<input type="text" class="pj-meet-amount" data-field="result_amount" data-target="prev" autocomplete="off" value="{{ p.result_text or won(p.result_amount) }}" placeholder="결과" />
|
||||||
|
{% else %}{{ p.result_text or won(p.result_amount) }}{% endif %}
|
||||||
|
</td>
|
||||||
|
{% else %}
|
||||||
|
<td class="pj-meet-c-text is-prev is-none" colspan="4"><span class="pj-muted">{% if h.prev_exists %}지난주 회의록에 없는 줄{% else %}지난주({{ prev_week[5:] | replace('-', '/') }}~) 회의록 없음{% endif %}</span></td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
{% endfor %}
|
||||||
|
</table>
|
||||||
|
{% if edit %}<p class="pj-goal-note">글자를 선택하면 색상·크기·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다.
|
||||||
|
셀 오른쪽 경계는 너비 조절·더블클릭 자동 맞춤, 우클릭은 현재/전체 열 자동 맞춤입니다.
|
||||||
|
주요 업무 셀의 위·아래·왼쪽 테두리를 끌면 내용과 서식을 옮깁니다.
|
||||||
|
같은 구역에서 끌기·Shift+클릭으로 범위를 선택한 뒤 Del로 지우고 Ctrl+Z로 되돌립니다.
|
||||||
|
{% if meeting.cell_merges %}우클릭으로 세로 셀 병합·병합 해제를 사용할 수 있습니다.{% endif %}</p>{% endif %}
|
||||||
|
{% if edit %}
|
||||||
|
<div class="pj-goal-foot">
|
||||||
|
<button type="button" class="pj-btn" id="pj-meet-sec-new">+ 구역 추가</button>
|
||||||
|
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 금액은 원 단위(120만·1.5억도 됨). 항목을 우클릭하거나 ⋯ 를 누르면
|
||||||
|
줄 추가·순서·삭제. 정량 목표·결과는 숫자나 글(예: 20개) 모두 됩니다. 지난주 결과는 지난 주차 회의록 줄에 저장됩니다.</span>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>window.PJ_MEET_MEMBERS = {{ (meet_members or []) | tojson }};</script>
|
||||||
|
{% include "project/_side_modals.html" %}
|
||||||
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
|
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||||
|
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||||
|
<script src="/static/project.js?v=20261014a" defer></script>
|
||||||
|
{% endblock %}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
{# 연간 목표 — 좌측 사이드바 "목표" → 연도. 스프레드시트처럼 한 표에
|
{# 연간 목표 — 좌측 사이드바 "목표" → 연도. 스프레드시트처럼 한 표에
|
||||||
① 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자
|
① 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자
|
||||||
② 업무 영역(상품·마케팅·컨텐츠·유통 …)별 연간·월별 글.
|
② 업무 영역(상품·마케팅·컨텐츠·유통 …)별 연간·월별 글.
|
||||||
입력·구조 변경은 관리자만(칸별 즉시 저장, project.js initGoals), 나머지는 보기만.
|
입력·구조 변경은 Pro user 이상(칸별 즉시 저장, project.js initGoals), 나머지는 보기만.
|
||||||
DB: project_db 013 (goal_years·goal_metrics·goal_areas·goal_rows·goal_cells). #}
|
DB: project_db 013 (goal_years·goal_metrics·goal_areas·goal_rows·goal_cells). #}
|
||||||
<div class="pj-wrap pj-inbox-view pj-goal-view">
|
<div class="pj-wrap pj-inbox-view pj-goal-view">
|
||||||
<div class="pj-layout">
|
<div class="pj-layout">
|
||||||
@@ -19,10 +19,10 @@
|
|||||||
|
|
||||||
<section class="pj-main">
|
<section class="pj-main">
|
||||||
<div class="pj-section-head">
|
<div class="pj-section-head">
|
||||||
<h2>{{ goal_year }}년 목표</h2>
|
<h2 class="pj-goal-title">{{ goal_year }}년 목표</h2>
|
||||||
{% if board %}
|
{% if board %}
|
||||||
<div class="pj-goal-head-acts">
|
<div class="pj-goal-head-acts">
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<label class="pj-goal-unit">매출 단위
|
<label class="pj-goal-unit">매출 단위
|
||||||
<input type="text" id="pj-goal-unit" maxlength="20" placeholder="예: 백만원"
|
<input type="text" id="pj-goal-unit" maxlength="20" placeholder="예: 백만원"
|
||||||
value="{{ board.sales_unit }}" data-year="{{ goal_year }}" />
|
value="{{ board.sales_unit }}" data-year="{{ goal_year }}" />
|
||||||
@@ -31,19 +31,22 @@
|
|||||||
data-year="{{ goal_year }}">연도 삭제</button>
|
data-year="{{ goal_year }}">연도 삭제</button>
|
||||||
{% else %}
|
{% else %}
|
||||||
{% if board.sales_unit %}<span class="pj-goal-unit-ro">매출 단위: {{ board.sales_unit }}</span>{% endif %}
|
{% if board.sales_unit %}<span class="pj-goal-unit-ro">매출 단위: {{ board.sales_unit }}</span>{% endif %}
|
||||||
<span class="pj-goal-note">목표는 관리자만 입력할 수 있습니다.</span>
|
<span class="pj-goal-note">목표는 Pro user 이상만 입력할 수 있습니다.</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{% if pj_pro and goals_enabled and board %}
|
||||||
|
{% include "project/_cell_format.html" %}
|
||||||
|
{% endif %}
|
||||||
<div class="pj-view pj-goal-pane" id="pj-goal-pane">
|
<div class="pj-view pj-goal-pane" id="pj-goal-pane">
|
||||||
{% if not goals_enabled %}
|
{% if not goals_enabled %}
|
||||||
<div class="pj-empty">연간 목표가 아직 준비되지 않았습니다(DB 마이그레이션 013 필요).</div>
|
<div class="pj-empty">연간 목표가 아직 준비되지 않았습니다(DB 마이그레이션 013 필요).</div>
|
||||||
{% elif not board %}
|
{% elif not board %}
|
||||||
<div class="pj-empty pj-goal-empty">
|
<div class="pj-empty pj-goal-empty">
|
||||||
<p>{{ goal_year }}년 목표가 아직 없습니다.</p>
|
<p>{{ goal_year }}년 목표가 아직 없습니다.</p>
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<p class="pj-goal-empty-sub">만들면 가장 가까운 이전 연도의 업무 영역 구성을 그대로 가져옵니다(처음이면 상품·마케팅·컨텐츠·유통).</p>
|
<p class="pj-goal-empty-sub">만들면 가장 가까운 이전 연도의 업무 영역 구성을 그대로 가져옵니다(처음이면 상품·마케팅·컨텐츠·유통).</p>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-goal-create" data-year="{{ goal_year }}">{{ goal_year }}년 목표 만들기</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-goal-create" data-year="{{ goal_year }}">{{ goal_year }}년 목표 만들기</button>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -51,100 +54,130 @@
|
|||||||
{% else %}
|
{% else %}
|
||||||
{% set sm = board.metrics.sales %}
|
{% set sm = board.metrics.sales %}
|
||||||
{% set rm = board.metrics.roas %}
|
{% set rm = board.metrics.roas %}
|
||||||
|
{# 월 칸은 pj-goal-m + data-h(분기 1~4) — 분기 접기(initGoals)가 이걸로 숨긴다.
|
||||||
|
분기 칸 클래스는 예전 이름 pj-goal-half-col 그대로(연간 칸처럼 굵게·회색 합계) #}
|
||||||
|
{# 매출 목표 칸(020) — 누르면 그 달 월 목표(직접 입력)·주차별 목표 입력 창, 맨 아래 차이(월 목표 − 주차 합계) #}
|
||||||
{% macro num_cell(metric, kind, labels, mo) -%}
|
{% macro num_cell(metric, kind, labels, mo) -%}
|
||||||
<td class="pj-goal-numtd{% if mo == this_month %} is-now{% endif %}">
|
{%- set weekly = week_targets and metric == 'sales' and kind == 'target' -%}
|
||||||
{%- if is_admin -%}
|
<td class="pj-goal-numtd pj-goal-m{% if mo == this_month %} is-now{% endif %}{% if weekly %} is-weekly{% endif %}" data-h="{{ (mo - 1) // 3 + 1 }}">
|
||||||
|
{%- if pj_pro -%}
|
||||||
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
|
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
|
||||||
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
||||||
|
{%- if weekly %} readonly data-weekly="1" title="{{ mo }}월 목표·주차별 목표 입력"{% endif %}
|
||||||
value="{{ labels.get(mo, '') }}" />
|
value="{{ labels.get(mo, '') }}" />
|
||||||
{%- else -%}
|
{%- else -%}
|
||||||
<span class="pj-goal-num" data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}">{{ labels.get(mo, '') }}</span>
|
<span class="pj-goal-num" data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
||||||
|
{%- if weekly %} data-weekly="1" tabindex="0" title="{{ mo }}월 주차별 목표 보기"{% endif %}>{{ labels.get(mo, '') }}</span>
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
</td>
|
</td>
|
||||||
{%- endmacro %}
|
{%- endmacro %}
|
||||||
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
|
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
|
||||||
data-admin="{{ 'true' if is_admin else 'false' }}">
|
data-pro="{{ 'true' if pj_pro else 'false' }}"
|
||||||
|
data-halves="{{ 'true' if board.halves else 'false' }}">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
{# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(localStorage pj_goal_col_w) #}
|
{# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(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-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-c2"><span class="pj-goal-colresize" data-col="c2" title="끌어서 너비 조절"></span></th>
|
||||||
<th class="pj-goal-year-col">연간</th>
|
{# 연간·월·분기 칸도 머리 칸 오른쪽 끝을 끌어 너비 조절(data-col: y · m1~m12 · q1~q4) #}
|
||||||
{% for mo in months %}<th class="{% if mo == this_month %}is-now{% endif %}">{{ mo }}월</th>{% endfor %}
|
<th class="pj-goal-year-col" data-col="y">연간<span class="pj-goal-colresize" data-col="y" title="끌어서 너비 조절"></span></th>
|
||||||
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{# 월 이름을 누르면 그 달 주간 회의록(/goals/{연도}/meetings/{월}) #}
|
||||||
|
{% for mo in hmonths %}<th class="pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ h }}" data-col="m{{ mo }}"><a class="pj-goal-mlabel pj-goal-mlink" href="/project/goals/{{ goal_year }}/meetings/{{ mo }}" title="{{ mo }}월 주간 회의록">{{ mo }}월</a><span class="pj-goal-colresize" data-col="m{{ mo }}" title="끌어서 너비 조절"></span></th>{% endfor %}
|
||||||
|
{# 분기 칸 — 머리 칸 아무 곳이나 누르면 그 분기의 월 칸을 접었다 편다(localStorage pj_goal_fold_q).
|
||||||
|
아이콘은 엑셀 열 그룹처럼 네모 안 − (펼침, 누르면 접힘) / + (접힘, 누르면 펼침).
|
||||||
|
분기 색(data-h → --qc)은 머리 위 색 띠(월 가늘게·분기 두껍게)와 분기 열 옅은 음영 #}
|
||||||
|
<th class="pj-goal-half-col pj-goal-fold-th" data-h="{{ h }}" data-col="q{{ h }}">
|
||||||
|
<button type="button" class="pj-goal-fold" data-h="{{ h }}" aria-expanded="true"
|
||||||
|
data-label="{{ hmonths[0] }}~{{ hmonths[-1] }}월"
|
||||||
|
title="{{ hmonths[0] }}~{{ hmonths[-1] }}월 접기"><svg class="pj-goal-fold-ic" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><rect x="1.75" y="1.75" width="12.5" height="12.5" rx="3"/><path d="M5 8h6"/><path class="pj-goal-fold-v" d="M8 5v6"/></svg></button>{{ hname }}
|
||||||
|
<span class="pj-goal-colresize" data-col="q{{ h }}" title="끌어서 너비 조절"></span>
|
||||||
|
</th>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
{# ── 숫자 지표 ── #}
|
{# ── 숫자 지표 — 연간·분기 칸은 화면에서 계산(매출 합계·달성률, 로아스 매출 가중 평균), 로아스는 % 단위 ── #}
|
||||||
<tbody class="pj-goal-kpi">
|
<tbody class="pj-goal-kpi">
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c1" rowspan="3">매출</th>
|
<th class="pj-goal-c1" rowspan="3">매출</th>
|
||||||
<th class="pj-goal-c2">목표</th>
|
<th class="pj-goal-c2">목표</th>
|
||||||
<td class="pj-goal-sum" data-metric="sales" data-kind="target"></td>
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="sales" data-kind="target" data-scope="0"></td>
|
||||||
{% for mo in months %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="sales" data-kind="target" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c2">실적</th>
|
<th class="pj-goal-c2">실적</th>
|
||||||
<td class="pj-goal-sum" data-metric="sales" data-kind="actual"></td>
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="sales" data-kind="actual" data-scope="0"></td>
|
||||||
{% for mo in months %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="sales" data-kind="actual" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr class="pj-goal-rate-row">
|
<tr class="pj-goal-rate-row">
|
||||||
<th class="pj-goal-c2">달성</th>
|
<th class="pj-goal-c2">달성</th>
|
||||||
<td class="pj-goal-rate" data-month="0"></td>
|
<td class="pj-goal-rate pj-goal-year-col" data-month="0"></td>
|
||||||
{% for mo in months %}<td class="pj-goal-rate{% if mo == this_month %} is-now{% endif %}" data-month="{{ mo }}"></td>{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}<td class="pj-goal-rate pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ h }}" data-month="{{ mo }}"></td>{% endfor %}
|
||||||
|
<td class="pj-goal-rate pj-goal-half-col" data-month="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c1" rowspan="2">로아스</th>
|
<th class="pj-goal-c1" rowspan="2">로아스</th>
|
||||||
<th class="pj-goal-c2">목표</th>
|
<th class="pj-goal-c2">목표</th>
|
||||||
<td class="pj-goal-sum pj-goal-sum-na"></td>
|
{# 로아스 연간·분기 = 월 매출로 가중한 평균(광고비 = 매출 ÷ 로아스로 환산) — project.js recompute #}
|
||||||
{% for mo in months %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %}
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="roas" data-kind="target" data-scope="0"></td>
|
||||||
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="roas" data-kind="target" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c2">실적</th>
|
<th class="pj-goal-c2">실적</th>
|
||||||
<td class="pj-goal-sum pj-goal-sum-na"></td>
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="roas" data-kind="actual" data-scope="0"></td>
|
||||||
{% for mo in months %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="roas" data-kind="actual" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|
||||||
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #}
|
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(Pro user 이상) ── #}
|
||||||
{% for area in board.areas %}
|
{% for area in board.areas %}
|
||||||
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" data-color="{{ area.color }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
||||||
{% for row in area.rows %}
|
{% for row in area.rows %}
|
||||||
<tr data-row-id="{{ row.id }}">
|
<tr data-row-id="{{ row.id }}">
|
||||||
{% if loop.first %}
|
{% if loop.first %}
|
||||||
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
|
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
|
||||||
<span class="pj-goal-area-text">{{ area.name }}</span>
|
{# 구역 메뉴(색·위로·아래로·줄 추가·영역 삭제) — 우클릭 또는 ⋮ 버튼(키보드 Tab → Enter/Space, 터치 탭). project.js areaMenuItems #}
|
||||||
{% if is_admin %}
|
<span class="pj-goal-area-text"{% if pj_pro %} data-goal-edit="area" tabindex="0" role="button" title="눌러서 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ area.name }}</span>
|
||||||
<span class="pj-goal-tools">
|
{% if pj_pro %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="area" aria-haspopup="menu" aria-expanded="false"
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-rename" data-name="{{ area.name }}" title="이름 바꾸기">✎</button>
|
aria-label="{{ area.name }} 구역 메뉴" title="구역 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-color" data-color="{{ area.color }}" title="색 바꾸기"><span class="material-symbols-outlined">palette</span></button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-up" title="위로">↑</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-down" title="아래로">↓</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-add" title="줄 추가">+</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-del" data-name="{{ area.name }}" title="영역 삭제">×</button>
|
|
||||||
</span>
|
|
||||||
{% endif %}
|
|
||||||
</th>
|
</th>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<th class="pj-goal-c2 pj-goal-row-label">
|
{# 항목 칸(2열) — 같은 항목 칸으로 묶인 줄(016 label_cont)은 묶음 첫 줄이 rowspan 으로 덮는다 #}
|
||||||
<span class="pj-goal-row-text">{{ row.label }}</span>
|
{% if not row.label_cont %}
|
||||||
{% if is_admin %}
|
<th class="pj-goal-c2 pj-goal-row-label"{% if (row.label_span or 1) > 1 %} rowspan="{{ row.label_span }}"{% endif %} data-label-span="{{ row.label_span or 1 }}">
|
||||||
<span class="pj-goal-tools">
|
<span class="pj-goal-row-text"{% if pj_pro %} data-goal-edit="row" tabindex="0" role="button" title="눌러서 줄 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ row.label }}</span>
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-rename" data-label="{{ row.label }}" title="줄 이름 바꾸기">✎</button>
|
{% if pj_pro %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="row" aria-haspopup="menu" aria-expanded="false"
|
||||||
{% if area.rows | length > 1 %}
|
aria-label="{{ (row.label or '이름 없는') }} 줄 메뉴" title="줄 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-up" title="위로">↑</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-down" title="아래로">↓</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-del" data-label="{{ row.label }}" title="줄 삭제">×</button>
|
|
||||||
{% endif %}
|
|
||||||
</span>
|
|
||||||
{% endif %}
|
|
||||||
</th>
|
</th>
|
||||||
{% for mo in [0] + months %}
|
{% endif %}
|
||||||
<td class="pj-goal-texttd{% if mo == 0 %} pj-goal-year-col{% endif %}{% if mo == this_month %} is-now{% endif %}">
|
{# 칸 배치는 router._goal_area_layout — 엑셀식 사각형 병합(colspan·rowspan), 가려진 칸은 없다 #}
|
||||||
{%- if is_admin -%}
|
{% for c in row.layout %}
|
||||||
<textarea class="pj-goal-text" rows="1" data-row="{{ row.id }}" data-month="{{ mo }}"
|
{% set editable = pj_pro and (c.kind != 'quarter' or (board.halves and (c.m not in (15, 16) or board.quarters))) %}
|
||||||
placeholder="{{ '연간 목표' if mo == 0 else '' }}">{{ row.cells.get(mo, '') }}</textarea>
|
{% set merged = c.span > 1 or c.rspan > 1 %}
|
||||||
|
<td class="pj-goal-texttd {{ 'pj-goal-m' if c.kind == 'month' else ('pj-goal-year-col' if c.kind == 'year' else 'pj-goal-half-col') }}{% if merged %} is-merged{% endif %}{% if c.now %} is-now{% endif %}"
|
||||||
|
{% if c.kind in ('month', 'quarter') %}data-h="{{ c.h }}" {% endif %}data-month="{{ c.m }}" data-span="{{ c.span }}" data-rspan="{{ c.rspan }}"
|
||||||
|
{%- if c.span > 1 %} colspan="{{ c.span }}" style="--span: {{ c.span }}"{% endif %}{% if c.rspan > 1 %} rowspan="{{ c.rspan }}"{% endif %}>
|
||||||
|
{%- if editable -%}
|
||||||
|
<div class="pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="목표 내용"
|
||||||
|
data-row="{{ row.id }}" data-month="{{ c.m }}"
|
||||||
|
data-placeholder="{{ '연간 목표' if c.m == 0 else ((c.h ~ '분기 목표') if c.kind == 'quarter' else '') }}">{{ c.html|safe }}</div>
|
||||||
{%- else -%}
|
{%- else -%}
|
||||||
<div class="pj-goal-text-ro">{{ row.cells.get(mo, '') }}</div>
|
<div class="pj-goal-text-ro">{{ c.html|safe }}</div>
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
</td>
|
</td>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -153,10 +186,13 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</table>
|
</table>
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<div class="pj-goal-foot">
|
<div class="pj-goal-foot">
|
||||||
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
|
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
|
||||||
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다.</span>
|
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 글자를 드래그해 선택하면 선택한 셀 상단에서 12색 견본·크기 2px 증감·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다. 모든 행의 셀 오른쪽 경계를 끌어 열 너비를 조절하고, 더블클릭하면 그 열의 가장 긴 문단에 맞춥니다. 숫자 칸을 비우면 지워집니다. 구역·항목 칸을 우클릭하거나 칸의 ⋮ 버튼(키보드 Tab·Enter, 터치)을 누르면 색·순서·줄 추가·삭제 메뉴가 나옵니다.
|
||||||
|
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함).
|
||||||
|
{%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
|
||||||
|
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -166,8 +202,10 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% if goal_area_colors %}<script>window.PJ_GOAL_COLORS = {{ goal_area_colors | tojson }};</script>{% endif %}
|
{% if goal_area_colors %}<script>window.PJ_GOAL_COLORS = {{ goal_area_colors | tojson }};</script>{% endif %}
|
||||||
|
{% if week_targets %}<script>window.PJ_GOAL_WEEKS = {{ week_targets | tojson }}; window.PJ_GOAL_UNIT = {{ (board.sales_unit if board else '') | tojson }};</script>{% endif %}
|
||||||
{% include "project/_side_modals.html" %}
|
{% include "project/_side_modals.html" %}
|
||||||
{% include "project/_member_tasks_modal.html" %}
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||||
|
<script src="/static/project.js?v=20261014a" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
|
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
{# ── 프로젝트 관리 도움말 — 처음 쓰는 사람을 위한 기능 안내(정적 페이지, DB 불필요).
|
{# ── 프로젝트 관리 도움말 — 처음 쓰는 사람을 위한 기능 안내(정적 페이지, DB 불필요).
|
||||||
기능이 바뀌면 이 페이지도 같이 고친다(docs/PROJECT_MODULE.md 와 짝). ── #}
|
기능이 바뀌면 이 페이지도 같이 고친다(docs/PROJECT_MODULE.md 와 짝). ── #}
|
||||||
<div class="pjh">
|
<div class="pjh" id="top">
|
||||||
<nav class="pjh-toc" aria-label="도움말 목차">
|
<nav class="pjh-toc" aria-label="도움말 목차">
|
||||||
<p class="pjh-toc-title">목차</p>
|
<p class="pjh-toc-title">목차</p>
|
||||||
<ol>
|
<ol>
|
||||||
@@ -20,38 +20,55 @@
|
|||||||
<li><a href="#roles">누가 무엇을 할 수 있나요</a></li>
|
<li><a href="#roles">누가 무엇을 할 수 있나요</a></li>
|
||||||
<li><a href="#project">프로젝트 만들기·고치기</a></li>
|
<li><a href="#project">프로젝트 만들기·고치기</a></li>
|
||||||
<li><a href="#views">보기 전환과 필터</a></li>
|
<li><a href="#views">보기 전환과 필터</a></li>
|
||||||
<li><a href="#board">보드 — 섹션과 작업 카드</a></li>
|
<li><a href="#board">보드 — 섹션과 업무 카드</a></li>
|
||||||
<li><a href="#card-subtasks">카드에서 하위 작업 다루기</a></li>
|
<li><a href="#card-subtasks">카드에서 세부 업무 다루기</a></li>
|
||||||
<li><a href="#task">작업 편집 창</a></li>
|
<li><a href="#task">업무 편집 창</a></li>
|
||||||
<li><a href="#subtasks">작업 창의 하위 작업</a></li>
|
<li><a href="#subtasks">업무 창의 세부 업무</a></li>
|
||||||
<li><a href="#dates">날짜 고르기</a></li>
|
<li><a href="#dates">날짜 고르기</a></li>
|
||||||
<li><a href="#list">목록 보기</a></li>
|
<li><a href="#list">목록 보기</a></li>
|
||||||
<li><a href="#calendar">캘린더 보기</a></li>
|
<li><a href="#calendar">캘린더 보기</a></li>
|
||||||
<li><a href="#timeline">타임라인 보기</a></li>
|
<li><a href="#timeline">타임라인 보기</a></li>
|
||||||
<li><a href="#dashboard">대시보드</a></li>
|
<li><a href="#dashboard">대시보드</a></li>
|
||||||
<li><a href="#mytasks">내 작업</a></li>
|
<li><a href="#mytasks">내 업무</a></li>
|
||||||
<li><a href="#comments">댓글과 @태그</a></li>
|
<li><a href="#comments">댓글과 @태그</a></li>
|
||||||
<li><a href="#inbox">수신함과 알림</a></li>
|
<li><a href="#inbox">수신함과 알림</a></li>
|
||||||
<li><a href="#search">전체 검색과 공유 링크</a></li>
|
<li><a href="#search">전체 검색과 공유 링크</a></li>
|
||||||
<li><a href="#trash">휴지통 (관리자)</a></li>
|
<li><a href="#trash">휴지통 (Pro user 이상)</a></li>
|
||||||
|
<li><a href="#goals">연간 목표</a></li>
|
||||||
|
<li><a href="#meetings">주간 회의록</a></li>
|
||||||
<li><a href="#tips">단축키와 자주 묻는 질문</a></li>
|
<li><a href="#tips">단축키와 자주 묻는 질문</a></li>
|
||||||
</ol>
|
</ol>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div class="pjh-body">
|
<div class="pjh-body">
|
||||||
|
<div class="pjh-search" id="pjh-search" hidden>
|
||||||
|
<form id="pjh-search-form" role="search" aria-label="도움말 검색">
|
||||||
|
<label for="pjh-query">도움말 검색</label>
|
||||||
|
<div class="pjh-search-field">
|
||||||
|
<input type="search" id="pjh-query" name="q" placeholder="예: 회의록, 셀 병합, 매출 갱신" autocomplete="off"
|
||||||
|
aria-describedby="pjh-search-hint pjh-search-status" aria-controls="pjh-results" />
|
||||||
|
<button type="submit">검색</button>
|
||||||
|
<button type="button" id="pjh-search-clear" hidden>지우기</button>
|
||||||
|
</div>
|
||||||
|
<p class="pjh-search-hint" id="pjh-search-hint">한 글자부터 제목·본문을 검색합니다. 결과를 누르면 해당 설명으로 바로 이동합니다. 여러 단어는 띄어 쓰세요.</p>
|
||||||
|
</form>
|
||||||
|
<p class="pjh-search-status" id="pjh-search-status" role="status" aria-live="polite" aria-atomic="true"></p>
|
||||||
|
<ol class="pjh-results" id="pjh-results" aria-label="도움말 검색 결과" hidden></ol>
|
||||||
|
</div>
|
||||||
<!-- 머리말 + 빠른 시작 -->
|
<!-- 머리말 + 빠른 시작 -->
|
||||||
<header class="pjh-hero" id="top">
|
<header class="pjh-hero">
|
||||||
<h1>프로젝트 관리 도움말</h1>
|
<h1>프로젝트 관리 도움말</h1>
|
||||||
<p>프로젝트 관리는 <b>아사나(Asana) 방식</b>으로 팀의 일을 정리하는 도구입니다.
|
<p>프로젝트 관리는 <b>아사나(Asana) 방식</b>으로 팀의 일을 정리하는 도구입니다.
|
||||||
프로젝트 안에 할 일(작업)을 만들고, 담당자와 마감일을 정하고, 댓글로 이야기하며 끝까지 챙깁니다.
|
프로젝트 안에 할 일(업무)을 만들고, 담당자와 마감일을 정하고, 댓글로 이야기하며 끝까지 챙깁니다.
|
||||||
처음이라면 아래 다섯 단계만 따라 해도 바로 쓸 수 있어요.</p>
|
처음이라면 아래 다섯 단계만 따라 해도 바로 쓸 수 있어요.</p>
|
||||||
<div class="pjh-quick">
|
<div class="pjh-quick">
|
||||||
<div class="pjh-quick-step"><b>1단계</b>왼쪽 목록에서 <b style="display:inline;color:inherit">프로젝트</b>를 누릅니다.</div>
|
<div class="pjh-quick-step"><b>1단계</b>왼쪽 목록에서 <b style="display:inline;color:inherit">프로젝트</b>를 누릅니다.</div>
|
||||||
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 작업 추가</span>로 할 일을 만듭니다.</div>
|
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 메인 업무 추가</span>로 할 일을 만듭니다.</div>
|
||||||
<div class="pjh-quick-step"><b>3단계</b>카드의 사람·달력 아이콘으로 담당자와 마감일을 정합니다.</div>
|
<div class="pjh-quick-step"><b>3단계</b>카드의 사람·달력 아이콘으로 담당자와 마감일을 정합니다.</div>
|
||||||
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
|
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
|
||||||
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
|
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
|
||||||
</div>
|
</div>
|
||||||
|
<p class="pjh-quick-links">계획과 회의를 준비한다면 <a href="#goals">연간 목표</a> · <a href="#meetings">주간 회의록</a> 설명부터 읽어 보세요.</p>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- 1. 용어 -->
|
<!-- 1. 용어 -->
|
||||||
@@ -62,15 +79,15 @@
|
|||||||
<tr><th>용어</th><th>뜻</th></tr>
|
<tr><th>용어</th><th>뜻</th></tr>
|
||||||
<tr><td>프로젝트</td><td>함께 진행하는 일의 큰 묶음입니다. 예) “마케팅”, “신상품 출시”. 색상과 아이콘으로 구분합니다.</td></tr>
|
<tr><td>프로젝트</td><td>함께 진행하는 일의 큰 묶음입니다. 예) “마케팅”, “신상품 출시”. 색상과 아이콘으로 구분합니다.</td></tr>
|
||||||
<tr><td>섹션</td><td>프로젝트 안의 단계나 분류입니다. 보드에서 세로 칸 하나가 섹션입니다. 예) “할 일 · 진행 중 · 검토 · 완료”.</td></tr>
|
<tr><td>섹션</td><td>프로젝트 안의 단계나 분류입니다. 보드에서 세로 칸 하나가 섹션입니다. 예) “할 일 · 진행 중 · 검토 · 완료”.</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>업무를 더 잘게 나눈 할 일입니다. 업무 안에 목록으로 붙습니다. 원래 업무는 <b>상위 업무</b>라고 부릅니다.</td></tr>
|
||||||
<tr><td>담당자</td><td>그 작업을 책임지고 하는 사람 한 명입니다.</td></tr>
|
<tr><td>담당자</td><td>그 업무를 책임지고 하는 사람 한 명입니다.</td></tr>
|
||||||
<tr><td>협업자</td><td>작업의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
|
<tr><td>협업자</td><td>업무의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
|
||||||
<tr><td>마감일 / 시작일</td><td>언제까지 끝낼지(마감일), 언제 시작하는지(시작일, 선택)입니다.</td></tr>
|
<tr><td>마감일 / 시작일</td><td>언제까지 끝낼지(마감일), 언제 시작하는지(시작일, 선택)입니다.</td></tr>
|
||||||
<tr><td>우선순위</td><td>높음 · 보통 · 낮음. 급한 일을 표시합니다.</td></tr>
|
<tr><td>우선순위</td><td>높음 · 보통 · 낮음. 급한 일을 표시합니다.</td></tr>
|
||||||
<tr><td>@태그</td><td>설명이나 댓글에서 <kbd>@</kbd>를 누르고 사람을 고르면, 그 사람의 수신함에 작업이 쌓입니다.</td></tr>
|
<tr><td>@태그</td><td>설명이나 댓글에서 <kbd>@</kbd>를 누르고 사람을 고르면, 그 사람의 수신함에 업무가 쌓입니다.</td></tr>
|
||||||
<tr><td>수신함</td><td>나를 태그한 작업과 나에게 온 알림을 모아 보는 곳입니다.</td></tr>
|
<tr><td>수신함</td><td>나를 태그한 업무와 나에게 온 알림을 모아 보는 곳입니다.</td></tr>
|
||||||
<tr><td>내 작업</td><td>모든 프로젝트에서 내가 담당자인 작업만 모아 보는 곳입니다.</td></tr>
|
<tr><td>내 업무</td><td>모든 프로젝트에서 내가 담당자인 업무만 모아 보는 곳입니다.</td></tr>
|
||||||
</table>
|
</table>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -78,32 +95,32 @@
|
|||||||
<section class="pjh-sec" id="layout">
|
<section class="pjh-sec" id="layout">
|
||||||
<h2><span class="pjh-num">2</span>화면 구성</h2>
|
<h2><span class="pjh-num">2</span>화면 구성</h2>
|
||||||
<div class="pjh-map" aria-hidden="true">
|
<div class="pjh-map" aria-hidden="true">
|
||||||
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말</span></div>
|
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div>
|
||||||
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||||
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>오른쪽 위: 범위(이 프로젝트 / 전체 프로젝트)<br>필터 바<br>작업들</div>
|
<div class="pjh-map-main"><b>가운데 업무 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>업무들</div>
|
||||||
</div>
|
</div>
|
||||||
<h3>왼쪽 사이드바</h3>
|
<h3>왼쪽 사이드바</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 작업을 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
|
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 업무를 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
|
||||||
<li><b>수신함</b> — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
<li><b>수신함</b> — 나를 태그한 업무와 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
||||||
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
|
<li><b>내 업무</b> — 내가 담당자인 업무 모음. 숫자 배지는 아직 끝나지 않은 업무 수입니다. (<a href="#mytasks">15장</a>)</li>
|
||||||
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
<li><b>휴지통</b> — 지운 업무를 3개월 보관합니다. Pro user 이상에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||||
<li><b>목표</b> — 누르면 바로 아래에 연도가 펼쳐집니다. 연도를 누르면 오른쪽에 그해 전체 목표가 한 표로 나옵니다 —
|
<li>왼쪽 메뉴의 오른쪽 경계를 끌면 너비를 최소 170px까지 줄일 수 있습니다. 경계에 키보드 포커스를 놓고 좌우 방향키로도 조절할 수 있으며 너비는 내 브라우저에 기억됩니다. 전체 멤버는 메뉴 너비에 맞춰 4열 또는 3열로 자동 배치됩니다.</li>
|
||||||
맨 위에 <b>매출</b>(목표·실적·달성률)과 <b>로아스</b>(목표·실적)를 달마다, 그 아래에 <b>업무 영역</b>(상품·마케팅·컨텐츠·유통 등)별로
|
<li><b>목표</b> — 연도를 골라 매출·로아스와 업무 영역별 연간·분기·월 계획을 봅니다. (<a href="#goals">연간 목표 설명</a>)</li>
|
||||||
연간·월별 계획을 적습니다. 매출의 <b>연간</b> 칸은 월 합계, <b>달성</b>은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다.
|
<li><b>주간 회의록</b> — 목표 표의 월 이름을 눌러 이번주 계획과 지난주 리뷰를 함께 봅니다. (<a href="#meetings">주간 회의록 설명</a>)</li>
|
||||||
<b>입력은 관리자만</b> 할 수 있고(칸을 고치면 바로 저장), 다른 직원은 보기만 합니다. 관리자는 <b>+ 연도 추가</b>로 새해 목표를
|
|
||||||
만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역 이름 칸에 마우스를 올려 이름·색·순서·줄 추가·삭제를 합니다.</li>
|
|
||||||
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
||||||
<li><b>전체 멤버</b> — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
<li><b>전체 멤버</b> — Pro user 이상에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 업무를 한눈에 봅니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>위쪽 바</h3>
|
<h3>위쪽 바</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">notifications</span></span> 종 아이콘 — 읽지 않은 알림 수가 표시되고, 누르면 수신함으로 갑니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">notifications</span></span> 종 아이콘 — 읽지 않은 알림 수가 표시되고, 누르면 수신함으로 갑니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">fit_screen</span></span> 화면 배율 — 누르면(파랗게 켜짐) 화면 전체를 75%로 줄입니다. 2880×1620 모니터를 Windows 배율 200%로 쓰면 화면이 꽉 차 보이는데, 이때 켜면 1920×1080 모니터와 같은 모습이 됩니다. 브라우저마다 기억합니다. 메뉴·말풍선 같은 작은 팝업은 원래 크기로 뜹니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">fit_screen</span></span> 화면 배율 — 누르면(파랗게 켜짐) 화면 전체를 75%로 줄입니다. 2880×1620 모니터를 Windows 배율 200%로 쓰면 화면이 꽉 차 보이는데, 이때 켜면 1920×1080 모니터와 같은 모습이 됩니다. 브라우저마다 기억합니다. 메뉴·말풍선 같은 작은 팝업은 원래 크기로 뜹니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
|
||||||
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 폰트를 고르고 미리 본 뒤 <span class="pjh-ui">저장</span>을 누르면 Project 화면에 적용되고 창이 닫힙니다.
|
||||||
|
기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드 중 선택할 수 있습니다. 설정은 이 브라우저의 모든 Project 화면에서 기억합니다. <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>프로젝트 제목</h3>
|
<h3>프로젝트 제목</h3>
|
||||||
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버·관리자만)</p>
|
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p>
|
||||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||||
<div>여러 사람이 동시에 써도 걱정 없습니다. 다른 사람이 바꾼 내용은 <b>약 8초 안에</b> 내 화면에 자동으로 반영됩니다(새로고침하지 않아도 됩니다). 내가 입력 중인 창은 건드리지 않습니다.</div></div>
|
<div>여러 사람이 동시에 써도 걱정 없습니다. 다른 사람이 바꾼 내용은 <b>약 8초 안에</b> 내 화면에 자동으로 반영됩니다(새로고침하지 않아도 됩니다). 내가 입력 중인 창은 건드리지 않습니다.</div></div>
|
||||||
</section>
|
</section>
|
||||||
@@ -111,26 +128,52 @@
|
|||||||
<!-- 3. 권한 -->
|
<!-- 3. 권한 -->
|
||||||
<section class="pjh-sec" id="roles">
|
<section class="pjh-sec" id="roles">
|
||||||
<h2><span class="pjh-num">3</span>누가 무엇을 할 수 있나요</h2>
|
<h2><span class="pjh-num">3</span>누가 무엇을 할 수 있나요</h2>
|
||||||
<p class="pjh-lead">프로젝트 관리 메뉴는 관리자 페이지에서 “프로젝트 관리” 권한을 받은 직원에게 보입니다.</p>
|
<p class="pjh-lead">프로젝트 관리 메뉴는 관리자 페이지에서 “프로젝트 관리” 권한을 받은 직원에게 보입니다.
|
||||||
|
등급은 <b>수퍼관리자 · Admin · Pro user · User</b> 네 가지이며(관리자 페이지에서 지정, 수퍼관리자는 한 명으로 고정), 등급과 상관없이
|
||||||
|
<b>그 프로젝트의 멤버·소유자만</b> 프로젝트를 볼 수 있습니다(수퍼관리자만 예외).</p>
|
||||||
|
<h3>프로젝트</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>할 수 있는 일</th><th>누가</th></tr>
|
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
|
||||||
<tr><td>프로젝트 보기</td><td>그 프로젝트의 <b>멤버</b>(또는 관리자). 멤버가 아니면 주소를 알아도 열리지 않습니다.</td></tr>
|
<tr><td>프로젝트 보기, 업무·섹션 만들기·고치기·옮기기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||||
<tr><td>작업·하위 작업·댓글</td><td>그 프로젝트 멤버 누구나 만들고 고칠 수 있습니다.</td></tr>
|
<tr><td>업무 삭제(휴지통으로)</td><td>O</td><td>O</td><td>O</td></tr>
|
||||||
<tr><td>작업·섹션·프로젝트 삭제</td><td><b>만든 사람만</b> 지울 수 있습니다(최고 관리자는 예외).</td></tr>
|
<tr><td>섹션 삭제</td><td>O</td><td>만든 사람만</td><td>만든 사람만</td></tr>
|
||||||
<tr><td>댓글 고치기·지우기</td><td>댓글을 쓴 사람(또는 관리자)만.</td></tr>
|
<tr><td>서브프로젝트 만들기</td><td>O</td><td>O</td><td>O</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>새 프로젝트 만들기 (<span class="pjh-ui">+</span>)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
<tr><td>멤버 배정·제외, 프로젝트 소유자 바꾸기</td><td>관리자</td></tr>
|
<tr><td>프로젝트 이름·색·아이콘 수정 (<span class="pjh-ui">✎</span>·제목 바로 고치기)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
<tr><td>다른 프로젝트에서 연결돼 온 작업</td><td>원래 프로젝트 멤버가 아니면 <b>읽기만</b> — 내용·댓글·첨부는 보이지만 고치거나 댓글을 달 수 없습니다(연결된 보드 안에서 섹션 옮기기는 됩니다).</td></tr>
|
<tr><td>프로젝트 소유자 바꾸기</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
<tr><td>멤버에서 빠졌을 때</td><td>그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고, 예전 링크로도 열리지 않습니다. 새 알림도 오지 않습니다.</td></tr>
|
<tr><td>프로젝트 삭제</td><td>O</td><td>만든 사람만</td><td>만든 사람만</td></tr>
|
||||||
<tr><td>휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트</td><td>관리자</td></tr>
|
<tr><td>멤버 배정·제외</td><td>O</td><td>O (자기가 멤버인 프로젝트)</td><td>X</td></tr>
|
||||||
<tr><td>목표 보기</td><td>누구나 · <b>목표 입력·연도 추가·업무 영역 편집</b>은 관리자</td></tr>
|
<tr><td>사이드바 프로젝트 순서 바꾸기 (<span class="pjh-ui">⣿</span>)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
|
<tr><td>댓글 고치기·지우기</td><td>O</td><td>남의 댓글도</td><td>본인 댓글만</td></tr>
|
||||||
|
<tr><td>휴지통 보기·복구</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
|
<tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td>O</td><td>O (멤버인 프로젝트 범위)</td><td>X</td></tr>
|
||||||
|
<tr><td>대시보드 “담당자별 업무 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr>
|
||||||
|
<tr><td>사이드바 “전체 멤버”</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
|
<tr><td>수신함·내 업무·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr>
|
||||||
|
</table>
|
||||||
|
<p>만든 사람 기록이 없는 옛 섹션·프로젝트는 Admin 이상만 지울 수 있습니다. 다른 프로젝트에서 연결돼 온 업무는 원래 프로젝트 멤버가 아니면
|
||||||
|
<b>읽기만</b> 됩니다(연결된 보드 안에서 섹션 옮기기는 됩니다). 멤버에서 빠지면 그 프로젝트의 업무는 내 업무·수신함·알림·검색에서 사라지고,
|
||||||
|
예전 링크로도 열리지 않습니다.</p>
|
||||||
|
<h3>목표·주간 회의록</h3>
|
||||||
|
<table class="pjh-table">
|
||||||
|
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
|
||||||
|
<tr><td>연간 목표 표 보기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||||
|
<tr><td>목표 표 입력·구조 변경(매출·로아스, 영역·줄, 칸 병합·이동)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
|
<tr><td>주차별 매출 목표·월 전체 목표 입력</td><td>O</td><td>O</td><td>X (값 보기만)</td></tr>
|
||||||
|
<tr><td>연도 추가·삭제</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
|
<tr><td>회의록 만들기·글 수정·줄 추가·삭제·칸 병합</td><td>O</td><td>O</td><td>O (완료 전까지)</td></tr>
|
||||||
|
<tr><td>지난주 결과 입력</td><td>O</td><td>O</td><td>O (다음 주 회의록이 열려 있는 동안)</td></tr>
|
||||||
|
<tr><td>회의 완료·완료 해제(완료하면 수정 잠금)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
|
<tr><td>회의록 삭제</td><td>O</td><td>O</td><td>X</td></tr>
|
||||||
|
<tr><td>회의록 보드 열기·링크 복사</td><td>O</td><td>O</td><td>O</td></tr>
|
||||||
|
<tr><td>회의록 “업무 등록 표”로 업무 만들기</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td></tr>
|
||||||
</table>
|
</table>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 4. 프로젝트 -->
|
<!-- 4. 프로젝트 -->
|
||||||
<section class="pjh-sec" id="project">
|
<section class="pjh-sec" id="project">
|
||||||
<h2><span class="pjh-num">4</span>프로젝트 만들기·고치기</h2>
|
<h2><span class="pjh-num">4</span>프로젝트 만들기·고치기</h2>
|
||||||
<h3>새 프로젝트 만들기 (관리자)</h3>
|
<h3>새 프로젝트 만들기 (Pro user 이상)</h3>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li>왼쪽 사이드바 <b>프로젝트</b> 제목 옆의 <span class="pjh-ui">+</span>를 누릅니다.</li>
|
<li>왼쪽 사이드바 <b>프로젝트</b> 제목 옆의 <span class="pjh-ui">+</span>를 누릅니다.</li>
|
||||||
<li><b>이름</b>(필수)과 <b>설명</b>을 적습니다.</li>
|
<li><b>이름</b>(필수)과 <b>설명</b>을 적습니다.</li>
|
||||||
@@ -138,9 +181,13 @@
|
|||||||
<li><b>색상</b>(32가지)과 <b>아이콘</b>을 고릅니다. 아이콘 첫 칸 <span class="pjh-ui">Aa</span>를 고르면 아이콘 대신 이름 첫 글자가 나옵니다.</li>
|
<li><b>색상</b>(32가지)과 <b>아이콘</b>을 고릅니다. 아이콘 첫 칸 <span class="pjh-ui">Aa</span>를 고르면 아이콘 대신 이름 첫 글자가 나옵니다.</li>
|
||||||
<li>함께할 <b>멤버</b>에 체크하고 <span class="pjh-ui">만들기</span>를 누릅니다. 만든 사람은 자동으로 프로젝트 주인이 됩니다.</li>
|
<li>함께할 <b>멤버</b>에 체크하고 <span class="pjh-ui">만들기</span>를 누릅니다. 만든 사람은 자동으로 프로젝트 주인이 됩니다.</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
<p>프로젝트는 만들어졌는데 일부 멤버를 배정하지 못하면 창이 닫히지 않고 <b>배정하지 못한 멤버</b>가 빨갛게 표시됩니다.
|
||||||
|
<span class="pjh-ui">실패한 멤버 다시 배정</span>을 누르면 그 멤버만 다시 배정합니다(프로젝트를 또 만들지 않습니다).
|
||||||
|
창을 닫으면 만든 프로젝트로 넘어가며, 남은 멤버는 프로젝트 화면에서 배정하면 됩니다.
|
||||||
|
다른 사람을 소유자로 정해 만들면 만든 사람은 일반 멤버로 함께 들어갑니다(나중에 멤버에서 뺄 수 있습니다).</p>
|
||||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
||||||
<div>새 프로젝트는 섹션 없이 빈 보드로 시작합니다. 보드의 <span class="pjh-ui">+ 섹션 추가</span>로 “할 일 · 진행 중 · 완료”처럼 단계를 먼저 만들어 두면 편합니다. (<a href="#board">6장</a>)</div></div>
|
<div>새 프로젝트는 섹션 없이 빈 보드로 시작합니다. 보드의 <span class="pjh-ui">+ 섹션 추가</span>로 “할 일 · 진행 중 · 완료”처럼 단계를 먼저 만들어 두면 편합니다. (<a href="#board">6장</a>)</div></div>
|
||||||
<h3>프로젝트 수정 (관리자)</h3>
|
<h3>프로젝트 수정 (Pro user 이상)</h3>
|
||||||
<p>사이드바의 프로젝트 이름에 마우스를 올리면 오른쪽에 <span class="pjh-ui">✎</span>(수정)과 <span class="pjh-ui">×</span>(삭제)가 나옵니다.
|
<p>사이드바의 프로젝트 이름에 마우스를 올리면 오른쪽에 <span class="pjh-ui">✎</span>(수정)과 <span class="pjh-ui">×</span>(삭제)가 나옵니다.
|
||||||
이름에서 <b>마우스 오른쪽 버튼</b>을 눌러도 <span class="pjh-ui">열기 · 수정 · 삭제</span> 메뉴가 나옵니다.</p>
|
이름에서 <b>마우스 오른쪽 버튼</b>을 눌러도 <span class="pjh-ui">열기 · 수정 · 삭제</span> 메뉴가 나옵니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
@@ -148,17 +195,18 @@
|
|||||||
<li><b>프로젝트 완료</b>에 체크하면 목록 맨 아래 “완료 프로젝트”로 옮겨지고 흐리게 보입니다.</li>
|
<li><b>프로젝트 완료</b>에 체크하면 목록 맨 아래 “완료 프로젝트”로 옮겨지고 흐리게 보입니다.</li>
|
||||||
<li>색이 밝으면(연노랑·하늘색 등) 글자와 아이콘이 자동으로 어둡게 바뀌어 잘 보입니다.</li>
|
<li>색이 밝으면(연노랑·하늘색 등) 글자와 아이콘이 자동으로 어둡게 바뀌어 잘 보입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>순서 바꾸기 (관리자)</h3>
|
<h3>순서 바꾸기 (Pro user 이상)</h3>
|
||||||
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.</p>
|
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.
|
||||||
|
순서는 모두가 같이 보는 순서이고, 내가 멤버인 프로젝트만 옮길 수 있습니다.</p>
|
||||||
<h3>프로젝트 삭제</h3>
|
<h3>프로젝트 삭제</h3>
|
||||||
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람만</b> 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
|
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 업무도 모두 함께 지워집니다.</p>
|
||||||
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
|
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
|
||||||
<div>프로젝트 삭제는 되돌릴 수 없습니다. 끝난 프로젝트는 지우기보다 <b>프로젝트 완료</b>로 표시하는 것을 권합니다.</div></div>
|
<div>프로젝트 삭제는 되돌릴 수 없습니다. 끝난 프로젝트는 지우기보다 <b>프로젝트 완료</b>로 표시하는 것을 권합니다.</div></div>
|
||||||
<h3>멤버 배정 (관리자)</h3>
|
<h3>멤버 배정 (Pro user 이상)</h3>
|
||||||
<p>프로젝트 화면 제목 오른쪽에 멤버 사진이 겹쳐서 보입니다.</p>
|
<p>프로젝트 화면 제목 오른쪽에 멤버 사진이 겹쳐서 보입니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="pjh-ui">+</span> — 멤버를 추가합니다(프로젝트 관리 권한이 있는 직원 중에서 고릅니다).</li>
|
<li><span class="pjh-ui">+</span> — 멤버 배정·제외 창이 열립니다. 지금 멤버는 체크된 채로 나오며, <b>체크하면 배정, 체크를 풀면 제외</b>됩니다(제외는 확인 후). 후보는 프로젝트 관리 권한이 있는 직원이고, 소유자는 뺄 수 없습니다.</li>
|
||||||
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 작업 목록이 뜹니다.</li>
|
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 업무 목록이 뜹니다.</li>
|
||||||
<li>사진에서 <b>우클릭</b> → <span class="pjh-ui">제외</span>로 멤버에서 뺍니다.</li>
|
<li>사진에서 <b>우클릭</b> → <span class="pjh-ui">제외</span>로 멤버에서 뺍니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
@@ -167,7 +215,7 @@
|
|||||||
<section class="pjh-sec" id="views">
|
<section class="pjh-sec" id="views">
|
||||||
<h2><span class="pjh-num">5</span>보기 전환과 필터</h2>
|
<h2><span class="pjh-num">5</span>보기 전환과 필터</h2>
|
||||||
<h3>보기 탭</h3>
|
<h3>보기 탭</h3>
|
||||||
<p>프로젝트 화면 맨 위 왼쪽의 탭으로 같은 작업을 다른 모양으로 봅니다.</p>
|
<p>프로젝트 화면 맨 위 왼쪽의 탭으로 같은 업무를 다른 모양으로 봅니다.</p>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>탭</th><th>이럴 때 좋아요</th></tr>
|
<tr><th>탭</th><th>이럴 때 좋아요</th></tr>
|
||||||
<tr><td>보드</td><td>섹션(단계)별 카드로 흐름을 볼 때. 카드를 끌어 단계를 옮깁니다. (<a href="#board">6장</a>)</td></tr>
|
<tr><td>보드</td><td>섹션(단계)별 카드로 흐름을 볼 때. 카드를 끌어 단계를 옮깁니다. (<a href="#board">6장</a>)</td></tr>
|
||||||
@@ -177,10 +225,12 @@
|
|||||||
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
|
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
|
||||||
</table>
|
</table>
|
||||||
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
|
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
|
||||||
<p>화면 오른쪽 위 토글입니다. <b>이 프로젝트</b>는 지금 프로젝트만, <b>전체 프로젝트</b>는 내가 볼 수 있는 모든 프로젝트의 작업을 함께 보여줍니다.
|
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
|
||||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.</p>
|
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
|
||||||
|
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 업무인지 이름이 붙습니다.
|
||||||
|
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 업무</b>도 한 번씩 함께 보입니다.</p>
|
||||||
<h3>필터 바</h3>
|
<h3>필터 바</h3>
|
||||||
<p>탭 아래 한 줄로 작업을 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
<p>탭 아래 한 줄로 업무를 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>찾기</b> — 제목·설명·담당자에 들어간 글자로 거릅니다.</li>
|
<li><b>찾기</b> — 제목·설명·담당자에 들어간 글자로 거릅니다.</li>
|
||||||
<li><b>상태</b> — 전체 / 미완료 / 완료</li>
|
<li><b>상태</b> — 전체 / 미완료 / 완료</li>
|
||||||
@@ -196,60 +246,64 @@
|
|||||||
|
|
||||||
<!-- 6. 보드 -->
|
<!-- 6. 보드 -->
|
||||||
<section class="pjh-sec" id="board">
|
<section class="pjh-sec" id="board">
|
||||||
<h2><span class="pjh-num">6</span>보드 — 섹션과 작업 카드</h2>
|
<h2><span class="pjh-num">6</span>보드 — 섹션과 업무 카드</h2>
|
||||||
<p class="pjh-lead">보드는 섹션(세로 칸)이 옆으로 늘어선 화면입니다. 섹션이 많으면 가로로 스크롤되고, 한 섹션에 카드가 많으면 그 섹션 안에서만 세로로 스크롤됩니다.</p>
|
<p class="pjh-lead">보드는 섹션(세로 칸)이 옆으로 늘어선 화면입니다. 섹션이 많으면 가로로 스크롤되고, 한 섹션에 카드가 많으면 그 섹션 안에서만 세로로 스크롤됩니다.</p>
|
||||||
<h3>섹션 다루기</h3>
|
<h3>섹션 다루기</h3>
|
||||||
<ul>
|
<ul>
|
||||||
|
<li><b>그룹 축소</b> — 섹션 머리의 왼쪽 화살표를 누르면 카드가 숨겨지고 제목·업무 수가 세로로 표시됩니다. 반대 방향 화살표를 누르면 펼쳐집니다. 축소 상태는 내 브라우저에 기억됩니다.</li>
|
||||||
<li><b>섹션 추가</b> — 마지막 섹션 바로 오른쪽의 <span class="pjh-ui">+ 섹션 추가</span>.</li>
|
<li><b>섹션 추가</b> — 마지막 섹션 바로 오른쪽의 <span class="pjh-ui">+ 섹션 추가</span>.</li>
|
||||||
<li><b>이름 바꾸기</b> — 섹션 이름을 누르면 그 자리에서 고칩니다. <kbd>Enter</kbd> 저장, <kbd>Esc</kbd> 취소.</li>
|
<li><b>이름 바꾸기</b> — 섹션 이름을 누르면 그 자리에서 고칩니다. <kbd>Enter</kbd> 저장, <kbd>Esc</kbd> 취소.</li>
|
||||||
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
|
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
|
||||||
<li><b>… 메뉴</b>(머리 오른쪽 <span class="pjh-ui">…</span> 또는 머리 우클릭):
|
<li><b>… 메뉴</b>(머리 오른쪽 <span class="pjh-ui">…</span> 또는 머리 우클릭):
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="pjh-ui">작업 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
<li><span class="pjh-ui">메인 업무 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
||||||
<li><span class="pjh-ui">섹션 편집</span> — 색상과 <b>기본 담당자</b>를 정합니다. 색상 첫 칸(연회색)은 “색 없음”입니다.</li>
|
<li><span class="pjh-ui">섹션 편집</span> — 색상과 <b>기본 담당자</b>를 정합니다. 색상 첫 칸(연회색)은 “색 없음”입니다.</li>
|
||||||
<li><span class="pjh-ui">섹션 작업 모두 완료</span> — 그 섹션의 미완료 작업을 한 번에 완료합니다.</li>
|
<li><span class="pjh-ui">섹션 업무 모두 완료</span> — 그 섹션의 미완료 업무를 한 번에 완료합니다.</li>
|
||||||
<li><span class="pjh-ui">완료 섹션으로 지정</span> — 이 섹션으로 옮긴 카드는 <b>자동으로 완료</b>되고, 밖으로 빼면 다시 미완료가 됩니다. 완료 섹션은 흐리게, 보드 끝에 놓입니다.</li>
|
<li><span class="pjh-ui">완료 섹션으로 지정</span> — 이 섹션으로 옮긴 카드는 <b>자동으로 완료</b>되고, 밖으로 빼면 다시 미완료가 됩니다. 완료 섹션은 흐리게, 보드 끝에 놓입니다.</li>
|
||||||
<li><span class="pjh-ui">삭제</span> — 섹션을 만든 사람만. 안의 작업은 지워지지 않고 “미지정” 칸으로 모입니다.</li>
|
<li><span class="pjh-ui">삭제</span> — 섹션을 만든 사람만. 안의 업무는 지워지지 않고 “미지정” 칸으로 모입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
||||||
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 작업을 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 업무를 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
||||||
<h3>작업 카드 다루기</h3>
|
<h3>업무 카드 다루기</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span> 또는 섹션 맨 아래 <span class="pjh-ui">+ 작업 추가</span>. 오른쪽에 작업 편집 창이 열립니다.</li>
|
<li><b>상단 메인 업무 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 업무 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
||||||
<li><b>열기</b> — 카드를 누르면 오른쪽에 작업 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
<li><b>하단 메인 업무 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 메인 업무 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>업무 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 업무를 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
||||||
|
<li><b>열기</b> — 카드를 누르면 오른쪽에 업무 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
||||||
|
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 업무는 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 업무는 상태만 표시합니다.</li>
|
||||||
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
|
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
|
||||||
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.</li>
|
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.</li>
|
||||||
<li><b>우클릭 메뉴</b> — <span class="pjh-ui">열기 · 작업 링크 복사 · 완료로 표시 · 삭제</span></li>
|
<li><b>우클릭 메뉴</b> — <span class="pjh-ui">열기 · 업무 링크 복사 · 완료로 표시 · 삭제</span></li>
|
||||||
<li><b>댓글</b> — 카드의 <span class="pjh-ui">💬 N</span>을 한 번 누르면 댓글 대화창이 열립니다. (<a href="#comments">16장</a>)</li>
|
<li><b>댓글</b> — 카드의 <span class="pjh-ui">💬 N</span>을 한 번 누르면 댓글 대화창이 열립니다. (<a href="#comments">16장</a>)</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>마감일 색의 의미</h3>
|
<h3>마감일 색의 의미</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>표시</th><th>뜻</th></tr>
|
<tr><th>표시</th><th>뜻</th></tr>
|
||||||
<tr><td style="color:#3f8f6b">오늘 · 내일</td><td>곧 마감(초록)</td></tr>
|
<tr><td style="color:#3f8f6b">오늘 · 내일</td><td>곧 마감(초록)</td></tr>
|
||||||
<tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 작업도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr>
|
<tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 업무도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr>
|
||||||
<tr><td>09/30(수)</td><td>그 밖의 날짜(기본 글자색)</td></tr>
|
<tr><td>09/30(수)</td><td>그 밖의 날짜(기본 글자색)</td></tr>
|
||||||
</table>
|
</table>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 7. 카드의 하위 작업 -->
|
<!-- 7. 카드의 세부 작업 -->
|
||||||
<section class="pjh-sec" id="card-subtasks">
|
<section class="pjh-sec" id="card-subtasks">
|
||||||
<h2><span class="pjh-num">7</span>카드에서 하위 작업 다루기</h2>
|
<h2><span class="pjh-num">7</span>카드에서 세부 업무 다루기</h2>
|
||||||
<p class="pjh-lead">하위 작업이 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 하위 작업 목록이 펼쳐집니다.</p>
|
<p class="pjh-lead">세부 업무가 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 세부 업무 목록이 펼쳐집니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>완료</b> — 줄 왼쪽 <span class="pjh-ui">✓</span>를 누릅니다.</li>
|
<li><b>완료</b> — 줄 왼쪽 <span class="pjh-ui">✓</span>를 누릅니다.</li>
|
||||||
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
|
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
|
||||||
<li><b>열기</b> — 줄을 누르면 그 하위 작업이 작업처럼 편집 창으로 열립니다.</li>
|
<li><b>열기</b> — 줄을 누르면 그 세부 업무가 업무처럼 편집 창으로 열립니다.</li>
|
||||||
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 하위 작업 삭제</span></li>
|
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 업무 열기 · 완료로 표시 · 세부 업무 삭제</span></li>
|
||||||
<li><b>다른 작업으로 옮기기</b> — 하위 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 하위 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
<li><b>순서 바꾸기</b> — 펼친 세부 업무 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
||||||
|
<li><b>다른 업무로 옮기기</b> — 세부 업무 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 업무의 세부 업무가 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>+ 하위 작업 추가</h3>
|
<h3>+ 세부 업무 추가</h3>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 하위 작업 추가</span>를 누릅니다.</li>
|
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 세부 업무 추가</span>를 누릅니다.</li>
|
||||||
<li>새 줄의 “작업 이름 입력” 칸에 이름을 씁니다.</li>
|
<li>새 줄의 “업무 이름 입력” 칸에 이름을 씁니다.</li>
|
||||||
<li>필요하면 달력 아이콘으로 마감일, 사람 아이콘으로 담당자를 고릅니다.</li>
|
<li>필요하면 달력 아이콘으로 마감일, 사람 아이콘으로 담당자를 고릅니다.</li>
|
||||||
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 하위 작업을 이어서 쓸 수 있습니다.</li>
|
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 세부 업무를 이어서 쓸 수 있습니다.</li>
|
||||||
<li>이름을 쓴 채 <b>다른 곳을 누르면</b> <kbd>Enter</kbd>와 같이 만들어지고 줄이 닫힙니다.</li>
|
<li>이름을 쓴 채 <b>다른 곳을 누르면</b> <kbd>Enter</kbd>와 같이 만들어지고 줄이 닫힙니다.</li>
|
||||||
<li>만들지 않고 닫으려면 <kbd>Esc</kbd>를 누르거나, 빈 채로 다른 곳을 누릅니다.</li>
|
<li>만들지 않고 닫으려면 <kbd>Esc</kbd>를 누르거나, 빈 채로 다른 곳을 누릅니다.</li>
|
||||||
</ol>
|
</ol>
|
||||||
@@ -257,23 +311,23 @@
|
|||||||
|
|
||||||
<!-- 8. 작업 편집 창 -->
|
<!-- 8. 작업 편집 창 -->
|
||||||
<section class="pjh-sec" id="task">
|
<section class="pjh-sec" id="task">
|
||||||
<h2><span class="pjh-num">8</span>작업 편집 창</h2>
|
<h2><span class="pjh-num">8</span>업무 편집 창</h2>
|
||||||
<p class="pjh-lead">카드·목록 줄·캘린더 막대를 누르면 화면 오른쪽에 작업 편집 창이 열립니다. 창의 왼쪽 가장자리를 끌면 너비를 넓히거나 좁힐 수 있습니다.</p>
|
<p class="pjh-lead">카드·목록 줄·캘린더 막대를 누르면 화면 오른쪽에 업무 편집 창이 열립니다. 창의 왼쪽 가장자리를 끌면 너비를 넓히거나 좁힐 수 있습니다.</p>
|
||||||
<h3>맨 위 버튼</h3>
|
<h3>맨 위 버튼</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>버튼</th><th>하는 일</th></tr>
|
<tr><th>버튼</th><th>하는 일</th></tr>
|
||||||
<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 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>업무를 완료합니다. 다시 누르면 <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>업무를 지웁니다(만든 사람만). 세부 업무가 있으면 함께 지울지 한 번 더 묻습니다. 지운 업무는 휴지통에 3개월 보관됩니다.</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>
|
<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>
|
</table>
|
||||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||||
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 하위 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 업무는 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 세부 업무 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
||||||
<h3>제목과 기본 정보</h3>
|
<h3>제목과 기본 정보</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>제목</b> — 맨 위 큰 글씨를 눌러 바로 고칩니다.</li>
|
<li><b>제목</b> — 맨 위 큰 글씨를 눌러 바로 고칩니다.</li>
|
||||||
<li><b>담당자</b> — 사진+이름을 누르면 “아이콘 + 이름” 목록에서 고릅니다. <span class="pjh-ui">담당자 없음</span>도 있습니다.</li>
|
<li><b>담당자</b> — 사진+이름을 누르면 “아이콘 + 이름” 목록에서 고릅니다. <span class="pjh-ui">담당자 없음</span>도 있습니다.</li>
|
||||||
<li><b>섹션</b> — 이 작업이 들어갈 섹션을 고릅니다.</li>
|
<li><b>섹션</b> — 이 업무가 들어갈 섹션을 고릅니다.</li>
|
||||||
<li><b>우선순위</b> — 높음 · 보통 · 낮음</li>
|
<li><b>우선순위</b> — 높음 · 보통 · 낮음</li>
|
||||||
<li><b>마감일</b> — 달력 아이콘을 누르면 날짜 창이 열립니다. (<a href="#dates">10장</a>)</li>
|
<li><b>마감일</b> — 달력 아이콘을 누르면 날짜 창이 열립니다. (<a href="#dates">10장</a>)</li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -282,7 +336,7 @@
|
|||||||
<li>협업자는 사진+이름으로 보입니다. 사람에 마우스를 올리면 <span class="pjh-ui">×</span>가 나와 뺄 수 있습니다.</li>
|
<li>협업자는 사진+이름으로 보입니다. 사람에 마우스를 올리면 <span class="pjh-ui">×</span>가 나와 뺄 수 있습니다.</li>
|
||||||
<li>협업자가 없으면 점선 원 <span class="pjh-ui">협업자 없음</span>을 눌러 추가하고, 있으면 옆 <span class="pjh-ui">+</span>로 추가합니다.</li>
|
<li>협업자가 없으면 점선 원 <span class="pjh-ui">협업자 없음</span>을 눌러 추가하고, 있으면 옆 <span class="pjh-ui">+</span>로 추가합니다.</li>
|
||||||
<li>오른쪽 <span class="pjh-ui">협업자로 참여</span> / <span class="pjh-ui">협업자에서 나가기</span>로 나 자신을 넣고 뺍니다.</li>
|
<li>오른쪽 <span class="pjh-ui">협업자로 참여</span> / <span class="pjh-ui">협업자에서 나가기</span>로 나 자신을 넣고 뺍니다.</li>
|
||||||
<li>협업자에게는 작업 완료와 새 댓글 알림이 갑니다.</li>
|
<li>협업자에게는 업무 완료와 새 댓글 알림이 갑니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>설명</h3>
|
<h3>설명</h3>
|
||||||
<ul>
|
<ul>
|
||||||
@@ -290,39 +344,39 @@
|
|||||||
<li><b>체크박스(체크리스트)</b> — 글머리 목록처럼 씁니다. <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 지금 줄(또는 고른 줄들)이 체크리스트가 되어 줄마다 체크박스가 붙습니다. <kbd>Enter</kbd>로 새 줄을 만들면 체크박스도 함께 생기고, 빈 줄에서 <kbd>Enter</kbd>를 누르면 목록이 끝납니다. 체크박스를 누르면 체크되고 그 줄은 흐리게 취소선이 그어집니다. 다시 <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 평범한 글로, 글머리·번호 버튼을 누르면 그 목록으로 바뀝니다. 체크 상태도 바로 저장됩니다.</li>
|
<li><b>체크박스(체크리스트)</b> — 글머리 목록처럼 씁니다. <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 지금 줄(또는 고른 줄들)이 체크리스트가 되어 줄마다 체크박스가 붙습니다. <kbd>Enter</kbd>로 새 줄을 만들면 체크박스도 함께 생기고, 빈 줄에서 <kbd>Enter</kbd>를 누르면 목록이 끝납니다. 체크박스를 누르면 체크되고 그 줄은 흐리게 취소선이 그어집니다. 다시 <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 평범한 글로, 글머리·번호 버튼을 누르면 그 목록으로 바뀝니다. 체크 상태도 바로 저장됩니다.</li>
|
||||||
<li><b>이미지</b> — 캡처한 그림을 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 바로 붙여 넣을 수 있습니다. 그림을 누르면 모서리를 끌어 크기를 바꾸거나 지울 수 있습니다.</li>
|
<li><b>이미지</b> — 캡처한 그림을 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 바로 붙여 넣을 수 있습니다. 그림을 누르면 모서리를 끌어 크기를 바꾸거나 지울 수 있습니다.</li>
|
||||||
<li><b>링크</b> — 웹 주소를 붙여 넣으면 자동으로 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
<li><b>링크</b> — 웹 주소를 붙여 넣으면 자동으로 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||||
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 작업이 쌓입니다.</li>
|
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 업무가 쌓입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>첨부 파일</h3>
|
<h3>첨부 파일</h3>
|
||||||
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름 옆에 이미지·엑셀·텍스트·PPT·문서·PDF 형식별 아이콘이 표시됩니다. 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
||||||
<h3>프로젝트 (다른 프로젝트에 추가)</h3>
|
<h3>프로젝트 (다른 프로젝트에 추가)</h3>
|
||||||
<p>작업 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 작업을 디자인 프로젝트 보드에도 올리기.</p>
|
<p>업무 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 업무를 디자인 프로젝트 보드에도 올리기. 협업자 아래의 프로젝트 줄에 연결 목록·프로젝트 선택·섹션 선택·추가 버튼이 한 줄로 표시됩니다. 창이 좁으면 이 줄을 좌우로 스크롤할 수 있습니다.</p>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li>“프로젝트” 칸에서 프로젝트를 고릅니다.</li>
|
<li>“프로젝트” 칸에서 프로젝트를 고릅니다.</li>
|
||||||
<li>그 프로젝트에서 들어갈 섹션을 고릅니다.</li>
|
<li>그 프로젝트에서 들어갈 섹션을 고릅니다.</li>
|
||||||
<li><span class="pjh-ui">다른 프로젝트에 추가</span>를 누릅니다. 빼려면 이름 옆 <span class="pjh-ui">×</span>(연결 해제).</li>
|
<li><span class="pjh-ui">다른 프로젝트에 추가</span>를 누릅니다. 빼려면 이름 옆 <span class="pjh-ui">×</span>(연결 해제).</li>
|
||||||
</ol>
|
</ol>
|
||||||
<p>작업은 하나라서 어느 보드에서 고쳐도 모두 같이 바뀝니다.</p>
|
<p>업무는 하나라서 원래 프로젝트에서 고친 내용이 연결된 보드에도 반영됩니다. 원래 프로젝트의 멤버가 아니면 연결된 업무의 내용·댓글·첨부는 읽기만 할 수 있습니다. 연결된 보드 안에서 섹션을 옮기는 것은 가능합니다.</p>
|
||||||
<h3>댓글</h3>
|
<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>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <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>
|
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 업무를 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 9. 작업 창의 하위 작업 -->
|
<!-- 9. 작업 창의 세부 작업 -->
|
||||||
<section class="pjh-sec" id="subtasks">
|
<section class="pjh-sec" id="subtasks">
|
||||||
<h2><span class="pjh-num">9</span>작업 창의 하위 작업</h2>
|
<h2><span class="pjh-num">9</span>업무 창의 세부 업무</h2>
|
||||||
<p class="pjh-lead">작업 편집 창 가운데 “하위 작업” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
<p class="pjh-lead">업무 편집 창 가운데 “세부 업무” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>추가</b> — 목록 아래 입력칸에 이름을 쓰고, 필요하면 담당자·마감일을 고른 뒤 <span class="pjh-ui">추가</span> 또는 <kbd>Enter</kbd>.</li>
|
<li><b>추가</b> — 목록 아래 입력칸에 이름을 쓰고, 필요하면 담당자·마감일을 고른 뒤 <span class="pjh-ui">추가</span> 또는 <kbd>Enter</kbd>.</li>
|
||||||
<li><b>순서 바꾸기</b> — 줄에 마우스를 올리면 왼쪽에 <span class="pjh-ui">⠿</span> 손잡이가 나옵니다. 잡고 위아래로 끌어 놓습니다.</li>
|
<li><b>순서 바꾸기</b> — 줄에 마우스를 올리면 왼쪽에 <span class="pjh-ui">⠿</span> 손잡이가 나옵니다. 잡고 위아래로 끌어 놓습니다.</li>
|
||||||
<li><b>완료</b> — <span class="pjh-ui">✓</span>를 누릅니다. 완료한 줄은 취소선이 그어집니다.</li>
|
<li><b>완료</b> — <span class="pjh-ui">✓</span>를 누릅니다. 완료한 줄은 취소선이 그어집니다.</li>
|
||||||
<li><b>이름 고치기</b> — 이름 글자를 눌러 바로 고칩니다(칸은 이름 길이만큼만 차지합니다).</li>
|
<li><b>이름 고치기</b> — 이름 글자를 눌러 바로 고칩니다(칸은 이름 길이만큼만 차지합니다).</li>
|
||||||
<li><b>마감일·담당자</b> — 날짜 글자나 사람 아이콘을 누릅니다. 비어 있으면 줄에 마우스를 올렸을 때 점선 아이콘이 나옵니다.</li>
|
<li><b>마감일·담당자</b> — 날짜 글자나 사람 아이콘을 누릅니다. 비어 있으면 줄에 마우스를 올렸을 때 점선 아이콘이 나옵니다.</li>
|
||||||
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 하위 작업이 편집 창으로 열립니다.</li>
|
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 세부 업무가 편집 창으로 열립니다.</li>
|
||||||
<li><b>하위 작업의 하위 작업</b> — 그 하위 작업 안에도 하위 작업이 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
<li><b>세부 업무의 세부 업무</b> — 그 세부 업무 안에도 세부 업무가 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
||||||
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">하위 작업 삭제</span>.</li>
|
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">세부 업무 삭제</span>.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>하위 작업을 열었을 때</h3>
|
<h3>세부 업무를 열었을 때</h3>
|
||||||
<p>하위 작업도 작업과 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 작업 이름</span>이 보이고, 누르면 상위 작업으로 돌아갑니다. 하위 작업에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
<p>세부 업무도 업무와 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 업무 이름</span>이 보이고, 누르면 상위 업무로 돌아갑니다. 세부 업무에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 10. 날짜 -->
|
<!-- 10. 날짜 -->
|
||||||
@@ -337,7 +391,7 @@
|
|||||||
<li>창 바깥을 누르거나 <kbd>Esc</kbd>로 닫습니다.</li>
|
<li>창 바깥을 누르거나 <kbd>Esc</kbd>로 닫습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||||
<div>보드 카드와 하위 작업 줄에서는 날짜를 누르는 즉시 저장됩니다. 작업 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
<div>보드 카드와 세부 업무 줄에서는 날짜를 누르는 즉시 저장됩니다. 업무 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 11. 목록 -->
|
<!-- 11. 목록 -->
|
||||||
@@ -345,9 +399,9 @@
|
|||||||
<h2><span class="pjh-num">11</span>목록 보기</h2>
|
<h2><span class="pjh-num">11</span>목록 보기</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>이 프로젝트</b> 범위에서는 섹션별로 묶여 보이고, <b>전체 프로젝트</b>에서는 프로젝트·섹션이 칸으로 나오는 표가 됩니다.</li>
|
<li><b>이 프로젝트</b> 범위에서는 섹션별로 묶여 보이고, <b>전체 프로젝트</b>에서는 프로젝트·섹션이 칸으로 나오는 표가 됩니다.</li>
|
||||||
<li>칸 제목(작업 · 담당자 · 섹션 · 우선순위 · 시작 · 마감)을 누르면 그 기준으로 정렬하고, 한 번 더 누르면 반대로 정렬합니다.</li>
|
<li>칸 제목(업무 · 담당자 · 섹션 · 우선순위 · 시작 · 마감)을 누르면 그 기준으로 정렬하고, 한 번 더 누르면 반대로 정렬합니다.</li>
|
||||||
<li>칸 제목 사이 경계를 끌면 칸 너비가 바뀝니다.</li>
|
<li>칸 제목 사이 경계를 끌면 칸 너비가 바뀝니다.</li>
|
||||||
<li>줄을 누르면 작업 편집 창, 우클릭하면 작업 메뉴, <span class="pjh-ui">💬</span>를 누르면 댓글 대화창이 열립니다.</li>
|
<li>줄을 누르면 업무 편집 창, 우클릭하면 업무 메뉴, <span class="pjh-ui">💬</span>를 누르면 댓글 대화창이 열립니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -355,11 +409,11 @@
|
|||||||
<section class="pjh-sec" id="calendar">
|
<section class="pjh-sec" id="calendar">
|
||||||
<h2><span class="pjh-num">12</span>캘린더 보기</h2>
|
<h2><span class="pjh-num">12</span>캘린더 보기</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>한 달 달력에 작업이 <b>시작일~마감일</b> 막대로 표시됩니다(시작일이 없으면 마감일 하루). 공휴일은 빨간색입니다.</li>
|
<li>한 달 달력에 업무가 <b>시작일~마감일</b> 막대로 표시됩니다(시작일이 없으면 마감일 하루). 공휴일은 빨간색입니다.</li>
|
||||||
<li><span class="pjh-ui">‹</span> <span class="pjh-ui">›</span>로 지난달·다음 달로 갑니다.</li>
|
<li><span class="pjh-ui">‹</span> <span class="pjh-ui">›</span>로 지난달·다음 달로 갑니다.</li>
|
||||||
<li>막대를 <b>누르면</b> 작업 편집 창이 열리고, <b>끌어서 다른 날에 놓으면</b> 날짜가 옮겨집니다.</li>
|
<li>막대를 <b>누르면</b> 업무 편집 창이 열리고, <b>끌어서 다른 날에 놓으면</b> 날짜가 옮겨집니다.</li>
|
||||||
<li>하루에 작업이 많으면 <span class="pjh-ui">+N</span>이 나옵니다. 누르면 그날 작업 목록이 뜹니다.</li>
|
<li>하루에 업무가 많으면 <span class="pjh-ui">+N</span>이 나옵니다. 누르면 그날 업무 목록이 뜹니다.</li>
|
||||||
<li>막대 우클릭 → 작업 메뉴(열기 · 작업 링크 복사 · 완료로 표시 · 삭제).</li>
|
<li>막대 우클릭 → 업무 메뉴(열기 · 업무 링크 복사 · 완료로 표시 · 삭제).</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -367,14 +421,14 @@
|
|||||||
<section class="pjh-sec" id="timeline">
|
<section class="pjh-sec" id="timeline">
|
||||||
<h2><span class="pjh-num">13</span>타임라인 보기</h2>
|
<h2><span class="pjh-num">13</span>타임라인 보기</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>기간이 있는(시작일 또는 마감일이 있는) 작업이 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
|
<li>기간이 있는(시작일 또는 마감일이 있는) 업무가 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
|
||||||
<li>작업은 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 하위 작업이 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 작업은 기간만큼 막대로 늘어납니다.</li>
|
<li>업무는 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 세부 업무가 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 업무는 기간만큼 막대로 늘어납니다.</li>
|
||||||
<li>카드에 하위 작업이 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “하위 작업 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 하위 작업은 작업 편집 창에서 봅니다.</li>
|
<li>카드에 세부 업무가 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “세부 업무 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 세부 업무는 업무 편집 창에서 봅니다.</li>
|
||||||
<li>줄 색은 <b>섹션 편집에서 정한 섹션 색</b>입니다(색이 없는 섹션은 프로젝트 색). 왼쪽 섹션 이름 앞에도 같은 색 네모가 붙습니다. 주말은 세로줄이 옅은 회색입니다.</li>
|
<li>줄 색은 <b>프로젝트 색</b>입니다(섹션별 색 지정은 없앴습니다 — 보드의 섹션 머리는 모두 같은 연회색). 주말은 세로줄이 옅은 회색입니다.</li>
|
||||||
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 작업은 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
|
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 업무는 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
|
||||||
<li>처음 열면 하루 칸이 날짜 글자(“30일 (수)”) 폭만큼이라 한 화면에 여러 날이 보입니다. <kbd>Ctrl</kbd> + 마우스 휠로 확대·축소(하루 칸이 날짜 글자 폭이 되면 더 줄어들지 않습니다), 빈 곳을 끌면 좌우로 이동합니다(보던 구간은 기억). <span class="pjh-ui">오늘</span>로 오늘 날짜로 돌아옵니다.</li>
|
<li>처음 열면 하루 칸이 날짜 글자(“30일 (수)”) 폭만큼이라 한 화면에 여러 날이 보입니다. <kbd>Ctrl</kbd> + 마우스 휠로 확대·축소(하루 칸이 날짜 글자 폭이 되면 더 줄어들지 않습니다), 빈 곳을 끌면 좌우로 이동합니다(보던 구간은 기억). <span class="pjh-ui">오늘</span>로 오늘 날짜로 돌아옵니다.</li>
|
||||||
<li>아래 날짜 줄은 캘린더와 같은 색입니다 — <span style="color:#1d4ed8;font-weight:700">토요일은 파랑</span>, <span style="color:#c22b10;font-weight:700">일요일·국경일·대체공휴일은 빨강</span>. 공휴일은 날짜 밑에 이름(예: 추석, 대체휴일)이 나오고, 마우스를 올리면 전체 이름이 보입니다.</li>
|
<li>아래 날짜 줄은 캘린더와 같은 색입니다 — <span style="color:#1d4ed8;font-weight:700">토요일은 파랑</span>, <span style="color:#c22b10;font-weight:700">일요일·국경일·대체공휴일은 빨강</span>. 공휴일은 날짜 밑에 이름(예: 추석, 대체휴일)이 나오고, 마우스를 올리면 전체 이름이 보입니다.</li>
|
||||||
<li>카드의 <b>작업 이름을 누르면</b> 오른쪽에 작업 편집 창이 열립니다(더블클릭도 같음). <b>우클릭</b> → 작업 메뉴. 마우스를 올리면 작업 정보가 보입니다.</li>
|
<li>카드의 <b>업무 이름을 누르면</b> 오른쪽에 업무 편집 창이 열립니다(더블클릭도 같음). <b>우클릭</b> → 업무 메뉴. 마우스를 올리면 업무 정보가 보입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -382,24 +436,24 @@
|
|||||||
<section class="pjh-sec" id="dashboard">
|
<section class="pjh-sec" id="dashboard">
|
||||||
<h2><span class="pjh-num">14</span>대시보드</h2>
|
<h2><span class="pjh-num">14</span>대시보드</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>위쪽 숫자 카드 4개: <b>완료된 작업 합계 · 미완료 작업 합계 · 마감일이 지난 작업 합계 · 작업 합계</b></li>
|
<li>위쪽 숫자 카드 4개: <b>완료된 업무 합계 · 미완료 업무 합계 · 마감일이 지난 업무 합계 · 업무 합계</b></li>
|
||||||
<li><b>미완료 작업 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
|
<li><b>미완료 업무 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
|
||||||
<li><b>작업 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
|
<li><b>업무 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
|
||||||
<li><b>예정된 작업 합계(담당자별)</b> — 사람별로 일정이 잡힌 미완료 작업 수(상위 10명). <b>관리자에게만</b> 보입니다.</li>
|
<li><b>담당자별 업무 합계(메인·세부 업무, 완료)</b> — 이 범위에서 사람별로 배정된 업무 <b>전부</b>(마감일이 없어도, 필터와 관계없이)를 사람마다 <b>메인 업무·세부 업무 세로 막대</b>로 보여 줍니다(막대 하나 = 그 업무 전체, 초록으로 찬 높이 = 완료율, 위 숫자 = 완료/전체와 %, 이름 아래 = 전체 완료율). 막대를 누르면 오른쪽에서 그 사람의 업무 목록(미완료·완료)이 나오고, 항목을 누르면 업무 편집 창이 열립니다. 편집 창을 닫으면 숫자와 목록이 다시 계산됩니다. 세부 업무는 세부 업무에 지정된 담당자 기준입니다. <b>Pro user 이상에게만</b> 보입니다.</li>
|
||||||
<li>범위(이 프로젝트/전체 프로젝트)와 필터 바 설정을 그대로 따라 계산합니다.</li>
|
<li>범위(이 프로젝트/전체 프로젝트)와 필터 바 설정을 그대로 따라 계산합니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 15. 내 작업 -->
|
<!-- 15. 내 작업 -->
|
||||||
<section class="pjh-sec" id="mytasks">
|
<section class="pjh-sec" id="mytasks">
|
||||||
<h2><span class="pjh-num">15</span>내 작업</h2>
|
<h2><span class="pjh-num">15</span>내 업무</h2>
|
||||||
<p class="pjh-lead">왼쪽 사이드바 <b>내 작업</b>(프로젝트 관리 첫 화면)은 모든 프로젝트에서 내가 담당자인 작업만 한 표로 보여줍니다.</p>
|
<p class="pjh-lead">왼쪽 사이드바 <b>내 업무</b>(프로젝트 관리 첫 화면)은 모든 프로젝트에서 내가 담당자인 업무만 한 표로 보여줍니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>위쪽 탭 <span class="pjh-ui">진행 중 · 완료 · 전체</span>로 고릅니다. 옆에 전체 개수와 지연(마감 지남) 개수가 나옵니다.</li>
|
<li>위쪽 탭 <span class="pjh-ui">진행 중 · 완료 · 전체</span>로 고릅니다. 옆에 전체 개수와 지연(마감 지남) 개수가 나옵니다.</li>
|
||||||
<li>찾기(제목·설명·프로젝트), 마감(마감 지남·오늘·이번 주·마감일 없음), 우선순위로 거를 수 있습니다.</li>
|
<li>찾기(제목·설명·프로젝트), 마감(마감 지남·오늘·이번 주·마감일 없음), 우선순위로 거를 수 있습니다.</li>
|
||||||
<li>칸 제목을 누르면 정렬합니다.</li>
|
<li>칸 제목을 누르면 정렬합니다.</li>
|
||||||
<li>줄을 누르면 그 작업의 프로젝트 화면으로 가서 작업 편집 창이 바로 열립니다. 우클릭하면 작업 메뉴가 나옵니다.</li>
|
<li>줄을 누르면 그 업무의 프로젝트 화면으로 가서 업무 편집 창이 바로 열립니다. 우클릭하면 업무 메뉴가 나옵니다.</li>
|
||||||
<li>내가 담당자인 하위 작업은 상위 작업 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
<li>내가 담당자인 세부 업무는 상위 업무 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -407,26 +461,26 @@
|
|||||||
<section class="pjh-sec" id="comments">
|
<section class="pjh-sec" id="comments">
|
||||||
<h2><span class="pjh-num">16</span>댓글과 @태그</h2>
|
<h2><span class="pjh-num">16</span>댓글과 @태그</h2>
|
||||||
<h3>댓글 대화창</h3>
|
<h3>댓글 대화창</h3>
|
||||||
<p>카드·목록·캘린더·내 작업에 보이는 <span class="pjh-ui">💬 N</span>을 <b>한 번 누르면</b> 메신저처럼 생긴 댓글 대화창이 열립니다.</p>
|
<p>카드·목록·캘린더·내 업무에 보이는 <span class="pjh-ui">💬 N</span>을 <b>한 번 누르면</b> 메신저처럼 생긴 댓글 대화창이 열립니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>입력칸에 쓰고 <span class="pjh-ui">전송</span> 또는 <kbd>Enter</kbd>.</li>
|
<li>입력칸에 쓰고 <span class="pjh-ui">전송</span> 또는 <kbd>Enter</kbd>. <kbd>Shift</kbd>+<kbd>Enter</kbd>로 줄바꿈합니다. 입력칸은 높이 70px로 고정되며 긴 글은 칸 안에서 스크롤됩니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">attach_file</span></span>로 파일을 붙이거나, 캡처한 이미지를 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 붙여 넣습니다. 이미지는 작은 그림으로 보입니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">attach_file</span></span>로 파일을 붙이거나, 캡처한 이미지를 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 붙여 넣습니다. 이미지는 작은 그림으로 보입니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>를 누르면 이모티콘 창이 열립니다. 종류별 탭으로 넘기거나 <b>검색</b>(예: 축하, 감사, 완료)으로 찾고, 누르면 커서 자리에 들어갑니다. 자주 쓴 이모티콘은 맨 위에 모입니다. 작업 팝업 아래 댓글 입력칸에도 같은 버튼이 있습니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>를 누르면 이모티콘 창이 열립니다. 종류별 탭으로 넘기거나 <b>검색</b>(예: 축하, 감사, 완료)으로 찾고, 누르면 커서 자리에 들어갑니다. 자주 쓴 이모티콘은 맨 위에 모입니다. 업무 팝업 아래 댓글 입력칸에도 같은 버튼이 있습니다.</li>
|
||||||
<li>웹 주소를 붙여 넣으면 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
<li>웹 주소를 붙여 넣으면 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||||
<li>아직 읽지 않은 새 댓글이 있으면 말풍선이 깜빡이고 숫자가 빨간색으로 바뀝니다.</li>
|
<li>아직 읽지 않은 새 댓글이 있으면 말풍선이 깜빡이고 숫자가 빨간색으로 바뀝니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>반응 · 답글 · 완료 표시 (아사나식)</h3>
|
<h3>반응 · 답글 · 완료 표시 (아사나식)</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>반응</b> — 댓글에 마우스를 올리면 오른쪽 위에 👍 👀 🙌 ✅ 와 <span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>가 뜹니다. 누르면 댓글 아래에 반응이 붙고(누른 사람 수), 내가 누른 반응은 파랗게 보입니다. 다시 누르면 취소됩니다. 반응에 마우스를 올리면 누가 눌렀는지 보입니다.</li>
|
<li><b>반응</b> — 댓글에 마우스를 올리면 오른쪽 위에 👍 👀 🙌 ✅ 와 <span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>가 뜹니다. 누르면 댓글 아래에 반응이 붙고(누른 사람 수), 내가 누른 반응은 파랗게 보입니다. 다시 누르면 취소됩니다. 반응에 마우스를 올리면 누가 눌렀는지 보입니다.</li>
|
||||||
<li><b>답글</b> — 같은 도구 모음의 <span class="pjh-ui"><span class="material-symbols-outlined">reply</span></span>. 작업 창에서는 원 댓글 아래 들여쓰기로 달리고, 댓글 대화창에서는 입력칸 위에 “OO 님에게 답글”이 뜬 뒤 보내면 말풍선 위에 원 댓글이 인용됩니다. 원 댓글을 지우면 답글도 함께 지워집니다.</li>
|
<li><b>답글</b> — 같은 도구 모음의 <span class="pjh-ui"><span class="material-symbols-outlined">reply</span></span>. 업무 창에서는 원 댓글 아래 들여쓰기로 달리고, 댓글 대화창에서는 입력칸 위에 “OO 님에게 답글”이 뜬 뒤 보내면 말풍선 위에 원 댓글이 인용됩니다. 원 댓글을 지우면 답글도 함께 지워집니다.</li>
|
||||||
<li><b>작업 완료</b> — 작업을 완료하면 댓글 사이에 <span class="pjh-ui">✔ OO 님이 이 작업을 완료했습니다</span> 줄이 자동으로 생깁니다(댓글 수에는 세지 않습니다). 완료를 취소하면 이 줄도 사라지고, 다시 완료하면 마지막 완료 한 줄만 보입니다.</li>
|
<li><b>업무 완료</b> — 업무를 완료하면 댓글 사이에 <span class="pjh-ui">✔ OO 님이 이 업무를 완료했습니다</span> 줄이 자동으로 생깁니다(댓글 수에는 세지 않습니다). 완료를 취소하면 이 줄도 사라지고, 다시 완료하면 마지막 완료 한 줄만 보입니다.</li>
|
||||||
<li><b>@태그 표시</b> — 댓글 속 <kbd>@아이디</kbd>는 프로필 아이콘 + 이름 칩으로 보입니다.</li>
|
<li><b>@태그 표시</b> — 댓글 속 <kbd>@아이디</kbd>는 프로필 아이콘 + 이름 칩으로 보입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>@태그로 동료 부르기</h3>
|
<h3>@태그로 동료 부르기</h3>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li>설명이나 댓글에서 <kbd>@</kbd>를 누릅니다.</li>
|
<li>설명이나 댓글에서 <kbd>@</kbd>를 누릅니다.</li>
|
||||||
<li>이름 몇 글자를 치면 목록이 좁혀집니다. 방향키와 <kbd>Enter</kbd> 또는 마우스로 고릅니다.</li>
|
<li>이름 몇 글자를 치면 목록이 좁혀집니다. 방향키와 <kbd>Enter</kbd> 또는 마우스로 고릅니다.</li>
|
||||||
<li>저장(설명) 또는 전송(댓글)하면, 태그된 사람의 <b>수신함 → 나를 태그한 작업</b>에 이 작업이 올라가고 그 사람은 자동으로 협업자가 됩니다.</li>
|
<li>저장(설명) 또는 전송(댓글)하면, 태그된 사람의 <b>수신함 → 나를 태그한 업무</b>에 이 업무가 올라가고 그 사람은 자동으로 협업자가 됩니다.</li>
|
||||||
</ol>
|
</ol>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -435,19 +489,22 @@
|
|||||||
<h2><span class="pjh-num">17</span>수신함과 알림</h2>
|
<h2><span class="pjh-num">17</span>수신함과 알림</h2>
|
||||||
<h3>수신함 화면</h3>
|
<h3>수신함 화면</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>나를 태그한 작업</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
|
<li><b>나를 태그한 업무</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
|
||||||
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 항목을 누르면 읽음이 되고, <span class="pjh-ui">확인</span>을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열립니다(나를 태그한 작업도 같음). 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.</li>
|
<li><b>알림</b> — 업무 배정 · 업무 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 업무 창</b>이 열리고(나를 태그한 업무도 같음), 업무 창이 열린 채 다른 줄을 누르면 업무 창이 그 업무로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 업무의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 업무가 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
|
||||||
|
업무 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(업무 창을 직접 닫을 때와 같음).
|
||||||
|
확인(읽음) 처리가 서버에 저장되지 않은 줄은 굵게 남아 있어 다시 누를 수 있습니다.
|
||||||
|
다른 프로젝트에서 연결돼 와 읽기만 되는 업무의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
||||||
<li><span class="pjh-ui">알림 모두 읽음</span>으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
<li><span class="pjh-ui">알림 모두 읽음</span>으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>어떤 알림이 누구에게 가나요?</h3>
|
<h3>어떤 알림이 누구에게 가나요?</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>알림</th><th>받는 사람</th></tr>
|
<tr><th>알림</th><th>받는 사람</th></tr>
|
||||||
<tr><td>작업 배정</td><td>새로 담당자가 된 사람</td></tr>
|
<tr><td>업무 배정</td><td>새로 담당자가 된 사람</td></tr>
|
||||||
<tr><td>작업 완료 · 새 댓글</td><td>담당자와 협업자</td></tr>
|
<tr><td>업무 완료 · 새 댓글</td><td>담당자와 협업자</td></tr>
|
||||||
<tr><td>마감 알림</td><td>담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다.</td></tr>
|
<tr><td>마감 알림</td><td>담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다.</td></tr>
|
||||||
<tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 작업”)</td></tr>
|
<tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 업무”)</td></tr>
|
||||||
</table>
|
</table>
|
||||||
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 작업 배정·완료는 관리자 메일로도 갑니다.</p>
|
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 18. 검색과 공유 -->
|
<!-- 18. 검색과 공유 -->
|
||||||
@@ -456,70 +513,231 @@
|
|||||||
<h3>전체 검색</h3>
|
<h3>전체 검색</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li>왼쪽 사이드바 맨 위 검색창. 어느 화면에서든 <kbd>/</kbd> 키를 누르면 바로 검색창으로 갑니다.</li>
|
<li>왼쪽 사이드바 맨 위 검색창. 어느 화면에서든 <kbd>/</kbd> 키를 누르면 바로 검색창으로 갑니다.</li>
|
||||||
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 작업(하위 작업 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 업무(세부 업무 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
||||||
<li>결과를 누르면 그 작업이 열립니다.</li>
|
<li>결과를 누르면 그 업무가 열립니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>공유 링크</h3>
|
<h3>공유 링크</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li>작업 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">작업 링크 복사</span>로 주소를 복사합니다.</li>
|
<li>업무 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">업무 링크 복사</span>로 주소를 복사합니다.</li>
|
||||||
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 하위 작업 링크는 하위 작업 자체가 열립니다.</li>
|
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 업무가 바로 열립니다. 세부 업무 링크는 세부 업무 자체가 열립니다.</li>
|
||||||
<li>그 프로젝트의 <b>멤버만</b> 열 수 있어 밖으로 새지 않습니다.</li>
|
<li>현재 그 업무를 볼 수 있는 멤버·소유자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 19. 휴지통 -->
|
<!-- 19. 휴지통 -->
|
||||||
<section class="pjh-sec" id="trash">
|
<section class="pjh-sec" id="trash">
|
||||||
<h2><span class="pjh-num">19</span>휴지통 (관리자)</h2>
|
<h2><span class="pjh-num">19</span>휴지통 (Pro user 이상)</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>지운 작업은 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 하위 작업 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
<li>지운 업무는 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 세부 업무 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
||||||
<li>관리자는 왼쪽 사이드바 <b>휴지통</b>에서 지운 작업 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다.</li>
|
<li>Pro user 이상은 왼쪽 사이드바 <b>휴지통</b>에서 지운 업무 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다. 자기가 멤버인 프로젝트의 업무만 보입니다.</li>
|
||||||
<li><span class="pjh-ui">복구</span>를 누르면 원래 프로젝트 · 섹션 자리로 그대로 돌아옵니다. 복구된 줄의 <span class="pjh-ui">복구됨 · 열기</span>로 바로 열어 볼 수 있습니다.</li>
|
<li><span class="pjh-ui">복구</span>를 누르면 원래 프로젝트 · 섹션 자리로 그대로 돌아옵니다. 복구된 줄의 <span class="pjh-ui">복구됨 · 열기</span>로 바로 열어 볼 수 있습니다.</li>
|
||||||
<li>3개월이 지나면 영구 삭제됩니다.</li>
|
<li>3개월이 지나면 영구 삭제됩니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||||
<div>하위 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
|
<div>세부 업무만 따로 지웠는데 상위 업무도 지워진 상태라면, 상위 업무를 먼저 복구해야 합니다.</div></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 20. 단축키와 FAQ -->
|
<!-- 20. 연간 목표 -->
|
||||||
|
<section class="pjh-sec" id="goals">
|
||||||
|
<h2><span class="pjh-num">20</span>연간 목표</h2>
|
||||||
|
<p class="pjh-lead">한 해의 매출 목표·실적과 업무 계획을 한 표에서 관리합니다. 숫자는 위쪽 지표에, 실행 계획은 아래쪽 업무 영역에 적습니다. 프로젝트 관리 권한이 있는 직원은 볼 수 있고, 입력·구조 변경은 Pro user 이상만 할 수 있습니다.</p>
|
||||||
|
|
||||||
|
<h3 id="goals-start">목표 열기와 연도 만들기</h3>
|
||||||
|
<ol class="pjh-steps">
|
||||||
|
<li>왼쪽 사이드바 <span class="pjh-ui">목표</span>를 눌러 연도 목록을 펼친 뒤 원하는 연도를 누릅니다. 올해는 목표가 아직 없어도 목록에 보입니다.</li>
|
||||||
|
<li>Pro user 이상은 빈 연도 화면에서 <span class="pjh-ui">해당 연도 목표 만들기</span>, 또는 사이드바의 <span class="pjh-ui">+ 연도 추가</span>로 새 표를 만듭니다.</li>
|
||||||
|
<li>가장 가까운 이전 연도의 업무 영역·줄 구성을 가져옵니다. 이전 연도가 없으면 다음 연도의 구성을 사용하고, 처음이면 상품·마케팅·컨텐츠·유통으로 시작합니다. 이전 숫자와 계획 글은 복사하지 않습니다.</li>
|
||||||
|
<li>위쪽 <span class="pjh-ui">매출 단위</span>를 확인한 뒤 월별 숫자와 계획을 입력합니다.</li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<h3 id="goals-metrics">매출·로아스 입력과 달성률 계산</h3>
|
||||||
|
<table class="pjh-table">
|
||||||
|
<tr><th>칸</th><th>입력·계산 방법</th></tr>
|
||||||
|
<tr><td>매출 목표</td><td>월 칸을 누르면 그 달 입력 창이 열립니다. 맨 위 <b>월 전체 목표</b>를 직접 넣고, 아래에 <b>주차별 목표</b>(매출 단위)를 넣은 뒤 <span class="pjh-ui">저장</span>합니다. 월 목표는 주차 합계와 따로 저장되고, 맨 아래에 <b>주차 합계</b>와 <b>차이(월 목표 − 주차 합계)</b>가 나옵니다 — +면 아직 주차에 못 나눈 금액, −면 주차 합계가 월 목표를 넘은 것입니다. 주차는 <a href="#meetings-week">주간 회의록 주차</a>와 같습니다.</td></tr>
|
||||||
|
<tr><td>매출 실적</td><td>Pro user 이상이 월별 숫자를 직접 입력합니다. 목표 표의 실적은 회의록의 자동 매출과 별도로 관리하므로 실적 모듈에서 자동으로 채워지지 않습니다.</td></tr>
|
||||||
|
<tr><td>매출 단위</td><td>예를 들어 단위가 <b>백만원</b>이면 30은 30,000,000원입니다. 단위를 바꿔도 이미 적은 숫자는 자동 환산되지 않으므로 숫자와 단위를 함께 확인하세요.</td></tr>
|
||||||
|
<tr><td>연간·분기 매출</td><td>해당 기간에 입력한 월 숫자의 합계입니다. 합계 칸에 따로 입력하지 않습니다.</td></tr>
|
||||||
|
<tr><td>달성</td><td>실적 ÷ 목표 × 100입니다. 월별로 계산하며, 연간·분기는 <b>기간 전체 목표 합계</b> 대비 입력된 실적 합계로 계산합니다. 목표가 없거나 0이면 달성률을 표시하지 않습니다. 100% 이상은 초록으로 표시됩니다.</td></tr>
|
||||||
|
<tr><td>로아스(ROAS)</td><td>광고비 대비 매출 비율을 <b>% 단위</b>로 적습니다. 예: 300은 300%입니다. 연간·분기는 월 매출과 ROAS로 환산한 광고비를 합쳐 계산하고, 필요한 월 매출이 빠져 있으면 입력된 ROAS의 단순 평균을 사용합니다.</td></tr>
|
||||||
|
</table>
|
||||||
|
<p>숫자는 <kbd>Enter</kbd> 또는 칸을 떠날 때 저장됩니다. 숫자 칸을 비우면 값을 지우며, <kbd>Esc</kbd>를 누르면 마지막 저장값으로 돌아갑니다.</p>
|
||||||
|
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>1~3월 목표가 각각 100이고 1월 실적만 50이면 1분기 달성은 50 ÷ 300 = 약 16.7%입니다. 아직 실적을 넣지 않은 달의 목표도 분기 목표 합계에 포함됩니다.</div></div>
|
||||||
|
|
||||||
|
<h3 id="goals-plan">업무 영역·항목·연간·분기·월 계획</h3>
|
||||||
|
<p>업무 영역은 상품·마케팅처럼 큰 분류, 항목은 그 안의 세부 주제입니다. 한 항목의 연간 칸에는 큰 방향, 분기 칸에는 중간 목표, 월 칸에는 구체적인 실행 계획을 적으면 주간 회의에서 확인하기 쉽습니다.</p>
|
||||||
|
<ul>
|
||||||
|
<li><span class="pjh-ui">+ 업무 영역 추가</span>를 누르면 새 영역이 생기고 이름을 바로 고칠 수 있습니다.</li>
|
||||||
|
<li>영역·항목 이름을 클릭해 고칩니다. <kbd>Enter</kbd>는 저장, <kbd>Esc</kbd>는 취소입니다.</li>
|
||||||
|
<li>이름 칸을 우클릭하거나 <span class="pjh-ui">⋮</span>를 누르면 영역 색·위아래 순서·줄 추가·삭제 메뉴가 나옵니다. 항목 메뉴에서는 해당 줄 위·아래에 줄을 추가할 수 있습니다. 영역의 마지막 줄은 지울 수 없습니다.</li>
|
||||||
|
<li>연간 글 칸에서 우클릭해 줄을 추가하면 같은 항목 이름 아래에 여러 줄로 나눠 계획을 적을 수 있습니다.</li>
|
||||||
|
<li>키보드는 <kbd>Tab</kbd>으로 이름이나 ⋮ 버튼에 이동해 <kbd>Enter</kbd>로 열고, 메뉴에서 <kbd>↑</kbd><kbd>↓</kbd>·<kbd>Enter</kbd>로 선택합니다. <kbd>Esc</kbd>로 닫습니다. 터치 화면에서는 ⋮를 누릅니다.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3 id="goals-format">글자 서식 바꾸기</h3>
|
||||||
|
<p>글 칸에서 글자를 드래그해 선택하면 해당 셀 상단에 서식 도구가 나타납니다. <b>선택한 글자에만</b> 12색 견본·크기·굵게·기울임·밑줄을 적용합니다. 크기 버튼은 2px씩 조절하며 범위는 10~32px입니다.</p>
|
||||||
|
<p>굵게·기울임·밑줄은 다시 누르면 해제됩니다. <span class="pjh-ui">서식 초기화</span>는 선택한 글자의 서식만 되돌리고 내용은 유지합니다. 글과 서식은 입력을 약 0.8초 멈추거나 칸을 떠날 때 자동 저장됩니다.</p>
|
||||||
|
|
||||||
|
<h3 id="goals-table">분기 접기·열 너비·행 높이</h3>
|
||||||
|
<ul>
|
||||||
|
<li>열은 연간 → 1~3월 → 1분기 → 4~6월 → 2분기 → 7~9월 → 3분기 → 10~12월 → 4분기 순서입니다. <b>분기 머리 칸</b>을 누르면 해당 월 3개가 부드럽게 접히거나 펼쳐집니다. 숫자와 글은 펼침이 끝난 뒤 나타납니다. 네모 안 <b>−</b>는 접기, <b>+</b>는 펼치기입니다.</li>
|
||||||
|
<li>어느 행에서든 셀의 <b>오른쪽 경계</b>를 끌어 열 너비를 조절합니다. 경계를 더블클릭하면 가장 긴 문단에 맞춥니다. 직접 넣은 줄바꿈·글자 크기·굵기도 반영합니다.</li>
|
||||||
|
<li>셀 우클릭의 <span class="pjh-ui">현재 열 너비 자동 맞춤</span>·<span class="pjh-ui">전체 열 너비 자동 맞춤</span>도 사용할 수 있습니다. 전체 맞춤은 접힌 월 열까지 포함합니다. 병합 칸은 다른 열을 유지하며 오른쪽 끝 열 너비를 조절합니다.</li>
|
||||||
|
<li>접힘·열 너비는 내 브라우저에 기억됩니다. 행 높이는 가장 높은 글 칸에 맞춰 늘고, 글이 줄면 함께 줄어듭니다. 1열(업무 영역)·2열(항목 이름)은 병합된 칸도 항상 세로 가운데 정렬이며, 목표 내용은 상단 정렬입니다.</li>
|
||||||
|
<li>가로 스크롤에서는 구분·항목·연간 칸이, 세로 스크롤에서는 머리와 매출·로아스 지표가 고정됩니다.</li>
|
||||||
|
<li><b>월 이름</b>을 누르면 그 달의 <a href="#meetings">주간 회의록</a>으로 이동합니다.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3 id="goals-merge">셀 병합·병합 해제</h3>
|
||||||
|
<ol class="pjh-steps">
|
||||||
|
<li>Pro user 이상은 업무 영역의 글 칸을 마우스로 끌어 여러 칸을 선택한 뒤 우클릭 → <span class="pjh-ui">셀 병합</span>을 누릅니다.</li>
|
||||||
|
<li>가로 병합은 <b>같은 분기의 월 칸끼리</b> 가능합니다. 연간·분기 칸은 세로로만 병합합니다. 선택한 칸들의 글은 순서대로 첫 칸에 모입니다.</li>
|
||||||
|
<li>병합된 칸을 우클릭 → <span class="pjh-ui">병합 해제</span>하면 다시 나뉩니다. 글은 왼쪽 위 칸에 남습니다.</li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<h3 id="goals-save">저장 실패와 연도 삭제</h3>
|
||||||
|
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합을 진행하기 전에 저장을 시도하고, 실패하면 해당 업무를 멈춥니다.</p>
|
||||||
|
<p>저장되지 않은 초안은 내 브라우저에도 잠시 보관합니다. 다음에 같은 화면을 열면 복원하지만, 그 사이 다른 사람이 같은 칸을 바꿨으면 자동으로 덮어쓰지 않습니다. 저장 안 된 상태로 페이지를 떠나려 하면 브라우저가 확인합니다.</p>
|
||||||
|
<p>Pro user 이상의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 21. 주간 회의록 -->
|
||||||
|
<section class="pjh-sec" id="meetings">
|
||||||
|
<h2><span class="pjh-num">21</span>주간 회의록</h2>
|
||||||
|
<p class="pjh-lead">월 목표를 기준으로 지난주 결과를 리뷰하고 이번주 주요 업무와 금액 목표를 정하는 화면입니다. 연간 목표의 월 계획, 실적 모듈의 매출, 주별 결정 사항을 함께 확인합니다. 프로젝트 관리 권한이 있는 직원은 <b>누구나 회의록을 만들고 고칠 수 있습니다</b>. Pro user 이상이 <span class="pjh-ui">회의 완료</span>를 누르면 그 회의록은 아무도 고칠 수 없게 잠기고(🔒 회의 완료 표시), Pro user 이상은 <span class="pjh-ui">완료 해제</span>로 다시 열 수 있습니다. 회의록 삭제도 Pro user 이상만 합니다.</p>
|
||||||
|
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>지난주 리뷰의 <b>결과</b>(글·금액)는 다음 주 회의에서 적는 값이라, 지난주 회의록이 완료돼 있어도 이번 주 회의록이 열려 있으면 적을 수 있습니다. 이번 주 회의록까지 완료하면 함께 잠깁니다. 다음 주차 회의록이 아직 없으면 그 주 회의록이 열려 있는 동안만 결과를 고칠 수 있습니다.</div></div>
|
||||||
|
|
||||||
|
<h3 id="meetings-week">회의록 열기와 주차 기준</h3>
|
||||||
|
<p>왼쪽 연도 앞 화살표를 누르면 해당 연도의 하위 월 전체를 접거나 펼칠 수 있습니다. 연도 글자를 누르면 연간 목표를 엽니다. 연도와 월의 접기·펼치기 선택은 이 브라우저에 기억됩니다.</p>
|
||||||
|
<ol class="pjh-steps">
|
||||||
|
<li>왼쪽 <span class="pjh-ui">목표</span>에서 연도를 선택하고 표 머리의 <b>월 이름</b>을 누릅니다.</li>
|
||||||
|
<li>이미 만든 회의록은 왼쪽 목표 연도 아래의 <b>월 폴더</b>에서도 열 수 있습니다. 폴더 아이콘과 월 이름을 눌러 접거나 펼치고, 주차·날짜 항목을 누르면 오른쪽 회의록만 바뀝니다. 왼쪽 메뉴와 스크롤 위치는 유지됩니다. 입력한 칸은 이동 전에 저장하며, 저장에 실패하면 현재 회의록을 유지합니다. 접기·펼치기는 이 브라우저에 기억됩니다.</li>
|
||||||
|
<li>위쪽 주차 탭 또는 오른쪽 작은 달력의 한 줄을 눌러 주차를 고릅니다. 달력 줄을 누르면 그 줄의 이 달 날짜가 든 주차가 열립니다. 점은 회의록이 있는 주차, <span class="pjh-ui">이번 주</span>는 현재 주차입니다. 이전·다음 달 버튼으로 달을 바꿉니다.</li>
|
||||||
|
<li>주차는 <b>그 달 안에서만</b> 나눕니다. 기본은 월요일~일요일입니다.
|
||||||
|
<ul>
|
||||||
|
<li>1일이 월~금요일이면 1일부터 그 주 일요일까지가 1주차입니다. 예: 2026년 10월 1주차는 10/1(목)~10/4.</li>
|
||||||
|
<li>1일이 토·일요일이면 1일부터 다음 주 일요일까지가 1주차입니다. 예: 2026년 8월 1주차는 8/1(토)~8/9.</li>
|
||||||
|
<li>말일이 월·화요일이면 그 하루·이틀은 앞 주차에 붙습니다. 예: 2026년 8월 마지막 주차는 8/24~8/31(월).</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li><span class="pjh-ui">해당 연도 목표</span> 버튼은 연간 목표 표로 돌아갑니다.</li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<h3 id="meetings-create">회의록 만들기와 이어받는 항목</h3>
|
||||||
|
<p>선택한 주에 회의록이 없으면 <span class="pjh-ui">해당 주차 회의록 만들기</span>가 보입니다(누구나 만들 수 있습니다). 화면을 열기만 해서는 회의록이 만들어지지 않습니다.</p>
|
||||||
|
<ul>
|
||||||
|
<li>줄이 있는 가장 가까운 앞선 회의록에서 <b>구역·항목 이름·색·순서</b>를 이어받습니다. 앞선 회의록이 없으면 가장 가까운 다음 회의록의 구성을 가져옵니다.</li>
|
||||||
|
<li>어느 쪽에도 회의록이 없으면 해당 연도 목표 표의 업무 영역과 기본 양식으로 시작합니다.</li>
|
||||||
|
<li>주요 업무·금액·메모는 새로 적습니다. 구성을 이어받는 것과 <b>지난주 리뷰</b>는 다릅니다. 리뷰에는 바로 앞 주차의 같은 항목만 표시됩니다.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3 id="meetings-month-plan">이 달 계획 확인</h3>
|
||||||
|
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 굵게·기울임·밑줄·글자 색상과 줄바꿈·들여쓰기를 유지하고, 글자 크기는 월 계획의 기본 크기로 표시합니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
|
||||||
|
|
||||||
|
<h3 id="meetings-kpis">위쪽 3칸 — 월 계획·숫자, 결정 사항, 업무 등록</h3>
|
||||||
|
<p>제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 <b>월 계획</b>이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 <b>결정사항</b>(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 <b>업무 등록</b> 표입니다.</p>
|
||||||
|
<ol class="pjh-steps">
|
||||||
|
<li><b>업무 등록</b>(제목에 <b>N주차 업무 등록</b>) — 주차마다 한 표를 <b>모두가 같이</b> 봅니다(다른 사람이 적거나 등록한 줄도 보임, 30초마다·창을 다시 볼 때 새로 읽음). 내가 멤버가 아닌 프로젝트를 고른 남의 줄은 프로젝트 이름을 가립니다. 회의 완료면 읽기 전용입니다.
|
||||||
|
<b>업무</b> 칸 — 비워 두면 고른 섹션에 새 업무로, 업무를 고르면 <b>그 업무의 세부 업무</b>로 등록합니다(목록 = 그 섹션의 진행 중인 메인 업무, 고르면 섹션 칸은 —). 등록된 줄의 <b>제목을 누르면 오른쪽에 업무 창</b>이 열려 바로 편집할 수 있습니다(업무 창에서 저장이 끝나야 닫히거나 다른 업무로 바뀝니다).
|
||||||
|
<span class="pjh-ui">크게 열기</span> — 같은 표를 넓은 창으로 열어 씁니다(줄·저장은 그대로, <kbd>Esc</kbd>·×로 닫기). 제목 칸에 업무 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다(완료 프로젝트·완료 섹션은 목록에 나오지 않습니다). 목록 맨 위 <span class="pjh-ui">새 프로젝트</span>(Pro user 이상)·<span class="pjh-ui">새 섹션</span>(그 프로젝트 멤버)을 누르면 이름만 적어 바로 만들고 그 칸에 골라집니다. 새 프로젝트는 섹션 없이 시작하니 섹션 칸에서 <span class="pjh-ui">새 섹션</span>을 만들어 고르세요.</li>
|
||||||
|
<li>프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).</li>
|
||||||
|
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 업무가 만들어지고, 줄 오른쪽에 <b>체크 표시</b>(누르면 새 탭에서 업무 열기)가 생기고, 제목을 누르면 오른쪽에 업무 창이 열립니다. 줄은 서버에 저장돼 같은 주차를 보는 모두에게 보입니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
|
||||||
|
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 업무도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 업무 삭제는 만든 사람만 할 수 있습니다.</li>
|
||||||
|
</ol>
|
||||||
|
<table class="pjh-table">
|
||||||
|
<tr><th>지표</th><th>뜻과 출처</th></tr>
|
||||||
|
<tr><td>월 목표 매출</td><td>연간 목표 표의 해당 월 매출 목표(= 주차별 목표 합계)입니다. 매출 단위가 원·천원·만원·십만원·백만원·천만원·억원이면 원으로 환산해 함께 보여 줍니다.</td></tr>
|
||||||
|
<tr><td>월 누적 목표 매출</td><td>연간 목표 표에서 입력한 <b>주차별 목표의 1주차~선택한 주차 합계</b>(원)입니다. 주차별 목표가 없으면 비어 있고, 목표 표로 가는 안내가 나옵니다.</td></tr>
|
||||||
|
<tr><td>월 누적 실적</td><td>실적 모듈의 매출 집계 쇼핑몰 매출을 <b>그 달 1일부터 오늘까지</b> 합칩니다. 지난 주차를 보면 그 주차 마지막 날까지입니다.</td></tr>
|
||||||
|
<tr><td>누적 목표 대비 달성</td><td>월 누적 실적 − 월 누적 목표 매출 금액(넘으면 +, 모자라면 −)과 월 누적 실적 ÷ 월 누적 목표 매출 %입니다. 100% 이상은 초록입니다.</td></tr>
|
||||||
|
</table>
|
||||||
|
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>주차별 목표가 1주차 2천만, 2주차 3천만이고 2주차까지의 실적이 4천5백만원이면 누적 목표 대비 달성은 −5,000,000원(90%)입니다.</div></div>
|
||||||
|
|
||||||
|
<h3 id="meetings-edit">주요 업무·정량 목표·참석자·메모 입력</h3>
|
||||||
|
<ol class="pjh-steps">
|
||||||
|
<li>줄별 <b>정량 목표</b>에 각 항목의 이번 주차 목표를 적습니다. 금액(원 단위)뿐 아니라 <code>20개</code>처럼 글도 됩니다. 전체 매출 목표는 연간 목표 표의 주차별 목표에서 정합니다.</li>
|
||||||
|
<li>각 항목의 <b>주요 업무</b>에 실행할 일과 일정을 적습니다.</li>
|
||||||
|
<li><span class="pjh-ui">참석자</span>를 눌러 프로젝트 관리 권한이 있는 등록 직원 중 선택합니다. 찾기·전원 선택·모두 해제를 사용할 수 있으며, 칩의 <span class="pjh-ui">×</span>로 참석자를 뺍니다.</li>
|
||||||
|
<li>참석자 오른쪽 <span class="pjh-ui">회의록 보드</span>를 누르면 그 주차의 Google 슬라이드가 새 창으로 열립니다. 처음 누르면 회의록 보드 공유 드라이브에 빈 슬라이드(제목 틀 없음)를 <b>"10월 2주차 (10/5~10/11)"</b> 같은 이름으로 만들고, 다음부터는 같은 파일을 엽니다. 직원 누구나 열 수 있으며, 슬라이드 편집 권한은 공유 드라이브 권한을 따릅니다. 창이 안 뜨면 브라우저의 팝업 허용을 확인하세요.</li>
|
||||||
|
<li>위쪽 가운데 <b>결정사항</b>에 회의 결론과 진행상황을 수시로 공유하고 완료되어야 할 일을 적습니다.</li>
|
||||||
|
</ol>
|
||||||
|
<p>금액은 <code>1,200,000</code>·<code>120만</code>·<code>1.5억</code>·<code>3천만</code>·<code>1억2천만</code>처럼 입력할 수 있습니다. <kbd>Enter</kbd> 또는 칸을 떠날 때 원 단위로 저장되고, 빈칸은 값을 지웁니다. 숫자로 읽히지 않는 값(예: <code>20개</code>)은 적은 글 그대로 저장됩니다. 글·메모는 입력을 약 0.8초 멈추거나 칸을 떠날 때, 참석자는 바꾸는 즉시 저장됩니다.</p>
|
||||||
|
|
||||||
|
<p>목표·주간 회의록 표에서 입력한 글·숫자·이름이 칸보다 길면 열 너비가 자동으로 늘어납니다. 글 셀에서는 <kbd>Enter</kbd>를 한 번 누르면 바로 다음 줄로 이동합니다. 지운 뒤 너비를 줄이려면 열 너비 자동 맞춤을 사용하세요.</p>
|
||||||
|
<p>주요 업무 셀에서는 목표 표의 셀 편집 도구를 함께 사용할 수 있습니다.</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>글자 서식</b> — 글자 일부를 선택하고 위쪽 도구에서 색·크기·굵게·기울임·밑줄을 바꿉니다. 초기화 버튼은 선택한 글자의 서식을 지웁니다.</li>
|
||||||
|
<li><b>열 너비</b> — 회의록을 열 때마다 <b>전체 열 너비 자동 맞춤</b>으로 시작합니다. 오른쪽 경계를 끌어 조절하고, 경계를 더블클릭하거나 우클릭 메뉴에서 현재 열·전체 열 너비를 내용에 맞춥니다. 직접 바꾼 너비는 그 화면에서만 유지되고 다시 열면 자동 맞춤으로 돌아갑니다.</li>
|
||||||
|
<li><b>세로 정렬</b> — 1열(구역)·2열(항목)은 긴 행이나 병합된 구역도 항상 세로 가운데 정렬합니다. 할 일·리뷰 내용은 상단 정렬입니다.</li>
|
||||||
|
<li><b>범위 선택·지우기</b> — 같은 구역의 이번주 글 셀을 드래그하거나 첫 셀을 누른 뒤 <kbd>Shift</kbd>+클릭으로 선택합니다. 우클릭의 내용 지우기 또는 <kbd>Delete</kbd>로 지우고, <kbd>Ctrl</kbd>+<kbd>Z</kbd>로 되돌립니다.</li>
|
||||||
|
<li><b>내용 이동</b> — 셀 테두리를 다른 이번주 글 셀로 끌면 내용과 서식이 함께 이동합니다. 대상에 글이 있으면 덮어쓰기를 확인합니다. 이동 중에는 두 셀의 저장을 기다립니다.</li>
|
||||||
|
<li><b>병합·해제</b> — 같은 구역의 글 셀을 여러 줄 선택하고 우클릭의 셀 병합을 누릅니다. 해제해도 합친 글은 첫 셀에 남습니다. 병합된 줄을 이동·삭제하거나 그 사이에 줄을 추가하려면 먼저 병합을 해제하세요.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3 id="meetings-review">지난주 리뷰·결과·정량 목표</h3>
|
||||||
|
<p>지난주 리뷰는 <b>바로 앞 주차의 같은 항목</b>에서 가져옵니다(앞 주차가 앞 달 마지막 주차일 수 있습니다). 이름 변경·순서 이동·회의록 생성 순서와 관계없이 이어진 같은 줄을 찾습니다. 그 주차 회의록이 없으면 “회의록 없음”, 회의록은 있지만 항목이 없으면 “지난주 회의록에 없는 줄”로 표시합니다. 몇 주 전 기록을 지난주로 대신 보여 주지 않습니다.</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>전주 업무</b> — 지난 주차에 적은 주요 업무를 그대로 보여 줍니다(읽기 전용).</li>
|
||||||
|
<li><b>결과</b>(글) — 지난 주차 업무를 어떻게 했는지 적습니다(누구나).</li>
|
||||||
|
<li><b>전주 목표</b> — 지난 주차 회의록에서 그 줄에 적은 정량 목표입니다.</li>
|
||||||
|
<li><b>결과</b>(오른쪽 끝) — 지난 주차 결과를 직접 입력합니다(누구나, 다음 주 회의록이 열려 있는 동안). 금액도, <code>18개</code> 같은 글도 됩니다(실적 모듈에서 자동 입력되지 않습니다).</li>
|
||||||
|
<li><b>저장 위치</b> — 이번 화면에서 입력한 지난주 결과(글·금액)는 <b>지난 주차 회의록의 줄</b>에 저장됩니다. 주요 업무·정량 목표는 이번 주차 회의록에 저장됩니다.</li>
|
||||||
|
<li><span class="pjh-ui">순서 바꾸기</span>는 이번주와 지난주 리뷰의 좌우 배치만 바꿉니다. 선택은 로그인한 사람별로 내 브라우저에 기억됩니다.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3 id="meetings-markets">매출 갱신·실적 표시</h3>
|
||||||
|
<p>실적 모듈 매출은 위쪽 숫자 칸(월 누적 실적·누적 목표 대비 달성)에만 쓰입니다. 줄(쿠팡·네이버 등)마다의 이번주 실적·지난주 결과는 자동으로 표시·입력되지 않으며, 지난주 결과는 직접 입력합니다.</p>
|
||||||
|
<p>실적 갱신 권한이 있으면 주차를 열 때 지난주부터 선택한 주의 오늘까지 매출을 자동 갱신합니다. 같은 주의 자동 갱신은 브라우저에서 10분 간격으로 제한하며, 성공 시에는 별도 큰 안내 없이 숫자가 바뀝니다. 실패·일부 쇼핑몰 실패 시 작은 안내와 <span class="pjh-ui">다시 시도</span>가 나옵니다. 마지막 갱신 성공 시각은 실적 모듈 기록이며 숫자에 마우스를 올려 확인할 수 있습니다.</p>
|
||||||
|
<table class="pjh-table">
|
||||||
|
<tr><th>표시·상태</th><th>확인할 내용</th></tr>
|
||||||
|
<tr><td>미확인</td><td>조회에 실패해 값을 알 수 없습니다. <b>0원과 다릅니다.</b> 이에 의존하는 누적 목표 대비 달성도 계산하지 않습니다. 안내의 다시 시도를 사용하거나 실적 연결 상태를 확인하세요.</td></tr>
|
||||||
|
<tr><td>0원</td><td>매출 조회는 성공했지만 해당 기간에 저장된 실적이 없거나 합계가 0원입니다. 필요하면 실적 화면에서 매출 자료를 갱신하세요.</td></tr>
|
||||||
|
<tr><td>실적 미연결·집계 대상 없음</td><td>자동 실적·누적이 비어 있습니다. 회의록 계획·메모는 계속 입력할 수 있습니다.</td></tr>
|
||||||
|
<tr><td>실적 갱신 권한 없음</td><td>새 매출을 요청하지 않고 저장된 실적을 보여 줍니다. 회의록 조회 권한과 매출 갱신 권한은 별개입니다.</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3 id="meetings-rows">구역·줄 추가·순서·삭제</h3>
|
||||||
|
<ul>
|
||||||
|
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
|
||||||
|
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</li>
|
||||||
|
<li><b>주요 업무</b> 칸을 우클릭해 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가</span>를 하면 <b>항목 칸은 그대로</b> 두고 그 항목 안에 줄이 늘어납니다(줄마다 주요 업무·정량 목표는 따로). 같은 메뉴의 <span class="pjh-ui">줄 삭제</span>는 그 한 줄만 지웁니다. 묶인 항목 칸은 항목 칸 메뉴의 <span class="pjh-ui">항목 칸 나누기</span>로 다시 나눕니다. 줄을 추가·삭제하면 새로고침 없이 표가 그 자리에서 움직이며 바뀝니다.</li>
|
||||||
|
<li><b>구역 순서</b> — 첫 열 <b>구분</b> 칸을 우클릭하거나 마우스를 올려 나오는 <span class="pjh-ui">⋯</span>를 누르면 <span class="pjh-ui">구역 위로 · 구역 아래로 · 구역 끝에 줄 추가</span>가 나옵니다. 구역 안의 줄 순서·병합은 그대로 함께 옮겨지고, 다음에 만드는 회의록도 바뀐 순서를 이어받습니다(회의 완료 전까지, 누구나).</li>
|
||||||
|
<li>줄을 삭제하면 주요 업무·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3 id="meetings-save">저장 확인·인쇄·회의록 삭제</h3>
|
||||||
|
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동 같은 업무에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
||||||
|
<p><span class="pjh-ui">인쇄</span>는 브라우저 인쇄창을 엽니다. 인쇄용 화면에서는 사이드바·작은 달력·편집 도구를 숨깁니다. 브라우저의 PDF 저장도 사용할 수 있습니다.</p>
|
||||||
|
<p>Pro user 이상의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 22. 단축키와 FAQ -->
|
||||||
<section class="pjh-sec" id="tips">
|
<section class="pjh-sec" id="tips">
|
||||||
<h2><span class="pjh-num">20</span>단축키와 자주 묻는 질문</h2>
|
<h2><span class="pjh-num">22</span>단축키와 자주 묻는 질문</h2>
|
||||||
<h3>단축키</h3>
|
<h3>단축키</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>키</th><th>하는 일</th></tr>
|
<tr><th>키</th><th>하는 일</th></tr>
|
||||||
<tr><td><kbd>/</kbd></td><td>전체 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
<tr><td><kbd>/</kbd></td><td>업무 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
||||||
<tr><td><kbd>Esc</kbd></td><td>작업 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
<tr><td><kbd>Esc</kbd></td><td>업무 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
||||||
<tr><td><kbd>Enter</kbd></td><td>하위 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
<tr><td><kbd>Enter</kbd></td><td>세부 업무 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
||||||
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
|
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
|
||||||
<tr><td>마우스 오른쪽 버튼</td><td>작업 · 하위 작업 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
<tr><td>마우스 오른쪽 버튼</td><td>업무 · 세부 업무 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
||||||
</table>
|
</table>
|
||||||
<h3>자주 묻는 질문</h3>
|
<h3>자주 묻는 질문</h3>
|
||||||
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 관리자에게 멤버 배정을 부탁하세요.</p>
|
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 그 프로젝트의 Pro user 이상 멤버나 관리자에게 멤버 배정을 부탁하세요.</p>
|
||||||
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>작업·섹션·프로젝트는 만든 사람만 지울 수 있습니다. 만든 사람이나 최고 관리자에게 부탁하세요.</p>
|
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 업무는 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
|
||||||
<p><b>Q. 작업을 잘못 지웠어요.</b><br>3개월 안이라면 관리자가 휴지통에서 복구할 수 있습니다.</p>
|
<p><b>Q. 업무를 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
|
||||||
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
|
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
|
||||||
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
||||||
<p><b>Q. 하위 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>하위 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
|
<p><b>Q. 세부 업무를 다른 프로젝트 업무로 옮길 수 있나요?</b><br>세부 업무는 같은 프로젝트 안의 업무로만 옮길 수 있습니다.</p>
|
||||||
<p><b>Q. 작업을 두 프로젝트에 같이 두고 싶어요.</b><br>작업 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
<p><b>Q. 업무를 두 프로젝트에 같이 두고 싶어요.</b><br>업무 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
||||||
|
<p><b>Q. 목표 표의 실적과 회의록 매출이 달라요.</b><br>목표 표의 월 실적은 직접 입력한 숫자이고, 회의록 매출은 실적 모듈 자료입니다. 매출 단위와 집계 기간도 확인하세요. (<a href="#goals-metrics">숫자 지표</a> · <a href="#meetings-kpis">회의록 지표</a>)</p>
|
||||||
|
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 바로 앞 주차 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
|
||||||
|
<p><b>Q. 도움말에서 필요한 설명을 빠르게 찾고 싶어요.</b><br>이 페이지 위쪽 검색창에 단어를 입력하고 결과를 누르세요. 제목·본문의 일치 단어가 강조되고 해당 소제목으로 이동합니다. <kbd>Enter</kbd>는 첫 결과로 이동, <kbd>Esc</kbd>나 <span class="pjh-ui">지우기</span>는 검색을 초기화합니다.</p>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<a class="pjh-top" href="#top" title="맨 위로" aria-label="맨 위로"><span class="material-symbols-outlined">arrow_upward</span></a>
|
<a class="pjh-top" href="#top" title="맨 위로" aria-label="맨 위로"><span class="material-symbols-outlined">arrow_upward</span></a>
|
||||||
|
|
||||||
<script>
|
<script src="/static/project-help.js?v=20261003a" defer></script>
|
||||||
// 목차 — 지금 읽고 있는 장을 강조한다(스크롤 위치 기준).
|
|
||||||
(function () {
|
|
||||||
var links = Array.prototype.slice.call(document.querySelectorAll(".pjh-toc a"));
|
|
||||||
var secs = links.map(function (a) { return document.querySelector(a.getAttribute("href")); });
|
|
||||||
if (!("IntersectionObserver" in window)) return;
|
|
||||||
var io = new IntersectionObserver(function (entries) {
|
|
||||||
entries.forEach(function (en) {
|
|
||||||
if (!en.isIntersecting) return;
|
|
||||||
var i = secs.indexOf(en.target);
|
|
||||||
links.forEach(function (a, k) { a.classList.toggle("is-active", k === i); });
|
|
||||||
});
|
|
||||||
}, { rootMargin: "-10% 0px -75% 0px" });
|
|
||||||
secs.forEach(function (s) { if (s) io.observe(s); });
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -18,28 +18,32 @@
|
|||||||
<div class="pj-section-head">
|
<div class="pj-section-head">
|
||||||
<h2>수신함</h2>
|
<h2>수신함</h2>
|
||||||
<div style="display:flex; gap:8px;">
|
<div style="display:flex; gap:8px;">
|
||||||
|
{# PC 알림 프로그램(023) — 연결·내려받기 화면은 수신함 안에서 들어간다 #}
|
||||||
|
<a class="pj-btn pj-inbox-notifier" href="/project/notifier" title="브라우저가 뒤에 있어도 PC 화면에 알림 띄우기">
|
||||||
|
<span class="material-symbols-outlined">desktop_windows</span>PC 알림</a>
|
||||||
<button type="button" class="pj-btn" id="pj-mentions-readall">태그 모두 확인</button>
|
<button type="button" class="pj-btn" id="pj-mentions-readall">태그 모두 확인</button>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-readall">알림 모두 읽음</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-readall">알림 모두 읽음</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-view pj-inbox-pane">
|
<div class="pj-view pj-inbox-pane">
|
||||||
|
|
||||||
<!-- 아사나 Inbox 처럼 "나를 태그(@)한 업무"를 맨 위에 리스트로 보여준다.
|
<!-- 아사나 Inbox 처럼 "나를 태그(@)한 업무"를 맨 위에 리스트로 보여준다. 확인 안 한 태그·읽지 않은 알림만.
|
||||||
"확인"을 누르면 수신함에 머문 채 오른쪽에 그 작업 창이 열린다
|
줄을 누르면 수신함에 머문 채 오른쪽에 그 작업 창이 열리고(project.js initInboxTaskPanel),
|
||||||
(프로젝트 화면을 ?task=&embed=1 로 iframe 에 — project.js initInboxTaskPanel). -->
|
확인한 줄은 다른 줄을 고르거나 창을 닫으면 목록에서 빠진다. -->
|
||||||
<div class="pj-inbox-section">
|
<div class="pj-inbox-section">
|
||||||
<h3 class="pj-inbox-h3">
|
<h3 class="pj-inbox-h3">
|
||||||
나를 태그한 작업
|
나를 태그한 업무
|
||||||
<span class="pj-inbox-count" id="pj-mention-unread"
|
<span class="pj-inbox-count" id="pj-mention-unread"
|
||||||
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
||||||
</h3>
|
</h3>
|
||||||
{% if not mentioned_tasks %}
|
{% if not mentioned_tasks %}
|
||||||
<div class="pj-empty">태그된 작업이 없습니다.</div>
|
<div class="pj-empty">태그된 업무가 없습니다.</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<ul class="pj-inbox pj-mention-list" id="pj-mention-tasks">
|
<ul class="pj-inbox pj-mention-list" id="pj-mention-tasks">
|
||||||
{% for t in mentioned_tasks %}
|
{% for t in mentioned_tasks %}
|
||||||
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}"
|
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}" tabindex="0" role="button"
|
||||||
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}">
|
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}"
|
||||||
|
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 업무 창">
|
||||||
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
|
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
|
||||||
<div class="pj-inbox-body">
|
<div class="pj-inbox-body">
|
||||||
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
|
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
|
||||||
@@ -50,8 +54,6 @@
|
|||||||
{% if t.mention_actor %} · {% set nm = t.mention_actor.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }}님이 태그{% endif %}
|
{% if t.mention_actor %} · {% set nm = t.mention_actor.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }}님이 태그{% endif %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<a class="pj-btn pj-inbox-go" href="/project/p/{{ t.project_id }}?task={{ t.id }}"
|
|
||||||
data-task-id="{{ t.id }}">확인</a>
|
|
||||||
</li>
|
</li>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
</ul>
|
||||||
@@ -65,14 +67,16 @@
|
|||||||
{% else %}
|
{% else %}
|
||||||
<ul class="pj-inbox" id="pj-inbox">
|
<ul class="pj-inbox" id="pj-inbox">
|
||||||
{% for n in notifications %}
|
{% for n in notifications %}
|
||||||
<li class="pj-inbox-item {% if not n.is_read %}is-unread{% endif %}"
|
<li class="pj-inbox-item {% if not n.is_read %}is-unread{% endif %}" tabindex="0" role="button"
|
||||||
data-id="{{ n.id }}"
|
data-id="{{ n.id }}"
|
||||||
{% if n.task_id %}data-project="{{ n.project_id }}"{% endif %}>
|
{% if n.task_id %}data-project="{{ n.project_id }}" data-task-id="{{ n.task_id }}"{% endif %}
|
||||||
|
{% if n.task_id %}data-href="/project/t/{{ n.task_id }}"{% elif n.project_id %}data-href="/project/p/{{ n.project_id }}"{% endif %}>
|
||||||
<span class="material-symbols-outlined pj-inbox-icon">
|
<span class="material-symbols-outlined pj-inbox-icon">
|
||||||
{% if n.type == 'assigned' %}assignment_ind
|
{% if n.type == 'assigned' %}assignment_ind
|
||||||
{% elif n.type == 'completed' %}task_alt
|
{% elif n.type == 'completed' %}task_alt
|
||||||
{% elif n.type == 'comment' %}chat_bubble
|
{% elif n.type == 'comment' %}chat_bubble
|
||||||
{% elif n.type == 'mention' %}alternate_email
|
{% elif n.type == 'mention' %}alternate_email
|
||||||
|
{% elif n.type == 'reaction' %}add_reaction
|
||||||
{% elif n.type == 'due_soon' %}schedule
|
{% elif n.type == 'due_soon' %}schedule
|
||||||
{% elif n.type == 'due_today' %}today
|
{% elif n.type == 'due_today' %}today
|
||||||
{% elif n.type == 'overdue' %}alarm
|
{% elif n.type == 'overdue' %}alarm
|
||||||
@@ -85,12 +89,6 @@
|
|||||||
{% if n.actor_email %}{% set nm = n.actor_email.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }} · {% endif %}{{ n.created_at[:16].replace('T',' ') }}
|
{% if n.actor_email %}{% set nm = n.actor_email.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }} · {% endif %}{{ n.created_at[:16].replace('T',' ') }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% if n.project_id %}
|
|
||||||
{# 작업 알림은 "확인" → 수신함에 머문 채 오른쪽에 작업 창(project.js initInboxTaskPanel) #}
|
|
||||||
<a class="pj-btn pj-inbox-go"
|
|
||||||
href="/project/p/{{ n.project_id }}{% if n.task_id %}?task={{ n.task_id }}{% endif %}"
|
|
||||||
{% if n.task_id %}data-task-id="{{ n.task_id }}"{% endif %}>확인</a>
|
|
||||||
{% endif %}
|
|
||||||
</li>
|
</li>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
</ul>
|
||||||
@@ -104,5 +102,5 @@
|
|||||||
{% include "project/_side_modals.html" %}
|
{% include "project/_side_modals.html" %}
|
||||||
{% include "project/_member_tasks_modal.html" %}
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261014a" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
{# 프로젝트 모듈의 첫 화면 = 내 업무. 예전 프로젝트 홈(카드 그리드)은 없앴다. #}
|
{# 프로젝트 모듈의 첫 화면 = 내 업무. 예전 프로젝트 홈(카드 그리드)은 없앴다. #}
|
||||||
<div class="pj-wrap pj-mytasks-view" data-me="{{ user.email }}"
|
<div class="pj-wrap pj-mytasks-view" data-me="{{ user.email }}"
|
||||||
data-is-admin="{{ 'true' if is_admin else 'false' }}"
|
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||||
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}">
|
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}">
|
||||||
<div class="pj-layout">
|
<div class="pj-layout">
|
||||||
{% with current_pid = 0, side_active = "mytasks" %}{% include "project/_side.html" %}{% endwith %}
|
{% with current_pid = 0, side_active = "mytasks" %}{% include "project/_side.html" %}{% endwith %}
|
||||||
@@ -31,7 +31,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="pj-title-wrap">
|
<div class="pj-title-wrap">
|
||||||
<h1 class="pj-project-title">
|
<h1 class="pj-project-title">
|
||||||
<span class="pj-project-title-pill" style="--pj-color: #7b68ee">내 작업</span>
|
<span class="pj-project-title-pill" style="--pj-color: #7b68ee">내 업무</span>
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-mytasks-summary" id="pj-mytasks-summary"></div>
|
<div class="pj-mytasks-summary" id="pj-mytasks-summary"></div>
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
<div class="pj-filterbar" id="pj-mt-filterbar">
|
<div class="pj-filterbar" id="pj-mt-filterbar">
|
||||||
<label class="pj-fb-search">
|
<label class="pj-fb-search">
|
||||||
<span class="material-symbols-outlined">filter_list</span>
|
<span class="material-symbols-outlined">filter_list</span>
|
||||||
<input type="search" id="pj-mt-q" placeholder="내 작업에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
|
<input type="search" id="pj-mt-q" placeholder="내 업무에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
|
||||||
</label>
|
</label>
|
||||||
<select id="pj-mt-due" class="pj-fb-select" title="마감일">
|
<select id="pj-mt-due" class="pj-fb-select" title="마감일">
|
||||||
<option value="all">마감: 전체</option>
|
<option value="all">마감: 전체</option>
|
||||||
@@ -62,7 +62,7 @@
|
|||||||
<thead></thead>
|
<thead></thead>
|
||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
</table>
|
</table>
|
||||||
<div class="pj-empty" id="pj-mytasks-empty" hidden>표시할 작업이 없습니다.</div>
|
<div class="pj-empty" id="pj-mytasks-empty" hidden>표시할 업무가 없습니다.</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
<span class="material-symbols-outlined">attach_file</span>
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
<input type="file" id="pj-cm-file-input" multiple hidden />
|
<input type="file" id="pj-cm-file-input" multiple hidden />
|
||||||
</label>
|
</label>
|
||||||
<input type="text" id="pj-cm-input" placeholder="댓글 입력… (이미지는 붙여넣기 가능)" autocomplete="off" />
|
<textarea id="pj-cm-input" class="pj-composer-ta" rows="1" placeholder="댓글 입력… (Shift+Enter 줄바꿈, 이미지는 붙여넣기 가능)" autocomplete="off"></textarea>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -100,5 +100,5 @@
|
|||||||
"today": {{ today | tojson }}
|
"today": {{ today | tojson }}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261014a" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}
|
||||||
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{# PC 알림 프로그램(023) — 트레이 프로그램(desktop/notifier) 내려받기, 연결 승인(?code=), 연결된 PC 해제.
|
||||||
|
토큰은 프로그램이 받아 PC 에 암호화 저장(Windows DPAPI). 이 화면은 토큰 원문을 보지 않는다. #}
|
||||||
|
<div class="pj-wrap pj-inbox-view pj-notifier-view">
|
||||||
|
<div class="pj-layout">
|
||||||
|
{% with current_pid = 0, side_active = "inbox" %}{% include "project/_side.html" %}{% endwith %}
|
||||||
|
|
||||||
|
<section class="pj-main">
|
||||||
|
<div class="pj-section-head"><h2><a class="pj-notifier-back" href="/project/inbox">수신함</a> › PC 알림 프로그램</h2></div>
|
||||||
|
<div class="pj-view pj-inbox-pane pj-notifier-pane">
|
||||||
|
{% if not notifier_enabled %}
|
||||||
|
<div class="pj-empty">PC 알림 연결이 아직 준비되지 않았습니다(DB 마이그레이션 023 필요).</div>
|
||||||
|
{% else %}
|
||||||
|
|
||||||
|
{% if code %}
|
||||||
|
<div class="pj-notifier-card is-link" id="pj-notifier-link" data-code="{{ code }}">
|
||||||
|
{% if link and not link.approved_at %}
|
||||||
|
<h3>이 PC 를 내 알림에 연결할까요?</h3>
|
||||||
|
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
|
||||||
|
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
|
||||||
|
<b>{{ user.name or user.email }}</b> 님의 태그·업무 배정 알림이 뜹니다.</p>
|
||||||
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
|
||||||
|
{% elif link %}
|
||||||
|
<h3>이미 연결을 승인했습니다</h3>
|
||||||
|
<p class="pj-notifier-note">알림 프로그램이 곧 연결을 마칩니다. 이 창은 닫아도 됩니다.</p>
|
||||||
|
{% else %}
|
||||||
|
<h3>연결 코드가 없거나 만료되었습니다</h3>
|
||||||
|
<p class="pj-notifier-note">연결 코드는 10분 동안만 쓸 수 있습니다. 알림 프로그램에서 [연결]을 다시 누르세요.</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="pj-notifier-card">
|
||||||
|
<h3>설치</h3>
|
||||||
|
<ol class="pj-notifier-steps">
|
||||||
|
<li>{% if download_ready %}<a class="pj-btn pj-btn-primary pj-btn-sm" href="/project/notifier/download">DBXNotifier.exe 내려받기</a>
|
||||||
|
{% else %}관리자에게 <b>DBXNotifier.exe</b> 파일을 받으세요.{% endif %}
|
||||||
|
설치 없이 파일 하나로 실행됩니다(Windows 10·11).</li>
|
||||||
|
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
|
||||||
|
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
|
||||||
|
</ol>
|
||||||
|
<p class="pj-notifier-note">나를 태그하거나 업무가 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
|
||||||
|
[열기]를 누르면 브라우저에서 그 업무가 열립니다.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pj-notifier-card">
|
||||||
|
<h3>연결된 PC</h3>
|
||||||
|
{% if devices %}
|
||||||
|
<table class="pj-table pj-notifier-table">
|
||||||
|
<thead><tr><th>PC 이름</th><th>연결한 때</th><th>마지막 확인</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for d in devices %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ d.device_name or '-' }}</td>
|
||||||
|
<td>{{ (d.created_at or '')[:16] | replace('T', ' ') }}</td>
|
||||||
|
<td>{{ (d.last_seen_at or '-')[:16] | replace('T', ' ') }}</td>
|
||||||
|
<td class="pj-trash-act"><button type="button" class="pj-btn pj-btn-sm pj-notifier-revoke"
|
||||||
|
data-id="{{ d.id }}" data-name="{{ d.device_name }}">연결 해제</button></td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{% else %}
|
||||||
|
<p class="pj-notifier-note">연결된 PC 가 없습니다.</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% include "project/_side_modals.html" %}
|
||||||
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
async function post(url, body) {
|
||||||
|
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) });
|
||||||
|
const data = await res.json().catch(function () { return {}; });
|
||||||
|
if (!res.ok) throw new Error(data.detail || ("HTTP " + res.status));
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
const approve = document.getElementById("pj-notifier-approve");
|
||||||
|
if (approve) approve.addEventListener("click", async function () {
|
||||||
|
approve.disabled = true;
|
||||||
|
try {
|
||||||
|
await post("/project/api/notifier/link/approve", { code: document.getElementById("pj-notifier-link").dataset.code });
|
||||||
|
location.replace("/project/notifier?code=" + encodeURIComponent(document.getElementById("pj-notifier-link").dataset.code));
|
||||||
|
} catch (e) { approve.disabled = false; alert("연결 실패: " + e.message); }
|
||||||
|
});
|
||||||
|
document.querySelectorAll(".pj-notifier-revoke").forEach(function (b) {
|
||||||
|
b.addEventListener("click", async function () {
|
||||||
|
if (!confirm((b.dataset.name || "이 PC") + " 의 알림 연결을 해제할까요?")) return;
|
||||||
|
b.disabled = true;
|
||||||
|
try { await post("/project/api/notifier/devices/" + b.dataset.id + "/revoke"); location.reload(); }
|
||||||
|
catch (e) { b.disabled = false; alert("해제 실패: " + e.message); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<script src="/static/project.js?v=20261014a" defer></script>
|
||||||
|
{% endblock %}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
<!-- 타임라인 vis-timeline — self-host -->
|
<!-- 타임라인 vis-timeline — self-host -->
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
<div class="pj-wrap pj-project-view"
|
<div class="pj-wrap pj-project-view"
|
||||||
data-project-id="{{ project.id }}"
|
data-project-id="{{ project.id }}"
|
||||||
data-can-manage="{{ 'true' if can_manage else 'false' }}"
|
data-can-manage="{{ 'true' if can_manage else 'false' }}"
|
||||||
data-is-admin="{{ 'true' if is_admin else 'false' }}"
|
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||||
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
|
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
|
||||||
data-me="{{ user.email }}">
|
data-me="{{ user.email }}">
|
||||||
|
|
||||||
@@ -43,13 +43,13 @@
|
|||||||
<div class="pj-head-left">
|
<div class="pj-head-left">
|
||||||
<!-- 프로젝트 제목 + 이 프로젝트의 멤버 아이콘.
|
<!-- 프로젝트 제목 + 이 프로젝트의 멤버 아이콘.
|
||||||
마우스를 올리면 이름(data-tip → initHoverTips), 클릭하면 그 사람이
|
마우스를 올리면 이름(data-tip → initHoverTips), 클릭하면 그 사람이
|
||||||
이 프로젝트에서 맡은 업무 팝업, 우클릭(관리자)하면 제외. 목록은
|
이 프로젝트에서 맡은 업무 팝업, 우클릭(Pro user 이상)하면 제외. 목록은
|
||||||
renderMemberList 가 같은 마크업으로 다시 그린다.
|
renderMemberList 가 같은 마크업으로 다시 그린다.
|
||||||
"전체 프로젝트" 스코프에선 제목이 "전체 프로젝트"로 바뀌고 멤버는 숨긴다
|
"전체 프로젝트" 스코프에선 제목이 "전체 프로젝트"로 바뀌고 멤버는 숨긴다
|
||||||
(.pj-title-wrap.is-all-scope). -->
|
(.pj-title-wrap.is-all-scope). -->
|
||||||
<div class="pj-title-wrap" id="pj-title-wrap">
|
<div class="pj-title-wrap" id="pj-title-wrap">
|
||||||
<h1 class="pj-project-title">
|
<h1 class="pj-project-title">
|
||||||
<span class="pj-project-title-pill" style="--pj-color: {{ project.color or '#4573d2' }}"><span class="material-symbols-outlined pj-pill-ic">{{ project.icon or 'folder' }}</span><span class="pj-pill-name">{{ project.name }}</span></span>
|
<span class="pj-project-title-pill" style="--pj-color: {{ project.color or '#4573d2' }}">{% set _pic = project.icon or 'folder' %}{% set _a = _pic.startswith('asana:') %}<span class="material-symbols-outlined pj-pill-ic{% if _a %} pj-ic-asana{% endif %}">{{ _pic[6:] if _a else _pic }}</span><span class="pj-pill-name">{{ project.name }}</span></span>
|
||||||
</h1>
|
</h1>
|
||||||
<h1 class="pj-project-title pj-all-title">
|
<h1 class="pj-project-title pj-all-title">
|
||||||
<span class="pj-project-title-all"><span class="material-symbols-outlined pj-pill-ic">apps</span><span class="pj-pill-name">전체 프로젝트</span></span>
|
<span class="pj-project-title-all"><span class="material-symbols-outlined pj-pill-ic">apps</span><span class="pj-pill-name">전체 프로젝트</span></span>
|
||||||
@@ -66,8 +66,8 @@
|
|||||||
</span>
|
</span>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<button type="button" class="pj-title-addmember" id="pj-add-member" title="멤버 배정">+</button>
|
<button type="button" class="pj-title-addmember" id="pj-add-member" title="멤버 배정·제외">+</button>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-view-tabs pj-view-tabs-line" id="pj-view-tabs">
|
<div class="pj-view-tabs pj-view-tabs-line" id="pj-view-tabs">
|
||||||
@@ -80,7 +80,8 @@
|
|||||||
</div>
|
</div>
|
||||||
<!-- 아사나처럼 기본은 "이 프로젝트"만 보여준다. 전체 프로젝트 보기는
|
<!-- 아사나처럼 기본은 "이 프로젝트"만 보여준다. 전체 프로젝트 보기는
|
||||||
예전처럼 접근 가능한 모든 프로젝트를 합쳐서 보여주는 모드. -->
|
예전처럼 접근 가능한 모든 프로젝트를 합쳐서 보여주는 모드. -->
|
||||||
<div class="pj-view-tabs" id="pj-scope-toggle">
|
{# 2026-10-08 — 토글은 숨기고 왼쪽 메뉴 "전체 보기"(Pro user 이상, ?scope=all)로 바꿈. 상태 보관용으로만 남김 #}
|
||||||
|
<div class="pj-view-tabs" id="pj-scope-toggle" style="display:none">
|
||||||
<button type="button" class="pj-tab is-active" data-scope="project">이 프로젝트</button>
|
<button type="button" class="pj-tab is-active" data-scope="project">이 프로젝트</button>
|
||||||
<button type="button" class="pj-tab" data-scope="all">전체 프로젝트</button>
|
<button type="button" class="pj-tab" data-scope="all">전체 프로젝트</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -190,7 +191,7 @@
|
|||||||
<div class="pj-view" data-view="list" hidden>
|
<div class="pj-view" data-view="list" hidden>
|
||||||
<table class="pj-table" id="pj-list">
|
<table class="pj-table" id="pj-list">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>작업</th><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>
|
</thead>
|
||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -213,12 +214,9 @@
|
|||||||
<h3 id="pj-stage-modal-title">새 섹션</h3>
|
<h3 id="pj-stage-modal-title">새 섹션</h3>
|
||||||
<input type="hidden" id="pj-stg-id" />
|
<input type="hidden" id="pj-stg-id" />
|
||||||
<label>이름<input type="text" id="pj-stg-name" placeholder="섹션 이름" autocomplete="off" /></label>
|
<label>이름<input type="text" id="pj-stg-name" placeholder="섹션 이름" autocomplete="off" /></label>
|
||||||
<label>색상
|
|
||||||
<span class="pj-color-palette" id="pj-stg-colors"></span>
|
|
||||||
</label>
|
|
||||||
<div class="pj-field-label">기본 담당자
|
<div class="pj-field-label">기본 담당자
|
||||||
<div class="pj-member-picker" id="pj-stg-assignee"></div>
|
<div class="pj-member-picker" id="pj-stg-assignee"></div>
|
||||||
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 작업을 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 작업만 이 사람에게 자동 배정됩니다.</span>
|
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 업무를 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 업무만 이 사람에게 자동 배정됩니다.</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-modal-actions">
|
<div class="pj-modal-actions">
|
||||||
<span style="flex:1"></span>
|
<span style="flex:1"></span>
|
||||||
@@ -239,13 +237,13 @@
|
|||||||
<div class="pj-modal-actions pj-modal-actions-top">
|
<div class="pj-modal-actions pj-modal-actions-top">
|
||||||
<!-- 공유 — 이 업무의 퍼머링크(/project/t/{id})를 클립보드에 복사.
|
<!-- 공유 — 이 업무의 퍼머링크(/project/t/{id})를 클립보드에 복사.
|
||||||
받은 사람이 열면 로그인 후 이 업무 팝업이 바로 뜬다(멤버만). -->
|
받은 사람이 열면 로그인 후 이 업무 팝업이 바로 뜬다(멤버만). -->
|
||||||
<button type="button" class="pj-btn pj-btn-share" id="pj-share-task" hidden title="이 작업 링크 복사">
|
<button type="button" class="pj-btn pj-btn-share" id="pj-share-task" hidden title="이 업무 링크 복사">
|
||||||
<span class="material-symbols-outlined">link</span> 공유
|
<span class="material-symbols-outlined">link</span> 공유
|
||||||
</button>
|
</button>
|
||||||
<button type="button" class="pj-btn pj-btn-complete" id="pj-toggle-complete" hidden>✓ 완료로 표시</button>
|
<button type="button" class="pj-btn pj-btn-complete" id="pj-toggle-complete" hidden>✓ 완료로 표시</button>
|
||||||
<button type="button" class="pj-btn pj-btn-danger" id="pj-delete-task" hidden>삭제</button>
|
<button type="button" class="pj-btn pj-btn-danger" id="pj-delete-task" hidden>삭제</button>
|
||||||
<!-- 수신함 오른쪽 패널(?embed=1)에서만 보인다 — 이 작업이 있는 프로젝트 화면으로 이동. -->
|
<!-- 수신함 오른쪽 패널(?embed=1)에서만 보인다 — 이 작업이 있는 프로젝트 화면으로 이동. -->
|
||||||
<button type="button" class="pj-btn pj-btn-goto-project" id="pj-goto-project" title="이 작업이 있는 프로젝트 화면으로 이동">
|
<button type="button" class="pj-btn pj-btn-goto-project" id="pj-goto-project" title="이 업무가 있는 프로젝트 화면으로 이동">
|
||||||
<span class="material-symbols-outlined">open_in_new</span> 프로젝트로 이동
|
<span class="material-symbols-outlined">open_in_new</span> 프로젝트로 이동
|
||||||
</button>
|
</button>
|
||||||
<span style="flex:1"></span>
|
<span style="flex:1"></span>
|
||||||
@@ -259,16 +257,16 @@
|
|||||||
<!-- 아사나처럼 큰 제목은 이 무테 입력칸 하나뿐이다(위의 작은 안내줄은
|
<!-- 아사나처럼 큰 제목은 이 무테 입력칸 하나뿐이다(위의 작은 안내줄은
|
||||||
없앴다 — 버튼 줄 바로 아래 공간을 아낀다). -->
|
없앴다 — 버튼 줄 바로 아래 공간을 아낀다). -->
|
||||||
<input type="hidden" id="pj-t-id" />
|
<input type="hidden" id="pj-t-id" />
|
||||||
<!-- 하위 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
|
<!-- 세부 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
|
||||||
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 작업 열기">
|
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 업무 열기">
|
||||||
<span class="material-symbols-outlined">subdirectory_arrow_left</span>
|
<span class="material-symbols-outlined">subdirectory_arrow_left</span>
|
||||||
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
|
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
|
||||||
</button>
|
</button>
|
||||||
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="작업 제목"></textarea>
|
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="업무 제목"></textarea>
|
||||||
<!-- 다른 프로젝트에서 연결돼 온 작업을 원 소속 권한 없이 열었을 때 — 보기만 된다(서버도 변경 거절). -->
|
<!-- 다른 프로젝트에서 연결돼 온 작업을 원 소속 권한 없이 열었을 때 — 보기만 된다(서버도 변경 거절). -->
|
||||||
<div class="pj-readonly-note" id="pj-t-readonly" hidden>
|
<div class="pj-readonly-note" id="pj-t-readonly" hidden>
|
||||||
<span class="material-symbols-outlined">visibility</span>
|
<span class="material-symbols-outlined">visibility</span>
|
||||||
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 작업이라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
|
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 업무라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pj-modal-body">
|
<div class="pj-modal-body">
|
||||||
@@ -330,6 +328,18 @@
|
|||||||
</div>
|
</div>
|
||||||
<button type="button" class="pj-follow-toggle" id="pj-follow-toggle">협업자로 참여</button>
|
<button type="button" class="pj-follow-toggle" id="pj-follow-toggle">협업자로 참여</button>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 프로젝트 연결 — 협업자 아래에서 목록·선택·추가를 한 줄로 표시. -->
|
||||||
|
<div class="pj-meta-row2 pj-projects-row" id="pj-links-block" hidden>
|
||||||
|
<span class="pj-meta-cell-label pj-projects-label">
|
||||||
|
<span class="material-symbols-outlined pj-gicon pj-gicon-sm" aria-hidden="true">link</span> 프로젝트
|
||||||
|
</span>
|
||||||
|
<div class="pj-link-chips" id="pj-link-chips"></div>
|
||||||
|
<div class="pj-link-form" id="pj-link-form">
|
||||||
|
<select id="pj-link-project" aria-label="연결할 프로젝트"><option value="">프로젝트 선택…</option></select>
|
||||||
|
<select id="pj-link-stage" aria-label="연결할 섹션"><option value="">섹션 선택…</option></select>
|
||||||
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-link-save">다른 프로젝트에 추가</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -339,69 +349,38 @@
|
|||||||
<span class="pj-extra-label">설명</span>
|
<span class="pj-extra-label">설명</span>
|
||||||
<span class="pj-muted-sm" id="pj-desc-hint"></span>
|
<span class="pj-muted-sm" id="pj-desc-hint"></span>
|
||||||
</div>
|
</div>
|
||||||
{# 서식 도구 — 모든 버튼을 같은 아이콘 글꼴(Material Symbols)·같은 크기로 그려
|
{% include "project/_desc_fmtbar.html" %}
|
||||||
한 줄에 딱 맞춰 선다(예전엔 글자·이모지가 섞여 높이가 들쭉날쭉했다). #}
|
|
||||||
<div class="pj-desc-fmtbar" id="pj-desc-fmtbar">
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="bold" title="굵게 (Ctrl+B)"><span class="material-symbols-outlined">format_bold</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
|
|
||||||
<span class="pj-desc-fmtsep"></span>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertCheckbox" title="체크박스 넣기"><span class="material-symbols-outlined">check_box</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="formatBlock" data-arg="blockquote" title="인용구"><span class="material-symbols-outlined">format_quote</span></button>
|
|
||||||
<span class="pj-desc-fmtsep"></span>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="createLink" title="링크 삽입"><span class="material-symbols-outlined">link</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="removeFormat" title="서식 지우기"><span class="material-symbols-outlined">format_clear</span></button>
|
|
||||||
<span class="pj-desc-fmtsep"></span>
|
|
||||||
<label class="pj-desc-fmtbtn" id="pj-desc-imgbtn" title="이미지 추가"><span class="material-symbols-outlined">image</span><input type="file" id="pj-desc-img-input" accept="image/*" hidden /></label>
|
|
||||||
</div>
|
|
||||||
<div class="pj-desc-wrap">
|
<div class="pj-desc-wrap">
|
||||||
<div class="pj-desc-editor" id="pj-t-desc" contenteditable="true" data-placeholder="설명을 입력하세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
<div class="pj-desc-editor" id="pj-t-desc" contenteditable="true" data-placeholder="설명을 입력하세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 하위 업무 — 설명 바로 아래 줄에서 팝업 너비 전체를 쓴다.
|
<!-- 세부 업무 — 설명 바로 아래 줄에서 팝업 너비 전체를 쓴다.
|
||||||
기존 업무 편집 시에만. -->
|
기존 업무 편집 시에만. -->
|
||||||
<div class="pj-task-extra pj-subtask-full" id="pj-subtask-block" hidden>
|
<div class="pj-task-extra pj-subtask-full" id="pj-subtask-block" hidden>
|
||||||
<div class="pj-extra-head">
|
<div class="pj-extra-head">
|
||||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 하위 작업
|
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 세부 업무
|
||||||
</div>
|
</div>
|
||||||
<ul class="pj-subtask-list" id="pj-subtask-list"></ul>
|
<ul class="pj-subtask-list" id="pj-subtask-list"></ul>
|
||||||
<div class="pj-subtask-form">
|
<div class="pj-subtask-form">
|
||||||
<input type="text" id="pj-subtask-input" placeholder="하위 작업 제목…" autocomplete="off" />
|
<input type="text" id="pj-subtask-input" placeholder="세부 업무 제목…" autocomplete="off" />
|
||||||
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
|
{# 아이콘 순서는 보드 카드 새 줄과 같게 — 마감일 · 담당자 · 협업자 #}
|
||||||
<input type="date" id="pj-subtask-add-due" />
|
<input type="date" id="pj-subtask-add-due" />
|
||||||
|
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
|
||||||
|
<button type="button" class="pj-assignee-btn is-empty pj-subtask-add-fol" id="pj-subtask-add-followers" title="협업자 지정">협업자 없음</button>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-subtask-add">추가</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-subtask-add">추가</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 첨부파일 | 연결된 프로젝트 — 나란히 2열(팝업 너비 전체를 나눠 쓴다).
|
<!-- 첨부파일 — 팝업 너비 전체, 기존 업무 편집 시에만. -->
|
||||||
기존 업무 편집 시에만. -->
|
<div class="pj-task-extra" id="pj-attach-block" hidden>
|
||||||
<div class="pj-side-2col">
|
<div class="pj-extra-head">
|
||||||
<div class="pj-task-extra" id="pj-attach-block" hidden>
|
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">attach_file</span> 첨부 파일
|
||||||
<div class="pj-extra-head">
|
<label class="pj-upload-btn">
|
||||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">attach_file</span> 첨부 파일
|
파일 추가<input type="file" id="pj-attach-input" hidden />
|
||||||
<label class="pj-upload-btn">
|
</label>
|
||||||
파일 추가<input type="file" id="pj-attach-input" hidden />
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<ul class="pj-attach-list" id="pj-attach-list"></ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 연결된 프로젝트 — 멀티호밍(아사나식). -->
|
|
||||||
<div class="pj-task-extra" id="pj-links-block" hidden>
|
|
||||||
<div class="pj-extra-head">
|
|
||||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">link</span> 프로젝트
|
|
||||||
</div>
|
|
||||||
<div class="pj-link-chips" id="pj-link-chips"></div>
|
|
||||||
<div class="pj-link-form" id="pj-link-form">
|
|
||||||
<select id="pj-link-project"><option value="">프로젝트 선택…</option></select>
|
|
||||||
<select id="pj-link-stage"><option value="">섹션 선택…</option></select>
|
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-link-save">다른 프로젝트에 추가</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<ul class="pj-attach-list" id="pj-attach-list"></ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 댓글(활동) — 팝업 너비 전체를 쓰는 맨 아래 줄. 길어지면 자체
|
<!-- 댓글(활동) — 팝업 너비 전체를 쓰는 맨 아래 줄. 길어지면 자체
|
||||||
@@ -420,7 +399,7 @@
|
|||||||
바깥이라 끝까지 내려도 마지막 내용은 이 칸 바로 위에서 멈추고 가리지 않는다. -->
|
바깥이라 끝까지 내려도 마지막 내용은 이 칸 바로 위에서 멈추고 가리지 않는다. -->
|
||||||
<div class="pj-comment-dock" id="pj-comment-dock" hidden>
|
<div class="pj-comment-dock" id="pj-comment-dock" hidden>
|
||||||
<div class="pj-comment-form">
|
<div class="pj-comment-form">
|
||||||
<input type="text" id="pj-comment-input" placeholder="댓글을 추가하거나 @로 멤버를 태그하세요" autocomplete="off" />
|
<textarea id="pj-comment-input" class="pj-composer-ta" rows="1" placeholder="댓글을 추가하거나 @로 멤버를 태그하세요 (Shift+Enter 줄바꿈)" autocomplete="off"></textarea>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-comment-send">등록</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-comment-send">등록</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -428,25 +407,20 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% if is_admin %}
|
{% if pj_pro %}
|
||||||
<!-- 멤버 배정 모달 — 등록된 사용자(프로젝트 권한 보유)를 자동 목록화 -->
|
<!-- 멤버 배정 모달 — 등록된 사용자(프로젝트 권한 보유)를 자동 목록화 -->
|
||||||
<div class="pj-modal" id="pj-modal-member" hidden>
|
<div class="pj-modal" id="pj-modal-member" hidden>
|
||||||
<div class="pj-modal-card">
|
<div class="pj-modal-card">
|
||||||
<h3>멤버 배정</h3>
|
<h3>멤버 배정 · 제외</h3>
|
||||||
<p class="pj-modal-hint">관리자 페이지에서 <b>프로젝트 관리</b> 권한을 켠 직원이 후보로 나옵니다. 여러 명을 한 번에 선택할 수 있습니다.</p>
|
<p class="pj-modal-hint">체크하면 배정, 체크를 풀면 제외됩니다(지금 멤버는 체크된 채로 나옵니다). 후보는 관리자 페이지에서
|
||||||
|
<b>프로젝트 관리</b> 권한을 켠 직원입니다. 배정된 멤버는 모두 이 프로젝트를 보고 수정할 수 있고, 소유자는 뺄 수 없습니다.</p>
|
||||||
<div class="pj-field-label">직원
|
<div class="pj-field-label">직원
|
||||||
<div class="pj-member-picker" id="pj-m-users">불러오는 중…</div>
|
<div class="pj-member-picker" id="pj-m-users">불러오는 중…</div>
|
||||||
</div>
|
</div>
|
||||||
<label>역할
|
|
||||||
<select id="pj-m-role">
|
|
||||||
<option value="member" selected>멤버</option>
|
|
||||||
<option value="manager">관리(서브·작업 관리)</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<div class="pj-modal-actions">
|
<div class="pj-modal-actions">
|
||||||
<span style="flex:1"></span>
|
<span style="flex:1"></span>
|
||||||
<button type="button" class="pj-btn" data-close>취소</button>
|
<button type="button" class="pj-btn" data-close>취소</button>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-member">배정</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-member">저장</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -466,7 +440,7 @@
|
|||||||
<span class="material-symbols-outlined">attach_file</span>
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
<input type="file" id="pj-cm-file-input" multiple hidden />
|
<input type="file" id="pj-cm-file-input" multiple hidden />
|
||||||
</label>
|
</label>
|
||||||
<input type="text" id="pj-cm-input" placeholder="댓글 입력… (이미지는 붙여넣기 가능)" autocomplete="off" />
|
<textarea id="pj-cm-input" class="pj-composer-ta" rows="1" placeholder="댓글 입력… (Shift+Enter 줄바꿈, 이미지는 붙여넣기 가능)" autocomplete="off"></textarea>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -496,5 +470,5 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261014a" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261014a" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
|
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{# 휴지통 — 관리자 전용. 지운 업무(하위 업무·댓글·팔로워·첨부 포함)를 3개월
|
{# 휴지통 — Pro user 이상. 지운 업무(세부 업무·댓글·팔로워·첨부 포함)를 3개월
|
||||||
보관하고, [복구] 로 원래 id 그대로 되살린다(project_db 010). #}
|
보관하고, [복구] 로 원래 id 그대로 되살린다(project_db 010). #}
|
||||||
<div class="pj-wrap pj-inbox-view pj-trash-view">
|
<div class="pj-wrap pj-inbox-view pj-trash-view">
|
||||||
<div class="pj-layout">
|
<div class="pj-layout">
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
<section class="pj-main">
|
<section class="pj-main">
|
||||||
<div class="pj-section-head">
|
<div class="pj-section-head">
|
||||||
<h2>휴지통</h2>
|
<h2>휴지통</h2>
|
||||||
<span class="pj-trash-note">삭제한 작업은 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 관리자만 할 수 있습니다.</span>
|
<span class="pj-trash-note">삭제한 업무는 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 Pro user 이상만 할 수 있습니다.</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-view pj-inbox-pane">
|
<div class="pj-view pj-inbox-pane">
|
||||||
{% if not trash_enabled %}
|
{% if not trash_enabled %}
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
<table class="pj-table pj-trash-table" id="pj-trash-table">
|
<table class="pj-table pj-trash-table" id="pj-trash-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>작업</th>
|
<th>업무</th>
|
||||||
<th>프로젝트</th>
|
<th>프로젝트</th>
|
||||||
<th>포함</th>
|
<th>포함</th>
|
||||||
<th>삭제한 사람</th>
|
<th>삭제한 사람</th>
|
||||||
@@ -45,7 +45,7 @@
|
|||||||
<td class="pj-trash-title">{{ it.title }}</td>
|
<td class="pj-trash-title">{{ it.title }}</td>
|
||||||
<td>{{ it.project_name or '-' }}</td>
|
<td>{{ it.project_name or '-' }}</td>
|
||||||
<td class="pj-trash-meta">
|
<td class="pj-trash-meta">
|
||||||
{% if it.task_count > 1 %}하위 작업 {{ it.task_count - 1 }}{% endif %}
|
{% if it.task_count > 1 %}세부 업무 {{ it.task_count - 1 }}{% endif %}
|
||||||
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
|
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
|
||||||
{% if it.attachment_count %} · 첨부 파일 {{ it.attachment_count }}{% endif %}
|
{% if it.attachment_count %} · 첨부 파일 {{ it.attachment_count }}{% endif %}
|
||||||
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
|
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
|
||||||
@@ -70,5 +70,5 @@
|
|||||||
{% include "project/_side_modals.html" %}
|
{% include "project/_side_modals.html" %}
|
||||||
{% include "project/_member_tasks_modal.html" %}
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261014a" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+1295
File diff suppressed because it is too large
Load Diff
@@ -59,29 +59,86 @@
|
|||||||
|
|
||||||
var state = { option: null, variants: [], displayTypes: {}, orphans: [], imageBase: "" };
|
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 () {
|
openBtn.addEventListener("click", function () {
|
||||||
var nameEl = document.getElementById("cf24-name-text");
|
var nameEl = document.getElementById("cf24-name-text");
|
||||||
modal.open((nameEl ? nameEl.textContent : "") + " (상품번호 " + no + ")");
|
modal.open((nameEl ? nameEl.textContent : "") + " (상품번호 " + no + ")");
|
||||||
|
myGen = modal.gen;
|
||||||
load();
|
load();
|
||||||
});
|
});
|
||||||
|
|
||||||
function load() {
|
function load() {
|
||||||
|
var seq = ++loadSeq;
|
||||||
|
var gen = myGen;
|
||||||
body.innerHTML = '<p class="cf24-muted">카페24에서 불러오는 중…</p>';
|
body.innerHTML = '<p class="cf24-muted">카페24에서 불러오는 중…</p>';
|
||||||
return apiJson("GET", "/cafe24/products/" + no + "/options")
|
return apiJson("GET", "/cafe24/products/" + no + "/options")
|
||||||
.then(function (data) {
|
.then(function (data) {
|
||||||
|
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||||
state.option = data.option;
|
state.option = data.option;
|
||||||
state.variants = data.variants || [];
|
state.variants = data.variants || [];
|
||||||
state.displayTypes = data.display_types || {};
|
state.displayTypes = data.display_types || {};
|
||||||
state.imageBase = data.image_base || "";
|
state.imageBase = data.image_base || "";
|
||||||
render();
|
render();
|
||||||
|
return true;
|
||||||
})
|
})
|
||||||
.catch(function (err) {
|
.catch(function (err) {
|
||||||
|
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||||
body.innerHTML = '<p class="cf24-err">옵션을 불러오지 못했습니다: ' + esc(err.message) +
|
body.innerHTML = '<p class="cf24-err">옵션을 불러오지 못했습니다: ' + esc(err.message) +
|
||||||
'</p><button type="button" class="erp-btn erp-btn-outline" id="cf24-opt-retry">다시 시도</button>';
|
'</p><button type="button" class="erp-btn erp-btn-outline" id="cf24-opt-retry">다시 시도</button>';
|
||||||
body.querySelector("#cf24-opt-retry").addEventListener("click", load);
|
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) {
|
function typeSelect(current, name) {
|
||||||
var out = '<select name="' + name + '">';
|
var out = '<select name="' + name + '">';
|
||||||
@@ -236,25 +293,34 @@
|
|||||||
통합 목록 — 옵션값 1 : 품목 1
|
통합 목록 — 옵션값 1 : 품목 1
|
||||||
═══════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════ */
|
||||||
// 행 = 품목 목록 순서. index 는 options 응답 안 위치(옵션 PUT 짝맞춤용).
|
// 행 = 품목 목록 순서. index 는 options 응답 안 위치(옵션 PUT 짝맞춤용).
|
||||||
// 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
// 품목과 옵션값은 **옵션값 번호(value_no)** 로 먼저 짝짓고, 없을 때만 이름으로 짝짓는다.
|
||||||
|
// (옵션값 이름을 바꾼 직후 카페24 품목 조회가 예전 이름을 돌려줘도 정상 품목이 숨지 않게.
|
||||||
|
// 서버가 품목코드별 쓰기 기록으로 표기를 바로잡고 value_no 를 붙여 준다.)
|
||||||
|
// 방금 추가해 품목이 아직 안 보이는 옵션값(pending)은 "품목 생성 대기" 행으로 그린다.
|
||||||
|
// 그 밖에 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
||||||
function unifiedRows() {
|
function unifiedRows() {
|
||||||
var opt = state.option;
|
var opt = state.option;
|
||||||
state.orphans = [];
|
state.orphans = [];
|
||||||
if (!opt || !opt.has_option) return [];
|
if (!opt || !opt.has_option) return [];
|
||||||
var group = opt.options[0];
|
var group = opt.options[0];
|
||||||
var byText = {};
|
var entries = group.option_value.map(function (v, vi) { return { index: vi, value: v, variant: null }; });
|
||||||
group.option_value.forEach(function (v, vi) { byText[v.option_text] = { 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 = [];
|
var rows = [];
|
||||||
state.variants.forEach(function (variant) {
|
state.variants.forEach(function (variant) {
|
||||||
if (!variant.options.length) return;
|
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;
|
if (!r || r.variant) return;
|
||||||
r.variant = variant;
|
r.variant = variant;
|
||||||
rows.push(r);
|
rows.push(r);
|
||||||
});
|
});
|
||||||
group.option_value.forEach(function (v) {
|
entries.forEach(function (r) {
|
||||||
var r = byText[v.option_text];
|
if (r.variant) return;
|
||||||
if (rows.indexOf(r) < 0) state.orphans.push(r);
|
if (r.value.pending) { r.await = true; rows.push(r); }
|
||||||
|
else state.orphans.push(r);
|
||||||
});
|
});
|
||||||
return rows;
|
return rows;
|
||||||
}
|
}
|
||||||
@@ -266,8 +332,10 @@
|
|||||||
var thumbSrc = [v.option_image_file, v.option_link_image,
|
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) : ""];
|
state.option && state.option.has_option ? variantImageFor(state.option.options[0].option_name, v.option_text) : ""];
|
||||||
var code = variant ? variant.variant_code : "";
|
var code = variant ? variant.variant_code : "";
|
||||||
|
var awaiting = !!r.await && !code;
|
||||||
// data-index: options 응답 안 위치(옵션 PUT 짝맞춤용, 새 행은 빈 값) / data-pos: 처음 그린 순서(순서 변경 판정용)
|
// 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-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>" +
|
'<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 || "") + '" />' +
|
'<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-u-name"><input type="text" name="option_text" value="' + esc(v.option_text) + '" placeholder="옵션값 이름" /></td>' +
|
||||||
'<td class="cf24-v-syscode">' + (code
|
'<td class="cf24-v-syscode">' + (code
|
||||||
? '<button type="button" class="cf24-v-copy" data-copy-text="' + esc(code) + '" title="클릭하면 품목코드를 복사합니다">' + esc(code) + "</button>"
|
? '<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-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-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("display", variant ? !!variant.display : true) + "</td>" +
|
||||||
'<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : 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>";
|
"</tr>";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+36
-6
@@ -534,6 +534,7 @@
|
|||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
.cpg-prod-manual-row .erp-field { flex: 1 1 160px; min-width: 0; }
|
.cpg-prod-manual-row .erp-field { flex: 1 1 160px; min-width: 0; }
|
||||||
|
.cpg-prod-manual-row .cpg-weight-field { flex: 0 1 120px; }
|
||||||
.cpg-prod-manual-row .erp-input { min-width: 0; width: 100%; }
|
.cpg-prod-manual-row .erp-input { min-width: 0; width: 100%; }
|
||||||
|
|
||||||
/* 상자 그림 안 박스 호수 라벨 (예: 2호) */
|
/* 상자 그림 안 박스 호수 라벨 (예: 2호) */
|
||||||
@@ -1009,16 +1010,21 @@ body.cpg-dragging { cursor: grabbing; user-select: none; }
|
|||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
}
|
}
|
||||||
/* 열 폭: 제품명 160 / 제품코드 96 / 상태 72 / 동작 104 고정,
|
/* 열 폭: 제품명 160 / 제품코드 96 / (포장무게 84) / 상태 72 / 동작 104 고정,
|
||||||
쿠팡상품코드는 남는 폭을 흡수 → 다른 열이 지정 폭 그대로 유지된다. */
|
쿠팡상품코드는 남는 폭을 흡수 → 다른 열이 지정 폭 그대로 유지된다.
|
||||||
|
상태·동작은 끝에서부터 센다(포장무게 열이 있든 없든 — 마이그레이션 007 전이면 없음). */
|
||||||
.cpg-prod-right .erp-table th:nth-child(1),
|
.cpg-prod-right .erp-table th:nth-child(1),
|
||||||
.cpg-prod-right .erp-table td:nth-child(1) { width: 160px; }
|
.cpg-prod-right .erp-table td:nth-child(1) { width: 160px; }
|
||||||
.cpg-prod-right .erp-table th:nth-child(2),
|
.cpg-prod-right .erp-table th:nth-child(2),
|
||||||
.cpg-prod-right .erp-table td:nth-child(2) { width: 96px; }
|
.cpg-prod-right .erp-table td:nth-child(2) { width: 96px; }
|
||||||
.cpg-prod-right .erp-table th:nth-child(4),
|
.cpg-prod-right .erp-table th.cpg-weight-col,
|
||||||
.cpg-prod-right .erp-table td:nth-child(4) { width: 72px; }
|
.cpg-prod-right .erp-table td.cpg-weight-col { width: 84px; text-align: right; font-variant-numeric: tabular-nums; }
|
||||||
.cpg-prod-right .erp-table th:nth-child(5),
|
.cpg-prod-right .erp-table th.cpg-weight-col .cpg-sort { margin-left: auto; }
|
||||||
.cpg-prod-right .erp-table td:nth-child(5) { width: 104px; }
|
.cpg-weight-unit { margin-left: 2px; font-size: 11px; color: var(--erp-muted, #8a8f98); }
|
||||||
|
.cpg-prod-right .erp-table th:nth-last-child(2),
|
||||||
|
.cpg-prod-right .erp-table td:nth-last-child(2) { width: 72px; }
|
||||||
|
.cpg-prod-right .erp-table th:nth-last-child(1),
|
||||||
|
.cpg-prod-right .erp-table td:nth-last-child(1) { width: 104px; }
|
||||||
/* 제품코드·쿠팡상품코드는 mono 라 조금 더 좁게 */
|
/* 제품코드·쿠팡상품코드는 mono 라 조금 더 좁게 */
|
||||||
.cpg-prod-right .erp-table td:nth-child(2),
|
.cpg-prod-right .erp-table td:nth-child(2),
|
||||||
.cpg-prod-right .erp-table td:nth-child(3) { font-size: 12px; }
|
.cpg-prod-right .erp-table td:nth-child(3) { font-size: 12px; }
|
||||||
@@ -1319,12 +1325,17 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
|||||||
}
|
}
|
||||||
.cpg-boxno-count.is-on { color: #217346; font-weight: 700; }
|
.cpg-boxno-count.is-on { color: #217346; font-weight: 700; }
|
||||||
.cpg-boxno-table { table-layout: fixed; width: 100%; }
|
.cpg-boxno-table { table-layout: fixed; width: 100%; }
|
||||||
|
/* 출고 상세 상자 목록 — 위 요약 카드와 20px 띄움 */
|
||||||
|
.cpg-calc-sum .cpg-boxno-scroll { margin-top: 20px; }
|
||||||
|
/* 표 오른쪽 끝 = 요약 카드 오른쪽 끝 — 스크롤바 칸(10px)+여백(2px)을 카드 안쪽 여백(16px)으로 내보낸다 */
|
||||||
|
.cpg-calc-sum .cpg-boxno-scroll { margin-right: -12px; }
|
||||||
.cpg-boxno-table th, .cpg-boxno-table td {
|
.cpg-boxno-table th, .cpg-boxno-table td {
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
padding: 4px 8px;
|
padding: 4px 8px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||||
border-bottom: 1px solid var(--color-cloud-gray);
|
border-bottom: 1px solid var(--color-cloud-gray);
|
||||||
|
text-align: center; /* 표 안 모든 칸 가운데 정렬 */
|
||||||
}
|
}
|
||||||
.cpg-boxno-table thead th {
|
.cpg-boxno-table thead th {
|
||||||
position: sticky; top: 0; z-index: 2;
|
position: sticky; top: 0; z-index: 2;
|
||||||
@@ -1339,6 +1350,16 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
|||||||
.cpg-boxno-c-name { width: auto; }
|
.cpg-boxno-c-name { width: auto; }
|
||||||
.cpg-boxno-c-code { width: 100px; }
|
.cpg-boxno-c-code { width: 100px; }
|
||||||
.cpg-boxno-c-qty { width: 62px; }
|
.cpg-boxno-c-qty { width: 62px; }
|
||||||
|
.cpg-boxno-c-weight { width: 92px; }
|
||||||
|
/* 상자 무게 합계(g) — 상자 단위 한 칸(rowspan), 오른쪽 정렬 숫자. 무게 없는 제품이 있으면 작은 표시 */
|
||||||
|
.cpg-boxno-weight {
|
||||||
|
text-align: center; vertical-align: middle; font-variant-numeric: tabular-nums; font-weight: 600;
|
||||||
|
border-left: 1px solid var(--color-cloud-gray);
|
||||||
|
}
|
||||||
|
.cpg-boxno-weight .cpg-weight-unit { font-weight: 400; }
|
||||||
|
.cpg-boxno-wmiss {
|
||||||
|
display: block; margin-top: 1px; font-size: 10.5px; font-weight: 600; color: #b45309; white-space: nowrap;
|
||||||
|
}
|
||||||
.cpg-boxno-cell {
|
.cpg-boxno-cell {
|
||||||
text-align: center; font-weight: 700;
|
text-align: center; font-weight: 700;
|
||||||
font-family: var(--font-geist-mono);
|
font-family: var(--font-geist-mono);
|
||||||
@@ -1346,6 +1367,14 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
|||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
}
|
}
|
||||||
.cpg-boxno-code { color: var(--color-midtone-gray); font-family: var(--font-geist-mono); }
|
.cpg-boxno-code { color: var(--color-midtone-gray); font-family: var(--font-geist-mono); }
|
||||||
|
/* 합계 행 — 수량·무게(kg) 합계. 클릭 체크 대상 아님 */
|
||||||
|
.cpg-boxno-table tfoot td {
|
||||||
|
background: var(--color-ghost-gray);
|
||||||
|
font-weight: 700;
|
||||||
|
border-top: 1px solid var(--color-subtle-ash);
|
||||||
|
border-bottom: 0;
|
||||||
|
}
|
||||||
|
.cpg-boxno-table tfoot .cpg-boxno-cell { font-family: inherit; }
|
||||||
.cpg-boxno-table tbody tr.is-boxtop td { border-top: 1px solid var(--color-cloud-gray); }
|
.cpg-boxno-table tbody tr.is-boxtop td { border-top: 1px solid var(--color-cloud-gray); }
|
||||||
.cpg-boxno-table tbody tr { cursor: pointer; }
|
.cpg-boxno-table tbody tr { cursor: pointer; }
|
||||||
.cpg-boxno-table tbody tr:hover td { background: var(--color-ghost-gray); }
|
.cpg-boxno-table tbody tr:hover td { background: var(--color-ghost-gray); }
|
||||||
@@ -1469,6 +1498,7 @@ a.cpg-boxno-dl:hover { background: #1a5c38; border-color: #1a5c38; font-weight:
|
|||||||
max-height: none;
|
max-height: none;
|
||||||
overflow: visible;
|
overflow: visible;
|
||||||
}
|
}
|
||||||
|
.cpg-calc-sum .cpg-boxno-scroll { margin-right: 0; padding-right: 0; } /* 스크롤 없음 — 스크롤바 칸도 없다 */
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── 넓은 화면(3열): ③ 카드 자체가 스크롤러 ──
|
/* ── 넓은 화면(3열): ③ 카드 자체가 스크롤러 ──
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
// 긴급 공지 관리(/notice/, 수퍼관리자) — 만들기·고치기·취소·미리 보기·확인 현황.
|
||||||
|
// 내용 편집기·날짜 팝업·받는 사람 고르기는 프로젝트 화면 부품 그대로(window.PJLib — project.js, PJ_LIB_ONLY):
|
||||||
|
// · 내용 = 작업 설명란과 같은 편집기(굵게·기울임·밑줄·취소선·글자 색/크기·목록·체크리스트·인용·링크·서식 지우기·이미지
|
||||||
|
// 붙여넣기/버튼·크기 조절), 이미지는 /notice/api/images 로 올린다.
|
||||||
|
// · 띄울 날짜 = 아사나식 날짜 팝업(공휴일·오늘·지우기), 시각은 옆 칸.
|
||||||
|
// · 받는 사람 = 프로젝트 멤버 고르기와 같은 아이콘 + 이름 + 체크.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
const root = document.getElementById("ntc-root");
|
||||||
|
if (!root || !window.PJLib) return;
|
||||||
|
const L = window.PJLib;
|
||||||
|
const $ = function (id) { return document.getElementById(id); };
|
||||||
|
const people = window.NTC_PEOPLE || [];
|
||||||
|
const byEmail = {};
|
||||||
|
people.forEach(function (p) { byEmail[String(p.email).toLowerCase()] = p; });
|
||||||
|
const nameOf = function (e) { const p = byEmail[String(e).toLowerCase()]; return p ? p.name : String(e).split("@")[0]; };
|
||||||
|
const esc = function (s) {
|
||||||
|
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
||||||
|
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const shortWhen = function (iso) {
|
||||||
|
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso || "");
|
||||||
|
return m ? m[1] + "-" + m[2] + "-" + m[3] + " " + m[4] + ":" + m[5] : "";
|
||||||
|
};
|
||||||
|
async function api(method, url, body, isForm) {
|
||||||
|
const opts = { method: method, credentials: "same-origin", headers: {} };
|
||||||
|
if (body !== undefined) {
|
||||||
|
if (isForm) opts.body = body;
|
||||||
|
else { opts.headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(body); }
|
||||||
|
}
|
||||||
|
const res = await fetch(url, opts);
|
||||||
|
let data = null;
|
||||||
|
try { data = await res.json(); } catch (_) {}
|
||||||
|
if (!res.ok) {
|
||||||
|
const d = data && data.detail;
|
||||||
|
throw new Error(typeof d === "string" ? d : "HTTP " + res.status);
|
||||||
|
}
|
||||||
|
return data || {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = $("ntc-title"), dateEl = $("ntc-date"), timeEl = $("ntc-time"), idEl = $("ntc-id");
|
||||||
|
const peopleBox = $("ntc-people"), msg = $("ntc-msg"), save = $("ntc-save");
|
||||||
|
const say = function (text, ok) { msg.textContent = text || ""; msg.hidden = !text; msg.classList.toggle("is-ok", !!ok); };
|
||||||
|
|
||||||
|
// ── 내용 — 작업 설명란 편집기 ──
|
||||||
|
const editor = L.createDescEditor({
|
||||||
|
box: $("ntc-body"), fmtbar: $("ntc-fmtbar"), imgInput: $("ntc-img-input"), hint: $("ntc-hint"), mentions: false,
|
||||||
|
uploadImage: async function (file) {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("file", file, file.name || "image");
|
||||||
|
return (await api("POST", "/notice/api/images", fd, true)).image.url;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// ── 날짜 — 프로젝트 날짜 팝업 ──
|
||||||
|
L.enhanceDateInput(dateEl, { placeholder: "날짜(비우면 바로)" });
|
||||||
|
// ── 받는 사람 — 프로젝트 멤버 고르기 모양 ──
|
||||||
|
peopleBox.innerHTML = people.map(L.memberPickHtml).join("") || '<span class="pj-empty-sm">등록된 사람이 없습니다.</span>';
|
||||||
|
function toAll() { return root.querySelector('input[name="ntc-to"]:checked').value === "all"; }
|
||||||
|
root.querySelectorAll('input[name="ntc-to"]').forEach(function (r) {
|
||||||
|
r.addEventListener("change", function () { peopleBox.hidden = toAll(); });
|
||||||
|
});
|
||||||
|
function picked() {
|
||||||
|
return Array.from(peopleBox.querySelectorAll("input[type=checkbox]:checked")).map(function (c) { return c.value; });
|
||||||
|
}
|
||||||
|
function setPicked(emails) {
|
||||||
|
const want = (emails || []).map(function (e) { return String(e).toLowerCase(); });
|
||||||
|
peopleBox.querySelectorAll("input[type=checkbox]").forEach(function (c) { c.checked = want.indexOf(c.value.toLowerCase()) >= 0; });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 저장(만들기·고치기) ──
|
||||||
|
function showAtValue() {
|
||||||
|
// 날짜를 비우면 바로(서버가 지금으로), 날짜만 있으면 그날 00:00, 시각까지 있으면 그 시각 — 모두 한국시간
|
||||||
|
return dateEl.value ? dateEl.value + "T" + (timeEl.value || "00:00") : "";
|
||||||
|
}
|
||||||
|
function payload() {
|
||||||
|
return {
|
||||||
|
title: title.value.trim(), body_html: editor.getHtml(), show_at: showAtValue(),
|
||||||
|
to_all: toAll(), targets: picked(), reshow: $("ntc-reshow").checked,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function resetForm() {
|
||||||
|
idEl.value = ""; title.value = ""; editor.setHtml(""); dateEl.value = ""; timeEl.value = "";
|
||||||
|
root.querySelector('input[name="ntc-to"][value="all"]').checked = true;
|
||||||
|
peopleBox.hidden = true;
|
||||||
|
setPicked([]);
|
||||||
|
$("ntc-reshow").checked = false; $("ntc-reshow-row").hidden = true;
|
||||||
|
$("ntc-form-title").textContent = "새 긴급 공지";
|
||||||
|
save.textContent = "공지 만들기";
|
||||||
|
}
|
||||||
|
$("ntc-reset").addEventListener("click", function () { resetForm(); say(""); });
|
||||||
|
let saving = false;
|
||||||
|
save.addEventListener("click", async function () {
|
||||||
|
if (saving) return;
|
||||||
|
saving = true; save.disabled = true;
|
||||||
|
try {
|
||||||
|
await editor.whenIdle(); // 이미지 올리는 중이면 끝난 뒤 저장(빠진 채 저장되지 않게)
|
||||||
|
const p = payload();
|
||||||
|
if (!p.title) { say("제목을 입력하세요."); title.focus(); return; }
|
||||||
|
if (!p.to_all && !p.targets.length) { say("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요."); return; }
|
||||||
|
const id = idEl.value;
|
||||||
|
if (id) await api("PUT", "/notice/api/notices/" + id, p);
|
||||||
|
else await api("POST", "/notice/api/notices", p);
|
||||||
|
resetForm();
|
||||||
|
say(id ? "공지를 고쳤습니다." : "공지를 만들었습니다. 띄울 시각이 되면 받는 사람 화면 가운데에 나타납니다.", true);
|
||||||
|
await loadList();
|
||||||
|
} catch (e) { say("저장하지 못했습니다: " + e.message); }
|
||||||
|
finally { saving = false; save.disabled = false; }
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── 미리 보기 — 받는 사람 화면과 같은 모양 ──
|
||||||
|
$("ntc-preview").addEventListener("click", function () { preview(title.value.trim() || "(제목 없음)", editor.getHtml()); });
|
||||||
|
function preview(t, html) {
|
||||||
|
const box = document.createElement("div");
|
||||||
|
box.className = "erp-notice-backdrop";
|
||||||
|
box.innerHTML = '<div class="erp-notice-card" role="dialog" aria-modal="true">' +
|
||||||
|
'<div class="erp-notice-head"><span class="erp-notice-badge">긴급 공지 · 미리 보기</span></div>' +
|
||||||
|
'<h2 class="erp-notice-title"></h2><div class="erp-notice-body"></div>' +
|
||||||
|
'<div class="erp-notice-foot"><span class="erp-notice-meta">받는 사람 화면에는 [확인]만 있습니다</span>' +
|
||||||
|
'<button type="button" class="erp-notice-ok">닫기</button></div></div>';
|
||||||
|
box.querySelector(".erp-notice-title").textContent = t;
|
||||||
|
box.querySelector(".erp-notice-body").innerHTML = html; // 저장하면 서버가 다시 정리한다
|
||||||
|
document.body.appendChild(box);
|
||||||
|
const ok = box.querySelector(".erp-notice-ok");
|
||||||
|
ok.addEventListener("click", function () { box.remove(); });
|
||||||
|
box.addEventListener("keydown", function (e) { if (e.key === "Escape") box.remove(); });
|
||||||
|
ok.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 목록 ──
|
||||||
|
let list = [];
|
||||||
|
function stateOf(n) {
|
||||||
|
if (n.cancelled_at) return ["is-cancelled", "취소됨"];
|
||||||
|
if (new Date(n.show_at) > new Date()) return ["is-scheduled", "예약 " + shortWhen(n.show_at)];
|
||||||
|
return ["is-live", "표시 중"];
|
||||||
|
}
|
||||||
|
function render() {
|
||||||
|
const box = $("ntc-list");
|
||||||
|
if (!list.length) { box.textContent = "아직 공지가 없습니다."; return; }
|
||||||
|
box.innerHTML = list.map(function (n) {
|
||||||
|
const st = stateOf(n);
|
||||||
|
const acked = Object.keys(n.acks || {});
|
||||||
|
const who = n.to_all ? "전체" : n.targets.map(nameOf).join(", ");
|
||||||
|
const ackLine = n.to_all ? "확인 " + acked.length + "명"
|
||||||
|
: "확인 " + n.targets.filter(function (e) { return n.acks[e]; }).length + " / " + n.targets.length + "명";
|
||||||
|
const rows = (n.to_all ? acked : n.targets).map(function (e) {
|
||||||
|
return n.acks[e] ? "<li>" + esc(nameOf(e)) + " — " + esc(shortWhen(n.acks[e])) + "</li>"
|
||||||
|
: '<li class="is-no">' + esc(nameOf(e)) + " — 아직 확인 안 함</li>";
|
||||||
|
}).join("");
|
||||||
|
return '<div class="ntc-item" data-id="' + n.id + '">' +
|
||||||
|
'<div class="ntc-item-head"><span class="ntc-state ' + st[0] + '">' + esc(st[1]) + "</span>" +
|
||||||
|
'<span class="ntc-item-title">' + esc(n.title) + "</span>" +
|
||||||
|
'<span class="ntc-item-acts">' +
|
||||||
|
'<button type="button" class="pj-btn pj-btn-sm" data-act="preview">미리 보기</button>' +
|
||||||
|
'<button type="button" class="pj-btn pj-btn-sm" data-act="edit">고치기</button>' +
|
||||||
|
'<button type="button" class="pj-btn pj-btn-sm" data-act="cancel">' + (n.cancelled_at ? "취소 되돌리기" : "취소") + "</button>" +
|
||||||
|
"</span></div>" +
|
||||||
|
'<div class="ntc-item-meta">띄울 시각 ' + esc(shortWhen(n.show_at)) + " · 받는 사람 " + esc(who) +
|
||||||
|
" · 만든 사람 " + esc(nameOf(n.created_by)) + "</div>" +
|
||||||
|
'<details class="ntc-acks"><summary>' + esc(ackLine) + "</summary><ul>" + (rows || "<li>아직 없습니다</li>") + "</ul></details>" +
|
||||||
|
"</div>";
|
||||||
|
}).join("");
|
||||||
|
}
|
||||||
|
async function loadList() {
|
||||||
|
try { list = (await api("GET", "/notice/api/notices")).notices || []; render(); }
|
||||||
|
catch (e) { $("ntc-list").textContent = "목록을 읽지 못했습니다: " + e.message; }
|
||||||
|
}
|
||||||
|
$("ntc-list").addEventListener("click", async function (e) {
|
||||||
|
const b = e.target.closest("[data-act]");
|
||||||
|
if (!b) return;
|
||||||
|
const n = list.find(function (x) { return String(x.id) === b.closest(".ntc-item").dataset.id; });
|
||||||
|
if (!n) return;
|
||||||
|
if (b.dataset.act === "preview") { preview(n.title, n.body_html); return; }
|
||||||
|
if (b.dataset.act === "edit") {
|
||||||
|
idEl.value = n.id; title.value = n.title; editor.setHtml(n.body_html);
|
||||||
|
dateEl.value = (n.show_at || "").slice(0, 10); timeEl.value = (n.show_at || "").slice(11, 16);
|
||||||
|
root.querySelector('input[name="ntc-to"][value="' + (n.to_all ? "all" : "some") + '"]').checked = true;
|
||||||
|
peopleBox.hidden = n.to_all;
|
||||||
|
setPicked(n.targets);
|
||||||
|
$("ntc-reshow-row").hidden = false; $("ntc-reshow").checked = false;
|
||||||
|
$("ntc-form-title").textContent = "공지 고치기";
|
||||||
|
save.textContent = "고친 내용 저장";
|
||||||
|
say("");
|
||||||
|
title.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (b.dataset.act === "cancel") {
|
||||||
|
const cancel = !n.cancelled_at;
|
||||||
|
if (cancel) {
|
||||||
|
const q = "'" + n.title + "' 공지를 취소할까요? 아직 확인하지 않은 사람에게도 더 뜨지 않습니다.";
|
||||||
|
const yes = window.erpConfirm ? await window.erpConfirm(q, { okText: "공지 취소", cancelText: "닫기" }) : window.confirm(q);
|
||||||
|
if (!yes) return;
|
||||||
|
}
|
||||||
|
b.disabled = true;
|
||||||
|
try { await api("POST", "/notice/api/notices/" + n.id + "/cancel", { cancel: cancel }); await loadList(); }
|
||||||
|
catch (err) { say("처리하지 못했습니다: " + err.message); b.disabled = false; }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
loadList();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
/* 긴급 공지 — 화면 가로·세로 정가운데(erp-notice.js). 화면 배율(.erp-app zoom) 밖 body 에 붙는다. */
|
||||||
|
.erp-notice-backdrop {
|
||||||
|
position: fixed; inset: 0; z-index: 6000;
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
padding: 16px; box-sizing: border-box;
|
||||||
|
background: rgba(15, 17, 21, .5);
|
||||||
|
}
|
||||||
|
.erp-notice-backdrop[hidden] { display: none; }
|
||||||
|
.erp-notice-card {
|
||||||
|
width: min(640px, 100%); max-height: min(86vh, 900px); box-sizing: border-box;
|
||||||
|
display: flex; flex-direction: column; gap: 10px;
|
||||||
|
padding: 22px 24px 18px; border-radius: 14px; background: #fff; color: #1e1f21;
|
||||||
|
box-shadow: 0 18px 50px rgba(0, 0, 0, .35); border-top: 6px solid #e5484d;
|
||||||
|
animation: erp-notice-in .18s ease-out;
|
||||||
|
}
|
||||||
|
@keyframes erp-notice-in { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }
|
||||||
|
.erp-notice-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||||
|
.erp-notice-badge {
|
||||||
|
display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 999px;
|
||||||
|
background: #fde8e8; color: #c62a2f; font-size: 12.5px; font-weight: 800;
|
||||||
|
}
|
||||||
|
.erp-notice-count { font-size: 12.5px; font-weight: 700; color: #6b7079; }
|
||||||
|
.erp-notice-title { margin: 0; font-size: 20px; font-weight: 800; line-height: 1.35; word-break: keep-all; overflow-wrap: anywhere; }
|
||||||
|
.erp-notice-body {
|
||||||
|
flex: 1 1 auto; min-height: 0; overflow: auto; font-size: 14.5px; line-height: 1.65; color: #2b2f36;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.erp-notice-body p { margin: 0 0 .6em; }
|
||||||
|
.erp-notice-body img { display: block; max-width: 100%; height: auto; margin: 8px 0; border-radius: 8px; }
|
||||||
|
.erp-notice-body a { color: #3b6fd8; text-decoration: underline; }
|
||||||
|
/* 작업 설명란 편집기와 같은 서식(project.css .pj-desc-editor) — 프로젝트 밖 화면에서도 같게 보이게 */
|
||||||
|
.erp-notice-body blockquote { margin: 6px 0; padding: 2px 12px; border-left: 3px solid #d5d9de; color: #565c66; }
|
||||||
|
.erp-notice-body ul, .erp-notice-body ol { margin: 4px 0; padding-left: 22px; }
|
||||||
|
.erp-notice-body ul.pj-checklist { list-style: none; padding-left: 24px; }
|
||||||
|
.erp-notice-body ul.pj-checklist > li { position: relative; }
|
||||||
|
.erp-notice-body ul.pj-checklist > li::before {
|
||||||
|
content: ""; position: absolute; left: -22px; top: .3em; width: 14px; height: 14px;
|
||||||
|
box-sizing: border-box; border: 1.5px solid #8f959d; border-radius: 3px; background: #fff;
|
||||||
|
}
|
||||||
|
.erp-notice-body ul.pj-checklist > li[data-checked="true"]::before {
|
||||||
|
border-color: #7b68ee; background: #7b68ee center / 10px 10px no-repeat
|
||||||
|
url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2 6.3l2.6 2.6L10 3.4' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
|
||||||
|
}
|
||||||
|
.erp-notice-body ul.pj-checklist > li[data-checked="true"] { color: #9aa1a9; text-decoration: line-through; }
|
||||||
|
.erp-notice-body img[width] { height: auto; }
|
||||||
|
.erp-notice-error { margin: 0; padding: 6px 10px; border-radius: 6px; background: #fdecec; color: #b42318; font-size: 13px; }
|
||||||
|
.erp-notice-error[hidden] { display: none; }
|
||||||
|
.erp-notice-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 6px; border-top: 1px solid #eceef1; }
|
||||||
|
.erp-notice-meta { font-size: 12.5px; color: #6b7079; }
|
||||||
|
.erp-notice-ok {
|
||||||
|
min-width: 96px; padding: 9px 20px; border: none; border-radius: 8px; cursor: pointer;
|
||||||
|
background: #e5484d; color: #fff; font-size: 14.5px; font-weight: 800;
|
||||||
|
}
|
||||||
|
.erp-notice-ok:hover { background: #d23c41; }
|
||||||
|
.erp-notice-ok:focus-visible { outline: 3px solid rgba(229, 72, 77, .35); outline-offset: 2px; }
|
||||||
|
.erp-notice-ok:disabled { opacity: .6; cursor: default; }
|
||||||
|
|
||||||
|
/* 관리 화면(/notice/) */
|
||||||
|
.ntc-wrap { display: grid; grid-template-columns: minmax(420px, 640px) 1fr; gap: 18px; align-items: start; }
|
||||||
|
@media (max-width: 1100px) { .ntc-wrap { grid-template-columns: 1fr; } }
|
||||||
|
.ntc-card { background: #fff; border: 1px solid #e6e8eb; border-radius: 12px; padding: 18px; }
|
||||||
|
.ntc-card h2 { margin: 0 0 12px; font-size: 16px; }
|
||||||
|
.ntc-field { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; font-size: 13px; font-weight: 700; color: #3b4048; }
|
||||||
|
.ntc-field input[type=text], .ntc-time {
|
||||||
|
font: inherit; font-weight: 500; padding: 8px 10px; border: 1px solid #d5d9de; border-radius: 8px;
|
||||||
|
}
|
||||||
|
.ntc-sub { font-weight: 500; color: #8a9099; }
|
||||||
|
.ntc-desc .pj-desc-toolbar { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.ntc-desc .pj-desc-wrap { position: relative; }
|
||||||
|
.ntc-desc .pj-desc-editor { min-height: 180px; max-height: 460px; overflow: auto; font-weight: 400;
|
||||||
|
padding: 10px 12px; border: 1px solid #d5d9de; border-radius: 8px; }
|
||||||
|
.ntc-desc .pj-desc-editor:focus { border-color: #7b68ee; box-shadow: 0 0 0 3px rgba(123, 104, 238, .15); outline: none; }
|
||||||
|
.ntc-when { display: flex; align-items: center; gap: 8px; font-weight: 500; }
|
||||||
|
.ntc-time { padding: 6px 8px; }
|
||||||
|
.ntc-targets { display: flex; flex-direction: column; gap: 8px; font-weight: 500; }
|
||||||
|
.ntc-to { display: flex; gap: 16px; flex-wrap: wrap; }
|
||||||
|
.ntc-people { max-height: 260px; }
|
||||||
|
.ntc-people[hidden] { display: none; }
|
||||||
|
.ntc-inline { flex-direction: row; align-items: center; font-weight: 500; }
|
||||||
|
.ntc-actions { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
|
||||||
|
.ntc-msg { margin: 8px 0 0; font-size: 13px; color: #b42318; }
|
||||||
|
.ntc-msg[hidden] { display: none; }
|
||||||
|
.ntc-msg.is-ok { color: #1f7a3a; }
|
||||||
|
.ntc-list { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.ntc-item { border: 1px solid #e6e8eb; border-radius: 10px; padding: 12px 14px; }
|
||||||
|
.ntc-item-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.ntc-item-title { font-weight: 800; font-size: 14.5px; }
|
||||||
|
.ntc-state { padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 800; }
|
||||||
|
.ntc-state.is-live { background: #fde8e8; color: #c62a2f; }
|
||||||
|
.ntc-state.is-scheduled { background: #e8efff; color: #3456b8; }
|
||||||
|
.ntc-state.is-cancelled { background: #eef0f2; color: #6b7079; }
|
||||||
|
.ntc-item-meta { margin-top: 4px; font-size: 12.5px; color: #6b7079; }
|
||||||
|
.ntc-item-acts { margin-left: auto; display: flex; gap: 6px; }
|
||||||
|
.ntc-acks { margin-top: 8px; font-size: 12.5px; color: #3b4048; }
|
||||||
|
.ntc-acks summary { cursor: pointer; font-weight: 700; }
|
||||||
|
.ntc-acks ul { margin: 6px 0 0; padding-left: 18px; }
|
||||||
|
.ntc-acks .is-no { color: #b42318; }
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
// 긴급 공지 — ERP 모든 화면(erp_base.html) 가운데에 띄운다(2026-10-12).
|
||||||
|
// · GET /notice/api/pending — 띄울 시각이 지났고 아직 [확인] 안 한 내 공지(오래된 것부터). 30초마다·창을 다시 볼 때.
|
||||||
|
// · [확인]을 누를 때까지 닫히지 않는다(Esc·바깥 클릭으로 안 닫힘). 여러 건이면 차례대로(1/3).
|
||||||
|
// · [확인] = POST /notice/api/{id}/ack — 실패하면 창을 그대로 두고 알린다. 다른 탭에서 확인하면 이 탭도 다음 확인 때 닫힌다.
|
||||||
|
// · 본문 HTML 은 서버가 정리한 것(이미지는 /notice/images/{id} 만). 수신함 오른쪽 작업 창(iframe) 안에서는 돌지 않는다.
|
||||||
|
// · 024 미적용(503)·로그아웃(401)이면 조용히 멈춘다.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
if (window.top !== window) return; // iframe(수신함 작업 창 등) 안에서는 바깥 화면이 띄운다
|
||||||
|
const POLL_MS = 30000;
|
||||||
|
let queue = [], shown = null, box = null, timer = 0, busy = false, stopped = false;
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
||||||
|
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function when(iso) {
|
||||||
|
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso || "");
|
||||||
|
return m ? m[2] + "/" + m[3] + " " + m[4] + ":" + m[5] : "";
|
||||||
|
}
|
||||||
|
function who(email) {
|
||||||
|
const id = String(email || "").split("@")[0];
|
||||||
|
return id ? id.charAt(0).toUpperCase() + id.slice(1) : "";
|
||||||
|
}
|
||||||
|
function schedule() { clearTimeout(timer); if (!stopped) timer = setTimeout(poll, POLL_MS); }
|
||||||
|
|
||||||
|
async function poll() {
|
||||||
|
if (busy || stopped) return;
|
||||||
|
if (document.hidden) { schedule(); return; }
|
||||||
|
busy = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch("/notice/api/pending", { headers: { Accept: "application/json" }, credentials: "same-origin" });
|
||||||
|
if (res.status === 401 || res.status === 403 || res.status === 503 || res.status === 404) { stopped = true; return; }
|
||||||
|
if (!res.ok) return;
|
||||||
|
const data = await res.json();
|
||||||
|
queue = Array.isArray(data.notices) ? data.notices : [];
|
||||||
|
// 다른 탭·다른 곳에서 확인했거나 취소된 공지는 닫는다
|
||||||
|
if (shown && !queue.some(function (n) { return n.id === shown.id; })) close();
|
||||||
|
if (!shown && queue.length) open(queue[0]);
|
||||||
|
else if (shown) paintCount();
|
||||||
|
} catch (_) {
|
||||||
|
// 네트워크 오류는 다음 주기에 다시
|
||||||
|
} finally {
|
||||||
|
busy = false;
|
||||||
|
schedule();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function paintCount() {
|
||||||
|
if (!box || !shown) return;
|
||||||
|
const i = queue.findIndex(function (n) { return n.id === shown.id; });
|
||||||
|
const c = box.querySelector(".erp-notice-count");
|
||||||
|
c.textContent = queue.length > 1 ? (i + 1) + " / " + queue.length : "";
|
||||||
|
c.hidden = queue.length <= 1;
|
||||||
|
}
|
||||||
|
function open(n) {
|
||||||
|
shown = n;
|
||||||
|
if (!box) {
|
||||||
|
box = document.createElement("div");
|
||||||
|
box.className = "erp-notice-backdrop";
|
||||||
|
box.innerHTML =
|
||||||
|
'<div class="erp-notice-card" role="alertdialog" aria-modal="true" aria-labelledby="erp-notice-title">' +
|
||||||
|
'<div class="erp-notice-head"><span class="erp-notice-badge">긴급 공지</span><span class="erp-notice-count" hidden></span></div>' +
|
||||||
|
'<h2 class="erp-notice-title" id="erp-notice-title"></h2>' +
|
||||||
|
'<div class="erp-notice-body"></div>' +
|
||||||
|
'<p class="erp-notice-error" role="alert" hidden></p>' +
|
||||||
|
'<div class="erp-notice-foot"><span class="erp-notice-meta"></span>' +
|
||||||
|
'<button type="button" class="erp-notice-ok">확인</button></div></div>';
|
||||||
|
document.body.appendChild(box); // 화면 배율(.erp-app zoom) 밖 — 늘 화면 정가운데
|
||||||
|
box.querySelector(".erp-notice-ok").addEventListener("click", ack);
|
||||||
|
// [확인] 전에는 닫지 않는다 — Esc 는 막고, 포커스는 창 안에
|
||||||
|
box.addEventListener("keydown", function (e) {
|
||||||
|
if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); }
|
||||||
|
if (e.key === "Tab") { e.preventDefault(); box.querySelector(".erp-notice-ok").focus(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
box.querySelector(".erp-notice-title").textContent = n.title || "";
|
||||||
|
box.querySelector(".erp-notice-body").innerHTML = n.body_html || ""; // 서버가 정리한 HTML
|
||||||
|
box.querySelector(".erp-notice-meta").textContent =
|
||||||
|
[who(n.created_by), when(n.show_at)].filter(Boolean).join(" · ");
|
||||||
|
box.querySelector(".erp-notice-error").hidden = true;
|
||||||
|
box.querySelector(".erp-notice-body").scrollTop = 0;
|
||||||
|
box.hidden = false;
|
||||||
|
paintCount();
|
||||||
|
const ok = box.querySelector(".erp-notice-ok");
|
||||||
|
ok.disabled = false;
|
||||||
|
ok.focus();
|
||||||
|
}
|
||||||
|
function close() {
|
||||||
|
shown = null;
|
||||||
|
if (box) box.hidden = true;
|
||||||
|
}
|
||||||
|
async function ack() {
|
||||||
|
if (!shown) return;
|
||||||
|
const n = shown, ok = box.querySelector(".erp-notice-ok"), err = box.querySelector(".erp-notice-error");
|
||||||
|
ok.disabled = true;
|
||||||
|
err.hidden = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch("/notice/api/" + n.id + "/ack", { method: "POST", credentials: "same-origin" });
|
||||||
|
if (!res.ok && res.status !== 404) throw new Error("HTTP " + res.status); // 404 = 취소·삭제됨 — 닫는다
|
||||||
|
try { localStorage.setItem("erp_notice_ack", String(n.id) + ":" + Date.now()); } catch (_) {}
|
||||||
|
queue = queue.filter(function (x) { return x.id !== n.id; });
|
||||||
|
if (queue.length) open(queue[0]); else close();
|
||||||
|
} catch (e) {
|
||||||
|
err.textContent = "확인을 저장하지 못했습니다. 다시 눌러 주세요. (" + e.message + ")";
|
||||||
|
err.hidden = false;
|
||||||
|
ok.disabled = false;
|
||||||
|
ok.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("storage", function (e) { if (e.key === "erp_notice_ack") poll(); });
|
||||||
|
document.addEventListener("visibilitychange", function () { if (!document.hidden) poll(); });
|
||||||
|
if (window.__ERP_NOTICE_TEST__) window.__erpNotice = { poll: poll, state: function () { return { queue: queue, shown: shown, stopped: stopped }; } };
|
||||||
|
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", poll);
|
||||||
|
else poll();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/* 마감 지난 내 업무 알림 — ERP 모든 화면 위쪽 가운데(erp-overdue.js). body 에 붙어 화면 배율(.erp-app zoom) 밖. 긴급 공지(6000)보다 아래. */
|
||||||
|
.erp-overdue {
|
||||||
|
position: fixed; top: 12px; left: 50%; transform: translateX(-50%); z-index: 5500;
|
||||||
|
width: min(560px, calc(100vw - 32px)); box-sizing: border-box;
|
||||||
|
padding: 12px 14px 10px; border-radius: 12px; background: #fff; color: #1e1f21;
|
||||||
|
border: 1px solid #f3c5c6; border-top: 4px solid #e5484d;
|
||||||
|
box-shadow: 0 12px 36px rgba(16, 24, 40, .22);
|
||||||
|
font-size: 13.5px; animation: erp-overdue-in .22s ease-out;
|
||||||
|
}
|
||||||
|
.erp-overdue[hidden] { display: none; }
|
||||||
|
@keyframes erp-overdue-in { from { opacity: 0; transform: translate(-50%, -10px); } to { opacity: 1; transform: translate(-50%, 0); } }
|
||||||
|
.erp-overdue-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
|
||||||
|
.erp-overdue-head b { flex: 1 1 auto; font-size: 14.5px; color: #c62a2f; }
|
||||||
|
.erp-overdue-ic { font-size: 17px; }
|
||||||
|
.erp-overdue-close {
|
||||||
|
flex: none; border: 1px solid #d8dce2; background: #fff; color: #4b5059; border-radius: 8px;
|
||||||
|
padding: 4px 10px; font: inherit; font-size: 12px; cursor: pointer;
|
||||||
|
}
|
||||||
|
.erp-overdue-close:hover { background: #f3f4f6; }
|
||||||
|
.erp-overdue-list { display: flex; flex-direction: column; max-height: 50vh; overflow-y: auto; }
|
||||||
|
.erp-overdue-item {
|
||||||
|
display: flex; align-items: center; gap: 10px; padding: 7px 6px; border-radius: 8px;
|
||||||
|
color: inherit; text-decoration: none;
|
||||||
|
}
|
||||||
|
.erp-overdue-item:hover { background: #fdf2f2; }
|
||||||
|
.erp-overdue-dot { flex: none; width: 9px; height: 9px; border-radius: 3px; }
|
||||||
|
.erp-overdue-text { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; }
|
||||||
|
.erp-overdue-text b, .erp-overdue-text small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.erp-overdue-text b { font-weight: 600; }
|
||||||
|
.erp-overdue-text small { color: #6b7079; font-size: 11.5px; }
|
||||||
|
.erp-overdue-late { flex: none; color: #c62a2f; font-size: 12px; font-weight: 700; white-space: nowrap; }
|
||||||
|
.erp-overdue-more { padding: 6px; font-size: 12px; color: #3b6fd8; text-decoration: none; }
|
||||||
|
.erp-overdue-more:hover { text-decoration: underline; }
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user