Compare commits
115 Commits
d0e3e3622b
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
| a1dc52bec8 | |||
| 62cc5e2778 | |||
| 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 |
@@ -126,6 +126,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다.
|
||||
# CAFE24_SHOP_URL=https://www.miras.co.kr
|
||||
#
|
||||
# 멀티쇼핑몰 번호(쉼표). 옵션/품목 팝업에서 바꾼 품목 진열·판매를 이 쇼핑몰 모두에 같은 값으로
|
||||
# 보낸다(추가금액·자체코드는 기본몰 1 만). 번호는 카페24 관리자 → 멀티쇼핑몰 관리에서 확인.
|
||||
# 미설정 시 1(기본몰)만.
|
||||
# CAFE24_SHOP_NOS=1,2,3
|
||||
#
|
||||
# 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전
|
||||
# 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도
|
||||
# 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다.
|
||||
@@ -161,6 +166,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# 초기화: 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 읽기 전용) ───
|
||||
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
||||
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
||||
@@ -175,6 +185,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# 초기화: scripts/sql/performance_db_init.sql (docs/DATABASES.md 참고)
|
||||
# PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/performance_db
|
||||
#
|
||||
# 말레이시아 실적(app/modules/malaysia_performance — 실적 코드 그대로, DB 만 따로). 미설정 시 "설정 필요" 안내.
|
||||
# 만들기: scripts/sql/malaysia_performance_db_seed.sql 머리말(performance_db 구조 복사 + 쇼핑몰 seed), 역할은 performance_app 공유.
|
||||
# MALAYSIA_PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/malaysia_performance_db
|
||||
#
|
||||
# 쇼핑몰 API 인증정보(ID·Key·Secret·Token)는 여기에 넣지 않는다 —
|
||||
# 실적 → 설정 화면에서 입력하면 아래 마스터 키로 AES-256-GCM 암호화해 DB 에 저장한다.
|
||||
# 마스터 키는 DB 에 저장되지 않으며, 잃어버리면 저장된 인증정보를 복구할 수 없다(별도 안전 보관).
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `[프로젝트]` `[Project]` | `project/` | `project_db` | `project` | `docs/PROJECT_MODULE.md` (178KB, 절만) | `project*.js/css`, `erp-overdue.*` |
|
||||
| `[실적]` | `performance/` | `performance_db` | `performance` | `docs/PERFORMANCE_MODULE.md` (절만) | `performance.*` |
|
||||
| `[말레이시아 실적]` | `malaysia_performance/`(얇은 마운트 — 코드는 `performance/` + `variant.py`) | `malaysia_performance_db` | `malaysia_performance` | (모듈 CLAUDE.md) | `performance.*` (실적과 공유) |
|
||||
| `[카페24]` | `cafe24/` | `cafe24_db` | `cafe24` | `docs/CAFE24_MODULE.md` (절만) | `cafe24.css`, `cafe24-options.js` |
|
||||
| `[쿠팡]` | `cupang/` | `cupang_db` | `cupang` | (모듈 CLAUDE.md 가 기준) | `cupang.*` |
|
||||
| `[입출고]` | `inout/` | `inout_db` | `inout` | `docs/INOUT_MODULE.md` | `inout.*` |
|
||||
@@ -47,6 +48,7 @@
|
||||
| `[공지]` `[긴급공지]` | `notice/` | `project_db`(024) | 수퍼관리자 | `docs/NOTICE_MODULE.md` | `erp-notice*` |
|
||||
| `[자산]` | `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` |
|
||||
| `[배포]` `[서버]` | `docker-compose*.yml`, `Dockerfile`, `scripts/` | — | — | `docs/DEPLOYMENT.md` | — |
|
||||
| `[DB]` | `scripts/sql/` | — | — | `docs/DATABASES.md` | — |
|
||||
@@ -58,14 +60,16 @@
|
||||
- `itemcode_db` 읽기 전용 상품: 쿠팡·말레이시아재고·입출고 (`itemcode_ro` 권한).
|
||||
- `app/integrations/cafe24/` 토큰: 카페24 + 실적(카페24 어댑터).
|
||||
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
|
||||
- 실적 코드·화면(`performance/`·`performance.js/css`): 실적 + 말레이시아 실적(`variant.py`) — 바꾸면 둘 다 확인.
|
||||
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
|
||||
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(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`(프로젝트 회의록 보드).
|
||||
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
|
||||
- `app/mail.py`: 프로젝트 알림 메일.
|
||||
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
|
||||
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다.
|
||||
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`).
|
||||
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다.
|
||||
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -3,6 +3,11 @@ FROM python:3.12-slim
|
||||
# 작업 디렉토리
|
||||
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 .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
@@ -486,7 +486,7 @@ VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을
|
||||
|
||||
|
||||
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]]:
|
||||
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
|
||||
|
||||
@@ -506,7 +506,7 @@ def update_variants(
|
||||
continue
|
||||
try:
|
||||
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:
|
||||
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
|
||||
|
||||
+38
@@ -26,8 +26,12 @@ from .modules.expense import CategoryStore, build_expense_store
|
||||
from .modules.expense import router as expense_router
|
||||
from .modules.inout import build_inout_items, build_inout_store
|
||||
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 router as malaysia_router
|
||||
from .modules.malaysia_performance import build_malaysia_performance_store
|
||||
from .modules.malaysia_performance import router as malaysia_performance_router
|
||||
from .modules.notice import build_notice_store
|
||||
from .modules.notice import router as notice_router
|
||||
from .modules.outreach import build_outreach_store
|
||||
@@ -62,9 +66,13 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"project": "프로젝트 관리",
|
||||
"cafe24": "카페24 상품관리",
|
||||
"performance": "실적",
|
||||
"malaysia_performance": "말레이시아 실적",
|
||||
"asset": "자산관리",
|
||||
"inout": "입출고 관리",
|
||||
"outreach": "안내문 발송",
|
||||
"live": "라이브 커머스",
|
||||
"live_host": "라이브 호스트 등록",
|
||||
"live_host_edit": "라이브 호스트 수정",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
@@ -161,6 +169,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "notice" / "templates",
|
||||
BASE_DIR / "modules" / "inout" / "templates",
|
||||
BASE_DIR / "modules" / "outreach" / "templates",
|
||||
BASE_DIR / "modules" / "live" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -223,6 +232,8 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
|
||||
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
||||
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
||||
# 말레이시아 실적(틱톡·쇼피·라자다 수동 입력): 실적 모듈 코드 그대로, DB 만 따로(MALAYSIA_PERFORMANCE_DB_URL 없으면 "설정 필요").
|
||||
app.state.malaysia_performance_store = build_malaysia_performance_store(dsn=env("MALAYSIA_PERFORMANCE_DB_URL") or None)
|
||||
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
|
||||
# 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503).
|
||||
app.state.notice_store = build_notice_store(app.state.project_store)
|
||||
@@ -233,6 +244,8 @@ 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)
|
||||
@@ -243,10 +256,12 @@ app.include_router(dispatch_router)
|
||||
app.include_router(project_router)
|
||||
app.include_router(cafe24_router)
|
||||
app.include_router(performance_router)
|
||||
app.include_router(malaysia_performance_router) # /malaysia/performance — 실적 라우터 두 번째 마운트(라우트 이름은 실적이 먼저)
|
||||
app.include_router(asset_router)
|
||||
app.include_router(notice_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:
|
||||
@@ -439,6 +454,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"status": "ready",
|
||||
"category": "관리",
|
||||
},
|
||||
{
|
||||
"key": "malaysia_performance",
|
||||
"title": "말레이시아 실적",
|
||||
"subtitle": "Malaysia Sales",
|
||||
"description": "틱톡·쇼피·라자다의 쇼핑몰·라이브커머스 매출(RM)과 광고비를 일자별로 입력하고 합계를 봅니다.",
|
||||
"url": "/malaysia/performance/",
|
||||
"health_url": "/malaysia/performance/health",
|
||||
"status": "ready",
|
||||
"category": "관리",
|
||||
},
|
||||
{
|
||||
"key": "inout",
|
||||
"title": "입출고 관리",
|
||||
@@ -459,6 +484,17 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
{
|
||||
"key": "live",
|
||||
"title": "라이브 커머스",
|
||||
"card_title": "라이브 커머스 · Live Commerce", # 메인 카드만 한글·영문 둘 다(사이드바는 짧게)
|
||||
"subtitle": "Malaysia",
|
||||
"description": "말레이시아 라이브 방송의 호스트 정보와 방송 스케줄·판매금액·결과 이미지를 관리합니다.",
|
||||
"url": "/live/",
|
||||
"health_url": "/live/health",
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
]
|
||||
items.append({
|
||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||
@@ -476,6 +512,7 @@ def _icon_svg(name: str) -> str:
|
||||
paths = {
|
||||
"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"/>',
|
||||
"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"/>',
|
||||
@@ -488,6 +525,7 @@ def _icon_svg(name: str) -> str:
|
||||
"project": '<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="8" y1="13" x2="13" y2="13"/><line x1="8" y1="16" x2="11" y2="16"/>',
|
||||
"cafe24": '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9h10"/><path d="M7 13h7"/><path d="M7 17h4"/>',
|
||||
"performance": '<path d="M3 3v18h18"/><rect x="7" y="12" width="3" height="6"/><rect x="12" y="8" width="3" height="10"/><rect x="17" y="5" width="3" height="13"/>',
|
||||
"malaysia_performance": '<path d="M3 3v18h18"/><path d="M7 15l4-4 3 3 6-6"/><path d="M16 8h4v4"/>',
|
||||
"modules": '<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>',
|
||||
}
|
||||
body = paths.get(name, paths["modules"])
|
||||
|
||||
@@ -3,27 +3,37 @@
|
||||
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/CAFE24_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
|
||||
> 정적 파일: `app/static/cafe24.css`, `cafe24-options.js`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||
> 공통 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) 조회·편집·즉시적용·예약적용·버전 이력.
|
||||
- 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`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
|
||||
품목 진열·판매는 `CAFE24_SHOP_NOS`(예 1,2,3)의 모든 멀티쇼핑몰에 같은 값으로 보냄(추가금액 등은 기본몰만).
|
||||
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
|
||||
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/` 부터).
|
||||
「모바일 스와이프 복사(이름)」은 키가 품목코드 대신 옵션값 이름(`swipeCode(tbody, true)`, 품목코드 있는 행만).
|
||||
- 예약(편집기 아래 「예약 적용」): 대표 이미지(썸네일) · 상세페이지 · 진열 · 판매를 지정 시각에. 대표 이미지 파일은 `cafe24_schedule_images`(마이그레이션 006)에 보관, worker 가 이미지 먼저 교체.
|
||||
- 권한키 `cafe24`(연결/해제는 admin 전용).
|
||||
|
||||
## 규칙
|
||||
|
||||
- **카페24 PUT options 는 옵션값 추가를 오류 없이 무시한다** — 기존 옵션에 행 추가는 「옵션 재생성」(DELETE → POST, 품목코드 새로 부여)으로만. 저장 버튼이 새 행을 보면 재생성 확인창으로 넘긴다.
|
||||
|
||||
- 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지.
|
||||
- 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력.
|
||||
- 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지).
|
||||
- 디자인 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"))
|
||||
|
||||
|
||||
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]:
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
+31
-17
@@ -819,27 +819,41 @@ class Cafe24Store:
|
||||
set_selling: bool | None,
|
||||
memo: str = "",
|
||||
created_by: str = "",
|
||||
image: bytes | None = None,
|
||||
image_type: str = "",
|
||||
image_name: str = "",
|
||||
) -> 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:
|
||||
row = conn.execute(
|
||||
"""
|
||||
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 "",
|
||||
),
|
||||
"SELECT data FROM cafe24_schedule_images WHERE schedule_id = %s", (int(schedule_id),)
|
||||
).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]]:
|
||||
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
|
||||
|
||||
@@ -37,7 +37,7 @@ from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
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
|
||||
|
||||
logger = logging.getLogger("cafe24.product_info")
|
||||
@@ -145,12 +145,46 @@ def product_basic(
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
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}
|
||||
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,
|
||||
result="SUCCESS", detail=detail)
|
||||
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
||||
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
||||
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
|
||||
"quantity": v.get("quantity"),
|
||||
"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 ""),
|
||||
}
|
||||
|
||||
@@ -482,19 +517,11 @@ def options_update(
|
||||
try:
|
||||
body = store.build_update_options_request(
|
||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
||||
allow_append=True,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if loaded["option"]["option_preset_code"]:
|
||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
||||
# 뒤에 덧붙인 옵션값 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
||||
added_texts = [
|
||||
v["option_text"]
|
||||
for o, n in zip(body["original_options"], body["options"])
|
||||
for v in n["option_value"][len(o["option_value"]):]
|
||||
]
|
||||
added = len(added_texts)
|
||||
|
||||
try:
|
||||
updated = products.update_options(api.client, product_no, body)
|
||||
@@ -508,7 +535,7 @@ def options_update(
|
||||
record_error = _save_snapshot_safe(
|
||||
st, product_no, "options",
|
||||
_options_snapshot(updated, befores=[loaded["raw_option"], loaded["effective_option"]],
|
||||
osec=loaded["options_section"], recent=added_texts),
|
||||
osec=loaded["options_section"], recent=[]),
|
||||
)
|
||||
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
||||
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||
@@ -541,29 +568,15 @@ def options_update(
|
||||
summary = "; ".join(
|
||||
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
||||
for o in body["options"]
|
||||
) + (f" (+{added} 추가)" if added else "")
|
||||
|
||||
fresh: list[dict[str, Any]] | None = None
|
||||
if added:
|
||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
||||
# 늦게 나타나는 품목은 pending 으로 표시된다(_annotate).
|
||||
_osec, vsec = _snapshot_sections(st, product_no)
|
||||
fresh = _patch_variants(
|
||||
vsec, products.wait_for_variants(api.client, product_no, len(loaded["raw_variants"]) + added)
|
||||
)
|
||||
)
|
||||
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||
result="SUCCESS", detail=summary[:900])
|
||||
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
||||
|
||||
shown_option, shown_variants = _annotate(
|
||||
updated, fresh if fresh is not None else renamed_variants, added_texts
|
||||
)
|
||||
out: dict[str, Any] = {"ok": True, "option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"record_warning": record_error}
|
||||
if added:
|
||||
out["added"] = added
|
||||
return out
|
||||
shown_option, shown_variants = _annotate(updated, renamed_variants, [])
|
||||
return {"ok": True, "option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"record_warning": record_error}
|
||||
|
||||
|
||||
@product_info_router.delete("/products/{product_no}/options")
|
||||
@@ -652,12 +665,13 @@ def variants_update(
|
||||
product_no: int,
|
||||
payload: dict[str, Any] = Body(default_factory=dict),
|
||||
) -> dict[str, Any]:
|
||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다 — **행별 결과**.
|
||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매 · 재고(사용·수량·품절표시)를 한 번에 바꾼다 — **행별 결과**.
|
||||
|
||||
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
||||
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
|
||||
"""
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
@@ -684,7 +698,8 @@ def variants_update(
|
||||
code = result["variant_code"]
|
||||
if result["status"] == products.VARIANT_OK:
|
||||
patch = dict(sent.get(code) or {})
|
||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order",
|
||||
"use_inventory", "display_soldout", "quantity"):
|
||||
value = (result.get("variant") or {}).get(key)
|
||||
if value is not None:
|
||||
patch[key] = value
|
||||
@@ -695,9 +710,26 @@ def variants_update(
|
||||
failed[code] = result["error"]
|
||||
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(
|
||||
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:
|
||||
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
||||
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()},
|
||||
"failed": failed,
|
||||
"unknown": unknown,
|
||||
"shop_failed": shop_failed,
|
||||
"record_warning": record_error,
|
||||
}
|
||||
|
||||
@@ -133,10 +133,11 @@ def _iso(value: Any) -> str:
|
||||
|
||||
|
||||
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
||||
"""왼쪽 목록에 쓸 필드만 — 상품번호·대표 이미지·상품명·진열·판매·최근수정."""
|
||||
normalized = products.normalize_product(raw)
|
||||
return {
|
||||
"product_no": normalized["product_no"],
|
||||
"thumb": str(raw.get("tiny_image") or raw.get("detail_image") or ""),
|
||||
"product_name": normalized["product_name"],
|
||||
"display": normalized["display"],
|
||||
"selling": normalized["selling"],
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""카페24 예약관리 — 지정 시각에 상세페이지·진열/판매를 자동 적용.
|
||||
"""카페24 예약관리 — 지정 시각에 대표 이미지·상세페이지·진열/판매를 자동 적용.
|
||||
|
||||
되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다.
|
||||
한 예약에서 세 가지를 각각 고를 수 있다.
|
||||
한 예약에서 네 가지를 각각 고를 수 있다.
|
||||
|
||||
대표 이미지 고른 파일로 그 시각에 교체 (파일은 DB 보관 — 마이그레이션 006)
|
||||
상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로)
|
||||
진열 진열 / 미진열 / 변경 없음
|
||||
판매 판매 / 중지 / 변경 없음
|
||||
@@ -19,13 +20,14 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Form, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
|
||||
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard
|
||||
from .routes_product_info import _read_image
|
||||
from .routes_products import _no_store, load_product
|
||||
|
||||
logger = logging.getLogger("cafe24.schedules")
|
||||
@@ -53,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
||||
has_html=bool(row.get("has_html")),
|
||||
set_display=row.get("set_display"),
|
||||
set_selling=row.get("set_selling"),
|
||||
has_image=bool(row.get("image_type")),
|
||||
),
|
||||
"editable": store.is_editable(row.get("status") or ""),
|
||||
"needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW,
|
||||
@@ -63,7 +66,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
||||
ctx.update(
|
||||
{
|
||||
"page_title": "카페24 — 예약관리",
|
||||
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
||||
"page_subtitle": "지정 시각에 대표 이미지·상세페이지·진열/판매 자동 적용",
|
||||
"rows": rows,
|
||||
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
|
||||
"review": sum(1 for r in rows if r["needs_review"]),
|
||||
@@ -85,12 +88,14 @@ def schedule_create(
|
||||
set_selling: str = Form(""),
|
||||
memo: str = Form(""),
|
||||
list_query: str = Form(""),
|
||||
image: UploadFile | None = File(None),
|
||||
):
|
||||
"""편집기에서 예약을 등록한다.
|
||||
|
||||
HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다.
|
||||
단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때
|
||||
저장되는 값이 화면에서 본 것과 같다.
|
||||
대표 이미지 파일을 고르면 파일을 DB 에 보관했다가 그 시각에 교체한다(마이그레이션 006).
|
||||
"""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
@@ -105,9 +110,16 @@ def schedule_create(
|
||||
display_flag = store.parse_tristate(set_display)
|
||||
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(
|
||||
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(상세페이지 / 진열 / 판매).",
|
||||
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(대표 이미지 / 상세페이지 / 진열 / 판매).",
|
||||
status_code=303,
|
||||
)
|
||||
|
||||
@@ -146,9 +158,12 @@ def schedule_create(
|
||||
set_selling=selling_flag,
|
||||
memo=memo,
|
||||
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(
|
||||
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(
|
||||
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}")
|
||||
def schedule_current_flags(request: Request, product_no: int) -> dict:
|
||||
"""예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용)."""
|
||||
|
||||
+47
-22
@@ -452,10 +452,12 @@ def parse_schedule_at(value: object, *, now: datetime | None = None) -> datetime
|
||||
|
||||
|
||||
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:
|
||||
"""예약 내용을 한 줄로 요약(목록·로그 표시용)."""
|
||||
parts: list[str] = []
|
||||
if has_image:
|
||||
parts.append("대표이미지")
|
||||
if has_html:
|
||||
parts.append("상세페이지")
|
||||
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
|
||||
|
||||
|
||||
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:
|
||||
try:
|
||||
minutes = int(str(value or "").strip())
|
||||
@@ -973,16 +984,15 @@ def build_update_options_request(
|
||||
edited: list[dict],
|
||||
*,
|
||||
option_list_type: str = "",
|
||||
allow_append: bool = False,
|
||||
) -> dict:
|
||||
"""옵션명/옵션값(이름·이미지·색상·표시방식) 수정 요청.
|
||||
|
||||
카페24 PUT options 는 `original_options`(수정 전) 와 `options`(수정 후) 를
|
||||
**위치**로 짝지어 이름을 바꾼다. 그래서
|
||||
- 옵션값을 **뒤에 덧붙이는** 것(`allow_append`)만 허용한다 — 앞쪽 위치는 그대로라
|
||||
기존 이름이 밀리지 않는다(카페24가 추가를 거부하면 그 오류가 그대로 올라온다).
|
||||
- 옵션값 **삭제**(개수 감소)는 거부한다 — 중간을 빼면 뒤 값들이 한 칸씩 당겨져
|
||||
엉뚱한 품목의 이름이 바뀐다. 정리는 옵션 재생성(삭제 후 생성)으로 한다.
|
||||
**위치**로 짝지어 이름을 바꾼다. 옵션값 개수는 바꿀 수 없다:
|
||||
- **추가**: 카페24 문서상 PUT 은 옵션 항목 추가를 지원하지 않는다 — 실물에서
|
||||
덧붙여 보내도 오류 없이 무시되어 "저장했는데 사라짐"이 됐다(2026-11-06).
|
||||
추가는 옵션 재생성(삭제 후 POST)으로 한다.
|
||||
- **삭제**: 중간을 빼면 뒤 값들이 한 칸씩 당겨져 엉뚱한 품목의 이름이 바뀐다.
|
||||
original: GET 응답의 options 그대로. edited: 화면에서 보낸 같은 모양의 목록.
|
||||
"""
|
||||
if len(original) != len(edited):
|
||||
@@ -997,10 +1007,10 @@ def build_update_options_request(
|
||||
f"옵션 「{o.get('option_name')}」 의 옵션값을 줄일 수 없습니다. "
|
||||
"옵션값 삭제는 카페24 API 가 지원하지 않습니다 — 옵션 재생성으로 정리하세요."
|
||||
)
|
||||
if len(e_vals) > len(o_vals) and not allow_append:
|
||||
if len(e_vals) > len(o_vals):
|
||||
raise ValueError(
|
||||
f"옵션 「{o.get('option_name')}」 의 옵션값 개수가 카페24와 다릅니다. "
|
||||
"다시 읽은 뒤 수정하세요."
|
||||
f"옵션 「{o.get('option_name')}」 에 옵션값을 추가할 수 없습니다. "
|
||||
"카페24 API 는 기존 옵션에 옵션값 추가를 지원하지 않습니다 — 「옵션 재생성」으로 추가하세요."
|
||||
)
|
||||
name = str(e.get("option_name") or "").strip()
|
||||
if not name:
|
||||
@@ -1036,17 +1046,6 @@ def build_update_options_request(
|
||||
n_item[key] = value
|
||||
orig_entry["option_value"].append(o_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)
|
||||
new_out.append(new_entry)
|
||||
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"
|
||||
|
||||
|
||||
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]:
|
||||
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
|
||||
out: list[dict] = []
|
||||
@@ -1089,9 +1106,17 @@ def build_variant_updates(rows: list[dict]) -> list[dict]:
|
||||
amount = parse_additional_amount(row["additional_amount"])
|
||||
if amount is not None:
|
||||
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:
|
||||
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 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다.
|
||||
if row.get("display_order") is not None:
|
||||
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 }}" />
|
||||
|
||||
<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">
|
||||
<input class="cf24-memo" type="text" name="memo" maxlength="200"
|
||||
placeholder="변경 메모 (버전 이력에 남습니다)" />
|
||||
@@ -156,7 +156,7 @@
|
||||
<details class="cf24-details">
|
||||
<summary>예약 적용 — 지정한 시각에 자동 반영</summary>
|
||||
<form class="cf24-schedule-form" id="cf24-schedule-form" method="post"
|
||||
action="/cafe24/schedules"
|
||||
action="/cafe24/schedules" enctype="multipart/form-data"
|
||||
data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?">
|
||||
<input type="hidden" name="product_no" value="{{ product_no }}" />
|
||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||
@@ -205,6 +205,15 @@
|
||||
<option value="off">중지</option>
|
||||
</select>
|
||||
</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">
|
||||
<span>메모</span>
|
||||
<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>
|
||||
</div>
|
||||
<p class="cf24-muted" style="margin:8px 0 0;">
|
||||
진열·판매만 바꾸려면 위 체크를 해제하세요. 셋 중 하나 이상은 선택해야 합니다.
|
||||
대표 이미지·진열·판매만 바꾸려면 위 체크를 해제하세요. 넷 중 하나 이상은 선택해야 합니다.
|
||||
대표 이미지는 JPG·PNG·GIF·WEBP, 10MB 이하(목록/축소 이미지는 카페24가 자동 생성).
|
||||
</p>
|
||||
</form>
|
||||
</details>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{# 카페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 %}"
|
||||
href="/cafe24/">상품관리</a>
|
||||
<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" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261103c" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
@@ -45,6 +45,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<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-flag" data-sort-key="display" 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-updated="{{ r.updated_date }}">
|
||||
<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 }}">
|
||||
<a href="/cafe24/?{{ qs }}selected={{ r.product_no }}">{{ r.product_name }}</a>
|
||||
</td>
|
||||
@@ -128,7 +130,7 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="/static/cafe24-options.js?v=20261020a"></script>
|
||||
<script src="/static/cafe24-options.js?v=20261110c"></script>
|
||||
<script>
|
||||
(function () {
|
||||
var pane = document.getElementById("cf24-editor-pane");
|
||||
@@ -368,6 +370,41 @@
|
||||
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 초과 소스는 색칠을 안 해 미리보기도 안 뜬다, 그런 상품이 나오면 글자 위치 계산으로 교체. */
|
||||
@@ -408,6 +445,10 @@
|
||||
else moveLines(isDown);
|
||||
return;
|
||||
}
|
||||
if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (isUp || isDown) && stepImgSuffix(isUp)) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
// Shift+Delete — 줄 삭제. (윈도우 기본 동작인 "잘라내기"를 대신한다)
|
||||
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey &&
|
||||
(e.key === "Delete" || e.code === "Delete")) {
|
||||
@@ -522,6 +563,17 @@
|
||||
// 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다.
|
||||
var schedForm = pane.querySelector("#cf24-schedule-form");
|
||||
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) {
|
||||
var box = document.getElementById("cf24-html-pc");
|
||||
var holder = document.getElementById("cf24-schedule-html");
|
||||
@@ -537,7 +589,8 @@
|
||||
// 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다.
|
||||
// (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다)
|
||||
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;
|
||||
dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다.
|
||||
schedForm.submit();
|
||||
@@ -876,6 +929,7 @@
|
||||
window.erpAlert("상품명은 비울 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
if ("price" in payload) lines.push("\n※ 옵션 품목은 판매 가격이 그대로이도록 추가금액을 함께 조정합니다.");
|
||||
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
|
||||
.then(function (ok) {
|
||||
if (!ok) return;
|
||||
@@ -890,7 +944,10 @@
|
||||
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
|
||||
commitValues(form);
|
||||
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"); })
|
||||
.then(function () { btn.disabled = false; });
|
||||
@@ -916,6 +973,8 @@
|
||||
if (link) { link.href = p.detail_image; link.classList.remove("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) {
|
||||
var v = p[el.dataset.imageKey];
|
||||
if (!v) return;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
@@ -37,7 +37,7 @@
|
||||
<th style="width:130px;">예정 시각</th>
|
||||
<th style="width:66px;">상품</th>
|
||||
<th>상품명</th>
|
||||
<th style="width:150px;">적용 내용</th>
|
||||
<th style="width:170px;">적용 내용</th>
|
||||
<th style="width:96px;">상태</th>
|
||||
<th>메모 / 오류</th>
|
||||
<th style="width:130px;">등록자</th>
|
||||
@@ -53,7 +53,8 @@
|
||||
<a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a>
|
||||
</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">
|
||||
{% 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>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
@@ -396,6 +396,8 @@ class FakeCafe24:
|
||||
self._variant_puts += 1
|
||||
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
|
||||
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
|
||||
if (json or {}).get("shop_no", 1) != 1: # 다른 쇼핑몰 — 기본몰 상태는 그대로
|
||||
return {"variants": [dict(r) for r in (json or {}).get("requests") or []]}
|
||||
out = []
|
||||
for r in (json or {}).get("requests") or []:
|
||||
for var in self.variants:
|
||||
@@ -411,6 +413,13 @@ class FakeCafe24:
|
||||
|
||||
def post(self, path, *, json=None, **kw):
|
||||
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)
|
||||
return copy.deepcopy(out) if out is not None else {}
|
||||
|
||||
|
||||
@@ -649,6 +649,9 @@ def test_describe_schedule_action():
|
||||
assert store.describe_schedule_action(
|
||||
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():
|
||||
@@ -1083,6 +1086,22 @@ def test_resolve_description_accepts_iso_created_at():
|
||||
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():
|
||||
assert store.parse_grace_minutes("30") == 30
|
||||
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
|
||||
else:
|
||||
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"}]}]
|
||||
try:
|
||||
store.build_update_options_request(original, more)
|
||||
except ValueError:
|
||||
pass
|
||||
except ValueError as exc:
|
||||
assert "옵션 재생성" in str(exc)
|
||||
else:
|
||||
raise AssertionError("append without flag 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 여도 거부 (위치 짝맞춤으로 이름이 밀린다)
|
||||
raise AssertionError("append accepted")
|
||||
# 줄이기도 거부 (위치 짝맞춤으로 이름이 밀린다)
|
||||
two = [{"option_name": "A", "option_value": [{"option_text": "1"}, {"option_text": "2"}]}]
|
||||
try:
|
||||
store.build_update_options_request(two, original, allow_append=True)
|
||||
store.build_update_options_request(two, original)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
@@ -1288,6 +1304,38 @@ def test_delete_variant_wrapper():
|
||||
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():
|
||||
rows = [
|
||||
{"variant_code": "p000000r000a", "custom_variant_code": " ABC ", "additional_amount": "1,000", "display": "on"},
|
||||
@@ -1305,6 +1353,18 @@ def test_build_variant_updates():
|
||||
pass
|
||||
else:
|
||||
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)
|
||||
assert store.build_variant_updates([{"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 .common import read_lag_grace_minutes
|
||||
from .routes_products import load_product
|
||||
|
||||
logger = logging.getLogger("cafe24.worker")
|
||||
|
||||
@@ -77,9 +78,28 @@ def _summary(row: dict[str, Any]) -> str:
|
||||
has_html=bool(row.get("revision_id")),
|
||||
set_display=row.get("set_display"),
|
||||
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:
|
||||
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
|
||||
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:
|
||||
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
||||
|
||||
image_type = str(row.get("image_type") or "")
|
||||
new_image = ""
|
||||
try:
|
||||
html: str | None = None
|
||||
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 "")
|
||||
if not html.strip():
|
||||
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(
|
||||
st, writes.product_lock_key(product_no), actor=ACTOR,
|
||||
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
||||
) as lock:
|
||||
outcome = writes.write_product(
|
||||
st, api, product_no,
|
||||
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
||||
set_display=set_display, set_selling=set_selling,
|
||||
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
|
||||
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
|
||||
)
|
||||
if image:
|
||||
if not fence():
|
||||
raise writes.WriteBusy("예약 lease 를 잃었습니다 — 다른 worker 가 처리합니다.")
|
||||
new_image = _apply_image(st, api, product_no, image, image_type)
|
||||
outcome = writes.WriteOutcome()
|
||||
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:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
||||
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),
|
||||
schedule_id=schedule_id, result="SUCCESS",
|
||||
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
|
||||
+ (f" / 대표이미지 → '{new_image}'" if new_image else "")
|
||||
+ (f" / {note}" if note else ""),
|
||||
)
|
||||
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
{% block head_extra %}
|
||||
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — 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/cupang.css?v=20261023d" />
|
||||
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||
@@ -249,7 +249,7 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
<script src="/static/cupang-outbound.js?v=20261023d" defer></script>
|
||||
<script>
|
||||
(function () {
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
|
||||
- 미입고 현황(제품별 합계·발주별·지연).
|
||||
- 발주 목록 상태 보기(진행 중·완료·종결·취소·전체)는 **사람마다 기억**(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`).
|
||||
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
|
||||
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
|
||||
@@ -40,6 +43,9 @@
|
||||
- **입고 담당 발주 알림 자동 발송**(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 필요).
|
||||
|
||||
- **간단 발주 메일**(2026-11-04): 공장 이름에 "대성화학"·"인천공장"이 들어가면(`store.SIMPLE_MAIL_FACTORIES`, 띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·**박스당 수량·박스 수**·비고만, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다(단가가 공장에 나가지 않게). 색상 줄 배경·합계 수량은 그대로.
|
||||
박스 값은 발주 품목 사본이 아니라 **메일을 만들 때의 상품 정보**(`router._mail_order` → `store.line_boxes`, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`). 다른 공장 메일엔 박스 칸 없음.
|
||||
|
||||
## 입고 요청 메일 (005, 2026-10-19)
|
||||
|
||||
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
|
||||
@@ -94,10 +100,17 @@
|
||||
- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`).
|
||||
- 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)
|
||||
|
||||
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 300px). 스크롤해도 위에 붙음.
|
||||
달력 크기 = 화면에 따라 300~440px(`clamp(300px, 23vw, 440px)`, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
|
||||
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 270px). 스크롤해도 위에 붙음.
|
||||
달력 크기 = 화면에 따라 270~396px(`clamp(270px, 20.7vw, 396px)`, 2026-11-05 90% 로 줄임, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
|
||||
글자·칸은 달력 너비 기준 `cqw`(300px 일 때 1cqw = 3px)라 같은 비율로 커진다 — 새 크기 값도 px 대신 cqw 로.
|
||||
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
|
||||
공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
|
||||
@@ -109,3 +122,5 @@
|
||||
|
||||
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
|
||||
- 날짜 서식은 모두 `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`).
|
||||
|
||||
+28
-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 "
|
||||
"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 []
|
||||
# 입고일 열 — 같은 날 여러 번 입고해도 날짜는 하나
|
||||
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]]] = {}
|
||||
for ln in lines:
|
||||
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]
|
||||
out = []
|
||||
for h in heads:
|
||||
@@ -351,7 +357,7 @@ class InoutDBStore:
|
||||
continue
|
||||
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),
|
||||
"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:
|
||||
break
|
||||
return out
|
||||
@@ -637,7 +643,12 @@ class InoutDBStore:
|
||||
self._need_products()
|
||||
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)
|
||||
bagged = self.bags_ready() and any("boxes_per_pallet" in r for r in rows)
|
||||
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 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다)
|
||||
for r in rows:
|
||||
if "body_per_box" in r:
|
||||
@@ -759,6 +770,22 @@ class InoutDBStore:
|
||||
self._boxes_checked = time.monotonic()
|
||||
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:
|
||||
if not self.groups_ready():
|
||||
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
|
||||
|
||||
@@ -106,6 +106,16 @@ def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]:
|
||||
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:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
|
||||
@@ -114,7 +124,7 @@ def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, An
|
||||
return render_template(request, name, {
|
||||
"user": user, "is_admin": perms["admin"], "perms": perms,
|
||||
"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"], # 톱니 팝업 바로 열기
|
||||
**ctx,
|
||||
}, status_code=status_code)
|
||||
@@ -267,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_label"] = store.fmt_num(price) if price is not None else ""
|
||||
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)
|
||||
catalog_n = st.catalog_count()
|
||||
return _render(request, "inout/order_form.html", user, {
|
||||
@@ -709,6 +719,10 @@ def _mail_order(request: Request, order_id: int) -> tuple[Any, dict[str, Any], d
|
||||
order = _order_or_404(st, order_id)
|
||||
if order["cancelled_at"]:
|
||||
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
|
||||
|
||||
|
||||
@@ -939,8 +953,10 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
|
||||
known.add(e)
|
||||
reader = _items(request)
|
||||
products = st.list_products()
|
||||
bags_ready = st.bags_ready()
|
||||
for pr in products:
|
||||
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(),
|
||||
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
|
||||
"boxes_ready": st.boxes_ready(),
|
||||
@@ -1099,7 +1115,9 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
|
||||
code = str((r or {}).get("code") or "").strip().upper()
|
||||
try:
|
||||
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))
|
||||
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
|
||||
gid = str(r.get("group_id") or "").strip()
|
||||
@@ -1198,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 "",
|
||||
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
|
||||
"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)
|
||||
if reader is None or not reader.enabled:
|
||||
return JSONResponse({"items": [], "enabled": False,
|
||||
|
||||
+88
-27
@@ -248,6 +248,28 @@ def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False)
|
||||
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]:
|
||||
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
||||
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
|
||||
@@ -263,16 +285,18 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
who = sender_name or sender_email
|
||||
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
|
||||
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
||||
if money["amount"] is not None:
|
||||
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||
simple = is_simple_mail_factory(order.get("factory_name"))
|
||||
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
|
||||
if money["pp_kg"] is not None:
|
||||
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 not simple:
|
||||
if money["amount"] is not None:
|
||||
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||
if money["pp_kg"] is not None:
|
||||
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"):
|
||||
facts.append(("요청 사항", order["memo"]))
|
||||
|
||||
@@ -289,12 +313,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||||
text += [f"- {k}: {v}" for k, v in facts]
|
||||
text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||||
text += ["", "[발주 품목] 제품 코드 · 제품명 · 수량 · 박스당 수량 · 박스 수 · 비고" if simple else "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||||
for i, x in enumerate(lines, start=1):
|
||||
c = cells(x)
|
||||
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {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']}"
|
||||
b = line_boxes(x)
|
||||
if simple:
|
||||
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 ""))
|
||||
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
||||
# HTML 본문 — 값은 모두 escape
|
||||
@@ -323,12 +352,14 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
hexc = color_hex(x.get("color"))
|
||||
ctd = f"{td}background:{hexc};" if hexc else td
|
||||
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(
|
||||
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}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>'
|
||||
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["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>{detail}'
|
||||
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
|
||||
# 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg)
|
||||
foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else ""
|
||||
@@ -336,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_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else ""
|
||||
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 = (
|
||||
'<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>"
|
||||
@@ -343,14 +384,12 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
|
||||
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||||
'<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'<th style="{td}">수량</th><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>'
|
||||
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>{head_detail}'
|
||||
f'<th style="{td}">비고</th></tr></thead>'
|
||||
f'<tbody>{"".join(rows)}</tbody>'
|
||||
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}">{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}{r}">{total:,}</th>{foot_detail}'
|
||||
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
||||
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||
@@ -547,7 +586,8 @@ def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
q = int(x["qty"])
|
||||
a = line_amount(q, x.get("unit_price"))
|
||||
if a is None:
|
||||
missing += 1
|
||||
if not is_bag(x.get("item_name")): # 봉투·백은 단가가 원래 없음 — "단가 미입력" 안내에서 뺀다
|
||||
missing += 1
|
||||
else:
|
||||
amount = (amount or Decimal(0)) + a
|
||||
w = to_dec(x.get("weight_g"))
|
||||
@@ -557,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 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
||||
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
||||
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}
|
||||
|
||||
|
||||
@@ -586,7 +626,8 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]
|
||||
def has_values(p: dict[str, Any]) -> bool:
|
||||
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||
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)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -598,9 +639,9 @@ MAX_PER_BOX = 1_000_000
|
||||
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 이상 정수(쉼표 허용)."""
|
||||
label = BOX_FIELDS[key]
|
||||
label = label or BOX_FIELDS[key]
|
||||
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||||
if not s:
|
||||
return None
|
||||
@@ -608,7 +649,7 @@ def parse_per_box(raw: Any, *, key: str) -> int | None:
|
||||
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
|
||||
n = int(s)
|
||||
if n < 1:
|
||||
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(뚜껑이 없으면 빈칸).")
|
||||
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(없으면 빈칸).")
|
||||
if n > MAX_PER_BOX:
|
||||
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||||
return n
|
||||
@@ -618,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}
|
||||
|
||||
|
||||
# 봉투·백(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)
|
||||
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
|
||||
|
||||
@@ -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 boxes_ready %}<b>통 수량(박스)</b>·<b>뚜껑 수량(박스)</b> = 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑이 없으면 빈칸) — 새 발주서에서 박스 수·파렛트 수를 계산합니다.{% endif %}
|
||||
이름에 "미라클 봉투"·"미라클백"이 들어간 상품은 <b>봉투·백</b> 표에서 <b>박스당 수량</b>·<b>1파렛트당 박스 수량</b>을 넣습니다(단가·무게·은 없음).
|
||||
</p>
|
||||
<div class="io-prod-bar">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
||||
@@ -151,14 +152,23 @@
|
||||
</div>
|
||||
{% if products %}
|
||||
<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 %}">
|
||||
<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>
|
||||
<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>
|
||||
<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 %}{% 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>
|
||||
{% for p in products %}
|
||||
{% for p in rows %}
|
||||
{% 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 %}>
|
||||
<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>
|
||||
{% if groups_ready %}
|
||||
<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 %}
|
||||
</select></td>
|
||||
{% 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="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 }} 은 함유량" />
|
||||
{% 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>
|
||||
{% 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="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 %}
|
||||
@@ -186,6 +201,8 @@
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -21,18 +21,20 @@
|
||||
<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 %}
|
||||
</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>
|
||||
<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="발주번호·제품 코드·제품 이름" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="erp-card-block">
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table io-table">
|
||||
<table class="erp-table io-table io-list-table">
|
||||
<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>
|
||||
{% if perms.super %}<th class="io-col-trash"><span class="sr-only">삭제</span></th>{% endif %}
|
||||
</tr></thead>
|
||||
@@ -45,6 +47,7 @@
|
||||
<td class="io-items">{{ o.items_label }}<div class="erp-row-sub">{{ o.line_count }}종</div></td>
|
||||
<td>{{ ymd(o.order_date) }}</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.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>
|
||||
@@ -61,7 +64,7 @@
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% 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 %}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -71,4 +74,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" defer></script>{% endblock %}
|
||||
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
</footer>
|
||||
</dialog>
|
||||
{%- endmacro -%}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% set active = order.status in ('open', 'partial') %}
|
||||
@@ -155,7 +155,7 @@
|
||||
</div>
|
||||
{% if receiving %}
|
||||
<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>
|
||||
<div class="erp-field io-photo-field">
|
||||
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
|
||||
@@ -262,4 +262,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" 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" %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -23,8 +23,8 @@
|
||||
</select>
|
||||
{% if not factories %}<span class="io-hint">공장이 없습니다 — 관리자가 옵션에서 먼저 공장을 추가해야 합니다.</span>{% endif %}
|
||||
</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="due_date" value="{{ vals.due_date }}" /></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 }}" aria-label="입고 예정일" /></label>
|
||||
<label class="erp-field"><span>메모</span><input type="text" name="memo" value="{{ vals.memo }}" maxlength="500" placeholder="공장 전달 사항 등" /></label>
|
||||
</div>
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
<tbody>
|
||||
{% for ln in lines %}
|
||||
{% 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-item-cell">
|
||||
<input type="hidden" name="item_code" value="{{ ln.code }}" />
|
||||
@@ -64,13 +64,20 @@
|
||||
<span class="io-pallet-vis" data-k="vis"></span>
|
||||
<span class="erp-muted" data-k="note">1파렛트 = {{ pallet_boxes }}박스</span>
|
||||
</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 %}
|
||||
</td></tr></tfoot>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<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-item-cell">
|
||||
<input type="hidden" name="item_code" value="" />
|
||||
@@ -95,4 +102,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" 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" %}
|
||||
{% from "inout/_macros.html" import due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261102a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -91,4 +91,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261102a" 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 %}
|
||||
@@ -0,0 +1,36 @@
|
||||
# [말레이시아 실적] — `app/modules/malaysia_performance/`, `malaysia_performance_db` (2026-11-20)
|
||||
|
||||
> 이 폴더는 **얇은 마운트**(`__init__.py` 하나)다. 코드·템플릿·`performance.js/css` 는 전부 실적 모듈(`app/modules/performance/`) 것을 그대로 쓴다.
|
||||
> 실적과 다른 점은 `app/modules/performance/variant.py` 의 `MY` 한 곳. 실적 화면·기능을 고치면 이 화면에도 그대로 들어간다 — 둘 다 확인.
|
||||
|
||||
## 구성
|
||||
|
||||
- 주소 `/malaysia/performance/`(매출 실적) · `/ads`(광고비) · `/settings`(톱니). 권한키 `malaysia_performance`. 메뉴 "말레이시아 실적"(관리).
|
||||
- `main.py`: `app.state.malaysia_performance_store` = `MALAYSIA_PERFORMANCE_DB_URL`(없으면 "설정 필요"), `include_router` 는 실적 다음(라우트 이름은 실적이 먼저).
|
||||
- 요청 → 마운트 의존성 `variant.use_malaysia`(async) → ContextVar `MY` → `common.get_store`·권한·`base_ctx`·`ad_spend.channel_names/roas_sales`·`dashboard.sales_ad_channels/load_unit`·금액 파싱이 이 값을 본다.
|
||||
|
||||
## 매출 실적
|
||||
|
||||
- 쇼핑몰 = 틱톡·쇼피·라자다 **그룹**(합계 열), 각 그룹 하위 **쇼핑몰**·**라이브커머스** 두 칸(직접 추가 쇼핑몰 = 수동 입력 전용). 그룹 열 = 두 칸 합계, 일 합계 = 6칸 합계.
|
||||
코드 `group_<쇼핑몰>`·`custom_<쇼핑몰>_shop`·`custom_<쇼핑몰>_live` — `scripts/sql/malaysia_performance_db_seed.sql` 과 `variant.MY` 가 같아야 한다(이름은 설정에서 바꿔도 됨).
|
||||
- 금액 = **RM 소수 2자리**. 저장은 **센(0.01 RM) 정수**(`variant.MY.scale = 100`) — 계산·수수료·ROAS 코드는 실적 그대로.
|
||||
입력 `formula.parse_amount(raw, scale)`·엑셀 `manual_upload.parse_amount(v, scale)`(RM 글자 허용), 화면 `dashboard.amount_text(v, "rm")`·`variant.num_text/money_text/input_text`, JS `money()`(`.perf data-cents`).
|
||||
- 매출 업데이트 버튼·다음 업데이트·화면 자동 새로 고침 없음(API 수집 없음 — `jobs` 는 한국 실적 것). 엑셀 업로드 샘플은 지금 쇼핑몰 이름으로 만든다(`router._manual_sample_from`).
|
||||
- 그룹 칸 아래 주황 줄 = 그 쇼핑몰 광고비(ROAS%), ROAS = 쇼핑몰 + 라이브커머스 매출 ÷ 광고비(`variant.MY.ad_lines`·`ad_roas_sales`).
|
||||
|
||||
## 광고비
|
||||
|
||||
- 채널 = 틱톡·쇼피·라자다(`tiktok`·`shopee`·`lazada`), 날짜 칸 직접 입력만(업로드·광고 API 없음). 금액 RM(센 저장).
|
||||
|
||||
## 설정
|
||||
|
||||
- 쇼핑몰 표(사용·매출 집계·수동 입력·수수료율·이름·그룹·순서·추가/삭제) + 보기 설정 + 공통 보기 설정(열 숨기기). API 인증·광고 API·자동 업데이트·암호화 키·과거 매출·테스트 데이터 카드 없음, 매출 단위 = RM 고정.
|
||||
|
||||
## DB
|
||||
|
||||
- `malaysia_performance_db` = performance_db **구조만 복사**(`pg_dump --schema-only`) + seed. 역할 `performance_app` 공유. 만드는 순서는 seed 파일 머리말.
|
||||
- performance_db 에 새 마이그레이션을 만들면 이 DB 에도 적용한다.
|
||||
|
||||
## 테스트
|
||||
|
||||
- `app/modules/performance/tests/test_malaysia_variant.py`(센 파싱·그룹 합계·광고비 줄·화면 주소·API 저장 단위·샘플), `tests/js/perf_malaysia.browser.test.js`(렌더 `perf_my_*.html`).
|
||||
@@ -0,0 +1,22 @@
|
||||
"""[말레이시아 실적] — 실적 모듈(app/modules/performance) 코드·화면을 그대로 쓰는 두 번째 인스턴스(2026-11-20).
|
||||
|
||||
주소 /malaysia/performance/…, 저장 malaysia_performance_db(실적과 같은 표 구조), 권한키 malaysia_performance.
|
||||
다른 점은 performance/variant.py MY 한 곳 — 틱톡·쇼피·라자다(쇼핑몰·라이브커머스) 수동 입력, RM 소수 2자리(센 정수 저장).
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from ..performance import build_performance_store
|
||||
from ..performance import router as _performance_router
|
||||
from ..performance.variant import use_malaysia
|
||||
|
||||
router = APIRouter(prefix="/malaysia")
|
||||
router.include_router(_performance_router, dependencies=[Depends(use_malaysia)])
|
||||
|
||||
__all__ = ["router", "build_malaysia_performance_store"]
|
||||
|
||||
|
||||
def build_malaysia_performance_store(*, dsn: str | None) -> Any:
|
||||
return build_performance_store(dsn=dsn)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
{% block head_extra %}
|
||||
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — 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" />
|
||||
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||
{% endblock %}
|
||||
@@ -64,7 +64,7 @@
|
||||
</section>
|
||||
</div>
|
||||
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261111a" defer></script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -4,6 +4,14 @@
|
||||
> 정적 파일: `app/static/performance.css`, `performance.js`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||
> 다른 모듈과 연결: 카페24 어댑터는 `app/integrations/cafe24` 토큰 재사용 · Project 주간 회의록 머리 카드가 `performance_store` 매출을 읽기 전용으로 씀 · `APP_ENCRYPTION_KEY` 는 입출고(Gmail 토큰)와 공유.
|
||||
|
||||
## 두 인스턴스 — [실적] · [말레이시아 실적] (2026-11-20)
|
||||
|
||||
- 같은 코드·템플릿·`performance.js` 를 `/performance`(한국, `performance_db`)와 `/malaysia/performance`(`malaysia_performance_db`)에 붙인다.
|
||||
다른 점은 **`variant.py` 한 곳**(`KR`·`MY`) — 저장소·권한키·주소·광고 채널·통화. 요청마다 `variant.current()`(ContextVar, 말레이시아 마운트 의존성 `use_malaysia`).
|
||||
- 고칠 때: 주소는 템플릿 `{{ pv.base }}`·JS `BASE`(`.perf data-base`)만 — **`/performance` 를 새로 하드코딩하지 말 것**.
|
||||
금액 글자는 `num`·`money_t`·`inval`(템플릿)·`money()`(JS) — 말레이시아는 센 정수(÷100, RM 소수 2자리, `data-cents`). 한국 전용 기능(API 수집·자동 업데이트·광고 API·카페24 열)은 `pv.is_kr` 로.
|
||||
- 상세 `app/modules/malaysia_performance/CLAUDE.md`. 마이그레이션은 두 DB 모두에.
|
||||
|
||||
## 구조 (네 영역 분리)
|
||||
|
||||
1. 수집 — `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리).
|
||||
@@ -79,7 +87,7 @@
|
||||
|
||||
## 매출 실적 화면 (2026-10-19)
|
||||
|
||||
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
|
||||
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 % + **전년 같은 기간 대비 %**(2026-11-16, `calc.Period.yoy_range` — 1년 전 같은 날짜, 진행 중이면 오늘까지, 연 보기는 직전 비교가 이미 전년이라 없음), 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
|
||||
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
|
||||
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
|
||||
- **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload.
|
||||
@@ -87,7 +95,12 @@
|
||||
(`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` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
|
||||
- **열 접기**(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`)에 계속 유지,
|
||||
@@ -108,9 +121,10 @@
|
||||
|
||||
## 광고비 (`/performance/ads`)
|
||||
|
||||
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
|
||||
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. (틱톡 탭은 2026-11-20 삭제 — 코드·`tiktok_ads.py`·데이터(마이그레이션 012) 모두)
|
||||
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
|
||||
- **기타광고비** 열(`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·토스·애터미아자몰 일 광고비를 연·월·일로.
|
||||
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
|
||||
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
|
||||
|
||||
@@ -22,11 +22,11 @@ from __future__ import annotations
|
||||
import csv
|
||||
import io
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from datetime import date, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any, Callable, Mapping, Sequence
|
||||
|
||||
from . import calc
|
||||
from . import calc, variant
|
||||
from .ad_sources.base import ACCOUNTS_KEY
|
||||
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
||||
|
||||
@@ -34,6 +34,7 @@ from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES
|
||||
CHANNELS: tuple[tuple[str, str], ...] = (
|
||||
("google", "구글"),
|
||||
("meta", "메타"),
|
||||
("kakao_pf", "카톡 플친"), # 2026-11-16 — 카카오톡 플러스친구(자사몰 광고, 직접 입력), ROAS 없음, 매출 탭 카페24 줄에 구글·메타 아래
|
||||
("naver", "네이버"),
|
||||
("coupang_wing", "쿠팡(윙)"),
|
||||
("coupang_rocket", "쿠팡(로켓)"),
|
||||
@@ -54,11 +55,22 @@ CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
|
||||
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
|
||||
FILE_ROAS = frozenset({"google", "meta", "naver"})
|
||||
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["coupang_wing"] = "coupang"
|
||||
|
||||
|
||||
def channel_names() -> dict[str, str]:
|
||||
"""지금 인스턴스의 광고비 탭 채널(순서 = 표 열) — 한국 실적 = CHANNELS, 말레이시아 실적 = 틱톡·쇼피·라자다(variant.MY)."""
|
||||
return dict(variant.current().ad_channels or CHANNELS)
|
||||
|
||||
|
||||
def roas_sales() -> dict[str, tuple[str, ...]]:
|
||||
"""광고 채널 → ROAS 매출 쇼핑몰 코드들(그 합계 ÷ 광고비). 말레이시아 = 쇼핑몰 + 라이브커머스."""
|
||||
v = variant.current()
|
||||
return dict(v.ad_roas_sales) if v.ad_channels else {ch: (c,) for ch, c in ROAS_SALES_CODE.items()}
|
||||
|
||||
|
||||
def roas(sales: int, spend: int) -> int | None:
|
||||
"""ROAS(%) = 매출 ÷ 광고비 × 100, 정수로 반올림. 광고비가 없으면 None."""
|
||||
if not spend or spend <= 0:
|
||||
@@ -68,7 +80,7 @@ def roas(sales: int, spend: int) -> int | None:
|
||||
|
||||
def roas_basis(code: str) -> str:
|
||||
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
|
||||
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
|
||||
return "" if code not in roas_sales() else channel_names().get(code, code)
|
||||
|
||||
|
||||
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
|
||||
@@ -93,8 +105,8 @@ def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
|
||||
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
|
||||
if code in FILE_ROAS:
|
||||
return file_of(code) if file_of else None
|
||||
mcode = ROAS_SALES_CODE.get(code)
|
||||
return None if mcode is None else roas(sales_of(mcode), spend)
|
||||
mcodes = roas_sales().get(code)
|
||||
return None if mcodes is None else roas(sum(sales_of(m) for m in mcodes), spend)
|
||||
|
||||
ROCKET_DATE_COL = 0 # 1열 날짜
|
||||
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
|
||||
@@ -476,13 +488,42 @@ 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_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
custom_from: date | None = None, custom_to: date | None = None,
|
||||
holidays: Mapping[str, str] | None = None,
|
||||
sales_codes: Sequence[str] = ()) -> dict[str, Any]:
|
||||
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
|
||||
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
|
||||
codes = list(CHANNEL_CODES)
|
||||
names = channel_names()
|
||||
codes = list(names)
|
||||
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
|
||||
@@ -512,7 +553,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
|
||||
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
|
||||
total_codes = list(sales_codes)
|
||||
need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes))
|
||||
need = sorted({m for ms in roas_sales().values() for m in ms} | set(total_codes))
|
||||
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
|
||||
|
||||
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
|
||||
@@ -522,39 +563,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
|
||||
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
|
||||
|
||||
word = {"day": "오늘" if period.start == today else "해당일",
|
||||
"week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
||||
"custom": "선택 기간"}[period.kind]
|
||||
word = _period_word(period, today)
|
||||
kpis = [
|
||||
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
||||
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
||||
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
||||
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
|
||||
"note": f"총매출 {variant.money_text(sales_total)}" if sales_total else "매출 없음"},
|
||||
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
|
||||
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
||||
]
|
||||
|
||||
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if k == "custom":
|
||||
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
||||
return f"?period={k}&d={anchor_d.isoformat()}"
|
||||
|
||||
if period.kind == "custom":
|
||||
from datetime import timedelta # noqa: WPS433
|
||||
|
||||
length = timedelta(days=period.days)
|
||||
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
||||
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
||||
else:
|
||||
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
||||
# 빠른 선택은 이번달·올해만(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},
|
||||
]}
|
||||
|
||||
nav = _period_nav(period, today)
|
||||
share = calc.by_code(cells, codes, period.start, period.end)
|
||||
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
|
||||
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||
@@ -581,7 +600,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"period_kind": period.kind,
|
||||
"today": today.isoformat(),
|
||||
"codes": codes,
|
||||
"names": dict(CHANNEL_NAMES),
|
||||
"names": names,
|
||||
"kpis": kpis,
|
||||
"table": table,
|
||||
"month": month,
|
||||
@@ -589,7 +608,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"roas_basis": {c: roas_basis(c) for c in codes},
|
||||
"detail_channels": sorted(DETAIL_CHANNELS),
|
||||
"chart_daily": calc.daily_series(period, codes, cells),
|
||||
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
|
||||
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
|
||||
# 업로드로 들어온 칸(표시용) — "날짜|채널"
|
||||
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||||
if s == "upload" and period.start <= d <= period.end),
|
||||
@@ -600,7 +619,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"formula_cells": {f"{d.isoformat()}|{c}": f for (d, c), f in
|
||||
(store.ad_formulas(period.start, period.end) if hasattr(store, "ad_formulas")
|
||||
and not migration_needed else {}).items()},
|
||||
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
|
||||
"upload_channels": [{"code": c, "name": names[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS if c in names],
|
||||
"migration_needed": migration_needed,
|
||||
# 날짜 칸 메모(마이그레이션 010) — "날짜|채널" → 메모
|
||||
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
|
||||
|
||||
@@ -156,6 +156,17 @@ class Period:
|
||||
unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간")
|
||||
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(
|
||||
kind: str,
|
||||
|
||||
@@ -12,7 +12,9 @@ from typing import Any
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
|
||||
MODULE_KEY = "performance"
|
||||
from . import variant
|
||||
|
||||
MODULE_KEY = "performance" # 한국 실적 — 요청마다는 variant.current().module_key(말레이시아 실적 = malaysia_performance)
|
||||
MODULE_NAME = "실적"
|
||||
|
||||
CONFIG_HELP = (
|
||||
@@ -20,10 +22,19 @@ CONFIG_HELP = (
|
||||
"scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 "
|
||||
"PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
|
||||
)
|
||||
CONFIG_HELP_MY = (
|
||||
"말레이시아 실적 모듈이 아직 설정되지 않았습니다. "
|
||||
"app/modules/malaysia_performance/CLAUDE.md 대로 malaysia_performance_db 를 만들고 "
|
||||
"MALAYSIA_PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
|
||||
)
|
||||
|
||||
|
||||
def config_help() -> str:
|
||||
return CONFIG_HELP if variant.current().is_kr else CONFIG_HELP_MY
|
||||
|
||||
|
||||
def get_store(request: Request) -> Any:
|
||||
return getattr(request.app.state, "performance_store", None)
|
||||
return getattr(request.app.state, variant.current().store_attr, None)
|
||||
|
||||
|
||||
def key_ring():
|
||||
@@ -60,8 +71,9 @@ def require_user(request: Request) -> dict[str, Any]:
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||
if not has_module(user, MODULE_KEY):
|
||||
raise HTTPException(status_code=403, detail=f"{MODULE_NAME} 모듈 권한이 없습니다.")
|
||||
v = variant.current()
|
||||
if not has_module(user, v.module_key):
|
||||
raise HTTPException(status_code=403, detail=f"{v.module_name} 모듈 권한이 없습니다.")
|
||||
return user
|
||||
|
||||
|
||||
@@ -78,7 +90,7 @@ def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[s
|
||||
user = require_admin(request) if admin else require_user(request)
|
||||
st = get_store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail=CONFIG_HELP)
|
||||
raise HTTPException(status_code=503, detail=config_help())
|
||||
return st, user
|
||||
|
||||
|
||||
@@ -90,8 +102,9 @@ def guard(request: Request, *, admin: bool = False):
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return login_redirect(request)
|
||||
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
|
||||
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
|
||||
v = variant.current()
|
||||
if not has_module(user, v.module_key) or (admin and not is_admin(user)):
|
||||
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{v.module_name} 접근 권한이 없습니다."
|
||||
return render_template(request, "denied.html",
|
||||
{"reason": reason, "user": user, "is_admin": is_admin(user)}, status_code=403)
|
||||
st = get_store(request)
|
||||
@@ -106,21 +119,25 @@ def render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse
|
||||
|
||||
return render_template(
|
||||
request, "denied.html",
|
||||
{"reason": CONFIG_HELP, "user": user, "is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active=MODULE_KEY)},
|
||||
{"reason": config_help(), "user": user, "is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active=variant.current().module_key)},
|
||||
status_code=503,
|
||||
)
|
||||
|
||||
|
||||
def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "실적") -> dict[str, Any]:
|
||||
def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "") -> dict[str, Any]:
|
||||
from app.main import build_erp_nav # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
v = variant.current()
|
||||
if not v.is_kr and page_title:
|
||||
page_title = f"말레이시아 {page_title}"
|
||||
return {
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active=MODULE_KEY),
|
||||
"nav_items": build_erp_nav(user, active=v.module_key),
|
||||
"active_tab": active_tab,
|
||||
"page_title": page_title,
|
||||
"page_subtitle": "쇼핑몰 통합 매출",
|
||||
"page_title": page_title or v.module_name,
|
||||
"page_subtitle": "쇼핑몰 통합 매출" if v.is_kr else "틱톡·쇼피·라자다 매출",
|
||||
**variant.template_ctx(),
|
||||
}
|
||||
|
||||
@@ -145,12 +145,21 @@ def load_hidden(store: Any) -> set[str]:
|
||||
return set(_shared_setting(store, HIDDEN_SETTING) or ())
|
||||
|
||||
|
||||
RM_UNIT = "rm" # 말레이시아 실적(2026-11-20) — 금액 = 센 정수, 화면 = RM 소수 2자리(단위 설정 없음)
|
||||
|
||||
|
||||
def load_unit(store: Any) -> str:
|
||||
from . import variant # noqa: WPS433
|
||||
|
||||
if not variant.current().is_kr:
|
||||
return RM_UNIT
|
||||
return normalize_unit(_shared_setting(store, UNIT_SETTING))
|
||||
|
||||
|
||||
def amount_text(value: Any, unit: str = "won") -> str:
|
||||
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
|
||||
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림), RM 은 센 ÷ 100 소수 두 자리."""
|
||||
if unit == RM_UNIT:
|
||||
return f"{(Decimal(int(value)) / 100).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,.2f}"
|
||||
div, places, _ = UNITS[normalize_unit(unit)]
|
||||
if div == 1:
|
||||
return f"{int(value):,}"
|
||||
@@ -161,7 +170,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],
|
||||
period: Any, q_start: date, q_end: date) -> None:
|
||||
"""매출 칸 아래 광고비(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 = 수수료 차감 매출 기준
|
||||
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
|
||||
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
|
||||
@@ -217,11 +226,13 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
|
||||
|
||||
|
||||
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
|
||||
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고,
|
||||
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타·카톡 플친(자사몰 광고), 네이버 = 네이버 광고,
|
||||
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
|
||||
from . import ad_spend # noqa: WPS433
|
||||
from . import ad_spend, variant # noqa: WPS433
|
||||
|
||||
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)}
|
||||
if variant.current().ad_lines: # 말레이시아 실적 — 쇼핑몰 그룹(합계) 칸 아래에 그 쇼핑몰 광고비
|
||||
return dict(variant.current().ad_lines)
|
||||
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친")), "naver": (("naver", ""),)}
|
||||
for ch, c in ad_spend.ROAS_SALES_CODE.items():
|
||||
out[c] = out.get(c, ()) + ((ch, ""),)
|
||||
return out
|
||||
@@ -261,7 +272,10 @@ 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)
|
||||
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)
|
||||
gb = groupbuy_code(markets)
|
||||
# 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다
|
||||
@@ -292,6 +306,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
|
||||
"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(summary, codes, period.start, period.end)
|
||||
# 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다
|
||||
@@ -315,7 +331,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
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, *group_members], cells, period, q_start, q_end)
|
||||
for r in table:
|
||||
for g, members in group_members.items():
|
||||
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
|
||||
|
||||
@@ -80,12 +80,13 @@ class _Parser:
|
||||
return Decimal(tok)
|
||||
|
||||
|
||||
def parse_amount(raw: object) -> tuple[int | None, str | None]:
|
||||
"""칸 입력 → (원 단위 금액, 계산식). 빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음."""
|
||||
def parse_amount(raw: object, scale: int = 1) -> tuple[int | None, str | None]:
|
||||
"""칸 입력 → (저장 단위 금액, 계산식). scale=100 = 센(말레이시아 실적 RM 소수 2자리 — 12.5 → 1250).
|
||||
빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음."""
|
||||
text = str(raw if raw is not None else "").strip()
|
||||
for a, b in _OPS.items():
|
||||
text = text.replace(a, b)
|
||||
text = re.sub(r"[,\s원]", "", text)
|
||||
text = re.sub(r"[,\s원]|RM", "", text, flags=re.IGNORECASE)
|
||||
if text.startswith("="): # 엑셀 버릇으로 = 를 붙여도 된다
|
||||
text = text[1:]
|
||||
if text == "":
|
||||
@@ -100,7 +101,7 @@ def parse_amount(raw: object) -> tuple[int | None, str | None]:
|
||||
raise FormulaError("계산할 수 없는 식입니다.") from None
|
||||
if p.peek() is not None:
|
||||
raise FormulaError("계산식이 올바르지 않습니다.")
|
||||
amount = int(value.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||
amount = int((value * scale).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||
# 숫자 하나(앞 부호만 있는 것 포함)는 계산식이 아니다
|
||||
is_formula = any(t in "+-*/()" for t in tokens[1:]) or (tokens[0] == "(")
|
||||
return amount, (text if is_formula else None)
|
||||
|
||||
@@ -77,8 +77,8 @@ def parse_date(value: Any) -> date | None:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
|
||||
|
||||
def parse_amount(value: Any) -> int | None:
|
||||
"""금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||
def parse_amount(value: Any, scale: int = 1) -> int | None:
|
||||
"""금액 칸 → 저장 단위 정수(원, scale=100 이면 센 — 말레이시아 실적 RM 소수 2자리). 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||
if value is None or isinstance(value, bool):
|
||||
if value is None:
|
||||
return None
|
||||
@@ -86,7 +86,7 @@ def parse_amount(value: Any) -> int | None:
|
||||
if isinstance(value, (int, float, Decimal)):
|
||||
num = Decimal(str(value))
|
||||
else:
|
||||
text = re.sub(r"[,\s원₩]", "", str(value))
|
||||
text = re.sub(r"[,\s원₩]|RM", "", str(value), flags=re.IGNORECASE)
|
||||
if text == "":
|
||||
return None
|
||||
try:
|
||||
@@ -95,7 +95,7 @@ def parse_amount(value: Any) -> int | None:
|
||||
raise ValueError from None
|
||||
if not num.is_finite():
|
||||
raise ValueError
|
||||
return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||
return int((num * scale).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
|
||||
@@ -111,7 +111,7 @@ def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[st
|
||||
|
||||
|
||||
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
|
||||
extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult:
|
||||
extra_names: Mapping[str, Iterable[str]] | None = None, scale: int = 1) -> ParseResult:
|
||||
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
|
||||
if not content:
|
||||
raise UploadError("빈 파일입니다.")
|
||||
@@ -160,7 +160,7 @@ def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: d
|
||||
amounts: dict[int, int] = {}
|
||||
for i, raw in cells.items():
|
||||
try:
|
||||
amt = parse_amount(raw)
|
||||
amt = parse_amount(raw, scale)
|
||||
except ValueError:
|
||||
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
|
||||
continue
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
||||
GET /performance/settings 실적 설정(관리자)
|
||||
JSON API — 모듈 권한
|
||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||
PUT /performance/api/my-col-fold 일자별 표에서 접은 열(보는 사람 본인에게만, 매출 실적·광고비 따로)
|
||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
|
||||
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
|
||||
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
||||
@@ -56,7 +57,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
from . import calc, common
|
||||
from . import calc, common, variant
|
||||
from .adapters.registry import all_adapters, get_adapter
|
||||
|
||||
router = APIRouter(prefix="/performance", tags=["performance"])
|
||||
@@ -65,7 +66,7 @@ MAX_EVENT_DAYS = 31
|
||||
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
|
||||
MAX_BACKFILL_DAYS = 366
|
||||
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
|
||||
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
|
||||
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(저장 단위 — 원, 말레이시아 실적은 센)
|
||||
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
|
||||
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
@@ -113,7 +114,7 @@ def _code_or_404(store: Any, code: str):
|
||||
@router.get("/health")
|
||||
def health(request: Request) -> JSONResponse:
|
||||
st = common.get_store(request)
|
||||
return JSONResponse({"ok": st is not None, "module": "performance",
|
||||
return JSONResponse({"ok": st is not None, "module": variant.current().module_key,
|
||||
"encryption_key": common.key_status()["ok"]})
|
||||
|
||||
|
||||
@@ -151,6 +152,7 @@ def dashboard_page(
|
||||
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})
|
||||
|
||||
|
||||
@@ -163,7 +165,7 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
|
||||
|
||||
from . import auto_sync # noqa: WPS433
|
||||
|
||||
if not auto_sync.enabled():
|
||||
if not auto_sync.enabled() or not variant.current().is_kr: # 말레이시아 실적은 API 수집 없음(수동 입력만)
|
||||
return None
|
||||
try:
|
||||
sched = auto_sync.load_schedules(store)[0][kind]
|
||||
@@ -177,11 +179,15 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
|
||||
"label": auto_sync.describe(sched)}
|
||||
|
||||
|
||||
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]:
|
||||
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str] | None:
|
||||
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
|
||||
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다."""
|
||||
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다.
|
||||
말레이시아 실적은 없음 — 진행 작업(jobs)은 한국 실적 것이라 보면 엉뚱하게 새로 고친다."""
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
if not variant.current().is_kr:
|
||||
return None
|
||||
|
||||
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
||||
return {"kind": kind, "seen": job.id if job else ""}
|
||||
|
||||
@@ -206,7 +212,7 @@ def _unit_ctx(store: Any, ctx: dict[str, Any]) -> None:
|
||||
|
||||
unit = load_unit(store)
|
||||
ctx["unit"] = unit
|
||||
ctx["unit_label"] = UNITS[unit][2]
|
||||
ctx["unit_label"] = UNITS[unit][2] if unit in UNITS else "RM"
|
||||
ctx["amt"] = lambda v: amount_text(v, unit)
|
||||
|
||||
|
||||
@@ -241,8 +247,16 @@ def ads_page(
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||
sales_codes=total_sales_codes(_sales_marketplaces(store)),
|
||||
)
|
||||
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
||||
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.
|
||||
_ad_update_ctx(store, user, ctx)
|
||||
_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 .ad_sources.registry import get_source # noqa: WPS433
|
||||
from .ad_sync import last_ad_update_at # noqa: WPS433
|
||||
@@ -257,9 +271,6 @@ def ads_page(
|
||||
ctx["ad_running"] = jobs.running_job("ads") is not None
|
||||
ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
|
||||
ctx["update_watch"] = _update_watch("ads", user)
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/ads.html",
|
||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
@@ -273,6 +284,12 @@ def settings_page(request: Request):
|
||||
store, user = g
|
||||
from .dashboard import build_settings # noqa: WPS433
|
||||
|
||||
if not variant.current().is_kr: # 말레이시아 실적 — 쇼핑몰(수동 입력)·보기 설정만(API 인증·광고 API·자동 업데이트 카드 없음)
|
||||
ctx = build_settings(store, configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
|
||||
_unit_ctx(store, ctx)
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/settings.html",
|
||||
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
||||
creds, _ = common.services(request, store)
|
||||
ad_creds, ad_sync = _ad_services(store)
|
||||
versions = creds.key_versions_in_use()
|
||||
@@ -502,7 +519,7 @@ def _cell_amount(raw: Any) -> tuple[int | None, str | None]:
|
||||
from .formula import FormulaError, parse_amount # noqa: WPS433
|
||||
|
||||
try:
|
||||
amount, formula = parse_amount(raw)
|
||||
amount, formula = parse_amount(raw, variant.current().scale)
|
||||
except FormulaError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"{exc} (숫자 또는 1000+2000 같은 계산식)") from None
|
||||
if amount is not None and abs(amount) > MAX_MANUAL_AMOUNT:
|
||||
@@ -539,13 +556,31 @@ def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, An
|
||||
|
||||
@router.get("/api/manual-sales/sample.xlsx")
|
||||
def api_manual_sample(request: Request) -> Any:
|
||||
common.require_store(request)
|
||||
store, _ = common.require_store(request)
|
||||
if not variant.current().is_kr: # 말레이시아 실적 — 지금 수동 입력 쇼핑몰 이름으로 만든다(한국 샘플은 한국 쇼핑몰)
|
||||
return _manual_sample_from(store)
|
||||
if not MANUAL_SAMPLE_PATH.is_file():
|
||||
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
|
||||
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
|
||||
|
||||
def _manual_sample_from(store: Any) -> Any:
|
||||
import io # noqa: WPS433
|
||||
|
||||
import openpyxl # noqa: WPS433
|
||||
from fastapi.responses import Response # noqa: WPS433
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.append(["날짜", *[m["name"] for m in store.list_marketplaces() if m.get("manual_input") and not m.get("is_group")]])
|
||||
ws.append([today_kst().isoformat()])
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return Response(buf.getvalue(), headers={"Content-Disposition": 'attachment; filename="upload_sample.xlsx"'},
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
|
||||
|
||||
@router.post("/api/manual-sales/upload")
|
||||
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
|
||||
@@ -559,7 +594,8 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
|
||||
markets = [m for m in store.list_marketplaces() if get_adapter(m["code"]) is not None and m["enabled"]]
|
||||
extra = {m["code"]: tuple(n for n in (get_adapter(m["code"]).name, _short_name(m["name"])) if n) for m in markets}
|
||||
try:
|
||||
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
|
||||
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra,
|
||||
scale=variant.current().scale)
|
||||
except manual_upload.UploadError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
names = {m["code"]: m["name"] for m in markets}
|
||||
@@ -588,9 +624,9 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
|
||||
# JSON API — 광고비(모듈 권한자 누구나)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _ad_channel(channel: str) -> str:
|
||||
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
||||
from .ad_spend import channel_names # noqa: WPS433
|
||||
|
||||
if channel not in CHANNEL_NAMES:
|
||||
if channel not in channel_names():
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||
return channel
|
||||
|
||||
@@ -602,14 +638,14 @@ MEMO_MAX = 1000
|
||||
def api_cell_memo(request: Request, kind: str, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""날짜 칸 메모(2026-10-22, 마이그레이션 010) — kind = sales(매출 실적, 쇼핑몰) / ad(광고비, 광고 채널).
|
||||
memo 가 비면 지움. 칸에 금액을 넣을 수 있는 사람(모듈 권한자 누구나)이 쓴다."""
|
||||
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
||||
from .ad_spend import channel_names # noqa: WPS433
|
||||
from .db import MemoMigrationNeeded # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
if kind == "sales":
|
||||
_code_or_404(store, code)
|
||||
elif kind == "ad":
|
||||
if code not in CHANNEL_NAMES:
|
||||
if code not in channel_names():
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 메모 종류입니다.")
|
||||
@@ -661,7 +697,7 @@ def api_ad_spend_details(request: Request, channel: str, from_: str = Query(...,
|
||||
rows = store.ad_details(channel, start, end)
|
||||
except ad_spend.AdMigrationNeeded as exc:
|
||||
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
|
||||
return JSONResponse({"channel": channel, "name": ad_spend.channel_names()[channel], "from": start.isoformat(),
|
||||
"to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
|
||||
|
||||
|
||||
@@ -682,7 +718,7 @@ def api_ad_spend_upload(
|
||||
_ad_channel(channel)
|
||||
parser = ad_spend.PARSERS.get(channel)
|
||||
if parser is None:
|
||||
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
|
||||
raise HTTPException(status_code=400, detail=f"{ad_spend.channel_names()[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
|
||||
uploads = list(files or []) + ([file] if file is not None else [])
|
||||
if not uploads:
|
||||
raise HTTPException(status_code=400, detail="파일을 고르세요.")
|
||||
@@ -710,7 +746,7 @@ def api_ad_spend_upload(
|
||||
except ad_spend.AdMigrationNeeded as exc:
|
||||
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||
days = sorted(d for d, _ in res.entries)
|
||||
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
|
||||
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.channel_names()[channel],
|
||||
"total": sum(a for _, a in res.entries), "skipped": res.skipped, "files": len(uploads),
|
||||
"overlap_days": len(overlap), "empty_days": [d.isoformat() for d in res.empty_days[:62]],
|
||||
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
||||
@@ -984,6 +1020,39 @@ def api_display_unit(request: Request, payload: dict[str, Any] = Body(...)) -> J
|
||||
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
|
||||
|
||||
|
||||
@@ -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 %}
|
||||
@@ -1,16 +1,16 @@
|
||||
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||
<nav class="perf-tabs" aria-label="{{ pv.module_name }} 메뉴">
|
||||
<div class="perf-tabs-main" role="tablist">
|
||||
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/"
|
||||
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="{{ pv.base }}/"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a>
|
||||
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
|
||||
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="{{ pv.base }}/ads"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||
</div>
|
||||
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
|
||||
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="{{ pv.base }}/settings"
|
||||
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||
</nav>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120a" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -8,12 +8,12 @@
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
||||
{%- else -%}{{ num(v) }}{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
|
||||
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
|
||||
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %}>
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<div class="perf-toolbar">
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
{% include "performance/_period_nav.html" %}
|
||||
|
||||
<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="{{ pv.base }}/ads"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||
<input type="hidden" name="period" value="custom" />
|
||||
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
|
||||
<span class="perf-muted">~</span>
|
||||
@@ -34,21 +34,7 @@
|
||||
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||
</form>
|
||||
|
||||
{# 광고비 업데이트(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 %}
|
||||
{% include "performance/_ad_update.html" %}
|
||||
</div>
|
||||
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
||||
|
||||
@@ -66,7 +52,7 @@
|
||||
<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>
|
||||
<span class="perf-muted">{{ k.note }}</span>
|
||||
{% else %}
|
||||
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
|
||||
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">{{ money_t(k.value) }}</b>
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
@@ -94,7 +80,7 @@
|
||||
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
||||
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
|
||||
{#- 열 너비(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">
|
||||
<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>
|
||||
<tr>
|
||||
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
@@ -117,7 +103,7 @@
|
||||
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) if not up and not ap else none %}
|
||||
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) -#}
|
||||
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if up %} is-upload{% endif %}{% if ap %} is-api{% endif %}{% if memo %} has-memo{% endif %}"
|
||||
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-memo-code="{{ c }}" data-manual-value="{{ v if v else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-memo-code="{{ c }}" data-manual-value="{{ inval(v) if v else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
{% else %}
|
||||
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
{% endif %}
|
||||
@@ -128,11 +114,17 @@
|
||||
</table>
|
||||
</div>
|
||||
{% if period_kind != 'year' %}
|
||||
{% if pv.is_kr %}
|
||||
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
|
||||
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
|
||||
파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(1000+2000 처럼 = 없이 입력하면 바로 계산), 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
|
||||
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
|
||||
{% else %}
|
||||
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>(RM, 소수 2자리)를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰(쇼핑몰 + 라이브커머스) 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출).
|
||||
파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(10.5+20 처럼 = 없이 입력하면 바로 계산).</p>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -183,7 +175,7 @@
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적 광고비</h2></div>
|
||||
<div class="perf-year-sum">
|
||||
<div><span>광고비</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
|
||||
<div><span>광고비</span><b>{{ money_t(year.total.gross) }}</b></div>
|
||||
</div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-year">
|
||||
@@ -209,12 +201,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if pv.is_kr %}
|
||||
<p class="perf-foot perf-muted">
|
||||
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
|
||||
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
|
||||
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다.
|
||||
</p>
|
||||
{% else %}
|
||||
<p class="perf-foot perf-muted">
|
||||
금액 단위 RM. ROAS = 그 쇼핑몰(쇼핑몰 + 라이브커머스) 매출 ÷ 광고비 × 100. 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<script type="application/json" id="perf-data">{{ {
|
||||
@@ -225,7 +223,7 @@
|
||||
"period_kind": period_kind,
|
||||
"memo_kind": "ad",
|
||||
"today": today,
|
||||
"manual_api": "/performance/api/ad-spend/",
|
||||
"manual_api": pv.base ~ "/api/ad-spend/",
|
||||
"manual_word": "광고비",
|
||||
"period_start": period.start.isoformat(),
|
||||
"period_end": period.end.isoformat(),
|
||||
@@ -237,4 +235,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261120a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -9,7 +9,7 @@
|
||||
{%- endmacro -%}
|
||||
{#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#}
|
||||
{%- macro money(v) -%}
|
||||
{%- if unit == 'won' -%}₩{{ amt(v) }}{%- else -%}{{ amt(v) }}<small class="perf-unit-suffix">{{ unit_label }}</small>{%- endif -%}
|
||||
{%- if unit == 'won' -%}₩{{ amt(v) }}{%- elif unit == 'rm' -%}RM {{ amt(v) }}{%- else -%}{{ amt(v) }}<small class="perf-unit-suffix">{{ unit_label }}</small>{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#}
|
||||
{%- macro adl(lines) -%}
|
||||
@@ -30,7 +30,7 @@
|
||||
{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
<section class="perf" id="perf-dash" data-metric="{{ metric }}">
|
||||
<section class="perf" id="perf-dash" data-metric="{{ metric }}" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %}>
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<!-- ── 기간 · 필터 · 업데이트 ── -->
|
||||
@@ -44,7 +44,7 @@
|
||||
|
||||
{% include "performance/_period_nav.html" %}
|
||||
|
||||
<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="{{ pv.base }}/"{% 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>
|
||||
@@ -55,7 +55,7 @@
|
||||
|
||||
<details class="perf-filter" id="perf-filter">
|
||||
<summary class="erp-btn erp-btn-outline">쇼핑몰: {% if selected_all %}전체{% else %}{{ codes | length }}곳{% endif %}</summary>
|
||||
<form class="perf-filter-pop" method="get" action="/performance/">
|
||||
<form class="perf-filter-pop" method="get" action="{{ pv.base }}/">
|
||||
<input type="hidden" name="period" value="{{ period_kind }}" />
|
||||
{% if period_kind == 'custom' %}
|
||||
<input type="hidden" name="from" value="{{ period.start.isoformat() }}" />
|
||||
@@ -73,6 +73,7 @@
|
||||
</form>
|
||||
</details>
|
||||
|
||||
{% if pv.is_kr %}{#- 말레이시아 실적은 API 수집 없음(수동 입력만) — 업데이트 줄 없음 -#}
|
||||
<div class="perf-update">
|
||||
<span class="perf-muted" id="perf-last-update">마지막 업데이트
|
||||
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
||||
@@ -86,10 +87,11 @@
|
||||
{% if running %}업데이트 중 · 진행 보기{% else %}매출 업데이트{% endif %}
|
||||
</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if no_marketplaces %}
|
||||
<div class="perf-notice">매출에 포함된 쇼핑몰이 없습니다. {% if is_admin %}<a href="/performance/settings">실적 설정</a>에서 쇼핑몰 사용을 켜세요.{% endif %}</div>
|
||||
<div class="perf-notice">매출에 포함된 쇼핑몰이 없습니다. {% if is_admin %}<a href="{{ pv.base }}/settings">{{ pv.module_name }} 설정</a>에서 쇼핑몰 사용을 켜세요.{% endif %}</div>
|
||||
{% endif %}
|
||||
|
||||
{% if problems %}
|
||||
@@ -111,6 +113,14 @@
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% 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>
|
||||
{% endfor %}
|
||||
|
||||
@@ -119,7 +129,7 @@
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
|
||||
<span class="perf-head-notes">{% if unit != 'won' %}<span class="perf-muted">단위: {{ unit_label }}</span>{% endif %}
|
||||
<span class="perf-adl-note" title="매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값. 카페24 는 구글·메타"><span class="perf-adl-key"></span>광고비(ROAS%)</span></span>
|
||||
<span class="perf-adl-note" title="매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값.{% if pv.is_kr %} 카페24 는 구글·메타{% else %} 쇼핑몰 그룹(합계) 칸 아래, ROAS = 쇼핑몰 + 라이브커머스 매출 ÷ 광고비{% endif %}"><span class="perf-adl-key"></span>광고비(ROAS%)</span></span>
|
||||
{% if manual_upload_names %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload"
|
||||
title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button>
|
||||
@@ -134,7 +144,7 @@
|
||||
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
||||
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#}
|
||||
{#- 열 너비(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">
|
||||
<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>
|
||||
<tr>
|
||||
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
@@ -162,7 +172,7 @@
|
||||
{% set gattr %}{% if sub %} data-group-child="{{ col.group }}"{% endif %}{% endset %}
|
||||
{% set gc0 %}{% if sub %}<div class="perf-gc">{% endif %}{% endset %}{% set gc1 %}{% if sub %}</div>{% endif %}{% endset %}
|
||||
{% 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) }}{{ adl(r.ads[c]) }}</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>
|
||||
@@ -171,7 +181,7 @@
|
||||
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
|
||||
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) — 우클릭 메모 삽입·수정·삭제, 있으면 칸 오른쪽 위 빨간 삼각형 -#}
|
||||
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if glast %} is-glast{% endif %}{% if memo %} has-memo{% endif %}"{{ gattr }} data-manual-code="{{ c }}" data-date="{{ r.date }}" data-memo-code="{{ c }}"
|
||||
data-manual-value="{{ m.gross if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0">{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</td>
|
||||
data-manual-value="{{ inval(m.gross) if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0">{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</td>
|
||||
{% else %}
|
||||
{#- 메모(2026-10-22) — API 쇼핑몰 날짜 칸도 우클릭 메모(data-memo-code). 왼쪽 클릭은 그대로 주문 내역 -#}
|
||||
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) if r.kind == 'day' else none %}
|
||||
@@ -186,7 +196,7 @@
|
||||
</div>
|
||||
{% if manual_codes and period_kind != 'year' %}
|
||||
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
|
||||
비우고 저장하면 다시 API 수집값. <b>1000+2000</b> 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
|
||||
비우고 저장하면 {% if pv.is_kr %}다시 API 수집값{% else %}지움{% endif %}. <b>{{ '1000+2000' if pv.is_kr else '10.5+20' }}</b> 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -270,11 +280,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if pv.is_kr %}
|
||||
<p class="perf-foot perf-muted">
|
||||
매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며
|
||||
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
|
||||
일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).
|
||||
</p>
|
||||
{% else %}
|
||||
<p class="perf-foot perf-muted">
|
||||
금액 단위 RM(소수 2자리). 쇼핑몰마다 쇼핑몰 매출과 라이브커머스 매출을 따로 입력하고, 쇼핑몰 그룹 열 = 두 매출 합계입니다.
|
||||
수수료는 그날 적용되는 수수료율로 계산하며 센(0.01 RM) 미만 반올림합니다. 일 합계·상단 금액·그래프·누적 = 모든 쇼핑몰·라이브커머스 합계.
|
||||
</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<script type="application/json" id="perf-data">{{ {
|
||||
@@ -294,4 +311,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261120a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120a" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
<section class="perf perf-settings" id="perf-settings">
|
||||
<section class="perf perf-settings" id="perf-settings" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %}>
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
|
||||
{% if is_admin and not key_info.ok %}
|
||||
{% set api_cols = pv.is_kr %}{#- 말레이시아 실적 = 수동 입력만(API 연동·연결 상태·동기화 칸 없음) -#}
|
||||
{% if is_admin and pv.is_kr and not key_info.ok %}
|
||||
<div class="perf-notice is-warn">
|
||||
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
|
||||
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
|
||||
@@ -20,8 +21,9 @@
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">쇼핑몰 설정</h2>
|
||||
{% if is_admin %}
|
||||
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
|
||||
{% if api_cols %}<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
|
||||
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있고, API 가 설정돼 있어도 매출 업데이트(수동·자동)에서 빠집니다.</span>
|
||||
{% else %}<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. 매출은 매출 실적 일자별 표의 날짜 칸에 직접 입력합니다(RM, 소수 2자리).</span>{% endif %}
|
||||
{% else %}
|
||||
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
||||
{% endif %}
|
||||
@@ -35,9 +37,9 @@
|
||||
<th>매출 집계</th>
|
||||
<th>수동 입력</th>{% endif %}
|
||||
<th>수수료율</th>
|
||||
{% if is_admin %}<th>API 설정</th>
|
||||
{% if is_admin and api_cols %}<th>API 설정</th>
|
||||
<th>연결 상태</th>{% endif %}
|
||||
<th>마지막 동기화</th>
|
||||
{% if api_cols %}<th>마지막 동기화</th>{% endif %}
|
||||
{% if is_admin %}<th></th>{% endif %}
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -51,7 +53,7 @@
|
||||
{% if is_admin %}<span class="perf-drag" title="끌어서 순서 변경(그룹은 하위 쇼핑몰과 함께 움직임)" aria-hidden="true">⠿</span>{% endif %}
|
||||
<span class="perf-group-name">{{ r.name }}</span> <span class="perf-pill">그룹</span>
|
||||
</th>
|
||||
<td colspan="{{ 7 if is_admin else 2 }}" class="perf-muted">하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침)</td>
|
||||
<td colspan="{{ (7 if is_admin else 2) - (0 if api_cols else (3 if is_admin else 1)) }}" class="perf-muted">하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침)</td>
|
||||
{% if is_admin %}
|
||||
<td class="perf-nowrap">
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rename">이름 변경</button>
|
||||
@@ -87,7 +89,7 @@
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
|
||||
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
|
||||
</td>
|
||||
{% if is_admin %}
|
||||
{% if is_admin and api_cols %}
|
||||
<td>
|
||||
{% if r.manual_only %}<span class="perf-pill">수동 입력 전용</span>
|
||||
{% elif r.shared %}<span class="perf-pill">공통 연동</span>
|
||||
@@ -102,7 +104,7 @@
|
||||
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
||||
{% if api_cols %}<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>{% endif %}
|
||||
{% if is_admin %}
|
||||
<td class="perf-nowrap">
|
||||
{% if r.is_custom %}
|
||||
@@ -138,7 +140,7 @@
|
||||
{% endif %}
|
||||
<p class="perf-foot perf-muted">
|
||||
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
||||
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
|
||||
{% if is_admin and api_cols %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -169,6 +171,7 @@
|
||||
<h2 class="perf-h">공통 보기 설정</h2>
|
||||
<span class="perf-muted">모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.</span>
|
||||
</div>
|
||||
{% if pv.is_kr %}{#- 말레이시아 실적은 RM 고정 -#}
|
||||
<div class="perf-opt-row">
|
||||
<span class="perf-opt-label">매출 단위</span>
|
||||
<div class="perf-quick" role="radiogroup" aria-label="매출 단위">
|
||||
@@ -180,6 +183,7 @@
|
||||
<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>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="perf-opt-row">
|
||||
<span class="perf-opt-label">숨길 쇼핑몰</span>
|
||||
<div class="perf-hide-list">
|
||||
@@ -192,7 +196,7 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if is_admin and auto_sync_settings %}
|
||||
{% if is_admin and pv.is_kr 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 %}
|
||||
@@ -249,7 +253,7 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if is_admin %}
|
||||
{% if is_admin and pv.is_kr %}
|
||||
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
|
||||
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
|
||||
<div class="erp-card perf-card" id="perf-ad-sources">
|
||||
@@ -347,4 +351,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261120a" defer></script>{% endblock %}
|
||||
|
||||
@@ -120,7 +120,7 @@ class _Store:
|
||||
def test_ad_dashboard_month():
|
||||
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
sales_codes=["cafe24"])
|
||||
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||
assert ctx["codes"] == ["google", "meta", "kakao_pf", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||
"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 없음
|
||||
k = {x["key"]: x for x in ctx["kpis"]}
|
||||
|
||||
@@ -380,3 +380,30 @@ def test_cafe24_real_shows_same_ad_lines(client):
|
||||
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():
|
||||
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["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
|
||||
|
||||
@@ -187,6 +187,29 @@ def test_kpi_is_net_only():
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||
assert [k["key"] for k in ctx["kpis"]] == ["net"]
|
||||
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):
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""[말레이시아 실적](2026-11-20) — 실적 라우터를 /malaysia/performance 에 한 번 더 붙인 인스턴스(variant.MY).
|
||||
|
||||
틱톡·쇼피·라자다 그룹(쇼핑몰 + 라이브커머스 하위), 금액 = 센 정수(RM 소수 2자리), 광고비 채널 = 틱톡·쇼피·라자다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import common, dashboard, formula, manual_upload, variant
|
||||
|
||||
TODAY = date(2026, 10, 7)
|
||||
D5 = date(2026, 10, 5)
|
||||
|
||||
|
||||
def _row(code, name, sort, **kw):
|
||||
return {"code": code, "name": name, "sort_order": sort, "enabled": True, "include_in_sales": True,
|
||||
"manual_input": True, "is_custom": True, "is_group": False, "parent_code": None, **kw}
|
||||
|
||||
|
||||
class _Store:
|
||||
"""scripts/sql/malaysia_performance_db_seed.sql 과 같은 행 — 그룹 3 + 하위(쇼핑몰·라이브) 6."""
|
||||
|
||||
def __init__(self):
|
||||
self.rows = []
|
||||
for i, (c, n) in enumerate((("tiktok", "틱톡"), ("shopee", "쇼피"), ("lazada", "라자다"))):
|
||||
self.rows += [_row(f"group_{c}", n, i * 10 + 10, is_group=True, include_in_sales=False, manual_input=False),
|
||||
_row(f"custom_{c}_shop", f"{n} 쇼핑몰", i * 10 + 11, parent_code=f"group_{c}"),
|
||||
_row(f"custom_{c}_live", f"{n} 라이브커머스", i * 10 + 12, parent_code=f"group_{c}")]
|
||||
self.manual = {(D5, "custom_tiktok_shop"): 123_450, (D5, "custom_tiktok_live"): 10_005, # RM 1,234.50 · 100.05
|
||||
(D5, "custom_shopee_shop"): 50_000}
|
||||
self.ads = {(D5, "tiktok"): 26_691} # RM 266.91 → ROAS = 1,334.55 ÷ 266.91 = 500%
|
||||
self.saved = []
|
||||
|
||||
def get_setting(self, key):
|
||||
return None
|
||||
|
||||
def list_marketplaces(self):
|
||||
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
return {k: v for k, v in self.manual.items() if start <= k[0] <= end and k[1] in codes}
|
||||
|
||||
manual_amounts = lambda self, start, end, codes, active_only=True: self.daily_amounts(start, end, codes) # noqa: E731
|
||||
|
||||
def rate_table(self):
|
||||
return {}
|
||||
|
||||
def statuses(self):
|
||||
return {}
|
||||
|
||||
def last_update_at(self):
|
||||
return None
|
||||
|
||||
def running_codes(self):
|
||||
return []
|
||||
|
||||
def ad_amounts(self, start, end):
|
||||
rows = {k: v for k, v in self.ads.items() if start <= k[0] <= end}
|
||||
return rows, {k: "manual" for k in rows}
|
||||
|
||||
def set_manual_sale(self, code, d, amount, user="", formula=None):
|
||||
self.saved.append(("sale", code, d, amount, formula))
|
||||
|
||||
def api_amount(self, code, d):
|
||||
return 0
|
||||
|
||||
def set_ad_spend(self, channel, d, amount, *, source, user="", formula=None):
|
||||
self.saved.append(("ad", channel, d, amount, formula))
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def my():
|
||||
token = variant._current.set(variant.MY)
|
||||
yield
|
||||
variant._current.reset(token)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
perf_router = importlib.import_module("app.modules.performance.router")
|
||||
from app.modules.malaysia_performance import router as my_router
|
||||
|
||||
store = _Store()
|
||||
user = {"email": "king@x", "name": "King", "is_admin": True}
|
||||
|
||||
class _Creds:
|
||||
def configured_codes(self, adapters):
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, user))
|
||||
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
app.include_router(my_router)
|
||||
c = TestClient(app)
|
||||
c.store = store
|
||||
return c
|
||||
|
||||
|
||||
def test_amount_parsing_scales_to_sen():
|
||||
assert formula.parse_amount("1,234.5", 100) == (123_450, None)
|
||||
assert formula.parse_amount("RM 10.005", 100) == (1001, None) # 센 미만 반올림
|
||||
assert formula.parse_amount("10.5+20", 100) == (3050, "10.5+20")
|
||||
assert formula.parse_amount("1000+2000") == (3000, "1000+2000") # 한국 실적 그대로(원)
|
||||
assert manual_upload.parse_amount("RM 12.34", 100) == 1234 and manual_upload.parse_amount(12.345, 100) == 1235
|
||||
assert manual_upload.parse_amount("12,000") == 12000
|
||||
|
||||
|
||||
def test_text_helpers(my):
|
||||
assert variant.num_text(123_450) == "1,234.50" and variant.money_text(5) == "RM 0.05"
|
||||
assert variant.input_text(123_450) == "1234.50" and variant.input_text(None) == ""
|
||||
assert dashboard.amount_text(-10_005, dashboard.load_unit(None)) == "-100.05"
|
||||
|
||||
|
||||
def test_text_helpers_kr_unchanged():
|
||||
assert variant.current() is variant.KR
|
||||
assert variant.num_text(1234) == "1,234" and variant.money_text(1234) == "₩1,234" and variant.input_text(5) == "5"
|
||||
|
||||
|
||||
def test_get_store_follows_variant(my):
|
||||
state = SimpleNamespace(performance_store="kr", malaysia_performance_store="my")
|
||||
assert common.get_store(SimpleNamespace(app=SimpleNamespace(state=state))) == "my"
|
||||
|
||||
|
||||
def test_group_sums_and_ad_line_under_group(my):
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
|
||||
assert day5["cells"]["group_tiktok"]["gross"] == 133_455 # 쇼핑몰 + 라이브커머스
|
||||
assert day5["total"]["gross"] == 183_455 # 그룹은 일 합계에 또 안 더함
|
||||
assert day5["ads"]["group_tiktok"] == [{"label": "", "amount": 26_691, "roas": 500}]
|
||||
|
||||
|
||||
def test_ad_dashboard_channels(my):
|
||||
from app.modules.performance.ad_spend import build_ad_dashboard
|
||||
|
||||
ctx = build_ad_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY,
|
||||
sales_codes=[m["code"] for m in dashboard._sales_marketplaces(_Store())])
|
||||
assert ctx["codes"] == ["tiktok", "shopee", "lazada"] and ctx["upload_channels"] == []
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
|
||||
assert day5["roas"]["tiktok"] == 500 and day5["roas"]["shopee"] is None
|
||||
assert ctx["kpis"][1]["note"].startswith("총매출 RM ")
|
||||
|
||||
|
||||
def test_pages_render_malaysia(client):
|
||||
html = client.get("/malaysia/performance/?period=week&d=2026-10-07").text
|
||||
assert 'data-base="/malaysia/performance"' in html and 'data-cents="1"' in html
|
||||
assert 'href="/malaysia/performance/ads"' in html and 'id="perf-sync-btn"' not in html
|
||||
assert "1,234.50" in html and "1,334.55" in html and 'data-manual-value="1234.50"' in html
|
||||
assert 'data-group-cell="group_tiktok"' in html and "266.91" in html
|
||||
ads = client.get("/malaysia/performance/ads?period=week&d=2026-10-07").text
|
||||
assert ">틱톡" in ads and "구글" not in ads.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||
assert '"manual_api": "/malaysia/performance/api/ad-spend/"' in ads
|
||||
settings = client.get("/malaysia/performance/settings").text
|
||||
assert "광고 API 연동" not in settings and "자동 업데이트" not in settings and "매출 단위" not in settings
|
||||
# 같은 앱의 한국 실적은 그대로
|
||||
kr = client.get("/performance/?period=week&d=2026-10-07").text
|
||||
assert 'data-base="/performance"' in kr and "data-cents" not in kr
|
||||
|
||||
|
||||
def test_api_saves_sen(client):
|
||||
r = client.put("/malaysia/performance/api/manual-sales/custom_tiktok_live/2026-10-07", json={"amount": "12.34"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert client.store.saved[-1] == ("sale", "custom_tiktok_live", TODAY, 1234, None)
|
||||
r = client.put("/malaysia/performance/api/ad-spend/shopee/2026-10-07", json={"amount": "1.5*2"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert client.store.saved[-1] == ("ad", "shopee", TODAY, 300, "1.5*2")
|
||||
assert client.put("/malaysia/performance/api/ad-spend/google/2026-10-07", json={"amount": "1"}).status_code == 404
|
||||
assert client.get("/malaysia/performance/health").json()["module"] == "malaysia_performance"
|
||||
|
||||
|
||||
def test_sample_lists_malaysia_shops(client):
|
||||
import io
|
||||
|
||||
import openpyxl
|
||||
|
||||
r = client.get("/malaysia/performance/api/manual-sales/sample.xlsx")
|
||||
assert r.status_code == 200
|
||||
head = next(openpyxl.load_workbook(io.BytesIO(r.content)).active.iter_rows(values_only=True))
|
||||
assert head[:3] == ("날짜", "틱톡 쇼핑몰", "틱톡 라이브커머스") and len(head) == 7
|
||||
@@ -160,6 +160,11 @@ def test_periods():
|
||||
# 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
|
||||
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))
|
||||
# 전년 같은 기간 — 진행 중이면 오늘까지, 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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""실적 모듈 인스턴스(2026-11-20) — 같은 코드·화면으로 [실적](한국)과 [말레이시아 실적]을 띄운다.
|
||||
|
||||
app.main 이 router 를 두 번 붙인다: /performance(한국, 기본값) · /malaysia/performance(말레이시아 — 마운트 의존성
|
||||
use_malaysia 가 이 요청의 ContextVar 를 MY 로). 저장소·권한키·주소·광고 채널·통화는 current() 로 읽는다.
|
||||
데이터는 DB 로 나뉜다(같은 표 구조 — malaysia_performance_db, app/modules/malaysia_performance/CLAUDE.md).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass, field
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Variant:
|
||||
key: str # kr | my
|
||||
base: str # 주소 앞부분(템플릿·JS 가 이 뒤에 /api/… 를 붙인다)
|
||||
module_key: str # 권한키
|
||||
module_name: str # 메뉴·탭 이름
|
||||
store_attr: str # app.state 저장소 이름
|
||||
db_name: str # 안내 문구용
|
||||
scale: int = 1 # 금액 저장 단위 — 1 = 원, 100 = 센(RM 소수 2자리를 정수로 저장해 계산은 그대로)
|
||||
currency: str = "₩"
|
||||
# 광고비 탭 채널 — 비면 한국 실적 채널(ad_spend.CHANNELS)
|
||||
ad_channels: tuple[tuple[str, str], ...] = ()
|
||||
# 광고 채널 → ROAS 매출 쇼핑몰 코드들(합계) · 매출 실적 열(그룹) → 그 칸 아래 광고비 줄 [(채널, 줄 이름)]
|
||||
ad_roas_sales: dict[str, tuple[str, ...]] = field(default_factory=dict)
|
||||
ad_lines: dict[str, tuple[tuple[str, str], ...]] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def is_kr(self) -> bool:
|
||||
return self.key == "kr"
|
||||
|
||||
|
||||
KR = Variant("kr", "/performance", "performance", "실적", "performance_store", "performance_db")
|
||||
|
||||
# 쇼핑몰마다 그룹(합계 열) + 쇼핑몰·라이브커머스 하위 2개 — 코드는 scripts/sql/malaysia_performance_db_seed.sql 과 같다
|
||||
_MY_SHOPS = (("tiktok", "틱톡"), ("shopee", "쇼피"), ("lazada", "라자다"))
|
||||
MY = Variant(
|
||||
"my", "/malaysia/performance", "malaysia_performance", "말레이시아 실적", "malaysia_performance_store",
|
||||
"malaysia_performance_db", scale=100, currency="RM",
|
||||
ad_channels=_MY_SHOPS,
|
||||
ad_roas_sales={c: (f"custom_{c}_shop", f"custom_{c}_live") for c, _ in _MY_SHOPS},
|
||||
ad_lines={f"group_{c}": ((c, ""),) for c, _ in _MY_SHOPS},
|
||||
)
|
||||
|
||||
_current: ContextVar[Variant] = ContextVar("perf_variant", default=KR)
|
||||
|
||||
|
||||
def current() -> Variant:
|
||||
return _current.get()
|
||||
|
||||
|
||||
async def use_malaysia() -> None:
|
||||
"""말레이시아 마운트 의존성 — async 라 요청 태스크 컨텍스트에 설정되고 동기 핸들러(스레드풀)로 복사된다."""
|
||||
_current.set(MY)
|
||||
|
||||
|
||||
def num_text(value: Any) -> str:
|
||||
"""금액(저장 단위 정수) → 쉼표 숫자. 원 = 정수, 센 = RM 소수 2자리."""
|
||||
v = current()
|
||||
if v.scale == 1:
|
||||
return f"{int(value or 0):,}"
|
||||
return f"{(Decimal(int(value or 0)) / v.scale).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,.2f}"
|
||||
|
||||
|
||||
def money_text(value: Any) -> str:
|
||||
"""통화 기호 붙인 금액 — ₩1,234 / RM 1,234.50."""
|
||||
v = current()
|
||||
return f"₩{num_text(value)}" if v.scale == 1 else f"{v.currency} {num_text(value)}"
|
||||
|
||||
|
||||
def input_text(value: Any) -> str:
|
||||
"""날짜 칸 편집창에 보일 값(쉼표 없음) — 빈 값은 빈 글자."""
|
||||
if value in (None, ""):
|
||||
return ""
|
||||
v = current()
|
||||
if v.scale == 1:
|
||||
return str(int(value))
|
||||
return f"{Decimal(int(value)) / v.scale:.2f}"
|
||||
|
||||
|
||||
def template_ctx() -> dict[str, Any]:
|
||||
"""모든 실적 화면 공통 — pv(인스턴스), num·money·inval(금액 글자)."""
|
||||
return {"pv": current(), "num": num_text, "money_t": money_text, "inval": input_text}
|
||||
@@ -17,6 +17,8 @@
|
||||
- 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title).
|
||||
- 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다.
|
||||
- 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`
|
||||
(2026-10-27, 휴가 신청 날짜 칸). 모양·동작을 바꾸면 그쪽도 같이 고칠 것(나중에 프로젝트도 공용 파일로 옮기면 하나가 됨).
|
||||
|
||||
@@ -24,7 +26,8 @@
|
||||
|
||||
- **수퍼관리자(`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 와 같다.
|
||||
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버·소유자 변경.
|
||||
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·담당자별 합계·전체 멤버·소유자 변경.
|
||||
- 전체 보기 메뉴 = Project 옵션 대상자(아래 "Project 옵션" 절, `access.can_all_view`, 화면 `pj_all_view`).
|
||||
- Admin 이상 또는 만든 사람: 프로젝트·섹션 삭제. 멤버 누구나: 작업 삭제·서브프로젝트(표는 6-14).
|
||||
- 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동).
|
||||
- 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403).
|
||||
@@ -47,7 +50,7 @@
|
||||
- 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe).
|
||||
- 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글.
|
||||
- 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`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 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
|
||||
@@ -95,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 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐.
|
||||
- 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`).
|
||||
- **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17).
|
||||
@@ -111,6 +122,10 @@
|
||||
- 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에.
|
||||
- 폰트 = 누구나·이 브라우저(localStorage `pj_font`).
|
||||
- 처음 여는 탭·보드 카드 표지 = **수퍼관리자·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)
|
||||
|
||||
@@ -70,6 +70,14 @@ def is_pro(user: dict[str, Any] | None) -> bool:
|
||||
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:
|
||||
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
|
||||
return can_use_module(user) and _is_super(user)
|
||||
|
||||
@@ -888,6 +888,14 @@ class ProjectStore:
|
||||
for k in ("start_time", "due_time"):
|
||||
if k in fields:
|
||||
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_completed = False
|
||||
@@ -899,7 +907,11 @@ class ProjectStore:
|
||||
prev = self._serialize(row)
|
||||
sets: list[str] = []
|
||||
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:
|
||||
sets.append(f"{k} = %s")
|
||||
params.append(clean[k])
|
||||
@@ -1746,6 +1758,18 @@ class ProjectStore:
|
||||
([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):
|
||||
@@ -2268,9 +2292,27 @@ class ProjectStore:
|
||||
).fetchall()
|
||||
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(
|
||||
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:
|
||||
"""마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True,
|
||||
이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서
|
||||
@@ -2289,7 +2331,7 @@ class ProjectStore:
|
||||
"INSERT INTO project_notifications "
|
||||
"(recipient_email, actor_email, project_id, task_id, type, title, body) "
|
||||
"VALUES (%s,'',%s,%s,%s,%s,%s)",
|
||||
(rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)),
|
||||
(rcpt, project_id, task_id, ntype or kind, store.norm_str(title), store.norm_str(body)),
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@
|
||||
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
|
||||
동시에 돌아도 위 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_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9)
|
||||
@@ -41,6 +46,7 @@ logger = logging.getLogger("project.reminders")
|
||||
KIND_DUE_SOON = "due_soon"
|
||||
KIND_DUE_TODAY = "due_today"
|
||||
KIND_OVERDUE = "overdue"
|
||||
NTYPE_DAILY = "daily"
|
||||
OVERDUE_WINDOW_DAYS = 7
|
||||
|
||||
|
||||
@@ -139,6 +145,39 @@ def run_due_reminders(
|
||||
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:
|
||||
from app.mail import send_email # noqa: WPS433
|
||||
|
||||
@@ -176,22 +215,41 @@ def start_reminder_thread(st: Any) -> bool:
|
||||
|
||||
def _loop() -> None:
|
||||
last_run: date | None = None
|
||||
last_due_try = 0.0
|
||||
daily_done: tuple[date, str] | None = None # 마지막으로 보낸 (날짜, 시각)
|
||||
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:
|
||||
now = now_kst()
|
||||
today = now.date()
|
||||
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)
|
||||
if is_workday(today):
|
||||
times = store.normalize_project_options(st.get_project_options())["daily_alert_times"]
|
||||
slot = daily_slot(times, now.strftime("%H:%M"))
|
||||
if slot and daily_done not in ((today, slot), (today, "skip")):
|
||||
made = run_daily_alerts(st, today=today, slot=slot)
|
||||
daily_done = (today, slot)
|
||||
if made:
|
||||
logger.info("매일 업무 알림 %s: %d건", slot, made)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if type(exc).__name__ == "UndefinedTable":
|
||||
# 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지)
|
||||
logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요")
|
||||
last_run = now_kst().date()
|
||||
if type(exc).__name__ in ("UndefinedColumn", "UndefinedTable"):
|
||||
daily_done = (today, "skip") # 033(또는 008) 미적용 — 오늘은 그만(로그 도배 방지)
|
||||
logger.warning("매일 업무 알림 skip — project_db_033 마이그레이션 필요")
|
||||
else:
|
||||
logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__)
|
||||
time.sleep(300)
|
||||
logger.warning("매일 업무 알림 실패(%s) — 1분 뒤 재시도", type(exc).__name__)
|
||||
time.sleep(60)
|
||||
|
||||
threading.Thread(target=_loop, name="project-reminders", daemon=True).start()
|
||||
return True
|
||||
|
||||
@@ -105,12 +105,15 @@ def _require_pro(request: Request) -> dict[str, Any]:
|
||||
return user
|
||||
|
||||
|
||||
def _role_ctx(user: dict[str, Any]) -> dict[str, Any]:
|
||||
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용."""
|
||||
def _role_ctx(user: dict[str, Any], request: Request | None = None) -> dict[str, Any]:
|
||||
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용,
|
||||
pj_all_view 는 왼쪽 "전체 보기" 메뉴(Project 옵션 all_view_users — request 가 없으면 옵션 기본값 기준)."""
|
||||
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),
|
||||
"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:
|
||||
@@ -429,7 +432,7 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
||||
"scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 "
|
||||
"컨테이너를 재기동하세요.",
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
},
|
||||
status_code=503,
|
||||
@@ -678,7 +681,7 @@ def my_tasks_page(request: Request) -> HTMLResponse:
|
||||
"project/mytasks.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"page_title": "내 업무",
|
||||
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
|
||||
@@ -726,7 +729,7 @@ def task_permalink(request: Request, task_id: int):
|
||||
{
|
||||
"reason": reason,
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
},
|
||||
status_code=status,
|
||||
@@ -806,7 +809,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
"reason": "이 프로젝트의 멤버만 볼 수 있습니다. "
|
||||
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
},
|
||||
status_code=403,
|
||||
@@ -896,8 +899,9 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
"project/project.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"pj_options": _project_options(st),
|
||||
"pj_daily_ready": st.daily_ready(), # 033 — 새 업무·세부 업무 추가 칸 날짜 팝업의 [매일]
|
||||
"can_manage": can_manage,
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"page_title": project["name"],
|
||||
@@ -967,7 +971,7 @@ def _db_or_503(request: Request) -> Any:
|
||||
|
||||
|
||||
def _project_options(st: Any) -> dict[str, Any]:
|
||||
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지) — 읽기 실패해도 화면은 기본값으로 연다."""
|
||||
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지·전체 보기 대상자) — 읽기 실패해도 화면은 기본값으로 연다."""
|
||||
if st is None:
|
||||
return store.normalize_project_options(None)
|
||||
try:
|
||||
@@ -1218,6 +1222,7 @@ def api_assignable_users(request: Request) -> JSONResponse:
|
||||
"name": u.get("name") or u["email"].split("@")[0],
|
||||
"id": u["email"].split("@")[0],
|
||||
"avatar": u.get("picture") or "",
|
||||
"pro": access.is_pro(u), # Project 옵션 "전체 보기" 대상자 기본값(설정 전 = Pro user 이상)
|
||||
}
|
||||
for u in user_store.list_all()
|
||||
if has_module(u, "project")
|
||||
@@ -1545,12 +1550,22 @@ def _create_task_for(
|
||||
"""작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
|
||||
돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서."""
|
||||
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:
|
||||
task = st.create_task(**_task_create_fields(user, project_id, payload))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError as 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)
|
||||
|
||||
|
||||
@@ -1673,6 +1688,8 @@ def api_update_task(
|
||||
try:
|
||||
task = st.update_task(task_id=task_id, fields=payload, actor=user["email"],
|
||||
assignee_allowed=_registered_project_user)
|
||||
except UndefinedColumn:
|
||||
raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.")
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError:
|
||||
@@ -2813,7 +2830,7 @@ def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]
|
||||
return out
|
||||
|
||||
|
||||
_ALERT_TYPES = ("mention", "assigned")
|
||||
_ALERT_TYPES = ("mention", "assigned", "daily") # daily = 매일 하는 업무(reminders.run_daily_alerts, 033)
|
||||
_ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것)
|
||||
_ALERT_PAGE = 200
|
||||
_ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게
|
||||
@@ -2963,7 +2980,7 @@ def notifier_page(request: Request) -> Any:
|
||||
"project/notifier.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"nav_projects": _nav_projects(st, user, admin),
|
||||
"goal_years": _goal_years_nav(st),
|
||||
@@ -3114,7 +3131,7 @@ def trash_page(request: Request) -> HTMLResponse:
|
||||
"project/trash.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"nav_projects": _nav_projects(st, user, True),
|
||||
"goal_years": _goal_years_nav(st),
|
||||
@@ -3191,7 +3208,7 @@ def help_page(request: Request) -> HTMLResponse:
|
||||
"project/help.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"page_title": "프로젝트 관리 도움말",
|
||||
"page_subtitle": "처음 쓰는 분을 위한 기능 안내",
|
||||
@@ -3240,7 +3257,7 @@ def inbox_page(request: Request) -> HTMLResponse:
|
||||
"project/inbox.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"nav_projects": nav_projects,
|
||||
"goal_years": _goal_years_nav(st),
|
||||
@@ -3450,7 +3467,7 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
||||
"project/goals.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"nav_projects": _nav_projects(st, user, admin),
|
||||
"goal_years": _goal_years_nav(st),
|
||||
@@ -4001,7 +4018,7 @@ def goal_meeting_page(request: Request, year: int, month: int, week: str | None
|
||||
"project/goal_meeting.html",
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
**_role_ctx(user, request),
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"nav_projects": _nav_projects(st, user, admin),
|
||||
"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] = {
|
||||
"default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭
|
||||
"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]:
|
||||
@@ -394,6 +428,13 @@ def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
|
||||
out["default_view"] = raw["default_view"]
|
||||
if isinstance(raw.get("board_cover"), bool):
|
||||
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
|
||||
|
||||
|
||||
@@ -413,6 +454,16 @@ def validate_project_options(payload: Any) -> dict[str, Any]:
|
||||
if not isinstance(payload["board_cover"], bool):
|
||||
raise ValueError("카드 표지 값이 올바르지 않습니다.")
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
{# Project 옵션 — 상단 바 톱니. 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정. 저장 버튼을 눌러야 한꺼번에 반영된다.
|
||||
· 일반(폰트) — 모두에게 보이고 이 브라우저에만 저장(localStorage pj_font, 아래 인라인 스크립트가 복원).
|
||||
· 프로젝트 화면(처음 여는 탭)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에
|
||||
· 프로젝트 화면(처음 여는 탭·"전체 보기" 메뉴 대상자)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에
|
||||
저장해 모든 사용자에게 적용. 창을 열 때 GET /project/api/options, 저장은 PUT. project.html 이 data-default-view·
|
||||
data-board-cover 로 받아 project.js 가 쓴다. 저장하면 "pj-options-change" 이벤트로 보던 보드에 바로 반영.
|
||||
· 알림(매일 하는 업무 알림 시각 여러 개) — 수퍼관리자·Admin, 모든 사용자.
|
||||
· 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #}
|
||||
<button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션">
|
||||
<span class="material-symbols-outlined">settings</span>
|
||||
@@ -24,6 +25,8 @@
|
||||
<span class="material-symbols-outlined">space_dashboard</span>프로젝트 화면</button>
|
||||
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-board" id="pj-opt-tab-board" data-pane="board" tabindex="-1">
|
||||
<span class="material-symbols-outlined">view_kanban</span>보드</button>
|
||||
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-alert" id="pj-opt-tab-alert" data-pane="alert" tabindex="-1">
|
||||
<span class="material-symbols-outlined">notifications</span>알림</button>
|
||||
{% endif %}
|
||||
{% if user and user.is_super_admin %}
|
||||
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-admin" id="pj-opt-tab-admin" data-pane="admin" tabindex="-1">
|
||||
@@ -62,7 +65,16 @@
|
||||
<label><input type="radio" name="default_view" value="timeline"><span class="material-symbols-outlined">view_timeline</span>타임라인</label>
|
||||
<label><input type="radio" name="default_view" value="dashboard"><span class="material-symbols-outlined">monitoring</span>대시보드</label>
|
||||
</div>
|
||||
<small class="pj-options-note">왼쪽 "전체 보기"는 지금처럼 대시보드로 열립니다.</small>
|
||||
</div>
|
||||
{# 전체 보기 대상자(2026-11-11) — 체크한 사람에게만 왼쪽 "전체 보기" 메뉴가 보인다. 설정 전(all_view_users=null)이면
|
||||
Pro user 이상이 체크된 채로 열린다. 후보 = project 권한 보유자(GET /project/api/assignable-users). #}
|
||||
<div class="pj-options-row is-stack">
|
||||
<div class="pj-options-allview-head">
|
||||
<span class="pj-options-label" id="pj-options-allview-label"><b>"전체 보기" 메뉴를 볼 사람</b><small>체크한 사람에게만 왼쪽 "전체 보기"가 보입니다(멤버인 프로젝트만 모아 봄, 대시보드로 열림)</small></span>
|
||||
<button type="button" class="pj-btn pj-options-allview-all" id="pj-options-allview-all">전체 선택</button>
|
||||
</div>
|
||||
<div class="pj-member-picker pj-options-allview" id="pj-options-allview" role="group" aria-labelledby="pj-options-allview-label"></div>
|
||||
<small class="pj-options-note" id="pj-options-allview-count"></small>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -76,6 +88,18 @@
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
{# 알림(2026-11-11) — 매일 하는 업무(033 repeat_daily) 알림 시각 여러 개(daily_alert_times, 영업일, 서버 reminders.py). #}
|
||||
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-alert" aria-labelledby="pj-opt-tab-alert" data-pane="alert" hidden>
|
||||
<h3>알림 <span class="pj-options-badge is-global"><span class="material-symbols-outlined">groups</span>모든 사용자에게 적용</span></h3>
|
||||
<div class="pj-options-group">
|
||||
<div class="pj-options-row is-stack">
|
||||
<span class="pj-options-label" id="pj-options-daily-label"><b>매일 하는 업무 알림 시각</b><small>날짜 팝업에서 [매일]로 정한 업무를 이 시각마다 담당자(없으면 협업자)에게 알립니다 — 평일(공휴일 제외)</small></span>
|
||||
<ol class="pj-options-times" id="pj-options-daily-times" aria-labelledby="pj-options-daily-label"></ol>
|
||||
<div><button type="button" class="pj-btn" id="pj-options-daily-add"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">add</span> 알림 추가</button></div>
|
||||
<small class="pj-options-note">알림이 하나도 없으면 매일 업무 알림을 보내지 않습니다.</small>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if user and user.is_super_admin %}
|
||||
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-admin" aria-labelledby="pj-opt-tab-admin" data-pane="admin" hidden>
|
||||
@@ -105,4 +129,4 @@
|
||||
document.documentElement.dataset.pjFont = pf;
|
||||
} catch (_) {}
|
||||
</script>
|
||||
<script src="/static/project-options.js?v=20261016c" defer></script>
|
||||
<script src="/static/project-options.js?v=20261111e" defer></script>
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
|
||||
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
|
||||
goal_year_active 목표 화면에서 보고 있는 연도
|
||||
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·전체 보기·휴지통·전체 멤버·연도 추가
|
||||
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·휴지통·전체 멤버·연도 추가
|
||||
pj_all_view "전체 보기" 메뉴 — Project 옵션 대상자(설정 전이면 Pro user 이상, router._role_ctx)
|
||||
pj_admin Admin 이상 — 남이 만든 프로젝트도 삭제(그 밖은 만든 사람만)
|
||||
목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림),
|
||||
새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #}
|
||||
@@ -39,9 +40,9 @@
|
||||
<span class="pj-side-navbadge" id="pj-mention-badge"
|
||||
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
||||
</a>
|
||||
{# 전체 보기(2026-10-08, Pro user 이상 — 멤버인 프로젝트 범위) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
|
||||
{# 전체 보기(2026-10-08 — 멤버인 프로젝트 범위, 2026-11-11 부터 볼 사람은 Project 옵션 "프로젝트 화면" 대상자) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
|
||||
화면을 ?scope=all 로 연다 — 볼 수 있는 모든 프로젝트의 작업. 프로젝트 화면에서는 project.js 가 새로고침 없이 바꾼다. #}
|
||||
{% if pj_pro %}
|
||||
{% if pj_all_view %}
|
||||
{% set _all_pid = current_pid or ((nav_projects | rejectattr("status", "equalto", "completed") | list | first or {}).id or 0) %}
|
||||
{% if _all_pid %}
|
||||
<a class="pj-side-navlink" id="pj-side-allview" href="/project/p/{{ _all_pid }}?scope=all">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<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" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -289,5 +289,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261026a" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<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" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -207,5 +207,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261026a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261111f" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -96,7 +96,7 @@
|
||||
<h2><span class="pjh-num">2</span>화면 구성</h2>
|
||||
<div class="pjh-map" aria-hidden="true">
|
||||
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div>
|
||||
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(옵션에서 고른 사람) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||
<div class="pjh-map-main"><b>가운데 업무 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>업무들</div>
|
||||
</div>
|
||||
<h3>왼쪽 사이드바</h3>
|
||||
@@ -118,10 +118,11 @@
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 왼쪽 분류를 골라 설정을 바꾸고 <span class="pjh-ui">저장</span>을 누르면 한꺼번에 적용되고 창이 닫힙니다.
|
||||
<b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다.
|
||||
아래 프로젝트 화면·보드 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
|
||||
아래 프로젝트 화면·보드·알림 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
|
||||
분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다.
|
||||
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). 왼쪽 "전체 보기"는 늘 대시보드로 열립니다.
|
||||
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). <b>"전체 보기" 메뉴를 볼 사람</b> — 직원 아이콘을 체크한 사람에게만 왼쪽 "전체 보기"가 보입니다([전체 선택]으로 한 번에, 처음엔 Pro user 이상이 체크돼 있음). "전체 보기"는 늘 대시보드로 열립니다.
|
||||
<b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영).
|
||||
<b>알림</b>: 매일 하는 업무 알림 시각 — <span class="pjh-ui">알림 추가</span>로 여러 개, 시각은 각각 정하고 휴지통 아이콘으로 뺍니다(처음엔 오전 9시 하나, 모두 빼면 매일 업무 알림 없음).
|
||||
<span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
||||
</ul>
|
||||
<h3>프로젝트 제목</h3>
|
||||
@@ -151,7 +152,7 @@
|
||||
<tr><td>사이드바 프로젝트 순서 바꾸기 (<span class="pjh-ui">⣿</span>)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>댓글 고치기·지우기</td><td>O</td><td>남의 댓글도</td><td>본인 댓글만</td></tr>
|
||||
<tr><td>휴지통 보기·복구</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td>O</td><td>O (멤버인 프로젝트 범위)</td><td>X</td></tr>
|
||||
<tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td colspan="3">Project 옵션 → 프로젝트 화면에서 고른 사람(처음엔 Pro user 이상, 멤버인 프로젝트 범위)</td></tr>
|
||||
<tr><td>대시보드 “담당자별 업무 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr>
|
||||
<tr><td>사이드바 “전체 멤버”</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>수신함·내 업무·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr>
|
||||
@@ -230,7 +231,7 @@
|
||||
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
|
||||
</table>
|
||||
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
|
||||
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
|
||||
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Project 옵션에서 고른 사람(처음엔 Pro user 이상)은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
|
||||
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
|
||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 업무인지 이름이 붙습니다.
|
||||
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 업무</b>도 한 번씩 함께 보입니다.</p>
|
||||
@@ -291,6 +292,7 @@
|
||||
<tr><td style="color:#3f8f6b">오늘 · 내일</td><td>곧 마감(초록)</td></tr>
|
||||
<tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 업무도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr>
|
||||
<tr><td>09/30(수)</td><td>그 밖의 날짜(기본 글자색)</td></tr>
|
||||
<tr><td style="color:#b07a00"><span class="material-symbols-outlined" style="font-size:15px;vertical-align:-3px">repeat</span>매일</td><td><b>매일 하는 업무</b> — 마감일 없이 매일 해야 하는 업무. 날짜 창 아래 <span class="pjh-ui">매일</span>을 누르면 정해지고(다시 누르거나 날짜를 고르면 풀림), 정한 시각마다 알림이 갑니다(17장).</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
@@ -524,6 +526,7 @@
|
||||
<tr><td>업무 완료 · 새 댓글</td><td>담당자와 협업자</td></tr>
|
||||
<tr><td>마감 알림</td><td>담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다.</td></tr>
|
||||
<tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 업무”)</td></tr>
|
||||
<tr><td>매일 업무</td><td>담당자(없으면 협업자). <b>매일 하는 업무</b>(마감일 칸 <span class="material-symbols-outlined" style="font-size:15px;vertical-align:-3px">repeat</span>매일)가 끝나지 않았으면 평일(공휴일 제외) Project 옵션 → 알림에서 정한 시각마다 화면 아래 큰 알림에 <b>노란 줄</b>로 뜹니다(PC 알림 프로그램도).</td></tr>
|
||||
</table>
|
||||
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.</p>
|
||||
</section>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<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" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -106,5 +106,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<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" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<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" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261111f" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -27,7 +27,7 @@
|
||||
<div class="pj-wrap pj-project-view"
|
||||
data-project-id="{{ project.id }}"
|
||||
data-can-manage="{{ 'true' if can_manage else 'false' }}"
|
||||
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-all-view="{{ 'true' if pj_all_view else 'false' }}" data-daily-ready="{{ '1' if pj_daily_ready else '' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
|
||||
data-default-view="{{ pj_options.default_view if pj_options else 'board' }}"
|
||||
data-board-cover="{{ '0' if pj_options and not pj_options.board_cover else '1' }}"
|
||||
@@ -476,5 +476,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<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" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/project.js?v=20261111d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -134,5 +134,5 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script type="application/json" id="vac-holidays">{{ holidays | tojson }}</script>
|
||||
<script src="/static/erp-datepop.js?v=20261102a" defer></script>
|
||||
<script src="/static/erp-datepop.js?v=20261106a" defer></script>
|
||||
<script src="/static/vacation.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
@@ -149,5 +149,5 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/erp-datepop.js?v=20261102a" defer></script>
|
||||
{% block scripts %}<script src="/static/erp-datepop.js?v=20261106a" defer></script>
|
||||
<script src="/static/vacation.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
+129
-60
@@ -7,9 +7,9 @@
|
||||
옵션이 없는 상품: 행을 자유롭게 추가/삭제해 두고 저장하면 옵션 생성(POST options,
|
||||
카페24가 품목을 자동 생성) → 부여된 품목코드를 받아 → 자체코드/추가금액을 품목에
|
||||
PUT → 썸네일이 있으면 옵션 PUT. 저장 뒤 다시 읽어 품목코드가 바로 보인다.
|
||||
품목 추가: 「+ 행 추가」로 넣은 행은 저장 시 옵션값을 **뒤에 덧붙여** PUT 한다
|
||||
(앞쪽 위치는 그대로라 기존 이름이 밀리지 않는다). 카페24가 품목을 자동 생성하면
|
||||
그 코드로 자체코드/추가금액을 이어서 PUT 한다. 거부하면 오류를 그대로 보여준다.
|
||||
품목 추가: 카페24 PUT options 는 옵션값 추가를 지원하지 않는다(덧붙여 보내면 오류 없이
|
||||
무시되어 저장 후 사라졌다 — 2026-11-06). 「+ 행 추가」·불러오기로 넣은 새 행이 있으면
|
||||
「저장」이 확인창을 거쳐 「옵션 재생성」으로 반영한다(품목코드 새로 부여).
|
||||
품목 삭제: 행의 ✕ → DELETE /variants/{code} (문서에 있는 유일한 제거 수단). 옵션값
|
||||
자체는 남을 수 있어(품목 없는 옵션값) 하단에 따로 보여주고, 정리는 「옵션 재생성」
|
||||
(전체 삭제 → 현재 행으로 다시 생성 → 코드/금액/썸네일 재반영, 품목코드가 바뀜)으로.
|
||||
@@ -149,10 +149,16 @@
|
||||
return out + "</select>";
|
||||
}
|
||||
|
||||
// 품목 토글 — [켜짐, 꺼짐] 표기
|
||||
var FLAG_LABELS = {
|
||||
display: ["진열", "미진열"], selling: ["판매", "중지"],
|
||||
use_inventory: ["사용", "미사용"], display_soldout: ["표시", "안함"]
|
||||
};
|
||||
var FLAGS = Object.keys(FLAG_LABELS);
|
||||
|
||||
function toggleBtn(flag, on) {
|
||||
var label = flag === "display" ? (on ? "진열" : "미진열") : (on ? "판매" : "중지");
|
||||
return '<button type="button" class="cf24-v-toggle' + (on ? " is-on" : "") + '" data-flag="' + flag +
|
||||
'" data-on="' + (on ? 1 : 0) + '" data-initial="' + (on ? 1 : 0) + '">' + label + "</button>";
|
||||
'" data-on="' + (on ? 1 : 0) + '" data-initial="' + (on ? 1 : 0) + '">' + FLAG_LABELS[flag][on ? 0 : 1] + "</button>";
|
||||
}
|
||||
|
||||
function paintToggle(btn, on, resetInitial) {
|
||||
@@ -160,7 +166,25 @@
|
||||
if (resetInitial) btn.dataset.initial = btn.dataset.on;
|
||||
btn.classList.toggle("is-on", on);
|
||||
btn.classList.toggle("is-dirty", btn.dataset.on !== btn.dataset.initial);
|
||||
btn.textContent = btn.dataset.flag === "display" ? (on ? "진열" : "미진열") : (on ? "판매" : "중지");
|
||||
btn.textContent = FLAG_LABELS[btn.dataset.flag][on ? 0 : 1];
|
||||
}
|
||||
|
||||
// 재고관리 · 재고 수량 · 품절표시 칸 (진열·판매 다음)
|
||||
var INVENTORY_TH = '<th class="cf24-v-flag">재고관리</th><th class="cf24-v-qty">재고</th><th class="cf24-v-flag">품절표시</th>';
|
||||
function inventoryCells(variant) {
|
||||
var qty = variant && variant.quantity != null ? String(variant.quantity) : "0";
|
||||
return '<td class="cf24-v-flag">' + toggleBtn("use_inventory", !!(variant && variant.use_inventory)) + "</td>" +
|
||||
'<td class="cf24-v-qty"><input type="text" name="quantity" inputmode="numeric" value="' + esc(qty) + '" /></td>' +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("display_soldout", !!(variant && variant.display_soldout)) + "</td>";
|
||||
}
|
||||
|
||||
// 행의 품목 입력 요소들 — 저장 패치(variantPatch/newRowPatch)용
|
||||
function variantFields(tr, into) {
|
||||
into.custom = tr.querySelector('[name="custom_variant_code"]');
|
||||
into.amount = tr.querySelector('[name="additional_amount"]');
|
||||
into.quantity = tr.querySelector('[name="quantity"]');
|
||||
FLAGS.forEach(function (flag) { into[flag] = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]'); });
|
||||
return into;
|
||||
}
|
||||
|
||||
function bindToggles(container) {
|
||||
@@ -246,7 +270,8 @@
|
||||
// 썸네일은 행에 **지금 보이는** 이미지(버튼 → 연결 → 품목 이미지, 깨진 후보는 건너뛴 결과)다.
|
||||
// // 상품명
|
||||
// "P00000CM000A": "/web/product/extra/202503/….jpg",
|
||||
function swipeCode(tbody) {
|
||||
// byName 이면 품목코드 대신 옵션값 이름을 키로 쓴다(「모바일 스와이프 복사(이름)」).
|
||||
function swipeCode(tbody, byName) {
|
||||
var lines = ["// " + (state.productName || ("상품번호 " + no))];
|
||||
var count = 0;
|
||||
var missing = 0;
|
||||
@@ -256,7 +281,8 @@
|
||||
var img = tr.querySelector("img.cf24-opt-thumb");
|
||||
var path = img ? shopPath(img.getAttribute("src")) : "";
|
||||
if (!path) missing++;
|
||||
lines.push(' "' + code + '": "' + path + '",');
|
||||
var key = byName ? tr.querySelector('[name="option_text"]').value.trim() : code;
|
||||
lines.push(" " + JSON.stringify(key) + ': "' + path + '",');
|
||||
count++;
|
||||
});
|
||||
return { text: lines.join("\n"), count: count, missing: missing };
|
||||
@@ -307,6 +333,48 @@
|
||||
function amountPlain(v) { return String(parseInt(String(v || "0").replace(/,/g, ""), 10) || 0); }
|
||||
function norm(s) { return String(s || "").replace(/\s+/g, "").toLowerCase(); }
|
||||
|
||||
// 판매 가격 칸 = 기본 정보 판매가 + 추가금액. 화면 계산용이고 저장되는 값은 추가금액뿐이다.
|
||||
function basePrice() {
|
||||
var el = root.querySelector('#cf24-basic-form [name="price"]');
|
||||
return parseInt(amountPlain(el && el.value), 10);
|
||||
}
|
||||
function salePrice(amount) { return String(basePrice() + parseInt(amountPlain(amount), 10)); }
|
||||
function salePriceCell(amount) {
|
||||
return '<td class="cf24-v-amount"><input type="text" class="cf24-sale-price" inputmode="numeric" value="' + salePrice(amount) + '" /></td>';
|
||||
}
|
||||
|
||||
function bindSalePrice(tbody) {
|
||||
// capture: 불러오기·입력 복원이 보내는 input 이벤트는 버블링하지 않는다.
|
||||
tbody.addEventListener("input", function (e) {
|
||||
var tr = e.target.closest("tr");
|
||||
var sale = tr.querySelector(".cf24-sale-price");
|
||||
var amount = tr.querySelector('[name="additional_amount"]');
|
||||
if (e.target === sale) {
|
||||
sale.value = sale.value.replace(/\D/g, "");
|
||||
amount.value = sale.value ? String(parseInt(sale.value, 10) - basePrice()) : "0";
|
||||
amount.dispatchEvent(new Event("input")); // 변경 표시
|
||||
} else if (e.target === amount && document.activeElement !== sale) {
|
||||
sale.value = salePrice(amount.value);
|
||||
}
|
||||
}, true);
|
||||
tbody.addEventListener("focusout", function (e) {
|
||||
if (!e.target.classList.contains("cf24-sale-price")) return;
|
||||
e.target.value = salePrice(e.target.closest("tr").querySelector('[name="additional_amount"]').value);
|
||||
});
|
||||
tbody.addEventListener("keydown", function (e) {
|
||||
// isComposing: 한글 조합 중 Enter 는 글자 확정용이다 — 여기서 옮기면 글자가 깨지거나 두 칸 내려간다.
|
||||
if (e.isComposing || !e.target.matches('[name="option_text"], [name="custom_variant_code"], [name="additional_amount"], .cf24-sale-price, [name="quantity"]')) return;
|
||||
var down = e.key === "Enter" || e.key === "ArrowDown";
|
||||
if (!down && e.key !== "ArrowUp") return;
|
||||
e.preventDefault();
|
||||
var tr = e.target.closest("tr")[down ? "nextElementSibling" : "previousElementSibling"];
|
||||
if (!tr) return;
|
||||
var next = tr.cells[e.target.closest("td").cellIndex].querySelector('input[type="text"]');
|
||||
next.focus();
|
||||
next.select();
|
||||
});
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════
|
||||
화면 분기
|
||||
═══════════════════════════════════════════════════════════ */
|
||||
@@ -378,8 +446,10 @@
|
||||
: '<span class="cf24-muted">저장 시 부여</span>') + "</td>" +
|
||||
'<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(variant ? variant.custom_variant_code : "") + '" /></td>' +
|
||||
'<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(variant ? variant.additional_amount : "0")) + '" /></td>' +
|
||||
salePriceCell(variant ? variant.additional_amount : "0") +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("display", variant ? !!variant.display : true) + "</td>" +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : true) + "</td>" +
|
||||
inventoryCells(variant) +
|
||||
'<td class="cf24-u-del">' + (awaiting ? "" : '<button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button>') + "</td>" +
|
||||
"</tr>";
|
||||
}
|
||||
@@ -396,14 +466,15 @@
|
||||
' <label class="cf24-side-field cf24-u-optname"><span>옵션명</span><input type="text" name="option_name" value="' + esc(group.option_name) + '" placeholder="예: 구성" /></label>' +
|
||||
' <label class="cf24-side-field cf24-side-field-type"><span>표시방식</span>' + typeSelect(group.option_display_type || DEFAULT_TYPE, "option_display_type") + "</label>" +
|
||||
' <span class="cf24-u-head-actions">' +
|
||||
(isNew ? "" : ' <button type="button" class="erp-btn erp-btn-outline" id="cf24-u-swipe" title="품목코드와 썸네일 경로를 모바일 스와이프(product-swiper.js) 형식으로 복사합니다">모바일 스와이프 코드 복사</button>') +
|
||||
(isNew ? "" : ' <button type="button" class="erp-btn erp-btn-outline cf24-u-swipe" data-by="code" title="품목코드와 썸네일 경로를 모바일 스와이프(product-swiper.js) 형식으로 복사합니다">모바일 스와이프 복사(코드)</button>' +
|
||||
' <button type="button" class="erp-btn erp-btn-outline cf24-u-swipe" data-by="name" title="옵션값 이름과 썸네일 경로를 모바일 스와이프(product-swiper.js) 형식으로 복사합니다">모바일 스와이프 복사(이름)</button>') +
|
||||
' <button type="button" class="erp-btn erp-btn-outline" id="cf24-u-import">옵션값 불러오기</button>' +
|
||||
' <button type="button" class="erp-btn erp-btn-outline" id="cf24-u-add">+ 행 추가</button>' +
|
||||
" </span>" +
|
||||
"</div>" +
|
||||
'<div class="cf24-u-tablewrap"><table class="cf24-variants cf24-u-table"><thead><tr>' +
|
||||
'<th class="cf24-u-drag"></th><th class="cf24-u-thumb">썸네일</th><th>옵션값 이름</th><th class="cf24-v-syscode">품목코드</th>' +
|
||||
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th><th class="cf24-u-del"></th>' +
|
||||
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th>' + INVENTORY_TH + '<th class="cf24-u-del"></th>' +
|
||||
"</tr></thead><tbody id=\"cf24-u-body\">";
|
||||
rows.forEach(function (r, i) { html += rowHtml(r, canDrag, i); });
|
||||
if (isNew) html += rowHtml({ index: null, value: null, variant: null }, true, null);
|
||||
@@ -417,7 +488,7 @@
|
||||
html += '<p class="cf24-side-note cf24-u-note">' +
|
||||
(isNew
|
||||
? "저장하면 옵션(조합형)을 만들고 카페24가 품목을 자동 생성합니다. 부여된 품목코드를 받아 자체 품목코드·추가금액·썸네일까지 함께 반영합니다."
|
||||
: "「+ 행 추가」한 값은 저장 시 옵션값 끝에 덧붙여 품목을 만듭니다. ✕ 는 품목을 바로 삭제합니다. " +
|
||||
: "「+ 행 추가」한 값은 카페24 API 가 옵션값 추가를 지원하지 않아 저장 시 「옵션 재생성」으로 반영합니다(품목코드 새로 부여). ✕ 는 품목을 바로 삭제합니다. " +
|
||||
(canDrag ? "행을 드래그하면 품목 진열순서로 저장됩니다. " : "") +
|
||||
"썸네일은 표시방식이 「미리보기(이미지)」일 때 쇼핑몰에 보입니다.") +
|
||||
"</p>" +
|
||||
@@ -433,6 +504,7 @@
|
||||
var tbody = body.querySelector("#cf24-u-body");
|
||||
var msg = body.querySelector("#cf24-u-msg");
|
||||
trackDirty(wrap);
|
||||
bindSalePrice(tbody);
|
||||
bindToggles(tbody);
|
||||
bindCopy(tbody);
|
||||
bindThumbUploads(tbody, msg);
|
||||
@@ -446,9 +518,8 @@
|
||||
tr.querySelector('[name="option_text"]').focus();
|
||||
});
|
||||
body.querySelector("#cf24-u-import").addEventListener("click", function () { openImport(isNew, tbody, msg); });
|
||||
var swipeBtn = body.querySelector("#cf24-u-swipe");
|
||||
if (swipeBtn) swipeBtn.addEventListener("click", function () {
|
||||
var out = swipeCode(tbody);
|
||||
body.querySelectorAll(".cf24-u-swipe").forEach(function (swipeBtn) { swipeBtn.addEventListener("click", function () {
|
||||
var out = swipeCode(tbody, swipeBtn.dataset.by === "name");
|
||||
if (!out.count) { window.erpAlert("품목코드가 있는 행이 없습니다."); return; }
|
||||
copyText(out.text, function () {
|
||||
var old = swipeBtn.textContent;
|
||||
@@ -457,7 +528,7 @@
|
||||
msg.textContent = "스와이프 코드 " + out.count + "개 품목 복사" +
|
||||
(out.missing ? " — 썸네일 없는 품목 " + out.missing + "개는 경로가 비어 있습니다" : "");
|
||||
});
|
||||
});
|
||||
}); });
|
||||
body.querySelector("#cf24-u-save").addEventListener("click", function () { saveUnified(isNew, tbody, msg); });
|
||||
var del = body.querySelector("#cf24-opt-delete");
|
||||
if (del) del.addEventListener("click", deleteOptions);
|
||||
@@ -523,8 +594,8 @@
|
||||
link: tr.querySelector('[name="option_link_image"]').value,
|
||||
custom: tr.querySelector('[name="custom_variant_code"]').value,
|
||||
amount: tr.querySelector('[name="additional_amount"]').value,
|
||||
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]').dataset.on,
|
||||
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]').dataset.on
|
||||
quantity: tr.querySelector('[name="quantity"]').value,
|
||||
flags: FLAGS.map(function (flag) { return tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]').dataset.on; })
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -552,11 +623,12 @@
|
||||
set('[name="option_text"]', k.text);
|
||||
set('[name="custom_variant_code"]', k.custom);
|
||||
set('[name="additional_amount"]', k.amount);
|
||||
set('[name="quantity"]', k.quantity);
|
||||
if (k.image) { tr.querySelector('[name="option_image_file"]').value = k.image; }
|
||||
if (k.link) { tr.querySelector('[name="option_link_image"]').value = k.link; }
|
||||
["display", "selling"].forEach(function (flag) {
|
||||
FLAGS.forEach(function (flag, i) {
|
||||
var btn = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]');
|
||||
if (btn && btn.dataset.on !== k[flag]) paintToggle(btn, k[flag] === "1", false);
|
||||
if (btn && btn.dataset.on !== k.flags[i]) paintToggle(btn, k.flags[i] === "1", false);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -720,7 +792,7 @@
|
||||
/* ── 저장 (통합) ── */
|
||||
function collectUnified(tbody) {
|
||||
return Array.prototype.map.call(tbody.children, function (tr, i) {
|
||||
return {
|
||||
return variantFields(tr, {
|
||||
tr: tr,
|
||||
position: i,
|
||||
isNew: tr.classList.contains("is-new"),
|
||||
@@ -728,12 +800,8 @@
|
||||
code: tr.dataset.code || "",
|
||||
text: tr.querySelector('[name="option_text"]').value.trim(),
|
||||
image: tr.querySelector('[name="option_image_file"]').value,
|
||||
link: tr.querySelector('[name="option_link_image"]').value,
|
||||
custom: tr.querySelector('[name="custom_variant_code"]'),
|
||||
amount: tr.querySelector('[name="additional_amount"]'),
|
||||
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]'),
|
||||
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]')
|
||||
};
|
||||
link: tr.querySelector('[name="option_link_image"]').value
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -755,20 +823,25 @@
|
||||
var any = false;
|
||||
if (r.custom.value !== r.custom.defaultValue) { patch.custom_variant_code = r.custom.value.trim(); any = true; }
|
||||
if (r.amount.value !== r.amount.defaultValue) { patch.additional_amount = r.amount.value.trim() || "0"; any = true; }
|
||||
if (r.display.dataset.on !== r.display.dataset.initial) { patch.display = r.display.dataset.on === "1" ? "on" : "off"; any = true; }
|
||||
if (r.selling.dataset.on !== r.selling.dataset.initial) { patch.selling = r.selling.dataset.on === "1" ? "on" : "off"; any = true; }
|
||||
if (r.quantity.value !== r.quantity.defaultValue) { patch.quantity = r.quantity.value.trim() || "0"; any = true; }
|
||||
FLAGS.forEach(function (flag) {
|
||||
if (r[flag].dataset.on !== r[flag].dataset.initial) { patch[flag] = r[flag].dataset.on === "1" ? "on" : "off"; any = true; }
|
||||
});
|
||||
if (withOrder) { patch.display_order = r.position + 1; any = true; }
|
||||
return any ? patch : null;
|
||||
}
|
||||
|
||||
// 새 행(아직 품목 없음)의 초기 패치 — 기본값(빈 코드·0원·진열·판매)과 다른 것만
|
||||
// 새 행(아직 품목 없음)의 초기 패치 — 기본값(빈 코드·0원·진열·판매·재고관리 미사용·재고 0·품절표시 안함)과 다른 것만
|
||||
function newRowPatch(r, code) {
|
||||
var p = { variant_code: code };
|
||||
var any = false;
|
||||
if (r.custom.value.trim()) { p.custom_variant_code = r.custom.value.trim(); any = true; }
|
||||
if (amountPlain(r.amount.value) !== "0") { p.additional_amount = r.amount.value.trim(); any = true; }
|
||||
if (r.display.dataset.on !== "1") { p.display = "off"; any = true; }
|
||||
if (r.selling.dataset.on !== "1") { p.selling = "off"; any = true; }
|
||||
if (amountPlain(r.quantity.value) !== "0") { p.quantity = r.quantity.value.trim(); any = true; }
|
||||
FLAGS.forEach(function (flag) {
|
||||
var defaultOn = flag === "display" || flag === "selling";
|
||||
if ((r[flag].dataset.on === "1") !== defaultOn) { p[flag] = defaultOn ? "off" : "on"; any = true; }
|
||||
});
|
||||
return any ? p : null;
|
||||
}
|
||||
|
||||
@@ -780,6 +853,12 @@
|
||||
|
||||
function saveUnified(isNew, tbody, msg) {
|
||||
var rows = collectUnified(tbody);
|
||||
// 카페24 PUT options 는 옵션값 추가를 지원하지 않는다(덧붙여 보내면 오류 없이 무시 → 저장 후 사라짐).
|
||||
// 새 행이 있으면 유일한 방법인 옵션 재생성(삭제 후 다시 등록)으로 넘긴다.
|
||||
if (!isNew && rows.some(function (r) { return r.isNew; })) {
|
||||
rebuildFlow(tbody, msg, "카페24 API 는 기존 옵션에 옵션값 추가를 지원하지 않아, 추가한 행을 저장하려면 옵션을 재생성해야 합니다.\n\n");
|
||||
return;
|
||||
}
|
||||
var problem = validateNames(rows);
|
||||
if (problem) { window.erpAlert(problem); return; }
|
||||
var optName = body.querySelector('[name="option_name"]').value.trim();
|
||||
@@ -803,11 +882,6 @@
|
||||
if (r.text !== ov.option_text || r.image !== (ov.option_image_file || "") || r.link !== (ov.option_link_image || "")) optionsChanged = true;
|
||||
return { option_text: r.text, option_image_file: r.image, option_link_image: r.link, option_color: ov.option_color || "" };
|
||||
});
|
||||
var newRows = rows.filter(function (r) { return r.isNew; });
|
||||
newRows.forEach(function (r) {
|
||||
edited.push({ option_text: r.text, option_image_file: r.image, option_link_image: r.link, option_color: "" });
|
||||
optionsChanged = true;
|
||||
});
|
||||
var orderChanged = tbody.classList.contains("is-order-dirty");
|
||||
var patches = [];
|
||||
rows.forEach(function (r) {
|
||||
@@ -818,8 +892,8 @@
|
||||
if (!optionsChanged && !patches.length) { setMsg(msg, "바뀐 값이 없습니다.", ""); return; }
|
||||
|
||||
var lines = [];
|
||||
if (optionsChanged) lines.push("옵션명·옵션값 이름/썸네일/표시방식" + (newRows.length ? " (+ 옵션값 " + newRows.length + "개 추가 → 품목 생성)" : ""));
|
||||
if (patches.length) lines.push("품목 " + patches.length + "건 (자체코드·추가금액·진열/판매" + (orderChanged ? "·순서" : "") + ")");
|
||||
if (optionsChanged) lines.push("옵션명·옵션값 이름/썸네일/표시방식");
|
||||
if (patches.length) lines.push("품목 " + patches.length + "건 (자체코드·추가금액·진열/판매·재고" + (orderChanged ? "·순서" : "") + ")");
|
||||
window.erpConfirm("카페24에 바로 반영합니다. 계속할까요?\n\n- " + lines.join("\n- ")).then(function (ok) {
|
||||
if (!ok) return;
|
||||
saveBtn.disabled = true;
|
||||
@@ -833,18 +907,6 @@
|
||||
}).then(function (data) {
|
||||
state.option = data.option;
|
||||
if (data.variants) state.variants = data.variants;
|
||||
if (newRows.length) {
|
||||
// 새 품목코드를 이름으로 짝지어 자체코드·추가금액·진열/판매 패치를 만든다
|
||||
var map = codesByValue(state.variants);
|
||||
var missing = 0;
|
||||
newRows.forEach(function (r) {
|
||||
var code = map[norm(r.text)];
|
||||
if (!code) { missing++; return; }
|
||||
var p = newRowPatch(r, code);
|
||||
if (p) patches.push(p);
|
||||
});
|
||||
if (missing) setMsg(msg, "옵션값은 추가됐지만 품목 " + missing + "건은 카페24 품목 조회가 늦어 자체코드/추가금액을 넣지 못했습니다 — 저장 후 다시 시도하세요.", "is-err");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -853,10 +915,15 @@
|
||||
setMsg(msg, "품목 " + patches.length + "건 반영 중…", "");
|
||||
return apiJson("PUT", "/cafe24/products/" + no + "/variants", { rows: patches });
|
||||
});
|
||||
var shopWarn = "";
|
||||
chain
|
||||
.then(function () { return load(); })
|
||||
.then(function (data) {
|
||||
var bad = Object.keys((data && data.shop_failed) || {});
|
||||
if (bad.length) shopWarn = " 단, 다른 쇼핑몰(" + bad.join(", ") + "번) 진열/판매 반영 실패: " + data.shop_failed[bad[0]];
|
||||
return load();
|
||||
})
|
||||
.then(function () {
|
||||
setMsg(body.querySelector("#cf24-u-msg"), "카페24에 반영했습니다.", "is-ok");
|
||||
setMsg(body.querySelector("#cf24-u-msg"), "카페24에 반영했습니다." + shopWarn, shopWarn ? "is-err" : "is-ok");
|
||||
})
|
||||
.catch(function (err) {
|
||||
setMsg(msg, "실패: " + err.message + " — 화면을 다시 불러옵니다.", "is-err");
|
||||
@@ -930,7 +997,7 @@
|
||||
}
|
||||
|
||||
// 옵션 재생성 — 전체 삭제 후 현재 행(이름·코드·금액·진열/판매·썸네일)으로 다시 만든다.
|
||||
function rebuildFlow(tbody, msg) {
|
||||
function rebuildFlow(tbody, msg, intro) {
|
||||
var rows = collectUnified(tbody);
|
||||
var problem = validateNames(rows.map(function (r) { return { text: r.text, isNew: false }; }));
|
||||
if (problem) { window.erpAlert(problem); return; }
|
||||
@@ -939,7 +1006,7 @@
|
||||
if (!optName) { window.erpAlert("옵션명을 입력하세요."); return; }
|
||||
var saveBtn = body.querySelector("#cf24-u-save");
|
||||
var orphanNote = state.orphans.length ? "\n- 품목 없는 옵션값 " + state.orphans.length + "개는 사라집니다." : "";
|
||||
window.erpConfirm("옵션을 전부 지우고 현재 " + rows.length + "행으로 다시 만듭니다.\n\n- 모든 품목코드가 새로 부여됩니다(주문 이력·외부 연동이 품목코드를 참조하면 영향).\n- 재고 수량은 초기화될 수 있습니다." + orphanNote + "\n\n되돌릴 수 없습니다. 계속할까요?")
|
||||
window.erpConfirm((intro || "") + "옵션을 전부 지우고 현재 " + rows.length + "행으로 다시 만듭니다.\n\n- 모든 품목코드가 새로 부여됩니다(주문 이력·외부 연동이 품목코드를 참조하면 영향).\n- 재고 수량은 초기화될 수 있습니다." + orphanNote + "\n\n되돌릴 수 없습니다. 계속할까요?")
|
||||
.then(function (ok) { if (ok) createFromRows(rows, optName, optType, saveBtn, msg, true); });
|
||||
}
|
||||
|
||||
@@ -973,7 +1040,7 @@
|
||||
html += '<p class="cf24-muted">품목이 아직 조회되지 않았습니다. 잠시 뒤 창을 닫았다 다시 여세요.</p>';
|
||||
} else {
|
||||
html += '<div class="cf24-variants-wrap"><table class="cf24-variants"><thead><tr><th class="cf24-v-imgcol"></th><th>옵션</th><th class="cf24-v-syscode">품목코드</th>' +
|
||||
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th><th class="cf24-u-del"></th></tr></thead><tbody>';
|
||||
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th>' + INVENTORY_TH + '<th class="cf24-u-del"></th></tr></thead><tbody>';
|
||||
variants.forEach(function (v) {
|
||||
var label = v.options.map(function (o) { return o.value; }).join(" / ") || v.variant_code;
|
||||
html += '<tr class="cf24-v-item" data-code="' + esc(v.variant_code) + '">' +
|
||||
@@ -982,7 +1049,9 @@
|
||||
'<td class="cf24-v-syscode"><button type="button" class="cf24-v-copy" data-copy-text="' + esc(v.variant_code) + '">' + esc(v.variant_code) + "</button></td>" +
|
||||
'<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(v.custom_variant_code) + '" /></td>' +
|
||||
'<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(v.additional_amount)) + '" /></td>' +
|
||||
salePriceCell(v.additional_amount) +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("display", !!v.display) + "</td><td class=\"cf24-v-flag\">" + toggleBtn("selling", !!v.selling) + "</td>" +
|
||||
inventoryCells(v) +
|
||||
'<td class="cf24-u-del"><button type="button" class="cf24-u-remove" data-code="' + esc(v.variant_code) + '" title="품목 삭제 (카페24에 바로 반영)">✕</button></td></tr>';
|
||||
});
|
||||
html += "</tbody></table></div><div class=\"cf24-side-actions\" style=\"margin-top:8px;\"><span class=\"cf24-muted\" id=\"cf24-var-msg\"></span>" +
|
||||
@@ -999,6 +1068,7 @@
|
||||
var wrap = body.querySelector(".cf24-variants-wrap");
|
||||
if (wrap) {
|
||||
trackDirty(wrap);
|
||||
bindSalePrice(wrap.querySelector("tbody"));
|
||||
bindToggles(wrap);
|
||||
bindCopy(wrap);
|
||||
body.querySelector("#cf24-var-save").addEventListener("click", function () { saveMultiVariants(wrap); });
|
||||
@@ -1064,9 +1134,7 @@
|
||||
var saveBtn = body.querySelector("#cf24-var-save");
|
||||
var rows = [];
|
||||
wrap.querySelectorAll("tr[data-code]").forEach(function (tr) {
|
||||
var r = { code: tr.dataset.code, custom: tr.querySelector('[name="custom_variant_code"]'), amount: tr.querySelector('[name="additional_amount"]'),
|
||||
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]'), selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]') };
|
||||
var p = variantPatch(r, false);
|
||||
var p = variantPatch(variantFields(tr, { code: tr.dataset.code }), false);
|
||||
if (p) rows.push(p);
|
||||
});
|
||||
if (!rows.length) { setMsg(msg, "바뀐 품목이 없습니다.", ""); return; }
|
||||
@@ -1083,6 +1151,7 @@
|
||||
if (!tr) return;
|
||||
if (u.custom_variant_code !== undefined) tr.querySelector('[name="custom_variant_code"]').value = u.custom_variant_code;
|
||||
if (u.additional_amount !== undefined) tr.querySelector('[name="additional_amount"]').value = amountPlain(u.additional_amount);
|
||||
if (u.quantity != null) tr.querySelector('[name="quantity"]').value = String(u.quantity);
|
||||
tr.querySelectorAll(".cf24-v-toggle").forEach(function (btn) {
|
||||
if (u[btn.dataset.flag] !== undefined) paintToggle(btn, !!u[btn.dataset.flag], true);
|
||||
});
|
||||
@@ -1090,8 +1159,8 @@
|
||||
if (v.variant_code !== code) return;
|
||||
if (u.custom_variant_code !== undefined) v.custom_variant_code = u.custom_variant_code;
|
||||
if (u.additional_amount !== undefined) v.additional_amount = u.additional_amount;
|
||||
if (u.display !== undefined) v.display = !!u.display;
|
||||
if (u.selling !== undefined) v.selling = !!u.selling;
|
||||
if (u.quantity != null) v.quantity = u.quantity;
|
||||
FLAGS.forEach(function (flag) { if (u[flag] !== undefined) v[flag] = !!u[flag]; });
|
||||
});
|
||||
});
|
||||
commitValues(wrap);
|
||||
|
||||
+33
-6
@@ -17,6 +17,7 @@
|
||||
.erp-page {
|
||||
max-width: none;
|
||||
box-sizing: border-box;
|
||||
padding-top: 10px; /* 상단 탭 위 여백 — 아래 여백은 _nav.html 의 margin-bottom 과 같은 10px */
|
||||
}
|
||||
|
||||
.cf24-card {
|
||||
@@ -123,12 +124,14 @@
|
||||
|
||||
.cf24-list-table tbody td {
|
||||
padding: 6px 4px;
|
||||
vertical-align: top;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* 목록 폭 550px 기준. 고정폭을 뺀 나머지(약 290px)가 상품명 몫이다.
|
||||
진열/판매 칸은 제목(2글자) + 정렬 화살표가 들어갈 만큼만. */
|
||||
.cf24-col-no { width: 40px; text-align: right; color: var(--color-midtone-gray, #737373); }
|
||||
.cf24-col-thumb { width: 64px; box-sizing: content-box; }
|
||||
.cf24-thumb { display: block; width: 64px; height: 64px; object-fit: contain; background: var(--color-ghost-gray, #f2f2f2); }
|
||||
.cf24-col-flag { width: 40px; text-align: center; }
|
||||
.cf24-col-date { width: 78px; white-space: nowrap; color: var(--color-midtone-gray, #737373); }
|
||||
.cf24-col-name { word-break: break-word; }
|
||||
@@ -278,7 +281,6 @@
|
||||
.cf24-shortcuts {
|
||||
font-size: var(--text-caption, 12px);
|
||||
color: #79a6dd;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 편집 폼과 코드 칸은 **줄어들지 않는다.** 아래 「예약 적용」·「버전 이력」을 펼치면
|
||||
@@ -747,6 +749,27 @@
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
/* 예약 대표 이미지 — 칸 제목은 다른 칸과 같게, 파일 고르기는 가로 한 줄 */
|
||||
.cf24-schedule-image {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: var(--text-caption, 12px);
|
||||
color: var(--color-midtone-gray, #737373);
|
||||
}
|
||||
.cf24-schedule-grid label.cf24-file-pick {
|
||||
flex-direction: row;
|
||||
}
|
||||
.cf24-sched-img {
|
||||
display: block;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
margin-top: 4px;
|
||||
object-fit: cover;
|
||||
border: 1px solid var(--color-border, #e5e5e5);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* 날짜/시간을 별도 input 으로 나눈다 — datetime-local 은 한국어 로캘에서
|
||||
"2026. 08. 14. 오후 07:00" 형태로 길어져 auto-fit minmax(160px, 1fr) 칸에
|
||||
잘렸다(실측). 지금은 표시 텍스트를 우리가 직접 그리므로(아래 .cf24-dt-*) 폭을
|
||||
@@ -856,7 +879,8 @@
|
||||
/* 목록은 320~460px 사이에서 **먼저** 줄어들고(편집기 640px 를 남기는 폭), 편집기가 남는 폭을, 패널은 380px 고정.
|
||||
minmax(320px, 460px) 였을 때는 목록이 460px 를 먼저 차지해 1440폭(세로 모니터)에서 편집기가 288px 로 눌렸다(2026-10-15).
|
||||
1920px: 목록 460 → 편집기 약 850px. 1601px: 목록 320 → 편집기 약 610px. 그보다 좁으면 아래 2분할. */
|
||||
grid-template-columns: clamp(320px, calc(100% - 380px - 24px - 640px), 460px) minmax(0, 1fr) 380px;
|
||||
/* 대표 이미지 열(64+패딩 8) 만큼 목록 상·하한을 72px 올렸다 — 상품명 칸 폭은 그대로. */
|
||||
grid-template-columns: clamp(392px, calc(100% - 380px - 24px - 640px), 532px) minmax(0, 1fr) 380px;
|
||||
}
|
||||
|
||||
/* 2분할(정보 패널을 편집기 아래로) 경계 — 가로 화면은 예전대로 1360px 이하, **세로 화면은 1600px 이하**(2026-10-15).
|
||||
@@ -866,7 +890,7 @@
|
||||
/* 폭이 모자라면 정보 패널을 편집기 아래로 내린다(목록은 그대로 왼쪽).
|
||||
아래 칸은 높이를 제한해 편집기가 너무 눌리지 않게 한다(패널 안에서 스크롤). */
|
||||
.cf24-split.cf24-split-3 {
|
||||
grid-template-columns: minmax(300px, 380px) minmax(0, 1fr);
|
||||
grid-template-columns: minmax(372px, 452px) minmax(0, 1fr);
|
||||
grid-template-areas: "list editor" "list side";
|
||||
grid-template-rows: minmax(0, 1fr) auto;
|
||||
}
|
||||
@@ -1307,7 +1331,8 @@ body.cf24-modal-open {
|
||||
}
|
||||
|
||||
.cf24-variants th {
|
||||
font-weight: 500;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: var(--color-midtone-gray, #737373);
|
||||
white-space: nowrap;
|
||||
@@ -1324,7 +1349,9 @@ body.cf24-modal-open {
|
||||
.cf24-v-code { width: 132px; }
|
||||
.cf24-v-amount { width: 90px; }
|
||||
.cf24-v-amount input { text-align: right; }
|
||||
.cf24-v-flag { width: 56px; text-align: center; }
|
||||
.cf24-v-qty { width: 70px; }
|
||||
.cf24-v-qty input { text-align: right; }
|
||||
.cf24-variants .cf24-v-flag { width: 56px; text-align: center; }
|
||||
|
||||
/* 품목코드 — 클릭하면 클립보드로. 눌리는 것임을 커서·밑줄로 알린다. */
|
||||
.cf24-v-copy {
|
||||
|
||||
@@ -63,7 +63,8 @@
|
||||
const HOLIDAY_SHORT = { "부처님오신날": "석가탄신일", "추석·개천절": "추석" };
|
||||
|
||||
// 요일 줄 + 6주 날짜 칸(팝업·붙박이 달력 공용). extra(iso) = 그 칸에 더할 클래스 목록
|
||||
function gridHtml(viewY, viewM, holidays, today, extra) {
|
||||
// locale(선택, 라이브 커머스 영문 화면): { weekdays[7], shortName(이름), title(연, 월0), prev, next } — 없으면 한글
|
||||
function gridHtml(viewY, viewM, holidays, today, extra, locale) {
|
||||
const first = new Date(viewY, viewM, 1);
|
||||
const gridStart = new Date(viewY, viewM, 1 - first.getDay());
|
||||
let days = "";
|
||||
@@ -78,14 +79,14 @@
|
||||
if (iso === today) cls.push("is-today");
|
||||
cls.push.apply(cls, extra(iso, d));
|
||||
if (holName) cls.push("has-hol");
|
||||
const holShort = /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName);
|
||||
const holShort = locale && locale.shortName ? locale.shortName(holName) : /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName);
|
||||
days += '<button type="button" class="' + cls.join(" ") + '" data-iso="' + iso + '"' +
|
||||
(holName ? ' title="' + esc(holName) + '"' : "") + ">" +
|
||||
'<span class="pj-dp-num">' + d.getDate() + "</span>" +
|
||||
(holName ? '<span class="pj-dp-hol">' + esc(holShort) + "</span>" : "") + "</button>";
|
||||
}
|
||||
return '<div class="pj-dp-grid">' +
|
||||
["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) {
|
||||
((locale && locale.weekdays) || ["일", "월", "화", "수", "목", "금", "토"]).map(function (w, i) {
|
||||
return '<span class="pj-dp-wd' + (i === 0 ? " is-sun" : i === 6 ? " is-sat" : "") + '">' + w + "</span>";
|
||||
}).join("") + days + "</div>";
|
||||
}
|
||||
@@ -355,7 +356,7 @@
|
||||
|
||||
// 화면에 붙박이는 기간 달력(2026-11-02, 휴가 신청) — 팝업과 같은 달력 서식(.pj-dp-*).
|
||||
// 첫 클릭 = 시작일(동그라미), 다음 클릭 = 종료일(둥근 막대), 그다음 클릭 = 새로 시작. 시작일보다 앞을 누르면 그 날이 새 시작일.
|
||||
// opts: { start, end, holidays, single() — true 면 클릭마다 하루, onChange(start, end) }. 반환 { set(start, end) }
|
||||
// opts: { start, end, holidays, single() — true 면 클릭마다 하루, onChange(start, end), locale, dayClass(iso) — 칸에 더할 클래스 목록(라이브 = 방송 있는 날) }. 반환 { set(start, end) }
|
||||
function mountRange(box, opts) {
|
||||
const holidays = opts.holidays || {};
|
||||
const today = isoToday();
|
||||
@@ -373,12 +374,15 @@
|
||||
return c;
|
||||
}
|
||||
function render() {
|
||||
const loc = opts.locale || {};
|
||||
box.innerHTML =
|
||||
'<div class="pj-dp-nav">' +
|
||||
'<button type="button" class="pj-dp-navbtn" data-nav="-1" title="이전 달"><span class="material-symbols-outlined">chevron_left</span></button>' +
|
||||
'<span class="pj-dp-title">' + viewY + "년 " + (viewM + 1) + "월</span>" +
|
||||
'<button type="button" class="pj-dp-navbtn" data-nav="1" title="다음 달"><span class="material-symbols-outlined">chevron_right</span></button>' +
|
||||
"</div>" + gridHtml(viewY, viewM, holidays, today, bandClasses);
|
||||
'<button type="button" class="pj-dp-navbtn" data-nav="-1" title="' + esc(loc.prev || "이전 달") + '"><span class="material-symbols-outlined">chevron_left</span></button>' +
|
||||
'<span class="pj-dp-title">' + esc(loc.title ? loc.title(viewY, viewM) : viewY + "년 " + (viewM + 1) + "월") + "</span>" +
|
||||
'<button type="button" class="pj-dp-navbtn" data-nav="1" title="' + esc(loc.next || "다음 달") + '"><span class="material-symbols-outlined">chevron_right</span></button>' +
|
||||
"</div>" + gridHtml(viewY, viewM, holidays, today, function (iso, d) {
|
||||
return opts.dayClass ? bandClasses(iso, d).concat(opts.dayClass(iso)) : bandClasses(iso, d);
|
||||
}, opts.locale);
|
||||
}
|
||||
box.addEventListener("click", function (e) {
|
||||
const nav = e.target.closest(".pj-dp-navbtn");
|
||||
|
||||
@@ -54,6 +54,7 @@
|
||||
});
|
||||
// ── 날짜 — 프로젝트 날짜 팝업 ──
|
||||
L.enhanceDateInput(dateEl, { placeholder: "날짜(비우면 바로)" });
|
||||
if (L.enhanceTimeInput) L.enhanceTimeInput(timeEl, { placeholder: "00:00" }); // 프로젝트 공용 시각 팝업(5분 단위)
|
||||
// ── 받는 사람 — 프로젝트 멤버 고르기 모양 ──
|
||||
peopleBox.innerHTML = people.map(L.memberPickHtml).join("") || '<span class="pj-empty-sm">등록된 사람이 없습니다.</span>';
|
||||
function toAll() { return root.querySelector('input[name="ntc-to"]:checked').value === "all"; }
|
||||
|
||||
+14
-3
@@ -15,8 +15,10 @@
|
||||
/* 거르기 줄 */
|
||||
.io-filter { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.io-filter .erp-select { width: auto; }
|
||||
.io-filter-right { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; margin-left: auto; }
|
||||
.io-search { width: 260px; }
|
||||
.io-filter input[type="date"] { width: 150px; }
|
||||
.io .pj-date-btn { margin-top: 0; height: 34px; box-sizing: border-box; }
|
||||
.io .pj-date-btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.io-date { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--color-midtone-gray); }
|
||||
.io-seg { display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash); border-radius: 10px; background: #fff; }
|
||||
.io-seg-btn { padding: 5px 12px; border-radius: 8px; font-size: 12.5px; color: var(--color-rich-black); text-decoration: none; white-space: nowrap; }
|
||||
@@ -27,6 +29,13 @@
|
||||
.io-table td, .io-table th { white-space: nowrap; }
|
||||
.io-table td.io-items { white-space: normal; min-width: 160px; }
|
||||
.io-num { text-align: right !important; font-variant-numeric: tabular-nums; }
|
||||
/* 발주 목록 머리글 — 숫자 열도 가운데(.io-num 의 !important 를 덮음) */
|
||||
.io-table.io-list-table thead th { text-align: center !important; font-size: calc(var(--text-caption, 12px) * 1.11 * .9); font-weight: 700; background: var(--color-ghost-gray, #f2f2f2); }
|
||||
/* 발주 목록 글자 = 원래 크기의 90% — 칸(13px)·작은 글자(12·11.5·11px) 비율 유지 */
|
||||
.io-table.io-list-table tbody td { font-size: 11.7px; }
|
||||
.io-list-table .erp-row-sub, .io-list-table .erp-muted, .io-list-table .io-progress-pct, .io-list-table .io-late { font-size: 10.8px; }
|
||||
.io-list-table .io-badge { font-size: 10.35px; }
|
||||
.io-list-table .io-over-sub, .io-list-table .io-badge-note { font-size: 9.9px; }
|
||||
.io-code { font-family: ui-monospace, Consolas, monospace; font-size: 12px; }
|
||||
.io-order-no { font-weight: 600; color: var(--color-rich-black); text-decoration: none; font-family: ui-monospace, Consolas, monospace; }
|
||||
.io-order-no:hover { text-decoration: underline; }
|
||||
@@ -275,6 +284,7 @@
|
||||
.io-prod-search { width: 220px; }
|
||||
.io-prod-scroll { max-height: min(440px, calc(100vh - 340px)); overflow-y: auto; border: 1px solid var(--color-subtle-ash); border-radius: 8px; }
|
||||
.io-prod-table thead th { position: sticky; top: 0; z-index: 1; background: #fafbfc; }
|
||||
.io-prod-part-title { padding: 10px 12px 6px; font-size: 13.2px; font-weight: 700; }
|
||||
.io-prod-table col.w-code { width: 128px; }
|
||||
.io-prod-table col.w-num { width: 120px; }
|
||||
.io-prod-table col.w-ag { width: 92px; }
|
||||
@@ -345,12 +355,12 @@
|
||||
달력은 화면 너비에 따라 300~440px(2026-10-21 "달력 오른쪽 여백이 많다 — 더 키워 달라") — 입출고 화면은 ERP 공용 최대 폭(1550px)을 풀어
|
||||
넓은 화면의 빈 여백을 쓴다. 좁은 화면(1100px 미만)은 한 열 — 달력은 아래로. ── */
|
||||
.erp-page:has(> .io-split) { max-width: none; }
|
||||
.io-split { display: grid; grid-template-columns: minmax(0, 1fr) clamp(300px, 23vw, 440px); gap: 20px; align-items: start; }
|
||||
.io-split { display: grid; grid-template-columns: minmax(0, 1fr) clamp(270px, 20.7vw, 396px); gap: 20px; align-items: start; }
|
||||
.io-split > .io { min-width: 0; }
|
||||
.io-side { min-width: 0; position: sticky; top: 12px; display: flex; flex-direction: column; gap: 6px; container-type: inline-size; }
|
||||
@media (max-width: 1100px) {
|
||||
.io-split { grid-template-columns: minmax(0, 1fr); }
|
||||
.io-side { position: static; width: 300px; }
|
||||
.io-side { position: static; width: 270px; }
|
||||
}
|
||||
/* 달력 = 오른쪽 열 너비 × (320/300) 높이 — 프로젝트 달력 모양(.pj-cal)을 작게: 머리(제목 ‹ › 오늘) + 둥근 테두리 안 요일 줄(회색) + 6주.
|
||||
크기는 모두 달력 너비 기준(cqw — 300px 일 때 1cqw = 3px, 예전 300×320 그대로)이라 커지면 글자·칸이 같은 비율로 커진다. */
|
||||
@@ -462,6 +472,7 @@
|
||||
.io-box-pick { border: 1px solid #cfe0fb; background: #f0f6ff; color: #1d4f91; border-radius: 6px; padding: 0 6px; height: 20px; font-size: 11.5px; cursor: pointer; }
|
||||
.io-box-pick:hover { background: #dce9ff; }
|
||||
.io-pallet { margin-top: 8px; display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 14px; font-size: 13px; }
|
||||
.io-pallet[hidden] { display: none; }
|
||||
.io-pallet b { font-variant-numeric: tabular-nums; }
|
||||
.io-pallet-main { font-size: 14px; font-weight: 600; }
|
||||
.io-pallet-main b { font-size: 16px; color: #1d4f91; }
|
||||
|
||||
+68
-20
@@ -21,6 +21,18 @@
|
||||
}
|
||||
function fmt(n) { return n.toLocaleString("ko-KR"); }
|
||||
|
||||
// ── 날짜 칸 = ERP 공용 달력(프로젝트와 같은 모양, 국경일·대체공휴일 빨강·이름, 마우스를 올리면 이름) ──
|
||||
// 필수 칸은 [지우기]를 뺀다 — 숨긴 required 칸이 비면 브라우저가 안내 없이 저장을 막는다.
|
||||
if (window.ErpDatePop) {
|
||||
let holidays = {};
|
||||
try { holidays = JSON.parse((document.getElementById("io-holidays") || {}).textContent || "{}"); } catch (_) { holidays = {}; }
|
||||
document.querySelectorAll('input[type="date"]').forEach(function (input) {
|
||||
const pop = window.ErpDatePop.enhance(input, { label: input.getAttribute("aria-label") || "날짜",
|
||||
format: window.ErpDatePop.fmtFull, clear: !input.required, holidays: holidays });
|
||||
if (pop) pop.button.disabled = input.disabled;
|
||||
});
|
||||
}
|
||||
|
||||
// ── 목록 줄 누르기 → 발주서 ──
|
||||
document.addEventListener("click", function (e) {
|
||||
const row = e.target.closest(".io-row-link");
|
||||
@@ -56,6 +68,7 @@
|
||||
// 힌트 = 통·뚜껑 입수의 최소공배수(둘 다 박스가 꽉 차는 수량 단위)와 지금 수량에 가까운 그 배수(누르면 수량 칸에 넣음).
|
||||
const palletBoxes = parseInt(form.dataset.palletBoxes || "0", 10);
|
||||
const pallet = document.getElementById("io-pallet");
|
||||
const bagPallet = document.getElementById("io-pallet-bag");
|
||||
const gcd = function (a, b) { while (b) { const t = a % b; a = b; b = t; } return a; };
|
||||
const lcm = function (a, b) { return a / gcd(a, b) * b; };
|
||||
function boxCell(tr, n, has) {
|
||||
@@ -64,13 +77,14 @@
|
||||
const out = { body: 0, lid: 0, unset: has && !body };
|
||||
if (!cell) return out;
|
||||
if (!has) { cell.innerHTML = "-"; return out; }
|
||||
if (!body) { cell.innerHTML = '<span class="erp-muted" title="옵션 → 상품 정보에서 통 수량(박스)을 넣으면 계산합니다">박스 입수 미설정</span>'; return out; }
|
||||
const bag = tr.dataset.bag === "1"; // 봉투·백 — 통·뚜껑 구분 없음
|
||||
if (!body) { cell.innerHTML = '<span class="erp-muted" title="옵션 → 상품 정보에서 ' + (bag ? "박스당 수량" : "통 수량(박스)") + '을 넣으면 계산합니다">박스 입수 미설정</span>'; return out; }
|
||||
out.body = n ? Math.ceil(n / body) : 0;
|
||||
out.lid = n && lid ? Math.ceil(n / lid) : 0;
|
||||
const unit = lid ? lcm(body, lid) : body; // 통·뚜껑이 모두 꽉 차는 수량 단위
|
||||
let html = '<div class="io-box-main">통 <b>' + fmt(out.body) + "</b>박스" +
|
||||
(lid ? ' · 뚜껑 <b>' + fmt(out.lid) + "</b>박스" : ' · <span class="erp-muted">뚜껑 없음</span>') + "</div>";
|
||||
const per = "통 " + fmt(body) + "개/박스" + (lid ? " · 뚜껑 " + fmt(lid) + "개/박스" : "");
|
||||
let html = '<div class="io-box-main">' + (bag ? "" : "통 ") + "<b>" + fmt(out.body) + "</b>박스" +
|
||||
(bag ? "" : lid ? ' · 뚜껑 <b>' + fmt(out.lid) + "</b>박스" : ' · <span class="erp-muted">뚜껑 없음</span>') + "</div>";
|
||||
const per = (bag ? "" : "통 ") + fmt(body) + "개/박스" + (lid ? " · 뚜껑 " + fmt(lid) + "개/박스" : "");
|
||||
let hint;
|
||||
if (n && n % unit === 0) {
|
||||
hint = '<span class="io-box-ok">✓ ' + (lid ? "통·뚜껑 박스가 모두 꽉 찹니다" : "박스가 꽉 찹니다") + "</span>";
|
||||
@@ -105,22 +119,25 @@
|
||||
'<rect class="io-pal-base" x="1" y="' + (H + 3) + '" width="5" height="3"/><rect class="io-pal-base" x="' + (W / 2 - 2.5) + '" y="' + (H + 3) + '" width="5" height="3"/>' +
|
||||
'<rect class="io-pal-base" x="' + (W - 6) + '" y="' + (H + 3) + '" width="5" height="3"/></svg>';
|
||||
}
|
||||
function palletVis(all) {
|
||||
// cap = 1파렛트 박스 수. mixed = 1파렛트 박스 수가 다른 봉투·백이 섞임 — all 은 cap 기준 환산값이라 잔량은 %만 보여 준다.
|
||||
function palletVis(all, cap, mixed) {
|
||||
if (!all) return "";
|
||||
const full = Math.floor(all / palletBoxes), rem = all % palletBoxes, MAX = 10;
|
||||
const full = Math.floor(all / cap), rem = all % cap, MAX = 10;
|
||||
const cells = Math.min(cap, 60); // cap 은 입력값 — 아주 커도 그림 칸 수는 60칸까지(비율로 칠함)
|
||||
let html = "";
|
||||
if (full) {
|
||||
let icons = "";
|
||||
for (let i = 0; i < Math.min(full, MAX); i++) icons += palletSvg(palletBoxes, palletBoxes);
|
||||
for (let i = 0; i < Math.min(full, MAX); i++) icons += palletSvg(cells, cells);
|
||||
html += '<span class="io-pal-group" title="꽉 찬 파렛트 ' + full + '개">' + icons +
|
||||
(full > MAX ? '<span class="io-pal-more">+' + (full - MAX) + "</span>" : "") +
|
||||
'<span class="io-pal-cap">꽉 찬 파렛트 <b>' + fmt(full) + "</b></span></span>";
|
||||
}
|
||||
if (rem) {
|
||||
const pct = Math.round(rem / palletBoxes * 100);
|
||||
html += '<span class="io-pal-group is-rem" title="잔량 파렛트 ' + rem + "/" + palletBoxes + '박스">' + palletSvg(rem, palletBoxes) +
|
||||
'<span class="io-pal-cap">잔량 <b>' + rem + "</b>박스 · <b>" + pct + "%</b><br>" +
|
||||
'<span class="io-pal-need">' + (palletBoxes - rem) + "박스 더 실으면 한 파렛트</span></span></span>";
|
||||
const pct = Math.round(rem / cap * 100);
|
||||
const drawn = Math.min(cells - 1, Math.max(1, Math.round(rem / cap * cells)));
|
||||
html += '<span class="io-pal-group is-rem" title="잔량 파렛트 ' + (mixed ? pct + "%" : rem + "/" + cap + "박스") + '">' + palletSvg(drawn, cells) +
|
||||
'<span class="io-pal-cap">잔량 ' + (mixed ? "<b>" + pct + "%</b></span></span>" : "<b>" + rem + "</b>박스 · <b>" + pct + "%</b><br>" +
|
||||
'<span class="io-pal-need">' + (cap - rem) + "박스 더 실으면 한 파렛트</span></span></span>");
|
||||
} else {
|
||||
html += '<span class="io-pal-ok">✓ 모든 파렛트가 꽉 찹니다</span>';
|
||||
}
|
||||
@@ -129,6 +146,7 @@
|
||||
function renumber() {
|
||||
let q = 0, k = 0, amount = 0, missing = 0;
|
||||
let bodyBoxes = 0, lidBoxes = 0, unset = 0;
|
||||
let bagLines = 0, bagBoxes = 0, bagCapped = 0, bagShare = 0, bagCap = 0, bagMixed = false, bagUnset = 0;
|
||||
body.querySelectorAll(".io-line").forEach(function (tr, i) {
|
||||
tr.querySelector(".io-col-no").textContent = String(i + 1);
|
||||
const n = num(tr.querySelector(".io-qty").value);
|
||||
@@ -137,9 +155,22 @@
|
||||
const cell = tr.querySelector(".io-amount");
|
||||
// 금액 = 수량 × 단가(상품 정보 단가, 이미 있던 품목은 발주 당시 단가) — 표시만, 저장은 서버가 단가 사본으로
|
||||
if (cell) cell.textContent = has && price !== null && n ? (Math.round(price * n * 100) / 100).toLocaleString("ko-KR") : "-";
|
||||
if (has) { k++; q += n; if (price === null) missing++; else amount += price * n; }
|
||||
if (has) { k++; q += n; if (price !== null) amount += price * n; else if (tr.dataset.bag !== "1") missing++; } // 봉투·백은 단가가 원래 없음
|
||||
const bx = boxCell(tr, n, has);
|
||||
bodyBoxes += bx.body; lidBoxes += bx.lid; if (bx.unset) unset++;
|
||||
if (has && tr.dataset.bag === "1") {
|
||||
const cap = parseInt(tr.dataset.palletBox || "0", 10) || 0;
|
||||
bagLines++;
|
||||
bagBoxes += bx.body;
|
||||
if (cap) { // 1파렛트 박스 수가 다른 봉투·백은 차지하는 비율로 더함
|
||||
bagCapped += bx.body;
|
||||
bagShare += bx.body / cap;
|
||||
if (bagCap && cap !== bagCap) bagMixed = true;
|
||||
bagCap = Math.max(bagCap, cap);
|
||||
}
|
||||
if (bx.unset || !cap) bagUnset++;
|
||||
} else {
|
||||
bodyBoxes += bx.body; lidBoxes += bx.lid; if (bx.unset) unset++;
|
||||
}
|
||||
const unit = unitOf(tr); // ◀ ▶ = 공배수만큼(입수가 없으면 누를 수 없음)
|
||||
tr.querySelectorAll(".io-step").forEach(function (b) {
|
||||
b.disabled = !unit || (b.dataset.step === "-1" && !n);
|
||||
@@ -150,9 +181,19 @@
|
||||
const all = bodyBoxes + lidBoxes, pallets = Math.ceil(all / palletBoxes);
|
||||
const set = function (key, v) { pallet.querySelector('[data-k="' + key + '"]').textContent = v; };
|
||||
set("body", fmt(bodyBoxes)); set("lid", fmt(lidBoxes)); set("boxes", fmt(all)); set("pallets", fmt(pallets));
|
||||
pallet.querySelector('[data-k="vis"]').innerHTML = palletVis(all);
|
||||
pallet.querySelector('[data-k="vis"]').innerHTML = palletVis(all, palletBoxes);
|
||||
set("note", "1파렛트 = " + palletBoxes + "박스" + (unset ? " · 박스 입수 미설정 " + unset + "종 제외" : ""));
|
||||
}
|
||||
if (bagPallet) {
|
||||
bagPallet.hidden = !bagLines;
|
||||
const setBag = function (key, v) { bagPallet.querySelector('[data-k="' + key + '"]').textContent = v; };
|
||||
setBag("boxes", fmt(bagBoxes));
|
||||
// 섞이면 가장 큰 1파렛트 박스 수로 환산(소수 오차로 한 파렛트 더 나오지 않게 반올림 후 올림)
|
||||
const bagAll = bagMixed ? Math.ceil(Math.round(bagShare * bagCap * 1e6) / 1e6) : bagCapped;
|
||||
setBag("pallets", fmt(bagCap ? Math.ceil(bagAll / bagCap) : 0));
|
||||
bagPallet.querySelector('[data-k="vis"]').innerHTML = palletVis(bagAll, bagCap, bagMixed);
|
||||
setBag("note", bagUnset ? "박스당 수량·1파렛트당 박스 수량 미설정 " + bagUnset + "종 제외" : "");
|
||||
}
|
||||
totalQty.textContent = fmt(q);
|
||||
totalLines.textContent = fmt(k);
|
||||
if (totalAmount) totalAmount.textContent = (Math.round(amount * 100) / 100).toLocaleString("ko-KR");
|
||||
@@ -284,7 +325,10 @@
|
||||
const row = input.closest("tr");
|
||||
if (row) { // 단가(상품 정보) — 금액 계산용, 박스 입수(007) — 박스·파렛트 계산용
|
||||
row.dataset.price = it.price === null || it.price === undefined ? "" : String(it.price);
|
||||
if ("bodyBox" in row.dataset) { row.dataset.bodyBox = it.body_per_box || ""; row.dataset.lidBox = it.lid_per_box || ""; }
|
||||
if ("bodyBox" in row.dataset) {
|
||||
row.dataset.bodyBox = it.body_per_box || ""; row.dataset.lidBox = it.lid_per_box || "";
|
||||
row.dataset.bag = it.is_bag ? "1" : ""; row.dataset.palletBox = it.boxes_per_pallet || "";
|
||||
}
|
||||
const pc = row.querySelector(".io-price");
|
||||
if (pc) pc.textContent = it.unit_price || "-";
|
||||
}
|
||||
@@ -490,13 +534,13 @@
|
||||
const opt = sel.options[sel.selectedIndex];
|
||||
const grouped = !!sel.value;
|
||||
tr.classList.toggle("is-grouped", grouped);
|
||||
const vals = tr.querySelectorAll(".io-group-val");
|
||||
if (vals[0]) vals[0].textContent = (opt && opt.dataset.silver) || "-";
|
||||
if (vals[1]) {
|
||||
const silverVal = tr.querySelector(".io-group-val.io-r"), colorVal = tr.querySelector(".io-color.io-group-val"); // 봉투·백 줄엔 은 칸 없음
|
||||
if (silverVal) silverVal.textContent = (opt && opt.dataset.silver) || "-";
|
||||
if (colorVal) {
|
||||
const key = (opt && opt.dataset.color) || "none";
|
||||
const csel = tr.querySelector(".io-color-select");
|
||||
const copt = csel && Array.from(csel.options).find(function (o) { return o.value === key; });
|
||||
const sw = vals[1].querySelector(".io-swatch"), nm = vals[1].querySelector(".io-color-name");
|
||||
const sw = colorVal.querySelector(".io-swatch"), nm = colorVal.querySelector(".io-color-name");
|
||||
if (sw) { sw.style.background = (copt && copt.dataset.hex) || "#fff"; sw.classList.toggle("is-none", !(copt && copt.dataset.hex)); }
|
||||
if (nm) nm.textContent = copt ? copt.textContent : "";
|
||||
}
|
||||
@@ -531,6 +575,9 @@
|
||||
tr.hidden = !hit;
|
||||
if (hit) shown++;
|
||||
});
|
||||
body.querySelectorAll(".io-prod-part").forEach(function (part) { // 찾은 줄이 없는 표는 제목째 숨김
|
||||
part.hidden = !part.querySelector("tbody tr:not([hidden])");
|
||||
});
|
||||
const cnt = body.querySelector("#io-prod-count");
|
||||
if (cnt) cnt.dataset.base = cnt.dataset.base || cnt.textContent;
|
||||
if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base;
|
||||
@@ -561,7 +608,8 @@
|
||||
const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); };
|
||||
const row = { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
|
||||
if (tr.querySelector('[data-key="group_id"]')) { row.group_id = v("group_id"); row.color = v("color"); } // 006
|
||||
if (tr.querySelector('[data-key="body_per_box"]')) { row.body_per_box = v("body_per_box"); row.lid_per_box = v("lid_per_box"); } // 007
|
||||
if (tr.querySelector('[data-key="boxes_per_pallet"]')) { row.body_per_box = v("body_per_box"); row.boxes_per_pallet = v("boxes_per_pallet"); } // 008 봉투·백
|
||||
else if (tr.querySelector('[data-key="body_per_box"]')) { row.body_per_box = v("body_per_box"); row.lid_per_box = v("lid_per_box"); } // 007
|
||||
return row;
|
||||
});
|
||||
if (rows.length) await act("/inout/settings/products/save", { rows: rows });
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
@@ -0,0 +1,175 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·호스트 설정 */
|
||||
/* 공용 .erp-page 는 폭 100% + 안쪽 여백이라 그대로면 화면보다 넓어진다. 라이브 커머스는 화면 전체 너비를 쓴다(공용 최대 1550px 해제). */
|
||||
.erp-page:has(> .lv), .erp-page:has(> .lv-split) { box-sizing: border-box; max-width: none; padding: var(--sp-16, 16px); }
|
||||
.lv { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.lv *, .lv-dlg *, .lv-dlg *::before, .lv-dlg *::after { box-sizing: border-box; }
|
||||
.lv-dlg [hidden] { display: none !important; }
|
||||
.lv-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.lv-gap { flex: 1 1 auto; }
|
||||
.lv-month { margin: 0 6px; font-size: 18px; font-weight: 600; white-space: nowrap; }
|
||||
.lv-note { margin: 0; padding: 10px 14px; border-radius: 8px; background: #eef6ff; color: #0b4a8b; border: 1px solid #cfe3fb; font-size: 13px; }
|
||||
|
||||
.lv-table td { vertical-align: middle; overflow-wrap: anywhere; }
|
||||
.lv-table th { white-space: nowrap; }
|
||||
.lv-table tr.lv-off td { color: var(--color-midtone-gray, #666); }
|
||||
.lv-r { text-align: right; }
|
||||
.lv-table th.lv-r { text-align: right; }
|
||||
/* 스케줄표 머리글(2026-11-06) — 가운데·굵게·검정·공용 크기의 112% */
|
||||
.lv-table.lv-sched thead th { text-align: center; font-weight: 700; color: #000; font-size: calc(var(--text-caption, 13px) * 1.12); }
|
||||
.lv-c { text-align: center; }
|
||||
.lv-pf { display: inline-block; width: 22px; height: 22px; vertical-align: middle; }
|
||||
.lv-num { font-variant-numeric: tabular-nums; }
|
||||
.lv-nowrap { white-space: nowrap; }
|
||||
.lv-sub { margin: 0; font-size: 12px; color: var(--color-midtone-gray, #666); }
|
||||
.lv-actions { white-space: nowrap; text-align: right; }
|
||||
.lv-thumbs { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.lv-thumbs img { display: block; width: 44px; height: 44px; object-fit: cover; border-radius: 6px; border: 1px solid var(--color-subtle-ash, #e5e5e5); }
|
||||
|
||||
/* 공용 .erp-table 은 640px 아래에서 제목 줄을 숨기고 카드로 바뀐다 — 칸 이름을 칸마다 보여 준다 */
|
||||
@media (max-width: 640px) {
|
||||
.lv-table td[data-label]::before { content: attr(data-label); display: block; font-size: 12px; font-weight: 400; color: var(--color-midtone-gray, #666); text-align: left; }
|
||||
.lv-table td.lv-r, .lv-table td.lv-c { text-align: left; }
|
||||
}
|
||||
|
||||
.lv-views { display: inline-flex; gap: 4px; margin-left: 10px; }
|
||||
.lv-lang { display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 999px; background: #fff; }
|
||||
.lv-lang button { min-width: 40px; padding: 4px 10px; border: 0; border-radius: 999px; background: none; font-size: 12px; font-weight: 600; color: #4b5563; cursor: pointer; }
|
||||
.lv-lang button.is-active { background: #111; color: #fff; }
|
||||
/* 영문 화면은 받은 화면처럼 대문자 */
|
||||
.lv[lang="en"] .lv-kpi span, .lv[lang="en"] .lv-card-nums span, .lv[lang="en"] .lv-cal thead .lv-cal-time, .lv[lang="en"] .lv-cal tfoot .lv-cal-time, .lv[lang="en"] .lv-total dt { text-transform: uppercase; }
|
||||
|
||||
/* ── 달력 보기 ── */
|
||||
.lv-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
|
||||
.lv-kpi { display: flex; flex-direction: column; gap: 0; padding: 4px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
|
||||
.lv-kpi span { font-size: 10px; font-weight: 600; letter-spacing: .04em; color: var(--color-midtone-gray, #666); }
|
||||
.lv-kpi b { font-size: 15px; font-variant-numeric: tabular-nums; }
|
||||
.lv-tip { margin: 0; padding: 2px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #f6f8fb; font-size: 11.5px; color: #374151; }
|
||||
|
||||
/* 달력 보기 = 세로 2분할: 왼쪽 표 + 오른쪽 위에 붙는 달력(공용 erp-datepop 서식) */
|
||||
.lv-split { display: grid; grid-template-columns: minmax(0, 1fr) 240px; gap: 12px; }
|
||||
.lv-split > .lv { gap: 6px; }
|
||||
/* 풀HD 브라우저(세로 약 880~940px)에서 페이지 세로 스크롤 없이 한 화면 — 표 상자가 남은 높이를 쓰고, 더 좁은 창이나 카드가 겹친 칸은 표 안에서 스크롤 */
|
||||
@media (min-width: 1101px) {
|
||||
.erp-page:has(> .lv-split) { overflow: hidden; padding: 10px 12px; }
|
||||
.lv-split { flex: 1 1 auto; min-height: 0; grid-template-rows: minmax(0, 1fr); }
|
||||
.lv-split > .lv { min-height: 0; }
|
||||
.lv-split .lv-cal-wrap { flex: 1 1 auto; min-height: 0; max-height: none; }
|
||||
.lv-split .lv-cal { height: 100%; }
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.lv-split { grid-template-columns: minmax(0, 1fr); }
|
||||
.lv-side { order: -1; max-width: 340px; }
|
||||
.lv-preview { display: none; } /* 좁은 화면(휴대폰)은 마우스 올리기가 없음 — 링크를 누르면 새 탭 */
|
||||
}
|
||||
/* 오른쪽 줄 = 달력 + 그 아래 빈 곳에 결과 이미지 미리보기(카드의 이미지 링크에 마우스를 올린 동안) */
|
||||
.lv-side { display: flex; flex-direction: column; gap: 10px; min-height: 0; }
|
||||
.lv-preview { flex: 1 1 auto; display: flex; flex-direction: column; gap: 4px; min-height: 0; margin: 0; padding: 8px; border: 1px solid #cfd4dc; border-radius: 10px; background: #fff;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, .14); }
|
||||
.lv-preview[hidden] { display: none; }
|
||||
.lv-preview img { flex: 1 1 auto; min-height: 0; width: 100%; object-fit: contain; object-position: top; }
|
||||
/* 이미지 보기 창 — 화면 가운데(모달 기본), 원본 크기, 크면 창 안에서 스크롤. 회전은 무대(stage) 크기를 돌린 크기로 바꿔 스크롤이 맞게 */
|
||||
.lv-viewer { max-width: 94vw; max-height: 94vh; padding: 0; border: 1px solid #cfd4dc; border-radius: 12px; background: #fff; overflow: hidden; }
|
||||
.lv-viewer[open] { display: flex; flex-direction: column; }
|
||||
.lv-viewer::backdrop { background: rgba(0, 0, 0, .6); }
|
||||
.lv-viewer-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 8px 10px; border-bottom: 1px solid #e3e6eb; }
|
||||
.lv-viewer-cap { font-size: 12.5px; font-weight: 600; color: #374151; }
|
||||
.lv-viewer-count { font-size: 12px; font-variant-numeric: tabular-nums; color: #4b5563; }
|
||||
.lv-viewer-body { display: flex; min-height: 0; overflow: auto; background: #f3f4f6; }
|
||||
.lv-viewer-stage { position: relative; flex: none; margin: auto; } /* margin:auto = 작으면 가운데, 크면 스크롤 시작이 잘리지 않음 */
|
||||
.lv-viewer-stage img { position: absolute; left: 50%; top: 50%; max-width: none; transform: translate(-50%, -50%); }
|
||||
.lv-preview figcaption { flex: none; font-size: 10.5px; font-weight: 600; color: #4b5563; text-align: center; }
|
||||
/* 오른쪽 달력 = 공용 달력의 80% */
|
||||
.lv-side-cal { flex: none; box-sizing: border-box; padding: 10px; border: 1px solid #cfd4dc; border-radius: 10px; background: #fff; font-size: 10.4px; }
|
||||
.lv-side-cal .pj-dp-nav { margin: 0 0 4px; }
|
||||
.lv-side-cal .pj-dp-title { font-size: 11.2px; }
|
||||
.lv-side-cal .pj-dp-navbtn { width: 22px; height: 22px; }
|
||||
.lv-side-cal .pj-dp-navbtn .material-symbols-outlined { font-size: 18px; }
|
||||
.lv-side-cal .pj-dp-wd { padding: 3px 0 4px; font-size: 9.6px; }
|
||||
.lv-side-cal .pj-dp-day { height: 27px; font-size: 10.8px; }
|
||||
.lv-side-cal .pj-dp-day::before { width: 24px; height: 24px; top: 13.5px; }
|
||||
.lv-side-cal .pj-dp-num { height: 27px; }
|
||||
.lv-side-cal .pj-dp-day.has-hol { height: 37px; }
|
||||
.lv-side-cal .pj-dp-hol { margin-top: -2px; font-size: 8px; }
|
||||
/* 글자 굵게(오늘은 공용 800 그대로), 방송 있는 날 = 숫자 원 오른쪽 위 초록 점 */
|
||||
.lv-side-cal .pj-dp-title, .lv-side-cal .pj-dp-wd, .lv-side-cal .pj-dp-day:not(.is-today), .lv-side-cal .pj-dp-hol { font-weight: 700; }
|
||||
.lv-side-cal .pj-dp-day.has-live::after { content: ""; position: absolute; top: 1px; left: calc(50% + 7px); width: 6px; height: 6px; border-radius: 50%; background: #16a34a; z-index: 1; }
|
||||
.lv-side-cal .pj-dp-day.is-out.has-live::after { opacity: .4; }
|
||||
.lv-cal-wrap { overflow: auto; max-height: calc(100vh - 150px); border: 1px solid #cfd4dc; border-radius: 10px; background: #fff; }
|
||||
.lv-cal { border-collapse: separate; border-spacing: 0; min-width: max-content; }
|
||||
.lv-cal th, .lv-cal td { border-right: 1px solid #e3e6eb; border-bottom: 1px solid #e3e6eb; }
|
||||
.lv-cal thead th { position: sticky; top: 0; z-index: 2; width: 182px; min-width: 182px; height: 1px; padding: 3px 6px; background: #e4e8ee; text-align: center; font-weight: 700; }
|
||||
.lv-cal thead th.is-weekend { background: #f5efd3; color: #7a5c00; }
|
||||
.lv-cal thead th.is-today { box-shadow: inset 0 -3px 0 #111; }
|
||||
.lv-cal-weekday { font-size: 11.5px; letter-spacing: .03em; }
|
||||
.lv-cal-count { display: inline-block; min-width: 15px; padding: 0 3px; margin-left: 2px; border: 1px solid #cfd4dc; border-radius: 4px; background: #fff; color: #374151; font-size: 9.5px; font-weight: 600; }
|
||||
.lv-cal-date { margin-top: 0; font-size: 9.5px; font-weight: 600; color: #6b7280; }
|
||||
.lv-cal .lv-cal-time { position: sticky; left: 0; z-index: 1; width: 112px; min-width: 112px; padding: 2px 6px; background: #f6f7f9; text-align: center; font-size: 11.5px; font-weight: 700; white-space: nowrap; }
|
||||
.lv-cal thead .lv-cal-time { z-index: 3; background: #d9dee6; }
|
||||
.lv-cal .lv-cal-time small { display: block; margin-top: 0; font-size: 9px; line-height: 1.1; font-weight: 600; color: #6b7280; }
|
||||
.lv-cal tbody .lv-cal-time { line-height: 1.2; } /* 1시간 칸 18줄 — 빈 달은 풀HD 한 화면 */
|
||||
.lv-cell { padding: 2px; vertical-align: top; background: #fff; }
|
||||
.lv-cell.is-weekend { background: #fffdf3; }
|
||||
.lv-cell.is-drop { background: #e8f1ff; box-shadow: inset 0 0 0 2px #3b82f6; }
|
||||
.lv-cell-add { display: block; width: 100%; height: 100%; min-height: 22px; border: 1px dashed #d8dce3; border-radius: 6px; background: transparent; color: #b0b6c0; font-size: 14px; cursor: pointer; }
|
||||
.lv-cell-add:hover, .lv-cell-add:focus-visible { border-color: #6b7280; color: #374151; }
|
||||
/* 카드 = 합친 칸 높이 전체(2시간 방송 = 두 칸). 표 칸의 height:1px 은 최소값일 뿐 — 안의 height:100% 가 칸 높이를 따르게 하는 방법 */
|
||||
.lv-cell { height: 1px; }
|
||||
.lv-cards { display: flex; flex-direction: column; gap: 2px; height: 100%; }
|
||||
.lv-cards .lv-card { flex: 1 1 auto; display: flex; flex-direction: column; }
|
||||
.lv-cards .lv-card-nums { flex: 1 1 auto; align-items: center; }
|
||||
.lv-card { border: 1px solid #1f2937; border-radius: 6px; background: #fff; overflow: hidden; }
|
||||
.lv-card-head { display: flex; align-items: center; gap: 3px; padding: 1px 4px; border-bottom: 1px solid #1f2937; cursor: grab; }
|
||||
.lv-card-head:active { cursor: grabbing; }
|
||||
.lv-card-name small { display: block; overflow: hidden; text-overflow: ellipsis; text-transform: none; font-size: 9px; line-height: 1.1; font-weight: 600; letter-spacing: 0; }
|
||||
.lv-card-pf { flex: none; width: 12px; height: 12px; } /* 호스트 쇼핑몰 아이콘(예전 ✥ 자리) */
|
||||
.lv-card-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-align: center; text-overflow: ellipsis; white-space: nowrap; text-transform: uppercase; font-size: 11px; line-height: 1.2; font-weight: 800; letter-spacing: .03em; color: #111; }
|
||||
.lv-card-edit { padding: 0 2px; border: 0; background: none; color: #374151; font-size: 11px; cursor: pointer; }
|
||||
.lv-card-nums { display: grid; grid-template-columns: 1fr 1fr; }
|
||||
.lv-card-nums div { display: flex; align-items: baseline; justify-content: center; gap: 4px; padding: 1px 2px; white-space: nowrap; }
|
||||
.lv-card-nums div + div { border-left: 1px solid #e3e6eb; }
|
||||
.lv-card-nums span { font-size: 9px; font-weight: 600; color: #4b5563; }
|
||||
.lv-card-nums b { font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.lv-card-foot { display: flex; justify-content: space-between; gap: 4px; padding: 0 4px; border-top: 1px solid #e3e6eb; background: #f6f7f9; font-size: 9px; font-weight: 600; color: #4b5563; }
|
||||
.lv-card-foot b { color: #8a2c0d; }
|
||||
.lv-card-foot a { color: #1d4f91; }
|
||||
.lv-cal tfoot th, .lv-cal tfoot td { position: sticky; bottom: 0; z-index: 2; height: 1px; padding: 3px 6px; background: #101a33; color: #fff; border-color: #2a3550; }
|
||||
.lv-cal tfoot .lv-cal-time { z-index: 3; background: #101a33; font-size: 11px; }
|
||||
.lv-total { display: flex; flex-direction: column; gap: 0; margin: 0; font-size: 9.5px; line-height: 1.25; font-weight: 600; }
|
||||
.lv-total div { display: flex; justify-content: space-between; gap: 6px; }
|
||||
.lv-total dt { color: #aab3c5; }
|
||||
.lv-total dd { margin: 0; font-variant-numeric: tabular-nums; color: #fbbf72; white-space: nowrap; }
|
||||
.lv-total dd.is-sales { color: #6ee7a8; }
|
||||
.lv-dlg input[readonly] { background: #f1f5f9; color: #475569; }
|
||||
|
||||
.lv-dlg { width: min(560px, calc(100vw - 32px)); max-height: calc(100vh - 40px); padding: 0; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 12px; }
|
||||
.lv-dlg::backdrop { background: rgba(0, 0, 0, .35); }
|
||||
/* 창이 나타날 때 — 살짝 아래에서 올라오며 커지고, 뒤 배경은 서서히 어두워짐. 움직임 줄이기 설정이면 바로 뜬다 */
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.lv-dlg[open] { animation: lv-dlg-in .2s cubic-bezier(.2, .8, .2, 1); }
|
||||
.lv-dlg[open]::backdrop { animation: lv-dlg-fade .2s ease-out; }
|
||||
}
|
||||
@keyframes lv-dlg-in { from { opacity: 0; transform: translateY(14px) scale(.97); } to { opacity: 1; transform: none; } }
|
||||
@keyframes lv-dlg-fade { from { opacity: 0; } to { opacity: 1; } }
|
||||
.lv-dlg form { display: flex; flex-direction: column; gap: 12px; padding: 20px 22px; }
|
||||
.lv-dlg h3 { margin: 0; font-size: 17px; font-weight: 600; }
|
||||
.lv-field { display: flex; flex: 1 1 0; flex-direction: column; gap: 4px; min-width: 0; font-size: 13px; font-weight: 500; }
|
||||
.lv-field .erp-input, .lv-field .erp-select { width: 100%; min-width: 0; font-weight: 400; }
|
||||
.lv-field textarea { resize: vertical; }
|
||||
.lv-row { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.lv-row .lv-field { flex-basis: 140px; }
|
||||
.lv-check { display: flex; align-items: center; gap: 6px; font-size: 13px; }
|
||||
/* 쇼핑몰 로고(말레이시아 배송 모듈 이미지) — 두 로고 같은 상자 크기. 창: 안 고르면 흑백, 고르면 컬러 */
|
||||
.lv-logo { display: block; width: 88px; height: 26px; object-fit: contain; }
|
||||
.lv-platforms { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 24px; margin: 0; padding: 0; border: 0; }
|
||||
.lv-platforms legend { width: 100%; margin-bottom: 6px; padding: 0; font-size: 13px; font-weight: 500; }
|
||||
.lv-platform { display: flex; align-items: center; gap: 8px; cursor: pointer; }
|
||||
.lv-platform input { margin: 0; accent-color: var(--color-deep-black, #000); }
|
||||
.lv-platform .lv-logo { filter: grayscale(1); opacity: .45; transition: filter .15s, opacity .15s; }
|
||||
.lv-platform input:checked + .lv-logo { filter: none; opacity: 1; }
|
||||
.lv-table .erp-switch input:focus-visible + .erp-switch-slider { outline: 2px solid var(--color-deep-black, #000); outline-offset: 2px; }
|
||||
.lv-saved { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; font-size: 13px; }
|
||||
.lv-saved li { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.lv-saved a { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lv-msg { margin: 0; padding: 9px 12px; border-radius: 8px; background: #fbe9e6; color: #a1261b; border: 1px solid #efc6bf; font-size: 13px; }
|
||||
.lv-msg.is-info { background: #e8f1ff; color: #1d4f91; border-color: #c5d8f5; } /* 이미지에서 매출 읽기 안내(오류 아님) */
|
||||
.lv-foot { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
@@ -0,0 +1,329 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·달력·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음).
|
||||
달력: 오른쪽 달력으로 날짜 이동, 카드 끌어 옮기기·맞바꾸기. 다시 그린 뒤에도 보던 가로 위치 유지. */
|
||||
(function () {
|
||||
"use strict";
|
||||
const calWrap = document.getElementById("lv-cal-wrap");
|
||||
const CAL_POS = "lv_cal_left";
|
||||
const CAL_JUMP = "lv_cal_jump";
|
||||
function tr(text) { return (window.LV_T && window.LV_T[text]) || text; }
|
||||
const dialogText = function () { return { okText: tr("확인"), cancelText: tr("취소") }; };
|
||||
function reload() {
|
||||
if (calWrap) { try { sessionStorage.setItem(CAL_POS, String(calWrap.scrollLeft)); } catch (_) {} }
|
||||
location.reload();
|
||||
}
|
||||
// 한글·영문 전환 — 브라우저마다 기억(쿠키, /live 안에서만), 서버가 그 언어로 그린다
|
||||
document.addEventListener("click", function (e) {
|
||||
const b = e.target.closest("button[data-lang]");
|
||||
if (!b) return;
|
||||
document.cookie = "live_lang=" + b.dataset.lang + "; path=/live; max-age=31536000; SameSite=Lax" + (location.protocol === "https:" ? "; Secure" : "");
|
||||
reload();
|
||||
});
|
||||
const dlg = document.getElementById("lv-dlg");
|
||||
const form = document.getElementById("lv-form");
|
||||
if (!dlg || !form) return;
|
||||
const title = dlg.querySelector("#lv-dlg-title");
|
||||
const msg = form.querySelector("[data-msg]");
|
||||
const saved = form.querySelector("[data-saved]");
|
||||
const hostSelect = form.querySelector('select[name="host_id"]');
|
||||
const fileInput = form.querySelector('input[type="file"]');
|
||||
|
||||
function say(text, info) {
|
||||
msg.textContent = text || "";
|
||||
msg.hidden = !text;
|
||||
msg.classList.toggle("is-info", !!info);
|
||||
}
|
||||
|
||||
async function post(url, body) {
|
||||
try {
|
||||
const res = await fetch(url, { method: "POST", body: body, headers: { Accept: "application/json" } });
|
||||
const data = await res.json().catch(function () { return {}; });
|
||||
return { ok: res.ok && data.ok !== false, message: data.message || data.detail || "HTTP " + res.status, data: data };
|
||||
} catch (_) {
|
||||
return { ok: false, message: tr("서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.") };
|
||||
}
|
||||
}
|
||||
|
||||
// 사용 안 함 호스트는 그 호스트로 이미 등록된 방송을 고칠 때만 보인다
|
||||
function showHosts(current) {
|
||||
if (!hostSelect) return;
|
||||
Array.from(hostSelect.options).forEach(function (opt) {
|
||||
const off = opt.dataset.inactive === "1" && opt.value !== String(current || "");
|
||||
opt.hidden = off;
|
||||
opt.disabled = off;
|
||||
});
|
||||
}
|
||||
|
||||
function showSaved(images) {
|
||||
if (!saved) return;
|
||||
saved.textContent = "";
|
||||
(images || []).forEach(function (im) {
|
||||
const li = document.createElement("li");
|
||||
const link = document.createElement("a");
|
||||
link.href = "/live/images/" + im.id;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener";
|
||||
link.textContent = im.filename || "#" + im.id;
|
||||
const del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "erp-btn erp-btn-outline erp-btn-sm";
|
||||
del.dataset.post = "/live/images/" + im.id + "/delete";
|
||||
del.dataset.confirm = tr("{name} 를 지울까요?").replace("{name}", im.filename || tr("이 이미지"));
|
||||
del.textContent = tr("지우기");
|
||||
li.append(link, del);
|
||||
saved.appendChild(li);
|
||||
});
|
||||
saved.hidden = !saved.children.length;
|
||||
}
|
||||
|
||||
function open(row) {
|
||||
form.reset();
|
||||
say("");
|
||||
const editing = !!(row && row.id);
|
||||
title.textContent = editing ? title.dataset.edit : title.dataset.add;
|
||||
form.querySelectorAll("[data-edit-only]").forEach(function (el) { el.hidden = !editing; });
|
||||
form.elements.id.value = "";
|
||||
Array.from(form.elements).forEach(function (el) {
|
||||
if (!row || !el.name || !(el.name in row)) return;
|
||||
if (el.type === "checkbox") el.checked = !!row[el.name];
|
||||
else if (el.type === "radio") el.checked = el.value === row[el.name];
|
||||
else if (el.type !== "file") el.value = row[el.name];
|
||||
});
|
||||
showHosts(editing && row.host_id);
|
||||
if (editing && hostSelect) hostSelect.value = String(row.host_id); // 위에서 보이게 한 뒤 다시 고름
|
||||
showSaved(editing && row.images);
|
||||
recalc();
|
||||
dlg.showModal();
|
||||
}
|
||||
|
||||
// Fee(시간 × 시간당 요금)·커미션(판매금액 × %) 자동 계산 — 보기만(저장 안 함), store.session_pay 와 같게 센트 반올림
|
||||
const feeOut = form.querySelector("[data-fee]");
|
||||
const comOut = form.querySelector("[data-commission]");
|
||||
function money(cents) { return (cents / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
|
||||
function minutesOf(v) { const m = /^(\d{1,2}):(\d{2})/.exec(v || ""); return m ? Number(m[1]) * 60 + Number(m[2]) : null; }
|
||||
function recalc() {
|
||||
if (!feeOut || !comOut) return;
|
||||
const s = minutesOf(form.elements.start_time.value), en = minutesOf(form.elements.end_time.value);
|
||||
const mins = s === null || en === null || s === en ? null : (en - s + 1440) % 1440; // 끝이 더 이르면 자정을 넘긴 방송
|
||||
feeOut.value = mins === null ? "" : money(Math.round(mins * Number(feeOut.dataset.fee) * 100 / 60));
|
||||
const sales = Number(String(form.elements.sales_amount.value).replace(/^\s*rm/i, "").replace(/[,\s]/g, ""));
|
||||
const raw = form.elements.sales_amount.value.trim();
|
||||
comOut.value = !raw || !isFinite(sales) || sales < 0 ? "" : money(Math.round(Math.round(sales * 100) * Number(comOut.dataset.commission) / 100));
|
||||
}
|
||||
form.addEventListener("input", function (e) {
|
||||
if (["start_time", "end_time", "sales_amount"].indexOf(e.target.name) >= 0) recalc();
|
||||
});
|
||||
|
||||
const addBtn = document.getElementById("lv-add");
|
||||
if (addBtn) addBtn.addEventListener("click", function () { open(null); });
|
||||
dlg.addEventListener("click", function (e) {
|
||||
if (e.target.closest("[data-close]")) dlg.close();
|
||||
});
|
||||
|
||||
document.addEventListener("click", async function (e) {
|
||||
const edit = e.target.closest("[data-edit]");
|
||||
if (edit && edit.tagName === "BUTTON") { open(JSON.parse(edit.dataset.edit)); return; }
|
||||
const fresh = e.target.closest("button[data-new]");
|
||||
if (fresh) { open(JSON.parse(fresh.dataset.new)); return; }
|
||||
const btn = e.target.closest("button[data-post]");
|
||||
if (!btn) return;
|
||||
if (!(await window.erpConfirm(btn.dataset.confirm, dialogText()))) return;
|
||||
const r = await post(btn.dataset.post);
|
||||
if (r.ok) { reload(); return; }
|
||||
if (dlg.open) say(r.message); else window.erpAlert(r.message, dialogText());
|
||||
});
|
||||
|
||||
// 호스트 목록의 사용 토글 — 바로 저장, 실패하면 되돌림. 줄 흐림(lv-off)만 바꾸고 다시 그리지 않음
|
||||
document.addEventListener("change", async function (e) {
|
||||
const sw = e.target.closest("input[data-active]");
|
||||
if (!sw) return;
|
||||
const body = new FormData();
|
||||
body.set("is_active", sw.checked ? "1" : "0");
|
||||
sw.disabled = true;
|
||||
const r = await post(sw.dataset.active, body);
|
||||
sw.disabled = false;
|
||||
if (!r.ok) { sw.checked = !sw.checked; window.erpAlert(r.message, dialogText()); return; }
|
||||
const line = sw.closest("tr");
|
||||
line.classList.toggle("lv-off", !sw.checked);
|
||||
const edit = line.querySelector("[data-edit]"); // 고치기 창이 옛 값으로 열려 저장 때 되돌리지 않게
|
||||
if (edit) { const row = JSON.parse(edit.dataset.edit); row.is_active = sw.checked; edit.dataset.edit = JSON.stringify(row); }
|
||||
});
|
||||
|
||||
// 결과 이미지를 고르면 서버가 글자 인식으로 매출(틱톡 LIVE 결과 화면의 첫 RM 금액)을 읽어 판매금액 칸에 채운다 — 저장은 사람이 확인 후
|
||||
const salesInput = form.elements.sales_amount;
|
||||
if (fileInput && salesInput) fileInput.addEventListener("change", async function () {
|
||||
const files = Array.from(fileInput.files);
|
||||
if (!files.length) return;
|
||||
const save = form.querySelector('button[type="submit"]');
|
||||
save.disabled = true;
|
||||
say(tr("이미지에서 매출을 읽는 중…"), true);
|
||||
let r = null;
|
||||
for (const f of files) { // 매출을 찾을 때까지 한 장씩
|
||||
const body = new FormData();
|
||||
body.set("image", f);
|
||||
r = await post("/live/broadcasts/read-sales", body);
|
||||
if (!r.ok || r.data.amount) break;
|
||||
}
|
||||
save.disabled = false;
|
||||
if (r.ok && r.data.amount) { salesInput.value = r.data.amount; recalc(); }
|
||||
say(r.message, r.ok);
|
||||
});
|
||||
|
||||
form.addEventListener("submit", async function (e) {
|
||||
e.preventDefault();
|
||||
const save = form.querySelector('button[type="submit"]');
|
||||
const body = new FormData(form);
|
||||
if (fileInput && !fileInput.files.length) body.delete("images");
|
||||
save.disabled = true;
|
||||
say("");
|
||||
const r = await post(form.getAttribute("action"), body);
|
||||
if (r.ok) { reload(); return; }
|
||||
save.disabled = false;
|
||||
say(r.message);
|
||||
});
|
||||
|
||||
if (!calWrap) return;
|
||||
|
||||
// ── 달력: 날짜로 가기(TIME 열이 고정이라 그 폭만큼 띄움) ──
|
||||
function jumpTo(iso) {
|
||||
const col = calWrap.querySelector('thead th[data-day="' + iso + '"]');
|
||||
const time = calWrap.querySelector("thead .lv-cal-time");
|
||||
if (col && time) calWrap.scrollLeft += col.getBoundingClientRect().left - time.getBoundingClientRect().right;
|
||||
}
|
||||
// 마지막 날들도 맨 왼쪽까지 오도록 표 끝에 여백(표 상자 너비 − 시간 열 − 날짜 열 하나)
|
||||
function endGap() {
|
||||
const time = calWrap.querySelector("thead .lv-cal-time");
|
||||
const col = calWrap.querySelector("thead th[data-day]");
|
||||
const table = calWrap.querySelector("table");
|
||||
if (time && col && table) table.style.marginRight = Math.max(0, calWrap.clientWidth - time.offsetWidth - col.offsetWidth) + "px";
|
||||
}
|
||||
endGap();
|
||||
window.addEventListener("resize", endGap);
|
||||
|
||||
// ── 오른쪽 달력(공용 erp-datepop, 말레이시아 공휴일): 날짜를 누르면 그 날이 표 맨 왼쪽, 다른 달이면 그 달 화면으로 가서 맨 왼쪽 ──
|
||||
let pending = null;
|
||||
try { pending = sessionStorage.getItem(CAL_JUMP); sessionStorage.removeItem(CAL_JUMP); } catch (_) {}
|
||||
const hasDay = function (iso) { return !!iso && !!calWrap.querySelector('thead th[data-day="' + iso + '"]'); };
|
||||
const todayHead = calWrap.querySelector("thead th[data-today]");
|
||||
const firstHead = calWrap.querySelector("thead th[data-day]");
|
||||
const shownDay = hasDay(pending) ? pending : todayHead ? todayHead.dataset.day : firstHead && firstHead.dataset.day;
|
||||
const sideBox = document.getElementById("lv-side-cal");
|
||||
if (sideBox && window.ErpDatePop) {
|
||||
let holidays = {};
|
||||
try { holidays = JSON.parse(document.getElementById("lv-my-holidays").textContent); } catch (_) {}
|
||||
let liveDays = {}; // 방송 있는 날 → 점
|
||||
try { JSON.parse(document.getElementById("lv-live-days").textContent).forEach(function (iso) { liveDays[iso] = true; }); } catch (_) {}
|
||||
const english = document.querySelector(".lv").lang === "en";
|
||||
window.ErpDatePop.mountRange(sideBox, {
|
||||
start: shownDay, end: shownDay, holidays: holidays, single: function () { return true; },
|
||||
dayClass: function (iso) { return liveDays[iso] ? ["has-live"] : []; },
|
||||
locale: english ? {
|
||||
weekdays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], prev: "Previous month", next: "Next month",
|
||||
title: function (y, m) { return new Date(y, m, 1).toLocaleString("en", { month: "long" }) + " " + y; },
|
||||
shortName: function (name) { return / \(Replacement\)$/.test(name) ? "Replacement" : name; },
|
||||
} : undefined,
|
||||
onChange: function (iso) {
|
||||
if (hasDay(iso)) { jumpTo(iso); return; }
|
||||
try { sessionStorage.setItem(CAL_JUMP, iso); } catch (_) {}
|
||||
location.href = "/live/calendar?month=" + iso.slice(0, 7);
|
||||
},
|
||||
});
|
||||
}
|
||||
let left = null;
|
||||
try { left = sessionStorage.getItem(CAL_POS); sessionStorage.removeItem(CAL_POS); } catch (_) {}
|
||||
if (hasDay(pending)) jumpTo(pending);
|
||||
else if (left !== null) calWrap.scrollLeft = Number(left);
|
||||
else if (todayHead) jumpTo(todayHead.dataset.day);
|
||||
|
||||
// ── 달력: 카드의 이미지 링크에 마우스를 올리거나 탭으로 가면 오른쪽 달력 아래에 결과 이미지(첫 장), 벗어나면 숨김 ──
|
||||
const preview = document.getElementById("lv-preview");
|
||||
if (preview) {
|
||||
const pImg = preview.querySelector("img"), pCap = preview.querySelector("figcaption");
|
||||
const linkOf = function (el) { return el && el.closest && el.closest("a[data-preview]"); };
|
||||
const show = function (a) {
|
||||
if (pImg.getAttribute("src") !== a.getAttribute("href")) pImg.src = a.getAttribute("href");
|
||||
pImg.alt = a.title;
|
||||
pCap.textContent = a.dataset.preview;
|
||||
preview.hidden = false;
|
||||
};
|
||||
calWrap.addEventListener("mouseover", function (e) { const a = linkOf(e.target); if (a) show(a); });
|
||||
calWrap.addEventListener("mouseout", function (e) { const a = linkOf(e.target); if (a && !a.contains(e.relatedTarget)) preview.hidden = true; });
|
||||
calWrap.addEventListener("focusin", function (e) { const a = linkOf(e.target); if (a) show(a); });
|
||||
calWrap.addEventListener("focusout", function (e) { if (linkOf(e.target)) preview.hidden = true; });
|
||||
}
|
||||
|
||||
// ── 달력: 이미지 링크를 누르면 화면 가운데 보기 창 — 원본 크기, 회전(보기만, 90°씩), 다운로드(원본), 여러 장이면 앞뒤 ──
|
||||
const viewer = document.getElementById("lv-viewer");
|
||||
if (viewer) {
|
||||
const vImg = viewer.querySelector("img"), stage = viewer.querySelector(".lv-viewer-stage");
|
||||
const vCap = viewer.querySelector(".lv-viewer-cap"), vCount = viewer.querySelector(".lv-viewer-count");
|
||||
const dl = viewer.querySelector("[data-download]"), steps = viewer.querySelectorAll("[data-step]");
|
||||
let ids = [], names = [], at = 0, turn = 0;
|
||||
const place = function () {
|
||||
const w = vImg.naturalWidth, h = vImg.naturalHeight, side = turn % 2 === 1;
|
||||
stage.style.width = (side ? h : w) + "px";
|
||||
stage.style.height = (side ? w : h) + "px";
|
||||
vImg.style.transform = "translate(-50%, -50%) rotate(" + turn * 90 + "deg)";
|
||||
};
|
||||
const load = function () {
|
||||
turn = 0;
|
||||
vImg.src = dl.href = "/live/images/" + ids[at];
|
||||
dl.download = names[at] || "image-" + ids[at];
|
||||
vCount.textContent = ids.length > 1 ? at + 1 + " / " + ids.length : "";
|
||||
steps.forEach(function (b) { b.hidden = ids.length < 2; });
|
||||
};
|
||||
vImg.addEventListener("load", place);
|
||||
calWrap.addEventListener("click", function (e) {
|
||||
const a = e.target.closest("a[data-images]");
|
||||
if (!a || e.ctrlKey || e.metaKey || e.shiftKey || e.button) return; // Ctrl·가운데 클릭 = 예전처럼 새 탭
|
||||
e.preventDefault();
|
||||
ids = JSON.parse(a.dataset.images);
|
||||
names = JSON.parse(a.dataset.names || "[]");
|
||||
at = 0;
|
||||
vCap.textContent = a.dataset.preview.replace(/ · \d+\/\d+$/, "");
|
||||
vImg.alt = a.title;
|
||||
load();
|
||||
if (preview) preview.hidden = true;
|
||||
viewer.showModal();
|
||||
});
|
||||
viewer.addEventListener("click", function (e) {
|
||||
if (e.target === viewer || e.target.closest("[data-viewer-close]")) { viewer.close(); return; } // 바깥(배경) = 닫기
|
||||
const step = e.target.closest("[data-step]");
|
||||
if (step) { at = (at + Number(step.dataset.step) + ids.length) % ids.length; load(); return; }
|
||||
if (e.target.closest("[data-rotate]")) { turn = (turn + 1) % 4; place(); }
|
||||
});
|
||||
}
|
||||
|
||||
// ── 달력: 카드 머리를 끌어 빈 칸으로 옮기기, 다른 카드 위에 놓아 맞바꾸기 ──
|
||||
let dragging = null;
|
||||
calWrap.addEventListener("dragstart", function (e) {
|
||||
const head = e.target.closest && e.target.closest(".lv-card-head");
|
||||
if (!head) return;
|
||||
dragging = head.closest("[data-card]").dataset.card;
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
e.dataTransfer.setData("text/plain", dragging);
|
||||
});
|
||||
calWrap.addEventListener("dragend", function () {
|
||||
dragging = null;
|
||||
calWrap.querySelectorAll(".is-drop").forEach(function (c) { c.classList.remove("is-drop"); });
|
||||
});
|
||||
calWrap.addEventListener("dragover", function (e) {
|
||||
const cell = dragging && e.target.closest("[data-drop]");
|
||||
if (!cell) return;
|
||||
e.preventDefault();
|
||||
calWrap.querySelectorAll(".is-drop").forEach(function (c) { if (c !== cell) c.classList.remove("is-drop"); });
|
||||
cell.classList.add("is-drop");
|
||||
});
|
||||
calWrap.addEventListener("drop", async function (e) {
|
||||
const cell = dragging && e.target.closest("[data-drop]");
|
||||
if (!cell) return;
|
||||
e.preventDefault();
|
||||
const id = dragging;
|
||||
const onto = e.target.closest("[data-card]");
|
||||
if (onto && onto.dataset.card === id) return;
|
||||
const body = new FormData();
|
||||
if (onto) body.set("swap_with", onto.dataset.card);
|
||||
else { body.set("broadcast_date", cell.dataset.day); body.set("start_time", cell.dataset.start); }
|
||||
const r = await post("/live/broadcasts/" + id + "/move", body);
|
||||
if (r.ok) reload(); else window.erpAlert(r.message, dialogText());
|
||||
});
|
||||
})();
|
||||
@@ -518,3 +518,19 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel
|
||||
.perf-main thead th:hover > .perf-colw-grip::after { background: #c3c6cb; }
|
||||
.perf-main thead th > .perf-colw-grip:hover::after, .perf-colw-grip.is-active::after { background: #1a56db; }
|
||||
body.perf-colw-dragging, body.perf-colw-dragging * { cursor: col-resize !important; user-select: none; }
|
||||
/* 열 접기(2026-11-06) — 일자별 표 머리글 위 버튼(performance.js initColFold), 접은 열 = 26px 띠(버튼만, 너비는 JS CFOLD_W 와 같게) */
|
||||
.perf-cfold { display: flex; align-items: center; justify-content: center; width: 20px; height: 16px; margin: -4px auto 2px; padding: 0;
|
||||
border: 0; border-radius: 4px; background: none; color: #b5b8bd; cursor: pointer; }
|
||||
.perf-cfold:hover { background: rgba(0, 0, 0, .08); color: #333; }
|
||||
.perf-cfold:focus-visible { outline: 2px solid #1a56db; outline-offset: 1px; }
|
||||
.perf-cfold svg { transition: transform .2s ease; }
|
||||
.perf-cfold[aria-expanded="false"] svg { transform: rotate(180deg); }
|
||||
.perf-main th.is-cfold, .perf-main td.is-cfold { width: 26px; min-width: 26px; max-width: 26px; padding-left: 0; padding-right: 0;
|
||||
font-size: 0; pointer-events: none; }
|
||||
.perf-main .is-cfold > :not(.perf-cfold) { display: none !important; } /* 보기 기준(총매출·차감) 표시 규칙보다 우선 */
|
||||
.perf-main th.is-cfold .perf-cfold { pointer-events: auto; margin-top: 0; }
|
||||
@media (prefers-reduced-motion: reduce) { .perf-cfold svg { transition: none; } }
|
||||
/* 열 접기 버튼 말풍선 — 커서 바로 위, 글자 = 열 제목 크기(12px 굵게) */
|
||||
.perf-cfold-tip { position: fixed; z-index: 2200; transform: translate(-50%, calc(-100% - 12px)); padding: 5px 9px; border-radius: 6px;
|
||||
background: #222; color: #fff; font-size: 12px; font-weight: 700; line-height: 1.4; white-space: nowrap; pointer-events: none;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, .18); }
|
||||
|
||||
+125
-51
@@ -1,6 +1,8 @@
|
||||
/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작.
|
||||
*
|
||||
* 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(/performance/api/…)로만.
|
||||
* 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(BASE/api/…)로만.
|
||||
* 같은 화면이 [실적](/performance)과 [말레이시아 실적](/malaysia/performance, 2026-11-20)에 쓰인다 — 주소는 .perf data-base,
|
||||
* 말레이시아는 data-cents(금액 = 센 정수, 화면 = RM 소수 2자리).
|
||||
* 인증정보 창은 저장된 비밀값을 받지 않는다(서버가 "저장됨" 여부만 준다).
|
||||
*/
|
||||
(function () {
|
||||
@@ -22,17 +24,26 @@
|
||||
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
||||
});
|
||||
}
|
||||
const PERF_ROOT = document.querySelector(".perf");
|
||||
const BASE = (PERF_ROOT && PERF_ROOT.dataset.base) || "/performance";
|
||||
const CENTS = !!(PERF_ROOT && PERF_ROOT.dataset.cents); // 말레이시아 실적 — 금액 = 센(0.01 RM) 정수
|
||||
const CUR = CENTS ? "RM" : "원";
|
||||
function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
|
||||
function won(n) { return n ? fmt(n) : '<span class="perf-zero">–</span>'; }
|
||||
// 금액(저장 단위) → 글자. 원 = 정수, 센 = RM 소수 2자리(서버 variant.num_text 와 같음)
|
||||
function money(n) {
|
||||
return CENTS ? (Number(n || 0) / 100).toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : fmt(n);
|
||||
}
|
||||
function won(n) { return n ? money(n) : '<span class="perf-zero">–</span>'; }
|
||||
// 매출 단위(실적 설정 "공통 보기 설정", 모든 사용자 같음) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리)
|
||||
function unitWon(n, unit) {
|
||||
if (!n) return won(0);
|
||||
if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR");
|
||||
if (unit === "million") return (Math.round(n / 100000) / 10).toLocaleString("ko-KR", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||
return fmt(n);
|
||||
return money(n);
|
||||
}
|
||||
// 축 눈금용 짧은 금액(1.2억 / 350만)
|
||||
function short(n) {
|
||||
if (CENTS) n = Math.round(n / 100);
|
||||
const a = Math.abs(n), s = n < 0 ? "-" : "";
|
||||
if (a >= 100000000) return s + (a / 100000000).toFixed(a >= 1000000000 ? 0 : 1).replace(/\.0$/, "") + "억";
|
||||
if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만";
|
||||
@@ -179,7 +190,7 @@
|
||||
b.disabled = true;
|
||||
b.textContent = "중지하는 중…";
|
||||
try {
|
||||
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
|
||||
const r = await api("POST", BASE + "/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
|
||||
encodeURIComponent(b.dataset.stop) + "/stop");
|
||||
last = r.job;
|
||||
renderSyncJob(m.body, r.job, false);
|
||||
@@ -197,7 +208,7 @@
|
||||
cancelBtn.disabled = true;
|
||||
cancelBtn.textContent = "취소하는 중…";
|
||||
try {
|
||||
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel");
|
||||
const r = await api("POST", BASE + "/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel");
|
||||
last = r.job;
|
||||
renderSyncJob(m.body, r.job, false);
|
||||
} catch (err) {
|
||||
@@ -207,7 +218,7 @@
|
||||
}
|
||||
});
|
||||
(existing ? Promise.resolve({ job: existing, joined: true })
|
||||
: api("POST", startUrl || "/performance/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
|
||||
: api("POST", startUrl || BASE + "/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
|
||||
last = res.job;
|
||||
jobId = res.job.id;
|
||||
const joined = res.joined;
|
||||
@@ -217,7 +228,7 @@
|
||||
async function poll() {
|
||||
if (closed) return;
|
||||
try {
|
||||
const r = await api("GET", "/performance/api/sync/jobs/" + encodeURIComponent(res.job.id));
|
||||
const r = await api("GET", BASE + "/api/sync/jobs/" + encodeURIComponent(res.job.id));
|
||||
last = r.job;
|
||||
renderSyncJob(m.body, r.job, joined);
|
||||
if (r.job.finished) {
|
||||
@@ -257,6 +268,7 @@
|
||||
// 바꾼 너비는 이 브라우저 localStorage(perf_colw_sales / perf_colw_ads, 열 = th data-col)에 계속 유지, 경계를 두 번 누르면 그 열만 자동 너비로.
|
||||
// 그룹 접기·펴기 애니메이션은 apply(접는 열)/animate/settle 로 열 너비를 0 ↔ 원래 너비로 함께 움직인다.
|
||||
const COLW_MIN = 36;
|
||||
const CFOLD_W = 26; // 접은 열 너비 — performance.css .is-cfold 와 같게
|
||||
function initColWidths(root) {
|
||||
const table = root.querySelector("table.perf-colw-manual");
|
||||
const row = table && table.tHead && table.tHead.rows[0];
|
||||
@@ -271,7 +283,11 @@
|
||||
}
|
||||
// 날짜 열(label)은 조절 안 함(2026-10-27) — 늘 자동 너비(글자 길이), 손잡이 없음
|
||||
function fixedCol(th) { return th.dataset.col === "label"; }
|
||||
function widthOf(th) { const c = th.dataset.col; return (!fixedCol(th) && saved[c]) || auto[c] || 80; }
|
||||
function widthOf(th) {
|
||||
if (th.classList.contains("is-cfold")) return CFOLD_W; // 접은 열(initColFold) — 좁은 띠
|
||||
const c = th.dataset.col;
|
||||
return (!fixedCol(th) && saved[c]) || auto[c] || 80;
|
||||
}
|
||||
function apply(zero) { // zero = 너비 0 으로 둘 열(접는 중·펴기 직전)
|
||||
let sum = 0;
|
||||
heads.forEach(function (th) {
|
||||
@@ -288,7 +304,7 @@
|
||||
table.style.width = "";
|
||||
heads.forEach(function (th) {
|
||||
const w = th.getBoundingClientRect().width;
|
||||
if (w > 0) auto[th.dataset.col] = Math.ceil(w);
|
||||
if (w > 0 && !th.classList.contains("is-cfold")) auto[th.dataset.col] = Math.ceil(w);
|
||||
});
|
||||
apply();
|
||||
}
|
||||
@@ -342,11 +358,68 @@
|
||||
};
|
||||
}
|
||||
|
||||
// 열 접기(2026-11-06) — 매출 실적·광고비 일자별 표 머리글 위 버튼으로 열 하나씩 접기/펴기(날짜 열 빼고).
|
||||
// 접은 열 = 좁은 띠(버튼만, 칸 클릭·메모 안 됨). 보는 사람(로그인 계정)마다 서버에 저장(PUT /api/my-col-fold) — 다른 사람 화면은 그대로.
|
||||
function initColFold(root, colw) {
|
||||
const table = root.querySelector("table[data-cfold-kind]");
|
||||
const row = table && table.tHead && table.tHead.rows[0];
|
||||
if (!row) return;
|
||||
let folded = [];
|
||||
try { folded = JSON.parse(table.dataset.colFold || "[]") || []; } catch (_) { folded = []; }
|
||||
const ICON = '<svg viewBox="0 0 12 12" width="12" height="12" aria-hidden="true"><path d="M7.5 3 4.5 6l3 3" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
||||
function setFold(th, fold) {
|
||||
const i = th.cellIndex;
|
||||
Array.prototype.forEach.call(table.rows, function (r) { if (r.cells[i]) r.cells[i].classList.toggle("is-cfold", fold); });
|
||||
const b = th.querySelector(".perf-cfold");
|
||||
b.setAttribute("aria-expanded", fold ? "false" : "true");
|
||||
b.setAttribute("aria-label", b.dataset.name + (fold ? " 열 펴기" : " 열 접기"));
|
||||
}
|
||||
// 버튼 위 말풍선(2026-11-06) — 커서 위를 따라다니며 쇼핑몰(열) 이름, 글자 크기 = 열 제목. 빈 title 로 머리글 th 의 기본 말풍선은 막는다
|
||||
let tip = null;
|
||||
function hideTip() { if (tip) { tip.remove(); tip = null; } }
|
||||
row.addEventListener("pointermove", function (e) {
|
||||
const b = e.target.closest(".perf-cfold");
|
||||
if (!b || (tip && tip._b !== b)) hideTip();
|
||||
if (!b) return;
|
||||
if (!tip) { tip = el("div", { class: "perf-cfold-tip", role: "tooltip", text: b.dataset.name }); tip._b = b; document.body.appendChild(tip); }
|
||||
tip.style.left = e.clientX + "px";
|
||||
tip.style.top = e.clientY + "px";
|
||||
});
|
||||
row.addEventListener("pointerleave", hideTip);
|
||||
window.addEventListener("scroll", hideTip, true);
|
||||
Array.prototype.forEach.call(row.cells, function (th) {
|
||||
const col = th.dataset.col;
|
||||
if (!col || col === "label") return;
|
||||
const b = document.createElement("button");
|
||||
b.type = "button";
|
||||
b.className = "perf-cfold";
|
||||
b.title = "";
|
||||
b.dataset.name = th.textContent.replace(/[✎\s]+/g, " ").trim();
|
||||
b.innerHTML = ICON;
|
||||
th.insertBefore(b, th.firstChild);
|
||||
setFold(th, folded.indexOf(col) >= 0);
|
||||
});
|
||||
if (colw && folded.length) colw.apply();
|
||||
row.addEventListener("click", function (e) {
|
||||
const b = e.target.closest(".perf-cfold");
|
||||
if (!b) return;
|
||||
e.stopPropagation();
|
||||
const th = b.parentElement, col = th.dataset.col;
|
||||
const fold = !th.classList.contains("is-cfold");
|
||||
setFold(th, fold);
|
||||
if (colw) colw.apply();
|
||||
folded = folded.filter(function (c) { return c !== col; });
|
||||
if (fold) folded.push(col);
|
||||
api("PUT", BASE + "/api/my-col-fold", { kind: table.dataset.cfoldKind, cols: folded })
|
||||
.catch(function (err) { alertMsg("접은 열을 저장하지 못했습니다: " + err.message); });
|
||||
});
|
||||
}
|
||||
|
||||
function initDashboard(root) {
|
||||
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
|
||||
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
|
||||
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
|
||||
const MANUAL_API = data.manual_api || "/performance/api/manual-sales/";
|
||||
const MANUAL_API = data.manual_api || BASE + "/api/manual-sales/";
|
||||
const MANUAL_WORD = data.manual_word || "총매출";
|
||||
const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다.";
|
||||
|
||||
@@ -358,7 +431,7 @@
|
||||
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
|
||||
b.classList.toggle("is-active", b.dataset.metric === m);
|
||||
});
|
||||
drawDaily(m);
|
||||
drawDaily(m, "perf-chart-daily", data.daily);
|
||||
drawShare(m);
|
||||
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
|
||||
}
|
||||
@@ -422,6 +495,7 @@
|
||||
if (fold) collapsed.push(code);
|
||||
try { localStorage.setItem(GROUP_KEY, JSON.stringify(collapsed)); } catch (_) { /* 기억만 못 함 */ }
|
||||
});
|
||||
initColFold(root, colw);
|
||||
|
||||
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
|
||||
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.
|
||||
@@ -434,7 +508,7 @@
|
||||
'<p class="perf-muted" style="margin:0 0 8px">1열에 <b>날짜</b>, 2열부터 <b>쇼핑몰 이름</b>을 머리글로 적고 그날 <b>총매출</b>을 넣습니다. ' +
|
||||
"값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.</p>" +
|
||||
'<p class="perf-muted" style="margin:0 0 10px">입력 가능한 쇼핑몰: ' + (shops || "없음") + "</p>" +
|
||||
'<p style="margin:0 0 12px"><a class="erp-btn erp-btn-outline erp-btn-sm" href="/performance/api/manual-sales/sample.xlsx" download>' +
|
||||
'<p style="margin:0 0 12px"><a class="erp-btn erp-btn-outline erp-btn-sm" href="' + BASE + '/api/manual-sales/sample.xlsx" download>' +
|
||||
"샘플 파일 받기</a></p>" +
|
||||
'<input type="file" class="erp-input perf-upload-file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="엑셀 파일" />' +
|
||||
'<div class="perf-upload-result"></div>';
|
||||
@@ -454,7 +528,7 @@
|
||||
fd.append("file", f);
|
||||
let res, body = null;
|
||||
try {
|
||||
res = await fetch("/performance/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd });
|
||||
res = await fetch(BASE + "/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd });
|
||||
try { body = await res.json(); } catch (_) { body = null; }
|
||||
} catch (err) {
|
||||
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
|
||||
@@ -524,7 +598,7 @@
|
||||
});
|
||||
let res, body = null;
|
||||
try {
|
||||
res = await fetch("/performance/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value),
|
||||
res = await fetch(BASE + "/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value),
|
||||
{ method: "POST", credentials: "same-origin", body: fd });
|
||||
try { body = await res.json(); } catch (_) { body = null; }
|
||||
} catch (err) {
|
||||
@@ -560,7 +634,7 @@
|
||||
let running = false;
|
||||
try {
|
||||
let cur = null;
|
||||
try { cur = (await api("GET", "/performance/api/ad-sync/current")).job; } catch (_) { cur = null; }
|
||||
try { cur = (await api("GET", BASE + "/api/ad-sync/current")).job; } catch (_) { cur = null; }
|
||||
let job;
|
||||
if (cur && !cur.finished) {
|
||||
job = await runSyncWithProgress(null, "광고비 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur);
|
||||
@@ -568,7 +642,7 @@
|
||||
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
|
||||
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
|
||||
job = await runSyncWithProgress({ from: from, to: to }, "광고비 업데이트 " + from + " ~ " + to, null,
|
||||
"/performance/api/ad-sync");
|
||||
BASE + "/api/ad-sync");
|
||||
}
|
||||
running = !!(job && !job.finished);
|
||||
const ok = [], bad = [], other = [];
|
||||
@@ -617,7 +691,7 @@
|
||||
const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true });
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
try {
|
||||
const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" +
|
||||
const res = await api("GET", BASE + "/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" +
|
||||
encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end));
|
||||
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).</p>'; return; }
|
||||
const cols = res.columns || [];
|
||||
@@ -706,7 +780,7 @@
|
||||
try {
|
||||
// 이미 돌고 있는 업데이트(다른 사람·자동 업데이트 포함)가 있으면 새로 시작하지 않고 그 진행 창을 다시 연다
|
||||
let cur = null;
|
||||
try { cur = (await api("GET", "/performance/api/sync/current")).job; } catch (_) { cur = null; }
|
||||
try { cur = (await api("GET", BASE + "/api/sync/current")).job; } catch (_) { cur = null; }
|
||||
let job;
|
||||
if (cur && !cur.finished) {
|
||||
job = await runSyncWithProgress(null, "매출 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur);
|
||||
@@ -791,7 +865,7 @@
|
||||
}, 120);
|
||||
}
|
||||
function saveManual(td, text) {
|
||||
const raw = String(text || "").replace(/[,\s원]/g, "").replace(/^=/, "");
|
||||
const raw = String(text || "").replace(/[,\s원]|RM/gi, "").replace(/^=/, "");
|
||||
if (raw !== "" && !/^[-+*/().\d×÷xX]+$/.test(raw)) {
|
||||
return Promise.reject(new Error("숫자 또는 1000+2000 같은 계산식만 입력하세요."));
|
||||
}
|
||||
@@ -800,7 +874,7 @@
|
||||
return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" +
|
||||
encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : raw });
|
||||
}).then(function (res) {
|
||||
const manual = res.manual == null ? "" : String(res.manual);
|
||||
const manual = res.manual == null ? "" : CENTS ? (res.manual / 100).toFixed(2) : String(res.manual);
|
||||
td.dataset.manualValue = manual;
|
||||
if (res.formula) td.dataset.formula = res.formula; else delete td.dataset.formula;
|
||||
td.classList.toggle("is-manual", manual !== "");
|
||||
@@ -896,7 +970,7 @@
|
||||
td.classList.toggle("has-memo", !!memo);
|
||||
}
|
||||
async function saveMemo(td, memo) {
|
||||
const res = await api("PUT", "/performance/api/cell-memos/" + encodeURIComponent(MEMO_KIND) + "/" +
|
||||
const res = await api("PUT", BASE + "/api/cell-memos/" + encodeURIComponent(MEMO_KIND) + "/" +
|
||||
encodeURIComponent(td.dataset.memoCode) + "/" + encodeURIComponent(td.dataset.date), { memo: memo });
|
||||
setCellMemo(td, res.memo || "");
|
||||
}
|
||||
@@ -973,7 +1047,7 @@
|
||||
const m = openModal(title, { wide: true }); // 넓은 창 + 상품명 줄바꿈 → 가로 스크롤 없이
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
try {
|
||||
const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) +
|
||||
const res = await api("GET", BASE + "/api/events?code=" + encodeURIComponent(code) +
|
||||
"&from=" + encodeURIComponent(from) + "&to=" + encodeURIComponent(to));
|
||||
const rows = res.rows || [];
|
||||
if (!rows.length) { m.body.innerHTML = '<p class="perf-muted">내역이 없습니다.</p>'; return; }
|
||||
@@ -1045,10 +1119,10 @@
|
||||
const n = v / p;
|
||||
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p;
|
||||
}
|
||||
function drawDaily(metric) {
|
||||
const box = document.getElementById("perf-chart-daily");
|
||||
function drawDaily(metric, boxId, series) {
|
||||
const box = document.getElementById(boxId);
|
||||
if (!box) return;
|
||||
const pts = data.daily || [];
|
||||
const pts = series || [];
|
||||
const vals = pts.map(function (p) { return p[metric] || 0; });
|
||||
if (!pts.length || vals.every(function (v) { return !v; })) {
|
||||
box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>";
|
||||
@@ -1071,7 +1145,7 @@
|
||||
const x = L + i * bw + bw * 0.15, w = Math.max(1, bw * 0.7);
|
||||
const y0 = y(0), y1 = y(v);
|
||||
g += '<rect class="bar' + (v < 0 ? " is-neg" : "") + '" x="' + x + '" y="' + Math.min(y0, y1) +
|
||||
'" width="' + w + '" height="' + Math.max(0.5, Math.abs(y1 - y0)) + '"><title>' + esc(p.label) + " " + fmt(v) + "원</title></rect>";
|
||||
'" width="' + w + '" height="' + Math.max(0.5, Math.abs(y1 - y0)) + '"><title>' + esc(p.label) + " " + money(v) + " " + CUR + "</title></rect>";
|
||||
if (i % every === 0) g += '<text x="' + (L + i * bw + bw / 2) + '" y="' + (H - 8) + '" text-anchor="middle">' + esc(p.label) + "</text>";
|
||||
});
|
||||
g += '<line class="axis" x1="' + L + '" x2="' + (W - R) + '" y1="' + y(0) + '" y2="' + y(0) + '"/>';
|
||||
@@ -1091,8 +1165,8 @@
|
||||
const w = Math.max(0, (W - L - R) * Math.max(0, v) / maxV);
|
||||
const pct = total > 0 ? (Math.max(0, v) / total * 100).toFixed(1) : "0.0";
|
||||
g += '<text x="' + (L - 8) + '" y="' + (y + 14) + '" text-anchor="end">' + esc(r.name) + "</text>" +
|
||||
'<rect class="bar" x="' + L + '" y="' + (y + 4) + '" width="' + w + '" height="13"><title>' + esc(r.name) + " " + fmt(v) + "원</title></rect>" +
|
||||
'<text x="' + (L + w + 6) + '" y="' + (y + 14) + '">' + fmt(v) + " (" + pct + "%)</text>";
|
||||
'<rect class="bar" x="' + L + '" y="' + (y + 4) + '" width="' + w + '" height="13"><title>' + esc(r.name) + " " + money(v) + " " + CUR + "</title></rect>" +
|
||||
'<text x="' + (L + w + 6) + '" y="' + (y + 14) + '">' + money(v) + " (" + pct + "%)</text>";
|
||||
});
|
||||
box.innerHTML = svg(W, H, g);
|
||||
}
|
||||
@@ -1137,7 +1211,7 @@
|
||||
if (pending || asking || document.hidden) return;
|
||||
asking = true;
|
||||
try {
|
||||
const st = await api("GET", "/performance/api/update-status?kind=" + encodeURIComponent(w.kind));
|
||||
const st = await api("GET", BASE + "/api/update-status?kind=" + encodeURIComponent(w.kind));
|
||||
if (st.done && st.done !== seen && !st.running) { pending = true; reloadWhenFree(); }
|
||||
} catch (_) { /* 잠깐 끊김·로그아웃 — 다음 차례에 */ } finally { asking = false; }
|
||||
}
|
||||
@@ -1276,7 +1350,7 @@
|
||||
}
|
||||
save.disabled = true;
|
||||
try {
|
||||
const res = await api("PUT", "/performance/api/auto-sync-schedule", payload);
|
||||
const res = await api("PUT", BASE + "/api/auto-sync-schedule", payload);
|
||||
rows.forEach(function (row) {
|
||||
const r = res[row.dataset.kind];
|
||||
if (!r) return;
|
||||
@@ -1298,7 +1372,7 @@
|
||||
b.addEventListener("click", async function () {
|
||||
const u = b.dataset.unit;
|
||||
try {
|
||||
await api("PUT", "/performance/api/display-unit", { unit: u });
|
||||
await api("PUT", BASE + "/api/display-unit", { unit: u });
|
||||
} catch (err) {
|
||||
alertMsg("저장 실패: " + err.message);
|
||||
return;
|
||||
@@ -1320,7 +1394,7 @@
|
||||
root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (b) {
|
||||
b.addEventListener("click", function () {
|
||||
const v = b.dataset.colw;
|
||||
document.cookie = "perf_colw=" + v + "; path=/performance; max-age=31536000; SameSite=Lax";
|
||||
document.cookie = "perf_colw=" + v + "; path=" + BASE + "; max-age=31536000; SameSite=Lax";
|
||||
root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (x) {
|
||||
x.classList.toggle("is-active", x === b);
|
||||
x.setAttribute("aria-checked", x === b ? "true" : "false");
|
||||
@@ -1332,7 +1406,7 @@
|
||||
});
|
||||
if (colwReset) colwReset.addEventListener("click", async function () {
|
||||
if (!(await confirmMsg("매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?"))) return;
|
||||
try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); } catch (_) { /* 저장소 없음 */ }
|
||||
try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); localStorage.removeItem("perf_colw_tiktok"); } catch (_) { /* 저장소 없음 */ }
|
||||
colwReset.textContent = "초기화했습니다";
|
||||
setTimeout(function () { colwReset.textContent = "조절한 너비 초기화"; }, 1800);
|
||||
});
|
||||
@@ -1343,7 +1417,7 @@
|
||||
c.addEventListener("change", function () {
|
||||
const codes = hideBoxes.filter(function (x) { return x.checked; }).map(function (x) { return x.dataset.hide; });
|
||||
hideSave = hideSave.then(function () {
|
||||
return api("PUT", "/performance/api/hidden-marketplaces", { codes: codes });
|
||||
return api("PUT", BASE + "/api/hidden-marketplaces", { codes: codes });
|
||||
}).catch(function (err) {
|
||||
c.checked = !c.checked;
|
||||
alertMsg("저장 실패: " + err.message);
|
||||
@@ -1360,7 +1434,7 @@
|
||||
payload[box.dataset.field] = box.checked;
|
||||
box.disabled = true;
|
||||
try {
|
||||
await api("PUT", "/performance/api/marketplaces/" + tr.dataset.code, payload);
|
||||
await api("PUT", BASE + "/api/marketplaces/" + tr.dataset.code, payload);
|
||||
} catch (err) {
|
||||
box.checked = !box.checked;
|
||||
alertMsg("저장 실패: " + err.message);
|
||||
@@ -1374,12 +1448,12 @@
|
||||
const tr = btn.closest("tr");
|
||||
const code = tr.dataset.code, name = tr.dataset.name;
|
||||
// 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰
|
||||
const base = "/performance/api/" + (tr.dataset.api || "marketplaces") + "/";
|
||||
const base = BASE + "/api/" + (tr.dataset.api || "marketplaces") + "/";
|
||||
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
|
||||
else if (btn.dataset.act === "creds") openCreds(code, name, base);
|
||||
else if (btn.dataset.act === "test") runTest(code, name, btn, base);
|
||||
else if (btn.dataset.act === "rename") openName(tr.dataset.group ? "그룹 이름 변경" : "쇼핑몰 이름 변경", name, function (v) {
|
||||
return api("PUT", "/performance/api/marketplaces/" + code, { name: v });
|
||||
return api("PUT", BASE + "/api/marketplaces/" + code, { name: v });
|
||||
});
|
||||
else if (btn.dataset.act === "delete") deleteCustom(code, name, !!tr.dataset.group);
|
||||
});
|
||||
@@ -1407,22 +1481,22 @@
|
||||
}
|
||||
const addShop = document.getElementById("perf-add-shop");
|
||||
if (addShop) addShop.addEventListener("click", function () {
|
||||
openName("쇼핑몰 추가(수동 입력)", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "shop", name: v }); });
|
||||
openName("쇼핑몰 추가(수동 입력)", "", function (v) { return api("POST", BASE + "/api/marketplaces", { kind: "shop", name: v }); });
|
||||
});
|
||||
const addGroup = document.getElementById("perf-add-group");
|
||||
if (addGroup) addGroup.addEventListener("click", function () {
|
||||
openName("그룹 추가", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "group", name: v }); });
|
||||
openName("그룹 추가", "", function (v) { return api("POST", BASE + "/api/marketplaces", { kind: "group", name: v }); });
|
||||
});
|
||||
async function deleteCustom(code, name, isGroup) {
|
||||
let msg;
|
||||
if (isGroup) msg = "그룹 [" + name + "]을 삭제할까요? 하위 쇼핑몰은 지워지지 않고 그룹 없음이 됩니다.";
|
||||
else {
|
||||
let days = 0;
|
||||
try { days = (await api("GET", "/performance/api/marketplaces/" + code + "/manual-days")).days || 0; } catch (_) { /* 확인 문구만 */ }
|
||||
try { days = (await api("GET", BASE + "/api/marketplaces/" + code + "/manual-days")).days || 0; } catch (_) { /* 확인 문구만 */ }
|
||||
msg = "쇼핑몰 [" + name + "]을 삭제할까요?" + (days ? " 입력해 둔 매출 " + fmt(days) + "일치와 수수료율도 함께 지워지며 되돌릴 수 없습니다." : "");
|
||||
}
|
||||
if (!(await confirmMsg(msg))) return;
|
||||
try { await api("DELETE", "/performance/api/marketplaces/" + code); location.reload(); }
|
||||
try { await api("DELETE", BASE + "/api/marketplaces/" + code); location.reload(); }
|
||||
catch (err) { alertMsg("삭제 실패: " + err.message); }
|
||||
}
|
||||
root.querySelectorAll("select[data-act-group]").forEach(function (sel) {
|
||||
@@ -1430,7 +1504,7 @@
|
||||
sel.addEventListener("change", async function () {
|
||||
sel.disabled = true;
|
||||
try {
|
||||
await api("PUT", "/performance/api/marketplaces/" + sel.closest("tr").dataset.code, { parent_code: sel.value });
|
||||
await api("PUT", BASE + "/api/marketplaces/" + sel.closest("tr").dataset.code, { parent_code: sel.value });
|
||||
location.reload(); // 행이 그룹 아래로(또는 밖으로) 옮겨 그려진다
|
||||
} catch (err) { sel.value = before; sel.disabled = false; alertMsg("저장 실패: " + err.message); }
|
||||
});
|
||||
@@ -1468,7 +1542,7 @@
|
||||
document.body.classList.remove("perf-dragging");
|
||||
const order = currentOrder();
|
||||
if (order.join(",") === start) return;
|
||||
try { await api("PUT", "/performance/api/marketplace-order", { codes: order }); }
|
||||
try { await api("PUT", BASE + "/api/marketplace-order", { codes: order }); }
|
||||
catch (err) { await alertMsg("순서 저장 실패: " + err.message); location.reload(); }
|
||||
}
|
||||
document.addEventListener("pointermove", move);
|
||||
@@ -1513,7 +1587,7 @@
|
||||
'</td><td><button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-del="' + r.id + '">삭제</button></td></tr>';
|
||||
}).join("") + "</tbody></table>";
|
||||
}
|
||||
try { renderHist((await api("GET", "/performance/api/marketplaces/" + code + "/rates")).rates || []); }
|
||||
try { renderHist((await api("GET", BASE + "/api/marketplaces/" + code + "/rates")).rates || []); }
|
||||
catch (err) { m.body.querySelector("#perf-rate-hist").textContent = err.message; }
|
||||
|
||||
m.body.addEventListener("click", async function (e) {
|
||||
@@ -1521,7 +1595,7 @@
|
||||
if (!b) return;
|
||||
if (!(await confirmMsg("이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다."))) return;
|
||||
try {
|
||||
renderHist((await api("DELETE", "/performance/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []);
|
||||
renderHist((await api("DELETE", BASE + "/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []);
|
||||
m.changed = true;
|
||||
} catch (err) { alertMsg(err.message); }
|
||||
});
|
||||
@@ -1529,7 +1603,7 @@
|
||||
const rate = m.body.querySelector("#perf-rate-in").value.trim();
|
||||
if (!rate) { m.body.querySelector("#perf-rate-in").focus(); return; }
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/marketplaces/" + code + "/rates", {
|
||||
const res = await api("POST", BASE + "/api/marketplaces/" + code + "/rates", {
|
||||
rate_percent: rate, effective_from: all.checked ? "2000-01-01" : from.value,
|
||||
memo: m.body.querySelector("#perf-rate-memo").value,
|
||||
});
|
||||
@@ -1545,7 +1619,7 @@
|
||||
|
||||
// ── API 인증정보 ──
|
||||
async function openCreds(code, name, base) {
|
||||
base = base || "/performance/api/marketplaces/";
|
||||
base = base || BASE + "/api/marketplaces/";
|
||||
const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
let info;
|
||||
@@ -1645,7 +1719,7 @@
|
||||
const label = btn.textContent;
|
||||
btn.textContent = "확인 중…";
|
||||
try {
|
||||
const res = await api("POST", (base || "/performance/api/marketplaces/") + code + "/test", {});
|
||||
const res = await api("POST", (base || BASE + "/api/marketplaces/") + code + "/test", {});
|
||||
await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined);
|
||||
location.reload();
|
||||
} catch (err) {
|
||||
@@ -1701,7 +1775,7 @@
|
||||
if (gen) gen.addEventListener("click", async function () {
|
||||
gen.disabled = true;
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/sample-data", {
|
||||
const res = await api("POST", BASE + "/api/sample-data", {
|
||||
action: "generate", from: document.getElementById("perf-sample-from").value,
|
||||
to: document.getElementById("perf-sample-to").value,
|
||||
});
|
||||
@@ -1713,7 +1787,7 @@
|
||||
if (del) del.addEventListener("click", async function () {
|
||||
if (!(await confirmMsg("테스트 데이터만 모두 삭제합니다. 실제 수집한 매출은 지우지 않습니다. 계속할까요?"))) return;
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/sample-data", { action: "delete" });
|
||||
const res = await api("POST", BASE + "/api/sample-data", { action: "delete" });
|
||||
await alertMsg("테스트 데이터 " + fmt(res.deleted) + "건을 삭제했습니다.");
|
||||
location.reload();
|
||||
} catch (err) { alertMsg(err.message); }
|
||||
@@ -1722,7 +1796,7 @@
|
||||
if (rekey) rekey.addEventListener("click", async function () {
|
||||
if (!(await confirmMsg("예전 키로 암호화된 인증정보를 현재 키로 다시 암호화합니다. 계속할까요?"))) return;
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/rekey");
|
||||
const res = await api("POST", BASE + "/api/rekey");
|
||||
await alertMsg("다시 암호화 " + res.reencrypted + "건" + (res.failed ? ", 실패 " + res.failed + "건(다시 입력 필요)" : ""));
|
||||
location.reload();
|
||||
} catch (err) { alertMsg(err.message); }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user