Compare commits
177 Commits
e197d3deb3
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
| e9f57b6ff6 | |||
| 262ae7fdf8 | |||
| 083eebfd95 | |||
| 0f4608cb43 | |||
| 8e5a682f0d | |||
| b0e816cbdc | |||
| c39139a605 | |||
| 91fd454b2c | |||
| 78d2e665ee | |||
| 4af44f2f7a | |||
| 60d5ca417d | |||
| 2465874198 | |||
| f982a5fa9c | |||
| aa701ed611 | |||
| 8bcf9b4b20 | |||
| dd648d4752 | |||
| 37df7be461 | |||
| 6e69abcfa3 | |||
| 0e6bb53c9c | |||
| 117f40c96f | |||
| ec0eb0a295 | |||
| 7f94e5efe7 | |||
| 3045bc6f99 | |||
| 1678f00c1b | |||
| 7a7e19636f | |||
| 34b8e2fb6b | |||
| 7c53b16566 | |||
| 8043110197 | |||
| 9f57f5d15e | |||
| 4cd349c3a1 | |||
| 5e9c1dac88 | |||
| 282ee559e0 | |||
| 1096fd68ab | |||
| 8bd62fbf6d | |||
| 9229d269c9 | |||
| 4286c45531 | |||
| f87641233b | |||
| 6822329ff2 | |||
| 36834c65b2 | |||
| 359ff29e95 | |||
| 548a163fc4 | |||
| 8636498bc9 | |||
| 9d2e9f6e1b | |||
| 8e1fa556ed | |||
| a65f53ccca | |||
| 547d594659 | |||
| e385b38885 | |||
| ab6c243ab7 | |||
| fc95c8bd25 | |||
| 828ba0938a | |||
| ecc76ae4d8 | |||
| 3b44cf2985 | |||
| f5ddfd366b | |||
| 21659bca35 | |||
| be4c663f70 | |||
| 6ec5485e70 | |||
| 9c94f70e54 | |||
| 7e0f7f7642 | |||
| 3d28d59e4d | |||
| eb208c0c52 | |||
| 1babc39b64 | |||
| 387341b1d8 | |||
| 3476146102 | |||
| de619eaf9f | |||
| de294a53a4 | |||
| 02f83947de | |||
| 2224eb6c22 | |||
| d9db230fe4 | |||
| ece5b06f7a | |||
| fd37e367a1 | |||
| 97b9729671 | |||
| db32d03e07 | |||
| cf0e3f2139 | |||
| e77f3d6a82 | |||
| e6ebf2188b | |||
| 43771edd77 | |||
| 42fdf98560 | |||
| c325d91bab | |||
| 74782da88c | |||
| e3b7e55695 | |||
| f3cb198681 | |||
| 44779c3979 | |||
| 162f9f28d5 | |||
| 99069619d6 | |||
| cff560ad71 | |||
| b637fdeeeb | |||
| 8449b02320 | |||
| 17b119d8c3 | |||
| b7e05f58aa | |||
| 50f25a7ec7 | |||
| 54e4e08802 | |||
| d27257f15b | |||
| 212a3dd6b0 | |||
| 01208ea4d4 | |||
| 49b3b6a0dc | |||
| 4477a68819 | |||
| 5126943a78 | |||
| 97d002a06c | |||
| 4171d61db1 | |||
| 677bf8f1d1 | |||
| 15dcabc538 | |||
| 25c885d5dd | |||
| 61f5b3c320 | |||
| 5d55081464 | |||
| f54f19fa45 | |||
| 876d9758bd | |||
| 0ba6192e95 | |||
| dd5010019d | |||
| 57745e114e | |||
| 307a0c31b1 | |||
| cfb6878bea | |||
| b0f559907f | |||
| b6c8173899 | |||
| d0e3e3622b | |||
| 6055d50dbe | |||
| 321041b65a | |||
| faed6581fd | |||
| 6b04b7ab6e | |||
| a85d562fa7 | |||
| 889522d935 | |||
| 5e5586a25c | |||
| 5cf1a33e98 | |||
| f4b80e8abc | |||
| 7e86e9c91b | |||
| 4ecde312f9 | |||
| 0c17b02468 | |||
| 97f4a904cd | |||
| f7a3afcebf | |||
| b3001c3051 | |||
| 443fa56671 | |||
| 884e654bea | |||
| ff3b36bf77 | |||
| 48cd7f0878 | |||
| 456dfe376f | |||
| 64e19e8c3e | |||
| 6543ce3f0f | |||
| 3a43f699f5 | |||
| c13f529721 | |||
| f904d5935c | |||
| 945b81ab4a | |||
| c85ba4acc3 | |||
| fa50a85730 | |||
| 12c733bafc | |||
| 72352a2ed9 | |||
| 38afbca839 | |||
| ede1f8e5e1 | |||
| 45f92f60ca | |||
| 4ec9f2944a | |||
| 439ecb035c | |||
| 5a660e73dd | |||
| 007a16eb9c | |||
| c9b4fa36fe | |||
| 2a3272e514 | |||
| e420b7f1af | |||
| 7914fc6056 | |||
| 667bdd813c | |||
| 66b5155b9b | |||
| 883fcd24f6 | |||
| fbed3ef159 | |||
| 2b3b36d646 | |||
| d9dd03ecc8 | |||
| d48a942932 | |||
| 3d2e20427c | |||
| d007122782 | |||
| f4d7e9588f | |||
| 7275f12a74 | |||
| 9c166be404 | |||
| 77355b10e4 | |||
| 6c87a736a6 | |||
| 3a0ec6e840 | |||
| 18d2835304 | |||
| fba27772a4 | |||
| c9e5a78115 | |||
| 2bbc2320dc | |||
| 07861dfe8c | |||
| 5d30433019 | |||
| 8c805fdd9c |
+19
-3
@@ -126,6 +126,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다.
|
# 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다.
|
||||||
# CAFE24_SHOP_URL=https://www.miras.co.kr
|
# CAFE24_SHOP_URL=https://www.miras.co.kr
|
||||||
#
|
#
|
||||||
|
# 멀티쇼핑몰 번호(쉼표). 옵션/품목 팝업에서 바꾼 품목 진열·판매를 이 쇼핑몰 모두에 같은 값으로
|
||||||
|
# 보낸다(추가금액·자체코드는 기본몰 1 만). 번호는 카페24 관리자 → 멀티쇼핑몰 관리에서 확인.
|
||||||
|
# 미설정 시 1(기본몰)만.
|
||||||
|
# CAFE24_SHOP_NOS=1,2,3
|
||||||
|
#
|
||||||
# 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전
|
# 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전
|
||||||
# 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도
|
# 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도
|
||||||
# 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다.
|
# 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다.
|
||||||
@@ -156,6 +161,16 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# 초기화: scripts/sql/inout_db_init.sql (docs/INOUT_MODULE.md). 제품(단품)은 아래 ITEMCODE_DB_URL 재사용.
|
# 초기화: scripts/sql/inout_db_init.sql (docs/INOUT_MODULE.md). 제품(단품)은 아래 ITEMCODE_DB_URL 재사용.
|
||||||
# INOUT_DB_URL=postgresql://inout_app:replace-me@postgres-db:5432/inout_db
|
# INOUT_DB_URL=postgresql://inout_app:replace-me@postgres-db:5432/inout_db
|
||||||
|
|
||||||
|
# ─── 안내문 발송 모듈 (outreach_db) — app/modules/outreach ───
|
||||||
|
# 리스트(이메일·인스타 주소 + 이름)에 안내문 메일 일괄 발송(보내는 사람 본인 Gmail — 입출고 Gmail 연결 재사용)·인스타 DM 반자동.
|
||||||
|
# 초기화: scripts/sql/outreach_db_init.sql (docs/DEPLOYMENT.md "안내문 발송 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||||
|
# OUTREACH_DB_URL=postgresql://outreach_app:replace-me@postgres-db:5432/outreach_db
|
||||||
|
|
||||||
|
# ─── 라이브 커머스 모듈 (live_db) — app/modules/live ───
|
||||||
|
# 말레이시아 라이브 방송의 호스트 정보·방송 스케줄·판매금액·결과 이미지.
|
||||||
|
# 초기화: scripts/sql/live_db_init.sql (docs/DEPLOYMENT.md "라이브 커머스 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||||
|
# LIVE_DB_URL=postgresql://live_app:replace-me@postgres-db:5432/live_db
|
||||||
|
|
||||||
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
||||||
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
||||||
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
||||||
@@ -181,10 +196,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일.
|
# 매출·광고비 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 오늘 포함 최근 10일.
|
||||||
# PERFORMANCE_AUTO_SYNC=false # 끄기
|
# 일정(간격·요일·시작/끝)은 실적 설정 "자동 업데이트" 카드에서 매출·광고비 따로 정한다(performance_db 011). 저장 전 기본 = 매일 9~19시 30분마다.
|
||||||
|
# PERFORMANCE_AUTO_SYNC=false # 끄기(설정 화면 일정과 상관없이)
|
||||||
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
|
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
|
||||||
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 일정 저장 전 기본 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||||
|
|
||||||
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
||||||
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
||||||
|
|||||||
@@ -46,6 +46,8 @@
|
|||||||
| `[경비]` `[개인경비]` | `expense/` | `expense_db` | `expense` | (모듈 CLAUDE.md) | — |
|
| `[경비]` `[개인경비]` | `expense/` | `expense_db` | `expense` | (모듈 CLAUDE.md) | — |
|
||||||
| `[공지]` `[긴급공지]` | `notice/` | `project_db`(024) | 수퍼관리자 | `docs/NOTICE_MODULE.md` | `erp-notice*` |
|
| `[공지]` `[긴급공지]` | `notice/` | `project_db`(024) | 수퍼관리자 | `docs/NOTICE_MODULE.md` | `erp-notice*` |
|
||||||
| `[자산]` | `asset/` | `asset_db` | `asset` | `docs/ASSET_MODULE.md` | `asset.*` |
|
| `[자산]` | `asset/` | `asset_db` | `asset` | `docs/ASSET_MODULE.md` | `asset.*` |
|
||||||
|
| `[안내문 발송]` | `outreach/` | `outreach_db` | `outreach` | (모듈 CLAUDE.md) | `outreach.*` |
|
||||||
|
| `[라이브커머스]` `[라이브]` | `live/` | `live_db` | `live`, `live_host` | (모듈 CLAUDE.md) | `live.*` |
|
||||||
| `[공통]` `[ERP]` | `app/main.py`, `app/templates/`(셸·로그인·관리자), 인증·권한 | — | — | `docs/PROJECT_OVERVIEW.md`, `docs/DESIGN.md` | `erp*.js/css`, `styles.css` |
|
| `[공통]` `[ERP]` | `app/main.py`, `app/templates/`(셸·로그인·관리자), 인증·권한 | — | — | `docs/PROJECT_OVERVIEW.md`, `docs/DESIGN.md` | `erp*.js/css`, `styles.css` |
|
||||||
| `[배포]` `[서버]` | `docker-compose*.yml`, `Dockerfile`, `scripts/` | — | — | `docs/DEPLOYMENT.md` | — |
|
| `[배포]` `[서버]` | `docker-compose*.yml`, `Dockerfile`, `scripts/` | — | — | `docs/DEPLOYMENT.md` | — |
|
||||||
| `[DB]` | `scripts/sql/` | — | — | `docs/DATABASES.md` | — |
|
| `[DB]` | `scripts/sql/` | — | — | `docs/DATABASES.md` | — |
|
||||||
@@ -59,12 +61,13 @@
|
|||||||
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
|
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
|
||||||
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
|
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
|
||||||
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
|
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
|
||||||
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`, 처리한 사람 본인 Gmail).
|
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail.
|
||||||
- `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드).
|
- `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드).
|
||||||
|
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
|
||||||
- `app/mail.py`: 프로젝트 알림 메일.
|
- `app/mail.py`: 프로젝트 알림 메일.
|
||||||
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
|
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
|
||||||
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다.
|
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다.
|
||||||
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`).
|
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,11 @@ FROM python:3.12-slim
|
|||||||
# 작업 디렉토리
|
# 작업 디렉토리
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
# 글자 인식(라이브 커머스 결과 이미지 → 매출, app/modules/live/ocr.py) — 영어 데이터만
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-eng \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# 의존성 먼저 설치 (캐시 활용)
|
# 의존성 먼저 설치 (캐시 활용)
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|||||||
@@ -486,7 +486,7 @@ 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]], *, shop_no: int = 1
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
|
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
|
||||||
|
|
||||||
@@ -506,7 +506,7 @@ def update_variants(
|
|||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
payload = client.put(
|
payload = client.put(
|
||||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
f"/admin/products/{no}/variants", json={"shop_no": int(shop_no), "requests": chunk}, product_no=no
|
||||||
)
|
)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
|
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
|
||||||
|
|||||||
+40
@@ -26,10 +26,14 @@ 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.inout import build_inout_items, build_inout_store
|
from .modules.inout import build_inout_items, build_inout_store
|
||||||
from .modules.inout import router as inout_router
|
from .modules.inout import router as inout_router
|
||||||
|
from .modules.live import build_live_store
|
||||||
|
from .modules.live import router as live_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 build_notice_store
|
||||||
from .modules.notice import router as notice_router
|
from .modules.notice import router as notice_router
|
||||||
|
from .modules.outreach import build_outreach_store
|
||||||
|
from .modules.outreach import router as outreach_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
|
||||||
@@ -62,6 +66,10 @@ MODULE_LABELS: dict[str, str] = {
|
|||||||
"performance": "실적",
|
"performance": "실적",
|
||||||
"asset": "자산관리",
|
"asset": "자산관리",
|
||||||
"inout": "입출고 관리",
|
"inout": "입출고 관리",
|
||||||
|
"outreach": "안내문 발송",
|
||||||
|
"live": "라이브 커머스",
|
||||||
|
"live_host": "라이브 호스트 등록",
|
||||||
|
"live_host_edit": "라이브 호스트 수정",
|
||||||
"expense_approver": "개인경비",
|
"expense_approver": "개인경비",
|
||||||
"vacation_approver": "휴가",
|
"vacation_approver": "휴가",
|
||||||
}
|
}
|
||||||
@@ -157,6 +165,8 @@ _MODULE_TEMPLATE_DIRS = [
|
|||||||
BASE_DIR / "modules" / "asset" / "templates",
|
BASE_DIR / "modules" / "asset" / "templates",
|
||||||
BASE_DIR / "modules" / "notice" / "templates",
|
BASE_DIR / "modules" / "notice" / "templates",
|
||||||
BASE_DIR / "modules" / "inout" / "templates",
|
BASE_DIR / "modules" / "inout" / "templates",
|
||||||
|
BASE_DIR / "modules" / "outreach" / "templates",
|
||||||
|
BASE_DIR / "modules" / "live" / "templates",
|
||||||
]
|
]
|
||||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||||
templates.env.loader = ChoiceLoader(
|
templates.env.loader = ChoiceLoader(
|
||||||
@@ -226,6 +236,11 @@ app.state.notice_store = build_notice_store(app.state.project_store)
|
|||||||
# 제품은 itemcode_db 단품(single_items) 읽기 전용 — ITEMCODE_DB_URL 재사용.
|
# 제품은 itemcode_db 단품(single_items) 읽기 전용 — ITEMCODE_DB_URL 재사용.
|
||||||
app.state.inout_store = build_inout_store(dsn=env("INOUT_DB_URL") or None)
|
app.state.inout_store = build_inout_store(dsn=env("INOUT_DB_URL") or None)
|
||||||
app.state.inout_items = build_inout_items()
|
app.state.inout_items = build_inout_items()
|
||||||
|
# 안내문 발송(메일 일괄·인스타 DM 반자동): OUTREACH_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||||
|
# 메일은 보내는 사람 본인 Gmail — 입출고 Gmail 연결(inout_store.inout_gmail_tokens)을 같이 쓴다.
|
||||||
|
app.state.outreach_store = build_outreach_store(dsn=env("OUTREACH_DB_URL") or None)
|
||||||
|
# 라이브 커머스(말레이시아 방송 호스트·스케줄): LIVE_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||||
|
app.state.live_store = build_live_store(dsn=env("LIVE_DB_URL") or None)
|
||||||
|
|
||||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||||
app.include_router(expense_router)
|
app.include_router(expense_router)
|
||||||
@@ -239,6 +254,8 @@ app.include_router(performance_router)
|
|||||||
app.include_router(asset_router)
|
app.include_router(asset_router)
|
||||||
app.include_router(notice_router)
|
app.include_router(notice_router)
|
||||||
app.include_router(inout_router)
|
app.include_router(inout_router)
|
||||||
|
app.include_router(outreach_router)
|
||||||
|
app.include_router(live_router)
|
||||||
|
|
||||||
|
|
||||||
def public_url_for(request: Request, route_name: str) -> str:
|
def public_url_for(request: Request, route_name: str) -> str:
|
||||||
@@ -441,6 +458,27 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
"status": "ready",
|
"status": "ready",
|
||||||
"category": "운영",
|
"category": "운영",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "outreach",
|
||||||
|
"title": "안내문 발송",
|
||||||
|
"subtitle": "Outreach",
|
||||||
|
"description": "이메일·인스타그램 리스트에 이름을 넣은 안내문을 메일로 일괄 발송하고 인스타 DM 을 보냅니다.",
|
||||||
|
"url": "/outreach/",
|
||||||
|
"health_url": "/outreach/health",
|
||||||
|
"status": "ready",
|
||||||
|
"category": "운영",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "live",
|
||||||
|
"title": "라이브 커머스",
|
||||||
|
"card_title": "라이브 커머스 · Live Commerce", # 메인 카드만 한글·영문 둘 다(사이드바는 짧게)
|
||||||
|
"subtitle": "Malaysia",
|
||||||
|
"description": "말레이시아 라이브 방송의 호스트 정보와 방송 스케줄·판매금액·결과 이미지를 관리합니다.",
|
||||||
|
"url": "/live/",
|
||||||
|
"health_url": "/live/health",
|
||||||
|
"status": "ready",
|
||||||
|
"category": "운영",
|
||||||
|
},
|
||||||
]
|
]
|
||||||
items.append({
|
items.append({
|
||||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||||
@@ -457,6 +495,8 @@ def _icon_svg(name: str) -> str:
|
|||||||
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
||||||
paths = {
|
paths = {
|
||||||
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
|
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
|
||||||
|
"outreach": '<path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/>',
|
||||||
|
"live": '<rect x="2" y="6" width="14" height="12" rx="2"/><path d="m16 11 6-4v10l-6-4"/>',
|
||||||
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
"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"/>',
|
||||||
|
|||||||
@@ -3,26 +3,37 @@
|
|||||||
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/CAFE24_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/CAFE24_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
|
||||||
> 정적 파일: `app/static/cafe24.css`, `cafe24-options.js`. 템플릿: `templates/`. 테스트: `tests/`.
|
> 정적 파일: `app/static/cafe24.css`, `cafe24-options.js`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||||
> 공통 API 계층: `app/integrations/cafe24/` — **실적 모듈 카페24 어댑터도 같은 토큰을 씀**, 바꾸면 실적 영향 확인.
|
> 공통 API 계층: `app/integrations/cafe24/` — **실적 모듈 카페24 어댑터도 같은 토큰을 씀**, 바꾸면 실적 영향 확인.
|
||||||
> 배포 시 이 모듈 변경이면 `dbx-cafe24-worker` 도 같이 재빌드.
|
> 배포 시 이 모듈 변경이면 worker 도 같이 재빌드 — compose 서비스명 `cafe24-worker`(컨테이너명 `dbx-cafe24-worker` 아님): `docker compose up -d --build --no-deps web cafe24-worker`.
|
||||||
|
|
||||||
## 기능
|
## 기능
|
||||||
|
|
||||||
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
|
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
|
||||||
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널).
|
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 목록에 64x64 대표 이미지(`tiny_image`, 없으면 `detail_image`).
|
||||||
|
- HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작).
|
||||||
|
- HTML 편집기에서 커서가 `<img>` 태그 안 어디에 있든 Ctrl+↑/↓ 로 `src` 파일명(`.jpg`/`.gif`/`.png`) 번호 변경. 없음 → `_2` → `_3` …, 이미 `_숫자` 면 다음 숫자부터. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 감 — 다른 편집이 끼거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
|
||||||
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
|
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
|
||||||
|
품목 진열·판매는 `CAFE24_SHOP_NOS`(예 1,2,3)의 모든 멀티쇼핑몰에 같은 값으로 보냄(추가금액 등은 기본몰만).
|
||||||
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
|
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
|
||||||
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
|
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
|
||||||
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 코드 복사」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
|
- 옵션/품목 팝업 「판매 가격」 열: 기본 정보 판매가 + 추가금액을 보여주고, 입력하면 추가금액을 역산(`cafe24-options.js` `bindSalePrice`). 저장되는 값은 추가금액뿐.
|
||||||
|
- 기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 품목 추가금액을 (옛 판매가 − 새 판매가)만큼 옮겨 품목 판매 가격을 유지(`_keep_variant_sale_prices`, `store.shift_additional_amounts`). 공급가·소비자가는 품목과 무관. 판매가는 이미 반영됐으므로 품목 조정 실패는 화면 메시지(`variants_error`)로만.
|
||||||
|
- 옵션/품목 팝업 「재고관리」(use_inventory)·「재고」(quantity)·「품절표시」(display_soldout) 열: 같은 PUT variants 로 기본몰에만 보냄(재고는 쇼핑몰 공통).
|
||||||
|
- 옵션/품목 팝업 옵션값 이름·자체 품목코드·추가금액·판매 가격·재고 칸: Enter·↓ 아래 행, ↑ 위 행 같은 열로 이동(한글 조합 중에는 이동 안 함).
|
||||||
|
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 복사(코드)」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
|
||||||
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
|
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
|
||||||
|
「모바일 스와이프 복사(이름)」은 키가 품목코드 대신 옵션값 이름(`swipeCode(tbody, true)`, 품목코드 있는 행만).
|
||||||
|
- 예약(편집기 아래 「예약 적용」): 대표 이미지(썸네일) · 상세페이지 · 진열 · 판매를 지정 시각에. 대표 이미지 파일은 `cafe24_schedule_images`(마이그레이션 006)에 보관, worker 가 이미지 먼저 교체.
|
||||||
- 권한키 `cafe24`(연결/해제는 admin 전용).
|
- 권한키 `cafe24`(연결/해제는 admin 전용).
|
||||||
|
|
||||||
## 규칙
|
## 규칙
|
||||||
|
|
||||||
|
- **카페24 PUT options 는 옵션값 추가를 오류 없이 무시한다** — 기존 옵션에 행 추가는 「옵션 재생성」(DELETE → POST, 품목코드 새로 부여)으로만. 저장 버튼이 새 행을 보면 재생성 확인창으로 넘긴다.
|
||||||
|
|
||||||
- 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지.
|
- 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지.
|
||||||
- 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력.
|
- 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력.
|
||||||
- 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지).
|
- 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지).
|
||||||
- 디자인 FTP(스와이프·상품상세) 쓰기는 임시 파일 → 검증 → rename. **카페24 FTP 는 허용 확장자만 받으므로 임시 이름도 원래 확장자로 끝나야 함**(`x_cf24tmp_<tag>.js`, `design_ftp.temp_names`). `x.js.cf24tmp-…` 는 `550 Operation not permitted`.
|
- 디자인 FTP(스와이프·상품상세) 쓰기는 임시 파일 → 검증 → rename. **카페24 FTP 는 허용 확장자만 받으므로 임시 이름도 원래 확장자로 끝나야 함**(`x_cf24tmp_<tag>.js`, `design_ftp.temp_names`). `x.js.cf24tmp-…` 는 `550 Operation not permitted`.
|
||||||
- 예약은 DB 저장 + 별도 worker(`worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다.
|
- 예약은 DB 저장 + 별도 worker(`worker.py`, compose 서비스 `cafe24-worker`, 컨테이너 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다.
|
||||||
|
|
||||||
## 읽기 지연 ("마지막 쓰기가 권위")
|
## 읽기 지연 ("마지막 쓰기가 권위")
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,15 @@ def read_lag_grace_minutes() -> int:
|
|||||||
return store.parse_grace_minutes(os.getenv("CAFE24_READ_LAG_GRACE_MIN"))
|
return store.parse_grace_minutes(os.getenv("CAFE24_READ_LAG_GRACE_MIN"))
|
||||||
|
|
||||||
|
|
||||||
|
def shop_nos() -> list[int]:
|
||||||
|
"""품목 진열·판매를 함께 맞출 멀티쇼핑몰 번호. `CAFE24_SHOP_NOS`(예: 1,2,3), 기본 [1]."""
|
||||||
|
import os # noqa: WPS433
|
||||||
|
|
||||||
|
from . import store # noqa: WPS433
|
||||||
|
|
||||||
|
return store.parse_shop_nos(os.getenv("CAFE24_SHOP_NOS"))
|
||||||
|
|
||||||
|
|
||||||
def require_user(request: Request) -> dict[str, Any]:
|
def require_user(request: Request) -> dict[str, Any]:
|
||||||
from app.main import get_current_user_record # noqa: WPS433
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
from app.store import has_module # noqa: WPS433
|
from app.store import has_module # noqa: WPS433
|
||||||
@@ -96,11 +105,11 @@ def guard(request: Request):
|
|||||||
반환이 tuple 이면 (store, user), 아니면 그대로 응답으로 돌려준다.
|
반환이 tuple 이면 (store, user), 아니면 그대로 응답으로 돌려준다.
|
||||||
"""
|
"""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, MODULE_KEY):
|
if not has_module(user, MODULE_KEY):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
|
|||||||
+31
-17
@@ -819,27 +819,41 @@ class Cafe24Store:
|
|||||||
set_selling: bool | None,
|
set_selling: bool | None,
|
||||||
memo: str = "",
|
memo: str = "",
|
||||||
created_by: str = "",
|
created_by: str = "",
|
||||||
|
image: bytes | None = None,
|
||||||
|
image_type: str = "",
|
||||||
|
image_name: str = "",
|
||||||
) -> int:
|
) -> int:
|
||||||
|
"""예약 등록. image 가 있으면 파일을 cafe24_schedule_images 에 같은 트랜잭션으로 남긴다(006).
|
||||||
|
|
||||||
|
이미지 없는 예약은 006 컬럼을 쓰지 않는다 — 마이그레이션 전에도 기존 예약 등록이 깨지지 않게.
|
||||||
|
"""
|
||||||
|
cols = ["product_no", "scheduled_at", "revision_id", "set_display", "set_selling", "memo", "created_by"]
|
||||||
|
vals: list[Any] = [int(product_no), scheduled_at, revision_id, set_display, set_selling,
|
||||||
|
(memo or "")[:500], created_by or ""]
|
||||||
|
if image:
|
||||||
|
cols += ["image_type", "image_name"]
|
||||||
|
vals += [image_type, (image_name or "")[:200]]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute(
|
||||||
|
f"INSERT INTO cafe24_product_schedules ({', '.join(cols)}) " # noqa: S608 — 고정 컬럼명만
|
||||||
|
f"VALUES ({', '.join(['%s'] * len(cols))}) RETURNING id",
|
||||||
|
vals,
|
||||||
|
).fetchone()
|
||||||
|
if row and image:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO cafe24_schedule_images (schedule_id, data) VALUES (%s, %s)",
|
||||||
|
(row["id"], image),
|
||||||
|
)
|
||||||
|
return int(row["id"]) if row else 0
|
||||||
|
|
||||||
|
def get_schedule_image(self, schedule_id: int) -> bytes:
|
||||||
|
"""예약 대표 이미지 파일. 없으면 b""."""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"SELECT data FROM cafe24_schedule_images WHERE schedule_id = %s", (int(schedule_id),)
|
||||||
INSERT INTO cafe24_product_schedules
|
|
||||||
(product_no, scheduled_at, revision_id, set_display, set_selling,
|
|
||||||
memo, created_by)
|
|
||||||
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
|
||||||
RETURNING id
|
|
||||||
""",
|
|
||||||
(
|
|
||||||
int(product_no),
|
|
||||||
scheduled_at,
|
|
||||||
revision_id,
|
|
||||||
set_display,
|
|
||||||
set_selling,
|
|
||||||
(memo or "")[:500],
|
|
||||||
created_by or "",
|
|
||||||
),
|
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return int(row["id"]) if row else 0
|
return bytes(row["data"]) if row else b""
|
||||||
|
|
||||||
def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||||
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
|
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ 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, writes
|
from . import store, writes
|
||||||
from .common import read_lag_grace_minutes, require_store
|
from .common import read_lag_grace_minutes, require_store, shop_nos
|
||||||
from .routes_products import load_product, locked_json, remember_write
|
from .routes_products import load_product, locked_json, remember_write
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.product_info")
|
logger = logging.getLogger("cafe24.product_info")
|
||||||
@@ -145,12 +145,46 @@ def product_basic(
|
|||||||
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 {})
|
||||||
|
shifted = (_keep_variant_sale_prices(st, api, product_no, before["price"], changes["price"])
|
||||||
|
if "price" in changes 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())
|
||||||
|
if shifted.get("detail"):
|
||||||
|
detail += f" / 품목 추가금액 조정: {shifted['detail']}"
|
||||||
writes.audit_safe(st, 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),
|
||||||
|
"variants_shifted": shifted.get("count", 0), "variants_error": shifted.get("error", "")}
|
||||||
|
|
||||||
|
|
||||||
|
def _keep_variant_sale_prices(st: Any, api: Any, product_no: int, old_price: str, new_price: str) -> dict[str, Any]:
|
||||||
|
"""판매가가 바뀐 뒤 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴다.
|
||||||
|
|
||||||
|
판매가는 이미 반영됐으므로 실패해도 예외를 올리지 않고 {"error": …} 로 알린다.
|
||||||
|
반환 {"count": 반영된 품목 수, "error": 사유, "detail": 감사 로그용}.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
variants = _load_options_and_variants(st, api, product_no)["effective_variants"]
|
||||||
|
requests = store.build_variant_updates(store.shift_additional_amounts(variants, old_price, new_price))
|
||||||
|
except (Cafe24Error, ValueError) as exc:
|
||||||
|
logger.warning("카페24 상품 %s 품목 추가금액 조정 준비 실패: %s", product_no, exc)
|
||||||
|
return {"error": f"품목 추가금액 조정 실패: {exc}", "detail": f"실패 {exc}"}
|
||||||
|
if not requests:
|
||||||
|
return {}
|
||||||
|
results = products.update_variants(api.client, product_no, requests)
|
||||||
|
sent = {r["variant_code"]: r["additional_amount"] for r in requests}
|
||||||
|
ok = {r["variant_code"]: sent[r["variant_code"]] for r in results if r["status"] == products.VARIANT_OK}
|
||||||
|
bad = [r for r in results if r["status"] != products.VARIANT_OK]
|
||||||
|
if ok:
|
||||||
|
_save_snapshot_safe(st, product_no, "variants", {c: {"additional_amount": a} for c, a in ok.items()})
|
||||||
|
detail = "; ".join(f"{c}={a}" for c, a in ok.items())
|
||||||
|
error = ""
|
||||||
|
if bad:
|
||||||
|
error = f"품목 {len(bad)}건 추가금액 조정 실패 — {bad[0]['error']} (옵션/품목 창에서 확인하세요)"
|
||||||
|
detail += f" / 실패 {len(bad)}건: {bad[0]['error']}"
|
||||||
|
logger.warning("카페24 상품 %s 품목 추가금액 조정 %s건 실패: %s", product_no, len(bad), bad[0]["error"])
|
||||||
|
return {"count": len(ok), "error": error, "detail": detail}
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -223,6 +257,7 @@ def _variant_view(v: dict[str, Any]) -> dict[str, Any]:
|
|||||||
"selling": products._flag(v.get("selling")), # noqa: SLF001
|
"selling": products._flag(v.get("selling")), # noqa: SLF001
|
||||||
"quantity": v.get("quantity"),
|
"quantity": v.get("quantity"),
|
||||||
"use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001
|
"use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001
|
||||||
|
"display_soldout": products._flag(v.get("display_soldout"), default=False), # noqa: SLF001
|
||||||
"image": str(v.get("image") or ""),
|
"image": str(v.get("image") or ""),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -482,19 +517,11 @@ def options_update(
|
|||||||
try:
|
try:
|
||||||
body = store.build_update_options_request(
|
body = store.build_update_options_request(
|
||||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
||||||
allow_append=True,
|
|
||||||
)
|
)
|
||||||
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
|
||||||
if loaded["option"]["option_preset_code"]:
|
if loaded["option"]["option_preset_code"]:
|
||||||
body["option_preset_code"] = 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:
|
try:
|
||||||
updated = products.update_options(api.client, product_no, body)
|
updated = products.update_options(api.client, product_no, body)
|
||||||
@@ -508,7 +535,7 @@ def options_update(
|
|||||||
record_error = _save_snapshot_safe(
|
record_error = _save_snapshot_safe(
|
||||||
st, product_no, "options",
|
st, product_no, "options",
|
||||||
_options_snapshot(updated, befores=[loaded["raw_option"], loaded["effective_option"]],
|
_options_snapshot(updated, befores=[loaded["raw_option"], loaded["effective_option"]],
|
||||||
osec=loaded["options_section"], recent=added_texts),
|
osec=loaded["options_section"], recent=[]),
|
||||||
)
|
)
|
||||||
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
||||||
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||||
@@ -541,29 +568,15 @@ def options_update(
|
|||||||
summary = "; ".join(
|
summary = "; ".join(
|
||||||
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
||||||
for o in body["options"]
|
for o in body["options"]
|
||||||
) + (f" (+{added} 추가)" if added else "")
|
)
|
||||||
|
|
||||||
fresh: list[dict[str, Any]] | None = None
|
|
||||||
if added:
|
|
||||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
|
||||||
# 늦게 나타나는 품목은 pending 으로 표시된다(_annotate).
|
|
||||||
_osec, vsec = _snapshot_sections(st, product_no)
|
|
||||||
fresh = _patch_variants(
|
|
||||||
vsec, products.wait_for_variants(api.client, product_no, len(loaded["raw_variants"]) + added)
|
|
||||||
)
|
|
||||||
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||||
result="SUCCESS", detail=summary[:900])
|
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(
|
shown_option, shown_variants = _annotate(updated, renamed_variants, [])
|
||||||
updated, fresh if fresh is not None else renamed_variants, added_texts
|
return {"ok": True, "option": _options_view(shown_option),
|
||||||
)
|
"variants": [_variant_view(v) for v in shown_variants],
|
||||||
out: dict[str, Any] = {"ok": True, "option": _options_view(shown_option),
|
"record_warning": record_error}
|
||||||
"variants": [_variant_view(v) for v in shown_variants],
|
|
||||||
"record_warning": record_error}
|
|
||||||
if added:
|
|
||||||
out["added"] = added
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.delete("/products/{product_no}/options")
|
@product_info_router.delete("/products/{product_no}/options")
|
||||||
@@ -652,12 +665,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: 반영된 값},
|
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
||||||
"failed": {code: 사유}, "unknown": {code: 사유}}
|
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||||
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||||
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||||
|
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
|
||||||
"""
|
"""
|
||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
@@ -684,7 +698,8 @@ def variants_update(
|
|||||||
code = result["variant_code"]
|
code = result["variant_code"]
|
||||||
if result["status"] == products.VARIANT_OK:
|
if result["status"] == products.VARIANT_OK:
|
||||||
patch = dict(sent.get(code) or {})
|
patch = dict(sent.get(code) or {})
|
||||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order",
|
||||||
|
"use_inventory", "display_soldout", "quantity"):
|
||||||
value = (result.get("variant") or {}).get(key)
|
value = (result.get("variant") or {}).get(key)
|
||||||
if value is not None:
|
if value is not None:
|
||||||
patch[key] = value
|
patch[key] = value
|
||||||
@@ -695,9 +710,26 @@ def variants_update(
|
|||||||
failed[code] = result["error"]
|
failed[code] = result["error"]
|
||||||
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
|
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
|
||||||
|
|
||||||
|
# 멀티쇼핑몰: 진열·판매는 쇼핑몰마다 따로라 기본몰(1)에 반영된 행의 진열·판매만
|
||||||
|
# 다른 쇼핑몰에도 똑같이 보낸다. 추가금액(통화가 다름)·자체코드·순서는 보내지 않는다.
|
||||||
|
flags = [
|
||||||
|
{"variant_code": code, **{k: sent[code][k] for k in ("display", "selling") if k in sent[code]}}
|
||||||
|
for code in by_code if {"display", "selling"} & set(sent.get(code) or {})
|
||||||
|
]
|
||||||
|
shop_failed: dict[str, str] = {}
|
||||||
|
for shop in (shop_nos()[1:] if flags else []):
|
||||||
|
bad = [r for r in products.update_variants(api.client, product_no, flags, shop_no=shop)
|
||||||
|
if r["status"] != products.VARIANT_OK]
|
||||||
|
if bad:
|
||||||
|
shop_failed[str(shop)] = f"{len(bad)}건 — {bad[0]['error']}"
|
||||||
|
|
||||||
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()
|
||||||
)
|
)
|
||||||
|
if flags and len(shop_nos()) > 1:
|
||||||
|
detail = f"[진열·판매 쇼핑몰 {','.join(map(str, shop_nos()))}] " + detail
|
||||||
|
if shop_failed:
|
||||||
|
detail += " / 다른 쇼핑몰 실패: " + "; ".join(f"{s}번 {e}" for s, e in shop_failed.items())
|
||||||
if failed or unknown:
|
if failed or unknown:
|
||||||
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
||||||
first = next(iter({**failed, **unknown}.values()), "")
|
first = next(iter({**failed, **unknown}.values()), "")
|
||||||
@@ -718,5 +750,6 @@ def variants_update(
|
|||||||
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
|
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
|
||||||
"failed": failed,
|
"failed": failed,
|
||||||
"unknown": unknown,
|
"unknown": unknown,
|
||||||
|
"shop_failed": shop_failed,
|
||||||
"record_warning": record_error,
|
"record_warning": record_error,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,10 +133,11 @@ def _iso(value: Any) -> str:
|
|||||||
|
|
||||||
|
|
||||||
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)
|
||||||
return {
|
return {
|
||||||
"product_no": normalized["product_no"],
|
"product_no": normalized["product_no"],
|
||||||
|
"thumb": str(raw.get("tiny_image") or raw.get("detail_image") or ""),
|
||||||
"product_name": normalized["product_name"],
|
"product_name": normalized["product_name"],
|
||||||
"display": normalized["display"],
|
"display": normalized["display"],
|
||||||
"selling": normalized["selling"],
|
"selling": normalized["selling"],
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
"""카페24 예약관리 — 지정 시각에 상세페이지·진열/판매를 자동 적용.
|
"""카페24 예약관리 — 지정 시각에 대표 이미지·상세페이지·진열/판매를 자동 적용.
|
||||||
|
|
||||||
되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다.
|
되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다.
|
||||||
한 예약에서 세 가지를 각각 고를 수 있다.
|
한 예약에서 네 가지를 각각 고를 수 있다.
|
||||||
|
|
||||||
|
대표 이미지 고른 파일로 그 시각에 교체 (파일은 DB 보관 — 마이그레이션 006)
|
||||||
상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로)
|
상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로)
|
||||||
진열 진열 / 미진열 / 변경 없음
|
진열 진열 / 미진열 / 변경 없음
|
||||||
판매 판매 / 중지 / 변경 없음
|
판매 판매 / 중지 / 변경 없음
|
||||||
@@ -19,13 +20,14 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, Request
|
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||||
|
|
||||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
|
||||||
|
|
||||||
from . import store, writes
|
from . import store, writes
|
||||||
from .common import base_ctx, guard
|
from .common import base_ctx, guard
|
||||||
|
from .routes_product_info import _read_image
|
||||||
from .routes_products import _no_store, load_product
|
from .routes_products import _no_store, load_product
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.schedules")
|
logger = logging.getLogger("cafe24.schedules")
|
||||||
@@ -53,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
|||||||
has_html=bool(row.get("has_html")),
|
has_html=bool(row.get("has_html")),
|
||||||
set_display=row.get("set_display"),
|
set_display=row.get("set_display"),
|
||||||
set_selling=row.get("set_selling"),
|
set_selling=row.get("set_selling"),
|
||||||
|
has_image=bool(row.get("image_type")),
|
||||||
),
|
),
|
||||||
"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,
|
"needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW,
|
||||||
@@ -63,7 +66,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
|||||||
ctx.update(
|
ctx.update(
|
||||||
{
|
{
|
||||||
"page_title": "카페24 — 예약관리",
|
"page_title": "카페24 — 예약관리",
|
||||||
"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"]),
|
"review": sum(1 for r in rows if r["needs_review"]),
|
||||||
@@ -85,12 +88,14 @@ def schedule_create(
|
|||||||
set_selling: str = Form(""),
|
set_selling: str = Form(""),
|
||||||
memo: str = Form(""),
|
memo: str = Form(""),
|
||||||
list_query: str = Form(""),
|
list_query: str = Form(""),
|
||||||
|
image: UploadFile | None = File(None),
|
||||||
):
|
):
|
||||||
"""편집기에서 예약을 등록한다.
|
"""편집기에서 예약을 등록한다.
|
||||||
|
|
||||||
HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다.
|
HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다.
|
||||||
단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때
|
단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때
|
||||||
저장되는 값이 화면에서 본 것과 같다.
|
저장되는 값이 화면에서 본 것과 같다.
|
||||||
|
대표 이미지 파일을 고르면 파일을 DB 에 보관했다가 그 시각에 교체한다(마이그레이션 006).
|
||||||
"""
|
"""
|
||||||
checked = guard(request)
|
checked = guard(request)
|
||||||
if not isinstance(checked, tuple):
|
if not isinstance(checked, tuple):
|
||||||
@@ -105,9 +110,16 @@ def schedule_create(
|
|||||||
display_flag = store.parse_tristate(set_display)
|
display_flag = store.parse_tristate(set_display)
|
||||||
selling_flag = store.parse_tristate(set_selling)
|
selling_flag = store.parse_tristate(set_selling)
|
||||||
|
|
||||||
if not want_html and display_flag is None and selling_flag is None:
|
image_data = b""
|
||||||
|
if image is not None and image.filename: # 파일을 안 고르면 브라우저가 이름 없는 빈 파트를 보낸다
|
||||||
|
try:
|
||||||
|
image_data = _read_image(image)
|
||||||
|
except HTTPException as exc:
|
||||||
|
return RedirectResponse(url=f"{back}&err={exc.detail}", status_code=303)
|
||||||
|
|
||||||
|
if not want_html and display_flag is None and selling_flag is None and not image_data:
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(상세페이지 / 진열 / 판매).",
|
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(대표 이미지 / 상세페이지 / 진열 / 판매).",
|
||||||
status_code=303,
|
status_code=303,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -146,9 +158,12 @@ def schedule_create(
|
|||||||
set_selling=selling_flag,
|
set_selling=selling_flag,
|
||||||
memo=memo,
|
memo=memo,
|
||||||
created_by=actor,
|
created_by=actor,
|
||||||
|
image=image_data or None,
|
||||||
|
image_type=(image.content_type or "").lower() if image_data and image else "",
|
||||||
|
image_name=(image.filename or "") if image_data and image else "",
|
||||||
)
|
)
|
||||||
detail = store.describe_schedule_action(
|
detail = store.describe_schedule_action(
|
||||||
has_html=want_html, set_display=display_flag, set_selling=selling_flag
|
has_html=want_html, set_display=display_flag, set_selling=selling_flag, has_image=bool(image_data)
|
||||||
)
|
)
|
||||||
st.log_audit(
|
st.log_audit(
|
||||||
actor=actor, action="schedule_create", product_no=product_no,
|
actor=actor, action="schedule_create", product_no=product_no,
|
||||||
@@ -179,6 +194,20 @@ def schedule_cancel(request: Request, schedule_id: int):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@schedules_router.get("/schedules/{schedule_id}/image")
|
||||||
|
def schedule_image(request: Request, schedule_id: int):
|
||||||
|
"""예약해 둔 대표 이미지 미리보기(목록 썸네일)."""
|
||||||
|
checked = guard(request)
|
||||||
|
if not isinstance(checked, tuple):
|
||||||
|
return checked
|
||||||
|
st, _user = checked
|
||||||
|
row = st.get_schedule(schedule_id)
|
||||||
|
data = st.get_schedule_image(schedule_id) if row.get("image_type") else b""
|
||||||
|
if not data:
|
||||||
|
return Response(status_code=404)
|
||||||
|
return Response(content=data, media_type=str(row["image_type"]), headers={"Cache-Control": "private, max-age=3600"})
|
||||||
|
|
||||||
|
|
||||||
@schedules_router.get("/schedules/preview/{product_no}")
|
@schedules_router.get("/schedules/preview/{product_no}")
|
||||||
def schedule_current_flags(request: Request, product_no: int) -> dict:
|
def schedule_current_flags(request: Request, product_no: int) -> dict:
|
||||||
"""예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용)."""
|
"""예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용)."""
|
||||||
|
|||||||
+47
-22
@@ -452,10 +452,12 @@ def parse_schedule_at(value: object, *, now: datetime | None = None) -> datetime
|
|||||||
|
|
||||||
|
|
||||||
def describe_schedule_action(
|
def describe_schedule_action(
|
||||||
*, has_html: bool, set_display: bool | None, set_selling: bool | None
|
*, has_html: bool, set_display: bool | None, set_selling: bool | None, has_image: bool = False
|
||||||
) -> str:
|
) -> str:
|
||||||
"""예약 내용을 한 줄로 요약(목록·로그 표시용)."""
|
"""예약 내용을 한 줄로 요약(목록·로그 표시용)."""
|
||||||
parts: list[str] = []
|
parts: list[str] = []
|
||||||
|
if has_image:
|
||||||
|
parts.append("대표이미지")
|
||||||
if has_html:
|
if has_html:
|
||||||
parts.append("상세페이지")
|
parts.append("상세페이지")
|
||||||
if set_display is not None:
|
if set_display is not None:
|
||||||
@@ -504,6 +506,15 @@ WRITE_REVISION_TYPES: tuple[str, ...] = (REVISION_MANUAL, REVISION_SCHEDULED, RE
|
|||||||
DEFAULT_READ_LAG_GRACE_MIN = 360
|
DEFAULT_READ_LAG_GRACE_MIN = 360
|
||||||
|
|
||||||
|
|
||||||
|
def parse_shop_nos(value: object) -> list[int]:
|
||||||
|
"""`CAFE24_SHOP_NOS`("1,2,3") → [1, 2, 3]. 기본 쇼핑몰 1 은 항상 맨 앞, 잘못된 값은 버린다."""
|
||||||
|
out = [1]
|
||||||
|
for part in str(value or "").replace(" ", "").split(","):
|
||||||
|
if part.isdigit() and int(part) > 0 and int(part) not in out:
|
||||||
|
out.append(int(part))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def parse_grace_minutes(value: object, default: int = DEFAULT_READ_LAG_GRACE_MIN) -> int:
|
def parse_grace_minutes(value: object, default: int = DEFAULT_READ_LAG_GRACE_MIN) -> int:
|
||||||
try:
|
try:
|
||||||
minutes = int(str(value or "").strip())
|
minutes = int(str(value or "").strip())
|
||||||
@@ -973,16 +984,15 @@ def build_update_options_request(
|
|||||||
edited: list[dict],
|
edited: list[dict],
|
||||||
*,
|
*,
|
||||||
option_list_type: str = "",
|
option_list_type: str = "",
|
||||||
allow_append: bool = False,
|
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""옵션명/옵션값(이름·이미지·색상·표시방식) 수정 요청.
|
"""옵션명/옵션값(이름·이미지·색상·표시방식) 수정 요청.
|
||||||
|
|
||||||
카페24 PUT options 는 `original_options`(수정 전) 와 `options`(수정 후) 를
|
카페24 PUT options 는 `original_options`(수정 전) 와 `options`(수정 후) 를
|
||||||
**위치**로 짝지어 이름을 바꾼다. 그래서
|
**위치**로 짝지어 이름을 바꾼다. 옵션값 개수는 바꿀 수 없다:
|
||||||
- 옵션값을 **뒤에 덧붙이는** 것(`allow_append`)만 허용한다 — 앞쪽 위치는 그대로라
|
- **추가**: 카페24 문서상 PUT 은 옵션 항목 추가를 지원하지 않는다 — 실물에서
|
||||||
기존 이름이 밀리지 않는다(카페24가 추가를 거부하면 그 오류가 그대로 올라온다).
|
덧붙여 보내도 오류 없이 무시되어 "저장했는데 사라짐"이 됐다(2026-11-06).
|
||||||
- 옵션값 **삭제**(개수 감소)는 거부한다 — 중간을 빼면 뒤 값들이 한 칸씩 당겨져
|
추가는 옵션 재생성(삭제 후 POST)으로 한다.
|
||||||
엉뚱한 품목의 이름이 바뀐다. 정리는 옵션 재생성(삭제 후 생성)으로 한다.
|
- **삭제**: 중간을 빼면 뒤 값들이 한 칸씩 당겨져 엉뚱한 품목의 이름이 바뀐다.
|
||||||
original: GET 응답의 options 그대로. edited: 화면에서 보낸 같은 모양의 목록.
|
original: GET 응답의 options 그대로. edited: 화면에서 보낸 같은 모양의 목록.
|
||||||
"""
|
"""
|
||||||
if len(original) != len(edited):
|
if len(original) != len(edited):
|
||||||
@@ -997,10 +1007,10 @@ def build_update_options_request(
|
|||||||
f"옵션 「{o.get('option_name')}」 의 옵션값을 줄일 수 없습니다. "
|
f"옵션 「{o.get('option_name')}」 의 옵션값을 줄일 수 없습니다. "
|
||||||
"옵션값 삭제는 카페24 API 가 지원하지 않습니다 — 옵션 재생성으로 정리하세요."
|
"옵션값 삭제는 카페24 API 가 지원하지 않습니다 — 옵션 재생성으로 정리하세요."
|
||||||
)
|
)
|
||||||
if len(e_vals) > len(o_vals) and not allow_append:
|
if len(e_vals) > len(o_vals):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"옵션 「{o.get('option_name')}」 의 옵션값 개수가 카페24와 다릅니다. "
|
f"옵션 「{o.get('option_name')}」 에 옵션값을 추가할 수 없습니다. "
|
||||||
"다시 읽은 뒤 수정하세요."
|
"카페24 API 는 기존 옵션에 옵션값 추가를 지원하지 않습니다 — 「옵션 재생성」으로 추가하세요."
|
||||||
)
|
)
|
||||||
name = str(e.get("option_name") or "").strip()
|
name = str(e.get("option_name") or "").strip()
|
||||||
if not name:
|
if not name:
|
||||||
@@ -1036,17 +1046,6 @@ def build_update_options_request(
|
|||||||
n_item[key] = value
|
n_item[key] = value
|
||||||
orig_entry["option_value"].append(o_item)
|
orig_entry["option_value"].append(o_item)
|
||||||
new_entry["option_value"].append(n_item)
|
new_entry["option_value"].append(n_item)
|
||||||
# 덧붙이는 새 옵션값 — 수정 전 목록에는 없고 수정 후 목록 끝에만 있다.
|
|
||||||
for ev in e_vals[len(o_vals):]:
|
|
||||||
text = str(ev.get("option_text") or "").strip()
|
|
||||||
if not text:
|
|
||||||
raise ValueError("추가할 옵션값 이름은 비울 수 없습니다.")
|
|
||||||
n_item = {"option_text": text}
|
|
||||||
for key in ("option_image_file", "option_link_image", "option_color"):
|
|
||||||
value = str(ev.get(key) or "").strip()
|
|
||||||
if value:
|
|
||||||
n_item[key] = value
|
|
||||||
new_entry["option_value"].append(n_item)
|
|
||||||
orig_out.append(orig_entry)
|
orig_out.append(orig_entry)
|
||||||
new_out.append(new_entry)
|
new_out.append(new_entry)
|
||||||
request: dict = {"original_options": orig_out, "options": new_out}
|
request: dict = {"original_options": orig_out, "options": new_out}
|
||||||
@@ -1072,6 +1071,24 @@ def parse_additional_amount(value: object) -> str | None:
|
|||||||
return f"{number}.00"
|
return f"{number}.00"
|
||||||
|
|
||||||
|
|
||||||
|
def shift_additional_amounts(variants: list[dict], old_price: object, new_price: object) -> list[dict]:
|
||||||
|
"""판매가 old → new 일 때 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴 행들.
|
||||||
|
|
||||||
|
build_variant_updates 에 그대로 넣는 화면 행 모양. 판매가가 같거나 숫자가 아니면 [].
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
delta = int(round(float(old_price))) - int(round(float(new_price))) # type: ignore[arg-type]
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return []
|
||||||
|
if not delta:
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
{"variant_code": str(v["variant_code"]),
|
||||||
|
"additional_amount": str(int(round(float(v.get("additional_amount") or 0))) + delta)}
|
||||||
|
for v in variants if v.get("variant_code")
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def build_variant_updates(rows: list[dict]) -> list[dict]:
|
def build_variant_updates(rows: list[dict]) -> list[dict]:
|
||||||
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
|
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
|
||||||
out: list[dict] = []
|
out: list[dict] = []
|
||||||
@@ -1089,9 +1106,17 @@ def build_variant_updates(rows: list[dict]) -> list[dict]:
|
|||||||
amount = parse_additional_amount(row["additional_amount"])
|
amount = parse_additional_amount(row["additional_amount"])
|
||||||
if amount is not None:
|
if amount is not None:
|
||||||
item["additional_amount"] = amount
|
item["additional_amount"] = amount
|
||||||
for flag in ("display", "selling"):
|
for flag in ("display", "selling", "use_inventory", "display_soldout"):
|
||||||
if row.get(flag) is not None:
|
if row.get(flag) is not None:
|
||||||
item[flag] = "T" if parse_tristate(row[flag]) else "F"
|
item[flag] = "T" if parse_tristate(row[flag]) else "F"
|
||||||
|
if row.get("quantity") is not None and str(row["quantity"]).strip() != "":
|
||||||
|
try:
|
||||||
|
qty = int(str(row["quantity"]).strip().replace(",", ""))
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError("재고 수량은 숫자여야 합니다.") from None
|
||||||
|
if not 0 <= qty <= ADDITIONAL_AMOUNT_MAX:
|
||||||
|
raise ValueError("재고 수량은 0 이상이어야 합니다.")
|
||||||
|
item["quantity"] = qty
|
||||||
# 진열 순서(1~300) — 카페24 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다.
|
# 진열 순서(1~300) — 카페24 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다.
|
||||||
if row.get("display_order") is not None:
|
if row.get("display_order") is not None:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""일회성 — 모든 옵션 상품의 품목 진열·판매를 기본몰(1) 값으로 다른 멀티쇼핑몰에 맞춘다.
|
||||||
|
|
||||||
|
# 미리보기(쓰지 않음): 바뀔 품목만 출력
|
||||||
|
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4
|
||||||
|
# 실제 반영 — 출력(바꾸기 전 값 포함)을 파일로 남겨 둔다
|
||||||
|
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4 --apply > sync.log
|
||||||
|
|
||||||
|
기본몰 값은 화면과 같은 기준(읽기 지연 보정)으로 읽는다. 다른 쇼핑몰에 없는 품목은 건너뛴다.
|
||||||
|
진열·판매만 보낸다(추가금액·자체코드는 건드리지 않음). 출력의 BEFORE 줄 = 되돌릴 때 쓸 원래 값.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def plan_flag_sync(base: list[dict[str, Any]], shop_variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""기본몰 품목(display/selling = bool) vs 다른 쇼핑몰 GET 품목('T'/'F') → 바꿀 PUT 요청."""
|
||||||
|
from app.integrations.cafe24 import products # noqa: WPS433
|
||||||
|
|
||||||
|
other = {str(v.get("variant_code") or ""): v for v in shop_variants}
|
||||||
|
out = []
|
||||||
|
for v in base:
|
||||||
|
o = other.get(v["variant_code"])
|
||||||
|
if o is None:
|
||||||
|
continue
|
||||||
|
req = {k: ("T" if v[k] else "F") for k in ("display", "selling")
|
||||||
|
if products._flag(o.get(k)) != v[k]} # noqa: SLF001
|
||||||
|
if req:
|
||||||
|
out.append({"variant_code": v["variant_code"], **req})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
from app.integrations.cafe24 import build_cafe24_api # noqa: WPS433
|
||||||
|
|
||||||
|
from . import build_cafe24_store # noqa: WPS433
|
||||||
|
|
||||||
|
ap =argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--shops", required=True, help="맞출 쇼핑몰 번호(쉼표), 예: 3,4")
|
||||||
|
ap.add_argument("--apply", action="store_true", help="실제로 카페24에 쓴다(없으면 미리보기)")
|
||||||
|
args = ap.parse_args(argv)
|
||||||
|
shops = [int(s) for s in args.shops.split(",") if s.strip().isdigit() and int(s) > 1]
|
||||||
|
if not shops:
|
||||||
|
print("--shops 에 2 이상 쇼핑몰 번호가 필요합니다.", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
|
||||||
|
st = build_cafe24_store(dsn=os.environ["CAFE24_DB_URL"])
|
||||||
|
try:
|
||||||
|
return _run(st, build_cafe24_api(st), shops, args.apply)
|
||||||
|
finally:
|
||||||
|
st.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _run(st: Any, api: Any, shops: list[int], apply: bool) -> int:
|
||||||
|
from app.integrations.cafe24 import products # noqa: WPS433
|
||||||
|
|
||||||
|
from . import writes # noqa: WPS433
|
||||||
|
from .routes_product_info import _load_options_and_variants # noqa: WPS433
|
||||||
|
|
||||||
|
items, truncated = products.list_all_products(api.client)
|
||||||
|
if truncated:
|
||||||
|
print("상품이 상한(1000)을 넘어 일부만 처리합니다.", file=sys.stderr)
|
||||||
|
mode = "APPLY" if apply else "DRY-RUN"
|
||||||
|
total = failed = 0
|
||||||
|
for item in items:
|
||||||
|
no = int(item["product_no"])
|
||||||
|
if str(item.get("has_option") or "T") == "F":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
base = _load_options_and_variants(st, api, no)["variants"]
|
||||||
|
except Exception as exc: # noqa: BLE001 — 한 상품 실패가 나머지를 막지 않게
|
||||||
|
print(f"ERROR {no} 기본몰 조회 실패: {exc}")
|
||||||
|
failed += 1
|
||||||
|
continue
|
||||||
|
for shop in shops:
|
||||||
|
try:
|
||||||
|
got = api.client.get(f"/admin/products/{no}/variants", params={"shop_no": shop}, product_no=no)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
print(f"ERROR {no} shop {shop} 조회 실패: {exc}")
|
||||||
|
failed += 1
|
||||||
|
continue
|
||||||
|
shop_vars = got.get("variants") if isinstance(got.get("variants"), list) else []
|
||||||
|
reqs = plan_flag_sync(base, shop_vars)
|
||||||
|
if not reqs:
|
||||||
|
continue
|
||||||
|
before = {str(v.get("variant_code")): {"display": v.get("display"), "selling": v.get("selling")}
|
||||||
|
for v in shop_vars if str(v.get("variant_code")) in {r["variant_code"] for r in reqs}}
|
||||||
|
print("BEFORE " + json.dumps({"product_no": no, "shop_no": shop, "variants": before}, ensure_ascii=False))
|
||||||
|
print(f"{mode} {no} shop {shop}: {len(reqs)}건 " + json.dumps(reqs, ensure_ascii=False))
|
||||||
|
total += len(reqs)
|
||||||
|
if not apply:
|
||||||
|
continue
|
||||||
|
bad = [r for r in products.update_variants(api.client, no, reqs, shop_no=shop)
|
||||||
|
if r["status"] != products.VARIANT_OK]
|
||||||
|
failed += len(bad)
|
||||||
|
writes.audit_safe(
|
||||||
|
st, actor="SYNC_SHOPS", action="update_variants", product_no=no,
|
||||||
|
result="FAIL" if bad else "SUCCESS",
|
||||||
|
detail=(f"[쇼핑몰 {shop} 진열·판매 = 기본몰] " + json.dumps(reqs, ensure_ascii=False)
|
||||||
|
+ (f" / 실패 {len(bad)}: {bad[0]['error']}" if bad else ""))[:900],
|
||||||
|
)
|
||||||
|
if bad:
|
||||||
|
print(f"ERROR {no} shop {shop}: 실패 {len(bad)}건 — {bad[0]['error']}")
|
||||||
|
print(f"{mode} 끝 — 상품 {len(items)}개 확인, 바꿀/바꾼 품목 {total}건, 오류 {failed}건")
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -122,7 +122,7 @@
|
|||||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||||
|
|
||||||
<div class="cf24-editor-bar">
|
<div class="cf24-editor-bar">
|
||||||
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del]</span>
|
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del] · 이미지 번호[Ctrl+↑↓]</span>
|
||||||
<span class="cf24-editor-bar-right">
|
<span class="cf24-editor-bar-right">
|
||||||
<input class="cf24-memo" type="text" name="memo" maxlength="200"
|
<input class="cf24-memo" type="text" name="memo" maxlength="200"
|
||||||
placeholder="변경 메모 (버전 이력에 남습니다)" />
|
placeholder="변경 메모 (버전 이력에 남습니다)" />
|
||||||
@@ -156,7 +156,7 @@
|
|||||||
<details class="cf24-details">
|
<details class="cf24-details">
|
||||||
<summary>예약 적용 — 지정한 시각에 자동 반영</summary>
|
<summary>예약 적용 — 지정한 시각에 자동 반영</summary>
|
||||||
<form class="cf24-schedule-form" id="cf24-schedule-form" method="post"
|
<form class="cf24-schedule-form" id="cf24-schedule-form" method="post"
|
||||||
action="/cafe24/schedules"
|
action="/cafe24/schedules" enctype="multipart/form-data"
|
||||||
data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?">
|
data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?">
|
||||||
<input type="hidden" name="product_no" value="{{ product_no }}" />
|
<input type="hidden" name="product_no" value="{{ product_no }}" />
|
||||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||||
@@ -205,6 +205,15 @@
|
|||||||
<option value="off">중지</option>
|
<option value="off">중지</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
|
{# 대표 이미지(썸네일) — 고르면 그 시각에 교체. 파일은 DB 에 보관했다가 worker 가 올린다. #}
|
||||||
|
<div class="cf24-schedule-wide cf24-schedule-image">
|
||||||
|
<span>대표 이미지</span>
|
||||||
|
<label class="cf24-file-pick">
|
||||||
|
<input type="file" name="image" id="cf24-schedule-image" accept="image/jpeg,image/png,image/gif,image/webp" />
|
||||||
|
<span class="erp-btn erp-btn-outline">파일 선택</span>
|
||||||
|
<span class="cf24-file-name" id="cf24-schedule-image-name">변경 없음</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
<label class="cf24-schedule-wide">
|
<label class="cf24-schedule-wide">
|
||||||
<span>메모</span>
|
<span>메모</span>
|
||||||
<input class="cf24-schedule-input" type="text" name="memo" maxlength="200"
|
<input class="cf24-schedule-input" type="text" name="memo" maxlength="200"
|
||||||
@@ -221,7 +230,8 @@
|
|||||||
<a class="erp-btn erp-btn-outline" href="/cafe24/schedules">예약 목록</a>
|
<a class="erp-btn erp-btn-outline" href="/cafe24/schedules">예약 목록</a>
|
||||||
</div>
|
</div>
|
||||||
<p class="cf24-muted" style="margin:8px 0 0;">
|
<p class="cf24-muted" style="margin:8px 0 0;">
|
||||||
진열·판매만 바꾸려면 위 체크를 해제하세요. 셋 중 하나 이상은 선택해야 합니다.
|
대표 이미지·진열·판매만 바꾸려면 위 체크를 해제하세요. 넷 중 하나 이상은 선택해야 합니다.
|
||||||
|
대표 이미지는 JPG·PNG·GIF·WEBP, 10MB 이하(목록/축소 이미지는 카페24가 자동 생성).
|
||||||
</p>
|
</p>
|
||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{# 카페24 모듈 공용 상단 탭. active_tab: products | design:pc_detail | design:mobile_detail | design:swiper | schedules | system #}
|
{# 카페24 모듈 공용 상단 탭. active_tab: products | design:pc_detail | design:mobile_detail | design:swiper | schedules | system #}
|
||||||
<div class="erp-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
|
<div class="erp-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:10px;">
|
||||||
<a class="erp-btn {% if active_tab=='products' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
<a class="erp-btn {% if active_tab=='products' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
||||||
href="/cafe24/">상품관리</a>
|
href="/cafe24/">상품관리</a>
|
||||||
<a class="erp-btn {% if active_tab=='design:pc_detail' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
<a class="erp-btn {% if active_tab=='design:pc_detail' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
@@ -45,6 +45,7 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="cf24-col-no" data-sort-key="no" data-sort-type="num">번호</th>
|
<th class="cf24-col-no" data-sort-key="no" data-sort-type="num">번호</th>
|
||||||
|
<th class="cf24-col-thumb"></th>
|
||||||
<th class="cf24-col-name" data-sort-key="name" data-sort-type="text">상품명</th>
|
<th class="cf24-col-name" data-sort-key="name" data-sort-type="text">상품명</th>
|
||||||
<th class="cf24-col-flag" data-sort-key="display" data-sort-type="num">진열</th>
|
<th class="cf24-col-flag" data-sort-key="display" data-sort-type="num">진열</th>
|
||||||
<th class="cf24-col-flag" data-sort-key="selling" data-sort-type="num">판매</th>
|
<th class="cf24-col-flag" data-sort-key="selling" data-sort-type="num">판매</th>
|
||||||
@@ -60,6 +61,7 @@
|
|||||||
data-selling="{{ 1 if r.selling else 0 }}"
|
data-selling="{{ 1 if r.selling else 0 }}"
|
||||||
data-updated="{{ r.updated_date }}">
|
data-updated="{{ r.updated_date }}">
|
||||||
<td class="cf24-col-no">{{ r.product_no }}</td>
|
<td class="cf24-col-no">{{ r.product_no }}</td>
|
||||||
|
<td class="cf24-col-thumb"><img class="cf24-thumb" {% if r.thumb %}src="{{ r.thumb }}"{% endif %} loading="lazy" alt="" /></td>
|
||||||
<td class="cf24-col-name" title="{{ r.product_name }}">
|
<td class="cf24-col-name" title="{{ r.product_name }}">
|
||||||
<a href="/cafe24/?{{ qs }}selected={{ r.product_no }}">{{ r.product_name }}</a>
|
<a href="/cafe24/?{{ qs }}selected={{ r.product_no }}">{{ r.product_name }}</a>
|
||||||
</td>
|
</td>
|
||||||
@@ -122,10 +124,13 @@
|
|||||||
<div class="cf24-modal-body cf24-options-body" id="cf24-options-body"></div>
|
<div class="cf24-modal-body cf24-options-body" id="cf24-options-body"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{# 소스의 <img> 위에 마우스를 올리면 화면 오른쪽에 뜨는 미리보기 — setupCodeEditor 가 켜고 끈다. #}
|
||||||
|
<div class="cf24-img-preview" id="cf24-img-preview" hidden><div class="cf24-img-preview-name"></div><img alt="이미지를 불러올 수 없습니다" /></div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<script src="/static/cafe24-options.js?v=20261020a"></script>
|
<script src="/static/cafe24-options.js?v=20261110c"></script>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var pane = document.getElementById("cf24-editor-pane");
|
var pane = document.getElementById("cf24-editor-pane");
|
||||||
@@ -164,14 +169,42 @@
|
|||||||
last = TOKEN_RE.lastIndex;
|
last = TOKEN_RE.lastIndex;
|
||||||
if (m[1]) { out += '<span class="cf24-t-com">' + esc(m[1]) + "</span>"; continue; }
|
if (m[1]) { out += '<span class="cf24-t-com">' + esc(m[1]) + "</span>"; continue; }
|
||||||
if (m[2]) { out += '<span class="cf24-t-doc">' + esc(m[2]) + "</span>"; continue; }
|
if (m[2]) { out += '<span class="cf24-t-doc">' + esc(m[2]) + "</span>"; continue; }
|
||||||
out += '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
|
var tag = '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
|
||||||
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
|
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
|
||||||
paintAttrs(m[5]) +
|
paintAttrs(m[5]) +
|
||||||
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
|
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
|
||||||
|
out += /^img$/i.test(m[4]) ? '<span class="cf24-t-img">' + tag + "</span>" : tag;
|
||||||
}
|
}
|
||||||
return out + esc(src.slice(last));
|
return out + esc(src.slice(last));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 상대 경로는 쇼핑몰 루트 기준이다: ../img/a.jpg → https://쇼핑몰/img/a.jpg
|
||||||
|
function imgPreviewUrl(tag) {
|
||||||
|
var m = tag.match(/\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
||||||
|
var src = m && (m[1] || m[2] || m[3]);
|
||||||
|
var shop = document.getElementById("cf24-url");
|
||||||
|
if (!src || !shop) return "";
|
||||||
|
try { return new URL(src, new URL("/", shop.value)).href; }
|
||||||
|
catch (err) { return ""; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function imgFileName(url) {
|
||||||
|
var name = new URL(url).pathname.split("/").pop();
|
||||||
|
// URL 이 한글 파일명을 %XX 로 바꿔 놓으므로 되돌린다.
|
||||||
|
try { return decodeURIComponent(name); }
|
||||||
|
catch (err) { return name; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showImgPreview(url) {
|
||||||
|
var box = document.getElementById("cf24-img-preview");
|
||||||
|
var img = box.lastElementChild;
|
||||||
|
if (url && img.getAttribute("src") !== url) {
|
||||||
|
img.src = url;
|
||||||
|
box.firstElementChild.textContent = imgFileName(url);
|
||||||
|
}
|
||||||
|
box.hidden = !url;
|
||||||
|
}
|
||||||
|
|
||||||
function setupCodeEditor() {
|
function setupCodeEditor() {
|
||||||
var ta = document.getElementById("cf24-html-pc");
|
var ta = document.getElementById("cf24-html-pc");
|
||||||
var hl = document.getElementById("cf24-hl-pc");
|
var hl = document.getElementById("cf24-hl-pc");
|
||||||
@@ -337,6 +370,62 @@
|
|||||||
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
|
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Ctrl+↑/↓ — 커서가 <img> 태그 안 어디에 있든 src 파일명(.jpg/.gif/.png)의 번호를 바꾼다.
|
||||||
|
a.jpg → a_2.jpg → a_3.jpg …, a_5.jpg → a_6.jpg …. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 간다.
|
||||||
|
원래 번호는 imgStep 에 기억한다 — 이 단축키 말고 소스가 바뀌거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
|
||||||
|
조건이 안 맞으면 false — 브라우저 기본 동작을 막지 않는다. */
|
||||||
|
var imgStep = null;
|
||||||
|
|
||||||
|
function stepImgSuffix(up) {
|
||||||
|
var at = ta.selectionStart, value = ta.value;
|
||||||
|
if (at !== ta.selectionEnd) return false;
|
||||||
|
|
||||||
|
var tagRe = /<img\s(?:"[^"]*"|'[^']*'|[^>"'])*>/gi, tag;
|
||||||
|
while ((tag = tagRe.exec(value)) && tagRe.lastIndex <= at);
|
||||||
|
if (!tag || tag.index >= at) return false;
|
||||||
|
|
||||||
|
var src = tag[0].match(/\ssrc\s*=\s*(?:"([^"]*)|'([^']*)|([^\s>"']+))/i);
|
||||||
|
var path = src && (src[1] || src[2] || src[3]);
|
||||||
|
var file = path && path.match(/^(.*)\.(?:jpg|gif|png)(?=[?#]|$)/i);
|
||||||
|
if (!file) return false;
|
||||||
|
|
||||||
|
var ext = tag.index + src.index + src[0].length - path.length + file[1].length; // 확장자 시작 위치
|
||||||
|
var num = file[1].match(/_(\d{1,15})$/); // 16자리부터는 숫자 계산이 어긋나 번호로 보지 않는다
|
||||||
|
var orig = imgStep && imgStep.value === value && imgStep.ext === ext ? imgStep.orig : (num ? num[1] : "");
|
||||||
|
var n = num ? Number(num[1]) : 1;
|
||||||
|
if (!up && n <= (orig ? Number(orig) : 1)) return true; // 원래 번호 아래로는 안 간다
|
||||||
|
|
||||||
|
var next = up ? n + 1 : n - 1;
|
||||||
|
// a_01 → a_02 처럼 원래 자릿수를 유지한다.
|
||||||
|
var text = !orig && next < 2 ? "" : "_" + String(next).padStart(orig.length, "0");
|
||||||
|
var from = ext - (num ? num[0].length : 0);
|
||||||
|
var caret = at >= ext ? at + text.length - (ext - from) : at <= from ? at : from + text.length;
|
||||||
|
applyEdit(from, ext, text, caret, caret);
|
||||||
|
imgStep = { value: ta.value, ext: from + text.length, orig: orig };
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 이미지 미리보기 — 맨 위 textarea 를 판정에서 잠깐 빼고 색칠 층의 <img> 를 찾는다.
|
||||||
|
글자 폭을 계산하지 않아 한글·탭·여러 줄 태그에서도 위치가 어긋나지 않는다.
|
||||||
|
shortcut: HL_LIMIT 초과 소스는 색칠을 안 해 미리보기도 안 뜬다, 그런 상품이 나오면 글자 위치 계산으로 교체. */
|
||||||
|
var hoverTag = null;
|
||||||
|
|
||||||
|
function setHoverTag(tag) {
|
||||||
|
if (tag === hoverTag) return;
|
||||||
|
if (hoverTag) hoverTag.classList.remove("cf24-t-img-on");
|
||||||
|
if (tag) tag.classList.add("cf24-t-img-on");
|
||||||
|
hoverTag = tag;
|
||||||
|
showImgPreview(tag ? imgPreviewUrl(tag.textContent) : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
ta.addEventListener("mousemove", function (e) {
|
||||||
|
ta.style.pointerEvents = "none";
|
||||||
|
var el = document.elementFromPoint(e.clientX, e.clientY);
|
||||||
|
ta.style.pointerEvents = "";
|
||||||
|
setHoverTag(el && el.closest(".cf24-t-img"));
|
||||||
|
});
|
||||||
|
ta.addEventListener("mouseleave", function () { setHoverTag(null); });
|
||||||
|
|
||||||
ta.addEventListener("scroll", sync);
|
ta.addEventListener("scroll", sync);
|
||||||
ta.addEventListener("input", function () { dirty = true; refresh(); });
|
ta.addEventListener("input", function () { dirty = true; refresh(); });
|
||||||
ta.addEventListener("keydown", function (e) {
|
ta.addEventListener("keydown", function (e) {
|
||||||
@@ -356,6 +445,10 @@
|
|||||||
else moveLines(isDown);
|
else moveLines(isDown);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (isUp || isDown) && stepImgSuffix(isUp)) {
|
||||||
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Shift+Delete — 줄 삭제. (윈도우 기본 동작인 "잘라내기"를 대신한다)
|
// Shift+Delete — 줄 삭제. (윈도우 기본 동작인 "잘라내기"를 대신한다)
|
||||||
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey &&
|
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey &&
|
||||||
(e.key === "Delete" || e.code === "Delete")) {
|
(e.key === "Delete" || e.code === "Delete")) {
|
||||||
@@ -470,6 +563,17 @@
|
|||||||
// 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다.
|
// 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다.
|
||||||
var schedForm = pane.querySelector("#cf24-schedule-form");
|
var schedForm = pane.querySelector("#cf24-schedule-form");
|
||||||
if (schedForm) {
|
if (schedForm) {
|
||||||
|
var schedImg = schedForm.querySelector("#cf24-schedule-image");
|
||||||
|
var schedImgName = schedForm.querySelector("#cf24-schedule-image-name");
|
||||||
|
if (schedImg) schedImg.addEventListener("change", function () {
|
||||||
|
var f = schedImg.files && schedImg.files[0];
|
||||||
|
if (f && f.size > 10 * 1024 * 1024) {
|
||||||
|
window.erpAlert("10MB 를 넘는 파일은 올릴 수 없습니다.");
|
||||||
|
schedImg.value = "";
|
||||||
|
f = null;
|
||||||
|
}
|
||||||
|
schedImgName.textContent = f ? f.name + " (" + Math.round(f.size / 1024) + "KB) — 그 시각에 교체" : "변경 없음";
|
||||||
|
});
|
||||||
schedForm.addEventListener("submit", function (e) {
|
schedForm.addEventListener("submit", function (e) {
|
||||||
var box = document.getElementById("cf24-html-pc");
|
var box = document.getElementById("cf24-html-pc");
|
||||||
var holder = document.getElementById("cf24-schedule-html");
|
var holder = document.getElementById("cf24-schedule-html");
|
||||||
@@ -485,7 +589,8 @@
|
|||||||
// 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다.
|
// 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다.
|
||||||
// (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다)
|
// (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다)
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
window.erpConfirm(schedForm.dataset.confirm).then(function (ok) {
|
var imgFile = schedImg && schedImg.files && schedImg.files[0];
|
||||||
|
window.erpConfirm(schedForm.dataset.confirm + (imgFile ? "\n\n대표 이미지: 「" + imgFile.name + "」(으)로 교체" : "")).then(function (ok) {
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다.
|
dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다.
|
||||||
schedForm.submit();
|
schedForm.submit();
|
||||||
@@ -824,6 +929,7 @@
|
|||||||
window.erpAlert("상품명은 비울 수 없습니다.");
|
window.erpAlert("상품명은 비울 수 없습니다.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if ("price" in payload) lines.push("\n※ 옵션 품목은 판매 가격이 그대로이도록 추가금액을 함께 조정합니다.");
|
||||||
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
|
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
|
||||||
.then(function (ok) {
|
.then(function (ok) {
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
@@ -838,7 +944,10 @@
|
|||||||
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
|
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
|
||||||
commitValues(form);
|
commitValues(form);
|
||||||
if (p.product_name) paintTitle(p.product_name);
|
if (p.product_name) paintTitle(p.product_name);
|
||||||
setMsg(msg, (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.", "is-ok");
|
var done = (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.";
|
||||||
|
if (data.variants_shifted) done += " 품목 " + data.variants_shifted + "건 추가금액 조정.";
|
||||||
|
if (data.variants_error) setMsg(msg, done + " " + data.variants_error, "is-err");
|
||||||
|
else setMsg(msg, done, "is-ok");
|
||||||
})
|
})
|
||||||
.catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); })
|
.catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); })
|
||||||
.then(function () { btn.disabled = false; });
|
.then(function () { btn.disabled = false; });
|
||||||
@@ -864,6 +973,8 @@
|
|||||||
if (link) { link.href = p.detail_image; link.classList.remove("is-hidden"); }
|
if (link) { link.href = p.detail_image; link.classList.remove("is-hidden"); }
|
||||||
if (empty) empty.classList.add("is-hidden");
|
if (empty) empty.classList.add("is-hidden");
|
||||||
}
|
}
|
||||||
|
var thumb = document.querySelector('#cf24-list tr.cf24-row[data-no="' + no + '"] .cf24-thumb');
|
||||||
|
if (thumb && (p.tiny_image || p.detail_image)) thumb.src = bust(p.tiny_image || p.detail_image);
|
||||||
root.querySelectorAll("[data-image-key]").forEach(function (el) {
|
root.querySelectorAll("[data-image-key]").forEach(function (el) {
|
||||||
var v = p[el.dataset.imageKey];
|
var v = p[el.dataset.imageKey];
|
||||||
if (!v) return;
|
if (!v) return;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
@@ -37,7 +37,7 @@
|
|||||||
<th style="width:130px;">예정 시각</th>
|
<th style="width:130px;">예정 시각</th>
|
||||||
<th style="width:66px;">상품</th>
|
<th style="width:66px;">상품</th>
|
||||||
<th>상품명</th>
|
<th>상품명</th>
|
||||||
<th style="width:150px;">적용 내용</th>
|
<th style="width:170px;">적용 내용</th>
|
||||||
<th style="width:96px;">상태</th>
|
<th style="width:96px;">상태</th>
|
||||||
<th>메모 / 오류</th>
|
<th>메모 / 오류</th>
|
||||||
<th style="width:130px;">등록자</th>
|
<th style="width:130px;">등록자</th>
|
||||||
@@ -53,7 +53,8 @@
|
|||||||
<a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a>
|
<a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a>
|
||||||
</td>
|
</td>
|
||||||
<td>{{ r.product_name or '—' }}</td>
|
<td>{{ r.product_name or '—' }}</td>
|
||||||
<td class="cf24-nowrap">{{ r.action_label }}</td>
|
<td class="cf24-nowrap">{{ r.action_label }}
|
||||||
|
{% if r.image_type %}<a href="/cafe24/schedules/{{ r.id }}/image" target="_blank" rel="noopener" title="{{ r.image_name }}"><img class="cf24-sched-img" src="/cafe24/schedules/{{ r.id }}/image" alt="{{ r.image_name }}" loading="lazy" /></a>{% endif %}</td>
|
||||||
<td class="cf24-nowrap">
|
<td class="cf24-nowrap">
|
||||||
{% 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>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|||||||
@@ -396,6 +396,8 @@ class FakeCafe24:
|
|||||||
self._variant_puts += 1
|
self._variant_puts += 1
|
||||||
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
|
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
|
||||||
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
|
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
|
||||||
|
if (json or {}).get("shop_no", 1) != 1: # 다른 쇼핑몰 — 기본몰 상태는 그대로
|
||||||
|
return {"variants": [dict(r) for r in (json or {}).get("requests") or []]}
|
||||||
out = []
|
out = []
|
||||||
for r in (json or {}).get("requests") or []:
|
for r in (json or {}).get("requests") or []:
|
||||||
for var in self.variants:
|
for var in self.variants:
|
||||||
@@ -411,6 +413,13 @@ class FakeCafe24:
|
|||||||
|
|
||||||
def post(self, path, *, json=None, **kw):
|
def post(self, path, *, json=None, **kw):
|
||||||
self.calls.append(("POST", path, json))
|
self.calls.append(("POST", path, json))
|
||||||
|
if path == f"/admin/products/{self.product_no}/images": # 대표이미지 등록(A 타입)
|
||||||
|
self._tick()
|
||||||
|
n = sum(1 for c in self.calls if c[1] == path)
|
||||||
|
image = {k: f"/web/product/{k.split('_')[0]}/{self.product_no}_{n}.png"
|
||||||
|
for k in ("detail_image", "list_image", "tiny_image", "small_image")}
|
||||||
|
self.state.update(image)
|
||||||
|
return {"image": image}
|
||||||
out = self._options_call("POST", path, json)
|
out = self._options_call("POST", path, json)
|
||||||
return copy.deepcopy(out) if out is not None else {}
|
return copy.deepcopy(out) if out is not None else {}
|
||||||
|
|
||||||
|
|||||||
@@ -649,6 +649,9 @@ def test_describe_schedule_action():
|
|||||||
assert store.describe_schedule_action(
|
assert store.describe_schedule_action(
|
||||||
has_html=False, set_display=None, set_selling=None
|
has_html=False, set_display=None, set_selling=None
|
||||||
) == "없음"
|
) == "없음"
|
||||||
|
assert store.describe_schedule_action(
|
||||||
|
has_html=True, set_display=None, set_selling=None, has_image=True
|
||||||
|
) == "대표이미지 · 상세페이지"
|
||||||
|
|
||||||
|
|
||||||
def test_normalize_schedule_status():
|
def test_normalize_schedule_status():
|
||||||
@@ -1083,6 +1086,22 @@ def test_resolve_description_accepts_iso_created_at():
|
|||||||
assert (html, state) == ("NEW", store.SYNC_PENDING)
|
assert (html, state) == ("NEW", store.SYNC_PENDING)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_shop_nos():
|
||||||
|
assert store.parse_shop_nos(None) == [1]
|
||||||
|
assert store.parse_shop_nos("2, 3,1,x,0,3") == [1, 2, 3]
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_flag_sync():
|
||||||
|
from app.modules.cafe24.sync_variant_flags import plan_flag_sync
|
||||||
|
|
||||||
|
base = [{"variant_code": "A", "display": True, "selling": False},
|
||||||
|
{"variant_code": "B", "display": True, "selling": True},
|
||||||
|
{"variant_code": "C", "display": False, "selling": False}]
|
||||||
|
shop = [{"variant_code": "A", "display": "F", "selling": "F"},
|
||||||
|
{"variant_code": "B", "display": "T", "selling": "T"}] # C 는 그 쇼핑몰에 없음
|
||||||
|
assert plan_flag_sync(base, shop) == [{"variant_code": "A", "display": "T"}]
|
||||||
|
|
||||||
|
|
||||||
def test_parse_grace_minutes():
|
def test_parse_grace_minutes():
|
||||||
assert store.parse_grace_minutes("30") == 30
|
assert store.parse_grace_minutes("30") == 30
|
||||||
assert store.parse_grace_minutes("") == store.DEFAULT_READ_LAG_GRACE_MIN
|
assert store.parse_grace_minutes("") == store.DEFAULT_READ_LAG_GRACE_MIN
|
||||||
@@ -1261,21 +1280,18 @@ def test_build_update_options_request_rejects_count_mismatch():
|
|||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise AssertionError(edited)
|
raise AssertionError(edited)
|
||||||
# 덧붙이기는 allow_append 일 때만
|
# 덧붙이기 거부 — 카페24 PUT 은 옵션값 추가를 무시한다(저장 후 사라짐). 재생성으로 안내.
|
||||||
more = [{"option_name": "A", "option_value": [{"option_text": "1"}, {"option_text": "2", "option_image_file": "https://d/2.png"}]}]
|
more = [{"option_name": "A", "option_value": [{"option_text": "1"}, {"option_text": "2", "option_image_file": "https://d/2.png"}]}]
|
||||||
try:
|
try:
|
||||||
store.build_update_options_request(original, more)
|
store.build_update_options_request(original, more)
|
||||||
except ValueError:
|
except ValueError as exc:
|
||||||
pass
|
assert "옵션 재생성" in str(exc)
|
||||||
else:
|
else:
|
||||||
raise AssertionError("append without flag accepted")
|
raise AssertionError("append accepted")
|
||||||
body = store.build_update_options_request(original, more, allow_append=True)
|
# 줄이기도 거부 (위치 짝맞춤으로 이름이 밀린다)
|
||||||
assert body["original_options"][0]["option_value"] == [{"option_text": "1"}]
|
|
||||||
assert body["options"][0]["option_value"] == [{"option_text": "1"}, {"option_text": "2", "option_image_file": "https://d/2.png"}]
|
|
||||||
# 줄이기는 allow_append 여도 거부 (위치 짝맞춤으로 이름이 밀린다)
|
|
||||||
two = [{"option_name": "A", "option_value": [{"option_text": "1"}, {"option_text": "2"}]}]
|
two = [{"option_name": "A", "option_value": [{"option_text": "1"}, {"option_text": "2"}]}]
|
||||||
try:
|
try:
|
||||||
store.build_update_options_request(two, original, allow_append=True)
|
store.build_update_options_request(two, original)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
@@ -1288,6 +1304,38 @@ def test_delete_variant_wrapper():
|
|||||||
assert client.calls[-1][:2] == ("DELETE", "/admin/products/7/variants/P000000R000A")
|
assert client.calls[-1][:2] == ("DELETE", "/admin/products/7/variants/P000000R000A")
|
||||||
|
|
||||||
|
|
||||||
|
def test_shift_additional_amounts_keeps_sale_price():
|
||||||
|
"""판매가 7900 → 12700: 품목 판매 가격(판매가+추가금액)은 그대로, 추가금액만 -4800."""
|
||||||
|
variants = [{"variant_code": "P000000R000A", "additional_amount": "0.00"},
|
||||||
|
{"variant_code": "P000000R000B", "additional_amount": "18000.00"}]
|
||||||
|
assert store.shift_additional_amounts(variants, "7900.00", "12700.00") == [
|
||||||
|
{"variant_code": "P000000R000A", "additional_amount": "-4800"},
|
||||||
|
{"variant_code": "P000000R000B", "additional_amount": "13200"},
|
||||||
|
]
|
||||||
|
assert store.shift_additional_amounts(variants, "7900.00", "7900") == []
|
||||||
|
assert store.shift_additional_amounts(variants, "", "7900") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_keep_variant_sale_prices_puts_shifted_amounts():
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from app.modules.cafe24 import routes_product_info as rpi
|
||||||
|
|
||||||
|
client = _RouteClient({
|
||||||
|
"GET /admin/products/7/options": {"option": {"has_option": "T", "options": []}},
|
||||||
|
"GET /admin/products/7/variants": {"variants": [
|
||||||
|
{"variant_code": "P000000R000A", "additional_amount": "6000.00"}]},
|
||||||
|
"PUT /admin/products/7/variants": {"variants": [
|
||||||
|
{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]},
|
||||||
|
})
|
||||||
|
st = fakes.MemoryStore()
|
||||||
|
out = rpi._keep_variant_sale_prices(st, SimpleNamespace(client=client), 7, "7900.00", "12900.00")
|
||||||
|
assert out["count"] == 1 and out["error"] == ""
|
||||||
|
put = [c for c in client.calls if c[0] == "PUT"][-1]
|
||||||
|
assert put[2]["requests"] == [{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]
|
||||||
|
assert st.get_write_snapshot(7)["variants"]["data"]["P000000R000A"]["additional_amount"] == "1000.00"
|
||||||
|
|
||||||
|
|
||||||
def test_build_variant_updates():
|
def test_build_variant_updates():
|
||||||
rows = [
|
rows = [
|
||||||
{"variant_code": "p000000r000a", "custom_variant_code": " ABC ", "additional_amount": "1,000", "display": "on"},
|
{"variant_code": "p000000r000a", "custom_variant_code": " ABC ", "additional_amount": "1,000", "display": "on"},
|
||||||
@@ -1305,6 +1353,18 @@ def test_build_variant_updates():
|
|||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise AssertionError("bad code accepted")
|
raise AssertionError("bad code accepted")
|
||||||
|
# 재고관리 사용 · 수량 · 품절표시
|
||||||
|
assert store.build_variant_updates([
|
||||||
|
{"variant_code": "P000000R000A", "use_inventory": "on", "quantity": "1,200", "display_soldout": "off"},
|
||||||
|
{"variant_code": "P000000R000B", "quantity": ""}, # 빈 수량 → 변경 없음
|
||||||
|
]) == [{"variant_code": "P000000R000A", "use_inventory": "T", "display_soldout": "F", "quantity": 1200}]
|
||||||
|
for bad in ("-1", "x"):
|
||||||
|
try:
|
||||||
|
store.build_variant_updates([{"variant_code": "P000000R000A", "quantity": bad}])
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError(bad)
|
||||||
# 드래그 정렬 → display_order (1~300)
|
# 드래그 정렬 → display_order (1~300)
|
||||||
assert store.build_variant_updates([{"variant_code": "P000000R000A", "display_order": "3"}]) == [
|
assert store.build_variant_updates([{"variant_code": "P000000R000A", "display_order": "3"}]) == [
|
||||||
{"variant_code": "P000000R000A", "display_order": 3}
|
{"variant_code": "P000000R000A", "display_order": 3}
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ from app.timezone import now_kst
|
|||||||
|
|
||||||
from . import store, writes
|
from . import store, writes
|
||||||
from .common import read_lag_grace_minutes
|
from .common import read_lag_grace_minutes
|
||||||
|
from .routes_products import load_product
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.worker")
|
logger = logging.getLogger("cafe24.worker")
|
||||||
|
|
||||||
@@ -77,9 +78,28 @@ def _summary(row: dict[str, Any]) -> str:
|
|||||||
has_html=bool(row.get("revision_id")),
|
has_html=bool(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"),
|
||||||
|
has_image=bool(row.get("image_type")),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_image(st: Any, api: Any, product_no: int, data: bytes, content_type: str) -> str:
|
||||||
|
"""예약 대표 이미지 교체(routes_product_info.product_image 와 같은 순서). 반환: 새 detail_image.
|
||||||
|
|
||||||
|
상세페이지·진열/판매보다 **먼저** 한다 — 뒤 단계가 실패해 재시도되면 같은 이미지를 한 번 더
|
||||||
|
올릴 뿐이라 안전하고, 앞 단계(시도 기록)가 SUCCESS 로 복구된 뒤 이미지가 빠지는 일이 없다.
|
||||||
|
"""
|
||||||
|
current, _ = load_product(st, api, product_no)
|
||||||
|
if not current:
|
||||||
|
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
images = products.set_main_image(api.client, product_no, data, content_type=content_type)
|
||||||
|
if not images.get("detail_image"):
|
||||||
|
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||||
|
writes.remember_product_write(
|
||||||
|
st, product_no, {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||||
|
)
|
||||||
|
return str(images["detail_image"])
|
||||||
|
|
||||||
|
|
||||||
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
|
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
|
||||||
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
|
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
|
||||||
retry_count = int(row.get("retry_count") or 0)
|
retry_count = int(row.get("retry_count") or 0)
|
||||||
@@ -113,6 +133,8 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
|||||||
def fence() -> bool:
|
def fence() -> bool:
|
||||||
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
||||||
|
|
||||||
|
image_type = str(row.get("image_type") or "")
|
||||||
|
new_image = ""
|
||||||
try:
|
try:
|
||||||
html: str | None = None
|
html: str | None = None
|
||||||
if revision_id:
|
if revision_id:
|
||||||
@@ -122,17 +144,26 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
|||||||
html = str(revision.get("html_content") or "")
|
html = str(revision.get("html_content") or "")
|
||||||
if not html.strip():
|
if not html.strip():
|
||||||
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||||
|
image = st.get_schedule_image(schedule_id) if image_type else b""
|
||||||
|
if image_type and not image:
|
||||||
|
raise Cafe24Error("예약해 둔 대표 이미지 파일을 찾을 수 없습니다.")
|
||||||
with writes.write_lock(
|
with writes.write_lock(
|
||||||
st, writes.product_lock_key(product_no), actor=ACTOR,
|
st, writes.product_lock_key(product_no), actor=ACTOR,
|
||||||
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
||||||
) as lock:
|
) as lock:
|
||||||
outcome = writes.write_product(
|
if image:
|
||||||
st, api, product_no,
|
if not fence():
|
||||||
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
raise writes.WriteBusy("예약 lease 를 잃었습니다 — 다른 worker 가 처리합니다.")
|
||||||
set_display=set_display, set_selling=set_selling,
|
new_image = _apply_image(st, api, product_no, image, image_type)
|
||||||
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
|
outcome = writes.WriteOutcome()
|
||||||
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
|
if html is not None or set_display is not None or set_selling is not None:
|
||||||
)
|
outcome = writes.write_product(
|
||||||
|
st, api, product_no,
|
||||||
|
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
||||||
|
set_display=set_display, set_selling=set_selling,
|
||||||
|
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
|
||||||
|
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
|
||||||
|
)
|
||||||
except writes.WriteSetupError as exc:
|
except writes.WriteSetupError as exc:
|
||||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(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))
|
next_retry_at=now_kst() + timedelta(seconds=SETUP_RETRY_SECONDS))
|
||||||
@@ -171,6 +202,7 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
|||||||
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
|
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
|
||||||
schedule_id=schedule_id, result="SUCCESS",
|
schedule_id=schedule_id, result="SUCCESS",
|
||||||
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
|
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
|
||||||
|
+ (f" / 대표이미지 → '{new_image}'" if new_image else "")
|
||||||
+ (f" / {note}" if note else ""),
|
+ (f" / {note}" if note else ""),
|
||||||
)
|
)
|
||||||
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||||
|
|||||||
@@ -75,11 +75,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
|||||||
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||||
"""로그인+권한+store 점검을 한 번에. 페이지 핸들러 진입부에서 사용."""
|
"""로그인+권한+store 점검을 한 번에. 페이지 핸들러 진입부에서 사용."""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "cupang"):
|
if not has_module(user, "cupang"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261111f" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
<link rel="stylesheet" href="/static/cupang.css?v=20261023d" />
|
<link rel="stylesheet" href="/static/cupang.css?v=20261023d" />
|
||||||
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||||
@@ -249,7 +249,7 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<script src="/static/project.js?v=20261027a" defer></script>
|
<script src="/static/project.js?v=20261111d" defer></script>
|
||||||
<script src="/static/cupang-outbound.js?v=20261023d" defer></script>
|
<script src="/static/cupang-outbound.js?v=20261023d" defer></script>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
|
|||||||
@@ -10,4 +10,5 @@
|
|||||||
- 작업 상태 토글(`dispatch_logs` 기록).
|
- 작업 상태 토글(`dispatch_logs` 기록).
|
||||||
- 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의.
|
- 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의.
|
||||||
- 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함.
|
- 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함.
|
||||||
|
- 기간별 발송 수량 엑셀(`/dispatch/period-export`, **수퍼 관리자 전용**): 날짜별·아이템별 수량(`_N` 배수 반영, 세트는 BOM 으로 낱개 분해) + 아이템×날짜 요약 시트 + 세트×날짜 요약 시트(낱개로 풀기 전 세트 수량).
|
||||||
- 엑셀은 openpyxl 파싱/생성.
|
- 엑셀은 openpyxl 파싱/생성.
|
||||||
|
|||||||
@@ -309,6 +309,41 @@ class DispatchStore:
|
|||||||
for r in rows
|
for r in rows
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def shipped_by_date_range(
|
||||||
|
self, *, date_from: str, date_to: str
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""기간(양끝 포함) 날짜·SKU별 합산 수량 — 기간별 발송 수량 엑셀용.
|
||||||
|
|
||||||
|
반환: [{"dispatch_date": "YYYY-MM-DD", "seller_sku", "product_name", "qty"}].
|
||||||
|
_N 배수 반영은 호출부(export)에서 한다.
|
||||||
|
"""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT b.dispatch_date, i.seller_sku,
|
||||||
|
MAX(i.product_name) AS product_name,
|
||||||
|
SUM(i.quantity)::int AS qty
|
||||||
|
FROM dispatch_items i
|
||||||
|
JOIN dispatch_parcels p ON p.id = i.parcel_id
|
||||||
|
JOIN dispatch_batches b ON b.id = p.batch_id
|
||||||
|
WHERE b.dispatch_date BETWEEN %s AND %s
|
||||||
|
GROUP BY b.dispatch_date, i.seller_sku
|
||||||
|
ORDER BY b.dispatch_date ASC, i.seller_sku ASC
|
||||||
|
""",
|
||||||
|
(date_from, date_to),
|
||||||
|
).fetchall()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"dispatch_date": r["dispatch_date"].isoformat()
|
||||||
|
if isinstance(r["dispatch_date"], date)
|
||||||
|
else str(r["dispatch_date"] or ""),
|
||||||
|
"seller_sku": r["seller_sku"] or "",
|
||||||
|
"product_name": r["product_name"] or "",
|
||||||
|
"qty": int(r["qty"] or 0),
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 말레이시아 재고 차감 1회성 가드
|
# 말레이시아 재고 차감 1회성 가드
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
|
|||||||
@@ -246,6 +246,158 @@ def stock_filename(dispatch_date: str) -> str:
|
|||||||
return f"{stamp}_sabangnet_outbound.xlsx"
|
return f"{stamp}_sabangnet_outbound.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
# ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
|
||||||
|
def missing_set_boms(
|
||||||
|
rows: list[dict[str, Any]], set_bom: dict[str, list[dict[str, Any]]]
|
||||||
|
) -> list[str]:
|
||||||
|
"""세트(MY-)인데 BOM 이 없어 낱개로 풀 수 없는 코드 목록(정렬)."""
|
||||||
|
return sorted({
|
||||||
|
b for b in (split_sku(r.get("seller_sku", ""))[0].strip().upper() for r in rows)
|
||||||
|
if b.startswith(_SET_PREFIX) and b not in set_bom
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate_shipped(
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
name_map: dict[str, str] | None = None,
|
||||||
|
set_bom: dict[str, list[dict[str, Any]]] | None = None,
|
||||||
|
) -> tuple[list[str], dict[str, str], dict[tuple[str, str], int]]:
|
||||||
|
"""날짜·SKU별 합산 행 → (날짜목록, {코드: 상품명}, {(날짜, 코드): 수량}).
|
||||||
|
|
||||||
|
seller_sku 의 _N 접미사는 배수로 곱해 실제 아이템코드로 합친다
|
||||||
|
(예: MT-0320_3 × 2 → MT-0320 6개). 세트(set_bom 에 있는 코드)는 구성 낱개로
|
||||||
|
풀어 (수량 × 구성수량) 을 낱개 코드에 더한다.
|
||||||
|
"""
|
||||||
|
name_map = name_map or {}
|
||||||
|
set_bom = set_bom or {}
|
||||||
|
dates: set[str] = set()
|
||||||
|
names: dict[str, str] = {}
|
||||||
|
qty: dict[tuple[str, str], int] = {}
|
||||||
|
|
||||||
|
def _add(d: str, code: str, n: int, fallback: str) -> None:
|
||||||
|
key = (d, code)
|
||||||
|
qty[key] = qty.get(key, 0) + n
|
||||||
|
if not names.get(code):
|
||||||
|
names[code] = resolve_product_name(code, name_map, fallback=fallback)
|
||||||
|
|
||||||
|
for r in rows:
|
||||||
|
base, mult = split_sku(r.get("seller_sku", ""))
|
||||||
|
code = base.strip().upper()
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
pieces = int(r.get("qty", 0) or 0) * mult
|
||||||
|
if pieces <= 0:
|
||||||
|
continue
|
||||||
|
d = r.get("dispatch_date", "") or ""
|
||||||
|
dates.add(d)
|
||||||
|
comps = set_bom.get(code)
|
||||||
|
if comps: # 세트 → 낱개 분해
|
||||||
|
for c in comps:
|
||||||
|
cc = str(c.get("component_code", "")).strip().upper()
|
||||||
|
n = pieces * int(c.get("component_qty", 0) or 0)
|
||||||
|
if cc and n > 0:
|
||||||
|
_add(d, cc, n, "")
|
||||||
|
else:
|
||||||
|
_add(d, code, pieces, r.get("product_name", "") or "")
|
||||||
|
return sorted(dates), names, qty
|
||||||
|
|
||||||
|
|
||||||
|
def build_period_xlsx(
|
||||||
|
*,
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
date_from: str,
|
||||||
|
date_to: str,
|
||||||
|
name_map: dict[str, str] | None = None,
|
||||||
|
set_bom: dict[str, list[dict[str, Any]]] | None = None,
|
||||||
|
) -> bytes:
|
||||||
|
"""기간별 발송 수량 xlsx(세트는 낱개로 풀어 합산). 시트 3개.
|
||||||
|
|
||||||
|
- 「날짜별」: 발송 날짜 / 아이템 코드 / 상품이름 / 수량 (날짜·코드 오름차순, 맨 끝 합계)
|
||||||
|
- 「아이템별 요약」: 아이템 코드 / 상품이름 / 날짜1..N / 합계 (맨 끝 날짜별 합계 행)
|
||||||
|
- 「세트별 요약」: 세트 코드 / 상품이름 / 날짜1..N / 합계 — 낱개로 풀기 전 세트 단위 수량
|
||||||
|
"""
|
||||||
|
from openpyxl import Workbook # noqa: WPS433
|
||||||
|
from openpyxl.styles import Alignment, Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
set_bom = set_bom or {}
|
||||||
|
dates, names, qty = aggregate_shipped(rows, name_map, set_bom)
|
||||||
|
codes = sorted(names)
|
||||||
|
# 세트 행만 BOM 없이 다시 합산하면 세트 단위 수량이 된다(_N 배수 반영은 같다).
|
||||||
|
set_rows = [r for r in rows if split_sku(r.get("seller_sku", ""))[0].strip().upper() in set_bom]
|
||||||
|
_sd, set_names, set_qty = aggregate_shipped(set_rows, name_map)
|
||||||
|
|
||||||
|
head_fill = PatternFill("solid", fgColor="E2E8F0")
|
||||||
|
head_font = Font(bold=True)
|
||||||
|
bold = Font(bold=True)
|
||||||
|
|
||||||
|
def _style_head(ws: Any) -> None:
|
||||||
|
for cell in ws[1]:
|
||||||
|
cell.fill = head_fill
|
||||||
|
cell.font = head_font
|
||||||
|
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
wb = Workbook()
|
||||||
|
|
||||||
|
# 시트 1 — 날짜별 목록
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "날짜별"
|
||||||
|
headers = ["발송 날짜", "아이템 코드", "상품이름", "수량"]
|
||||||
|
ws.append(headers)
|
||||||
|
total = 0
|
||||||
|
for d in dates:
|
||||||
|
for code in codes:
|
||||||
|
n = qty.get((d, code))
|
||||||
|
if not n:
|
||||||
|
continue
|
||||||
|
ws.append([d, code, names.get(code, ""), n])
|
||||||
|
total += n
|
||||||
|
ws.append(["합계", "", "", total])
|
||||||
|
for cell in ws[ws.max_row]:
|
||||||
|
cell.font = bold
|
||||||
|
_style_head(ws)
|
||||||
|
_autosize(ws, headers)
|
||||||
|
|
||||||
|
# 시트 2·3 — 코드(행) × 날짜(열) 요약. 날짜 열은 두 시트 모두 전체 발송 날짜로 맞춘다.
|
||||||
|
def _pivot(title: str, code_label: str, p_names: dict[str, str],
|
||||||
|
p_qty: dict[tuple[str, str], int]) -> None:
|
||||||
|
p_codes = sorted(p_names)
|
||||||
|
ws2 = wb.create_sheet(title)
|
||||||
|
headers2 = [code_label, "상품이름", *dates, "합계"]
|
||||||
|
ws2.append(headers2)
|
||||||
|
for code in p_codes:
|
||||||
|
per_day = [p_qty.get((d, code), 0) for d in dates]
|
||||||
|
ws2.append([code, p_names.get(code, ""), *[n or None for n in per_day], sum(per_day)])
|
||||||
|
day_totals = [sum(p_qty.get((d, c), 0) for c in p_codes) for d in dates]
|
||||||
|
ws2.append(["합계", "", *day_totals, sum(day_totals)])
|
||||||
|
for cell in ws2[ws2.max_row]:
|
||||||
|
cell.font = bold
|
||||||
|
_style_head(ws2)
|
||||||
|
ws2.freeze_panes = "C2"
|
||||||
|
_autosize(ws2, headers2)
|
||||||
|
for i in range(3, len(headers2) + 1): # 날짜 열은 좁게 고정
|
||||||
|
ws2.column_dimensions[get_column_letter(i)].width = 12
|
||||||
|
|
||||||
|
_pivot("아이템별 요약", "아이템 코드", names, qty)
|
||||||
|
_pivot("세트별 요약", "세트 코드", set_names, set_qty)
|
||||||
|
|
||||||
|
wb.properties.title = f"말레이시아 발송 수량 {date_from} ~ {date_to}"
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def period_filename(date_from: str, date_to: str) -> str:
|
||||||
|
"""기간별 발송 수량 파일명: 2026.10.01-2026.10.28_shipped_qty.xlsx."""
|
||||||
|
def _stamp(v: str) -> str:
|
||||||
|
d = _parse_date(v)
|
||||||
|
return d.strftime("%Y.%m.%d") if d else (v or "").strip()
|
||||||
|
|
||||||
|
return f"{_stamp(date_from)}-{_stamp(date_to)}_shipped_qty.xlsx"
|
||||||
|
|
||||||
|
|
||||||
def _cell(value: Any) -> Any:
|
def _cell(value: Any) -> Any:
|
||||||
"""송장/전화번호 등이 숫자로 보이면 엑셀이 과학표기/반올림 하므로 문자열 보존."""
|
"""송장/전화번호 등이 숫자로 보이면 엑셀이 과학표기/반올림 하므로 문자열 보존."""
|
||||||
if isinstance(value, int):
|
if isinstance(value, int):
|
||||||
|
|||||||
@@ -131,11 +131,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
|||||||
def _guard(request: Request):
|
def _guard(request: Request):
|
||||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "dispatch"):
|
if not has_module(user, "dispatch"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -477,6 +477,72 @@ def stock_export(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_PERIOD_MAX_DAYS = 366
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/period-export")
|
||||||
|
def period_export(
|
||||||
|
request: Request,
|
||||||
|
date_from: str,
|
||||||
|
date_to: str,
|
||||||
|
user: dict[str, Any] = Depends(_require_user),
|
||||||
|
) -> Response:
|
||||||
|
"""기간(양끝 포함) 날짜별·아이템별 발송 수량 xlsx — 슈퍼 관리자 전용.
|
||||||
|
|
||||||
|
seller_sku 의 _N 배수 반영, 세트(MY-)는 itemcode_db BOM 으로 낱개로 풀어 합산.
|
||||||
|
"""
|
||||||
|
if not bool(user.get("is_super_admin")):
|
||||||
|
raise HTTPException(status_code=403, detail="기간별 발송 수량은 슈퍼 관리자만 받을 수 있습니다.")
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
raise HTTPException(status_code=503, detail="dispatch_db 미설정")
|
||||||
|
d_from = export._parse_date(date_from)
|
||||||
|
d_to = export._parse_date(date_to)
|
||||||
|
if d_from is None or d_to is None:
|
||||||
|
raise HTTPException(status_code=400, detail="시작일·종료일을 YYYY-MM-DD 로 입력하세요.")
|
||||||
|
if d_from > d_to:
|
||||||
|
d_from, d_to = d_to, d_from
|
||||||
|
if (d_to - d_from).days + 1 > _PERIOD_MAX_DAYS:
|
||||||
|
raise HTTPException(status_code=400, detail=f"기간은 최대 {_PERIOD_MAX_DAYS}일까지 가능합니다.")
|
||||||
|
|
||||||
|
f, t = d_from.isoformat(), d_to.isoformat()
|
||||||
|
rows = st.shipped_by_date_range(date_from=f, date_to=t)
|
||||||
|
if not rows:
|
||||||
|
raise HTTPException(status_code=404, detail=f"{f} ~ {t} 기간의 발송 데이터가 없습니다.")
|
||||||
|
|
||||||
|
# 세트 BOM 이 없으면 낱개로 못 푼 채 파일이 만들어진다 — 조용히 틀리지 말고 알린다.
|
||||||
|
set_bom, _sab = _itemcode_bom_and_sabangnet(request)
|
||||||
|
missing_sets = export.missing_set_boms(rows, set_bom)
|
||||||
|
if missing_sets:
|
||||||
|
reader = getattr(request.app.state, "malaysia_itemcode", None)
|
||||||
|
hint = getattr(reader, "last_error", "") or getattr(reader, "reason", "")
|
||||||
|
detail = (
|
||||||
|
"세트 BOM 을 찾지 못해 낱개로 풀 수 없습니다: "
|
||||||
|
+ ", ".join(missing_sets)
|
||||||
|
+ ". itemcode_db 의 set_components 에 해당 세트 BOM 이 등록돼 있는지 확인하세요."
|
||||||
|
)
|
||||||
|
if hint:
|
||||||
|
detail += f" (itemcode 리더 오류: {hint})"
|
||||||
|
raise HTTPException(status_code=422, detail=detail)
|
||||||
|
|
||||||
|
xlsx_bytes = export.build_period_xlsx(
|
||||||
|
rows=rows, date_from=f, date_to=t,
|
||||||
|
name_map=_itemcode_name_map(request), set_bom=set_bom,
|
||||||
|
)
|
||||||
|
fname = export.period_filename(f, t)
|
||||||
|
headers = {
|
||||||
|
"Content-Disposition": (
|
||||||
|
f"attachment; filename=\"shipped_{f}_{t}.xlsx\"; "
|
||||||
|
f"filename*=UTF-8''{quote(fname)}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return Response(
|
||||||
|
content=xlsx_bytes,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/stock-deduct")
|
@router.post("/stock-deduct")
|
||||||
def stock_deduct(
|
def stock_deduct(
|
||||||
request: Request,
|
request: Request,
|
||||||
|
|||||||
@@ -114,7 +114,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="erp-card dsp-calwrap">
|
<div class="dsp-calwrap" style="display:flex;flex-direction:column;gap:16px;">
|
||||||
|
<div class="erp-card" style="margin:0;">
|
||||||
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="사방넷 출고 다운로드" data-en="Sabangnet Outbound Download">사방넷 출고 다운로드</h3></div>
|
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="사방넷 출고 다운로드" data-en="Sabangnet Outbound Download">사방넷 출고 다운로드</h3></div>
|
||||||
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
||||||
data-ko="날짜를 클릭하면 그날 출고를 낱개로 분해한 사방넷 출고 엑셀을 받습니다. 사방넷에 올리면 출고로 잡혀 재고가 차감됩니다."
|
data-ko="날짜를 클릭하면 그날 출고를 낱개로 분해한 사방넷 출고 엑셀을 받습니다. 사방넷에 올리면 출고로 잡혀 재고가 차감됩니다."
|
||||||
@@ -143,6 +144,24 @@
|
|||||||
<div id="dsp-cal-deduct-note" class="erp-muted" style="font-size:12px;"></div>
|
<div id="dsp-cal-deduct-note" class="erp-muted" style="font-size:12px;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{% if is_super %}
|
||||||
|
<div class="erp-card" style="margin:0;">
|
||||||
|
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="기간별 발송 수량" data-en="Shipped Qty by Period">기간별 발송 수량</h3></div>
|
||||||
|
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
||||||
|
data-ko="기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)"
|
||||||
|
data-en="Download shipped quantities per date and item for the period. Sets are split into singles; set counts are on a separate sheet. (Super admin only)">기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)</p>
|
||||||
|
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
|
||||||
|
<input type="date" id="dsp-pe-from" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
|
||||||
|
<span class="erp-muted">~</span>
|
||||||
|
<input type="date" id="dsp-pe-to" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
|
||||||
|
</div>
|
||||||
|
<button type="button" id="dsp-pe-dl" class="erp-btn erp-btn-primary" style="margin-top:10px;width:100%;"
|
||||||
|
data-ko="📊 기간별 발송 수량 엑셀 다운로드" data-en="📊 Download Shipped Qty Excel">📊 기간별 발송 수량 엑셀 다운로드</button>
|
||||||
|
<div id="dsp-pe-note" class="erp-muted" style="font-size:12px;margin-top:6px;"></div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -264,6 +283,53 @@
|
|||||||
render();
|
render();
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
|
||||||
|
(function () {
|
||||||
|
var btn = document.getElementById('dsp-pe-dl');
|
||||||
|
if (!btn) return;
|
||||||
|
var fromEl = document.getElementById('dsp-pe-from');
|
||||||
|
var toEl = document.getElementById('dsp-pe-to');
|
||||||
|
var note = document.getElementById('dsp-pe-note');
|
||||||
|
function pad(n) { return (n < 10 ? '0' : '') + n; }
|
||||||
|
function iso(d) { return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); }
|
||||||
|
function en() { return (window.dspLang && window.dspLang() === 'en'); }
|
||||||
|
// 기본: 이번 달 1일 ~ 오늘
|
||||||
|
var now = new Date();
|
||||||
|
fromEl.value = iso(new Date(now.getFullYear(), now.getMonth(), 1));
|
||||||
|
toEl.value = iso(now);
|
||||||
|
|
||||||
|
btn.onclick = function () {
|
||||||
|
var f = fromEl.value, t = toEl.value;
|
||||||
|
if (!f || !t) { alert(en() ? 'Pick both dates.' : '시작일과 종료일을 고르세요.'); return; }
|
||||||
|
btn.disabled = true;
|
||||||
|
note.textContent = en() ? 'Preparing…' : '만드는 중…';
|
||||||
|
var url = '/dispatch/period-export?date_from=' + encodeURIComponent(f) + '&date_to=' + encodeURIComponent(t);
|
||||||
|
fetch(url)
|
||||||
|
.then(function (r) {
|
||||||
|
if (!r.ok) {
|
||||||
|
return r.json().catch(function () { return {}; }).then(function (j) {
|
||||||
|
throw new Error((j && j.detail) || ('HTTP ' + r.status));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
var cd = r.headers.get('Content-Disposition') || '';
|
||||||
|
var m = cd.match(/filename\*=UTF-8''([^;]+)/);
|
||||||
|
var name = m ? decodeURIComponent(m[1]) : ('shipped_' + f + '_' + t + '.xlsx');
|
||||||
|
return r.blob().then(function (b) {
|
||||||
|
var a = document.createElement('a');
|
||||||
|
a.href = URL.createObjectURL(b);
|
||||||
|
a.download = name;
|
||||||
|
document.body.appendChild(a); a.click(); a.remove();
|
||||||
|
setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
|
||||||
|
note.textContent = '';
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(function (e) {
|
||||||
|
note.textContent = (e && e.message) || (en() ? 'Failed' : '실패');
|
||||||
|
})
|
||||||
|
.then(function () { btn.disabled = false; });
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
// ── 받는 사람 찾기(이름/주문/패키지/송장 번호 부분 일치) ──
|
// ── 받는 사람 찾기(이름/주문/패키지/송장 번호 부분 일치) ──
|
||||||
(function () {
|
(function () {
|
||||||
var wrap = document.getElementById('dsp-search');
|
var wrap = document.getElementById('dsp-search');
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""기간별 발송 수량 엑셀(export.aggregate_shipped / build_period_xlsx) 테스트.
|
||||||
|
|
||||||
|
DB 없이 집계·엑셀 생성만 검증한다.
|
||||||
|
python -m app.modules.dispatch.tests.test_period_export
|
||||||
|
또는 pytest 로 실행 가능.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
|
||||||
|
from app.modules.dispatch import export
|
||||||
|
|
||||||
|
_ROWS = [
|
||||||
|
{"dispatch_date": "2026-10-02", "seller_sku": "MT-0320", "product_name": "A", "qty": 2},
|
||||||
|
{"dispatch_date": "2026-10-01", "seller_sku": "MT-0320_3", "product_name": "A", "qty": 1},
|
||||||
|
{"dispatch_date": "2026-10-01", "seller_sku": "mt-0320", "product_name": "A", "qty": 1},
|
||||||
|
{"dispatch_date": "2026-10-01", "seller_sku": "MY-0001", "product_name": "Set", "qty": 4},
|
||||||
|
{"dispatch_date": "2026-10-02", "seller_sku": "", "product_name": "", "qty": 9},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_aggregate_multiplier_and_merge():
|
||||||
|
"""_N 배수 반영 + 대소문자/접미사 다른 같은 코드 합산, 빈 코드 제외(BOM 없으면 세트 그대로)."""
|
||||||
|
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0320": "상품A"})
|
||||||
|
assert dates == ["2026-10-01", "2026-10-02"], dates
|
||||||
|
assert qty[("2026-10-01", "MT-0320")] == 4 # 1×3 + 1
|
||||||
|
assert qty[("2026-10-02", "MT-0320")] == 2
|
||||||
|
assert qty[("2026-10-01", "MY-0001")] == 4
|
||||||
|
assert names["MT-0320"] == "상품A" # itemcode 이름 우선
|
||||||
|
assert names["MY-0001"] == "Set" # 없으면 파싱된 이름
|
||||||
|
|
||||||
|
|
||||||
|
_BOM = {"MY-0001": [
|
||||||
|
{"component_code": "MT-0320", "component_qty": 1},
|
||||||
|
{"component_code": "mt-0550", "component_qty": 2},
|
||||||
|
]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_aggregate_explodes_sets():
|
||||||
|
"""세트는 BOM 으로 낱개 분해해 같은 날 같은 낱개 코드에 합산."""
|
||||||
|
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0550": "상품B"}, _BOM)
|
||||||
|
assert ("2026-10-01", "MY-0001") not in qty
|
||||||
|
assert qty[("2026-10-01", "MT-0320")] == 8 # 1×3 + 1 + 세트 4×1
|
||||||
|
assert qty[("2026-10-01", "MT-0550")] == 8 # 세트 4×2
|
||||||
|
assert names["MT-0550"] == "상품B"
|
||||||
|
assert export.missing_set_boms(_ROWS, _BOM) == []
|
||||||
|
assert export.missing_set_boms(_ROWS, {}) == ["MY-0001"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_period_xlsx_sheets():
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
|
data = export.build_period_xlsx(
|
||||||
|
rows=_ROWS, date_from="2026-10-01", date_to="2026-10-02", name_map={}, set_bom=_BOM
|
||||||
|
)
|
||||||
|
wb = load_workbook(io.BytesIO(data))
|
||||||
|
assert wb.sheetnames == ["날짜별", "아이템별 요약", "세트별 요약"]
|
||||||
|
|
||||||
|
ws = wb["날짜별"]
|
||||||
|
rows = list(ws.iter_rows(values_only=True))
|
||||||
|
assert rows[0] == ("발송 날짜", "아이템 코드", "상품이름", "수량")
|
||||||
|
assert rows[1] == ("2026-10-01", "MT-0320", "A", 8)
|
||||||
|
assert rows[2] == ("2026-10-01", "MT-0550", None, 8)
|
||||||
|
assert rows[3] == ("2026-10-02", "MT-0320", "A", 2)
|
||||||
|
assert rows[-1][0] == "합계" and rows[-1][3] == 18
|
||||||
|
|
||||||
|
ws2 = wb["아이템별 요약"]
|
||||||
|
rows2 = list(ws2.iter_rows(values_only=True))
|
||||||
|
assert rows2[0] == ("아이템 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
|
||||||
|
assert rows2[1] == ("MT-0320", "A", 8, 2, 10)
|
||||||
|
assert rows2[2] == ("MT-0550", None, 8, None, 8)
|
||||||
|
assert rows2[3] == ("합계", None, 16, 2, 18)
|
||||||
|
|
||||||
|
# 세트는 낱개로 풀기 전 세트 단위 수량, 날짜 열은 전체 발송 날짜와 같다.
|
||||||
|
rows3 = list(wb["세트별 요약"].iter_rows(values_only=True))
|
||||||
|
assert rows3[0] == ("세트 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
|
||||||
|
assert rows3[1] == ("MY-0001", "Set", 4, None, 4)
|
||||||
|
assert rows3[2] == ("합계", None, 4, 0, 4)
|
||||||
|
|
||||||
|
|
||||||
|
def test_period_filename():
|
||||||
|
assert export.period_filename("2026-10-01", "2026-10-28") == "2026.10.01-2026.10.28_shipped_qty.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_aggregate_multiplier_and_merge()
|
||||||
|
test_aggregate_explodes_sets()
|
||||||
|
test_build_period_xlsx_sheets()
|
||||||
|
test_period_filename()
|
||||||
|
print("OK")
|
||||||
@@ -265,11 +265,11 @@ def expense_index(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "expense"):
|
if not has_module(user, "expense"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -325,11 +325,11 @@ def pending_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -362,11 +362,11 @@ def reports_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
store = _store(request)
|
store = _store(request)
|
||||||
_require_db_store(store)
|
_require_db_store(store)
|
||||||
year_str = request.query_params.get("year") or str(now_kst().year)
|
year_str = request.query_params.get("year") or str(now_kst().year)
|
||||||
@@ -436,11 +436,11 @@ def approved_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -667,11 +667,11 @@ def settings_page(request: Request) -> HTMLResponse:
|
|||||||
get_current_user_record,
|
get_current_user_record,
|
||||||
render_template,
|
render_template,
|
||||||
)
|
)
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
|
|||||||
@@ -10,6 +10,10 @@
|
|||||||
- 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`). 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인.
|
- 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`). 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인.
|
||||||
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
|
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
|
||||||
- 미입고 현황(제품별 합계·발주별·지연).
|
- 미입고 현황(제품별 합계·발주별·지연).
|
||||||
|
- 발주 목록 상태 보기(진행 중·완료·종결·취소·전체)는 **사람마다 기억**(2026-11-04) — `inout_settings` 키 `list_status:{이메일}`(마이그레이션 없음, 005 미적용이면 기억만 안 함). 주소에 `status` 가 있으면 저장, 없으면 저장값, 그것도 없으면 진행 중.
|
||||||
|
- 발주 목록 **입고일** 열(2026-11-05, 입고 예정일과 발주 사이, `db.list_orders` `receipt_dates`) — 여러 날에 나눠 입고하면 칸 안에서 줄바꿈(오래된 날부터), 같은 날 여러 번은 한 번만, 입고 전 `-`.
|
||||||
|
- 발주 목록 거르기 줄(2026-11-05) — 상태·공장은 왼쪽, 발주일~[찾기]는 오른쪽(`.io-filter-right`).
|
||||||
|
- 발주 목록 표 머리글(2026-11-05, `.io-list-table`) = 가운데·굵게·`--text-caption` × 111% × 90%·회색 배경, 표 글자 전체도 원래의 90%. 미입고 현황 등 다른 표는 그대로.
|
||||||
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
|
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
|
||||||
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
|
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
|
||||||
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
|
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
|
||||||
@@ -32,9 +36,16 @@
|
|||||||
**휴가 모듈도 같은 연결을 쓴다**(2026-10-27) — 휴가 옵션 [Gmail 연결]은 세션 `_gmail_origin=vacation` 을 달고 같은 콜백(`/inout/gmail/callback`)으로 돌아오며,
|
**휴가 모듈도 같은 연결을 쓴다**(2026-10-27) — 휴가 옵션 [Gmail 연결]은 세션 `_gmail_origin=vacation` 을 달고 같은 콜백(`/inout/gmail/callback`)으로 돌아오며,
|
||||||
콜백이 `_gmail_callback_vacation`(휴가 권한 확인, 휴가 옵션으로 복귀)으로 넘긴다. 토큰 표·끊기는 공용 — 바꾸면 휴가 메일(`vacation/notify.py`)도 확인.
|
콜백이 `_gmail_callback_vacation`(휴가 권한 확인, 휴가 옵션으로 복귀)으로 넘긴다. 토큰 표·끊기는 공용 — 바꾸면 휴가 메일(`vacation/notify.py`)도 확인.
|
||||||
- 보낸 기록·재발송 확인.
|
- 보낸 기록·재발송 확인.
|
||||||
|
- **본문 고치기**(2026-10-27): 발주 메일 미리보기 iframe 이 `designMode`(sandbox `allow-same-origin`, 스크립트 없음) — 고치면 [원래 본문으로]·닫을 때 확인,
|
||||||
|
보낼 때만 `html` 을 함께 POST → `store.clean_mail_html`(허용 태그·표·인라인 서식만, url()·이벤트·스크립트 제거) + 글 버전 `mail_html_to_text`. 안 고치면 서버 본문 그대로. 입고 요청 메일은 고치기 없음(cid 사진).
|
||||||
|
**서식 막대**(`initMail` 안 `RTE_BAR`, 안내문 발송 편집기와 같은 구성: 크기·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기) = iframe `execCommand`(styleWithCSS → span style).
|
||||||
|
Quill 은 표를 못 담아 안 씀. 크기는 fontSize 7 → px span 으로 바꿔 끼움. 선택은 본문 문서의 현재 선택 우선(막대 mousedown 때 기억은 대비용). 서버는 `text-decoration-line` → `text-decoration`.
|
||||||
- **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내.
|
- **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내.
|
||||||
- **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요).
|
- **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요).
|
||||||
|
|
||||||
|
- **간단 발주 메일**(2026-11-04): 공장 이름에 "대성화학"·"인천공장"이 들어가면(`store.SIMPLE_MAIL_FACTORIES`, 띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·**박스당 수량·박스 수**·비고만, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다(단가가 공장에 나가지 않게). 색상 줄 배경·합계 수량은 그대로.
|
||||||
|
박스 값은 발주 품목 사본이 아니라 **메일을 만들 때의 상품 정보**(`router._mail_order` → `store.line_boxes`, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`). 다른 공장 메일엔 박스 칸 없음.
|
||||||
|
|
||||||
## 입고 요청 메일 (005, 2026-10-19)
|
## 입고 요청 메일 (005, 2026-10-19)
|
||||||
|
|
||||||
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
|
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
|
||||||
@@ -52,6 +63,8 @@
|
|||||||
|
|
||||||
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
|
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
|
||||||
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
|
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
|
||||||
|
- **돌리기**(2026-11-02) — 크게 보기 창 왼쪽·오른쪽 버튼(입고 담당) → `POST /inout/orders/{id}/photos/{pid}/rotate?degrees=90|270` → 서버가 **저장된 사진 자체**를 돌려 덮어씀(`store.rotate_image`, EXIF 회전을 픽셀에 반영, 같은 형식, JPEG 품질 92) — 원본 링크·입고 요청 메일도 돌린 사진. 되돌리기 = 반대로 돌리기. HEIC·움직이는 GIF 는 못 돌림(HEIC 은 버튼 숨김).
|
||||||
|
사진 응답은 `no-cache` + ETag(돌린 뒤 예전 사진이 캐시에 남지 않게).
|
||||||
|
|
||||||
## 상품 정보 (004, 옵션 세 번째 탭)
|
## 상품 정보 (004, 옵션 세 번째 탭)
|
||||||
|
|
||||||
@@ -87,10 +100,17 @@
|
|||||||
- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`).
|
- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`).
|
||||||
- 007 확인 `db.boxes_ready`(groups_ready 와 같은 방식 — 연결 열기 전, 미적용 1분 기억). 그룹·색상 조회(`_PRODUCT_SELECT_006`)는 `p.*` 라 새 열이 따라온다.
|
- 007 확인 `db.boxes_ready`(groups_ready 와 같은 방식 — 연결 열기 전, 미적용 1분 기억). 그룹·색상 조회(`_PRODUCT_SELECT_006`)는 `p.*` 라 새 열이 따라온다.
|
||||||
|
|
||||||
|
## 봉투·백 (008, 2026-11-04)
|
||||||
|
|
||||||
|
- 이름에 **"미라클 봉투"·"미라클백"** 이 들어간 상품(`store.is_bag`, 저장 안 함 — 이름으로 판단) = 옵션 → 상품 정보에서 일반 상품과 **표를 나눔**(봉투·백 표가 위). 칸: **박스당 수량**(`body_per_box` 재사용)·**1파렛트당 박스 수량**(`inout_products.boxes_per_pallet`). 뚜껑 없음(저장하면 `lid_per_box` 는 NULL).
|
||||||
|
**단가·무게·은 칸 없음**(2026-11-04 사용자 지정) — 전에 넣은 값은 줄의 숨은 칸으로 저장 때 그대로 보내 지우지 않음. 그룹·색상 칸은 있음. 새 발주서 "단가 없는 N종"·발주서 화면과 발주 메일의 "단가 미입력 N종"(`store.order_totals`) 안내에서 봉투·백은 뺌.
|
||||||
|
- 새 발주서 합계 줄에 봉투·백 박스·파렛트를 **통·뚜껑과 따로** 표시: 파렛트 = ⌈Σ(박스 ÷ 그 상품 1파렛트 박스)⌉. 파렛트 그림도 통처럼(`palletVis(all, cap, mixed)`, 그림 칸은 60칸까지) — 1파렛트 박스 수가 다른 상품이 섞이면 가장 큰 값으로 환산해 잔량은 %만. 입수·1파렛트 값은 `store.box_info`(`_form_page`·`/api/items`).
|
||||||
|
- 008 확인 `db.bags_ready`(boxes_ready 와 같은 방식). 미적용이면 모두 일반 상품으로 동작.
|
||||||
|
|
||||||
## 오른쪽 달력 (2026-10-21)
|
## 오른쪽 달력 (2026-10-21)
|
||||||
|
|
||||||
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 300px). 스크롤해도 위에 붙음.
|
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 270px). 스크롤해도 위에 붙음.
|
||||||
달력 크기 = 화면에 따라 300~440px(`clamp(300px, 23vw, 440px)`, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
|
달력 크기 = 화면에 따라 270~396px(`clamp(270px, 20.7vw, 396px)`, 2026-11-05 90% 로 줄임, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
|
||||||
글자·칸은 달력 너비 기준 `cqw`(300px 일 때 1cqw = 3px)라 같은 비율로 커진다 — 새 크기 값도 px 대신 cqw 로.
|
글자·칸은 달력 너비 기준 `cqw`(300px 일 때 1cqw = 3px)라 같은 비율로 커진다 — 새 크기 값도 px 대신 cqw 로.
|
||||||
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
|
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
|
||||||
공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
|
공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
|
||||||
@@ -102,3 +122,5 @@
|
|||||||
|
|
||||||
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
|
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
|
||||||
- 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`).
|
- 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`).
|
||||||
|
- **날짜 칸 = ERP 공용 달력**(2026-11-05, `erp-datepop`, `_datepop.html` + `inout.js` 머리) — 발주 목록 기간·발주일·입고 예정일·입고일. `input[type=date]` 는 숨긴 값 저장소(폼 전송 그대로), 국경일·대체공휴일 빨강·이름 + 마우스를 올리면 이름(`title`, 표 = `project.store.KR_HOLIDAYS`, `router._date_holidays`).
|
||||||
|
필수 칸은 [지우기] 없음(숨긴 required 칸이 비면 브라우저가 안내 없이 저장을 막는다), 잠긴 입고일은 버튼도 disabled. 테스트 `tests/js/inout_datepop.browser.test.js`(`render_inout.py`).
|
||||||
|
|||||||
+57
-1
@@ -339,9 +339,15 @@ class InoutDBStore:
|
|||||||
"SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
"SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
||||||
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
||||||
"WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else []
|
"WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else []
|
||||||
|
# 입고일 열 — 같은 날 여러 번 입고해도 날짜는 하나
|
||||||
|
receipts = conn.execute("SELECT DISTINCT order_id, receipt_date FROM inout_receipts WHERE order_id = ANY(%s) "
|
||||||
|
"ORDER BY order_id, receipt_date", (ids,)).fetchall() if ids else []
|
||||||
by_order: dict[int, list[dict[str, Any]]] = {}
|
by_order: dict[int, list[dict[str, Any]]] = {}
|
||||||
for ln in lines:
|
for ln in lines:
|
||||||
by_order.setdefault(int(ln["order_id"]), []).append(ln)
|
by_order.setdefault(int(ln["order_id"]), []).append(ln)
|
||||||
|
receipt_dates: dict[int, list[date]] = {}
|
||||||
|
for r in receipts:
|
||||||
|
receipt_dates.setdefault(int(r["order_id"]), []).append(r["receipt_date"])
|
||||||
allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1]
|
allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1]
|
||||||
out = []
|
out = []
|
||||||
for h in heads:
|
for h in heads:
|
||||||
@@ -351,7 +357,7 @@ class InoutDBStore:
|
|||||||
continue
|
continue
|
||||||
names = [x["item_name"] or x["item_code"] for x in ls]
|
names = [x["item_name"] or x["item_code"] for x in ls]
|
||||||
out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls),
|
out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls),
|
||||||
"line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""})
|
"receipt_dates": receipt_dates.get(int(h["id"]), []), "line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""})
|
||||||
if len(out) >= limit:
|
if len(out) >= limit:
|
||||||
break
|
break
|
||||||
return out
|
return out
|
||||||
@@ -432,6 +438,19 @@ class InoutDBStore:
|
|||||||
if not row:
|
if not row:
|
||||||
raise ValueError("사진을 찾을 수 없습니다.")
|
raise ValueError("사진을 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
def rotate_receipt_photo(self, order_id: int, photo_id: int, degrees: int) -> None:
|
||||||
|
"""저장된 사진 자체를 돌린다(2026-11-02) — 화면·원본·입고 요청 메일 모두 돌린 사진."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
row = conn.execute("SELECT p.data FROM inout_receipt_photos p JOIN inout_receipts r ON r.id = p.receipt_id "
|
||||||
|
"WHERE p.id=%s AND r.order_id=%s", (photo_id, order_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("사진을 찾을 수 없습니다.")
|
||||||
|
data = store.rotate_image(bytes(row["data"]), degrees)
|
||||||
|
conn.execute("UPDATE inout_receipt_photos SET data=%s, size_bytes=%s WHERE id=%s", (data, len(data), photo_id))
|
||||||
|
|
||||||
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
|
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
|
||||||
"""사진 내용(+ 발주서 id) — 보여 주기용."""
|
"""사진 내용(+ 발주서 id) — 보여 주기용."""
|
||||||
try:
|
try:
|
||||||
@@ -510,6 +529,22 @@ class InoutDBStore:
|
|||||||
except UndefinedTable:
|
except UndefinedTable:
|
||||||
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
|
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
# 발주 목록 상태 거르기 — 사람마다 기억(2026-11-04). 같은 설정 표에 사람별 키(마이그레이션 없음), 005 미적용이면 기억만 안 한다.
|
||||||
|
def get_list_status(self, email: str) -> str:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT value FROM inout_settings WHERE key = %s",
|
||||||
|
("list_status:" + _norm_email(email),)).fetchone()
|
||||||
|
except UndefinedTable:
|
||||||
|
return ""
|
||||||
|
return row["value"] if row else ""
|
||||||
|
|
||||||
|
def save_list_status(self, email: str, status: str) -> None:
|
||||||
|
try:
|
||||||
|
self.save_settings({"list_status:" + _norm_email(email): status}, by=email)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
|
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
|
||||||
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
|
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
|
||||||
try:
|
try:
|
||||||
@@ -608,7 +643,12 @@ class InoutDBStore:
|
|||||||
self._need_products()
|
self._need_products()
|
||||||
grouped = self.groups_ready() and any("group_id" in r for r in rows)
|
grouped = self.groups_ready() and any("group_id" in r for r in rows)
|
||||||
boxed = self.boxes_ready() and any("body_per_box" in r for r in rows)
|
boxed = self.boxes_ready() and any("body_per_box" in r for r in rows)
|
||||||
|
bagged = self.bags_ready() and any("boxes_per_pallet" in r for r in rows)
|
||||||
with self._pool.connection() as conn, conn.transaction():
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
if bagged: # 008 — 봉투·백 1파렛트당 박스 수량
|
||||||
|
for r in rows:
|
||||||
|
if "boxes_per_pallet" in r:
|
||||||
|
conn.execute("UPDATE inout_products SET boxes_per_pallet=%s WHERE item_code=%s", (r["boxes_per_pallet"], r["code"]))
|
||||||
if boxed: # 007 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다)
|
if boxed: # 007 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다)
|
||||||
for r in rows:
|
for r in rows:
|
||||||
if "body_per_box" in r:
|
if "body_per_box" in r:
|
||||||
@@ -730,6 +770,22 @@ class InoutDBStore:
|
|||||||
self._boxes_checked = time.monotonic()
|
self._boxes_checked = time.monotonic()
|
||||||
return ok
|
return ok
|
||||||
|
|
||||||
|
def bags_ready(self) -> bool:
|
||||||
|
"""008 이 적용됐나(상품 boxes_per_pallet). boxes_ready 와 같은 방식."""
|
||||||
|
if getattr(self, "_bags_ok", False):
|
||||||
|
return True
|
||||||
|
if time.monotonic() - getattr(self, "_bags_checked", -1e9) < 60:
|
||||||
|
return False
|
||||||
|
if not self.products_ready():
|
||||||
|
return False
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' "
|
||||||
|
"AND column_name = 'boxes_per_pallet') AS ok").fetchone()["ok"])
|
||||||
|
self._bags_ok = ok
|
||||||
|
self._bags_checked = time.monotonic()
|
||||||
|
return ok
|
||||||
|
|
||||||
def _need_groups(self) -> None:
|
def _need_groups(self) -> None:
|
||||||
if not self.groups_ready():
|
if not self.groups_ready():
|
||||||
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
|
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
|
||||||
|
|||||||
+81
-25
@@ -11,7 +11,7 @@
|
|||||||
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
|
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
|
||||||
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
|
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
|
||||||
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
|
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
|
||||||
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
|
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete|rotate · GET /inout/photos/{pid} 입고증 사진
|
||||||
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
|
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
|
||||||
GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005)
|
GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005)
|
||||||
POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005)
|
POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005)
|
||||||
@@ -68,13 +68,11 @@ def _user(request: Request) -> dict[str, Any]:
|
|||||||
|
|
||||||
def _page_user(request: Request) -> Any:
|
def _page_user(request: Request) -> Any:
|
||||||
"""화면 주소 — 로그인 전이면 로그인으로 보냈다가 돌아온다."""
|
"""화면 주소 — 로그인 전이면 로그인으로 보냈다가 돌아온다."""
|
||||||
from urllib.parse import quote # noqa: WPS433
|
|
||||||
|
|
||||||
from app.main import get_current_user_record # noqa: WPS433
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
from app.store import login_redirect # noqa: WPS433
|
||||||
|
|
||||||
if get_current_user_record(request) is None:
|
if get_current_user_record(request) is None:
|
||||||
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
|
return login_redirect(request)
|
||||||
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
|
|
||||||
return _user(request)
|
return _user(request)
|
||||||
|
|
||||||
|
|
||||||
@@ -108,6 +106,16 @@ def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]:
|
|||||||
return p
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def _date_holidays() -> dict[str, str]:
|
||||||
|
"""날짜 칸 달력(erp-datepop)의 국경일·대체공휴일 — 프로젝트 달력과 같은 표."""
|
||||||
|
try:
|
||||||
|
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433
|
||||||
|
|
||||||
|
return dict(KR_HOLIDAYS)
|
||||||
|
except Exception: # noqa: BLE001 — 표를 못 읽어도 날짜 입력은 된다
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any], status_code: int = 200) -> HTMLResponse:
|
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any], status_code: int = 200) -> HTMLResponse:
|
||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
|
|
||||||
@@ -116,7 +124,7 @@ def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, An
|
|||||||
return render_template(request, name, {
|
return render_template(request, name, {
|
||||||
"user": user, "is_admin": perms["admin"], "perms": perms,
|
"user": user, "is_admin": perms["admin"], "perms": perms,
|
||||||
"nav_items": build_erp_nav(user, active="inout"),
|
"nav_items": build_erp_nav(user, active="inout"),
|
||||||
"msg": request.query_params.get("msg", ""), "today": today_kst(),
|
"msg": request.query_params.get("msg", ""), "today": today_kst(), "date_holidays": _date_holidays(),
|
||||||
"open_options": request.query_params.get("options") == "1" and perms["admin"], # 톱니 팝업 바로 열기
|
"open_options": request.query_params.get("options") == "1" and perms["admin"], # 톱니 팝업 바로 열기
|
||||||
**ctx,
|
**ctx,
|
||||||
}, status_code=status_code)
|
}, status_code=status_code)
|
||||||
@@ -173,13 +181,17 @@ def _opt_date(v: Any) -> date | None:
|
|||||||
# 발주 목록 · 미입고 현황
|
# 발주 목록 · 미입고 현황
|
||||||
# ────────────────────────────────────────────────────────────
|
# ────────────────────────────────────────────────────────────
|
||||||
@router.get("/", response_class=HTMLResponse)
|
@router.get("/", response_class=HTMLResponse)
|
||||||
def index(request: Request, status: str = "active", factory: str = "", q: str = "", date_from: str = Query("", alias="from"),
|
def index(request: Request, status: str = "", factory: str = "", q: str = "", date_from: str = Query("", alias="from"),
|
||||||
date_to: str = Query("", alias="to")) -> Any:
|
date_to: str = Query("", alias="to")) -> Any:
|
||||||
got = _ctx(request)
|
got = _ctx(request)
|
||||||
if not isinstance(got, tuple):
|
if not isinstance(got, tuple):
|
||||||
return got
|
return got
|
||||||
st, user = got
|
st, user = got
|
||||||
status = status if status in store.STATUS_FILTERS else "active"
|
saved = st.get_list_status(user.get("email", ""))
|
||||||
|
if status not in store.STATUS_FILTERS: # 주소에 상태가 없으면 이 사람이 마지막으로 고른 보기
|
||||||
|
status = saved if saved in store.STATUS_FILTERS else "active"
|
||||||
|
elif status != saved:
|
||||||
|
st.save_list_status(user.get("email", ""), status)
|
||||||
orders = st.list_orders(status=status, factory_id=_opt_int(factory), q=q, date_from=_opt_date(date_from),
|
orders = st.list_orders(status=status, factory_id=_opt_int(factory), q=q, date_from=_opt_date(date_from),
|
||||||
date_to=_opt_date(date_to))
|
date_to=_opt_date(date_to))
|
||||||
return _render(request, "inout/index.html", user, {
|
return _render(request, "inout/index.html", user, {
|
||||||
@@ -265,7 +277,7 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s
|
|||||||
ln["price"] = float(price) if price is not None else None
|
ln["price"] = float(price) if price is not None else None
|
||||||
ln["price_label"] = store.fmt_num(price) if price is not None else ""
|
ln["price_label"] = store.fmt_num(price) if price is not None else ""
|
||||||
bx = boxes.get(ln["code"]) or {} # 박스 입수(007) — 지금 상품 정보 값(발주 품목에 남기지 않음)
|
bx = boxes.get(ln["code"]) or {} # 박스 입수(007) — 지금 상품 정보 값(발주 품목에 남기지 않음)
|
||||||
ln["body_per_box"], ln["lid_per_box"] = bx.get("body_per_box"), bx.get("lid_per_box")
|
ln.update(store.box_info(bx))
|
||||||
reader = _items(request)
|
reader = _items(request)
|
||||||
catalog_n = st.catalog_count()
|
catalog_n = st.catalog_count()
|
||||||
return _render(request, "inout/order_form.html", user, {
|
return _render(request, "inout/order_form.html", user, {
|
||||||
@@ -488,7 +500,7 @@ def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any:
|
|||||||
_PHOTO_HEADERS = {
|
_PHOTO_HEADERS = {
|
||||||
"X-Content-Type-Options": "nosniff",
|
"X-Content-Type-Options": "nosniff",
|
||||||
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
|
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
|
||||||
"Cache-Control": "private, max-age=86400",
|
"Cache-Control": "private, no-cache",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -532,6 +544,21 @@ def receipt_photo_delete(request: Request, order_id: int, photo_id: int) -> Any:
|
|||||||
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
|
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/orders/{order_id}/photos/{photo_id}/rotate")
|
||||||
|
def receipt_photo_rotate(request: Request, order_id: int, photo_id: int, degrees: int = Query(...)) -> Any:
|
||||||
|
"""크게 보기 창의 회전 버튼 — 창을 닫지 않게 JSON 으로 답한다(화면이 사진을 다시 받아 그림)."""
|
||||||
|
got = _ctx(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
_require(st, user, "receive")
|
||||||
|
try:
|
||||||
|
st.rotate_receipt_photo(order_id, photo_id, degrees)
|
||||||
|
except (ValueError, LookupError) as exc:
|
||||||
|
return JSONResponse({"error": str(exc)}, status_code=400)
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/photos/{photo_id}")
|
@router.get("/photos/{photo_id}")
|
||||||
def photo_view(request: Request, photo_id: int) -> Response:
|
def photo_view(request: Request, photo_id: int) -> Response:
|
||||||
_user(request)
|
_user(request)
|
||||||
@@ -539,12 +566,18 @@ def photo_view(request: Request, photo_id: int) -> Response:
|
|||||||
row = st.get_photo(photo_id) if st is not None else None
|
row = st.get_photo(photo_id) if st is not None else None
|
||||||
if row is None:
|
if row is None:
|
||||||
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
|
||||||
|
from hashlib import md5 # noqa: WPS433
|
||||||
from urllib.parse import quote # noqa: WPS433
|
from urllib.parse import quote # noqa: WPS433
|
||||||
|
|
||||||
|
data = bytes(row["data"])
|
||||||
|
# 돌린 사진이 하루 동안 예전 모습으로 남지 않게 — 브라우저가 매번 내용이 같은지 묻는다(no-cache + ETag)
|
||||||
|
etag = '"' + md5(data, usedforsecurity=False).hexdigest() + '"'
|
||||||
|
if request.headers.get("if-none-match") == etag:
|
||||||
|
return Response(status_code=304, headers={"ETag": etag, "Cache-Control": _PHOTO_HEADERS["Cache-Control"]})
|
||||||
name = quote(str(row["filename"] or f"photo-{photo_id}"))
|
name = quote(str(row["filename"] or f"photo-{photo_id}"))
|
||||||
disp = "attachment" if row["content_type"] == "image/heic" else "inline" # HEIC 은 브라우저가 못 보여 줌 → 내려받기
|
disp = "attachment" if row["content_type"] == "image/heic" else "inline" # HEIC 은 브라우저가 못 보여 줌 → 내려받기
|
||||||
return Response(content=bytes(row["data"]), media_type=row["content_type"],
|
return Response(content=data, media_type=row["content_type"],
|
||||||
headers={**_PHOTO_HEADERS, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
|
headers={**_PHOTO_HEADERS, "ETag": etag, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
|
||||||
|
|
||||||
|
|
||||||
# ────────────────────────────────────────────────────────────
|
# ────────────────────────────────────────────────────────────
|
||||||
@@ -577,7 +610,7 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa
|
|||||||
except gmail.GmailError as exc:
|
except gmail.GmailError as exc:
|
||||||
return _redirect(_safe_next(next), str(exc))
|
return _redirect(_safe_next(next), str(exc))
|
||||||
request.session["_inout_gmail_next"] = _safe_next(next)
|
request.session["_inout_gmail_next"] = _safe_next(next)
|
||||||
request.session.pop("_gmail_origin", None) # 휴가 옵션에서 시작한 연결 표시가 남아 있으면 지움
|
request.session.pop("_gmail_origin", None) # 휴가·안내문 발송에서 시작한 연결 표시가 남아 있으면 지움
|
||||||
return await client.authorize_redirect(
|
return await client.authorize_redirect(
|
||||||
request, public_url_for(request, "inout_gmail_callback"),
|
request, public_url_for(request, "inout_gmail_callback"),
|
||||||
access_type="offline", prompt="consent", include_granted_scopes="true",
|
access_type="offline", prompt="consent", include_granted_scopes="true",
|
||||||
@@ -586,7 +619,7 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa
|
|||||||
|
|
||||||
@router.get("/gmail/callback", name="inout_gmail_callback")
|
@router.get("/gmail/callback", name="inout_gmail_callback")
|
||||||
async def gmail_callback(request: Request) -> Any:
|
async def gmail_callback(request: Request) -> Any:
|
||||||
if request.session.get("_gmail_origin") == "vacation":
|
if request.session.get("_gmail_origin") in _GMAIL_ORIGINS:
|
||||||
return await _gmail_callback_vacation(request)
|
return await _gmail_callback_vacation(request)
|
||||||
got = _ctx(request)
|
got = _ctx(request)
|
||||||
if not isinstance(got, tuple):
|
if not isinstance(got, tuple):
|
||||||
@@ -611,9 +644,17 @@ async def gmail_callback(request: Request) -> Any:
|
|||||||
return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 [메일 발송]으로 보낼 수 있습니다.")
|
return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 [메일 발송]으로 보낼 수 있습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
# 다른 모듈에서 시작한 [Gmail 연결] — 세션 _gmail_origin = 모듈 키 → (돌아갈 기본 주소, 권한 없을 때 문구, 연결 뒤 문구)
|
||||||
|
_GMAIL_ORIGINS: dict[str, tuple[str, str, str]] = {
|
||||||
|
"vacation": ("/vacation/options", "휴가 관리 모듈 권한이 없습니다.", "Gmail 을 연결했습니다 — 이제 휴가 메일이 내 Gmail 로 나갑니다."),
|
||||||
|
"outreach": ("/outreach/", "안내문 발송 모듈 권한이 없습니다.", "Gmail 을 연결했습니다 — 이제 안내문 메일을 내 Gmail 로 보낼 수 있습니다."),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async def _gmail_callback_vacation(request: Request) -> Any:
|
async def _gmail_callback_vacation(request: Request) -> Any:
|
||||||
"""휴가 옵션 [Gmail 연결](2026-10-27) — 같은 구글 리디렉션 주소를 함께 쓰므로 여기로 돌아온다(구글 클라우드 설정 추가 없음).
|
"""휴가 옵션·안내문 발송의 [Gmail 연결](2026-10-27) — 같은 구글 리디렉션 주소를 함께 쓰므로 여기로 돌아온다(구글 클라우드 설정 추가 없음).
|
||||||
입출고 담당 권한 대신 휴가 모듈 권한을 보고, 토큰은 입출고와 같은 inout_gmail_tokens 에(한 사람 = 연결 하나, 두 모듈이 같이 씀)."""
|
입출고 담당 권한 대신 그 모듈 권한(_GMAIL_ORIGINS)을 보고, 토큰은 입출고와 같은 inout_gmail_tokens 에(한 사람 = 연결 하나, 모듈이 같이 씀).
|
||||||
|
돌아갈 주소 = 세션 _gmail_next(그 모듈 경로 아래만, 예전 휴가 _vacation_gmail_next 도 읽음)."""
|
||||||
from urllib.parse import quote # noqa: WPS433
|
from urllib.parse import quote # noqa: WPS433
|
||||||
|
|
||||||
from authlib.integrations.starlette_client import OAuthError # noqa: WPS433
|
from authlib.integrations.starlette_client import OAuthError # noqa: WPS433
|
||||||
@@ -623,15 +664,18 @@ async def _gmail_callback_vacation(request: Request) -> Any:
|
|||||||
|
|
||||||
from . import gmail # noqa: WPS433
|
from . import gmail # noqa: WPS433
|
||||||
|
|
||||||
request.session.pop("_gmail_origin", None)
|
origin = str(request.session.pop("_gmail_origin", "") or "")
|
||||||
nxt = str(request.session.pop("_vacation_gmail_next", "") or "")
|
home, denied, done = _GMAIL_ORIGINS[origin]
|
||||||
if not nxt.startswith("/vacation/") or "//" in nxt or "\\" in nxt:
|
nxt = str(request.session.pop("_gmail_next", "") or request.session.pop("_vacation_gmail_next", "") or "")
|
||||||
nxt = "/vacation/options"
|
request.session.pop("_vacation_gmail_next", None)
|
||||||
|
if not nxt.startswith(f"/{origin}/") or "//" in nxt or "\\" in nxt:
|
||||||
|
nxt = home
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login?next=" + quote(nxt, safe=""), status_code=303)
|
return RedirectResponse(url="/login?next=" + quote(nxt, safe=""), status_code=303)
|
||||||
if not has_module(user, "vacation"):
|
# 휴가 협의자는 휴가 권한이 없어도 연결한다 — 휴가 연결 시작 때 그 신청의 협의자인지 확인해 세션에 남긴 값(2026-11-02)
|
||||||
raise HTTPException(status_code=403, detail="휴가 관리 모듈 권한이 없습니다.")
|
if not request.session.pop("_gmail_consultant", False) and not has_module(user, origin):
|
||||||
|
raise HTTPException(status_code=403, detail=denied)
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
if st is None:
|
if st is None:
|
||||||
return _redirect(nxt, "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다.")
|
return _redirect(nxt, "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다.")
|
||||||
@@ -645,7 +689,7 @@ async def _gmail_callback_vacation(request: Request) -> Any:
|
|||||||
return _redirect(nxt, msg)
|
return _redirect(nxt, msg)
|
||||||
except (gmail.GmailError, ValueError) as exc:
|
except (gmail.GmailError, ValueError) as exc:
|
||||||
return _redirect(nxt, str(exc))
|
return _redirect(nxt, str(exc))
|
||||||
return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 휴가 메일이 내 Gmail 로 나갑니다.")
|
return _redirect(nxt, done)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/gmail/disconnect")
|
@router.post("/gmail/disconnect")
|
||||||
@@ -675,6 +719,10 @@ def _mail_order(request: Request, order_id: int) -> tuple[Any, dict[str, Any], d
|
|||||||
order = _order_or_404(st, order_id)
|
order = _order_or_404(st, order_id)
|
||||||
if order["cancelled_at"]:
|
if order["cancelled_at"]:
|
||||||
raise HTTPException(status_code=400, detail="취소된 발주서는 메일로 보낼 수 없습니다.")
|
raise HTTPException(status_code=400, detail="취소된 발주서는 메일로 보낼 수 없습니다.")
|
||||||
|
if store.is_simple_mail_factory(order["factory_name"]) and st.boxes_ready(): # 박스 칸 — 발주 품목에 없어 지금 상품 정보 값
|
||||||
|
found = st.catalog_lookup([x["item_code"] for x in order["lines"]])
|
||||||
|
for x in order["lines"]:
|
||||||
|
x.update(store.box_info(found.get(x["item_code"]) or {}))
|
||||||
return st, user, order
|
return st, user, order
|
||||||
|
|
||||||
|
|
||||||
@@ -708,6 +756,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
|
|||||||
try:
|
try:
|
||||||
to = store.parse_emails(payload.get("to"), label="받는 사람", required=True)
|
to = store.parse_emails(payload.get("to"), label="받는 사람", required=True)
|
||||||
cc = store.parse_emails(payload.get("cc"), label="참조")
|
cc = store.parse_emails(payload.get("cc"), label="참조")
|
||||||
|
# 미리보기 창에서 본문을 고쳤으면 그 HTML(2026-10-27) — 안 고쳤으면 보내지 않고 서버가 만든 본문 그대로
|
||||||
|
edited = store.clean_mail_html(payload["html"]) if payload.get("html") else None
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||||
if order["mails"] and not payload.get("resend"):
|
if order["mails"] and not payload.get("resend"):
|
||||||
@@ -718,6 +768,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
|
|||||||
return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."},
|
return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."},
|
||||||
status_code=409)
|
status_code=409)
|
||||||
mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=email)
|
mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=email)
|
||||||
|
if edited is not None:
|
||||||
|
mail = {**mail, "html": edited, "text": store.mail_html_to_text(edited)}
|
||||||
try:
|
try:
|
||||||
refresh = gmail.decrypt_token(email, row["refresh_token_enc"])
|
refresh = gmail.decrypt_token(email, row["refresh_token_enc"])
|
||||||
raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc,
|
raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc,
|
||||||
@@ -901,8 +953,10 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
|
|||||||
known.add(e)
|
known.add(e)
|
||||||
reader = _items(request)
|
reader = _items(request)
|
||||||
products = st.list_products()
|
products = st.list_products()
|
||||||
|
bags_ready = st.bags_ready()
|
||||||
for pr in products:
|
for pr in products:
|
||||||
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
|
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
|
||||||
|
pr["is_bag"] = bags_ready and store.is_bag(pr.get("item_name"))
|
||||||
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
|
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
|
||||||
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
|
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
|
||||||
"boxes_ready": st.boxes_ready(),
|
"boxes_ready": st.boxes_ready(),
|
||||||
@@ -1061,7 +1115,9 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
|
|||||||
code = str((r or {}).get("code") or "").strip().upper()
|
code = str((r or {}).get("code") or "").strip().upper()
|
||||||
try:
|
try:
|
||||||
row = {"code": code, **store.validate_product_values(r)}
|
row = {"code": code, **store.validate_product_values(r)}
|
||||||
if "body_per_box" in (r or {}): # 007 — 통·뚜껑 박스 입수(빈칸 = 없음)
|
if "boxes_per_pallet" in (r or {}): # 008 — 봉투·백(박스당 수량·1파렛트당 박스 수량)
|
||||||
|
row.update(store.validate_bag_values(r))
|
||||||
|
elif "body_per_box" in (r or {}): # 007 — 통·뚜껑 박스 입수(빈칸 = 없음)
|
||||||
row.update(store.validate_box_values(r))
|
row.update(store.validate_box_values(r))
|
||||||
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
|
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
|
||||||
gid = str(r.get("group_id") or "").strip()
|
gid = str(r.get("group_id") or "").strip()
|
||||||
@@ -1160,7 +1216,7 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
|
|||||||
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
|
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
|
||||||
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
|
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
|
||||||
"color": r.get("color") or "none",
|
"color": r.get("color") or "none",
|
||||||
"body_per_box": r.get("body_per_box"), "lid_per_box": r.get("lid_per_box")} for r in rows]})
|
**store.box_info(r)} for r in rows]})
|
||||||
reader = _items(request)
|
reader = _items(request)
|
||||||
if reader is None or not reader.enabled:
|
if reader is None or not reader.enabled:
|
||||||
return JSONResponse({"items": [], "enabled": False,
|
return JSONResponse({"items": [], "enabled": False,
|
||||||
|
|||||||
+256
-27
@@ -9,6 +9,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import html as _html
|
import html as _html
|
||||||
|
import html.parser as _html_parser
|
||||||
import re
|
import re
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
@@ -247,6 +248,28 @@ def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False)
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# 간단 발주 메일(2026-11-04) — 이 공장들엔 품목 표를 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 요약에서도 금액·무게·은을 뺀다.
|
||||||
|
SIMPLE_MAIL_FACTORIES = ("대성화학", "인천공장")
|
||||||
|
|
||||||
|
|
||||||
|
def is_simple_mail_factory(name: Any) -> bool:
|
||||||
|
"""이름 일부·띄어쓰기가 달라도 맞게 — 놓치면 단가가 공장에 나간다."""
|
||||||
|
compact = "".join(str(name or "").split())
|
||||||
|
return any(word in compact for word in SIMPLE_MAIL_FACTORIES)
|
||||||
|
|
||||||
|
|
||||||
|
def line_boxes(x: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""간단 발주 메일 칸 — 박스당 수량·박스 수(올림). 뚜껑이 있으면 통·뚜껑 따로, 입수가 없으면 '-'(total None)."""
|
||||||
|
body, lid, qty = x.get("body_per_box"), x.get("lid_per_box"), int(x["qty"])
|
||||||
|
if not body:
|
||||||
|
return {"per": "-", "count": "-", "total": None}
|
||||||
|
boxes = -(-qty // body)
|
||||||
|
if not lid:
|
||||||
|
return {"per": f"{body:,}개", "count": f"{boxes:,}박스", "total": boxes}
|
||||||
|
lids = -(-qty // lid)
|
||||||
|
return {"per": f"통 {body:,}개 · 뚜껑 {lid:,}개", "count": f"통 {boxes:,} · 뚜껑 {lids:,}박스", "total": boxes + lids}
|
||||||
|
|
||||||
|
|
||||||
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
|
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
|
||||||
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
||||||
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
|
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
|
||||||
@@ -262,16 +285,18 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
|||||||
who = sender_name or sender_email
|
who = sender_name or sender_email
|
||||||
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
|
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
|
||||||
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
||||||
if money["amount"] is not None:
|
simple = is_simple_mail_factory(order.get("factory_name"))
|
||||||
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
|
||||||
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
|
||||||
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
|
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
|
||||||
if money["pp_kg"] is not None:
|
if not simple:
|
||||||
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
|
if money["amount"] is not None:
|
||||||
if money["pp_use_kg"] is not None:
|
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||||
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
|
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||||
if ag_kg is not None:
|
if money["pp_kg"] is not None:
|
||||||
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
|
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
|
||||||
|
if money["pp_use_kg"] is not None:
|
||||||
|
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
|
||||||
|
if ag_kg is not None:
|
||||||
|
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
|
||||||
if order.get("memo"):
|
if order.get("memo"):
|
||||||
facts.append(("요청 사항", order["memo"]))
|
facts.append(("요청 사항", order["memo"]))
|
||||||
|
|
||||||
@@ -288,12 +313,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
|||||||
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||||
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||||||
text += [f"- {k}: {v}" for k, v in facts]
|
text += [f"- {k}: {v}" for k, v in facts]
|
||||||
text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
text += ["", "[발주 품목] 제품 코드 · 제품명 · 수량 · 박스당 수량 · 박스 수 · 비고" if simple else "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||||||
for i, x in enumerate(lines, start=1):
|
for i, x in enumerate(lines, start=1):
|
||||||
c = cells(x)
|
c = cells(x)
|
||||||
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {c['price']} · 금액 {c['amount']}"
|
b = line_boxes(x)
|
||||||
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
|
if simple:
|
||||||
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}"
|
detail = f" · 박스당 {b['per']} · {b['count']}" if b["total"] is not None else ""
|
||||||
|
else:
|
||||||
|
detail = (f" · 단가 {c['price']} · 금액 {c['amount']}"
|
||||||
|
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
|
||||||
|
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}")
|
||||||
|
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개{detail}"
|
||||||
+ (f" ({x['memo']})" if x.get("memo") else ""))
|
+ (f" ({x['memo']})" if x.get("memo") else ""))
|
||||||
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
||||||
# HTML 본문 — 값은 모두 escape
|
# HTML 본문 — 값은 모두 escape
|
||||||
@@ -322,12 +352,14 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
|||||||
hexc = color_hex(x.get("color"))
|
hexc = color_hex(x.get("color"))
|
||||||
ctd = f"{td}background:{hexc};" if hexc else td
|
ctd = f"{td}background:{hexc};" if hexc else td
|
||||||
tr_style = f' style="background:{hexc}"' if hexc else ""
|
tr_style = f' style="background:{hexc}"' if hexc else ""
|
||||||
|
b = line_boxes(x)
|
||||||
|
detail = (f'<td style="{ctd}{r}">{e(b["per"])}</td><td style="{ctd}{r}">{e(b["count"])}</td>') if simple else (
|
||||||
|
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
|
||||||
|
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>')
|
||||||
rows.append(
|
rows.append(
|
||||||
f'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
|
f'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
|
||||||
f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||||
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>'
|
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>{detail}'
|
||||||
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
|
|
||||||
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>'
|
|
||||||
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
|
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
|
||||||
# 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg)
|
# 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg)
|
||||||
foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else ""
|
foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else ""
|
||||||
@@ -335,6 +367,16 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
|||||||
foot_use = f'{fmt_num(money["pp_use_kg"], 0)} kg' if money["pp_use_kg"] is not None else ""
|
foot_use = f'{fmt_num(money["pp_use_kg"], 0)} kg' if money["pp_use_kg"] is not None else ""
|
||||||
foot_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else ""
|
foot_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else ""
|
||||||
bg = "background:#f6f7f9;"
|
bg = "background:#f6f7f9;"
|
||||||
|
box_totals = [t for t in (line_boxes(x)["total"] for x in lines) if t is not None]
|
||||||
|
foot_boxes = f"{sum(box_totals):,}박스" if box_totals else ""
|
||||||
|
if box_totals and len(box_totals) < len(lines):
|
||||||
|
foot_boxes += f" (미설정 {len(lines) - len(box_totals)}종 제외)"
|
||||||
|
head_detail = f'<th style="{td}">박스당 수량</th><th style="{td}">박스 수</th>' if simple else (
|
||||||
|
f'<th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||||||
|
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>')
|
||||||
|
foot_detail = f'<th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_boxes)}</th>' if simple else (
|
||||||
|
f'<th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
||||||
|
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>')
|
||||||
html = (
|
html = (
|
||||||
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||||
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
|
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
|
||||||
@@ -342,14 +384,12 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
|||||||
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
|
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
|
||||||
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||||||
'<table style="border-collapse:collapse;min-width:640px;margin:0">'
|
'<table style="border-collapse:collapse;min-width:640px;margin:0">'
|
||||||
f'<thead><tr style="{bg}"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
f'<thead><tr style="{bg}"><th style="{td}">{"번호" if simple else "No"}</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||||
f'<th style="{td}">수량</th><th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
f'<th style="{td}">수량</th>{head_detail}'
|
||||||
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>'
|
|
||||||
f'<th style="{td}">비고</th></tr></thead>'
|
f'<th style="{td}">비고</th></tr></thead>'
|
||||||
f'<tbody>{"".join(rows)}</tbody>'
|
f'<tbody>{"".join(rows)}</tbody>'
|
||||||
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
|
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
|
||||||
f'<th style="{td}{bg}{r}">{total:,}</th><th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
f'<th style="{td}{bg}{r}">{total:,}</th>{foot_detail}'
|
||||||
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>'
|
|
||||||
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||||
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
||||||
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||||
@@ -357,6 +397,138 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
|||||||
return {"subject": subject, "text": "\n".join(text), "html": html}
|
return {"subject": subject, "text": "\n".join(text), "html": html}
|
||||||
|
|
||||||
|
|
||||||
|
# 발주 메일 본문 고치기(2026-10-27) — 미리보기 창에서 사람이 고친 HTML 을 그대로 보낸다.
|
||||||
|
# 표·서식(인라인 style)은 남기고 스크립트·이벤트 속성·외부 리소스(url()·img)는 뺀다. 글 버전은 고친 HTML 에서 다시 만든다.
|
||||||
|
MAIL_HTML_MAX = 300_000
|
||||||
|
_MAIL_TAGS = {"div", "p", "br", "span", "b", "strong", "i", "em", "u", "s", "strike", "font", "a", "ul", "ol", "li",
|
||||||
|
"h1", "h2", "h3", "h4", "blockquote", "sub", "sup", "hr",
|
||||||
|
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "colgroup", "col", "caption"}
|
||||||
|
_MAIL_VOID = {"br", "hr", "col"}
|
||||||
|
_MAIL_DROP = {"script", "style", "iframe", "object", "embed", "head", "title", "template", "noscript", "svg", "math",
|
||||||
|
"textarea", "select", "button", "form", "input", "link", "meta"}
|
||||||
|
_MAIL_ATTRS = {"colspan", "rowspan", "cellpadding", "cellspacing", "border", "align", "valign", "width", "height", "color"}
|
||||||
|
_MAIL_STYLE_PROPS = {"color", "background", "background-color", "font-family", "font-size", "font-weight", "font-style",
|
||||||
|
"text-decoration", "text-align", "vertical-align", "white-space", "line-height", "height", "width",
|
||||||
|
"min-width", "max-width", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||||
|
"margin", "margin-top", "margin-right", "margin-bottom", "margin-left", "border", "border-top",
|
||||||
|
"border-right", "border-bottom", "border-left", "border-color", "border-collapse", "border-spacing"}
|
||||||
|
_MAIL_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()'\"-]{1,120}$")
|
||||||
|
_MAIL_ATTR_VALUE_RE = re.compile(r"^[#\w%.-]{1,20}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _mail_style(value: str) -> str:
|
||||||
|
out = []
|
||||||
|
for decl in value.split(";"):
|
||||||
|
prop, _, val = decl.partition(":")
|
||||||
|
prop, val = prop.strip().lower(), val.strip()
|
||||||
|
if prop == "text-decoration-line": # 서식 막대(Chrome execCommand)가 밑줄·취소선을 이렇게 만든다 — 메일 프로그램은 text-decoration 만 아는 곳이 많다
|
||||||
|
prop = "text-decoration"
|
||||||
|
if prop in _MAIL_STYLE_PROPS and _MAIL_STYLE_VALUE_RE.match(val) and not re.search(r"url|expression|@import", val, re.I):
|
||||||
|
out.append(f"{prop}:{val}")
|
||||||
|
return ";".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
class _MailSanitizer(_html_parser.HTMLParser):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.out: list[str] = []
|
||||||
|
self.stack: list[str] = []
|
||||||
|
self.skip = 0
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag in _MAIL_DROP:
|
||||||
|
self.skip += 1
|
||||||
|
return
|
||||||
|
if self.skip or tag not in _MAIL_TAGS:
|
||||||
|
return
|
||||||
|
extra = ""
|
||||||
|
for k, v in attrs:
|
||||||
|
v = (v or "").strip()
|
||||||
|
if k == "style":
|
||||||
|
style = _mail_style(v)
|
||||||
|
if style:
|
||||||
|
extra += f' style="{_html.escape(style)}"'
|
||||||
|
elif k == "href" and tag == "a" and re.match(r"^(https?:|mailto:)", v, re.I):
|
||||||
|
extra += f' href="{_html.escape(v)}"'
|
||||||
|
elif k in _MAIL_ATTRS and _MAIL_ATTR_VALUE_RE.match(v):
|
||||||
|
extra += f' {k}="{_html.escape(v)}"'
|
||||||
|
self.out.append(f"<{tag}{extra}>")
|
||||||
|
if tag not in _MAIL_VOID:
|
||||||
|
self.stack.append(tag)
|
||||||
|
|
||||||
|
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag in _MAIL_VOID:
|
||||||
|
self.handle_starttag(tag, attrs)
|
||||||
|
|
||||||
|
def handle_endtag(self, tag: str) -> None:
|
||||||
|
if tag in _MAIL_DROP:
|
||||||
|
self.skip = max(0, self.skip - 1)
|
||||||
|
return
|
||||||
|
if self.skip or tag not in self.stack:
|
||||||
|
return
|
||||||
|
while self.stack:
|
||||||
|
t = self.stack.pop()
|
||||||
|
self.out.append(f"</{t}>")
|
||||||
|
if t == tag:
|
||||||
|
break
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
if not self.skip:
|
||||||
|
self.out.append(_html.escape(data, quote=False))
|
||||||
|
|
||||||
|
def result(self) -> str:
|
||||||
|
self.close()
|
||||||
|
while self.stack:
|
||||||
|
self.out.append(f"</{self.stack.pop()}>")
|
||||||
|
return "".join(self.out)
|
||||||
|
|
||||||
|
|
||||||
|
class _MailText(_html_parser.HTMLParser):
|
||||||
|
"""HTML → 글 버전 — 문단·줄은 줄바꿈, 표 칸은 " | " 로 잇는다."""
|
||||||
|
|
||||||
|
_BLOCK = {"p", "div", "tr", "li", "h1", "h2", "h3", "h4", "blockquote", "table", "hr"}
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts: list[str] = []
|
||||||
|
self.cell = False # 이 줄에 이미 칸이 있다 — 다음 칸 앞에 구분자
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag == "br" or tag in self._BLOCK:
|
||||||
|
self.parts.append("\n")
|
||||||
|
self.cell = False
|
||||||
|
elif tag in ("td", "th"):
|
||||||
|
if self.cell:
|
||||||
|
self.parts.append(" | ")
|
||||||
|
self.cell = True
|
||||||
|
if tag == "li":
|
||||||
|
self.parts.append("- ")
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
self.parts.append(re.sub(r"\s+", " ", data.replace("\xa0", " ")))
|
||||||
|
|
||||||
|
|
||||||
|
def clean_mail_html(html: Any) -> str:
|
||||||
|
"""고친 메일 본문 HTML → 보낼 HTML(허용 태그·속성·글자 서식만). 너무 길거나 글이 없으면 ValueError."""
|
||||||
|
raw = str(html or "")
|
||||||
|
if len(raw) > MAIL_HTML_MAX:
|
||||||
|
raise ValueError("메일 본문이 너무 깁니다.")
|
||||||
|
p = _MailSanitizer()
|
||||||
|
p.feed(raw)
|
||||||
|
out = p.result()
|
||||||
|
if not mail_html_to_text(out).strip():
|
||||||
|
raise ValueError("메일 본문이 비어 있습니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def mail_html_to_text(html: str) -> str:
|
||||||
|
p = _MailText()
|
||||||
|
p.feed(str(html or ""))
|
||||||
|
p.close()
|
||||||
|
lines = [ln.strip() for ln in "".join(p.parts).split("\n")]
|
||||||
|
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
|
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
|
||||||
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
|
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
|
||||||
@@ -414,7 +586,8 @@ def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
|||||||
q = int(x["qty"])
|
q = int(x["qty"])
|
||||||
a = line_amount(q, x.get("unit_price"))
|
a = line_amount(q, x.get("unit_price"))
|
||||||
if a is None:
|
if a is None:
|
||||||
missing += 1
|
if not is_bag(x.get("item_name")): # 봉투·백은 단가가 원래 없음 — "단가 미입력" 안내에서 뺀다
|
||||||
|
missing += 1
|
||||||
else:
|
else:
|
||||||
amount = (amount or Decimal(0)) + a
|
amount = (amount or Decimal(0)) + a
|
||||||
w = to_dec(x.get("weight_g"))
|
w = to_dec(x.get("weight_g"))
|
||||||
@@ -424,7 +597,7 @@ def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
|||||||
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
||||||
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
||||||
use = (use or Decimal(0)) + w * q * (Decimal(100) - p) / Decimal(100000)
|
use = (use or Decimal(0)) + w * q * (Decimal(100) - p) / Decimal(100000)
|
||||||
return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag,
|
return {"amount": amount, "missing_price": missing, "pp_kg": pp, "silver_g": ag,
|
||||||
"pp_use_kg": use}
|
"pp_use_kg": use}
|
||||||
|
|
||||||
|
|
||||||
@@ -453,7 +626,8 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]
|
|||||||
def has_values(p: dict[str, Any]) -> bool:
|
def has_values(p: dict[str, Any]) -> bool:
|
||||||
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||||
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
|
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
|
||||||
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS))
|
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS)
|
||||||
|
or p.get("boxes_per_pallet") is not None)
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -465,9 +639,9 @@ MAX_PER_BOX = 1_000_000
|
|||||||
PALLET_BOXES = 30
|
PALLET_BOXES = 30
|
||||||
|
|
||||||
|
|
||||||
def parse_per_box(raw: Any, *, key: str) -> int | None:
|
def parse_per_box(raw: Any, *, key: str = "", label: str = "") -> int | None:
|
||||||
"""박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용)."""
|
"""박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용)."""
|
||||||
label = BOX_FIELDS[key]
|
label = label or BOX_FIELDS[key]
|
||||||
s = str(raw if raw is not None else "").replace(",", "").strip()
|
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||||||
if not s:
|
if not s:
|
||||||
return None
|
return None
|
||||||
@@ -475,7 +649,7 @@ def parse_per_box(raw: Any, *, key: str) -> int | None:
|
|||||||
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
|
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
|
||||||
n = int(s)
|
n = int(s)
|
||||||
if n < 1:
|
if n < 1:
|
||||||
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(뚜껑이 없으면 빈칸).")
|
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(없으면 빈칸).")
|
||||||
if n > MAX_PER_BOX:
|
if n > MAX_PER_BOX:
|
||||||
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||||||
return n
|
return n
|
||||||
@@ -485,6 +659,26 @@ def validate_box_values(values: dict[str, Any]) -> dict[str, int | None]:
|
|||||||
return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS}
|
return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS}
|
||||||
|
|
||||||
|
|
||||||
|
# 봉투·백(2026-11-04, 마이그레이션 008) — 이름으로 판단(저장 안 함). 뚜껑 없음, 박스당 수량 = body_per_box, 1파렛트 박스 수는 상품마다.
|
||||||
|
BAG_NAME_WORDS = ("미라클 봉투", "미라클백")
|
||||||
|
|
||||||
|
|
||||||
|
def is_bag(name: Any) -> bool:
|
||||||
|
return any(word in str(name or "") for word in BAG_NAME_WORDS)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_bag_values(values: dict[str, Any]) -> dict[str, int | None]:
|
||||||
|
return {"body_per_box": parse_per_box(values.get("body_per_box"), label="박스당 수량"), "lid_per_box": None,
|
||||||
|
"boxes_per_pallet": parse_per_box(values.get("boxes_per_pallet"), label="1파렛트당 박스 수량")}
|
||||||
|
|
||||||
|
|
||||||
|
def box_info(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""발주서 화면 박스 계산 값 — 008 미적용(열 없음)이면 모두 일반 상품으로."""
|
||||||
|
bag = "boxes_per_pallet" in row and is_bag(row.get("item_name"))
|
||||||
|
return {"body_per_box": row.get("body_per_box"), "lid_per_box": None if bag else row.get("lid_per_box"),
|
||||||
|
"is_bag": bag, "boxes_per_pallet": row.get("boxes_per_pallet") if bag else None}
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
|
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
|
||||||
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
|
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
|
||||||
@@ -567,6 +761,41 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_image(data: bytes, degrees: int) -> bytes:
|
||||||
|
"""사진 내용을 시계 방향 90·270도로 돌려 같은 형식으로(2026-11-02). 휴대폰 사진의 회전 정보(EXIF)는 픽셀에 반영한 뒤 돌린다."""
|
||||||
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps # noqa: WPS433
|
||||||
|
|
||||||
|
if degrees not in (90, 270):
|
||||||
|
raise ValueError("사진은 왼쪽·오른쪽으로만 돌릴 수 있습니다.")
|
||||||
|
kind = sniff_image(data)
|
||||||
|
if kind == "image/heic":
|
||||||
|
raise ValueError("HEIC 사진은 돌릴 수 없습니다 — JPG 로 바꿔 다시 올려 주세요.")
|
||||||
|
try:
|
||||||
|
im = Image.open(BytesIO(data))
|
||||||
|
if getattr(im, "n_frames", 1) > 1:
|
||||||
|
raise ValueError("움직이는 사진은 돌릴 수 없습니다.")
|
||||||
|
icc = im.info.get("icc_profile")
|
||||||
|
im = ImageOps.exif_transpose(im)
|
||||||
|
# PIL 의 ROTATE_n 은 반시계 방향 — 시계 90도 = ROTATE_270
|
||||||
|
im = im.transpose(Image.Transpose.ROTATE_270 if degrees == 90 else Image.Transpose.ROTATE_90)
|
||||||
|
fmt = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP", "image/gif": "GIF"}[kind]
|
||||||
|
opts: dict[str, Any] = {"icc_profile": icc} if icc and fmt != "GIF" else {}
|
||||||
|
if fmt in ("JPEG", "WEBP"):
|
||||||
|
opts["quality"] = 92
|
||||||
|
buf = BytesIO()
|
||||||
|
im.save(buf, format=fmt, **opts)
|
||||||
|
except ValueError:
|
||||||
|
raise
|
||||||
|
except Exception as exc: # noqa: BLE001 — 깨진 파일 등(원본은 그대로 둔다)
|
||||||
|
raise ValueError("이 사진은 돌릴 수 없습니다.") from exc
|
||||||
|
out = buf.getvalue()
|
||||||
|
if len(out) > MAX_PHOTO_BYTES:
|
||||||
|
raise ValueError(f"돌린 사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지).")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
|
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
|
||||||
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
|
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{# 날짜 칸 = ERP 공용 달력(erp-datepop) — inout.js 가 input[type=date] 를 날짜 버튼으로 바꾼다. inout.js 보다 먼저 include. #}
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />
|
||||||
|
<script type="application/json" id="io-holidays">{{ (date_holidays or {}) | tojson }}</script>
|
||||||
|
<script src="/static/erp-datepop.js?v=20261106a" defer></script>
|
||||||
@@ -141,6 +141,7 @@
|
|||||||
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
|
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
|
||||||
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(<b>상품 그룹</b> 탭에서 한 번만 설정).{% endif %}
|
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(<b>상품 그룹</b> 탭에서 한 번만 설정).{% endif %}
|
||||||
{% if boxes_ready %}<b>통 수량(박스)</b>·<b>뚜껑 수량(박스)</b> = 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑이 없으면 빈칸) — 새 발주서에서 박스 수·파렛트 수를 계산합니다.{% endif %}
|
{% if boxes_ready %}<b>통 수량(박스)</b>·<b>뚜껑 수량(박스)</b> = 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑이 없으면 빈칸) — 새 발주서에서 박스 수·파렛트 수를 계산합니다.{% endif %}
|
||||||
|
이름에 "미라클 봉투"·"미라클백"이 들어간 상품은 <b>봉투·백</b> 표에서 <b>박스당 수량</b>·<b>1파렛트당 박스 수량</b>을 넣습니다(단가·무게·은 없음).
|
||||||
</p>
|
</p>
|
||||||
<div class="io-prod-bar">
|
<div class="io-prod-bar">
|
||||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
||||||
@@ -151,14 +152,23 @@
|
|||||||
</div>
|
</div>
|
||||||
{% if products %}
|
{% if products %}
|
||||||
<div class="io-prod-scroll">
|
<div class="io-prod-scroll">
|
||||||
|
{# 봉투·백(008) = 일반 상품과 표를 나눔, 짧은 목록이라 위에. 박스 칸 두 개만 다르고 나머지 칸은 같다 #}
|
||||||
|
{% set bags = products|selectattr('is_bag')|list %}
|
||||||
|
{% for bag_table, rows in [(true, bags), (false, products|rejectattr('is_bag')|list)] if rows %}
|
||||||
|
<div class="io-prod-part">
|
||||||
|
{% if bags %}<div class="io-prod-part-title">{{ '봉투·백' if bag_table else '일반 상품' }} <span class="io-sub">{{ rows|length }}개</span></div>{% endif %}
|
||||||
<table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
|
<table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
|
||||||
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% if boxes_ready %}<col class="w-box" /><col class="w-box" />{% endif %}{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
|
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}{% if not bag_table %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% endif %}{% if boxes_ready %}<col class="w-box" /><col class="w-box" />{% endif %}{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
|
||||||
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% if boxes_ready %}<th title="통이 한 박스에 몇 개">통 수량(박스)</th><th title="뚜껑이 한 박스에 몇 개 — 뚜껑이 없으면 빈칸">뚜껑 수량(박스)</th>{% endif %}{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
|
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}{% if not bag_table %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% endif %}{% if bag_table %}<th title="한 박스에 몇 개">박스당 수량</th><th title="한 파렛트에 몇 박스">1파렛트당 박스 수량</th>{% elif boxes_ready %}<th title="통이 한 박스에 몇 개">통 수량(박스)</th><th title="뚜껑이 한 박스에 몇 개 — 뚜껑이 없으면 빈칸">뚜껑 수량(박스)</th>{% endif %}{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for p in products %}
|
{% for p in rows %}
|
||||||
{% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
|
{% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
|
||||||
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name ~ ' ' ~ (p.group_name or ''))|lower }}"{% if groups_ready and p.group_id %} class="is-grouped"{% endif %}>
|
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name ~ ' ' ~ (p.group_name or ''))|lower }}"{% if groups_ready and p.group_id %} class="is-grouped"{% endif %}>
|
||||||
<td class="io-code">{{ p.item_code }}</td>
|
<td class="io-code">{{ p.item_code }}{% if bag_table %}
|
||||||
|
{# 봉투·백엔 단가·무게·은 칸이 없다 — 전에 넣은 값이 저장 때 지워지지 않게 숨은 칸으로 그대로 보낸다 #}
|
||||||
|
<input type="hidden" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" />
|
||||||
|
<input type="hidden" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" />
|
||||||
|
<input type="hidden" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" />{% endif %}</td>
|
||||||
<td class="io-prod-name">{{ p.item_name }}</td>
|
<td class="io-prod-name">{{ p.item_name }}</td>
|
||||||
{% if groups_ready %}
|
{% if groups_ready %}
|
||||||
<td><select class="io-in io-group-select" data-key="group_id" aria-label="{{ p.item_code }} 그룹">
|
<td><select class="io-in io-group-select" data-key="group_id" aria-label="{{ p.item_code }} 그룹">
|
||||||
@@ -166,12 +176,17 @@
|
|||||||
{% for g in groups %}<option value="{{ g.id }}" data-silver="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" data-color="{{ g.color }}" {% if p.group_id == g.id %}selected{% endif %}>{{ g.name }}</option>{% endfor %}
|
{% for g in groups %}<option value="{{ g.id }}" data-silver="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" data-color="{{ g.color }}" {% if p.group_id == g.id %}selected{% endif %}>{{ g.name }}</option>{% endfor %}
|
||||||
</select></td>
|
</select></td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
{% if not bag_table %}
|
||||||
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
|
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
|
||||||
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
|
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
|
||||||
<td><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
|
<td><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
|
||||||
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</td>
|
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</td>
|
||||||
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
|
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
|
||||||
{% if boxes_ready %}
|
{% endif %}
|
||||||
|
{% if bag_table %}
|
||||||
|
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 박스당 수량" /></td>
|
||||||
|
<td><input class="io-in io-in-num" data-key="boxes_per_pallet" value="{{ '{:,}'.format(p.boxes_per_pallet) if p.boxes_per_pallet else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 1파렛트당 박스 수량" /></td>
|
||||||
|
{% elif boxes_ready %}
|
||||||
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 통 수량(박스)" /></td>
|
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 통 수량(박스)" /></td>
|
||||||
<td><input class="io-in io-in-num" data-key="lid_per_box" value="{{ '{:,}'.format(p.lid_per_box) if p.lid_per_box else '' }}" inputmode="numeric" placeholder="없음" aria-label="{{ p.item_code }} 뚜껑 수량(박스)" /></td>
|
<td><input class="io-in io-in-num" data-key="lid_per_box" value="{{ '{:,}'.format(p.lid_per_box) if p.lid_per_box else '' }}" inputmode="numeric" placeholder="없음" aria-label="{{ p.item_code }} 뚜껑 수량(박스)" /></td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -186,6 +201,8 @@
|
|||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
|
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||||
@@ -21,18 +21,20 @@
|
|||||||
<option value="">전체 공장</option>
|
<option value="">전체 공장</option>
|
||||||
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
|
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
|
||||||
</select>
|
</select>
|
||||||
<label class="io-date">발주일 <input class="erp-input" type="date" name="from" value="{{ filters['from'] }}" /></label>
|
<div class="io-filter-right">
|
||||||
|
<label class="io-date">발주일 <input class="erp-input" type="date" name="from" value="{{ filters['from'] }}" aria-label="발주일 시작" /></label>
|
||||||
<span class="erp-muted">~</span>
|
<span class="erp-muted">~</span>
|
||||||
<input class="erp-input" type="date" name="to" value="{{ filters['to'] }}" aria-label="발주일 끝" />
|
<input class="erp-input" type="date" name="to" value="{{ filters['to'] }}" aria-label="발주일 끝" />
|
||||||
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="발주번호·제품 코드·제품 이름" />
|
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="발주번호·제품 코드·제품 이름" />
|
||||||
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
|
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div class="erp-card-block">
|
<div class="erp-card-block">
|
||||||
<div class="erp-table-wrap">
|
<div class="erp-table-wrap">
|
||||||
<table class="erp-table io-table">
|
<table class="erp-table io-table io-list-table">
|
||||||
<thead><tr>
|
<thead><tr>
|
||||||
<th>발주번호</th><th>공장</th><th>제품</th><th>발주일</th><th>입고 예정일</th>
|
<th>발주번호</th><th>공장</th><th>제품</th><th>발주일</th><th>입고 예정일</th><th>입고일</th>
|
||||||
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th><th>진행</th><th>상태</th>
|
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th><th>진행</th><th>상태</th>
|
||||||
{% if perms.super %}<th class="io-col-trash"><span class="sr-only">삭제</span></th>{% endif %}
|
{% if perms.super %}<th class="io-col-trash"><span class="sr-only">삭제</span></th>{% endif %}
|
||||||
</tr></thead>
|
</tr></thead>
|
||||||
@@ -45,6 +47,7 @@
|
|||||||
<td class="io-items">{{ o.items_label }}<div class="erp-row-sub">{{ o.line_count }}종</div></td>
|
<td class="io-items">{{ o.items_label }}<div class="erp-row-sub">{{ o.line_count }}종</div></td>
|
||||||
<td>{{ ymd(o.order_date) }}</td>
|
<td>{{ ymd(o.order_date) }}</td>
|
||||||
<td>{{ due(o.due_date, today, active) }}</td>
|
<td>{{ due(o.due_date, today, active) }}</td>
|
||||||
|
<td>{% for d in o.receipt_dates %}<div>{{ ymd(d) }}</div>{% else %}-{% endfor %}</td>
|
||||||
<td class="io-num">{{ n(o.summary.ordered) }}</td>
|
<td class="io-num">{{ n(o.summary.ordered) }}</td>
|
||||||
<td class="io-num">{{ n(o.summary.received) }}</td>
|
<td class="io-num">{{ n(o.summary.received) }}</td>
|
||||||
<td class="io-num{% if o.summary.remaining and active %} io-remaining{% endif %}">{{ n(o.summary.remaining) }}{% if o.summary.over %}<div class="io-over-sub">초과 +{{ n(o.summary.over) }}</div>{% endif %}</td>
|
<td class="io-num{% if o.summary.remaining and active %} io-remaining{% endif %}">{{ n(o.summary.remaining) }}{% if o.summary.over %}<div class="io-over-sub">초과 +{{ n(o.summary.over) }}</div>{% endif %}</td>
|
||||||
@@ -61,7 +64,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
{% else %}
|
{% else %}
|
||||||
<tr><td colspan="{{ 11 if perms.super else 10 }}" class="erp-empty">{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}</td></tr>
|
<tr><td colspan="{{ 12 if perms.super else 11 }}" class="erp-empty">{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}</td></tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -71,4 +74,4 @@
|
|||||||
{% include "inout/_calendar.html" %}
|
{% include "inout/_calendar.html" %}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
</footer>
|
</footer>
|
||||||
</dialog>
|
</dialog>
|
||||||
{%- endmacro -%}
|
{%- endmacro -%}
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{% set active = order.status in ('open', 'partial') %}
|
{% set active = order.status in ('open', 'partial') %}
|
||||||
@@ -155,7 +155,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{% if receiving %}
|
{% if receiving %}
|
||||||
<div class="io-receipt-bar{% if recv_done %} is-locked{% endif %}"{% if recv_done %} aria-disabled="true" title="전체 입고 완료 — 더 입고할 수 없습니다"{% endif %}>
|
<div class="io-receipt-bar{% if recv_done %} is-locked{% endif %}"{% if recv_done %} aria-disabled="true" title="전체 입고 완료 — 더 입고할 수 없습니다"{% endif %}>
|
||||||
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" required{{ dis }} /></label>
|
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" aria-label="입고일" required{{ dis }} /></label>
|
||||||
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등"{{ dis }} /></label>
|
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등"{{ dis }} /></label>
|
||||||
<div class="erp-field io-photo-field">
|
<div class="erp-field io-photo-field">
|
||||||
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
|
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
|
||||||
@@ -232,6 +232,10 @@
|
|||||||
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
|
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
|
||||||
<div class="io-viewer-bar">
|
<div class="io-viewer-bar">
|
||||||
<span class="io-viewer-title" id="io-viewer-title"></span>
|
<span class="io-viewer-title" id="io-viewer-title"></span>
|
||||||
|
{% if photo_admin %}
|
||||||
|
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="270" title="왼쪽으로 돌리기" aria-label="왼쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4v6h6"/><path d="M3.5 15a9 9 0 1 0 2.1-9.4L3 10"/></svg></button>
|
||||||
|
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="90" title="오른쪽으로 돌리기" aria-label="오른쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 4v6h-6"/><path d="M20.5 15a9 9 0 1 1-2.1-9.4L21 10"/></svg></button>
|
||||||
|
{% endif %}
|
||||||
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
|
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
|
||||||
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
|
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
|
||||||
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
|
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
|
||||||
@@ -258,4 +262,4 @@
|
|||||||
{% include "inout/_calendar.html" %}
|
{% include "inout/_calendar.html" %}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||||
@@ -23,8 +23,8 @@
|
|||||||
</select>
|
</select>
|
||||||
{% if not factories %}<span class="io-hint">공장이 없습니다 — 관리자가 옵션에서 먼저 공장을 추가해야 합니다.</span>{% endif %}
|
{% if not factories %}<span class="io-hint">공장이 없습니다 — 관리자가 옵션에서 먼저 공장을 추가해야 합니다.</span>{% endif %}
|
||||||
</label>
|
</label>
|
||||||
<label class="erp-field"><span>발주일 *</span><input type="date" name="order_date" value="{{ vals.order_date }}" required /></label>
|
<label class="erp-field"><span>발주일 *</span><input type="date" name="order_date" value="{{ vals.order_date }}" aria-label="발주일" required /></label>
|
||||||
<label class="erp-field"><span>입고 예정일</span><input type="date" name="due_date" value="{{ vals.due_date }}" /></label>
|
<label class="erp-field"><span>입고 예정일</span><input type="date" name="due_date" value="{{ vals.due_date }}" aria-label="입고 예정일" /></label>
|
||||||
<label class="erp-field"><span>메모</span><input type="text" name="memo" value="{{ vals.memo }}" maxlength="500" placeholder="공장 전달 사항 등" /></label>
|
<label class="erp-field"><span>메모</span><input type="text" name="memo" value="{{ vals.memo }}" maxlength="500" placeholder="공장 전달 사항 등" /></label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
<tbody>
|
<tbody>
|
||||||
{% for ln in lines %}
|
{% for ln in lines %}
|
||||||
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
|
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
|
||||||
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}"{% if boxes_ready %} data-body-box="{{ ln.body_per_box or '' }}" data-lid-box="{{ ln.lid_per_box or '' }}"{% endif %}>
|
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}"{% if boxes_ready %} data-body-box="{{ ln.body_per_box or '' }}" data-lid-box="{{ ln.lid_per_box or '' }}" data-bag="{{ '1' if ln.is_bag else '' }}" data-pallet-box="{{ ln.boxes_per_pallet or '' }}"{% endif %}>
|
||||||
<td class="io-col-no"></td>
|
<td class="io-col-no"></td>
|
||||||
<td class="io-item-cell">
|
<td class="io-item-cell">
|
||||||
<input type="hidden" name="item_code" value="{{ ln.code }}" />
|
<input type="hidden" name="item_code" value="{{ ln.code }}" />
|
||||||
@@ -64,13 +64,20 @@
|
|||||||
<span class="io-pallet-vis" data-k="vis"></span>
|
<span class="io-pallet-vis" data-k="vis"></span>
|
||||||
<span class="erp-muted" data-k="note">1파렛트 = {{ pallet_boxes }}박스</span>
|
<span class="erp-muted" data-k="note">1파렛트 = {{ pallet_boxes }}박스</span>
|
||||||
</div>
|
</div>
|
||||||
|
{# 봉투·백(008) — 상품마다 1파렛트 박스 수가 달라 통·뚜껑 파렛트와 따로 셈 #}
|
||||||
|
<div class="io-pallet" id="io-pallet-bag" aria-live="polite" hidden>
|
||||||
|
<span>봉투·백 <b data-k="boxes">0</b>박스</span>
|
||||||
|
<span class="io-pallet-main">→ <b data-k="pallets">0</b>파렛트</span>
|
||||||
|
<span class="io-pallet-vis" data-k="vis"></span>
|
||||||
|
<span class="erp-muted" data-k="note"></span>
|
||||||
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td></tr></tfoot>
|
</td></tr></tfoot>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template id="io-line-tpl">
|
<template id="io-line-tpl">
|
||||||
<tr class="io-line"{% if boxes_ready %} data-body-box="" data-lid-box=""{% endif %}>
|
<tr class="io-line"{% if boxes_ready %} data-body-box="" data-lid-box="" data-bag="" data-pallet-box=""{% endif %}>
|
||||||
<td class="io-col-no"></td>
|
<td class="io-col-no"></td>
|
||||||
<td class="io-item-cell">
|
<td class="io-item-cell">
|
||||||
<input type="hidden" name="item_code" value="" />
|
<input type="hidden" name="item_code" value="" />
|
||||||
@@ -95,4 +102,4 @@
|
|||||||
{% include "inout/_calendar.html" %}
|
{% include "inout/_calendar.html" %}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
{% from "inout/_macros.html" import due, n, ymd %}
|
{% from "inout/_macros.html" import due, n, ymd %}
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||||
@@ -91,4 +91,4 @@
|
|||||||
{% include "inout/_calendar.html" %}
|
{% include "inout/_calendar.html" %}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# [라이브커머스] 라이브 커머스 모듈 — `app/modules/live/`, `live_db`(2026-11-04)
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||||
|
> 정적 파일: `app/static/live.js`, `live.css`. 템플릿: `templates/live/`. 테스트: `tests/test_live.py`(`LIVE_TEST_DB_URL` 이 localhost 일 때 실제 DB).
|
||||||
|
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인). 쇼핑몰 로고 = 말레이시아 배송 모듈 `app/static/dispatch/courier/tiktok.png`·`shopee.png`(지우거나 이름을 바꾸면 호스트 설정 로고도 깨짐).
|
||||||
|
|
||||||
|
- 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `live`, DB `LIVE_DB_URL`(없으면 "설정 필요" 안내).
|
||||||
|
- **호스트 설정** `/live/settings` — 간단한 이름(필수, `display_name`, 마이그레이션 004 — 말레이 이름은 끝이 아버지 이름이라 자동으로 줄이지 않고 사람이 입력, 빈 예전 호스트는 화면에 Full Name)·Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number.
|
||||||
|
**계좌 등 개인정보라 ERP 관리자만**(`is_admin`) — 화면·저장·지우기 모두. 스케줄 화면에는 `db.host_choices`(이름·사용 여부)만 넘긴다.
|
||||||
|
**틱톡 계정은 호스트가 아니라 방송마다**(2026-11-05, 마이그레이션 003 `live_broadcasts.tiktok_handle`) — 호스트가 여러 계정에서 방송하므로. 방송 창에서 입력(선택), `@`·주소를 붙여 넣어도 계정명만 저장, 쓴 적 있는 계정을 제안(`db.account_choices`). `live_hosts.tiktok_handle` 은 값만 남아 있고 안 씀. 달력에서 옮기거나 맞바꿔도 계정은 그 방송에 그대로. 달력 카드 머리·스케줄표·방송 창의 호스트 = 간단한 이름, 카드 머리 아래 작은 글자 = 계정.
|
||||||
|
**`live_host_edit` 칩**(+ `live`, 관리자 페이지 토글) = 호스트 **고치기**(사용 여부 포함): 지우기 불가, 개인정보는 페이지에 싣지 않아 빈칸으로 열리고 비워 두면 그대로·입력하면 바뀜(이 칩으로는 지울 수 없음).
|
||||||
|
**`live_host` 칩**(+ `live` 칩 필요) = 새 호스트 **등록만**: 설정 화면에 이름·상태만 보이고, 입력한 계좌 등은 저장 후 못 봄. 고치기·지우기 불가, 사용 여부 못 고름(항상 사용).
|
||||||
|
**쇼핑몰**(2026-11-06, 마이그레이션 005 `live_hosts.platform`, `store.PLATFORMS` = tiktok·shopee) — 창 맨 위 라디오 + 로고(같은 상자 88×26, 안 고르면 흑백·고르면 컬러), 저장 때 필수. 목록 첫 열 = 로고. 예전 호스트는 빈 값(고치기에서 고르면 저장).
|
||||||
|
**목록의 사용 토글**(`POST /live/settings/hosts/{id}/active`, `db.set_host_active`) = 고치기 권한(관리자·`live_host_edit` 칩)만, 바로 저장·실패하면 되돌림. 권한 없으면 글자(사용/사용 안 함).
|
||||||
|
사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT).
|
||||||
|
- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·판매금액·시간 요금(Fee)·커미션·광고비·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력).
|
||||||
|
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money(값, 이름)`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
|
||||||
|
표 첫 열 = 호스트 쇼핑몰 아이콘(`/static/live-icon-tiktok.png`·`live-icon-shopee.png` = 말레이시아 배송 로고에서 심볼만 잘라 64px, 쇼핑몰 안 고른 호스트는 빈칸), 머리글 = 가운데·굵게·검정·공용 크기 112%(`.lv-sched`, 스케줄표만).
|
||||||
|
**방송 장소는 2026-11-06 에 창·표에서 뺌**(`venue` 열은 예전 값만 남고 저장 때 건드리지 않음, 달력 카드 말풍선에만 예전 값).
|
||||||
|
- **방송 창 금액**(2026-11-06, 마이그레이션 006) — **Fee**(시간 × RM 25 `HOURLY_RATE`)·**커미션**(판매금액 × 10% `COMMISSION_PERCENT`) = 자동, 저장 안 함(`store.session_pay`, 창에서는 `live.js recalc` 가 같은 계산 — 시간·판매금액을 바꾸거나 결과 이미지에서 매출을 읽으면 다시 계산). 요율이 코드 상수라 바꾸면 지난 방송 값도 바뀐다.
|
||||||
|
**광고비**(`live_broadcasts.ad_spend`)·**호스트 비용**(`host_fee`, 일단 수기 입력) = 입력·저장. 달력 카드 Fee·날짜/달 합계 호스트 비용 = `host_fee` 합(비우면 0).
|
||||||
|
- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 1시간 칸(2026-11-06 `store.SLOT_HOURS` 2 → 1, 06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS.
|
||||||
|
카드 머리 왼쪽 위 = 호스트 쇼핑몰 작은 아이콘(2026-11-06, 예전 ✥ 대신 — 머리 전체가 끌기 손잡이), 카드 머리 = **Tiktok Handle**(없으면 이름, 색 = 호스트 id 순 `HOST_COLORS`), SALES·COM·Fee. 카드 머리를 끌어 빈 칸으로 = 옮기기(`move`, 방송 길이 유지) · 다른 카드 위 = 맞바꾸기(`swap_with`, 날짜·시간 교환). 다시 그린 뒤 가로 위치 유지(sessionStorage). 빈 칸 + = 그 날짜·시간이 채워진 추가 창.
|
||||||
|
**AD SPEND** = 그날 방송 광고비(`ad_spend`) 합(2026-11-06 — 예전 날짜별 입력 `live_daily_ad_spend`·✎ 버튼·`/live/ad-spend` 없앰, 표는 값만 남김), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`).
|
||||||
|
- **한 화면 맞춤**(2026-11-05) — 달력 보기는 넓은 화면(1101px 이상)에서 페이지 세로 스크롤 없음: `.lv-cal-wrap` 이 남은 높이를 쓰고, 풀HD 브라우저(세로 880px 이상)면 방송이 없는 달은 18개 시간 칸·합계 줄이 표 안 스크롤 없이 들어간다(카드가 있는 줄은 카드 높이만큼 커져서 방송이 많으면 표 안에서 스크롤, 페이지는 안 움직임). **방송이 걸친 칸은 합친다**(2026-11-06, `store._covered_slots` → `rowspan`, 가려진 칸 `skip`) — 2시간 방송 = 두 칸, 끝이 정각이 아니면 그 칸까지, 자정 넘김은 그날 마지막 칸까지. 합친 칸 안에서 시작하는 다른 방송은 같은 칸에 들어가고 칸이 더 늘어난다(겹친 방송). 끌어 놓기는 합친 칸의 첫 시간으로. 카드·표 글자·칸 크기를 늘리면 `live_calendar.browser.test.js` 로 다시 확인.
|
||||||
|
- **오른쪽 달력**(2026-11-05, 달력 보기만, 세로 2분할 `.lv-split`, 240px = 공용 달력의 80%, 예전 날짜로 이동 줄 대신, 공용 `erp-datepop` `mountRange` + `locale` 옵션으로 영문) — 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지 — `endGap` 이 표 끝에 여백), 다른 달이면 그 달 화면으로 가서 맨 왼쪽(sessionStorage `lv_cal_jump`). 표시만 하고 요금·일수에 안 씀. 글자 굵게, **방송 있는 날 = 숫자 오른쪽 위 초록 점**(2026-11-06, `db.broadcast_days` 보는 달 ±1년 → `#lv-live-days`, 공용 `mountRange` 의 `dayClass` 옵션 → `has-live`). 테스트 `tests/js/live_calendar.browser.test.js`(`render_live.py`).
|
||||||
|
**말레이시아 공휴일 표 = `holidays.py`**(쿠알라룸푸르 기준, 2026·2027, 대체휴일 포함) — 이슬람 명절은 달 관측으로 바뀔 수 있고, 2028 은 공고되면 손으로 추가.
|
||||||
|
- **결과 이미지 미리보기**(2026-11-06, 달력 보기) — 카드 오른쪽 아래 이미지 링크(`a[data-preview]`)에 마우스를 올리거나 탭으로 가면 오른쪽 달력 아래 빈 곳(`#lv-preview`, `.lv-side` 세로 줄)에 첫 장을 보여 주고 벗어나면 숨김. 좁은 화면(1100px 이하)은 미리보기 없음.
|
||||||
|
링크를 **누르면 화면 가운데 보기 창**(`#lv-viewer` `<dialog>`) — 원본 크기(크면 창 안 스크롤), 회전(보기만, 90°씩, 다운로드는 원본), 다운로드(올린 파일 이름), 여러 장이면 ◀▶. Ctrl·가운데 클릭은 새 탭.
|
||||||
|
- **카드 높이 = 합친 칸 높이**(2026-11-06) — `.lv-cell { height:1px }` + `.lv-cards { height:100% }` 로 칸 높이를 채운다(같은 칸 여러 카드는 나눠 가짐).
|
||||||
|
- **결과 이미지 → 매출 자동 입력**(2026-11-06, `ocr.py`, `POST /live/broadcasts/read-sales`) — 창에서 이미지를 고르면 서버의 Tesseract(Dockerfile 에서 설치, 외부 전송 없음)가 이미지 **위 절반**을 읽어 첫 `RM` 금액(틱톡 LIVE 결과 화면의 Attr. GMV)을 판매금액 칸에 채운다(저장 안 함 — 사람이 확인 후 저장, 여러 장이면 찾을 때까지 한 장씩). `RM1.2K` 처럼 줄인 값·못 찾음 = 칸 그대로 + 안내. tesseract 가 없으면(로컬 개발 PC) 안내만.
|
||||||
|
- **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장.
|
||||||
|
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
|
||||||
|
- 라이브 커머스 화면은 공용 최대 폭(1550px)을 풀어 **화면 전체 너비**를 쓴다(`live.css` 맨 위, 스케줄표·달력·호스트 설정).
|
||||||
|
- 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON).
|
||||||
|
- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live, 기본 한글). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`).
|
||||||
|
**새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다.
|
||||||
|
- 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""라이브 커머스(live) 모듈 — 말레이시아 라이브 방송의 호스트 정보와 방송 스케줄(2026-11-04).
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/live) · 저장소: `db.py` (live_db) · 순수 함수: `store.py`(입력 검사·표시 형식)
|
||||||
|
- 템플릿: `templates/live/`, 화면 스크립트·스타일 `static/live.{js,css}`
|
||||||
|
|
||||||
|
LIVE_DB_URL 미설정이면 build_live_store 가 None → 화면이 "설정 필요" 안내(앱은 죽지 않음). 권한키 `live`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_live_store"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_live_store(*, dsn: str | None) -> Any:
|
||||||
|
if not dsn:
|
||||||
|
return None
|
||||||
|
from .db import LiveDBStore # 지연 import
|
||||||
|
|
||||||
|
return LiveDBStore(dsn)
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""live_db PostgreSQL 저장소 — 라이브 커머스 호스트·방송 스케줄·결과 이미지(2026-11-04).
|
||||||
|
|
||||||
|
- 연결: 환경변수 `LIVE_DB_URL` (예: postgresql://live_app:<pwd>@postgres-db:5432/live_db)
|
||||||
|
- 스키마는 앱이 만들지 않는다 — `scripts/sql/live_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만).
|
||||||
|
- 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg.errors import ForeignKeyViolation
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
from .i18n import LiveError
|
||||||
|
|
||||||
|
_HOST_COLUMNS = ("platform", "display_name", "full_name", "phone", "email", "address", "bank_name", "bank_account")
|
||||||
|
|
||||||
|
|
||||||
|
class LiveDBStore:
|
||||||
|
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 4):
|
||||||
|
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._pool.close()
|
||||||
|
|
||||||
|
# ── 호스트 ─────────────────────────────────────────────
|
||||||
|
def list_hosts(self) -> list[dict[str, Any]]:
|
||||||
|
"""전체 정보(계좌 포함) — 설정 화면(ERP 관리자)에서만 쓴다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM live_hosts ORDER BY is_active DESC, full_name, id").fetchall()
|
||||||
|
|
||||||
|
def host_choices(self) -> list[dict[str, Any]]:
|
||||||
|
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT id, platform, display_name, full_name, is_active FROM live_hosts ORDER BY full_name, id").fetchall()
|
||||||
|
|
||||||
|
def get_host(self, host_id: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM live_hosts WHERE id=%s", (host_id,)).fetchone()
|
||||||
|
|
||||||
|
def account_choices(self) -> list[str]:
|
||||||
|
"""방송 창 틱톡 계정 입력 제안 — 지금까지 방송에 쓴 계정."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT DISTINCT tiktok_handle FROM live_broadcasts WHERE tiktok_handle <> '' ORDER BY tiktok_handle").fetchall()
|
||||||
|
return [r["tiktok_handle"] for r in rows]
|
||||||
|
|
||||||
|
def save_host(self, host_id: int | None, values: dict[str, str], *, is_active: bool, by: str) -> int:
|
||||||
|
cols = [values[k] for k in _HOST_COLUMNS]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if host_id is None:
|
||||||
|
row = conn.execute(
|
||||||
|
"INSERT INTO live_hosts (platform, display_name, full_name, phone, email, address, bank_name, bank_account, "
|
||||||
|
"is_active, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(*cols, is_active, by, by)).fetchone()
|
||||||
|
else:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE live_hosts SET platform=%s, display_name=%s, full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, "
|
||||||
|
"is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
|
||||||
|
(*cols, is_active, by, host_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
return int(row["id"])
|
||||||
|
|
||||||
|
def set_host_active(self, host_id: int, is_active: bool, *, by: str) -> None:
|
||||||
|
"""목록의 사용 토글 — 사용 여부만 바꾼다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not conn.execute("UPDATE live_hosts SET is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
|
||||||
|
(is_active, by, host_id)).fetchone():
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
def delete_host(self, host_id: int) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("DELETE FROM live_hosts WHERE id=%s RETURNING id", (host_id,)).fetchone()
|
||||||
|
except ForeignKeyViolation:
|
||||||
|
raise LiveError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None
|
||||||
|
if not row:
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
# ── 방송 스케줄 ─────────────────────────────────────────
|
||||||
|
def list_broadcasts(self, start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT b.*, COALESCE(NULLIF(h.display_name, ''), h.full_name) AS host_name, h.platform AS host_platform FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id "
|
||||||
|
"WHERE b.broadcast_date >= %s AND b.broadcast_date < %s ORDER BY b.broadcast_date, b.start_time, b.id",
|
||||||
|
(start, end)).fetchall()
|
||||||
|
images = conn.execute(
|
||||||
|
"SELECT id, broadcast_id, filename FROM live_broadcast_images WHERE broadcast_id = ANY(%s) ORDER BY id",
|
||||||
|
([r["id"] for r in rows],)).fetchall()
|
||||||
|
for r in rows:
|
||||||
|
r["images"] = [i for i in images if i["broadcast_id"] == r["id"]]
|
||||||
|
return rows
|
||||||
|
|
||||||
|
def broadcast_days(self, start: date, end: date) -> list[str]:
|
||||||
|
"""start 이상 end 미만 방송이 있는 날(ISO) — 오른쪽 달력 점."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT DISTINCT broadcast_date FROM live_broadcasts WHERE broadcast_date >= %s AND broadcast_date < %s ORDER BY 1",
|
||||||
|
(start, end)).fetchall()
|
||||||
|
return [r["broadcast_date"].isoformat() for r in rows]
|
||||||
|
|
||||||
|
def save_broadcast(self, broadcast_id: int | None, values: dict[str, Any], images: list[dict[str, Any]], *, by: str) -> int:
|
||||||
|
"""방송·이미지를 한 트랜잭션으로. 사용 안 함 호스트는 이미 그 호스트인 방송을 고칠 때만 허용."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
current = None
|
||||||
|
if broadcast_id is not None:
|
||||||
|
found = conn.execute("SELECT host_id FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
|
||||||
|
if not found:
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
current = found["host_id"]
|
||||||
|
host = conn.execute("SELECT is_active FROM live_hosts WHERE id=%s", (values["host_id"],)).fetchone()
|
||||||
|
if not host:
|
||||||
|
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
if not host["is_active"] and values["host_id"] != current:
|
||||||
|
raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.")
|
||||||
|
# 방송 장소(venue)는 2026-11-06 부터 입력 안 받음 — 예전 값은 그대로 둔다
|
||||||
|
args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"],
|
||||||
|
values["tiktok_handle"], values["sales_amount"], values["ad_spend"], values["host_fee"], by)
|
||||||
|
if broadcast_id is None:
|
||||||
|
broadcast_id = int(conn.execute(
|
||||||
|
"INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, tiktok_handle, sales_amount, ad_spend, host_fee, updated_by, created_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*args, by)).fetchone()["id"])
|
||||||
|
else:
|
||||||
|
conn.execute("UPDATE live_broadcasts SET host_id=%s, broadcast_date=%s, start_time=%s, end_time=%s, "
|
||||||
|
"tiktok_handle=%s, sales_amount=%s, ad_spend=%s, host_fee=%s, updated_by=%s WHERE id=%s", (*args, broadcast_id))
|
||||||
|
have = conn.execute("SELECT count(*) AS n FROM live_broadcast_images WHERE broadcast_id=%s", (broadcast_id,)).fetchone()["n"]
|
||||||
|
if have + len(images) > store.MAX_IMAGES:
|
||||||
|
raise LiveError("방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).", max=store.MAX_IMAGES, have=have)
|
||||||
|
for im in images:
|
||||||
|
conn.execute("INSERT INTO live_broadcast_images (broadcast_id, filename, content_type, data, width, height, created_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(broadcast_id, im["filename"], im["content_type"], im["data"], im["width"], im["height"], by))
|
||||||
|
return broadcast_id
|
||||||
|
|
||||||
|
def delete_broadcast(self, broadcast_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone():
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
def move_broadcast(self, broadcast_id: int, day: date, start: time, *, by: str) -> None:
|
||||||
|
"""달력에서 빈 칸으로 옮기기 — 방송 길이는 그대로."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
row = conn.execute("SELECT start_time, end_time FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(day, start, store.moved_end(row["start_time"], row["end_time"], start), by, broadcast_id))
|
||||||
|
|
||||||
|
def swap_broadcasts(self, first_id: int, second_id: int, *, by: str) -> None:
|
||||||
|
"""달력에서 다른 방송 위로 놓기 — 두 방송의 날짜·시간을 맞바꾼다(id 순서로 잠가 교착 방지)."""
|
||||||
|
if first_id == second_id:
|
||||||
|
return
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
rows = conn.execute("SELECT id, broadcast_date, start_time, end_time FROM live_broadcasts WHERE id = ANY(%s) ORDER BY id FOR UPDATE",
|
||||||
|
([first_id, second_id],)).fetchall()
|
||||||
|
if len(rows) != 2:
|
||||||
|
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
for mine, other in ((rows[0], rows[1]), (rows[1], rows[0])):
|
||||||
|
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(other["broadcast_date"], other["start_time"], other["end_time"], by, mine["id"]))
|
||||||
|
|
||||||
|
# ── 결과 이미지 ─────────────────────────────────────────
|
||||||
|
def get_image(self, image_id: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT content_type, data FROM live_broadcast_images WHERE id=%s", (image_id,)).fetchone()
|
||||||
|
|
||||||
|
def delete_image(self, image_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not conn.execute("DELETE FROM live_broadcast_images WHERE id=%s RETURNING id", (image_id,)).fetchone():
|
||||||
|
raise LiveError("이미지를 찾을 수 없습니다.")
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""말레이시아 공휴일 표(쿠알라룸푸르 기준, 2026-11-05) — 달력 보기 오른쪽 달력에 표시만 한다(요금·일수 계산에 안 씀).
|
||||||
|
|
||||||
|
출처: publicholidays.com.my(KL 2026·2027), 2027 대체휴일은 총리실(JPM) 목록을 옮긴 maukerja.my 기준 — 공식 PDF 원문은 확인하지 못했다.
|
||||||
|
이슬람 명절(하리라야·이슬람 새해·예언자 탄신일 등)은 달 관측으로 며칠 바뀔 수 있고, 주마다 쉬는 날이 달라 다른 주 지사 생일 등은 넣지 않았다.
|
||||||
|
shortcut: 해마다 손으로 추가한다 — 2028 목록이 공고되면 여기에 더한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
_NAMES: dict[str, tuple[str, str]] = {
|
||||||
|
"new_year": ("새해", "New Year's Day"),
|
||||||
|
"thaipusam": ("타이푸삼", "Thaipusam"),
|
||||||
|
"ft_day": ("연방직할구의 날", "Federal Territory Day"),
|
||||||
|
"cny": ("음력 설", "Chinese New Year"),
|
||||||
|
"nuzul": ("코란 계시일", "Nuzul Al-Quran"),
|
||||||
|
"aidilfitri": ("하리라야 푸아사", "Hari Raya Aidilfitri"),
|
||||||
|
"labour": ("노동절", "Labour Day"),
|
||||||
|
"haji": ("하리라야 하지", "Hari Raya Haji"),
|
||||||
|
"wesak": ("웨삭", "Wesak Day"),
|
||||||
|
"agong": ("국왕 탄신일", "Agong's Birthday"),
|
||||||
|
"muharram": ("이슬람 새해", "Awal Muharram"),
|
||||||
|
"maulud": ("예언자 탄신일", "Maulidur Rasul"),
|
||||||
|
"merdeka": ("독립기념일", "Merdeka Day"),
|
||||||
|
"malaysia": ("말레이시아의 날", "Malaysia Day"),
|
||||||
|
"deepavali": ("디파발리", "Deepavali"),
|
||||||
|
"christmas": ("크리스마스", "Christmas Day"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# 날짜 → 공휴일. "@" 로 시작 = 대체휴일(일요일·겹친 공휴일 다음 평일).
|
||||||
|
_DAYS: dict[str, str] = {
|
||||||
|
"2026-01-01": "new_year", "2026-02-01": "thaipusam", "2026-02-02": "@thaipusam", "2026-02-03": "@ft_day",
|
||||||
|
"2026-02-17": "cny", "2026-02-18": "cny", "2026-03-07": "nuzul",
|
||||||
|
"2026-03-20": "aidilfitri", "2026-03-21": "aidilfitri", "2026-03-22": "aidilfitri", "2026-03-23": "@aidilfitri",
|
||||||
|
"2026-05-01": "labour", "2026-05-27": "haji", "2026-05-31": "wesak", "2026-06-01": "agong", "2026-06-02": "@wesak",
|
||||||
|
"2026-06-17": "muharram", "2026-08-25": "maulud", "2026-08-31": "merdeka", "2026-09-16": "malaysia",
|
||||||
|
"2026-11-08": "deepavali", "2026-11-09": "@deepavali", "2026-12-25": "christmas",
|
||||||
|
|
||||||
|
"2027-01-01": "new_year", "2027-01-22": "thaipusam", "2027-02-01": "ft_day",
|
||||||
|
"2027-02-06": "cny", "2027-02-07": "cny", "2027-02-08": "@cny", "2027-02-24": "nuzul",
|
||||||
|
"2027-03-10": "aidilfitri", "2027-03-11": "aidilfitri", "2027-05-01": "labour", "2027-05-17": "haji", "2027-05-20": "wesak",
|
||||||
|
"2027-06-06": "muharram", "2027-06-07": "agong", "2027-06-08": "@muharram", "2027-08-15": "maulud", "2027-08-16": "@maulud",
|
||||||
|
"2027-08-31": "merdeka", "2027-09-16": "malaysia", "2027-10-28": "deepavali", "2027-12-25": "christmas",
|
||||||
|
}
|
||||||
|
# 같은 날 둘(2026-02-01 일요일 — 타이푸삼 + 연방직할구의 날)
|
||||||
|
_ALSO = {"2026-02-01": "ft_day"}
|
||||||
|
|
||||||
|
|
||||||
|
def holiday_names(lang: str = "ko") -> dict[str, str]:
|
||||||
|
"""{날짜: 이름} — 달력에 넘기는 값. 대체휴일은 한글 '… 대체'(공용 달력이 '대체휴일'로 줄임)·영문 '… (Replacement)'."""
|
||||||
|
i = 1 if lang == "en" else 0
|
||||||
|
out = {}
|
||||||
|
for day, key in _DAYS.items():
|
||||||
|
name = _NAMES[key.lstrip("@")][i]
|
||||||
|
if key.startswith("@"):
|
||||||
|
name += " (Replacement)" if lang == "en" else " 대체"
|
||||||
|
if day in _ALSO:
|
||||||
|
name += " · " + _NAMES[_ALSO[day]][i]
|
||||||
|
out[day] = name
|
||||||
|
return out
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""라이브 커머스 한글·영문 전환(2026-11-04) — 한글 문구가 키, 없으면 한글 그대로. 언어는 쿠키 `live_lang`(브라우저마다).
|
||||||
|
|
||||||
|
새 문구는 여기에도 넣는다 — tests/test_live.py 가 템플릿·오류 문구가 모두 있는지, 영문 화면에 한글이 없는지 확인한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
LANG_COOKIE = "live_lang"
|
||||||
|
|
||||||
|
EN: dict[str, str] = {
|
||||||
|
# 위 막대·보기
|
||||||
|
"이전 달": "Previous month", "다음 달": "Next month", "보기 방식": "View", "표": "Table", "달력": "Calendar",
|
||||||
|
"호스트 설정": "Host Settings", "+ 방송 추가": "+ Add Broadcast", "언어": "Language",
|
||||||
|
"방송을 추가하려면 먼저 호스트를 등록해야 합니다.": "Register a host before adding a broadcast.",
|
||||||
|
"ERP 관리자에게 등록을 요청하세요.": "Ask an ERP admin to register one.",
|
||||||
|
# 방송 창
|
||||||
|
"방송 추가": "Add Broadcast", "방송 고치기": "Edit Broadcast", "호스트": "Host", "호스트를 고르세요": "Select a host",
|
||||||
|
"사용 안 함": "Inactive", "방송 날짜": "Broadcast Date", "시작 시간": "Start Time", "끝 시간": "End Time",
|
||||||
|
"시간은 말레이시아 시간으로 입력합니다.": "Enter times in Malaysia time.", "판매금액 (RM)": "Sales (RM)",
|
||||||
|
"방송 후 입력": "Enter after the broadcast",
|
||||||
|
"시간 요금 (RM)": "Fee (RM)", "커미션 (RM)": "Commission (RM)", "광고비 (RM)": "Ad Spend (RM)", "호스트 비용 (RM)": "Host Fee (RM)",
|
||||||
|
"시간 × RM {rate} — 자동": "Hours × RM {rate} — auto", "판매금액 × {percent}% — 자동": "Sales × {percent}% — auto", "직접 입력": "Enter manually",
|
||||||
|
"방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)": "Result images (JPG, PNG, WebP, 8 MB each, up to {n} per broadcast)",
|
||||||
|
"취소": "Cancel", "저장": "Save", "확인": "OK",
|
||||||
|
# 표
|
||||||
|
"날짜": "Date", "시간": "Time", "판매금액(RM)": "Sales (RM)", "커미션 10%(RM)": "Commission 10% (RM)",
|
||||||
|
"호스트 비용(RM)": "Host Fee (RM)", "방송 결과": "Result", "고치기": "Edit", "지우기": "Delete",
|
||||||
|
"시간 요금(RM)": "Fee (RM)", "광고비(RM)": "Ad Spend (RM)",
|
||||||
|
"{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.": "Delete the {date} broadcast by {host}? Its result images will be deleted too.",
|
||||||
|
"이 달에 등록한 방송이 없습니다.": "No broadcasts this month.",
|
||||||
|
# 달력
|
||||||
|
"판매금액": "Sales", "커미션": "Com", "비용": "Fee", "광고비": "Ad Spend", "호스트 비용": "Host Fee", "총 판매금액": "Total Sales",
|
||||||
|
"ROAS": "ROAS", "합계 & ROAS": "Total & ROAS",
|
||||||
|
"팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.":
|
||||||
|
"Tip: Drag & drop any host header to move or swap dates. Scroll right to see all {n} days of the month.",
|
||||||
|
"{date} {slot} 방송 추가": "Add broadcast on {date} {slot}", "{name} {date} {times} 고치기": "Edit {name} {date} {times}",
|
||||||
|
"방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}",
|
||||||
|
# 호스트 설정
|
||||||
|
"◀ 스케줄표": "◀ Schedule", "+ 호스트 등록": "+ Add Host", "호스트 등록": "Add Host", "호스트 고치기": "Edit Host",
|
||||||
|
"간단한 이름": "Short Name", "이름 (IC 기준)": "Full Name (as per IC)", "전화번호": "Phone Number", "이메일": "Email", "주소": "Address", "은행명": "Bank Name",
|
||||||
|
"계좌번호": "Bank Account Number", "틱톡 핸들": "Tiktok Handle", "상태": "Status", "사용": "Active",
|
||||||
|
"{name} 호스트를 지울까요?": "Delete host {name}?", "등록한 호스트가 없습니다.": "No hosts registered.",
|
||||||
|
"사용 (끄면 새 방송에서 고를 수 없습니다)": "Active (when off, the host can't be selected for new broadcasts)",
|
||||||
|
"이미지 매출이 줄인 값({value})이라 정확하지 않습니다. 판매금액을 직접 입력하세요.": "The sales in the image are abbreviated ({value}), so they're not exact. Please enter the Sales yourself.",
|
||||||
|
"이미지에서 매출(RM)을 찾지 못했습니다. 판매금액을 직접 입력하세요.": "Couldn't find the sales (RM) in the image. Please enter the Sales yourself.",
|
||||||
|
"이미지에서 매출 {value} 를 읽었습니다. 확인 후 저장하세요.": "Read sales {value} from the image. Please check it, then save.",
|
||||||
|
"서버에 글자 인식 프로그램(tesseract)이 없습니다. 판매금액을 직접 입력하세요.": "Text recognition (tesseract) isn't installed on the server. Please enter the Sales yourself.",
|
||||||
|
"이미지 글자 인식이 너무 오래 걸립니다. 판매금액을 직접 입력하세요.": "Reading the image took too long. Please enter the Sales yourself.",
|
||||||
|
"이미지 글자를 읽지 못했습니다. 판매금액을 직접 입력하세요.": "Couldn't read the text in the image. Please enter the Sales yourself.",
|
||||||
|
"이미지에서 매출을 읽는 중…": "Reading sales from the image…",
|
||||||
|
"이전 이미지": "Previous image", "다음 이미지": "Next image", "회전": "Rotate", "다운로드": "Download", "닫기": "Close",
|
||||||
|
"쇼핑몰": "Platform", "쇼핑몰(틱톡·쇼피)을 고르세요.": "Choose the platform (TikTok or Shopee).",
|
||||||
|
"사용으로 바꿨습니다.": "Set to active.", "사용 안 함으로 바꿨습니다.": "Set to inactive.",
|
||||||
|
# 화면 스크립트(live.js)
|
||||||
|
"서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.": "Could not reach the server. Your entries are kept — please try saving again.",
|
||||||
|
"이 이미지": "this image", "{name} 를 지울까요?": "Delete {name}?",
|
||||||
|
# 저장 결과·입력 오류
|
||||||
|
"저장했습니다.": "Saved.", "옮겼습니다.": "Moved.","방송을 지웠습니다.": "Broadcast deleted.",
|
||||||
|
"이미지를 지웠습니다.": "Image deleted.", "호스트를 저장했습니다.": "Host saved.", "호스트를 지웠습니다.": "Host deleted.",
|
||||||
|
"잘못된 요청입니다.": "Invalid request.",
|
||||||
|
"간단한 이름을 입력하세요.": "Enter the Short Name.", "이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).",
|
||||||
|
"개인정보는 보이지 않습니다. 비워 두면 그대로 유지됩니다.": "Personal details are hidden. Leave them blank to keep the current values.", "{label} 이(가) 너무 깁니다({limit}자까지).": "{label} is too long (up to {limit} characters).",
|
||||||
|
"이메일 형식이 올바르지 않습니다.": "The email format is invalid.", "전화번호는 숫자·+·-·괄호만 입력하세요.": "Phone Number may contain only digits, +, - and brackets.",
|
||||||
|
"계좌번호는 숫자·-만 입력하세요.": "Bank Account Number may contain only digits and -.",
|
||||||
|
"틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.": "Tiktok Handle may contain only letters, digits, underscores and dots.",
|
||||||
|
"{label}은(는) 숫자로 입력하세요.": "{label} must be a number.", "{label}은(는) 0 이상 숫자로 입력하세요.": "{label} must be a number of 0 or more.", "{label}이(가) 너무 큽니다.": "{label} is too large.",
|
||||||
|
"{label}을 입력하세요.": "Enter the {label}.", "{label}이 올바르지 않습니다.": "The {label} is invalid.",
|
||||||
|
"호스트를 고르세요.": "Select a host.", "방송 날짜를 입력하세요.": "Enter the broadcast date.",
|
||||||
|
"끝 시간이 시작 시간과 같습니다.": "End time is the same as start time.", "날짜가 올바르지 않습니다.": "The date is invalid.",
|
||||||
|
"호스트를 찾을 수 없습니다.": "Host not found.", "방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.": "A host with broadcasts can't be deleted — set the host to Inactive instead.",
|
||||||
|
"방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).": "Broadcast not found (someone may have deleted it).", "방송을 찾을 수 없습니다.": "Broadcast not found.",
|
||||||
|
"사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.": "This host is Inactive — select another host.",
|
||||||
|
"방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).": "Up to {max} images per broadcast (currently {have}).", "방송 한 건에 이미지는 {max}장까지입니다.": "Up to {max} images per broadcast.",
|
||||||
|
"이미지를 찾을 수 없습니다.": "Image not found.",
|
||||||
|
"{name}: {detail}": "{name}: {detail}",
|
||||||
|
# 권한·설정
|
||||||
|
"로그인이 필요합니다.": "Please sign in.", "라이브 커머스 모듈 권한이 없습니다.": "You don't have access to the Live Commerce module.",
|
||||||
|
"호스트 정보는 ERP 관리자만 볼 수 있습니다.": "Only ERP admins can view host information.", "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.": "The Live Commerce DB (LIVE_DB_URL) is not configured.",
|
||||||
|
"라이브 커머스 모듈 접근 권한이 없습니다.": "You don't have access to the Live Commerce module.",
|
||||||
|
"라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 .env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.":
|
||||||
|
"The Live Commerce module is not set up yet. Create live_db with scripts/sql/live_db_init.sql, add LIVE_DB_URL to .env and restart the container.",
|
||||||
|
# 자산 모듈 prepare_photo 오류(이미지 검사를 함께 쓴다)
|
||||||
|
"사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.": "The image must be a non-empty file of 8 MB or less.", "JPG, PNG, WebP 사진만 등록할 수 있습니다.": "Only JPG, PNG and WebP images are allowed.",
|
||||||
|
"사진은 2천만 화소 이하로 등록하세요.": "The image must be 20 megapixels or less.", "사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.": "Please compress the image and try again (5 MB or less once stored).",
|
||||||
|
"사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.": "The image can't be read. Please choose a valid JPG, PNG or WebP file.",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 화면 스크립트에 넘기는 문구(window.LV_T)
|
||||||
|
JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?",
|
||||||
|
"이미지에서 매출을 읽는 중…")
|
||||||
|
|
||||||
|
_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
|
||||||
|
|
||||||
|
|
||||||
|
def norm_lang(raw: Any) -> str:
|
||||||
|
return "en" if raw == "en" else "ko"
|
||||||
|
|
||||||
|
|
||||||
|
def t(text: str, lang: str = "ko") -> str:
|
||||||
|
return EN.get(text, text) if lang == "en" else text
|
||||||
|
|
||||||
|
|
||||||
|
def js_text(lang: str) -> dict[str, str]:
|
||||||
|
return {k: t(k, lang) for k in JS_KEYS}
|
||||||
|
|
||||||
|
|
||||||
|
def month_label(year: int, month: int, lang: str = "ko") -> str:
|
||||||
|
return f"{_MONTH_NAMES[month - 1]} {year}" if lang == "en" else f"{year}년 {month}월"
|
||||||
|
|
||||||
|
|
||||||
|
class LiveError(ValueError):
|
||||||
|
"""입력·저장 오류 — 언어에 맞게 다시 쓸 수 있게 문구 틀과 값을 따로 둔다. str() = 한글."""
|
||||||
|
|
||||||
|
def __init__(self, template: str, **params: Any):
|
||||||
|
self.template, self.params = template, params
|
||||||
|
super().__init__(template.format(**params))
|
||||||
|
|
||||||
|
def text(self, lang: str) -> str:
|
||||||
|
return t(self.template, lang).format(**{k: t(v, lang) if isinstance(v, str) else v for k, v in self.params.items()})
|
||||||
|
|
||||||
|
|
||||||
|
def error_text(exc: Exception, lang: str) -> str:
|
||||||
|
return exc.text(lang) if isinstance(exc, LiveError) else t(str(exc), lang)
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""방송 결과 이미지(틱톡 LIVE 결과 화면)에서 매출 읽기(2026-11-06).
|
||||||
|
|
||||||
|
틱톡 화면 맨 위 카드 `RM672.2 / Attr. GMV` 의 첫 `RM` 금액을 판매금액으로 쓴다. 글자 인식 = 서버의 Tesseract(`tesseract`
|
||||||
|
명령, Dockerfile 에서 설치) — 외부로 보내지 않는다. 읽은 값은 창의 칸에 채워 줄 뿐이고, 사람이 확인한 뒤 저장한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
from app.modules.asset.media import prepare_photo
|
||||||
|
|
||||||
|
from .i18n import LiveError
|
||||||
|
|
||||||
|
TIMEOUT_SECONDS = 30
|
||||||
|
# 'RM672.2', 'RM 1,234.50', 'RM1.2K'(줄인 값) — OCR 이 RM 사이에 빈칸을 넣기도 한다
|
||||||
|
_RM_RE = re.compile(r"R\s?M\s*([0-9][0-9,]*(?:[.,][0-9]+)?)\s*([KkMm](?![A-Za-z]))?")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_sales(text: str) -> tuple[Decimal | None, str]:
|
||||||
|
"""OCR 글자 → (금액, 읽은 원문). 첫 RM 금액을 쓴다(아래 Rewards 칸은 $). K·M 으로 줄인 값은 정확하지 않아 None."""
|
||||||
|
m = _RM_RE.search(text or "")
|
||||||
|
if not m:
|
||||||
|
return None, ""
|
||||||
|
raw, suffix = m.group(1), m.group(2)
|
||||||
|
shown = "RM" + raw + (suffix or "")
|
||||||
|
if suffix:
|
||||||
|
return None, shown
|
||||||
|
num = raw
|
||||||
|
if "." not in num and "," in num and len(num.rsplit(",", 1)[1]) <= 2: # 'RM672,2' = 점을 쉼표로 읽음
|
||||||
|
num = num[: num.rfind(",")] + "." + num.rsplit(",", 1)[1]
|
||||||
|
try:
|
||||||
|
value = Decimal(num.replace(",", ""))
|
||||||
|
except InvalidOperation:
|
||||||
|
return None, shown
|
||||||
|
return value.quantize(Decimal("0.01")), shown
|
||||||
|
|
||||||
|
|
||||||
|
def _ocr_text(img: Image.Image) -> str:
|
||||||
|
exe = shutil.which("tesseract")
|
||||||
|
if not exe:
|
||||||
|
raise LiveError("서버에 글자 인식 프로그램(tesseract)이 없습니다. 판매금액을 직접 입력하세요.")
|
||||||
|
gray = ImageOps.grayscale(img)
|
||||||
|
if gray.width < 1000: # 작은 캡처는 키워야 잘 읽힌다
|
||||||
|
gray = gray.resize((gray.width * 2, gray.height * 2), Image.LANCZOS)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
gray.save(buf, format="PNG")
|
||||||
|
try:
|
||||||
|
res = subprocess.run([exe, "stdin", "stdout", "-l", "eng", "--psm", "11"], input=buf.getvalue(),
|
||||||
|
capture_output=True, timeout=TIMEOUT_SECONDS, check=False)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
raise LiveError("이미지 글자 인식이 너무 오래 걸립니다. 판매금액을 직접 입력하세요.") from None
|
||||||
|
if res.returncode != 0:
|
||||||
|
raise LiveError("이미지 글자를 읽지 못했습니다. 판매금액을 직접 입력하세요.")
|
||||||
|
return res.stdout.decode("utf-8", "replace")
|
||||||
|
|
||||||
|
|
||||||
|
def read_sales(raw: bytes) -> tuple[Decimal | None, str]:
|
||||||
|
"""이미지 바이트 → (금액, 읽은 원문). 이미지가 아니면 ValueError(prepare_photo 문구)."""
|
||||||
|
data, _ctype, _w, _h = prepare_photo(raw) # 실제 이미지 확인·크기 제한(저장과 같은 규칙)
|
||||||
|
with Image.open(io.BytesIO(data)) as img:
|
||||||
|
img.load()
|
||||||
|
# 매출 카드는 화면 위쪽 — 위 절반만 읽어 빠르고, 아래 다른 금액을 잘못 잡지 않게
|
||||||
|
top = img.crop((0, 0, img.width, max(1, img.height // 2)))
|
||||||
|
return parse_sales(_ocr_text(top))
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
"""라이브 커머스(live) 라우터 — 말레이시아 라이브 방송의 호스트 정보·방송 스케줄(2026-11-04).
|
||||||
|
|
||||||
|
GET /live/ 스케줄표(?month=YYYY-MM) · GET /live/calendar 달력 보기(같은 달 값)
|
||||||
|
POST /live/broadcasts 방송 추가·고치기(id 칸이 있으면 고치기) + 결과 이미지 올리기
|
||||||
|
POST /live/broadcasts/{id}/delete 방송 지우기(이미지도 함께)
|
||||||
|
POST /live/broadcasts/{id}/move 달력에서 끌어 옮기기(broadcast_date·start_time) 또는 맞바꾸기(swap_with)
|
||||||
|
POST /live/ad-spend 날짜별 광고비(빈칸 = 지우기)
|
||||||
|
GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete
|
||||||
|
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보. `live_host` 칩은 이름·틱톡·상태만)
|
||||||
|
POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete
|
||||||
|
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자, `live` + `live_host` 칩 = 새 호스트 등록, `live` + `live_host_edit` 칩 = 고치기(둘 다 개인정보는 안 보임).
|
||||||
|
DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
|
||||||
|
저장 요청은 live.js 가 fetch 로 보내고 JSON {ok, message} 를 받는다(틀려도 입력한 값이 창에 남게).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
from pathlib import PurePath
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||||
|
|
||||||
|
from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo
|
||||||
|
from app.timezone import today_kst
|
||||||
|
|
||||||
|
from . import holidays, i18n, ocr, store
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/live", tags=["live"])
|
||||||
|
|
||||||
|
|
||||||
|
def _store(request: Request) -> Any:
|
||||||
|
return getattr(request.app.state, "live_store", None)
|
||||||
|
|
||||||
|
|
||||||
|
def _lang(request: Request) -> str:
|
||||||
|
return i18n.norm_lang(request.cookies.get(i18n.LANG_COOKIE))
|
||||||
|
|
||||||
|
|
||||||
|
def _t(request: Request, text: str) -> str:
|
||||||
|
return i18n.t(text, _lang(request))
|
||||||
|
|
||||||
|
|
||||||
|
def _user(request: Request) -> dict[str, Any]:
|
||||||
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
from app.store import has_module # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=401, detail=_t(request, "로그인이 필요합니다."))
|
||||||
|
if not has_module(user, "live"):
|
||||||
|
raise HTTPException(status_code=403, detail=_t(request, "라이브 커머스 모듈 권한이 없습니다."))
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _admin(request: Request) -> dict[str, Any]:
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
if not is_admin(user):
|
||||||
|
raise HTTPException(status_code=403, detail=_t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."))
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _can_add_host(user: dict[str, Any]) -> bool:
|
||||||
|
from app.store import has_module, is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
return is_admin(user) or has_module(user, "live_host")
|
||||||
|
|
||||||
|
|
||||||
|
def _can_edit_host(user: dict[str, Any]) -> bool:
|
||||||
|
from app.store import has_module, is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
return is_admin(user) or has_module(user, "live_host_edit")
|
||||||
|
|
||||||
|
|
||||||
|
def _db(request: Request) -> Any:
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
raise HTTPException(status_code=503, detail=_t(request, "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다."))
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _page(request: Request) -> Any:
|
||||||
|
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
|
||||||
|
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||||
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
return login_redirect(request)
|
||||||
|
if not has_module(user, "live"):
|
||||||
|
return render_template(request, "denied.html", {"reason": _t(request, "라이브 커머스 모듈 접근 권한이 없습니다."),
|
||||||
|
"is_admin": is_admin(user)}, status_code=403)
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
return render_template(request, "denied.html", {
|
||||||
|
"reason": _t(request, "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 "
|
||||||
|
".env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요."),
|
||||||
|
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="live")}, status_code=503)
|
||||||
|
return st, user
|
||||||
|
|
||||||
|
|
||||||
|
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any]) -> HTMLResponse:
|
||||||
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
lang = _lang(request)
|
||||||
|
return render_template(request, name, {"user": user, "is_admin": is_admin(user), "can_add_host": _can_add_host(user),
|
||||||
|
"can_edit_host": _can_edit_host(user), "lang": lang,
|
||||||
|
"t": lambda text: i18n.t(text, lang), "js_text": i18n.js_text(lang),
|
||||||
|
"hourly_rate": store.fmt_short(store.HOURLY_RATE), "commission_percent": store.fmt_short(store.COMMISSION_PERCENT),
|
||||||
|
"nav_items": build_erp_nav(user, active="live"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
|
def _ok(request: Request, message: str) -> JSONResponse:
|
||||||
|
return JSONResponse({"ok": True, "message": _t(request, message)})
|
||||||
|
|
||||||
|
|
||||||
|
def _fail(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
return JSONResponse({"ok": False, "message": i18n.error_text(exc, _lang(request))}, status_code=400)
|
||||||
|
|
||||||
|
|
||||||
|
def _opt_id(raw: str) -> int | None:
|
||||||
|
s = (raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
if not s.isdigit():
|
||||||
|
raise ValueError("잘못된 요청입니다.")
|
||||||
|
return int(s)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def health(request: Request) -> JSONResponse:
|
||||||
|
return JSONResponse({"status": "ok" if _store(request) is not None else "not_configured"})
|
||||||
|
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# 스케줄표
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
@router.get("/", response_class=HTMLResponse)
|
||||||
|
def index(request: Request, month: str = "") -> Any:
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
lang = _lang(request)
|
||||||
|
span = store.month_range(month, today_kst(), lang)
|
||||||
|
rows = [store.broadcast_view(b, lang) for b in st.list_broadcasts(span["start"], span["end"])]
|
||||||
|
return _render(request, "live/index.html", user, {"view": "table", "span": span, "rows": rows, "hosts": st.host_choices(),
|
||||||
|
"accounts": st.account_choices(), "max_images": store.MAX_IMAGES})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/calendar", response_class=HTMLResponse)
|
||||||
|
def calendar(request: Request, month: str = "") -> Any:
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
today, lang = today_kst(), _lang(request)
|
||||||
|
span = store.month_range(month, today, lang)
|
||||||
|
cal = store.build_calendar(span, st.list_broadcasts(span["start"], span["end"]), today, lang)
|
||||||
|
return _render(request, "live/calendar.html", user, {"view": "calendar", "span": span, "cal": cal, "hosts": st.host_choices(),
|
||||||
|
"accounts": st.account_choices(), "max_images": store.MAX_IMAGES,
|
||||||
|
"my_holidays": holidays.holiday_names(lang),
|
||||||
|
# 오른쪽 달력 점 — 앞뒤로 넘겨 볼 달까지(보는 달 ±1년)
|
||||||
|
"live_days": st.broadcast_days(span["start"] - timedelta(days=366), span["end"] + timedelta(days=366))})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts/{broadcast_id}/move")
|
||||||
|
def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Form(""), start_time: str = Form(""),
|
||||||
|
swap_with: str = Form("")) -> JSONResponse:
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
other = _opt_id(swap_with)
|
||||||
|
if other is not None:
|
||||||
|
st.swap_broadcasts(broadcast_id, other, by=user.get("email", ""))
|
||||||
|
else:
|
||||||
|
day, start = store.parse_move(broadcast_date, start_time)
|
||||||
|
st.move_broadcast(broadcast_id, day, start, by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "옮겼습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]:
|
||||||
|
"""고른 파일을 실제 이미지로 확인·메타데이터 제거(GPS 등). 틀리면 ValueError — 아무것도 저장하지 않게 DB 전에."""
|
||||||
|
picked = [f for f in files if f.filename]
|
||||||
|
if len(picked) > store.MAX_IMAGES:
|
||||||
|
raise i18n.LiveError("방송 한 건에 이미지는 {max}장까지입니다.", max=store.MAX_IMAGES)
|
||||||
|
out = []
|
||||||
|
for f in picked:
|
||||||
|
name = PurePath(f.filename.replace("\\", "/")).name[:200]
|
||||||
|
try:
|
||||||
|
data, ctype, width, height = prepare_photo(f.file.read(MAX_PHOTO_BYTES + 1))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise i18n.LiveError("{name}: {detail}", name=name, detail=str(exc)) from None
|
||||||
|
out.append({"filename": name, "content_type": ctype, "data": data, "width": width, "height": height})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts")
|
||||||
|
def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form(""), broadcast_date: str = Form(""),
|
||||||
|
start_time: str = Form(""), end_time: str = Form(""), tiktok_handle: str = Form(""),
|
||||||
|
sales_amount: str = Form(""), ad_spend: str = Form(""), host_fee: str = Form(""),
|
||||||
|
images: list[UploadFile] = File(default=[])) -> JSONResponse:
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
broadcast_id = _opt_id(id)
|
||||||
|
values = store.clean_broadcast({"host_id": host_id, "broadcast_date": broadcast_date, "start_time": start_time, "end_time": end_time,
|
||||||
|
"tiktok_handle": tiktok_handle, "sales_amount": sales_amount, "ad_spend": ad_spend, "host_fee": host_fee})
|
||||||
|
st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "저장했습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts/read-sales")
|
||||||
|
def broadcast_read_sales(request: Request, image: UploadFile = File(...)) -> JSONResponse:
|
||||||
|
"""결과 이미지(틱톡 LIVE 결과 화면)에서 매출 읽기 — 저장하지 않고 값만 돌려준다(창이 판매금액 칸에 채움)."""
|
||||||
|
_user(request)
|
||||||
|
try:
|
||||||
|
amount, shown = ocr.read_sales(image.file.read(MAX_PHOTO_BYTES + 1))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
if amount is None:
|
||||||
|
msg = (_t(request, "이미지 매출이 줄인 값({value})이라 정확하지 않습니다. 판매금액을 직접 입력하세요.").format(value=shown) if shown
|
||||||
|
else _t(request, "이미지에서 매출(RM)을 찾지 못했습니다. 판매금액을 직접 입력하세요."))
|
||||||
|
return JSONResponse({"ok": True, "amount": None, "message": msg})
|
||||||
|
return JSONResponse({"ok": True, "amount": str(amount), "message": _t(request, "이미지에서 매출 {value} 를 읽었습니다. 확인 후 저장하세요.").format(value=shown)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/broadcasts/{broadcast_id}/delete")
|
||||||
|
def broadcast_delete(request: Request, broadcast_id: int) -> JSONResponse:
|
||||||
|
_user(request)
|
||||||
|
try:
|
||||||
|
_db(request).delete_broadcast(broadcast_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "방송을 지웠습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/images/{image_id}")
|
||||||
|
def image(request: Request, image_id: int, thumb: int = 0) -> Response:
|
||||||
|
_user(request)
|
||||||
|
row = _db(request).get_image(image_id)
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail=_t(request, "이미지를 찾을 수 없습니다."))
|
||||||
|
data, ctype = (store.thumbnail(row["data"]), "image/jpeg") if thumb else (bytes(row["data"]), row["content_type"])
|
||||||
|
# 올린 뒤 내용이 바뀌지 않으므로 하루 캐시. 권한이 필요한 이미지라 private.
|
||||||
|
return Response(data, media_type=ctype, headers={"Cache-Control": "private, max-age=86400", "X-Content-Type-Options": "nosniff"})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/images/{image_id}/delete")
|
||||||
|
def image_delete(request: Request, image_id: int) -> JSONResponse:
|
||||||
|
_user(request)
|
||||||
|
try:
|
||||||
|
_db(request).delete_image(image_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "이미지를 지웠습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보). `live_host` 칩 = 새 호스트 등록만.
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
@router.get("/settings", response_class=HTMLResponse)
|
||||||
|
def settings(request: Request) -> Any:
|
||||||
|
from app.main import render_template # noqa: WPS433
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
if not (_can_add_host(user) or _can_edit_host(user)):
|
||||||
|
return render_template(request, "denied.html", {"reason": _t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."), "is_admin": False},
|
||||||
|
status_code=403)
|
||||||
|
# host_choices = 이름·상태뿐 — 계좌 등 개인정보는 칩이 있어도 관리자에게만
|
||||||
|
return _render(request, "live/settings.html", user, {"hosts": st.list_hosts() if is_admin(user) else st.host_choices()})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/hosts")
|
||||||
|
def host_save(request: Request, id: str = Form(""), platform: str = Form(""), display_name: str = Form(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""),
|
||||||
|
address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""),
|
||||||
|
is_active: str = Form("")) -> JSONResponse:
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
# `live_host` 칩 = 새 등록, `live_host_edit` 칩 = 고치기(개인정보는 안 보이고, 비워 두면 그대로)
|
||||||
|
user = _user(request)
|
||||||
|
if not (_can_edit_host(user) if id.strip() else _can_add_host(user)):
|
||||||
|
_admin(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
values = store.clean_host({"platform": platform, "display_name": display_name, "full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name,
|
||||||
|
"bank_account": bank_account})
|
||||||
|
host_id = _opt_id(id)
|
||||||
|
if host_id is not None and not is_admin(user): # 개인정보를 못 보므로 빈칸 = 지우기가 아니라 그대로
|
||||||
|
old = st.get_host(host_id)
|
||||||
|
if not old:
|
||||||
|
raise i18n.LiveError("호스트를 찾을 수 없습니다.")
|
||||||
|
values.update({k: values[k] or old[k] for k in store.PRIVATE_HOST_FIELDS})
|
||||||
|
# 등록만 되는 칩 화면엔 사용 여부 칸이 없다 — 항상 사용(사용 안 함으로 만들면 본인이 되돌릴 수 없음)
|
||||||
|
st.save_host(host_id, values, is_active=bool(is_active) or not _can_edit_host(user), by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "호스트를 저장했습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/hosts/{host_id}/active")
|
||||||
|
def host_active(request: Request, host_id: int, is_active: str = Form("")) -> JSONResponse:
|
||||||
|
"""목록의 사용 토글 — 고치기 권한(ERP 관리자·`live_host_edit` 칩)."""
|
||||||
|
user = _user(request)
|
||||||
|
if not _can_edit_host(user):
|
||||||
|
_admin(request)
|
||||||
|
try:
|
||||||
|
_db(request).set_host_active(host_id, is_active == "1", by=user.get("email", ""))
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "사용으로 바꿨습니다." if is_active == "1" else "사용 안 함으로 바꿨습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/hosts/{host_id}/delete")
|
||||||
|
def host_delete(request: Request, host_id: int) -> JSONResponse:
|
||||||
|
_admin(request)
|
||||||
|
try:
|
||||||
|
_db(request).delete_host(host_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
return _fail(request, exc)
|
||||||
|
return _ok(request, "호스트를 지웠습니다.")
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
"""라이브 커머스 순수 함수 — 입력 검사·표시 형식(DB 없이 시험 가능)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from .i18n import LiveError, month_label
|
||||||
|
|
||||||
|
MAX_IMAGES = 10 # 방송 한 건에
|
||||||
|
MAX_SALES = Decimal("999999999999.99")
|
||||||
|
THUMB_SIZE = 160
|
||||||
|
# shortcut: 요율이 코드 상수라 바꾸면 지난 방송 금액도 다시 계산된다 — 요율이 바뀌는 일이 생기면 방송마다 저장하도록 바꿀 것
|
||||||
|
HOURLY_RATE = Decimal("25") # 호스트 시간당 요금(RM)
|
||||||
|
COMMISSION_PERCENT = Decimal("10") # 판매금액의 %
|
||||||
|
SLOT_HOURS = 1 # 달력 한 칸(2026-11-06, 2시간 → 1시간)
|
||||||
|
FIRST_SLOT_HOUR = 6 # 달력에 늘 보이는 첫 칸(이보다 이른 칸은 방송이 있을 때만)
|
||||||
|
HOST_COLORS = ("#66d4e6", "#6ee05a", "#d4f06a", "#e9cf7a", "#ec9d88", "#cdb9ea", "#f4a9c8", "#a9c4f5")
|
||||||
|
_CENT = Decimal("0.01")
|
||||||
|
_WEEKDAYS = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY")
|
||||||
|
_MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC")
|
||||||
|
|
||||||
|
HOST_LIMITS = {"display_name": 50, "full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40}
|
||||||
|
HANDLE_LIMIT = 64
|
||||||
|
PLATFORMS = ("tiktok", "shopee") # 호스트 쇼핑몰(005) — 로고 = /static/dispatch/courier/<값>.png(말레이시아 배송 모듈 이미지)
|
||||||
|
PRIVATE_HOST_FIELDS = ("phone", "email", "address", "bank_name", "bank_account") # 화면에 보이는 사람 = ERP 관리자만
|
||||||
|
_LABELS = {"display_name": "간단한 이름", "full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명",
|
||||||
|
"bank_account": "계좌번호"}
|
||||||
|
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
|
||||||
|
_PHONE_RE = re.compile(r"^\+?[0-9()\-\s]+$")
|
||||||
|
_ACCOUNT_RE = re.compile(r"^[0-9\-\s]+$")
|
||||||
|
_HANDLE_RE = re.compile(r"^[A-Za-z0-9._]+$")
|
||||||
|
_HANDLE_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?tiktok\.com/@?", re.I)
|
||||||
|
WEEKDAYS_KO = "월화수목금토일"
|
||||||
|
_WEEKDAYS_EN_SHORT = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||||
|
|
||||||
|
|
||||||
|
def clean_handle(raw: Any) -> str:
|
||||||
|
"""'@name'·'https://www.tiktok.com/@name?lang=en' → 'name'."""
|
||||||
|
s = _HANDLE_URL_RE.sub("", str(raw or "").strip())
|
||||||
|
return re.split(r"[/?#]", s, maxsplit=1)[0].lstrip("@")
|
||||||
|
|
||||||
|
|
||||||
|
def clean_host(values: dict[str, Any]) -> dict[str, str]:
|
||||||
|
"""호스트 입력 검사 — 쇼핑몰·간단한 이름·이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError."""
|
||||||
|
out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS}
|
||||||
|
out["platform"] = str(values.get("platform") or "").strip().lower()
|
||||||
|
if out["platform"] not in PLATFORMS:
|
||||||
|
raise LiveError("쇼핑몰(틱톡·쇼피)을 고르세요.")
|
||||||
|
if not out["display_name"]:
|
||||||
|
raise LiveError("간단한 이름을 입력하세요.")
|
||||||
|
if not out["full_name"]:
|
||||||
|
raise LiveError("이름 (IC 기준)을 입력하세요.")
|
||||||
|
for key, limit in HOST_LIMITS.items():
|
||||||
|
if len(out[key]) > limit:
|
||||||
|
raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label=_LABELS[key], limit=limit)
|
||||||
|
if out["email"] and not _EMAIL_RE.match(out["email"]):
|
||||||
|
raise LiveError("이메일 형식이 올바르지 않습니다.")
|
||||||
|
if out["phone"] and not _PHONE_RE.match(out["phone"]):
|
||||||
|
raise LiveError("전화번호는 숫자·+·-·괄호만 입력하세요.")
|
||||||
|
if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]):
|
||||||
|
raise LiveError("계좌번호는 숫자·-만 입력하세요.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def parse_money(raw: Any, label: str = "판매금액") -> Decimal | None:
|
||||||
|
"""금액(RM) — 빈칸은 None(아직 입력 안 함), 0 이상, 소수 둘째 자리까지. 쉼표·RM 허용."""
|
||||||
|
s = re.sub(r"(?i)^rm|[,\s]", "", str(raw if raw is not None else "").strip())
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
n = Decimal(s)
|
||||||
|
except InvalidOperation:
|
||||||
|
raise LiveError("{label}은(는) 숫자로 입력하세요.", label=label) from None
|
||||||
|
if not n.is_finite() or n < 0:
|
||||||
|
raise LiveError("{label}은(는) 0 이상 숫자로 입력하세요.", label=label)
|
||||||
|
if n > MAX_SALES:
|
||||||
|
raise LiveError("{label}이(가) 너무 큽니다.", label=label)
|
||||||
|
return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_time(raw: Any, *, label: str, required: bool) -> time | None:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
if required:
|
||||||
|
raise LiveError("{label}을 입력하세요.", label=label)
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return time.fromisoformat(s).replace(second=0, microsecond=0, tzinfo=None)
|
||||||
|
except ValueError:
|
||||||
|
raise LiveError("{label}이 올바르지 않습니다.", label=label) from None
|
||||||
|
|
||||||
|
|
||||||
|
def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""방송 입력 검사 — 호스트·날짜·시작·끝 시간 필수(끝 시간으로 시간 요금 계산). 끝이 시작보다 이르면 자정을 넘긴 방송. 틀리면 ValueError."""
|
||||||
|
host = str(values.get("host_id") or "").strip()
|
||||||
|
if not host.isdigit():
|
||||||
|
raise LiveError("호스트를 고르세요.")
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(str(values.get("broadcast_date") or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
raise LiveError("방송 날짜를 입력하세요.") from None
|
||||||
|
start = _parse_time(values.get("start_time"), label="시작 시간", required=True)
|
||||||
|
end = _parse_time(values.get("end_time"), label="끝 시간", required=True)
|
||||||
|
if start == end:
|
||||||
|
raise LiveError("끝 시간이 시작 시간과 같습니다.")
|
||||||
|
handle = clean_handle(values.get("tiktok_handle"))
|
||||||
|
if len(handle) > HANDLE_LIMIT:
|
||||||
|
raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label="틱톡 핸들", limit=HANDLE_LIMIT)
|
||||||
|
if handle and not _HANDLE_RE.match(handle):
|
||||||
|
raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.")
|
||||||
|
return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end, "tiktok_handle": handle,
|
||||||
|
"sales_amount": parse_money(values.get("sales_amount")), "ad_spend": parse_money(values.get("ad_spend"), "광고비"),
|
||||||
|
"host_fee": parse_money(values.get("host_fee"), "호스트 비용")}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_move(day: Any, start: Any) -> tuple[date, time]:
|
||||||
|
"""달력 칸 — 날짜·시작 시간. 틀리면 ValueError."""
|
||||||
|
try:
|
||||||
|
when = date.fromisoformat(str(day or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
raise LiveError("날짜가 올바르지 않습니다.") from None
|
||||||
|
return when, _parse_time(start, label="시간", required=True)
|
||||||
|
|
||||||
|
|
||||||
|
def moved_end(old_start: time, old_end: time | None, new_start: time) -> time | None:
|
||||||
|
"""칸을 옮겨도 방송 길이는 그대로."""
|
||||||
|
if old_end is None:
|
||||||
|
return None
|
||||||
|
return (datetime.combine(date.min, new_start) + _duration(old_start, old_end)).time()
|
||||||
|
|
||||||
|
|
||||||
|
def _duration(start: time, end: time) -> timedelta:
|
||||||
|
minutes = (end.hour * 60 + end.minute - start.hour * 60 - start.minute) % 1440 # 끝이 더 이르면 자정을 넘긴 방송
|
||||||
|
return timedelta(minutes=minutes)
|
||||||
|
|
||||||
|
|
||||||
|
def session_pay(start: time, end: time | None, sales: Decimal | None) -> dict[str, Decimal]:
|
||||||
|
"""참고 금액(저장 안 함) — Fee = 시간 × 시간당 요금, 커미션 = 판매금액 × %. 같은 계산이 방송 창에도(live.js recalc).
|
||||||
|
호스트 비용은 2026-11-06 부터 수기 입력(live_broadcasts.host_fee)."""
|
||||||
|
hours = Decimal(_duration(start, end).seconds) / 3600 if end else Decimal(0)
|
||||||
|
base = (hours * HOURLY_RATE).quantize(_CENT, rounding=ROUND_HALF_UP)
|
||||||
|
commission = ((sales or Decimal(0)) * COMMISSION_PERCENT / 100).quantize(_CENT, rounding=ROUND_HALF_UP)
|
||||||
|
return {"hours": hours, "base": base, "commission": commission}
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_short(n: Decimal) -> str:
|
||||||
|
"""카드·합계용 — 소수점 아래가 0 이면 뺀다(48, 4.80, 1,234.50)."""
|
||||||
|
return f"{n:,.2f}".removesuffix(".00")
|
||||||
|
|
||||||
|
|
||||||
|
def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]:
|
||||||
|
"""방송 한 건 화면 값 — 표·달력 공통. b = db.list_broadcasts 한 줄."""
|
||||||
|
pay = session_pay(b["start_time"], b["end_time"], b["sales_amount"])
|
||||||
|
return {
|
||||||
|
"date": fmt_date(b["broadcast_date"], lang), "times": fmt_times(b["start_time"], b["end_time"]),
|
||||||
|
"host_name": b["host_name"], "tiktok_handle": b["tiktok_handle"], "venue": b["venue"],
|
||||||
|
"platform": b["host_platform"], # 호스트 쇼핑몰(tiktok·shopee, '' = 아직 안 고름) — 아이콘 /static/live-icon-<값>.png
|
||||||
|
"sales": fmt_money(b["sales_amount"]), "base": fmt_money(pay["base"]), "commission": fmt_money(pay["commission"]),
|
||||||
|
"ad_spend": fmt_money(b["ad_spend"]), "host_fee": fmt_money(b["host_fee"]),
|
||||||
|
"images": b["images"], "id": b["id"],
|
||||||
|
"label": b["host_name"], "color": HOST_COLORS[b["host_id"] % len(HOST_COLORS)],
|
||||||
|
"card_sales": fmt_short(b["sales_amount"] or Decimal(0)), "card_commission": fmt_short(pay["commission"]),
|
||||||
|
"card_fee": fmt_short(b["host_fee"] or Decimal(0)),
|
||||||
|
"edit": {"id": b["id"], "host_id": b["host_id"], "broadcast_date": b["broadcast_date"].isoformat(),
|
||||||
|
"start_time": f"{b['start_time']:%H:%M}", "end_time": f"{b['end_time']:%H:%M}" if b["end_time"] else "",
|
||||||
|
"tiktok_handle": b["tiktok_handle"],
|
||||||
|
**{k: f"{b[k]:.2f}" if b[k] is not None else "" for k in ("sales_amount", "ad_spend", "host_fee")},
|
||||||
|
"images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _roas(sales: Decimal, ad_spend: Decimal) -> str:
|
||||||
|
return f"{sales / ad_spend:.2f}" if ad_spend else "-"
|
||||||
|
|
||||||
|
|
||||||
|
def _slot_of(hour: int) -> int:
|
||||||
|
return hour // SLOT_HOURS * SLOT_HOURS
|
||||||
|
|
||||||
|
|
||||||
|
def _covered_slots(b: dict[str, Any]) -> list[int]:
|
||||||
|
"""방송이 걸친 칸(시작 칸 ~ 끝 시각 올림 직전 칸). 자정을 넘기거나 00:00 에 끝나면 그날 마지막 칸까지."""
|
||||||
|
s, e = b["start_time"], b["end_time"]
|
||||||
|
end = 24 if e <= s else e.hour + (1 if (e.minute or e.second) else 0)
|
||||||
|
return sorted({_slot_of(h) for h in range(s.hour, max(end, s.hour + 1))})
|
||||||
|
|
||||||
|
|
||||||
|
def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], today: date, lang: str = "ko") -> dict[str, Any]:
|
||||||
|
"""달력 보기 값 — 날짜(열)·SLOT_HOURS 칸(줄)·날짜별 합계(판매금액·광고비·호스트 비용 = 그날 방송 값 합, 2026-11-06)·달 합계.
|
||||||
|
카드는 시작 칸에, 그 칸은 방송이 걸친 칸만큼 아래로 합친다
|
||||||
|
(rowspan, 2026-11-06). 합친 칸 안에서 시작하는 다른 방송도 같은 칸에 들어가고 더 길면 칸이 더 늘어난다. 가려진 칸 = {"skip": True}."""
|
||||||
|
views = [(b, broadcast_view(b, lang)) for b in broadcasts]
|
||||||
|
used = {h for b, _ in views for h in _covered_slots(b)}
|
||||||
|
days = []
|
||||||
|
day = span["start"]
|
||||||
|
while day < span["end"]:
|
||||||
|
mine = [(b, v) for b, v in views if b["broadcast_date"] == day]
|
||||||
|
sales, fee, spend = (sum((b[k] or Decimal(0) for b, _ in mine), Decimal(0)) for k in ("sales_amount", "host_fee", "ad_spend"))
|
||||||
|
days.append({"iso": day.isoformat(), "date": day, "day": day.day, "weekday": _WEEKDAYS[day.weekday()] if lang == "en" else WEEKDAYS_KO[day.weekday()] + "요일",
|
||||||
|
"label": f"{day.day} {_MONTHS[day.month - 1]}" if lang == "en" else f"{day.month}월 {day.day}일", "is_weekend": day.weekday() >= 5, "is_today": day == today,
|
||||||
|
"count": len(mine), "sales": sales, "fee": fee, "spend": spend,
|
||||||
|
"sales_text": fmt_short(sales), "fee_text": fmt_short(fee), "spend_text": fmt_short(spend), "roas": _roas(sales, spend)})
|
||||||
|
day += timedelta(days=1)
|
||||||
|
hours = sorted(set(range(FIRST_SLOT_HOUR, 24, SLOT_HOURS)) | used) # 방송이 걸친 칸은 늘 있음 → 합칠 칸이 이어져 있다
|
||||||
|
columns = []
|
||||||
|
for d in days:
|
||||||
|
mine = [(b, v) for b, v in views if b["broadcast_date"] == d["date"]]
|
||||||
|
col, i = [], 0
|
||||||
|
while i < len(hours):
|
||||||
|
group = [(b, v) for b, v in mine if _slot_of(b["start_time"].hour) == hours[i]]
|
||||||
|
last, j = max((_covered_slots(b)[-1] for b, _ in group), default=hours[i]), i + 1
|
||||||
|
while j < len(hours) and hours[j] <= last:
|
||||||
|
more = [(b, v) for b, v in mine if _slot_of(b["start_time"].hour) == hours[j]]
|
||||||
|
group += more
|
||||||
|
last = max([last] + [_covered_slots(b)[-1] for b, _ in more])
|
||||||
|
j += 1
|
||||||
|
col.append({"iso": d["iso"], "is_weekend": d["is_weekend"], "cards": [v for _, v in group], "rowspan": j - i})
|
||||||
|
col += [{"skip": True}] * (j - i - 1)
|
||||||
|
i = j
|
||||||
|
columns.append(col)
|
||||||
|
slots = []
|
||||||
|
for k, hour in enumerate(hours):
|
||||||
|
end_hour = (hour + SLOT_HOURS) % 24
|
||||||
|
slots.append({"start": f"{hour:02d}:00", "end": f"{end_hour:02d}:00", "label": f"{hour:02d}:00 - {end_hour:02d}:00",
|
||||||
|
"cells": [col[k] for col in columns]})
|
||||||
|
sales, fee, spend = (sum((d[k] for d in days), Decimal(0)) for k in ("sales", "fee", "spend"))
|
||||||
|
return {"days": days, "slots": slots, "slot_note": f"{SLOT_HOURS} Hour{'s' if SLOT_HOURS > 1 else ''} (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)" if lang == "en" else f"{SLOT_HOURS}시간 (기본 RM{fmt_short(HOURLY_RATE * SLOT_HOURS)})",
|
||||||
|
"commission_percent": fmt_short(COMMISSION_PERCENT).split(".")[0],
|
||||||
|
"totals": {"sales": fmt_short(sales), "fee": fmt_short(fee), "spend": fmt_short(spend), "roas": _roas(sales, spend)}}
|
||||||
|
|
||||||
|
|
||||||
|
def month_range(raw: Any, today: date, lang: str = "ko") -> dict[str, Any]:
|
||||||
|
"""'YYYY-MM'(틀리거나 없으면 이번 달) → 그 달 첫날·다음 달 첫날·앞뒤 달 주소 값·제목."""
|
||||||
|
m = re.fullmatch(r"(\d{4})-(\d{2})", str(raw or "").strip())
|
||||||
|
year, month = (int(m[1]), int(m[2])) if m and 2000 <= int(m[1]) <= 2100 and 1 <= int(m[2]) <= 12 else (today.year, today.month)
|
||||||
|
start = date(year, month, 1)
|
||||||
|
end = date(year + (month == 12), month % 12 + 1, 1)
|
||||||
|
prev = date(year - (month == 1), (month - 2) % 12 + 1, 1)
|
||||||
|
return {"start": start, "end": end, "prev": prev.strftime("%Y-%m"), "next": end.strftime("%Y-%m"),
|
||||||
|
"label": month_label(year, month, lang)}
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_date(d: date, lang: str = "ko") -> str:
|
||||||
|
return f"{d:%Y.%m.%d} ({_WEEKDAYS_EN_SHORT[d.weekday()]})" if lang == "en" else f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_times(start: time, end: time | None) -> str:
|
||||||
|
return f"{start:%H:%M}" + (f" ~ {end:%H:%M}" if end else "")
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_money(n: Decimal | None) -> str:
|
||||||
|
return f"{n:,.2f}" if n is not None else ""
|
||||||
|
|
||||||
|
|
||||||
|
def thumbnail(data: bytes) -> bytes:
|
||||||
|
"""목록 작은 그림 — JPEG(투명은 흰 바탕). 저장할 때 이미 확인한 이미지만 들어온다."""
|
||||||
|
with Image.open(io.BytesIO(data)) as source:
|
||||||
|
source.thumbnail((THUMB_SIZE, THUMB_SIZE))
|
||||||
|
rgba = source.convert("RGBA")
|
||||||
|
canvas = Image.new("RGB", rgba.size, "white")
|
||||||
|
canvas.paste(rgba, mask=rgba.getchannel("A"))
|
||||||
|
out = io.BytesIO()
|
||||||
|
canvas.save(out, format="JPEG", quality=80)
|
||||||
|
return out.getvalue()
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{#- 스케줄표·달력 공통 위 막대 — 달 이동, 표/달력 전환, 언어, 호스트 설정, 방송 추가. view = table | calendar -#}
|
||||||
|
{% set here = '/live/calendar' if view == 'calendar' else '/live/' %}
|
||||||
|
{% set can_add = hosts | selectattr('is_active') | list %}
|
||||||
|
<div class="lv-bar">
|
||||||
|
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.prev }}" aria-label="{{ t('이전 달') }}">◀</a>
|
||||||
|
<h2 class="lv-month">{{ span.label }}</h2>
|
||||||
|
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.next }}" aria-label="{{ t('다음 달') }}">▶</a>
|
||||||
|
<nav class="lv-views" aria-label="{{ t('보기 방식') }}">
|
||||||
|
<a class="erp-btn {{ 'erp-btn-primary' if view == 'table' else 'erp-btn-outline' }}" href="/live/?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'table' %} aria-current="page"{% endif %}>{{ t('표') }}</a>
|
||||||
|
<a class="erp-btn {{ 'erp-btn-primary' if view == 'calendar' else 'erp-btn-outline' }}" href="/live/calendar?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'calendar' %} aria-current="page"{% endif %}>{{ t('달력') }}</a>
|
||||||
|
</nav>
|
||||||
|
<span class="lv-gap"></span>
|
||||||
|
{% include "live/_lang.html" %}
|
||||||
|
{% if can_add_host or can_edit_host %}<a class="erp-btn erp-btn-outline" href="/live/settings">{{ t('호스트 설정') }}</a>{% endif %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="lv-add"{% if not can_add %} disabled{% endif %}>{{ t('+ 방송 추가') }}</button>
|
||||||
|
</div>
|
||||||
|
{% if not can_add %}
|
||||||
|
<p class="lv-note">{{ t('방송을 추가하려면 먼저 호스트를 등록해야 합니다.') }} {% if can_add_host %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름만(계좌 등은 설정 화면). 틱톡 계정은 방송마다 — 쓴 적 있는 계정을 제안(새 계정도 입력 가능). -#}
|
||||||
|
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||||
|
<form id="lv-form" action="/live/broadcasts">
|
||||||
|
<h3 id="lv-dlg-title" data-add="{{ t('방송 추가') }}" data-edit="{{ t('방송 고치기') }}"></h3>
|
||||||
|
<input type="hidden" name="id" />
|
||||||
|
<label class="lv-field">{{ t('호스트') }}
|
||||||
|
<select class="erp-select" name="host_id" required>
|
||||||
|
<option value="">{{ t('호스트를 고르세요') }}</option>
|
||||||
|
{% for h in hosts %}<option value="{{ h.id }}"{% if not h.is_active %} data-inactive="1"{% endif %}>{{ h.display_name or h.full_name }}{% if not h.is_active %} — {{ t('사용 안 함') }}{% endif %}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="lv-field">{{ t('틱톡 핸들') }} <input class="erp-input" type="text" name="tiktok_handle" maxlength="200" placeholder="@handle" list="lv-accounts" autocomplete="off" /></label>
|
||||||
|
<datalist id="lv-accounts">{% for a in accounts %}<option value="{{ a }}"></option>{% endfor %}</datalist>
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('방송 날짜') }} <input class="erp-input" type="date" name="broadcast_date" required /></label>
|
||||||
|
<label class="lv-field">{{ t('시작 시간') }} <input class="erp-input" type="time" name="start_time" required /></label>
|
||||||
|
<label class="lv-field">{{ t('끝 시간') }} <input class="erp-input" type="time" name="end_time" required /></label>
|
||||||
|
</div>
|
||||||
|
<p class="lv-sub">{{ t('시간은 말레이시아 시간으로 입력합니다.') }}</p>
|
||||||
|
<label class="lv-field">{{ t('판매금액 (RM)') }} <input class="erp-input lv-num" type="text" name="sales_amount" inputmode="decimal" placeholder="{{ t('방송 후 입력') }}" /></label>
|
||||||
|
{#- Fee·커미션 = 자동 계산(저장 안 함, live.js recalc — store.session_pay 와 같은 계산). 광고비·호스트 비용 = 입력(2026-11-06) -#}
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('시간 요금 (RM)') }} <input class="erp-input lv-num" type="text" data-fee="{{ hourly_rate }}" readonly />
|
||||||
|
<small class="lv-sub">{{ t('시간 × RM {rate} — 자동').format(rate=hourly_rate) }}</small></label>
|
||||||
|
<label class="lv-field">{{ t('커미션 (RM)') }} <input class="erp-input lv-num" type="text" data-commission="{{ commission_percent }}" readonly />
|
||||||
|
<small class="lv-sub">{{ t('판매금액 × {percent}% — 자동').format(percent=commission_percent) }}</small></label>
|
||||||
|
</div>
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('광고비 (RM)') }} <input class="erp-input lv-num" type="text" name="ad_spend" inputmode="decimal" /></label>
|
||||||
|
<label class="lv-field">{{ t('호스트 비용 (RM)') }} <input class="erp-input lv-num" type="text" name="host_fee" inputmode="decimal" placeholder="{{ t('직접 입력') }}" /></label>
|
||||||
|
</div>
|
||||||
|
<label class="lv-field">{{ t('방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)').format(n=max_images) }}
|
||||||
|
<input type="file" name="images" accept="image/jpeg,image/png,image/webp" multiple />
|
||||||
|
</label>
|
||||||
|
<ul class="lv-saved" data-saved hidden></ul>
|
||||||
|
<p class="lv-msg" data-msg role="alert" hidden></p>
|
||||||
|
<div class="lv-foot">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{#- 한글·영문 전환 — 누르면 쿠키에 저장하고 다시 그린다(live.js). 언어 이름은 언어와 상관없이 그대로 보인다. -#}
|
||||||
|
<div class="lv-lang" role="group" aria-label="{{ t('언어') }}">
|
||||||
|
<button type="button" data-lang="ko"{% if lang != 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>한글</button>
|
||||||
|
<button type="button" data-lang="en"{% if lang == 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>EN</button>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<script>window.LV_T = {{ js_text | tojson }};</script>
|
||||||
|
<script src="/static/live.js?v=20261106f" defer></script>
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정.
|
||||||
|
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106h" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="lv-split">
|
||||||
|
<section class="lv" lang="{{ lang }}">
|
||||||
|
{% include "live/_bar.html" %}
|
||||||
|
|
||||||
|
<div class="lv-kpis">
|
||||||
|
<div class="lv-kpi"><span>{{ t('총 판매금액') }}</span><b>RM {{ cal.totals.sales }}</b></div>
|
||||||
|
<div class="lv-kpi"><span>{{ t('광고비') }}</span><b>RM {{ cal.totals.spend }}</b></div>
|
||||||
|
<div class="lv-kpi"><span>{{ t('호스트 비용') }}</span><b>RM {{ cal.totals.fee }}</b></div>
|
||||||
|
<div class="lv-kpi"><span>ROAS</span><b>{{ cal.totals.roas }}</b></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="lv-tip">{{ t('팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.').format(n=cal.days | length) }}</p>
|
||||||
|
|
||||||
|
<div class="lv-cal-wrap" id="lv-cal-wrap">
|
||||||
|
<table class="lv-cal">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="lv-cal-time" scope="col">{{ t('시간') }}</th>
|
||||||
|
{% for d in cal.days %}
|
||||||
|
<th scope="col" data-day="{{ d.iso }}"{% if d.is_today %} data-today="1"{% endif %} class="{% if d.is_weekend %}is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}">
|
||||||
|
<div class="lv-cal-weekday">{{ d.weekday }} <span class="lv-cal-count">{{ d.count }}</span></div>
|
||||||
|
<div class="lv-cal-date">{{ d.label }}</div>
|
||||||
|
</th>
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for slot in cal.slots %}
|
||||||
|
<tr>
|
||||||
|
<th class="lv-cal-time" scope="row">{{ slot.label }}<small>{{ cal.slot_note }}</small></th>
|
||||||
|
{% for cell in slot.cells %}{% if not cell.skip %}{#- skip = 위 칸에 합쳐진 칸(방송이 걸친 시간만큼 rowspan) -#}
|
||||||
|
<td class="lv-cell{% if cell.is_weekend %} is-weekend{% endif %}"{% if cell.rowspan > 1 %} rowspan="{{ cell.rowspan }}"{% endif %} data-drop data-day="{{ cell.iso }}" data-start="{{ slot.start }}">
|
||||||
|
{% if cell.cards %}<div class="lv-cards">{% endif %}{#- 카드가 합친 칸 높이를 채움(live.css) -#}
|
||||||
|
{% for c in cell.cards %}
|
||||||
|
<article class="lv-card" data-card="{{ c.id }}">
|
||||||
|
<header class="lv-card-head" draggable="true" style="background:{{ c.color }}" title="{{ c.host_name }} · {{ c.times }}{% if c.venue %} · {{ c.venue }}{% endif %}">
|
||||||
|
{% if c.platform %}<img class="lv-card-pf" src="/static/live-icon-{{ c.platform }}.png" alt="{{ {'tiktok': 'TikTok', 'shopee': 'Shopee'}[c.platform] }}" />{% endif %}
|
||||||
|
<span class="lv-card-name">{{ c.label }}{% if c.tiktok_handle %}<small>@{{ c.tiktok_handle }}</small>{% endif %}</span>
|
||||||
|
<button type="button" class="lv-card-edit" data-edit='{{ c.edit | tojson }}' aria-label="{{ t('{name} {date} {times} 고치기').format(name=c.label, date=c.date, times=c.times) }}">✎</button>
|
||||||
|
</header>
|
||||||
|
<div class="lv-card-nums">
|
||||||
|
<div><span>{{ t('판매금액') }}</span><b>{{ c.card_sales }}</b></div>
|
||||||
|
<div><span>{{ t('커미션') }} ({{ cal.commission_percent }}%)</span><b>{{ c.card_commission }}</b></div>
|
||||||
|
</div>
|
||||||
|
<footer class="lv-card-foot"><span>{{ t('비용') }}: <b>RM{{ c.card_fee }}</b></span>{% if c.images %}<a href="/live/images/{{ c.images[0].id }}" target="_blank" rel="noopener" title="{{ t('방송 결과 이미지') }}" data-preview="{{ c.label }} · {{ c.date }} {{ c.times }}{% if c.images | length > 1 %} · 1/{{ c.images | length }}{% endif %}" data-images='{{ c.images | map(attribute="id") | list | tojson }}' data-names='{{ c.images | map(attribute="filename") | list | tojson }}'>{{ t('이미지 {n}').format(n=c.images | length) }}</a>{% endif %}</footer>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
{% if cell.cards %}</div>{% endif %}
|
||||||
|
{% if not cell.cards and hosts | selectattr('is_active') | list %}
|
||||||
|
<button type="button" class="lv-cell-add" data-new='{{ {"broadcast_date": cell.iso, "start_time": slot.start, "end_time": slot.end} | tojson }}' aria-label="{{ t('{date} {slot} 방송 추가').format(date=cell.iso, slot=slot.label) }}">+</button>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
{% endif %}{% endfor %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
<th class="lv-cal-time" scope="row">{{ t('합계 & ROAS') }}</th>
|
||||||
|
{% for d in cal.days %}
|
||||||
|
<td>
|
||||||
|
<dl class="lv-total">
|
||||||
|
<div><dt>{{ t('총 판매금액') }}:</dt><dd class="is-sales">RM {{ d.sales_text }}</dd></div>
|
||||||
|
<div><dt>{{ t('광고비') }}:</dt><dd>RM {{ d.spend_text }}</dd></div>
|
||||||
|
<div><dt>{{ t('호스트 비용') }}:</dt><dd>RM {{ d.fee_text }}</dd></div>
|
||||||
|
<div><dt>ROAS:</dt><dd>{{ d.roas }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
</td>
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{#- 화면 오른쪽 위에 붙는 달력 — 날짜를 누르면 그 날이 표 맨 왼쪽(live.js), 말레이시아 공휴일(holidays.py) -#}
|
||||||
|
<div class="lv-side">
|
||||||
|
<aside class="lv-side-cal" id="lv-side-cal"></aside>
|
||||||
|
{#- 카드의 이미지 링크에 마우스를 올리면 달력 아래 빈 곳에 결과 이미지(live.js) -#}
|
||||||
|
<figure class="lv-preview" id="lv-preview" hidden><img alt="" /><figcaption></figcaption></figure>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% include "live/_dialog.html" %}
|
||||||
|
{#- 카드의 이미지 링크를 누르면 화면 가운데 원본 크기 이미지 — 회전(보기만)·다운로드(원본)·여러 장이면 앞뒤(live.js) -#}
|
||||||
|
<dialog class="lv-viewer" id="lv-viewer" aria-labelledby="lv-viewer-cap">
|
||||||
|
<div class="lv-viewer-bar">
|
||||||
|
<span class="lv-viewer-cap" id="lv-viewer-cap"></span>
|
||||||
|
<span class="lv-gap"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-step="-1" aria-label="{{ t('이전 이미지') }}">◀</button>
|
||||||
|
<span class="lv-viewer-count"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-step="1" aria-label="{{ t('다음 이미지') }}">▶</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-rotate>↻ {{ t('회전') }}</button>
|
||||||
|
<a class="erp-btn erp-btn-outline erp-btn-sm" data-download download>{{ t('다운로드') }}</a>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm" data-viewer-close>{{ t('닫기') }}</button>
|
||||||
|
</div>
|
||||||
|
<div class="lv-viewer-body"><div class="lv-viewer-stage"><img alt="" /></div></div>
|
||||||
|
</dialog>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}<script type="application/json" id="lv-my-holidays">{{ my_holidays | tojson }}</script>
|
||||||
|
<script type="application/json" id="lv-live-days">{{ live_days | tojson }}</script>
|
||||||
|
<script src="/static/erp-datepop.js?v=20261106a" defer></script>
|
||||||
|
{% include "live/_scripts.html" %}{% endblock %}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106h" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="lv" lang="{{ lang }}">
|
||||||
|
{% include "live/_bar.html" %}
|
||||||
|
|
||||||
|
<div class="erp-card-block">
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
{% set platform_names = {"tiktok": "TikTok", "shopee": "Shopee"} %}
|
||||||
|
<table class="erp-table lv-table lv-sched">
|
||||||
|
<thead><tr><th>{{ t('쇼핑몰') }}</th><th>{{ t('날짜') }}</th><th>{{ t('시간') }}</th><th>{{ t('호스트') }}</th><th class="lv-r">{{ t('판매금액(RM)') }}</th><th class="lv-r">{{ t('시간 요금(RM)') }}</th><th class="lv-r">{{ t('커미션 10%(RM)') }}</th><th class="lv-r">{{ t('광고비(RM)') }}</th><th class="lv-r">{{ t('호스트 비용(RM)') }}</th><th>{{ t('방송 결과') }}</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in rows %}
|
||||||
|
<tr>
|
||||||
|
<td class="lv-c" data-label="{{ t('쇼핑몰') }}">{% if r.platform %}<img class="lv-pf" src="/static/live-icon-{{ r.platform }}.png" alt="{{ platform_names[r.platform] }}" title="{{ platform_names[r.platform] }}" />{% endif %}</td>
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('날짜') }}">{{ r.date }}</td>
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('시간') }}">{{ r.times }}</td>
|
||||||
|
<td data-label="{{ t('호스트') }}">{{ r.host_name }}{% if r.tiktok_handle %}<div class="lv-sub">@{{ r.tiktok_handle }}</div>{% endif %}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('판매금액(RM)') }}">{{ r.sales }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('시간 요금(RM)') }}">{{ r.base }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('커미션 10%(RM)') }}">{{ r.commission }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('광고비(RM)') }}">{{ r.ad_spend }}</td>
|
||||||
|
<td class="lv-r lv-num" data-label="{{ t('호스트 비용(RM)') }}">{{ r.host_fee }}</td>
|
||||||
|
<td data-label="{{ t('방송 결과') }}"><div class="lv-thumbs">{% for im in r.images %}<a href="/live/images/{{ im.id }}" target="_blank" rel="noopener" title="{{ im.filename }}"><img src="/live/images/{{ im.id }}?thumb=1" alt="{{ im.filename }}" loading="lazy" /></a>{% endfor %}</div></td>
|
||||||
|
<td class="lv-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ r.edit | tojson }}'>{{ t('고치기') }}</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/broadcasts/{{ r.id }}/delete" data-confirm="{{ t('{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.').format(date=r.date, host=r.host_name) }}">{{ t('지우기') }}</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="11" class="erp-empty">{{ t('이 달에 등록한 방송이 없습니다.') }}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{% include "live/_dialog.html" %}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·지우기는 ERP 관리자만(router.settings), 칩 권한자는 이름·상태만 보임 — `live_host` = 새 등록, `live_host_edit` = 고치기(개인정보는 빈칸으로 열림, 비워 두면 그대로). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106h" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{#- 쇼핑몰(005, store.PLATFORMS) — 로고는 말레이시아 배송 모듈 이미지 -#}
|
||||||
|
{% set platform_names = {"tiktok": "TikTok", "shopee": "Shopee"} %}
|
||||||
|
<section class="lv" lang="{{ lang }}">
|
||||||
|
<div class="lv-bar">
|
||||||
|
<a class="erp-btn erp-btn-outline" href="/live/">{{ t('◀ 스케줄표') }}</a>
|
||||||
|
<h2 class="lv-month">{{ t('호스트 설정') }}</h2>
|
||||||
|
<span class="lv-gap"></span>
|
||||||
|
{% include "live/_lang.html" %}
|
||||||
|
{% if can_add_host %}<button type="button" class="erp-btn erp-btn-primary" id="lv-add">{{ t('+ 호스트 등록') }}</button>{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card-block">
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table lv-table">
|
||||||
|
<thead><tr><th>{{ t('쇼핑몰') }}</th><th>{{ t('간단한 이름') }}</th><th>{{ t('이름 (IC 기준)') }}</th>{% if is_admin %}<th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th>{% endif %}<th>{{ t('상태') }}</th>{% if can_edit_host %}<th></th>{% endif %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for h in hosts %}
|
||||||
|
<tr{% if not h.is_active %} class="lv-off"{% endif %}>
|
||||||
|
<td data-label="{{ t('쇼핑몰') }}">{% if h.platform %}<img class="lv-logo" src="/static/dispatch/courier/{{ h.platform }}.png" alt="{{ platform_names[h.platform] }}" title="{{ platform_names[h.platform] }}" />{% endif %}</td>
|
||||||
|
<td data-label="{{ t('간단한 이름') }}">{{ h.display_name }}</td>
|
||||||
|
<td data-label="{{ t('이름 (IC 기준)') }}">{{ h.full_name }}</td>
|
||||||
|
{% if is_admin %}
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('전화번호') }}">{{ h.phone }}</td>
|
||||||
|
<td data-label="{{ t('이메일') }}">{{ h.email }}</td>
|
||||||
|
<td data-label="{{ t('주소') }}">{{ h.address }}</td>
|
||||||
|
<td data-label="{{ t('은행명') }}">{{ h.bank_name }}</td>
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('계좌번호') }}">{{ h.bank_account }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if can_edit_host %}
|
||||||
|
<td data-label="{{ t('상태') }}"><label class="erp-switch" title="{{ t('사용') }}"><input type="checkbox" data-active="/live/settings/hosts/{{ h.id }}/active" aria-label="{{ t('사용') }} — {{ h.display_name or h.full_name }}"{% if h.is_active %} checked{% endif %} /><span class="erp-switch-slider"></span></label></td>
|
||||||
|
{% else %}
|
||||||
|
<td class="lv-nowrap" data-label="{{ t('상태') }}">{{ t('사용') if h.is_active else t('사용 안 함') }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if can_edit_host %}
|
||||||
|
<td class="lv-actions">
|
||||||
|
{% if is_admin %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "platform": h.platform, "display_name": h.display_name, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/settings/hosts/{{ h.id }}/delete" data-confirm="{{ t('{name} 호스트를 지울까요?').format(name=h.full_name) }}">{{ t('지우기') }}</button>
|
||||||
|
{% else %}
|
||||||
|
{#- 개인정보를 페이지에 싣지 않는다 -#}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "platform": h.platform, "display_name": h.display_name, "full_name": h.full_name, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="{{ 10 if is_admin else 5 if can_edit_host else 4 }}" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||||
|
<form id="lv-form" action="/live/settings/hosts">
|
||||||
|
<h3 id="lv-dlg-title" data-add="{{ t('호스트 등록') }}" data-edit="{{ t('호스트 고치기') }}"></h3>
|
||||||
|
<input type="hidden" name="id" />
|
||||||
|
<fieldset class="lv-platforms">
|
||||||
|
<legend>{{ t('쇼핑몰') }}</legend>
|
||||||
|
{% for p, name in platform_names.items() %}
|
||||||
|
<label class="lv-platform"><input type="radio" name="platform" value="{{ p }}" required /><img class="lv-logo" src="/static/dispatch/courier/{{ p }}.png" alt="{{ name }}" /></label>
|
||||||
|
{% endfor %}
|
||||||
|
</fieldset>
|
||||||
|
<label class="lv-field">{{ t('간단한 이름') }} <input class="erp-input" type="text" name="display_name" maxlength="50" required /></label>
|
||||||
|
<label class="lv-field">{{ t('이름 (IC 기준)') }} <input class="erp-input" type="text" name="full_name" maxlength="200" required /></label>
|
||||||
|
{% if not is_admin %}<p class="lv-sub" data-edit-only hidden>{{ t('개인정보는 보이지 않습니다. 비워 두면 그대로 유지됩니다.') }}</p>{% endif %}
|
||||||
|
<label class="lv-field">{{ t('전화번호') }} <input class="erp-input" type="tel" name="phone" maxlength="40" /></label>
|
||||||
|
<label class="lv-field">{{ t('이메일') }} <input class="erp-input" type="email" name="email" maxlength="254" /></label>
|
||||||
|
<label class="lv-field">{{ t('주소') }} <textarea class="erp-input" name="address" rows="2" maxlength="500"></textarea></label>
|
||||||
|
<div class="lv-row">
|
||||||
|
<label class="lv-field">{{ t('은행명') }} <input class="erp-input" type="text" name="bank_name" maxlength="100" /></label>
|
||||||
|
<label class="lv-field">{{ t('계좌번호') }} <input class="erp-input" type="text" name="bank_account" maxlength="40" inputmode="numeric" /></label>
|
||||||
|
</div>
|
||||||
|
{% if can_edit_host %}<label class="lv-check"><input type="checkbox" name="is_active" value="1" checked /> {{ t('사용 (끄면 새 방송에서 고를 수 없습니다)') }}</label>{% endif %}
|
||||||
|
<p class="lv-msg" data-msg role="alert" hidden></p>
|
||||||
|
<div class="lv-foot">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
|
||||||
@@ -90,11 +90,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
|||||||
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, "malaysia"):
|
if not has_module(user, "malaysia"):
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261111f" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<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>
|
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -64,7 +64,7 @@
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||||
<script src="/static/project.js?v=20261027a" defer></script>
|
<script src="/static/project.js?v=20261111d" defer></script>
|
||||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
<script src="/static/erp-notice-admin.js?v=20261111a" defer></script>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# [안내문 발송] 안내문 발송 모듈 — `app/modules/outreach/`, `outreach_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||||
|
> 정적 파일: `app/static/outreach.js`, `app/static/outreach.css`. 템플릿: `templates/outreach/`. 테스트: `tests/test_outreach.py`,
|
||||||
|
> `tests/js/outreach.browser.test.js`·`outreach_settings.browser.test.js`(`render_outreach.py`). 편집기 = `app/static/vendor/quill/`(Quill 2.0.3, BSD).
|
||||||
|
> 다른 모듈과 연결: 메일 = 입출고 Gmail 연결(`inout_store.inout_gmail_tokens`, `app/modules/inout/gmail.py`, 콜백 `/inout/gmail/callback` 이
|
||||||
|
> 세션 `_gmail_origin=outreach` 를 보고 `_GMAIL_ORIGINS` 로 처리) — 입출고·휴가와 같은 연결.
|
||||||
|
|
||||||
|
- 리스트(주소 + 이름)에 안내문을 보낸다(2026-10-27). 권한키 `outreach`(보기·리스트·보내기·설정 모두), DB `OUTREACH_DB_URL`(없으면 "설정 필요" 안내).
|
||||||
|
- **주소를 보고 메일/DM 판별**(`store.detect`): `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
|
||||||
|
게시물 주소(`/p/`·`/reel/`)·한글만은 오류. 같은 주소는 한 번(`UNIQUE(kind, handle)`, 이메일·계정명 소문자).
|
||||||
|
- 리스트 추가 = 붙여넣기(한 줄에 한 사람 `주소, 이름` — 쉼표·탭·띄어쓰기, 순서는 어느 쪽이든, `store.parse_line`) → [미리보기](메일/DM/오류·중복·이미 있음) → [리스트에 추가].
|
||||||
|
- **본문 `{이름}`** = 그 줄 이름(제목에도). 이름이 빈 줄은 보내지 않고 실패('이름 없음'), 화면에 "이름 필요" 표시.
|
||||||
|
- **메일 본문 = HTML**(설정 편집기, `fmt: "html"`) — 저장·읽을 때마다 `store.sanitize_html`(허용 태그 p·br·strong·em·u·s·span·a·ul·ol·li 등,
|
||||||
|
style 은 color·background-color·font-size·font-weight·font-style·text-decoration·text-align 만, 링크는 http(s)/mailto, ` ` → 띄어쓰기, 빈 문단 = `<br>`).
|
||||||
|
예전 글·기본 문구(`fmt` 없음) = `text_to_html`(줄마다 문단, `**굵게**`, 주소 링크). 메일 글 버전·DM 대체 글·{이름} 찾기 = `html_to_text`.
|
||||||
|
`{이름}` 은 글자마다 서식이 달라도 `fill_html` 이 바꾼다. 메일 HTML 은 `<p>` 에 margin:0(메일 프로그램 문단 여백 없앰).
|
||||||
|
- **메일** = [고른 메일 보내기] → `db.claim_for_send`(고른 줄 중 메일·대기/실패만 '발송중'으로 한 UPDATE — 두 번 눌러도·두 사람이 눌러도 한 번) →
|
||||||
|
`send.send_batch`(백그라운드, **보내는 사람 본인 Gmail**, 한 사람에 한 통·1초 간격, 설정 사진 = 본문 아래 cid) → 보냄/실패 + `outreach_logs`.
|
||||||
|
Gmail 연결 없으면 409(화면이 [Gmail 연결] 안내), 끊기면 남은 줄 실패. 서버 재시작 때 남은 '발송중' = 실패(`release_stuck`).
|
||||||
|
- **인스타 DM = 반자동** — 인스타 공식 API 는 처음 연락하는 사람에게 DM 을 보낼 수 없다(상대가 먼저 보낸 24시간 안만, 자동 DM 은 약관 위반·계정 정지 위험).
|
||||||
|
[DM 보내기] = 그 사람 이름이 든 문구 복사 + `https://ig.me/m/계정` 새 탭(누르는 순간 — 문구는 리스트 데이터에 미리 담음) → 붙여 넣어 보낸 뒤 [보냄](`dm-sent`, 기록).
|
||||||
|
**DM 문구** = 설정 `dm_body`(글, `store.dm_text`, 최대 1000자 `DM_MAX`, `{이름}`, 별표만 뺌) — 비어 있으면 메일 본문 글 + 끝 문구. "이름 필요"도 구분별(`needs_name(t, kind)`).
|
||||||
|
- **탭**(2026-10-30, `templates/outreach/_tabs.html`) — [발송 리스트](`/outreach/`) [DM 수동 보내기](`/outreach/dm`) + 맨 오른쪽 설정 톱니.
|
||||||
|
- **DM 수동 보내기 탭** `/outreach/dm`(`dm.html`, JS `outreach.js initDm`) — 3단:
|
||||||
|
왼쪽 = 이름 넣기(붙여 넣기·.txt/.csv 첫 칸, 머리글 "이름"·빈 줄·이미 있는 이름 뺌, 넣을 때마다 목록에 더함) + 이름 목록(× 한 명씩·[전체 삭제], 브라우저만 — 저장 안 함),
|
||||||
|
가운데 = 본문(`contenteditable="plaintext-only"`, 바로 고침, `{이름}` 자리 = 분홍 칩 — 직접 `{이름}` 이라 써도 됨), 오른쪽 = 저장한 본문 목록
|
||||||
|
(맨 위 "설정 DM 문구(기본)" = `dm_template` = `store.dm_text(template, NAME_TAG)`, 그 아래 저장한 것 — 누르면 불러옴(고친 글 있으면 확인)·× 하나씩 지우기).
|
||||||
|
이름을 누르면 칩이 그 이름으로 바뀌고 고친 글 + 이름을 바로 클립보드 복사 + 짧은 안내(1.6초). 글자 수 = 이름 넣은 글 기준, 1000자(`DM_MAX`) 넘으면 빨강.
|
||||||
|
**저장한 본문** = outreach_db 마이그레이션 002 `outreach_dm_bodies`(모듈 권한자 모두 같은 목록, 제목 = 첫 글 줄 40자 `store.dm_saved_body`, 1000자까지):
|
||||||
|
`POST /outreach/api/dm-bodies`(새 본문으로 저장)·`PUT …/{id}`(고른 본문 [저장])·`DELETE …/{id}` — 모두 `{items}` 돌려줌. 002 미적용이면 목록 안내만, API 503.
|
||||||
|
- 설정 = 탭 줄 맨 오른쪽 톱니(`.otr-gear`, 공용 `vendor/material-symbols`). `.otr .erp-card[hidden]` — 공용 `.erp-card` display:flex 가 hidden 을 덮어
|
||||||
|
[리스트 추가] 창이 늘 열려 있던 것 고침(2026-10-30).
|
||||||
|
- **설정** `/outreach/settings`(모듈 권한자 누구나) — **세로 2단**: 왼쪽 메일(제목·"(광고)"·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
|
||||||
|
오른쪽 인스타 DM(서식 없는 편집기·글자 수·[메일 본문 글 가져오기]), 위 막대 [저장]·[기본 문구로 되돌리기](칸만, 저장해야 적용) — 1100px 아래는 위아래.
|
||||||
|
입력 칸은 `form="otr-set-form"` 으로 위 막대 폼에 묶음(사진 폼과 겹치지 않게). 편집기 = Quill snow(글자 크기 px·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기),
|
||||||
|
저장 = `getSemanticHTML()` → `body`(fmt=html), DM `getText()` → `dm_body`. **`{이름}` 빨강 굵게 = 화면에서만**(class `otr-nametag-on`, 서버 정리 때 class 가 빠져 메일에는 안 남음).
|
||||||
|
기본 본문 = 미라네주방 공동구매 제안 문구(`store.DEFAULT_TEMPLATE`, 글). "(광고)" — 영리 목적 광고성 메일은 정보통신망법 제50조 대상일 수 있어 칸을 둠(법무 확인 권장).
|
||||||
|
본문 아래 사진 최대 10장(서버가 가로 700px JPEG 로 줄여 `outreach_images` 에, 순서 ◀▶).
|
||||||
|
- 리스트 줄: 이름 바로 고치기(칸 떠나면 저장), [미리보기](메일 = 제목·HTML, DM = 글), 고른 줄 다시 대기·지우기(발송중은 못 지움), 걸러 보기(전체·메일·DM·대기·보냄·실패).
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""안내문 발송(outreach) 모듈 — 리스트(이메일·인스타그램 주소 + 이름)에 안내문을 보낸다(2026-10-27).
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/outreach) · 저장소: `db.py` (outreach_db) · 순수 함수: `store.py`(주소 판별·{이름}·본문)
|
||||||
|
- 메일 일괄 발송: `send.py` — 보내는 사람 본인 Gmail(입출고·휴가와 같은 Gmail 연결)
|
||||||
|
- 인스타 DM: 반자동(문구 복사 + DM 창 열기 + [보냄] 기록) — 인스타 공식 API 는 처음 연락하는 사람에게 DM 을 보낼 수 없다.
|
||||||
|
- 템플릿: `templates/outreach/`, 화면 스크립트·스타일 `static/outreach.{js,css}`
|
||||||
|
|
||||||
|
OUTREACH_DB_URL 미설정이면 build_outreach_store 가 None → 화면이 "설정 필요" 안내(앱은 죽지 않음). 권한키 `outreach`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_outreach_store"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_outreach_store(*, dsn: str | None) -> Any:
|
||||||
|
if not dsn:
|
||||||
|
return None
|
||||||
|
from .db import OutreachDBStore # 지연 import
|
||||||
|
|
||||||
|
st = OutreachDBStore(dsn)
|
||||||
|
try:
|
||||||
|
st.release_stuck() # 서버가 보내던 중 다시 시작됨 → 발송중 줄을 실패로(다시 보낼 수 있게)
|
||||||
|
except Exception: # noqa: BLE001 — DB 가 잠시 없어도 앱은 뜬다
|
||||||
|
pass
|
||||||
|
return st
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
"""outreach_db PostgreSQL 저장소 — 안내문 발송(2026-10-27).
|
||||||
|
|
||||||
|
- 연결: 환경변수 `OUTREACH_DB_URL` (예: postgresql://outreach_app:<pwd>@postgres-db:5432/outreach_db)
|
||||||
|
- 스키마는 앱이 만들지 않는다 — `scripts/sql/outreach_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만).
|
||||||
|
- 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg.errors import UndefinedTable
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
MAX_IMAGES = 10
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(v: Any) -> str:
|
||||||
|
return v.astimezone(KST).isoformat(timespec="seconds") if isinstance(v, datetime) else ""
|
||||||
|
|
||||||
|
|
||||||
|
class OutreachDBStore:
|
||||||
|
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 4):
|
||||||
|
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._pool.close()
|
||||||
|
|
||||||
|
# ── 설정(제목·본문·보내는 이름·끝 문구·(광고)) ─────────────────
|
||||||
|
def get_template(self) -> dict[str, Any]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT value, updated_by, updated_at FROM outreach_settings WHERE key = 'template'").fetchone()
|
||||||
|
t = store.normalize_template(row["value"] if row and isinstance(row["value"], dict) else None)
|
||||||
|
t["updated_by"] = row["updated_by"] if row else ""
|
||||||
|
t["updated_at"] = _iso(row["updated_at"]) if row else ""
|
||||||
|
t["is_default"] = row is None
|
||||||
|
return t
|
||||||
|
|
||||||
|
def save_template(self, value: dict[str, Any], *, by: str) -> dict[str, Any]:
|
||||||
|
t = store.normalize_template(value)
|
||||||
|
if not t["subject"]:
|
||||||
|
raise ValueError("메일 제목을 쓰세요.")
|
||||||
|
if not store.html_to_text(t["body"]).strip():
|
||||||
|
raise ValueError("본문을 쓰세요.")
|
||||||
|
if len(t["body"]) > store.BODY_MAX:
|
||||||
|
raise ValueError("본문이 너무 깁니다(서식 포함) — 줄여 주세요.")
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO outreach_settings (key, value, updated_by, updated_at) VALUES ('template', %s, %s, now()) "
|
||||||
|
"ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = now()",
|
||||||
|
(Jsonb({k: t[k] for k in store.DEFAULT_TEMPLATE}), (by or "").lower()),
|
||||||
|
)
|
||||||
|
return self.get_template()
|
||||||
|
|
||||||
|
# ── 메일 본문 아래 사진 ────────────────────────────────
|
||||||
|
def list_images(self, *, with_data: bool = False) -> list[dict[str, Any]]:
|
||||||
|
cols = "id, filename, width, height, sort_order" + (", data" if with_data else "")
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(f"SELECT {cols} FROM outreach_images ORDER BY sort_order, id").fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def get_image(self, image_id: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM outreach_images WHERE id = %s", (image_id,)).fetchone()
|
||||||
|
|
||||||
|
def add_image(self, *, filename: str, data: bytes, width: int, height: int, by: str) -> int:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
n = conn.execute("SELECT COUNT(*) AS n, COALESCE(MAX(sort_order), -1) + 1 AS nxt FROM outreach_images").fetchone()
|
||||||
|
if n["n"] >= MAX_IMAGES:
|
||||||
|
raise ValueError(f"사진은 {MAX_IMAGES}장까지 넣을 수 있습니다.")
|
||||||
|
return int(conn.execute(
|
||||||
|
"INSERT INTO outreach_images (filename, data, width, height, sort_order, created_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s, %s) RETURNING id",
|
||||||
|
(filename[:200], data, width, height, int(n["nxt"]), (by or "").lower()),
|
||||||
|
).fetchone()["id"])
|
||||||
|
|
||||||
|
def delete_image(self, image_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("DELETE FROM outreach_images WHERE id = %s", (image_id,))
|
||||||
|
|
||||||
|
def move_image(self, image_id: int, direction: int) -> None:
|
||||||
|
"""사진 순서 한 칸 앞/뒤(-1/1)."""
|
||||||
|
ids = [r["id"] for r in self.list_images()]
|
||||||
|
if image_id not in ids:
|
||||||
|
return
|
||||||
|
i = ids.index(image_id)
|
||||||
|
j = i + (-1 if direction < 0 else 1)
|
||||||
|
if not 0 <= j < len(ids):
|
||||||
|
return
|
||||||
|
ids[i], ids[j] = ids[j], ids[i]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("UPDATE outreach_images m SET sort_order = v.ord FROM unnest(%s::int[]) WITH ORDINALITY AS v(id, ord) "
|
||||||
|
"WHERE m.id = v.id", (ids,))
|
||||||
|
|
||||||
|
# ── 리스트 ───────────────────────────────────────────
|
||||||
|
@staticmethod
|
||||||
|
def _row(r: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
d = dict(r)
|
||||||
|
d["id"] = int(d["id"])
|
||||||
|
for k in ("sent_at", "created_at", "updated_at"):
|
||||||
|
d[k] = _iso(d.get(k))
|
||||||
|
return d
|
||||||
|
|
||||||
|
def list_recipients(self) -> list[dict[str, Any]]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM outreach_recipients ORDER BY id").fetchall()
|
||||||
|
return [self._row(r) for r in rows]
|
||||||
|
|
||||||
|
def get_recipient(self, rid: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
r = conn.execute("SELECT * FROM outreach_recipients WHERE id = %s", (rid,)).fetchone()
|
||||||
|
return self._row(r) if r else None
|
||||||
|
|
||||||
|
def add_recipients(self, rows: list[dict[str, Any]], *, by: str) -> dict[str, int]:
|
||||||
|
"""[{address, name}] 추가 — 주소를 보고 메일/DM 을 정한다. 이미 있는 주소는 이름만 비어 있으면 채우고 건너뜀.
|
||||||
|
반환 {added, existed, invalid}. 틀린 주소는 저장하지 않고 센다(화면이 미리 보여 줌)."""
|
||||||
|
out = {"added": 0, "existed": 0, "invalid": 0}
|
||||||
|
who = (by or "").lower()
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
for r in rows:
|
||||||
|
d = store.detect(r.get("address"))
|
||||||
|
if not d["kind"]:
|
||||||
|
out["invalid"] += 1
|
||||||
|
continue
|
||||||
|
name = str(r.get("name") or "").strip()[:100]
|
||||||
|
got = conn.execute(
|
||||||
|
"INSERT INTO outreach_recipients (kind, handle, address, name, created_by) VALUES (%s, %s, %s, %s, %s) "
|
||||||
|
"ON CONFLICT (kind, handle) DO UPDATE SET name = CASE WHEN outreach_recipients.name = '' "
|
||||||
|
"THEN EXCLUDED.name ELSE outreach_recipients.name END RETURNING (xmax = 0) AS inserted",
|
||||||
|
(d["kind"], d["handle"], str(r.get("address") or "").strip()[:320], name, who),
|
||||||
|
).fetchone()
|
||||||
|
out["added" if got["inserted"] else "existed"] += 1
|
||||||
|
return out
|
||||||
|
|
||||||
|
def update_recipient(self, rid: int, *, name: Any = None, memo: Any = None, status: Any = None) -> dict[str, Any]:
|
||||||
|
sets, params = [], []
|
||||||
|
if name is not None:
|
||||||
|
sets.append("name = %s")
|
||||||
|
params.append(str(name).strip()[:100])
|
||||||
|
if memo is not None:
|
||||||
|
sets.append("memo = %s")
|
||||||
|
params.append(str(memo).strip()[:500])
|
||||||
|
if status is not None:
|
||||||
|
if status != "대기":
|
||||||
|
raise ValueError("상태는 '대기'(다시 보내기)로만 바꿀 수 있습니다.")
|
||||||
|
sets += ["status = '대기'", "last_error = ''"]
|
||||||
|
if not sets:
|
||||||
|
raise ValueError("바꿀 내용이 없습니다.")
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
r = conn.execute(f"UPDATE outreach_recipients SET {', '.join(sets)} WHERE id = %s RETURNING *", (*params, rid)).fetchone()
|
||||||
|
if not r:
|
||||||
|
raise KeyError(rid)
|
||||||
|
return self._row(r)
|
||||||
|
|
||||||
|
def delete_recipients(self, ids: list[int]) -> int:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
cur = conn.execute("DELETE FROM outreach_recipients WHERE id = ANY(%s) AND status <> '발송중'", ([int(i) for i in ids],))
|
||||||
|
return cur.rowcount
|
||||||
|
|
||||||
|
# ── 보내기 ───────────────────────────────────────────
|
||||||
|
def claim_for_send(self, ids: list[int]) -> list[dict[str, Any]]:
|
||||||
|
"""메일 일괄 발송 — 고른 줄 중 메일·대기/실패만 '발송중'으로 바꾸며 가져온다(한 UPDATE — 두 번 눌러도·두 사람이 눌러도 한 번만)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"UPDATE outreach_recipients SET status = '발송중', last_error = '' "
|
||||||
|
"WHERE id = ANY(%s) AND kind = 'email' AND status IN ('대기', '실패') RETURNING *",
|
||||||
|
([int(i) for i in ids],),
|
||||||
|
).fetchall()
|
||||||
|
return sorted((self._row(r) for r in rows), key=lambda r: r["id"])
|
||||||
|
|
||||||
|
def finish_send(self, rid: int, *, ok: bool, via: str, by: str, subject: str, error: str = "") -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
r = conn.execute(
|
||||||
|
"UPDATE outreach_recipients SET status = %s, sent_at = CASE WHEN %s THEN now() ELSE sent_at END, "
|
||||||
|
"sent_by = CASE WHEN %s THEN %s ELSE sent_by END, sent_via = CASE WHEN %s THEN %s ELSE sent_via END, "
|
||||||
|
"last_error = %s WHERE id = %s RETURNING kind, address, name",
|
||||||
|
("보냄" if ok else "실패", ok, ok, (by or "").lower(), ok, via, (error or "")[:500], rid),
|
||||||
|
).fetchone()
|
||||||
|
if r:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO outreach_logs (recipient_id, kind, address, name, subject, via, sent_by, ok, error) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||||
|
(rid, r["kind"], r["address"], r["name"], (subject or "")[:300], via, (by or "").lower(), ok, (error or "")[:500]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def mark_dm_sent(self, rid: int, *, by: str, subject: str) -> dict[str, Any]:
|
||||||
|
"""DM [보냄] — 인스타 줄만(사람이 DM 창에서 보낸 뒤 누름)."""
|
||||||
|
r = self.get_recipient(rid)
|
||||||
|
if r is None:
|
||||||
|
raise KeyError(rid)
|
||||||
|
if r["kind"] != "instagram":
|
||||||
|
raise ValueError("메일 줄은 [일괄 발송]으로 보냅니다.")
|
||||||
|
self.finish_send(rid, ok=True, via="dm", by=by, subject=subject)
|
||||||
|
return self.get_recipient(rid) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def release_stuck(self) -> int:
|
||||||
|
"""서버가 보내던 중 멈춘 줄(발송중)을 실패로 — 서버 시작 때(앱은 프로세스 하나, 보내기는 메모리 작업)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
cur = conn.execute("UPDATE outreach_recipients SET status = '실패', last_error = '보내던 중 서버가 다시 시작됨 — 다시 보내세요' "
|
||||||
|
"WHERE status = '발송중'")
|
||||||
|
return cur.rowcount
|
||||||
|
|
||||||
|
# ── DM 수동 보내기 탭의 저장한 본문(마이그레이션 002) ──────────
|
||||||
|
def list_dm_bodies(self) -> list[dict[str, Any]] | None:
|
||||||
|
"""새로 고친 것부터. 표가 없으면(002 미적용) None — 화면이 저장 목록만 숨긴다."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT id, title, body, created_by, updated_by, updated_at FROM outreach_dm_bodies "
|
||||||
|
"ORDER BY updated_at DESC, id DESC").fetchall()
|
||||||
|
except UndefinedTable:
|
||||||
|
return None
|
||||||
|
return [{**dict(r), "id": int(r["id"]), "updated_at": _iso(r["updated_at"])} for r in rows]
|
||||||
|
|
||||||
|
def save_dm_body(self, body: Any, *, by: str, body_id: int | None = None) -> int:
|
||||||
|
"""새로 저장(body_id 없음) 또는 그 본문 고치기. 저장한 id. 없는 id = KeyError."""
|
||||||
|
title, text = store.dm_saved_body(body)
|
||||||
|
by = (by or "").lower()
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if body_id is None:
|
||||||
|
return int(conn.execute(
|
||||||
|
"INSERT INTO outreach_dm_bodies (title, body, created_by, updated_by) VALUES (%s, %s, %s, %s) RETURNING id",
|
||||||
|
(title, text, by, by)).fetchone()["id"])
|
||||||
|
row = conn.execute("UPDATE outreach_dm_bodies SET title = %s, body = %s, updated_by = %s, updated_at = now() "
|
||||||
|
"WHERE id = %s RETURNING id", (title, text, by, body_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(body_id)
|
||||||
|
return int(row["id"])
|
||||||
|
|
||||||
|
def delete_dm_body(self, body_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("DELETE FROM outreach_dm_bodies WHERE id = %s", (body_id,))
|
||||||
|
|
||||||
|
def list_logs(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM outreach_logs ORDER BY sent_at DESC, id DESC LIMIT %s", (limit,)).fetchall()
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
d = dict(r)
|
||||||
|
d["sent_at"] = _iso(d["sent_at"])
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
@@ -0,0 +1,450 @@
|
|||||||
|
"""안내문 발송(outreach) 라우터 — 리스트(이메일·인스타 주소 + 이름)에 안내문 메일 일괄 발송·인스타 DM 반자동(2026-10-27).
|
||||||
|
|
||||||
|
GET /outreach/ 리스트 + 보내기 화면
|
||||||
|
GET /outreach/settings 설정 — 메일 제목·본문({이름})·보내는 이름·끝 문구·(광고)·본문 아래 사진
|
||||||
|
POST /outreach/settings 설정 저장 · POST /settings/images(올리기) · /settings/images/{id}/delete · /move
|
||||||
|
GET /outreach/images/{id} 사진(설정·미리보기)
|
||||||
|
GET /outreach/api/recipients 리스트(JSON — 발송 중 진행 보기)
|
||||||
|
POST /outreach/api/recipients/parse 붙여 넣은 글 해석 미리보기(메일/DM/오류)
|
||||||
|
POST /outreach/api/recipients 리스트에 추가 {text}
|
||||||
|
PUT /outreach/api/recipients/{id} 이름·메모 고치기, 다시 대기로 {status: "대기"}
|
||||||
|
POST /outreach/api/recipients/delete 지우기 {ids}
|
||||||
|
GET /outreach/api/recipients/{id}/preview 그 사람에게 갈 제목·HTML·DM 글
|
||||||
|
POST /outreach/api/send 고른 메일 줄 일괄 발송 {ids} — 본인 Gmail, 백그라운드
|
||||||
|
POST /outreach/api/recipients/{id}/dm-sent DM 보냄 표시(사람이 DM 창에서 보낸 뒤)
|
||||||
|
GET /outreach/gmail/connect · POST /gmail/disconnect 내 Gmail 연결(입출고·휴가와 같은 연결, 같은 구글 콜백)
|
||||||
|
권한: 모듈 권한키 `outreach`(보기·리스트·보내기·설정 모두). DB: OUTREACH_DB_URL(outreach_db) — 없으면 "설정 필요" 안내.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
|
from fastapi import APIRouter, BackgroundTasks, Body, File, Form, HTTPException, Request, UploadFile
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/outreach", tags=["outreach"])
|
||||||
|
|
||||||
|
IMAGE_MAX_W = 700
|
||||||
|
IMAGE_MAX_BYTES = 15 * 1024 * 1024
|
||||||
|
MAX_ADD = 2000
|
||||||
|
|
||||||
|
|
||||||
|
def _store(request: Request) -> Any:
|
||||||
|
return getattr(request.app.state, "outreach_store", None)
|
||||||
|
|
||||||
|
|
||||||
|
def _inout(request: Request) -> Any:
|
||||||
|
return getattr(request.app.state, "inout_store", None)
|
||||||
|
|
||||||
|
|
||||||
|
def _user(request: Request) -> dict[str, Any]:
|
||||||
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
from app.store import has_module # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||||
|
if not has_module(user, "outreach"):
|
||||||
|
raise HTTPException(status_code=403, detail="안내문 발송 모듈 권한이 없습니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _db(request: Request) -> Any:
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
raise HTTPException(status_code=503, detail="안내문 발송 DB(OUTREACH_DB_URL)가 설정되지 않았습니다.")
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _page(request: Request) -> Any:
|
||||||
|
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
|
||||||
|
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||||
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
return login_redirect(request)
|
||||||
|
if not has_module(user, "outreach"):
|
||||||
|
return render_template(request, "denied.html", {"reason": "안내문 발송 모듈 접근 권한이 없습니다.",
|
||||||
|
"is_admin": is_admin(user)}, status_code=403)
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
return render_template(request, "denied.html", {
|
||||||
|
"reason": "안내문 발송 모듈이 아직 설정되지 않았습니다. scripts/sql/outreach_db_init.sql 로 outreach_db 를 만들고 "
|
||||||
|
".env 에 OUTREACH_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.",
|
||||||
|
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="outreach")}, status_code=503)
|
||||||
|
return st, user
|
||||||
|
|
||||||
|
|
||||||
|
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any]) -> HTMLResponse:
|
||||||
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
return render_template(request, name, {"user": user, "is_admin": is_admin(user),
|
||||||
|
"nav_items": build_erp_nav(user, active="outreach"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
|
def _gmail_state(request: Request, user: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
from app.modules.inout import gmail # noqa: WPS433
|
||||||
|
|
||||||
|
inout = _inout(request)
|
||||||
|
connected = False
|
||||||
|
if inout is not None:
|
||||||
|
try:
|
||||||
|
connected = inout.gmail_token(user["email"]) is not None
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
connected = False
|
||||||
|
return {"available": inout is not None and gmail.configured(), "connected": connected, "email": user["email"]}
|
||||||
|
|
||||||
|
|
||||||
|
def _view(r: dict[str, Any], template: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""리스트 한 줄 화면용 — 구분 라벨, DM 이면 그 사람 이름을 넣은 DM 글·DM 창 주소(누르는 순간 복사·열기라 미리 담아 둔다)."""
|
||||||
|
out = {k: r.get(k) for k in ("id", "kind", "handle", "address", "name", "memo", "status", "sent_at", "sent_by", "sent_via",
|
||||||
|
"last_error")}
|
||||||
|
out["kind_label"] = store.KIND_LABELS.get(r["kind"], "")
|
||||||
|
out["needs_name"] = store.needs_name(template, r["kind"]) and not (r.get("name") or "").strip()
|
||||||
|
if r["kind"] == "instagram":
|
||||||
|
out["dm_link"] = store.dm_link(r["handle"])
|
||||||
|
out["profile_link"] = store.profile_link(r["handle"])
|
||||||
|
out["dm_text"] = store.dm_text(template, r.get("name") or "")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 화면
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
@router.get("/health")
|
||||||
|
def health(request: Request) -> JSONResponse:
|
||||||
|
return JSONResponse({"status": "ok" if _store(request) is not None else "not_configured"})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_class=HTMLResponse)
|
||||||
|
def index(request: Request) -> Any:
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
template = st.get_template()
|
||||||
|
rows = [_view(r, template) for r in st.list_recipients()]
|
||||||
|
return _render(request, "outreach/index.html", user, {
|
||||||
|
"page_title": "안내문 발송", "page_subtitle": "메일 일괄 발송 · 인스타 DM",
|
||||||
|
"template": template, "body_text": store.html_to_text(template["body"]), "needs_name": store.needs_name(template),
|
||||||
|
"images": st.list_images(), "rows": rows, "logs": st.list_logs(limit=50), "active_tab": "list",
|
||||||
|
"gmail": _gmail_state(request, user), "msg": request.query_params.get("msg", ""),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/dm", response_class=HTMLResponse)
|
||||||
|
def dm_page(request: Request) -> Any:
|
||||||
|
"""DM 수동 보내기 탭(2026-10-30) — 이름 목록 | 고칠 수 있는 본문(화면이 {이름} 을 바꿔 복사) | 저장한 본문 목록."""
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
return _render(request, "outreach/dm.html", user, {
|
||||||
|
"page_title": "안내문 발송", "page_subtitle": "DM 수동 보내기", "active_tab": "dm",
|
||||||
|
# {이름} 을 그대로 둔 DM 문구(리스트 줄 [DM 보내기]와 같은 글) + 저장한 본문 목록(002 미적용 = None)
|
||||||
|
"dm_template": store.dm_text(st.get_template(), store.NAME_TAG),
|
||||||
|
"dm_bodies": st.list_dm_bodies(), "dm_max": store.DM_MAX,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
_DM_BODIES_MIGRATION_MSG = "본문 저장 표가 없습니다 — outreach_db 마이그레이션 002(scripts/sql/outreach_db_002_dm_bodies.sql)를 적용하세요."
|
||||||
|
|
||||||
|
|
||||||
|
def _dm_body_save(request: Request, payload: dict[str, Any], body_id: int | None) -> JSONResponse:
|
||||||
|
from psycopg.errors import UndefinedTable # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
saved = st.save_dm_body(payload.get("body"), by=user.get("email", ""), body_id=body_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
except KeyError:
|
||||||
|
raise HTTPException(status_code=404, detail="저장한 본문이 없습니다(다른 사람이 지웠을 수 있음).")
|
||||||
|
except UndefinedTable:
|
||||||
|
raise HTTPException(status_code=503, detail=_DM_BODIES_MIGRATION_MSG)
|
||||||
|
return JSONResponse({"id": saved, "items": st.list_dm_bodies() or []})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/dm-bodies")
|
||||||
|
def api_dm_body_add(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""DM 수동 보내기 — 본문 새로 저장(제목 = 첫 줄)."""
|
||||||
|
return _dm_body_save(request, payload, None)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/dm-bodies/{body_id:int}")
|
||||||
|
def api_dm_body_update(request: Request, body_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""DM 수동 보내기 — 고른 저장 본문 고치기."""
|
||||||
|
return _dm_body_save(request, payload, body_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/dm-bodies/{body_id:int}")
|
||||||
|
def api_dm_body_delete(request: Request, body_id: int) -> JSONResponse:
|
||||||
|
from psycopg.errors import UndefinedTable # noqa: WPS433
|
||||||
|
|
||||||
|
_user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
st.delete_dm_body(body_id)
|
||||||
|
except UndefinedTable:
|
||||||
|
raise HTTPException(status_code=503, detail=_DM_BODIES_MIGRATION_MSG)
|
||||||
|
return JSONResponse({"items": st.list_dm_bodies() or []})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/settings", response_class=HTMLResponse)
|
||||||
|
def settings_page(request: Request) -> Any:
|
||||||
|
got = _page(request)
|
||||||
|
if not isinstance(got, tuple):
|
||||||
|
return got
|
||||||
|
st, user = got
|
||||||
|
return _render(request, "outreach/settings.html", user, {
|
||||||
|
"page_title": "안내문 발송 — 설정", "page_subtitle": "메일 제목 · 본문 · DM 문구 · 사진",
|
||||||
|
"template": st.get_template(), "default": store.normalize_template(None), "images": st.list_images(),
|
||||||
|
"max_images": 10, "dm_max": store.DM_MAX, "msg": request.query_params.get("msg", ""),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings")
|
||||||
|
def settings_save(request: Request, subject: str = Form(""), body: str = Form(""), sender_name: str = Form(""),
|
||||||
|
footer: str = Form(""), ad_label: str = Form(""), dm_body: str = Form(""),
|
||||||
|
fmt: str = Form("text")) -> RedirectResponse:
|
||||||
|
"""body = 설정 화면 편집기 HTML(fmt=html, 서버가 다시 정리) — fmt 없이 오면 글로 본다."""
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
st.save_template({"subject": subject, "body": body, "sender_name": sender_name, "footer": footer, "dm_body": dm_body,
|
||||||
|
"ad_label": ad_label in ("1", "on", "true"), "fmt": "html" if fmt == "html" else "text"},
|
||||||
|
by=user["email"])
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": "설정을 저장했습니다."}), status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
def _shrink(data: bytes) -> tuple[bytes, int, int]:
|
||||||
|
"""사진 → 메일용 JPEG(가로 최대 700px, 회전 정보 반영, 투명 = 흰 바탕). 못 여는 파일(HEIC 등)은 ValueError."""
|
||||||
|
from PIL import Image, ImageOps # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
im = Image.open(BytesIO(data))
|
||||||
|
im = ImageOps.exif_transpose(im)
|
||||||
|
if im.mode not in ("RGB", "L"):
|
||||||
|
rgba = im.convert("RGBA")
|
||||||
|
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||||
|
bg.paste(rgba, mask=rgba.split()[-1])
|
||||||
|
im = bg
|
||||||
|
if im.width > IMAGE_MAX_W:
|
||||||
|
im = im.resize((IMAGE_MAX_W, max(1, round(im.height * IMAGE_MAX_W / im.width))), Image.LANCZOS)
|
||||||
|
buf = BytesIO()
|
||||||
|
im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
raise ValueError("사진을 열 수 없습니다(JPG·PNG·WEBP 를 올리세요 — HEIC 는 안 됩니다).") from None
|
||||||
|
return buf.getvalue(), im.width, im.height
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/images")
|
||||||
|
def images_upload(request: Request, files: list[UploadFile] = File(...)) -> RedirectResponse:
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
added, errors = 0, []
|
||||||
|
for f in files:
|
||||||
|
data = f.file.read(IMAGE_MAX_BYTES + 1)
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
if len(data) > IMAGE_MAX_BYTES:
|
||||||
|
errors.append(f"{f.filename}: 15MB 보다 큽니다")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
jpg, w, h = _shrink(data)
|
||||||
|
st.add_image(filename=f.filename or "photo.jpg", data=jpg, width=w, height=h, by=user["email"])
|
||||||
|
added += 1
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(f"{f.filename}: {exc}")
|
||||||
|
msg = f"사진 {added}장을 넣었습니다." + (" · " + " · ".join(errors) if errors else "")
|
||||||
|
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": msg}) + "#images", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/images/{image_id:int}/delete")
|
||||||
|
def images_delete(request: Request, image_id: int) -> RedirectResponse:
|
||||||
|
_user(request)
|
||||||
|
_db(request).delete_image(image_id)
|
||||||
|
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": "사진을 뺐습니다."}) + "#images", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/settings/images/{image_id:int}/move")
|
||||||
|
def images_move(request: Request, image_id: int, direction: int = Form(...)) -> RedirectResponse:
|
||||||
|
_user(request)
|
||||||
|
_db(request).move_image(image_id, direction)
|
||||||
|
return RedirectResponse(url="/outreach/settings#images", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/images/{image_id:int}")
|
||||||
|
def image_view(request: Request, image_id: int) -> Response:
|
||||||
|
_user(request)
|
||||||
|
im = _db(request).get_image(image_id)
|
||||||
|
if im is None:
|
||||||
|
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
|
||||||
|
return Response(content=bytes(im["data"]), media_type="image/jpeg", headers={"Cache-Control": "private, max-age=3600"})
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 리스트 API
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
@router.get("/api/recipients")
|
||||||
|
def api_list(request: Request) -> JSONResponse:
|
||||||
|
_user(request)
|
||||||
|
st = _db(request)
|
||||||
|
template = st.get_template()
|
||||||
|
return JSONResponse({"rows": [_view(r, template) for r in st.list_recipients()]})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/recipients/parse")
|
||||||
|
def api_parse(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""붙여 넣은 글 → 줄마다 {address, name, kind, kind_label, handle, error, dup, exists} (저장 안 함)."""
|
||||||
|
_user(request)
|
||||||
|
st = _db(request)
|
||||||
|
rows = store.parse_bulk(str(payload.get("text") or ""))[:MAX_ADD]
|
||||||
|
have = {(r["kind"], r["handle"]) for r in st.list_recipients()}
|
||||||
|
for r in rows:
|
||||||
|
r["kind_label"] = store.KIND_LABELS.get(r["kind"] or "", "오류")
|
||||||
|
r["exists"] = bool(r["kind"]) and (r["kind"], r["handle"]) in have
|
||||||
|
return JSONResponse({"rows": rows})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/recipients")
|
||||||
|
def api_add(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
rows = [r for r in store.parse_bulk(str(payload.get("text") or "")) if not r["dup"]]
|
||||||
|
if len(rows) > MAX_ADD:
|
||||||
|
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_ADD}줄까지 넣을 수 있습니다.")
|
||||||
|
res = st.add_recipients(rows, by=user["email"])
|
||||||
|
return JSONResponse({"ok": True, **res})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/recipients/{rid:int}")
|
||||||
|
def api_update(request: Request, rid: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
_user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
r = st.update_recipient(rid, name=payload.get("name"), memo=payload.get("memo"), status=payload.get("status"))
|
||||||
|
except KeyError:
|
||||||
|
raise HTTPException(status_code=404, detail="리스트에 없는 줄입니다.")
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
return JSONResponse({"row": _view(r, st.get_template())})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/recipients/delete")
|
||||||
|
def api_delete(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
_user(request)
|
||||||
|
try:
|
||||||
|
ids = [int(i) for i in payload.get("ids") or []]
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="ids 가 올바르지 않습니다.")
|
||||||
|
return JSONResponse({"ok": True, "deleted": _db(request).delete_recipients(ids)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/recipients/{rid:int}/preview")
|
||||||
|
def api_preview(request: Request, rid: int) -> JSONResponse:
|
||||||
|
"""그 사람에게 갈 제목·HTML(사진은 /outreach/images 주소로)·DM 글."""
|
||||||
|
_user(request)
|
||||||
|
st = _db(request)
|
||||||
|
r = st.get_recipient(rid)
|
||||||
|
if r is None:
|
||||||
|
raise HTTPException(status_code=404, detail="리스트에 없는 줄입니다.")
|
||||||
|
t = st.get_template()
|
||||||
|
html = store.html_body(t, r["name"], [f"img-{im['id']}" for im in st.list_images()])
|
||||||
|
for im in st.list_images():
|
||||||
|
html = html.replace(f"cid:img-{im['id']}", f"/outreach/images/{im['id']}")
|
||||||
|
return JSONResponse({"subject": store.subject_for(t, r["name"]), "html": html,
|
||||||
|
"text": store.dm_text(t, r["name"]) if r["kind"] == "instagram" else store.plain_text(t, r["name"]),
|
||||||
|
"kind": r["kind"], "to": r["handle"], "sender_name": t["sender_name"]})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/send")
|
||||||
|
def api_send(request: Request, bg: BackgroundTasks, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""고른 줄 중 메일·대기/실패를 '발송중'으로 잡고(한 번만) 백그라운드로 본인 Gmail 발송. 진행은 GET /api/recipients 로."""
|
||||||
|
from . import send # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
try:
|
||||||
|
ids = [int(i) for i in payload.get("ids") or []]
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="ids 가 올바르지 않습니다.")
|
||||||
|
if not ids:
|
||||||
|
raise HTTPException(status_code=400, detail="보낼 줄을 고르세요.")
|
||||||
|
gm = _gmail_state(request, user)
|
||||||
|
if not gm["connected"]:
|
||||||
|
return JSONResponse({"ok": False, "reconnect": True,
|
||||||
|
"message": "Gmail 이 연결되지 않았습니다 — [Gmail 연결]을 먼저 하세요(내 Gmail 로 보냅니다)."},
|
||||||
|
status_code=409)
|
||||||
|
rows = st.claim_for_send(ids)
|
||||||
|
if not rows:
|
||||||
|
return JSONResponse({"ok": False, "message": "보낼 메일 줄이 없습니다(이미 보냈거나 보내는 중, 또는 DM 줄)."}, status_code=409)
|
||||||
|
bg.add_task(send.send_batch, st, _inout(request), rows=rows, user=dict(user))
|
||||||
|
return JSONResponse({"ok": True, "queued": len(rows)}, status_code=202)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/recipients/{rid:int}/dm-sent")
|
||||||
|
def api_dm_sent(request: Request, rid: int) -> JSONResponse:
|
||||||
|
user = _user(request)
|
||||||
|
st = _db(request)
|
||||||
|
t = st.get_template()
|
||||||
|
r0 = st.get_recipient(rid)
|
||||||
|
if r0 is None:
|
||||||
|
raise HTTPException(status_code=404, detail="리스트에 없는 줄입니다.")
|
||||||
|
try:
|
||||||
|
r = st.mark_dm_sent(rid, by=user["email"], subject=store.subject_for(t, r0["name"]))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
return JSONResponse({"row": _view(r, t)})
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 내 Gmail 연결 — 입출고·휴가와 같은 연결(inout_gmail_tokens), 같은 구글 콜백(/inout/gmail/callback)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
@router.get("/gmail/connect")
|
||||||
|
async def gmail_connect(request: Request) -> Any:
|
||||||
|
from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433
|
||||||
|
from app.modules.inout import gmail # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
if _inout(request) is None:
|
||||||
|
return RedirectResponse(url="/outreach/?" + urlencode({"msg": "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다."}),
|
||||||
|
status_code=303)
|
||||||
|
try:
|
||||||
|
client = gmail.oauth_client()
|
||||||
|
except gmail.GmailError as exc:
|
||||||
|
return RedirectResponse(url="/outreach/?" + urlencode({"msg": str(exc)}), status_code=303)
|
||||||
|
request.session["_gmail_origin"] = "outreach"
|
||||||
|
request.session["_gmail_next"] = "/outreach/"
|
||||||
|
return await client.authorize_redirect(
|
||||||
|
request, public_url_for(request, "inout_gmail_callback"),
|
||||||
|
access_type="offline", prompt="consent", include_granted_scopes="true",
|
||||||
|
login_hint=user.get("email", ""), hd=ALLOWED_DOMAIN)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/gmail/disconnect")
|
||||||
|
def gmail_disconnect(request: Request) -> RedirectResponse:
|
||||||
|
from app.modules.inout import gmail # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
inout = _inout(request)
|
||||||
|
if inout is not None:
|
||||||
|
row = inout.gmail_token(user["email"])
|
||||||
|
if row:
|
||||||
|
try:
|
||||||
|
gmail.revoke(gmail.decrypt_token(user["email"], row["refresh_token_enc"]))
|
||||||
|
except (gmail.GmailError, gmail.GmailNotConnected):
|
||||||
|
pass
|
||||||
|
inout.delete_gmail_token(user["email"])
|
||||||
|
return RedirectResponse(url="/outreach/?" + urlencode({"msg": "Gmail 연결을 끊었습니다(입출고·휴가 메일 연결도 함께)."}),
|
||||||
|
status_code=303)
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
"""안내문 메일 일괄 발송(2026-10-27) — 보내는 사람 본인 Gmail(입출고·휴가와 같은 Gmail 연결, gmail.send 만)로 한 사람에 한 통.
|
||||||
|
|
||||||
|
라우터가 고른 줄을 '발송중'으로 잡은 뒤(db.claim_for_send — 두 번 눌러도 한 번) 응답하고, 이 함수가 백그라운드에서 차례로 보낸다.
|
||||||
|
줄마다 {이름} 을 바꾼 제목·본문 + 설정 사진(본문 아래, cid)을 만들어 보내고 보냄/실패와 기록(outreach_logs)을 남긴다.
|
||||||
|
본문에 {이름} 이 있는데 이름이 빈 줄은 보내지 않고 실패('이름 없음'). Gmail 연결이 끊기면 남은 줄은 실패(다시 연결 안내).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
logger = logging.getLogger("app.outreach.send")
|
||||||
|
SEND_GAP_SECONDS = 1.0 # 한 통마다 쉬는 시간 — Gmail 이 짧은 시간에 몰린 발송을 막지 않게
|
||||||
|
|
||||||
|
|
||||||
|
def _cid(image_id: int) -> str:
|
||||||
|
return f"outreach-{image_id}@dbx"
|
||||||
|
|
||||||
|
|
||||||
|
def build_mail(template: dict[str, Any], images: list[dict[str, Any]], *, name: str, sender_name: str, sender_email: str,
|
||||||
|
to: str) -> bytes:
|
||||||
|
from app.modules.inout import gmail # noqa: WPS433
|
||||||
|
|
||||||
|
cids = [_cid(int(im["id"])) for im in images]
|
||||||
|
return gmail.build_message(
|
||||||
|
sender_name=template.get("sender_name") or sender_name, sender_email=sender_email, to=[to], cc=[],
|
||||||
|
subject=store.subject_for(template, name), text=store.plain_text(template, name),
|
||||||
|
html=store.html_body(template, name, cids),
|
||||||
|
inline_images=[{"cid": c, "data": bytes(im["data"])} for c, im in zip(cids, images)],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def send_batch(db: Any, inout_store: Any, *, rows: list[dict[str, Any]], user: dict[str, Any],
|
||||||
|
gap: float = SEND_GAP_SECONDS) -> dict[str, int]:
|
||||||
|
"""잡아 둔 줄(rows)을 차례로 보낸다 — {"sent", "failed"}. 예외를 밖으로 던지지 않는다(줄마다 결과를 남김)."""
|
||||||
|
from app.modules.inout import gmail # noqa: WPS433
|
||||||
|
|
||||||
|
email = str(user.get("email") or "").lower()
|
||||||
|
result = {"sent": 0, "failed": 0}
|
||||||
|
try:
|
||||||
|
template = db.get_template()
|
||||||
|
images = db.list_images(with_data=True)
|
||||||
|
subject_of = lambda r: store.subject_for(template, r["name"]) # noqa: E731
|
||||||
|
row = inout_store.gmail_token(email) if inout_store is not None else None
|
||||||
|
refresh = gmail.decrypt_token(email, row["refresh_token_enc"]) if row else None
|
||||||
|
except Exception as exc: # noqa: BLE001 — 준비 실패 = 잡아 둔 줄 모두 실패(발송중으로 남지 않게)
|
||||||
|
for r in rows:
|
||||||
|
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject="", error=f"보낼 준비 실패: {exc}")
|
||||||
|
result["failed"] = len(rows)
|
||||||
|
return result
|
||||||
|
stop_reason = "" if refresh else "Gmail 이 연결되지 않았습니다 — 안내문 발송 → [Gmail 연결] 뒤 다시 보내세요."
|
||||||
|
need_name = store.needs_name(template)
|
||||||
|
for i, r in enumerate(rows):
|
||||||
|
if stop_reason:
|
||||||
|
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=stop_reason)
|
||||||
|
result["failed"] += 1
|
||||||
|
continue
|
||||||
|
if need_name and not (r.get("name") or "").strip():
|
||||||
|
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r),
|
||||||
|
error="이름 없음 — 본문에 {이름} 이 있어 이름을 넣은 뒤 다시 보내세요.")
|
||||||
|
result["failed"] += 1
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
raw = build_mail(template, images, name=r["name"], sender_name=str(user.get("name") or ""),
|
||||||
|
sender_email=email, to=r["handle"])
|
||||||
|
gmail.send(refresh, raw)
|
||||||
|
except gmail.GmailNotConnected as exc:
|
||||||
|
try:
|
||||||
|
inout_store.delete_gmail_token(email)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
stop_reason = f"Gmail 연결이 끊겼습니다 — 다시 연결한 뒤 보내세요. ({exc})"
|
||||||
|
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=stop_reason)
|
||||||
|
result["failed"] += 1
|
||||||
|
continue
|
||||||
|
except Exception as exc: # noqa: BLE001 — 그 사람만 실패(받는 주소 오류 등), 다음 사람은 계속
|
||||||
|
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=str(exc)[:300])
|
||||||
|
result["failed"] += 1
|
||||||
|
continue
|
||||||
|
db.finish_send(r["id"], ok=True, via="gmail", by=email, subject=subject_of(r))
|
||||||
|
result["sent"] += 1
|
||||||
|
if gap and i < len(rows) - 1:
|
||||||
|
time.sleep(gap)
|
||||||
|
try:
|
||||||
|
if inout_store is not None and result["sent"]:
|
||||||
|
inout_store.mark_gmail(email)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
logger.info("안내문 메일 %s: 보냄 %s · 실패 %s", email, result["sent"], result["failed"])
|
||||||
|
return result
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
"""안내문 발송 — 순수 함수(DB 없음): 주소 판별(이메일 / 인스타그램), 리스트 붙여넣기 해석, {이름} 바꾸기, 메일 HTML·DM 글.
|
||||||
|
|
||||||
|
- 주소를 보고 정한다: `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
|
||||||
|
- 본문 `{이름}` = 그 줄 이름. 메일 본문 = 설정 화면 편집기의 HTML(`fmt: "html"`) — 저장·읽을 때마다 `sanitize_html`(허용 태그·스타일만).
|
||||||
|
예전 글·기본 문구(`fmt` 없음 = 글)는 `text_to_html`(`**굵게**` → 굵게, 주소 → 링크, 줄마다 문단).
|
||||||
|
- DM 글 = 설정 `dm_body`(인스타 DM 용 글, 서식 없음). 비어 있으면 메일 본문 글 + 끝 문구.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from html import escape
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
NAME_TAG = "{이름}"
|
||||||
|
KINDS = ("email", "instagram")
|
||||||
|
KIND_LABELS = {"email": "메일", "instagram": "DM"}
|
||||||
|
STATUSES = ("대기", "발송중", "보냄", "실패")
|
||||||
|
|
||||||
|
_EMAIL_RE = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$")
|
||||||
|
_IG_USER_RE = re.compile(r"^[A-Za-z0-9._]{1,30}$")
|
||||||
|
_IG_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?(?:instagram\.com|instagr\.am)/([^/?#\s]+)", re.IGNORECASE)
|
||||||
|
_IG_ME_RE = re.compile(r"^(?:https?://)?ig\.me/m/([^/?#\s]+)", re.IGNORECASE)
|
||||||
|
# instagram.com 아래 계정이 아닌 주소(게시물·릴스 등)
|
||||||
|
_IG_RESERVED = {"p", "reel", "reels", "tv", "explore", "stories", "direct", "accounts", "about", "legal", "developer"}
|
||||||
|
|
||||||
|
DEFAULT_TEMPLATE: dict[str, Any] = {
|
||||||
|
"subject": "누적매출 300억. 800만개 판매 신화 미라클통 '미라네주방'입니다.",
|
||||||
|
"sender_name": "미라네주방",
|
||||||
|
"ad_label": False,
|
||||||
|
"footer": "",
|
||||||
|
"dm_body": "",
|
||||||
|
"fmt": "text", # body 형식 — 기본 문구는 글, 설정 화면에서 저장하면 "html"
|
||||||
|
"body": """안녕하세요, {이름}님.
|
||||||
|
주방의 본질을 지키며 6년간 묵묵히 300억 매출의 신화를 써온 **'미라네주방'**입니다.
|
||||||
|
저희는 지난 6년간 제품력 하나로 국내/해외 800만 개 판매를 돌파하고 호주, 동남아 등 글로벌 시장에서 인정받았습니다.
|
||||||
|
브랜드의 가치를 지키기 위해 공동구매를 극도로 자제해왔으나,
|
||||||
|
최근 'ㅎ 인플루언서'와의 PPL 및 전용 상품 협업을 통해 단일 프로젝트 매출 약3억, 누적 약 8억원이라는 놀라운 기록을 확인하였고,
|
||||||
|
ㄷ'인플루언서'님과는 약 2억원의 매출을 달성하는 등 인플루언서 파트너십의 새로운 가능성을 보았습니다.
|
||||||
|
|
||||||
|
이에, 압도적인 신뢰도와 감각을 보유하신 {이름}님과의 공동구매 파트너십을 정중히 제안드립니다.
|
||||||
|
|
||||||
|
왜 '미라네주방'이어야 하는가?
|
||||||
|
시장 점유율로 증명된 '미라클통'의 힘: 누적 800만 개 판매. 이미 시장에서 검증된 제품은 팔로워들에게 구구절절 설명할 필요가 없습니다.
|
||||||
|
희소성의 가치: 아무나 할 수 있는 공구가 아닙니다. 공구를 지양해온 브랜드이기에 {이름}님의 피드에서 진행되는 공구는 팔로워들에게 더욱 특별한 기회로 인식될 것입니다.
|
||||||
|
|
||||||
|
1단계: 검증된 베스트셀러로 화력 확인 (Existing Product)
|
||||||
|
이미 800만 개가 팔려나가며 시장성이 검증된 ‘미라클통’ 등 기존 베스트셀러 라인으로 공동구매를 진행합니다.
|
||||||
|
팔로워들에게는 '구하고 싶어도 공구로 만나기 힘들었던 제품'이라는 명분을, 인플루언서님께는 확실한 수익과 유입을 보장합니다.
|
||||||
|
|
||||||
|
2단계: 화력 입증 시 {이름}님 전용 상품 개발 (Exclusive Product)
|
||||||
|
첫 공구에서 유의미한 매출 성과가 확인될 경우, 저희는 즉시 {이름}님만을 위한 전용 상품(PB/콜라보) 개발에 착수합니다.
|
||||||
|
전용 컬러, 단독 구성, 혹은 니즈를 반영한 신규 기능을 담아, 어디에서도 볼 수 없는 '귀하만의 제품'을 시장에 선보이게 됩니다.
|
||||||
|
이는 인플루언서로서의 브랜드 가치를 한 단계 높이는 결정적인 계기가 될 것입니다.
|
||||||
|
"'ㅎ인플루언서님'과의 콜라보 사례를 하단과 같이 사진 공유드립니다."
|
||||||
|
|
||||||
|
미라네주방은 단순히 한 번의 공구로 끝나는 관계를 원하지 않습니다.
|
||||||
|
{이름}님의 감각과 저희의 기술력이 만나 주방용품 시장의 판도를 바꿀 '전용 브랜드'를 함께 만들어가길 희망합니다.
|
||||||
|
긍정적인 검토 부탁드리며, 미라네주방의 성공 신화에 함께 올라타실 파트너가 되어주시길 기다리겠습니다.
|
||||||
|
|
||||||
|
감사합니다.
|
||||||
|
|
||||||
|
|
||||||
|
미라네주방 팀 드림
|
||||||
|
https://miras.co.kr/""",
|
||||||
|
}
|
||||||
|
SUBJECT_MAX, BODY_MAX, FOOTER_MAX = 200, 100000, 2000 # BODY_MAX = 정리한 HTML 길이
|
||||||
|
DM_MAX = 1000 # 인스타 DM 한 통 글자 수 한도
|
||||||
|
|
||||||
|
|
||||||
|
def _ig_user(value: str) -> str | None:
|
||||||
|
v = value.strip().strip("/")
|
||||||
|
if v.startswith("@"):
|
||||||
|
v = v[1:]
|
||||||
|
if not _IG_USER_RE.match(v) or v.startswith(".") or v.endswith(".") or ".." in v:
|
||||||
|
return None
|
||||||
|
if v.lower() in _IG_RESERVED:
|
||||||
|
return None
|
||||||
|
return v.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def detect(address: Any) -> dict[str, Any]:
|
||||||
|
"""주소 → {"kind": "email"|"instagram"|None, "handle", "error"}. handle = 이메일 소문자 / 인스타 계정명 소문자."""
|
||||||
|
raw = str(address or "").strip().strip("<>").strip()
|
||||||
|
if raw.lower().startswith("mailto:"):
|
||||||
|
raw = raw[7:]
|
||||||
|
if not raw:
|
||||||
|
return {"kind": None, "handle": "", "error": "주소가 비었습니다."}
|
||||||
|
if "@" in raw and not raw.startswith("@") and "/" not in raw:
|
||||||
|
if _EMAIL_RE.match(raw) and len(raw) <= 320:
|
||||||
|
return {"kind": "email", "handle": raw.lower(), "error": ""}
|
||||||
|
return {"kind": None, "handle": "", "error": f"이메일 주소가 올바르지 않습니다: {raw}"}
|
||||||
|
for rx in (_IG_ME_RE, _IG_URL_RE):
|
||||||
|
m = rx.match(raw)
|
||||||
|
if m:
|
||||||
|
user = _ig_user(m.group(1))
|
||||||
|
if user:
|
||||||
|
return {"kind": "instagram", "handle": user, "error": ""}
|
||||||
|
return {"kind": None, "handle": "", "error": f"인스타그램 계정 주소가 아닙니다: {raw}"}
|
||||||
|
user = _ig_user(raw)
|
||||||
|
if user and (raw.startswith("@") or re.search(r"[A-Za-z]", raw)):
|
||||||
|
return {"kind": "instagram", "handle": user, "error": ""}
|
||||||
|
return {"kind": None, "handle": "", "error": f"이메일도 인스타그램 주소도 아닙니다: {raw}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_explicit(part: str) -> bool:
|
||||||
|
"""이메일·@계정·인스타 주소처럼 '주소'가 분명한 칸인가(계정명만 쓴 칸보다 먼저 주소로 고른다)."""
|
||||||
|
p = part.strip()
|
||||||
|
return "@" in p or "instagram.com" in p.lower() or "instagr.am" in p.lower() or "ig.me/" in p.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_line(line: str) -> dict[str, Any] | None:
|
||||||
|
"""붙여 넣은 한 줄 → {"address", "name", ...detect}. 빈 줄·#주석 = None.
|
||||||
|
칸 나누기 = 탭 · 쉼표 · (둘 다 없으면) 공백. 주소가 분명한 칸(이메일·@·인스타 링크)을 주소로, 나머지는 이름.
|
||||||
|
둘 다 분명하지 않으면 '주소, 이름' 순서로 본다."""
|
||||||
|
s = line.strip()
|
||||||
|
if not s or s.startswith("#"):
|
||||||
|
return None
|
||||||
|
parts = [p.strip() for p in re.split(r"\t|,", s) if p.strip()]
|
||||||
|
if len(parts) == 1:
|
||||||
|
parts = s.split()
|
||||||
|
addr_i = next((i for i, p in enumerate(parts) if _looks_explicit(p) and detect(p)["kind"]), None)
|
||||||
|
if addr_i is None:
|
||||||
|
addr_i = next((i for i, p in enumerate(parts) if detect(p)["kind"]), 0)
|
||||||
|
address = parts[addr_i]
|
||||||
|
name = " ".join(p for i, p in enumerate(parts) if i != addr_i).strip()
|
||||||
|
return {"address": address, "name": name[:100], **detect(address)}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_bulk(text: str) -> list[dict[str, Any]]:
|
||||||
|
"""여러 줄 붙여넣기 → 줄마다 parse_line(빈 줄 건너뜀), 같은 주소는 처음 것만(dup=True 표시)."""
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
seen: set[tuple[str, str]] = set()
|
||||||
|
for i, line in enumerate(str(text or "").splitlines(), 1):
|
||||||
|
r = parse_line(line)
|
||||||
|
if r is None:
|
||||||
|
continue
|
||||||
|
r["line"] = i
|
||||||
|
key = (r["kind"] or "", r["handle"])
|
||||||
|
r["dup"] = bool(r["kind"]) and key in seen
|
||||||
|
seen.add(key)
|
||||||
|
out.append(r)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_template(value: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
|
"""설정 값 정리 — 빠진 칸은 기본값, 길이 제한."""
|
||||||
|
v = dict(DEFAULT_TEMPLATE)
|
||||||
|
for k, val in (value or {}).items():
|
||||||
|
if k in v:
|
||||||
|
v[k] = val
|
||||||
|
v["subject"] = str(v["subject"] or "").strip()[:SUBJECT_MAX]
|
||||||
|
body = str(v["body"] or "")[:BODY_MAX * 3]
|
||||||
|
v["body"] = sanitize_html(body if v["fmt"] == "html" else text_to_html(body))
|
||||||
|
v["fmt"] = "html"
|
||||||
|
v["footer"] = str(v["footer"] or "").replace("\r\n", "\n").strip()[:FOOTER_MAX]
|
||||||
|
v["dm_body"] = str(v["dm_body"] or "").replace("\r\n", "\n").strip()[:DM_MAX]
|
||||||
|
v["sender_name"] = str(v["sender_name"] or "").strip()[:60]
|
||||||
|
v["ad_label"] = bool(v["ad_label"])
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def needs_name(template: dict[str, Any], kind: str = "email") -> bool:
|
||||||
|
"""그 구분(메일/DM)으로 갈 글에 {이름}이 있는가 — DM 은 DM 문구(없으면 메일 본문)만 본다."""
|
||||||
|
if kind == "instagram" and (template.get("dm_body") or "").strip():
|
||||||
|
return NAME_TAG in template["dm_body"]
|
||||||
|
body = html_to_text(template.get("body") or "")
|
||||||
|
if kind == "instagram":
|
||||||
|
return NAME_TAG in body or NAME_TAG in (template.get("footer") or "")
|
||||||
|
return NAME_TAG in (template.get("subject") or "") or NAME_TAG in body
|
||||||
|
|
||||||
|
|
||||||
|
def fill(text: str, name: str) -> str:
|
||||||
|
return str(text or "").replace(NAME_TAG, str(name or "").strip())
|
||||||
|
|
||||||
|
|
||||||
|
def subject_for(template: dict[str, Any], name: str) -> str:
|
||||||
|
s = fill(template.get("subject") or "", name)
|
||||||
|
return ("(광고) " + s) if template.get("ad_label") and not s.startswith("(광고)") else s
|
||||||
|
|
||||||
|
|
||||||
|
def plain_text(template: dict[str, Any], name: str) -> str:
|
||||||
|
"""메일 글 부분(HTML 메일의 글 버전)·DM 문구가 없을 때의 DM 글 — 본문 글 + 끝 문구."""
|
||||||
|
body = fill(html_to_text(template.get("body") or ""), name).rstrip()
|
||||||
|
footer = (template.get("footer") or "").strip()
|
||||||
|
return body + ("\n\n" + fill(footer, name) if footer else "")
|
||||||
|
|
||||||
|
|
||||||
|
def dm_text(template: dict[str, Any], name: str) -> str:
|
||||||
|
"""인스타 DM 글 — DM 문구가 있으면 그것, 없으면 메일 글(plain_text). **굵게** 는 별표만 뺀다."""
|
||||||
|
dm = (template.get("dm_body") or "").strip()
|
||||||
|
if not dm:
|
||||||
|
return plain_text(template, name)
|
||||||
|
return re.sub(r"\*\*(.+?)\*\*", r"\1", fill(dm, name))
|
||||||
|
|
||||||
|
|
||||||
|
def dm_saved_body(value: Any) -> tuple[str, str]:
|
||||||
|
"""DM 수동 보내기 탭에 저장할 본문 → (제목, 본문). 제목 = 첫 글 줄 40자(목록 표시용). 비었거나 너무 길면 ValueError."""
|
||||||
|
body = str(value or "").replace("\r\n", "\n").strip()
|
||||||
|
if not body:
|
||||||
|
raise ValueError("본문을 쓰세요.")
|
||||||
|
if len(body) > DM_MAX:
|
||||||
|
raise ValueError(f"본문은 {DM_MAX}자까지입니다(인스타 DM 한도) — 지금 {len(body)}자.")
|
||||||
|
title = next((ln.strip() for ln in body.split("\n") if ln.strip()), "")
|
||||||
|
return (title[:40] + ("…" if len(title) > 40 else "")), body
|
||||||
|
|
||||||
|
|
||||||
|
# ── 메일 본문 HTML ─────────────────────────────────────────
|
||||||
|
_URL_RE = re.compile(r"https?://[^\s<>\"']+")
|
||||||
|
_ALLOWED_TAGS = {"p", "br", "strong", "b", "em", "i", "u", "s", "strike", "span", "a", "ul", "ol", "li",
|
||||||
|
"h1", "h2", "h3", "blockquote", "sub", "sup"}
|
||||||
|
_DROP_WITH_CONTENT = {"script", "style", "iframe", "object", "head", "title", "template", "noscript", "svg", "math",
|
||||||
|
"textarea", "select"}
|
||||||
|
_STYLE_PROPS = {"color", "background-color", "font-size", "font-weight", "font-style", "text-decoration", "text-align"}
|
||||||
|
_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()-]{1,60}$")
|
||||||
|
# {이름} — 편집기에서 글자마다 서식이 달라 태그가 끼어도 찾는다(태그는 남기고 글자만 이름으로)
|
||||||
|
_NAME_IN_HTML_RE = re.compile(r"\{((?:<[^>]*>)*)이((?:<[^>]*>)*)름((?:<[^>]*>)*)\}")
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_style(value: str) -> str:
|
||||||
|
out = []
|
||||||
|
for decl in value.split(";"):
|
||||||
|
prop, _, val = decl.partition(":")
|
||||||
|
prop, val = prop.strip().lower(), val.strip()
|
||||||
|
if prop in _STYLE_PROPS and _STYLE_VALUE_RE.match(val) and not re.search(r"url|expression", val, re.I):
|
||||||
|
out.append(f"{prop}: {val}")
|
||||||
|
return "; ".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
class _Sanitizer(HTMLParser):
|
||||||
|
"""허용 태그·속성(style 은 글자 서식만, a 는 http(s)/mailto 링크만)만 남기고 글은 escape. 태그 짝은 맞춰 닫는다.
|
||||||
|
편집기(Quill getSemanticHTML)가 띄어쓰기를 로 내보내 보통 띄어쓰기로 바꾼다(메일은 pre-wrap 이라 여러 칸도 그대로)."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.out: list[str] = []
|
||||||
|
self.stack: list[str] = []
|
||||||
|
self.skip = 0
|
||||||
|
self.empty_p = False # 지금 연 <p> 에 아직 글이 없다 — 닫을 때 <br> 을 넣어 빈 줄 높이를 지킨다
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag in _DROP_WITH_CONTENT:
|
||||||
|
self.skip += 1
|
||||||
|
return
|
||||||
|
if self.skip or tag not in _ALLOWED_TAGS:
|
||||||
|
return
|
||||||
|
if tag == "br":
|
||||||
|
self.out.append("<br>")
|
||||||
|
self.empty_p = False
|
||||||
|
return
|
||||||
|
a = {k: v or "" for k, v in attrs}
|
||||||
|
extra = ""
|
||||||
|
style = _clean_style(a.get("style", ""))
|
||||||
|
if style:
|
||||||
|
extra += f' style="{escape(style)}"'
|
||||||
|
href = a.get("href", "").strip()
|
||||||
|
if tag == "a" and re.match(r"^(https?:|mailto:)", href, re.I):
|
||||||
|
extra += f' href="{escape(href)}"'
|
||||||
|
self.out.append(f"<{tag}{extra}>")
|
||||||
|
self.stack.append(tag)
|
||||||
|
if tag == "p":
|
||||||
|
self.empty_p = True
|
||||||
|
|
||||||
|
def handle_endtag(self, tag: str) -> None:
|
||||||
|
if tag in _DROP_WITH_CONTENT:
|
||||||
|
self.skip = max(0, self.skip - 1)
|
||||||
|
return
|
||||||
|
if self.skip or tag not in self.stack:
|
||||||
|
return
|
||||||
|
while self.stack:
|
||||||
|
t = self.stack.pop()
|
||||||
|
if t == "p" and self.empty_p:
|
||||||
|
self.out.append("<br>")
|
||||||
|
self.empty_p = False
|
||||||
|
self.out.append(f"</{t}>")
|
||||||
|
if t == tag:
|
||||||
|
break
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
if self.skip:
|
||||||
|
return
|
||||||
|
text = data.replace("\r", "").replace("\n", " ").replace("\xa0", " ")
|
||||||
|
if not text.strip() and (not self.stack or self.stack[-1] in ("ul", "ol")):
|
||||||
|
return
|
||||||
|
if text:
|
||||||
|
self.out.append(escape(text, quote=False))
|
||||||
|
self.empty_p = False
|
||||||
|
|
||||||
|
def result(self) -> str:
|
||||||
|
self.close()
|
||||||
|
while self.stack:
|
||||||
|
self.handle_endtag(self.stack[-1])
|
||||||
|
return "".join(self.out)
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_html(html: str) -> str:
|
||||||
|
p = _Sanitizer()
|
||||||
|
p.feed(str(html or ""))
|
||||||
|
return p.result()
|
||||||
|
|
||||||
|
|
||||||
|
def text_to_html(text: str) -> str:
|
||||||
|
"""글(예전 본문·기본 문구) → 본문 HTML — 줄마다 문단, 빈 줄 = <p><br></p>, **굵게** → <strong>, 주소 → 링크."""
|
||||||
|
out = []
|
||||||
|
for line in str(text or "").replace("\r\n", "\n").rstrip("\n").split("\n"):
|
||||||
|
h = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", escape(line, quote=False))
|
||||||
|
h = _URL_RE.sub(lambda m: f'<a href="{m.group(0)}">{m.group(0)}</a>', h)
|
||||||
|
out.append(f"<p>{h or '<br>'}</p>")
|
||||||
|
return "".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
class _Text(HTMLParser):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts: list[str] = []
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||||
|
if tag == "br":
|
||||||
|
self.parts.append("\x00") # 문단 끝 바로 앞의 <br>(빈 줄 표시)은 줄을 하나 더 만들지 않는다
|
||||||
|
elif tag == "li":
|
||||||
|
self.parts.append("- ")
|
||||||
|
|
||||||
|
def handle_endtag(self, tag: str) -> None:
|
||||||
|
if tag in ("p", "li", "h1", "h2", "h3", "blockquote"):
|
||||||
|
if self.parts and self.parts[-1] == "\x00":
|
||||||
|
self.parts.pop()
|
||||||
|
self.parts.append("\n")
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
self.parts.append(data.replace("\xa0", " "))
|
||||||
|
|
||||||
|
|
||||||
|
def html_to_text(html: str) -> str:
|
||||||
|
"""본문 HTML → 글(메일 글 버전·DM·{이름} 찾기·리스트 화면 요약)."""
|
||||||
|
p = _Text()
|
||||||
|
p.feed(str(html or ""))
|
||||||
|
p.close()
|
||||||
|
return "".join(p.parts).replace("\x00", "\n").rstrip()
|
||||||
|
|
||||||
|
|
||||||
|
def fill_html(html: str, name: str) -> str:
|
||||||
|
return _NAME_IN_HTML_RE.sub(lambda m: escape(str(name or "").strip()) + m.group(1) + m.group(2) + m.group(3), str(html or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _p_margin(html: str) -> str:
|
||||||
|
"""메일 프로그램은 <p> 에 위아래 여백을 줘 편집기보다 줄 간격이 벌어진다 — margin:0 을 붙인다."""
|
||||||
|
return re.sub(r'<p( style=")?', lambda m: '<p style="margin:0;' if m.group(1) else '<p style="margin:0"', html)
|
||||||
|
|
||||||
|
|
||||||
|
def html_body(template: dict[str, Any], name: str, image_cids: list[str] | None = None) -> str:
|
||||||
|
"""메일 HTML — 본문(정리된 편집기 HTML, {이름} 바꿈) + 끝 문구(글 → escape·링크) + 사진은 본문 아래(cid)."""
|
||||||
|
body = fill_html(sanitize_html(template.get("body") or ""), name)
|
||||||
|
footer = (template.get("footer") or "").strip()
|
||||||
|
if footer:
|
||||||
|
body += "<p><br></p>" + text_to_html(fill(footer, name))
|
||||||
|
imgs = "".join(f'<p style="margin:12px 0 0"><img src="cid:{c}" alt="" style="max-width:100%;height:auto;border-radius:6px"></p>'
|
||||||
|
for c in (image_cids or []))
|
||||||
|
return ('<div style="font-family:Pretendard,\'Malgun Gothic\',sans-serif;font-size:14px;line-height:1.7;color:#111;white-space:pre-wrap">'
|
||||||
|
f"{_p_margin(body)}</div>{imgs}")
|
||||||
|
|
||||||
|
|
||||||
|
def dm_link(handle: str) -> str:
|
||||||
|
"""인스타 DM 창 — ig.me/m/계정(앱·웹 모두 그 사람과의 대화로)."""
|
||||||
|
return f"https://ig.me/m/{handle}"
|
||||||
|
|
||||||
|
|
||||||
|
def profile_link(handle: str) -> str:
|
||||||
|
return f"https://www.instagram.com/{handle}/"
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{#- 안내문 발송 탭(2026-10-30) — [발송 리스트] [DM 수동 보내기] + 맨 오른쪽 설정 톱니(실적·프로젝트와 같은 Material Symbols "settings") -#}
|
||||||
|
<nav class="otr-tabs" aria-label="안내문 발송 메뉴">
|
||||||
|
<div class="otr-tabs-main" role="tablist">
|
||||||
|
<a class="otr-tab{% if active_tab == 'list' %} is-active{% endif %}" href="/outreach/" role="tab"
|
||||||
|
aria-selected="{{ 'true' if active_tab == 'list' else 'false' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">forward_to_inbox</span>발송 리스트</a>
|
||||||
|
<a class="otr-tab{% if active_tab == 'dm' %} is-active{% endif %}" href="/outreach/dm" role="tab"
|
||||||
|
aria-selected="{{ 'true' if active_tab == 'dm' else 'false' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">chat</span>DM 수동 보내기</a>
|
||||||
|
</div>
|
||||||
|
<a class="otr-gear" href="/outreach/settings" title="설정" aria-label="설정">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||||
|
</nav>
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{#- DM 수동 보내기 탭(2026-10-30) — 왼쪽 = 이름 넣기(붙여 넣기·.txt/.csv 첫 칸) + 이름 목록(한 명씩·전체 지우기),
|
||||||
|
가운데 = 본문(고칠 수 있음, {이름} 자리는 분홍 이름 칩), 오른쪽 = 저장한 본문 목록(고르기·하나씩 지우기, outreach_db 002).
|
||||||
|
이름을 누르면 본문의 {이름} 이 그 이름으로 바뀌고 바로 클립보드에 복사. 이름 목록은 저장하지 않음(브라우저만). -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="otr otr-dm-page" id="otr-dm">
|
||||||
|
{% include "outreach/_tabs.html" %}
|
||||||
|
|
||||||
|
<div class="otr-dm-split">
|
||||||
|
<div class="erp-card otr-dm-left">
|
||||||
|
<div class="otr-add-head"><b>이름</b>
|
||||||
|
<span class="erp-muted">한 줄에 한 이름 — 붙여 넣거나 파일(.txt·.csv, 첫 칸)을 올리세요. 엑셀은 이름 칸을 복사해 붙여 넣으면 됩니다.</span></div>
|
||||||
|
<textarea class="erp-input otr-add-text" id="otr-dm-text" rows="4" placeholder="김철수 미라네 이수진"></textarea>
|
||||||
|
<div class="otr-add-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="otr-dm-load">이름 넣기</button>
|
||||||
|
<label class="erp-btn erp-btn-outline otr-dm-file">파일 올리기<input type="file" id="otr-dm-file" accept=".txt,.csv,text/plain,text/csv" hidden /></label>
|
||||||
|
</div>
|
||||||
|
<div class="otr-dm-listhead"><span class="erp-muted" id="otr-dm-sum">0명</span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm otr-danger" id="otr-dm-clear" disabled>전체 삭제</button></div>
|
||||||
|
<ul class="otr-dm-names" id="otr-dm-names" aria-label="이름 목록"></ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card otr-dm-right">
|
||||||
|
<div class="otr-add-head"><b>본문 <span class="otr-dm-cur" id="otr-dm-cur"></span></b>
|
||||||
|
<span class="erp-muted">바로 고칠 수 있습니다. 분홍 글자 = <code>{이름}</code> 자리(왼쪽 이름을 누르면 바뀌고 복사됨, 새 자리는 <code>{이름}</code> 이라고 쓰면 됨).</span></div>
|
||||||
|
<div class="otr-add-actions otr-dm-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="otr-dm-save" disabled title="오른쪽 목록에서 고른 본문을 이 글로 바꿉니다">저장</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="otr-dm-saveas">새 본문으로 저장</button>
|
||||||
|
<span class="erp-muted" id="otr-dm-count"></span>
|
||||||
|
</div>
|
||||||
|
<div class="otr-dm-body" id="otr-dm-body" contenteditable="plaintext-only" spellcheck="false" role="textbox" aria-multiline="true" aria-label="본문"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card otr-dm-saved">
|
||||||
|
<div class="otr-add-head"><b>저장한 본문</b><span class="erp-muted">누르면 가운데 본문으로 불러옵니다.</span></div>
|
||||||
|
{% if dm_bodies is none %}
|
||||||
|
<p class="otr-msg">본문 저장 표가 아직 없습니다 — 관리자가 outreach_db 마이그레이션 002(<code>scripts/sql/outreach_db_002_dm_bodies.sql</code>)를 적용하면 저장할 수 있습니다.</p>
|
||||||
|
{% endif %}
|
||||||
|
<ul class="otr-dm-names otr-dm-bodies" id="otr-dm-bodies" aria-label="저장한 본문 목록"></ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script type="application/json" id="otr-data">{{ {"dm_template": dm_template, "dm_bodies": dm_bodies, "dm_max": dm_max} | tojson }}</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}<script src="/static/outreach.js?v=20261030c" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{#- 안내문 발송(2026-10-27) — 리스트(주소 + 이름) → 메일은 [선택한 메일 보내기](본인 Gmail, 한 사람에 한 통), 인스타는 [DM 보내기](문구 복사 + DM 창)
|
||||||
|
→ 보낸 뒤 [보냄]. 주소를 보고 메일/DM 을 정한다(store.detect). 본문 {이름} = 그 줄 이름. -#}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="otr" id="otr" data-needs-name="{{ '1' if needs_name else '' }}">
|
||||||
|
{% include "outreach/_tabs.html" %}
|
||||||
|
|
||||||
|
<div class="otr-top">
|
||||||
|
<div class="otr-top-main">
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="otr-add-open">+ 리스트 추가</button>
|
||||||
|
</div>
|
||||||
|
<div class="otr-gmail">
|
||||||
|
{% if gmail.connected %}
|
||||||
|
<span class="otr-gmail-on">보내는 메일: <b>{{ gmail.email }}</b> (Gmail 연결됨)</span>
|
||||||
|
<form method="post" action="/outreach/gmail/disconnect" onsubmit="return confirm('Gmail 연결을 끊을까요? 입출고·휴가 메일 연결도 함께 끊깁니다.');">
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm">연결 끊기</button></form>
|
||||||
|
{% elif gmail.available %}
|
||||||
|
<span class="otr-gmail-off">메일은 내 Gmail 로 보냅니다 —</span>
|
||||||
|
<a class="erp-btn erp-btn-primary erp-btn-sm" href="/outreach/gmail/connect">Gmail 연결</a>
|
||||||
|
{% else %}
|
||||||
|
<span class="otr-gmail-off">Gmail 연결을 쓸 수 없는 서버입니다(입출고 DB·구글 OAuth·APP_ENCRYPTION_KEY 필요) — 메일은 보낼 수 없고 DM 만 됩니다.</span>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if msg %}<p class="otr-msg" role="status">{{ msg }}</p>{% endif %}
|
||||||
|
|
||||||
|
<div class="erp-card otr-tpl">
|
||||||
|
<div class="otr-tpl-head"><b>보낼 내용</b><span class="erp-muted">(설정에서 바꿉니다)</span></div>
|
||||||
|
<div class="otr-tpl-subject">{% if template.ad_label %}(광고) {% endif %}{{ template.subject }}</div>
|
||||||
|
<div class="otr-tpl-body">{{ body_text[:160] }}{% if body_text | length > 160 %}…{% endif %}</div>
|
||||||
|
<div class="erp-muted otr-tpl-meta">보내는 이름 {{ template.sender_name or '—' }} · 본문 아래 사진 {{ images | length }}장 · <code>{이름}</code> = 줄마다 그 사람 이름</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#- 리스트 추가 — 붙여 넣기 → [미리보기](메일/DM/오류 판별) → [리스트에 추가] -#}
|
||||||
|
<div class="erp-card otr-add" id="otr-add" hidden>
|
||||||
|
<div class="otr-add-head"><b>리스트 추가</b>
|
||||||
|
<span class="erp-muted">한 줄에 한 사람 — <code>주소, 이름</code> (쉼표·탭·띄어쓰기). 주소 = 이메일(<code>name@domain.com</code>) 또는
|
||||||
|
인스타(<code>@계정</code> · <code>instagram.com/계정</code> · 계정명). 엑셀에서 두 칸을 복사해 붙여도 됩니다.</span></div>
|
||||||
|
<textarea class="erp-input otr-add-text" id="otr-add-text" rows="6" placeholder="kim@miras.co.kr, 김철수 @mira.kitchen 미라네 https://www.instagram.com/lee_s/ 이수진"></textarea>
|
||||||
|
<div class="otr-add-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="otr-add-preview">미리보기</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="otr-add-save" disabled>리스트에 추가</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="otr-add-close">닫기</button>
|
||||||
|
<span class="erp-muted" id="otr-add-sum"></span>
|
||||||
|
</div>
|
||||||
|
<div class="erp-table-wrap otr-add-preview" id="otr-add-result" hidden></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card otr-list">
|
||||||
|
<div class="otr-filter" role="tablist" aria-label="보기">
|
||||||
|
{% for key, label in (('all', '전체'), ('email', '메일'), ('instagram', 'DM'), ('대기', '대기'), ('보냄', '보냄'), ('실패', '실패')) %}
|
||||||
|
<button type="button" class="otr-seg{% if key == 'all' %} is-active{% endif %}" data-filter="{{ key }}">{{ label }} <span class="otr-cnt" data-cnt="{{ key }}"></span></button>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table otr-table">
|
||||||
|
<thead><tr><th class="otr-c-check"><input type="checkbox" id="otr-check-all" aria-label="전체 고르기" /></th>
|
||||||
|
<th>구분</th><th>이름</th><th>주소</th><th>상태</th><th>보낸 때</th><th class="otr-c-acts"></th></tr></thead>
|
||||||
|
<tbody id="otr-tbody"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="erp-muted otr-empty" id="otr-empty" hidden>리스트가 비었습니다 — [+ 리스트 추가]로 넣으세요.</p>
|
||||||
|
<div class="otr-send-bar">
|
||||||
|
<span id="otr-selected">고른 줄 0</span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="otr-send"{% if not gmail.connected %} disabled title="Gmail 연결 뒤 보낼 수 있습니다"{% endif %}>고른 메일 보내기</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="otr-reset">고른 줄 다시 대기로</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline otr-danger" id="otr-delete">고른 줄 지우기</button>
|
||||||
|
<span class="erp-muted otr-send-note">메일 = 한 사람에 한 통(본인 Gmail, 1초 간격). DM = 줄의 [DM 보내기] → 문구가 복사되고 인스타 DM 창이 열리면 붙여 넣어 보낸 뒤 [보냄].</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if logs %}
|
||||||
|
<div class="erp-card otr-logs">
|
||||||
|
<div class="otr-tpl-head"><b>최근 보낸 기록</b><span class="erp-muted">({{ logs | length }})</span></div>
|
||||||
|
<ul>
|
||||||
|
{% for l in logs %}
|
||||||
|
<li class="{{ 'is-ok' if l.ok else 'is-fail' }}"><span class="otr-when">{{ l.sent_at[5:16] | replace('T', ' ') }}</span>
|
||||||
|
<b>{{ '메일' if l.kind == 'email' else 'DM' }}</b> {{ l.name or '(이름 없음)' }} · {{ l.address }}
|
||||||
|
<span class="erp-muted">— {{ l.sent_by }}{% if not l.ok %} · <span class="otr-err">{{ l.error }}</span>{% endif %}</span></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{#- 미리보기 창 -#}
|
||||||
|
<div class="otr-modal" id="otr-preview" hidden>
|
||||||
|
<div class="otr-modal-card" role="dialog" aria-modal="true" aria-label="미리보기">
|
||||||
|
<div class="otr-modal-head"><b id="otr-pv-title">미리보기</b><button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-close>닫기</button></div>
|
||||||
|
<div class="otr-pv-subject" id="otr-pv-subject"></div>
|
||||||
|
<iframe class="otr-pv-frame" id="otr-pv-frame" title="본문 미리보기" sandbox></iframe>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script type="application/json" id="otr-data">{{ {"rows": rows} | tojson }}</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}<script src="/static/outreach.js?v=20261030c" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{#- 안내문 발송 설정(2026-10-27) — 화면 세로 2단: 왼쪽 = 메일(제목·(광고)·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
|
||||||
|
오른쪽 = 인스타 DM(서식 없는 편집기, 비우면 메일 본문 글 + 끝 문구). 두 편집기 모두 {이름} = 빨강 굵게(화면에서만).
|
||||||
|
편집기 = Quill(/static/vendor/quill). 입력 칸은 form="otr-set-form" 으로 위 막대의 저장 폼에 묶는다(사진 폼과 겹치지 않게). -#}
|
||||||
|
{% block head_extra %}
|
||||||
|
<link rel="stylesheet" href="/static/vendor/quill/quill.snow.css" />
|
||||||
|
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="otr otr-settings">
|
||||||
|
<form method="post" action="/outreach/settings" id="otr-set-form" class="otr-set-bar">
|
||||||
|
<a class="erp-btn erp-btn-outline" href="/outreach/">◀ 리스트</a>
|
||||||
|
<span class="erp-muted otr-set-saved">{% if template.is_default %}기본 문구(아직 저장 안 함){% else %}마지막 저장 {{ template.updated_by }} · {{ template.updated_at[:16] | replace('T', ' ') }}{% endif %}</span>
|
||||||
|
<span class="otr-set-bar-gap"></span>
|
||||||
|
<input type="hidden" name="fmt" value="html" />
|
||||||
|
<input type="hidden" name="body" id="otr-body-input" />
|
||||||
|
<input type="hidden" name="dm_body" id="otr-dm-input" />
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="otr-default" title="칸만 바꿉니다 — [저장]을 눌러야 적용">기본 문구로 되돌리기</button>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
|
||||||
|
</form>
|
||||||
|
{% if msg %}<p class="otr-msg" role="status">{{ msg }}</p>{% endif %}
|
||||||
|
|
||||||
|
<div class="otr-split">
|
||||||
|
{#- 왼쪽 — 메일 -#}
|
||||||
|
<div class="otr-col">
|
||||||
|
<div class="erp-card otr-set-card">
|
||||||
|
<div class="otr-col-head"><span class="otr-kind is-email">메일</span><b>이메일 안내문</b>
|
||||||
|
<span class="erp-muted">[고른 메일 보내기]로 내 Gmail 에서 한 사람에 한 통씩</span></div>
|
||||||
|
<label class="erp-field otr-field"><span>메일 제목</span>
|
||||||
|
<input class="erp-input" type="text" name="subject" form="otr-set-form" maxlength="200" required value="{{ template.subject }}" /></label>
|
||||||
|
<label class="otr-check"><input type="checkbox" name="ad_label" form="otr-set-form" value="1"{% if template.ad_label %} checked{% endif %} />
|
||||||
|
<span>제목 앞에 <b>(광고)</b> 붙이기 <span class="erp-muted">— 영리 목적 광고성 메일은 정보통신망법 제50조에 따라 제목 앞 "(광고)"·수신 거부 방법을 적어야 합니다(법무 확인 권장)</span></span></label>
|
||||||
|
<label class="erp-field otr-field"><span>보내는 이름</span>
|
||||||
|
<input class="erp-input" type="text" name="sender_name" form="otr-set-form" maxlength="60" value="{{ template.sender_name }}" placeholder="받는 사람 메일함에 보이는 이름" /></label>
|
||||||
|
<div class="erp-field otr-field"><span>본문 <small class="erp-muted"><code class="otr-tag">{이름}</code> = 그 사람 이름(빨강은 이 화면에서만 — 메일에는 이름이 본문 서식대로) · 되돌리기 Ctrl+Z</small></span>
|
||||||
|
<div class="otr-editor" id="otr-body-editor"></div></div>
|
||||||
|
<label class="erp-field otr-field"><span>끝 문구 <small class="erp-muted">(본문 맨 아래 — 수신 거부 안내 등, 비워도 됨)</small></span>
|
||||||
|
<textarea class="erp-input" name="footer" form="otr-set-form" rows="2" maxlength="2000" placeholder="예: 더 이상 받기를 원하지 않으시면 이 메일에 '수신 거부'라고 회신해 주세요.">{{ template.footer }}</textarea></label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card otr-set-card" id="images">
|
||||||
|
<div class="otr-tpl-head"><b>본문 아래 사진</b><span class="erp-muted">메일 본문 맨 아래에 순서대로(최대 {{ max_images }}장, 가로 700px 로 줄여 저장). DM 에는 붙지 않습니다.</span></div>
|
||||||
|
<div class="otr-images">
|
||||||
|
{% for im in images %}
|
||||||
|
<figure class="otr-image">
|
||||||
|
<img src="/outreach/images/{{ im.id }}" alt="{{ im.filename }}" loading="lazy" />
|
||||||
|
<figcaption>{{ loop.index }}. {{ im.filename }}</figcaption>
|
||||||
|
<div class="otr-image-acts">
|
||||||
|
{% if not loop.first %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="-1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="앞으로">◀</button></form>{% endif %}
|
||||||
|
{% if not loop.last %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="뒤로">▶</button></form>{% endif %}
|
||||||
|
<form method="post" action="/outreach/settings/images/{{ im.id }}/delete" onsubmit="return confirm('이 사진을 뺄까요?');"><button class="erp-btn erp-btn-outline erp-btn-sm otr-danger">빼기</button></form>
|
||||||
|
</div>
|
||||||
|
</figure>
|
||||||
|
{% else %}
|
||||||
|
<p class="erp-muted">사진이 없습니다.</p>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% if images | length < max_images %}
|
||||||
|
<form method="post" action="/outreach/settings/images" enctype="multipart/form-data" class="otr-upload">
|
||||||
|
<input type="file" name="files" accept="image/jpeg,image/png,image/webp,image/gif" multiple required />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">사진 넣기</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#- 오른쪽 — 인스타 DM -#}
|
||||||
|
<div class="otr-col">
|
||||||
|
<div class="erp-card otr-set-card otr-dm-card">
|
||||||
|
<div class="otr-col-head"><span class="otr-kind is-instagram">DM</span><b>인스타 DM 문구</b>
|
||||||
|
<span class="erp-muted">[DM 보내기]를 누르면 복사되는 글</span></div>
|
||||||
|
<p class="erp-muted otr-note">인스타 DM 은 글자 서식·사진이 없어 글만 씁니다. <code class="otr-tag">{이름}</code> = 그 사람 이름.
|
||||||
|
비워 두면 메일 본문 글 + 끝 문구가 그대로 복사됩니다.</p>
|
||||||
|
<div class="otr-editor otr-editor-plain" id="otr-dm-editor"
|
||||||
|
data-placeholder="예: 안녕하세요, {이름}님! 누적 800만 개 판매 미라클통 '미라네주방'입니다. {이름}님과 공동구매를 함께하고 싶어 연락드렸어요. 자세한 제안서는 메일로 보내드릴 수 있습니다 — 편하신 메일 주소 알려주시면 감사하겠습니다 :)"></div>
|
||||||
|
<div class="otr-dm-foot">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="otr-dm-from-mail">메일 본문 글 가져오기</button>
|
||||||
|
<small class="erp-muted otr-count" id="otr-dm-count" data-max="{{ dm_max }}"></small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<script type="application/json" id="otr-default-data">{{ default | tojson }}</script>
|
||||||
|
<script type="application/json" id="otr-current-data">{{ {"body": template.body, "dm_body": template.dm_body} | tojson }}</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}
|
||||||
|
<script src="/static/vendor/quill/quill.js"></script>
|
||||||
|
<script src="/static/outreach.js?v=20261030c" defer></script>
|
||||||
|
{% endblock %}
|
||||||
@@ -31,7 +31,11 @@
|
|||||||
- 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로).
|
- 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로).
|
||||||
- **업데이트 중에도 [매출 업데이트] 누르기 가능**(2026-10-19) — 버튼이 "업데이트 중 · 진행 보기"로 바뀌고, 누르면 `GET /api/sync/current` 의 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로 다시 연다.
|
- **업데이트 중에도 [매출 업데이트] 누르기 가능**(2026-10-19) — 버튼이 "업데이트 중 · 진행 보기"로 바뀌고, 누르면 `GET /api/sync/current` 의 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로 다시 연다.
|
||||||
- 서버 시작 때 남은 `perf_sync_runs` running 행은 `abandon_running_runs` 로 "중단됨(서버 재시작)" 정리(앱은 프로세스 하나 — 진행 작업은 메모리에만). 예전엔 30분(`STALE_RUN_AFTER`) 동안 버튼이 '업데이트 중'으로 막히고 그 쇼핑몰이 '이미 진행 중'으로 건너뛰어졌다.
|
- 서버 시작 때 남은 `perf_sync_runs` running 행은 `abandon_running_runs` 로 "중단됨(서버 재시작)" 정리(앱은 프로세스 하나 — 진행 작업은 메모리에만). 예전엔 30분(`STALE_RUN_AFTER`) 동안 버튼이 '업데이트 중'으로 막히고 그 쇼핑몰이 '이미 진행 중'으로 건너뛰어졌다.
|
||||||
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`.
|
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`(끄기)·`_DAYS`·`_HOURS`(일정 저장 전 기본 시간대).
|
||||||
|
- **일정 = 실적 설정 "자동 업데이트" 카드**(2026-10-26, 관리자, 마이그레이션 011 `perf_settings` key `auto_sync`) — 매출 실적·광고비 **따로**:
|
||||||
|
사용·요일(0=월…6=일, [매일]·[평일])·시작/끝 시각(5분 단위)·간격(5~720분, 5분 단위, 기본 30). 회차 = 고른 요일의 시작, 시작+간격, … 끝까지(끝과 맞으면 끝도).
|
||||||
|
`PUT /api/auto-sync-schedule {sales, ads}`(`auto_sync.validate_schedule`, 011 미적용 503). 스레드(`auto_sync.Scheduler`)가 1분마다 일정을 다시 읽어
|
||||||
|
바뀐 종류만 지금부터 다시 계산, 종류마다 따로 스레드(`run_once(kinds=(kind,))`). 저장 값 없음·011 미적용 = 기본(매일 9~19시 30분마다).
|
||||||
- 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로).
|
- 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로).
|
||||||
|
|
||||||
## 수동 입력
|
## 수동 입력
|
||||||
@@ -53,6 +57,8 @@
|
|||||||
묶어 상자 안에서 스크롤했는데, 진짜 셸에서는 상자 아래가 화면 밖에 잘리고(`overscroll-behavior: contain`) 휠이 페이지로 안 넘어갔다.
|
묶어 상자 안에서 스크롤했는데, 진짜 셸에서는 상자 아래가 화면 밖에 잘리고(`overscroll-behavior: contain`) 휠이 페이지로 안 넘어갔다.
|
||||||
스크롤 막대 배경(트랙) 투명 = `scrollbar-color: #c3c6cb transparent`(표 상자·실적 화면 `.erp-page`). 테스트 `tests/js/perf_sticky.browser.test.js`
|
스크롤 막대 배경(트랙) 투명 = `scrollbar-color: #c3c6cb transparent`(표 상자·실적 화면 `.erp-page`). 테스트 `tests/js/perf_sticky.browser.test.js`
|
||||||
(진짜 `erp_base.html` 셸 렌더 `perf_*_shell.html` 로 휠 스크롤 — 스텁 셸로는 이 문제가 안 보였다).
|
(진짜 `erp_base.html` 셸 렌더 `perf_*_shell.html` 로 휠 스크롤 — 스텁 셸로는 이 문제가 안 보였다).
|
||||||
|
- **새로고침해도 스크롤 유지**(2026-11-02) — 수기 입력을 마치면 합계를 다시 계산하려고 새로고침하는데, 세로 스크롤은 `.erp-page` 상자라 브라우저가 복원하지 않아 맨 위로 돌아갔다.
|
||||||
|
`performance.js keepScroll` 이 떠날 때 세로·가로 위치를 sessionStorage `perf_scroll` 에 저장 → **새로고침일 때만** 복원(같은 주소, 메뉴·기간 이동은 맨 위부터). 자동 새로 고침·업로드 뒤 새로고침도 같음.
|
||||||
- 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003).
|
- 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003).
|
||||||
- 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
|
- 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
|
||||||
- **직접 추가 쇼핑몰·그룹·순서 드래그**(2026-10-22, 마이그레이션 009 `is_custom`·`is_group`·`parent_code`) — 설정 [+ 쇼핑몰 추가(수동 입력)]
|
- **직접 추가 쇼핑몰·그룹·순서 드래그**(2026-10-22, 마이그레이션 009 `is_custom`·`is_group`·`parent_code`) — 설정 [+ 쇼핑몰 추가(수동 입력)]
|
||||||
@@ -60,6 +66,12 @@
|
|||||||
직접 추가 쇼핑몰만 그룹 select 로 묶음, 이름 변경·삭제(삭제 = 그 쇼핑몰 수동 입력·수수료도). 매출 실적 표 그룹 열 = 보이는 하위 합계(일 합계엔 안 더함),
|
직접 추가 쇼핑몰만 그룹 select 로 묶음, 이름 변경·삭제(삭제 = 그 쇼핑몰 수동 입력·수수료도). 매출 실적 표 그룹 열 = 보이는 하위 합계(일 합계엔 안 더함),
|
||||||
▾/▸ 하위 열 접기(localStorage). ⠿ 드래그 → `PUT /api/marketplace-order` → `sort_order`, 화면 순서는 `dashboard.ordered_marketplaces`
|
▾/▸ 하위 열 접기(localStorage). ⠿ 드래그 → `PUT /api/marketplace-order` → `sort_order`, 화면 순서는 `dashboard.ordered_marketplaces`
|
||||||
(그룹 바로 뒤 하위) 한 곳. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
|
(그룹 바로 뒤 하위) 한 곳. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
|
||||||
|
- **카페24(전체)·카페24(실적) 열**(2026-11-02, 예전 "공구 제외") — 카페24 열 이름 = 카페24(전체)(`_short_name`), 바로 오른쪽 카페24(실적) = 카페24 − 직접 추가 쇼핑몰 "자사몰(공동구매)"("카페24 공동구매"도, 이름으로 찾음·띄어쓰기 무시 — 없으면 전체 그대로, 쇼핑몰 필터·숨김과 무관하게 뺌).
|
||||||
|
광고비 줄은 카페24(전체)와 같은 구글·메타(`dashboard._cafe24_real_column`, kind `diff`, 표 열만 — 일 합계엔 안 더함, 클릭·메모 없음). 공동구매 칸을 저장하면 그 줄 칸이 바로 바뀜(`performance.js saveManual`, td `data-diff-minus`·`data-base`), 합계 줄은 입력 마친 뒤 새로고침 때. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
|
||||||
|
- **합계 기준**(2026-11-02) — 일 합계 = 카페24(실적) + 공동구매 + 나머지 쇼핑몰(카페24(전체)는 안 더함 — 공동구매가 들어 있어 중복). 일 합계·ROAS·KPI·추이·비중·월/연 누적 모두 `dashboard._summary_cells`(카페24 칸 = 실적, 그래프·누적의 카페24 줄 이름도 `summary_names` = 카페24(실적)), 표의 카페24(전체) 열만 원래 값. 광고비 탭 매출 대비 광고비·합계 ROAS = `total_sales_codes`(카페24 있으면 공동구매 코드 뺌, 같은 금액). **프로젝트 회의록 머리 카드는 아직 예전 합계**(`project/router.py` `total` — 공동구매 중복).
|
||||||
|
- **매출 실적 표 열 숨기기**(2026-11-02) — 실적 설정 "공통 보기 설정" 카드(관리자만, `PUT /api/hidden-marketplaces`, `perf_settings` key `hidden_marketplaces`, 011 미적용 503) → **모든 사용자에게 적용**. **열만** 숨김(`dashboard.load_hidden`) — 일 합계·KPI·그래프·누적은 그대로, 그룹 열 = 보이는 하위 합계(다 숨기면 그룹 열도 없음). 쇼핑몰 필터(합계까지 바뀜)와 다름. 광고비 탭은 적용 안 함.
|
||||||
|
- **일 합계 열 위치**(2026-11-02) — 매출 실적·광고비 표 모두 날짜 바로 오른쪽, 날짜 열과 함께 가로 고정(왼쪽 위치 `--perf-label-w` = 날짜 열 너비, `performance.js stickyHead`).
|
||||||
|
- **기간 이동**(2026-11-02, `_period_nav.html` 공통) — 날짜 바로 좌우 화살표 SVG(글자 높이, 진한 회색), 글자 버튼 없음.
|
||||||
- **매출 실적 표 모양(2026-10-22)** — `table.perf-autofit`(매출 탭만, 모든 기간 같음): 표가 100% 로 늘지 않고 **열 너비 = 내용 길이**, 날짜 열은 고정 210px 대신 자동 +
|
- **매출 실적 표 모양(2026-10-22)** — `table.perf-autofit`(매출 탭만, 모든 기간 같음): 표가 100% 로 늘지 않고 **열 너비 = 내용 길이**, 날짜 열은 고정 210px 대신 자동 +
|
||||||
**가로 스크롤해도 고정**(sticky left, 오른쪽 그림자). 그룹 열 = 진한 보라 머리·왼쪽 묶음 선, 하위 열 = 옅은 보라 머리(위 띠)·옅은 칸, 마지막 하위(`is-glast`, 접히면 그룹 열 `is-gclosed`) = 오른쪽 선.
|
**가로 스크롤해도 고정**(sticky left, 오른쪽 그림자). 그룹 열 = 진한 보라 머리·왼쪽 묶음 선, 하위 열 = 옅은 보라 머리(위 띠)·옅은 칸, 마지막 하위(`is-glast`, 접히면 그룹 열 `is-gclosed`) = 오른쪽 선.
|
||||||
접기 단추 = 22px ⊟/⊞(SVG, 세로 막대가 돌아 바뀜). 접기·펴기 애니메이션 = 하위 칸 내용 `.perf-gc` 너비·칸 여백·투명도 260ms(`setGroup(code, fold, animate)`,
|
접기 단추 = 22px ⊟/⊞(SVG, 세로 막대가 돌아 바뀜). 접기·펴기 애니메이션 = 하위 칸 내용 `.perf-gc` 너비·칸 여백·투명도 260ms(`setGroup(code, fold, animate)`,
|
||||||
@@ -67,12 +79,25 @@
|
|||||||
|
|
||||||
## 매출 실적 화면 (2026-10-19)
|
## 매출 실적 화면 (2026-10-19)
|
||||||
|
|
||||||
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
|
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 % + **전년 같은 기간 대비 %**(2026-11-16, `calc.Period.yoy_range` — 1년 전 같은 날짜, 진행 중이면 오늘까지, 연 보기는 직전 비교가 이미 전년이라 없음), 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
|
||||||
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
|
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
|
||||||
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx` → `performance.js initNextUpdate`, 자동 업데이트 규칙 `auto_sync.next_slot` 과 같게 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트 꺼지면 숨김).
|
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
|
||||||
|
- **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload.
|
||||||
|
화면 데이터 `update_watch`(`router._update_watch` = 그린 때 마지막으로 끝난 작업 id, 보는 사람 것 제외) ↔ `GET /api/update-status?kind=sales|ads`
|
||||||
|
(`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림
|
||||||
|
(마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `performance.js initUpdateWatch`.
|
||||||
|
|
||||||
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
|
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타·카톡 플친 줄(이름 붙임, 카페24(전체)·카페24(실적) 같은 줄), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
|
||||||
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
|
- **열 접기**(2026-11-06) — 매출 실적·광고비 일자별 표 머리글 위 작은 화살표 버튼(`.perf-cfold`, `performance.js initColFold`)으로 열 하나씩 접기/펴기(날짜 열 빼고, 일 합계·그룹 열 포함).
|
||||||
|
접은 열 = 26px 띠(`is-cfold`, 칸 내용 숨김·클릭/메모 안 됨, 너비는 JS `CFOLD_W` 와 CSS 같게, 수동 열 너비 표도 같음). **로그인한 사람 본인에게만** —
|
||||||
|
`PUT /api/my-col-fold {kind: sales|ads, cols}` → `perf_settings` key `col_fold:<이메일 sha1>`(key 64자 제한) = `{sales, ads}`, 화면은 표 `data-col-fold`(라우터 `_load_col_fold`). 011 미적용이면 다 펼침·저장 503.
|
||||||
|
버튼 위 말풍선 = 커서 바로 위를 따라다니는 `.perf-cfold-tip`(열 이름, 12px 굵게 = 제목 글자), 버튼 `title=""` 로 머리글 기본 말풍선 막음.
|
||||||
|
그룹 하위 열 접기(⊟, localStorage)와는 별개. 테스트 `tests/js/perf_colfold.browser.test.js`, `test_custom_groups.py::test_api_my_col_fold_per_user`.
|
||||||
|
- **표 열 너비 자동/수동**(2026-10-27) — 설정 "보기 설정" **표 열 너비** [자동(글자 길이)]·[수동 조절](누구나, 이 브라우저 쿠키 `perf_colw`, `router._colw_ctx` → 템플릿 `colw`).
|
||||||
|
수동 = 매출 실적·광고비 일자별 표에 `perf-colw-manual` → `performance.js initColWidths` 가 자동 너비를 잰 뒤 `table-layout:fixed`(`is-colw-fixed`, 넘치는 글자 …),
|
||||||
|
머리글 오른쪽 경계 `.perf-colw-grip` 드래그(최소 36px)·두 번 누르면 그 열만 자동. **날짜 열(`label`)은 조절 불가 — 늘 자동 너비, 손잡이 없음, 저장값 무시**. 너비 = localStorage `perf_colw_sales`/`perf_colw_ads`(th `data-col` = 쇼핑몰·채널 코드·`label`·`total`)에 계속 유지,
|
||||||
|
설정 [조절한 너비 초기화]가 둘 다 지움. 그룹 접기·펴기 때 열 너비도 함께 움직임(`colw.animate/settle`). 테스트 `tests/js/perf_colw.browser.test.js`.
|
||||||
|
- **매출 단위** 원·천원·백만원(2026-11-02 모든 사용자 공통) — 설정 "공통 보기 설정"(관리자, `PUT /api/display-unit`, `perf_settings` key `display_unit`, 저장 값 없음·011 미적용 = 원, 예전 쿠키 `perf_unit` 은 안 봄), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. 표 열 너비는 사람(브라우저)마다 그대로.
|
||||||
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
|
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
|
||||||
|
|
||||||
## 날짜 칸 메모 (2026-10-22, 마이그레이션 010 `perf_cell_memos`)
|
## 날짜 칸 메모 (2026-10-22, 마이그레이션 010 `perf_cell_memos`)
|
||||||
@@ -86,11 +111,20 @@
|
|||||||
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
|
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
|
||||||
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
|
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
|
||||||
|
|
||||||
|
## 틱톡 (`/performance/tiktok`, 2026-11-05, 마이그레이션 없음)
|
||||||
|
|
||||||
|
- 광고비 탭 틀(기간 이동·KPI·표·그래프·연 누적), 표 열 = ROAS·광고비·매출. 값은 광고 API 만(읽기 전용, 칸 입력·메모 없음). 화면 데이터 `ad_spend.build_tiktok_dashboard`.
|
||||||
|
- **틱톡 탭에서만 보임** — 채널 코드 `tiktok` 은 `ad_sources` 에는 있지만 `ad_spend.CHANNELS` 에는 넣지 않는다(넣으면 광고비 탭 합계에 들어감). 쇼핑몰 표(`perf_marketplaces`)에도 없어 매출 실적 합계·열과 무관. 저장은 다른 광고 API 처럼 `perf_ad_spend`(`source='api'`), 매출 = `metrics["매출"]`.
|
||||||
|
- 설정 = 실적 설정 **광고 API 연동** 카드 → 틱톡 — 광고 계정 ID·장기 액세스 토큰·틱톡샵 ID(선택). [광고비 업데이트]·광고비 자동 업데이트에 함께 돈다.
|
||||||
|
- `ad_sources/tiktok_ads.py` — `report/integrated/get`(30일씩), 매출 = 웹 구매금액 + 틱톡샵 매출, 틱톡샵 ID 가 있으면 `gmv_max/report/get` 비용·매출도 더함(항목별 값은 metrics 에 따로 저장). 외화 계정은 그날 환율로 원화(`fx`). ROAS = 매출 ÷ 광고비.
|
||||||
|
**실제 토큰 대조 전**(2026-11-05) — 공식 문서를 읽지 못해 지표 이름은 이차 자료로 확인. 일반 보고서에 GMV Max 가 이미 들어 있으면 틱톡샵 ID 를 넣었을 때 중복되므로, 처음 쓸 때 광고 관리자 화면과 대조할 것.
|
||||||
|
|
||||||
## 광고비 (`/performance/ads`)
|
## 광고비 (`/performance/ads`)
|
||||||
|
|
||||||
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
|
- 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니.
|
||||||
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
|
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
|
||||||
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
|
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
|
||||||
|
- **카톡 플친** 열(`kakao_pf`, 메타 오른쪽, 2026-11-16) — 직접 입력, `NO_SALES` 라 ROAS 없음. 매출 탭 카페24 칸 아래 구글·메타 다음 줄, 일 합계 광고비에도 더함.
|
||||||
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
|
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
|
||||||
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
|
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
|
||||||
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
|
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
|
||||||
@@ -98,13 +132,13 @@
|
|||||||
- 네이버: 3열 기간·4열 총비용·12열 ROAS(구매완료 광고수익률(%)), 머리글 클릭 = 일자별 보고서 항목.
|
- 네이버: 3열 기간·4열 총비용·12열 ROAS(구매완료 광고수익률(%)), 머리글 클릭 = 일자별 보고서 항목.
|
||||||
총비용·광고수익률은 **머리글 이름으로 찾음**(열 구성 바뀐 보고서 — 고정 12열이 비어 ROAS 누락됐던 문제, 2026-10-20). 광고수익률 칸이 없거나 비면 구매완료 전환매출액 ÷ 총비용. 저장된 `roas` 가 빈 예전 행은 `db.ad_roas` 가 metrics 에서 다시 구함(`ad_spend.roas_from_metrics`).
|
총비용·광고수익률은 **머리글 이름으로 찾음**(열 구성 바뀐 보고서 — 고정 12열이 비어 ROAS 누락됐던 문제, 2026-10-20). 광고수익률 칸이 없거나 비면 구매완료 전환매출액 ÷ 총비용. 저장된 `roas` 가 빈 예전 행은 `db.ad_roas` 가 metrics 에서 다시 구함(`ad_spend.roas_from_metrics`).
|
||||||
- 일자별 보고서 창: ROAS 열은 **광고비 열 바로 오른쪽**, 네이버 "구매완료 광고수익률(%)" 머리글은 "ROAS(%)"로 표기(`ad_spend._roas_next_to_spend` → `labels`, 저장 키는 파일 머리글 그대로 — 예전 업로드도 그대로 적용).
|
- 일자별 보고서 창: ROAS 열은 **광고비 열 바로 오른쪽**, 네이버 "구매완료 광고수익률(%)" 머리글은 "ROAS(%)"로 표기(`ad_spend._roas_next_to_spend` → `labels`, 저장 키는 파일 머리글 그대로 — 예전 업로드도 그대로 적용).
|
||||||
- 매출 대비 광고비 KPI.
|
- KPI 는 **한 줄**(2026-10-30, 매출 실적처럼 `.perf-kpi-line` — 항목 `.perf-kpi-item` 을 세로 선으로 나눔, 좁은 화면은 한 항목씩): 광고비(전 기간 대비) · 매출 대비 광고비 · 연 누적 광고비. 월 누적 광고비 카드는 뺐다.
|
||||||
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 매출 자동 업데이트 회차에 함께.
|
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 광고비 자동 업데이트 일정(실적 설정 "자동 업데이트")대로.
|
||||||
- **[광고비 업데이트]**(2026-10-20, 예전 채널별 [구글/메타 광고 불러오기] 버튼 삭제) — 광고비 탭 오른쪽 위, 매출 탭과 같은 모양:
|
- **[광고비 업데이트]**(2026-10-20, 예전 채널별 [구글/메타 광고 불러오기] 버튼 삭제) — 광고비 탭 오른쪽 위, 매출 탭과 같은 모양:
|
||||||
마지막 업데이트(광고 API 마지막 성공 가져오기 `ad_sync.last_ad_update_at`) · 다음 업데이트까지(매출과 같은 회차 카운트다운) · 버튼.
|
마지막 업데이트(광고 API 마지막 성공 가져오기 `ad_sync.last_ad_update_at`) · 다음 업데이트까지(광고비 일정 카운트다운) · 버튼.
|
||||||
설정된 광고 API 전부를 진행 창 작업으로(`POST /api/ad-sync` → `jobs` kind="ads", 채널별 막대 수집 50% → 저장 → 완료, 채널별 [중지]·[업데이트 취소]는
|
설정된 광고 API 전부를 진행 창 작업으로(`POST /api/ad-sync` → `jobs` kind="ads", 채널별 막대 수집 50% → 저장 → 완료, 채널별 [중지]·[업데이트 취소]는
|
||||||
저장 직전까지, 진행·취소·중지 API 는 매출과 같은 `/api/sync/jobs/…`). 진행 중이면 새로 시작 안 하고 합류(`GET /api/ad-sync/current`, 매출 업데이트와 별개).
|
저장 직전까지, 진행·취소·중지 API 는 매출과 같은 `/api/sync/jobs/…`). 진행 중이면 새로 시작 안 하고 합류(`GET /api/ad-sync/current`, 매출 업데이트와 별개).
|
||||||
자동 업데이트 회차(`auto_sync.run_once`)는 매출과 광고비를 **동시에** 각각 진행 창 작업으로, 이미 돌고 있는 종류만 그 회차 건너뜀. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
|
자동 업데이트(`auto_sync.run_once`)는 매출·광고비를 각자 일정대로 각각 진행 창 작업으로(같은 시각이면 동시에), 이미 돌고 있는 종류는 그 회차 건너뜀. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
|
||||||
- **구글 = Google Ads API**(2026-10-15) — 고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26). 개발자 토큰은 2026-09-09 구글 폐지 — 접근 등급은 서비스 계정의 Cloud 프로젝트, 머리글 안 보냄. [광고비 업데이트]·자동 업데이트. 광고비 = 비용 × 1.1(부가세 포함)·ROAS(전환 가치 ÷ 비용, 구글 값 그대로)·항목.
|
- **구글 = Google Ads API**(2026-10-15) — 고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26). 개발자 토큰은 2026-09-09 구글 폐지 — 접근 등급은 서비스 계정의 Cloud 프로젝트, 머리글 안 보냄. [광고비 업데이트]·자동 업데이트. 광고비 = 비용 × 1.1(부가세 포함)·ROAS(전환 가치 ÷ 비용, 구글 값 그대로)·항목.
|
||||||
- **메타 = 메타 마케팅 API**(2026-10-16, `ad_sources/meta_ads.py`, 새 마이그레이션 없음) — 광고 계정 ID(여러 개, 날짜별 합산)·액세스 토큰(ads_read, 시스템 사용자 토큰 권장)·앱 시크릿(선택)·API 버전(기본 v26.0). 광고비 = 지출 금액 그대로(메타는 이미 부가세 포함 — × 1.1 은 구글만)·ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS). USD 등 외화 계정은 그날 환율로 원화 환산(`fx.py`, Frankfurter 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [광고비 업데이트]·자동 업데이트 회차.
|
- **메타 = 메타 마케팅 API**(2026-10-16, `ad_sources/meta_ads.py`, 새 마이그레이션 없음) — 광고 계정 ID(여러 개, 날짜별 합산)·액세스 토큰(ads_read, 시스템 사용자 토큰 권장)·앱 시크릿(선택)·API 버전(기본 v26.0). 광고비 = 지출 금액 그대로(메타는 이미 부가세 포함 — × 1.1 은 구글만)·ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS). USD 등 외화 계정은 그날 환율로 원화 환산(`fx.py`, Frankfurter 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [광고비 업데이트]·자동 업데이트 회차.
|
||||||
**기간으로 물으면 메타가 지출·노출·클릭을 0 으로 주는 문제**(2026-10-21 운영 확인, v26.0 — 링크 클릭·구매는 정상, 하루만 물으면 정상) →
|
**기간으로 물으면 메타가 지출·노출·클릭을 0 으로 주는 문제**(2026-10-21 운영 확인, v26.0 — 링크 클릭·구매는 정상, 하루만 물으면 정상) →
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
|
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다 —
|
||||||
|
틱톡만 예외: 광고비 탭에 안 나오게 CHANNELS 에 넣지 않고 틱톡 탭이 따로 읽는다)."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from .base import AdSource
|
from .base import AdSource
|
||||||
from .google_ads import GoogleAdsSource
|
from .google_ads import GoogleAdsSource
|
||||||
from .meta_ads import MetaAdsSource
|
from .meta_ads import MetaAdsSource
|
||||||
|
from .tiktok_ads import TiktokAdsSource
|
||||||
|
|
||||||
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
|
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource(), TiktokAdsSource())
|
||||||
_BY_CODE = {s.code: s for s in _SOURCES}
|
_BY_CODE = {s.code: s for s in _SOURCES}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,202 @@
|
|||||||
|
"""틱톡 광고(TikTok API for Business v1.3) — 날짜별 광고비·매출·ROAS. 화면은 틱톡 탭(광고비 탭·매출 실적에는 안 나옴).
|
||||||
|
|
||||||
|
인증(2026-11-05): 광고 계정(advertiser) ID 하나 + 장기 액세스 토큰(머리글 Access-Token). 토큰 앱에 보고서·광고 계정 읽기 권한이 있어야 한다.
|
||||||
|
|
||||||
|
조회
|
||||||
|
GET /report/integrated/get/ — report_type=BASIC · data_level=AUCTION_ADVERTISER · 차원 advertiser_id·stat_time_day.
|
||||||
|
매출 = 웹 구매금액(total_complete_payment_rate — 이름과 달리 금액) + 틱톡샵 매출(total_onsite_shopping_value).
|
||||||
|
GET /gmv_max/report/get/ — 틱톡샵 ID 를 넣었을 때만. 비용(cost)·매출(gross_revenue)을 더한다.
|
||||||
|
- 하루 단위 조회는 기간 제한이 있어 30일씩 나눠 묻는다.
|
||||||
|
- 금액은 광고 계정 통화 → 그날 환율로 원화(fx.krw_rates, 메타와 같음).
|
||||||
|
- ROAS(%) = 매출 ÷ 광고비 × 100(합친 값으로 계산 — 틱톡의 ROAS 칸은 더할 수 없다).
|
||||||
|
공식 문서가 스크립트 화면이라 지표 이름을 이차 자료로 확인했다 — 연결 테스트가 어제 하루를 실제로 물어 지표 이름 오류까지 잡는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.timezone import today_kst
|
||||||
|
|
||||||
|
from .. import fx
|
||||||
|
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, TokenExpired
|
||||||
|
from .base import AdDay, AdSource
|
||||||
|
from .meta_ads import _num, _won
|
||||||
|
|
||||||
|
API_BASE = "https://business-api.tiktok.com/open_api/v1.3"
|
||||||
|
MAX_DAYS = 366
|
||||||
|
SPAN_DAYS = 30
|
||||||
|
PAGE_SIZE = 100 # 계정 하나·30일 = 많아야 30줄이라 한 쪽이면 된다
|
||||||
|
RATE_LIMIT = 40100
|
||||||
|
|
||||||
|
REPORT_METRICS = ("spend", "impressions", "clicks", "complete_payment", "total_complete_payment_rate",
|
||||||
|
"onsite_shopping", "total_onsite_shopping_value")
|
||||||
|
GMV_METRICS = ("cost", "gross_revenue", "orders")
|
||||||
|
|
||||||
|
# metrics 키 — 화면 이름 그대로 저장. 틱톡 탭은 M_REVENUE 를 매출로 읽는다(ad_spend.build_tiktok_dashboard).
|
||||||
|
M_SPEND, M_REVENUE, M_ROAS = "광고비", "매출", "ROAS(%)"
|
||||||
|
M_IMPR, M_CLICKS, M_ORDERS = "노출수", "클릭수", "구매수"
|
||||||
|
M_WEB, M_SHOP, M_GMV_COST, M_GMV_REVENUE = "웹 구매금액", "틱톡샵 매출", "GMV Max 비용", "GMV Max 매출"
|
||||||
|
|
||||||
|
|
||||||
|
def _http(ctx: AdapterContext) -> httpx.Client:
|
||||||
|
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
|
||||||
|
return httpx.Client(timeout=ctx.timeout_sec)
|
||||||
|
|
||||||
|
|
||||||
|
def _spans(start: date, end: date) -> list[tuple[date, date]]:
|
||||||
|
"""기간을 SPAN_DAYS 일씩 나눈다."""
|
||||||
|
out = []
|
||||||
|
while start <= end:
|
||||||
|
stop = min(start + timedelta(days=SPAN_DAYS - 1), end)
|
||||||
|
out.append((start, stop))
|
||||||
|
start = stop + timedelta(days=1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class TiktokAdsSource(AdSource):
|
||||||
|
code = "tiktok"
|
||||||
|
name = "틱톡"
|
||||||
|
docs_url = "https://business-api.tiktok.com/portal/docs"
|
||||||
|
note = ("TikTok API for Business 로 날짜별 광고비·매출·ROAS 를 가져와 틱톡 탭에 보여 줍니다(매출 실적·광고비 탭 합계에는 들어가지 않음). "
|
||||||
|
"준비: 개발자 앱에서 광고 계정을 승인해 장기 액세스 토큰 발급(보고서·광고 계정 읽기 권한). 외화 계정은 그날 환율로 원화로 바꿉니다.")
|
||||||
|
|
||||||
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
return [
|
||||||
|
CredentialField("advertiser_id", "광고 계정 ID", placeholder="7123456789012345678",
|
||||||
|
help="틱톡 광고 관리자 주소의 aadvid= 뒤 숫자."),
|
||||||
|
CredentialField("access_token", "액세스 토큰", secret=True,
|
||||||
|
help="광고 계정을 승인할 때 받은 장기 액세스 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
|
||||||
|
CredentialField("shop_id", "틱톡샵 ID", required=False, placeholder="GMV Max 캠페인을 쓸 때만",
|
||||||
|
help="GMV Max 캠페인은 일반 보고서와 따로 조회합니다 — 넣으면 그 비용·매출도 더합니다. 안 쓰면 비워 둡니다."),
|
||||||
|
]
|
||||||
|
|
||||||
|
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||||
|
errors = super().validate_credentials(values)
|
||||||
|
advertiser = (values.get("advertiser_id") or "").strip()
|
||||||
|
if advertiser and advertiser != "__stored__" and not re.fullmatch(r"\d{5,30}", advertiser):
|
||||||
|
errors.append("광고 계정 ID 는 숫자여야 합니다.")
|
||||||
|
shop = (values.get("shop_id") or "").strip()
|
||||||
|
if shop and shop != "__stored__" and not re.fullmatch(r"\d{5,30}", shop):
|
||||||
|
errors.append("틱톡샵 ID 는 숫자여야 합니다.")
|
||||||
|
token = (values.get("access_token") or "").strip()
|
||||||
|
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
|
||||||
|
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
|
||||||
|
return errors
|
||||||
|
|
||||||
|
def _get(self, ctx: AdapterContext, client: httpx.Client, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""틱톡은 오류도 HTTP 200 + code 로 준다. 토큰은 머리글로만 보내 주소·오류 문구에 들어가지 않는다."""
|
||||||
|
ctx.progress.check()
|
||||||
|
token = (ctx.credentials.get("access_token") or "").strip()
|
||||||
|
try:
|
||||||
|
resp = client.get(API_BASE + path, params=params, headers={"Access-Token": token})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"틱톡 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
try:
|
||||||
|
body = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
raise ApiError(f"틱톡 API 응답을 읽을 수 없습니다(HTTP {resp.status_code}).") from None
|
||||||
|
code = body.get("code") if isinstance(body, dict) else None
|
||||||
|
if resp.status_code == 200 and code == 0:
|
||||||
|
return body.get("data") or {}
|
||||||
|
text = f"틱톡 API 오류({code if code is not None else resp.status_code}): {str((body or {}).get('message') or '')[:200]}"
|
||||||
|
if code == 40102:
|
||||||
|
raise TokenExpired(text + " — 액세스 토큰을 다시 발급해 넣으세요.")
|
||||||
|
if code == RATE_LIMIT:
|
||||||
|
raise ApiError(text + " — 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.")
|
||||||
|
if resp.status_code in (401, 403) or (isinstance(code, int) and 40100 < code < 40200):
|
||||||
|
raise AuthFailed(text + " — 토큰과 광고 계정 ID, 앱 권한을 확인하세요.")
|
||||||
|
raise ApiError(text)
|
||||||
|
|
||||||
|
def _info(self, ctx: AdapterContext, client: httpx.Client) -> dict[str, Any]:
|
||||||
|
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
|
||||||
|
rows = self._get(ctx, client, "/advertiser/info/", {
|
||||||
|
"advertiser_ids": json.dumps([advertiser]), "fields": json.dumps(["name", "currency", "timezone"])}).get("list") or []
|
||||||
|
if not rows:
|
||||||
|
raise AuthFailed("이 토큰으로 볼 수 없는 광고 계정입니다 — 광고 계정 ID 와 승인 여부를 확인하세요.")
|
||||||
|
return rows[0]
|
||||||
|
|
||||||
|
def _rows(self, ctx: AdapterContext, client: httpx.Client, path: str, metrics: tuple[str, ...], start: date, end: date,
|
||||||
|
**extra: Any) -> list[tuple[date, dict[str, Any]]]:
|
||||||
|
"""보고서 하나를 30일씩 물어 (날짜, 지표) 목록으로."""
|
||||||
|
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
|
||||||
|
out = []
|
||||||
|
for s, e in _spans(start, end):
|
||||||
|
data = self._get(ctx, client, path, {
|
||||||
|
"advertiser_id": advertiser, "dimensions": json.dumps(["advertiser_id", "stat_time_day"]), "metrics": json.dumps(metrics),
|
||||||
|
"start_date": s.isoformat(), "end_date": e.isoformat(), "page": 1, "page_size": PAGE_SIZE, **extra})
|
||||||
|
for r in data.get("list") or []:
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(str((r.get("dimensions") or {}).get("stat_time_day"))[:10])
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
out.append((day, r.get("metrics") or {}))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _collect(self, ctx: AdapterContext, client: httpx.Client, start: date, end: date) -> dict[date, dict[str, Decimal]]:
|
||||||
|
"""날짜 → 항목 합(계정 통화)."""
|
||||||
|
sums: dict[date, dict[str, Decimal]] = {}
|
||||||
|
|
||||||
|
def day_of(d: date) -> dict[str, Decimal]:
|
||||||
|
return sums.setdefault(d, {k: Decimal(0) for k in ("spend", "impr", "clicks", "orders", "web", "shop", "gmv_cost", "gmv")})
|
||||||
|
|
||||||
|
for d, m in self._rows(ctx, client, "/report/integrated/get/", REPORT_METRICS, start, end,
|
||||||
|
report_type="BASIC", data_level="AUCTION_ADVERTISER"):
|
||||||
|
one = day_of(d)
|
||||||
|
one["spend"] += _num(m.get("spend"))
|
||||||
|
one["impr"] += _num(m.get("impressions"))
|
||||||
|
one["clicks"] += _num(m.get("clicks"))
|
||||||
|
one["orders"] += _num(m.get("complete_payment")) + _num(m.get("onsite_shopping"))
|
||||||
|
one["web"] += _num(m.get("total_complete_payment_rate"))
|
||||||
|
one["shop"] += _num(m.get("total_onsite_shopping_value"))
|
||||||
|
shop_id = (ctx.credentials.get("shop_id") or "").strip()
|
||||||
|
if shop_id:
|
||||||
|
for d, m in self._rows(ctx, client, "/gmv_max/report/get/", GMV_METRICS, start, end, store_ids=json.dumps([shop_id])):
|
||||||
|
one = day_of(d)
|
||||||
|
one["orders"] += _num(m.get("orders"))
|
||||||
|
one["gmv_cost"] += _num(m.get("cost"))
|
||||||
|
one["gmv"] += _num(m.get("gross_revenue"))
|
||||||
|
return sums
|
||||||
|
|
||||||
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
|
self.require_configured(ctx)
|
||||||
|
yesterday = today_kst() - timedelta(days=1)
|
||||||
|
with _http(ctx) as client:
|
||||||
|
info = self._info(ctx, client)
|
||||||
|
self._collect(ctx, client, yesterday, yesterday) # 지표 이름·GMV Max 권한까지 실제로 확인
|
||||||
|
return f"연결됨 — {info.get('name') or '광고 계정'}({info.get('currency') or '?'}·{info.get('timezone') or '?'})"
|
||||||
|
|
||||||
|
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
||||||
|
if end < start:
|
||||||
|
start, end = end, start
|
||||||
|
if (end - start).days + 1 > MAX_DAYS:
|
||||||
|
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
|
||||||
|
self.require_configured(ctx)
|
||||||
|
with _http(ctx) as client:
|
||||||
|
currency = str(self._info(ctx, client).get("currency") or "").upper()
|
||||||
|
if not re.fullmatch(r"[A-Z]{3}", currency):
|
||||||
|
raise ApiError(f"광고 계정 통화({currency[:10] or '없음'})를 알 수 없습니다.")
|
||||||
|
sums = self._collect(ctx, client, start, end)
|
||||||
|
try:
|
||||||
|
rates = fx.krw_rates(client, currency, start, end) if sums else {}
|
||||||
|
except fx.FxError as exc:
|
||||||
|
raise ApiError(f"{currency} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
|
||||||
|
return [_day(d, sums[d], rates[d]) for d in sorted(sums)]
|
||||||
|
|
||||||
|
|
||||||
|
def _day(day: date, a: dict[str, Decimal], rate: Decimal) -> AdDay:
|
||||||
|
"""합친 값(계정 통화) → 하루치(원화). ROAS 는 비율이라 반올림 전 값으로."""
|
||||||
|
spend = (a["spend"] + a["gmv_cost"]) * rate
|
||||||
|
revenue = (a["web"] + a["shop"] + a["gmv"]) * rate
|
||||||
|
roas = (revenue / spend * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if spend > 0 else None
|
||||||
|
return AdDay(day=day, amount=_won(spend), roas=roas, metrics={
|
||||||
|
M_SPEND: _won(spend), M_REVENUE: _won(revenue), M_ROAS: float(roas) if roas is not None else None,
|
||||||
|
M_WEB: _won(a["web"] * rate), M_SHOP: _won(a["shop"] * rate), M_GMV_COST: _won(a["gmv_cost"] * rate), M_GMV_REVENUE: _won(a["gmv"] * rate),
|
||||||
|
M_IMPR: int(a["impr"]), M_CLICKS: int(a["clicks"]), M_ORDERS: int(a["orders"]),
|
||||||
|
})
|
||||||
@@ -22,18 +22,20 @@ from __future__ import annotations
|
|||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import date
|
from datetime import date, timedelta
|
||||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
from typing import Any, Callable, Mapping, Sequence
|
from typing import Any, Callable, Mapping, Sequence
|
||||||
|
|
||||||
from . import calc
|
from . import calc
|
||||||
from .ad_sources.base import ACCOUNTS_KEY
|
from .ad_sources.base import ACCOUNTS_KEY
|
||||||
|
from .ad_sources.tiktok_ads import M_REVENUE as TIKTOK_REVENUE_KEY
|
||||||
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
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).
|
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
|
||||||
CHANNELS: tuple[tuple[str, str], ...] = (
|
CHANNELS: tuple[tuple[str, str], ...] = (
|
||||||
("google", "구글"),
|
("google", "구글"),
|
||||||
("meta", "메타"),
|
("meta", "메타"),
|
||||||
|
("kakao_pf", "카톡 플친"), # 2026-11-16 — 카카오톡 플러스친구(자사몰 광고, 직접 입력), ROAS 없음, 매출 탭 카페24 줄에 구글·메타 아래
|
||||||
("naver", "네이버"),
|
("naver", "네이버"),
|
||||||
("coupang_wing", "쿠팡(윙)"),
|
("coupang_wing", "쿠팡(윙)"),
|
||||||
("coupang_rocket", "쿠팡(로켓)"),
|
("coupang_rocket", "쿠팡(로켓)"),
|
||||||
@@ -54,9 +56,10 @@ CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
|
|||||||
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
|
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
|
||||||
FILE_ROAS = frozenset({"google", "meta", "naver"})
|
FILE_ROAS = frozenset({"google", "meta", "naver"})
|
||||||
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
|
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
|
||||||
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다
|
NO_SALES = frozenset({"etc", "kakao_pf"}) # ROAS 를 계산하지 않는 채널 — 매출 탭 광고비 줄은 sales_ad_channels 에 적은 것만(카톡 플친 = 카페24)
|
||||||
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
|
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
|
||||||
ROAS_SALES_CODE["coupang_wing"] = "coupang"
|
ROAS_SALES_CODE["coupang_wing"] = "coupang"
|
||||||
|
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
|
||||||
|
|
||||||
|
|
||||||
def roas(sales: int, spend: int) -> int | None:
|
def roas(sales: int, spend: int) -> int | None:
|
||||||
@@ -476,6 +479,85 @@ def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
|||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 화면 데이터
|
# 화면 데이터
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _period_word(period: Any, today: date) -> str:
|
||||||
|
"""KPI 이름 앞 말 — 이번달·해당 월 등."""
|
||||||
|
return {"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]
|
||||||
|
|
||||||
|
|
||||||
|
def _period_nav(period: Any, today: date) -> dict[str, Any]:
|
||||||
|
"""기간 이동 화살표·빠른 선택(이번달·올해만 — 2026-10-26 오늘·이번주 버튼 삭제, 매출 실적과 같게)."""
|
||||||
|
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":
|
||||||
|
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)
|
||||||
|
return {"prev": prev_url, "next": next_url, "quick": [
|
||||||
|
{"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},
|
||||||
|
]}
|
||||||
|
|
||||||
|
|
||||||
|
def build_tiktok_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) -> dict[str, Any]:
|
||||||
|
"""틱톡 탭(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프, 열 = ROAS·광고비·매출. 광고 API 가 저장한 perf_ad_spend 만 읽는다.
|
||||||
|
CHANNELS 에 없어 광고비 탭·매출 실적 합계에는 들어가지 않는다."""
|
||||||
|
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
|
||||||
|
year_period = calc.resolve_period("year", ref)
|
||||||
|
migration_needed = False
|
||||||
|
try:
|
||||||
|
rows = store.ad_details(TIKTOK, min(period.start, cmp_start, year_period.start), max(period.end, year_period.end))
|
||||||
|
except AdMigrationNeeded:
|
||||||
|
rows, migration_needed = [], True
|
||||||
|
cells: dict[tuple[date, str], calc.Money] = {}
|
||||||
|
for r in rows:
|
||||||
|
d = date.fromisoformat(r["date"])
|
||||||
|
cells[(d, "spend")] = calc.Money(gross=int(r["amount"] or 0))
|
||||||
|
cells[(d, "sales")] = calc.Money(gross=int((r["metrics"] or {}).get(TIKTOK_REVENUE_KEY) or 0))
|
||||||
|
|
||||||
|
table = calc.main_table(period, ("spend", "sales"), cells, today=today, holidays=holidays)
|
||||||
|
for row in table:
|
||||||
|
row["roas"] = roas(row["cells"]["sales"]["gross"], row["cells"]["spend"]["gross"])
|
||||||
|
cur = {c: calc.sum_range(cells, [c], period.start, period.end).gross for c in ("spend", "sales")}
|
||||||
|
prev = {c: calc.sum_range(cells, [c], cmp_start, cmp_end).gross for c in ("spend", "sales")}
|
||||||
|
word = _period_word(period, today)
|
||||||
|
spend_y = calc.year_months(year_period.start.year, ["spend"], cells, today=today)
|
||||||
|
sales_y = calc.year_months(year_period.start.year, ["sales"], cells, today=today)
|
||||||
|
year_rows = [{"label": a["label"], "future": a["future"], "spend": a["gross"], "sales": b["gross"],
|
||||||
|
"roas": None if a["future"] else roas(b["gross"], a["gross"])}
|
||||||
|
for a, b in zip(spend_y["rows"], sales_y["rows"])]
|
||||||
|
return {
|
||||||
|
"nav": _period_nav(period, today),
|
||||||
|
"period": period,
|
||||||
|
"period_kind": period.kind,
|
||||||
|
"today": today.isoformat(),
|
||||||
|
"kpis": [
|
||||||
|
{"key": "spend", "label": f"{word} 광고비", "value": cur["spend"], "primary": True,
|
||||||
|
"delta": calc.pct_change(cur["spend"], prev["spend"]), "cmp": cmp_label, "invert": True},
|
||||||
|
{"key": "sales", "label": f"{word} 매출", "value": cur["sales"],
|
||||||
|
"delta": calc.pct_change(cur["sales"], prev["sales"]), "cmp": cmp_label},
|
||||||
|
{"key": "roas", "label": f"{word} ROAS", "pct": roas(cur["sales"], cur["spend"])},
|
||||||
|
],
|
||||||
|
"table": table,
|
||||||
|
"chart_sales": calc.daily_series(period, ["sales"], cells),
|
||||||
|
"chart_spend": calc.daily_series(period, ["spend"], cells),
|
||||||
|
"year": {"year": year_period.start.year, "rows": year_rows, "spend": spend_y["total"]["gross"], "sales": sales_y["total"]["gross"],
|
||||||
|
"roas": roas(sales_y["total"]["gross"], spend_y["total"]["gross"])},
|
||||||
|
"migration_needed": migration_needed,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||||
custom_from: date | None = None, custom_to: date | None = None,
|
custom_from: date | None = None, custom_to: date | None = None,
|
||||||
holidays: Mapping[str, str] | None = None,
|
holidays: Mapping[str, str] | None = None,
|
||||||
@@ -507,8 +589,6 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
|
|
||||||
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)
|
||||||
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)
|
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)
|
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
|
||||||
|
|
||||||
@@ -524,41 +604,17 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
|
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
|
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
|
||||||
|
|
||||||
word = {"day": "오늘" if period.start == today else "해당일",
|
word = _period_word(period, today)
|
||||||
"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 = [
|
kpis = [
|
||||||
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
||||||
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
||||||
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
||||||
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
|
"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,
|
{"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},
|
"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:
|
nav = _period_nav(period, today)
|
||||||
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)
|
|
||||||
# 빠른 선택은 이번달·올해만(2026-10-26 — 오늘·이번주 버튼 삭제, 매출 실적과 같게)
|
|
||||||
nav = {"prev": prev_url, "next": next_url, "quick": [
|
|
||||||
{"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)
|
share = calc.by_code(cells, codes, period.start, period.end)
|
||||||
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
|
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)
|
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||||
|
|||||||
@@ -1,17 +1,20 @@
|
|||||||
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
"""매출·광고비 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
||||||
|
|
||||||
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
|
일정(2026-10-26) — 실적 설정 "자동 업데이트" 카드에서 매출 실적·광고비를 **따로** 정한다(마이그레이션 011 perf_settings,
|
||||||
- 같은 회차에 광고비(설정된 광고 API — 구글·메타)도 같은 기간으로 **동시에** 가져온다(2026-10-20, 광고비 진행 창 작업
|
key 'auto_sync'). 종류마다 {enabled, interval(분, 5분 단위, 기본 30), days(0=월 … 6=일), start "HH:MM", end "HH:MM"}.
|
||||||
jobs kind="ads", 실패해도 매출과 무관). 광고비 탭 [광고비 업데이트]를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
- 회차 = 고른 요일의 start, start+interval, … end 까지(end 와 딱 맞으면 end 도). 시각은 5분 단위, KST.
|
||||||
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
- 저장한 일정은 1분 안에 반영(스레드가 1분마다 다시 읽는다). 저장 값이 없으면(011 미적용 포함) 기본 일정 =
|
||||||
- 그 시각에 이미 같은 종류 업데이트가 돌고 있으면 그 종류는 그 회차를 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
매일 env PERFORMANCE_AUTO_SYNC_HOURS(기본 9-19)시 정각 ~ 마지막 시 정각, 30분마다.
|
||||||
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
- 매출 = 진행 창 작업(jobs kind="sales") — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||||
|
- 광고비 = 설정된 광고 API(구글·메타) — 광고비 진행 창 작업(jobs kind="ads"). 광고비 탭 [광고비 업데이트]도 같은 진행 상황.
|
||||||
|
- 두 종류의 회차가 같은 시각이면 동시에 돈다(따로 스레드). 그 시각에 이미 같은 종류 업데이트가 돌고 있으면 그 종류는 그 회차를
|
||||||
|
건너뛴다. 한 회차가 간격을 넘기면 지나간 회차는 건너뛰고 다음 회차를 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
||||||
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
|
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
|
||||||
|
|
||||||
환경변수(.env)
|
환경변수(.env)
|
||||||
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
|
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐) — 끄면 설정 화면 일정과 상관없이 안 돈다
|
||||||
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
|
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
|
||||||
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
PERFORMANCE_AUTO_SYNC_HOURS=9-19 설정 화면에서 일정을 저장하기 전 기본 시간대(시작시-마지막시)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -31,7 +34,13 @@ logger = logging.getLogger("performance.auto_sync")
|
|||||||
AUTO_USER = "자동 업데이트"
|
AUTO_USER = "자동 업데이트"
|
||||||
DEFAULT_DAYS = 10
|
DEFAULT_DAYS = 10
|
||||||
DEFAULT_HOURS = (9, 19)
|
DEFAULT_HOURS = (9, 19)
|
||||||
SLOT_MINUTES = 30
|
DEFAULT_INTERVAL = 30
|
||||||
|
INTERVAL_STEP = 5
|
||||||
|
INTERVAL_MAX = 720
|
||||||
|
SETTING_KEY = "auto_sync"
|
||||||
|
KINDS = ("sales", "ads")
|
||||||
|
KIND_NAMES = {"sales": "매출 실적", "ads": "광고비"}
|
||||||
|
WEEKDAYS = ("월", "화", "수", "목", "금", "토", "일")
|
||||||
|
|
||||||
_started = False
|
_started = False
|
||||||
_start_lock = threading.Lock()
|
_start_lock = threading.Lock()
|
||||||
@@ -62,27 +71,127 @@ def hour_window() -> tuple[int, int]:
|
|||||||
return first, last
|
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:
|
def default_schedule() -> dict[str, Any]:
|
||||||
|
first, last = hour_window()
|
||||||
|
return {"enabled": True, "interval": DEFAULT_INTERVAL, "days": list(range(7)),
|
||||||
|
"start": f"{first:02d}:00", "end": f"{last:02d}:00"}
|
||||||
|
|
||||||
|
|
||||||
|
def _minutes(hhmm: str) -> int:
|
||||||
|
h, m = hhmm.split(":")
|
||||||
|
return int(h) * 60 + int(m)
|
||||||
|
|
||||||
|
|
||||||
|
def _time(raw: Any, label: str) -> str:
|
||||||
|
m = re.fullmatch(r"(\d{1,2}):(\d{2})", str(raw or "").strip())
|
||||||
|
if not m or not (0 <= int(m.group(1)) <= 23 and 0 <= int(m.group(2)) <= 59):
|
||||||
|
raise ValueError(f"{label}을 HH:MM 으로 넣어 주세요.")
|
||||||
|
if int(m.group(2)) % INTERVAL_STEP:
|
||||||
|
raise ValueError(f"{label}은 {INTERVAL_STEP}분 단위로 정할 수 있습니다.")
|
||||||
|
return f"{int(m.group(1)):02d}:{m.group(2)}"
|
||||||
|
|
||||||
|
|
||||||
|
def validate_schedule(raw: Any) -> dict[str, Any]:
|
||||||
|
"""설정 화면에서 받은 일정 하나 → 정리한 값. 잘못되면 ValueError(화면에 그대로 보여 줄 문구)."""
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
raise ValueError("일정 형식이 잘못되었습니다.")
|
||||||
|
on = bool(raw.get("enabled"))
|
||||||
|
try:
|
||||||
|
interval = int(raw.get("interval"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("간격(분)을 숫자로 넣어 주세요.") from None
|
||||||
|
if not (INTERVAL_STEP <= interval <= INTERVAL_MAX) or interval % INTERVAL_STEP:
|
||||||
|
raise ValueError(f"간격은 {INTERVAL_STEP}분 ~ {INTERVAL_MAX}분, {INTERVAL_STEP}분 단위로 정할 수 있습니다.")
|
||||||
|
days = raw.get("days")
|
||||||
|
if not isinstance(days, list) or any(not isinstance(d, int) or isinstance(d, bool) or not 0 <= d <= 6 for d in days):
|
||||||
|
raise ValueError("요일이 잘못되었습니다.")
|
||||||
|
days = sorted(set(days))
|
||||||
|
if on and not days:
|
||||||
|
raise ValueError("요일을 하나 이상 고르세요(자동 업데이트를 쓰지 않으려면 [사용]을 끄세요).")
|
||||||
|
start, end = _time(raw.get("start"), "시작 시각"), _time(raw.get("end"), "끝 시각")
|
||||||
|
if _minutes(end) < _minutes(start):
|
||||||
|
raise ValueError("끝 시각은 시작 시각과 같거나 뒤여야 합니다(밤을 넘기는 시간대는 안 됩니다).")
|
||||||
|
return {"enabled": on, "interval": interval, "days": days, "start": start, "end": end}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize(raw: Any) -> dict[str, dict[str, Any]]:
|
||||||
|
"""DB 에 저장된 값 → 종류마다 일정. 없거나 잘못된 종류는 기본 일정."""
|
||||||
|
out = {}
|
||||||
|
for k in KINDS:
|
||||||
|
try:
|
||||||
|
out[k] = validate_schedule((raw or {}).get(k)) if isinstance(raw, dict) else default_schedule()
|
||||||
|
except ValueError:
|
||||||
|
out[k] = default_schedule()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def load_schedules(store: Any) -> tuple[dict[str, dict[str, Any]], bool]:
|
||||||
|
"""(종류 → 일정, 011 적용 여부). DB 오류는 그대로 올린다(스레드는 직전 일정을 계속 쓴다)."""
|
||||||
|
from .db import SettingsMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
getter = getattr(store, "get_setting", None)
|
||||||
|
if getter is None: # 테스트용 가짜 저장소 등
|
||||||
|
return normalize(None), True
|
||||||
|
try:
|
||||||
|
return normalize(getter(SETTING_KEY)), True
|
||||||
|
except SettingsMigrationNeeded:
|
||||||
|
return normalize(None), False
|
||||||
|
|
||||||
|
|
||||||
|
def describe(sched: dict[str, Any]) -> str:
|
||||||
|
"""'매일 09:00~19:00 · 30분마다' / '평일 …' / '월·수·금 …' / '꺼짐'."""
|
||||||
|
if not sched.get("enabled") or not sched.get("days"):
|
||||||
|
return "꺼짐"
|
||||||
|
days = sched["days"]
|
||||||
|
if days == list(range(7)):
|
||||||
|
when = "매일"
|
||||||
|
elif days == list(range(5)):
|
||||||
|
when = "평일"
|
||||||
|
elif days == [5, 6]:
|
||||||
|
when = "주말"
|
||||||
|
else:
|
||||||
|
when = "·".join(WEEKDAYS[d] for d in days)
|
||||||
|
span = sched["start"] if sched["start"] == sched["end"] else f"{sched['start']}~{sched['end']}"
|
||||||
|
every = sched["interval"]
|
||||||
|
every_txt = f"{every // 60}시간" + (f" {every % 60}분" if every % 60 else "") if every >= 60 else f"{every}분"
|
||||||
|
return f"{when} {span}" + ("" if sched["start"] == sched["end"] else f" · {every_txt}마다")
|
||||||
|
|
||||||
|
|
||||||
|
def is_slot(t: datetime, sched: dict[str, Any]) -> bool:
|
||||||
|
"""t(분 단위로 자른 KST 시각)가 회차인가."""
|
||||||
|
if not sched.get("enabled") or t.weekday() not in sched["days"]:
|
||||||
return False
|
return False
|
||||||
return first <= t.hour < last or (t.hour == last and t.minute == 0)
|
m, start, end = t.hour * 60 + t.minute, _minutes(sched["start"]), _minutes(sched["end"])
|
||||||
|
return start <= m <= end and (m - start) % sched["interval"] == 0
|
||||||
|
|
||||||
|
|
||||||
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
|
def next_slot(after: datetime, sched: dict[str, Any]) -> datetime | None:
|
||||||
"""after 보다 뒤의 첫 회차 시각."""
|
"""after 보다 뒤의 첫 회차 시각(KST). 꺼져 있거나 요일이 없으면 None."""
|
||||||
t = after.replace(second=0, microsecond=0)
|
if not sched.get("enabled") or not sched.get("days"):
|
||||||
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
|
return None
|
||||||
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
|
start, end, step = _minutes(sched["start"]), _minutes(sched["end"]), sched["interval"]
|
||||||
if is_slot(t, hours):
|
day0 = after.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||||
return t
|
for d in range(8):
|
||||||
t += timedelta(minutes=SLOT_MINUTES)
|
base = day0 + timedelta(days=d)
|
||||||
raise ValueError("회차를 찾을 수 없습니다")
|
if base.weekday() not in sched["days"]:
|
||||||
|
continue
|
||||||
|
first = base + timedelta(minutes=start)
|
||||||
|
k = 0 if first > after else int((after - first).total_seconds() // (step * 60)) + 1
|
||||||
|
m = start + k * step
|
||||||
|
if m <= end:
|
||||||
|
return base + timedelta(minutes=m)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
|
# ════════════════════════════════════════════════════════════
|
||||||
"""한 회차 — 오늘 포함 최근 days 일. 매출(진행 창 작업)과 광고비(광고 진행 창 작업)를 동시에.
|
# 회차 실행
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def run_once(store: Any, app_state: Any, *, today: Any, days: int,
|
||||||
|
kinds: tuple[str, ...] = KINDS) -> dict[str, Any]:
|
||||||
|
"""한 회차 — 오늘 포함 최근 days 일. kinds 의 매출(진행 창 작업)·광고비(광고 진행 창 작업)를 동시에.
|
||||||
각각 이미 돌고 있으면 그 종류만 건너뜀."""
|
각각 이미 돌고 있으면 그 종류만 건너뜀."""
|
||||||
from . import common, jobs # noqa: WPS433
|
from . import common, jobs # noqa: WPS433
|
||||||
from .ad_sync import run_ad_job # noqa: WPS433
|
from .ad_sync import run_ad_job # noqa: WPS433
|
||||||
@@ -92,7 +201,7 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
|
|||||||
start, end = today - timedelta(days=days - 1), today
|
start, end = today - timedelta(days=days - 1), today
|
||||||
ads: list[dict[str, Any]] = []
|
ads: list[dict[str, Any]] = []
|
||||||
ad_thread = None
|
ad_thread = None
|
||||||
ads_skipped = jobs.running_job("ads") is not None
|
ads_skipped = "ads" not in kinds or jobs.running_job("ads") is not None
|
||||||
if not ads_skipped:
|
if not ads_skipped:
|
||||||
ad_job = jobs.create_job(user=AUTO_USER, start=start, end=end, kind="ads")
|
ad_job = jobs.create_job(user=AUTO_USER, start=start, end=end, kind="ads")
|
||||||
|
|
||||||
@@ -102,7 +211,7 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
|
|||||||
ad_thread = threading.Thread(target=_ads, name=f"perf-auto-ads-{ad_job.id}", daemon=True)
|
ad_thread = threading.Thread(target=_ads, name=f"perf-auto-ads-{ad_job.id}", daemon=True)
|
||||||
ad_thread.start()
|
ad_thread.start()
|
||||||
|
|
||||||
sales_skipped = jobs.running_job("sales") is not None
|
sales_skipped = "sales" not in kinds or jobs.running_job("sales") is not None
|
||||||
error = ""
|
error = ""
|
||||||
results: list[dict[str, Any]] = []
|
results: list[dict[str, Any]] = []
|
||||||
if not sales_skipped:
|
if not sales_skipped:
|
||||||
@@ -130,6 +239,36 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
|
|||||||
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
|
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
|
||||||
|
|
||||||
|
|
||||||
|
class Scheduler:
|
||||||
|
"""종류마다 다음 회차(due)를 들고 있다가 시각이 되면 그 종류만 따로 스레드로 돌린다.
|
||||||
|
tick(now) 이 1분마다 불리며 일정이 바뀐 종류는 지금부터 다시 계산(서버 시작·저장 직후 회차는 안 돌림)."""
|
||||||
|
|
||||||
|
def __init__(self, fire: Any):
|
||||||
|
self.fire = fire # fire(kind, due)
|
||||||
|
self.schedules: dict[str, dict[str, Any]] = {}
|
||||||
|
self.due: dict[str, datetime | None] = {}
|
||||||
|
|
||||||
|
def update(self, schedules: dict[str, dict[str, Any]], now: datetime) -> None:
|
||||||
|
for k in KINDS:
|
||||||
|
s = schedules.get(k) or default_schedule()
|
||||||
|
if self.schedules.get(k) != s:
|
||||||
|
self.schedules[k] = s
|
||||||
|
self.due[k] = next_slot(now, s)
|
||||||
|
|
||||||
|
def tick(self, now: datetime) -> None:
|
||||||
|
for k in KINDS:
|
||||||
|
due = self.due.get(k)
|
||||||
|
if due is not None and due <= now:
|
||||||
|
self.fire(k, due)
|
||||||
|
self.due[k] = next_slot(max(now, due), self.schedules[k])
|
||||||
|
|
||||||
|
def wait_seconds(self, now: datetime) -> float:
|
||||||
|
dues = [d for d in self.due.values() if d is not None]
|
||||||
|
if not dues:
|
||||||
|
return 60.0
|
||||||
|
return max(0.0, min(60.0, min((d - now).total_seconds() for d in dues)))
|
||||||
|
|
||||||
|
|
||||||
def start_auto_sync_thread(app_state: Any) -> bool:
|
def start_auto_sync_thread(app_state: Any) -> bool:
|
||||||
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
|
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
|
||||||
global _started # noqa: PLW0603
|
global _started # noqa: PLW0603
|
||||||
@@ -147,23 +286,38 @@ def start_auto_sync_thread(app_state: Any) -> bool:
|
|||||||
if _started:
|
if _started:
|
||||||
return False
|
return False
|
||||||
_started = True
|
_started = True
|
||||||
hours, days = hour_window(), sync_days()
|
days = sync_days()
|
||||||
|
|
||||||
|
def _fire(kind: str, due: datetime) -> None:
|
||||||
|
def _run() -> None:
|
||||||
|
try:
|
||||||
|
res = run_once(store, app_state, today=due.date(), days=days, kinds=(kind,))
|
||||||
|
logger.info("%s 자동 업데이트 %s: %s", KIND_NAMES[kind], due.strftime("%H:%M"), res)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("%s 자동 업데이트 실패 — 다음 회차에 다시", KIND_NAMES[kind])
|
||||||
|
|
||||||
|
threading.Thread(target=_run, name=f"performance-auto-{kind}", daemon=True).start()
|
||||||
|
|
||||||
|
sched = Scheduler(_fire)
|
||||||
|
|
||||||
|
def _reload(now: datetime) -> None:
|
||||||
|
try:
|
||||||
|
schedules, _ = load_schedules(store)
|
||||||
|
except Exception: # noqa: BLE001 — DB 가 잠시 끊기면 직전 일정 그대로(처음이면 기본 일정)
|
||||||
|
logger.warning("자동 업데이트 일정 읽기 실패 — 직전 일정 사용", exc_info=True)
|
||||||
|
schedules = sched.schedules or normalize(None)
|
||||||
|
sched.update(schedules, now)
|
||||||
|
|
||||||
def _loop() -> None:
|
def _loop() -> None:
|
||||||
due = next_slot(now_kst(), hours)
|
_reload(now_kst())
|
||||||
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
|
logger.info("실적 자동 업데이트 시작 — 최근 %d일, %s", days, ", ".join(
|
||||||
due.strftime("%m-%d %H:%M"))
|
f"{KIND_NAMES[k]} {describe(sched.schedules[k])} 다음 "
|
||||||
|
f"{sched.due[k].strftime('%m-%d %H:%M') if sched.due[k] else '없음'}" for k in KINDS))
|
||||||
while True:
|
while True:
|
||||||
wait = (due - now_kst()).total_seconds()
|
time.sleep(max(1.0, sched.wait_seconds(now_kst()))) # 시계 변경·절전·일정 저장에도 1분 안에 다시 확인
|
||||||
if wait > 0:
|
now = now_kst()
|
||||||
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
|
_reload(now)
|
||||||
continue
|
sched.tick(now)
|
||||||
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()
|
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -156,6 +156,17 @@ class Period:
|
|||||||
unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간")
|
unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간")
|
||||||
return prev_start, prev_end, f"{unit} {note}".strip()
|
return prev_start, prev_end, f"{unit} {note}".strip()
|
||||||
|
|
||||||
|
def yoy_range(self, today: date) -> tuple[date, date, str]:
|
||||||
|
"""1년 전 같은 날짜 범위(2026-11-16 매출 KPI 전년 대비). 진행 중인 기간이면 오늘까지만. 2/29 → 2/28."""
|
||||||
|
def back(d: date) -> date:
|
||||||
|
try:
|
||||||
|
return d.replace(year=d.year - 1)
|
||||||
|
except ValueError:
|
||||||
|
return d.replace(year=d.year - 1, day=28)
|
||||||
|
|
||||||
|
end = today if self.start <= today < self.end else self.end
|
||||||
|
return back(self.start), back(end), "전년 같은 기간"
|
||||||
|
|
||||||
|
|
||||||
def resolve_period(
|
def resolve_period(
|
||||||
kind: str,
|
kind: str,
|
||||||
|
|||||||
@@ -85,11 +85,11 @@ def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[s
|
|||||||
def guard(request: Request, *, admin: bool = False):
|
def guard(request: Request, *, admin: bool = False):
|
||||||
"""페이지 진입부. tuple(store, user) 이 아니면 그대로 응답으로 돌려준다."""
|
"""페이지 진입부. tuple(store, user) 이 아니면 그대로 응답으로 돌려준다."""
|
||||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||||
|
|
||||||
user = get_current_user_record(request)
|
user = get_current_user_record(request)
|
||||||
if user is None:
|
if user is None:
|
||||||
return RedirectResponse(url="/login", status_code=303)
|
return login_redirect(request)
|
||||||
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
|
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
|
||||||
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
|
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
|
||||||
return render_template(request, "denied.html",
|
return render_template(request, "denied.html",
|
||||||
|
|||||||
@@ -57,6 +57,46 @@ def _group_columns(store_rows: Sequence[Mapping[str, Any]], codes: Sequence[str]
|
|||||||
return cols, members
|
return cols, members
|
||||||
|
|
||||||
|
|
||||||
|
# 카페24(실적) 열(2026-11-02, 예전 "공구 제외") — 카페24(전체) 바로 오른쪽, 카페24 − 공동구매. 표 열만(일 합계·그래프·누적엔 안 더함).
|
||||||
|
# shortcut: 공동구매 쇼핑몰은 이름(띄어쓰기 무시)으로 찾는다 — 설정에서 다른 이름으로 바꾸면 빼지 않아 실적 = 전체가 된다, 자주 바뀌면 설정 값으로.
|
||||||
|
CAFE24_GB_NAMES = ("자사몰(공동구매)", "카페24공동구매")
|
||||||
|
CAFE24_EX_GB = "cafe24_ex_gb"
|
||||||
|
CAFE24_REAL_NAME = "카페24(실적)"
|
||||||
|
|
||||||
|
|
||||||
|
def groupbuy_code(markets: Sequence[Mapping[str, Any]]) -> str:
|
||||||
|
"""공동구매 쇼핑몰 코드, 없으면 빈 값."""
|
||||||
|
return next((m["code"] for m in markets if m["name"].replace(" ", "") in CAFE24_GB_NAMES), "")
|
||||||
|
|
||||||
|
|
||||||
|
def total_sales_codes(markets: Sequence[Mapping[str, Any]]) -> list[str]:
|
||||||
|
"""전체 매출에 더할 쇼핑몰 — 카페24(전체)에 공동구매가 들어 있어 카페24 가 있으면 공동구매는 뺀다(광고비 탭 매출 대비 광고비·합계 ROAS)."""
|
||||||
|
codes = [m["code"] for m in markets]
|
||||||
|
gb = groupbuy_code(markets)
|
||||||
|
return [c for c in codes if c != gb] if "cafe24" in codes else codes
|
||||||
|
|
||||||
|
|
||||||
|
def _summary_cells(cells: Mapping[tuple[date, str], calc.Money], gb: str) -> dict[tuple[date, str], calc.Money]:
|
||||||
|
"""합계용 칸(2026-11-02) — 카페24 칸 = 카페24(실적)(카페24 − 공동구매). 일 합계·KPI·그래프·누적은 이 값으로 더해 공동구매가 두 번 안 들어간다."""
|
||||||
|
out = dict(cells)
|
||||||
|
for (d, c), m in cells.items():
|
||||||
|
if c == gb:
|
||||||
|
a = cells.get((d, "cafe24"), calc.Money())
|
||||||
|
out[(d, "cafe24")] = calc.Money(gross=a.gross - m.gross, commission=a.commission - m.commission)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _cafe24_real_column(cols: list[dict[str, Any]], names: dict[str, str], short: dict[str, str], gb: str) -> None:
|
||||||
|
"""카페24(실적) 열 머리 — 공동구매가 없으면(gb 빈 값) 전체와 같은 값이고 화면 즉시 계산도 없다."""
|
||||||
|
col = next((c for c in cols if c["code"] == CAFE24_EX_GB), None)
|
||||||
|
if col is None:
|
||||||
|
return
|
||||||
|
# base·minus = 화면이 공동구매 칸 저장 때 이 줄 칸을 바로 다시 계산할 때 씀(performance.js saveManual)
|
||||||
|
col.update(kind="diff", base="cafe24", minus=gb)
|
||||||
|
names[CAFE24_EX_GB] = f"{names['cafe24']} − {names[gb]}" if gb else CAFE24_REAL_NAME
|
||||||
|
short[CAFE24_EX_GB] = CAFE24_REAL_NAME
|
||||||
|
|
||||||
|
|
||||||
def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None,
|
def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None,
|
||||||
configured: bool) -> str:
|
configured: bool) -> str:
|
||||||
if not marketplace.get("enabled"):
|
if not marketplace.get("enabled"):
|
||||||
@@ -69,15 +109,46 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any]
|
|||||||
return (status_row or {}).get("status") or "unknown"
|
return (status_row or {}).get("status") or "unknown"
|
||||||
|
|
||||||
|
|
||||||
# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름)
|
# 매출 단위(2026-10-19, 11-02 실적 설정 "공통 보기 설정" — 모든 사용자 같음, 마이그레이션 011 perf_settings) — (나누는 수, 소수 자리, 단위 이름)
|
||||||
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
|
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
|
||||||
UNIT_COOKIE = "perf_unit"
|
UNIT_SETTING = "display_unit"
|
||||||
|
|
||||||
|
|
||||||
def normalize_unit(value: Any) -> str:
|
def normalize_unit(value: Any) -> str:
|
||||||
return value if value in UNITS else "won"
|
return value if value in UNITS else "won"
|
||||||
|
|
||||||
|
|
||||||
|
# 일자별 표 열 너비(2026-10-27, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_colw) — auto = 글자 길이에 맞춤, manual = 머리글 경계 드래그
|
||||||
|
COLW_COOKIE = "perf_colw"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_colw(value: Any) -> str:
|
||||||
|
return "manual" if value == "manual" else "auto"
|
||||||
|
|
||||||
|
|
||||||
|
# 매출 실적 표 열 숨기기(2026-11-02, 실적 설정 "공통 보기 설정" — 관리자가 정하면 모든 사용자에게 적용, 마이그레이션 011 perf_settings) — 코드 목록, 열만 숨김
|
||||||
|
HIDDEN_SETTING = "hidden_marketplaces"
|
||||||
|
|
||||||
|
|
||||||
|
def _shared_setting(store: Any, key: str) -> Any:
|
||||||
|
"""모든 사용자 공통 설정 값. 저장 값 없음·011 미적용이면 None(화면은 그대로 열린다)."""
|
||||||
|
from .db import SettingsMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
reader = getattr(store, "get_setting", None)
|
||||||
|
try:
|
||||||
|
return reader(key) if reader else None
|
||||||
|
except SettingsMigrationNeeded:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def load_hidden(store: Any) -> set[str]:
|
||||||
|
return set(_shared_setting(store, HIDDEN_SETTING) or ())
|
||||||
|
|
||||||
|
|
||||||
|
def load_unit(store: Any) -> str:
|
||||||
|
return normalize_unit(_shared_setting(store, UNIT_SETTING))
|
||||||
|
|
||||||
|
|
||||||
def amount_text(value: Any, unit: str = "won") -> str:
|
def amount_text(value: Any, unit: str = "won") -> str:
|
||||||
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
|
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
|
||||||
div, places, _ = UNITS[normalize_unit(unit)]
|
div, places, _ = UNITS[normalize_unit(unit)]
|
||||||
@@ -90,7 +161,7 @@ def amount_text(value: Any, unit: str = "won") -> str:
|
|||||||
def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any],
|
def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any],
|
||||||
period: Any, q_start: date, q_end: date) -> None:
|
period: Any, q_start: date, q_end: date) -> None:
|
||||||
"""매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS).
|
"""매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS).
|
||||||
카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
|
카페24 = 구글·메타·카톡 플친 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
|
||||||
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
|
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
|
||||||
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
|
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
|
||||||
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
|
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
|
||||||
@@ -146,11 +217,11 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
|
|||||||
|
|
||||||
|
|
||||||
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
|
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
|
||||||
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고,
|
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타·카톡 플친(자사몰 광고), 네이버 = 네이버 광고,
|
||||||
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
|
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
|
||||||
from . import ad_spend # noqa: WPS433
|
from . import ad_spend # noqa: WPS433
|
||||||
|
|
||||||
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)}
|
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친")), "naver": (("naver", ""),)}
|
||||||
for ch, c in ad_spend.ROAS_SALES_CODE.items():
|
for ch, c in ad_spend.ROAS_SALES_CODE.items():
|
||||||
out[c] = out.get(c, ()) + ((ch, ""),)
|
out[c] = out.get(c, ()) + ((ch, ""),)
|
||||||
return out
|
return out
|
||||||
@@ -167,7 +238,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
names = {m["code"]: m["name"] for m in markets}
|
names = {m["code"]: m["name"] for m in markets}
|
||||||
short = {c: _short_name(names[c]) for c in all_codes}
|
short = {c: _short_name(names[c]) for c in all_codes}
|
||||||
# 그룹(009) — 그룹 열 = 보이는 하위 쇼핑몰 합계(표 열만, 합계·그래프·누적은 쇼핑몰 기준 그대로)
|
# 그룹(009) — 그룹 열 = 보이는 하위 쇼핑몰 합계(표 열만, 합계·그래프·누적은 쇼핑몰 기준 그대로)
|
||||||
cols, group_members = _group_columns(store_rows, codes)
|
# 표에 그릴 열 = 고른 쇼핑몰 + 카페24 바로 뒤 카페24(실적) − 숨긴 열(합계·그래프·누적은 codes 그대로)
|
||||||
|
hidden = load_hidden(store)
|
||||||
|
shown = [x for c in codes for x in ((c, CAFE24_EX_GB) if c == "cafe24" else (c,)) if x not in hidden]
|
||||||
|
cols, group_members = _group_columns(store_rows, shown)
|
||||||
for m in store_rows:
|
for m in store_rows:
|
||||||
if m["code"] in group_members:
|
if m["code"] in group_members:
|
||||||
names[m["code"]] = short[m["code"]] = m["name"]
|
names[m["code"]] = short[m["code"]] = m["name"]
|
||||||
@@ -187,9 +261,16 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
|
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)
|
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)
|
# 전년 같은 기간 대비(2026-11-16) — 연 보기는 직전 비교가 이미 전년이라 뺀다
|
||||||
|
yoy = period.yoy_range(today) if period.kind != "year" else None
|
||||||
|
|
||||||
|
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start, *(yoy[:1] if yoy else ()))
|
||||||
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())
|
gb = groupbuy_code(markets)
|
||||||
|
# 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다
|
||||||
|
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes if not gb or gb in codes else [*codes, gb]),
|
||||||
|
store.rate_table())
|
||||||
|
summary = _summary_cells(cells, gb)
|
||||||
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
|
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
|
||||||
manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes]
|
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_amounts = getattr(store, "manual_amounts", None)
|
||||||
@@ -201,8 +282,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
(manual_formulas(period.start, period.end, manual_codes) if manual_formulas and manual_codes else {}).items()
|
(manual_formulas(period.start, period.end, manual_codes) if manual_formulas and manual_codes else {}).items()
|
||||||
if f"{d.isoformat()}|{c}" in manual_cells}
|
if f"{d.isoformat()}|{c}" in manual_cells}
|
||||||
|
|
||||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
cur = calc.sum_range(summary, codes, period.start, period.end)
|
||||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
prev = calc.sum_range(summary, codes, cmp_start, cmp_end)
|
||||||
|
|
||||||
period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주",
|
period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||||
@@ -214,8 +295,12 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
|
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
|
||||||
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
|
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
|
||||||
]
|
]
|
||||||
|
if yoy:
|
||||||
|
kpis[0].update(yoy_delta=calc.pct_change(cur.net, calc.sum_range(summary, codes, yoy[0], yoy[1]).net), yoy_cmp=yoy[2])
|
||||||
|
|
||||||
share = calc.by_code(cells, codes, period.start, period.end)
|
share = calc.by_code(summary, codes, period.start, period.end)
|
||||||
|
# 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다
|
||||||
|
summary_names = {**names, "cafe24": CAFE24_REAL_NAME}
|
||||||
statuses = store.statuses()
|
statuses = store.statuses()
|
||||||
configured = configured or {}
|
configured = configured or {}
|
||||||
problems = []
|
problems = []
|
||||||
@@ -229,11 +314,18 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
|
|
||||||
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
|
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
|
||||||
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||||
|
# 일 합계 = 카페24(실적) + 공동구매 + 나머지(2026-11-02) — 공동구매를 필터로 뺐으면 실적 + 나머지.
|
||||||
|
# 일 합계 ROAS 도 이 값 기준이라 _ad_lines 앞에서.
|
||||||
|
for r, s in zip(table, calc.main_table(period, codes, summary, today=today, holidays=holidays)):
|
||||||
|
r["total"] = s["total"]
|
||||||
|
if "cafe24" in codes:
|
||||||
|
r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"]
|
||||||
_ad_lines(store, table, codes, cells, period, q_start, q_end)
|
_ad_lines(store, table, codes, cells, period, q_start, q_end)
|
||||||
for r in table:
|
for r in table:
|
||||||
for g, members in group_members.items():
|
for g, members in group_members.items():
|
||||||
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
|
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
|
||||||
for c in members).as_dict()
|
for c in members).as_dict()
|
||||||
|
_cafe24_real_column(cols, names, short, gb)
|
||||||
|
|
||||||
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||||
if kind == "custom":
|
if kind == "custom":
|
||||||
@@ -273,10 +365,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
"selected_all": len(codes) == len(all_codes),
|
"selected_all": len(codes) == len(all_codes),
|
||||||
"kpis": kpis,
|
"kpis": kpis,
|
||||||
"table": table,
|
"table": table,
|
||||||
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells),
|
"summary_names": summary_names,
|
||||||
"year": calc.year_months(year_period.start.year, codes, cells, today=today),
|
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, summary),
|
||||||
"chart_daily": calc.daily_series(period, codes, cells),
|
"year": calc.year_months(year_period.start.year, codes, summary, today=today),
|
||||||
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
|
"chart_daily": calc.daily_series(period, codes, summary),
|
||||||
|
"chart_share": [{"code": c, "name": summary_names[c], **share[c].as_dict()} for c in codes],
|
||||||
"problems": problems,
|
"problems": problems,
|
||||||
"manual_codes": manual_codes,
|
"manual_codes": manual_codes,
|
||||||
"manual_cells": manual_cells,
|
"manual_cells": manual_cells,
|
||||||
@@ -293,7 +386,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
|
|
||||||
|
|
||||||
def _short_name(name: str) -> str:
|
def _short_name(name: str) -> str:
|
||||||
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스"}.get(name, name)
|
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스", "카페24": "카페24(전체)"}.get(name, name)
|
||||||
|
|
||||||
|
|
||||||
def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapping[str, Any],
|
def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapping[str, Any],
|
||||||
@@ -349,7 +442,14 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
|
|||||||
else:
|
else:
|
||||||
blocks.append({"row": r, "children": []})
|
blocks.append({"row": r, "children": []})
|
||||||
stale = {v: n for v, n in key_versions_in_use.items() if key_info.get("current_version") and v != key_info["current_version"]}
|
stale = {v: n for v, n in key_versions_in_use.items() if key_info.get("current_version") and v != key_info["current_version"]}
|
||||||
return {"rows": rows, "blocks": blocks, "groups": groups,
|
# "매출 실적 표 열 숨기기" 목록 = 매출 실적 표에 나오는 열(그룹 열은 하위를 다 숨기면 사라진다)
|
||||||
|
hide_options: list[dict[str, str]] = []
|
||||||
|
for r in rows:
|
||||||
|
if not r["is_group"] and r["enabled"] and r["include_in_sales"]:
|
||||||
|
hide_options.append({"code": r["code"], "name": _short_name(r["name"])})
|
||||||
|
if r["code"] == "cafe24":
|
||||||
|
hide_options.append({"code": CAFE24_EX_GB, "name": CAFE24_REAL_NAME})
|
||||||
|
return {"rows": rows, "blocks": blocks, "groups": groups, "hide_options": hide_options, "hidden_codes": load_hidden(store),
|
||||||
"custom_ready": bool(store_rows) and "is_custom" in store_rows[0],
|
"custom_ready": bool(store_rows) and "is_custom" in store_rows[0],
|
||||||
"key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
|
"key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
|
||||||
"stale_key_rows": sum(stale.values()), "sample_count": sample_count,
|
"stale_key_rows": sum(stale.values()), "sample_count": sample_count,
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ class MemoMigrationNeeded(Exception):
|
|||||||
"""날짜 칸 메모(마이그레이션 010: perf_cell_memos)가 아직 적용되지 않음."""
|
"""날짜 칸 메모(마이그레이션 010: perf_cell_memos)가 아직 적용되지 않음."""
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsMigrationNeeded(Exception):
|
||||||
|
"""설정 값 저장(마이그레이션 011: perf_settings — 자동 업데이트 일정)이 아직 적용되지 않음."""
|
||||||
|
|
||||||
|
|
||||||
class ManualMigrationNeeded(Exception):
|
class ManualMigrationNeeded(Exception):
|
||||||
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
|
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
|
||||||
|
|
||||||
@@ -513,6 +517,28 @@ class PerformanceDBStore:
|
|||||||
except pg_errors.UndefinedTable:
|
except pg_errors.UndefinedTable:
|
||||||
raise MemoMigrationNeeded() from None
|
raise MemoMigrationNeeded() from None
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 설정 값(마이그레이션 011) — 키 하나 = JSONB. 'auto_sync' = 자동 업데이트 일정(auto_sync.py)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def get_setting(self, key: str) -> Any:
|
||||||
|
"""값(없으면 None). 011 미적용이면 SettingsMigrationNeeded."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT value FROM perf_settings WHERE key = %s", (key,)).fetchone()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise SettingsMigrationNeeded() from None
|
||||||
|
return row["value"] if row else None
|
||||||
|
|
||||||
|
def set_setting(self, key: str, value: Any, *, user: str = "") -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO perf_settings (key, value, updated_by) VALUES (%s, %s, %s) "
|
||||||
|
"ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, "
|
||||||
|
"updated_at = now()", (key, Jsonb(value), user))
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise SettingsMigrationNeeded() from None
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 광고비(마이그레이션 005)
|
# 광고비(마이그레이션 005)
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
|
|||||||
@@ -238,6 +238,14 @@ def get_job(job_id: str) -> SyncJob | None:
|
|||||||
return _JOBS.get(job_id)
|
return _JOBS.get(job_id)
|
||||||
|
|
||||||
|
|
||||||
|
def last_finished(kind: str = "sales", *, exclude_user: str = "") -> SyncJob | None:
|
||||||
|
"""가장 최근에 끝난 그 종류의 작업(exclude_user 가 시작한 것은 뺌). 화면이 자동 업데이트(다른 사람 업데이트 포함)가 끝난 것을
|
||||||
|
알아채 새로 그리려고(2026-10-26) — 보는 사람이 직접 누른 업데이트는 진행 창이 알아서 새로 그린다."""
|
||||||
|
with _LOCK:
|
||||||
|
done = [j for j in _JOBS.values() if j.finished and j.kind == kind and not (exclude_user and j.user == exclude_user)]
|
||||||
|
return max(done, key=lambda j: j.finished_at) if done else None
|
||||||
|
|
||||||
|
|
||||||
def running_job(kind: str = "sales") -> SyncJob | None:
|
def running_job(kind: str = "sales") -> SyncJob | None:
|
||||||
"""지금 돌고 있는 그 종류의 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
|
"""지금 돌고 있는 그 종류의 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
|
||||||
with _LOCK:
|
with _LOCK:
|
||||||
|
|||||||
@@ -5,7 +5,8 @@
|
|||||||
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
||||||
GET /performance/settings 실적 설정(관리자)
|
GET /performance/settings 실적 설정(관리자)
|
||||||
JSON API — 모듈 권한
|
JSON API — 모듈 권한
|
||||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
PUT /performance/api/my-col-fold 일자별 표에서 접은 열(보는 사람 본인에게만, 매출 실적·광고비 따로)
|
||||||
|
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||||
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
|
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
|
||||||
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
|
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
|
||||||
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
||||||
@@ -29,6 +30,8 @@ JSON API — 관리자
|
|||||||
POST /performance/api/marketplaces 쇼핑몰(수동 입력 전용)·그룹 직접 추가(009)
|
POST /performance/api/marketplaces 쇼핑몰(수동 입력 전용)·그룹 직접 추가(009)
|
||||||
DELETE /performance/api/marketplaces/{code} 직접 추가 쇼핑몰·그룹 삭제(그 쇼핑몰 수동 입력·수수료도)
|
DELETE /performance/api/marketplaces/{code} 직접 추가 쇼핑몰·그룹 삭제(그 쇼핑몰 수동 입력·수수료도)
|
||||||
PUT /performance/api/marketplace-order 쇼핑몰 순서(설정 드래그 — 매출 실적 열 순서)
|
PUT /performance/api/marketplace-order 쇼핑몰 순서(설정 드래그 — 매출 실적 열 순서)
|
||||||
|
PUT /performance/api/hidden-marketplaces 매출 실적 표 열 숨기기(모든 사용자에게 적용)
|
||||||
|
PUT /performance/api/display-unit 매출 단위(모든 사용자에게 적용)
|
||||||
GET /performance/api/marketplaces/{code}/manual-days 수동 입력해 둔 날 수(삭제 확인 문구)
|
GET /performance/api/marketplaces/{code}/manual-days 수동 입력해 둔 날 수(삭제 확인 문구)
|
||||||
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}
|
||||||
@@ -145,36 +148,78 @@ def dashboard_page(
|
|||||||
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
|
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
|
||||||
)
|
)
|
||||||
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
|
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
|
||||||
ctx["auto_sync"] = _auto_sync_ctx()
|
ctx["auto_sync"] = _auto_sync_ctx(store, "sales")
|
||||||
_unit_ctx(request, ctx)
|
ctx["update_watch"] = _update_watch("sales", user)
|
||||||
|
_unit_ctx(store, ctx)
|
||||||
|
_colw_ctx(request, ctx)
|
||||||
|
ctx["col_fold"] = _load_col_fold(store, user).get("sales", [])
|
||||||
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})
|
||||||
|
|
||||||
|
|
||||||
def _auto_sync_ctx() -> dict[str, Any] | None:
|
def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
|
||||||
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. 회차가 지나면 화면이 같은 규칙
|
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. kind = sales(매출 실적) / ads(광고비),
|
||||||
(hours·slot, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정. 자동 업데이트가 꺼져 있으면 None."""
|
일정은 실적 설정 "자동 업데이트"(2026-10-26, auto_sync.load_schedules). 회차가 지나면 화면이 같은 규칙
|
||||||
|
(schedule: 간격·요일·시작/끝, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정.
|
||||||
|
자동 업데이트가 꺼져 있거나(env·일정) 회차가 없으면 None."""
|
||||||
from app.timezone import now_kst # noqa: WPS433
|
from app.timezone import now_kst # noqa: WPS433
|
||||||
|
|
||||||
from . import auto_sync # noqa: WPS433
|
from . import auto_sync # noqa: WPS433
|
||||||
|
|
||||||
if not auto_sync.enabled():
|
if not auto_sync.enabled():
|
||||||
return None
|
return None
|
||||||
hours = auto_sync.hour_window()
|
try:
|
||||||
|
sched = auto_sync.load_schedules(store)[0][kind]
|
||||||
|
except Exception: # noqa: BLE001 — DB 오류: 카운트다운만 숨김
|
||||||
|
return None
|
||||||
now = now_kst()
|
now = now_kst()
|
||||||
return {"next_at": auto_sync.next_slot(now, hours).isoformat(), "now": now.isoformat(timespec="milliseconds"),
|
nxt = auto_sync.next_slot(now, sched)
|
||||||
"hours": list(hours), "slot": auto_sync.SLOT_MINUTES}
|
if nxt is None:
|
||||||
|
return None
|
||||||
|
return {"next_at": nxt.isoformat(), "now": now.isoformat(timespec="milliseconds"), "schedule": sched,
|
||||||
|
"label": auto_sync.describe(sched)}
|
||||||
|
|
||||||
|
|
||||||
def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None:
|
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]:
|
||||||
"""매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다."""
|
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
|
||||||
from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433
|
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다."""
|
||||||
|
from . import jobs # noqa: WPS433
|
||||||
|
|
||||||
unit = normalize_unit(request.cookies.get(UNIT_COOKIE))
|
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
||||||
|
return {"kind": kind, "seen": job.id if job else ""}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/update-status")
|
||||||
|
def api_update_status(request: Request, kind: str = "sales") -> JSONResponse:
|
||||||
|
"""지금 그 종류 업데이트가 도는지 · 마지막으로 끝난 업데이트(보는 사람이 시작한 것 제외) — 화면이 20초마다 본다.
|
||||||
|
메모리의 진행 작업만 보고 DB 는 안 읽는다."""
|
||||||
|
from . import jobs # noqa: WPS433
|
||||||
|
|
||||||
|
_, user = common.require_store(request)
|
||||||
|
if kind not in jobs.KINDS:
|
||||||
|
raise HTTPException(status_code=404, detail="알 수 없는 업데이트 종류입니다.")
|
||||||
|
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
||||||
|
return JSONResponse({"kind": kind, "running": jobs.running_job(kind) is not None, "done": job.id if job else "",
|
||||||
|
"user": job.user if job else ""})
|
||||||
|
|
||||||
|
|
||||||
|
def _unit_ctx(store: Any, ctx: dict[str, Any]) -> None:
|
||||||
|
"""매출 단위(원·천원·백만원) — 관리자가 실적 설정 "공통 보기 설정"에서 정하면 모든 사용자에게 같게. 템플릿은 amt(v) 로 그린다."""
|
||||||
|
from .dashboard import UNITS, amount_text, load_unit # noqa: WPS433
|
||||||
|
|
||||||
|
unit = load_unit(store)
|
||||||
ctx["unit"] = unit
|
ctx["unit"] = unit
|
||||||
ctx["unit_label"] = UNITS[unit][2]
|
ctx["unit_label"] = UNITS[unit][2]
|
||||||
ctx["amt"] = lambda v: amount_text(v, unit)
|
ctx["amt"] = lambda v: amount_text(v, unit)
|
||||||
|
|
||||||
|
|
||||||
|
def _colw_ctx(request: Request, ctx: dict[str, Any]) -> None:
|
||||||
|
"""일자별 표 열 너비(2026-10-27) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_colw)에 둔다.
|
||||||
|
manual 이면 표에 perf-colw-manual — performance.js initColWidths 가 머리글 경계 드래그 + 너비 기억(localStorage)."""
|
||||||
|
from .dashboard import COLW_COOKIE, normalize_colw # noqa: WPS433
|
||||||
|
|
||||||
|
ctx["colw"] = normalize_colw(request.cookies.get(COLW_COOKIE))
|
||||||
|
|
||||||
|
|
||||||
@router.get("/ads", response_class=HTMLResponse)
|
@router.get("/ads", response_class=HTMLResponse)
|
||||||
def ads_page(
|
def ads_page(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -190,16 +235,24 @@ def ads_page(
|
|||||||
return g
|
return g
|
||||||
store, user = g
|
store, user = g
|
||||||
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
||||||
from .dashboard import _sales_marketplaces # noqa: WPS433
|
from .dashboard import _sales_marketplaces, total_sales_codes # noqa: WPS433
|
||||||
|
|
||||||
today = today_kst()
|
today = today_kst()
|
||||||
ctx = build_ad_dashboard(
|
ctx = build_ad_dashboard(
|
||||||
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||||
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
sales_codes=total_sales_codes(_sales_marketplaces(store)),
|
||||||
)
|
)
|
||||||
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
_ad_update_ctx(store, user, ctx)
|
||||||
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.
|
_colw_ctx(request, ctx)
|
||||||
|
ctx["col_fold"] = _load_col_fold(store, user).get("ads", [])
|
||||||
|
return render_template(request, "performance/ads.html",
|
||||||
|
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
|
def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> None:
|
||||||
|
"""[광고비 업데이트](2026-10-20, 광고비·틱톡 탭 공통) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
||||||
|
마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차."""
|
||||||
from . import jobs # noqa: WPS433
|
from . import jobs # noqa: WPS433
|
||||||
from .ad_sources.registry import get_source # noqa: WPS433
|
from .ad_sources.registry import get_source # noqa: WPS433
|
||||||
from .ad_sync import last_ad_update_at # noqa: WPS433
|
from .ad_sync import last_ad_update_at # noqa: WPS433
|
||||||
@@ -212,9 +265,35 @@ def ads_page(
|
|||||||
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in configured.items() if ok]
|
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in configured.items() if ok]
|
||||||
ctx["ad_last_update_at"] = last_ad_update_at(store)
|
ctx["ad_last_update_at"] = last_ad_update_at(store)
|
||||||
ctx["ad_running"] = jobs.running_job("ads") is not None
|
ctx["ad_running"] = jobs.running_job("ads") is not None
|
||||||
ctx["auto_sync"] = _auto_sync_ctx()
|
ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
|
||||||
return render_template(request, "performance/ads.html",
|
ctx["update_watch"] = _update_watch("ads", user)
|
||||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
|
||||||
|
|
||||||
|
@router.get("/tiktok", response_class=HTMLResponse)
|
||||||
|
def tiktok_page(
|
||||||
|
request: Request,
|
||||||
|
period: str = "month",
|
||||||
|
d: str | None = None,
|
||||||
|
from_: str | None = Query(None, alias="from"),
|
||||||
|
to: str | None = None,
|
||||||
|
):
|
||||||
|
"""틱톡 탭(2026-11-05) — 일자별 ROAS·광고비·매출(광고 API 값, 읽기 전용). 설정 = 실적 설정 → 광고 API 연동."""
|
||||||
|
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_tiktok_dashboard # noqa: WPS433
|
||||||
|
|
||||||
|
today = today_kst()
|
||||||
|
ctx = build_tiktok_dashboard(store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||||
|
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays())
|
||||||
|
_ad_update_ctx(store, user, ctx)
|
||||||
|
ctx["tiktok_configured"] = any(s["code"] == "tiktok" for s in ctx["ad_sync_sources"])
|
||||||
|
_colw_ctx(request, ctx)
|
||||||
|
return render_template(request, "performance/tiktok.html",
|
||||||
|
{**common.base_ctx(user, active_tab="tiktok", page_title="틱톡"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/settings", response_class=HTMLResponse)
|
@router.get("/settings", response_class=HTMLResponse)
|
||||||
@@ -239,11 +318,63 @@ def settings_page(request: Request):
|
|||||||
)
|
)
|
||||||
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
|
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
|
||||||
ctx["ad_api_ready"] = store.ad_api_ready()
|
ctx["ad_api_ready"] = store.ad_api_ready()
|
||||||
_unit_ctx(request, ctx)
|
ctx["auto_sync_settings"] = _auto_sync_settings_ctx(store) # 카드는 관리자에게만(템플릿)
|
||||||
|
_unit_ctx(store, ctx)
|
||||||
|
_colw_ctx(request, ctx)
|
||||||
return render_template(request, "performance/settings.html",
|
return render_template(request, "performance/settings.html",
|
||||||
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
|
def _auto_sync_settings_ctx(store: Any) -> dict[str, Any]:
|
||||||
|
"""실적 설정 "자동 업데이트" 카드(2026-10-26) — 종류마다 일정·다음 회차, 011 적용 여부, env 로 꺼졌는지."""
|
||||||
|
from app.timezone import now_kst # noqa: WPS433
|
||||||
|
|
||||||
|
from . import auto_sync # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
schedules, ready = auto_sync.load_schedules(store)
|
||||||
|
error = ""
|
||||||
|
except Exception as exc: # noqa: BLE001 — DB 오류여도 설정 화면은 뜬다
|
||||||
|
schedules, ready, error = auto_sync.normalize(None), True, f"일정을 읽지 못했습니다({type(exc).__name__}) — 기본 일정을 보여 줍니다."
|
||||||
|
now = now_kst()
|
||||||
|
kinds = []
|
||||||
|
for k in auto_sync.KINDS:
|
||||||
|
nxt = auto_sync.next_slot(now, schedules[k])
|
||||||
|
kinds.append({"kind": k, "name": auto_sync.KIND_NAMES[k], "schedule": schedules[k],
|
||||||
|
"label": auto_sync.describe(schedules[k]), "next_at": nxt.isoformat() if nxt else ""})
|
||||||
|
return {"kinds": kinds, "ready": ready, "env_on": auto_sync.enabled(), "days": auto_sync.sync_days(),
|
||||||
|
"error": error, "weekdays": auto_sync.WEEKDAYS, "step": auto_sync.INTERVAL_STEP,
|
||||||
|
"max": auto_sync.INTERVAL_MAX}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/auto-sync-schedule")
|
||||||
|
def api_auto_sync_schedule(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""자동 업데이트 일정 저장(2026-10-26, 관리자, 마이그레이션 011) — {sales: 일정, ads: 일정}. 스레드가 1분 안에 반영."""
|
||||||
|
from app.timezone import now_kst # noqa: WPS433
|
||||||
|
|
||||||
|
from . import auto_sync # noqa: WPS433
|
||||||
|
from .db import SettingsMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request, admin=True)
|
||||||
|
value = {}
|
||||||
|
for k in auto_sync.KINDS:
|
||||||
|
try:
|
||||||
|
value[k] = auto_sync.validate_schedule(payload.get(k))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=f"{auto_sync.KIND_NAMES[k]}: {exc}") from None
|
||||||
|
try:
|
||||||
|
store.set_setting(auto_sync.SETTING_KEY, value, user=user.get("email", ""))
|
||||||
|
except SettingsMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail="일정을 저장하려면 performance_db 마이그레이션 011"
|
||||||
|
"(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None
|
||||||
|
now = now_kst()
|
||||||
|
out = {}
|
||||||
|
for k, sched in value.items():
|
||||||
|
nxt = auto_sync.next_slot(now, sched)
|
||||||
|
out[k] = {"schedule": sched, "label": auto_sync.describe(sched), "next_at": nxt.isoformat() if nxt else ""}
|
||||||
|
return JSONResponse({"ok": True, "env_on": auto_sync.enabled(), **out})
|
||||||
|
|
||||||
|
|
||||||
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
|
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
|
||||||
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
|
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
|
||||||
from .ad_sources.registry import all_sources # noqa: WPS433
|
from .ad_sources.registry import all_sources # noqa: WPS433
|
||||||
@@ -859,6 +990,77 @@ def api_marketplace_order(request: Request, payload: dict[str, Any] = Body(...))
|
|||||||
return JSONResponse({"ok": True})
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/hidden-marketplaces")
|
||||||
|
def api_hidden_marketplaces(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""매출 실적 표 열 숨기기(2026-11-02, 관리자, 마이그레이션 011) — 체크한 코드 전부. 모든 사용자의 표에 적용."""
|
||||||
|
from .dashboard import CAFE24_EX_GB, HIDDEN_SETTING # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request, admin=True)
|
||||||
|
raw = payload.get("codes")
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
raise HTTPException(status_code=400, detail="숨길 쇼핑몰 목록이 필요합니다.")
|
||||||
|
known = {m["code"] for m in store.list_marketplaces()} | {CAFE24_EX_GB}
|
||||||
|
codes = sorted({str(c) for c in raw} & known)
|
||||||
|
_save_shared_setting(store, HIDDEN_SETTING, codes, user)
|
||||||
|
return JSONResponse({"ok": True, "codes": codes})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/display-unit")
|
||||||
|
def api_display_unit(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""매출 단위(2026-11-02, 관리자, 마이그레이션 011) — won·thousand·million. 모든 사용자의 매출 실적 화면에 적용."""
|
||||||
|
from .dashboard import UNIT_SETTING, UNITS # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request, admin=True)
|
||||||
|
unit = payload.get("unit")
|
||||||
|
if not isinstance(unit, str) or unit not in UNITS:
|
||||||
|
raise HTTPException(status_code=400, detail="알 수 없는 매출 단위입니다.")
|
||||||
|
_save_shared_setting(store, UNIT_SETTING, unit, user)
|
||||||
|
return JSONResponse({"ok": True, "unit": unit})
|
||||||
|
|
||||||
|
|
||||||
|
COL_FOLD_KINDS = ("sales", "ads")
|
||||||
|
|
||||||
|
|
||||||
|
def _col_fold_key(user: dict[str, Any]) -> str:
|
||||||
|
"""접은 열(2026-11-06) — 사람마다 perf_settings 한 줄. key 는 64자 제한이라 이메일을 해시로(updated_by 에 이메일)."""
|
||||||
|
import hashlib # noqa: WPS433
|
||||||
|
|
||||||
|
return "col_fold:" + hashlib.sha1(str(user.get("email", "")).lower().encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _load_col_fold(store: Any, user: dict[str, Any]) -> dict[str, list[str]]:
|
||||||
|
"""{sales: [열 코드], ads: [...]} — 저장 없음·011 미적용·DB 오류면 빈 값(전부 펼침)."""
|
||||||
|
try:
|
||||||
|
value = store.get_setting(_col_fold_key(user))
|
||||||
|
except Exception: # noqa: BLE001 — 접기만 못 함
|
||||||
|
return {}
|
||||||
|
return value if isinstance(value, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/my-col-fold")
|
||||||
|
def api_my_col_fold(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""일자별 표에서 접은 열(2026-11-06, 모듈 권한자 누구나) — 로그인한 사람 본인 화면에만 적용, 매출 실적·광고비 따로."""
|
||||||
|
store, user = common.require_store(request)
|
||||||
|
kind, cols = payload.get("kind"), payload.get("cols")
|
||||||
|
if kind not in COL_FOLD_KINDS or not isinstance(cols, list) or len(cols) > 200:
|
||||||
|
raise HTTPException(status_code=400, detail="접은 열 목록이 올바르지 않습니다.")
|
||||||
|
cols = sorted({c for c in cols if isinstance(c, str) and 0 < len(c) <= 64 and c != "label"})
|
||||||
|
value = _load_col_fold(store, user)
|
||||||
|
value[kind] = cols
|
||||||
|
_save_shared_setting(store, _col_fold_key(user), value, user)
|
||||||
|
return JSONResponse({"ok": True, "cols": cols})
|
||||||
|
|
||||||
|
|
||||||
|
def _save_shared_setting(store: Any, key: str, value: Any, user: dict[str, Any]) -> None:
|
||||||
|
from .db import SettingsMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
store.set_setting(key, value, user=user.get("email", ""))
|
||||||
|
except SettingsMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail="저장하려면 performance_db 마이그레이션 011"
|
||||||
|
"(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None
|
||||||
|
|
||||||
|
|
||||||
@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)
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{# 광고비 업데이트(2026-10-20, 광고비·틱톡 탭 공통) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
|
||||||
|
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
|
||||||
|
{% if ad_sync_sources %}
|
||||||
|
<div class="perf-update">
|
||||||
|
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
|
||||||
|
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
||||||
|
{% if auto_sync %}
|
||||||
|
<span class="perf-muted perf-next-update" id="perf-next-update" title="광고비 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
|
||||||
|
{% endif %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
|
||||||
|
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
|
||||||
|
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{# 기간 이동(2026-11-02, 매출 실적·광고비 공통) — 날짜 바로 좌우에 화살표 이미지(SVG, 글자 높이), 글자 버튼 없음 #}
|
||||||
|
<div class="perf-nav">
|
||||||
|
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}" aria-label="{{ period.prev_label }}"><svg viewBox="0 0 10 16" aria-hidden="true"><path d="M8 1.5 2 8l6 6.5"/></svg></a>
|
||||||
|
<span class="perf-nav-label">{{ period.label }}</span>
|
||||||
|
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}" aria-label="{{ period.next_label }}"><svg viewBox="0 0 10 16" aria-hidden="true"><path d="M2 1.5 8 8l-6 6.5"/></svg></a>
|
||||||
|
</div>
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
{# 실적 모듈 탭 — [매출 실적] [광고비] [틱톡] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||||
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||||
@@ -9,6 +9,9 @@
|
|||||||
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
|
<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' }}">
|
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||||
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||||
|
<a class="perf-tab perf-tab-tiktok{% if active_tab == 'tiktok' %} is-active{% endif %}" href="/performance/tiktok"
|
||||||
|
role="tab" aria-selected="{{ 'true' if active_tab == 'tiktok' else 'false' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">music_note</span>틱톡</a>
|
||||||
</div>
|
</div>
|
||||||
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
|
<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 '수수료 설정' }}">
|
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027a" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
|
||||||
|
|
||||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||||
@@ -24,11 +24,7 @@
|
|||||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="perf-nav">
|
{% include "performance/_period_nav.html" %}
|
||||||
<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 %}>
|
<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 type="hidden" name="period" value="custom" />
|
||||||
@@ -38,21 +34,7 @@
|
|||||||
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(매출과 같은 회차)
|
{% include "performance/_ad_update.html" %}
|
||||||
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
|
|
||||||
{% if ad_sync_sources %}
|
|
||||||
<div class="perf-update">
|
|
||||||
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
|
|
||||||
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
|
||||||
{% if auto_sync %}
|
|
||||||
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다(매출과 같은 시각)">다음 업데이트까지 <b>—</b></span>
|
|
||||||
{% endif %}
|
|
||||||
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
|
|
||||||
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
|
|
||||||
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
||||||
|
|
||||||
@@ -61,27 +43,25 @@
|
|||||||
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
|
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<!-- ── KPI ── -->
|
<!-- ── KPI — 한 줄(2026-10-30, 매출 실적처럼): 광고비 · 매출 대비 광고비 · 연 누적 ── -->
|
||||||
<div class="perf-kpis">
|
<div class="perf-kpi-line">
|
||||||
{% for k in kpis %}
|
{% for k in kpis %}
|
||||||
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
<span class="perf-kpi-item">
|
||||||
<div class="perf-kpi-label">{{ k.label }}</div>
|
<span class="perf-muted">{{ k.label }}</span>
|
||||||
{% if k.key == 'ratio' %}
|
{% if k.key == 'ratio' %}
|
||||||
<div class="perf-kpi-value">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</div>
|
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</b>
|
||||||
<div class="perf-kpi-delta"><span class="perf-muted">{{ k.note }}</span></div>
|
<span class="perf-muted">{{ k.note }}</span>
|
||||||
{% else %}
|
{% else %}
|
||||||
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
|
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
|
||||||
<div class="perf-kpi-delta">
|
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
{% else %}
|
||||||
{% else %}
|
{% set up = k.delta > 0 %}
|
||||||
{% 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 %}">
|
||||||
<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>
|
||||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
{% endif %}
|
||||||
|
</span>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -99,12 +79,13 @@
|
|||||||
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
||||||
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
||||||
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
|
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
|
||||||
<table class="perf-table perf-main perf-autofit">
|
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
|
||||||
|
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="ads" data-cfold-kind="ads" data-col-fold="{{ (col_fold or []) | tojson | forceescape }}">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||||
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 ROAS(구매 전환값 ÷ 지출 금액){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
<th class="perf-th-total" data-col="total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" data-col="{{ c }}" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 ROAS(구매 전환값 ÷ 지출 금액){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th data-col="{{ c }}" title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -113,6 +94,7 @@
|
|||||||
<th class="perf-td-label" scope="row">
|
<th class="perf-td-label" scope="row">
|
||||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||||
</th>
|
</th>
|
||||||
|
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
|
||||||
{% for c in codes %}
|
{% for c in codes %}
|
||||||
{% set v = r.cells[c].gross %}
|
{% set v = r.cells[c].gross %}
|
||||||
{% if r.kind == 'day' and not migration_needed %}
|
{% if r.kind == 'day' and not migration_needed %}
|
||||||
@@ -126,7 +108,6 @@
|
|||||||
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -237,8 +218,9 @@
|
|||||||
"period_label": period.label,
|
"period_label": period.label,
|
||||||
"empty_text": "기간 내 광고비가 없습니다.",
|
"empty_text": "기간 내 광고비가 없습니다.",
|
||||||
"upload_channels": upload_channels,
|
"upload_channels": upload_channels,
|
||||||
"auto_sync": auto_sync
|
"auto_sync": auto_sync,
|
||||||
|
"update_watch": update_watch
|
||||||
} | tojson }}</script>
|
} | tojson }}</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20261027a" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261105a" 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=20261027a" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% 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>
|
||||||
@@ -42,11 +42,7 @@
|
|||||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="perf-nav">
|
{% include "performance/_period_nav.html" %}
|
||||||
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
|
|
||||||
<span class="perf-nav-label">{{ period.label }}</span>
|
|
||||||
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form class="perf-custom" id="perf-custom" method="get" action="/performance/"{% if period_kind != 'custom' %} hidden{% endif %}>
|
<form class="perf-custom" id="perf-custom" method="get" action="/performance/"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||||
<input type="hidden" name="period" value="custom" />
|
<input type="hidden" name="period" value="custom" />
|
||||||
@@ -82,7 +78,7 @@
|
|||||||
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
||||||
{% if auto_sync %}
|
{% if auto_sync %}
|
||||||
{# 다음 자동 업데이트까지 남은 시간 — 초 단위로 실시간(performance.js initNextUpdate, 2026-10-19) #}
|
{# 다음 자동 업데이트까지 남은 시간 — 초 단위로 실시간(performance.js initNextUpdate, 2026-10-19) #}
|
||||||
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다">다음 업데이트까지 <b>—</b></span>
|
<span class="perf-muted perf-next-update" id="perf-next-update" title="매출 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{# 업데이트 중에도 누를 수 있다 — 진행 중인 업데이트(수동·자동)의 진행 창을 다시 연다(2026-10-19) #}
|
{# 업데이트 중에도 누를 수 있다 — 진행 중인 업데이트(수동·자동)의 진행 창을 다시 연다(2026-10-19) #}
|
||||||
<button type="button" class="erp-btn erp-btn-primary{% if running %} is-running{% endif %}" id="perf-sync-btn"
|
<button type="button" class="erp-btn erp-btn-primary{% if running %} is-running{% endif %}" id="perf-sync-btn"
|
||||||
@@ -115,6 +111,14 @@
|
|||||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
{% if k.yoy_cmp %}
|
||||||
|
{% if k.yoy_delta is none %}<span class="perf-muted">{{ k.yoy_cmp }} 비교 없음</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="perf-delta {% if k.yoy_delta == 0 %}is-flat{% elif k.yoy_delta > 0 %}is-up{% else %}is-down{% endif %}">
|
||||||
|
{% if k.yoy_delta > 0 %}▲{% elif k.yoy_delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.yoy_delta | abs) }}%</span>
|
||||||
|
<span class="perf-muted">{{ k.yoy_cmp }} 대비</span>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|
||||||
@@ -137,18 +141,19 @@
|
|||||||
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
||||||
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
||||||
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#}
|
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#}
|
||||||
<table class="perf-table perf-main perf-autofit">
|
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
|
||||||
|
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="sales" data-cfold-kind="sales" data-col-fold="{{ (col_fold or []) | tojson | forceescape }}">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||||
|
<th class="perf-th-total" data-col="total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||||
{#- 그룹(2026-10-22) — 그룹 열 = 보이는 하위 쇼핑몰 합계, ⊟/⊞ 로 하위 열 접기/펴기(이 브라우저에 기억, 펼치고 접을 때 애니메이션).
|
{#- 그룹(2026-10-22) — 그룹 열 = 보이는 하위 쇼핑몰 합계, ⊟/⊞ 로 하위 열 접기/펴기(이 브라우저에 기억, 펼치고 접을 때 애니메이션).
|
||||||
하위 열은 .perf-gc 로 내용을 감싼다 — 접을 때 그 너비를 0 으로 줄여 열이 부드럽게 닫힌다. is-glast = 그룹의 마지막 하위 열(오른쪽 묶음 선) -#}
|
하위 열은 .perf-gc 로 내용을 감싼다 — 접을 때 그 너비를 0 으로 줄여 열이 부드럽게 닫힌다. is-glast = 그룹의 마지막 하위 열(오른쪽 묶음 선) -#}
|
||||||
{% for col in cols %}{% set c = col.code %}
|
{% for col in cols %}{% set c = col.code %}
|
||||||
{% set glast = col.kind == 'child' and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
{% set sub = col.kind == 'child' or (col.kind == 'diff' and col.group) %}{% set glast = sub and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
||||||
{% if col.kind == 'group' %}<th class="perf-th-group" data-group-head="{{ c }}" title="{{ names[c] }} — 하위 쇼핑몰 {{ group_members[c] | length }}곳 매출 합계"><span class="perf-gh"><button type="button" class="perf-gtoggle" data-group-toggle="{{ c }}" aria-expanded="true" aria-label="{{ short_names[c] }} 하위 쇼핑몰 접기" title="하위 쇼핑몰 접기/펴기"><svg viewBox="0 0 18 18" width="18" height="18" aria-hidden="true"><rect class="g-box" x="1" y="1" width="16" height="16" rx="4"/><path class="g-h" d="M5 9h8"/><path class="g-v" d="M9 5v8"/></svg></button><span>{{ short_names[c] }}</span></span></th>
|
{% if col.kind == 'group' %}<th class="perf-th-group" data-col="{{ c }}" data-group-head="{{ c }}" title="{{ names[c] }} — 하위 쇼핑몰 {{ group_members[c] | length }}곳 매출 합계"><span class="perf-gh"><button type="button" class="perf-gtoggle" data-group-toggle="{{ c }}" aria-expanded="true" aria-label="{{ short_names[c] }} 하위 쇼핑몰 접기" title="하위 쇼핑몰 접기/펴기"><svg viewBox="0 0 18 18" width="18" height="18" aria-hidden="true"><rect class="g-box" x="1" y="1" width="16" height="16" rx="4"/><path class="g-h" d="M5 9h8"/><path class="g-v" d="M9 5v8"/></svg></button><span>{{ short_names[c] }}</span></span></th>
|
||||||
{% else %}<th{% if col.kind == 'child' %} class="perf-th-child{% if glast %} is-glast{% endif %}" data-group-child="{{ col.group }}"{% endif %} title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{% if col.kind == 'child' %}<div class="perf-gc">{% endif %}{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}{% if col.kind == 'child' %}</div>{% endif %}</th>{% endif %}
|
{% else %}<th data-col="{{ c }}"{% if sub %} class="perf-th-child{% if glast %} is-glast{% endif %}" data-group-child="{{ col.group }}"{% endif %} title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{% if sub %}<div class="perf-gc">{% endif %}{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}{% if sub %}</div>{% endif %}</th>{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -157,14 +162,18 @@
|
|||||||
<th class="perf-td-label" scope="row">
|
<th class="perf-td-label" scope="row">
|
||||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||||
</th>
|
</th>
|
||||||
|
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
|
||||||
{% for col in cols %}
|
{% for col in cols %}
|
||||||
{% set c = col.code %}
|
{% set c = col.code %}
|
||||||
{% set m = r.cells[c] %}
|
{% set m = r.cells[c] %}
|
||||||
{% set glast = col.kind == 'child' and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
{% set sub = col.kind == 'child' or (col.kind == 'diff' and col.group) %}{% set glast = sub and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
||||||
{% set gattr %}{% if col.kind == 'child' %} data-group-child="{{ col.group }}"{% endif %}{% endset %}
|
{% set gattr %}{% if sub %} data-group-child="{{ col.group }}"{% endif %}{% endset %}
|
||||||
{% set gc0 %}{% if col.kind == 'child' %}<div class="perf-gc">{% endif %}{% endset %}{% set gc1 %}{% if col.kind == 'child' %}</div>{% endif %}{% endset %}
|
{% set gc0 %}{% if sub %}<div class="perf-gc">{% endif %}{% endset %}{% set gc1 %}{% if sub %}</div>{% endif %}{% endset %}
|
||||||
{% if col.kind == 'group' %}
|
{% if col.kind == 'group' %}
|
||||||
<td class="perf-num perf-td-group" data-group-cell="{{ c }}">{{ m3(m) }}</td>
|
<td class="perf-num perf-td-group" data-group-cell="{{ c }}">{{ m3(m) }}</td>
|
||||||
|
{% elif col.kind == 'diff' %}{#- 카페24(실적) = 카페24(전체) − 공동구매(dashboard._cafe24_real_column) — 계산 열이라 클릭·메모 없음, 광고비 줄은 카페24(전체)와 같음 -#}
|
||||||
|
{%- set b = r.cells[col.base] %}{#- 일 행 = 공동구매 칸 저장 때 performance.js 가 base(카페24 총매출,수수료,차감) − 새 값으로 바로 바꿈 -#}
|
||||||
|
<td class="perf-num{% if glast %} is-glast{% endif %}"{{ gattr }}{% if r.kind == 'day' and col.minus %} data-diff-minus="{{ col.minus }}" data-base="{{ b.gross }},{{ b.commission }},{{ b.net }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[col.base]) }}{{ gc1 }}</td>
|
||||||
{% elif r.kind == 'day' and c in manual_codes %}
|
{% elif r.kind == 'day' and c in manual_codes %}
|
||||||
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
|
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
|
||||||
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
|
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
|
||||||
@@ -178,7 +187,6 @@
|
|||||||
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}{% if r.kind == 'day' %} data-memo-code="{{ c }}" data-date="{{ r.date }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</td>
|
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}{% if r.kind == 'day' %} data-memo-code="{{ c }}" data-date="{{ r.date }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -214,7 +222,7 @@
|
|||||||
<tbody>
|
<tbody>
|
||||||
{% for r in month.rows %}
|
{% for r in month.rows %}
|
||||||
<tr>
|
<tr>
|
||||||
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
|
<th class="perf-td-label" scope="row">{{ summary_names[r.code] }}</th>
|
||||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||||
<td class="perf-num">{{ won(r.commission) }}</td>
|
<td class="perf-num">{{ won(r.commission) }}</td>
|
||||||
<td class="perf-num">{{ won(r.net) }}</td>
|
<td class="perf-num">{{ won(r.net) }}</td>
|
||||||
@@ -273,6 +281,7 @@
|
|||||||
<p class="perf-foot perf-muted">
|
<p class="perf-foot perf-muted">
|
||||||
매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며
|
매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며
|
||||||
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
|
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
|
||||||
|
일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -288,8 +297,9 @@
|
|||||||
"today": today,
|
"today": today,
|
||||||
"unit": unit,
|
"unit": unit,
|
||||||
"manual_upload_names": manual_upload_names,
|
"manual_upload_names": manual_upload_names,
|
||||||
"auto_sync": auto_sync
|
"auto_sync": auto_sync,
|
||||||
|
"update_watch": update_watch
|
||||||
} | tojson }}</script>
|
} | tojson }}</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20261027a" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261105a" 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=20261027a" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
|
||||||
|
|
||||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||||
|
|
||||||
@@ -142,11 +142,32 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #}
|
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만 #}
|
||||||
<div class="erp-card perf-card" id="perf-view-opts">
|
<div class="erp-card perf-card" id="perf-view-opts">
|
||||||
<div class="perf-card-head">
|
<div class="perf-card-head">
|
||||||
<h2 class="perf-h">보기 설정</h2>
|
<h2 class="perf-h">보기 설정</h2>
|
||||||
<span class="perf-muted">매출 실적 화면의 금액 단위입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
|
<span class="perf-muted">매출 실적·광고비 화면을 보는 방식입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
|
||||||
|
</div>
|
||||||
|
{# 표 열 너비(2026-10-27, 쿠키 perf_colw) — 매출 실적·광고비 일자별 표. 수동 = 머리글 오른쪽 경계 드래그, 너비는 이 브라우저 localStorage(perf_colw_sales/ads) #}
|
||||||
|
<div class="perf-opt-row">
|
||||||
|
<span class="perf-opt-label">표 열 너비</span>
|
||||||
|
<div class="perf-quick" role="radiogroup" aria-label="표 열 너비">
|
||||||
|
{% for k, label in [('auto', '자동(글자 길이)'), ('manual', '수동 조절')] %}
|
||||||
|
<button type="button" class="perf-seg{% if colw == k %} is-active{% endif %}" role="radio"
|
||||||
|
aria-checked="{{ 'true' if colw == k else 'false' }}" data-colw="{{ k }}">{{ label }}</button>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<span class="perf-muted" id="perf-colw-help">{% if colw == 'manual' %}매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.{% else %}열 너비가 글자 길이에 맞춰 자동으로 정해집니다.{% endif %}</span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" id="perf-colw-reset"{% if colw != 'manual' %} hidden{% endif %}>조절한 너비 초기화</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if is_admin %}
|
||||||
|
{# 공통 보기 설정(2026-11-02, 관리자, 마이그레이션 011 perf_settings) — 매출 단위·열 숨기기, 모든 사용자에게 적용 #}
|
||||||
|
<div class="erp-card perf-card" id="perf-shared-view">
|
||||||
|
<div class="perf-card-head">
|
||||||
|
<h2 class="perf-h">공통 보기 설정</h2>
|
||||||
|
<span class="perf-muted">모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="perf-opt-row">
|
<div class="perf-opt-row">
|
||||||
<span class="perf-opt-label">매출 단위</span>
|
<span class="perf-opt-label">매출 단위</span>
|
||||||
@@ -159,7 +180,74 @@
|
|||||||
<span class="perf-muted" id="perf-unit-example">예: 2,475,300원 →
|
<span class="perf-muted" id="perf-unit-example">예: 2,475,300원 →
|
||||||
{% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}</span>
|
{% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="perf-opt-row">
|
||||||
|
<span class="perf-opt-label">숨길 쇼핑몰</span>
|
||||||
|
<div class="perf-hide-list">
|
||||||
|
{% for m in hide_options %}
|
||||||
|
<label class="perf-check"><input type="checkbox" data-hide="{{ m.code }}"{% if m.code in hidden_codes %} checked{% endif %} /> {{ m.name }}</label>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<span class="perf-muted">체크한 쇼핑몰은 일자별 표에서 열만 숨겨집니다. 일 합계·그래프·누적 금액은 그대로입니다.</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if is_admin and auto_sync_settings %}
|
||||||
|
{# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위,
|
||||||
|
기본 30분). [저장] = PUT /api/auto-sync-schedule, 스레드(auto_sync.py)가 1분 안에 반영. #}
|
||||||
|
{% set au = auto_sync_settings %}
|
||||||
|
{% macro time_select(part, value, label) -%}
|
||||||
|
{%- set hh, mm = value.split(':') -%}
|
||||||
|
<select class="erp-input perf-auto-time" data-t="{{ part }}-h" aria-label="{{ label }} 시">
|
||||||
|
{%- for h in range(24) %}<option value="{{ '%02d' % h }}"{% if '%02d' % h == hh %} selected{% endif %}>{{ '%02d' % h }}시</option>{% endfor -%}
|
||||||
|
</select><select class="erp-input perf-auto-time" data-t="{{ part }}-m" aria-label="{{ label }} 분">
|
||||||
|
{%- for m in range(0, 60, au.step) %}<option value="{{ '%02d' % m }}"{% if '%02d' % m == mm %} selected{% endif %}>{{ '%02d' % m }}분</option>{% endfor -%}
|
||||||
|
</select>
|
||||||
|
{%- endmacro %}
|
||||||
|
<div class="erp-card perf-card" id="perf-auto-sync">
|
||||||
|
<div class="perf-card-head">
|
||||||
|
<h2 class="perf-h">자동 업데이트</h2>
|
||||||
|
<span class="perf-muted">매출 실적·광고비를 고른 요일의 시작 ~ 끝 시각 사이에 정한 간격으로 자동으로 가져옵니다(오늘 포함 최근 {{ au.days }}일).
|
||||||
|
시각·간격은 {{ au.step }}분 단위이며, 저장하면 1분 안에 적용됩니다.</span>
|
||||||
|
</div>
|
||||||
|
{% if not au.env_on %}<div class="perf-notice is-warn">서버 환경변수 PERFORMANCE_AUTO_SYNC=false 로 자동 업데이트가 꺼져 있습니다 — 일정은 저장되지만 돌지 않습니다.</div>{% endif %}
|
||||||
|
{% if not au.ready %}<div class="perf-notice is-warn">일정 저장 표가 아직 없습니다. performance_db 마이그레이션 011
|
||||||
|
(scripts/sql/performance_db_011_settings.sql)을 적용해야 저장할 수 있습니다. 지금은 기본 일정(아래)으로 돕니다.</div>{% endif %}
|
||||||
|
{% if au.error %}<div class="perf-notice is-warn">{{ au.error }}</div>{% endif %}
|
||||||
|
<div class="perf-auto-rows">
|
||||||
|
{% for k in au.kinds %}{% set sc = k.schedule %}
|
||||||
|
<div class="perf-auto-row{% if not sc.enabled %} is-off{% endif %}" data-kind="{{ k.kind }}">
|
||||||
|
<div class="perf-auto-name">
|
||||||
|
<b>{{ k.name }}</b>
|
||||||
|
<label class="perf-auto-on"><input type="checkbox" data-f="enabled"{% if sc.enabled %} checked{% endif %} /> 사용</label>
|
||||||
|
</div>
|
||||||
|
<div class="perf-auto-fields">
|
||||||
|
<div class="perf-auto-field"><span class="perf-opt-label">요일</span>
|
||||||
|
<span class="perf-auto-days">
|
||||||
|
{%- for w in au.weekdays %}<label class="perf-day{% if loop.index0 == 5 %} is-sat{% elif loop.index0 == 6 %} is-sun{% endif %}"><input type="checkbox" data-day="{{ loop.index0 }}"{% if loop.index0 in sc.days %} checked{% endif %} /><span>{{ w }}</span></label>{% endfor -%}
|
||||||
|
</span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-days="all">매일</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-days="weekday">평일</button>
|
||||||
|
</div>
|
||||||
|
<div class="perf-auto-field"><span class="perf-opt-label">시간</span>
|
||||||
|
{{ time_select('start', sc.start, k.name ~ ' 시작') }}<span class="perf-muted">부터</span>
|
||||||
|
{{ time_select('end', sc.end, k.name ~ ' 끝') }}<span class="perf-muted">까지</span>
|
||||||
|
</div>
|
||||||
|
<div class="perf-auto-field"><span class="perf-opt-label">간격</span>
|
||||||
|
<input class="erp-input perf-auto-interval" type="number" min="{{ au.step }}" max="{{ au.max }}" step="{{ au.step }}"
|
||||||
|
data-f="interval" value="{{ sc.interval }}" aria-label="{{ k.name }} 간격(분)" /><span class="perf-muted">분마다</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="perf-muted perf-auto-next" data-next>{{ k.label }}{% if k.next_at %} · 다음 {{ k.next_at[5:16] | replace('T', ' ') }}{% endif %}</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<div class="perf-auto-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" id="perf-auto-save">저장</button>
|
||||||
|
<span class="perf-muted" id="perf-auto-msg" role="status"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
|
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
|
||||||
@@ -167,8 +255,8 @@
|
|||||||
<div class="erp-card perf-card" id="perf-ad-sources">
|
<div class="erp-card perf-card" id="perf-ad-sources">
|
||||||
<div class="perf-card-head">
|
<div class="perf-card-head">
|
||||||
<h2 class="perf-h">광고 API 연동</h2>
|
<h2 class="perf-h">광고 API 연동</h2>
|
||||||
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
|
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 틱톡은 틱톡 탭에서만 보입니다(매출 실적·광고비 탭 합계 제외). 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
|
||||||
설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
|
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span>
|
||||||
</div>
|
</div>
|
||||||
{% if not ad_api_ready %}
|
{% if not ad_api_ready %}
|
||||||
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
|
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
|
||||||
@@ -259,4 +347,4 @@
|
|||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20261027a" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
|
||||||
|
|
||||||
|
{%- macro won(v) -%}
|
||||||
|
{%- if v is none -%}<span class="perf-na"></span>
|
||||||
|
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||||
|
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
||||||
|
{%- endmacro -%}
|
||||||
|
{%- macro pct(p) -%}{%- if p is none -%}<span class="perf-zero">–</span>{%- else -%}{{ "{:,}".format(p) }}%{%- endif -%}{%- endmacro -%}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{#- 틱톡(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프. 값은 광고 API 만(읽기 전용, 직접 입력 없음). 매출 실적·광고비 탭 합계에는 안 들어간다. -#}
|
||||||
|
<section class="perf perf-ads perf-tiktok" 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>
|
||||||
|
|
||||||
|
{% include "performance/_period_nav.html" %}
|
||||||
|
|
||||||
|
<form class="perf-custom" id="perf-custom" method="get" action="/performance/tiktok"{% 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>
|
||||||
|
|
||||||
|
{% include "performance/_ad_update.html" %}
|
||||||
|
</div>
|
||||||
|
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
||||||
|
|
||||||
|
{% if migration_needed %}
|
||||||
|
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005·006 을 적용해야 합니다.</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if not tiktok_configured %}
|
||||||
|
<div class="perf-notice is-warn">틱톡 API 가 아직 설정되지 않았습니다. {% if is_admin %}<a href="/performance/settings#perf-ad-sources">실적 설정 → 광고 API 연동</a>에서{% else %}관리자가 실적 설정 → 광고 API 연동에서{% endif %} 틱톡 [설정]을 입력하면 데이터가 들어옵니다.</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="perf-kpi-line">
|
||||||
|
{% for k in kpis %}
|
||||||
|
<span class="perf-kpi-item">
|
||||||
|
<span class="perf-muted">{{ k.label }}</span>
|
||||||
|
{% if k.key == 'roas' %}
|
||||||
|
<b class="perf-kpi-line-value is-sub">{{ pct(k.pct) }}</b>
|
||||||
|
{% else %}
|
||||||
|
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
|
||||||
|
{% 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 %}
|
||||||
|
{% endif %}
|
||||||
|
</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head">
|
||||||
|
<h2 class="perf-h">{% if period_kind == 'year' %}월별 틱톡 실적{% else %}일자별 틱톡 실적{% endif %}</h2>
|
||||||
|
</div>
|
||||||
|
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
||||||
|
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="tiktok">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||||
|
<th data-col="roas">ROAS</th>
|
||||||
|
<th data-col="spend">광고비</th>
|
||||||
|
<th data-col="sales">매출</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">
|
||||||
|
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||||
|
</th>
|
||||||
|
<td class="perf-num">{{ pct(r.roas) }}</td>
|
||||||
|
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.spend.gross) }}</span></td>
|
||||||
|
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.sales.gross) }}</span></td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="perf-grid2">
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 매출 추이</h2></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">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
|
||||||
|
<div class="perf-chart" id="perf-chart-daily2"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="perf-table perf-year">
|
||||||
|
<thead><tr><th class="perf-th-label">월</th><th>ROAS</th><th>광고비</th><th>매출</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in year.rows %}
|
||||||
|
<tr class="{% if r.future %}is-future{% endif %}">
|
||||||
|
<th class="perf-td-label" scope="row">{{ r.label }}</th>
|
||||||
|
<td class="perf-num">{% if not r.future %}{{ pct(r.roas) }}{% endif %}</td>
|
||||||
|
<td class="perf-num">{{ won(r.spend) }}</td>
|
||||||
|
<td class="perf-num">{{ won(r.sales) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr class="perf-row-total">
|
||||||
|
<th class="perf-td-label" scope="row">합계</th>
|
||||||
|
<td class="perf-num">{{ pct(year.roas) }}</td>
|
||||||
|
<td class="perf-num">{{ won(year.spend) }}</td>
|
||||||
|
<td class="perf-num">{{ won(year.sales) }}</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="perf-foot perf-muted">
|
||||||
|
틱톡 광고 API 값입니다. 매출 = 광고에 귀속된 구매금액(웹 구매 + 틱톡샵, 틱톡샵 ID 를 넣으면 GMV Max 포함)이며 틱톡샵 전체 판매액과는 다를 수 있습니다.
|
||||||
|
ROAS = 매출 ÷ 광고비 × 100, 외화 계정은 그날 환율로 원화로 바꿉니다. 이 값은 매출 실적·광고비 탭 합계에 들어가지 않습니다.
|
||||||
|
[광고비 업데이트]는 설정된 광고 API 전부를 함께 가져옵니다.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script type="application/json" id="perf-data">{{ {
|
||||||
|
"period_kind": period_kind,
|
||||||
|
"today": today,
|
||||||
|
"period_start": period.start.isoformat(),
|
||||||
|
"period_end": period.end.isoformat(),
|
||||||
|
"period_label": period.label,
|
||||||
|
"daily": chart_sales,
|
||||||
|
"daily2": chart_spend,
|
||||||
|
"empty_text": "기간 내 틱톡 데이터가 없습니다.",
|
||||||
|
"auto_sync": auto_sync,
|
||||||
|
"update_watch": update_watch
|
||||||
|
} | tojson }}</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
|
||||||
@@ -120,12 +120,12 @@ class _Store:
|
|||||||
def test_ad_dashboard_month():
|
def test_ad_dashboard_month():
|
||||||
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||||
sales_codes=["cafe24"])
|
sales_codes=["cafe24"])
|
||||||
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
assert ctx["codes"] == ["google", "meta", "kakao_pf", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||||
"gsshop", "elevenst", "lotteon", "toss", "atomy", "etc"] # 기타광고비(2026-10-22) = 애터미아자몰 오른쪽
|
"gsshop", "elevenst", "lotteon", "toss", "atomy", "etc"] # 기타광고비(2026-10-22) = 애터미아자몰 오른쪽
|
||||||
assert ctx["names"]["etc"] == "기타광고비" and ctx["roas_basis"]["etc"] == "" and "etc" not in ads.ROAS_SALES_CODE # 매출 쇼핑몰 없음 = ROAS 없음
|
assert ctx["names"]["etc"] == "기타광고비" and ctx["roas_basis"]["etc"] == "" and "etc" not in ads.ROAS_SALES_CODE # 매출 쇼핑몰 없음 = ROAS 없음
|
||||||
k = {x["key"]: x for x in ctx["kpis"]}
|
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["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 k["ytd"]["value"] == 370000 and "mtd" not in k # 월 누적 카드 뺌(2026-10-30)
|
||||||
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
|
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
|
||||||
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
|
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
|
||||||
assert ctx["detail_channels"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
|
assert ctx["detail_channels"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
|
"""매출·광고비 자동 업데이트 — 일정(간격·요일·시작/끝)·회차 시각 계산·종류별 실행·건너뛰기."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -7,26 +7,122 @@ from datetime import date, datetime, timedelta, timezone
|
|||||||
from app.modules.performance import auto_sync as au
|
from app.modules.performance import auto_sync as au
|
||||||
|
|
||||||
KST = timezone(timedelta(hours=9))
|
KST = timezone(timedelta(hours=9))
|
||||||
H = (9, 19)
|
D = au.default_schedule() # 매일 09:00 ~ 19:00, 30분마다 (env 없을 때)
|
||||||
|
|
||||||
|
|
||||||
def _t(h, m, d=13):
|
def _t(h, m, d=13): # 2026-10-13 = 화요일
|
||||||
return datetime(2026, 10, d, h, m, tzinfo=KST)
|
return datetime(2026, 10, d, h, m, tzinfo=KST)
|
||||||
|
|
||||||
|
|
||||||
def test_slots_every_half_hour_9_to_19():
|
def _s(**kw):
|
||||||
slots = [t for t in (_t(0, 0) + timedelta(minutes=30 * i) for i in range(48)) if au.is_slot(t, H)]
|
return {**D, **kw}
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_schedule_every_half_hour_9_to_19(monkeypatch):
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
|
||||||
|
assert au.default_schedule() == {"enabled": True, "interval": 30, "days": [0, 1, 2, 3, 4, 5, 6],
|
||||||
|
"start": "09:00", "end": "19:00"}
|
||||||
|
slots = [t for t in (_t(0, 0) + timedelta(minutes=5 * i) for i in range(288)) if au.is_slot(t, D)]
|
||||||
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
|
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)
|
assert not au.is_slot(_t(19, 30), D) and not au.is_slot(_t(8, 30), D) and not au.is_slot(_t(10, 15), D)
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20") # 일정 저장 전 기본 시간대 = env
|
||||||
|
assert au.default_schedule()["start"] == "08:00" and au.default_schedule()["end"] == "20:00"
|
||||||
|
|
||||||
|
|
||||||
def test_next_slot():
|
def test_next_slot():
|
||||||
assert au.next_slot(_t(8, 10), H) == _t(9, 0)
|
assert au.next_slot(_t(8, 10), D) == _t(9, 0)
|
||||||
assert au.next_slot(_t(9, 0), H) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
|
assert au.next_slot(_t(9, 0), D) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
|
||||||
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), H) == _t(9, 30)
|
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), D) == _t(9, 30)
|
||||||
assert au.next_slot(_t(18, 45), H) == _t(19, 0)
|
assert au.next_slot(_t(18, 45), D) == _t(19, 0)
|
||||||
assert au.next_slot(_t(19, 0), H) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
|
assert au.next_slot(_t(19, 0), D) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
|
||||||
assert au.next_slot(_t(23, 59), H) == _t(9, 0, d=14)
|
assert au.next_slot(_t(23, 59), D) == _t(9, 0, d=14)
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_slot_custom_interval_window_weekdays():
|
||||||
|
s = _s(interval=25, start="08:35", end="10:00")
|
||||||
|
assert au.next_slot(_t(8, 0), s) == _t(8, 35)
|
||||||
|
assert au.next_slot(_t(8, 35), s) == _t(9, 0)
|
||||||
|
assert au.next_slot(_t(9, 40), s) == _t(9, 50) # 08:35 · 09:00 · 09:25 · 09:50 (10:15 는 끝 뒤)
|
||||||
|
assert au.next_slot(_t(9, 50), s) == _t(8, 35, d=14)
|
||||||
|
assert au.is_slot(_t(9, 25), s) and not au.is_slot(_t(10, 0), s)
|
||||||
|
assert au.is_slot(_t(10, 0), _s(interval=5, start="08:35", end="10:00")) # 끝 시각과 딱 맞으면 끝도 회차
|
||||||
|
weekdays = _s(days=[0, 1, 2, 3, 4])
|
||||||
|
assert au.next_slot(datetime(2026, 10, 16, 19, 0, tzinfo=KST), weekdays) == _t(9, 0, d=19) # 금 저녁 → 월 9시
|
||||||
|
assert not au.is_slot(datetime(2026, 10, 17, 10, 0, tzinfo=KST), weekdays) # 토요일
|
||||||
|
once = _s(start="07:05", end="07:05", days=[2]) # 수요일 07:05 한 번
|
||||||
|
assert au.next_slot(_t(7, 5), once) == datetime(2026, 10, 14, 7, 5, tzinfo=KST)
|
||||||
|
assert au.next_slot(datetime(2026, 10, 14, 7, 5, tzinfo=KST), once) == datetime(2026, 10, 21, 7, 5, tzinfo=KST)
|
||||||
|
assert au.next_slot(_t(9, 0), _s(enabled=False)) is None and au.next_slot(_t(9, 0), _s(days=[])) is None
|
||||||
|
assert au.next_slot(_t(9, 0), _s(interval=720, start="00:00", end="23:55")) == _t(12, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_schedule():
|
||||||
|
ok = au.validate_schedule({"enabled": True, "interval": "45", "days": [4, 0, 0], "start": "7:05", "end": "21:30"})
|
||||||
|
assert ok == {"enabled": True, "interval": 45, "days": [0, 4], "start": "07:05", "end": "21:30"}
|
||||||
|
assert au.validate_schedule({**D, "enabled": False, "days": []})["days"] == [] # 끈 일정은 요일 없어도 됨
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
for bad, word in [({**D, "interval": 7}, "5분 단위"), ({**D, "interval": 0}, "간격"), ({**D, "interval": 725}, "간격"),
|
||||||
|
({**D, "interval": "x"}, "숫자"), ({**D, "days": []}, "요일을 하나"), ({**D, "days": [7]}, "요일"),
|
||||||
|
({**D, "days": [True]}, "요일"), ({**D, "start": "09:03"}, "5분 단위"), ({**D, "end": "24:00"}, "HH:MM"),
|
||||||
|
({**D, "start": "19:00", "end": "09:00"}, "끝 시각"), (None, "형식")]:
|
||||||
|
with pytest.raises(ValueError, match=word):
|
||||||
|
au.validate_schedule(bad)
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_and_load_schedules():
|
||||||
|
from app.modules.performance.db import SettingsMigrationNeeded
|
||||||
|
|
||||||
|
saved = {"sales": _s(interval=10), "ads": {"interval": 3}} # 광고비 값이 깨짐 → 그 종류만 기본
|
||||||
|
n = au.normalize(saved)
|
||||||
|
assert n["sales"]["interval"] == 10 and n["ads"] == D
|
||||||
|
assert au.normalize(None) == {"sales": D, "ads": D}
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self, value=None, missing=False):
|
||||||
|
self.value, self.missing = value, missing
|
||||||
|
|
||||||
|
def get_setting(self, key):
|
||||||
|
assert key == "auto_sync"
|
||||||
|
if self.missing:
|
||||||
|
raise SettingsMigrationNeeded()
|
||||||
|
return self.value
|
||||||
|
|
||||||
|
assert au.load_schedules(Store(saved)) == (n, True)
|
||||||
|
assert au.load_schedules(Store(missing=True)) == ({"sales": D, "ads": D}, False)
|
||||||
|
assert au.load_schedules(object()) == ({"sales": D, "ads": D}, True) # get_setting 없는 저장소
|
||||||
|
|
||||||
|
|
||||||
|
def test_describe():
|
||||||
|
assert au.describe(D) == "매일 09:00~19:00 · 30분마다"
|
||||||
|
assert au.describe(_s(days=[0, 1, 2, 3, 4], interval=90)) == "평일 09:00~19:00 · 1시간 30분마다"
|
||||||
|
assert au.describe(_s(days=[5, 6], interval=120)) == "주말 09:00~19:00 · 2시간마다"
|
||||||
|
assert au.describe(_s(days=[0, 2, 4], start="10:00", end="10:00")) == "월·수·금 10:00"
|
||||||
|
assert au.describe(_s(enabled=False)) == "꺼짐"
|
||||||
|
|
||||||
|
|
||||||
|
def test_scheduler_runs_each_kind_on_its_own_schedule():
|
||||||
|
fired = []
|
||||||
|
sch = au.Scheduler(lambda kind, due: fired.append((kind, due)))
|
||||||
|
schedules = {"sales": D, "ads": _s(interval=60, days=[0, 1, 2, 3, 4])}
|
||||||
|
sch.update(schedules, _t(9, 10)) # 시작 시각 회차는 안 돌림 — 다음부터
|
||||||
|
assert sch.due == {"sales": _t(9, 30), "ads": _t(10, 0)}
|
||||||
|
assert sch.wait_seconds(_t(9, 10)) == 60.0 and sch.wait_seconds(datetime(2026, 10, 13, 9, 29, 30, tzinfo=KST)) == 30.0
|
||||||
|
sch.tick(_t(9, 29))
|
||||||
|
assert fired == []
|
||||||
|
sch.tick(_t(9, 30))
|
||||||
|
assert fired == [("sales", _t(9, 30))] and sch.due["sales"] == _t(10, 0)
|
||||||
|
sch.tick(datetime(2026, 10, 13, 10, 0, 20, tzinfo=KST)) # 둘 다 10:00 → 둘 다(따로)
|
||||||
|
assert fired[1:] == [("sales", _t(10, 0)), ("ads", _t(10, 0))]
|
||||||
|
sch.tick(_t(11, 40)) # 밀린 회차(10:30·11:00·11:30)는 한 번만, 다음은 지금 뒤
|
||||||
|
assert fired[3:] == [("sales", _t(10, 30)), ("ads", _t(11, 0))]
|
||||||
|
assert sch.due == {"sales": _t(12, 0), "ads": _t(12, 0)}
|
||||||
|
sch.update(schedules, _t(11, 41)) # 일정 그대로 → due 그대로
|
||||||
|
assert sch.due["sales"] == _t(12, 0)
|
||||||
|
sch.update({**schedules, "sales": _s(interval=5)}, _t(11, 41)) # 매출 일정만 바뀜 → 매출만 지금부터 다시
|
||||||
|
assert sch.due == {"sales": _t(11, 45), "ads": _t(12, 0)}
|
||||||
|
sch.update({"sales": _s(interval=5), "ads": _s(enabled=False)}, _t(11, 41))
|
||||||
|
assert sch.due["ads"] is None and sch.due["sales"] == _t(11, 45)
|
||||||
|
|
||||||
|
|
||||||
def test_env_parsing(monkeypatch):
|
def test_env_parsing(monkeypatch):
|
||||||
@@ -42,6 +138,30 @@ def test_env_parsing(monkeypatch):
|
|||||||
assert au.hour_window() == (8, 20)
|
assert au.hour_window() == (8, 20)
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_once_only_given_kinds(monkeypatch):
|
||||||
|
"""종류마다 따로 회차(2026-10-26) — kinds=("ads",) 면 매출은 건드리지 않는다."""
|
||||||
|
from app.modules.performance import ad_sync, jobs
|
||||||
|
from app.modules.performance.sync import SyncService
|
||||||
|
|
||||||
|
sales = []
|
||||||
|
monkeypatch.setattr(SyncService, "sync_all", lambda self, **kw: sales.append(1) or [])
|
||||||
|
monkeypatch.setattr(ad_sync.AdSyncService, "sync_all", lambda self, start, end, *, user="", job=None: [])
|
||||||
|
monkeypatch.setattr(ad_sync, "ad_credentials", lambda store, ring: None)
|
||||||
|
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": None)
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def last_update_at(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def ad_source_statuses(self):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("ads",))
|
||||||
|
assert sales == [] and res["sales_skipped"] and not res["ads_skipped"] and res["from"] == "2026-10-11"
|
||||||
|
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("sales",))
|
||||||
|
assert sales == [1] and res["ads_skipped"] and not res["sales_skipped"]
|
||||||
|
|
||||||
|
|
||||||
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
||||||
from app.modules.performance import jobs
|
from app.modules.performance import jobs
|
||||||
from app.modules.performance.sync import SyncService
|
from app.modules.performance.sync import SyncService
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""자동 업데이트 일정 설정(2026-10-26, 마이그레이션 011) — 저장 API(관리자·검증·011 미적용 503), 화면 카운트다운 값(종류별 일정)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import auto_sync, common
|
||||||
|
from app.modules.performance.db import SettingsMigrationNeeded
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
KST = timezone(timedelta(hours=9))
|
||||||
|
D = auto_sync.default_schedule()
|
||||||
|
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self, value=None, missing=False):
|
||||||
|
self.value, self.missing, self.saved = value, missing, []
|
||||||
|
|
||||||
|
def get_setting(self, key):
|
||||||
|
if self.missing:
|
||||||
|
raise SettingsMigrationNeeded()
|
||||||
|
return self.value
|
||||||
|
|
||||||
|
def set_setting(self, key, value, *, user=""):
|
||||||
|
if self.missing:
|
||||||
|
raise SettingsMigrationNeeded()
|
||||||
|
self.saved.append((key, value, user))
|
||||||
|
self.value = value
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client_store(monkeypatch):
|
||||||
|
st, calls = Store(), []
|
||||||
|
|
||||||
|
def fake_require(request, admin=False):
|
||||||
|
calls.append(admin)
|
||||||
|
return st, {"email": "admin@x"}
|
||||||
|
|
||||||
|
monkeypatch.setattr(common, "require_store", fake_require)
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
|
||||||
|
monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST)) # 금요일
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
return TestClient(app), st, calls
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_schedule(client_store):
|
||||||
|
c, st, calls = client_store
|
||||||
|
body = {"sales": {"enabled": True, "interval": 15, "days": [0, 1, 2, 3, 4], "start": "08:30", "end": "20:00"},
|
||||||
|
"ads": {"enabled": False, "interval": 60, "days": [], "start": "09:00", "end": "18:00"}}
|
||||||
|
r = c.put("/performance/api/auto-sync-schedule", json=body)
|
||||||
|
assert r.status_code == 200 and calls == [True] # 관리자만
|
||||||
|
j = r.json()
|
||||||
|
assert st.saved == [("auto_sync", body, "admin@x")]
|
||||||
|
assert j["sales"]["next_at"] == "2026-10-16T19:00:00+09:00" and j["sales"]["label"] == "평일 08:30~20:00 · 15분마다"
|
||||||
|
assert j["ads"]["next_at"] == "" and j["ads"]["label"] == "꺼짐" and j["env_on"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_schedule_rejects_bad_values(client_store):
|
||||||
|
c, st, _ = client_store
|
||||||
|
bad = {"sales": {**D, "interval": 12}, "ads": D}
|
||||||
|
r = c.put("/performance/api/auto-sync-schedule", json=bad)
|
||||||
|
assert r.status_code == 400 and r.json()["detail"].startswith("매출 실적:") and "5분 단위" in r.json()["detail"]
|
||||||
|
r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": {**D, "start": "20:00", "end": "08:00"}})
|
||||||
|
assert r.status_code == 400 and r.json()["detail"].startswith("광고비:")
|
||||||
|
assert c.put("/performance/api/auto-sync-schedule", json={"sales": D}).status_code == 400 # 광고비 일정 없음
|
||||||
|
assert st.saved == []
|
||||||
|
st.missing = True
|
||||||
|
r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": D})
|
||||||
|
assert r.status_code == 503 and "011" in r.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_countdown_ctx_per_kind(monkeypatch):
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
|
||||||
|
monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST))
|
||||||
|
st = Store({"sales": {**D, "interval": 5}, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00"}})
|
||||||
|
sales = perf_router._auto_sync_ctx(st, "sales")
|
||||||
|
assert sales["next_at"] == "2026-10-16T18:55:00+09:00" and sales["schedule"]["interval"] == 5
|
||||||
|
assert sales["label"] == "매일 09:00~19:00 · 5분마다" and sales["now"].startswith("2026-10-16T18:50:00")
|
||||||
|
assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-16T19:00:00+09:00"
|
||||||
|
st.value = {"sales": D, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00", "end": "10:00"}}
|
||||||
|
assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-19T10:00:00+09:00" # 금 저녁 → 월 10시
|
||||||
|
st.value = {"sales": {**D, "enabled": False}, "ads": D}
|
||||||
|
assert perf_router._auto_sync_ctx(st, "sales") is None # 끈 종류는 카운트다운 숨김
|
||||||
|
st.missing = True
|
||||||
|
assert perf_router._auto_sync_ctx(st, "sales")["next_at"] == "2026-10-16T19:00:00+09:00" # 011 전 = 기본 일정
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
|
||||||
|
assert perf_router._auto_sync_ctx(st, "sales") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_card_ctx(monkeypatch):
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
|
||||||
|
ctx = perf_router._auto_sync_settings_ctx(Store(missing=True))
|
||||||
|
assert not ctx["ready"] and ctx["env_on"] and [k["kind"] for k in ctx["kinds"]] == ["sales", "ads"]
|
||||||
|
assert ctx["kinds"][0]["schedule"] == D and ctx["step"] == 5
|
||||||
|
|
||||||
|
class Broken:
|
||||||
|
def get_setting(self, key):
|
||||||
|
raise RuntimeError("db down")
|
||||||
|
|
||||||
|
ctx = perf_router._auto_sync_settings_ctx(Broken())
|
||||||
|
assert ctx["ready"] and "RuntimeError" in ctx["error"] and ctx["kinds"][1]["schedule"] == D
|
||||||
@@ -6,11 +6,12 @@ import importlib
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, HTTPException
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
from app.modules.performance import common, dashboard
|
from app.modules.performance import common, dashboard
|
||||||
from app.modules.performance.adapters.registry import get_adapter
|
from app.modules.performance.adapters.registry import get_adapter
|
||||||
|
from app.modules.performance.db import SettingsMigrationNeeded
|
||||||
|
|
||||||
TODAY = date(2026, 10, 7)
|
TODAY = date(2026, 10, 7)
|
||||||
|
|
||||||
@@ -36,6 +37,13 @@ class _Store:
|
|||||||
(date(2026, 10, 6), "custom_a"): 7_000}
|
(date(2026, 10, 6), "custom_a"): 7_000}
|
||||||
self.order = None
|
self.order = None
|
||||||
self.deleted = []
|
self.deleted = []
|
||||||
|
self.settings = {}
|
||||||
|
|
||||||
|
def get_setting(self, key):
|
||||||
|
return self.settings.get(key)
|
||||||
|
|
||||||
|
def set_setting(self, key, value, *, user=""):
|
||||||
|
self.settings[key] = value
|
||||||
|
|
||||||
def list_marketplaces(self):
|
def list_marketplaces(self):
|
||||||
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
|
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
|
||||||
@@ -113,8 +121,8 @@ def test_dashboard_group_column_sums_children_without_double_count():
|
|||||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||||
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
|
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
|
||||||
assert [(c["code"], c["kind"]) for c in ctx["cols"]] == [
|
assert [(c["code"], c["kind"]) for c in ctx["cols"]] == [
|
||||||
("cafe24", "shop"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"), ("custom_a", "child"),
|
("cafe24", "shop"), (dashboard.CAFE24_EX_GB, "diff"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"),
|
||||||
("custom_c", "shop")]
|
("custom_a", "child"), ("custom_c", "shop")]
|
||||||
assert ctx["group_members"] == {"group_x": ["custom_b", "custom_a"]}
|
assert ctx["group_members"] == {"group_x": ["custom_b", "custom_a"]}
|
||||||
assert ctx["names"]["group_x"] == "오프라인"
|
assert ctx["names"]["group_x"] == "오프라인"
|
||||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
@@ -127,7 +135,7 @@ def test_dashboard_group_column_sums_children_without_double_count():
|
|||||||
|
|
||||||
def test_dashboard_filter_hides_group_when_no_child_selected():
|
def test_dashboard_filter_hides_group_when_no_child_selected():
|
||||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["cafe24", "custom_c"])
|
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["cafe24", "custom_c"])
|
||||||
assert [c["code"] for c in ctx["cols"]] == ["cafe24", "custom_c"] and ctx["group_members"] == {}
|
assert [c["code"] for c in ctx["cols"]] == ["cafe24", dashboard.CAFE24_EX_GB, "custom_c"] and ctx["group_members"] == {}
|
||||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["custom_a"])
|
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["custom_a"])
|
||||||
assert [c["kind"] for c in ctx["cols"]] == ["group", "child"]
|
assert [c["kind"] for c in ctx["cols"]] == ["group", "child"]
|
||||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
@@ -221,3 +229,181 @@ def test_dashboard_page_renders_group_header_and_child_cells(client):
|
|||||||
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
|
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
|
||||||
assert 'data-group-cell="group_x"' in body and "150,000" in body
|
assert 'data-group-cell="group_x"' in body and "150,000" in body
|
||||||
assert 'data-group-child="group_x" data-manual-code="custom_a" data-date="2026-10-05"' in body
|
assert 'data-group-child="group_x" data-manual-code="custom_a" data-date="2026-10-05"' in body
|
||||||
|
|
||||||
|
|
||||||
|
def _real(ctx, date_iso):
|
||||||
|
return next(r for r in ctx["table"] if r.get("date") == date_iso)["cells"][dashboard.CAFE24_EX_GB]
|
||||||
|
|
||||||
|
|
||||||
|
def test_cafe24_real_column():
|
||||||
|
"""카페24(실적) = 카페24(전체) 바로 오른쪽, 카페24 − 자사몰(공동구매). 표 열만 — 일 합계엔 안 더함."""
|
||||||
|
st = _Store()
|
||||||
|
# 공동구매 없음 = 전체 그대로
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
assert _real(ctx, "2026-10-05")["gross"] == 1_000_000
|
||||||
|
assert ctx["short_names"]["cafe24"] == "카페24(전체)" and ctx["short_names"][dashboard.CAFE24_EX_GB] == "카페24(실적)"
|
||||||
|
|
||||||
|
st._find("custom_c")["name"] = "자사몰 (공동구매)"
|
||||||
|
st._find("custom_c")["parent_code"] = "group_x"
|
||||||
|
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
assert [c["code"] for c in ctx["cols"]][:2] == ["cafe24", dashboard.CAFE24_EX_GB]
|
||||||
|
assert ctx["cols"][1] == {"code": dashboard.CAFE24_EX_GB, "kind": "diff", "group": "", "base": "cafe24", "minus": "custom_c"}
|
||||||
|
assert _real(ctx, "2026-10-05") == {"gross": 700_000, "commission": 0, "net": 700_000}
|
||||||
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
|
# 일 합계 = 카페24(실적) 700,000 + 공동구매 300,000 + 매장 150,000 — 카페24(전체) 1,000,000 은 안 더함
|
||||||
|
assert day5["total"] == {"gross": 1_150_000, "commission": 10_000, "net": 1_140_000}
|
||||||
|
week = next(r for r in ctx["table"] if r["kind"] == "week")
|
||||||
|
assert week["cells"][dashboard.CAFE24_EX_GB]["gross"] == 700_000
|
||||||
|
assert week["total"]["gross"] == 1_157_000 # 주간합계도 같은 규칙(매장 157,000)
|
||||||
|
|
||||||
|
# 공동구매를 필터로 빼도 실적에서는 뺀다 — 일 합계 = 실적 + 나머지
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["cafe24"])
|
||||||
|
assert _real(ctx, "2026-10-05")["gross"] == 700_000
|
||||||
|
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 700_000
|
||||||
|
# 카페24 를 고르지 않으면 열 없음, 일 합계에 공동구매 그대로
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["custom_c"])
|
||||||
|
assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]]
|
||||||
|
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 300_000
|
||||||
|
|
||||||
|
|
||||||
|
def test_summaries_match_day_total():
|
||||||
|
"""KPI·추이·비중·월/연 누적도 일 합계와 같은 기준 — 공동구매가 두 번 안 들어감, 카페24 줄 = 카페24(실적)."""
|
||||||
|
st = _Store()
|
||||||
|
st._find("custom_c")["name"] = "자사몰(공동구매)"
|
||||||
|
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
week_total = next(r for r in ctx["table"] if r["kind"] == "week")["total"]
|
||||||
|
assert week_total["gross"] == 1_157_000 # 카페24(전체) 1,000,000 + 매장 157,000
|
||||||
|
assert ctx["kpis"][0]["value"] == week_total["net"]
|
||||||
|
assert next(p for p in ctx["chart_daily"] if p["date"] == "2026-10-05")["gross"] == 1_150_000
|
||||||
|
assert sum(s["gross"] for s in ctx["chart_share"]) == 1_157_000
|
||||||
|
assert next(s for s in ctx["chart_share"] if s["code"] == "cafe24")["name"] == "카페24(실적)"
|
||||||
|
assert ctx["month"]["total"]["gross"] == 1_157_000 and ctx["year"]["total"]["gross"] == 1_157_000
|
||||||
|
assert next(r for r in ctx["month"]["rows"] if r["code"] == "cafe24")["gross"] == 700_000
|
||||||
|
assert ctx["year"]["rows"][9]["gross"] == 1_157_000
|
||||||
|
# 카페24(전체) 열은 원래 값 그대로, 공동구매 열도 그대로
|
||||||
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
|
assert day5["cells"]["cafe24"]["gross"] == 1_000_000 and day5["cells"]["custom_c"]["gross"] == 300_000
|
||||||
|
|
||||||
|
|
||||||
|
def test_total_sales_codes_drops_groupbuy_only_with_cafe24():
|
||||||
|
m = lambda c, n: {"code": c, "name": n} # noqa: E731
|
||||||
|
assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("x", "자사몰 (공동구매)"), m("y", "네이버")]) == ["cafe24", "y"]
|
||||||
|
assert dashboard.total_sales_codes([m("x", "자사몰(공동구매)"), m("y", "네이버")]) == ["x", "y"]
|
||||||
|
assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("y", "네이버")]) == ["cafe24", "y"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_day_total_roas_uses_real_total():
|
||||||
|
"""일 합계 ROAS = 일 합계 금액(공동구매 중복 없음) ÷ 일 합계 광고비."""
|
||||||
|
st = _Store()
|
||||||
|
st._find("custom_c")["name"] = "자사몰(공동구매)"
|
||||||
|
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||||
|
st.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 115_000}, {})
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
|
assert day5["ads_total"]["amount"] == 115_000 and day5["ads_total"]["roas"] == 1000 # 1,150,000 ÷ 115,000
|
||||||
|
|
||||||
|
|
||||||
|
def test_hidden_columns_only_hide_table_columns():
|
||||||
|
"""열 숨기기(모든 사용자 공통 설정) — 열만 숨김, 일 합계·그래프 그대로. 하위를 다 숨기면 그룹 열도 없음."""
|
||||||
|
st = _Store()
|
||||||
|
st.settings[dashboard.HIDDEN_SETTING] = ["cafe24", "custom_a", "custom_b"]
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
assert [c["code"] for c in ctx["cols"]] == [dashboard.CAFE24_EX_GB, "naver", "custom_c"]
|
||||||
|
assert _real(ctx, "2026-10-05")["gross"] == 1_000_000 # 전체를 숨겨도 실적은 계산됨
|
||||||
|
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 1_150_000
|
||||||
|
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
|
||||||
|
st.settings[dashboard.HIDDEN_SETTING] = [dashboard.CAFE24_EX_GB]
|
||||||
|
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_hidden_setting_missing_migration_shows_everything():
|
||||||
|
st = _Store()
|
||||||
|
|
||||||
|
def raises(key):
|
||||||
|
raise SettingsMigrationNeeded()
|
||||||
|
|
||||||
|
st.get_setting = raises
|
||||||
|
assert dashboard.load_hidden(st) == set()
|
||||||
|
assert "naver" in [c["code"] for c in dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)["cols"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_hidden_marketplaces(client):
|
||||||
|
"""저장값이 그대로 다른 사용자 화면에도 — 쿠키가 아니라 서버 설정(모르는 코드는 버림)."""
|
||||||
|
r = client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver", "ghost", dashboard.CAFE24_EX_GB, "naver"]})
|
||||||
|
assert r.status_code == 200 and r.json()["codes"] == [dashboard.CAFE24_EX_GB, "naver"]
|
||||||
|
assert client.store.settings[dashboard.HIDDEN_SETTING] == [dashboard.CAFE24_EX_GB, "naver"]
|
||||||
|
head = TestClient(client.app).get("/performance/?period=week&d=2026-10-07").text.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||||
|
assert 'data-col="naver"' not in head and 'data-col="cafe24"' in head
|
||||||
|
assert client.put("/performance/api/hidden-marketplaces", json={"codes": "naver"}).status_code == 400
|
||||||
|
assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).json()["codes"] == []
|
||||||
|
|
||||||
|
def raises(key, value, *, user=""):
|
||||||
|
raise SettingsMigrationNeeded()
|
||||||
|
|
||||||
|
client.store.set_setting = raises
|
||||||
|
assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).status_code == 503
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_hidden_marketplaces_admin_only(client, monkeypatch):
|
||||||
|
def require_store(request, admin=False):
|
||||||
|
if admin:
|
||||||
|
raise HTTPException(status_code=403)
|
||||||
|
return client.store, {"email": "u@x"}
|
||||||
|
|
||||||
|
monkeypatch.setattr(common, "require_store", require_store)
|
||||||
|
assert client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver"]}).status_code == 403
|
||||||
|
assert dashboard.HIDDEN_SETTING not in client.store.settings
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_page_renders_cafe24_real(client):
|
||||||
|
client.store._find("custom_c")["name"] = "자사몰(공동구매)"
|
||||||
|
client.store.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||||
|
client.store.settings[dashboard.HIDDEN_SETTING] = ["naver"]
|
||||||
|
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
|
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||||
|
# 날짜 → 일 합계 → 카페24(전체) → 카페24(실적)
|
||||||
|
assert head.index('data-col="label"') < head.index('data-col="total"') < head.index('data-col="cafe24"') < head.index(f'data-col="{dashboard.CAFE24_EX_GB}"')
|
||||||
|
assert "카페24(전체)" in head and "카페24(실적)" in head and 'data-col="naver"' not in head
|
||||||
|
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
|
||||||
|
assert "700,000" in body
|
||||||
|
# 일 행만 화면 즉시 계산용 값(카페24 총매출,수수료,차감) — performance.js saveManual
|
||||||
|
assert 'data-diff-minus="custom_c" data-base="1000000,0,1000000"' in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_cafe24_real_shows_same_ad_lines(client):
|
||||||
|
"""카페24(전체)의 구글·메타 광고비 줄이 카페24(실적) 칸에도 그대로."""
|
||||||
|
client.store.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 11_000, (date(2026, 10, 5), "meta"): 22_000}, {})
|
||||||
|
body = client.get("/performance/?period=week&d=2026-10-07").text.split("<tbody>", 1)[1]
|
||||||
|
row = next(tr for tr in body.split("<tr ") if 'data-date="2026-10-05"' in tr)
|
||||||
|
assert row.count("<i>구글</i>11,000") == 2 and row.count("<i>메타</i>22,000") == 2
|
||||||
|
assert row.index("<i>구글</i>") < row.index("data-code=\"naver\"")
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_my_col_fold_per_user(client, monkeypatch):
|
||||||
|
"""열 접기(2026-11-06) — 로그인한 사람마다 따로 저장, 매출 실적·광고비 따로, 화면은 그 사람 값만 그린다."""
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
r = client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": ["naver", "label", "naver", 3, "total"]})
|
||||||
|
assert r.status_code == 200 and r.json()["cols"] == ["naver", "total"]
|
||||||
|
assert client.put("/performance/api/my-col-fold", json={"kind": "ads", "cols": ["google"]}).status_code == 200
|
||||||
|
mine = perf_router._col_fold_key({"email": "king@x"})
|
||||||
|
assert len(mine) <= 64 and client.store.settings[mine] == {"sales": ["naver", "total"], "ads": ["google"]}
|
||||||
|
assert 'data-col-fold="["naver", "total"]"' in client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
|
assert client.put("/performance/api/my-col-fold", json={"kind": "x", "cols": []}).status_code == 400
|
||||||
|
assert client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": "naver"}).status_code == 400
|
||||||
|
|
||||||
|
# 다른 사람 — 저장값 없음 → 다 펼침, 저장해도 king 값은 그대로
|
||||||
|
other = {"email": "u@x", "name": "U", "is_admin": False}
|
||||||
|
monkeypatch.setattr(common, "guard", lambda request, admin=False: (client.store, other))
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (client.store, other))
|
||||||
|
assert 'data-col-fold="[]"' in client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
|
client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": ["cafe24"]})
|
||||||
|
assert client.store.settings[mine]["sales"] == ["naver", "total"]
|
||||||
|
|
||||||
|
def raises(key, value, *, user=""):
|
||||||
|
raise SettingsMigrationNeeded()
|
||||||
|
|
||||||
|
client.store.set_setting = raises
|
||||||
|
assert client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": []}).status_code == 503
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ class _Store:
|
|||||||
|
|
||||||
def test_sales_ad_channels_mapping():
|
def test_sales_ad_channels_mapping():
|
||||||
m = dashboard.sales_ad_channels()
|
m = dashboard.sales_ad_channels()
|
||||||
assert m["cafe24"] == (("google", "구글"), ("meta", "메타"))
|
assert m["cafe24"] == (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친"))
|
||||||
assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),)
|
assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),)
|
||||||
assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
|
assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
|
||||||
|
|
||||||
@@ -121,15 +121,51 @@ def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
|
|||||||
assert 'class="perf-adl"' in html and "<i>구글</i>100,000<em>(413%)</em>" in html and "<i>메타</i>50,000" in html
|
assert 'class="perf-adl"' in html and "<i>구글</i>100,000<em>(413%)</em>" in html and "<i>메타</i>50,000" in html
|
||||||
assert "200,000<em>(300%)</em>" in html and "단위:" not in html
|
assert "200,000<em>(300%)</em>" in html and "단위:" not in html
|
||||||
|
|
||||||
client.cookies.set("perf_unit", "thousand")
|
# 매출 단위 = 서버 공통 설정(2026-11-02) — 예전 브라우저 쿠키는 안 봄
|
||||||
|
client.cookies.set("perf_unit", "million")
|
||||||
|
assert "단위:" not in client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
|
client.cookies.delete("perf_unit")
|
||||||
|
store.get_setting = lambda key: "thousand" if key == dashboard.UNIT_SETTING else None
|
||||||
html = client.get("/performance/?period=week&d=2026-10-07").text
|
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
assert "단위: 천원" in html and "2,000<" in html and "<i>구글</i>100<em>(413%)</em>" in html
|
assert "단위: 천원" in html and "2,000<" in html and "<i>구글</i>100<em>(413%)</em>" in html
|
||||||
assert "2,000,000<" not in html.split("perf-main", 1)[1].split("</table>", 1)[0]
|
assert "2,000,000<" not in html.split("perf-main", 1)[1].split("</table>", 1)[0]
|
||||||
client.cookies.set("perf_unit", "million")
|
store.get_setting = lambda key: "million" if key == dashboard.UNIT_SETTING else None
|
||||||
html = client.get("/performance/?period=week&d=2026-10-07").text
|
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html
|
assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_display_unit(monkeypatch):
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from fastapi import FastAPI, HTTPException
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
saved = {}
|
||||||
|
store = _Store()
|
||||||
|
store.set_setting = lambda key, value, *, user="": saved.__setitem__(key, (value, user))
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
assert client.put("/performance/api/display-unit", json={"unit": "thousand"}).json()["unit"] == "thousand"
|
||||||
|
assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x")
|
||||||
|
assert client.put("/performance/api/display-unit", json={"unit": "nope"}).status_code == 400
|
||||||
|
assert client.put("/performance/api/display-unit", json={"unit": ["won"]}).status_code == 400
|
||||||
|
|
||||||
|
def not_admin(request, admin=False):
|
||||||
|
if admin:
|
||||||
|
raise HTTPException(status_code=403)
|
||||||
|
return store, {"email": "u@x"}
|
||||||
|
|
||||||
|
monkeypatch.setattr(common, "require_store", not_admin)
|
||||||
|
assert client.put("/performance/api/display-unit", json={"unit": "won"}).status_code == 403
|
||||||
|
assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x")
|
||||||
|
|
||||||
|
|
||||||
def test_total_roas_uses_whole_day_total():
|
def test_total_roas_uses_whole_day_total():
|
||||||
"""일 합계 ROAS = 그날 일 합계 금액(광고비 없는 쇼핑몰 매출 포함) ÷ 일 합계 광고비 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다."""
|
"""일 합계 ROAS = 그날 일 합계 금액(광고비 없는 쇼핑몰 매출 포함) ÷ 일 합계 광고비 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다."""
|
||||||
class _S(_Store):
|
class _S(_Store):
|
||||||
@@ -151,6 +187,29 @@ def test_kpi_is_net_only():
|
|||||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||||
assert [k["key"] for k in ctx["kpis"]] == ["net"]
|
assert [k["key"] for k in ctx["kpis"]] == ["net"]
|
||||||
assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567
|
assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567
|
||||||
|
assert ctx["kpis"][0]["yoy_cmp"] == "전년 같은 기간" and ctx["kpis"][0]["yoy_delta"] is None # 작년 매출 없음
|
||||||
|
assert "yoy_cmp" not in dashboard.build_dashboard(_Store(), kind="year", anchor=TODAY, today=TODAY)["kpis"][0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_kakao_pf_line_under_cafe24():
|
||||||
|
"""카톡 플친(2026-11-16) — 광고비 탭 열, ROAS 없음, 매출 탭 카페24 칸 아래 구글·메타 다음 줄."""
|
||||||
|
from app.modules.performance import ad_spend
|
||||||
|
|
||||||
|
assert ad_spend.CHANNEL_NAMES["kakao_pf"] == "카톡 플친" and "kakao_pf" not in ad_spend.ROAS_SALES_CODE
|
||||||
|
|
||||||
|
class _S(_Store):
|
||||||
|
def ad_amounts(self, start, end):
|
||||||
|
rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "kakao_pf"): 30_000}
|
||||||
|
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||||
|
return rows, {k: "manual" for k in rows}
|
||||||
|
|
||||||
|
def ad_roas(self, start, end):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
day5 = next(r for r in dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)["table"]
|
||||||
|
if r.get("date") == "2026-10-05")
|
||||||
|
assert [(a["label"], a["amount"], a["roas"]) for a in day5["ads"]["cafe24"]] == [("구글", 100_000, None), ("카톡 플친", 30_000, None)]
|
||||||
|
assert day5["ads_total"]["amount"] == 130_000
|
||||||
|
|
||||||
|
|
||||||
def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch):
|
def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch):
|
||||||
|
|||||||
@@ -160,6 +160,11 @@ def test_periods():
|
|||||||
# 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
|
# 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
|
||||||
s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31))
|
s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31))
|
||||||
assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28))
|
assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28))
|
||||||
|
# 전년 같은 기간 — 진행 중이면 오늘까지, 2/29 → 2/28
|
||||||
|
s, e, label = calc.resolve_period("month", date(2026, 11, 16)).yoy_range(today=date(2026, 11, 16))
|
||||||
|
assert (s, e, label) == (date(2025, 11, 1), date(2025, 11, 16), "전년 같은 기간")
|
||||||
|
s, e, _ = calc.resolve_period("month", date(2028, 2, 10)).yoy_range(today=date(2028, 3, 5))
|
||||||
|
assert (s, e) == (date(2027, 2, 1), date(2027, 2, 28))
|
||||||
assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None
|
assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,216 @@
|
|||||||
|
"""틱톡 탭(2026-11-05) — 입력 검사·요청 매개변수·30일 나누기·매출 합산·환율·오류 안내·화면 데이터·다른 탭과 분리.
|
||||||
|
틱톡 서버는 가짜(httpx MockTransport)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance import ad_spend, fx
|
||||||
|
from app.modules.performance.ad_sources import tiktok_ads as tt
|
||||||
|
from app.modules.performance.ad_sources.registry import get_source
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, TokenExpired
|
||||||
|
|
||||||
|
TOKEN = "tiktoktoken0123456789abcdefSECRET"
|
||||||
|
|
||||||
|
|
||||||
|
class Creds:
|
||||||
|
def __init__(self, values):
|
||||||
|
self.values = values
|
||||||
|
|
||||||
|
def get(self, key):
|
||||||
|
return self.values.get(key, "")
|
||||||
|
|
||||||
|
def has(self, key):
|
||||||
|
return bool(self.values.get(key))
|
||||||
|
|
||||||
|
|
||||||
|
def ctx(**extra):
|
||||||
|
return AdapterContext(code="tiktok", credentials=Creds({"advertiser_id": "71234567", "access_token": TOKEN, **extra}), timeout_sec=5.0)
|
||||||
|
|
||||||
|
|
||||||
|
def server(monkeypatch, *, currency="KRW", report=None, gmv=None, seen=None):
|
||||||
|
"""가짜 틱톡 + 환율 서버. seen 에 (경로, 쿼리, 머리글)을 쌓는다."""
|
||||||
|
def handler(req: httpx.Request) -> httpx.Response:
|
||||||
|
url = urlparse(str(req.url))
|
||||||
|
q = {k: v[0] for k, v in parse_qs(url.query).items()}
|
||||||
|
if seen is not None:
|
||||||
|
seen.append((url.path, q, req.headers.get("access-token")))
|
||||||
|
if "business-api.tiktok.com" not in str(req.url):
|
||||||
|
return httpx.Response(200, json=[{"date": "2026-10-05", "base": "MYR", "quote": "KRW", "rate": 300}])
|
||||||
|
if url.path.endswith("/advertiser/info/"):
|
||||||
|
return httpx.Response(200, json={"code": 0, "data": {"list": [{"name": "DBX", "currency": currency, "timezone": "Asia/Seoul"}]}})
|
||||||
|
rows = gmv if url.path.endswith("/gmv_max/report/get/") else report
|
||||||
|
if isinstance(rows, httpx.Response):
|
||||||
|
return rows
|
||||||
|
return httpx.Response(200, json={"code": 0, "data": {"list": [
|
||||||
|
{"dimensions": {"stat_time_day": f"{d} 00:00:00"}, "metrics": m} for d, m in (rows or {}).items()]}})
|
||||||
|
monkeypatch.setattr(tt, "_http", lambda c: httpx.Client(transport=httpx.MockTransport(handler)))
|
||||||
|
|
||||||
|
|
||||||
|
def test_registered_but_not_a_channel():
|
||||||
|
"""틱톡은 광고 연동에는 있지만 광고비 탭 채널이 아니다(틱톡 탭에서만 보임)."""
|
||||||
|
assert get_source("tiktok").name == "틱톡"
|
||||||
|
assert "tiktok" not in ad_spend.CHANNEL_CODES
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("values,word", [
|
||||||
|
({"advertiser_id": "abc", "access_token": TOKEN}, "광고 계정 ID"),
|
||||||
|
({"advertiser_id": "71234567", "access_token": "short"}, "액세스 토큰"),
|
||||||
|
({"advertiser_id": "71234567", "access_token": TOKEN, "shop_id": "x1"}, "틱톡샵 ID"),
|
||||||
|
])
|
||||||
|
def test_validation(values, word):
|
||||||
|
assert any(word in e for e in tt.TiktokAdsSource().validate_credentials(values))
|
||||||
|
|
||||||
|
|
||||||
|
def test_stored_values_pass_validation():
|
||||||
|
assert tt.TiktokAdsSource().validate_credentials({"advertiser_id": "71234567", "access_token": "__stored__"}) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_sums_revenue_and_splits_30_days(monkeypatch):
|
||||||
|
seen = []
|
||||||
|
server(monkeypatch, seen=seen, report={"2026-10-05": {
|
||||||
|
"spend": "1000", "impressions": "50", "clicks": "5", "complete_payment": "1", "onsite_shopping": "2",
|
||||||
|
"total_complete_payment_rate": "2000", "total_onsite_shopping_value": "1000.4"}})
|
||||||
|
days = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 9, 1), date(2026, 11, 3))
|
||||||
|
reports = [q for path, q, _ in seen if path.endswith("/report/integrated/get/")]
|
||||||
|
assert [(q["start_date"], q["end_date"]) for q in reports] == [
|
||||||
|
("2026-09-01", "2026-09-30"), ("2026-10-01", "2026-10-30"), ("2026-10-31", "2026-11-03")]
|
||||||
|
assert reports[0]["data_level"] == "AUCTION_ADVERTISER" and "stat_time_day" in json.loads(reports[0]["dimensions"])
|
||||||
|
assert not [p for p, _, _ in seen if p.endswith("/gmv_max/report/get/")] # 틱톡샵 ID 없으면 안 물음
|
||||||
|
assert all(h == TOKEN for _, _, h in seen) and not any(TOKEN in json.dumps(q) for _, q, _ in seen) # 토큰은 머리글로만
|
||||||
|
# 같은 날 응답이 쪽마다 오므로 3번 더해진다 — 가짜 서버가 기간과 무관하게 같은 줄을 주는 탓, 합산 동작 자체를 확인
|
||||||
|
d = days[0]
|
||||||
|
assert d.day == date(2026, 10, 5) and d.amount == 3000 and d.metrics[tt.M_REVENUE] == 9001
|
||||||
|
assert d.roas == Decimal("300.04") and d.metrics[tt.M_ORDERS] == 9
|
||||||
|
|
||||||
|
|
||||||
|
def test_gmv_max_added_only_with_shop_id(monkeypatch):
|
||||||
|
seen = []
|
||||||
|
server(monkeypatch, seen=seen, report={"2026-10-05": {"spend": "100", "total_onsite_shopping_value": "100"}},
|
||||||
|
gmv={"2026-10-05": {"cost": "100", "gross_revenue": "500", "orders": "3"}})
|
||||||
|
d = tt.TiktokAdsSource().fetch_days(ctx(shop_id="7555"), date(2026, 10, 5), date(2026, 10, 5))[0]
|
||||||
|
assert d.amount == 200 and d.metrics[tt.M_REVENUE] == 600 and d.roas == Decimal("300.00")
|
||||||
|
assert d.metrics[tt.M_GMV_REVENUE] == 500 and d.metrics[tt.M_GMV_COST] == 100 # 대조용으로 따로 남김
|
||||||
|
gmv_q = next(q for p, q, _ in seen if p.endswith("/gmv_max/report/get/"))
|
||||||
|
assert json.loads(gmv_q["store_ids"]) == ["7555"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_foreign_currency_uses_that_day_rate(monkeypatch):
|
||||||
|
fx.clear_cache()
|
||||||
|
server(monkeypatch, currency="MYR", report={"2026-10-05": {"spend": "10", "total_onsite_shopping_value": "40"}})
|
||||||
|
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
|
||||||
|
assert d.amount == 3000 and d.metrics[tt.M_REVENUE] == 12000 and d.roas == Decimal("400.00")
|
||||||
|
fx.clear_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_spend_means_no_roas(monkeypatch):
|
||||||
|
server(monkeypatch, report={"2026-10-05": {"spend": "0", "total_onsite_shopping_value": "40"}})
|
||||||
|
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
|
||||||
|
assert d.roas is None and d.metrics[tt.M_ROAS] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("code,exc", [(40102, TokenExpired), (40105, AuthFailed), (40100, ApiError), (40002, ApiError)])
|
||||||
|
def test_error_codes(monkeypatch, code, exc):
|
||||||
|
server(monkeypatch, report=httpx.Response(200, json={"code": code, "message": "bad"}))
|
||||||
|
with pytest.raises(exc) as got:
|
||||||
|
tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))
|
||||||
|
assert str(code) in str(got.value) and TOKEN not in str(got.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_connection_also_asks_report(monkeypatch):
|
||||||
|
"""연결 테스트가 보고서까지 물어야 지표 이름 오류를 저장 전에 잡는다."""
|
||||||
|
seen = []
|
||||||
|
server(monkeypatch, seen=seen)
|
||||||
|
msg = tt.TiktokAdsSource().test_connection(ctx())
|
||||||
|
assert "DBX" in msg and "KRW" in msg
|
||||||
|
assert any(p.endswith("/report/integrated/get/") for p, _, _ in seen)
|
||||||
|
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self, rows=None, missing=False):
|
||||||
|
self.rows, self.missing = rows or [], missing
|
||||||
|
|
||||||
|
def ad_details(self, code, start, end):
|
||||||
|
assert code == "tiktok"
|
||||||
|
if self.missing:
|
||||||
|
raise ad_spend.AdMigrationNeeded("005")
|
||||||
|
return [r for r in self.rows if start.isoformat() <= r["date"] <= end.isoformat()]
|
||||||
|
|
||||||
|
|
||||||
|
def row(day, spend, sales):
|
||||||
|
return {"date": day, "amount": spend, "roas": None, "metrics": {tt.M_REVENUE: sales}, "source": "api"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_table_and_kpis():
|
||||||
|
store = Store([row("2026-10-05", 1000, 3000), row("2026-10-06", 1000, 1000), row("2026-09-05", 500, 500)])
|
||||||
|
ctx_ = ad_spend.build_tiktok_dashboard(store, kind="month", anchor=date(2026, 10, 15), today=date(2026, 10, 31),
|
||||||
|
holidays={"2026-10-09": "한글날"})
|
||||||
|
total = ctx_["table"][0]
|
||||||
|
assert total["kind"] == "total" and total["cells"]["spend"]["gross"] == 2000 and total["cells"]["sales"]["gross"] == 4000 and total["roas"] == 200
|
||||||
|
day = next(r for r in ctx_["table"] if r.get("date") == "2026-10-05")
|
||||||
|
assert day["roas"] == 300
|
||||||
|
assert next(r for r in ctx_["table"] if r.get("date") == "2026-10-09")["holiday"] == "한글날"
|
||||||
|
kpi = {k["key"]: k for k in ctx_["kpis"]}
|
||||||
|
assert kpi["spend"]["value"] == 2000 and kpi["sales"]["value"] == 4000 and kpi["roas"]["pct"] == 200
|
||||||
|
assert kpi["spend"]["delta"] == 300.0 and kpi["sales"]["delta"] == 700.0
|
||||||
|
assert ctx_["year"]["spend"] == 2500 and ctx_["year"]["sales"] == 4500 and ctx_["year"]["rows"][9]["roas"] == 200
|
||||||
|
assert ctx_["year"]["rows"][10]["future"] is True and ctx_["year"]["rows"][10]["roas"] is None
|
||||||
|
assert sum(p["gross"] for p in ctx_["chart_sales"]) == 4000 and sum(p["gross"] for p in ctx_["chart_spend"]) == 2000
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_without_table_or_data():
|
||||||
|
got = ad_spend.build_tiktok_dashboard(Store(missing=True), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
|
||||||
|
assert got["migration_needed"] is True and got["table"][0]["roas"] is None
|
||||||
|
assert {k["key"]: k for k in got["kpis"]}["roas"]["pct"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_ads_tab_ignores_tiktok_rows():
|
||||||
|
"""perf_ad_spend 에 틱톡 줄이 있어도 광고비 탭 합계에 안 들어간다."""
|
||||||
|
class AdStore:
|
||||||
|
def ad_amounts(self, start, end):
|
||||||
|
return {(date(2026, 10, 5), "google"): 100, (date(2026, 10, 5), "tiktok"): 9000}, {}
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
got = ad_spend.build_ad_dashboard(AdStore(), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
|
||||||
|
assert got["table"][0]["total"]["gross"] == 100 and "tiktok" not in got["codes"]
|
||||||
|
assert {k["key"]: k for k in got["kpis"]}["spend"]["value"] == 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_page_renders_after_ads_tab(monkeypatch):
|
||||||
|
"""진짜 라우터·템플릿 — 탭 순서, 열 순서, 값, 미설정 안내, 칸 입력 없음."""
|
||||||
|
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") # 패키지의 router 는 APIRouter 객체
|
||||||
|
store = Store([row("2026-10-05", 1000, 3000)])
|
||||||
|
user = {"email": "a@x", "name": "A", "role": "user"}
|
||||||
|
|
||||||
|
class Sync:
|
||||||
|
def configured(self):
|
||||||
|
return {"google": True, "tiktok": False}
|
||||||
|
|
||||||
|
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
|
||||||
|
monkeypatch.setattr(perf_router, "_ad_services", lambda st: (None, Sync()))
|
||||||
|
monkeypatch.setattr(perf_router, "_auto_sync_ctx", lambda st, kind: None)
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 31))
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
html = TestClient(app).get("/performance/tiktok").text
|
||||||
|
tabs = html.split('class="perf-tabs-main"', 1)[1]
|
||||||
|
assert tabs.index("광고비</a>") < tabs.index("틱톡</a>") and "perf-tab-tiktok is-active" in tabs
|
||||||
|
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||||
|
assert head.index("ROAS") < head.index("광고비") < head.index("매출")
|
||||||
|
assert "3,000" in html and "300%" in html
|
||||||
|
assert "틱톡 API 가 아직 설정되지 않았습니다" in html and "data-manual-code" not in html
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""화면 자동 새로 고침(2026-10-26) — 자동 업데이트가 끝나면 매출 실적·광고비 화면이 알아채도록:
|
||||||
|
jobs.last_finished(종류별·보는 사람 것 제외) · GET /api/update-status · 화면 데이터 update_watch."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import auto_sync, common, jobs
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def clean_jobs(monkeypatch):
|
||||||
|
monkeypatch.setattr(jobs, "_JOBS", {})
|
||||||
|
|
||||||
|
|
||||||
|
def _job(kind="sales", user=auto_sync.AUTO_USER, finished=True, at=None):
|
||||||
|
j = jobs.create_job(user=user, start=None, end=None, kind=kind)
|
||||||
|
if finished:
|
||||||
|
j.finish()
|
||||||
|
if at is not None:
|
||||||
|
j.finished_at = at
|
||||||
|
return j
|
||||||
|
|
||||||
|
|
||||||
|
def test_last_finished_by_kind_and_excludes_viewer():
|
||||||
|
assert jobs.last_finished("sales") is None
|
||||||
|
a = _job(at=time.time() - 100)
|
||||||
|
b = _job(user="me@x", at=time.time() - 10) # 보는 사람이 누른 것 — 진행 창이 알아서 새로 그림
|
||||||
|
ad = _job(kind="ads", at=time.time())
|
||||||
|
_job(finished=False) # 도는 중인 작업은 아님
|
||||||
|
assert jobs.last_finished("sales") is b
|
||||||
|
assert jobs.last_finished("sales", exclude_user="me@x") is a
|
||||||
|
assert jobs.last_finished("ads", exclude_user="me@x") is ad
|
||||||
|
assert perf_router._update_watch("sales", {"email": "me@x"}) == {"kind": "sales", "seen": a.id}
|
||||||
|
assert perf_router._update_watch("ads", {"email": "other@x"}) == {"kind": "ads", "seen": ad.id}
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_status_api(monkeypatch):
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "me@x"}))
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
c = TestClient(app)
|
||||||
|
assert c.get("/performance/api/update-status?kind=sales").json() == {"kind": "sales", "running": False, "done": "", "user": ""}
|
||||||
|
run = _job(finished=False)
|
||||||
|
r = c.get("/performance/api/update-status?kind=sales").json()
|
||||||
|
assert r["running"] and r["done"] == ""
|
||||||
|
run.finish()
|
||||||
|
r = c.get("/performance/api/update-status?kind=sales").json()
|
||||||
|
assert r == {"kind": "sales", "running": False, "done": run.id, "user": auto_sync.AUTO_USER}
|
||||||
|
_job(user="me@x") # 내 업데이트는 done 을 바꾸지 않는다
|
||||||
|
assert c.get("/performance/api/update-status?kind=sales").json()["done"] == run.id
|
||||||
|
assert c.get("/performance/api/update-status?kind=ads").json()["done"] == "" # 광고비는 따로
|
||||||
|
assert c.get("/performance/api/update-status?kind=nope").status_code == 404
|
||||||
@@ -17,6 +17,8 @@
|
|||||||
- 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title).
|
- 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title).
|
||||||
- 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다.
|
- 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다.
|
||||||
- UI 버그는 로컬 헤드리스 크롬/엣지로 렌더·좌표 덤프해 재현 후 고칠 것.
|
- UI 버그는 로컬 헤드리스 크롬/엣지로 렌더·좌표 덤프해 재현 후 고칠 것.
|
||||||
|
- **시각 고르기 = 공용 시각 팝업**(2026-11-11, `openTimePopover`·`enhanceTimeInput`, `PJLib` 로도) — 날짜 팝업 모양, 시 00~23·분 5분 단위, 끝에서 멈춤.
|
||||||
|
프로젝트(긴급 공지 포함)에서 `<input type="time">` 기본 시계 금지. 모달 dialog 안 칸이면 그 창 안에 popover 로 붙음(body 면 inert 로 마우스가 안 먹음).
|
||||||
- 날짜 팝업(`openDatePopover`·`enhanceDateInput`·`.pj-datepop` CSS)은 다른 모듈용 공용 복사본이 있다 — `app/static/erp-datepop.js`·`.css`
|
- 날짜 팝업(`openDatePopover`·`enhanceDateInput`·`.pj-datepop` CSS)은 다른 모듈용 공용 복사본이 있다 — `app/static/erp-datepop.js`·`.css`
|
||||||
(2026-10-27, 휴가 신청 날짜 칸). 모양·동작을 바꾸면 그쪽도 같이 고칠 것(나중에 프로젝트도 공용 파일로 옮기면 하나가 됨).
|
(2026-10-27, 휴가 신청 날짜 칸). 모양·동작을 바꾸면 그쪽도 같이 고칠 것(나중에 프로젝트도 공용 파일로 옮기면 하나가 됨).
|
||||||
|
|
||||||
@@ -24,7 +26,8 @@
|
|||||||
|
|
||||||
- **수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User**.
|
- **수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User**.
|
||||||
- 판단: `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`). `is_admin` 은 ERP 상단 관리자 메뉴용 그대로. pro 는 프로젝트 모듈 밖에서는 user 와 같다.
|
- 판단: `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`). `is_admin` 은 ERP 상단 관리자 메뉴용 그대로. pro 는 프로젝트 모듈 밖에서는 user 와 같다.
|
||||||
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버·소유자 변경.
|
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·담당자별 합계·전체 멤버·소유자 변경.
|
||||||
|
- 전체 보기 메뉴 = Project 옵션 대상자(아래 "Project 옵션" 절, `access.can_all_view`, 화면 `pj_all_view`).
|
||||||
- Admin 이상 또는 만든 사람: 프로젝트·섹션 삭제. 멤버 누구나: 작업 삭제·서브프로젝트(표는 6-14).
|
- Admin 이상 또는 만든 사람: 프로젝트·섹션 삭제. 멤버 누구나: 작업 삭제·서브프로젝트(표는 6-14).
|
||||||
- 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동).
|
- 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동).
|
||||||
- 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403).
|
- 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403).
|
||||||
@@ -47,10 +50,14 @@
|
|||||||
- 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe).
|
- 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe).
|
||||||
- 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글.
|
- 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글.
|
||||||
- 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다.
|
- 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다.
|
||||||
- 사이드바 메뉴: 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표.
|
- 사이드바 메뉴: 수신함·전체 보기(Project 옵션 대상자 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표.
|
||||||
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
|
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
|
||||||
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(정렬 "기본"일 때만, 전체 보기는 섹션 맨 끝).
|
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(정렬 "기본"일 때만, 전체 보기는 섹션 맨 끝).
|
||||||
**필터를 켜도 순서 변경 가능**(2026-10-19 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
|
**필터를 켜도 순서 변경 가능**(2026-10-19 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
|
||||||
|
**연결 업무(● 다른 프로젝트 카드)도 순서 저장**(2026-10-30 버그 수정, 마이그레이션 032 `task_project_links.sort_order`) — 예전엔 연결 카드가 원 소속
|
||||||
|
`tasks.sort_order` 로 줄을 서고 `db.reorder_tasks` 가 `tasks.stage_id = 섹션` 인 업무만 고쳐, 실시간 동기화로 다시 받으면 카드가 제자리로 돌아갔다.
|
||||||
|
이제 `reorder_tasks` 가 연결 행 순서도 저장, `list_tasks_for_projects` 는 연결 행을 `COALESCE(l.sort_order, 원 소속 순서)` 로 정렬(`db.link_order_ready`, 032 미적용이면 예전 그대로).
|
||||||
|
연결 카드를 다른 섹션으로 옮길 때도 놓은 자리 저장. 테스트 `tests/test_project_module.py test_reorder_keeps_linked_card_position`(실제 PG).
|
||||||
- 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터).
|
- 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터).
|
||||||
- 대시보드: "업무 합계(프로젝트별)" 카드, 섹션별 카드 삭제, 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에(6-16·6-17·6-19).
|
- 대시보드: "업무 합계(프로젝트별)" 카드, 섹션별 카드 삭제, 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에(6-16·6-17·6-19).
|
||||||
- 담당자별 패널 날짜 mm/dd(요일)·지난 마감 빨강(6-20).
|
- 담당자별 패널 날짜 mm/dd(요일)·지난 마감 빨강(6-20).
|
||||||
@@ -76,6 +83,10 @@
|
|||||||
- **업무를 옮기면 드라이브 파일도 이동**(2026-10-20): 섹션·프로젝트·상위 업무가 바뀌면(`api_update_task`·`move-parent`·`move-project`, `_drive_path_changed`) 백그라운드 `_relocate_drive_files` 가 업무+하위 전체(`db.task_subtree_ids`)의 설명 링크 파일을 새 폴더로(`GoogleDriveFiles.move_to` — appProperties `dbxTaskId` 가 그 업무인 파일만). 제목 변경은 안 옮김, 예전 폴더는 남김.
|
- **업무를 옮기면 드라이브 파일도 이동**(2026-10-20): 섹션·프로젝트·상위 업무가 바뀌면(`api_update_task`·`move-parent`·`move-project`, `_drive_path_changed`) 백그라운드 `_relocate_drive_files` 가 업무+하위 전체(`db.task_subtree_ids`)의 설명 링크 파일을 새 폴더로(`GoogleDriveFiles.move_to` — appProperties `dbxTaskId` 가 그 업무인 파일만). 제목 변경은 안 옮김, 예전 폴더는 남김.
|
||||||
- 그 밖의 업무 창 자리 → 예전처럼 첨부(`POST …/attachments`, `uploadTaskFiles`).
|
- 그 밖의 업무 창 자리 → 예전처럼 첨부(`POST …/attachments`, `uploadTaskFiles`).
|
||||||
- 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 주소 붙여넣기 시 자동 링크. 설명란 링크 = 굵게·기울임·밑줄 + 한 글자처럼(2026-10-19 — `normalizeEditorLinks` 가 `contenteditable=false`, 링크 바로 뒤 Backspace·앞 Delete = 링크 통째로 `execCommand delete`(Ctrl+Z 가능), 저장 HTML 에선 `getHtml` 이 잠금 표시를 뺀다). 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동).
|
- 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 주소 붙여넣기 시 자동 링크. 설명란 링크 = 굵게·기울임·밑줄 + 한 글자처럼(2026-10-19 — `normalizeEditorLinks` 가 `contenteditable=false`, 링크 바로 뒤 Backspace·앞 Delete = 링크 통째로 `execCommand delete`(Ctrl+Z 가능), 저장 HTML 에선 `getHtml` 이 잠금 표시를 뺀다). 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동).
|
||||||
|
**링크 서식 = 크기·굵기만**(2026-10-30) — 잠긴 링크라 execCommand 가 안에 안 들어가, 고른 범위에 걸친 링크는 링크 안쪽 `<span style>` 하나로(`setLinkStyle`):
|
||||||
|
크기 = 글자 크기 도구 그대로, 굵기 = 굵게 버튼·Ctrl+B(`boldWithLinks` — 링크 기본이 굵게라 "보통" = `font-weight: 400`, 서버 `desc_inline_style` 은 400 만 받음).
|
||||||
|
글자와 같이 고르면 execCommand 가 글자에 만든 굵기를 따름(잠긴 링크가 끼면 queryCommandState 가 틀려 글자 노드 계산값으로). 링크 서식 변경은 Ctrl+Z 안 됨.
|
||||||
|
테스트 `tests/js/board_drive.browser.test.js` 6), `tests/test_project_icons_desc_style.py`.
|
||||||
- 설명란·댓글에서 @로 멤버 태그(`task_mentions`, 마이그레이션 006) → 수신함에 그 작업이 쌓임. 댓글 `@아이디` 는 아이콘+이름 칩.
|
- 설명란·댓글에서 @로 멤버 태그(`task_mentions`, 마이그레이션 006) → 수신함에 그 작업이 쌓임. 댓글 `@아이디` 는 아이콘+이름 칩.
|
||||||
- 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea).
|
- 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea).
|
||||||
- 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503). 반응 = 댓글 쓴 사람에게 알림(`type=reaction`).
|
- 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503). 반응 = 댓글 쓴 사람에게 알림(`type=reaction`).
|
||||||
@@ -87,6 +98,14 @@
|
|||||||
|
|
||||||
## 알림
|
## 알림
|
||||||
|
|
||||||
|
- **매일 하는 업무**(2026-11-11, 마이그레이션 033 `tasks.repeat_daily`) — 날짜 팝업 `openDatePopover({allowDaily, daily})` 아래 [매일](repeat 아이콘) =
|
||||||
|
`{due_date: null, repeat_daily: true}`(서버 `db.update_task` 가 마감일·시각 비움, 마감일을 고르면 자동으로 꺼짐). 업무 행에 `repeat_daily` 키가 있을 때만(=033 적용) 버튼이 보인다.
|
||||||
|
카드·목록·내 업무·세부 업무·업무 창 마감 칸 = `dueInfo(…, daily)` → `.is-daily`(CSS ::before repeat 아이콘 + "매일", 노랑).
|
||||||
|
알림 = `reminders.run_daily_alerts`(데몬 1분 주기, 영업일, `daily_alert_times` 중 지난 가장 늦은 시각 하나 — `task_reminders` kind `daily@HH:MM`·그날로 중복 방지)
|
||||||
|
→ 담당자(없으면 협업자)에게 `type=daily` 알림 → 큰 팝업 `_ALERT_TYPES` 에 포함, 줄 배경 노랑(`.pj-alert-item.is-daily`), PC 알림 프로그램 `Alert.IsDaily`.
|
||||||
|
추가 칸(보드 아래 메인 업무 추가·카드 세부 업무 추가 줄)에도 [매일] — `data-daily-ready`(`db.daily_ready`), `POST …/tasks` 의 `repeat_daily: true` = 만든 뒤 `update_task` 로 켬.
|
||||||
|
033 미적용이면 [매일] 숨김·PUT/POST 503·알림 skip.
|
||||||
|
|
||||||
- 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐.
|
- 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐.
|
||||||
- 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`).
|
- 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`).
|
||||||
- **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17).
|
- **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17).
|
||||||
@@ -103,6 +122,10 @@
|
|||||||
- 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에.
|
- 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에.
|
||||||
- 폰트 = 누구나·이 브라우저(localStorage `pj_font`).
|
- 폰트 = 누구나·이 브라우저(localStorage `pj_font`).
|
||||||
- 처음 여는 탭·보드 카드 표지 = **수퍼관리자·Admin 만 수정·모든 사용자에게 적용**(서버 `project_options` 마이그레이션 029, `GET/PUT /project/api/options`, `store.normalize_project_options`).
|
- 처음 여는 탭·보드 카드 표지 = **수퍼관리자·Admin 만 수정·모든 사용자에게 적용**(서버 `project_options` 마이그레이션 029, `GET/PUT /project/api/options`, `store.normalize_project_options`).
|
||||||
|
- **"전체 보기" 메뉴를 볼 사람**(2026-11-11) = 프로젝트 화면 분류에 처음 여는 탭과 묶음. 옵션 키 `all_view_users`(이메일 목록, DB 변경 없음 — 029 키·값 표),
|
||||||
|
`null`(설정 전) = 예전처럼 Pro user 이상. 후보 = `GET /api/assignable-users`(아이콘+이름 `memberPickHtml`, `pro` 표시로 기본 체크) + [전체 선택/해제].
|
||||||
|
메뉴 표시만 정함(데이터는 멤버 범위 그대로) — 사이드바 `pj_all_view`(`_role_ctx(user, request)`), `project.js canAllView`(`data-all-view`). 대시보드 담당자별 합계는 여전히 Pro user 이상.
|
||||||
|
- **알림 분류 — 매일 하는 업무 알림 시각**(2026-11-11) = 옵션 키 `daily_alert_times`(["HH:MM"…] 최대 12, 기본 ["09:00"], 빈 목록 = 끔). 행마다 시각 칸 + 휴지통, [알림 추가].
|
||||||
- 긴급 공지 = 수퍼관리자만.
|
- 긴급 공지 = 수퍼관리자만.
|
||||||
|
|
||||||
## 연간 목표 (마이그레이션 013, `goal_*` 테이블, 6-9)
|
## 연간 목표 (마이그레이션 013, `goal_*` 테이블, 6-9)
|
||||||
|
|||||||
@@ -70,6 +70,14 @@ def is_pro(user: dict[str, Any] | None) -> bool:
|
|||||||
return role_of(user) in ("super", "admin", "pro")
|
return role_of(user) in ("super", "admin", "pro")
|
||||||
|
|
||||||
|
|
||||||
|
def can_all_view(user: dict[str, Any] | None, allowed: list[str] | None) -> bool:
|
||||||
|
"""왼쪽 "전체 보기" 메뉴를 보는가 — Project 옵션 all_view_users(목록에 든 사람만), 설정 전(None)이면 Pro user 이상.
|
||||||
|
메뉴 표시만 정한다 — 전체 보기도 멤버인 프로젝트 범위라 데이터 권한은 그대로(모듈 권한은 화면 진입에서 이미 확인)."""
|
||||||
|
if allowed is None:
|
||||||
|
return is_pro(user)
|
||||||
|
return str((user or {}).get("email") or "").strip().lower() in allowed
|
||||||
|
|
||||||
|
|
||||||
def sees_all_projects(user: dict[str, Any] | None) -> bool:
|
def sees_all_projects(user: dict[str, Any] | None) -> bool:
|
||||||
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
|
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
|
||||||
return can_use_module(user) and _is_super(user)
|
return can_use_module(user) and _is_super(user)
|
||||||
|
|||||||
@@ -578,6 +578,8 @@ class ProjectStore:
|
|||||||
if assignee_email:
|
if assignee_email:
|
||||||
extra = "AND t.assignee_email = %(assignee)s"
|
extra = "AND t.assignee_email = %(assignee)s"
|
||||||
params["assignee"] = store.norm_str(assignee_email, lower=True)
|
params["assignee"] = store.norm_str(assignee_email, lower=True)
|
||||||
|
# 연결 행 순서 = 이 프로젝트에서 옮긴 자리(032), 아직 안 옮겼거나 032 미적용이면 원 소속 순서
|
||||||
|
link_ord = "COALESCE(l.sort_order, lt.sort_order)" if self.link_order_ready() else "lt.sort_order"
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
f"""
|
f"""
|
||||||
@@ -592,11 +594,11 @@ class ProjectStore:
|
|||||||
CASE WHEN x.is_linked THEN x.link_stage_id ELSE t.stage_id END AS stage_id
|
CASE WHEN x.is_linked THEN x.link_stage_id ELSE t.stage_id END AS stage_id
|
||||||
FROM (
|
FROM (
|
||||||
SELECT id AS task_id, project_id AS context_project_id,
|
SELECT id AS task_id, project_id AS context_project_id,
|
||||||
FALSE AS is_linked, NULL::bigint AS link_stage_id
|
FALSE AS is_linked, NULL::bigint AS link_stage_id, sort_order AS ord
|
||||||
FROM tasks
|
FROM tasks
|
||||||
WHERE parent_task_id IS NULL AND project_id = ANY(%(ids)s)
|
WHERE parent_task_id IS NULL AND project_id = ANY(%(ids)s)
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT l.task_id, l.project_id, TRUE, l.stage_id
|
SELECT l.task_id, l.project_id, TRUE, l.stage_id, {link_ord}
|
||||||
FROM task_project_links l
|
FROM task_project_links l
|
||||||
JOIN tasks lt ON lt.id = l.task_id
|
JOIN tasks lt ON lt.id = l.task_id
|
||||||
WHERE l.project_id = ANY(%(ids)s)
|
WHERE l.project_id = ANY(%(ids)s)
|
||||||
@@ -608,7 +610,7 @@ class ProjectStore:
|
|||||||
LEFT JOIN project_stages s ON s.id = t.stage_id
|
LEFT JOIN project_stages s ON s.id = t.stage_id
|
||||||
LEFT JOIN project_stages es ON es.id = x.link_stage_id
|
LEFT JOIN project_stages es ON es.id = x.link_stage_id
|
||||||
WHERE TRUE {extra}
|
WHERE TRUE {extra}
|
||||||
ORDER BY x.context_project_id, t.sort_order ASC, t.id ASC
|
ORDER BY x.context_project_id, x.ord ASC, t.id ASC
|
||||||
LIMIT %(limit)s
|
LIMIT %(limit)s
|
||||||
""",
|
""",
|
||||||
params,
|
params,
|
||||||
@@ -886,6 +888,14 @@ class ProjectStore:
|
|||||||
for k in ("start_time", "due_time"):
|
for k in ("start_time", "due_time"):
|
||||||
if k in fields:
|
if k in fields:
|
||||||
clean[k] = store.validate_time(fields[k])
|
clean[k] = store.validate_time(fields[k])
|
||||||
|
# 매일 하는 업무(033) — 켜면 마감일·마감 시각을 비운다(마감일 없이 매일).
|
||||||
|
if "repeat_daily" in fields:
|
||||||
|
if not isinstance(fields["repeat_daily"], bool):
|
||||||
|
raise ValueError("매일 반복 값이 올바르지 않습니다.")
|
||||||
|
clean["repeat_daily"] = fields["repeat_daily"]
|
||||||
|
if fields["repeat_daily"]:
|
||||||
|
clean["due_date"] = None
|
||||||
|
clean["due_time"] = None
|
||||||
|
|
||||||
newly_assigned: str | None = None
|
newly_assigned: str | None = None
|
||||||
newly_completed = False
|
newly_completed = False
|
||||||
@@ -897,7 +907,11 @@ class ProjectStore:
|
|||||||
prev = self._serialize(row)
|
prev = self._serialize(row)
|
||||||
sets: list[str] = []
|
sets: list[str] = []
|
||||||
params: list[Any] = []
|
params: list[Any] = []
|
||||||
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time"):
|
# 마감일을 고르면 매일 반복은 꺼진다(열이 있을 때만 — 033 미적용이면 키가 없다)
|
||||||
|
if clean.get("due_date") and prev.get("repeat_daily") and "repeat_daily" not in clean:
|
||||||
|
clean["repeat_daily"] = False
|
||||||
|
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time",
|
||||||
|
"repeat_daily"):
|
||||||
if k in clean:
|
if k in clean:
|
||||||
sets.append(f"{k} = %s")
|
sets.append(f"{k} = %s")
|
||||||
params.append(clean[k])
|
params.append(clean[k])
|
||||||
@@ -1734,6 +1748,39 @@ class ProjectStore:
|
|||||||
"WHERE t.id = v.id AND t.stage_id = %s",
|
"WHERE t.id = v.id AND t.stage_id = %s",
|
||||||
([int(i) for i in ordered_ids], stage_id),
|
([int(i) for i in ordered_ids], stage_id),
|
||||||
)
|
)
|
||||||
|
# 연결 업무(다른 프로젝트 카드)는 tasks.stage_id 가 원 소속 섹션이라 위에서 안 바뀐다 — 연결별 순서(032)에.
|
||||||
|
# 예전엔 저장 안 돼 실시간 동기화 때 카드가 제자리로 돌아갔다(2026-10-30).
|
||||||
|
if self.link_order_ready():
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE task_project_links l SET sort_order = v.ord - 1 "
|
||||||
|
"FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) "
|
||||||
|
"WHERE l.task_id = v.id AND l.stage_id = %s",
|
||||||
|
([int(i) for i in ordered_ids], stage_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
def daily_ready(self) -> bool:
|
||||||
|
"""tasks.repeat_daily(마이그레이션 033, 매일 하는 업무) 가 있는지. 한 번 켜지면 기억."""
|
||||||
|
if getattr(self, "_daily_ready", False):
|
||||||
|
return True
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' "
|
||||||
|
"AND table_name = 'tasks' AND column_name = 'repeat_daily'"
|
||||||
|
).fetchone())
|
||||||
|
self._daily_ready = ok
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def link_order_ready(self) -> bool:
|
||||||
|
"""task_project_links.sort_order(마이그레이션 032) 가 있는지. 한 번 켜지면 기억."""
|
||||||
|
if getattr(self, "_link_order_ready", False):
|
||||||
|
return True
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' "
|
||||||
|
"AND table_name = 'task_project_links' AND column_name = 'sort_order'"
|
||||||
|
).fetchone())
|
||||||
|
self._link_order_ready = ok
|
||||||
|
return ok
|
||||||
|
|
||||||
def reorder_subtasks(self, *, parent_task_id: int, ordered_ids: list[int]) -> None:
|
def reorder_subtasks(self, *, parent_task_id: int, ordered_ids: list[int]) -> None:
|
||||||
"""작업 팝업의 세부 작업 목록 드래그 재정렬 — 이 상위 작업의 세부 작업만
|
"""작업 팝업의 세부 작업 목록 드래그 재정렬 — 이 상위 작업의 세부 작업만
|
||||||
@@ -2245,9 +2292,27 @@ class ProjectStore:
|
|||||||
).fetchall()
|
).fetchall()
|
||||||
return [self._serialize(r) for r in rows]
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
|
def list_open_daily_tasks(self) -> list[dict[str, Any]]:
|
||||||
|
"""매일 하는 업무(033 repeat_daily) 중 미완료 + 팔로워 목록. 보관 프로젝트는 뺀다.
|
||||||
|
033 미적용이면 psycopg_errors.UndefinedColumn(알림 데몬이 그날은 건너뜀)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT t.id, t.title, t.assignee_email, t.project_id, t.parent_task_id, p.name AS project_name,
|
||||||
|
COALESCE((SELECT array_agg(f.user_email ORDER BY f.user_email)
|
||||||
|
FROM task_followers f WHERE f.task_id = t.id),
|
||||||
|
'{}'::text[]) AS followers
|
||||||
|
FROM tasks t
|
||||||
|
JOIN projects p ON p.id = t.project_id
|
||||||
|
WHERE t.repeat_daily AND t.completed_at IS NULL AND p.status <> 'archived'
|
||||||
|
ORDER BY t.id
|
||||||
|
""",
|
||||||
|
).fetchall()
|
||||||
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
def add_reminder_notification(
|
def add_reminder_notification(
|
||||||
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
|
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
|
||||||
project_id: int | None, title: str, body: str,
|
project_id: int | None, title: str, body: str, ntype: str | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True,
|
"""마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True,
|
||||||
이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서
|
이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서
|
||||||
@@ -2266,7 +2331,7 @@ class ProjectStore:
|
|||||||
"INSERT INTO project_notifications "
|
"INSERT INTO project_notifications "
|
||||||
"(recipient_email, actor_email, project_id, task_id, type, title, body) "
|
"(recipient_email, actor_email, project_id, task_id, type, title, body) "
|
||||||
"VALUES (%s,'',%s,%s,%s,%s,%s)",
|
"VALUES (%s,'',%s,%s,%s,%s,%s)",
|
||||||
(rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)),
|
(rcpt, project_id, task_id, ntype or kind, store.norm_str(title), store.norm_str(body)),
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,11 @@
|
|||||||
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
|
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
|
||||||
동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다.
|
동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다.
|
||||||
|
|
||||||
|
매일 하는 업무(033 tasks.repeat_daily, run_daily_alerts) — Project 옵션 daily_alert_times 시각(KST, 영업일)이
|
||||||
|
지나면 미완료 매일 업무의 담당자(없으면 협업자)에게 수신함 알림(type=daily, 큰 팝업에 따로 색). 데몬은 1분마다 깨어
|
||||||
|
지난 시각 중 가장 늦은 것 하나만 보낸다(서버가 꺼져 있다 켜져도 몇 번씩 쏟아지지 않게). 중복 방지는 같은
|
||||||
|
task_reminders(kind='daily@HH:MM', due_date=그날).
|
||||||
|
|
||||||
환경변수:
|
환경변수:
|
||||||
PROJECT_REMINDERS false 면 끈다(기본 켜짐)
|
PROJECT_REMINDERS false 면 끈다(기본 켜짐)
|
||||||
PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9)
|
PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9)
|
||||||
@@ -41,6 +46,7 @@ logger = logging.getLogger("project.reminders")
|
|||||||
KIND_DUE_SOON = "due_soon"
|
KIND_DUE_SOON = "due_soon"
|
||||||
KIND_DUE_TODAY = "due_today"
|
KIND_DUE_TODAY = "due_today"
|
||||||
KIND_OVERDUE = "overdue"
|
KIND_OVERDUE = "overdue"
|
||||||
|
NTYPE_DAILY = "daily"
|
||||||
OVERDUE_WINDOW_DAYS = 7
|
OVERDUE_WINDOW_DAYS = 7
|
||||||
|
|
||||||
|
|
||||||
@@ -139,6 +145,39 @@ def run_due_reminders(
|
|||||||
return counts
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def daily_slot(times: list[str], hhmm: str) -> str | None:
|
||||||
|
"""설정 시각들 중 지금(hhmm)까지 지난 가장 늦은 시각 — 없으면 None."""
|
||||||
|
passed = [t for t in times if t <= hhmm]
|
||||||
|
return max(passed) if passed else None
|
||||||
|
|
||||||
|
|
||||||
|
def run_daily_alerts(
|
||||||
|
st: Any, *, today: date, slot: str, lookup: access.UserLookup | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""매일 하는 업무 알림 한 번(그날 slot 시각분). 새로 만든 알림 수. 수신자·권한·중복 규칙은 마감 알림과 같다."""
|
||||||
|
made = 0
|
||||||
|
for t in st.list_open_daily_tasks():
|
||||||
|
assignee = store.norm_str(t.get("assignee_email"), lower=True)
|
||||||
|
wanted = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
|
||||||
|
try:
|
||||||
|
recipients = access.filter_recipients(st, t, wanted, lookup)
|
||||||
|
except Exception: # noqa: BLE001 - 권한 확인이 안 되면 이번엔 보내지 않는다
|
||||||
|
logger.warning("매일 업무 알림 수신자 확인 실패: task=%s", t["id"])
|
||||||
|
continue
|
||||||
|
for rcpt in recipients:
|
||||||
|
try:
|
||||||
|
created = st.add_reminder_notification(
|
||||||
|
task_id=t["id"], kind=f"daily@{slot}", due_date=today.isoformat(), recipient_email=rcpt,
|
||||||
|
project_id=t["project_id"], title=f"매일 업무: {t['title']}",
|
||||||
|
body=f"{t.get('project_name') or ''} · 매일 {slot}", ntype=NTYPE_DAILY,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001 - 기록도 되돌려졌으니 다음 실행에서 다시 시도
|
||||||
|
logger.warning("매일 업무 알림 생성 실패(다음 실행에 재시도): task=%s", t["id"])
|
||||||
|
continue
|
||||||
|
made += int(bool(created))
|
||||||
|
return made
|
||||||
|
|
||||||
|
|
||||||
def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None:
|
def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None:
|
||||||
from app.mail import send_email # noqa: WPS433
|
from app.mail import send_email # noqa: WPS433
|
||||||
|
|
||||||
@@ -176,22 +215,41 @@ def start_reminder_thread(st: Any) -> bool:
|
|||||||
|
|
||||||
def _loop() -> None:
|
def _loop() -> None:
|
||||||
last_run: date | None = None
|
last_run: date | None = None
|
||||||
|
last_due_try = 0.0
|
||||||
|
daily_done: tuple[date, str] | None = None # 마지막으로 보낸 (날짜, 시각)
|
||||||
while True:
|
while True:
|
||||||
|
now = now_kst()
|
||||||
|
today = now.date()
|
||||||
|
if time.monotonic() - last_due_try >= 300: # 마감 알림은 예전처럼 5분마다 확인
|
||||||
|
last_due_try = time.monotonic()
|
||||||
|
try:
|
||||||
|
if last_run != today and now.hour >= hour and is_workday(today):
|
||||||
|
counts = run_due_reminders(st, today=today)
|
||||||
|
last_run = today
|
||||||
|
logger.info("마감 알림 실행: %s", counts)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
if type(exc).__name__ == "UndefinedTable":
|
||||||
|
# 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지)
|
||||||
|
logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요")
|
||||||
|
last_run = now_kst().date()
|
||||||
|
else:
|
||||||
|
logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__)
|
||||||
try:
|
try:
|
||||||
now = now_kst()
|
if is_workday(today):
|
||||||
today = now.date()
|
times = store.normalize_project_options(st.get_project_options())["daily_alert_times"]
|
||||||
if last_run != today and now.hour >= hour and is_workday(today):
|
slot = daily_slot(times, now.strftime("%H:%M"))
|
||||||
counts = run_due_reminders(st, today=today)
|
if slot and daily_done not in ((today, slot), (today, "skip")):
|
||||||
last_run = today
|
made = run_daily_alerts(st, today=today, slot=slot)
|
||||||
logger.info("마감 알림 실행: %s", counts)
|
daily_done = (today, slot)
|
||||||
|
if made:
|
||||||
|
logger.info("매일 업무 알림 %s: %d건", slot, made)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
if type(exc).__name__ == "UndefinedTable":
|
if type(exc).__name__ in ("UndefinedColumn", "UndefinedTable"):
|
||||||
# 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지)
|
daily_done = (today, "skip") # 033(또는 008) 미적용 — 오늘은 그만(로그 도배 방지)
|
||||||
logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요")
|
logger.warning("매일 업무 알림 skip — project_db_033 마이그레이션 필요")
|
||||||
last_run = now_kst().date()
|
|
||||||
else:
|
else:
|
||||||
logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__)
|
logger.warning("매일 업무 알림 실패(%s) — 1분 뒤 재시도", type(exc).__name__)
|
||||||
time.sleep(300)
|
time.sleep(60)
|
||||||
|
|
||||||
threading.Thread(target=_loop, name="project-reminders", daemon=True).start()
|
threading.Thread(target=_loop, name="project-reminders", daemon=True).start()
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -89,13 +89,11 @@ def _require_user(request: Request) -> dict[str, Any]:
|
|||||||
def _page_user(request: Request) -> Any:
|
def _page_user(request: Request) -> Any:
|
||||||
"""화면(HTML) 주소용 — 로그인 전이면 오류 JSON 대신 로그인 화면으로 보냈다가 이 주소로 되돌아온다
|
"""화면(HTML) 주소용 — 로그인 전이면 오류 JSON 대신 로그인 화면으로 보냈다가 이 주소로 되돌아온다
|
||||||
(공유한 회의록·업무 링크를 로그인 안 된 브라우저에서 열 때, 2026-10-14). 로그인했으면 _require_user 와 같다."""
|
(공유한 회의록·업무 링크를 로그인 안 된 브라우저에서 열 때, 2026-10-14). 로그인했으면 _require_user 와 같다."""
|
||||||
from urllib.parse import quote # noqa: WPS433
|
|
||||||
|
|
||||||
from app.main import get_current_user_record # noqa: WPS433
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
from app.store import login_redirect # noqa: WPS433
|
||||||
|
|
||||||
if get_current_user_record(request) is None:
|
if get_current_user_record(request) is None:
|
||||||
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
|
return login_redirect(request)
|
||||||
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
|
|
||||||
return _require_user(request)
|
return _require_user(request)
|
||||||
|
|
||||||
|
|
||||||
@@ -107,12 +105,15 @@ def _require_pro(request: Request) -> dict[str, Any]:
|
|||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
def _role_ctx(user: dict[str, Any]) -> dict[str, Any]:
|
def _role_ctx(user: dict[str, Any], request: Request | None = None) -> dict[str, Any]:
|
||||||
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용."""
|
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용,
|
||||||
|
pj_all_view 는 왼쪽 "전체 보기" 메뉴(Project 옵션 all_view_users — request 가 없으면 옵션 기본값 기준)."""
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
opts = _project_options(_store(request) if request is not None else None)
|
||||||
return {"is_admin": is_admin(user), "pj_pro": access.is_pro(user),
|
return {"is_admin": is_admin(user), "pj_pro": access.is_pro(user),
|
||||||
"pj_admin": access.is_project_admin(user)}
|
"pj_admin": access.is_project_admin(user),
|
||||||
|
"pj_all_view": access.can_all_view(user, opts["all_view_users"])}
|
||||||
|
|
||||||
|
|
||||||
def _can_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> bool:
|
def _can_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> bool:
|
||||||
@@ -431,7 +432,7 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
|||||||
"scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 "
|
"scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 "
|
||||||
"컨테이너를 재기동하세요.",
|
"컨테이너를 재기동하세요.",
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
},
|
},
|
||||||
status_code=503,
|
status_code=503,
|
||||||
@@ -680,7 +681,7 @@ def my_tasks_page(request: Request) -> HTMLResponse:
|
|||||||
"project/mytasks.html",
|
"project/mytasks.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"page_title": "내 업무",
|
"page_title": "내 업무",
|
||||||
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
|
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
|
||||||
@@ -728,7 +729,7 @@ def task_permalink(request: Request, task_id: int):
|
|||||||
{
|
{
|
||||||
"reason": reason,
|
"reason": reason,
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
},
|
},
|
||||||
status_code=status,
|
status_code=status,
|
||||||
@@ -808,7 +809,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
|||||||
"reason": "이 프로젝트의 멤버만 볼 수 있습니다. "
|
"reason": "이 프로젝트의 멤버만 볼 수 있습니다. "
|
||||||
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
|
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
},
|
},
|
||||||
status_code=403,
|
status_code=403,
|
||||||
@@ -898,8 +899,9 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
|||||||
"project/project.html",
|
"project/project.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"pj_options": _project_options(st),
|
"pj_options": _project_options(st),
|
||||||
|
"pj_daily_ready": st.daily_ready(), # 033 — 새 업무·세부 업무 추가 칸 날짜 팝업의 [매일]
|
||||||
"can_manage": can_manage,
|
"can_manage": can_manage,
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"page_title": project["name"],
|
"page_title": project["name"],
|
||||||
@@ -969,7 +971,7 @@ def _db_or_503(request: Request) -> Any:
|
|||||||
|
|
||||||
|
|
||||||
def _project_options(st: Any) -> dict[str, Any]:
|
def _project_options(st: Any) -> dict[str, Any]:
|
||||||
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지) — 읽기 실패해도 화면은 기본값으로 연다."""
|
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지·전체 보기 대상자) — 읽기 실패해도 화면은 기본값으로 연다."""
|
||||||
if st is None:
|
if st is None:
|
||||||
return store.normalize_project_options(None)
|
return store.normalize_project_options(None)
|
||||||
try:
|
try:
|
||||||
@@ -1220,6 +1222,7 @@ def api_assignable_users(request: Request) -> JSONResponse:
|
|||||||
"name": u.get("name") or u["email"].split("@")[0],
|
"name": u.get("name") or u["email"].split("@")[0],
|
||||||
"id": u["email"].split("@")[0],
|
"id": u["email"].split("@")[0],
|
||||||
"avatar": u.get("picture") or "",
|
"avatar": u.get("picture") or "",
|
||||||
|
"pro": access.is_pro(u), # Project 옵션 "전체 보기" 대상자 기본값(설정 전 = Pro user 이상)
|
||||||
}
|
}
|
||||||
for u in user_store.list_all()
|
for u in user_store.list_all()
|
||||||
if has_module(u, "project")
|
if has_module(u, "project")
|
||||||
@@ -1547,12 +1550,22 @@ def _create_task_for(
|
|||||||
"""작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
|
"""작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
|
||||||
돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서."""
|
돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서."""
|
||||||
project, followers = _task_create_checks(request, st, user, project_id, payload)
|
project, followers = _task_create_checks(request, st, user, project_id, payload)
|
||||||
|
daily = payload.get("repeat_daily", False) # 추가 칸 날짜 팝업 [매일](033) — 만든 뒤 켠다(마감일은 비움)
|
||||||
|
if not isinstance(daily, bool):
|
||||||
|
raise HTTPException(status_code=400, detail="매일 반복 값이 올바르지 않습니다.")
|
||||||
try:
|
try:
|
||||||
task = st.create_task(**_task_create_fields(user, project_id, payload))
|
task = st.create_task(**_task_create_fields(user, project_id, payload))
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc))
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
except KeyError as exc:
|
except KeyError as exc:
|
||||||
raise HTTPException(status_code=404, detail=str(exc))
|
raise HTTPException(status_code=404, detail=str(exc))
|
||||||
|
if daily:
|
||||||
|
try:
|
||||||
|
task = st.update_task(task_id=task["id"], fields={"repeat_daily": True}, actor=user["email"])
|
||||||
|
except UndefinedColumn:
|
||||||
|
raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.")
|
||||||
|
task.pop("_newly_assigned", None)
|
||||||
|
task.pop("_newly_completed", None)
|
||||||
return task, _task_created_effects(request, st, user, project, task, followers, bg)
|
return task, _task_created_effects(request, st, user, project, task, followers, bg)
|
||||||
|
|
||||||
|
|
||||||
@@ -1675,6 +1688,8 @@ def api_update_task(
|
|||||||
try:
|
try:
|
||||||
task = st.update_task(task_id=task_id, fields=payload, actor=user["email"],
|
task = st.update_task(task_id=task_id, fields=payload, actor=user["email"],
|
||||||
assignee_allowed=_registered_project_user)
|
assignee_allowed=_registered_project_user)
|
||||||
|
except UndefinedColumn:
|
||||||
|
raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.")
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc))
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
except KeyError:
|
except KeyError:
|
||||||
@@ -2815,7 +2830,7 @@ def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
_ALERT_TYPES = ("mention", "assigned")
|
_ALERT_TYPES = ("mention", "assigned", "daily") # daily = 매일 하는 업무(reminders.run_daily_alerts, 033)
|
||||||
_ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것)
|
_ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것)
|
||||||
_ALERT_PAGE = 200
|
_ALERT_PAGE = 200
|
||||||
_ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게
|
_ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게
|
||||||
@@ -2948,12 +2963,10 @@ def notifier_download(request: Request) -> Any:
|
|||||||
def notifier_page(request: Request) -> Any:
|
def notifier_page(request: Request) -> Any:
|
||||||
"""PC 알림 프로그램 — 연결 승인(?code=)·연결된 PC 목록·내려받기."""
|
"""PC 알림 프로그램 — 연결 승인(?code=)·연결된 PC 목록·내려받기."""
|
||||||
from app.main import DATA_DIR, build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
from app.main import DATA_DIR, build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin, login_redirect # noqa: WPS433
|
||||||
from urllib.parse import quote # noqa: WPS433
|
|
||||||
|
|
||||||
if get_current_user_record(request) is None:
|
if get_current_user_record(request) is None:
|
||||||
return RedirectResponse(url="/login?next=" + quote(str(request.url.path) + (
|
return login_redirect(request)
|
||||||
"?" + request.url.query if request.url.query else ""), safe=""), status_code=303)
|
|
||||||
user = _require_user(request)
|
user = _require_user(request)
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
if st is None:
|
if st is None:
|
||||||
@@ -2967,7 +2980,7 @@ def notifier_page(request: Request) -> Any:
|
|||||||
"project/notifier.html",
|
"project/notifier.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"nav_projects": _nav_projects(st, user, admin),
|
"nav_projects": _nav_projects(st, user, admin),
|
||||||
"goal_years": _goal_years_nav(st),
|
"goal_years": _goal_years_nav(st),
|
||||||
@@ -3118,7 +3131,7 @@ def trash_page(request: Request) -> HTMLResponse:
|
|||||||
"project/trash.html",
|
"project/trash.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"nav_projects": _nav_projects(st, user, True),
|
"nav_projects": _nav_projects(st, user, True),
|
||||||
"goal_years": _goal_years_nav(st),
|
"goal_years": _goal_years_nav(st),
|
||||||
@@ -3195,7 +3208,7 @@ def help_page(request: Request) -> HTMLResponse:
|
|||||||
"project/help.html",
|
"project/help.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"page_title": "프로젝트 관리 도움말",
|
"page_title": "프로젝트 관리 도움말",
|
||||||
"page_subtitle": "처음 쓰는 분을 위한 기능 안내",
|
"page_subtitle": "처음 쓰는 분을 위한 기능 안내",
|
||||||
@@ -3244,7 +3257,7 @@ def inbox_page(request: Request) -> HTMLResponse:
|
|||||||
"project/inbox.html",
|
"project/inbox.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"nav_projects": nav_projects,
|
"nav_projects": nav_projects,
|
||||||
"goal_years": _goal_years_nav(st),
|
"goal_years": _goal_years_nav(st),
|
||||||
@@ -3454,7 +3467,7 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
|||||||
"project/goals.html",
|
"project/goals.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"nav_projects": _nav_projects(st, user, admin),
|
"nav_projects": _nav_projects(st, user, admin),
|
||||||
"goal_years": _goal_years_nav(st),
|
"goal_years": _goal_years_nav(st),
|
||||||
@@ -4005,7 +4018,7 @@ def goal_meeting_page(request: Request, year: int, month: int, week: str | None
|
|||||||
"project/goal_meeting.html",
|
"project/goal_meeting.html",
|
||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user, request),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"nav_projects": _nav_projects(st, user, admin),
|
"nav_projects": _nav_projects(st, user, admin),
|
||||||
"goal_years": _goal_years_nav(st),
|
"goal_years": _goal_years_nav(st),
|
||||||
|
|||||||
@@ -383,7 +383,41 @@ PROJECT_VIEWS: tuple[str, ...] = ("board", "list", "calendar", "timeline", "dash
|
|||||||
PROJECT_OPTION_DEFAULTS: dict[str, Any] = {
|
PROJECT_OPTION_DEFAULTS: dict[str, Any] = {
|
||||||
"default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭
|
"default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭
|
||||||
"board_cover": True, # 보드 카드 표지(설명의 첫 이미지)
|
"board_cover": True, # 보드 카드 표지(설명의 첫 이미지)
|
||||||
|
"all_view_users": None, # 왼쪽 "전체 보기" 메뉴를 볼 사람(이메일 목록) — None = 예전처럼 Pro user 이상
|
||||||
|
"daily_alert_times": ["09:00"], # 매일 업무(033 repeat_daily) 알림 시각들(KST, 영업일)
|
||||||
}
|
}
|
||||||
|
ALL_VIEW_USERS_MAX = 2000
|
||||||
|
DAILY_ALERT_TIMES_MAX = 12
|
||||||
|
|
||||||
|
|
||||||
|
def _time_list(raw: Any) -> list[str] | None:
|
||||||
|
"""'HH:MM' 목록 → 정규화·중복 제거·정렬. 목록이 아니거나 잘못된 시각이 끼면 None(빈 목록 = 알림 끔)."""
|
||||||
|
if not isinstance(raw, list) or len(raw) > DAILY_ALERT_TIMES_MAX:
|
||||||
|
return None
|
||||||
|
out: set[str] = set()
|
||||||
|
for t in raw:
|
||||||
|
if not isinstance(t, str):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
v = validate_time(t)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
out.add(v)
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _email_list(raw: Any) -> list[str] | None:
|
||||||
|
"""이메일 목록 → 소문자·중복 제거·정렬. 목록이 아니거나 이상한 값이 끼면 None."""
|
||||||
|
if not isinstance(raw, list) or len(raw) > ALL_VIEW_USERS_MAX:
|
||||||
|
return None
|
||||||
|
out: set[str] = set()
|
||||||
|
for e in raw:
|
||||||
|
if not isinstance(e, str) or "@" not in e or len(e) > 254:
|
||||||
|
return None
|
||||||
|
out.add(e.strip().lower())
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
|
def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
@@ -394,6 +428,13 @@ def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
|
|||||||
out["default_view"] = raw["default_view"]
|
out["default_view"] = raw["default_view"]
|
||||||
if isinstance(raw.get("board_cover"), bool):
|
if isinstance(raw.get("board_cover"), bool):
|
||||||
out["board_cover"] = raw["board_cover"]
|
out["board_cover"] = raw["board_cover"]
|
||||||
|
if raw.get("all_view_users") is not None:
|
||||||
|
out["all_view_users"] = _email_list(raw["all_view_users"])
|
||||||
|
times = _time_list(raw.get("daily_alert_times"))
|
||||||
|
if times is not None:
|
||||||
|
out["daily_alert_times"] = times
|
||||||
|
else:
|
||||||
|
out["daily_alert_times"] = list(PROJECT_OPTION_DEFAULTS["daily_alert_times"])
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -413,6 +454,16 @@ def validate_project_options(payload: Any) -> dict[str, Any]:
|
|||||||
if not isinstance(payload["board_cover"], bool):
|
if not isinstance(payload["board_cover"], bool):
|
||||||
raise ValueError("카드 표지 값이 올바르지 않습니다.")
|
raise ValueError("카드 표지 값이 올바르지 않습니다.")
|
||||||
out["board_cover"] = payload["board_cover"]
|
out["board_cover"] = payload["board_cover"]
|
||||||
|
if "all_view_users" in payload:
|
||||||
|
v = payload["all_view_users"]
|
||||||
|
out["all_view_users"] = None if v is None else _email_list(v)
|
||||||
|
if v is not None and out["all_view_users"] is None:
|
||||||
|
raise ValueError("전체 보기 대상자 값이 올바르지 않습니다.")
|
||||||
|
if "daily_alert_times" in payload:
|
||||||
|
times = _time_list(payload["daily_alert_times"])
|
||||||
|
if times is None:
|
||||||
|
raise ValueError(f"매일 업무 알림 시각이 올바르지 않습니다(HH:MM, 최대 {DAILY_ALERT_TIMES_MAX}개).")
|
||||||
|
out["daily_alert_times"] = times
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -973,6 +1024,9 @@ def desc_inline_style(value: str) -> str:
|
|||||||
kept.append(f"color: {val}")
|
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):
|
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}")
|
kept.append(f"font-size: {val}")
|
||||||
|
# 링크 굵기 "보통"(2026-10-30) — 링크 기본이 굵게라 보통으로 되돌릴 때만 쓴다(굵게는 값 없음)
|
||||||
|
elif prop == "font-weight" and val in ("400", "normal") and not any(k.startswith("font-weight:") for k in kept):
|
||||||
|
kept.append("font-weight: 400")
|
||||||
return "; ".join(kept)
|
return "; ".join(kept)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user